-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathModule.php
More file actions
1536 lines (1383 loc) · 57.5 KB
/
Copy pathModule.php
File metadata and controls
1536 lines (1383 loc) · 57.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php declare(strict_types=1);
/*
* Copyright 2015-2026 Daniel Berthereau
* Copyright 2016-2017 BibLibre
*
* 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 ImageServer;
if (!class_exists('Common\TraitModule', false)) {
require_once file_exists(dirname(__DIR__) . '/Common/src/TraitModule.php')
? dirname(__DIR__) . '/Common/src/TraitModule.php'
: dirname(__DIR__) . '/Common/TraitModule.php';
}
use Common\Stdlib\PsrMessage;
use Common\TraitModule;
use ImageServer\Form\ConfigForm;
use Laminas\EventManager\Event;
use Laminas\EventManager\SharedEventManagerInterface;
use Laminas\ModuleManager\ModuleManager;
use Laminas\Mvc\Controller\AbstractController;
use Laminas\Mvc\MvcEvent;
use Laminas\View\Renderer\PhpRenderer;
use Omeka\Entity\Media;
use Omeka\Module\AbstractModule;
use Omeka\Mvc\Controller\Plugin\Messenger;
/**
* Image Server
*
* @copyright Daniel Berthereau, 2015-2026
* @copyright Biblibre, 2016-2017
* @license http://www.cecill.info/licences/Licence_CeCILL_V2.1-en.txt
*/
class Module extends AbstractModule
{
use TraitModule;
const NAMESPACE = __NAMESPACE__;
protected $dependencies = [
'IiifServer',
];
public function init(ModuleManager $moduleManager): void
{
require_once __DIR__ . '/vendor/autoload.php';
}
public function onBootstrap(MvcEvent $event): void
{
parent::onBootstrap($event);
$acl = $this->getServiceLocator()->get('Omeka\Acl');
$acl
->allow(
null,
[
\ImageServer\Controller\ImageController::class,
]
);
}
protected function preInstall(): void
{
$services = $this->getServiceLocator();
$translator = $services->get('MvcTranslator');
if (!method_exists($this, 'checkModuleActiveVersion') || !$this->checkModuleActiveVersion('Common', '3.4.84')) {
$message = new \Omeka\Stdlib\Message(
$translator->translate('The module %1$s should be upgraded to version %2$s or later.'), // @translate
'Common', '3.4.84'
);
throw new \Omeka\Module\Exception\ModuleCannotInstallException((string) $message);
}
$errors = [];
if (!$this->checkModuleActiveVersion('IiifServer', '3.6.32')) {
$errors[] = (string) new \Omeka\Stdlib\Message(
$translator->translate('The module %1$s should be upgraded to version %2$s or later.'), // @translate
'Iiif Server', '3.6.32'
);
}
$config = $services->get('Config');
$basePath = $config['file_store']['local']['base_path'] ?: (OMEKA_PATH . '/files');
// The local store "files" may be hard-coded.
$moduleConfig = include __DIR__ . '/config/module.config.php';
$defaultSettings = $moduleConfig['imageserver']['config'];
$tileDir = $defaultSettings['imageserver_image_tile_dir'];
$tileDir = trim(strtr($tileDir, ['\\' => '/']), '/');
if (empty($tileDir)) {
$errors[] = (string) new PsrMessage(
'The tile dir is not defined.' // @translate
);
} elseif (!$this->checkDestinationDir($basePath . '/' . $tileDir)) {
$errors[] = (string) new PsrMessage(
'The directory "{directory}" is not writeable.', // @translate
['directory' => $basePath . '/' . $tileDir]
);
}
// Create the tile cache directory for the fast tile script.
$cachePath = $basePath . '/' . $tileDir . '/cache';
if ($this->checkDestinationDir($cachePath) && !$this->checkDestinationDir($cachePath)) {
$errors[] = (string) new PsrMessage(
'The directory "{directory}" is not writeable.', // @translate
['directory' => $cachePath]
);
}
if ($errors) {
throw new \Omeka\Module\Exception\ModuleCannotInstallException(implode("\n", $errors));
}
$plugins = $services->get('ControllerPluginManager');
$messenger = $plugins->get('messenger');
$messenger->addSuccess(new PsrMessage(
'The tiles will be saved in the directory "{dir}".', // @translate
['dir' => $basePath . '/' . $tileDir]
));
@copy(
$basePath . '/' . 'index.html',
$basePath . '/' . $tileDir . '/' . 'index.html'
);
}
protected function postInstall(): void
{
$services = $this->getServiceLocator();
$settings = $services->get('Omeka\Settings');
$messenger = $services->get('ControllerPluginManager')
->get('messenger');
$hasPhpVips = $this->isPhpVipsAvailable();
$hasVipsCli = (bool) trim(
(string) shell_exec('which vips 2>/dev/null')
);
// Auto-select best imager.
if ($hasPhpVips) {
$settings->set('imageserver_imager', 'PhpVips');
$messenger->addSuccess(new PsrMessage(
'php-vips detected and set as default image processor (fastest).' // @translate
));
} elseif ($hasVipsCli) {
$settings->set('imageserver_imager', 'Vips');
$messenger->addSuccess(new PsrMessage(
'Vips CLI detected and set as default image processor. For better performance, install php-vips (composer require jcupitt/vips).' // @translate
));
}
// Keep deepzoom as default tile type: static files served
// directly by Apache (~0.5ms per tile) without PHP.
// Set base url.
$urlHelper = $services->get('ViewHelperManager')->get('url');
$top = rtrim($urlHelper('top', [], ['force_canonical' => true]), '/') . '/';
$settings->set('imageserver_base_url', $top);
}
protected function postUninstall(): void
{
$services = $this->getServiceLocator();
$settings = $services->get('Omeka\Settings');
// Remove the fast tile script rule from .htaccess.
$this->removeFastTileHtaccess();
// Convert all media tile ingesters and renderers into upload/file.
$connection = $services->get('Omeka\Connection');
$sql = <<<'SQL'
UPDATE `media`
SET `ingester` = "upload"
WHERE `ingester` IN ("tile", "file");
SQL;
$connection->executeStatement($sql);
$sql = <<<'SQL'
UPDATE `media`
SET `renderer` = "file"
WHERE `renderer` = "tile";
SQL;
$connection->executeStatement($sql);
// Nuke all the tiles.
$basePath = $services->get('Config')['file_store']['local']['base_path'] ?: (OMEKA_PATH . '/files');
$tileDir = $settings->get('imageserver_image_tile_dir');
if (empty($tileDir)) {
$messenger = $services->get('ControllerPluginManager')->get('messenger');
$messenger->addWarning(new PsrMessage(
'The tile dir is not defined and was not removed.' // @translate
));
} else {
$tileDir = $basePath . '/' . $tileDir;
// A security check.
$removable = $tileDir == realpath($tileDir);
if ($removable) {
$this->rmdir($tileDir);
} else {
$messenger = $services->get('ControllerPluginManager')->get('messenger');
$messenger->addWarning(new PsrMessage(
'The tile dir "{dir}" is not a real path and was not removed.', // @translate
['dir' => $tileDir]
));
}
}
}
public function warnUninstall(Event $event): void
{
$view = $event->getTarget();
$module = $view->vars()->module;
if ($module->getId() != __NAMESPACE__) {
return;
}
$services = $this->getServiceLocator();
$settings = $services->get('Omeka\Settings');
$basePath = $services->get('Config')['file_store']['local']['base_path'] ?: (OMEKA_PATH . '/files');
$tileDir = $settings->get('imageserver_image_tile_dir');
$removable = false;
if (empty($tileDir)) {
$message = new PsrMessage(
'The tile dir is not defined and won’t be removed.' // @translate
);
} else {
$tileDir = $basePath . '/' . $tileDir;
$removable = $tileDir == realpath($tileDir);
if ($removable) {
$message = new PsrMessage('All tiles will be removed!'); // @translate
} else {
$message = new PsrMessage(
'The tile dir "{dir}" is not a real path and cannot be removed.', // @translate
['dir' => $tileDir]
);
}
}
// TODO Add a checkbox to let the choice to remove or not.
$html = '<ul class="messages"><li class="warning">';
$html .= '<strong>';
$html .= 'WARNING'; // @translate
$html .= '</strong>' . ' ';
$html .= $message;
$html .= '</li></ul>';
if ($removable) {
$html .= '<p>';
$html .= new PsrMessage(
'To keep the tiles, rename the dir "{dir}" before and after uninstall.', // @translate
['dir' => $tileDir]
);
$html .= '</p>';
}
$html .= '<p>';
$html .= new PsrMessage(
'All media rendered as "tile" will be rendered as "file".' // @translate
);
$html .= '</p>';
echo $html;
}
public function attachListeners(SharedEventManagerInterface $sharedEventManager): void
{
// There are no event "api.create.xxx" for media.
// Save dimensions before and create tiles after.
$sharedEventManager->attach(
\Omeka\Api\Adapter\MediaAdapter::class,
'api.hydrate.post',
[$this, 'handleBeforeSaveMedia']
);
$sharedEventManager->attach(
\Omeka\Api\Adapter\ItemAdapter::class,
'api.create.post',
[$this, 'handleAfterSaveItem']
);
$sharedEventManager->attach(
\Omeka\Api\Adapter\ItemAdapter::class,
'api.update.post',
[$this, 'handleAfterSaveItem']
);
$sharedEventManager->attach(
\Omeka\Api\Adapter\MediaAdapter::class,
'api.create.post',
[$this, 'handleAfterSaveMedia']
);
$sharedEventManager->attach(
\Omeka\Api\Adapter\MediaAdapter::class,
'api.update.post',
[$this, 'handleAfterSaveMedia']
);
$sharedEventManager->attach(
\Omeka\Entity\Media::class,
'entity.remove.post',
[$this, 'deleteMediaTiles']
);
$sharedEventManager->attach(
\Omeka\Form\SettingForm::class,
'form.add_elements',
[$this, 'handleMainSettings']
);
$sharedEventManager->attach(
\Omeka\Form\SiteSettingsForm::class,
'form.add_elements',
[$this, 'handleSiteSettings']
);
$sharedEventManager->attach(
'Omeka\Controller\Admin\Module',
'view.details',
[$this, 'warnUninstall']
);
}
public function getConfigForm(PhpRenderer $renderer)
{
$services = $this->getServiceLocator();
$plugins = $services->get('ControllerPluginManager');
$messenger = $plugins->get('messenger');
// Clear any previous messages, then run diagnostics.
$messenger->clear();
$this->runDiagnostics();
// Collect diagnostic messages and clear them from the flash
// messenger so they appear only in the audit tab.
$diagnostics = $messenger->get();
$messenger->clear();
$settings = $services->get('Omeka\Settings');
$formManager = $services->get('FormElementManager');
$renderer->ckEditor();
$this->initDataToPopulate($settings, 'config');
$data = $this->prepareDataToPopulate($settings, 'config');
if ($data === null) {
return null;
}
$view = $renderer;
$translate = $view->plugin('translate');
$escape = $view->plugin('escapeHtml');
$form = $formManager->get(ConfigForm::class);
$form->init();
// Update bulk note with current tile type.
$tileTypeLabels = [
'deepzoom' => $translate('Deep Zoom Image'), // @translate
'zoomify' => $translate('Zoomify'), // @translate
'jpeg2000' => $translate('Jpeg 2000'), // @translate
'tiled_tiff' => $translate('Tiled tiff'), // @translate
];
$currentTileType = $settings->get('imageserver_image_tile_type', 'deepzoom');
$bulkFieldset = $form->get('imageserver_bulk_prepare');
$note = $bulkFieldset->get('note');
$noteText = $translate('Run tiling and/or dimension sizing for existing images via a background job. Dimensions are needed for the IIIF info.json. Tiles improve zoom performance in viewers.'); // @translate
$noteText .= ' ' . new PsrMessage(
'Current tile format: {format}.', // @translate
['format' => $tileTypeLabels[$currentTileType] ?? $currentTileType]
);
$note->setOption('text', $noteText);
$form->setData($data);
$form->prepare();
// --- Audit tab ---
$levelClasses = [
Messenger::ERROR => 'error',
Messenger::SUCCESS => 'success',
Messenger::WARNING => 'warning',
Messenger::NOTICE => 'notice',
];
$auditHtml = '';
foreach ($diagnostics as $type => $messages) {
$class = $levelClasses[$type] ?? 'notice';
foreach ($messages as $msg) {
$text = $msg instanceof PsrMessage
? ($msg->escapeHtml() === false ? (string) $msg : $escape((string) $msg))
: $escape((string) $msg);
$auditHtml .= '<p class="' . $class . '">' . $text . '</p>';
}
}
if (!$auditHtml) {
$auditHtml = '<p class="success">'
. $escape($translate('All checks passed.'))
. '</p>';
}
// --- Collect elements by group ---
$elementGroups = $form->getOption('element_groups') ?: [];
$elementsInGroups = [];
$elementsNotInGroups = [];
foreach ($form as $element) {
if ($element instanceof \Laminas\Form\FieldsetInterface) {
continue;
}
$group = $element->getOption('element_group');
if ($group && isset($elementGroups[$group])) {
$elementsInGroups[$group][] = $element;
} else {
$elementsNotInGroups[] = $element;
}
}
// Render a group as a fieldset with legend.
$renderGroup = function (string $groupName) use ($elementsInGroups, $elementGroups, $escape, $translate, $view): string {
if (empty($elementsInGroups[$groupName])) {
return '';
}
$html = sprintf(
'<fieldset id="%s"><legend>%s</legend>',
$escape($groupName),
$escape($translate($elementGroups[$groupName]))
);
foreach ($elementsInGroups[$groupName] as $el) {
$html .= $view->formRow($el);
}
return $html . '</fieldset>';
};
// --- Configuration tab: infra + tiling ---
$configHtml = '';
foreach ($elementsNotInGroups as $el) {
$configHtml .= $view->formRow($el);
}
$configHtml .= $renderGroup('infra');
$configHtml .= $renderGroup('tiling');
// --- Metadata tab ---
$metadataHtml = $renderGroup('metadata');
// --- Bulk tab ---
$bulkFieldset = $form->get('imageserver_bulk_prepare');
$bulkHtml = $view->formCollection($bulkFieldset);
// --- Module navigation bar ---
$iiifModules = ['IiifServer', 'ImageServer', 'IiifSearch'];
$moduleNav = $view->moduleConfigNav($iiifModules, 'ImageServer');
// --- Tabbed layout ---
return $moduleNav
. '<ul class="section-nav" style="list-style:none;padding:0;">'
. '<li class="active"><a href="#imageserver-audit">'
. $escape($translate('Audit'))
. '</a></li>'
. '<li><a href="#imageserver-config">'
. $escape($translate('Configuration'))
. '</a></li>'
. '<li><a href="#imageserver-metadata">'
. $escape($translate('Metadata'))
. '</a></li>'
. '<li><a href="#imageserver-bulk">'
. $escape($translate('Bulk processing'))
. '</a></li>'
. '</ul>'
. '<div id="imageserver-audit" class="section active">'
. $auditHtml
. '</div>'
. '<div id="imageserver-config" class="section">'
. $configHtml
. '</div>'
. '<div id="imageserver-metadata" class="section">'
. $metadataHtml
. '</div>'
. '<div id="imageserver-bulk" class="section">'
. $bulkHtml
. '</div>';
}
public function handleConfigForm(AbstractController $controller)
{
$services = $this->getServiceLocator();
$settings = $services->get('Omeka\Settings');
$rawPost = $controller->getRequest()->getPost()->toArray();
// Dispatch bulk jobs first, before handleConfigFormAuto which may
// return false on form validation and block the dispatch.
if (!empty($rawPost['imageserver_bulk_prepare']['process'])
&& !empty($rawPost['imageserver_bulk_prepare']['tasks'])
) {
$this->dispatchBulkJob($controller, $rawPost);
}
if (!$this->handleConfigFormAuto($controller)) {
return false;
}
$this->runDiagnostics();
$urlHelper = $services->get('ViewHelperManager')->get('url');
$top = rtrim($urlHelper('top', [], ['force_canonical' => true]), '/') . '/';
$settings->set('imageserver_base_url', $top);
// Get a fresh form instance for array-valued settings that
// handleConfigFormAuto cannot handle.
$form = $services->get('FormElementManager')
->get(ConfigForm::class);
$form->setData($rawPost);
$form->isValid();
$params = $form->getData();
$this->normalizeMediaApiSettings($params);
return true;
}
/**
* Dispatch the bulk sizing/tiling/cleaning job.
*/
protected function dispatchBulkJob(
AbstractController $controller,
array $rawPost
): void {
$services = $this->getServiceLocator();
$messenger = $services->get('ControllerPluginManager')
->get('messenger');
$params = $rawPost['imageserver_bulk_prepare'];
$query = [];
parse_str($params['query'] ?? '', $query);
unset($query['submit']);
$params['query'] = $query;
$params['remove_destination'] ??= 'skip';
$params['update_renderer'] = false;
$params['filter'] = empty($params['filter_sized'])
? 'all' : $params['filter_sized'];
$params = array_intersect_key($params, [
'query' => null,
'tasks' => null,
'remove_destination' => null,
'filter' => null,
'update_renderer' => null,
]);
if (!$params['tasks']) {
$messenger->addError(new PsrMessage(
'No task defined.' // @translate
));
return;
}
if (in_array('tile_clean', $params['tasks'])
&& count($params['tasks']) > 1
) {
$messenger->addError(new PsrMessage(
'The task to clean tiles should be run alone.' // @translate
));
return;
}
$dispatcher = $services->get(\Omeka\Job\Dispatcher::class);
if (in_array('tile_clean', $params['tasks'])) {
$params = array_intersect_key($params, [
'query' => null,
'remove_destination' => null,
'update_renderer' => null,
]);
$job = $dispatcher->dispatch(
\ImageServer\Job\BulkTileClean::class, $params
);
$message = 'Cleaning tiles and tile metadata attached to specified items, in background ({link}job #{job_id}{link_end}, {link_log}logs{link_end}).'; // @translate
} elseif (in_array('tile', $params['tasks'])
&& in_array('size', $params['tasks'])
) {
$job = $dispatcher->dispatch(
\ImageServer\Job\BulkSizerAndTiler::class, $params
);
$message = 'Creating tiles and dimensions for images attached to specified items, in background ({link}job #{job_id}{link_end}, {link_log}logs{link_end}).'; // @translate
} elseif (in_array('size', $params['tasks'])) {
$params = array_intersect_key($params, [
'query' => null, 'filter' => null,
]);
$job = $dispatcher->dispatch(
\ImageServer\Job\BulkSizer::class, $params
);
$message = 'Creating dimensions for images attached to specified items, in background ({link}job #{job_id}{link_end}, {link_log}logs{link_end}).'; // @translate
} elseif (in_array('tile', $params['tasks'])) {
$params = array_intersect_key($params, [
'query' => null,
'remove_destination' => null,
'update_renderer' => null,
]);
$job = $dispatcher->dispatch(
\ImageServer\Job\BulkTiler::class, $params
);
$message = 'Creating tiles for images attached to specified items, in background ({link}job #{job_id}{link_end}, {link_log}logs{link_end}).'; // @translate
} else {
return;
}
$urlHelper = $services->get('ViewHelperManager')->get('url');
$message = new PsrMessage(
$message,
[
'link' => sprintf('<a href="%s">',
htmlspecialchars($urlHelper('admin/id', ['controller' => 'job', 'id' => $job->getId()]))
),
'job_id' => $job->getId(),
'link_end' => '</a>',
'link_log' => class_exists('Log\Module', false)
? sprintf('<a href="%1$s">', $urlHelper('admin/default', ['controller' => 'log'], ['query' => ['job_id' => $job->getId()]]))
: sprintf('<a href="%1$s" target="_blank">', $urlHelper('admin/id', ['controller' => 'job', 'action' => 'log', 'id' => $job->getId()])),
]
);
$message->setEscapeHtml(false);
$messenger->addSuccess($message);
}
protected function checkTilingMode(): bool
{
$services = $this->getServiceLocator();
$settings = $services->get('Omeka\Settings');
if ($settings->get('imageserver_tile_mode') !== 'manual') {
return true;
}
$messenger = $services->get('ControllerPluginManager')->get('messenger');
$message = new PsrMessage(
'The option "auto-tiling" is not set: unless you use an external image server sharing the original or a specific directory, it is recommended to enable it once all existing images have been tiled to avoid to tile new images manually.' // @translate
);
$messenger->addWarning($message);
return false;
}
/**
* Run all infrastructure diagnostics via messenger.
* Messages are retrieved by getConfigForm() for the audit tab.
*/
protected function runDiagnostics(): void
{
// When an external image server handles image requests,
// most local diagnostics are irrelevant.
if ($this->checkExternalServer()) {
$this->checkDeprecatedThumbnailer();
return;
}
$this->checkTilingMode();
$this->checkImager();
$this->checkTileType();
$this->checkDeprecatedThumbnailer();
$this->checkTilingStatus();
$this->checkFastTileScript();
$this->checkDirectories();
$this->checkPhpMemory();
$this->checkIiifVersion();
$this->checkRights();
$this->checkBaseUrl();
$this->checkHttp2();
$this->checkOpcache();
}
/**
* Check if an external image server is configured.
*
* @return bool True if external server is active (skip local
* diagnostics).
*/
protected function checkExternalServer(): bool
{
$services = $this->getServiceLocator();
$settings = $services->get('Omeka\Settings');
$externalUrl = $settings->get('iiifserver_media_api_url');
if (empty($externalUrl)) {
return false;
}
$messenger = $services->get('ControllerPluginManager')
->get('messenger');
$message = new PsrMessage(
'An external image server is configured ({url}). Local image processing, tiling and performance diagnostics are skipped.', // @translate
['url' => $externalUrl]
);
$messenger->addSuccess($message);
return true;
}
/**
* Recommend tiled tiff when vips is available.
*/
/**
* Check tile type and recommend the best option.
*
* - Deepzoom: tiles are static files served by Apache (~0.5ms).
* Best for serving performance. Works with any imager. Many
* small files on disk (thousands per image).
* - Tiled TIFF: single file per image, vips extracts regions
* instantly (~10ms). Better for storage and creation speed.
* Requires vips for extraction and goes through PHP.
*/
protected function checkTileType(): void
{
$services = $this->getServiceLocator();
$settings = $services->get('Omeka\Settings');
$messenger = $services->get('ControllerPluginManager')
->get('messenger');
$tileType = $settings->get('imageserver_image_tile_type', 'deepzoom');
$hasVips = $this->isPhpVipsAvailable()
|| (bool) trim((string) shell_exec('which vips 2>/dev/null'));
if ($tileType === 'tiled_tiff' && !$hasVips) {
$message = new PsrMessage(
'Tile type is "tiled tiff" but vips is not available. Only vips can extract regions from tiled TIFF. Switch to "deepzoom" or install vips.' // @translate
);
$messenger->addError($message);
} elseif ($tileType === 'tiled_tiff') {
$message = new PsrMessage(
'Tile type is "tiled tiff": compact storage (single file per image), requires vips for each tile request (~10ms via PHP). For faster tile serving (~0.5ms), use "deepzoom" (static files served by Apache).' // @translate
);
$messenger->addSuccess($message);
} elseif ($tileType === 'deepzoom') {
$message = new PsrMessage(
'Tile type is "deepzoom": fastest tile serving (static files, ~0.5ms via Apache). Creates many small files on disk.' // @translate
);
$messenger->addSuccess($message);
}
}
/**
* Check if vips thumbnailer is referenced in config to force module Vips.
*/
protected function checkDeprecatedThumbnailer(): void
{
$services = $this->getServiceLocator();
$config = $services->get('Config');
$messenger = $services->get('ControllerPluginManager')->get('messenger');
$alias = $config['service_manager']['aliases']['Omeka\File\Thumbnailer'] ?? null;
if ($alias === 'ImageServer\File\Thumbnailer\Vips') {
$message = new PsrMessage(
'The vips thumbnailer from ImageServer has been removed. Remove the alias "Omeka\File\Thumbnailer" from your file config/local.config.php. Then, install and enable the module Vips.' // @translate
);
$messenger->addError($message);
}
}
/**
* Check which image processor is available and auto-select vips.
*/
protected function checkImager(): void
{
$services = $this->getServiceLocator();
$settings = $services->get('Omeka\Settings');
$messenger = $services->get('ControllerPluginManager')
->get('messenger');
$imager = $settings->get('imageserver_imager', 'Auto');
$hasVipsCli = (bool) trim(
(string) shell_exec('which vips 2>/dev/null')
);
$hasPhpVips = $this->isPhpVipsAvailable();
$hasImagick = extension_loaded('imagick');
$hasGd = extension_loaded('gd');
$available = [];
if ($hasVipsCli) {
$version = trim(
(string) shell_exec('vips --version 2>/dev/null')
);
$available[] = 'vips CLI (' . $version . ')';
if (version_compare($version, 'vips-8.10', '<')) {
$message = new PsrMessage(
'Vips version {version} is older than 8.10. Upgrade is recommended for full feature support.', // @translate
['version' => $version]
);
$messenger->addWarning($message);
}
}
if ($hasPhpVips) {
$available[] = 'php-vips';
}
if ($hasImagick) {
$available[] = 'Imagick';
}
if ($hasGd) {
$available[] = 'GD';
}
$message = new PsrMessage(
'Available image processors: {list}.', // @translate
['list' => implode(', ', $available) ?: 'none']
);
$messenger->addSuccess($message);
// Auto-select best vips mode when current setting is Auto.
if ($imager === 'Auto' && $hasPhpVips) {
$settings->set('imageserver_imager', 'PhpVips');
$message = new PsrMessage(
'php-vips detected and set as default image processor (fastest).' // @translate
);
$messenger->addSuccess($message);
} elseif ($imager === 'Auto' && $hasVipsCli) {
$settings->set('imageserver_imager', 'Vips');
$message = new PsrMessage(
'Vips CLI detected and set as default image processor. For better performance, install php-vips (composer require jcupitt/vips).' // @translate
);
$messenger->addSuccess($message);
} elseif (!in_array($imager, ['PhpVips', 'Vips', 'Auto']) && ($hasPhpVips || $hasVipsCli)) {
$message = new PsrMessage(
'Vips is available but not selected as image processor. It is recommended for best performance and memory efficiency.' // @translate
);
$messenger->addWarning($message);
}
if (!$hasVipsCli && !$hasPhpVips) {
$message = new PsrMessage(
'Vips is not installed. Install libvips-tools (apt install libvips-tools) or php-vips (composer require jcupitt/vips) for best performance.' // @translate
);
$messenger->addWarning($message);
}
}
/**
* Check tile coverage: count tiled vs untiled image media.
*/
protected function checkTilingStatus(): void
{
$services = $this->getServiceLocator();
$connection = $services->get('Omeka\Connection');
$messenger = $services->get('ControllerPluginManager')
->get('messenger');
// Count image media with and without tile data.
$totalImages = (int) $connection->fetchOne(<<<'SQL'
SELECT COUNT(*) FROM media
WHERE media_type LIKE 'image/%'
AND media_type != 'image/svg+xml'
SQL
);
if (!$totalImages) {
return;
}
// Tile info is stored in data.tile (deepzoom, zoomify,
// tiled_tiff, or jpeg2000).
$tiledImages = (int) $connection->fetchOne(<<<'SQL'
SELECT COUNT(*) FROM media
WHERE media_type LIKE 'image/%'
AND media_type != 'image/svg+xml'
AND JSON_EXTRACT(data, '$.tile') IS NOT NULL
SQL
);
$untiled = $totalImages - $tiledImages;
if ($untiled === 0) {
$message = new PsrMessage(
'All {total} images are tiled.', // @translate
['total' => $totalImages]
);
$messenger->addSuccess($message);
return;
}
$message = new PsrMessage(
'{untiled} of {total} images are not tiled. Pre-tiling improves display performance significantly. Use the bulk tiler in the config form below.', // @translate
['untiled' => $untiled, 'total' => $totalImages]
);
if ($untiled > $totalImages / 2) {
$messenger->addWarning($message);
} else {
$messenger->addSuccess($message);
}
// Warn about large untiled images.
$settings = $services->get('Omeka\Settings');
$maxSize = (int) $settings->get('imageserver_image_max_size', 5000000);
$largeUntiled = (int) $connection->fetchOne(<<<'SQL'
SELECT COUNT(*) FROM media
WHERE media_type LIKE 'image/%'
AND media_type != 'image/svg+xml'
AND size > ?
AND JSON_EXTRACT(data, '$.tile') IS NULL
SQL,
[$maxSize]
);
if ($largeUntiled) {
$hasVips = $this->isPhpVipsAvailable()
|| (bool) trim((string) shell_exec('which vips 2>/dev/null'));
if ($hasVips) {
$message = new PsrMessage(
'{count} large images (> {size} bytes) are not tiled. Vips handles them dynamically, but pre-tiling is recommended for best performance.', // @translate
['count' => $largeUntiled, 'size' => $maxSize]
);
$messenger->addSuccess($message);
} else {
$message = new PsrMessage(
'{count} large images (> {size} bytes) are not tiled and vips is not available. These images cannot be processed dynamically. Pre-tile them or install vips.', // @translate
['count' => $largeUntiled, 'size' => $maxSize]
);
$messenger->addError($message);
}
}
}
/**
* Check if the fast tile script is set up in .htaccess.
* If writable, add the rule automatically.
*/
protected function checkFastTileScript(): void
{
$services = $this->getServiceLocator();
$messenger = $services->get('ControllerPluginManager')
->get('messenger');
$scriptPath = __DIR__ . '/data/scripts/iiiftile.php';
if (!file_exists($scriptPath)) {
return;
}
$htaccessPath = OMEKA_PATH . '/.htaccess';
$htaccess = @file_get_contents($htaccessPath);
if ($htaccess === false) {
return;
}
$marker = '# Module ImageServer: fast IIIF tile server.';
// Determine the script path relative to the Omeka root.
// Modules may be in modules/ or composer-addons/modules/.
$modulePath = realpath(__DIR__);
$omekaPath = realpath(OMEKA_PATH);
$relativeScript = str_replace(
$omekaPath . '/',
'',
$modulePath . '/data/scripts/iiiftile.php'
);
if (strpos($htaccess, 'iiiftile.php') !== false) {
// Check that the path in .htaccess matches the current
// module location (modules/ vs composer-addons/modules/).
if (strpos($htaccess, $relativeScript) !== false) {
$message = new PsrMessage(
'The fast IIIF tile script is active in .htaccess.' // @translate
);
$messenger->addSuccess($message);
} else {
$message = new PsrMessage(
'The fast IIIF tile script is in .htaccess but the path does not match the current module location. Update it to: {path}', // @translate
['path' => $relativeScript]
);
$messenger->addError($message);
// Auto-fix if writable.
if (is_writable($htaccessPath)) {
$htaccess = preg_replace(
'#(RewriteRule\s+iiif/\(.*\)\s+)\S*iiiftile\.php#',
'$1' . $relativeScript,
$htaccess
);
file_put_contents($htaccessPath, $htaccess);
$message = new PsrMessage(
'The path has been updated automatically in .htaccess.' // @translate
);
$messenger->addSuccess($message);
}
}
return;
}
$rule = "$marker\n"
. "RewriteCond %{REQUEST_URI} /iiif/([23]/)?[^/]+/[^/]+/[^/]+/[^/]+/[^.]+\.\w+$\n"
. "RewriteRule iiif/(.*) $relativeScript [END,E=IIIF_PATH:/iiif/\$1]\n";
if (!is_writable($htaccessPath)) {
$message = new PsrMessage(
'For a better performance, it is recommended to redirect urls to iiif images to a specific quick script. However, the .htaccess file is not writeable. Add the following rules manually after "RewriteEngine On":{line_break}{rule}', // @translate
['line_break' => '<br>', 'rule' => '<pre>' . htmlspecialchars($rule) . '</pre>']
);