/
KohaILSDI.php
2077 lines (1917 loc) · 73.1 KB
/
KohaILSDI.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
/**
* KohaILSDI ILS Driver
*
* PHP version 8
*
* Copyright (C) Alex Sassmannshausen, PTFS Europe 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 Alex Sassmannshausen <alex.sassmannshausen@ptfs-europe.com>
* @author Tom Misilo <misilot@fit.edu>
* @author Josef Moravec <josef.moravec@gmail.com>
* @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 Laminas\Log\LoggerAwareInterface;
use PDO;
use PDOException;
use VuFind\Date\DateException;
use VuFind\Exception\ILS as ILSException;
use VuFindHttp\HttpServiceAwareInterface;
use function array_slice;
use function count;
use function in_array;
use function intval;
use function is_callable;
/**
* VuFind Driver for Koha, using web APIs (ILSDI)
*
* Minimum Koha Version: 3.18.6
*
* @category VuFind
* @package ILS_Drivers
* @author Alex Sassmannshausen <alex.sassmannshausen@ptfs-europe.com>
* @author Tom Misilo <misilot@fit.edu>
* @author Josef Moravec <josef.moravec@gmail.com>
* @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License
* @link https://vufind.org/wiki/development:plugins:ils_drivers Wiki
*/
class KohaILSDI extends AbstractBase implements HttpServiceAwareInterface, LoggerAwareInterface
{
use \VuFind\Cache\CacheTrait {
getCacheKey as protected getBaseCacheKey;
}
use \VuFindHttp\HttpServiceAwareTrait;
use \VuFind\Log\LoggerAwareTrait;
/**
* Web services host
*
* @var string
*/
protected $host;
/**
* ILS base URL
*
* @var string
*/
protected $ilsBaseUrl;
/**
* Location codes
*
* @var array
*/
protected $locations;
/**
* Codes of locations available for pickup
*
* @var array
*/
protected $pickupEnableBranchcodes;
/**
* Codes of locations always should be available
* - For example reference material or material
* not for loan
*
* @var array
*/
protected $availableLocationsDefault;
/**
* Default location code
*
* @var string
*/
protected $defaultLocation;
/**
* Database connection
*
* @var PDO
*/
protected $db;
/**
* Date converter object
*
* @var \VuFind\Date\Converter
*/
protected $dateConverter;
/**
* Should validate passwords against Koha system?
*
* @var bool
*/
protected $validatePasswords;
/**
* Authorised values category for location, defaults to 'LOC'
*
* @var string
*/
protected $locationAuthorisedValuesCategory;
/**
* Default terms for block types, can be overridden by configuration
*
* @var array
*/
protected $blockTerms = [
'SUSPENSION' => 'Account Suspended',
'OVERDUES' => 'Account Blocked (Overdue Items)',
'MANUAL' => 'Account Blocked',
'DISCHARGE' => 'Account Blocked for Discharge',
];
/**
* Display comments for patron debarments, see KohaILSDI.ini
*
* @var array
*/
protected $showBlockComments;
/**
* Should we show permanent location (or current)
*
* @var bool
*/
protected $showPermanentLocation;
/**
* Should we show homebranch instead of holdingbranch
*
* @var bool
*/
protected $showHomebranch;
/**
* Constructor
*
* @param \VuFind\Date\Converter $dateConverter Date converter object
*/
public function __construct(\VuFind\Date\Converter $dateConverter)
{
$this->dateConverter = $dateConverter;
}
/**
* 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 (empty($this->config)) {
throw new ILSException('Configuration needs to be set.');
}
// Base for API address
$this->host = $this->config['Catalog']['host'] ?? 'localhost';
// Storing the base URL of ILS
$this->ilsBaseUrl = $this->config['Catalog']['url'] ?? '';
// Default location defined in 'KohaILSDI.ini'
$this->defaultLocation
= $this->config['Holds']['defaultPickUpLocation'] ?? null;
$this->pickupEnableBranchcodes
= $this->config['Holds']['pickupLocations'] ?? [];
// Locations that should default to available, defined in 'KohaILSDI.ini'
$this->availableLocationsDefault
= $this->config['Other']['availableLocations'] ?? [];
// If we are using SAML/Shibboleth for authentication for both ourselves
// and Koha then we can't validate the patrons passwords against Koha as
// they won't have one. (Double negative logic used so that if the config
// option isn't present in KohaILSDI.ini then ILS passwords will be
// validated)
$this->validatePasswords
= empty($this->config['Catalog']['dontValidatePasswords']);
// The Authorised Values Category use for locations should default to 'LOC'
$this->locationAuthorisedValuesCategory
= $this->config['Catalog']['locationAuthorisedValuesCategory'] ?? 'LOC';
$this->showPermanentLocation
= $this->config['Catalog']['showPermanentLocation'] ?? false;
$this->showHomebranch = $this->config['Catalog']['showHomebranch'] ?? false;
$this->debug('Config Summary:');
$this->debug('DB Host: ' . $this->host);
$this->debug('ILS URL: ' . $this->ilsBaseUrl);
$this->debug('Locations: ' . $this->locations);
$this->debug('Default Location: ' . $this->defaultLocation);
// Now override the default with any defined in the `KohaILSDI.ini` config
// file
foreach (['SUSPENSION','OVERDUES','MANUAL','DISCHARGE'] as $blockType) {
if (!empty($this->config['Blocks'][$blockType])) {
$this->blockTerms[$blockType] = $this->config['Blocks'][$blockType];
}
}
// Allow the users to set if an account block's comments should be included
// by setting the block type to true or false () in the `KohaILSDI.ini`
// config file (defaults to false if not present)
$this->showBlockComments = [];
foreach (['SUSPENSION','OVERDUES','MANUAL','DISCHARGE'] as $blockType) {
$this->showBlockComments[$blockType]
= !empty($this->config['Show_Block_Comments'][$blockType]);
}
}
/**
* Initialize the DB driver.
*
* Validate configuration and perform all resource-intensive tasks needed to
* make the driver active.
*
* @throws ILSException
* @return void
*/
protected function initDb()
{
if (empty($this->config)) {
throw new ILSException('Configuration needs to be set.');
}
//Connect to MySQL
try {
$this->db = new PDO(
'mysql:host=' . $this->host .
';port=' . $this->config['Catalog']['port'] .
';dbname=' . $this->config['Catalog']['database'],
$this->config['Catalog']['username'],
$this->config['Catalog']['password'],
[PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8']
);
// Throw PDOExceptions if something goes wrong
$this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//Return result set like mysql_fetch_assoc()
$this->db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
// set communication encoding to utf8
$this->db->exec('SET NAMES utf8');
// Drop the ONLY_FULL_GROUP_BY entry from sql_mode as it breaks this
// ILS Driver on modern
$setSqlModes = $this->db->prepare('SET sql_mode = :sqlMode');
$sqlModes = $this->db->query('SELECT @@sql_mode');
foreach ($sqlModes as $row) {
$sqlMode = implode(
',',
array_filter(
explode(',', $row['@@sql_mode']),
function ($mode) {
return $mode != 'ONLY_FULL_GROUP_BY';
}
)
);
$setSqlModes->execute(['sqlMode' => $sqlMode]);
}
} catch (PDOException $e) {
$this->debug('Connection failed: ' . $e->getMessage());
$this->throwAsIlsException($e);
}
$this->debug('Connected to DB');
}
/**
* Get the database connection (and make sure it is initialized).
*
* @return PDO
*/
protected function getDb()
{
if (!$this->db) {
$this->initDb();
}
return $this->db;
}
/**
* Check if a table exists in the current database.
*
* @param string $table Table to search for.
*
* @return bool
*/
protected function tableExists($table)
{
$cacheKey = "kohailsdi-tables-$table";
$cachedValue = $this->getCachedData($cacheKey);
if ($cachedValue !== null) {
return $cachedValue;
}
$returnValue = false;
// Try a select statement against the table
// Run it in try/catch in case PDO is in ERRMODE_EXCEPTION.
try {
$result = $this->getDb()->query("SELECT 1 FROM $table LIMIT 1");
// Result is FALSE (no table found) or PDOStatement Object (table found)
$returnValue = $result !== false;
} catch (PDOException $e) {
// We got an exception == table not found
$returnValue = false;
}
$this->putCachedData($cacheKey, $returnValue);
return $returnValue;
}
/**
* Koha ILS-DI driver specific override of method to ensure uniform cache keys
* for cached VuFind objects.
*
* @param string|null $suffix Optional suffix that will get appended to the
* object class name calling getCacheKey()
*
* @return string
*/
protected function getCacheKey($suffix = null)
{
return $this->getBaseCacheKey(
md5($this->ilsBaseUrl) . $suffix
);
}
/**
* Get Field
*
* Check $contents is not "", return it; else return $default.
*
* @param string $contents string to be checked
* @param string $default value to return if $contents is ""
*
* @return string
*/
protected function getField($contents, $default = 'Unknown')
{
if ((string)$contents != '') {
return (string)$contents;
} else {
return $default;
}
}
/**
* Make Request
*
* Makes a request to the Koha ILSDI API
*
* @param string $api_query Query string for request
* @param string $http_method HTTP method (default = GET)
*
* @throws ILSException
* @return obj
*/
protected function makeRequest($api_query, $http_method = 'GET')
{
//$url = $this->host . $this->api_path . $api_query;
$url = $this->ilsBaseUrl . '?service=' . $api_query;
$this->debug("URL: '$url'");
$http_headers = [
'Accept: text/xml',
'Accept-encoding: plain',
];
try {
$client = $this->httpService->createClient($url);
$client->setMethod($http_method);
$client->setHeaders($http_headers);
$result = $client->send();
} catch (\Exception $e) {
$this->debug('Result is invalid.');
$this->throwAsIlsException($e);
}
if (!$result->isSuccess()) {
$this->debug('Result is invalid.');
throw new ILSException('HTTP error');
}
$answer = $result->getBody();
//$answer = str_replace('xmlns=', 'ns=', $answer);
$result = simplexml_load_string($answer);
if (!$result) {
$this->debug("XML is not valid, URL: $url");
throw new ILSException(
"XML is not valid, URL: $url method: $http_method answer: $answer."
);
}
return $result;
}
/**
* Make Ilsdi Request Array
*
* Makes a request to the Koha ILSDI API
*
* @param string $service Called function (GetAvailability,
* GetRecords,
* GetAuthorityRecords,
* LookupPatron,
* AuthenticatePatron,
* GetPatronInfo,
* GetPatronStatus,
* GetServices,
* RenewLoan,
* HoldTitle,
* HoldItem,
* CancelHold)
* @param array $params Key is parameter name, value is parameter value
* @param string $http_method HTTP method (default = GET)
*
* @throws ILSException
* @return obj
*/
protected function makeIlsdiRequest($service, $params, $http_method = 'GET')
{
$start = microtime(true);
$url = $this->ilsBaseUrl . '?service=' . $service;
foreach ($params as $paramname => $paramvalue) {
$url .= "&$paramname=" . urlencode($paramvalue);
}
$this->debug("URL: '$url'");
$http_headers = [
'Accept: text/xml',
'Accept-encoding: plain',
];
try {
$client = $this->httpService->createClient($url);
$client->setMethod($http_method);
$client->setHeaders($http_headers);
$result = $client->send();
} catch (\Exception $e) {
$this->debug('Result is invalid.');
$this->throwAsIlsException($e);
}
if (!$result->isSuccess()) {
$this->debug('Result is invalid.');
throw new ILSException('HTTP error');
}
$end = microtime(true);
$time1 = $end - $start;
$start = microtime(true);
$result = simplexml_load_string($result->getBody());
if (!$result) {
$this->debug("XML is not valid, URL: $url");
throw new ILSException(
"XML is not valid, URL: $url"
);
}
$end = microtime(true);
$time2 = $end - $start;
$this->debug("Request times: $time1 - $time2");
return $result;
}
/**
* To Koha Date
*
* Turns a display date into a date format expected by Koha.
*
* @param ?string $display_date Date to be converted
*
* @throws ILSException
* @return ?string $koha_date
*/
protected function toKohaDate(?string $display_date): ?string
{
// Convert last interest date from display format to Koha format
$koha_date = !empty($display_date)
? $this->dateConverter->convertFromDisplayDate('Y-m-d', $display_date)
: null;
return $koha_date;
}
/**
* Public Function which retrieves renew, hold and cancel settings from the
* driver ini file.
*
* @param string $function The name of the feature to be checked
* @param array $params Optional feature-specific parameters (array)
*
* @return array An array with key-value pairs.
*
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function getConfig($function, $params = [])
{
if ('getMyTransactionHistory' === $function) {
if (empty($this->config['TransactionHistory']['enabled'])) {
return false;
}
return [
'max_results' => 100,
'sort' => [
'checkout desc' => 'sort_checkout_date_desc',
'checkout asc' => 'sort_checkout_date_asc',
'return desc' => 'sort_return_date_desc',
'return asc' => 'sort_return_date_asc',
'due desc' => 'sort_due_date_desc',
'due asc' => 'sort_due_date_asc',
],
'default_sort' => 'checkout desc',
];
}
return $this->config[$function] ?? false;
}
/**
* Get Pick Up Locations
*
* This is responsible for gettting a list of valid library locations for
* holds / recall retrieval
*
* @param array $patron Patron information returned by the patronLogin
* method.
* @param array $holdDetails Optional array, only passed in when getting a list
* in the context of placing or editing a hold. When placing a hold, it contains
* most of the same values passed to placeHold, minus the patron data. When
* editing a hold it contains all the hold information returned by getMyHolds.
* May be used to limit the pickup options or may be ignored. The driver must
* not add new options to the return array based on this data or other areas of
* VuFind may behave incorrectly.
*
* @throws ILSException
* @return array An array of associative arrays with locationID and
* locationDisplay keys
*
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function getPickUpLocations($patron = false, $holdDetails = null)
{
if (!$this->locations) {
if (!$this->pickupEnableBranchcodes) {
// No defaultPickupLocation is defined in config
// AND no pickupLocations are defined either
if (
isset($holdDetails['item_id']) && (empty($holdDetails['level'])
|| $holdDetails['level'] == 'item')
) {
// We try to get the actual branchcode the item is found at
$item_id = $holdDetails['item_id'];
$sql = "SELECT holdingbranch
FROM items
WHERE itemnumber=($item_id)";
try {
$sqlSt = $this->getDb()->prepare($sql);
$sqlSt->execute();
$this->pickupEnableBranchcodes = $sqlSt->fetch();
} catch (PDOException $e) {
$this->debug('Connection failed: ' . $e->getMessage());
$this->throwAsIlsException($e);
}
} elseif (
!empty($holdDetails['level'])
&& $holdDetails['level'] == 'title'
) {
// We try to get the actual branchcodes the title is found at
$id = $holdDetails['id'];
$sql = "SELECT DISTINCT holdingbranch
FROM items
WHERE biblionumber=($id)";
try {
$sqlSt = $this->getDb()->prepare($sql);
$sqlSt->execute();
foreach ($sqlSt->fetchAll() as $row) {
$this->pickupEnableBranchcodes[] = $row['holdingbranch'];
}
} catch (PDOException $e) {
$this->debug('Connection failed: ' . $e->getMessage());
$this->throwAsIlsException($e);
}
}
}
$branchcodes = "'" . implode(
"','",
$this->pickupEnableBranchcodes
) . "'";
$sql = "SELECT branchcode as locationID,
branchname as locationDisplay
FROM branches
WHERE branchcode IN ($branchcodes)";
try {
$sqlSt = $this->getDb()->prepare($sql);
$sqlSt->execute();
$this->locations = $sqlSt->fetchAll();
} catch (PDOException $e) {
$this->debug('Connection failed: ' . $e->getMessage());
$this->throwAsIlsException($e);
}
}
return $this->locations;
// we get them from the API
// FIXME: Not yet possible: API incomplete.
// TODO: When API: pull locations dynamically from API.
/* $response = $this->makeRequest("organizations/branch"); */
/* $locations_response_array = $response->OrganizationsGetRows; */
/* foreach ($locations_response_array as $location_response) { */
/* $locations[] = array( */
/* 'locationID' => $location_response->OrganizationID, */
/* 'locationDisplay' => $location_response->Name, */
/* ); */
/* } */
}
/**
* Get Default Pick Up Location
*
* Returns the default pick up location set in KohaILSDI.ini
*
* @param array $patron Patron information returned by the patronLogin
* method.
* @param array $holdDetails Optional array, only passed in when getting a list
* in the context of placing a hold; contains most of the same values passed to
* placeHold, minus the patron data. May be used to limit the pickup options
* or may be ignored.
*
* @return string The default pickup location for the patron.
*
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function getDefaultPickUpLocation($patron = false, $holdDetails = null)
{
return $this->defaultLocation;
}
/**
* Place Hold
*
* Attempts to place a hold or recall on a particular item and returns
* an array with result details or throws an exception on failure of support
* classes
*
* @param array $holdDetails An array of item and patron data
*
* @throws ILSException
* @return mixed An array of data on the request including
* whether or not it was successful and a system message (if available)
*/
public function placeHold($holdDetails)
{
$patron = $holdDetails['patron'];
$patron_id = $patron['id'];
$request_location = $patron['ip'] ?? '127.0.0.1';
$bib_id = $holdDetails['id'];
$item_id = $holdDetails['item_id'];
$pickup_location = !empty($holdDetails['pickUpLocation'])
? $holdDetails['pickUpLocation'] : $this->defaultLocation;
$level = isset($holdDetails['level'])
&& !empty($holdDetails['level']) ? $holdDetails['level'] : 'item';
try {
$needed_before_date = $this->toKohaDate(
$holdDetails['requiredBy'] ?? null
);
} catch (\Exception $e) {
return [
'success' => false,
'sysMessage' => 'hold_date_invalid',
];
}
$this->debug('patron: ' . $this->varDump($patron));
$this->debug('patron_id: ' . $patron_id);
$this->debug('request_location: ' . $request_location);
$this->debug('item_id: ' . $item_id);
$this->debug('bib_id: ' . $bib_id);
$this->debug('pickup loc: ' . $pickup_location);
$this->debug('Needed before date: ' . $needed_before_date);
$this->debug('Level: ' . $level);
// The following check is mainly required for certain old buggy Koha versions
// that allowed multiple holds from the same user to the same item
$sql = 'select count(*) as RCOUNT from reserves where borrowernumber = :rid '
. 'and itemnumber = :iid';
$reservesSqlStmt = $this->getDb()->prepare($sql);
$reservesSqlStmt->execute([':rid' => $patron_id, ':iid' => $item_id]);
$reservesCount = $reservesSqlStmt->fetch()['RCOUNT'];
if ($reservesCount > 0) {
$this->debug('Fatal error: Patron has already reserved this item.');
return [
'success' => false,
'sysMessage' => 'It seems you have already reserved this item.',
];
}
if ($level == 'title') {
$rqString = "HoldTitle&patron_id=$patron_id&bib_id=$bib_id"
. "&request_location=$request_location"
. "&pickup_location=$pickup_location";
} else {
$rqString = "HoldItem&patron_id=$patron_id&bib_id=$bib_id"
. "&item_id=$item_id"
. "&pickup_location=$pickup_location";
}
$dateString = empty($needed_before_date)
? '' : "&expiry_date=$needed_before_date";
$rsp = $this->makeRequest($rqString . $dateString);
if ($rsp->{'code'} == 'IllegalParameter' && $dateString != '') {
// In older versions of Koha, the date parameters were named differently
// and even never implemented, so if we got IllegalParameter, we know
// the Koha version is before 20.05 and could retry without expiry_date
// parameter. See:
// https://git.koha-community.org/Koha-community/Koha/commit/c8bf308e1b453023910336308d59566359efc535
$rsp = $this->makeRequest($rqString);
}
//TODO - test this new functionality
/*
if ( $level == "title" ) {
$rsp2 = $this->makeIlsdiRequest("HoldTitle",
array("patron_id" => $patron_id,
"bib_id" => $bib_id,
"request_location" => $request_location,
"pickup_location" => $pickup_location,
"pickup_expiry_date" => $needed_before_date,
"needed_before_date" => $needed_before_date
));
} else {
$rsp2 = $this->makeIlsdiRequest("HoldItem",
array("patron_id" => $patron_id,
"bib_id" => $bib_id,
"item_id" => $item_id,
"pickup_location" => $pickup_location,
"pickup_expiry_date" => $needed_before_date,
"needed_before_date" => $needed_before_date
));
}
*/
$this->debug('Title: ' . $rsp->{'title'});
$this->debug('Pickup Location: ' . $rsp->{'pickup_location'});
$this->debug('Code: ' . $rsp->{'code'});
if ($rsp->{'code'} != '') {
$this->debug('Error Message: ' . $rsp->{'message'});
return [
'success' => false,
'sysMessage' => $this->getField($rsp->{'code'})
. $holdDetails['level'],
];
}
return [
'success' => true,
//"sysMessage" => $message,
];
}
/**
* 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 (not currently used)
*
* @throws DateException
* @throws ILSException
* @return array On success, an associative array with the following
* keys: id, availability (boolean), status, location, reserve, callnumber,
* duedate, number, barcode.
*
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function getHolding($id, array $patron = null, array $options = [])
{
$this->debug(
"Function getHolding($id, "
. implode(',', (array)$patron)
. ') called'
);
$started = microtime(true);
$holding = [];
$available = true;
$duedate = $status = '';
$loc = '';
$locationField = $this->showPermanentLocation
? 'permanent_location' : 'location';
$sql = "select i.itemnumber as ITEMNO, i.location,
COALESCE(av.lib_opac,av.lib,av.authorised_value,i.$locationField)
AS LOCATION,
i.holdingbranch as HLDBRNCH, i.homebranch as HOMEBRANCH,
i.reserves as RESERVES, i.itemcallnumber as CALLNO, i.barcode as BARCODE,
i.copynumber as COPYNO, i.notforloan as NOTFORLOAN,
i.enumchron AS ENUMCHRON,
i.itemnotes as PUBLICNOTES, b.frameworkcode as DOCTYPE,
t.frombranch as TRANSFERFROM, t.tobranch as TRANSFERTO,
i.itemlost as ITEMLOST, i.itemlost_on AS LOSTON,
i.stocknumber as STOCKNUMBER
from items i join biblio b on i.biblionumber = b.biblionumber
left outer join
(SELECT itemnumber, frombranch, tobranch from branchtransfers
where datearrived IS NULL) as t USING (itemnumber)
left join authorised_values as av
on i.$locationField = av.authorised_value
where i.biblionumber = :id
AND (av.category = :av_category OR av.category IS NULL)
order by i.itemnumber DESC";
$sqlReserves = 'select count(*) as RESERVESCOUNT from reserves '
. 'WHERE biblionumber = :id AND found IS NULL';
$sqlWaitingReserve = 'select count(*) as WAITING from reserves '
. "WHERE itemnumber = :item_id and found = 'W'";
if ($this->tableExists('biblio_metadata')) {
$sqlHoldings = 'SELECT '
. 'ExtractValue(( SELECT metadata FROM biblio_metadata '
. "WHERE biblionumber = :id AND format='marcxml'), "
. "'//datafield[@tag=\"866\"]/subfield[@code=\"a\"]') AS MFHD;";
} else {
$sqlHoldings = 'SELECT ExtractValue(( SELECT marcxml FROM biblioitems '
. 'WHERE biblionumber = :id), '
. "'//datafield[@tag=\"866\"]/subfield[@code=\"a\"]') AS MFHD;";
}
try {
$itemSqlStmt = $this->getDb()->prepare($sql);
$itemSqlStmt->execute(
[
':id' => $id,
':av_category' => $this->locationAuthorisedValuesCategory,
]
);
$sqlStmtReserves = $this->getDb()->prepare($sqlReserves);
$sqlStmtWaitingReserve = $this->getDb()->prepare($sqlWaitingReserve);
$sqlStmtReserves->execute([':id' => $id]);
$sqlStmtHoldings = $this->getDb()->prepare($sqlHoldings);
$sqlStmtHoldings->execute([':id' => $id]);
} catch (PDOException $e) {
$this->debug('Connection failed: ' . $e->getMessage());
$this->throwAsIlsException($e);
}
$this->debug('Rows count: ' . $itemSqlStmt->rowCount());
$notes = $sqlStmtHoldings->fetch();
$reservesRow = $sqlStmtReserves->fetch();
$reservesCount = $reservesRow['RESERVESCOUNT'];
foreach ($itemSqlStmt->fetchAll() as $rowItem) {
$inum = $rowItem['ITEMNO'];
$sqlStmtWaitingReserve->execute([':item_id' => $inum]);
$waitingReserveRow = $sqlStmtWaitingReserve->fetch();
$waitingReserve = $waitingReserveRow['WAITING'];
if ($rowItem['LOCATION'] == 'PROC') {
$available = false;
$status = 'In processing';
$duedate = '';
} else {
$sql = 'select date_due as DUEDATE from issues
where itemnumber = :inum';
switch ($rowItem['NOTFORLOAN']) {
case 0:
// If the item is available for loan, then check its current
// status
$issueSqlStmt = $this->getDb()->prepare($sql);
$issueSqlStmt->execute([':inum' => $inum]);
$rowIssue = $issueSqlStmt->fetch();
if ($rowIssue) {
$available = false;
$status = 'Checked out';
$duedate = $rowIssue['DUEDATE'];
} else {
$available = true;
$status = 'Available';
// No due date for an available item
$duedate = '';
}
break;
case 1: // The item is not available for loan
default:
$available = false;
$status = 'Not for loan';
$duedate = '';
break;
}
}
/*
* If the Item is in any of locations defined by
* availableLocations[] in the KohaILSDI.ini file
* the item is considered available
*/
if (in_array($rowItem['LOCATION'], $this->availableLocationsDefault)) {
$available = true;
$duedate = '';
$status = 'Available';
}
// If Item is Lost or Missing, provide that status
if ($rowItem['ITEMLOST'] > 0) {
$available = false;
$duedate = $rowItem['LOSTON'];
$status = 'Lost/Missing';
}
$duedate_formatted = $this->displayDate($duedate);
if ($rowItem['HLDBRNCH'] == null && $rowItem['HOMEBRANCH'] == null) {
$loc = 'Unknown';
} else {
$loc = $rowItem['LOCATION'];
}
if ($this->showHomebranch) {
$branch = $rowItem['HOMEBRANCH'] ?? $rowItem['HLDBRNCH'] ?? '';
} else {
$branch = $rowItem['HLDBRNCH'] ?? $rowItem['HOMEBRANCH'] ?? '';
}
$sqlBranch = 'select branchname as BNAME
from branches
where branchcode = :branch';
$branchSqlStmt = $this->getDb()->prepare($sqlBranch);
//Retrieving the full branch name
if ($loc != 'Unknown') {
$branchSqlStmt->execute([':branch' => $branch]);
$row = $branchSqlStmt->fetch();
if ($row) {
$loc = $row['BNAME'] . ' - ' . $loc;
}
}
$onTransfer = false;
if (
($rowItem['TRANSFERFROM'] != null)
&& ($rowItem['TRANSFERTO'] != null)
) {
$branchSqlStmt->execute([':branch' => $rowItem['TRANSFERFROM']]);
$rowFrom = $branchSqlStmt->fetch();
$transferfrom = $rowFrom
? $rowFrom['BNAME'] : $rowItem['TRANSFERFROM'];
$branchSqlStmt->execute([':branch' => $rowItem['TRANSFERTO']]);
$rowTo = $branchSqlStmt->fetch();
$transferto = $rowTo ? $rowTo['BNAME'] : $rowItem['TRANSFERTO'];
$status = 'In transit between library locations';
$available = false;