-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathModule.php
1565 lines (1388 loc) · 62.4 KB
/
Module.php
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 declare(strict_types=1);
/*
* Copyright 2017-2024 Daniel Berthereau
*
* This software is governed by the CeCILL license under French law and abiding
* by the rules of distribution of free software. You can use, modify and/or
* redistribute the software under the terms of the CeCILL license as circulated
* by CEA, CNRS and INRIA at the following URL "http://www.cecill.info".
*
* As a counterpart to the access to the source code and rights to copy, modify
* and redistribute granted by the license, users are provided only with a
* limited warranty and the software’s author, the holder of the economic
* rights, and the successive licensors have only limited liability.
*
* In this respect, the user’s attention is drawn to the risks associated with
* loading, using, modifying and/or developing or reproducing the software by
* the user in light of its specific status of free software, that may mean that
* it is complicated to manipulate, and that also therefore means that it is
* reserved for developers and experienced professionals having in-depth
* computer knowledge. Users are therefore encouraged to load and test the
* software’s suitability as regards their requirements in conditions enabling
* the security of their systems and/or data to be ensured and, more generally,
* to use and operate it in the same conditions as regards security.
*
* The fact that you are presently reading this means that you have had
* knowledge of the CeCILL license and that you accept its terms.
*/
namespace EasyAdmin;
if (!class_exists(\Common\TraitModule::class)) {
require_once dirname(__DIR__) . '/Common/TraitModule.php';
}
use Common\Stdlib\PsrMessage;
use Common\TraitModule;
use DateTime;
use EasyAdmin\Entity\ContentLock;
use Laminas\EventManager\Event;
use Laminas\EventManager\SharedEventManagerInterface;
use Laminas\ModuleManager\ModuleManager;
use Laminas\Mvc\MvcEvent;
use Laminas\Session\Container;
use Omeka\Api\Representation\AbstractResourceEntityRepresentation;
use Omeka\Module\AbstractModule;
/**
* Easy Admin
*
* @copyright Daniel Berthereau, 2017-2024
* @license http://www.cecill.info/licences/Licence_CeCILL_V2.1-en.txt
*/
class Module extends AbstractModule
{
use TraitModule;
const NAMESPACE = __NAMESPACE__;
protected $dependencies = [
'Common',
];
public function init(ModuleManager $moduleManager): void
{
require_once __DIR__ . '/vendor/autoload.php';
}
public function onBootstrap(MvcEvent $event): void
{
parent::onBootstrap($event);
/** @var \Omeka\Permissions\Acl $acl */
$acl = $this->getServiceLocator()->get('Omeka\Acl');
// Any user who can create an item can use bulk upload.
// Admins are not included because they have the rights by default.
$roles = [
\Omeka\Permissions\Acl::ROLE_EDITOR,
\Omeka\Permissions\Acl::ROLE_REVIEWER,
\Omeka\Permissions\Acl::ROLE_AUTHOR,
];
$acl
->allow(
$roles,
['EasyAdmin\Controller\Upload'],
[
'index',
]
);
}
protected function preInstall(): void
{
$services = $this->getServiceLocator();
$translate = $services->get('ControllerPluginManager')->get('translate');
$translator = $services->get('MvcTranslator');
if (!method_exists($this, 'checkModuleActiveVersion') || !$this->checkModuleActiveVersion('Common', '3.4.64')) {
$message = new \Omeka\Stdlib\Message(
$translate('The module %1$s should be upgraded to version %2$s or later.'), // @translate
'Common', '3.4.64'
);
throw new \Omeka\Module\Exception\ModuleCannotInstallException((string) $message);
}
$js = __DIR__ . '/asset/vendor/flow.js/flow.min.js';
if (!file_exists($js)) {
$message = new PsrMessage(
'The libraries should be installed. See module’s installation documentation.' // @translate
);
throw new \Omeka\Module\Exception\ModuleCannotInstallException((string) $message->setTranslator($translator));
}
$this->installDir();
$config = $services->get('Config');
$basePath = $config['file_store']['local']['base_path'] ?: (OMEKA_PATH . '/files');
$settings = $services->get('Omeka\Settings');
$settings->set('easyadmin_local_path', $settings->get('bulkimport_local_path') ?: $basePath . '/preload');
$settings->set('easyadmin_allow_empty_files', (bool) $settings->get('bulkimport_allow_empty_files'));
}
protected function installDir(): void
{
// Don't use PsrMessage during install.
$services = $this->getServiceLocator();
$config = $services->get('Config');
$basePath = $config['file_store']['local']['base_path'] ?: (OMEKA_PATH . '/files');
$messenger = $services->get('ControllerPluginManager')->get('messenger');
$translator = $services->get('MvcTranslator');
// Automatic upgrade from module Bulk Check.
$result = null;
$bulkCheckPath = $basePath . '/bulk_check';
if (file_exists($bulkCheckPath) && is_dir($bulkCheckPath)) {
$result = rename($bulkCheckPath, $basePath . '/check');
if (!$result) {
$message = new PsrMessage(
'Upgrading module BulkCheck: Unable to rename directory "files/bulk_check" into "files/check". Trying to create it.' // @translate
);
$messenger->addWarning($message);
}
}
if (!$result && !$this->checkDestinationDir($basePath . '/check')) {
$message = new PsrMessage(
'The directory "{dir}" is not writeable.', // @translate
['dir' => $basePath]
);
throw new \Omeka\Module\Exception\ModuleCannotInstallException((string) $message->setTranslator($translator));
}
if (!$this->checkDestinationDir($basePath . '/backup')) {
$message = new PsrMessage(
'The directory "{dir}" is not writeable.', // @translate
['dir' => $basePath]
);
throw new \Omeka\Module\Exception\ModuleCannotInstallException((string) $message->setTranslator($translator));
}
if (!$this->checkDestinationDir($basePath . '/import')) {
$message = new PsrMessage(
'The directory "{dir}" is not writeable.', // @translate
['dir' => $basePath]
);
throw new \Omeka\Module\Exception\ModuleCannotInstallException((string) $message->setTranslator($translator));
}
/** @var \Omeka\Module\Manager $moduleManager */
$modules = [
'BulkCheck',
'EasyInstall',
'Maintenance',
];
$connection = $services->get('Omeka\Connection');
$moduleManager = $services->get('Omeka\ModuleManager');
foreach ($modules as $moduleName) {
$module = $moduleManager->getModule($moduleName);
$sql = 'DELETE FROM `module` WHERE `id` = "' . $moduleName . '";';
$connection->executeStatement($sql);
$sql = 'DELETE FROM `setting` WHERE `id` LIKE "' . strtolower($moduleName) . '\\_%";';
$connection->executeStatement($sql);
$sql = 'DELETE FROM `site_setting` WHERE `id` LIKE "' . strtolower($moduleName) . '\\_%";';
$connection->executeStatement($sql);
if ($module) {
$message = new PsrMessage(
'The module "{module}" was upgraded by module "{module_2}" and uninstalled.', // @translate
['module' => $moduleName, 'module_2' => 'Easy Admin']
);
$messenger->addWarning($message);
}
}
}
protected function preUninstall(): void
{
if (!empty($_POST['remove-dir-check'])) {
$config = $this->getServiceLocator()->get('Config');
$basePath = $config['file_store']['local']['base_path'] ?: (OMEKA_PATH . '/files');
$this->rmDir($basePath . '/check');
}
}
public function warnUninstall(Event $event): void
{
$view = $event->getTarget();
$module = $view->vars()->module;
if ($module->getId() != __NAMESPACE__) {
return;
}
$services = $this->getServiceLocator();
$t = $services->get('MvcTranslator');
$config = $this->getServiceLocator()->get('Config');
$basePath = $config['file_store']['local']['base_path'] ?: (OMEKA_PATH . '/files');
$html = '<p>';
$html .= '<strong>';
$html .= $t->translate('WARNING:'); // @translate
$html .= '</strong>';
$html .= '</p>';
$html .= '<p>';
$html .= sprintf(
$t->translate('All stored files from checks and fixes, if any, will be removed from folder "{folder}".'), // @translate
$basePath . '/check'
);
$html .= '</p>';
$html .= '<label><input name="remove-dir-check" type="checkbox" form="confirmform">';
$html .= $t->translate('Remove directory "files/check"'); // @translate
$html .= '</label>';
echo $html;
}
public function attachListeners(SharedEventManagerInterface $sharedEventManager): void
{
// Manage buttons in admin resources.
// TODO Use Omeka S v4.1 event "view.show.page_actions".
$sharedEventManager->attach(
'Omeka\Controller\Admin\Item',
'view.layout',
[$this, 'handleViewLayoutResource']
);
$sharedEventManager->attach(
'Omeka\Controller\Admin\ItemSet',
'view.layout',
[$this, 'handleViewLayoutResource']
);
$sharedEventManager->attach(
'Omeka\Controller\Admin\Media',
'view.layout',
[$this, 'handleViewLayoutResource']
);
$sharedEventManager->attach(
'Omeka\Controller\Admin\Item',
'view.details',
[$this, 'handleViewDetailsResource']
);
$sharedEventManager->attach(
'Omeka\Controller\Admin\ItemSet',
'view.details',
[$this, 'handleViewDetailsResource']
);
$sharedEventManager->attach(
'Omeka\Controller\Admin\Media',
'view.details',
[$this, 'handleViewDetailsResource']
);
// Manage previous/next resource. Require module EasyAdmin.
// TODO Manage item sets and media for search?
$sharedEventManager->attach(
'Omeka\Controller\Admin\Item',
'view.browse.before',
[$this, 'handleViewBrowse']
);
$sharedEventManager->attach(
\AdvancedSearch\Controller\SearchController::class,
'view.layout',
[$this, 'handleViewBrowse']
);
// Add js for the item add/edit pages to manage ingester "bulk_upload".
$sharedEventManager->attach(
'Omeka\Controller\Admin\Item',
'view.add.before',
[$this, 'addHeadersAdmin']
);
$sharedEventManager->attach(
'Omeka\Controller\Admin\Item',
'view.edit.before',
[$this, 'addHeadersAdmin']
);
// Manage the special media ingester "bulk_upload".
$sharedEventManager->attach(
\Omeka\Api\Adapter\ItemAdapter::class,
'api.hydrate.pre',
[$this, 'handleItemApiHydratePre']
);
$sharedEventManager->attach(
\Omeka\Api\Adapter\ItemAdapter::class,
'api.create.post',
[$this, 'handleAfterSaveItem'],
-10
);
$sharedEventManager->attach(
\Omeka\Api\Adapter\ItemAdapter::class,
'api.update.post',
[$this, 'handleAfterSaveItem'],
-10
);
// Optimize asset.
$sharedEventManager->attach(
\Omeka\Api\Adapter\AssetAdapter::class,
'api.create.post',
[$this, 'handleAfterSaveAsset']
);
$sharedEventManager->attach(
\Omeka\Api\Adapter\AssetAdapter::class,
'api.update.post',
[$this, 'handleAfterSaveAsset']
);
$sharedEventManager->attach(
\Omeka\Form\AssetEditForm::class,
'form.add_elements',
[$this, 'handleFormAsset']
);
// Content locking in admin board.
// It is useless in public board, because there is the moderation.
$sharedEventManager->attach(
'Omeka\Controller\Admin\Item',
'view.edit.before',
[$this, 'contentLockingOnEdit']
);
$sharedEventManager->attach(
'Omeka\Controller\Admin\ItemSet',
'view.edit.before',
[$this, 'contentLockingOnEdit']
);
$sharedEventManager->attach(
'Omeka\Controller\Admin\Media',
'view.edit.before',
[$this, 'contentLockingOnEdit']
);
// The check for content locking can be done via `api.hydrate.pre` or
// `api.update.pre`, that is bypassable in code.
$sharedEventManager->attach(
\Omeka\Api\Adapter\ItemAdapter::class,
'api.update.pre',
[$this, 'contentLockingOnSave']
);
$sharedEventManager->attach(
\Omeka\Api\Adapter\ItemSetAdapter::class,
'api.update.pre',
[$this, 'contentLockingOnSave']
);
$sharedEventManager->attach(
\Omeka\Api\Adapter\MediaAdapter::class,
'api.update.pre',
[$this, 'contentLockingOnSave']
);
// There is no good event for deletion. So either js on layout, either
// view.details and js, eiher override confirm form and/or delete confirm
// to add elements or add a trigger in delete-confirm-details.
// Here, view details + inline js to avoid to load a js in many views.
$sharedEventManager->attach(
'Omeka\Controller\Admin\Item',
'view.details',
[$this, 'contentLockingOnDeleteConfirm']
);
$sharedEventManager->attach(
'Omeka\Controller\Admin\ItemSet',
'view.details',
[$this, 'contentLockingOnDeleteConfirm']
);
$sharedEventManager->attach(
'Omeka\Controller\Admin\Media',
'view.details',
[$this, 'contentLockingOnDeleteConfirm']
);
$sharedEventManager->attach(
\Omeka\Api\Adapter\ItemAdapter::class,
'api.delete.pre',
[$this, 'contentLockingOnDelete']
);
$sharedEventManager->attach(
\Omeka\Api\Adapter\ItemSetAdapter::class,
'api.delete.pre',
[$this, 'contentLockingOnDelete']
);
$sharedEventManager->attach(
\Omeka\Api\Adapter\MediaAdapter::class,
'api.delete.pre',
[$this, 'contentLockingOnDelete']
);
$sharedEventManager->attach(
\Omeka\Form\SettingForm::class,
'form.add_elements',
[$this, 'handleMainSettings']
);
// Check last version of modules.
$sharedEventManager->attach(
'Omeka\Controller\Admin\Module',
'view.browse.after',
[$this, 'checkAddonVersions']
);
$sharedEventManager->attach(
\Omeka\Media\Ingester\Manager::class,
'service.registered_names',
[$this, 'handleMediaIngesterRegisteredNames']
);
// Display a warn before uninstalling.
$sharedEventManager->attach(
'Omeka\Controller\Admin\Module',
'view.details',
[$this, 'warnUninstall']
);
}
public function handleViewLayoutResource(Event $event): void
{
/** @var \Laminas\View\Renderer\PhpRenderer $view */
$view = $event->getTarget();
$params = $view->params()->fromRoute();
$action = $params['action'] ?? 'browse';
if ($action !== 'show') {
return;
}
$controller = $params['__CONTROLLER__'] ?? $params['controller'] ?? '';
$controllersToResourceTypes = [
'item' => 'items',
'item-set' => 'item_sets',
'media' => 'media',
'Omeka\Controller\Admin\Item' => 'items',
'Omeka\Controller\Admin\ItemSet' => 'item_sets',
'Omeka\Controller\Admin\Media' => 'media',
];
if (!isset($controllersToResourceTypes[$controller])) {
return;
}
// The resource is not available in the main view.
$id = isset($params['id']) ? (int) $params['id'] : 0;
if (!$id) {
return;
}
$resourceType = $controllersToResourceTypes[$controller];
$controller = array_search($controller, $controllersToResourceTypes);
$services = $this->getServiceLocator();
$settings = $services->get('Omeka\Settings');
$interface = $settings->get('easyadmin_interface') ?: [];
$buttonPublicView = in_array('resource_public_view', $interface);
$buttonPreviousNext = in_array('resource_previous_next', $interface);
if (!$buttonPublicView && !$buttonPreviousNext) {
return;
}
/** @var \Omeka\Api\Representation\AbstractResourceEntityRepresentation $resource */
// Normally, the current resource should be present in vars.
$vars = $view->vars();
if ($vars->offsetExists('resource')) {
$resource = $vars->offsetGet('resource');
} else {
try {
$resource = $services->get('Omeka\ApiManager')->read($resourceType, ['id' => $id], ['initialize' => false, 'finalize' => false])->getContent();
} catch (\Exception $e) {
return;
}
}
$html = $vars->offsetGet('content');
// Add public view only when there is no site, since they are added in
// Omeka S v4.1 for items. But only for items: so for consistent ux, set
// the button in the new place for all resources.
if ($buttonPublicView) {
$isOldOmeka = version_compare(\Omeka\Module::VERSION, '4.1', '<');
$skip = !$isOldOmeka && $resourceType === 'items' && count($resource->sites());
if (!$skip) {
$plugins = $services->get('ViewHelperManager');
$translate = $plugins->get('translate');
$htmlSites = $this->prepareSitesResource($resource);
if ($resourceType === 'item_sets' && count($resource->sites())) {
$translated = $translate('Sites');
$htmlRegex = <<<REGEX
<div class="meta-group[\w _-]*">\s*<h4>$translated</h4>.*</div>\s*<div class="meta-group
REGEX;
$html = preg_replace('~' . $htmlRegex . '~s', $htmlSites . '<div class="meta-group', $html, 1);
} else {
$translated = $resourceType === 'item_sets' ? $translate('Items') : $translate('Created');
$htmlPost = <<<REGEX
<div class="meta-group">
<h4>$translated</h4>
REGEX;
$htmlRegex = <<<REGEX
<div class="meta-group">\s*<h4>$translated</h4>
REGEX;
$html = preg_replace('~' . $htmlRegex . '~s', $htmlSites . $htmlPost, $html, 1);
}
}
}
if ($buttonPreviousNext) {
/** @see \EasyAdmin\View\Helper\PreviousNext */
$linkBrowseView = $view->previousNext($resource, [
'source_query' => 'session',
'back' => true,
]);
if ($linkBrowseView) {
$html = preg_replace(
'~<div id="page-actions">(.*?)</div>~s',
'<div id="page-actions">$1 ' . $linkBrowseView . '</div>',
$html,
1
);
}
}
$vars->offsetSet('content', $html);
}
public function handleViewDetailsResource(Event $event): void
{
/** @var \Omeka\Api\Representation\AbstractResourceEntityRepresentation $resource */
$resource = $event->getParam('entity');
$services = $this->getServiceLocator();
$settings = $services->get('Omeka\Settings');
$interface = $settings->get('easyadmin_interface') ?: [];
$buttonPublicView = in_array('resource_public_view', $interface);
if ($buttonPublicView) {
// TODO Fix for item sets.
$isOldOmeka = version_compare(\Omeka\Module::VERSION, '4.1', '<');
$skip = !$isOldOmeka && $resource->resourceName() === 'items' && count($resource->sites());
if (!$skip) {
$htmlSites = $this->prepareSitesResource($resource);
echo $htmlSites;
}
}
if ($resource instanceof \Omeka\Api\Representation\MediaRepresentation) {
$view = $event->getTarget();
echo $view->partial('admin/media/show-details-renderer', [
'media' => $resource,
'resource' => $resource,
]);
}
}
protected function prepareSitesResource(AbstractResourceEntityRepresentation $resource): string
{
$services = $this->getServiceLocator();
$plugins = $services->get('ViewHelperManager');
$defaultSite = $plugins->get('defaultSite');
$defaultSiteSlug = $defaultSite('slug');
$resourceType = $resource->resourceName();
$res = $resourceType === 'media' ? $resource->item() : $resource;
$sites = $res->sites();
$hasSites = count($sites);
if (!$hasSites && $defaultSiteSlug) {
$sites = [$defaultSite()];
}
if (!count($sites)) {
return '';
}
// See application/view/omeka/admin/item/show.phtml.
/** @var \Common\Stdlib\EasyMeta $easyMeta */
$url = $plugins->get('url');
$translate = $plugins->get('translate');
$hyperlink = $plugins->get('hyperlink');
$easyMeta = $services->get('Common\EasyMeta');
$controller = $resource->getControllerName();
$resourceId = $resource->id();
$htmlSites = '';
$htmlSite = <<<'HTML'
<div class="value">
__SITE_TITLE__
__RESOURCE_LINK__
</div>
HTML;
foreach ($sites as $site) {
$siteTitle = $site->title();
$externalLinkText = new PsrMessage(
'View this {resource_type} in "{site}"', // @translate
['resource_type' => $easyMeta->resourceLabel($resourceType), 'site' => $siteTitle]
);
$replace = [
'__SITE_TITLE__' => $site->link($siteTitle) . ($hasSites ? '' : $translate('[not in site]')), // @translate
'__RESOURCE_LINK__' => $hyperlink(
'',
$url('site/resource-id', ['site-slug' => $site->slug(), 'controller' => $controller, 'id' => $resourceId]),
['class' => 'o-icon-external', 'target' => '_blank', 'aria-label' => $externalLinkText, 'title' => $externalLinkText]
),
];
$htmlSites .= str_replace(array_keys($replace), array_values($replace), $htmlSite);
}
// The class item-sites is kept for css.
$translatedSites = $translate('Sites'); // @translate
$html = <<<HTML
<div class="meta-group $controller-sites item-sites">
<h4>$translatedSites</h4>
$htmlSites
</div>
HTML;
return $html;
}
/**
* Copy in:
* @see \BlockPlus\Module::handleViewBrowse()
* @see \EasyAdmin\Module::handleViewBrowse()
*/
public function handleViewBrowse(Event $event): void
{
$session = new Container('EasyAdmin');
if (!isset($session->lastBrowsePage)) {
$session->lastBrowsePage = [];
$session->lastQuery = [];
}
$params = $event->getTarget()->params();
// $ui = $params->fromRoute('__SITE__') ? 'public' : 'admin';
$ui = 'admin';
// Why not use $this->getServiceLocator()->get('Request')->getServer()->get('REQUEST_URI')?
$session->lastBrowsePage[$ui]['items'] = $_SERVER['REQUEST_URI'];
// Store the processed query too for quicker process later and because
// the controller may modify it (default sort order).
$session->lastQuery[$ui]['items'] = $params->fromQuery();
}
public function addHeadersAdmin(Event $event): void
{
$view = $event->getTarget();
$assetUrl = $view->plugin('assetUrl');
$view->headLink()
->appendStylesheet($assetUrl('css/bulk-upload.css', 'EasyAdmin'));
$view->headScript()
->appendFile($assetUrl('vendor/flow.js/flow.min.js', 'EasyAdmin'), 'text/javascript', ['defer' => 'defer'])
->appendFile($assetUrl('js/bulk-upload.js', 'EasyAdmin'), 'text/javascript', ['defer' => 'defer']);
}
public function handleItemApiHydratePre(Event $event): void
{
$services = $this->getServiceLocator();
$tempDir = $services->get('Config')['temp_dir'] ?: sys_get_temp_dir();
$tempDir = rtrim($tempDir, '/\\');
/** @var \Omeka\Api\Request $request */
$request = $event->getParam('request');
$data = $request->getContent();
if (empty($data['o:media'])) {
return;
}
// Remove removed files.
$filesData = $data['filesData'] ?? [];
if (empty($filesData['file'])) {
return;
}
foreach ($filesData['file'] ?? [] as $key => $fileData) {
$filesData['file'][$key] = json_decode($fileData, true) ?: [];
}
/**
* @var \Omeka\Stdlib\ErrorStore $errorStore
* @var \Omeka\File\TempFileFactory $tempFileFactory
* @var \Omeka\File\Validator $validator
*/
$errorStore = $event->getParam('errorStore');
$settings = $services->get('Omeka\Settings');
$validator = $services->get(\Omeka\File\Validator::class);
$tempFileFactory = $services->get(\Omeka\File\TempFileFactory::class);
$validateFile = (bool) $settings->get('disable_file_validation', false);
$allowEmptyFiles = (bool) $settings->get('easyadmin_allow_empty_files', false);
$uploadErrorCodes = [
UPLOAD_ERR_OK => 'File successfuly uploaded.', // @translate
UPLOAD_ERR_INI_SIZE => 'The total of file sizes exceeds the the server limit directive.', // @translate
UPLOAD_ERR_FORM_SIZE => 'The file size exceeds the specified limit.', // @translate
UPLOAD_ERR_PARTIAL => 'The file was only partially uploaded.', // @translate
UPLOAD_ERR_NO_FILE => 'No file was uploaded.', // @translate
UPLOAD_ERR_NO_TMP_DIR => 'The temporary folder to store the file is missing.', // @translate
UPLOAD_ERR_CANT_WRITE => 'Failed to write file to disk.', // @translate
UPLOAD_ERR_EXTENSION => 'A PHP extension stopped the file upload.', // @translate
];
$newDataMedias = [];
foreach ($data['o:media'] as $dataMedia) {
$newDataMedias[] = $dataMedia;
if (empty($dataMedia['o:ingester'])
|| $dataMedia['o:ingester'] !== 'bulk_upload'
) {
continue;
}
$index = $dataMedia['file_index'] ?? null;
if (is_null($index) || !isset($filesData['file'][$index])) {
$errorStore->addError('upload', 'There is no uploaded files.'); // @translate
continue;
}
if (empty($filesData['file'][$index])) {
$errorStore->addError('upload', 'There is no uploaded files.'); // @translate
continue;
}
// Convert the media to a list of media for the item hydration.
// Check errors first to indicate issues to user early.
$listFiles = [];
$hasError = false;
foreach ($filesData['file'][$index] as $subIndex => $fileData) {
// The user selected "allow partial upload", so no data for this
// index.
if (empty($fileData)) {
continue;
}
// Fix strict type issues in case of an issue on a file.
$fileData['name'] ??= '';
$fileData['tmp_name'] ??= '';
if (!empty($fileData['error'])) {
$errorStore->addError('upload', new PsrMessage(
'File #{index} "{filename}" has an error: {error}.', // @translate
['index' => ++$subIndex, 'filename' => $fileData['name'], 'error' => $uploadErrorCodes[$fileData['error']]]
));
$hasError = true;
continue;
} elseif (substr($fileData['name'], 0, 1) === '.') {
$errorStore->addError('upload', new PsrMessage(
'File #{index} "{filename}" must not start with a ".".', // @translate
['index' => ++$subIndex, 'filename' => $fileData['name']]
));
$hasError = true;
continue;
} elseif (!preg_match('/^[^\/\\\\{}$?!<>]+$/', $fileData['name'])) {
$errorStore->addError('upload', new PsrMessage(
'File #{index} "{filename}" must not contain a reserved character.', // @translate
['index' => ++$subIndex, 'filename' => $fileData['name']]
));
$hasError = true;
continue;
} elseif (!preg_match('/^[^\/\\\\{}$?!<>]+$/', $fileData['tmp_name'])) {
$errorStore->addError('upload', new PsrMessage(
'File #{index} temp name "{filename}" must not contain a reserved character.', // @translate
['index' => ++$subIndex, 'filename' => $fileData['tmp_name']]
));
$hasError = true;
continue;
} elseif (empty($fileData['size'])) {
if ($validateFile && !$allowEmptyFiles) {
$errorStore->addError('upload', new PsrMessage(
'File #{index} "{filename}" is an empty file.', // @translate
['index' => ++$subIndex, 'filename' => $fileData['name']]
));
$hasError = true;
continue;
}
} else {
// Don't use uploader::upload(), because the file would be
// renamed, so use temp file validator directly.
// Don't check media-type directly, because it should manage
// derivative media-types ("application/tei+xml", etc.) that
// may not be extracted by system.
$tempFile = $tempFileFactory->build();
$tempFile->setSourceName($fileData['name']);
$tempFile->setTempPath($tempDir . DIRECTORY_SEPARATOR . $fileData['tmp_name']);
if (!$validator->validate($tempFile, $errorStore)) {
// Errors are already stored.
continue;
}
}
$listFiles[] = $fileData;
}
if ($hasError) {
continue;
}
// Remove the added media directory from list of media.
array_pop($newDataMedias);
foreach ($listFiles as $index => $fileData) {
$dataMedia['ingest_file_data'] = $fileData;
$newDataMedias[] = $dataMedia;
}
}
$data['o:media'] = $newDataMedias;
$request->setContent($data);
}
public function handleAfterSaveItem(Event $event): void
{
// Prepare thumbnailing only if needed.
$needThumbnailing = false;
/**
* @var \Omeka\Entity\Item $item
* @var \Omeka\Entity\Media $media
*/
$item = $event->getParam('response')->getContent();
foreach ($item->getMedia() as $media) {
if (!$media->hasThumbnails()
&& $media->getMediaType()
&& $media->getIngester() === 'bulk_upload'
) {
$needThumbnailing = true;
break;
}
}
if (!$needThumbnailing) {
return;
}
$services = $this->getServiceLocator();
// Create the thumbnails for the media ingested with "bulk_upload" via a
// job to avoid the 30 seconds issue with numerous files.
$args = [
'item_id' => $item->getId(),
'ingester' => 'bulk_upload',
'only_missing' => true,
];
// Of course, it is useless for a background job.
// FIXME Use a plugin, not a fake job. Or strategy "sync", but there is a doctrine exception on owner of the job.
// $strategy = $this->isBackgroundProcess() ? $services->get(\Omeka\Job\DispatchStrategy\Synchronous::class) : null;
$strategy = null;
if ($this->isBackgroundProcess()) {
$job = new \Omeka\Entity\Job();
$job->setPid(null);
$job->setStatus(\Omeka\Entity\Job::STATUS_IN_PROGRESS);
$job->setClass(\EasyAdmin\Job\FileDerivativeBulkUpload::class);
$job->setArgs($args);
$job->setOwner($services->get('Omeka\AuthenticationService')->getIdentity());
$job->setStarted(new \DateTime('now'));
$jobClass = new \EasyAdmin\Job\FileDerivativeBulkUpload($job, $services);
$jobClass->perform();
} else {
/** @var \Omeka\Job\Dispatcher $dispatcher */
$dispatcher = $services->get(\Omeka\Job\Dispatcher::class);
$dispatcher->dispatch(\EasyAdmin\Job\FileDerivativeBulkUpload::class, $args, $strategy);
}
}
public function handleAfterSaveAsset(Event $event): void
{
/**
* @var \Omeka\Entity\Asset $asset
* @var \Omeka\Api\Request $request
*/
$request = $event->getParam('request');
$optimize = $request->getValue('optimize');
if (!$optimize) {
return;
}
$fileData = $request->getFileData();
if (!empty($fileData['file']['error'])) {
return;
}
$asset = $event->getParam('response')->getContent();
if (!$asset) {
return;
}
// Process the optimization.
/**
* @var \Laminas\Log\Logger $logger
* @var \Omeka\File\TempFile $tempFile
* @var \Omeka\File\Downloader $downloader
* @var \Omeka\File\Store\StoreInterface $store
* @var \Doctrine\ORM\EntityManager $entityManager
* @var \Omeka\Api\Adapter\AssetAdapter $assetAdapter
* @var \Omeka\File\ThumbnailManager $thumbnailManager
* @var \Omeka\Mvc\Controller\Plugin\Messenger $messenger
* @var \Omeka\Api\Representation\AssetRepresentation $assetRepresentation
*/
$services = $this->getServiceLocator();
$store = $services->get('Omeka\File\Store');
$logger = $services->get('Omeka\Logger');
$messenger = $services->get('ControllerPluginManager')->get('messenger');
$downloader = $services->get('Omeka\File\Downloader');
$assetAdapter = $services->get('Omeka\ApiAdapterManager')->get('assets');
$thumbnailManager = $services->get('Omeka\File\ThumbnailManager');
$assetRepresentation = $assetAdapter->getRepresentation($asset);
// Get asset as a temp file.
$assetUrl = $assetRepresentation->assetUrl();
$errorStore = new \Omeka\Stdlib\ErrorStore;
$tempFile = $downloader->download($assetUrl, $errorStore);
if (!$tempFile) {
$logger->err(new PsrMessage(
'An error occurred when fetching asset "{asset_filename}" (#{asset_id}): {errors}', // @translate
['asset_filename' => $asset->getName(), 'asset_id' => $asset->getId(), 'errors' => $errorStore->getErrors()]
));
$messenger->addErrors($errorStore->getErrors());
return;
}
$thumbnailer = $thumbnailManager->buildThumbnailer();
$thumbnailer->setSource($tempFile);
// SetOptions() is required to set the path for ImageMagick when used.
$thumbnailer->setOptions([]);
try {
$newFilePath = $thumbnailer->create('default', 800);
} catch (\Exception $e) {
$message = new PsrMessage(
'An error occurred when optimizing asset "{asset_filename}" (#{asset_id}): {error}', // @translate
['asset_filename' => $asset->getName(), 'asset_id' => $asset->getId(), 'error' => $e->getMessage()]
);
$logger->err($message->getMessage(), $message->getContext());
$messenger->addError($message);
$tempFile->delete();
return;
}
// Check if the new size is really smaller: minimum 90% to keep quality.
$originalFileSize = $tempFile->getSize();
$newFileSize = filesize($newFilePath);
$gain = 100 - ($newFileSize * 100 / $originalFileSize);
// Remove the downloaded file.
$tempFile->delete();
if ($gain < 10) {
unlink($newFilePath);
return;
}
// Store the file with the new extension.
try {
$tempFile->setStorageId($asset->getStorageId());
$tempFile->setTempPath($newFilePath);
$tempFile->store('asset', 'jpg');
} catch (\Omeka\File\Exception\RuntimeException $e) {
$message = new PsrMessage(
'An error occurred when storing asset "{asset_filename}" (#{asset_id}): {error}', // @translate
['asset_filename' => $asset->getName(), 'asset_id' => $asset->getId(), 'error' => $e->getMessage()]
);
$logger->err($message->getMessage(), $message->getContext());
$messenger->addError($message);
$tempFile->delete();
return;
}
// Delete the temporary new file.
$tempFile->delete();
// Remove the original file if the extension was different.
if ($asset->getExtension() !== 'jpg') {
$store->delete('asset/' . $asset->getFilename());
}
// Update the asset in database with the new media type and extension.
if ($asset->getExtension() !== 'jpg'
|| $asset->getMediaType() !== 'image/jpeg'
) {
// Update the original name with the new extension only when there
// was one.
$assetName = $asset->getName();
$assetExtension = $asset->getExtension();
if (!strcasecmp((string) pathinfo($assetName, PATHINFO_EXTENSION), $assetExtension)) {
$asset->setName(mb_substr($assetName, 0, - mb_strlen($assetExtension) - 1) . '.jpg');
}
// Use entity manager to avoid a loop of events.
$asset->setExtension('jpg');
$asset->setMediaType('image/jpeg');
$entityManager = $services->get('Omeka\EntityManager');
$entityManager->persist($asset);