/
_ldap.plugin.php
1408 lines (1224 loc) · 53.9 KB
/
_ldap.plugin.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
/**
* This file implements the LDAP authentification plugin.
*
* This file is part of the b2evolution project - {@link http://b2evolution.net/}.
*
* Documentation can be found at {@link http://plugins.b2evolution.net/ldap-plugin}.
*
* @copyright (c)2003-2015 by Francois PLANQUE - {@link http://fplanque.net/}
* Parts of this file are copyright (c)2004-2007 by Daniel HAHLER - {@link http://thequod.de/contact}.
*
* @license http://b2evolution.net/about/license.html GNU General Public License (GPL)
*
* {@internal Open Source relicensing agreement:
* Daniel HAHLER grants Francois PLANQUE the right to license
* Daniel HAHLER's contributions to this file and the b2evolution project
* under any OSI approved OSS license (http://www.opensource.org/licenses/).
* }}
*
* @package plugins
*/
if( !defined('EVO_MAIN_INIT') ) die( 'Please, do not access this page directly.' );
/**
* LDAP authentification plugin.
*
* It handles the event 'LoginAttempt' and tries to bind to one or several LDAP servers with
* the login and password of the user who is trying to login.
*
* If successfully bound, the plugin will query for additional info about the user.
*
* - A b2evolution user will be created with a random password that will never be told to the user.
* This forces the user to always use a valid LDAP account for subsequent connections.
* @todo don't show option to change passwords to LDAP users
* - User account info will be updated at each login. A new random password will also be regenerated (just in case)
*
* @todo Register tools tab to search in LDAP (blueyed).
* @todo Add setting subsets, which allow to map User object properties (dropdown) to LDAP search result entries (what's now hardcoded with "sn", "givenname" and "email")
*
* @package plugins
*/
class ldap_plugin extends Plugin
{
var $version = '6.8.8';
var $group = 'authentication';
var $code = 'evo_ldap_auth';
var $priority = 50;
var $author = 'b2evolution Group (original plugin by Daniel Hahler)';
/**
* Init
*/
function PluginInit( & $params )
{
$this->name = T_('LDAP authentication');
$this->short_desc = T_('Creates users if they could be authenticated through LDAP.');
}
/**
* Define some dependencies.
*
* @see Plugin::GetDependencies()
* @return array
*/
function GetDependencies()
{
return array(
'requires' => array(
'app_min' => '6.6.6-stable',
),
'recommends' => array(
'app_min' => '6.7.0-alpha',
),
);
}
function GetDefaultSettings( & $params )
{
global $Settings, $app_version;
return array(
'fallback_grp_ID' => array(
'label' => T_('Default primary group'),
'type' => 'select_group',
'note' => T_('The primary group to use for new users (can be overriden by LDAP attributes below). Select "No Group" to prevent creating new users without specifc LDAP Attributes.' ),
'allow_none' => true,
'defaultvalue' => isset($Settings) ? $Settings->get('newusers_grp_ID') : NULL,
),
'search_sets' => array(
'label' => T_('LDAP servers to check'),
'note' => T_('This plugin can search a username sequentially on several different LDAP servers / with different LDAP queries.'),
'type' => version_compare( $app_version, '6.6.5', '>' ) ? 'array:array:string' : 'array',
'max_count' => 10,
'entries_label' => T_('Server'),
'entries' => array(
'disabled' => array(
'label' => T_('Disabled'),
'defaultvalue' => 0,
'type' => 'checkbox',
'note' => T_('Check to disable this LDAP server.'),
),
'server' => array(
'label' => T_('LDAP Server'),
'note' => T_('Hostname with or without port').' '.sprintf( T_('E.g. «%s»'), 'ldap.example.com:389' ),
'size' => 30,
),
'protocol_version' => array(
'label' => $this->T_('LDAP protocol version'),
'type' => 'select',
'options' => array(
'auto' => $this->T_('automatic'),
'v3' => $this->T_('Version 3'),
'v2' => $this->T_('Version 2')
),
'note' => $this->T_('A specific protocol version, or "auto" for "current one, then 3 and 2".'),
),
'encoding' => array(
'label' => T_('Data encoding'),
'note' => sprintf( T_('Data encoding of the LDAP server if it is not UTF-8. E.g. %s'), 'ISO-8859-1, UTF-16, KOI8-R, CP1250.' ),
'size' => 10,
),
'rdn' => array(
'label' => T_('RDN for binding/authenticating'),
'note' => T_('The LDAP RDN, used to bind to the server (%s gets replaced by the user login).').' '.sprintf( T_('E.g. «%s»'), 'cn=%s,ou=Users,o=Organisation' ),
'size' => 40,
),
'base_dn' => array(
'label' => T_('User Details - Base DN'),
'note' => T_('The LDAP base DN, used as base DN to search for detailed user info after binding.').' '.sprintf( T_('E.g. «%s»'), 'ou=Users,o=Organisation' ),
'size' => 40,
),
'search_filter' => array(
'label' => T_('User Details - Search filter'),
'note' => T_('The search filter used to get information about the user (%s gets replaced by the user login).').' '.sprintf( T_('E.g. «%s»'), 'uid=%s' ),
'size' => 40,
),
'expand_pics' => array(
'label' => T_('Expand profile pictures to a square'),
'note' => T_('This will add white margins to the pictures'),
'type' => 'checkbox',
),
'assign_user_to_group_by' => array(
'label' => T_('Assign primary group by'),
'note' => T_('LDAP search result key to assign the group by.').' '.sprintf( T_('E.g. «%s»'), 'department' ),
'size' => 30,
),
'tpl_new_grp_ID' => array(
'label' => T_('Template for new primary groups'),
'type' => 'select_group',
'note' => T_('The group to use as template, if we create a new group. Set this to "No Group" in order not to create any new groups.'),
'allow_none' => true,
),
'secondary_grp_base_dn' => array(
'label' => T_('Secondary Groups - Base DN'),
'note' => T_('The LDAP base DN, used as base DN to search for secondary groups.').' '.sprintf( T_('E.g. «%s»'), 'ou=Groups,o=Organisation' ),
'size' => 40,
),
'secondary_grp_search_filter' => array(
'label' => T_('Secondary Groups - Search filter'),
'note' => T_('The search filter used to get the list of groups we are interested in (filter at will) (%s gets replaced by the user login).').' '.sprintf( T_('E.g. «%s»'), 'objectClass=groupofuniquenames' ),
'size' => 60,
),
'secondary_grp_name_attribute' => array(
'label' => T_('Secondary Groups - Name Attribute'),
'note' => T_('Attribute to be used as teh group name.').' '.sprintf( T_('E.g. «cn»'), 'cn' ),
'size' => 10,
),
'secondary_grp_name_prefix' => array(
'label' => T_('Secondary Groups - Name Prefix'),
'note' => T_('Only groups with this prefix will be considered.').' '.sprintf( T_('E.g. «cms_»'), '' ),
'size' => 10,
),
'tpl_new_secondary_grp_ID' => array(
'label' => T_('Template for new secondary groups'),
'type' => 'select_group',
'note' => T_('The group to use as template, if we create a new group. Set this to "No Group" in order not to create any new groups.'),
'allow_none' => true,
),
),
),
);
}
/**
* Define here default user settings
*
* @return array
*/
function GetDefaultUserSettings( & $params )
{
return array(
// It is a hidden setting, Used only to remember what number of ldap settings worked on last user logging action:
'search_set_num' => array(
'label' => '', // keep empty to hide on used edit advanced form
'defaultvalue' => 0, // use first settings by default
'type' => 'string'
),
);
}
/**
* Event handler: called when a user attemps to login.
*
* This function will check if the user exists in the LDAP directory and create it locally if it does not.
*
* @param array 'login', 'pass' and 'pass_md5'
*/
function LoginAttempt( & $params )
{
global $localtimenow;
global $Settings, $Hit, $evo_charset;
// Check if LDAP is available:
if( !function_exists( 'ldap_connect' ) )
{
$this->debug_log( 'This PHP installation does not support LDAP functions.' );
return false; // Login failed!
}
// Get ready to go through ALL LDAP Servers configured in the plugin:
$search_sets = $this->Settings->get( 'search_sets' );
if( empty($search_sets) )
{
$this->debug_log( 'No LDAP servers have been configured in the LDAP plugin settings.' );
return false; // Login failed!
}
// Detect if we already have a local user with the same login:
$UserCache = & get_Cache( 'UserCache' );
if( $local_User = & $UserCache->get_by_login( $params['login'] ) )
{
$this->debug_log( 'User <b>'.$params['login'].'</b> already exists locally. We will UPDATE it with the latest LDAP attibutes.' );
$update_mode = true;
// Try to find a number of a search set which was used on successful logging previous time by current user:
$user_search_set_num = intval( $this->UserSettings->get( 'search_set_num', $local_User->ID ) );
if( $user_search_set_num > 0 && isset( $search_sets[ $user_search_set_num ] ) )
{ // We have found this, Reorder the array to use the successful set firstly:
$success_search_set = $search_sets[ $user_search_set_num ];
unset( $search_sets[ $user_search_set_num ] );
$search_sets = array( $user_search_set_num => $success_search_set ) + $search_sets;
}
}
else
$update_mode = false;
$this->debug_log( sprintf('LDAP plugin will attempt to login with login=<b>%s</b> / pass=<b>%s</b> / MD5 pass=<b>%s</b>', $params['login'], $params['pass'], $params['pass_md5']) );
// ------ Loop through list of configured LDAP Servers: ------
foreach( $search_sets as $l_id => $l_set )
{
$this->debug_log( 'Step 1 : STARTING LDAP AUTH WITH SERVER #'.$l_id );
// --- CONNECT TO SERVER ---
$server_port = explode(':', $l_set['server']);
$server = $server_port[0];
$port = isset($server_port[1]) ? $server_port[1] : 389;
if( ! empty($l_set['disabled']) )
{
$this->debug_log( 'Skipping disabled LDAP server «'.$server.':'.$port.'»!' );
continue;
}
if( !($ldap_conn = @ldap_connect( $server, $port )) )
{
$this->debug_log( 'Could not connect to LDAP server «'.$server.':'.$port.'»!' );
continue;
}
$this->debug_log( 'Connected to server «'.$server.':'.$port.'»..' );
$ldap_rdn = str_replace( '%s', $params['login'], $l_set['rdn'] );
$this->debug_log( 'Using RDN «'.$ldap_rdn.'» for binding...' );
// --- SET PROTOCOL VERSION ---
// Get protocol version to use:
if( ! ldap_get_option($ldap_conn, LDAP_OPT_PROTOCOL_VERSION, $initial_protocol_version) )
{
$this->debug_log( 'Failed to get LDAP_OPT_PROTOCOL_VERSION.' );
$initial_protocol_version = null;
}
$protocol_version = isset($l_set['protocol_version']) ? $l_set['protocol_version'] : 'auto'; // new setting in 2.01
if( $protocol_version[0] == 'v' )
{ // transform "vX" => "X"
$try_versions = array( substr($protocol_version, 1) );
}
else
{ // "auto"
$try_versions = array(3, 2);
if( isset($initial_protocol_version) )
{
array_unshift($try_versions, $initial_protocol_version);
}
$try_versions = array_unique($try_versions);
}
$this->debug_log( 'We will try protocol versions: '.implode(', ', $try_versions) );
// --- VERIFY USER CREDENTIALS BY BINDING TO SERVER ---
// you might use this for testing with Apache DS: if( !@ldap_bind($ldap_conn, 'uid=admin,ou=system', 'secret') )
// Bind:
$bound = false;
$bind_errors = array();
foreach( $try_versions as $try_version )
{
$this->debug_log( sprintf('Trying to connect with protocol version: %s / RDN: %s / pass: %s', $try_version, $ldap_rdn, $params['pass'] ) );
ldap_set_option($ldap_conn, LDAP_OPT_PROTOCOL_VERSION, $try_version);
if( @ldap_bind($ldap_conn, $ldap_rdn, $params['pass']) )
{ // Success
$this->debug_log( 'Binding worked.' );
$bound = true;
break;
}
else
{
$this->debug_log( 'Binding failed. Errno: '.ldap_errno($ldap_conn).' Error: '.ldap_error($ldap_conn) );
}
}
if( ! $bound )
{
if( isset($initial_protocol_version) )
{ // Reset this for the next search set:
ldap_set_option($ldap_conn, LDAP_OPT_PROTOCOL_VERSION, $initial_protocol_version);
}
continue;
}
$this->debug_log( 'User successfully bound to server.' );
// --- STEP 2 : TRY TO OBTAIN MORE INFO ABOUT USER ---
// Search user info
$filter = str_replace( '%s', $params['login'], $l_set['search_filter'] );
$this->debug_log( sprintf( 'Step 2 : Now querying for additional user info. base_dn: <b>%s</b>, filter: <b>%s</b>', $l_set['base_dn'], $filter ) );
$search_result = @ldap_search( $ldap_conn, $l_set['base_dn'], $filter );
if( ! $search_result )
{ // this may happen with an empty base_dn
$this->debug_log( 'Invalid ldap_search result. Skipping to next search set. Errno: '.ldap_errno($ldap_conn).' Error: '.ldap_error($ldap_conn) );
continue;
}
$search_info = ldap_get_entries($ldap_conn, $search_result);
//$this->debug_log( 'Results returned by LDAP Server: <pre>'.var_export( $search_info, true ).'</pre>' );
if( $search_info['count'] != 1 )
{ // We have found 0 or more than 1 users, which is a problem...
$this->debug_log( '# of entries found with search: '.$search_info['count'].' - Skipping...' );
/*
for ($i=0; $i<$search_info["count"]; $i++) {
echo "dn: ". $search_info[$i]["dn"] ."<br>";
echo "first cn entry: ". $search_info[$i]["cn"][0] ."<br>";
echo "first email entry: ". $search_info[$i]["mail"][0] ."<p>";
}
*/
continue;
}
$this->debug_log( 'User info has been found.' );
// --- CREATE OR UPDATE USER ACCOUNT IN B2EVO ---
if( $update_mode == false )
{
$this->debug_log( 'Step 3 : Creating a local user in b2evolution...' );
$local_User = new User();
$local_User->set( 'login', $params['login'] );
$local_User->set( 'locale', locale_from_httpaccept() ); // use the browser's locale
$local_User->set_datecreated( $localtimenow );
// $local_User->set( 'level', 1 );
}
else
{ // User exists already exists
$this->debug_log( 'Step 3 : Updating the existing local user.' );
}
$this->debug_log( 'Randomize password in b2evolution DB and autoactivate user.' );
// Generate a random password (we never want LDAP users to be able to login without a prior LDAP check) (also on update, just in case...
$local_User->set_password( generate_random_passwd( 32 ) ); // $params['pass'] );
$local_User->set( 'status', 'autoactivated' ); // Activate the user automatically (no email activation necessary)
if( ! empty( $l_set['encoding'] ) )
{ // Convert each input string to current server encoding:
$exclude_encoding_fields = array( 'uid', 'mail', 'jpegphoto' );
if( isset( $search_info[0] ) && is_array( $search_info[0] ) )
{
foreach( $search_info[0] as $search_info_key => $search_info_data )
{
if( isset( $search_info_data[0] ) && is_string( $search_info_data[0] ) &&
! in_array( $search_info_key, $exclude_encoding_fields ) )
{ // Convert string from LDAP server encoding to current server encoding:
$search_info[0][ $search_info_key ][0] = convert_charset( $search_info_data[0], $l_set['encoding'], $evo_charset );
}
}
}
}
// Make some updates:
// mail -> email:
if( isset($search_info[0]['mail'][0]))
{
$local_User->set_email( $search_info[0]['mail'][0] );
}
// uid -> nickname
if( isset($search_info[0]['uid'][0]))
{
$this->debug_log( 'UID: <b>'.$search_info[0]['uid'][0].'</b>' );
$local_User->set( 'nickname', $search_info[0]['uid'][0] );
}
else
{ // if not found, use login.
$local_User->set( 'nickname', $params['login'] );
}
// givenname -> Firstname:
if( isset($search_info[0]['givenname'][0]))
{
$this->debug_log( 'First name (givenname): <b>'.$search_info[0]['givenname'][0].'</b>' );
$local_User->set( 'firstname', $search_info[0]['givenname'][0] );
}
// sn -> Lastname:
if( isset($search_info[0]['sn'][0]))
{
$this->debug_log( 'Last name (sn): <b>'.$search_info[0]['sn'][0].'</b>' );
$local_User->set( 'lastname', $search_info[0]['sn'][0] );
}
// roomnumber -> user field "roomnumber" (if not found, autocreate it in group "Address")
if( isset($search_info[0]['roomnumber'][0]))
{
$this->debug_log( 'Room number: <b>'.$search_info[0]['roomnumber'][0].'</b>' );
$this->userfield_update_by_code( $local_User, 'roomnumber', $search_info[0]['roomnumber'][0], 'Address', 'Room Number', 'word' );
}
// businesscategory -> user field "businesscategory" (if not found, autocreate it in group "About me")
if( isset($search_info[0]['businesscategory'][0]))
{
$this->debug_log( 'Business Category: <b>'.$search_info[0]['businesscategory'][0].'</b>' );
$this->userfield_update_by_code( $local_User, 'businesscategory', $search_info[0]['businesscategory'][0], 'About me', 'Business Category', 'text' );
}
// telephonenumber -> user field "officephone" (if not found, autocreate it in group "Phone")
if( isset($search_info[0]['telephonenumber'][0]))
{
$this->debug_log( 'Office phone: <b>'.$search_info[0]['telephonenumber'][0].'</b>' );
$this->userfield_update_by_code( $local_User, 'officephone', $search_info[0]['telephonenumber'][0], 'Phone', 'Office phone', 'phone' );
}
// mobile -> user field "cellphone" (if not found, autocreate it in group "Phone")
if( isset($search_info[0]['mobile'][0]))
{
$this->debug_log( 'Cell phone: <b>'.$search_info[0]['mobile'][0].'</b>' );
$this->userfield_update_by_code( $local_User, 'cellphone', $search_info[0]['mobile'][0], 'Phone', 'Cell phone', 'phone' );
}
// employeenumber -> user field "employeenumber" (if not found, autocreate it in group "About me")
if( isset($search_info[0]['employeenumber'][0]))
{
$this->debug_log( 'Employee number: <b>'.$search_info[0]['employeenumber'][0].'</b>' );
$this->userfield_update_by_code( $local_User, 'employeenumber', $search_info[0]['employeenumber'][0], 'About me', 'Employee number', 'word' );
}
// title -> user field "title" (if not found, autocreate it in group "About me")
if( isset($search_info[0]['title'][0]))
{
$this->debug_log( 'Title: <b>'.$search_info[0]['title'][0].'</b>' );
$this->userfield_update_by_code( $local_User, 'title', $search_info[0]['title'][0], 'About me', 'Title', 'word' );
$userfield_title = $search_info[0]['title'][0]; // Use this as role for all organizations below
}
else
{
$userfield_title = '';
}
// departmentnumber -> join Organization with the same name (create if doesn't exist)
if( isset($search_info[0]['departmentnumber'][0]))
{
$this->debug_log( 'Department Number: <b>'.$search_info[0]['departmentnumber'][0].'</b>' );
$this->userorg_update_by_name( $local_User, $search_info[0]['departmentnumber'][0], $userfield_title );
}
// o -> join Organization with the same name (create if doesn't exist)
if( isset($search_info[0]['o'][0]))
{
$this->debug_log( 'Organization: <b>'.$search_info[0]['o'][0].'</b>' );
$this->userorg_update_by_name( $local_User, $search_info[0]['o'][0], $userfield_title );
}
// telexnumber -> user field "officefax" (if not found, autocreate it in group "Phone")
if( isset($search_info[0]['telexnumber'][0]))
{
$this->debug_log( 'Office FAX: <b>'.$search_info[0]['telexnumber'][0].'</b>' );
$this->userfield_update_by_code( $local_User, 'officefax', $search_info[0]['telexnumber'][0], 'Phone', 'Office FAX', 'phone' );
}
// ---- GROUP STUFF ----
if( $update_mode == true )
{ // Updating existing user
$this->debug_log( 'Updating existing user: we do NOT touch the primary group.' );
$local_User->dbupdate();
$this->debug_log( 'OK -- User has been updated.' );
}
else
{
// Try to assign prilary group from the search results:
$assigned_group = false;
if( ! empty($l_set['assign_user_to_group_by']) )
{
$this->debug_log( 'Plugin is configured to assign the Primary Group by the '.$l_set['assign_user_to_group_by'].' key...' );
if( isset($search_info[0][$l_set['assign_user_to_group_by']])
&& isset($search_info[0][$l_set['assign_user_to_group_by']][0]) )
{ // There is info we want to assign by
$assign_by_value = $search_info[0][$l_set['assign_user_to_group_by']][0];
$this->debug_log( 'User info says has '.$l_set['assign_user_to_group_by'].' = "<b>'.$assign_by_value.'</b>"' );
$GroupCache = & get_Cache( 'GroupCache' );
if( $users_Group = & $GroupCache->get_by_name( $assign_by_value, false ) )
{ // A group with the users value returned exists.
$local_User->set_Group( $users_Group );
$assigned_group = true;
$this->debug_log( 'Assigning User to existing Primary Group.' );
}
else
{
$this->debug_log( 'Group with that name does not exist...' );
if( $new_Group = & $this->usergroup_create( $l_set['tpl_new_grp_ID'], $assign_by_value ) )
{ // Link the user to new created group:
$local_User->set_Group( $new_Group );
$assigned_group = true;
$this->debug_log( 'Assigned User to new Primary Group.' );
}
}
}
}
if( ! $assigned_group )
{ // Default group:
$this->debug_log( 'Falling back to default primary group...' );
$users_Group = NULL;
$fallback_grp_ID = $this->Settings->get( 'fallback_grp_ID' );
if( empty($fallback_grp_ID) )
{
$this->debug_log( 'No default/fallback primary group configured.' );
$this->debug_log( 'User NOT created, try next LDAP server...' );
//Continue to next LDAP server:
continue;
}
else
{
$GroupCache = & get_Cache( 'GroupCache' );
$users_Group = & $GroupCache->get_by_ID($fallback_grp_ID);
if( $users_Group )
{ // either $this->default_group_name is not given or wrong
$local_User->set_Group( $users_Group );
$assigned_group = true;
$this->debug_log( 'Using default/fallback primary group: <b>'.$users_Group->get('name').'</b>' );
}
else
{
$this->debug_log( 'Default/fallback primary group does not exist ('.$fallback_grp_ID.').' );
$this->debug_log( 'User NOT created, try next LDAP server...' );
//Continue to next LDAP server:
continue;
}
}
}
$local_User->dbinsert();
$UserCache->add( $local_User );
$this->debug_log( 'OK -- User has been created.' );
}
// Remember this settings number in order use this first in next logging time by current user:
$this->UserSettings->set( 'search_set_num', $l_id, $local_User->ID );
$this->UserSettings->dbupdate();
// Assign user to organizations:
$this->userorg_assign_to_user( $local_User );
// jpegphoto -> Save as profile pictue "ldap.jpeg" and associate with user
if( isset($search_info[0]['jpegphoto'][0]))
{
$this->debug_log( 'Photo: <img src="data:image/jpeg;base64,'.base64_encode($search_info[0]['jpegphoto'][0]).'" />' );
// Save to disk and attach to user:
$this->userimg_attach_photo( $local_User, $search_info[0]['jpegphoto'][0], ! empty( $l_set['expand_pics'] ) );
}
// --- EXTRA GROUPS ---
if( !empty( $l_set['secondary_grp_search_filter'] ) )
{
global $app_version;
if( evo_version_compare( $app_version, '6.7.0-alpha' ) < 0 )
{ // The plugin is used on b2evo 6.6
$this->debug_log( 'Secondary groups not handled. This feature requires b2evolution v6.7.0-alpha or newer.' );
}
elseif( empty($l_set['secondary_grp_name_attribute']) )
{
$this->debug_log( 'Missing name attribute for secondary groups' );
}
else
{
$filter = str_replace( '%s', $params['login'], $l_set['secondary_grp_search_filter'] );
$grp_name_attribute = $l_set['secondary_grp_name_attribute'];
$this->debug_log( sprintf( 'Step 4 : Now querying for secondary groups. base_dn: <b>%s</b>, filter: <b>%s</b>, name attribue=<b>%s</b>', $l_set['secondary_grp_base_dn'], $filter, $grp_name_attribute ) );
$search_result = @ldap_search( $ldap_conn, $l_set['secondary_grp_base_dn'], $filter, array($grp_name_attribute) );
if( ! $search_result )
{ // this may happen with an empty base_dn
$this->debug_log( 'Invalid ldap_search result. No secondary groups will be assigned. Errno: '.ldap_errno($ldap_conn).' Error: '.ldap_error($ldap_conn) );
}
else
{
$search_info = ldap_get_entries($ldap_conn, $search_result);
// $this->debug_log( 'Results returned by LDAP Server: <pre>'.var_export( $search_info, true ).'</pre>' );
$secondary_groups = array();
// $this->debug_log( 'Secondary groups name prefix: <pre>'.var_export( $l_set['secondary_grp_name_prefix'], true ).'</pre>' );
// Walk through results:
foreach( $search_info as $group_candidate )
{
if( is_array( $group_candidate ) && isset($group_candidate[$grp_name_attribute][0]) )
{
$group_candidate_cn = $group_candidate[$grp_name_attribute][0];
if( empty($l_set['secondary_grp_name_prefix']) || strpos($group_candidate_cn, $l_set['secondary_grp_name_prefix']) === 0 )
{ // prefix is ok
$this->debug_log( 'Accepted Secondary Group: '.$group_candidate_cn );
$secondary_groups[] = $group_candidate_cn;
}
else
{ // prefix is NOT ok
$this->debug_log( 'REJECTED Secondary Group: '.$group_candidate_cn );
}
}
}
// Hardcode two secondary groups:
// $secondary_groups = array( 'Blog B members', 'Blog D Members' );
$this->debug_log( 'Secondary groups to be assigned: <pre>'.var_export( $secondary_groups, true ).'</pre>' );
// Update secondary groups for the User:
$this->usersecgroup_update( $local_User, $secondary_groups, $l_set['tpl_new_secondary_grp_ID'] );
}
}
}
if( isset($initial_protocol_version) )
{
ldap_set_option($ldap_conn, LDAP_OPT_PROTOCOL_VERSION, $initial_protocol_version);
}
// --- CONSIDER THE LOGIN ATTEMPT TO BE SUCCESSFUL AND WE ACCEPT IT ---
// Update this value which has been passed by REFERENCE:
$params['pass_ok'] = true;
return true; // Login was a success (but return "true" does not trigger anything special in b2evolution)
}
if( isset($initial_protocol_version) )
{
ldap_set_option($ldap_conn, LDAP_OPT_PROTOCOL_VERSION, $initial_protocol_version);
}
return false; // Login failed!
}
/**
* We need the RAW password to bind to LDAP servers.
* @return true
*/
function LoginAttemptNeedsRawPassword()
{
return true;
}
/**
* Add new or Update an exsisting user field by code
*
* @param object User
* @param string Field code
* @param string Field value
* @param string Field group name
* @param string Field name
* @param string Field type: 'text', 'word', 'email', 'number', 'phone', 'url'
*/
function userfield_update_by_code( & $User, $field_code, $field_value, $field_group_name, $field_name, $field_type )
{
$field_value = utf8_trim( $field_value );
if( empty( $field_value ) )
{ // Don't add an user field with empty value:
return;
}
// Get user field ID by code:
$field_ID = $this->userfield_get_by_code( $field_code, $field_group_name, $field_name, $field_type );
if( ! $field_ID )
{ // Some error on creating new user field, We cannot update this field:
// Exit here:
$this->debug_log( sprintf( 'Skip an updating of user field "%s" because new field cannot be created.', $field_name ) );
return;
}
// Load all user fields:
$User->userfields_load();
// What to do with the field depending on field type and new value:
// 'add', 'update', 'nothing'
$field_action = 'add';
if( ! empty( $User->userfields_by_code[ $field_code ] ) && is_array( $User->userfields_by_code[ $field_code ] ) )
{ // This user field is already defined for the user
$userfield = $User->userfields[ $User->userfields_by_code[ $field_code ][0] ];
if( $userfield->ufdf_duplicated == 'forbidden' )
{ // This field cannot has multiple values, Update it to new value:
$field_action = 'update';
$field_ID = $userfield->uf_ID;
}
else
{ // Multiple values field
$userfield_values = array();
foreach( $User->userfields_by_code[ $field_code ] as $userfield_ID )
{
$userfield_values[] = $User->userfields[ $userfield_ID ]->uf_varchar;
}
if( in_array( $field_value, $userfield_values ) )
{ // User already has this field with the same action, Don't add a duplicate:
$field_action = 'nothing';
}
}
}
switch( $field_action )
{
case 'add':
// Add new user field to the user it is not defined yet:
$User->userfield_add( $field_ID, $field_value );
$this->debug_log( sprintf( 'Add new user field "%s"', $field_code ) );
break;
case 'update':
// Update user field of the user to new value:
$User->userfield_update( $field_ID, $field_value );
$this->debug_log( sprintf( 'Update user field "%s" to new value', $field_code ) );
break;
}
}
/**
* Get user field group ID by name AND Try to create new if it doesn't exist yet
*
* @param string Field code
* @param string Field group name
* @param string Field name
* @param string Field type: 'text', 'word', 'email', 'number', 'phone', 'url'
* @return integer Field ID
*/
function userfield_get_by_code( $field_code, $field_group_name, $field_name, $field_type )
{
if( is_null( $this->userfields ) )
{ // Load all user fields in cache on first time request:
global $DB;
$SQL = new SQL();
$SQL->SELECT( 'ufdf_ID, ufdf_code' );
$SQL->FROM( 'T_users__fielddefs' );
$this->userfields = $DB->get_assoc( $SQL->get(), 'Load all user fields in cache array of LDAP plugin' );
// Convert all user field codes to lowercase:
$this->userfields = array_map( 'utf8_strtolower', $this->userfields );
}
// Code MUST be lowercase ASCII only:
$field_code = utf8_strtolower( $field_code );
// Check if requested user field code already exists in DB:
$field_ID = array_search( $field_code, $this->userfields );
if( $field_ID === false )
{ // No user field in DB, Try to create new:
$field_group_ID = $this->userfield_get_group_by_name( $field_group_name );
if( ! $field_group_ID )
{ // Some error on creating new user field group, We cannot create new user field without group:
// Exit here:
$this->debug_log( sprintf( 'Skip a creating of new user field "%s" because new group "%s" cannot be created.', $field_name, $field_group_name ) );
return;
}
// Load Userfield class:
load_class( 'users/model/_userfield.class.php', 'Userfield' );
$Userfield = new Userfield();
$Userfield->set( 'code', $field_code );
$Userfield->set( 'ufgp_ID', $field_group_ID );
$Userfield->set( 'name', $field_name );
$Userfield->set( 'type', $field_type );
$Userfield->set( 'order', $Userfield->get_last_order( $field_group_ID ) );
$Userfield->set( 'duplicated', 'forbidden' );
if( $Userfield->dbinsert() )
{ // New user field has been created
$field_ID = $Userfield->ID;
// Add new user field code in cache array:
$this->userfields[ $field_ID ] = $field_code;
$this->debug_log( sprintf( 'New user field "%s" has been created in system', $field_name ) );
}
}
return $field_ID;
}
/**
* Get user field group ID by name AND Try to create new if it doesn't exist yet
*
* @param string Field group name
* @return integer Field group ID
*/
function userfield_get_group_by_name( $field_group_name )
{
if( is_null( $this->userfield_groups ) )
{ // Load all user field groups in cache on first time request:
global $DB;
$SQL = new SQL();
$SQL->SELECT( 'ufgp_ID, ufgp_name' );
$SQL->FROM( 'T_users__fieldgroups' );
$this->userfield_groups = $DB->get_assoc( $SQL->get(), 'Load all user field groups in cache array of LDAP plugin' );
// Convert all user field group names to lowercase:
$this->userfield_groups = array_map( 'utf8_strtolower', $this->userfield_groups );
}
// Check if requested user field group already exists in DB:
$field_group_ID = array_search( utf8_strtolower( $field_group_name ), $this->userfield_groups );
if( $field_group_ID === false )
{ // No user field group in DB, Try to create new:
// Load UserfieldGroup class:
load_class( 'users/model/_userfieldgroup.class.php', 'UserfieldGroup' );
$UserfieldGroup = new UserfieldGroup();
$UserfieldGroup->set( 'name', $field_group_name );
$UserfieldGroup->set( 'order', 0 );
if( $UserfieldGroup->dbinsert() )
{ // New user field group has been created
$field_group_ID = $UserfieldGroup->ID;
// Add new user field group in cache array:
$this->userfield_groups[ $field_group_ID ] = utf8_strtolower( $field_group_name );
$this->debug_log( sprintf( 'New user field group "%s" has been created in system', $field_group_name ) );
}
}
return $field_group_ID;
}
/**
* Assign user to organization AND Try to create new organization if it doesn't exist yet
*
* @param object User
* @param string Organization name
* @param string Organization role
*/
function userorg_update_by_name( & $User, $org_name, $org_role = '' )
{
$org_name = utf8_trim( $org_name );
if( empty( $org_name ) )
{ // Don't update an user organization with empty name:
return;
}
if( is_null( $this->userorgs ) )
{ // Initialize array to keep what organizations should be assigned to the user:
$this->userorgs = array();
}
// Get organization ID by name AND save it in array to update after user insertion:
$org_ID = $this->userorg_get_by_name( $org_name );
$this->userorgs[ $org_ID ] = $org_role;
}
/**
* Get organization ID by name AND Try to create new if it doesn't exist yet
*
* @param string Organization name
* @return integer Organization ID
*/
function userorg_get_by_name( $org_name )
{
global $app_version;
if( is_null( $this->organizations ) )
{ // Load all user field groups in cache on first time request:
global $DB;
$SQL = new SQL();
$SQL->SELECT( 'org_ID, org_name' );
$SQL->FROM( 'T_users__organization' );
$this->organizations = $DB->get_assoc( $SQL->get(), 'Load all organizations in cache array of LDAP plugin' );
// Convert all organization names to lowercase and normalize them:
foreach( $this->organizations as $organization_ID => $organization_name )
{
$this->organizations[ $organization_ID ] = utf8_strtolower( $this->normalize( $organization_name ) );
}
}
// Check if requested organization already exists in DB:
$org_ID = array_search( utf8_strtolower( $this->normalize( $org_name ) ), $this->organizations );
if( $org_ID === false )
{ // No organization in DB, Try to create new:
// Load Organization class:
load_class( 'users/model/_organization.class.php', 'Organization' );
$Organization = new Organization();
if( evo_version_compare( $app_version, '6.7.0-alpha' ) >= 0 )
{ // The plugin is used on b2evo 6.7+
$Organization->set( 'owner_user_ID', '1' );
}
$Organization->set( 'name', $org_name );
if( $Organization->dbinsert() )
{ // New organization has been created
$org_ID = $Organization->ID;
// Add new organization in cache array:
$this->organizations[ $org_ID ] = utf8_strtolower( $this->normalize( $org_name ) );
$this->debug_log( sprintf( 'New organization "%s" has been created in system', $org_name ) );
}
}
return $org_ID;
}
/**
* Assign user to organizations
*
* @param object User
*/
function userorg_assign_to_user( & $User )
{
if( empty( $User->ID ) || empty( $this->userorgs ) )
{ // User must be created and organizations should be added
return;
}
// Get current user organization to don't lose them:
$curr_orgs = $User->get_organizations_data();
$orgs = array();
foreach( $curr_orgs as $curr_org_ID => $curr_org )
{ // Keep current organizations:
$orgs[ $curr_org_ID ] = $curr_org['role'];
}
foreach( $this->userorgs as $org_ID => $org_role )
{ // Update current organizations with new:
// NOTE: Role will be updated to new value ONLY when organization is NOT accepted yet because of perm restriction
$orgs[ $org_ID ] = $org_role;
}
$org_IDs = array();
$org_roles = array();
foreach( $orgs as $org_ID => $org_role )
{ // Initialize arrays to update the organizations:
$org_IDs[] = $org_ID;
$org_roles[] = $org_role;
}