forked from Islandora/islandora_bagit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathislandora_bagit.module
1276 lines (1166 loc) · 46.8 KB
/
islandora_bagit.module
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
/**
* @file
* Module to create BagIt Bags from Islandora objects. Requires the library at
* https://github.com/scholarslab/BagItPHP. Consult the README.txt for
* instructions.
*/
/**
* Implements hook_init().
*/
function islandora_bagit_init() {
if (isset($_SESSION['islandora_object'])) {
unset($_SESSION['islandora_object']);
}
drupal_register_shutdown_function('islandora_bagit_create_bag_on_shutdown');
}
/**
* Implements hook_permission().
*/
function islandora_bagit_permission() {
return array(
'create Islandora Bags' => array(
'title' => t('Create Islandora Bags'),
'description' => t('Create Islandora Bags'),
),
'administer Islandora BagIt' => array(
'title' => t('Administer Islandora BagIt'),
'description' => t('Administer Islandora BagIt'),
),
);
}
/**
* Custom menu access callback.
*
* @param object $islandora_object
* The Islandora object to create a Bag for.
*
* @return bool
* TRUE if user has access, FALSE if not.
*/
function islandora_bagit_access_check($islandora_object) {
return islandora_object_access('create Islandora Bags', $islandora_object);
}
/**
* Implements hook_menu().
*/
function islandora_bagit_menu() {
$items = array();
$items['admin/islandora/tools/bagit'] = array(
'title' => 'Islandora BagIt',
'description' => 'Configure Islandora BagIt.',
'page callback' => 'drupal_get_form',
'page arguments' => array('islandora_bagit_admin_settings'),
'access arguments' => array('administer Islandora BagIt'),
'type' => MENU_NORMAL_ITEM,
);
$items['islandora/object/%islandora_object/manage/bagit'] = array(
'title' => 'Create Bag(s)',
'page callback' => 'islandora_bagit_create_bag',
'page arguments' => array(2),
'access callback' => 'islandora_bagit_access_check',
'access arguments' => array(2),
'type' => MENU_LOCAL_TASK,
);
return $items;
}
/**
* Admin settings form builder.
*/
function islandora_bagit_admin_settings() {
$form['islandora_bagit_library_dir'] = array(
'#title' => t('Location of the BagIt library'),
'#type' => 'textfield',
'#size' => 60,
'#default_value' => variable_get('islandora_bagit_library_dir', 'BagItPHP'),
'#description' => t("Directory where the Scholars' Lab BagIt for PHP library
is installed, relative to sites/all/libraries. Do not use a leading or
trailing slash."),
'#maxlength' => 255,
'#required' => TRUE,
);
$form['islandora_bagit_bag_tmp_dir'] = array(
'#title' => t('Temporary directory for unserialized Bags'),
'#type' => 'textfield',
'#size' => 60,
'#default_value' => variable_get('islandora_bagit_bag_tmp_dir', file_directory_temp()),
'#description' => t("Filesystem directory where the unserialized Bag
directories are written, named by PID. Needs to exist and to be
writable by the web server. Do not include the trailing slash."),
'#maxlength' => 255,
'#required' => TRUE,
);
$form['islandora_bagit_delete_unserialized_bag'] = array(
'#type' => 'checkbox',
'#title' => t('Delete unserialized (zipped) Bags.'),
'#default_value' => variable_get('islandora_bagit_delete_unserialized_bag', 1),
'#description' => t('Check this option if you want to automatically delete
unserialized Bags.'),
);
$bagit_output_dir = variable_get('file_public_path', conf_path() . '/files');
$form['islandora_bagit_bag_output_dir'] = array(
'#title' => t('Output directory for serialized Bags'),
'#type' => 'textfield',
'#size' => 60,
'#default_value' => variable_get('islandora_bagit_bag_output_dir', $bagit_output_dir),
'#description' => t("Filesystem directory where serialized (.tgz or .zip) Bags
are written, named by PID. Needs to exist and to be writable by the web
server. Do not include the trailing slash. If you want users to be able to
download the Bags, this directory needs to be below your site's file system directory."),
'#maxlength' => 255,
'#required' => TRUE,
);
$form['islandora_bagit_create_on_ingest'] = array(
'#type' => 'checkbox',
'#title' => t('Create Bag on object ingest'),
'#default_value' => variable_get('islandora_bagit_create_on_ingest', 0),
'#description' => t('Check this option if you want to create a Bag for
an object when it is ingested.'),
);
$form['islandora_bagit_create_on_modify'] = array(
'#type' => 'checkbox',
'#title' => t('Create Bag on object modification'),
'#default_value' => variable_get('islandora_bagit_create_on_modify', 0),
'#description' => t('Check this option if you want to create a Bag for
an object when it or any of its datasteams are modified.'),
);
$form['islandora_bagit_provide_download_link'] = array(
'#type' => 'checkbox',
'#title' => t('Provide link to download the Bag'),
'#default_value' => variable_get('islandora_bagit_provide_download_link', 1),
'#description' => t("This link will work only if 'Output directory for
serialized Bags' is accessible via the web."),
);
$form['islandora_bagit_multiple_bag_type'] = array(
'#type' => 'select',
'#title' => t('Collection batch type'),
'#default_value' => variable_get('islandora_bagit_multiple_bag_type', 'object'),
'#options' => array(
'object' => t('one Bag per object'),
'collection' => t('one Bag per collection'),
'no_children' => t('the Collection object only; children will not be bagged'),
),
'#description' => t('Choose whether collection-level batches create one Bag per object or one Bag per collection.'),
);
$form['islandora_bagit_serialize_collection_bags'] = array(
'#type' => 'checkbox',
'#title' => t('Serialize collection Bags.'),
'#default_value' => variable_get('islandora_bagit_serialize_collection_bags', 0),
'#description' => t('Check this option if you want to serialize (zip) one-Bag-per-collection Bags.'),
);
$description = t("Base name for the Bags. The object's PID is appended to this value.");
$default_bag_name = variable_get('islandora_bagit_bag_name', 'Bag-');
$form['islandora_bagit_bag_name'] = array(
'#title' => t('Bag name'),
'#type' => 'textfield',
'#size' => 60,
'#default_value' => $default_bag_name,
'#description' => $description,
'#maxlength' => 255,
'#required' => TRUE,
);
$form['islandora_bagit_show_messages'] = array(
'#type' => 'checkbox',
'#title' => t('Display messages'),
'#default_value' => variable_get('islandora_bagit_show_messages', 1),
'#description' => t('Check this option if you want to display messages
associated with Bag creation to the end user.'),
);
$form['islandora_bagit_log_bag_creation'] = array(
'#type' => 'checkbox',
'#title' => t('Log the creation of Bags'),
'#default_value' => variable_get('islandora_bagit_log_bag_creation', 1),
'#description' => t('Check this option if you want to log the
creation of Bags to the Drupal watchdog.'),
);
$form['islandora_bagit_compression_type'] = array(
'#type' => 'select',
'#title' => t('Compression type'),
'#default_value' => variable_get('islandora_bagit_compression_type', 'tgz'),
'#options' => array(
'tgz' => t('tgz'),
'zip' => t('zip'),
),
'#description' => t('The compression used on serialized Bags.'),
);
$object_plugins = islandora_bagit_get_plugins('object');
foreach ($object_plugins as $plugin) {
$object_plugin_options[$plugin] = $plugin;
}
$form['islandora_bagit_object_plugins'] = array(
'#title' => t('Object plugins'),
'#type' => 'checkboxes',
'#options' => $object_plugin_options,
'#default_value' => variable_get('islandora_bagit_object_plugins', array(
'plugin_object_ds_basic' => 'plugin_object_ds_basic',
)),
'#description' => t("Object-level plugins. Plugins are fired in their order in this list and all add files to the same Bag. You should choose at least one plugin."),
);
$collection_plugins = islandora_bagit_get_plugins('collection');
foreach ($collection_plugins as $plugin) {
$collection_plugin_options[$plugin] = $plugin;
}
$form['islandora_bagit_collection_plugin'] = array(
'#title' => t('Collection plugins'),
'#type' => 'select',
'#options' => $collection_plugin_options,
'#default_value' => variable_get('islandora_bagit_collection_plugin', ''),
);
$form['islandora_bagit_baginfo_settings'] = array(
'#title' => t('Bag metadata'),
'#type' => 'fieldset',
'#collapsible' => TRUE,
'#collapsed' => TRUE,
'#description' => t("Optional metadata written to the Bag's bag-info.txt file."),
);
$form['islandora_bagit_baginfo_settings']['islandora_bagit_transferring_organization'] = array(
'#title' => t('Organization transferring the content'),
'#type' => 'textfield',
'#size' => 60,
'#default_value' => variable_get('islandora_bagit_transferring_organization', ''),
'#description' => t("Leave blank to omit from bag-info.txt."),
'#maxlength' => 255,
);
$form['islandora_bagit_baginfo_settings']['islandora_bagit_transferring_organization_address'] = array(
'#title' => t('Mailing address of the organization'),
'#type' => 'textfield',
'#size' => 60,
'#default_value' => variable_get('islandora_bagit_transferring_organization_address', ''),
'#description' => t("Leave blank to omit from bag-info.txt."),
'#maxlength' => 255,
);
$form['islandora_bagit_baginfo_settings']['islandora_bagit_contact_name'] = array(
'#title' => t('Contact name'),
'#type' => 'textfield',
'#size' => 60,
'#default_value' => variable_get('islandora_bagit_contact_name', ''),
'#description' => t("Person at the source organization who is responsible
for the content transfer. Leave blank to omit from bag-info.txt."),
'#maxlength' => 255,
);
$form['islandora_bagit_baginfo_settings']['islandora_bagit_contact_phone'] = array(
'#title' => t('Contact phone'),
'#type' => 'textfield',
'#size' => 60,
'#default_value' => variable_get('islandora_bagit_contact_phone', ''),
'#description' => t("International format telephone number of person or
position responsible. Leave blank to omit from bag-info.txt."),
'#maxlength' => 255,
);
$form['islandora_bagit_baginfo_settings']['islandora_bagit_contact_email'] = array(
'#title' => t('Contact email'),
'#type' => 'textfield',
'#size' => 60,
'#default_value' => variable_get('islandora_bagit_contact_email', ''),
'#description' => t("Fully qualified email address of person or
position responsible. Leave blank to omit from bag-info.txt."),
'#maxlength' => 255,
);
$form['islandora_bagit_baginfo_settings']['islandora_bagit_profile_uri'] = array(
'#type' => 'textfield',
'#title' => t('BagIt profile URI'),
'#default_value' => variable_get('islandora_bagit_profile_uri', ''),
'#description' => t('See https://github.com/ruebot/bagit-profiles for more information. Note that Islandora BagIt does not validate Bags against profiles.'),
'#maxlength' => 255,
);
$form['islandora_bagit_baginfo_settings']['islandora_bagit_bagging_date'] = array(
'#type' => 'checkbox',
'#title' => t('Bagging date'),
'#default_value' => variable_get('islandora_bagit_bagging_date', 0),
'#description' => t("Date (YYYY-MM-DD) that the content was prepared for
delivery."),
);
$form['islandora_bagit_baginfo_settings']['islandora_bagit_payload_octetstream_sum'] = array(
'#type' => 'checkbox',
'#title' => t('Octetstream sum'),
'#default_value' => variable_get('islandora_bagit_payload_octetstream_sum', FALSE),
'#description' => t('The "octetstream sum" of the payload.'),
);
return system_settings_form($form);
}
/**
* Creates the object-level Bag.
*
* Also acts as the 'controller' to pass program flow off to the appropriate
* batch functions.
*
* @param object $islandora_object
* The Islandora object to create a Bag for.
*
* @return string|array
* Either an empty array, a blank string, or a string containing
* a link to 'Download the Bag.'
*/
function islandora_bagit_create_bag($islandora_object) {
// First, check to see if the object is a collection, and if it is,
// reroute to the relevant batch function.
foreach ($islandora_object as $ds) {
if ($ds->id == 'COLLECTION_POLICY') {
if (variable_get('islandora_bagit_multiple_bag_type', 'object') == 'object') {
islandora_bagit_create_object_bag_batch($islandora_object);
}
elseif (variable_get('islandora_bagit_multiple_bag_type', 'object') == 'collection') {
islandora_bagit_create_collection_bag_batch($islandora_object);
}
elseif (variable_get('islandora_bagit_multiple_bag_type', 'object') == 'no_children') {
break;
}
return array();
}
}
// Sanitize the PID so it is usable in file paths.
$pid = str_replace(array(':', '-'), '_', $islandora_object->id);
// Save all the datastreams to a randomly named temporary directory so
// they can be added to the Bag. We delete these files after creating the Bag.
$random_string = substr(md5(rand()), 0, 7);
$tmp_ds_directory = variable_get('islandora_bagit_bag_tmp_dir', file_directory_temp()) .
'/islandora_bagit_tmp/' . $random_string;
if (!file_exists($tmp_ds_directory)) {
mkdir($tmp_ds_directory, 0777, TRUE);
}
// Load the BagItPHP library.
$bagit_library_dir = variable_get('islandora_bagit_library_dir', 'BagItPHP');
if ($bagit_library_path = libraries_get_path($bagit_library_dir)) {
require_once $bagit_library_path . '/lib/bagit.php';
}
$bag_file_name = variable_get('islandora_bagit_bag_name', 'Bag-') . $pid;
$bag_output_path = variable_get('islandora_bagit_bag_output_dir', '/tmp') .
DIRECTORY_SEPARATOR . $bag_file_name;
// Because the BagItPHP library does some things by default if the bag output
// directory already exists (like read the fetch.txt file), we always need to
// delete the directory if it exists.
if (file_exists($bag_output_path)) {
rrmdir($bag_output_path);
}
// A list of all the files added to the bag, to show the user and add to
// the watchdog entries.
$all_added_files = array();
// Needed for islandora_bagit_get_octetstream_sum().
$all_added_files_sources = array();
// Get bag-info.txt metadata.
$bag_info = islandora_bagit_create_baginfo();
// Create a new bag.
$bag = new BagIt($bag_output_path, TRUE, TRUE, FALSE, $bag_info);
// Iterate through all the object plugins. Each plugin must return the
// parameters required for addFile() (i.e., a list of file source and
// destination paths) or FALSE if it doesn't want to create a file.
$plugins = variable_get('islandora_bagit_object_plugins', array(''));
$files_to_add = array();
if (count($plugins)) {
foreach ($plugins as $plugin => $enabled) {
if ($enabled) {
module_load_include('inc', 'islandora_bagit', 'plugins/' . $plugin);
$plugin_init_function = 'islandora_bagit_' . $plugin . '_init';
// Process the plugins.
if ($files_to_add = $plugin_init_function($islandora_object, $tmp_ds_directory)) {
foreach ($files_to_add as $file) {
$bag->addFile($file['source'], $file['dest']);
$all_added_files[] = $file['dest'];
$all_added_files_sources[] = $file['source'];
}
}
}
}
// Generate octetstream sum.
if (variable_get('islandora_bagit_payload_octetstream_sum', 0)) {
$sum = islandora_bagit_get_octetstream_sum($all_added_files_sources);
$bag->setBagInfoData('Payload-Oxum', $sum);
}
$bag->update();
}
else {
drupal_set_message(t('There are no files to add to the Bag.'), 'warning');
watchdog('bagit', 'BagIt Bag not created for !object: plugins found no files.',
array('!object' => $islandora_object->id));
return '';
}
// Allow other modules to modify the Bag using
// mymodule_islandora_bagit_alter($bag, $islandora_object).
drupal_alter('islandora_bagit', $bag, $islandora_object);
// Write out the serialized (i.e., compressed) Bag.
$serialized_bag_path = variable_get('islandora_bagit_bag_output_dir', '/tmp') .
DIRECTORY_SEPARATOR . $bag_file_name;
$compression_type = variable_get('islandora_bagit_compression_type', 'tgz');
if (file_exists($serialized_bag_path . '.' . $compression_type)) {
unlink($serialized_bag_path . '.' . $compression_type);
}
$bag->package($serialized_bag_path, $compression_type);
if (variable_get('islandora_bagit_delete_unserialized_bag', 1)) {
rrmdir($bag_output_path);
}
// Delete the temp directory created by file create plugins, if it exists.
$bag_tmp_dir = variable_get('islandora_bagit_bag_tmp_dir', file_directory_temp()) .
DIRECTORY_SEPARATOR . $pid;
if (file_exists($bag_tmp_dir)) {
rrmdir($bag_tmp_dir);
}
// Clean up the temp directory where we downloaded the datastreams.
if (file_exists($tmp_ds_directory)) {
rrmdir($tmp_ds_directory);
}
$all_added_files = array_unique($all_added_files);
$serialized_all_added_files = implode(', ', $all_added_files);
if (variable_get('islandora_bagit_log_bag_creation', 1)) {
watchdog('islandora_bagit', 'Bag created for PID !pid (!files).',
array('!pid' => $islandora_object->id, '!files' => $serialized_all_added_files));
}
$serialized_bag_path .= '.' . $compression_type;
if (variable_get('islandora_bagit_show_messages', 1)) {
drupal_set_message(t("Bag created and saved at %path", array(
'%path' => $serialized_bag_path,
)));
drupal_set_message(t("Files added: %files",
array('%files' => $serialized_all_added_files)));
}
// Allow other modules to fire the post-Bag creation hook.
$post_create_data = module_invoke_all('islandora_bagit_post_create', $islandora_object->id, $serialized_bag_path);
if (variable_get('islandora_bagit_provide_download_link', 1)) {
// file_build_uri() needs a relative path.
if (variable_get('islandora_file_default_scheme') == 'private') {
$drupal_files_path = variable_get('islandora_file_private_path');
}
else {
$drupal_files_path = variable_get('islandora_file_public_path', conf_path() . '/files');
}
$relative_bag_path = preg_replace("#$drupal_files_path#", '', $serialized_bag_path);
$download_path = file_create_url(file_build_uri($relative_bag_path));
return l(t('Download the Bag'), $download_path);
}
else {
return array();
}
}
/**************************
* Object batch functions *
*************************/
/**
* Creates a set of Bags, one per child object, via the Drupal Batch API.
*
* @param object $islandora_object
* The Islandora collection object to create the Bags for.
*/
function islandora_bagit_create_object_bag_batch($islandora_object) {
$objects_to_include = islandora_bagit_get_batch_members($islandora_object);
$objects_to_include[] = $islandora_object->id;
$num_objects = count($objects_to_include);
$operations = array();
// Add earch object in the collection to the $operations array.
foreach ($objects_to_include as $pid) {
$operations[] = array(
'islandora_bagit_process_object_batch',
array($pid, $num_objects),
);
}
$batch = array(
'operations' => $operations,
'title' => t('Creating Bags'),
'init_message' => t('Initializing'),
'error_message' => t('An error occurred'),
'finished' => 'islandora_bagit_object_batch_finished',
);
batch_set($batch);
// batch_process() is required if the batch is not initiated within a form
// handler. Parameter is the URL to redirect the user to, in this case, do
// not redirect.
batch_process('');
}
/**
* Process one object in the batch.
*
* @param string $pid
* The current object's PID.
*
* @param string $num_objects
* The number of objects in this batch.
*
* @param array $context
* The Batch API $context array.
*/
function islandora_bagit_process_object_batch($pid, $num_objects, &$context) {
if (empty($context['sandbox'])) {
$context['sandbox'] = array();
$context['sandbox']['progress'] = 0;
$context['sandbox']['current_node'] = 0;
$context['sandbox']['max'] = $num_objects;
$context['results'][] = $pid;
$context['message'] = t('Creating Bag for object @pid', array('@pid' => $pid));
}
$islandora_object = islandora_object_load($pid);
islandora_bagit_create_bag($islandora_object);
}
/**
* Batch API 'finished' callback.
*
* @param bool $success
* TRUE if no fatal PHP errors were detected.
*
* @param array $results
* List of all the object PIDs processed.
*
* @param array $operations
* List of all the operations processed.
*/
function islandora_bagit_object_batch_finished($success, $results, $operations) {
if ($success) {
drupal_set_message(t('@count Bags processed.', array('@count' => count($results))));
}
else {
$error_operation = reset($operations);
drupal_set_message(t('An error occurred while processing @operation with arguments : @args',
array(
'@operation' => $error_operation[0],
'@args' => print_r($error_operation[0], TRUE),
)));
}
}
/******************************
* Collection batch functions *
* ***************************/
/**
* Creates a single Bag containing all objects in a collection.
*
* Uses the Drupal Batch API.
*
* @param object $islandora_object
* The Islandora collection object to create the Bag for.
*/
function islandora_bagit_create_collection_bag_batch($islandora_object) {
// Sanitize the PID so it is usable in file paths.
$pid = str_replace(array(':', '-'), '_', $islandora_object->id);
// Save all the datastreams to a randomly named temporary directory so
// they can be added to the Bag. We delete these files after creating the Bag.
$random_string = substr(md5(rand()), 0, 7);
$tmp_ds_directory = variable_get('islandora_bagit_bag_tmp_dir', file_directory_temp()) .
'/islandora_bagit_tmp/' . $random_string;
if (!file_exists($tmp_ds_directory)) {
mkdir($tmp_ds_directory, 0777, TRUE);
}
// Load the BagItPHP library.
$bagit_library_dir = variable_get('islandora_bagit_library_dir', 'BagItPHP');
if ($bagit_library_path = libraries_get_path($bagit_library_dir)) {
require_once $bagit_library_path . '/lib/bagit.php';
}
$bag_file_name = variable_get('islandora_bagit_bag_name', 'Bag-') . $pid;
$bag_output_path = variable_get('islandora_bagit_bag_output_dir', '/tmp') .
DIRECTORY_SEPARATOR . $bag_file_name;
// Because the BagItPHP library does some things by default if the bag output
// directory already exists (like read the fetch.txt file), we always need to
// delete the directory if it exists.
if (file_exists($bag_output_path)) {
rrmdir($bag_output_path);
}
// A list of all the files added to the bag, to show the user and add to
// the watchdog entries. This is populated in
// islandora_bagit_process_collection_batch().
$_SESSION['islandora_bagit_all_added_files'] = array();
if (variable_get('islandora_bagit_payload_octetstream_sum', FALSE)) {
// Variables to hold the number of files in the batch bag and their
// summed size.
$_SESSION['islandora_bagit_batch_octetstream_sum_count'] = '0';
$_SESSION['islandora_bagit_batch_octetstream_sum_size'] = '0';
}
// Get list of all objects to include in this Bag.
$objects_to_include = islandora_bagit_get_batch_members($islandora_object);
$objects_to_include[] = $islandora_object->id;
$num_objects = count($objects_to_include);
$operations = array();
$collection_plugins = variable_get('islandora_bagit_collection_plugins', array(''));
$object_plugins = variable_get('islandora_bagit_object_plugins', array(''));
// Get bag-info.txt metadata.
$bag_info = islandora_bagit_create_baginfo();
// Create a new bag.
$bag = new BagIt($bag_output_path, TRUE, TRUE, FALSE, $bag_info);
islandora_bagit_serialize_bag_object($bag, $pid, $tmp_ds_directory);
// We need the $pid in islandora_bagit_collection_batch_finish_bag().
$_SESSION['islandora_bagit_collection_object_pid'] = $pid;
// Iterate through all the objects and create an entry in $operations
// for each one.
foreach ($objects_to_include as $object_to_include_pid) {
if (count($collection_plugins) && count($object_plugins)) {
$operations[] = array('islandora_bagit_process_collection_batch',
array($object_to_include_pid, $num_objects, $tmp_ds_directory));
}
else {
drupal_set_message(t('There are no files to add to the Bag.'), 'warning');
watchdog('bagit', 'BagIt Bag not created for !object: plugins found no files.',
array('!object' => $islandora_object->id));
return '';
}
}
if (count($operations)) {
$batch = array(
'operations' => $operations,
'title' => t('Creating Bag'),
'init_message' => t('Initializing'),
'error_message' => t('An error occurred'),
'finished' => 'islandora_bagit_collection_batch_finished',
);
// It would be awesome if we could use $batch['progressive'] = FALSE
// but that is pointless (see https://drupal.org/node/638712).
batch_set($batch);
// batch_process() is required if the batch is not initiated within a form
// handler. Paramter is the URL to redirect the user to, in this case, do
// not redirect.
batch_process('');
}
else {
return '';
}
}
/**
* Process one object in the collection batch.
*
* @param string $pid
* The current object's PID.
*
* @param string $num_objects
* The number of objects in this batch.
*
* @param array $context
* The Batch API $context array.
*/
function islandora_bagit_process_collection_batch($pid, $num_objects, $tmp_ds_directory, &$context) {
// Load the BagItPHP library to avoid 'incomplete object' errors.
$bagit_library_dir = variable_get('islandora_bagit_library_dir', 'BagItPHP');
if ($bagit_library_path = libraries_get_path($bagit_library_dir)) {
require_once $bagit_library_path . '/lib/bagit.php';
}
$bag = islandora_bagit_unserialize_bag_object();
if (empty($context['sandbox'])) {
$context['sandbox'] = array();
$context['sandbox']['progress'] = 0;
$context['sandbox']['current_node'] = 0;
$context['sandbox']['max'] = $num_objects;
$context['results'][] = $pid;
$context['message'] = t('Adding object @pid to Bag', array('@pid' => $pid));
}
$islandora_object = islandora_object_load($pid);
// Iterate through all the object plugins. Each plugin must return the
// parameters required for addFile() (i.e., a list of file source and
// destination paths) or FALSE if it doesn't want to create a file.
$collection_plugin = variable_get('islandora_bagit_collection_plugin', '');
$object_plugins = variable_get('islandora_bagit_object_plugins', array(''));
// Since $bag->addFile() is being called after we loop through all the object
// plugins, we need an array where we can accumulate the returned arrays from
// each plugin.
$all_files_to_add = array();
foreach ($object_plugins as $object_plugin => $enabled) {
if ($enabled) {
module_load_include('inc', 'islandora_bagit', 'plugins/' . $object_plugin);
$object_plugin_init_function = 'islandora_bagit_' . $object_plugin . '_init';
// Process the object plugins.
$files_to_add = $object_plugin_init_function($islandora_object, $tmp_ds_directory);
}
if (count($files_to_add)) {
foreach ($files_to_add as $file_to_add) {
if (!in_array($file_to_add, $all_files_to_add)) {
$all_files_to_add[] = $file_to_add;
}
}
}
}
if (count($all_files_to_add)) {
// Pass $all_files_to_add from the object plugins to the collection plugin.
module_load_include('inc', 'islandora_bagit', 'plugins/' . $collection_plugin);
$collection_plugin_init_function = 'islandora_bagit_' . $collection_plugin . '_init';
$all_files_to_add = $collection_plugin_init_function($islandora_object, $all_files_to_add, $tmp_ds_directory);
// Now that the collection plugin has been fired, update the Bag.
$all_added_files = $_SESSION['islandora_bagit_all_added_files'];
foreach ($all_files_to_add as $file) {
$bag->addFile($file['source'], $file['dest']);
$all_added_files[] = $file['dest'];
// Update the octetstream values for this batch Bag.
if (variable_get('islandora_bagit_payload_octetstream_sum', FALSE)) {
$_SESSION['islandora_bagit_batch_octetstream_sum_count']++;
$_SESSION['islandora_bagit_batch_octetstream_sum_size'] = $_SESSION['islandora_bagit_batch_octetstream_sum_size'] +
filesize($file['source']);
}
}
$bag->update();
$_SESSION['islandora_bagit_all_added_files'] = array_unique($all_added_files);
// Serialize the Bag object for later use.
islandora_bagit_serialize_bag_object($bag, $pid, $tmp_ds_directory);
}
}
/**
* Batch API 'finished' callback.
*
* @param bool $success
* TRUE if no fatal PHP errors were detected.
*
* @param array $results
* List of all the object PIDs processed.
*
* @param array $operations
* List of all the operations processed.
*/
function islandora_bagit_collection_batch_finished($success, $results, $operations) {
if ($success) {
islandora_bagit_collection_batch_finish_bag();
// Clean up session variables added by the collection-level batch.
unset($_SESSION['islandora_bagit_tmp_ds_directory']);
unset($_SESSION['islandora_bagit_collection_object_pid']);
unset($_SESSION['islandora_bagit_all_added_files']);
drupal_set_message(t('@count objects added to Bag.', array('@count' => count($results))));
}
else {
$error_operation = reset($operations);
drupal_set_message(t('An error occurred while processing @operation with arguments : @args',
array(
'@operation' => $error_operation[0],
'@args' => print_r($error_operation[0], TRUE),
)));
}
}
/**
* Placeholder line to meet Coder style checks.
*
* Performs the tasks that follow batch_process() in
* islandora_bagit_create_collection_bag_batch().
*
* Since batch_process() performs a redirect, any code that follows it
* is not run. Setting $batch['progressive'] to FALSE is supposed to
* avoid the redirect but is broken; see issue at
* https://drupal.org/node/638712. The only way to get the code
* in this function to fire is to call it in the batch's'finished'
* callback.
*
* return @array
*/
function islandora_bagit_collection_batch_finish_bag() {
$pid = $_SESSION['islandora_bagit_collection_object_pid'];
$tmp_ds_directory = $_SESSION['islandora_bagit_tmp_ds_directory'];
$all_added_files = $_SESSION['islandora_bagit_all_added_files'];
$bag_file_name = variable_get('islandora_bagit_bag_name', 'Bag-') . $pid;
$bag_output_path = variable_get('islandora_bagit_bag_output_dir', '/tmp') .
DIRECTORY_SEPARATOR . $bag_file_name;
// Load the BagItPHP library to avoid 'incomplete object' errors.
$bagit_library_dir = variable_get('islandora_bagit_library_dir', 'BagItPHP');
if ($bagit_library_path = libraries_get_path($bagit_library_dir)) {
require_once $bagit_library_path . '/lib/bagit.php';
}
// Now that we have completed the batch and added all objects, get the
// Bag from the session so we can alter it, serialize it, et.
$bag = islandora_bagit_unserialize_bag_object();
// Add octetstream sum and clean up the related session variables.
if (variable_get('islandora_bagit_payload_octetstream_sum', FALSE)) {
// Variables to hold the number of files in the batch bag and their
// summed size.
$octetstream_num_files = $_SESSION['islandora_bagit_batch_octetstream_sum_count'];
$octetstream_total_size = $_SESSION['islandora_bagit_batch_octetstream_sum_size'];
$bag->setBagInfoData('Payload-Oxum', $octetstream_total_size .
'.' . $octetstream_num_files);
$bag->update();
unset($_SESSION['islandora_bagit_batch_octetstream_sum_count']);
unset($_SESSION['islandora_bagit_batch_octetstream_sum_size']);
}
// Allow other modules to modify the Bag using
// mymodule_islandora_bagit_alter($bag, $islandora_object).
drupal_alter('islandora_bagit', $bag, $islandora_object);
if (variable_get('islandora_bagit_serialize_collection_bags', 0)) {
// Write out the serialized (i.e., compressed) Bag.
$serialized_bag_path = variable_get('islandora_bagit_bag_output_dir', '/tmp') .
DIRECTORY_SEPARATOR . $bag_file_name;
$compression_type = variable_get('islandora_bagit_compression_type', 'tgz');
$bag->package($serialized_bag_path, $compression_type);
if (variable_get('islandora_bagit_show_messages', 1)) {
$serialized_bag_path .= '.' . $compression_type;
drupal_set_message(t('Serialized collection Bag created and saved at <a href="/@path">@path</a>', array(
'@path' => $serialized_bag_path,
)));
}
if (variable_get('islandora_bagit_delete_unserialized_bag', 1)) {
rrmdir($bag_output_path);
}
}
else {
drupal_set_message(t("Collection Bag created at %path", array(
'%path' => $bag_output_path)));
}
// Delete the temp directory created by file create plugins, if it exists.
$bag_tmp_dir = variable_get('islandora_bagit_bag_tmp_dir', file_directory_temp()) .
DIRECTORY_SEPARATOR . $pid;
if (file_exists($bag_tmp_dir)) {
rrmdir($bag_tmp_dir);
}
// Clean up the temp director where we downloaded the datastreams.
if (file_exists($tmp_ds_directory)) {
rrmdir($tmp_ds_directory);
}
$serialized_all_added_files = implode(', ', $all_added_files);
if (variable_get('islandora_bagit_log_bag_creation', 1)) {
watchdog('islandora_bagit', 'Bag created for PID !pid (!files).',
array('!pid' => $pid, '!files' => $serialized_all_added_files));
}
if (variable_get('islandora_bagit_show_messages', 1)) {
drupal_set_message(t("Files added: %files",
array('%files' => $serialized_all_added_files)));
}
// Allow other modules to fire the post-Bag creation hook.
if (variable_get('islandora_bagit_serialize_collection_bags', 0)) {
$post_create_data = module_invoke_all('islandora_bagit_post_create', $pid, $serialized_bag_path);
}
else {
$post_create_data = module_invoke_all('islandora_bagit_post_create', $pid, $bag_output_path);
}
if (variable_get('islandora_bagit_provide_download_link', 1) && variable_get('islandora_bagit_serialize_collection_bags', 0)) {
// file_build_uri() needs a relative path.
if (variable_get('islandora_file_default_scheme') == 'private') {
$drupal_files_path = variable_get('islandora_file_private_path');
}
else {
$drupal_files_path = variable_get('islandora_file_public_path', conf_path() . '/files');
}
$relative_bag_path = preg_replace("#$drupal_files_path#", '', $serialized_bag_path);
$download_path = file_create_url(file_build_uri($relative_bag_path));
return l(t('Download the Bag'), $download_path);
}
else {
return array();
}
}
/*****************************************************************
* Islandora hooks for detecting object and datastream ingestion *
* and modification. *
* **************************************************************/
/**
* Implements hook_islandora_object_ingested().
*
* Creates a Bag when an object is ingested.
*/
function islandora_bagit_islandora_object_ingested(FedoraObject $islandora_object) {
if (islandora_bagit_access_check($islandora_object)) {
if (variable_get('islandora_bagit_create_on_ingest', 0)) {
// Don't create a Bag if we are dealing with a collection.
if (!isset($islandora_object["COLLECTION_POLICY"])) {
islandora_bagit_create_bag($islandora_object);
}
}
}
}
/**
* Implements hook_islandora_object_modified().
*
* This hook applies to object properties only, and not to modifications
* to datastreams.
*
* We store a copy of the Islandora object in the session table to avoid
* multiple Bags being created on datastream modification, since whenever
* you update a datastream, the object gets updated as well, firing this hook.
*/
function islandora_bagit_islandora_object_modified(FedoraObject $islandora_object) {
if (islandora_bagit_access_check($islandora_object)) {
if (variable_get('islandora_bagit_create_on_modify', 0)) {
// Don't create a Bag if we are dealing with a collection.
if (!isset($islandora_object["COLLECTION_POLICY"])) {
$_SESSION['islandora_object'] = $islandora_object;
}
}
}
}
/**
* Implements hook_islandora_datastream_modified().
*
* Fired when the properties or content of any datastream are about
* to be modified.
*
* We store a copy of the Islandora object in the session table to avoid
* multiple Bags being created on datastream modification.
*/
function islandora_bagit_islandora_datastream_modified(AbstractObject $islandora_object, AbstractDatastream $datastream) {
if (islandora_bagit_access_check($islandora_object)) {
if (variable_get('islandora_bagit_create_on_modify', 0)) {
// Don't create a Bag if we are dealing with a collection.
if (!isset($islandora_object["COLLECTION_POLICY"])) {
$_SESSION['islandora_object'] = $islandora_object;
}
}
}
}
/**
* Implements hook_islandora_datastream_modified().
*/
function islandora_bagit_islandora_datastream_ingested(AbstractObject $islandora_object, AbstractDatastream $datastream) {
if (islandora_bagit_access_check($islandora_object)) {
if (variable_get('islandora_bagit_create_on_modify', 0)) {
// Don't create a Bag if we are dealing with a collection.
if (!isset($islandora_object["COLLECTION_POLICY"])) {
$_SESSION['islandora_object'] = $islandora_object;
}
}
}
}
/**
* Implements hook_islandora_datastream_purged().
*/
function islandora_bagit_islandora_datastream_purged(AbstractObject $islandora_object, $dsid) {
if (islandora_bagit_access_check($islandora_object)) {
if (variable_get('islandora_bagit_create_on_modify', 0)) {
// Don't create a Bag if we are dealing with a collection.
if (!isset($islandora_object["COLLECTION_POLICY"])) {
$_SESSION['islandora_object'] = $islandora_object;
}
}