-
Notifications
You must be signed in to change notification settings - Fork 0
/
fbs.module
675 lines (609 loc) · 19.2 KB
/
fbs.module
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
<?php
/**
* @file
* FBS provider module.
*/
include_once 'fbs.features.inc';
// Load Field module hooks. Wrapping in function exists, so we'll still be
// able to load this file in tests.
if (function_exists('module_load_include')) {
module_load_include('inc', 'fbs', 'fbs.field');
}
/**
* Implements hook_init().
*
* Register autoloader for our (non-Drupal) classes.
*/
function fbs_init()
{
require_once dirname(__FILE__) . "/vendor/autoload.php";
}
/**
* Implements hook_ding_provider().
*/
function fbs_ding_provider()
{
$path = drupal_get_path('module', 'fbs');
return array(
'title' => 'FBS provider',
'settings' => 'fbs_settings_form',
'provides' => array(
'availability' => array(
'prefix' => 'availability',
'file' => $path . '/includes/fbs.availability.inc',
),
'debt' => array(
'prefix' => 'debt',
'file' => $path . '/includes/fbs.debt.inc',
),
'loan' => array(
'prefix' => 'loan',
'file' => $path . '/includes/fbs.loan.inc',
),
'reservation' => array(
'prefix' => 'reservation',
'file' => $path . '/includes/fbs.reservation.inc',
),
'user' => array(
'prefix' => 'user',
'file' => $path . '/includes/fbs.user.inc',
),
'wayf' => array(
'prefix' => 'wayf',
'file' => $path . '/includes/fbs.wayf.inc',
),
),
);
}
/**
* Get info for patron.
*
* Wrapper around ding_user_get_creds() to facilitate testing.
*
* @param object|null $account
* User to get patron info about. Uses current user if not supplied.
*
* @return array
* Patron info.
*/
function fbs_get_patron_info($account = NULL)
{
global $user;
if (!$account) {
$account = $user;
}
// If set on user, use those. This should only be the case in tests.
if (isset($account->creds)) {
return $account->creds;
}
$creds = ding_user_get_creds($user);
return $creds;
}
/**
* Return patron id for user.
*
* @param object|null $account
* User to get patron id for. Optional, defaults to current user.
*
* @return string|null
* Patron id or NULL if not found.
*/
function fbs_patron_id($account = NULL)
{
$patron_info = fbs_get_patron_info($account);
return isset($patron_info['patronId']) ? $patron_info['patronId'] : NULL;
}
/**
* Get the service object.
*
* Parameters is for injecting in tests. Don't use.
*
* @param string|null $agency_id
* Local agency id. Defaults to fbs_agency variable.
* @param string|null $endpoint
* Url of service endpoint. Defalts to fbs_endpoint variable.
* @param Reload\Prancer\HttpClient|null $client
* HTTP client to use. Defaults to new instance of FBSFakeHttpClient if
* endpoint matches "localtest".
* @param Reload\Prancer\Serializer|null $serializer
* Serializer to use.
* @param bool $reset
* Don't use cache but return a new instance.
*
* @return FBS
* Service class.
*/
function fbs_service($agency_id = NULL, $endpoint = NULL, $client = NULL, $serializer = NULL, $reset = FALSE)
{
// No drupal_static. We want to be callable from tests.
static $service;
if (!$service || $reset) {
$agency_id = !is_null($agency_id) ? $agency_id : variable_get('fbs_agency', '');
$endpoint = !is_null($endpoint) ? $endpoint : variable_get('fbs_endpoint', '');
if ($endpoint && preg_match('{localtest}', $endpoint)) {
$client = new FBSFakeHttpClient();
}
// Ensure exactly one trailing slash.
$endpoint = rtrim($endpoint, '/') . '/';
$service = new FBS($agency_id, $endpoint, $client, $serializer);
}
return $service;
}
/**
* Provider settings form.
*/
function fbs_settings_form()
{
$form = array();
$form['fbs'] = array(
'#type' => 'fieldset',
'#title' => t('FBS service settings'),
'#tree' => FALSE,
);
$form['fbs']['fbs_endpoint'] = array(
'#type' => 'textfield',
'#title' => t('FBS endpoint URL'),
'#description' => t('The URL for the FBS REST service, usually something like https://et.cicero-fbs.com/rest'),
'#required' => TRUE,
'#default_value' => variable_get('fbs_endpoint', ''),
);
$form['fbs']['fbs_agency'] = array(
'#type' => 'textfield',
'#title' => t('ISIL'),
'#description' => t('ISIL code of the library, for example DK-810015.'),
'#default_value' => variable_get('fbs_agency', ''),
);
$form['fbs']['fbs_username'] = array(
'#type' => 'textfield',
'#title' => t('Username'),
'#description' => t('Username for FBS.'),
'#default_value' => variable_get('fbs_username', ''),
);
$form['fbs']['fbs_password'] = array(
'#type' => 'textfield',
'#title' => t('Password'),
'#description' => t('Password for FBS.'),
'#default_value' => variable_get('fbs_password', ''),
);
$form['fbs']['fbs_master_password'] = array(
'#type' => 'textfield',
'#title' => t('Master Password'),
'#description' => t('Master Password for FBS. This will allow you to login as another user'),
'#default_value' => variable_get('fbs_master_password', ''),
);
// Add the option to select default interest period, which default as default
// to 180 days.
$periods = fbs_interest_periods();
$default = variable_get('fbs_default_interest_period', 180);
$form['fbs'] += ding_reservation_interest_period_selector('create', 'fbs_default_interest_period', variable_get('fbs_default_interest_period', 180), fbs_interest_periods());
$form['fbs']['fbs_enable_reservation_deletion'] = array(
'#type' => 'checkbox',
'#title' => t('Enable reservation deletion'),
'#default_value' => variable_get('fbs_enable_reservation_deletion', FALSE),
'#description' => t('Allow users to delete their reservations as well as ready for pickup ones.'),
);
$form['fbs']['fbs_search_departments'] = array(
'#type' => 'textarea',
'#default_value' => variable_get('fbs_search_departments', ''),
'#title' => t('departments you can search in'),
'#attributes' => array(
'placeholder' => t('eksempel: voksen|ocv med 1 pr. linje'),
),
'#description' => t(''),
);
$form['fbs']['fbs_nonreserveable_collections'] = array(
'#type' => 'textarea',
'#default_value' => variable_get('fbs_nonreserveable_collections', ''),
'#title' => t('nonreserveable collectionms'),
'#attributes' => array(
'placeholder' => t(''),
),
'#description' => t(''),
);
$form['fbs']['fbs_nonhome_locations'] = array(
'#type' => 'textarea',
'#default_value' => variable_get('fbs_nonhome_locations', ''),
'#title' => t('nonhome locations'),
'#attributes' => array(
'placeholder' => t(''),
),
'#description' => t(''),
);
$form['fbs']['fbs_nonreserveable_locations'] = array(
'#type' => 'textarea',
'#default_value' => variable_get('fbs_nonreserveable_locations', ''),
'#title' => t('non reserveable locations'),
'#attributes' => array(
'placeholder' => t(''),
),
'#description' => t(''),
);
$form['fbs']['fbs_nonhome_departments'] = array(
'#type' => 'textarea',
'#default_value' => variable_get('fbs_nonhome_departments', ''),
'#title' => t('nonhome departments'),
'#attributes' => array(
'placeholder' => t(''),
),
'#description' => t(''),
);
$form['fbs']['fbs_nonhome_material_groups'] = array(
'#type' => 'textarea',
'#default_value' => variable_get('fbs_nonhome_material_groups', ''),
'#title' => t('nonhome material groups'),
'#attributes' => array(
'placeholder' => t(''),
),
'#description' => t(''),
);
$form['fbs']['fbs_search_departments'] = array(
'#type' => 'textarea',
'#default_value' => variable_get('fbs_search_departments', ''),
'#title' => t('departments for advanced search field.'),
'#attributes' => array(
'placeholder' => t('eksempel: voksen|ocv med 1 pr. linje'),
),
'#description' => t(''),
);
$form['fbs']['fbs_exclude_branches'] = array(
'#type' => 'textarea',
'#default_value' => variable_get('fbs_exclude_branches', ''),
'#title' => t('exclude library branches'),
'#attributes' => array(
'placeholder' => t('eksempel: DK-746103 med 1 pr. linje'),
),
'#description' => t(''),
);
$form['fbs']['fbs_exclude_from_view'] = array(
'#type' => 'textarea',
'#default_value' => variable_get('fbs_exclude_from_view', ''),
'#title' => t('exclude library branches from view'),
'#attributes' => array(
'placeholder' => t('eksempel: DK-746103 med 1 pr. linje'),
),
'#description' => t(''),
);
return system_settings_form($form);
}
/**
* Submit function. Trim values.
*/
function fbs_settings_form_submit($form, &$form_state)
{
foreach ($form_state['values'] as $name => $value) {
$form_state['values'][$name] = trim($value);
}
system_settings_form_submit($form, $form_state);
}
/**
* Implements hook_profile2_presave().
*/
function fbs_profile2_presave($entity)
{
global $user;
if ($entity->type != 'provider_fbs') {
return;
}
if (isset($entity->is_new) && $entity->is_new) {
// Profile is being created, return.
return;
}
if ($entity->uid != $user->uid) {
// Profile is not the current user's. We can't get the existing values, so
// we wont try to update.
return;
}
$patron = ding_user_get_creds($user);
$wrapper = entity_metadata_wrapper('profile2', $entity);
$current_on_hold = array();
$current_on_hold = $wrapper->field_fbs_on_hold->value();
if (!$current_on_hold) {
$current_on_hold = array('from' => '', 'to' => '');
}
$current = array(
'phoneNumber' => $wrapper->field_fbs_phone->value(),
'emailAddress' => $wrapper->field_fbs_mail->value(),
'receiveSms' => (bool) isset($wrapper->field_fbs_phone_notification) ? $wrapper->field_fbs_phone_notification->value() : false,
'receiveEmail' => (bool) $wrapper->field_fbs_mail_notification->value(),
'preferredPickupBranch' => $wrapper->field_fbs_preferred_branch->value(),
);
if ($patron['on_hold']) {
$existing_on_hold = $patron['on_hold'];
} else {
$existing_on_hold = array('from' => '', 'to' => '');
}
$existing = array(
'phoneNumber' => $patron['phone'],
'emailAddress' => $patron['mail'],
'receiveSms' => (bool) $patron['phone_notification'],
'receiveEmail' => (bool) $patron['mail_notification'],
'preferredPickupBranch' => $patron['preferred_branch'],
'onHold' => $patron['on_hold'],
);
if (array_diff_assoc($current, $existing) || array_diff_assoc($current_on_hold, $existing_on_hold)) {
// Update
$update = new FBS\Model\UpdatePatronRequest();
// Settings
$patron_settings = new FBS\Model\PatronSettings();
// Phone
if (isset($current['phoneNumber']) && $current['phoneNumber'] != "") {
$phone = new FBS\Model\PhoneNumber();
$phone->phoneNumber = $current['phoneNumber'];
$phone->receiveNotification = $current['receiveSms'];
$patron_settings->phoneNumbers[0] = $phone;
}
// E-mail
if (isset($current['emailAddress']) && $current['emailAddress'] != "") {
$email = new FBS\Model\EmailAddresses();
$email->emailAddress = $current['emailAddress'];
$email->receiveNotification = $current['receiveEmail'];
$patron_settings->emailAddresses[0] = $email;
}
// PickUp
$patron_settings->preferredPickupBranch = $current['preferredPickupBranch'];
// On Hold
$period = new FBS\Model\Period();
$period->from = $current_on_hold['from'];
$period->to = $current_on_hold['to'];
$patron_settings->onHold = $period;
// Sets patron settings on update variable
$update->patron = $patron_settings;
// updates user in FBS
fbs_service()->Patron->update(fbs_service()->agencyId, $patron['patronId'], $update);
// updates user in Drupal
$details = fbs_service()->Patron->details(fbs_service()->agencyId, $patron['patronId']);
$result['creds'] = _fbs_patron_info($details->patron);
global $user;
ding_user_save_creds($result, $user);
}
}
/**
* Update preferred branch if it is not set.
*
* @param object $account
* User to update preferred branch on.
* @param string $branch_id
* Branch id to update to.
*/
function fbs_update_preferred_branch($account, $branch_id)
{
global $user;
// Only update when it's for the current user.
if ($account->uid != $user->uid) {
return;
}
$profile = ding_user_provider_profile($account);
//$wrapper = entity_metadata_wrapper('profile2', $profile);
if ($profile->field_fbs_preferred_branch['und'][0]['value'] == "") {
$profile->field_fbs_preferred_branch['und'][0]['value'] = $branch_id;
$profile->save();
}
}
/**
* Get library branches.
*
* @return array
* Array of ISIL => branchname.
*/
function fbs_branches()
{
$branches = &drupal_static(__FUNCTION__);
if (!isset($branches)) {
if ($cached = cache_get('branches', 'cache')) {
$branches = $cached->data;
}
}
if (is_null($branches)) {
$res = fbs_service()->Placement->getBranches(fbs_service()->agencyId);
$exclude_branches = explode(PHP_EOL, variable_get('fbs_exclude_branches', ''));
foreach ($res as $branch) {
$exclude = false;
foreach ($exclude_branches as $ex_branch_id) {
$tmp = $branch->branchId;
if (strcmp(trim($tmp), trim($ex_branch_id)) == 0) {
$exclude = true;
break;
}
}
if (!$exclude) {
$branches[$branch->branchId] = $branch->title;
}
}
asort($branches);
cache_set('branches', $branches, $bin = 'cache', $expire = CACHE_TEMPORARY);
}
return $branches;
}
/**
* Get interest periods.
*
* @return array
* Array of days => human readable string.
*/
function fbs_interest_periods()
{
$periods = array(
1 => 30,
2 => 60,
3 => 90,
6 => 180,
12 => 360,
);
$options = array();
foreach ($periods as $months => $days) {
$options[$days] = format_plural($months, '1 month', '@count months');
}
return $options;
}
/**
* Implements hook_form_FORM_ID_form_alter().
*
* Remove order_nr from the reservation listing. We don't have anything sane to
* display there.
*/
function fbs_form_ding_reservation_reservations_form_alter(&$form, &$form_state)
{
if (isset($form['reservations'])) {
foreach ($form['reservations'] as &$reservation) {
if (isset($reservation['#information']['order_nr'])) {
unset($reservation['#information']['order_nr']);
}
}
}
}
/**
* Implements hook_form_FORM_ID_alter().
*
* Access options for the attributes in the holdings field.
*/
function fbs_form_ding_availability_admin_settings_form_alter(&$form, &$form_state, $form_id)
{
$form['holdings'] = array(
'#type' => 'fieldset',
'#title' => t('Holdings levels display'),
'#description' => t('Configure holdings display modes.'),
);
$form['holdings']['fbs_show_material_group'] = array(
'#type' => 'checkbox',
'#title' => t('Show material group description'),
'#default_value' => variable_get('fbs_show_material_group', 0),
);
$form['holdings']['fbs_holdings_suffix_type'] = array(
'#type' => 'radios',
'#title' => t('Holdings suffix'),
'#description' => t('Select which type of suffix to use for holdings. Simple shows a mix between DK5 and inverted creator, while Shelf mark simulates the shelf mark from ALMA using marc-data from the well.'),
'#default_value' => variable_get('fbs_holdings_suffix_type', 'simple'),
'#options' => array(
'simple' => t('Simple'),
'shelf_mark' => t('Shelf mark'),
),
);
}
/**
* Pack patron info in an array.
*
* Saves all the data we'll need for profile editing into an array that can be
* serialized in ding_user creds.
*
* @param FBS\Model\Patron $patron
* Patron data to save.
*
* @return array
* Data to save.
*/
function _fbs_patron_info(FBS\Model\Patron $patron)
{
$creds = array(
'patronId' => $patron->patronId,
'name' => $patron->name,
'phone' => $patron->phoneNumber,
'mail' => $patron->emailAddress,
'phone_notification' => $patron->receiveSms,
'mail_notification' => $patron->receiveEmail,
'preferred_branch' => $patron->preferredPickupBranch,
'resident' => $patron->resident,
'on_hold' => NULL,
'address' => NULL,
);
if ($patron->onHold) {
$creds['on_hold'] = array(
'from' => $patron->onHold->from,
'to' => $patron->onHold->to,
);
}
if ($patron->address) {
$creds['address'] = array(
'street' => $patron->address->street,
'city' => $patron->address->city,
'postal' => $patron->address->postalCode,
'country' => $patron->address->country,
);
}
return $creds;
}
/**
* Return a reversible local_id for a periodical.
*
* Ding wants an unique id for a periodical. We don't have that, so we pack the
* record id and periodical information together in a pseudo id.
*
* @param string $record_id
* Id of the ting object.
* @param FBS\Model\Periodical $periodical
* The Periodical instance.
*
* @return string
* The pseudo id.
*/
function _fbs_periodical_get_local_id($record_id, FBS\Model\Periodical $periodical)
{
// We're using - as a placeholder for empty values, it ensures that there'll
// be something between the colons, which in turn means we don't have to
// deal with the possibility of two colons in a row.
$parts = array(
!empty($periodical->volume) ? $periodical->volume : '-',
!empty($periodical->volumeYear) ? $periodical->volumeYear : '-',
!empty($periodical->volumeNumber) ? $periodical->volumeNumber : '-',
$record_id,
);
$parts = array_map(function ($part) {
// "Escape" the colons, so we can split on ":" later.
return strtr($part, array(':' => '::'));
}, $parts);
return 'fbs-' . implode(':', $parts);
}
/**
* Parse local_id into record and periodical.
*
* Parse the pseudo id created by _fbs_periodical_get_local_id() into a record
* id and periodical.
*
* @param string $local_id
* The pseudo id.
*
* @return array
* Array of record_id and PeriodicalReservation.
*/
function _fbs_periodical_parse_local_id($local_id)
{
$periodical = NULL;
if (preg_match('/^fbs-(.*)$/', $local_id, $matches)) {
// This is a zero-width negative lookbehind assertion ("(?<!:)") and a
// zero-width negative lookahead assertion ("(?!:)") that checks that the
// colon in the middle doesn't have a colon in front or behind it. The
// "zero-width" means that the preceding/following char is not part of the
// matched string. That's why "[^:]:[^:]" wont do, it'll match the
// non-colon char, which means preg_split will shave chars off the strings
// we want.
$parts = preg_split('/(?<!:):(?!:)/', $matches[1]);
// Replace '-' with NULL and reverse the "escaping" of colon.
$parts = array_map(function ($part) {
return $part === '-' ? NULL : strtr($part, array('::' => ':'));
}, $parts);
}
$periodical = new FBS\Model\PeriodicalReservation();
list(
$periodical->volume,
$periodical->volumeYear,
$periodical->volumeNumber,
$record_id
) = $parts;
return array($record_id, $periodical);
}
/**
* Static cache for WAYF logins.
*
* Not pretty, but due to the way that ding_wayf is implemented, this is what we
* need.
*/
function _fbs_wayf_login($name, $value = NULL)
{
$logins = &drupal_static(__FUNCTION__, array());
if ($value) {
$logins['name'] = $value;
}
if (isset($logins['name'])) {
return $logins['name'];
}
return NULL;
}