php IncludeModuleLangFil __FILE__ class CLDAP var arFields arGroupList

  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
<?php
IncludeModuleLangFile(__FILE__);
class CLDAP
{
var $arFields, $arGroupList = false;
var $conn;
protected static $PHOTO_ATTRIBS = array("thumbnailPhoto", "jpegPhoto");
function Connect($arFields = Array())
{
if(!is_object($this))
{
$ldap = new CLDAP();
$ldap->arFields = $arFields;
if($ldap->Connect())
return $ldap;
return false;
}
if($this->conn = @ldap_connect($this->arFields["SERVER"], $this->arFields['PORT']))
{
@ldap_set_option($this->conn, LDAP_OPT_PROTOCOL_VERSION, 3);
@ldap_set_option($this->conn, LDAP_OPT_REFERRALS, 0);
@ldap_set_option($this->conn, LDAP_OPT_SIZELIMIT, COption::GetOptionInt("ldap", "group_limit", 0));
@ldap_set_option($this->conn, LDAP_OPT_TIMELIMIT, 100);
@ldap_set_option($this->conn, LDAP_OPT_TIMEOUT, 5);
@ldap_set_option($this->conn, LDAP_OPT_NETWORK_TIMEOUT, 5);
if(@ldap_bind($this->conn))
return true;
}
return false;
}
function BindAdmin()
{
if(strlen($this->arFields["ADMIN_LOGIN"])<=0)
return false;
$r = @ldap_bind($this->conn,
(isset($this->arFields["~ADMIN_LOGIN"])?$this->arFields["~ADMIN_LOGIN"]:$this->arFields["ADMIN_LOGIN"]),
(isset($this->arFields["~ADMIN_PASSWORD"])?$this->arFields["~ADMIN_PASSWORD"]:$this->arFields["ADMIN_PASSWORD"])
);
return $r;
}
function Bind($login, $password)
{
if($this->arFields["CONVERT_UTF8"]=="Y")
{
$login = $GLOBALS["APPLICATION"]->ConvertCharset($login, SITE_CHARSET, "utf-8");
$password = $GLOBALS["APPLICATION"]->ConvertCharset($password, SITE_CHARSET, "utf-8");
}
$r = @ldap_bind($this->conn, $login, $password);
return $r;
}
function Disconnect()
{
ldap_close($this->conn);
}
function RootDSE()
{
$values = $this->_RootDSE('namingcontexts');
if ($values == false)
$values = $this->_RootDSE('namingContexts');
return $this->WorkAttr($values);
}
function _RootDSE($filtr)
{
$sr = ldap_read($this->conn, '', 'objectClass=*', Array($filtr), 0);
//$sr = ldap_read($this->conn, '', 'objectClass=*');
$entry = ldap_first_entry($this->conn, $sr);
$attributes = ldap_get_attributes($this->conn, $entry);
$values = false;
if ($attributes['count'] > 0)
$values = @ldap_get_values_len($this->conn, $entry, $filtr);
return $values;
}
function WorkAttr($values)
{
if(is_array($values) && $values['count']==1)
{
if($this->arFields["CONVERT_UTF8"]=="Y")
return $GLOBALS["APPLICATION"]->ConvertCharset($values[0], "utf-8", SITE_CHARSET);
return $values[0];
}
unset($values['count']);
if($this->arFields["CONVERT_UTF8"]=="Y")
foreach($values as $key=>$val)
$values[$key] = $GLOBALS["APPLICATION"]->ConvertCharset($val, "utf-8", SITE_CHARSET);
return $values;
}
function QueryArray($str = '(ObjectClass=*)', $fields = false)
{
if(strlen($this->arFields['BASE_DN'])<=0)
return false;
$arBaseDNs = explode(";", $this->arFields['BASE_DN']);
$info = false;
foreach($arBaseDNs as $BaseDN)
{
$BaseDN = trim($BaseDN);
if($BaseDN == "")
continue;
if($this->arFields["CONVERT_UTF8"]=="Y")
{
$BaseDN = $GLOBALS["APPLICATION"]->ConvertCharset($BaseDN, SITE_CHARSET, "utf-8");
$str = $GLOBALS["APPLICATION"]->ConvertCharset($str, SITE_CHARSET, "utf-8");
}
if($fields === false)
$sr = @ldap_search($this->conn, $BaseDN, $str);
else
$sr = @ldap_search($this->conn, $BaseDN, $str, $fields);
if($sr)
{
$entry = ldap_first_entry($this->conn, $sr);
if($entry)
{
if(!is_array($info))
{
$info = Array();
$i=0;
}
do
{
$attributes = ldap_get_attributes($this->conn, $entry);
for($j=0; $j<$attributes['count']; $j++)
{
$values = ldap_get_values_len($this->conn, $entry, $attributes[$j]);
$bPhotoAttr = in_array($attributes[$j], self::$PHOTO_ATTRIBS);
$info[$i][strtolower($attributes[$j])] = $bPhotoAttr ? $values : $this->WorkAttr($values);
}
if(!is_set($info[$i], 'dn'))
{
if($this->arFields["CONVERT_UTF8"]=="Y")
$info[$i]['dn'] = $GLOBALS["APPLICATION"]->ConvertCharset(ldap_get_dn($this->conn, $entry), "utf-8", SITE_CHARSET);
else
$info[$i]['dn'] = ldap_get_dn($this->conn, $entry);
}
$i++;
}
while($entry = ldap_next_entry($this->conn, $entry));
}
}
}
return $info;
}
function Query($str = '(ObjectClass=*)', $fields = false)
{
$info = $this->QueryArray($str, $fields);
$result = new CDBResult;
$result->InitFromArray($info);
return $result;
}
// query for group list from AD - server
function GetGroupListArray($query = '')
{
static $groupslists = array();
$group_filter = $this->arFields['GROUP_FILTER'];
if(strlen(trim($group_filter))>0 && substr(trim($group_filter), 0, 1)!='(')
$group_filter = '('.trim($group_filter).')';
$query = '(&'.$group_filter.$query.')';
if (!array_key_exists($query, $groupslists))
{
$this->BindAdmin();
$arGroupAttr = array(
isset($this->arFields["~GROUP_ID_ATTR"]) ? $this->arFields["~GROUP_ID_ATTR"] : $this->arFields["GROUP_ID_ATTR"],
isset($this->arFields["~GROUP_NAME_ATTR"]) ? $this->arFields["~GROUP_NAME_ATTR"] : $this->arFields["GROUP_NAME_ATTR"],
isset($this->arFields["~GROUP_MEMBERS_ATTR"]) ? $this->arFields["~GROUP_MEMBERS_ATTR"] : $this->arFields["GROUP_MEMBERS_ATTR"],
"name", "cn", "gidNumber", "description", "memberof",
"primarygrouptoken", "primarygroupid", "samaccountname",
"distinguishedname"
);
if ($this->arFields['USER_GROUP_ACCESSORY'] == 'Y')
$arGroupAttr[] = (isset($this->arFields["~USER_GROUP_ATTR"]) ? $this->arFields["~USER_GROUP_ATTR"] : $this->arFields["USER_GROUP_ATTR"]);
$arGroupsTmp = $this->QueryArray($query, $arGroupAttr);
if (!$arGroupsTmp)
return false;
$arGroups = array();
$group_id_attr = strtolower($this->arFields['GROUP_ID_ATTR']);
if(is_set($this->arFields, 'GROUP_NAME_ATTR'))
$group_name_attr = strtolower($this->arFields['GROUP_NAME_ATTR']);
else
$group_name_attr = false;
foreach ($arGroupsTmp as $grp)
{
$grp['ID'] = $grp[$group_id_attr];
if ($group_name_attr && is_set($grp, $group_name_attr))
$grp['NAME'] = $grp[$group_name_attr];
$arGroups[$grp['ID']] = $grp;
}
$groupslists[$query] = $arGroups;
}
return $groupslists[$query];
}
function GetGroupList($query = '')
{
$arGroups = $this->GetGroupListArray($query);
$result = new CDBResult();
$result->InitFromArray($arGroups);
return $result;
}
function OnUserLogin($arArgs)
{
if(!function_exists("ldap_connect"))
return;
global $USER, $DB, $APPLICATION;
extract($arArgs);
if(strlen($LOGIN)<=0 || strlen($PASSWORD)<=0)
return ;
$arFilter = Array("ACTIVE"=>"Y");
$p = strpos($LOGIN, "\\");
if( $p===false && COption::GetOptionString("ldap", "ntlm_auth_without_prefix", "Y") != "Y")
return false;
elseif( $p > 0 )
{
$arFilter["CODE"] = substr($LOGIN, 0, $p);
$LOGIN = substr($LOGIN, $p+1);
}
$arParams = Array(
"LOGIN" => &$LOGIN,
"PASSWORD" => &$PASSWORD,
"LDAP_FILTER" => &$arFilter,
);
$APPLICATION->ResetException();
$db_events = GetModuleEvents("ldap", "OnBeforeUserLogin");
while($arEvent = $db_events->Fetch())
{
// TODO check whether wrapping of &$arParams into another array is reasonable as part of migration from ExecuteModuleEvent to ExecuteModuleEventEx
if(ExecuteModuleEventEx($arEvent, array(&$arParams))===false)
{
if($err = $APPLICATION->GetException())
$result_message = Array("MESSAGE"=>$err->GetString()."<br>", "TYPE"=>"ERROR");
else
{
$APPLICATION->ThrowException("Unknown error");
$result_message = Array("MESSAGE"=>"Unknown error"."<br>", "TYPE"=>"ERROR");
}
return false;
}
}
$db_ldap_serv = CLdapServer::GetList(Array(), $arFilter);
while($xLDAP = $db_ldap_serv->GetNextServer())
{
if($xLDAP->Connect())
{
// user AD parameters are queried here, inside FindUser function
if ($arLdapUser = $xLDAP->FindUser($LOGIN, $PASSWORD))
{
//print_r($arLdapUser);
$ID = $xLDAP->SetUser($arLdapUser, (COption::GetOptionString("ldap", "add_user_when_auth", "Y")=="Y"));
if($ID > 0)
{
$arArgs["STORE_PASSWORD"] = "N";
$xLDAP->Disconnect();
return $ID;
}
}
$xLDAP->Disconnect();
}
}
return false;
}
// this function is called on user logon (either normal or ntlm) to find user in ldap
function FindUser($LOGIN, $PASSWORD = false)
{
$login_field = $LOGIN;
$password_field = $PASSWORD;
$this->BindAdmin();
$user_filter = "(&".$this->arFields["~USER_FILTER"]."(".$this->arFields["~USER_ID_ATTR"]."=".$this->specialchars($login_field)."))";
$dbLdapUsers = $this->Query($user_filter);
if (!$dbLdapUsers)
return false;
if($arLdapUser = $dbLdapUsers->Fetch())
{
if($PASSWORD !== false) // also check auth
{
$user_dn = $arLdapUser['dn'];
if (!$this->Bind($user_dn, $password_field))
return false;
}
return $this->GetUserFields($arLdapUser);
}
return false;
}
// converts LDAP values to those suitable for user fields
function GetUserFields($arLdapUser, &$departmentCache=FALSE)
{
global $APPLICATION;
$arFields = array(
'DN' => $arLdapUser['dn'],
'LOGIN' => $arLdapUser[strtolower($this->arFields['~USER_ID_ATTR'])],
'EXTERNAL_AUTH_ID' => 'LDAP#'.$this->arFields['ID'],
'LDAP_GROUPS' => $arLdapUser[strtolower($this->arFields['~USER_GROUP_ATTR'])],
);
// list of user field definitions
$arRes = $GLOBALS["USER_FIELD_MANAGER"]->GetUserFields("USER", 0, LANGUAGE_ID);
// for each field, do the conversion
foreach($this->arFields["FIELD_MAP"] as $userField=>$attr)
{
if(is_array($arRes[$userField]))
{
//"USER_TYPE_ID"
if($arRes[$userField]["MULTIPLE"]=="Y")
{
if (is_array($arLdapUser[strtolower($attr)]))
$arFields[$userField] = array_values($arLdapUser[strtolower($attr)]);
else
$arFields[$userField] = array($arLdapUser[strtolower($attr)]);
}
else if (!empty($arLdapUser[strtolower($attr)]))
$arFields[$userField] = $arLdapUser[strtolower($attr)];
else if (!empty($arRes[$userField]['SETTINGS']['DEFAULT_VALUE']))
{
if (is_array($arRes[$userField]['SETTINGS']['DEFAULT_VALUE']))
{
if (!empty($arRes[$userField]['SETTINGS']['DEFAULT_VALUE']['VALUE']))
$arFields[$userField] = $arRes[$userField]['SETTINGS']['DEFAULT_VALUE']['VALUE'];
}
else
$arFields[$userField] = $arRes[$userField]['SETTINGS']['DEFAULT_VALUE'];
}
}
elseif(preg_match("/(.*)&([0-9]+)/", $attr, $arMatch))
{
if(intval($arLdapUser[strtolower($arMatch[1])]) & intval($arMatch[2]))
$arFields[$userField] = "N";
else
$arFields[$userField] = "Y";
}
elseif ($userField == "PERSONAL_PHOTO")
{
$arFields["PERSONAL_PHOTO"] = "";
if($arLdapUser[strtolower($attr)] == "")
continue;
$fExt = CLdapUtil::GetImgTypeBySignature($arLdapUser[strtolower($attr)][0]);
if(!$fExt)
continue;
$tmpDir = CTempFile::GetDirectoryName();
CheckDirPath($tmpDir);
$fname = "ad_".rand().".".$fExt;
if(!file_put_contents($tmpDir.$fname,$arLdapUser[strtolower($attr)][0]))
continue;
$arFields["PERSONAL_PHOTO"] = array(
"name" => $fname,
"type" => CFile::GetContentType($tmpDir.$fname),
"tmp_name" => $tmpDir.$fname
);
}
else
$arFields[$userField] = $arLdapUser[strtolower($attr)];
if(is_null($arFields[$userField]))
$arFields[$userField]=false;
}
$APPLICATION->ResetException();
$db_events = GetModuleEvents("ldap", "OnLdapUserFields");
while($arEvent = $db_events->Fetch())
{
$arParams = array(array(&$arFields, $arLdapUser));
if(ExecuteModuleEventEx($arEvent, $arParams)===false)
{
if(!($err = $APPLICATION->GetException()))
$APPLICATION->ThrowException("Unknown error");
return false;
}
$arFields = $arParams[0][0];
}
// set a department field, if needed
if (empty($arFields['UF_DEPARTMENT']) && isModuleInstalled('intranet')
&& $this->arFields['IMPORT_STRUCT'] && $this->arFields['IMPORT_STRUCT']=='Y')
{
//$arLdapUser[$this->arFields['USER_DN_ATTR']]
$username = $arLdapUser[$this->arFields['USER_ID_ATTR']];
if ($arDepartment = $this->GetDepartmentIdForADUser($arLdapUser[$this->arFields['USER_DEPARTMENT_ATTR']],$arLdapUser[$this->arFields['USER_MANAGER_ATTR']],$username,$departmentCache))
{
// fill in cache. it is done outside the function because it has many exit points
if ($departmentCache)
$departmentCache[$username] = $arDepartment;
// this is not final assignment
// $arFields['UF_DEPARTMENT'] sould contain array of department ids
// but somehow we have to return an information whether this user is a department head
// so we'll save this data here temporarily
$arFields['UF_DEPARTMENT'] = $arDepartment;
}
else
$arFields['UF_DEPARTMENT'] = array();
// at this point $arFields['UF_DEPARTMENT'] should be set to some value, even an empty array is ok
}
if (!is_array($arFields['LDAP_GROUPS']))
$arFields['LDAP_GROUPS'] = (!empty($arFields['LDAP_GROUPS']) ? array($arFields['LDAP_GROUPS']) : array());
$primarygroupid_name_attr = 'primarygroupid';
$primarygrouptoken_name_attr = 'primarygrouptoken';
if ($this->arFields['USER_GROUP_ACCESSORY'] == 'Y')
{
$primarygroupid_name_attr = strtolower($this->arFields['GROUP_ID_ATTR']);
$primarygrouptoken_name_attr = strtolower($this->arFields['USER_GROUP_ATTR']);
$userIdAttr = strtolower($this->arFields['USER_ID_ATTR']);
$groupMemberAttr = strtolower($this->arFields['GROUP_MEMBERS_ATTR']);
}
$arAllGroups = $this->GetGroupListArray();
if (!is_array($arAllGroups) || count($arAllGroups) <= 0)
return $arFields;
$arGroup = reset($arAllGroups);
do
{
if(in_array($arGroup['ID'], $arFields['LDAP_GROUPS']))
continue;
if (
(is_set($arLdapUser, $primarygroupid_name_attr)
&& $arGroup[$primarygrouptoken_name_attr] == $arLdapUser[$primarygroupid_name_attr]
)
||
($this->arFields['USER_GROUP_ACCESSORY'] == 'Y'
&& is_set($arGroup, $groupMemberAttr)
&& (
(is_array($arGroup[$groupMemberAttr])
&& in_array($arLdapUser[$userIdAttr], $arGroup[$groupMemberAttr])
)
||
$arLdapUser[$userIdAttr] == $arGroup[$groupMemberAttr]
)
)
)
{
$arFields['LDAP_GROUPS'][] = $arGroup['ID'];
if ($this->arFields['USER_GROUP_ACCESSORY'] == 'N')
break;
}
}
while ($arGroup = next($arAllGroups));
return $arFields;
}
// Gets department ID for AD user. If department doesn't exist, creates a new one. Returns FALSE if there should be no department set.
// returns array:
// 'ID' - department id
// 'IS_HEAD' - true if this user is head of the department, false if not
function GetDepartmentIdForADUser($department, $managerDN, $username, &$cache=FALSE, $iblockId = FALSE, $names = FALSE)
{
global $APPLICATION;
// check for loops in manager structure, if loop is found - quit
// should be done before cache lookup
if ($names && isset($names[$username]))
return false;
// if department id for this user is already stored in cache
if ($cache)
{
$departmentCached = $cache[$username];
// if user was not set as head earlier, then do not get his id from cache
if ($departmentCached)
return $departmentCached;
}
// if it is a first call in recursive chain
if (!$iblockId)
{
// check module inclusions
if (!IsModuleInstalled('intranet') || !CModule::IncludeModule('iblock'))
return false;
// get structure's iblock id
$iblockId=COption::GetOptionInt("intranet", "iblock_structure", false, false);
if (!$iblockId)
return false;
$names = array();
}
// save current username as already visited
$names[$username] = true;
// manager's department ID
$managerDepId = false;
// if there's a manager - query it
if ($managerDN)
{
$user = substr($managerDN, 0, strpos($managerDN, ','));
$userArr = $this->GetUserArray($user);
if (count($userArr)>0)
{
// contents of userArr are already in local encoding, no need for conversion here
$mgrDepartment = $userArr[0][$this->arFields['USER_DEPARTMENT_ATTR']];
if ($mgrDepartment && trim($mgrDepartment)!='')
{
// if manager's department name is set - then get it's id
$mgrManagerDN = $userArr[0][$this->arFields['USER_MANAGER_ATTR']];
$mgrUserName = $userArr[0][$this->arFields['USER_ID_ATTR']];
$arManagerDep = $this->GetDepartmentIdForADUser($mgrDepartment, $mgrManagerDN, $mgrUserName, $cache, $iblockId, $names);
// fill in cache
if ($cache && $arManagerDep)
$cache[$mgrUserName] = $arManagerDep;
}
}
}
// prepare result and create department (if needed)
$arResult = array('IS_HEAD'=>true); // by default, thinking of user as a head of the department
if ($arManagerDep)
{ // if got manager's data correctly
if ($department && trim($department)!='' && ($mgrDepartment!=$department))
{ // if our department is set && differs from manager's, set manager's as parent
$parentSectionId = $arManagerDep['ID'];
}
else
{
// - if user has no department, but somehow have manager - then he is assumed to be in manager's department
// - if user has same department name as manager - then he is not head
// here we can return manager's department id immediately
$arResult = $arManagerDep;
$arResult['IS_HEAD'] = false;
return $arResult;
}
}
else
{
// if there's no manager's data
if ($department && trim($department)!='')
$parentSectionId = $this->arFields['ROOT_DEPARTMENT'];
else
{
// if have no manager's department and no own department:
// - use default as our department and root as parent section if default is set
// - or just root if default has empty value
// - or return false, if setting of default department is turned off
if ($this->arFields['STRUCT_HAVE_DEFAULT'] && $this->arFields['STRUCT_HAVE_DEFAULT'] == "Y")
{
// if can use default department
$department = $this->arFields['DEFAULT_DEPARTMENT_NAME'];
if ($department && trim($department)!='')
{
// if department is not empty
$parentSectionId = $this->arFields['ROOT_DEPARTMENT'];
}
else
{
// if it is empty - return parent
return array('ID' => $this->arFields['ROOT_DEPARTMENT']);
}
}
else
{
// if have no department in AD and no default - then do not set a department
return false;
}
}
}
// 3. if there's no department set for this user, this means there was no default department name (which substituted in *) - then there's no need to set department id for this user at all
if (!$department || trim($department)=='')
return false;
// 4. detect this user's department ID, using parent id and department name string, which we certainly have now (these 2 parameters are required to get an ID)
// see if this department already exists
$bs = new CIBlockSection();
$dbExistingSections = GetIBlockSectionList(
$iblockId,
($parentSectionId >= 0 ? $parentSectionId : false),
$arOrder = Array("left_margin" => "asc"),
$cnt = 0,
$arFilter = Array('NAME' => $department)
);
$departmentId = false;
if($arItem = $dbExistingSections->GetNext())
$departmentId = $arItem['ID'];
if (!$departmentId)
{
//create new department
$arNewSectFields = Array(
"ACTIVE" => "Y",
"IBLOCK_ID" => $iblockId,
"NAME" => $department
);
if ($parentSectionId>=0)
$arNewSectFields["IBLOCK_SECTION_ID"] = $parentSectionId;
// and get it's Id
$departmentId = $bs->Add($arNewSectFields);
}
$arElement = $GLOBALS["USER_FIELD_MANAGER"]->GetUserFields(
'IBLOCK_'.$iblockId.'_SECTION',
$departmentId
);
// if the head of the department is already set, do not change it
if (!empty($arElement['UF_HEAD']['VALUE']))
$arResult['IS_HEAD'] = false;
$arResult['ID'] = $departmentId;
return $arResult;
}
// get user list (with attributes) from AD server
function GetUserList($arFilter = Array())
{
$query = '';
foreach($arFilter as $key=>$value)
{
$key = strtoupper($key);
switch($key)
{
case 'GROUP_ID':
//"SELECT ".
// "FROM "
case 'GROUP_DN':
$temp = '';
$temp_cnt = 0;
if(!is_array($value))
$value = array($value);
foreach($value as $group)
{
if(strlen($group)<=0)
continue;
$temp_cnt++;
$temp .= '('.$this->arFields['USER_GROUP_ATTR'].'='.$this->specialchars($group).')';
}
$query .= '(|'.$temp.')';
break;
}
}
$user_filter = $this->arFields['USER_FILTER'];
if(strlen(trim($user_filter))>0 && substr(trim($user_filter), 0, 1)!='(')
$user_filter = '('.trim($user_filter).')';
$query = '(&'.$user_filter.$query.')';
$arResult = $this->Query($query);
return $arResult;
}
function GetUserArray($cn)
{
$user_filter = $this->arFields['USER_FILTER'];
if(strlen(trim($user_filter))>0 && substr(trim($user_filter), 0, 1)!='(')
$user_filter = '('.trim($user_filter).')';
$query = '(&'.$user_filter.'('.$cn.'))';
return $this->QueryArray($query);
}
function specialchars($str)
{
$from = Array("\\", ',', '+', '"', '<', '>', ';', "\n", "\r", '=', '*');
$to = Array('\5C', '\2C', '\2B', '\22', '\3C', '\3E', '\3B', '\0A', '\0D', '\3D', '\*');
return str_replace($from, $to, $str);
}
function OnExternalAuthList()
{
$arResult = Array();
$db_ldap_serv = CLdapServer::GetList();
while($arLDAP = $db_ldap_serv->Fetch())
{
$arResult[] = Array(
'ID' => 'LDAP#'.$arLDAP['ID'],
'NAME' => $arLDAP['NAME']
);
}
return $arResult;
}
function NTLMAuth()
{
global $USER, $DB;
if ($USER->IsAuthorized())
return ;
$ntlm_varname = trim(COption::GetOptionString('ldap', 'ntlm_varname', 'REMOTE_USER'));
if (array_key_exists($ntlm_varname, $_SERVER) && strlen($LOGIN = $_SERVER[$ntlm_varname]) > 0)
{
$DOMAIN = "";
if (($pos = strpos($LOGIN, "\\")) !== false)
{
$DOMAIN = substr($LOGIN, 0, $pos);
$LOGIN = substr($LOGIN, $pos + 1);
}
$arFilterServer = array('ACTIVE' => 'Y');
if (strlen($DOMAIN) > 0)
$arFilterServer['CODE'] = $DOMAIN;
else
{
$DEF_DOMAIN_ID = intval(COption::GetOptionInt('ldap', 'ntlm_default_server', 0));
if($DEF_DOMAIN_ID > 0)
$arFilterServer['ID'] = $DEF_DOMAIN_ID;
else
return ;
}
$db_ldap_serv = CLdapServer::GetList(Array(), $arFilterServer);
/*@var $xLDAP CLDAP*/
if ($xLDAP = $db_ldap_serv->GetNextServer())
{
if ($xLDAP->Connect())
{
if ($arLdapUser = $xLDAP->FindUser($LOGIN))
{
$ID = $xLDAP->SetUser($arLdapUser);
if($ID > 0)
$USER->Authorize($ID);
}
$xLDAP->Disconnect();
}
}
}
}
/**
*
* Recieves the users groups list includes all groups parents list
* searching by memberOf in group properties
* @param $arFindGroups - user groups
* @param $arUserGroups - full array with uppergroups
* @param $arAllGroups - list of all ldap groups
*/
function GetAllMemberOf($arFindGroups, &$arUserGroups, $arAllGroups)
{
if(!$arFindGroups || $arFindGroups=='')
return;
if(!is_array($arFindGroups))
$arFindGroups = Array($arFindGroups);
foreach($arFindGroups as $group_id)
{
if(in_array($group_id, $arUserGroups))
continue;
$arUserGroups[] = $group_id;
$this->GetAllMemberOf($arAllGroups[$group_id]["memberof"], $arUserGroups, $arAllGroups);
}
}
function GetGroupMaps()
{
global $DB;
static $arGroupMaps = false;
if(!is_array($arGroupMaps))
{
$arGroupMaps = Array();
$rsCorellations = $DB->Query("SELECT LDAP_GROUP_ID, GROUP_ID FROM b_ldap_group WHERE LDAP_SERVER_ID=".intval($this->arFields['ID']));
while ($arCorellation = $rsCorellations->Fetch())
{
if(!is_array($arGroupMaps[$arCorellation["LDAP_GROUP_ID"]]))
$arGroupMaps[$arCorellation["LDAP_GROUP_ID"]] = Array();
$arGroupMaps[$arCorellation["LDAP_GROUP_ID"]][] = $arCorellation["GROUP_ID"];
}
}
return $arGroupMaps;
}
//Need this to delete old photo
static function PrepareUserPhoto($uid, &$arLdapUser)
{
if(!isset($arLdapUser["PERSONAL_PHOTO"]))
return false;
$dbRes = CUser::GetById($uid);
$arUser = $dbRes->Fetch();
if(!isset($arUser["PERSONAL_PHOTO"]) || is_null($arUser["PERSONAL_PHOTO"]))
return false;
if($arLdapUser["PERSONAL_PHOTO"] == "")
$arLdapUser["PERSONAL_PHOTO"]["del"] = "Y";
$arLdapUser["PERSONAL_PHOTO"]["old_file"] = $arUser["PERSONAL_PHOTO"];
return true;
}
// update user info, using previously loaded data from AD, make additional calls to AD if needed
function SetUser($arLdapUser, $bAddNew = true)
{
global $USER, $DB;
if(!is_object($USER))
{
$USER = new CUser();
$bUSERGen = true;
}
// process previously saved department data
if (isModuleInstalled('intranet') && is_array($arLdapUser['UF_DEPARTMENT']))
{
$isHead = $arLdapUser['UF_DEPARTMENT']['IS_HEAD'];
// replace temporary value with a real one
$arLdapUser['UF_DEPARTMENT'] = array($arLdapUser['UF_DEPARTMENT']['ID']);
}
if(isset($arLdapUser["ID"]))
{
$ID = intval($arLdapUser["ID"]);
self::PrepareUserPhoto($ID,$arLdapUser);
$USER->Update($ID, $arLdapUser);
}
else
{
$ldapUserID = 0;
if (isset($_REQUEST["ldap_user_id"]) && strlen($_REQUEST["ldap_user_id"]) == 32)
{
$dbUser = CUser::GetList($O, $B, Array("XML_ID" => $_REQUEST["ldap_user_id"], 'EXTERNAL_AUTH_ID' => $arLdapUser['EXTERNAL_AUTH_ID']));
if ($arUser = $dbUser->Fetch())
$ldapUserID = $arUser["ID"];
}
$res = CUser::GetList($O, $B, Array('LOGIN_EQUAL_EXACT' => $arLdapUser['LOGIN'], 'EXTERNAL_AUTH_ID' => $arLdapUser['EXTERNAL_AUTH_ID']));
$arLdapUser['PASSWORD'] = uniqid(rand(), true);
if(!($ar_res = $res->Fetch()) && $ldapUserID < 1)
{
if($bAddNew)
{
if(strlen($arLdapUser["EMAIL"])<=0)
$arLdapUser["EMAIL"] = COption::GetOptionString("ldap", "default_email", 'no@email');
$ID = $USER->Add($arLdapUser);
}
else
$ID = 0;
}
else
{
$ID = ($ldapUserID > 1 ? $ldapUserID : $ar_res['ID']);
self::PrepareUserPhoto($ID,$arLdapUser);
$USER->Update($ID, $arLdapUser);
}
$ID = intval($ID);
}
// - add this user to groups
if ($ID > 0)
{
// - set as head of department
if (isModuleInstalled('intranet') && $isHead)
CLdapUtil::SetDepartmentHead($ID,$arLdapUser['UF_DEPARTMENT'][0]);
// For each group finding all superior ones
$arUserLdapGroups = Array();
$arLdapGroups = $this->GetGroupListArray();
$this->GetAllMemberOf($arLdapUser['LDAP_GROUPS'], $arUserLdapGroups, $arLdapGroups);
$arGroupMaps = $this->GetGroupMaps();
$arUserBitrixGroups = $USER->GetUserGroup($ID);
$arUserBitrixGroupsNew = array();
foreach($arGroupMaps as $fromLdapGroup=>$arToUserGroups)
{
foreach($arToUserGroups as $toUserGroup)
{
if (($k = array_search($toUserGroup, $arUserBitrixGroups)) !== false)
unset($arUserBitrixGroups[$k]);
// If there is such a group among user's
if (in_array($fromLdapGroup, $arUserLdapGroups))
$arUserBitrixGroupsNew[] = $toUserGroup;
}
}
$arUserBitrixGroups = array_merge($arUserBitrixGroups, $arUserBitrixGroupsNew);
$USER->SetUserGroup($ID, $arUserBitrixGroups);
}
if($bUSERGen)
unset($USER);
return $ID;
}
}
?>