-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathModule.php
More file actions
2413 lines (2184 loc) · 95.9 KB
/
Copy pathModule.php
File metadata and controls
2413 lines (2184 loc) · 95.9 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);
/**
* Advanced Search
*
* Improve search with new fields, auto-suggest, filters, facets, specific pages, etc.
*
* @copyright BibLibre, 2016-2017
* @copyright Daniel Berthereau, 2017-2026
* @license http://www.cecill.info/licences/Licence_CeCILL_V2.1-en.txt
*
* 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 AdvancedSearch;
// Common may be installed but not registered in autoloader, in particular
// during upgrade. So dynamically register all classes of the module.
if (!defined('COMMON_PSR4_FALLBACK')) {
foreach ([
OMEKA_PATH . '/modules/Common/src',
OMEKA_PATH . '/composer-addons/modules/Common/src',
dirname(__DIR__) . '/Common/src',
] as $commonSrc) {
if (file_exists($commonSrc . '/TraitModule.php')) {
define('COMMON_PSR4_FALLBACK', $commonSrc);
spl_autoload_register(static function ($class): void {
if (str_starts_with($class, 'Common\\')) {
$file = COMMON_PSR4_FALLBACK . '/' . strtr(substr($class, 7), '\\', '/') . '.php';
if (file_exists($file)) {
require_once $file;
}
}
});
break;
}
}
}
use AdvancedSearch\Api\Representation\SearchEngineRepresentation;
use Common\Stdlib\PsrMessage;
use Common\TraitModule;
use Laminas\EventManager\Event;
use Laminas\EventManager\SharedEventManagerInterface;
use Laminas\Mvc\MvcEvent;
use Omeka\Module\AbstractModule;
class Module extends AbstractModule
{
use TraitModule;
const NAMESPACE = __NAMESPACE__;
/**
* @var bool
*/
protected $isBatchUpdate;
/**
* Cache of indexable search engine ids by resource type for the request.
*
* @var array<string, int[]>
*/
protected $indexableSearchEngineIds = [];
public function getServiceConfig(): array
{
// During upgrade of Common, the service EasyMeta is not available.
// So load it in any case, else the module AdvancedSearch should be
// disabled directly in database or filesystem to fix upgrade.
// It allows to finish the upgrade.
// Similarly, protect navigation against missing routes during upgrade.
$config = $this->getNavigationProtectionServiceConfig();
if (!class_exists('Common\Stdlib\EasyMeta', false)) {
require_once dirname(__DIR__) . '/Common/src/Stdlib/EasyMeta.php';
require_once dirname(__DIR__) . '/Common/src/Service/Stdlib/EasyMetaFactory.php';
$config['factories']['Common\EasyMeta'] = \Common\Service\Stdlib\EasyMetaFactory::class;
}
return $config;
}
public function onBootstrap(MvcEvent $event): void
{
parent::onBootstrap($event);
$this->addAclRules();
$this->addRoutes();
}
protected function preInstall(): void
{
$services = $this->getServiceLocator();
$translator = $services->get('MvcTranslator');
$errors = [];
if (PHP_VERSION_ID < 80100) {
$errors[] = (string) new \Omeka\Stdlib\Message(
$translator->translate('The module %1$s requires PHP %2$s or later.'), // @translate
'AdvancedSearch', '8.1'
);
}
if (!method_exists($this, 'checkModuleActiveVersion') || !$this->checkModuleActiveVersion('Common', '3.4.91')) {
$errors[] = (string) new \Omeka\Stdlib\Message(
$translator->translate('The module %1$s should be upgraded to version %2$s or later.'), // @translate
'Common', '3.4.91'
);
}
// The module Thesaurus, when installed, should be up to date, else the
// maps and the queries on thesaurus fields may not work. The check
// applies whether it is enabled or not, since its data remain, but not
// to a module only present on the disk.
if ($this->isModuleInstalled('Thesaurus')
&& !$this->isModuleVersionAtLeast('Thesaurus', '3.4.26')
) {
$errors[] = (string) new \Omeka\Stdlib\Message(
$translator->translate('The module %1$s should be upgraded to version %2$s or later.'), // @translate
'Thesaurus', '3.4.26'
);
}
if ($errors) {
throw new \Omeka\Module\Exception\ModuleCannotInstallException(implode("\n", $errors));
}
}
/**
* Check if a module is installed, active or not.
*
* The module manager returns a module for any directory it finds, so the
* sole presence of a module says nothing: an archive that was unzipped and
* never installed, or a module with a broken ini, is returned like an
* installed one. Only the state tells that the module was really installed,
* so that its tables, its settings and its data are there, whether it is
* currently enabled or not.
*
* @todo Remove this method once Common 3.4.91, that provides it, is required.
*/
protected function isModuleInstalled(string $module): bool
{
/** @var \Omeka\Module\Manager $moduleManager */
$moduleManager = $this->getServiceLocator()->get('Omeka\ModuleManager');
$module = $moduleManager->getModule($module);
return $module
&& in_array($module->getState(), [
\Omeka\Module\Manager::STATE_ACTIVE,
\Omeka\Module\Manager::STATE_NOT_ACTIVE,
\Omeka\Module\Manager::STATE_NEEDS_UPGRADE,
], true);
}
protected function postInstall(): void
{
$services = $this->getServiceLocator();
/** @var \Omeka\Module\Manager $moduleManager */
$moduleManager = $services->get('Omeka\ModuleManager');
$messenger = $services->get('ControllerPluginManager')->get('messenger');
if (!$this->isModuleActive('Reference')) {
$messenger->addWarning('The module Reference is required to use the facets with the default internal adapter, but not for the Solr adapter.'); // @translate
} elseif (!$this->isModuleVersionAtLeast('Reference', '3.4.58')) {
$messenger->addWarning(new PsrMessage(
'The module {module} should be upgraded to version {version} or later.', // @translate
['module' => 'Reference', 'version' => '3.4.58']
));
}
// The module is automatically disabled when Search is uninstalled.
$module = $moduleManager->getModule('SearchSolr');
if ($module && in_array($module->getState(), [
\Omeka\Module\Manager::STATE_ACTIVE,
\Omeka\Module\Manager::STATE_NOT_ACTIVE,
\Omeka\Module\Manager::STATE_NEEDS_UPGRADE,
])) {
$version = $module->getIni('version');
if (version_compare($version, '3.5.62', '<')) {
$messenger->addWarning(new PsrMessage(
'The module {module} should be upgraded to version {version} or later.', // @translate
['module' => 'SearchSolr', 'version' => '3.5.62']
));
} elseif ($module->getState() !== \Omeka\Module\Manager::STATE_ACTIVE) {
$messenger->addNotice(new PsrMessage(
'The module {module} can be reenabled.', // @translate
['module' => 'SearchSolr']
));
}
}
$this->installResources();
}
public function attachListeners(SharedEventManagerInterface $sharedEventManager): void
{
// Handle cron reindexation: use EasyAdmin/Cron module if available,
// otherwise run independently via view.layout trigger.
if (class_exists('EasyAdmin\Job\CronTasks', false)
|| class_exists('Cron\Job\CronTasks', false)
) {
$sharedEventManager->attach(
\EasyAdmin\Job\CronTasks::class,
'easyadmin.cron.execute',
[$this, 'handleCronExecute']
);
} else {
// Handle cron reindexation independently when EasyAdmin/Cron
// module is not installed. Triggered on admin page load.
$sharedEventManager->attach(
'*',
'view.layout',
[$this, 'handleCron']
);
}
$sharedEventManager->attach(
'*',
'view.layout',
[$this, 'addHeaders']
);
/** @see \AdvancedSearch\Api\ManagerDelegator::search() */
$adapters = [
\Omeka\Api\Adapter\ItemAdapter::class,
\Omeka\Api\Adapter\ItemSetAdapter::class,
\Omeka\Api\Adapter\MediaAdapter::class,
\Omeka\Api\Adapter\ResourceAdapter::class,
// Annotation is not supported any more for now, but all features
// are included directly inside the module.
// \Annotate\Api\Adapter\AnnotationAdapter::class,
// \Generateur\Api\Adapter\GenerationAdapter::class,
];
foreach ($adapters as $adapter) {
// Improve search by property: remove properties from query, process
// normally, then process properties normally in api.search.query.
// This process is required because it is not possible to override
// the method buildPropertyQuery() in AbstractResourceEntityAdapter.
// The point is the same to search resource without template, class,
// item set, site and owner.
// Because this event does not apply when initialize = false, the
// api manager has a delegator that does the same.
// TODO Use a single event but with another priority?
$sharedEventManager->attach(
$adapter,
'api.search.pre',
[$this, 'startOverrideQuery'],
// Let any other module, except core, to search properties.
-200
);
// Add the search query filters for resources.
$sharedEventManager->attach(
$adapter,
'api.search.query',
[$this, 'endOverrideQuery'],
// Process before any other module in order to reset query.
+200
);
}
// Manage exception for full text search with resource adapter.
$sharedEventManager->attach(
\Omeka\Api\Adapter\ResourceAdapter::class,
'api.search.query',
[$this, 'overrideQueryResourceFullText'],
// Process after Omeka\Module.
-10
);
$sharedEventManager->attach(
\Omeka\Form\Element\PropertySelect::class,
'form.vocab_member_select.query',
[$this, 'onFormVocabMemberSelectQuery']
);
$sharedEventManager->attach(
\Omeka\Form\Element\ResourceClassSelect::class,
'form.vocab_member_select.query',
[$this, 'onFormVocabMemberSelectQuery']
);
$controllers = [
'Omeka\Controller\Admin\Item',
'Omeka\Controller\Admin\ItemSet',
'Omeka\Controller\Admin\Media',
'Omeka\Controller\Admin\Query',
'Omeka\Controller\Site\Item',
'Omeka\Controller\Site\ItemSet',
'Omeka\Controller\Site\Media',
// TODO Add user.
];
foreach ($controllers as $controller) {
// Specify fields to filter from the advanced search form.
// Let other modules append partial first.
$sharedEventManager->attach(
$controller,
'view.advanced_search',
[$this, 'handleViewAdvancedSearch'],
-100
);
}
// The search pages use the core process to display used filters.
$sharedEventManager->attach(
\AdvancedSearch\Controller\SearchController::class,
'view.search.filters',
[$this, 'filterSearchFilters']
);
// Append json-ld when enabled.
$sharedEventManager->attach(
\AdvancedSearch\Controller\SearchController::class,
'view.browse.after',
[$this, 'appendBrowseAfter']
);
// Store the last browse context in session for prev/next navigation
// on the item page via the resource page block "resourceNav".
$sharedEventManager->attach(
\AdvancedSearch\Controller\SearchController::class,
'view.browse.after',
[$this, 'storeResourceNavFromSearch']
);
$sharedEventManager->attach(
\Omeka\Controller\Site\Item::class,
'view.browse.after',
[$this, 'storeResourceNavFromBrowse']
);
if (class_exists(\Selection\Controller\Site\SelectionController::class, false)) {
// Require selection show template to trigger view.browse.after.
$sharedEventManager->attach(
\Selection\Controller\Site\SelectionController::class,
'view.browse.after',
[$this, 'storeResourceNavFromSelection']
);
}
// Listeners for the indexing of items, item sets and media.
// Let other modules to update data before indexing.
// See the fix for issue before 3.4.7 for Omeka < 4.1.
// Nevertheless, batch process with "remove" or "append" is not indexed.
// Items.
$sharedEventManager->attach(
\Omeka\Api\Adapter\ItemAdapter::class,
'api.create.post',
[$this, 'updateSearchEngine'],
-100
);
$sharedEventManager->attach(
\Omeka\Api\Adapter\ItemAdapter::class,
'api.update.post',
[$this, 'updateSearchEngine'],
-100
);
$sharedEventManager->attach(
\Omeka\Api\Adapter\ItemAdapter::class,
'api.delete.post',
[$this, 'updateSearchEngine'],
-100
);
$sharedEventManager->attach(
\Omeka\Api\Adapter\ItemAdapter::class,
'api.batch_update.pre',
[$this, 'preBatchUpdateSearchEngine'],
-100
);
$sharedEventManager->attach(
\Omeka\Api\Adapter\ItemAdapter::class,
'api.batch_update.post',
[$this, 'postBatchUpdateSearchEngine'],
-100
);
$sharedEventManager->attach(
\Omeka\Api\Adapter\ItemAdapter::class,
'api.batch_create.post',
[$this, 'postBatchCreateSearchEngine'],
-100
);
// Item sets.
$sharedEventManager->attach(
\Omeka\Api\Adapter\ItemSetAdapter::class,
'api.create.post',
[$this, 'updateSearchEngine'],
-100
);
$sharedEventManager->attach(
\Omeka\Api\Adapter\ItemSetAdapter::class,
'api.update.post',
[$this, 'updateSearchEngine'],
-100
);
$sharedEventManager->attach(
\Omeka\Api\Adapter\ItemSetAdapter::class,
'api.delete.post',
[$this, 'updateSearchEngine'],
-100
);
$sharedEventManager->attach(
\Omeka\Api\Adapter\ItemSetAdapter::class,
'api.batch_update.pre',
[$this, 'preBatchUpdateSearchEngine'],
-100
);
$sharedEventManager->attach(
\Omeka\Api\Adapter\ItemSetAdapter::class,
'api.batch_update.post',
[$this, 'postBatchUpdateSearchEngine'],
-100
);
$sharedEventManager->attach(
\Omeka\Api\Adapter\ItemSetAdapter::class,
'api.batch_create.post',
[$this, 'postBatchCreateSearchEngine'],
-100
);
// Medias. There is no api.create.post for medias.
$sharedEventManager->attach(
\Omeka\Api\Adapter\MediaAdapter::class,
'api.update.post',
[$this, 'updateSearchEngineMedia'],
-100
);
$sharedEventManager->attach(
\Omeka\Api\Adapter\MediaAdapter::class,
'api.delete.pre',
[$this, 'preUpdateSearchEngineMedia'],
-100
);
$sharedEventManager->attach(
\Omeka\Api\Adapter\MediaAdapter::class,
'api.delete.post',
[$this, 'updateSearchEngineMedia'],
-100
);
$sharedEventManager->attach(
\Omeka\Api\Adapter\MediaAdapter::class,
'api.batch_update.pre',
[$this, 'preBatchUpdateSearchEngine'],
-100
);
$sharedEventManager->attach(
\Omeka\Api\Adapter\MediaAdapter::class,
'api.batch_update.post',
[$this, 'postBatchUpdateSearchEngine'],
-100
);
// Annotations.
$sharedEventManager->attach(
\Annotate\Api\Adapter\AnnotationAdapter::class,
'api.create.post',
[$this, 'updateSearchEngine'],
-100
);
$sharedEventManager->attach(
\Annotate\Api\Adapter\AnnotationAdapter::class,
'api.update.post',
[$this, 'updateSearchEngine'],
-100
);
$sharedEventManager->attach(
\Annotate\Api\Adapter\AnnotationAdapter::class,
'api.delete.post',
[$this, 'updateSearchEngine'],
-100
);
$sharedEventManager->attach(
\Annotate\Api\Adapter\AnnotationAdapter::class,
'api.batch_update.pre',
[$this, 'preBatchUpdateSearchEngine'],
-100
);
$sharedEventManager->attach(
\Annotate\Api\Adapter\AnnotationAdapter::class,
'api.batch_update.post',
[$this, 'postBatchUpdateSearchEngine'],
-100
);
$sharedEventManager->attach(
\Annotate\Api\Adapter\AnnotationAdapter::class,
'api.batch_create.post',
[$this, 'postBatchCreateSearchEngine'],
-100
);
// Specific resource types of modules: concepts and digital objects.
foreach ([
\Thesaurus\Api\Adapter\ConceptAdapter::class,
\DigitalObject\Api\Adapter\DigitalObjectAdapter::class,
] as $adapter) {
foreach ([
'api.create.post' => 'updateSearchEngine',
'api.update.post' => 'updateSearchEngine',
'api.delete.post' => 'updateSearchEngine',
'api.batch_update.pre' => 'preBatchUpdateSearchEngine',
'api.batch_update.post' => 'postBatchUpdateSearchEngine',
'api.batch_create.post' => 'postBatchCreateSearchEngine',
] as $eventName => $method) {
$sharedEventManager->attach(
$adapter,
$eventName,
[$this, $method],
-100
);
}
}
// Listeners for sites.
$sharedEventManager->attach(
\Omeka\Api\Adapter\SiteAdapter::class,
'api.create.post',
[$this, 'addSearchConfigToSite']
);
// Keep main setting "advancedsearch_all_configs" in sync with the
// search_config table without requiring a visit to the search manager.
$sharedEventManager->attach(
\AdvancedSearch\Api\Adapter\SearchConfigAdapter::class,
'api.create.post',
[$this, 'refreshSearchConfigsList']
);
$sharedEventManager->attach(
\AdvancedSearch\Api\Adapter\SearchConfigAdapter::class,
'api.update.post',
[$this, 'refreshSearchConfigsList']
);
$sharedEventManager->attach(
\AdvancedSearch\Api\Adapter\SearchConfigAdapter::class,
'api.delete.post',
[$this, 'refreshSearchConfigsList']
);
// Listeners for configs.
$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\Form\SiteSettingsForm::class,
'form.add_input_filters',
[$this, 'handleSiteSettingsInputFilter']
);
// Listeners to close the rest api to non-admin users.
// The search config and the related resources are needed by the public
// front-end, so they are readable via the internal api. But they are
// administrative resources: their settings describe the internal index,
// the aliases and the hidden filters, so they are not published via the
// rest api, that is available to anonymous visitors by default.
foreach ([
\AdvancedSearch\Api\Adapter\SearchConfigAdapter::class,
\AdvancedSearch\Api\Adapter\SearchEngineAdapter::class,
\AdvancedSearch\Api\Adapter\SearchSuggesterAdapter::class,
] as $adapter) {
foreach (['api.search.pre', 'api.read.pre'] as $event) {
$sharedEventManager->attach($adapter, $event, [$this, 'denyRestApiToNonAdmin']);
}
}
}
/**
* Forbid the rest api to non-admin users, but keep the internal api.
*
* The check is done on the adapter and not on the controller or the route,
* because only the adapter throws the exception inside the api action, so
* the error is rendered as a json 403 and not as a html 500.
*/
public function denyRestApiToNonAdmin(Event $event): void
{
$services = $this->getServiceLocator();
if (!$services->get('Omeka\Status')->isApiRequest()) {
return;
}
// During a rest api request on any resource, the module may read the
// search config internally, so check the requested resource, else the
// rest api would be broken for all resources.
$resourceName = $event->getTarget()->getResourceName();
$routeMatch = $services->get('Application')->getMvcEvent()->getRouteMatch();
if (!$routeMatch || $routeMatch->getParam('resource') !== $resourceName) {
return;
}
$user = $services->get('Omeka\AuthenticationService')->getIdentity();
if ($user && $services->get('Omeka\Acl')->isAdminRole($user->getRole())) {
return;
}
throw new \Omeka\Api\Exception\PermissionDeniedException(
(string) new PsrMessage(
'The resource "{resource}" is not available through the rest api.', // @translate
['resource' => $resourceName]
)
);
}
protected function addAclRules(): void
{
/** @var \Omeka\Permissions\Acl $acl */
$acl = $this->getServiceLocator()->get('Omeka\Acl');
// Since Omeka 1.4, modules are ordered, so Guest comes after Access.
// See \Guest\Module::onBootstrap(). Manage other roles too: contributor, etc.
/** @see https://github.com/omeka/omeka-s/pull/2241 */
if (class_exists('Guest\Module', false) || class_exists('GuestRole\Module', false)) {
if (!$acl->hasRole('guest')) {
$acl->addRole('guest');
}
}
if (class_exists('GuestPrivate\Module', false)) {
if (!$acl->hasRole('guest_private')) {
$acl->addRole('guest_private');
}
if (!$acl->hasRole('guest_private_site')) {
$acl->addRole('guest_private_site');
}
}
$acl
// All can search and suggest, only admins can admin.
->allow(
null,
[
\AdvancedSearch\Controller\SearchController::class,
]
)
// To search require read/search access to adapter.
->allow(
null,
[
\AdvancedSearch\Api\Adapter\SearchConfigAdapter::class,
\AdvancedSearch\Api\Adapter\SearchEngineAdapter::class,
\AdvancedSearch\Api\Adapter\SearchSuggesterAdapter::class,
],
['read', 'search']
)
// To search require read access to entities.
->allow(
null,
[
\AdvancedSearch\Entity\SearchConfig::class,
\AdvancedSearch\Entity\SearchEngine::class,
\AdvancedSearch\Entity\SearchSuggester::class,
],
['read']
);
}
protected function addRoutes(): void
{
$services = $this->getServiceLocator();
/** @var \Omeka\Mvc\Status $status */
$status = $services->get('Omeka\Status');
$isApiRequest = $status->isApiRequest();
if ($isApiRequest) {
return;
}
$router = $services->get('Router');
if (!$router instanceof \Laminas\Router\Http\TreeRouteStack) {
return;
}
// Avoid issue when upgrading Common.
if (!$services->has('Common\EasyMeta')) {
return;
}
$settings = $services->get('Omeka\Settings');
$searchConfigs = $settings->get('advancedsearch_all_configs', []);
// A specific check to manage site admin or public site.
// The site slug is required to build public routes in background job.
// The default site is not available when module Common is upgrading.
$siteSlug = $status->getRouteParam('site-slug');
if (!$siteSlug) {
$helpers = $services->get('ViewHelperManager');
$siteSlug = $helpers->has('defaultSite')
? $helpers->get('defaultSite')('slug')
: null;
}
// The search routes are all literal an contains all data.
// They are all built early. Check is done in controller.
// To avoid collision with module Search, the routes use the slug.
// The search slug is stored in options to simplify checks.
// TODO Where is it used? So keep it for now.
$isAdminRequest = $status->isAdminRequest();
if ($isAdminRequest) {
$baseRoutes = ['search-admin-page-'];
// Quick check if this is a site admin page. The list is required to
// create the navigation.
if ($siteSlug) {
$baseRoutes[] = 'search-page-';
}
foreach ($baseRoutes as $baseRoute) foreach ($searchConfigs as $searchConfigId => $searchConfigSlug) {
$router->addRoute(
$baseRoute . $searchConfigSlug,
[
'type' => \Laminas\Router\Http\Segment::class,
'options' => [
'route' => '/admin/' . $searchConfigSlug,
'defaults' => [
'__NAMESPACE__' => 'AdvancedSearch\Controller',
'__ADMIN__' => true,
'controller' => \AdvancedSearch\Controller\SearchController::class,
'action' => 'search',
'id' => $searchConfigId,
'page-slug' => $searchConfigSlug,
'search-slug' => $searchConfigSlug,
],
],
'may_terminate' => true,
'child_routes' => [
'suggest' => [
'type' => \Laminas\Router\Http\Literal::class,
'options' => [
'route' => '/suggest',
'defaults' => [
'__NAMESPACE__' => 'AdvancedSearch\Controller',
'__ADMIN__' => true,
'controller' => \AdvancedSearch\Controller\SearchController::class,
'action' => 'suggest',
'id' => $searchConfigId,
'page-slug' => $searchConfigSlug,
'search-slug' => $searchConfigSlug,
],
],
],
'form' => [
'type' => \Laminas\Router\Http\Literal::class,
'options' => [
'route' => '/form',
'defaults' => [
'__NAMESPACE__' => 'AdvancedSearch\Controller',
'__ADMIN__' => true,
'controller' => \AdvancedSearch\Controller\SearchController::class,
'action' => 'form',
'id' => $searchConfigId,
'page-slug' => $searchConfigSlug,
'search-slug' => $searchConfigSlug,
],
],
],
],
]
);
}
return;
}
if (!$siteSlug) {
return;
}
// Use of the api requires to check authentication and roles, but roles
// are not yet all loaded (guest, annotator, etc.).
// Anyway, it's just a route and a check is done in the controller.
/** @var \Doctrine\ORM\EntityManager $entityManager */
$entityManager = $services->get('Omeka\EntityManager');
$site = $entityManager
->getRepository(\Omeka\Entity\Site::class)
->findOneBy(['slug' => $siteSlug]);
if (!$site) {
return;
}
/** @var \Omeka\Settings\SiteSettings $siteSettings */
$siteSettings = $services->get('Omeka\Settings\Site');
// The site settings is not set yet, so set it.
$siteSettings->setTargetId($site->getId());
$siteSearchConfigs = $siteSettings->get('advancedsearch_configs', []);
$siteSearchConfigs = array_intersect_key($searchConfigs, array_flip($siteSearchConfigs));
$feedModule = $services->get('Omeka\ModuleManager')
->getModule('Feed');
$hasFeed = $feedModule
&& $feedModule->getState() === \Omeka\Module\Manager::STATE_ACTIVE;
foreach ($siteSearchConfigs as $searchConfigId => $searchConfigSlug) {
$childRoutes = [
'suggest' => [
'type' => \Laminas\Router\Http\Literal::class,
'options' => [
'route' => '/suggest',
'defaults' => [
'__NAMESPACE__' => 'AdvancedSearch\Controller',
'__SITE__' => true,
'controller' => \AdvancedSearch\Controller\SearchController::class,
'action' => 'suggest',
'id' => $searchConfigId,
'page-slug' => $searchConfigSlug,
'search-slug' => $searchConfigSlug,
],
],
],
'form' => [
'type' => \Laminas\Router\Http\Literal::class,
'options' => [
'route' => '/form',
'defaults' => [
'__NAMESPACE__' => 'AdvancedSearch\Controller',
'__SITE__' => true,
'controller' => \AdvancedSearch\Controller\SearchController::class,
'action' => 'form',
'id' => $searchConfigId,
'page-slug' => $searchConfigSlug,
'search-slug' => $searchConfigSlug,
],
],
],
];
if ($hasFeed) {
$childRoutes['atom'] = [
'type' => \Laminas\Router\Http\Literal::class,
'options' => [
'route' => '/atom',
'defaults' => [
'__NAMESPACE__' => 'Feed\Controller',
'__SITE__' => true,
'controller' => 'Feed\Controller\Feed',
'action' => 'rss',
'feed' => 'atom',
'search_config_id' => $searchConfigId,
],
],
];
$childRoutes['rss'] = [
'type' => \Laminas\Router\Http\Literal::class,
'options' => [
'route' => '/rss',
'defaults' => [
'__NAMESPACE__' => 'Feed\Controller',
'__SITE__' => true,
'controller' => 'Feed\Controller\Feed',
'action' => 'rss',
'feed' => 'rss',
'search_config_id' => $searchConfigId,
],
],
];
}
$router->addRoute(
'search-page-' . $searchConfigSlug,
[
'type' => \Laminas\Router\Http\Segment::class,
'options' => [
'route' => '/s/:site-slug/' . $searchConfigSlug,
'defaults' => [
'__NAMESPACE__' => 'AdvancedSearch\Controller',
'__SITE__' => true,
'controller' => \AdvancedSearch\Controller\SearchController::class,
'action' => 'search',
'id' => $searchConfigId,
'page-slug' => $searchConfigSlug,
'search-slug' => $searchConfigSlug,
],
],
'may_terminate' => true,
'child_routes' => $childRoutes,
]
);
}
}
public function handleSiteSettings(Event $event): void
{
$this->handleAnySettings($event, 'site_settings');
$this->finalizeSiteSettings();
}
/**
* Normalize the per-site hidden query filters when the site settings form
* is submitted, so the stored value is already in the flat shape consumed
* by both InternalQuerier and SolariumQuerier. The textarea element parses
* each "slug = url-query" line into an array, which may still contain the
* legacy "property[N][property|type|text]" / "filter[N][field|type|val]"
* keys; convert them once at save-time instead of at every request.
*/
public function handleSiteSettingsInputFilter(Event $event): void
{
$inputFilter = $event->getParam('inputFilter');
if (!$inputFilter) {
return;
}
$name = 'advancedsearch_hidden_query_filters_per_config';
if (!$inputFilter->has($name)) {
return;
}
$inputFilter->get($name)->getFilterChain()->attach(
new \Laminas\Filter\Callback([
'callback' => function ($value) {
if (!is_array($value) || !$value) {
return $value;
}
foreach ($value as $slug => $filters) {
if (is_array($filters) && $filters) {
$value[$slug] = \AdvancedSearch\Stdlib\SearchResources::normalizeHiddenQueryFilters($filters);
}
}
return $value;
},
])
);
}
protected function finalizeSiteSettings(): void
{
// The redirections are stored as a single map "item set id => mode",
// so an item set cannot be set to two modes at the same time, unlike
// the four lists used until version 3.4.64.
$services = $this->getServiceLocator();
$siteSettings = $services->get('Omeka\Settings\Site');
$redirects = $siteSettings->get('advancedsearch_item_sets_redirects') ?: [];
if (!is_array($redirects)) {
$redirects = [];
}
// Keep only real item set ids and the key "default", and a mode that
// is a keyword or the slug or the url of a page.
$result = [];
foreach ($redirects as $key => $mode) {
$mode = trim((string) $mode);
$key = trim((string) $key);
if ($mode === '' || ($key !== 'default' && !(int) $key)) {
continue;
}
$result[$key === 'default' ? 'default' : (int) $key] = $mode;
}
$result = ['default' => $result['default'] ?? 'browse'] + $result;
$siteSettings->set('advancedsearch_item_sets_redirects', $result);
}
/**
* Clean useless fields and store some keys to process them one time only.
*
* @see \AdvancedSearch\Api\ManagerDelegator::search()
* @see \AdvancedSearch\Stdlib\SearchResources::startOverrideQuery()
*/
public function startOverrideQuery(Event $event): void
{
/** @var \Omeka\Api\Request $request */
$request = $event->getParam('request');
// Don't override for api index search.
if ($request->getOption('is_index_search')) {
return;
}
/** @see \AdvancedSearch\Stdlib\SearchResources::startOverrideRequest() */
$this->getServiceLocator()->get('AdvancedSearch\SearchResources')
->startOverrideRequest($request);
}
/**
* Reset original fields and process search after core.
*