forked from DBCDK/ding_user
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathding_user.module
More file actions
1244 lines (1129 loc) · 39.4 KB
/
ding_user.module
File metadata and controls
1244 lines (1129 loc) · 39.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* @file
* Ding user handling module.
*/
/**
* Default seconds to cache user credentials before wiping them.
*/
define('DING_USER_DEFAULT_CREDS_LIFETIME', 900);
/**
* Implements hook_ctools_plugin_directory().
*
* It simply tells panels where to find the .inc files that define various
* args, contexts, content_types. In this case the subdirectories of
* ctools_plugin_example/panels are used.
*/
function ding_user_ctools_plugin_directory($owner, $plugin_type) {
return 'plugins/' . $plugin_type;
}
/**
* Implements hook_ctools_plugin_api().
*
* If you do this, CTools will pick up default panels pages
* in ding_user.pages_default.inc.
*/
function ding_user_ctools_plugin_api($module, $api) {
if ($module == 'page_manager' && $api == 'pages_default') {
return array('version' => 1);
}
}
/**
* Implements hook_menu().
*/
function ding_user_menu() {
$items = array();
$items['user/%user/authenticate'] = array(
'title' => 'Authenticate',
'page callback' => 'drupal_get_form',
'page arguments' => array('ding_user_authenticate_form'),
'access callback' => 'ding_user_access',
'access arguments' => array(1),
'file' => 'ding_user.pages.inc',
'type' => MENU_CALLBACK,
);
return $items;
}
/**
* Implements hook_menu_alter().
*/
function ding_user_menu_alter(&$items) {
// Hook in authentication handling to the regular user edit page.
// But don't if page_manager overrides it.
if (!module_exists('page_manager') || variable_get('page_manager_user_edit_disabled', TRUE)) {
if (isset($items['user/%user/edit']) && $items['user/%user/edit']['page callback'] == 'drupal_get_form') {
// @TODO: Are there any sites not running panels and will this work with
// profile2 ?
$items['user/%user/edit']['page callback'] = 'ding_provider_get_form';
}
}
$items['user/%user/view']['title'] = 'User profile';
$items['user/%user/edit']['title'] = 'Edit user profile';
if (!empty($items['user/%pm_arg/status'])) {
$items['user/%pm_arg/status']['title'] = 'User status';
}
}
/**
* Implements hook_page_manager_contexts_alter().
*
* This is actually a Panels everywhere hook. In future it may be renamed:
* hook_panels_everywhere_contexts_alter()
*
* Panels everywhere puts a extra form tag around the whole page on some pages.
* This is wrong because there already is a form tag which creates an illegal
* html markup with nested form tag.
*
* This happens because Panels Everwhere reuses code from panels. Because there
* exist a form in contexts the function function panels_render_display() puts
* an extra form around the code.
*
* The code unsets the form_id in panels everywhere module order to supress the
* superfluous form tag
*
* See Panels module: function panels_render_display().
*/
function ding_user_page_manager_contexts_alter(&$contexts, $placeholders) {
foreach ($contexts as $id => $context) {
if (!empty($context->form_id)) {
unset($context->form_id);
}
}
}
/**
* Implements hook_entity_info_alter().
*/
function ding_user_entity_info_alter(&$entity_info) {
$ding_entity_info = ding_entity_info('ding_entity');
// Entity might not be defined yet (is the case in the installer).
if (isset($entity_info[$ding_entity_info['entity_type']]['view modes'])) {
// Add a user_list display mode for addon modules to use.
$entity_info[$ding_entity_info['entity_type']]['view modes'] += array(
'user_list' => array(
'label' => t('User lists'),
'custom settings' => TRUE,
),
);
}
}
/**
* Access callback.
*
* Allows access if the account is the same as the logged in user.
*/
function ding_user_access($account) {
return ($GLOBALS['user']->uid == $account->uid) && $account->uid > 0;
}
/**
* Implements hook_cron().
*/
function ding_user_cron() {
// Clear out expired credentials.
cache_clear_all(NULL, 'cache_ding_user_credentials');
}
/**
* Implements hook_form_alter().
*
* Modify user login form to use our backend.
*/
function ding_user_form_alter(&$form, $form_state, $form_id) {
switch ($form_id) {
case 'user_login':
case 'user_login_block':
// Change input type on name field to password as the user may enter CPR.
$form['name']['#type'] = 'password';
// Make the name and password not required to by-pass error handling in
// default validation function. To prevent the "request new password"
// message.
$form['name']['#required'] = FALSE;
$form['pass']['#required'] = FALSE;
// Add our own validation handler, after the default Drupal login
// validator.
$pos = array_search('user_login_authenticate_validate', $form['#validate']);
if ($pos === FALSE) {
// Not found, insert as next to last.
$pos = count($form['#validate']) - 1;
}
else {
// After, not before.
$pos += 1;
}
array_splice($form['#validate'], $pos, 0, 'ding_user_user_login_validate');
// Falling through on purpose (if not reservation and login via ajax will
// fail.).
// Falling through on purpose.
case 'ding_user_authenticate_form':
if (isset($form_state['ajaxify'])) {
$form['actions']['submit']['#ajax'] = array(
'callback' => 'ding_user_authenticate_form_callback',
'wrapper' => drupal_html_id($form_id),
);
}
break;
}
}
/**
* Implements hook_form_FORM_ID_alter().
*
* For provider users, hide OG, Drupal password, and add in a pincode field
* (user_profile_form).
*/
function ding_user_form_user_profile_form_alter(&$form, &$form_state) {
if (ding_user_is_provider_user($form_state['user'])) {
// Don't show og group.
// @todo: shouldn't this be elsewhere?
$form['group_audience']['#access'] = FALSE;
// Don't show Drupal password. We don't use it.
$form['account']['current_pass']['#access'] = FALSE;
$form['account']['pass']['#access'] = FALSE;
// Add pincode change field. Defaults to 4 chars, as that seems the common
// option, providers may form_alter this.
$form['account']['pincode'] = array(
'#type' => 'password_confirm',
'#size' => 4,
'#maxlength' => 4,
'#process' => array(
'form_process_password_confirm',
// Not adding user_form_process_password_confirm here, as it only adds
// the strength checker, which we don't want.
'ding_user_form_process_password_confirm',
),
'#description' => t('To change the current pincode, enter the new pincode in both fields.'),
);
// Adjust description of mail field.
$form['account']['mail']['#description'] = t('The e-mail address is not made public and will only be used if you wish to receive certain news or notifications by e-mail.');
// Remove the validator requiring the current password to change email
// address.
$pos = array_search('user_validate_current_pass', $form['#validate']);
if ($pos !== FALSE) {
unset($form['#validate'][$pos]);
}
// In order to bypass the problem with unique email adresses we use our own
// validator.
// Find the $form['#validate'] entry for the default validator,
// and replace it with our validator. Based on the sharedemail module.
if (is_array($form['#validate'])) {
$key = array_search('user_account_form_validate', $form['#validate'], TRUE);
if ($key !== FALSE) {
$form['#validate'][$key] = 'ding_user_account_form_validate';
}
}
}
}
/**
* Taken from shared email module.
*
* To bypass the problem that a users email address must be unique
* we implement our own validator.
*
* Form validation handler for user_account_form().
*
* This function adds a prefix to the e-mail address before calling
* user_account_form_validate() to perform the default form validation,
* then restores the e-mail address.
*
* @param array $form
* The user form that was submitted.
* @param array $form_state
* The state of the form.
*
* @see user_account_form()
* @see user_account_form_validate()
*/
function ding_user_account_form_validate($form, &$form_state) {
// Test whether the e-mail address should be disguised.
$mail = ding_user_is_shared_email($form, $form_state);
if ($mail) {
$form_state['values']['mail'] = 'dingusermail_' . $mail;
}
// Call the User module's validate function.
user_account_form_validate($form, $form_state);
// Restore the actual e-mail address.
if ($mail) {
$form_state['values']['mail'] = $mail;
}
}
/**
* Taken from shared email module.
*
* Check whether the e-mail address should be disguised during validation.
*
* If the e-mail address is valid, check whether there are any other users
* with the same address. If there are, the address must be modified
* so that the User module's validation function will think it's unique.
*
* @param array $form
* The user form that was submitted.
* @param array $form_state
* The state of the form.
*
* @return string|bool
* Returns the e-mail address if it's a duplicate and is allowed.
* Otherwise nothing is returned.
*/
function ding_user_is_shared_email($form, &$form_state) {
$mail = trim($form_state['values']['mail']);
// If e-mail address is invalid, don't have to disguise it.
if (!user_validate_mail($mail)) {
// Get the UIDs of all other users who have this e-mail address.
$account = $form['#user'];
$existing = db_select('users')
->fields('users', array('uid'))
->condition('uid', $account->uid, '<>')
->condition('mail', db_like($mail), 'LIKE')
->execute()
->fetchCol();
if (count($existing) > 0) {
return $mail;
}
}
return FALSE;
}
/**
* Password confirm element process.
*
* Add in handling of #maxlength and change the titles of the fields.
*/
function ding_user_form_process_password_confirm($element) {
if (!empty($element['#maxlength'])) {
$element['pass1']['#maxlength'] = $element['pass2']['#maxlength'] = $element['#maxlength'];
// Unset #maxlength, or _form_validate will attempt to check the length of
// this element, whose value will be an array.
unset($element['#maxlength']);
}
// Fixup the titles.
$element['pass1']['#title'] = t('Pincode');
$element['pass2']['#title'] = t('Confirm pincode');
return $element;
}
/**
* Create the profile type for the given provider.
*
* This is a fallback in case the provider didn't create one.
*/
function ding_user_create_profile_type($provider) {
$provider_profile_type = 'provider_' . $provider['module'];
$profile_type = new ProfileType(array(
'type' => $provider_profile_type,
'label' => 'Provider profile for ' . $provider['title'],
'userCategory' => TRUE,
'userView' => TRUE,
));
$profile_type->save();
return $profile_type;
}
/**
* Get the provider profile for the given user.
*/
function ding_user_provider_profile($account) {
$profile_type = ding_user_get_provider_profile_type();
return profile2_load_by_user($account, $profile_type->type);
}
/**
* Implements hook_user_presave().
*
* Update provider with changes to email/pass.
*/
function ding_user_user_presave(&$edit, $account, $category) {
// If the changes originate from the provider we don't need to
// update them back to the provider.
if (isset($edit['from_provider']) && $edit['from_provider']) {
return;
}
// Ensure that we're dealing with a provider user.
if (empty($account->uid) || !ding_user_is_provider_user($account)) {
return;
}
// Do not presave during login phase.
if (!empty($account->ding_user_login_process)) {
unset($account->ding_user_login_process);
return;
}
$changes = array();
if (isset($edit['mail']) && $edit['mail'] != $account->mail) {
$changes['mail'] = $edit['mail'];
}
// If pincode is not empty, it's changed.
if (!empty($edit['pincode'])) {
$changes['pass'] = $edit['pincode'];
// Unset it, so it doesn't get saved.
unset($edit['pincode']);
}
if (!empty($changes)) {
try {
$update_res = ding_provider_invoke('user', 'account_update', $account, $changes);
if (!empty($update_res['creds'])) {
ding_user_save_creds($update_res);
}
}
catch (Exception $e) {
// If update_account fails, we're in trouble, as we're too far in to
// set form errors. So we'll just tell the user that it couldn't be, and
// not save the fields.
drupal_set_message(t("There was a problem communicating with library system. Please contact the site administrator."), 'error');
watchdog_exception('ding_user', $e);
if (isset($changes['mail'])) {
drupal_set_message(t("Email not saved."), 'error');
// Don't save a new email address.
unset($edit['mail']);
}
if (isset($changes['pass'])) {
drupal_set_message(t("New pincode not saved."), 'error');
// Pass was already unset.
}
}
}
}
/**
* Implements hook_user_logout().
*
* Lets user stays on page, after logout.
*/
function ding_user_user_logout($account) {
// Ensure the credentials is removed from cache.
cache_clear_all(session_name() . '-' . $account->uid, 'cache_ding_user_credentials');
// ... both HTTP and HTTPS.
cache_clear_all(substr(session_name(), 1) . '-' . $account->uid, 'cache_ding_user_credentials');
}
/**
* Implements hook_username_alter().
*
* Use display_name.
*/
function ding_user_username_alter(&$name, $account) {
if (isset($account->data)) {
if (is_string($account->data)) {
$data = unserialize($account->data);
}
else {
$data = $account->data;
}
if (!empty($data) && isset($data['display_name'])) {
$name = $data['display_name'];
}
}
}
/**
* Implements hook_ding_provider_user().
*/
function ding_user_ding_provider_user() {
return array(
'user' => array(
'required' => TRUE,
'install time setup' => TRUE,
),
);
}
/**
* Return the url to redirect user to in order to authenticate/log in.
*
* Used by ding_provider.
*/
function ding_user_auth_page() {
global $user;
if (user_is_logged_in()) {
return 'user/' . $user->uid . '/authenticate';
}
return 'user/login';
}
/**
* Return a local hash for the given name.
*
* As logins may be CPR numbers, which is really sensitive information, we use
* a hash of the name and the Drupal private key as authname.
*/
function ding_user_default_authname($name) {
// If another password.inc is in use, that doesn't define
// _password_base64_encode(), we'll fail horribly. We'll probably need to
// define our own base64 function, but we'll cross that bridge when we reach
// it.
require_once DRUPAL_ROOT . '/' . variable_get('password_inc', 'includes/password.inc');
// A sha512 is 64 bytes, which becomes 128 hexadecimal chars, which is
// exactly the size of the authname field in the database. So we ask hash
// for binary data and lets _password_base64_encode base64 encode it to 86
// characters, leaving enough room for our suffix.
$hash = hash('sha512', drupal_get_private_key() . $name, TRUE);
return _password_base64_encode($hash, drupal_strlen($hash)) . '@ding_user';
}
/**
* Custom validator for the login form.
*
* Handles authentication with provider, and setting up a profile2 for the
* user/provider.
*/
function ding_user_user_login_validate($form, &$form_state) {
// If $form_state['uid'] is set and has a true value, Drupal already found a
// user, so we don't bother. Also, we require name and pass.
if (isset($form_state['uid']) && $form_state['uid']) {
// Normal Drupal user have been logged in.
return;
}
try {
// Trying to login the user using the provider.
$auth_res = ding_provider_invoke('user', 'authenticate', $form_state['values']['name'], $form_state['values']['pass']);
if (!is_array($auth_res) || !isset($auth_res['success'])) {
watchdog('ding_user', 'Provider returned invalid result: @res', array('@res' => print_r($auth_res, TRUE)), WATCHDOG_DEBUG);
return;
}
if ($auth_res['success']) {
if (isset($auth_res['authname']) && !empty($auth_res['authname'])) {
// If provider supplied an authname, use it.
$auth_name = $auth_res['authname'];
}
else {
// Else use a standard authname.
$auth_name = ding_user_default_authname($form_state['values']['name']);
}
// Create new account in Drupal and if one exists update it.
$account = _ding_user_create_account($auth_name, $auth_res);
// Save credentials for later. Do it early as the provider might expect
// them in a hook_profile2_presave hook trigged by us saving a new
// profile, or themselves in the profile_init callback.
ding_user_save_creds($auth_res);
// Attempt to upgrade an existing anonymous consent storage to this user.
_ding_user_upgrade_anonymous_ecc_consent($account);
$profile = _ding_user_create_profile2($account);
// Set additional tabs in profile2.
_ding_user_profile2_tabs($account);
// Let provider initialise the profile. Assume they save it if need be.
if (ding_provider_implements('user', 'profile_init')) {
$profile = _ding_user_create_profile2($account);
ding_provider_invoke('user', 'profile_init', $profile, $auth_res);
}
// Log user in.
$form_state['uid'] = $account->uid;
// We're not calling user_login_submit like user_external_login_register
// does, it's already the submit handler.
// TODO: Do we still need this?
if (ding_provider_implements('user', 'authenticate_finalize')) {
ding_provider_invoke('user', 'authenticate_finalize', $account);
}
}
else {
// Check if any messages was returned from the provider.
if (isset($auth_res['messages'])) {
foreach ($auth_res['messages'] as $message) {
$type = 'warning';
if (is_array($message)) {
list($message, $type) = $message;
}
drupal_set_message(check_plain($message), $type);
}
}
// Check if name and pass where filled out. These fields are not required
// in the form to prevent the default form validation from displaying the
// reset password link, which would not make sens for provider users.
foreach (array('name', 'pass') as $field) {
if (empty($form_state['values'][$field])) {
form_set_error($field, t('!name field is required.', array('!name' => $form[$field]['#title'])));
}
}
// If we reach this code the login have failed and we always want to
// display this message.
form_set_error('name', t('Sorry, unrecognized username or password. Please contact your local library to request a new password. Contact information can be found on the <a href="@url">library</a> page.', array('@url' => url('biblioteker'))));
// Obfuscate the user name. We just set the form value to the obfuscated
// version as user.module will log the failure with the name from the
// form. If the provider defines its own authnames, this wont match the
// username that the user would have, but we can't expect the provider
// to supply it for invalid logins.
form_set_value($form['name'], ding_user_default_authname($form_state['values']['name']), $form_state);
}
}
catch (Exception $exception) {
if ($exception instanceof DingProviderUserException) {
// Rethrow user exceptions.
throw $exception;
}
elseif ($exception instanceof DingProviderAuthException) {
// Redirect to auth page
if (module_exists('ding_user') && ($authpage = ding_user_auth_page())) {
drupal_set_message(t('Sorry, unrecognized username or password. Please contact your local library to request a new password. Contact information can be found on the <a href="@url">library</a> page.', array('@url' => url('biblioteker'))), 'error');
}
}
if (arg(0) != 'ding_provider_error') {
watchdog('ding_provider', 'Uncaught exception in ding_provider_invoke_page: @message', array('@message' => $exception->getMessage()), WATCHDOG_ERROR);
// Redirect to error page.
drupal_goto('ding_provider_error');
}
else {
// Exception thrown, log error and carry on.
watchdog_exception('ding_user', $exception);
}
}
}
/**
* Attempt to upgrade any anonymous consent from this device.
*/
function _ding_user_upgrade_anonymous_ecc_consent($account) {
$cookie_name = eu_cookie_compliance_get_settings()['cookie_name'] . '-cid';
if (isset($_COOKIE[$cookie_name])) {
$cid = $_COOKIE[$cookie_name];
// Upgrade the consent. Use try-catch as we do not in any case wanna cause
// issues during provider login process.
try {
db_update('eu_cookie_compliance_basic_consent')
->fields(['uid' => $account->uid])
->condition('cid', $cid)
->execute();
watchdog('ding_user', 'Attempted consent storage upgrade for cid: %cid to provider user uid: %uid', [
'%cid' => $cid,
'%uid' => $account->uid,
]);
// Remove our cid-cookie again.
setcookie($cookie_name, "", 1, '/');
}
catch (Exception $e) {
watchdog_exception('ding_user', $e);
}
}
}
/**
* Create a provider account for drupal.
*
* The username will be a hash value of authname. This account will be coupled
* with the provider user via the authmap table.
*
* @param string $auth_name
* Name used to authenticate the user.
* @param array $auth_res
* Authentication information from the provider.
*
* @return entity
* Drupal user object.
*/
function _ding_user_create_account($auth_name, $auth_res) {
// We'd like to use user_external_login_register(), but it saves the user
// and invokes hook_user_login before we have a chance to mess with it. So
// we do what it would do.
$account = user_external_load($auth_name);
if (!$account) {
// Register this new user.
$fields = array(
// Name is only 60 chars, and authname is longer. Use a shorter SHA1
// hash.
'name' => hash('sha1', $auth_name),
'pass' => user_password(),
'init' => $auth_name,
'status' => 1,
'access' => REQUEST_TIME,
'mail' => '',
);
if (isset($auth_res['user'])) {
$fields['mail'] = $auth_res['user']['mail'];
$fields['data'] = array(
'display_name' => $auth_res['user']['data']['display_name'],
'blocked' => $auth_res['user']['blocked'],
);
}
// Set provider role.
$roles = user_roles(TRUE);
$rid = array_search('provider', $roles);
$fields['roles'] = array(
DRUPAL_AUTHENTICATED_RID => 'authenticated user',
$rid => 'provider',
);
$account = user_save('', $fields);
// Terminate if an error occurred during user_save().
if (!$account) {
watchdog('ding_user', "User account could not be created for: %name.", array('%name' => $auth_res['user']['data']['display_name']), WATCHDOG_ERROR);
drupal_set_message(t("Error saving user account."), 'error');
return NULL;
}
user_set_authmaps($account, array("authname_ding_user" => $auth_name));
}
else {
// Update display name and mail address as they may have been change in the
// library system.
$edit = array();
$edit['mail'] = $auth_res['user']['mail'];
$edit['data'] = array(
'display_name' => $auth_res['user']['data']['display_name'],
'blocked' => $auth_res['user']['blocked'],
);
user_save($account, $edit);
}
// Save credentials for the session.
ding_user_save_creds($auth_res);
return $account;
}
/**
* Implements hook_profile2_access().
*
* @TODO; is this correct. Should permissions be set in admin ?
* is it enough to check for provider_user ?
*/
function ding_user_profile2_access($op, $profile = NULL, $account = NULL) {
if (empty($profile)) {
return FALSE;
}
elseif (ding_user_is_provider_user($profile)) {
return TRUE;
}
return FALSE;
}
/**
* Implements hook_user_profile_tabs().
*
* Get profile2 definitions ('type_name', $form ).
* create a profile2 if it doesn't exist.
* load the profile
* Bind profile to user.
*/
function _ding_user_profile2_tabs($account) {
// Load profiles by invoking hook_user_profile2_tab.
$profile_tabs = module_invoke_all('user_profile2_tabs');
foreach ($profile_tabs as $profile_tab) {
$profile_type = profile2_get_types($profile_tab->type);
// Special case - profile_type has not yet been created.
if (!$profile_type) {
$profile_type = new ProfileType(array(
'type' => $profile_tab->type,
'label' => $profile_tab->label,
'userCategory' => TRUE,
'userView' => TRUE,
));
$profile_type->save();
}
// Normal case: get the profile type.
// Create a profile for current user.
$profile = new Profile(array(
'user' => $account,
'type' => $profile_type,
));
// Bind profile to user.
$profile->save();
}
}
/**
* Implements hook_form_FORM_ID_alter().
*
* Add pin-code fields to the provider profile(s), so the users can change their
* library pin-code.
*/
function ding_user_form_profile2_form_alter(&$form, &$form_state) {
global $user;
if (ding_user_is_provider_user($user)) {
// Check that it's the provider profile we are looking at.
$profile_type = ding_user_get_provider_profile_type();
if ($form_state['profile2']->type == $profile_type->type) {
// Add pin-code change field.
$maxlength = ding_user_get_pincode_length();
$form['pass'] = array(
'#type' => 'fieldset',
'#title' => t('Change pincode'),
);
$form['pass']['pincode'] = array(
'#type' => 'password_confirm',
'#size' => $maxlength,
'#maxlength' => $maxlength,
'#process' => array(
'form_process_password_confirm',
// Not adding user_form_process_password_confirm here, as it only adds
// the strength checker, which we don't want.
'ding_user_form_process_password_confirm',
),
'#description' => t('To change the current pincode, enter the new pincode in both fields.'),
);
// Add submit handler to change the pin-code as it's not part of the
// profile fields.
$form['#submit'][] = 'ding_user_profile_update_submit';
}
}
$fee_sms = variable_get('ding_user_fee_sms', t('Notice that there is a fee for receiving a SMS'));
$form['ding_user_fee_sms'] = array(
'#type' => 'item',
'#markup' => $fee_sms,
'#weight' => 0,
);
}
/**
* Updates the users pin-code as part of the profile update.
*
* It's done in this submit function as the pin-code is not part of provider
* profile and this ensures that it never in any way get stored in the DB.
*
* Furthermore the pin-code fields are injected into the profile form in the
* form alter above as there is not password field available, that would not
* store it in the database.
*/
function ding_user_profile_update_submit(&$form, &$form_state) {
$pincode = isset($form_state['values']['pincode']) ? $form_state['values']['pincode'] : '';
// If pin-code is not empty, it's changed.
if (!empty($pincode)) {
global $user;
try {
$update_res = ding_provider_invoke('user', 'update_pincode', $user, $pincode);
if (!empty($update_res['creds'])) {
// Updated drupal credentials.
ding_user_save_creds($update_res);
}
}
catch (Exception $exception) {
// If update_account fails, we're in trouble, as we're too far in to
// set form errors. So we'll just tell the user that it couldn't be, and
// not save the fields.
drupal_set_message(t("There was a problem communicating with library system. Please contact the site administrator."), 'error');
watchdog_exception('ding_user', $exception);
drupal_set_message(t("New pincode not saved."), 'error');
}
}
}
/**
* Helper for creating external user.
*
* @param object $account
* User account to be binded.
*
* @return array|bool|mixed|\Profile
* Returns user profile.
*/
function _ding_user_create_profile2($account) {
$profile = ding_user_provider_profile($account);
if (!$profile) {
// Load profile2 type.
$profile_type = ding_user_get_provider_profile_type();
// Create a profile for current user.
$profile = new Profile(array(
'user' => $account,
'type' => $profile_type,
));
// Bind this profile to the user.
$profile->save();
}
return $profile;
}
/**
* Implements hook_forms().
*
* Enables the profile2 form panels pane to generate a form for a profile2
* entity. The code is largely taken from the profile2 page module, but we only
* need this part of the module.
*/
function ding_user_forms($form_id, $args) {
// For efficiency, only act if the third argument is 'profile2'.
if (isset($args[2]) && is_string($args[2]) && $args[2] == 'profile2') {
// Reuse profile2 page extension code.
include_once drupal_get_path('module', 'profile2') . '/contrib/profile2_page.inc';
$info = entity_get_info('profile2');
// Translate bundle form ids to the base form id 'profile2_form'.
$forms = array();
foreach ($info['bundles'] as $bundle => $bundle_info) {
$forms['profile2_edit_' . $bundle . '_form']['callback'] = 'profile2_form';
$forms['profile2_edit_' . $bundle . '_form']['wrapper callback'] = 'entity_ui_form_defaults';
}
return $forms;
}
}
/**
* Ajax command to authenticate. Used by ding_provider.
*/
function ajax_command_ding_user_authenticate($extra_data) {
global $user, $language;
// @todo add support for user/login here.
module_load_include('inc', 'ding_user', 'ding_user.pages');
if ($user->uid) {
$title = t('Authenticate');
$form_id = 'ding_user_authenticate_form';
}
else {
$title = t('Type your credentials');
$form_id = 'user_login';
}
// Change default ajax action to default login form's if https is enabled.
if (variable_get('https', FALSE)) {
$form = drupal_get_form('user_login');
$url = parse_url($_SERVER['HTTP_REFERER']);
$path_start = strpos($_SERVER['HTTP_REFERER'], '/', drupal_strlen($url['scheme']) + 3);
$referer = drupal_substr($_SERVER['HTTP_REFERER'], $path_start + 1);
// Filter out any language prefixes as it will be automatically added to the
// URL again.
if (!empty($language->language) && preg_match('/' . $language->prefix . '/', $referer) > 0) {
$referer = preg_replace('/' . $language->prefix . '\//', '', $referer);
}
$form['#action'] = 'https://' . $_SERVER['SERVER_NAME'] . url('user/login') . '?destination=' . $referer;
}
else {
$form_state = array(
'ajaxify' => TRUE,
);
$form = drupal_build_form($form_id, $form_state);
}
$login_form = drupal_render($form);
return ajax_command_ding_popup('ding_user', $title, $login_form, array('resubmit' => TRUE, 'extra_data' => $extra_data));
}
/**
* Ajax callback.
*/
function ding_user_authenticate_form_callback($form, &$form_state) {
switch ($form['form_id']['#value']) {
case 'ding_user_authenticate_form':
$success = $form_state['authentication_success'];
break;
case 'user_login':
$success = !empty($form_state['uid']);
break;
}
$response = array(
'#type' => 'ajax',
'#commands' => array(),
);
if ($success) {
// Close dialog if successful.
$response['#commands'][] = ajax_command_ding_popup_close('ding_user');
// Allow other modules to modify the command set.
//drupal_alter('artesis_ajax_commands', $response['#commands']);
}
else {
// Else redisplay form and messages.
$html = theme('status_messages') . drupal_render($form);
$response['#commands'][] = ajax_command_ding_popup('ding_user', t('Authenticate'), $html);
}
return $response;
}
/**
* Retrieves the users credentials from the current session.
*
* @param object $user
* A user object. The the current logged in user will be used if non is given.
*
* @return array
* Array with the user credentials.
*
* @throws DingProviderAuthException
* Throws DingProviderAuthException if not authenticated.
*/
function ding_user_get_creds($user = NULL) {
if (is_null($user)) {
global $user;
}
if (isset($_SESSION['ding_user'])) {
// User has not timed out by auto logout module so return credentials.
return $_SESSION['ding_user']['creds'];
}
throw new DingProviderAuthException();
}
/**
* Get a unique id from the provider.
*
* @param object $account
* User account to get id for. Defaults to NULL which then results in the
* currently logged in user.