-
Notifications
You must be signed in to change notification settings - Fork 0
/
idu.drush.inc
2348 lines (2009 loc) · 78.8 KB
/
idu.drush.inc
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
/**
* Some available drush functions...
*
* drush_log('Log an event using drush', 'warning');
* drush_set_error('Set an error with drush.');
* t('Translate strings with drush');
* drush_print('Print to command line with drush');
* drush_print_table($rows, TRUE); //print a command line table with drush
* drush_confirm('Are you sure you want to continue?', $indent = 0); //Add drush confirmation
*
*/
/**
* Implements hook_drush_help().
*/
function idu_drush_help($command) {
switch ($command) {
case 'drush:iduTest':
return t('Just a temporary test feature.');
case 'drush:iduFix':
return t("Attempts to apply the specified 'Fix' to one or more existing PIDs.");
case 'drush:iduUpdate':
return t("Attempts to apply the specified 'Update' to one or more existing PIDs.");
case 'drush:iduSpecial':
return t("Attempts to apply the specified 'Special' operation to a single existing PID.");
case 'drush:iduHandle':
return t("Attempts to apply the specified Handle operation to one or more existing PIDs.");
}
return;
}
/**
* Implements hook_drush_command().
*/
function idu_drush_command( ) {
$items = array();
$items['iduTest'] = array(
'description' => t('Just a temporary test feature.'),
'examples' => array(
'Example' => 'drush iduTest',
),
'aliases' => array('iduTest'),
);
$items['iduFix'] = array(
'description' => t("Attempts to apply the specified 'fix' to one or more existing PIDs."),
'arguments' => array(
'first' => t("First PID to process. The namespace portion of this PID defines the default primary namespace. This parameter may be specified as 'namespace:first-last' in place of the --repeat option."),
'fix' => "Completes the name of the drush_idu_fix_NAME function to be called for each processed object. Available Fix functions are:
Clean -
Removes all unnecessary datastreams from an existing object.
Derivatives -
Attempts to regenerate ALL derivatives for an existing object.
Purge -
Deletes the object. Be careful with this one!
PurgeDatastream -
Deletes the --dsid datastream. Be careful with this one too!
PurgeFamily -
Delete an object and all of its constituents!
PurgeInactive -
Deletes the specified objects if they are in an Inactive or Deleted
state.
ChangeText -
Changes --find text to --replace either in general or within the
value of a specified --xpath.
DCTransform -
Applies the specified self-transform to an object's MODS then
applies a specified MODS-to-DC Transform.
SelfTransform -
Applies the specified --self self-transform to the specified
--dsid datastream.
Thumbnail -
Applies the specified thumbnail image to an object.
IndexSolr -
Attempts to update an object's Solr index.
Relax -
Applies a 'relaxed' POLICY to an object to make it visible
to all.
MIMEFix -
Corrects errant image/jpg and image/tif MIME types,
changing them to image/jpeg and image/tiff.
toPHPP -
Migrates an object from the grinnell:generic collection
to grinnell:phpp.
toIR -
Migrates an object from any collection to the grinnell:generic
collection.
TitleBookPage -
Changes the label/title of a book page to
'Parent Title - Page XXX'.
isConstituentOf -
Changes a literal isConstituentOf value to a proper
attribute form.
CompoundTN -
Creates a CompoundTN datastream for a compound parent object.
The new image datastream is constructed from up to four
child object thumbnails.
ConvertTIFtoJP2 -
Converts an object OBJ datastream to a JP2 using options
specified by --convert or --compress.
CopyDatastream -
Copies the named --dsid datastream to one named --replace, and if
--self is specified, runs the self transform on the original
datastream.
MakeSibling -
Attempts to make the specified object a sibling of an existing
--sibling PID.
MakeFamily -
Converts the specified object to a compound parent and makes the
original content a new child of that parent.
UpdateDC -
Ensures that no specified objects have an empty (or no) dc:date,
dc:creator OR dc:source value. Default values are 'Unspecified' and
'Unknown'.
PurgeElements -
Removes all --xpath matched elements from the specified --dsid
datastream.",
),
'options' => array(
'dsid' => t("Specifies the datastream ID in which to make changes."),
'collection' => t("Specifies the target collection (may include a wildcard like '*test') from which objects will be selected."),
'date' => t("Specifies a dc:date value for the UpdateDC fix. Default is 'Unspecified'."),
'creator' => t("Specifies a dc:creator value for the UpdateDC fix. Default is 'Unknown'."),
'source' => t("Specifies the DC field from which dc:source is to be constructed. Default is 'dc:creator'."),
'xpath' => t("Specifies a metadata XPath whenever one is needed. Note that it is wise to put your XPath in double quotes and use single quotes within where necessary."),
'find' => t("Specifies text to be found (and in some cases replaced)."),
'replace' => t("Specifies the text that 'find' will be replaced with."),
'substitutionsFile' => t("In place of 'find' and 'replace', this option specifies the path to a 'csv' style file from which 'find, replace' pairs will be read."),
'self' => t("Specifies the path to the self-transform XSL file to be applied. Defaults to public://cleanup_mods.xsl."),
'xsl' => t("Specifies the path to the MODS-to-DC transform XSL file to be applied. Defaults to public://mods_to_dc_grinnell-modified-2014-09-24.xsl."),
'image' => t("Specifies the path to a jpeg image to be applied by the specified Fix operation. Defaults to public://audio_thumbnail.jpg."),
'mime' => t("Specifies the OBJ MIME type of objects to process. Defaults to 'image/tiff'."),
'only' => t("Specifies the ONLY DSID to be regenerated, --only=TECHMD is one example. Defaults to * for all derivatives."),
'convert' => t("Specifies a file containing ImageMagick 'convert' options for the ConvertTIFtoJP2 fix."),
'compress' => t("Specifies a file containing Kakadu 'compress' options for the ConvertTIFtoJP2 fix."),
'sibling' => t("Specifies the PID of one existing child object in need of a sibling."),
'parent' => t("Specifies the PID of an existing parent object in need of a child."),
),
'examples' => array(
'Example' => "drush iduF grinnell:10000 ChangeText --dsid=MODS --xpath=\"/mods:mods/mods:relatedItem/mods:identifier[@type='uri']\"",
),
'aliases' => array('iduF'),
);
$items['iduUpdate'] = array(
'description' => t("Attempts to apply the specified 'Update' to one or more existing PIDs."),
'arguments' => array(
'first' => t("First PID to process. The namespace portion of this PID defines the default primary namespace. This parameter may be specified as 'namespace:first-last' in place of the --repeat option."),
'update' => "Completes the name of the drush_idu_update_NAME function to be called for each processed object. Available Update functions are:
Dates -
Reads the FOXML date entities shown here and maps the data to MODS RecordInfo elements.
<foxml:property NAME=\"info:fedora/fedora-system:def/model#createdDate\" VALUE=\"2004-12-10T00:21:58.000Z\"/>
<foxml:property NAME=\"info:fedora/fedora-system:def/view#lastModifiedDate\" VALUE=\"2005-01-20T22:46:07.506Z\"/>",
),
'options' => array(
'repeat' => t("Specifies the total number of PIDs, beginning with 'first' to be processed. Default is 1."),
),
'examples' => array(
'Example' => "drush iduU grinnell:10000 Dates",
),
'aliases' => array('iduU'),
);
$items['iduHandle'] = array(
'description' => t("Attempts to apply the specified Handle operation to one or more existing PIDs."),
'arguments' => array(
'first' => t("First PID to process. The namespace portion of this PID defines the default primary namespace. This parameter may be specified as 'namespace:first-last' in place of the --repeat option."),
'handle_op' => "Completes the name of the drush_idu_Handle_NAME function to be called for each processed object. Available Handle functions are:
Create - Attempts to create a new handle for an existing object.
Modify - Attempts to modify an existing handle for an existing object.",
),
'options' => array(
'repeat' => t("Specifies the total number of PIDs, beginning with 'first' to be processed. Default is 1."),
'force' => t("If specified, handle assignment will proceed even if the mods:identifier[@type='hdl'] element is not compatible with handle_op."),
),
'examples' => array(
'Example' => "drush iduH grinnell:10000 Create --repeat=100",
),
'aliases' => array('iduH'),
);
$items['iduSpecial'] = array(
'description' => t("Attempts to apply the specified 'Special' operation to a single, existing PID."),
'arguments' => array(
'pidAlpha' => t('The primary PID to be processed. Example: grinnell:52.'),
'operation' => t('Completes the name of the idu_drush_special_OPERATION function to be called. Available operations are: PrintRI, SingleCompound, FixArtist and FixStatus.'),
),
'options' => array(
'secondary' => t('An optional secondary PID to be used in the process. Defaults to NULL.'),
),
'examples' => array(
'Example' => "drush iduS grinnell:622 SingleCompound",
),
'aliases' => array('iduS'),
);
return $items;
}
/**
* Examine common iduX command arguments/options and set control variables for subsequent processing.
*
* @param string $pidSpec
* The range (or single) PID argument as specified in the iduX command.
* @param int $last
* Returns the 'last' PID value based on the range specification, if any. Note that $last may or may not be an existing object.
* @param int $pidn
* Returns the integer PID number of 'range'. Note that $pidn may or may not be an existing object.
* @param int $range
* Returns 'last' - 'first' + 1, the total number of PIDs to address.
* @param string $namespace
* Returns the namespace (without a colon!) associated with the PID numbers returned by the function.
* @param bool $return
* If TRUE, the function returns an array of valid PID numbers.
* @return array
* An array of valid PID numbers, without a namespace prefix, from the specified range.
*
*/
function idu_drush_prep($pidSpec, &$last, &$pidn, &$range, &$namespace, $return=FALSE) {
/* Get some necessary options!
$fedoraURL = drush_get_option('fedoraURL', 'http://repository7.grinnell.edu:8080/fedora');
$username = drush_get_option('username', 'fedoraAdmin');
$password = drush_get_option('password', NULL);
// Open the repository.
$connection = new RepositoryConnection($fedoraURL, $username, $password);
$connection->reuseConnection = TRUE;
$repository = new FedoraRepository(
new FedoraApi($connection),
new SimpleCache()); */
// Open a repository connection.
$my_tuque = islandora_get_tuque_connection( );
// $repository = $my_tuque->repository;
// Test fetch the islandora:root object to check the connection.
$pid = "islandora:root";
if (!$fedora_object = islandora_object_load($pid)) {
drush_log("Error: idu_drush_prep was unable to verify a repository connection!", 'error');
return FALSE;
} else {
drush_log("Connection to the repository is complete.", 'status');
}
// Initialize some things.
list($namespace, $pidN) = explode(':', $pidSpec); // Break the PID spec into namespace and PID number.
list($begin, $end) = explode('-', $pidN); // Break $pidN into beginning and end of range, if necessary
$pidn = intval($begin);
if (is_null($end)) {
$repeat = 0;
} else {
$repeat = intval($end) - intval($begin);
}
$range = $repeat + 1;
// If $pidN is not an integer or if $end is null (there is no '-' separator defining a range)
// then we have only one PID to process...do it!
if (intval($pidN) === 0 || is_null($end)) {
drush_log("Completed fetch of a single object PID.", 'status');
return array($pidSpec);
}
/* If no namespace given, use the icg_namespace variable. Otherwise, set the icg_namespace variable.
if (is_null($namespace)) {
$namespace = strstr(variable_get('icg_namespace', 'test'), ':', TRUE);
} else {
variable_set('icg_namespace', "$namespace:");
} */
// Calculate first and last PID numbers and set variables accordingly.
variable_set('icg_first', $pidn);
$last = $pidn + $repeat;
variable_set('icg_last', $last);
$start = date('H:i:s');
drush_log("Starting operation for PIDs $pidn to $last at $start.", 'status');
// Pre-fetch the specified PIDs if requested.
if ($return) {
drush_log("Fetching all valid object PIDs in the specified range.", 'status');
$pids = idu_drush_getPIDs($namespace, $pidn, $last);
drush_log("Completed fetch of " . count($pids) . " valid object PIDs.", 'status');
return $pids;
} else {
return FALSE;
}
}
/**
* Prints a progress bar directly to STDOUT.
*
* Call with no values (NULLs) for $current and $range to initialize the progress bar.
*
* @param string $label
* Label to appear above the bar when initialized.
* @param int|NULL $current
* The current counter (from 0 to $range) in the icg_first to icg_last progression.
* @param int|NULL $range
* The total number of steps in the icg_first to icg_last progression.
*/
function idu_drush_print_progress($label, $current=NULL, $range=NULL) {
static $green = "\033[1;32m";
static $white = "\033[0;37m";
if (is_null($current)) {
$output = $green . "Progress: $label \n";
print $output;
return;
}
$ratio = ($current+1) / $range;
$percentage = floor($ratio * 100) . '%';
$columns = drush_get_context('DRUSH_COLUMNS', 80);
// Subtract 10 characters for the percentage, brackets, spaces and arrow.
$progress_columns = $columns - 10;
// If ratio is 1 (complete), the > becomes a = to make a full bar.
$arrow = ($ratio < 1) ? '>' : '=';
// Print a new line if ratio is 1 (complete). Otherwise, use a CR.
$line_ending = ($ratio < 1) ? "\r" : "\n";
// Determine the current length of the progress string.
$current_length = floor($ratio * $progress_columns);
$progress_string = str_pad('', $current_length, "=");
$output = $green . '[';
$output .= $progress_string . $arrow;
$output .= str_pad('', $progress_columns - $current_length);
$output .= ']';
$output .= str_pad('', 5 - strlen($percentage)) . $percentage;
$output .= $line_ending . $white;
print $output;
}
/**
* Drush idu_fix_* function to purge an object (be careful!) from the repository.
*
* Invoke this function with an iduF process using a command of the form:
* drush iduF <pid> Purge
*
* Note that if the health report indicates this object to have constituents, they will be marked
* for subsequent removal in the pending_drush_commands.sh file.
*
* @param string $pid
* The PID to be purged.
* @param array $options
* There are NO purge-specific options.
* @return int
* The number of repair operations performed, or zero if none.
*/
function idu_drush_fix_Purge($pid, $options=NULL) {
list($ns, $r) = explode(':', $pid);
// For any exception, report and skip this PID
if (!$object = islandora_object_load($pid)) {
drush_log(__FUNCTION__."($pid) returned NO object!", 'error');
return 0;
}
// Get this object's health from the available CSV data. Verify that we have the correct object.
if ($row = or_get($pid)) {
if ($row['B'] === $pid) {
list($nC, $constituents) = idu_get_count_and_content($row['H']); // from the RI
if ($nC > 0) {
idu_drush_post_to_file("Purge existing children of object $pid.", NULL);
$parts = explode(',', $constituents);
foreach ($parts as $part) {
if (preg_match('/^(\d+)$/', $part)) {
idu_drush_post_to_file(NULL, "drush iduF $ns:$part Purge\n");
} else if (preg_match('/^(\d+)\-(\d+)$/', $part, $matches)) {
$num = intval($matches[2]) - intval($matches[1]);
idu_drush_post_to_file(NULL, "drush iduF $ns:$matches[1] Purge --repeat=$num\n");
}
}
}
}
}
idu_repo( )->purgeObject($pid);
return 1;
}
/**
* Drush idu_fix_* function to relax POLICY on an existing object by moving the POLICY datastream out of the way.
*
* Invoke this function during iduC process using an option of the form:
* drush iduF <pid> Relax --find=<text string>
*
* If a --find option is specified the change will be made ONLY if the specified string exists
* in the DC datastream, and if both --find and --dsid exist then only the specified DSID will be searched.
*
* @param int $r
* The PID number to operate on.
* @param array $options
* An array of options. In this case $options['find'] and $options['dsid'] may exist
* @return int
* The number of repair operations performed, or zero if none.
*/
function idu_drush_fix_Relax($pid, $options=NULL) {
// For any exception, report and skip this PID
if (!$object = islandora_object_load($pid)) {
drush_log(__FUNCTION__."($pid) returned NO object!", 'error');
return 0;
}
if (isset($options)) {
$find = (isset($options['find']) ? $options['find'] : NULL);
$dsid = (isset($options['dsid']) ? $options['dsid'] : NULL);
}
if (isset($find)) {
if (isset($dsid)) {
$ds = $object[$dsid];
} else {
$ds = $object['DC'];
}
$content = $ds->content;
if (!strpos($content, $find)) { return 0; }
}
if (isset($object['POLICY'])) {
$newDS = icg_copy_datastream($object, 'POLICY', 'text/xml', 'X', 'Old_POLICY');
$object->ingestDatastream($newDS);
unset($object['POLICY']);
} else {
return 0;
}
return 1;
}
/**
* Drush idu_fix_* function to change RELS-EXT and RELS-INT from text/xml (v6) MIME type application/rdf+xml (v7).
*
* Invoke this function during iduC process using an option of the form:
* --fix=RELSMIME
*
* @param int $r
* The PID number to operate on.
* @return int
* The number of repair operations performed, or zero if none.
*
function idu_drush_fix_RELSMIME($r) {
die('idu_drush_fix_RELSMIME is disabled. ');
$pid = variable_get('icg_namespace').$r;
try {
$object = idu_repo( )->getObject($pid);
} catch (Exception $e) {
return 0; // for any exception...skip this PID
}
$count = 0;
if ($ds = $object->getDatastream('RELS-EXT')) {
$mime = $ds->mimetype;
if ($mime === 'text/xml') {
$ds->mimetype = 'application/rdf+xml';
++ $count;
}
}
if ($ds = $object->getDatastream('RELS-INT')) {
$mime = $ds->mimetype;
if ($mime === 'text/xml') {
$ds->mimetype = 'application/rdf+xml';
++ $count;
}
}
return $count;
}
/**
* Drush idu_drush_fix_* function to correct image/tif and image/jpg MIME types, changing them to image/tiff or
* image/jpeg as needed.
*
* Invoke this function using 'drush iduF <pid> MIMEFix'.
*
* @param string
* The PID number to operate on.
* @return int
* The number of repair operations performed, or zero if none.
*/
function idu_drush_fix_MIMEFix($pid) {
// For any exception, report and skip this PID
if (!$object = islandora_object_load($pid)) {
drush_log(__FUNCTION__."($pid) returned NO object!", 'error');
return 0;
}
$count = 0;
foreach ($object as $ds) {
if ($ds->state != 'A') {
continue;
} else if ($ds->mimetype === 'image/tif') {
$ds->mimetype = 'image/tiff';
++ $count;
} else if ($ds->mimetype === 'image/jpg') {
$ds->mimetype = 'image/jpeg';
++ $count;
}
}
return $count;
}
/**
* Drush idu_fix_* function to change the text of elements in the target datastream and xpath.
*
* Invoke this function via iduF and the 'ChangeText' operation parameter. Something like this...
*
* drush iduF grinnell:501 ChangeText --substitutionsFile="public://findReplace.csv" --dsid=MODS --xpath="/mods:mods/mods:description/mods:identifier[@type='uri']
*
* Applicable options include the following:
*
* --substitutionsFile=<file path> If this option is specified then --find and --replace are ignored and
* pairs of find => replace strings are pulled instead from the named file. Default is NULL.
*
* --find=<string> If this option is specified, and --substitutionsFile is not, then the specified string
* is searched for in the target datastreams and replaced with values specified in --replace.
*
* --replace=<string> See --find above.
*
* --dsid=<string> This option specifies the ID of the datastream to be operated on in each object.
*
* --xpath=<string> This option, if present, specifies an xpath used to query the target datastream. If specified,
* find => replace operations are restricted to the value returned by the xpath, so only the text() value of
* the xpath can be changed. If --xpath is omitted it defaults to NULL and this specifies that the entire
* datastream be treated as a string and find => replace then operates on it as a string. You can effectively
* alter the ‘structure’ of a datastream in this mode so BE VERY CAREFUL!
*
* @param string $pid
* The PID to operate on.
* @param array $options
* An array of options. In this case $options['findReplace'] should carry an associative array
* with one or more find => replace pairs.
* @return int
* The number of repair operations performed, or zero if none.
*/
function idu_drush_fix_ChangeText($pid, $options) {
// For any exception, report and skip this PID
if (!$object = islandora_object_load($pid)) {
drush_log(__FUNCTION__."($pid) returned NO object!", 'error');
return 0;
}
// Get the pre-processed find and replace options.
$findReplace = $options['findReplace'];
// Check for other options...
$dsid = drush_get_option('dsid', 'MODS');
$xpath = drush_get_option('xpath', NULL);
$total = $cnt = 0;
if ($ds = $object[$dsid]) {
$count = 0;
$content = $ds->content;
foreach ($findReplace as $from => $to) {
if (strpos($content, $from)) {
if (is_null($xpath)) {
$content = str_replace($from, $to, $content, $cnt);
$count += $cnt;
} else {
$xml = new DOMDocument;
$xml->loadXML($content);
$dx = new DOMXPath($xml);
$results = $dx->query($xpath);
foreach ($results as $node) {
$value = (string) $node->nodeValue;
if (strpos(' ' . $value, $from)) {
$node->nodeValue = str_replace($from, $to, $value, $cnt);
$count += $cnt;
$content = $xml->saveXML( );
}
}
}
}
}
if ($count > 0) {
$total += $count;
$object[$dsid]->setContentFromString($content);
}
}
return $total;
}
/**
* Callback function for drush iduSpecial.
*
* This callback runs a specified 'special' operation for ONE object.
*
* @param $pid
* The primary PID to process.
* @param string $operation
* Specifies the 'special' operation to be performed by calling function idu_drush_special_$operation.
*/
function drush_idu_iduSpecial($pid, $operation) {
// Get the operation parameter and make sure such a function exists...
$function = 'idu_drush_special_'.$operation;
if (!function_exists($function)) { die("The specified Special function $function does not exist! "); }
// Report some info.
$start = date('H:i:s');
drush_log("Starting iduSpecial '$operation' for PID $pid at $start.", 'status');
$count = call_user_func($function, $pid);
// Done.
$finish = date('H:i:s');
if ($count == 1) {
drush_log("Successfully completed ONE $operation operation at $finish.", 'status');
} else if ($count <> 1) {
drush_log("Successfully completed $count operations at $finish.", 'status');
} else {
drush_log("The Special $operation was unsuccessful and returned NO valid results at $finish.", 'error');
}
}
/**
* Drush idu_fix_* function to regenerate derivatives.
*
* Invoke this function using iduF <pids> Derivatives (with --only=TECHMD if you only want new FITS metadata).
*
* @param string $pid
* The object PID to operate on.
* @return int
* The number of repair operations performed, or zero if none.
*/
function idu_drush_fix_Derivatives($pid) {
// For any exception, report and skip this PID
if (!$object = islandora_object_load($pid)) {
drush_log(__FUNCTION__."($pid) returned NO object!", 'error');
return 0;
}
$only = drush_get_option('only', '*');
// Check for --mime option. If present and the object has no OBJ or the OBJ MIME is not of the correct
// type, then skip this object.
$mime = drush_get_option('mime', NULL);
if (!is_null($mime)) {
if (!$obj = $object['OBJ']) { return 0; }
$objMIME = $obj->mimetype;
if ($mime != $objMIME) { return 0; }
}
$count = 0;
$rels = $object->relationships->get(FEDORA_MODEL_URI, 'hasModel');
$nCM = count($rels);
if ($nCM != 1) { return 0; }
$cModel = $rels[0]['object']['value'];
// Create new derivatives.
switch ($cModel) {
case 'islandora:sp_basic_image' :
if (module_exists('islandora_basic_image')) {
if ($only === '*' || $only === "TN") {
islandora_basic_image_create_thumbnail($object, TRUE);
$count++;
}
if ($only === '*' || $only === "MEDIUM_SIZE") {
islandora_basic_image_create_medium_size($object, TRUE);
$count++;
}
}
if (module_exists('islandora_fits') && ($only === '*' || $only === "TECHMD")) {
$fit = islandora_fits_create_techmd($object, TRUE, array('source_dsid'=>'OBJ'));
if ($fit['success']) { ++$count; }
}
break;
case 'islandora:pageCModel' :
case 'islandora:sp_large_image_cmodel' :
if (module_exists('islandora_large_image')) {
if ($only === '*' || $only === "TN") {
islandora_large_image_create_tn_derivative($object, TRUE);
$count++;
}
if ($only === '*' || $only === "JPG") {
islandora_large_image_create_jpg_derivative($object, TRUE);
$count++;
}
if ($only === '*' || $only === "JP2") {
islandora_large_image_create_jp2_derivative($object, TRUE);
$count++;
}
}
if (module_exists('islandora_fits') && ($only === '*' || $only === "TECHMD")) {
$fit = islandora_fits_create_techmd($object, TRUE, array('source_dsid'=>'OBJ'));
if ($fit['success']) { ++$count; }
}
break;
case 'islandora:sp_pdf' :
if (module_exists('islandora_pdf')) {
if ($only === '*' || $only === "FULL_TEXT") {
islandora_pdf_add_fulltext_derivative($object, TRUE);
$count++;
}
if ($only === '*' || $only === "PREVIEW") {
islandora_pdf_add_preview_derivative($object, TRUE);
$count++;
}
if ($only === '*' || $only === "TN") {
islandora_pdf_add_tn_derivative($object, TRUE);
$count++;
}
}
if (module_exists('islandora_fits') && ($only === '*' || $only === "TECHMD")) {
$fit = islandora_fits_create_techmd($object, TRUE, array('source_dsid'=>'OBJ'));
if ($fit['success']) { ++$count; }
}
break;
case 'islandora:sp-audioCModel' :
if (module_exists('islandora_audio')) {
if ($only === '*' || $only === "TN") {
islandora_audio_create_thumbnail($object, TRUE);
$count++;
}
if ($only === '*' || $only === 'PROXY_MP3' ) {
islandora_audio_create_mp3($object, TRUE);
$count++;
}
}
if (module_exists('islandora_fits') && ($only === '*' || $only === "TECHMD")) {
$fit = islandora_fits_create_techmd($object, TRUE, array('source_dsid'=>'OBJ'));
if ($fit['success']) { ++$count; }
}
break;
}
return $count;
}
/**
* Drush idu_fix_* function to apply MODS self-transform and MODS-to-DC transforms to an existing object.
*
* Invoke this function with an iduF process using a command of the form:
* drush iduF first DCTransform
*
* Applicable options are:
* --self=<path to the MODS self-transform XSL file> Defaults to public://cleanup_mods.xsl
* --xsl=<path to the MODS-to-DC transform XSL file> Defaults to public://mods_to_dc_grinnell-modified-2015-04-03.xsl
*
* @param string $pid
* The PID (from the list of first-to-last) to operate on.
* @return int
* The number of repair operations performed, or zero if none.
*/
function idu_drush_fix_DCTransform($pid) {
// For any exception, report and skip this PID
if (!$object = islandora_object_load($pid)) {
drush_log(__FUNCTION__."($pid) returned NO object!", 'error');
return 0;
}
// Check for an existing MODS... if none, we're done.
if (!$mods = $object['MODS']) { return 0; }
// Check for existing DC record... if not, we're done.
if (!$dc = $object['DC']) { return 0; }
// Get the MODS self-transform.
$xsl = new DOMDocument( );
$transform = drush_get_option('self', 'public://cleanup_mods.xsl');
if (!$xsl->load($transform)) { die("Failed to load Transform file '$transform!'"); }
$xslt = new XSLTProcessor( );
$xslt->importStyleSheet($xsl);
// Apply it to the MODS content.
$document = DOMDocument::loadXml($object['MODS']->content);
if ($doc = $xslt->transformToDoc($document)) {
$after = $doc->saveXML();
$object['MODS']->setContentFromString($after);
}
// Now, get the MODS-to-DC transform.
$xsl = new DOMDocument( );
$transform = drush_get_option('xsl', 'public://mods_to_dc_grinnell-modified-2015-04-03.xsl');
if (!$xsl->load($transform)) { die("Failed to load Transform file '$transform!'"); }
$xslt = new XSLTProcessor( );
$xslt->importStyleSheet($xsl);
// Apply the MODS-to-DC transform.
$document = DOMDocument::loadXml($object['MODS']->content);
if ($doc = $xslt->transformToDoc($document)) {
$after = $doc->saveXML();
$object['DC']->setContentFromString($after);
}
// Re-index this object in Solr.
update_solr_index($pid);
return 1;
}
/**
* Drush idu_fix_* function to apply a specified self-transform existing object datastream.
*
* Invoke this function with an iduF process using a command of the form:
* drush iduF first SelfTransform
*
* Applicable options are:
* --self=<path to the self-transform XSL file> Defaults to public://cleanup_mods.xsl
* --dsid=The target datastream ID such as 'MODS', 'MADS' or 'DC'. Defaults to 'MODS'.
*
* @param string $pid
* The PID (from the list of first-to-last) to operate on.
* @return int
* The number of repair operations performed, or zero if none.
*/
function idu_drush_fix_SelfTransform($pid) {
// For any exception, report and skip this PID
if (!$object = islandora_object_load($pid)) {
drush_log(__FUNCTION__."($pid) returned NO object!", 'error');
return 0;
}
// Check that the specified datastream exists... if not, we're done.
$dsid = drush_get_option('dsid', 'MODS');
if (!$ds = $object[$dsid]) { return 0; }
// Get the specified self-transform.
$xsl = new DOMDocument( );
$transform = drush_get_option('self', 'public://cleanup_mods.xsl');
if (!$xsl->load($transform)) { die("Failed to load Transform file '$transform!'"); }
$xslt = new XSLTProcessor( );
$xslt->importStyleSheet($xsl);
// Apply it to the $ds content.
$document = DOMDocument::loadXml($object[$dsid]->content);
if ($doc = $xslt->transformToDoc($document)) {
$after = $doc->saveXML();
$object[$dsid]->setContentFromString($after);
}
// Re-index this object in Solr.
update_solr_index($pid);
return 1;
}
/**
* Returns an array of existing PIDs (numbers only, no namespace prefix) found in the specified namespace and range.
*
* @param string $ns
* The target namespace (without a colon) of the PIDs to be returned.
* @param $first
* The first PID number to check.
* @param $last
* The last PID number to check.
* @return array
* The PID numbers of all objects found in the range. The variable icg_last is
* automatically set to largest number returned here.
*
* @TODO This should use a query against the RI!
*
*/
function idu_drush_getPIDs($ns, $first, $last) {
$pids = array( );
// @TODO Check the --collection option to restrict selection. Defaults to *, ALL collections.
// Loop through the repo looking for objects in the specified range.
for ($largest=0, $i=$first, $notFound=0; $i<=$last; $i++) {
$pid = "$ns:$i";
// For any exception, report and skip this PID
if (!$object = islandora_object_load($pid)) {
drush_log(__FUNCTION__."($pid) returned NO object!", 'warning');
$notFound++;
continue; // for any exception...skip this PID
}
$pids[] = $i;
$largest = $i;
}
// If any PIDs were not found, report them.
if ($notFound > 0) { drush_log("A total of $notFound PIDs in the specified range were NOT FOUND.", 'warning'); }
// Set the icg_last value.
variable_set('icg_last', $largest);
return $pids;
}
/**
* Write a comment and/or follow-up iduF (or similar command) to a script for use later on.
*
* @param string $comment
* @param string $command
*/
function idu_drush_post_to_file($comment, $command, $path=NULL) {
// if $path is NULL... Fetch the --script option.
if (is_null($path)) {
$script = drush_get_option('script', 'public://iduPendingOps.sh');
} else {
$script = $path;
}
// If there is a comment, prepend $comment with # and a timestamp.
if (!is_null($comment)) {
file_put_contents($script, "# $comment [" . date('Y-m-d H:i:s') . "] \n", FILE_APPEND);
}
// Now output the command as-is.
if (!is_null($command)) {
file_put_contents($script, "$command\n", FILE_APPEND);
}
}
/**
* Add a child object (page or constituent) to an existing list of children.
*
* @param string $kids
* Existing '[count] list' string.
* @param integer $newKid
* New ID to be added, if necessary.
* @return bool|string
* Returns an updated '[count] list' or FALSE for no change.
*/
function idu_drush_add_child_to_list($kids, $newKid) {
$new = intval($newKid);
$range = array( );
list($count, $content) = idu_get_count_and_content($kids);
$children = explode(',', $content);
if ($count == 0) { // first child...simply add it
return "[1] $newKid";
} else if (in_array($newKid, $children)) { // child already in the list, do nothing
return FALSE;
} else { // child not already present, unless it falls in an existing range
foreach ($children as $child) {
if (preg_match('/(\d+)-(\d+)/', $child, $range)) { // we have a range of values...see if $newKid is within
if (($new >= intval($range[1])) && ($new <= intval($range[2]))) { return FALSE; }
}
}
// If we reach this point then we know $newKid is not yet accounted for...add it.
++ $count;
$last = end($children);
if (preg_match('/(\d+)-(\d+)/', $last, $range)) { // we have a range of values in the last position, add to it
if (intval($range[2]) == $new-1) { // extend the range
$range[2] = $new;
$updated = "[$count] ";