-
Notifications
You must be signed in to change notification settings - Fork 350
/
Demo.php
2860 lines (2682 loc) · 95.3 KB
/
Demo.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
/**
* Advanced Dummy ILS Driver -- Returns sample values based on Solr index.
*
* Note that some sample values (holds, transactions, fines) are stored in
* the session. You can log out and log back in to get a different set of
* values.
*
* PHP version 8
*
* Copyright (C) Villanova University 2007, 2022.
* Copyright (C) The National Library of Finland 2014.
*
* 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 ILS_Drivers
* @author Greg Pendlebury <vufind-tech@lists.sourceforge.net>
* @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:plugins:ils_drivers Wiki
*/
namespace VuFind\ILS\Driver;
use ArrayObject;
use Laminas\Http\Request as HttpRequest;
use Laminas\Session\Container as SessionContainer;
use VuFind\Date\DateException;
use VuFind\Exception\ILS as ILSException;
use VuFind\ILS\Logic\AvailabilityStatus;
use VuFind\ILS\Logic\AvailabilityStatusInterface;
use VuFindSearch\Command\RandomCommand;
use VuFindSearch\Query\Query;
use VuFindSearch\Service as SearchService;
use function array_key_exists;
use function array_slice;
use function count;
use function in_array;
use function is_callable;
use function strlen;
/**
* Advanced Dummy ILS Driver -- Returns sample values based on Solr index.
*
* @category VuFind
* @package ILS_Drivers
* @author Greg Pendlebury <vufind-tech@lists.sourceforge.net>
* @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:plugins:ils_drivers Wiki
*/
class Demo extends AbstractBase implements \VuFind\I18n\HasSorterInterface
{
use \VuFind\I18n\HasSorterTrait;
/**
* Catalog ID used to distinquish between multiple Demo driver instances with the
* MultiBackend driver
*
* @var string
*/
protected $catalogId = 'demo';
/**
* Connection used when getting random bib ids from Solr
*
* @var SearchService
*/
protected $searchService;
/**
* Total count of records in the Solr index (used for random bib lookup)
*
* @var int
*/
protected $totalRecords;
/**
* Container for storing persistent simulated ILS data.
*
* @var SessionContainer[]
*/
protected $session = [];
/**
* Factory function for constructing the SessionContainer.
*
* @var callable
*/
protected $sessionFactory;
/**
* HTTP Request object (if available).
*
* @var ?HttpRequest
*/
protected $request;
/**
* Should we return bib IDs in MyResearch responses?
*
* @var bool
*/
protected $idsInMyResearch = true;
/**
* Should we support Storage Retrieval Requests?
*
* @var bool
*/
protected $storageRetrievalRequests = true;
/**
* Should we support ILLRequests?
*
* @var bool
*/
protected $ILLRequests = true;
/**
* Date converter object
*
* @var \VuFind\Date\Converter
*/
protected $dateConverter;
/**
* Failure probability settings
*
* @var array
*/
protected $failureProbabilities = [];
/**
* Courses for use in course reserves.
*
* @var array
*/
protected $courses = ['Course A', 'Course B', 'Course C'];
/**
* Departments for use in course reserves.
*
* @var array
*/
protected $departments = ['Dept. A', 'Dept. B', 'Dept. C'];
/**
* Instructors for use in course reserves.
*
* @var array
*/
protected $instructors = ['Instructor A', 'Instructor B', 'Instructor C'];
/**
* Item and pick up locations
*
* @var array
*/
protected $locations = [
[
'locationID' => 'A',
'locationDisplay' => 'Campus A',
],
[
'locationID' => 'B',
'locationDisplay' => 'Campus B',
],
[
'locationID' => 'C',
'locationDisplay' => 'Campus C',
],
];
/**
* Default pickup location
*
* @var string
*/
protected $defaultPickUpLocation;
/**
* Constructor
*
* @param \VuFind\Date\Converter $dateConverter Date converter object
* @param SearchService $ss Search service
* @param callable $sessionFactory Factory function returning
* SessionContainer object for fake data to simulate consistency and reduce Solr
* hits
* @param HttpRequest $request HTTP request object (optional)
*/
public function __construct(
\VuFind\Date\Converter $dateConverter,
SearchService $ss,
$sessionFactory,
HttpRequest $request = null
) {
$this->dateConverter = $dateConverter;
$this->searchService = $ss;
if (!is_callable($sessionFactory)) {
throw new \Exception('Invalid session factory passed to constructor.');
}
$this->sessionFactory = $sessionFactory;
$this->request = $request;
}
/**
* Initialize the driver.
*
* Validate configuration and perform all resource-intensive tasks needed to
* make the driver active.
*
* @throws ILSException
* @return void
*/
public function init()
{
if (isset($this->config['Catalog']['id'])) {
$this->catalogId = $this->config['Catalog']['id'];
}
if (isset($this->config['Catalog']['idsInMyResearch'])) {
$this->idsInMyResearch = $this->config['Catalog']['idsInMyResearch'];
}
if (isset($this->config['Catalog']['storageRetrievalRequests'])) {
$this->storageRetrievalRequests
= $this->config['Catalog']['storageRetrievalRequests'];
}
if (isset($this->config['Catalog']['ILLRequests'])) {
$this->ILLRequests = $this->config['Catalog']['ILLRequests'];
}
if (isset($this->config['Failure_Probabilities'])) {
$this->failureProbabilities = $this->config['Failure_Probabilities'];
}
$this->defaultPickUpLocation
= $this->config['Holds']['defaultPickUpLocation'] ?? '';
if ($this->defaultPickUpLocation === 'user-selected') {
$this->defaultPickUpLocation = false;
}
$this->checkIntermittentFailure();
}
/**
* Check for a simulated failure. Returns true for failure, false for
* success.
*
* @param string $method Name of method that might fail
* @param int $default Default probability (if config is empty)
*
* @return bool
*/
protected function isFailing($method, $default = 0)
{
// Method may come in like Class::Method, we just want the Method part
$parts = explode('::', $method);
$key = array_pop($parts);
$probability = $this->failureProbabilities[$key] ?? $default;
return rand(1, 100) <= $probability;
}
/**
* Generate a fake location name.
*
* @param bool $returnText If true, return location text; if false, return ID
*
* @return string
*/
protected function getFakeLoc($returnText = true)
{
$locations = $this->locations;
$loc = rand() % count($locations);
return $returnText
? $locations[$loc]['locationDisplay']
: $locations[$loc]['locationID'];
}
/**
* Generate fake services.
*
* @return array
*/
protected function getFakeServices()
{
// Load service configuration; return empty array if no services defined.
$services = isset($this->config['Records']['services'])
? (array)$this->config['Records']['services']
: [];
if (empty($services)) {
return [];
}
// Make it more likely we have a single service than many:
$count = rand(1, 5) == 1 ? rand(1, count($services)) : 1;
$keys = (array)array_rand($services, $count);
$fakeServices = [];
foreach ($keys as $key) {
if ($key !== null) {
$fakeServices[] = $services[$key];
}
}
return $fakeServices;
}
/**
* Generate a fake status message.
*
* @return string
*/
protected function getFakeStatus()
{
$loc = rand() % 10;
switch ($loc) {
case 10:
return 'Missing';
case 9:
return 'On Order';
case 8:
return 'Invoiced';
case 7:
return 'Uncertain';
default:
return 'Available';
}
}
/**
* Generate a fake call number.
*
* @return string
*/
protected function getFakeCallNum()
{
$codes = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
$a = $codes[rand() % strlen($codes)];
$b = rand() % 899 + 100;
$c = rand() % 9999;
return $a . $b . '.' . $c;
}
/**
* Generate a fake call number prefix sometimes.
*
* @return string
*/
protected function getFakeCallNumPrefix()
{
$codes = '0123456789';
$prefix = substr(str_shuffle($codes), 1, rand(0, 1));
if (!empty($prefix)) {
return 'Prefix: ' . $prefix;
}
return '';
}
/**
* Get a random ID from the Solr index.
*
* @return string
*/
protected function getRandomBibId()
{
[$id] = $this->getRandomBibIdAndTitle();
return $id;
}
/**
* Get a random ID and title from the Solr index.
*
* @return array [id, title]
*/
protected function getRandomBibIdAndTitle()
{
$source = $this->getRecordSource();
$query = $this->config['Records']['query'] ?? '*:*';
$command = new RandomCommand($source, new Query($query), 1);
$result = $this->searchService->invoke($command)->getResult();
if (count($result) === 0) {
throw new \Exception("Problem retrieving random record from $source.");
}
$record = current($result->getRecords());
return [$record->getUniqueId(), $record->getTitle()];
}
/**
* Get the name of the search backend providing records.
*
* @return string
*/
protected function getRecordSource()
{
return $this->config['Records']['source'] ?? DEFAULT_SEARCH_BACKEND;
}
/**
* Should we simulate a system failure?
*
* @return void
* @throws ILSException
*/
protected function checkIntermittentFailure()
{
if ($this->isFailing(__METHOD__, 0)) {
throw new ILSException('Simulating low-level system failure');
}
}
/**
* Are renewals blocked?
*
* @return bool
*/
protected function checkRenewBlock()
{
return $this->isFailing(__METHOD__, 25);
}
/**
* Check whether the patron is blocked from placing requests (holds/ILL/SRR).
*
* @param array $patron Patron data from patronLogin().
*
* @return mixed A boolean false if no blocks are in place and an array
* of block reasons if blocks are in place
*
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function getRequestBlocks($patron)
{
return $this->isFailing(__METHOD__, 10)
? ['simulated request block'] : false;
}
/**
* Check whether the patron has any blocks on their account.
*
* @param array $patron Patron data from patronLogin().
*
* @return mixed A boolean false if no blocks are in place and an array
* of block reasons if blocks are in place
*
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function getAccountBlocks($patron)
{
return $this->isFailing(__METHOD__, 10)
? ['simulated account block'] : false;
}
/**
* Generates a random, fake holding array
*
* @param string $id set id
* @param string $number set number for multiple items
* @param array $patron Patron data
*
* @return array
*/
protected function getRandomHolding($id, $number, array $patron = null)
{
$status = $this->getFakeStatus();
$location = $this->getFakeLoc();
$locationhref = ($location === 'Campus A') ? 'http://campus-a' : false;
switch ($status) {
case 'Uncertain':
$availability = AvailabilityStatusInterface::STATUS_UNCERTAIN;
break;
case 'Available':
if (rand(1, 2) === 1) {
// Legacy boolean value
$availability = true;
} else {
$availability = AvailabilityStatusInterface::STATUS_AVAILABLE;
$status = 'Item in Library';
}
break;
default:
if (rand(1, 2) === 1) {
// Legacy boolean value
$availability = false;
} else {
$availability = AvailabilityStatusInterface::STATUS_UNAVAILABLE;
}
break;
}
$result = [
'id' => $id,
'source' => $this->getRecordSource(),
'item_id' => $number,
'number' => $number,
'barcode' => sprintf('%08d', rand() % 50000),
'availability' => $availability,
'status' => $status,
'location' => $location,
'locationhref' => $locationhref,
'reserve' => rand(1, 4) === 1 ? 'Y' : 'N',
'callnumber' => $this->getFakeCallNum(),
'callnumber_prefix' => $this->getFakeCallNumPrefix(),
'duedate' => '',
'is_holdable' => true,
'addLink' => $patron ? true : false,
'level' => 'copy',
'storageRetrievalRequest' => 'auto',
'addStorageRetrievalRequestLink' => $patron ? 'check' : false,
'ILLRequest' => 'auto',
'addILLRequestLink' => $patron ? 'check' : false,
'services' => $status == 'Available' ? $this->getFakeServices() : [],
];
switch (rand(1, 5)) {
case 1:
$result['location'] = 'Digital copy available';
$result['locationhref'] = 'http://digital';
$result['__electronic__'] = true;
$result['availability'] = true;
$result['status'] = '';
break;
case 2:
$result['location'] = 'Electronic Journals';
$result['locationhref'] = 'http://electronic';
$result['__electronic__'] = true;
$result['availability'] = true;
$result['status'] = 'Available from ' . rand(2010, 2019);
}
return $result;
}
/**
* Generate an associative array containing some sort of ID (for cover
* generation).
*
* @return array
*/
protected function getRandomItemIdentifier()
{
switch (rand(1, 4)) {
case 1:
return ['isbn' => '1558612742'];
case 2:
return ['oclc' => '55114477'];
case 3:
return ['issn' => '1133-0686'];
}
return ['upc' => '733961100525'];
}
/**
* Generate a list of holds, storage retrieval requests or ILL requests.
*
* @param string $requestType Request type (Holds, StorageRetrievalRequests or
* ILLRequests)
*
* @return ArrayObject List of requests
*/
protected function createRequestList($requestType)
{
// How many items are there? %10 - 1 = 10% chance of none,
// 90% of 1-9 (give or take some odd maths)
$items = rand() % 10 - 1;
$requestGroups = $this->getRequestGroups(null, null);
$list = new ArrayObject();
for ($i = 0; $i < $items; $i++) {
$location = $this->getFakeLoc(false);
$randDays = rand() % 10;
$currentItem = [
'location' => $location,
'create' => $this->dateConverter->convertToDisplayDate(
'U',
strtotime("now - {$randDays} days")
),
'expire' => $this->dateConverter->convertToDisplayDate(
'U',
strtotime('now + 30 days')
),
'item_id' => $i,
'reqnum' => $i,
];
// Inject a random identifier of some sort:
$currentItem += $this->getRandomItemIdentifier();
if ($i == 2 || rand() % 5 == 1) {
// Mimic an ILL request
$currentItem['id'] = "ill_request_$i";
$currentItem['title'] = "ILL Hold Title $i";
$currentItem['institution_id'] = 'ill_institution';
$currentItem['institution_name'] = 'ILL Library';
$currentItem['institution_dbkey'] = 'ill_institution';
} else {
if ($this->idsInMyResearch) {
[$currentItem['id'], $currentItem['title']]
= $this->getRandomBibIdAndtitle();
$currentItem['source'] = $this->getRecordSource();
} else {
$currentItem['title'] = 'Demo Title ' . $i;
}
}
if ($requestType == 'Holds') {
$pos = rand() % 5;
if ($pos > 1) {
$currentItem['position'] = $pos;
$currentItem['available'] = false;
$currentItem['in_transit'] = (rand() % 2) === 1;
} else {
$currentItem['available'] = true;
$currentItem['in_transit'] = false;
if (rand() % 3 != 1) {
$lastDate = strtotime('now + 3 days');
$currentItem['last_pickup_date'] = $this->dateConverter
->convertToDisplayDate('U', $lastDate);
}
}
$pos = rand(0, count($requestGroups) - 1);
$currentItem['requestGroup'] = $requestGroups[$pos]['name'];
$currentItem['cancel_details'] = $currentItem['updateDetails']
= (!$currentItem['available'] && !$currentItem['in_transit'])
? $currentItem['reqnum'] : '';
if (rand(0, 3) === 1) {
$currentItem['proxiedBy'] = 'Fictional Proxy User';
}
} else {
$status = rand() % 5;
$currentItem['available'] = $status == 1;
$currentItem['canceled'] = $status == 2;
$currentItem['processed'] = ($status == 1 || rand(1, 3) == 3)
? $this->dateConverter->convertToDisplayDate('U', time())
: '';
if ($requestType == 'ILLRequests') {
$transit = rand() % 2;
if (
!$currentItem['available']
&& !$currentItem['canceled']
&& $transit == 1
) {
$currentItem['in_transit'] = $location;
} else {
$currentItem['in_transit'] = false;
}
}
}
$list->append($currentItem);
}
return $list;
}
/**
* Get Status
*
* This is responsible for retrieving the status information of a certain
* record.
*
* @param string $id The record id to retrieve the holdings for
*
* @return mixed On success, an associative array with the following keys:
* id, availability (boolean), status, location, reserve, callnumber.
*/
public function getStatus($id)
{
return $this->getSimulatedStatus($id);
}
/**
* Get suppressed records.
*
* @return array ID numbers of suppressed records in the system.
*/
public function getSuppressedRecords()
{
return $this->config['Records']['suppressed'] ?? [];
}
/**
* Get the session container (constructing it on demand if not already present)
*
* @param string $patron ID of current patron
*
* @return SessionContainer
*/
protected function getSession($patron = null)
{
$sessionKey = md5($this->catalogId . '/' . ($patron ?? 'default'));
// SessionContainer not defined yet? Build it now:
if (!isset($this->session[$sessionKey])) {
$this->session[$sessionKey] = ($this->sessionFactory)($sessionKey);
}
$result = $this->session[$sessionKey];
// Special case: check for clear_demo request parameter to reset:
if ($this->request && $this->request->getQuery('clear_demo')) {
$result->exchangeArray([]);
}
return $result;
}
/**
* Get Simulated Status (support method for getStatus/getHolding)
*
* This is responsible for retrieving the status information of a certain
* record.
*
* @param string $id The record id to retrieve the holdings for
* @param array $patron Patron data
*
* @return mixed On success, an associative array with the following keys:
* id, availability (boolean), status, location, reserve, callnumber.
*
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
protected function getSimulatedStatus($id, array $patron = null)
{
$id = (string)$id;
if ($json = $this->config['StaticHoldings'][$id] ?? null) {
foreach (json_decode($json, true) as $i => $status) {
if ($status['use_status_class'] ?? false) {
$availability = $status['availability'] ?? false;
if ($status['use_unknown_message'] ?? false) {
$availability = AvailabilityStatusInterface::STATUS_UNKNOWN;
}
$status['availability'] = new AvailabilityStatus(
$availability,
$status['status'] ?? '',
$status['extraStatusInformation'] ?? []
);
unset($status['status']);
unset($status['use_unknown_message']);
}
$this->setStatus($id, $status, $i > 0, $patron);
}
}
// Do we have a fake status persisted in the session?
$session = $this->getSession($patron['id'] ?? null);
if (isset($session->statuses[$id])) {
return $session->statuses[$id];
}
// Create fake entries for a random number of items
$holding = [];
$records = rand() % 15;
for ($i = 1; $i <= $records; $i++) {
$holding[] = $this->setStatus($id, [], true, $patron);
}
return $holding;
}
/**
* Set Status
*
* @param string $id id for record
* @param array $holding associative array with options to specify
* number, barcode, availability, status, location,
* reserve, callnumber, duedate, is_holdable, and addLink
* @param bool $append add another record or replace current record
* @param array $patron Patron data
*
* @return array
*/
protected function setStatus(string $id, $holding = [], $append = true, $patron = null)
{
$session = $this->getSession($patron['id'] ?? null);
$i = isset($session->statuses[$id])
? count($session->statuses[$id]) + 1 : 1;
$holding = array_merge($this->getRandomHolding($id, $i, $patron), $holding);
// if statuses is already stored
if ($session->statuses) {
// and this id is part of it
if ($append && isset($session->statuses[$id])) {
// add to the array
$session->statuses[$id][] = $holding;
} else {
// if we're over-writing or if there's nothing stored for this id
$session->statuses[$id] = [$holding];
}
} else {
// brand new status storage!
$session->statuses = [$id => [$holding]];
}
return $holding;
}
/**
* Get Statuses
*
* This is responsible for retrieving the status information for a
* collection of records.
*
* @param array $ids The array of record ids to retrieve the status for
*
* @return array An array of getStatus() return values on success.
*/
public function getStatuses($ids)
{
$this->checkIntermittentFailure();
if ($this->isFailing(__METHOD__, 0)) {
return array_map(
function ($id) {
return [
[
'id' => $id,
'error' => 'Simulated failure',
],
];
},
$ids
);
}
return array_map([$this, 'getStatus'], $ids);
}
/**
* Get Holding
*
* This is responsible for retrieving the holding information of a certain
* record.
*
* @param string $id The record id to retrieve the holdings for
* @param array $patron Patron data
* @param array $options Extra options
*
* @return array On success, an associative array with the following keys:
* id, availability (boolean), status, location, reserve, callnumber,
* duedate, number, barcode.
*/
public function getHolding($id, array $patron = null, array $options = [])
{
$this->checkIntermittentFailure();
if ($this->isFailing(__METHOD__, 0)) {
return [
'id' => $id,
'error' => 'Simulated failure',
];
}
// Get basic status info:
$status = $this->getSimulatedStatus($id, $patron);
$issue = 1;
// Add notes and summary:
foreach (array_keys($status) as $i) {
$itemNum = $i + 1;
$noteCount = rand(1, 3);
$status[$i]['holdings_notes'] = [];
$status[$i]['item_notes'] = [];
for ($j = 1; $j <= $noteCount; $j++) {
$status[$i]['holdings_notes'][] = "Item $itemNum holdings note $j"
. ($j === 1 ? ' https://vufind.org/?f=1&b=2#sample_link' : '');
$status[$i]['item_notes'][] = "Item $itemNum note $j";
}
$summCount = rand(1, 3);
$status[$i]['summary'] = [];
for ($j = 1; $j <= $summCount; $j++) {
$status[$i]['summary'][] = "Item $itemNum summary $j";
}
$volume = intdiv($issue, 4) + 1;
$seriesIssue = $issue % 4;
$issue = $issue + 1;
$status[$i]['enumchron'] = "volume $volume, issue $seriesIssue";
if (rand(1, 100) <= ($this->config['Holdings']['boundWithProbability'] ?? 25)) {
$status[$i]['bound_with_records'] = [];
$boundWithCount = 3;
for ($j = 0; $j < $boundWithCount; $j++) {
$randomRecord = array_combine(['bibId', 'title'], $this->getRandomBibIdAndTitle());
$status[$i]['bound_with_records'][] = $randomRecord;
}
$boundWithIndex = rand(0, $boundWithCount + 1);
array_splice($status[$i]['bound_with_records'], $boundWithIndex, 0, [
[
'title' => 'The Title on This Page',
'bibId' => $id,
],
]);
}
}
// Filter out electronic holdings from the normal holdings list:
$status = array_filter(
$status,
function ($a) {
return !($a['__electronic__'] ?? false);
}
);
// Slice out a chunk if pagination is enabled.
$slice = null;
if ($options['itemLimit'] ?? null) {
// For sensible pagination, we need to sort by location:
$callback = function ($a, $b) {
return $this->getSorter()->compare($a['location'], $b['location']);
};
usort($status, $callback);
$slice = array_slice(
$status,
$options['offset'] ?? 0,
$options['itemLimit']
);
}
// Electronic holdings:
$statuses = $this->getStatus($id);
$electronic = [];
foreach ($statuses as $item) {
if ($item['__electronic__'] ?? false) {
// Don't expose internal __electronic__ flag upstream:
unset($item['__electronic__']);
$electronic[] = $item;
}
}
// Send back final value:
return [
'total' => count($status),
'holdings' => $slice ?: $status,
'electronic_holdings' => $electronic,
];
}
/**
* Get Purchase History
*
* This is responsible for retrieving the acquisitions history data for the
* specific record (usually recently received issues of a serial).
*
* @param string $id The record id to retrieve the info for
*
* @return array An array with the acquisitions data on success.
*/
public function getPurchaseHistory($id)
{
$this->checkIntermittentFailure();
$issues = rand(0, 3);
$retval = [];
for ($i = 0; $i < $issues; $i++) {
$retval[] = ['issue' => 'issue ' . ($i + 1)];
}
return $retval;
}
/**
* Patron Login
*
* This is responsible for authenticating a patron against the catalog.
*
* @param string $username The patron username
* @param string $password The patron password
*
* @throws ILSException
* @return mixed Associative array of patron info on successful login,
* null on unsuccessful login.
*/
public function patronLogin($username, $password)
{
$this->checkIntermittentFailure();
$user = [
'id' => trim($username),
'firstname' => 'Lib',
'lastname' => 'Rarian',
'cat_username' => trim($username),
'cat_password' => trim($password),
'email' => 'Lib.Rarian@library.not',
'major' => null,
'college' => null,
];
$loginMethod = $this->config['Catalog']['loginMethod'] ?? 'password';
if ('email' === $loginMethod) {
$user['email'] = $username;
$user['cat_password'] = '';
return $user;
}
if (isset($this->config['Users'])) {
if (
!isset($this->config['Users'][$username])
|| $password !== $this->config['Users'][$username]
) {
return null;