-
Notifications
You must be signed in to change notification settings - Fork 359
/
Server.php
1424 lines (1295 loc) · 45.6 KB
/
Server.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
/**
* OAI Server class
*
* PHP version 8
*
* Copyright (C) Villanova University 2010.
* Copyright (C) The National Library of Finland 2018-2019.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* @category VuFind
* @package OAI_Server
* @author Demian Katz <demian.katz@villanova.edu>
* @author Ere Maijala <ere.maijala@helsinki.fi>
* @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License
* @link https://vufind.org/wiki/development Wiki
*/
namespace VuFind\OAI;
use SimpleXMLElement;
use VuFind\Db\Entity\ChangeTrackerEntityInterface;
use VuFind\Db\Service\ChangeTrackerServiceInterface;
use VuFind\Db\Service\OaiResumptionServiceInterface;
use VuFind\Exception\RecordMissing as RecordMissingException;
use VuFind\SimpleXML;
use VuFindApi\Formatter\RecordFormatter;
use function count;
use function in_array;
use function intval;
use function strlen;
/**
* OAI Server class
*
* This class provides OAI server functionality.
*
* @category VuFind
* @package OAI_Server
* @author Demian Katz <demian.katz@villanova.edu>
* @author Ere Maijala <ere.maijala@helsinki.fi>
* @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License
* @link https://vufind.org/wiki/development Wiki
*/
class Server
{
/**
* Repository base URL
*
* @var string
*/
protected $baseURL;
/**
* Base URL of host containing VuFind.
*
* @var string
*/
protected $baseHostURL;
/**
* Incoming request parameters
*
* @var array
*/
protected $params;
/**
* Search object class to use
*
* @var string
*/
protected $searchClassId = 'Solr';
/**
* What Solr core are we serving up?
*
* @var string
*/
protected $core = 'biblio';
/**
* ISO-8601 date format
*
* @var string
*/
protected $iso8601 = 'Y-m-d\TH:i:s\Z';
/**
* Records per page in lists
*
* @var int
*/
protected $pageSize = 100;
/**
* Solr field for set membership
*
* @var string
*/
protected $setField = null;
/**
* Supported metadata formats
*
* @var array
*/
protected $metadataFormats = [];
/**
* Namespace used for ID prefixing (if any)
*
* @var string
*/
protected $idNamespace = null;
/**
* Repository name used in "Identify" response
*
* @var string
*/
protected $repositoryName = 'VuFind';
/**
* Earliest datestamp used in "Identify" response
*
* @var string
*/
protected $earliestDatestamp = '2000-01-01T00:00:00Z';
/**
* Admin email used in "Identify" response
*
* @var string
*/
protected $adminEmail;
/**
* Record link helper (optional)
*
* @var \VuFind\View\Helper\Root\RecordLinker
*/
protected $recordLinkerHelper = null;
/**
* Set queries
*
* @var array
*/
protected $setQueries = [];
/*
* Default query used when a set is not specified
*
* @var string
*/
protected $defaultQuery = '';
/*
* Record formatter
*
* @var RecordFormatter
*/
protected $recordFormatter = null;
/**
* Fields to return when the 'vufind' format is requested. Empty array means the
* format is disabled.
*
* @var array
*/
protected $vufindApiFields = [];
/**
* Filter queries specific to the requested record format
*
* @var array
*/
protected $recordFormatFilters = [];
/**
* Limit on display of deleted records (in days); older deleted records will not
* be returned by the server. Set to null for no limit.
*
* @var int
*/
protected $deleteLifetime = null;
/**
* Should we use cursorMarks for Solr retrieval? Normally this is the best
* option, but it is incompatible with some other Solr features and may need
* to be disabled in rare circumstances (e.g. when using field collapsing/
* result grouping).
*
* @var bool
*/
protected $useCursorMark = true;
/**
* Constructor
*
* @param \VuFind\Search\Results\PluginManager $resultsManager Search manager for retrieving records
* @param \VuFind\Record\Loader $recordLoader Record loader
* @param ChangeTrackerServiceInterface $trackerService ChangeTracker Service
* @param OaiResumptionServiceInterface $resumptionService Database service for resumption tokens
*/
public function __construct(
protected \VuFind\Search\Results\PluginManager $resultsManager,
protected \VuFind\Record\Loader $recordLoader,
protected ChangeTrackerServiceInterface $trackerService,
protected OaiResumptionServiceInterface $resumptionService
) {
}
/**
* Initialize settings
*
* @param \VuFind\Config\Config $config VuFind configuration
* @param string $baseURL The base URL for the OAI server
* @param array $params The incoming OAI-PMH parameters (i.e. $_GET)
*
* @return void
*/
public function init(\VuFind\Config\Config $config, $baseURL, array $params)
{
$this->baseURL = $baseURL;
$parts = parse_url($baseURL);
$this->baseHostURL = $parts['scheme'] . '://' . $parts['host'];
if (isset($parts['port'])) {
$this->baseHostURL .= $parts['port'];
}
$this->params = $params;
$this->initializeSettings($config); // Load config.ini settings
}
/**
* Add a record linker helper (optional -- allows enhancement of some metadata
* with VuFind-specific links).
*
* @param \VuFind\View\Helper\Root\RecordLinker $helper Helper to set
*
* @return void
*/
public function setRecordLinkerHelper($helper)
{
$this->recordLinkerHelper = $helper;
}
/**
* Add a record formatter (optional -- allows the vufind record format to be
* returned).
*
* @param RecordFormatter $formatter Record formatter
*
* @return void
*/
public function setRecordFormatter($formatter)
{
$this->recordFormatter = $formatter;
// Reset metadata formats so they can be reinitialized; the formatter
// may enable additional options.
$this->metadataFormats = [];
}
/**
* Get the current UTC date/time in ISO 8601 format.
*
* @param string $time Time string to represent as UTC (default = 'now')
*
* @return string
*/
protected function getUTCDateTime($time = 'now')
{
// All times must be in UTC, so translate the current time to the
// appropriate time zone:
$utc = new \DateTime($time, new \DateTimeZone('UTC'));
return date_format($utc, $this->iso8601);
}
/**
* Respond to the OAI-PMH request.
*
* @return string
*/
public function getResponse()
{
if (!$this->hasParam('verb')) {
return $this->showError('badVerb', 'Missing Verb Argument');
} else {
switch ($this->params['verb']) {
case 'GetRecord':
return $this->getRecord();
case 'Identify':
return $this->identify();
case 'ListIdentifiers':
case 'ListRecords':
return $this->listRecords($this->params['verb']);
case 'ListMetadataFormats':
return $this->listMetadataFormats();
case 'ListSets':
return $this->listSets();
default:
return $this->showError('badVerb', 'Illegal OAI Verb');
}
}
}
/**
* Assign necessary interface variables to display a deleted record.
*
* @param SimpleXMLElement $xml XML to update
* @param ChangeTrackerEntityInterface $trackerEntity ChangeTracker entity
* @param bool $headerOnly Only attach the header?
*
* @return void
*/
protected function attachDeleted($xml, $trackerEntity, $headerOnly = false)
{
// Deleted records only have a header, no metadata. However, depending
// on the context we are attaching them, they may or may not need a
// <record> tag wrapping the header.
$record = $headerOnly ? $xml : $xml->addChild('record');
$this->attachRecordHeader(
$record,
$this->prefixID($trackerEntity->getId()),
date($this->iso8601, $trackerEntity->getDeleted()->getTimestamp()),
[],
'deleted'
);
}
/**
* Attach a record header to an XML document.
*
* @param SimpleXMLElement $xml XML to update
* @param string $id Record id
* @param string $date Record modification date
* @param array $sets Set(s) containing record
* @param string $status Record status code
*
* @return void
*/
protected function attachRecordHeader(
$xml,
$id,
$date,
$sets = [],
$status = ''
) {
$header = $xml->addChild('header');
if (!empty($status)) {
$header['status'] = $status;
}
$header->identifier = $id;
$header->datestamp = $date;
foreach ($sets as $set) {
$header->addChild('setSpec', htmlspecialchars($set));
}
}
/**
* Support method for attachNonDeleted() to build the VuFind metadata for
* a record driver.
*
* @param object $record A record driver object
*
* @return string
*/
protected function getVuFindMetadata($record)
{
// Root node
$recordDoc = new \DOMDocument();
$vufindFormat = $this->getMetadataFormats()['oai_vufind_json'];
$rootNode = $recordDoc->createElementNS(
$vufindFormat['namespace'],
'oai_vufind_json:record'
);
$rootNode->setAttribute(
'xmlns:xsi',
'http://www.w3.org/2001/XMLSchema-instance'
);
$rootNode->setAttribute(
'xsi:schemaLocation',
$vufindFormat['namespace'] . ' ' . $vufindFormat['schema']
);
$recordDoc->appendChild($rootNode);
// Add oai_dc part
$oaiDc = new \DOMDocument();
$oaiDc->loadXML(
$record->getXML('oai_dc', $this->baseHostURL, $this->recordLinkerHelper)
);
$rootNode->appendChild(
$recordDoc->importNode($oaiDc->documentElement, true)
);
// Add VuFind metadata
$records = $this->recordFormatter->format(
[$record],
$this->vufindApiFields
);
$metadataNode = $recordDoc->createElementNS(
$vufindFormat['namespace'],
'oai_vufind_json:metadata'
);
$metadataNode->setAttribute('type', 'application/json');
$metadataNode->appendChild(
$recordDoc->createCDATASection(json_encode($records[0]))
);
$rootNode->appendChild($metadataNode);
return $recordDoc->saveXML();
}
/**
* Attach a non-deleted record to an XML document.
*
* @param SimpleXMLElement $container XML container for new record
* @param object $record A record driver object
* @param string $format Metadata format to obtain (false for none)
* @param bool $headerOnly Only attach the header?
* @param string $set Currently active set
*
* @return bool
*/
protected function attachNonDeleted(
$container,
$record,
$format,
$headerOnly = false,
$set = ''
) {
// Get the XML (and display an error if it is unsupported):
if ($format === false) {
$xml = ''; // no metadata if in header-only mode!
} elseif ('oai_vufind_json' === $format && $this->supportsVuFindMetadata()) {
$xml = $this->getVuFindMetadata($record); // special case
} else {
$xml = $record
->getXML($format, $this->baseHostURL, $this->recordLinkerHelper);
if ($xml === false) {
return false;
}
}
// Headers should be returned only if the metadata format matching
// the supplied metadataPrefix is available.
// If RecordDriver returns nothing, skip this record.
if (empty($xml)) {
return true;
}
// Check for sets:
$fields = $record->getRawData();
if (null !== $this->setField && !empty($fields[$this->setField])) {
$sets = (array)$fields[$this->setField];
} else {
$sets = [];
}
if (!empty($set)) {
$sets = array_unique(array_merge($sets, [$set]));
}
// Get modification date:
$date = $record->getLastIndexed();
if (empty($date)) {
$date = $this->getUTCDateTime('now');
}
// Set up header (inside or outside a <record> container depending on
// preferences):
$recXml = $headerOnly ? $container : $container->addChild('record');
$this->attachRecordHeader(
$recXml,
$this->prefixID($record->getUniqueID()),
$date,
$sets
);
// Inject metadata if necessary:
if (!$headerOnly && !empty($xml)) {
$metadata = $recXml->addChild('metadata');
SimpleXML::appendElement($metadata, $xml);
}
return true;
}
/**
* Respond to a GetRecord request.
*
* @return string
*/
protected function getRecord()
{
// Validate parameters
if (!$this->hasParam('metadataPrefix')) {
return $this->showError('badArgument', 'Missing Metadata Prefix');
}
if (!$this->hasParam('identifier')) {
return $this->showError('badArgument', 'Missing Identifier');
}
// Start building response
$response = $this->createResponse();
$xml = $response->addChild('GetRecord');
// Retrieve the record from the index
if ($record = $this->loadRecord($this->params['identifier'])) {
$success = $this->attachNonDeleted(
$xml,
$record,
$this->params['metadataPrefix']
);
if (!$success) {
return $this->showError('cannotDisseminateFormat', 'Unknown Format');
}
} else {
// No record in index -- is this deleted?
$row = $this->trackerService->getChangeTrackerEntity(
$this->core,
$this->stripID($this->params['identifier'])
);
if (!empty($row) && !empty($row->getDeleted())) {
$this->attachDeleted($xml, $row);
} else {
// Not deleted and not found in index -- error!
return $this->showError('idDoesNotExist', 'Unknown Record');
}
}
// Display the record:
return $response->asXML();
}
/**
* Was the specified parameter provided?
*
* @param string $param Name of the parameter to check.
*
* @return bool True if parameter is set and non-empty.
*/
protected function hasParam($param)
{
return isset($this->params[$param]) && !empty($this->params[$param]);
}
/**
* Respond to an Identify request:
*
* @return string
*/
protected function identify()
{
$response = $this->createResponse();
$xml = $response->addChild('Identify');
$xml->repositoryName = $this->repositoryName;
$xml->baseURL = $this->baseURL;
$xml->protocolVersion = '2.0';
$xml->adminEmail = $this->adminEmail;
$xml->earliestDatestamp = $this->earliestDatestamp;
$xml->deletedRecord = 'transient';
$xml->granularity = 'YYYY-MM-DDThh:mm:ssZ';
if (!empty($this->idNamespace)) {
$id = $xml->addChild('description')->addChild(
'oai-identifier',
null,
'http://www.openarchives.org/OAI/2.0/oai-identifier'
);
$id->addAttribute(
'xsi:schemaLocation',
'http://www.openarchives.org/OAI/2.0/oai-identifier '
. 'http://www.openarchives.org/OAI/2.0/oai-identifier.xsd',
'http://www.w3.org/2001/XMLSchema-instance'
);
$id->scheme = 'oai';
$id->repositoryIdentifier = $this->idNamespace;
$id->delimiter = ':';
$id->sampleIdentifier = 'oai:' . $this->idNamespace . ':123456';
}
return $response->asXML();
}
/**
* Does the current configuration support the VuFind metadata format (using
* the API's record formatter.
*
* @return bool
*/
protected function supportsVuFindMetadata()
{
return !empty($this->vufindApiFields) && null !== $this->recordFormatter;
}
/**
* Initialize data about metadata formats. (This is called on demand and is
* defined as a separate method to allow easy override by child classes).
*
* @return void
*/
protected function initializeMetadataFormats()
{
$this->metadataFormats['oai_dc'] = [
'schema' => 'http://www.openarchives.org/OAI/2.0/oai_dc.xsd',
'namespace' => 'http://www.openarchives.org/OAI/2.0/oai_dc/'];
$this->metadataFormats['marc21'] = [
'schema' => 'http://www.loc.gov/standards/marcxml/schema/MARC21slim.xsd',
'namespace' => 'http://www.loc.gov/MARC21/slim'];
if ($this->supportsVuFindMetadata()) {
$this->metadataFormats['oai_vufind_json'] = [
'schema' => 'https://vufind.org/xsd/oai_vufind_json-1.0.xsd',
'namespace' => 'http://vufind.org/oai_vufind_json-1.0',
];
} else {
unset($this->metadataFormats['oai_vufind_json']);
}
}
/**
* Get metadata formats; initialize the list if necessary.
*
* @return array
*/
protected function getMetadataFormats()
{
if (empty($this->metadataFormats)) {
$this->initializeMetadataFormats();
}
return $this->metadataFormats;
}
/**
* Load data from the OAI section of config.ini. (This is called by the
* constructor and is only a separate method to allow easy override by child
* classes).
*
* @param \VuFind\Config\Config $config VuFind configuration
*
* @return void
*/
protected function initializeSettings(\VuFind\Config\Config $config)
{
// Override default repository name if configured:
if (isset($config->OAI->repository_name)) {
$this->repositoryName = $config->OAI->repository_name;
}
// Override default ID namespace if configured:
if (isset($config->OAI->identifier)) {
$this->idNamespace = $config->OAI->identifier;
}
// Override page size if configured:
if (isset($config->OAI->page_size)) {
$this->pageSize = $config->OAI->page_size;
}
// Use either OAI-specific or general email address; we must have SOMETHING.
$this->adminEmail = $config->OAI->admin_email ?? $config->Site->email;
// Use a Solr field to determine sets, if configured:
if (isset($config->OAI->set_field)) {
$this->setField = $config->OAI->set_field;
}
// Initialize custom sets queries:
if (isset($config->OAI->set_query)) {
$this->setQueries = $config->OAI->set_query->toArray();
}
// Use a default query, if configured:
if (isset($config->OAI->default_query)) {
$this->defaultQuery = $config->OAI->default_query;
}
// Initialize VuFind API format fields:
$this->vufindApiFields = array_filter(
explode(
',',
$config->OAI->vufind_api_format_fields ?? ''
)
);
// Initialize filters specific to requested metadataPrefix:
if (isset($config->OAI->record_format_filters)) {
$this->recordFormatFilters
= $config->OAI->record_format_filters->toArray();
}
// Initialize delete lifetime, if set:
if (isset($config->OAI->delete_lifetime)) {
$this->deleteLifetime = intval($config->OAI->delete_lifetime);
}
// Change cursormark behavior if necessary:
$cursor = $config->OAI->use_cursor ?? true;
if (!$cursor || strtolower($cursor) === 'false') {
$this->useCursorMark = false;
}
}
/**
* Respond to a ListMetadataFormats request.
*
* @return string
*/
protected function listMetadataFormats()
{
// If a specific ID was provided, try to load the related record; otherwise,
// set $record to false so we know it is a generic request.
if (isset($this->params['identifier'])) {
if (!($record = $this->loadRecord($this->params['identifier']))) {
return $this->showError('idDoesNotExist', 'Unknown Record');
}
} else {
$record = false;
}
// Loop through all available metadata formats and see if they apply in
// the current context (all apply if $record is false, since that
// means that no specific record ID was requested; otherwise, they only
// apply if the current record driver supports them):
$response = $this->createResponse();
$xml = $response->addChild('ListMetadataFormats');
foreach ($this->getMetadataFormats() as $prefix => $details) {
if (
$record === false
|| $record->getXML($prefix) !== false
|| ('oai_vufind_json' === $prefix && $this->supportsVuFindMetadata())
) {
$node = $xml->addChild('metadataFormat');
$node->metadataPrefix = $prefix;
if (isset($details['schema'])) {
$node->schema = $details['schema'];
}
if (isset($details['namespace'])) {
$node->metadataNamespace = $details['namespace'];
}
}
}
// Display the response:
return $response->asXML();
}
/**
* Respond to a ListIdentifiers or ListRecords request (the $verb parameter
* determines the exact format of the response).
*
* @param string $verb 'ListIdentifiers' or 'ListRecords'
*
* @return string
*/
protected function listRecords($verb = 'ListRecords')
{
// Load and validate parameters; if an Exception is thrown, we need to parse
// and output an appropriate error.
try {
$params = $this->listRecordsGetParams();
} catch (\Exception $e) {
$parts = explode(':', $e->getMessage(), 2);
if (count($parts) != 2) {
throw $e;
}
return $this->showError($parts[0], $parts[1]);
}
// Normalize the provided dates into Unix timestamps. Depending on whether
// they come from the OAI-PMH request or the database, the format may be
// slightly different; this ensures they are reduced to a consistent value!
$from = $this->normalizeDate($params['from']);
$until = $this->normalizeDate($params['until'], '23:59:59');
if (!$this->listRecordsValidateDates($from, $until)) {
return;
}
// Copy the cursor from the parameters so we can track our current position
// separately from our initial position!
$currentCursor = $params['cursor'];
$response = $this->createResponse();
$xml = $response->addChild($verb);
// The verb determines whether we're returning headers only or full records:
$headersOnly = ($verb != 'ListRecords');
// Apply the delete lifetime limit to the from date if necessary:
$deleteCutoff = $this->deleteLifetime
? strtotime('-' . $this->deleteLifetime . ' days') : 0;
$deleteFrom = ($deleteCutoff < $from) ? $from : $deleteCutoff;
// Get deleted records in the requested range (if applicable):
$deletedCount = $this->listRecordsGetDeletedCount($deleteFrom, $until);
if ($deletedCount > 0 && $currentCursor < $deletedCount) {
$deleted = $this
->listRecordsGetDeleted($deleteFrom, $until, $currentCursor);
foreach ($deleted as $current) {
$this->attachDeleted($xml, $current, $headersOnly);
$currentCursor++;
}
}
// Figure out how many non-deleted records we need to display:
$recordLimit = ($params['cursor'] + $this->pageSize) - $currentCursor;
// Depending on cursormark mode, we either need to get the latest mark or
// else calculate a Solr offset.
if ($this->useCursorMark) {
$offset = $cursorMark = $params['cursorMark'] ?? '';
} else {
$cursorMark = ''; // always empty for checks below
$offset = ($currentCursor >= $deletedCount)
? $currentCursor - $deletedCount : 0;
}
$format = $params['metadataPrefix'];
// Get non-deleted records from the Solr index:
$set = $params['set'] ?? '';
$result = $this->listRecordsGetNonDeleted(
$from,
$until,
$offset,
$recordLimit,
$format,
$set
);
$nonDeletedCount = $result->getResultTotal();
foreach ($result->getResults() as $doc) {
$this->attachNonDeleted($xml, $doc, $format, $headersOnly, $set);
$currentCursor++;
}
// We only need a cursor mark if we fetched results from Solr; if our
// $recordLimit is 0, it means that we're still in the process of
// retrieving deleted records, and we're only hitting Solr to obtain a
// total record count. Therefore, we don't want to change the cursor
// mark yet, or it will break pagination of deleted records.
$nextCursorMark = $recordLimit > 0 ? $result->getCursorMark() : '';
// If our cursor didn't reach the last record, we need a resumption token!
$listSize = $deletedCount + $nonDeletedCount;
if (
$listSize > $currentCursor
&& ('' === $cursorMark || $nextCursorMark !== $cursorMark)
) {
$this->saveResumptionToken(
$xml,
$params,
$currentCursor,
$listSize,
$nextCursorMark
);
} elseif ($params['cursor'] > 0) {
// If we reached the end of the list but there is more than one page, we
// still need to display an empty <resumptionToken> tag:
$token = $xml->addChild('resumptionToken');
$token->addAttribute('completeListSize', $listSize);
$token->addAttribute('cursor', $params['cursor']);
}
return $response->asXML();
}
/**
* Respond to a ListSets request.
*
* @return string
*/
protected function listSets()
{
// Resumption tokens are not currently supported for this verb:
if ($this->hasParam('resumptionToken')) {
return $this->showError(
'badResumptionToken',
'Invalid resumption token'
);
}
// If no set field is enabled, we can't provide a set list:
if (null === $this->setField && empty($this->setQueries)) {
return $this->showError('noSetHierarchy', 'Sets not supported');
}
// Begin building XML:
$response = $this->createResponse();
$xml = $response->addChild('ListSets');
// Load set field if applicable:
if (null !== $this->setField) {
// If we got this far, we can load all available set values. For now,
// we'll assume that this list is short enough to load in one response;
// it may be necessary to implement a resumption token mechanism if this
// proves not to be the case:
$results = $this->resultsManager->get($this->searchClassId);
try {
$facets = $results->getFullFieldFacets([$this->setField]);
} catch (\Exception $e) {
$facets = null;
}
if (empty($facets) || !isset($facets[$this->setField]['data']['list'])) {
$this->unexpectedError('Cannot find sets');
}
// Extract facet values from the Solr response:
foreach ($facets[$this->setField]['data']['list'] as $x) {
$set = $xml->addChild('set');
$set->setSpec = $x['value'];
$set->setName = $x['displayText'];
}
}
// Iterate over custom sets:
if (!empty($this->setQueries)) {
foreach ($this->setQueries as $setName => $solrQuery) {
$set = $xml->addChild('set');
$set->setName = $set->setSpec = $setName;
$set->setDescription = $solrQuery;
}
}
// Display the list:
return $response->asXML();
}
/**
* Get an object containing the next page of deleted records from the specified
* date range.
*
* @param int $from Start date.
* @param int $until End date.
* @param int $currentCursor Offset into result set
*
* @return ChangeTrackerEntityInterface[]
*/
protected function listRecordsGetDeleted($from, $until, $currentCursor)
{
return $this->trackerService->getDeletedEntities(
$this->core,
\DateTime::createFromFormat('U', $from),
\DateTime::createFromFormat('U', $until),
$currentCursor,
$this->pageSize
);
}
/**
* Get a count of all deleted records in the specified date range.
*
* @param int $from Start date.
* @param int $until End date.
*
* @return int
*/
protected function listRecordsGetDeletedCount($from, $until)
{
return $this->trackerService->getDeletedCount(
$this->core,
\DateTime::createFromFormat('U', $from),
\DateTime::createFromFormat('U', $until)
);
}
/**
* Get an array of information on non-deleted records in the specified range.
*
* @param int $from Start date.
* @param int $until End date.
* @param mixed $offset Solr offset, or cursorMark for the position in the full
* result list (depending on settings).
* @param int $limit Max number of full records to return.
* @param string $format Requested record format
* @param string $set Set to limit to (empty string for none).
*
* @return \VuFind\Search\Base\Results Search result object.
*/
protected function listRecordsGetNonDeleted(
$from,
$until,
$offset,
$limit,
$format,
$set = ''
) {
// Set up search parameters:
$results = $this->resultsManager->get($this->searchClassId);