forked from ojsde/lucene
-
Notifications
You must be signed in to change notification settings - Fork 4
/
LucenePlugin.php
1267 lines (1080 loc) · 40.7 KB
/
LucenePlugin.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
/**
* @file LucenePlugin.php
*
* Copyright (c) 2014-2023 Simon Fraser University
* Copyright (c) 2003-2023 John Willinsky
* Distributed under the GNU GPL v3. For full terms see the file docs/COPYING.
*
* @class LucenePlugin
* @ingroup plugins_generic_lucene
*
* @brief Lucene plugin class
*/
namespace APP\plugins\generic\lucene;
use PKP\plugins\GenericPlugin;
use PKP\plugins\PluginRegistry;
use PKP\linkAction\LinkAction;
use PKP\linkAction\request\AjaxModal;
use PKP\plugins\Hook;
use PKP\config\Config;
use PKP\core\JSONMessage;
use APP\plugins\generic\lucene\classes\SolrSearchRequest;
use APP\plugins\generic\lucene\classes\SolrWebService;
use APP\plugins\generic\lucene\classes\EmbeddedServer;
use APP\plugins\generic\lucene\classes\form\LuceneSettingsForm;
use PKP\db\DAORegistry;
use APP\core\Application;
use APP\search\ArticleSearch;
use APP\facades\Repo;
use APP\template\TemplateManager;
define('LUCENE_PLUGIN_DEFAULT_RANKING_BOOST', 1.0); // Default: No boost (=weight factor one).
class LucenePlugin extends GenericPlugin {
/** @var SolrWebService */
var $_solrWebService;
/** @var array */
var $_mailTemplates = [];
/** @var string */
var $_spellingSuggestion;
/** @var string */
var $_spellingSuggestionField;
/** @var array */
var $_highlightedArticles;
/** @var array */
var $_enabledFacetCategories;
/** @var array */
var $_facets;
public function __construct()
{
parent::__construct();
$this->application = Application::get()->getName();
}
//
// Getters and Setters
//
/**
* Get the solr web service.
* @return SolrWebService
*/
function getSolrWebService() {
return $this->_solrWebService;
}
/**
* Facets corresponding to a recent search
* (if any).
* @return boolean
*/
function getFacets() {
return $this->_facets;
}
/**
* Set an alternative article mailer implementation.
*
* NB: Required to override the mailer
* implementation for testing.
*
* @param $emailKey string
* @param $mailTemplate MailTemplate
*/
function setMailTemplate($emailKey, $mailTemplate) {
$this->_mailTemplates[$emailKey] = $mailTemplate;
}
/**
* Instantiate a MailTemplate
*
* @param $emailKey string
* @param $journal Journal
*/
function getMailTemplate($emailKey, $journal = null) {
if (!isset($this->_mailTemplates[$emailKey])) {
$mailTemplate = new MailTemplate($emailKey, null, $journal, true, true);
$this->_mailTemplates[$emailKey] = $mailTemplate;
}
return $this->_mailTemplates[$emailKey];
}
//
// Implement template methods from Plugin.
//
/**
* @copydoc Plugin::register()
*/
function register($category, $path, $mainContextId = null) {
$success = parent::register($category, $path, $mainContextId);
if (!Config::getVar('general', 'installed') || defined('RUNNING_UPGRADE')) return $success;
if ($success && $this->getEnabled($mainContextId)) {
// Register callbacks (application-level).
Hook::add('PluginRegistry::loadCategory', [$this, 'callbackLoadCategory']);
Hook::add('LoadHandler', [$this, 'callbackLoadHandler']);
// Register callbacks (data-access level).
Hook::add('Schema::get::submission', function ($hookName, $args) {
$schema = $args[0];
$schema->properties->indexingState = (object)[
'type' => 'string',
'apiSummary' => false,
'validation' => ['nullable']
];
});
$customRanking = (boolean) $this->getSetting(CONTEXT_SITE, 'customRanking');
if ($customRanking) {
Hook::add('Schema::get::section', function($hookName, $args) {
$schema = &$args[0];
$schema->properties->customRanking = (object)[
'type' => 'string',
'apiSummary' => false,
'validation' => ['nullable']
];
});
}
// Register callbacks (controller-level).
//these are current.
Hook::add('ArticleSearch::getResultSetOrderingOptions', [$this, 'callbackGetResultSetOrderingOptions']);
Hook::add('SubmissionSearch::retrieveResults', [$this, 'callbackRetrieveResults']);
Hook::add('ArticleSearchIndex::articleMetadataChanged', [$this, 'callbackArticleMetadataChanged']);
Hook::add('ArticleSearchIndex::submissionFileChanged', [$this, 'callbackSubmissionFileChanged']);
Hook::add('ArticleSearchIndex::submissionFileDeleted', [$this, 'callbackSubmissionFileDeleted']);
Hook::add('ArticleSearchIndex::submissionFilesChanged', [$this, 'callbackSubmissionFilesChanged']);
Hook::add('ArticleSearchIndex::submissionDeleted', [$this, 'callbackArticleDeleted']);
Hook::add('ArticleSearchIndex::articleDeleted', [$this, 'callbackArticleDeleted']);
Hook::add('ArticleSearchIndex::articleChangesFinished', [$this, 'callbackArticleChangesFinished']);
Hook::add('ArticleSearchIndex::rebuildIndex', [$this, 'callbackRebuildIndex']);
Hook::add('ArticleSearch::getSimilarityTerms', [$this, 'callbackGetSimilarityTerms']);
// Register callbacks (forms).
// For custom ranking. Seems to work, but value is either not saved, or not set as seleceted after loading form
if ($customRanking) {
Hook::add('sectionform::Constructor', [$this, 'callbackSectionFormConstructor']);
Hook::add('sectionform::initdata', [$this, 'callbackSectionFormInitData']);
Hook::add('sectionform::readuservars', [$this, 'callbackSectionFormReadUserVars']);
Hook::add('sectionform::execute', [$this, 'callbackSectionFormExecute']);
Hook::add('Templates::Manager::Sections::SectionForm::AdditionalMetadata', [$this, 'callbackTemplateSectionFormAdditionalMetadata']);
}
PluginRegistry::register('blocks', new LuceneFacetsBlockPlugin($this), $this->getPluginPath());
// Register callbacks (view-level).
Hook::add('TemplateManager::display', [$this, 'callbackTemplateDisplay']);
//used to show alterative spelling suggestions
Hook::add('Templates::Search::SearchResults::PreResults', [$this, 'callbackTemplatePreResults']);
//used to show additional filters for selected facet values
Hook::add('Templates::Search::SearchResults::AdditionalFilters', [$this, 'callbackTemplateAdditionalFilters']);
// Called from template article_summary.tpl, used to add highlighted additional info to searchresult.
//As Templates::Search::SearchResults::AdditionalArticleLinks has been removed
//from OJS 3, we also need this same hook to display additionalArticleLinks .
Hook::add('Templates::Issue::Issue::Article', [$this, 'callbackTemplateSearchResultHighligtedText']);
Hook::add('Templates::Issue::Issue::Article', [$this, 'callbackTemplateSimilarDocumentsLinks']);
// Does not seem to be called anymore. Either has to be added to core search again, or we add it some other way only for lucene
Hook::add('Templates::Search::SearchResults::SyntaxInstructions', [$this, 'callbackTemplateSyntaxInstructions']);
Hook::add('Publication::unpublish', [$this, 'callbackUnpublish']);
// Instantiate the web service.
$searchHandler = $this->getSetting(CONTEXT_SITE, 'searchEndpoint');
$username = $this->getSetting(CONTEXT_SITE, 'username');
$password = $this->getSetting(CONTEXT_SITE, 'password');
$instId = $this->getSetting(CONTEXT_SITE, 'instId');
$this->_solrWebService = new SolrWebService($searchHandler, $username, $password, $instId);
}
return $success;
}
/**
* @see Plugin::getDisplayName()
*/
function getDisplayName() {
return __('plugins.generic.lucene.displayName');
}
/**
* @see Plugin::getDescription()
*/
function getDescription() {
return __('plugins.generic.lucene.description');
}
/**
* @see Plugin::getInstallSitePluginSettingsFile()
*/
function getInstallSitePluginSettingsFile() {
return $this->getPluginPath() . '/settings.xml';
}
/**
* @see Plugin::getInstallEmailTemplatesFile()
*/
function getInstallEmailTemplatesFile() {
return ($this->getPluginPath() . '/emailTemplates.xml');
}
/**
* @see Plugin::getInstallEmailTemplateDataFile()
*/
function getInstallEmailTemplateDataFile() {
return ($this->getPluginPath() . '/locale/{$installedLocale}/emailTemplates.xml');
}
/**
* @see Plugin::isSitePlugin()
*/
function isSitePlugin() {
return true;
}
//
// Implement template methods from GenericPlugin.
//
/**
* @copydoc Plugin::getActions()
*/
function getActions($request, $actionArgs) {
$router = $request->getRouter();
return array_merge(
$this->getEnabled() ? [
new LinkAction(
'settings',
new AjaxModal(
$router->url($request, null, null, 'manage', null, array_merge($actionArgs, array('verb' => 'settings'))),
$this->getDisplayName()
),
__('manager.plugins.settings'),
null
),
] : [],
parent::getActions($request, $actionArgs)
);
}
/**
* @copydoc Plugin::manage()
*/
function manage($args, $request) {
switch ($request->getUserVar('verb')) {
case 'settings':
// Instantiate an embedded server instance.
$embeddedServer = new EmbeddedServer();
// Instantiate the settings form.
$form = new LuceneSettingsForm($this, $embeddedServer);
// Handle request to save configuration data.
if ($request->getUserVar('rebuildIndex')) {
// Re-init data. It should be visible to users
// that whatever data they may have entered into
// the form was not saved.
$form->initData();
//journal = null reindexes all dictionaries
$message = null;
$journal = null;
if ($request->getUserVar('journalToReindex')) {
$journalId = $request->getUserVar('journalToReindex');
$journalDao = DAORegistry::getDAO('JournalDAO');
$journal = $journalDao->getById($journalId);
if (! $journal instanceof \APP\journal\Journal) $journal = null;
}
$this->_rebuildIndex(false, $journal, true, false, $message);
$form->setData('rebuildIndexMessages', $message);
}
else if ($request->getUserVar('rebuildDictionaries')) {
// Re-init data. It should be visible to users
// that whatever data they may have entered into
// the form was not saved.
$form->initData();
// rebuild dictionaries
$message = '';
$this->_rebuildIndex(false, null, false, true, $message);
$form->setData('rebuildIndexMessages', $message);
}
else if ($request->getUserVar('stopServer')) {
$form->initData();
// As this is a system plug-in we follow usual
// plug-in policy and allow journal managers to start/
// stop the server although this will affect all journals
// of the installation.
$embeddedServer->stopAndWait();
}
else if ($request->getUserVar('startServer')) {
$form->initData();
$embeddedServer->start();
}
else if ($request->getUserVar('save')) {
$form->readInputData();
if ($form->validate()) {
$form->execute();
return new JSONMessage(true);
}
}
else {
// Re-init data. It should be visible to users
// that whatever data they may have entered into
// the form was not saved.
$form->initData();
}
return new JSONMessage(true, $form->fetch($request));
}
return parent::manage($args, $request);
}
//
// Application level hook implementations.
//
/**
* @see PluginRegistry::loadCategory()
*/
function callbackLoadCategory($hookName, $args) {
// We only contribute to the block plug-in category.
$category = $args[0];
if ($category != 'blocks') return false;
// We only contribute a plug-in if at least one
// faceting category is enabled.
$enabledFacetCategories = $this->_getEnabledFacetCategories();
if (empty($enabledFacetCategories)) return false;
// Instantiate the block plug-in for facets.
$luceneFacetsBlockPlugin = new LuceneFacetsBlockPlugin($this);
// Add the plug-in to the registry.
$plugins =& $args[1];
$seq = $luceneFacetsBlockPlugin->getSeq();
if (!isset($plugins[$seq])) $plugins[$seq] = [];
$plugins[$seq][$luceneFacetsBlockPlugin->getPluginPath()] = $luceneFacetsBlockPlugin;
return false;
}
/**
* @see PKPPageRouter::route()
*/
function callbackLoadHandler($hookName, $args) {
// Check the page.
$page = $args[0];
if ($page !== 'lucene') return;
// Check the operation.
$op = $args[1];
$handler = & $args[3];
$publicOps = [
'queryAutocomplete',
'pullChangedArticles',
'similarDocuments',
];
if (!in_array($op, $publicOps)) return;
// Get the journal object from the context (optimized).
$request = Application::get()->getRequest();
$router = $request->getRouter();
$journal = $router->getContext($request);
/* @var $journal Journal */
// Looks as if our handler had been requested.
$handler = new LuceneHandler($this);
return true;
}
//
// Controller level hook implementations.
//
/**
* @see ArticleSearch::getResultSetOrderingOptions()
*/
public function callbackGetResultSetOrderingOptions(string $hookName, array $params) {
$resultSetOrderingOptions =& $params[1];
// FIXME: not implemented
}
public function callbackRetrieveResults(string $hookName, array $params) {
assert($hookName == 'SubmissionSearch::retrieveResults');
// Unpack the parameters.
list($journal, $keywords, $fromDate, $toDate, $orderBy, $orderDir, $exclude, $page, $itemsPerPage) = $params;
$totalResults =& $params[9]; // need to use reference
$error =& $params[10]; // need to use reference
$results =& $params[11];
// Instantiate a search request.
$searchRequest = new SolrSearchRequest();
$searchRequest->setJournal($journal);
$searchRequest->setFromDate($fromDate);
$searchRequest->setToDate($toDate);
if (isset($keywords[SUBMISSION_SEARCH_AUTHOR])) $searchRequest->setAuthors($keywords[SUBMISSION_SEARCH_AUTHOR]);
$searchRequest->setOrderBy($orderBy);
$searchRequest->setOrderDir($orderDir == 'asc' ? true : false);
$searchRequest->setPage($page);
$searchRequest->setItemsPerPage($itemsPerPage);
$searchRequest->addQueryFromKeywords($keywords);
$searchRequest->setExcludedIds($exclude);
// Get the ordering criteria.
list($orderBy, $orderDir) = $this->_getResultSetOrdering($journal);
$searchRequest->setOrderBy($orderBy);
$searchRequest->setOrderDir($orderDir == 'asc' ? true : false);
// Configure alternative spelling suggestions.
$spellcheck = (boolean) $this->getSetting(CONTEXT_SITE, 'spellcheck');
$searchRequest->setSpellcheck($spellcheck);
// Configure highlighting.
$highlighting = (boolean) $this->getSetting(CONTEXT_SITE, 'highlighting');
$searchRequest->setHighlighting($highlighting);
// Configure faceting.
// 1) Faceting will be disabled for filtered search categories.
$activeFilters = array_keys($searchRequest->getQuery());
if ($journal instanceof \APP\journal\Journal) $activeFilters[] = 'journalTitle';
if (!empty($fromDate) || !empty($toDate)) $activeFilters[] = 'publicationDate';
// 2) Switch faceting on for enabled categories that have no
// active filters.
$facetCategories = array_values(array_diff($this->_getEnabledFacetCategories(), $activeFilters));
$searchRequest->setFacetCategories($facetCategories);
// Configure custom ranking.
$customRanking = (boolean) $this->getSetting(CONTEXT_SITE, 'customRanking');
if ($customRanking) {
if ($journal instanceof \APP\journal\Journal) {
$sections = Repo::section()->getCollector()->filterByContextIds([$journal->getId()])->getMany();
} else {
$sections = Repo::section()->getCollector()->getMany();
}
foreach ($sections as $section) {
$sectionBoost = (float) $section->getData('rankingBoost');
if ($sectionBoost != null && $sectionBoost != LUCENE_PLUGIN_DEFAULT_RANKING_BOOST) {
$searchRequest->addBoostFactor(
'section_id', $section->getId(), $sectionBoost
);
}
}
unset($sections);
}
// Call the solr web service.
$solrWebService = $this->getSolrWebService();
$result = $solrWebService->retrieveResults($searchRequest, $totalResults, $this->getSetting(CONTEXT_SITE, 'useSolr7'));
if (is_null($result)) {
$error = $solrWebService->getServiceMessage();
$this->_informTechAdmin($error, $journal, true);
$error .= ' ' . __('plugins.generic.lucene.message.techAdminInformed');
return [];
} else {
// Store spelling suggestion, highlighting and faceting info
// internally. We cannot route these back through the request
// as the default search implementation does not support
// these features.
if ($spellcheck && isset($result['spellingSuggestion'])) {
$this->_spellingSuggestion = $result['spellingSuggestion'];
// Identify the field for which we got the suggestion.
foreach ($keywords as $bitmap => $searchPhrase) {
if (!empty($searchPhrase)) {
switch ($bitmap) {
case null:
$queryField = 'query';
break;
case SUBMISSION_SEARCH_INDEX_TERMS:
$queryField = 'indexTerms';
break;
default:
$articleSearch = new ArticleSearch();
$indexFieldMap = $articleSearch->getIndexFieldMap();
assert(isset($indexFieldMap[$bitmap]));
$queryField = $indexFieldMap[$bitmap];
}
}
}
$this->_spellingSuggestionField = $queryField;
}
if ($highlighting && isset($result['highlightedArticles'])) {
$this->_highlightedArticles = $result['highlightedArticles'];
}
if (!empty($facetCategories) && isset($result['facets'])) {
$this->_facets = $result['facets'];
}
// Return the scored results.
if (isset($result['scoredResults']) && !empty($result['scoredResults'])) {
$results = $result['scoredResults'];
}
return true;
}
}
/**
* @see ArticleSearchIndex::articleMetadataChanged()
*/
function callbackArticleMetadataChanged($hookName, $params) {
assert($hookName == 'ArticleSearchIndex::articleMetadataChanged');
list($article) = $params;
/* @var $article Article */
$this->_solrWebService->setArticleStatus($article->getId());
// in OJS core in many cases callbackArticleChangesFinished is not called.
// So we call it ourselves, it won't do anything is pull-indexing is active
$this->callbackArticleChangesFinished(null, null, $article->getData('contextId'));
return true;
}
/**
* @see ArticleSearchIndex::submissionFilesChanged()
*/
function callbackSubmissionFilesChanged($hookName, $params) {
assert($hookName == 'ArticleSearchIndex::submissionFilesChanged');
list($article) = $params;
/* @var $article Article */
$this->_solrWebService->setArticleStatus($article->getId());
return true;
}
/**
* @see ArticleSearchIndex::submissionFileChanged()
*/
function callbackSubmissionFileChanged($hookName, $params) {
assert($hookName == 'ArticleSearchIndex::submissionFileChanged');
list($articleId, $type, $fileId) = $params;
$this->_solrWebService->setArticleStatus($article->getId());
// in OJS core in many cases callbackArticleChangesFinished is not called.
// So we call it ourselves, it won't do anything is pull-indexing is active
$this->callbackArticleChangesFinished(null, null,$article->getData('contextId'));
return true;
}
/**
* @see ArticleSearchIndex::submissionFileDeleted()
*/
function callbackSubmissionFileDeleted($hookName, $params) {
assert($hookName == 'ArticleSearchIndex::submissionFileDeleted');
list($articleId, $type, $assocId) = $params;
$this->_solrWebService->setArticleStatus($article->getId());
return true;
}
/**
* @see ArticleSearchIndex::articleDeleted()
*/
function callbackArticleDeleted($hookName, $params) {
assert($hookName == 'ArticleSearchIndex::articleDeleted');
list($articleId) = $params;
// Deleting an article must always be done synchronously
// (even in pull-mode) as we'll no longer have an object
// to keep our change information.
$this->_solrWebService->deleteArticleFromIndex($articleId);
return true;
}
function callbackUnpublish($hookName, $params) {
list($newPublication, $publication, $submission) = $params;
$solrWebService = $this->getSolrWebService();
$solrWebService->deleteArticleFromIndex($submission->getId());
return true;
}
/**
* @see ArticleSearchIndex::articleChangesFinished()
*/
function callbackArticleChangesFinished($hookName, $params, $journalId = null) {
// In the case of pull-indexing we ignore this call
// and let the Solr server initiate indexing.
if ($this->getSetting(CONTEXT_SITE, 'pullIndexing')) return true;
// If the plugin is configured to push changes to the
// server then we'll now batch-update all articles that
// changed since the last update. We use a batch size of 5
// for online index updates to limit the time a request may be
// locked in case a race condition with a large index update
// occurs.
$solrWebService = $this->getSolrWebService();
$result = $solrWebService->pushChangedArticles(5, $journalId);
if (is_null($result)) {
$this->_informTechAdmin($solrWebService->getServiceMessage());
}
return true;
}
/**
* @see ArticleSearchIndex::rebuildIndex()
*/
function callbackRebuildIndex($hookName, $params) {
assert($hookName == 'ArticleSearchIndex::rebuildIndex');
// Unpack the parameters.
list($log, $journal, $switches) = $params;
// Check switches.
$rebuildIndex = true;
$rebuildDictionaries = false;
//$updateBoostFile = false;
if (is_array($switches)) {
if (in_array('-n', $switches)) {
$rebuildIndex = false;
}
if (in_array('-d', $switches)) {
$rebuildDictionaries = true;
}
/*
if (in_array('-b', $switches)) {
$updateBoostFile = true;
}*/
}
// Rebuild the index.
$messages = null;
$this->_rebuildIndex($log, $journal, $rebuildIndex, $rebuildDictionaries, $messages);
return true;
}
/**
* @see ArticleSearch::getSimilarityTerms()
*/
function callbackGetSimilarityTerms($hookName, $params) {
$articleId = $params[0];
$searchTerms =& $params[1];
// Identify "interesting" terms of the
// given article and return them "by ref".
$solrWebService = $this->getSolrWebService();
$searchTerms = $solrWebService->getInterestingTerms($articleId);
return true;
}
//
// Form hook implementations.
//
/**
* @see Form::__construct()
*/
function callbackSectionFormConstructor($hookName, $params) {
// Check whether we got a valid ranking boost option.
$acceptedValues = array_keys($this->_getRankingBoostOptions());
$form =& $params[0];
$form->addCheck(
new FormValidatorInSet(
$form, 'rankingBoostOption', FORM_VALIDATOR_REQUIRED_VALUE,
'plugins.generic.lucene.sectionForm.rankingBoostInvalid',
$acceptedValues
)
);
return false;
}
/**
* @see Form::initData()
*/
function callbackSectionFormInitData($hookName, $params) {
$form =& $params[0];
/* @var $form SectionForm */
// Read the section's ranking boost.
$rankingBoost = LUCENE_PLUGIN_DEFAULT_RANKING_BOOST;
$journal = Application::get()->getRequest()->getJournal();
$section = null;
if ($form->getSectionId()) {
$section = Repo::section()->get($form->getSectionId(), $journal->getId());
}
if ($section instanceof \APP\section\Section) {
$rankingBoostSetting = $section->getData('rankingBoost');
if (is_numeric($rankingBoostSetting)) $rankingBoost = (float) $rankingBoostSetting;
}
// The ranking boost is a floating-poing multiplication
// factor (0, 0.5, 1, 2). Translate this into an integer
// option value (0, 1, 2, 4).
$rankingBoostOption = (int) ($rankingBoost * 2);
$rankingBoostOptions = $this->_getRankingBoostOptions();
if (!in_array($rankingBoostOption, array_keys($rankingBoostOptions))) {
$rankingBoostOption = (int) (LUCENE_PLUGIN_DEFAULT_RANKING_BOOST * 2);
}
$form->setData('rankingBoostOption', $rankingBoostOption);
return false;
}
/**
* @see Form::readUserVars()
*/
function callbackSectionFormReadUserVars($hookName, $params) {
$userVars =& $params[1];
$userVars[] = 'rankingBoostOption';
return false;
}
/**
* Callback for execution upon section form save
* @param $hookName string
* @param $params array
* @return mixed
*/
function callbackSectionFormExecute($hookName, $params) {
// Convert the ranking boost option back into a ranking boost factor.
$form =& $params[0];
/* @var $form SectionForm */
$rankingBoostOption = $form->getData('rankingBoostOption');
$rankingBoostOptions = $this->_getRankingBoostOptions();
if (in_array($rankingBoostOption, array_keys($rankingBoostOptions))) {
$rankingBoost = ((float) $rankingBoostOption) / 2;
}
else {
$rankingBoost = LUCENE_PLUGIN_DEFAULT_RANKING_BOOST;
}
$journal = Application::get()->getRequest()->getJournal();
// Get or create the section object
if ($form->getSectionId()) {
$section = Repo::section()->get($form->getSectionId(), $journal->getId());
// Update the ranking boost of the section.
$section->setData('rankingBoost', $rankingBoost);
Repo::section()->edit($section, ['rankingBoost']);
}
return false;
}
//
// View level hook implementations.
//
/**
* @see TemplateManager::display()
*/
function callbackTemplateDisplay($hookName, $params) {
$template = $params[1];
if ($template == 'frontend/pages/indexSite.tpl') return false;
// avoid recursive calls of the template
if (strpos($template,'plugins-') !== false) return false;
if (strpos($template,'frontend/pages/') === false) return false;
// Get the request.
$request = Application::get()->getRequest();
// Get the context
$journal = $request->getContext();
// Assign our private stylesheet.
/** @var TemplateManager */
$templateMgr = $params[0];
$templateMgr->addStylesheet('lucene', $request->getBaseUrl() . '/' . $this->getPluginPath() . '/templates/lucene.css');
// Result set ordering options.
$orderByOptions = $this->_getResultSetOrderingOptions($journal);
$templateMgr->assign('luceneOrderByOptions', $orderByOptions);
$orderDirOptions = $this->_getResultSetOrderingDirectionOptions();
$templateMgr->assign('luceneOrderDirOptions', $orderDirOptions);
// Similar documents.
if ($this->getSetting(CONTEXT_SITE, 'simdocs')) {
$templateMgr->assign('simDocsEnabled', true);
}
if ($this->getSetting(CONTEXT_SITE, 'autosuggest')) {
$templateMgr->assign('enableAutosuggest', true);
$templateMgr->display('extends:'.$template.'|'.$this->getTemplateResource('luceneSearch.tpl'));
return true;
}
return false;
}
/**
* @see templates/search/searchResults.tpl
*/
function callbackTemplatePreResults($hookName, $params) {
$request = Application::get()->getRequest();
$templateMgr = TemplateManager::getManager($request);
// The spelling suggestion value is set in
// LucenePlugin::callbackRetrieveResults(), see there.
$templateMgr->assign('spellingSuggestion', $this->_spellingSuggestion);
$templateMgr->assign(
'spellingSuggestionUrlParams',
[$this->_spellingSuggestionField => $this->_spellingSuggestion]
);
$templateMgr->display($this->getTemplateResource('preResults.tpl'));
return false;
}
function callbackTemplateAdditionalFilters($hookName, $params) {
$request = Application::get()->getRequest();
$templateMgr = TemplateManager::getManager($request);
$smarty =& $params[1];
$enabledFacets = $this->_getEnabledFacetCategories();
$facets = $this->getFacets();
$selectedFacets = [];
foreach ($enabledFacets as $currentFacet) {
if ($currentValue = $smarty->getTemplateVars($currentFacet)) {
$facetDisplayName = __('plugins.generic.lucene.faceting.' . $currentFacet);
//author is already available in standard filtersection, so we don't show that again
if ($currentFacet != "authors") {
$selectedFacets[$currentFacet] = ['facetDisplayName' => $facetDisplayName,
'facetValue' => $currentValue
];
}
}
}
$templateMgr->assign('selectedFacets', $selectedFacets);
$templateMgr->display($this->getTemplateResource('additionalFilters.tpl'));
return false;
}
/**
* @see templates/frontend/objects/article_summary.tpl
*/
function callbackTemplateSearchResultHighligtedText($hookName, $params) {
$smarty =& $params[1];
$article = $smarty->getTemplateVars('article');
// Check whether the "highlighting" feature is enabled.
if (!$this->getSetting(CONTEXT_SITE, 'highlighting')) return false;
// Check and prepare the article parameter.
if (!(isset($article) && is_numeric($article->getId()))) {
return false;
}
$articleId = $article->getId();
// Check whether we have highlighting info for the given article.
if (!isset($this->_highlightedArticles[$articleId])) return false;
// Return the excerpt (a template seems overkill here).
// Escaping should have been taken care of when analyzing the text, so
// there should be no XSS risk here (but we need the <em> tag in the
// highlighted result).
$output =& $params[2];
$output .= '<div class="plugins_generic_lucene_highlighting">... '
. trim($this->_highlightedArticles[$articleId]) . ' ..."</div>';
return false;
}
/**
* @see templates/search/searchResults.tpl
*/
function callbackTemplateSimilarDocumentsLinks($hookName, $params) {
// Check whether the "similar documents" feature is
// enabled.
if (!$this->getSetting(0, 'simdocs')) return false;
$smarty =& $params[1];
$article = $smarty->getTemplateVars('article');
// Check and prepare the article parameter.
if (!(isset($article) && is_numeric($article->getId()))) {
return false;
}
$urlParams = ['articleId' => $article->getId()];
// Create a URL that links to "similar documents".
$request = Application::get()->getRequest();
$router = $request->getRouter();
$simdocsUrl = $router->url(
$request, null, 'lucene', 'similarDocuments', null, $urlParams
);
// Return a link to the URL (a template seems overkill here).
$output =& $params[2];
$output .= '<div class="plugins_generic_lucene_similardocuments"><a href="' . $simdocsUrl . '" class="file">'
. __('plugins.generic.lucene.results.similarDocuments')
. '</a></div>';
return false;
}
/**
* @see templates/search/searchResults.tpl
*/
function callbackTemplateSyntaxInstructions($hookName, $params) {
$output =& $params[2];
$output .= __('plugins.generic.lucene.results.syntaxInstructions');
return false;
}
/**
* @see templates/manager/sections/sectionForm.tpl
*/
function callbackTemplateSectionFormAdditionalMetadata($hookName, $params) {
// Assign the ranking boost options to the template.
$request = Application::get()->getRequest();
$templateMgr = TemplateManager::getManager($request);
$templateMgr->assign('rankingBoostOptions', $this->_getRankingBoostOptions());;
$templateMgr->display($this->getTemplateResource('additionalSectionMetadata.tpl'));
return false;
}
/**
* Return the available options for result
* set ordering.
* @param $journal Journal
* @return array
*/
function _getResultSetOrderingOptions($journal) {
$resultSetOrderingOptions = [];
if ($this->getSetting(CONTEXT_SITE, 'orderByRelevance')) {
$resultSetOrderingOptions['score'] = __('plugins.generic.lucene.results.orderBy.relevance');
}
if ($this->getSetting(CONTEXT_SITE, 'orderByAuthor')) {
$resultSetOrderingOptions['authors'] = __('plugins.generic.lucene.results.orderBy.author');
}
if ($this->getSetting(CONTEXT_SITE, 'orderByIssue')) {
$resultSetOrderingOptions['issuePublicationDate'] = __('plugins.generic.lucene.results.orderBy.issue');
}
if ($this->getSetting(CONTEXT_SITE, 'orderByDate')) {
$resultSetOrderingOptions['publicationDate'] = __('plugins.generic.lucene.results.orderBy.date');
}
if ($this->getSetting(CONTEXT_SITE, 'orderByArticle')) {
$resultSetOrderingOptions['title'] = __('plugins.generic.lucene.results.orderBy.article');
}
// Only show the "journal title" option if we have several journals.
if (! $journal instanceof \APP\journal\Journal && $this->getSetting(CONTEXT_SITE, 'orderByJournal')) {
$resultSetOrderingOptions['journalTitle'] = __('plugins.generic.lucene.results.orderBy.journal');
}
return $resultSetOrderingOptions;
}
/**
* Return the available options for the result
* set ordering direction.
* @return array