-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathprocessProquest.php
More file actions
1602 lines (1318 loc) · 66.8 KB
/
processProquest.php
File metadata and controls
1602 lines (1318 loc) · 66.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
error_reporting(E_ALL);
/**
* Description of processProquest
*
* @author MEUSEB
*
* annotations by Jesse Martinez.
*/
/*
* Islandora/Fedora library.
*/
require_once '/var/www/html/drupal/sites/all/libraries/tuque/RepositoryConnection.php';
require_once '/var/www/html/drupal/sites/all/libraries/tuque/FedoraApi.php';
require_once '/var/www/html/drupal/sites/all/libraries/tuque/FedoraApiSerializer.php';
require_once '/var/www/html/drupal/sites/all/libraries/tuque/Repository.php';
require_once '/var/www/html/drupal/sites/all/libraries/tuque/RepositoryException.php';
require_once '/var/www/html/drupal/sites/all/libraries/tuque/FedoraRelationships.php';
require_once '/var/www/html/drupal/sites/all/libraries/tuque/Cache.php';
require_once '/var/www/html/drupal/sites/all/libraries/tuque/HttpConnection.php';
/**
* Custom FTP connection handler.
*/
require_once 'proquestFTP.php';
/*
* BC Islandora definitions.
*/
define('ISLANDORA_BC_ROOT_PID', 'bc-ir:GraduateThesesCollection');
define('ISLANDORA_BC_ROOT_PID_EMBARGO', 'bc-ir:GraduateThesesCollectionRestricted');
define('ISLANDORA_BC_XACML_POLICY','POLICY');
define('GRADUATE_THESES','bc-ir:GraduateThesesCollection');
define('GRADUATE_THESES_RESTRICTED','bc-ir:GraduateThesesCollectionRestricted');
define('DEFAULT_LOG_FILE_LOCATION', '/tmp/proquest-log/');
define('DEFAULT_DEBUG_VALUE', false);
/**
* Batch processes Proquest ETDs.
*
* This class allows for the following workflow:
* - Initialize FTP server connection.
* - Gathers and extracts the ETD zip files from FTP server onto a local directory.
* - Generates metadata files from ETD zip file contents.
* - Initialize connection to Fedora file repository server.
* - Ingests ETD files and metadata into Fedora, and generates various datastreams.
*/
class processProquest {
public $settings;
public $debug;
protected $ftp;
protected $localFiles; // array
protected $connection;
protected $api;
protected $api_m;
protected $repository;
protected $toProcess = 0; // Number of PIDs for supplementary files.
protected $logFile = "";
protected $logError = false;
/**
* Class constructor.
*
* This builds a local '$this' object that contains various script settings.
*
* @param string $config An ini file containing various configurations.
* @param bool $debug Run script in debug mode, which doesn't ingest ETD into Fedora.
*/
public function __construct($config, $debug = DEFAULT_DEBUG_VALUE) {
$this->settings = parse_ini_file($config, true);
// Verify that $debug is a bool value.
if ( is_bool($debug) ){
$this->debug = $debug;
} else {
$this->debug = DEFAULT_DEBUG_VALUE;
}
$this->writeLog("Starting processProquest script.", "");
$this->writeLog("Running with DEBUG value: " . ($this->debug ? "TRUE" : "FALSE"), "");
}
/**
* Initialize logging file.
*
* @param string $file_name The name to give the log file.
* @return boolean Log init status.
*/
private function initLog($file_name = null) {
// Set log file name.
if ( is_null($file_name) ) {
$file_name = "ingest";
}
$date = date("Ymd-His", time());
// Set log location in case DEFAULT_LOG_FILE_LOCATION or $this->settings['log']["location"] isn't set.
$log_location = "/tmp/processProquest-test/";
if ( isset($this->settings['log']["location"]) ) {
$log_location = $this->settings['log']["location"];
} else if (defined(DEFAULT_LOG_FILE_LOCATION) == TRUE) {
$log_location = DEFAULT_LOG_FILE_LOCATION;
} else {
// DEFAULT_LOG_FILE_LOCATION really should be set in this class.
//return false;
}
// Build final log path and name. Ex: /var/log/processProquest/log-20200216-123456.txt
$this->logFile = $log_location . $file_name . "-" . $date . ".txt";
// Create file if it doesn't exist.
if( !is_file($this->logFile) ) {
$res = file_put_contents($this->logFile, "");
// In case of complete file creation error.
if ($res === false) {
echo "ERROR: Can't write to log file! " . $res;
$this->logError = true;
return false;
}
}
echo "Writing to log file: " . $this->logFile . "\n";
return true;
}
/**
* Simple logging.
*
* @param string $message The message to log.
* @param string $etd The ETD name.
* @return boolean Write status.
*/
private function writeLog($message, $function_name = "", $etd = "") {
// Check if there is a known issue with log writing.
if ($this->logError === true){
// Nothing we can do at this point.
return false;
}
// Check if $this->$logFile is set, and run initLog if not.
if ( empty($this->logFile) ) {
$res = $this->initLog();
// If initLog fails then we can't write to logs.
if ($res === false) {
return false;
}
}
// Add some text wrapping to $etd, if set.
if ( !empty($etd) ) {
$etd = "[" . $etd . "]";
}
// Format the date and time. Ex: 16/Feb/2020:07:45:12
$time = @date('[d/M/Y:H:i:s]');
// Append message to the log file.
if ($fd = @fopen($this->logFile, "a")) {
//$result = fputcsv($fd, array($time, $message));
$res = fwrite($fd, "$time ($function_name) $etd $message" . PHP_EOL);
// Check if fwrite failed.
if ($res === false) {
// Only print this error message once.
if ($this->logError === false) {
echo "ERROR: Can't write to log file! " . $res;
$this->logError = true;
}
return false;
}
fclose($fd);
} else {
// Only print this error message once.
if ($this->logError === false) {
echo "ERROR: Can't open log file! " . $res;
$this->logError = true;
}
return false;
}
// Finally, output to stdout
echo "$time ($function_name) $etd $message\n";
return true;
}
/**
* Send email notification.
*
* @param string $message The email body to send.
* @return boolean Was the email sent successfully.
*/
private function sendEmail($message) {
$fn = "sendEmail";
$log_location_message = "\n\nA detailed log file for this ingest has been generated on the server at this location:\n • " . $this->logFile;
$email_to = $this->settings['notify']['email'];
$email_subject = "Message from processProquest";
$email_message = $message . $log_location_message;
// Sanity checks.
if ( empty($email_to) ) {
$this->writeLog("ERROR: Email to: field is empty!", $fn);
return false;
}
if ( empty($email_subject) ) {
$this->writeLog("ERROR: Email subject: field is empty!", $fn);
return false;
}
if ( empty($email_message) ) {
$this->writeLog("ERROR: Email body: field is empty!", $fn);
return false;
}
$this->writeLog("Attempting to send out the following email:\n\tto:[" . $email_to . "]\n\tbody:[" . $email_message . "]", $fn);
// DEBUG: don't send email.
$res = true;
if ($this->debug === true) {
$this->writeLog("DEBUG: Not sending email notification.", $fn);
} else {
$res = mail($email_to, $email_subject, $email_message);
return true;
}
// Check mail success.
if ($res === false) {
$this->writeLog("ERROR: Email not sent!", $fn);
return false;
}
$this->writeLog("Email sent.", $fn);
return true;
}
/**
* Strips out punctuation, spaces, and unicode chars from a string.
*
* @return string A normalized string.
*/
private function normalizeString($str) {
# remove trailing spaces
$str = trim($str);
# replace spaces with dashes
$str = str_replace(" ", "-", $str);
# remove any character that isn't alphanumeric or a dash
$str = preg_replace("/[^a-z0-9-]+/i", "", $str);
return $str;
}
/**
* Initializes an FTP connection.
*
* Calls on proquestFTP.php
*
* @return boolean Success value.
*/
function initFTP() {
$fn = "initFTP";
$this->writeLog("Initializing FTP connection.", $fn);
$urlFTP = $this->settings['ftp']['server'];
$userFTP = $this->settings['ftp']['user'];
$passwordFTP = $this->settings['ftp']['password'];
if (empty($urlFTP) || empty($userFTP) || empty($passwordFTP)) {
$this->writeLog("ERROR: FTP login values missing!", $fn);
return false;
}
// Create ftp object used for connection.
$this->ftp = new proquestFTP($urlFTP);
// Set session time out. Default is 90.
$this->ftp->ftp_set_option(FTP_TIMEOUT_SEC, 150);
// Pass login credentials to login method.
if ( $this->ftp->ftp_login($userFTP, $passwordFTP) ) {
$this->writeLog("FTP connection sucecssful.", $fn);
return true;
} else {
// TODO: get ftp error message
$this->writeLog("ERROR: FTP connection failed!", $fn);
return false;
}
}
/**
* Gather ETD zip files from FTP server.
*
* Create a local directory for each zip file from FTP server and save into directory.
* Local directory name is based on file name.
* Next, varify that PDF and XML files exist. Also keep track of supplementary files.
* Lastly, expand zip file contents into local directory.
*
* @return boolean Success value.
*/
function getFiles() {
$fn = "getFiles";
$this->writeLog("Fetching ETD files from FTP server.", $fn);
// Look at specific directory on FTP server for ETD files. Ex: /path/to/files/
$fetchdirFTP = $this->settings['ftp']['fetchdir'];
// Define local directory for file processing. Ex: /tmp/processed/
$localdirFTP = $this->settings['ftp']['localdir'];
if ( empty($localdirFTP) ) {
$this->writeLog("ERROR: Local working directory not set!", $fn);
return false;
}
// Change FTP directory if $fetchdirFTP is not empty (aka root directory).
if ($fetchdirFTP != "") {
if ( $this->ftp->ftp_chdir($fetchdirFTP) ) {
$this->writeLog("Changed to FTP directory: " . $fetchdirFTP, $fn);
} else {
$this->writeLog("ERROR: Cound not change FTP directory: " . $fetchdirFTP , $fn);
return false;
}
}
$this->writeLog("Currently in FTP directory: " . $fetchdirFTP, $fn);
/**
* Look for files that begin with a specific string.
* In our specific case the file prefix is "etdadmin_upload".
* Save results into $etdFiles array.
*/
$etdFiles = $this->ftp->ftp_nlist("etdadmin_upload*");
// Sanity check to see if there are any ETD files to process.
// TODO: Handle some type of error message?
if ( empty($etdFiles) ) {
$this->writeLog("Did not find any files to fetch. Quitting.", $fn);
return true;
}
/**
* Loop through each match in $etdFiles.
* There may be multiple matched files so process each individually.
*/
$f = 0;
foreach ($etdFiles as $filename) {
$f++;
/**
* Set the directory name for each ETD file.
* This is based on the file name without any file extension.
* Ex: etd_file_name_1234.zip -> /tmp/processing/etd_file_name_1234
*/
// Sanity check to see if filename is more than four chars. Continue if string fails.
if (strlen($filename) <= 4) {
$this->writeLog("Warning! File name only has " . strlen($filename) . " characters. Skipping this file." , $fn);
continue;
}
// Get the regular file name without file extension.
$etdname = substr($filename,0,strlen($filename)-4);
// Set the path of the local working fdrectory. Ex: /tmp/processing/file_name_1234
$etdDir = $localdirFTP . $etdname;
// Save the shortname as a local object variable
$this->localFiles[$etdDir]['ETD_SHORTNAME'] = $etdname;
$this->writeLog("BEGIN Gathering ETD file #" . $f . " - " . $filename, $fn);
// Create the local directory if it doesn't already exists.
$this->writeLog("Now building local working directory...", $fn, $etdname);
if ( file_exists($etdDir) ) {
$this->writeLog("Local working directory already exists: " . $etdDir, $fn, $etdname);
}
else if ( !mkdir($etdDir, 0755, true) ) {
$this->writeLog("Failed to create local working directory: " . $etdDir, $fn, $etdname);
continue;
} else {
$this->writeLog("Created ETD local working directory: " . $etdDir, $fn, $etdname);
}
$localFile = $etdDir . "/" . $filename;
// HACK: give loop some time to create directory.
sleep(2);
/**
* Gets the file from the FTP server.
* Saves it locally to local working directory. Ex: /tmp/processing/file_name_1234
* File is saved locally as a binary file.
*/
if ( $this->ftp->ftp_get($localFile, $filename, FTP_BINARY) ) {
$this->writeLog("Fetched ETD zip file from FTP server.", $fn, $etdname);
} else {
$this->writeLog("ERROR: Failed to fetch file from FTP server!" . $localFile, $fn, $etdname);
continue;
}
// Store location of local directory if it hasn't been stored yet.
if( isset($this->localFiles[$etdDir]) ) {
$this->localFiles[$etdDir];
}
// Unzip ETD zip file.
$ziplisting = zip_open($localFile);
// zip_open returns a resource handle on success and an integer on error.
if (!is_resource($ziplisting)) {
$this->writeLog("ERROR: Failed to open zip file!", $fn, $etdname);
continue;
}
$supplement = 0;
// Go through entire zip file and process contents.
$z = 0;
while ($zip_entry = zip_read($ziplisting)) {
$z++;
$this->writeLog("Now reading zip file #" . $z, $fn, $etdname);
// Get file name.
$file = zip_entry_name($zip_entry);
$this->writeLog("Zip file name: " . $file, $fn, $etdname);
/**
* Match for a specific string in file.
*
* Make note of expected files:
* - PDF.
* - XML.
* - all else (AKA supplementary files).
*
* The String "0016" is specific to BC.
*/
if (preg_match('/0016/', $file)) {
// Check if this is a PDF or XML file.
// TODO: handle string case in comparison. Ex: "pdf" vs "PDF".
if (substr($file,strlen($file)-3) === 'pdf') {
$this->localFiles[$etdDir]['ETD'] = $file;
$this->writeLog("This is an PDF file.", $fn, $etdname);
} elseif (substr($file,strlen($file)-3) === 'xml') {
$this->localFiles[$etdDir]['METADATA'] = $file;
$this->writeLog("This is an XML metadata file.", $fn, $etdname);
} else {
/**
* Supplementary files - could be permissions or data.
* Metadata will contain boolean key for permission in DISS_file_descr element.
* [0] element should always be folder.
*/
$this->localFiles[$etdDir]['UNKNOWN'.$supplement] = $file;
$supplement++;
$this->writeLog("This is a supplementary file.", $fn, $etdname);
}
}
}
/**
* Sanity check that both:
* - $this->localFiles[$etdDir]['ETD']
* - $this->localFiles[$etdDir]['METADATA']
* are defined and are nonempty strings.
*/
$this->writeLog("Running sanity check that ETD PDF and XML file were found...", $fn, $etdname);
if ( empty($this->localFiles[$etdDir]['ETD']) ) {
$this->writeLog("Warning! The ETD PDF file was not found or set!", $fn, $etdname);
}
$this->writeLog("Great! The ETD PDF file was found.", $fn, $etdname);
if ( empty($this->localFiles[$etdDir]['METADATA']) ) {
$this->writeLog("Warning! The ETD XML file was not found or set!", $fn, $etdname);
}
$this->writeLog("Great! The ETD XML file was found.", $fn, $etdname);
$zip = new ZipArchive;
// Open and extract zip file to local directory.
$res = $zip->open($localFile);
if ($res === TRUE) {
$zip->extractTo($etdDir);
$zip->close();
$this->writeLog("Extracting ETD zip file: " . $localFile, $fn, $etdname);
} else {
$this->writeLog("ERROR: Failed to extract ETD zip file! " . $res, $fn, $etdname);
continue;
}
$this->writeLog("END Gathering ETD file #" . $f . " - " . $filename, $fn);
}
// Completed fetching all ETD zip files.
$this->writeLog("Completed fetching all ETD zip files from FTP server.", $fn);
}
/**
* Generate metadata from gathered ETD files.
*
* This will generate:
* - OA permissions.
* - Embargo settings.
* - MODS metadata.
* - PID, title, author values.
*
* @return boolean Success value.
*/
function processFiles() {
$fn = "processFiles";
// Sanity check to see if there are any ETD files to process.
if ( empty($this->localFiles) ) {
$this->writeLog("Did not find any files to process. Quitting.", $fn);
return true;
}
$this->writeLog("Now processing ETD files.", $fn);
/**
* Load Proquest MODS XSLT stylesheet.
* Ex: /path/to/proquest/crosswalk/Proquest_MODS.xsl
*/
$xslt = new xsltProcessor;
$proquestxslt = new DOMDocument();
$proquestxslt->load($this->settings['xslt']['xslt']);
if ( $xslt->importStyleSheet($proquestxslt) ) {
$this->writeLog("Loaded MODS XSLT stylesheet.", $fn);
} else {
$this->writeLog("ERROR: Failed to load MODS XSLT stylesheet!", $fn);
return false;
}
/**
* Load Fedora Label XSLT stylesheet.
* Ex: /path/to/proquest/xsl/getLabel.xsl
*/
$label = new xsltProcessor;
$labelxslt = new DOMDocument();
$labelxslt->load($this->settings['xslt']['label']);
if ( $label->importStyleSheet($labelxslt) ) {
$this->writeLog("Loaded Fedora Label XSLT stylesheet.", $fn);
} else {
$this->writeLog("ERROR: Failed to load Fedora Label XSLT stylesheet!", $fn);
return false;
}
/**
* Given the array of ETD local files, generate additional metadata.
*/
$s = 0;
foreach ($this->localFiles as $directory => $submission) {
$s++;
// Pull out the ETD shortname that was generated in getFiles()
$etdname = $this->localFiles[$directory]['ETD_SHORTNAME'];
if ( empty($etdname) ) {
$etdname = substr($this->localFiles[$directory]["ETD"],0,strlen($this->localFiles[$directory]["ETD"])-4);
$this->localFiles[$directory]['ETD_SHORTNAME'] = $etdname;
}
$this->writeLog("BEGIN Processing ETD #" . $s . " - " . $etdname, $fn);
// Create XPath object from the ETD XML file.
$metadata = new DOMDocument();
$metadata->load($directory . '//' . $submission['METADATA']);
$xpath = new DOMXpath($metadata);
/**
* Get OA permission.
* This looks for the existance of an "oa" node in the XPath object.
* Ex: /DISS_submission/DISS_repository/DISS_acceptance/text()
*/
$this->writeLog("Searching for OA agreement...", $fn, $etdname);
$openaccess = 0;
$oaElements = $xpath->query($this->settings['xslt']['oa']);
if ($oaElements->length === 0 ) {
$this->writeLog("No OA agreement found.", $fn, $etdname);
} elseif ($oaElements->item(0)->C14N() === '0') {
$this->writeLog("No OA agreement found.", $fn, $etdname);
} else {
$openaccess = $oaElements->item(0)->C14N();
$this->writeLog("Found an OA agreement.", $fn, $etdname);
}
$this->localFiles[$directory]['OA'] = $openaccess;
/**
* Get embargo permission/dates.
* This looks for the existance of an "embargo" node in the XPath object.
* Ex: /DISS_submission/DISS_repository/DISS_delayed_release/text()
*/
$this->writeLog("Searching for embargo information...", $fn, $etdname);
$embargo = 0;
$emElements = $xpath->query($this->settings['xslt']['embargo']);
if ($emElements->item(0) ) {
// Convert date string into proper PHP date object format.
$embargo = $emElements->item(0)->C14N();
$embargo = str_replace(" ","T",$embargo);
$embargo = $embargo . "Z";
$this->localFiles[$directory]['EMBARGO'] = $embargo;
$this->writeLog("Using embargo date of: " . $embargo, $fn, $etdname);
}
/**
* Check to see if the OA and embargo permissions match.
* If so, set the embargo permission/date to "indefinite".
*/
// TODO: should this be a corresponding ELSE IF clause to the previous IF clause?
// This looks like $embargo would only match $openaccess if they are both 0.
if ($openaccess === $embargo) {
$embargo = 'indefinite';
$this->localFiles[$directory]['EMBARGO'] = $embargo;
$this->writeLog("Using embargo date of: " . $embargo, $fn, $etdname);
} else {
$this->writeLog("No embargo date found.", $fn, $etdname);
}
/**
* Fetch next PID from Fedora.
* Prepend PID with locally defined Fedora namespace.
* Ex: "bc-ir:" for BC.
*/
// DEBUG: make up PID.
if ($this->debug === true) {
$pid = "bc-ir:" . rand(50000,100000);
$this->writeLog("DEBUG: Generating random PID for testing (NOT fetched from Fedora): " . $pid, $fn, $etdname);
} else {
$pid = $this->api_m->getNextPid($this->settings['fedora']['namespace'], 1);
$this->writeLog("Fetched new PID from Fedora: " . $pid, $fn, $etdname);
}
$this->localFiles[$directory]['PID'] = $pid;
$this->writeLog("Fedora PID value for this ETD: " . $pid, $fn, $etdname);
/**
* Insert the PID value into the Proquest MODS XSLT stylesheet.
* The "handle" value should be set the PID.
*/
$res = $xslt->setParameter('mods', 'handle', $pid);
if ($res === false) {
$this->writeLog("ERROR: Could not update XSLT stylesheet with PID value!", $fn, $etdname);
//$this->ingestHandlerPostProcess(false, $etdname, $this->etd);
continue;
}
$this->writeLog("Update XSLT stylesheet with PID value.", $fn, $etdname);
/**
* Generate MODS file.
* This file is generated by applying the Proquest MODS XSLT stylesheet to the ETD XML file.
* Additional metadata will be generated from the MODS file.
*/
$mods = $xslt->transformToDoc($metadata);
if ($mods === false) {
$this->writeLog("ERROR: Could not transform ETD MODS XML file!", $fn, $etdname);
//$this->ingestHandlerPostProcess(false, $etdname, $this->etd);
continue;
}
$this->writeLog("Transformed ETD MODS XML file with XSLT stylesheet.", $fn, $etdname);
/**
* Generate ETD title/Fedora Label.
* The title is generated by applying the Fedora Label XSLT stylesheet to the above generated MODS file.
* This uses mods:titleInfo.
*/
$fedoraLabel = $label->transformToXml($mods);
if ($fedoraLabel === false) {
$this->writeLog("ERROR: Could not generate ETD title using Fedora Label XSLT stylesheet!", $fn, $etdname);
//$this->ingestHandlerPostProcess(false, $etdname, $this->etd);
continue;
}
$this->localFiles[$directory]['LABEL'] = $fedoraLabel;
$this->writeLog("Generated ETD title: " . $fedoraLabel, $fn, $etdname);
/**
* Generate ETD author.
* This looks for the existance of an "author" node in the MODS XPath object.
* Ex: /mods:mods/mods:name[@type='personal'][@usage='primary']/mods:displayForm/text()
*/
$xpathAuthor = new DOMXpath($mods);
$authorElements = $xpathAuthor->query($this->settings['xslt']['creator']);
$author = $authorElements->item(0)->C14N();
$this->writeLog("Generated ETD author: [" . $author . "]", $fn, $etdname);
/**
* Normalize the ETD author string. This forms the internal file name convention.
* Ex: Jane Anne O'Foo => Jane-Anne-OFoo
*/
#$normalizedAuthor = str_replace(array(" ",",","'",".","'",'"',"""), array("-","","","","","",""), $author);
$normalizedAuthor = $this->normalizeString($author);
$this->writeLog("Generated normalized ETD author: [" . $normalizedAuthor . "]", $fn, $etdname);
$this->writeLog("Now using the normalized ETD author name to update ETD PDF and MODS files.", $fn, $etdname);
// Create placeholder full-text text file using normalized author's name.
$this->localFiles[$directory]['FULLTEXT'] = $normalizedAuthor . ".txt";
//$this->writeLog("Generated placeholder full text file name: " . $this->localFiles[$directory]['FULLTEXT'], $fn, $etdname);
// Rename Proquest PDF using normalized author's name.
$res = rename($directory . "/". $submission['ETD'] , $directory . "/" . $normalizedAuthor . ".pdf");
if ($res === false) {
$this->writeLog("ERROR: Could not rename ETD PDF file!", $fn, $etdname);
//$this->ingestHandlerPostProcess(false, $etdname, $this->etd);
continue;
}
// Update local file path for ETD PDF file.
$this->localFiles[$directory]['ETD'] = $normalizedAuthor . ".pdf";
$this->writeLog("Renamed ETD PDF file from " . $submission['ETD'] . " to " . $this->localFiles[$directory]['ETD'], $fn, $etdname);
// Save MODS using normalized author's name.
$res = $mods->save($directory . "/" . $normalizedAuthor . ".xml");
if ($res === false) {
$this->writeLog("ERROR: Could not create new ETD MODS file!", $fn, $etdname);
//$this->ingestHandlerPostProcess(false, $etdname, $this->etd);
continue;
}
// Update local file path for MODS file.
$this->localFiles[$directory]['MODS'] = $normalizedAuthor . ".xml";
$this->writeLog("Created new ETD MODS file " . $this->localFiles[$directory]['MODS'], $fn, $etdname);
/**
* Check for supplemental files.
* This looks for the existance of an "DISS_attachment" node in the ETD XML XPath object.
* Ex: /DISS_submission/DISS_content/DISS_attachment
*
* Previous comments (possibly outdated):
* UNKNOWN0 in lookup should mean there are other files
* also, Proquest MD will have DISS_attachment
* ($this->localFiles[$directory]['UNKNOWN0']) or
*/
$suppxpath = new DOMXpath($metadata);
$suElements = $suppxpath->query($this->settings['xslt']['supplement']);
$this->writeLog("Checking for existence supplemental files...", $fn, $etdname);
// Check if there are zero or more supplemental files.
if ($suElements->item(0) ) {
$this->localFiles[$directory]['PROCESS'] = "0";
$this->writeLog("No supplemental files found.", $fn, $etdname);
} else {
$this->localFiles[$directory]['PROCESS'] = "1";
$this->writeLog("Found a supplemental file(s).", $fn, $etdname);
// Keep track of how many additional PIDs will need to be generated.
$this->toProcess++;
}
$this->writeLog("END Processing ETD #" . $s . " - " . $etdname, $fn);
}
// Completed processing all ETD files.
$this->writeLog("Completed processing all ETD files.", $fn);
}
/**
* Initializes a connection to a Fedora file repository server.
*/
function initFedoraConnection() {
$this->connection = new RepositoryConnection($this->settings['fedora']['url'],
$this->settings['fedora']['username'],
$this->settings['fedora']['password']);
$this->api = new FedoraApi($this->connection);
$this->repository = new FedoraRepository($this->api, new simpleCache());
// Fedora Management API.
$this->api_m = $this->repository->api->m;
}
// Set global values for all ingest* functions
public $pidcount = 0;
public $successCount = 0;
public $failureCount = 0;
// Initialize messages for notification email.
public $successMessage = "";
public $failureMessage = "";
public $processingMessage = "";
/**
* Manages the post-process handling of an ETD ingest
*
* @param boolean $status The success status of the calling function.
* @param string $etdname The name of the ETD to print.
* @param object $etd An object containing the ETD submission metadata.
* @return boolean Returns true.
*/
function ingestHandlerPostProcess($status, $etdname, $etd){
$fn = "ingestHandlerPostProcess";
global $pidcount, $successCount, $failureCount;
global $successMessage, $failureMessage, $processingMessage;
$submission = $etd["submission"];
$fnameFTP = $etd["fnameFTP"];
$fullfnameFTP = $etd["fullfnameFTP"];
$pidcount++;
// Check if ingest was successful, and manage where to put FTP ETD file.
if ($status) {
$this->writeLog("Successfully ingested Fedora object.", $fn, $etdname);
$successCount++;
$successMessage .= " • " . $submission['PID'] . "\t";
// Set success status for email message.
if (isset($submission['EMBARGO'])) {
$successMessage .= "EMBARGO UNTIL: " . $submission['EMBARGO'] . "\t";
} else {
$successMessage .= "NO EMBARGO" . "\t";
}
$successMessage .= $submission['LABEL'] . "\n";
// Move processed PDF file to a new directory. Ex: /path/to/files/processed
$processdirFTP = $this->settings['ftp']['processdir'];
$fullProcessdirFTP = "~/" . $processdirFTP . "/" . $fnameFTP;
$this->writeLog("Currently in FTP directory: " . $this->ftp->ftp_pwd(), $fn, $etdname);
$this->writeLog("Now attempting to move " . $fullfnameFTP . " into " . $fullProcessdirFTP, $fn, $etdname);
$ftpRes = true;
if ($this->debug === true) {
$this->writeLog("DEBUG: Not moving ETD files on FTP.", $fn, $etdname);
} else {
$ftpRes = $this->ftp->ftp_rename($fullfnameFTP, $fullProcessdirFTP);
}
// Check if there was an error moving the ETD file on the FTP server.
if ($ftpRes === false) {
$this->writeLog("ERROR: Could not move ETD file to 'processed' FTP directory!", $fn, $etdname);
}
$this->writeLog("Moved ETD file to 'processed' FTP directory.", $fn, $etdname);
} else {
//$this->writeLog("ERROR: Ingestion of Fedora object failed.", $fn, $etdname);
$failureCount++;
$failureMessage .= $submission['PID'] . "\t";
// Set failure status for email message.
if (isset($submission['EMBARGO'])) {
$failureMessage .= "EMBARGO UNTIL: " . $submission['EMBARGO'] . "\t";
} else {
$failureMessage .= "NO EMBARGO" . "\t";
}
$failureMessage .= $submission['LABEL'] . "\n";
// Move processed PDF file to a new directory. Ex: /path/to/files/failed
$faildirFTP = $this->settings['ftp']['faildir'];
$fullFaildirFTP = "~/" . $faildirFTP . "/" . $fnameFTP;
$this->writeLog("Now attempting to move " . $fullfnameFTP . " into " . $fullFaildirFTP, $fn, $etdname);
$ftpRes = true;
if ($this->debug === true) {
$this->writeLog("DEBUG: Not moving ETD files on FTP.", $fn, $etdname);
} else {
$ftpRes = $this->ftp->ftp_rename($fullfnameFTP, $fullFaildirFTP);
}
// Check if there was an error moving the ETD file on the FTP server.
if ($ftpRes === false) {
$this->writeLog("ERROR: Could not move ETD file to 'failed' FTP directory!", $fn, $etdname);
}
$this->writeLog("Moved ETD file to 'failed' FTP directory.", $fn, $etdname);
}
return true;
}
/**
* Ingest files into Fedora
*
* This creates and ingests the following Fedora datastreams:
* - RELS-EXT (external relationship)
* - MODS (updated MODS fole)
* - ARCHIVE (original Proquest MODS)
* - ARCHIVE-PDF (original PDF)
* - PDF (updated PDF with splashpage)
* - FULL_TEXT (full text of PDF)
* - TN (thumbnail image of PDF)
* - PREVIEW (image of PDF first page)
* - XACML (access control policy)
* - RELS-INT (internal relationship)
*
* Next, it ingests the completed object into Fedora.
* Then, tidies up ETD files on FTP server.
* Lastly, send out notification email.
*/
function ingest() {
$fn = "ingest";
// Sanity check to see if there are any ETD files to process.
if ( empty($this->localFiles) ) {
$this->writeLog("Did not find any files to ingest. Quitting.", $fn);
// Shortcut to sending email update.
$message = "No ETD files to process.";
$res = $this->sendEmail($message);
return true;
}
$this->writeLog("Now Ingesting ETD files.", $fn);
global $pidcount, $successCount, $failureCount;
global $successMessage, $failureMessage, $processingMessage;
$successMessage = "The following ETDs ingested successfully:\n";
$failureMessage = "\n\nWARNING!! The following ETDs __FAILED__ to ingest:\n";
$processingMessage = "\n\nThe following staging directories were used:\n";
$fop = '/var/www/html/drupal/sites/all/modules/boston_college/data/fop/cfg.xml';
$executable_fop = '/opt/fop/fop';
$executable_convert = '/usr/bin/convert';
$executable_pdftk = '/usr/bin/pdftk';
$executable_pdftotext = '/usr/bin/pdftotext';
// TODO: list the file path for script log.
// Go through each ETD local file bundle.
$i = 0;
foreach ($this->localFiles as $directory => $submission) {
$i++;
$processingMessage .= " • " .$directory . "\n";
// Pull out the ETD shortname that was generated in getFiles()
$etdname = $this->localFiles[$directory]['ETD_SHORTNAME'];
if ( empty($etdname) ) {
$etdname = substr($this->localFiles[$directory]["ETD"],0,strlen($this->localFiles[$directory]["ETD"])-4);
$this->localFiles[$directory]['ETD_SHORTNAME'] = $etdname;
}
$this->writeLog("BEGIN Ingesting ETD #" . (string)$i . " - " . $etdname, $fn);
// Reconstruct name of zip file from the local ETD work space directory name.
// TODO: there must be a better way to do this...
$directoryArray = explode('/', $directory);
$fnameFTP = array_values(array_slice($directoryArray, -1))[0] . '.zip';
// Build full FTP path for ETD file incase $fetchdirFTP is not the root directory.
$fetchdirFTP = $this->settings['ftp']['fetchdir'];
$fullfnameFTP = "";
if ($fetchdirFTP == "") {
$fullfnameFTP = $fnameFTP;
} else {
$fullfnameFTP = "~/" . $fetchdirFTP . "/" . $fnameFTP;
}
$this->writeLog("The full path of the ETD file on the FTP server is: " . $fullfnameFTP, $fn, $etdname);
// collect some values for ingestHandlerPostProcess()
$this->etd["submission"] = $submission;
$this->etd["fnameFTP"] = $fnameFTP;
$this->etd["fullfnameFTP"] = $fullfnameFTP;
// Check for supplemental files, and create log message.
if ($this->localFiles[$directory]['PROCESS'] === '1') {
// Still Load - but notify admin about supp files.
$this->writeLog("Supplementary files found.", $fn, $etdname);
}
// Instantiated a Fedora object and use the generated PID as its ID.
try {
$object = $this->repository->constructObject($this->localFiles[$directory]['PID']);
$this->writeLog("Instantiated a Fedora object with PID: " . $this->localFiles[$directory]['PID'], $fn, $etdname);
} catch (Exception $e) {
$this->writeLog("ERROR: Could not instanciate Fedora object: " . $e->getMessage(), $fn, $etdname);
$this->writeLog("trace:\n" . $e->getTraceAsString(), $fn, $etdname);
$this->ingestHandlerPostProcess(false, $etdname, $this->etd);
continue;