Completed
Pull Request — master (#9090)
by Blizzz
60:29 queued 39:29
created
apps/user_ldap/lib/Wizard.php 2 patches
Indentation   +1314 added lines, -1314 removed lines patch added patch discarded remove patch
@@ -41,1320 +41,1320 @@
 block discarded – undo
41 41
 use OC\ServerNotAvailableException;
42 42
 
43 43
 class Wizard extends LDAPUtility {
44
-	/** @var \OCP\IL10N */
45
-	static protected $l;
46
-	protected $access;
47
-	protected $cr;
48
-	protected $configuration;
49
-	protected $result;
50
-	protected $resultCache = array();
51
-
52
-	const LRESULT_PROCESSED_OK = 2;
53
-	const LRESULT_PROCESSED_INVALID = 3;
54
-	const LRESULT_PROCESSED_SKIP = 4;
55
-
56
-	const LFILTER_LOGIN      = 2;
57
-	const LFILTER_USER_LIST  = 3;
58
-	const LFILTER_GROUP_LIST = 4;
59
-
60
-	const LFILTER_MODE_ASSISTED = 2;
61
-	const LFILTER_MODE_RAW = 1;
62
-
63
-	const LDAP_NW_TIMEOUT = 4;
64
-
65
-	/**
66
-	 * Constructor
67
-	 * @param Configuration $configuration an instance of Configuration
68
-	 * @param ILDAPWrapper $ldap an instance of ILDAPWrapper
69
-	 * @param Access $access
70
-	 */
71
-	public function __construct(Configuration $configuration, ILDAPWrapper $ldap, Access $access) {
72
-		parent::__construct($ldap);
73
-		$this->configuration = $configuration;
74
-		if(is_null(Wizard::$l)) {
75
-			Wizard::$l = \OC::$server->getL10N('user_ldap');
76
-		}
77
-		$this->access = $access;
78
-		$this->result = new WizardResult();
79
-	}
80
-
81
-	public function  __destruct() {
82
-		if($this->result->hasChanges()) {
83
-			$this->configuration->saveConfiguration();
84
-		}
85
-	}
86
-
87
-	/**
88
-	 * counts entries in the LDAP directory
89
-	 *
90
-	 * @param string $filter the LDAP search filter
91
-	 * @param string $type a string being either 'users' or 'groups';
92
-	 * @return int
93
-	 * @throws \Exception
94
-	 */
95
-	public function countEntries(string $filter, string $type): int {
96
-		$reqs = ['ldapHost', 'ldapPort', 'ldapBase'];
97
-		if($type === 'users') {
98
-			$reqs[] = 'ldapUserFilter';
99
-		}
100
-		if(!$this->checkRequirements($reqs)) {
101
-			throw new \Exception('Requirements not met', 400);
102
-		}
103
-
104
-		$attr = ['dn']; // default
105
-		$limit = 1001;
106
-		if($type === 'groups') {
107
-			$result =  $this->access->countGroups($filter, $attr, $limit);
108
-		} else if($type === 'users') {
109
-			$result = $this->access->countUsers($filter, $attr, $limit);
110
-		} else if ($type === 'objects') {
111
-			$result = $this->access->countObjects($limit);
112
-		} else {
113
-			throw new \Exception('Internal error: Invalid object type', 500);
114
-		}
115
-
116
-		return (int)$result;
117
-	}
118
-
119
-	/**
120
-	 * formats the return value of a count operation to the string to be
121
-	 * inserted.
122
-	 *
123
-	 * @param int $count
124
-	 * @return string
125
-	 */
126
-	private function formatCountResult(int $count): string {
127
-		if($count > 1000) {
128
-			return '> 1000';
129
-		}
130
-		return (string)$count;
131
-	}
132
-
133
-	public function countGroups() {
134
-		$filter = $this->configuration->ldapGroupFilter;
135
-
136
-		if(empty($filter)) {
137
-			$output = self::$l->n('%s group found', '%s groups found', 0, array(0));
138
-			$this->result->addChange('ldap_group_count', $output);
139
-			return $this->result;
140
-		}
141
-
142
-		try {
143
-			$groupsTotal = $this->countEntries($filter, 'groups');
144
-		} catch (\Exception $e) {
145
-			//400 can be ignored, 500 is forwarded
146
-			if($e->getCode() === 500) {
147
-				throw $e;
148
-			}
149
-			return false;
150
-		}
151
-		$output = self::$l->n(
152
-			'%s group found',
153
-			'%s groups found',
154
-			$groupsTotal,
155
-			[$this->formatCountResult($groupsTotal)]
156
-		);
157
-		$this->result->addChange('ldap_group_count', $output);
158
-		return $this->result;
159
-	}
160
-
161
-	/**
162
-	 * @return WizardResult
163
-	 * @throws \Exception
164
-	 */
165
-	public function countUsers() {
166
-		$filter = $this->access->getFilterForUserCount();
167
-
168
-		$usersTotal = $this->countEntries($filter, 'users');
169
-		$output = self::$l->n(
170
-			'%s user found',
171
-			'%s users found',
172
-			$usersTotal,
173
-			[$this->formatCountResult($usersTotal)]
174
-		);
175
-		$this->result->addChange('ldap_user_count', $output);
176
-		return $this->result;
177
-	}
178
-
179
-	/**
180
-	 * counts any objects in the currently set base dn
181
-	 *
182
-	 * @return WizardResult
183
-	 * @throws \Exception
184
-	 */
185
-	public function countInBaseDN() {
186
-		// we don't need to provide a filter in this case
187
-		$total = $this->countEntries('', 'objects');
188
-		if($total === false) {
189
-			throw new \Exception('invalid results received');
190
-		}
191
-		$this->result->addChange('ldap_test_base', $total);
192
-		return $this->result;
193
-	}
194
-
195
-	/**
196
-	 * counts users with a specified attribute
197
-	 * @param string $attr
198
-	 * @param bool $existsCheck
199
-	 * @return int|bool
200
-	 */
201
-	public function countUsersWithAttribute($attr, $existsCheck = false) {
202
-		if(!$this->checkRequirements(array('ldapHost',
203
-										   'ldapPort',
204
-										   'ldapBase',
205
-										   'ldapUserFilter',
206
-										   ))) {
207
-			return  false;
208
-		}
209
-
210
-		$filter = $this->access->combineFilterWithAnd(array(
211
-			$this->configuration->ldapUserFilter,
212
-			$attr . '=*'
213
-		));
214
-
215
-		$limit = ($existsCheck === false) ? null : 1;
216
-
217
-		return $this->access->countUsers($filter, array('dn'), $limit);
218
-	}
219
-
220
-	/**
221
-	 * detects the display name attribute. If a setting is already present that
222
-	 * returns at least one hit, the detection will be canceled.
223
-	 * @return WizardResult|bool
224
-	 * @throws \Exception
225
-	 */
226
-	public function detectUserDisplayNameAttribute() {
227
-		if(!$this->checkRequirements(array('ldapHost',
228
-										'ldapPort',
229
-										'ldapBase',
230
-										'ldapUserFilter',
231
-										))) {
232
-			return  false;
233
-		}
234
-
235
-		$attr = $this->configuration->ldapUserDisplayName;
236
-		if ($attr !== '' && $attr !== 'displayName') {
237
-			// most likely not the default value with upper case N,
238
-			// verify it still produces a result
239
-			$count = (int)$this->countUsersWithAttribute($attr, true);
240
-			if($count > 0) {
241
-				//no change, but we sent it back to make sure the user interface
242
-				//is still correct, even if the ajax call was cancelled meanwhile
243
-				$this->result->addChange('ldap_display_name', $attr);
244
-				return $this->result;
245
-			}
246
-		}
247
-
248
-		// first attribute that has at least one result wins
249
-		$displayNameAttrs = array('displayname', 'cn');
250
-		foreach ($displayNameAttrs as $attr) {
251
-			$count = (int)$this->countUsersWithAttribute($attr, true);
252
-
253
-			if($count > 0) {
254
-				$this->applyFind('ldap_display_name', $attr);
255
-				return $this->result;
256
-			}
257
-		}
258
-
259
-		throw new \Exception(self::$l->t('Could not detect user display name attribute. Please specify it yourself in advanced LDAP settings.'));
260
-	}
261
-
262
-	/**
263
-	 * detects the most often used email attribute for users applying to the
264
-	 * user list filter. If a setting is already present that returns at least
265
-	 * one hit, the detection will be canceled.
266
-	 * @return WizardResult|bool
267
-	 */
268
-	public function detectEmailAttribute() {
269
-		if(!$this->checkRequirements(array('ldapHost',
270
-										   'ldapPort',
271
-										   'ldapBase',
272
-										   'ldapUserFilter',
273
-										   ))) {
274
-			return  false;
275
-		}
276
-
277
-		$attr = $this->configuration->ldapEmailAttribute;
278
-		if ($attr !== '') {
279
-			$count = (int)$this->countUsersWithAttribute($attr, true);
280
-			if($count > 0) {
281
-				return false;
282
-			}
283
-			$writeLog = true;
284
-		} else {
285
-			$writeLog = false;
286
-		}
287
-
288
-		$emailAttributes = array('mail', 'mailPrimaryAddress');
289
-		$winner = '';
290
-		$maxUsers = 0;
291
-		foreach($emailAttributes as $attr) {
292
-			$count = $this->countUsersWithAttribute($attr);
293
-			if($count > $maxUsers) {
294
-				$maxUsers = $count;
295
-				$winner = $attr;
296
-			}
297
-		}
298
-
299
-		if($winner !== '') {
300
-			$this->applyFind('ldap_email_attr', $winner);
301
-			if($writeLog) {
302
-				\OCP\Util::writeLog('user_ldap', 'The mail attribute has ' .
303
-					'automatically been reset, because the original value ' .
304
-					'did not return any results.', \OCP\Util::INFO);
305
-			}
306
-		}
307
-
308
-		return $this->result;
309
-	}
310
-
311
-	/**
312
-	 * @return WizardResult
313
-	 * @throws \Exception
314
-	 */
315
-	public function determineAttributes() {
316
-		if(!$this->checkRequirements(array('ldapHost',
317
-										   'ldapPort',
318
-										   'ldapBase',
319
-										   'ldapUserFilter',
320
-										   ))) {
321
-			return  false;
322
-		}
323
-
324
-		$attributes = $this->getUserAttributes();
325
-
326
-		natcasesort($attributes);
327
-		$attributes = array_values($attributes);
328
-
329
-		$this->result->addOptions('ldap_loginfilter_attributes', $attributes);
330
-
331
-		$selected = $this->configuration->ldapLoginFilterAttributes;
332
-		if(is_array($selected) && !empty($selected)) {
333
-			$this->result->addChange('ldap_loginfilter_attributes', $selected);
334
-		}
335
-
336
-		return $this->result;
337
-	}
338
-
339
-	/**
340
-	 * detects the available LDAP attributes
341
-	 * @return array|false The instance's WizardResult instance
342
-	 * @throws \Exception
343
-	 */
344
-	private function getUserAttributes() {
345
-		if(!$this->checkRequirements(array('ldapHost',
346
-										   'ldapPort',
347
-										   'ldapBase',
348
-										   'ldapUserFilter',
349
-										   ))) {
350
-			return  false;
351
-		}
352
-		$cr = $this->getConnection();
353
-		if(!$cr) {
354
-			throw new \Exception('Could not connect to LDAP');
355
-		}
356
-
357
-		$base = $this->configuration->ldapBase[0];
358
-		$filter = $this->configuration->ldapUserFilter;
359
-		$rr = $this->ldap->search($cr, $base, $filter, array(), 1, 1);
360
-		if(!$this->ldap->isResource($rr)) {
361
-			return false;
362
-		}
363
-		$er = $this->ldap->firstEntry($cr, $rr);
364
-		$attributes = $this->ldap->getAttributes($cr, $er);
365
-		$pureAttributes = array();
366
-		for($i = 0; $i < $attributes['count']; $i++) {
367
-			$pureAttributes[] = $attributes[$i];
368
-		}
369
-
370
-		return $pureAttributes;
371
-	}
372
-
373
-	/**
374
-	 * detects the available LDAP groups
375
-	 * @return WizardResult|false the instance's WizardResult instance
376
-	 */
377
-	public function determineGroupsForGroups() {
378
-		return $this->determineGroups('ldap_groupfilter_groups',
379
-									  'ldapGroupFilterGroups',
380
-									  false);
381
-	}
382
-
383
-	/**
384
-	 * detects the available LDAP groups
385
-	 * @return WizardResult|false the instance's WizardResult instance
386
-	 */
387
-	public function determineGroupsForUsers() {
388
-		return $this->determineGroups('ldap_userfilter_groups',
389
-									  'ldapUserFilterGroups');
390
-	}
391
-
392
-	/**
393
-	 * detects the available LDAP groups
394
-	 * @param string $dbKey
395
-	 * @param string $confKey
396
-	 * @param bool $testMemberOf
397
-	 * @return WizardResult|false the instance's WizardResult instance
398
-	 * @throws \Exception
399
-	 */
400
-	private function determineGroups($dbKey, $confKey, $testMemberOf = true) {
401
-		if(!$this->checkRequirements(array('ldapHost',
402
-										   'ldapPort',
403
-										   'ldapBase',
404
-										   ))) {
405
-			return  false;
406
-		}
407
-		$cr = $this->getConnection();
408
-		if(!$cr) {
409
-			throw new \Exception('Could not connect to LDAP');
410
-		}
411
-
412
-		$this->fetchGroups($dbKey, $confKey);
413
-
414
-		if($testMemberOf) {
415
-			$this->configuration->hasMemberOfFilterSupport = $this->testMemberOf();
416
-			$this->result->markChange();
417
-			if(!$this->configuration->hasMemberOfFilterSupport) {
418
-				throw new \Exception('memberOf is not supported by the server');
419
-			}
420
-		}
421
-
422
-		return $this->result;
423
-	}
424
-
425
-	/**
426
-	 * fetches all groups from LDAP and adds them to the result object
427
-	 *
428
-	 * @param string $dbKey
429
-	 * @param string $confKey
430
-	 * @return array $groupEntries
431
-	 * @throws \Exception
432
-	 */
433
-	public function fetchGroups($dbKey, $confKey) {
434
-		$obclasses = array('posixGroup', 'group', 'zimbraDistributionList', 'groupOfNames', 'groupOfUniqueNames');
435
-
436
-		$filterParts = array();
437
-		foreach($obclasses as $obclass) {
438
-			$filterParts[] = 'objectclass='.$obclass;
439
-		}
440
-		//we filter for everything
441
-		//- that looks like a group and
442
-		//- has the group display name set
443
-		$filter = $this->access->combineFilterWithOr($filterParts);
444
-		$filter = $this->access->combineFilterWithAnd(array($filter, 'cn=*'));
445
-
446
-		$groupNames = array();
447
-		$groupEntries = array();
448
-		$limit = 400;
449
-		$offset = 0;
450
-		do {
451
-			// we need to request dn additionally here, otherwise memberOf
452
-			// detection will fail later
453
-			$result = $this->access->searchGroups($filter, array('cn', 'dn'), $limit, $offset);
454
-			foreach($result as $item) {
455
-				if(!isset($item['cn']) && !is_array($item['cn']) && !isset($item['cn'][0])) {
456
-					// just in case - no issue known
457
-					continue;
458
-				}
459
-				$groupNames[] = $item['cn'][0];
460
-				$groupEntries[] = $item;
461
-			}
462
-			$offset += $limit;
463
-		} while ($this->access->hasMoreResults());
464
-
465
-		if(count($groupNames) > 0) {
466
-			natsort($groupNames);
467
-			$this->result->addOptions($dbKey, array_values($groupNames));
468
-		} else {
469
-			throw new \Exception(self::$l->t('Could not find the desired feature'));
470
-		}
471
-
472
-		$setFeatures = $this->configuration->$confKey;
473
-		if(is_array($setFeatures) && !empty($setFeatures)) {
474
-			//something is already configured? pre-select it.
475
-			$this->result->addChange($dbKey, $setFeatures);
476
-		}
477
-		return $groupEntries;
478
-	}
479
-
480
-	public function determineGroupMemberAssoc() {
481
-		if(!$this->checkRequirements(array('ldapHost',
482
-										   'ldapPort',
483
-										   'ldapGroupFilter',
484
-										   ))) {
485
-			return  false;
486
-		}
487
-		$attribute = $this->detectGroupMemberAssoc();
488
-		if($attribute === false) {
489
-			return false;
490
-		}
491
-		$this->configuration->setConfiguration(array('ldapGroupMemberAssocAttr' => $attribute));
492
-		$this->result->addChange('ldap_group_member_assoc_attribute', $attribute);
493
-
494
-		return $this->result;
495
-	}
496
-
497
-	/**
498
-	 * Detects the available object classes
499
-	 * @return WizardResult|false the instance's WizardResult instance
500
-	 * @throws \Exception
501
-	 */
502
-	public function determineGroupObjectClasses() {
503
-		if(!$this->checkRequirements(array('ldapHost',
504
-										   'ldapPort',
505
-										   'ldapBase',
506
-										   ))) {
507
-			return  false;
508
-		}
509
-		$cr = $this->getConnection();
510
-		if(!$cr) {
511
-			throw new \Exception('Could not connect to LDAP');
512
-		}
513
-
514
-		$obclasses = array('groupOfNames', 'groupOfUniqueNames', 'group', 'posixGroup', '*');
515
-		$this->determineFeature($obclasses,
516
-								'objectclass',
517
-								'ldap_groupfilter_objectclass',
518
-								'ldapGroupFilterObjectclass',
519
-								false);
520
-
521
-		return $this->result;
522
-	}
523
-
524
-	/**
525
-	 * detects the available object classes
526
-	 * @return WizardResult
527
-	 * @throws \Exception
528
-	 */
529
-	public function determineUserObjectClasses() {
530
-		if(!$this->checkRequirements(array('ldapHost',
531
-										   'ldapPort',
532
-										   'ldapBase',
533
-										   ))) {
534
-			return  false;
535
-		}
536
-		$cr = $this->getConnection();
537
-		if(!$cr) {
538
-			throw new \Exception('Could not connect to LDAP');
539
-		}
540
-
541
-		$obclasses = array('inetOrgPerson', 'person', 'organizationalPerson',
542
-						   'user', 'posixAccount', '*');
543
-		$filter = $this->configuration->ldapUserFilter;
544
-		//if filter is empty, it is probably the first time the wizard is called
545
-		//then, apply suggestions.
546
-		$this->determineFeature($obclasses,
547
-								'objectclass',
548
-								'ldap_userfilter_objectclass',
549
-								'ldapUserFilterObjectclass',
550
-								empty($filter));
551
-
552
-		return $this->result;
553
-	}
554
-
555
-	/**
556
-	 * @return WizardResult|false
557
-	 * @throws \Exception
558
-	 */
559
-	public function getGroupFilter() {
560
-		if(!$this->checkRequirements(array('ldapHost',
561
-										   'ldapPort',
562
-										   'ldapBase',
563
-										   ))) {
564
-			return false;
565
-		}
566
-		//make sure the use display name is set
567
-		$displayName = $this->configuration->ldapGroupDisplayName;
568
-		if ($displayName === '') {
569
-			$d = $this->configuration->getDefaults();
570
-			$this->applyFind('ldap_group_display_name',
571
-							 $d['ldap_group_display_name']);
572
-		}
573
-		$filter = $this->composeLdapFilter(self::LFILTER_GROUP_LIST);
574
-
575
-		$this->applyFind('ldap_group_filter', $filter);
576
-		return $this->result;
577
-	}
578
-
579
-	/**
580
-	 * @return WizardResult|false
581
-	 * @throws \Exception
582
-	 */
583
-	public function getUserListFilter() {
584
-		if(!$this->checkRequirements(array('ldapHost',
585
-										   'ldapPort',
586
-										   'ldapBase',
587
-										   ))) {
588
-			return false;
589
-		}
590
-		//make sure the use display name is set
591
-		$displayName = $this->configuration->ldapUserDisplayName;
592
-		if ($displayName === '') {
593
-			$d = $this->configuration->getDefaults();
594
-			$this->applyFind('ldap_display_name', $d['ldap_display_name']);
595
-		}
596
-		$filter = $this->composeLdapFilter(self::LFILTER_USER_LIST);
597
-		if(!$filter) {
598
-			throw new \Exception('Cannot create filter');
599
-		}
600
-
601
-		$this->applyFind('ldap_userlist_filter', $filter);
602
-		return $this->result;
603
-	}
604
-
605
-	/**
606
-	 * @return bool|WizardResult
607
-	 * @throws \Exception
608
-	 */
609
-	public function getUserLoginFilter() {
610
-		if(!$this->checkRequirements(array('ldapHost',
611
-										   'ldapPort',
612
-										   'ldapBase',
613
-										   'ldapUserFilter',
614
-										   ))) {
615
-			return false;
616
-		}
617
-
618
-		$filter = $this->composeLdapFilter(self::LFILTER_LOGIN);
619
-		if(!$filter) {
620
-			throw new \Exception('Cannot create filter');
621
-		}
622
-
623
-		$this->applyFind('ldap_login_filter', $filter);
624
-		return $this->result;
625
-	}
626
-
627
-	/**
628
-	 * @return bool|WizardResult
629
-	 * @param string $loginName
630
-	 * @throws \Exception
631
-	 */
632
-	public function testLoginName($loginName) {
633
-		if(!$this->checkRequirements(array('ldapHost',
634
-			'ldapPort',
635
-			'ldapBase',
636
-			'ldapLoginFilter',
637
-		))) {
638
-			return false;
639
-		}
640
-
641
-		$cr = $this->access->connection->getConnectionResource();
642
-		if(!$this->ldap->isResource($cr)) {
643
-			throw new \Exception('connection error');
644
-		}
645
-
646
-		if(mb_strpos($this->access->connection->ldapLoginFilter, '%uid', 0, 'UTF-8')
647
-			=== false) {
648
-			throw new \Exception('missing placeholder');
649
-		}
650
-
651
-		$users = $this->access->countUsersByLoginName($loginName);
652
-		if($this->ldap->errno($cr) !== 0) {
653
-			throw new \Exception($this->ldap->error($cr));
654
-		}
655
-		$filter = str_replace('%uid', $loginName, $this->access->connection->ldapLoginFilter);
656
-		$this->result->addChange('ldap_test_loginname', $users);
657
-		$this->result->addChange('ldap_test_effective_filter', $filter);
658
-		return $this->result;
659
-	}
660
-
661
-	/**
662
-	 * Tries to determine the port, requires given Host, User DN and Password
663
-	 * @return WizardResult|false WizardResult on success, false otherwise
664
-	 * @throws \Exception
665
-	 */
666
-	public function guessPortAndTLS() {
667
-		if(!$this->checkRequirements(array('ldapHost',
668
-										   ))) {
669
-			return false;
670
-		}
671
-		$this->checkHost();
672
-		$portSettings = $this->getPortSettingsToTry();
673
-
674
-		if(!is_array($portSettings)) {
675
-			throw new \Exception(print_r($portSettings, true));
676
-		}
677
-
678
-		//proceed from the best configuration and return on first success
679
-		foreach($portSettings as $setting) {
680
-			$p = $setting['port'];
681
-			$t = $setting['tls'];
682
-			\OCP\Util::writeLog('user_ldap', 'Wiz: trying port '. $p . ', TLS '. $t, \OCP\Util::DEBUG);
683
-			//connectAndBind may throw Exception, it needs to be catched by the
684
-			//callee of this method
685
-
686
-			try {
687
-				$settingsFound = $this->connectAndBind($p, $t);
688
-			} catch (\Exception $e) {
689
-				// any reply other than -1 (= cannot connect) is already okay,
690
-				// because then we found the server
691
-				// unavailable startTLS returns -11
692
-				if($e->getCode() > 0) {
693
-					$settingsFound = true;
694
-				} else {
695
-					throw $e;
696
-				}
697
-			}
698
-
699
-			if ($settingsFound === true) {
700
-				$config = array(
701
-					'ldapPort' => $p,
702
-					'ldapTLS' => (int)$t
703
-				);
704
-				$this->configuration->setConfiguration($config);
705
-				\OCP\Util::writeLog('user_ldap', 'Wiz: detected Port ' . $p, \OCP\Util::DEBUG);
706
-				$this->result->addChange('ldap_port', $p);
707
-				return $this->result;
708
-			}
709
-		}
710
-
711
-		//custom port, undetected (we do not brute force)
712
-		return false;
713
-	}
714
-
715
-	/**
716
-	 * tries to determine a base dn from User DN or LDAP Host
717
-	 * @return WizardResult|false WizardResult on success, false otherwise
718
-	 */
719
-	public function guessBaseDN() {
720
-		if(!$this->checkRequirements(array('ldapHost',
721
-										   'ldapPort',
722
-										   ))) {
723
-			return false;
724
-		}
725
-
726
-		//check whether a DN is given in the agent name (99.9% of all cases)
727
-		$base = null;
728
-		$i = stripos($this->configuration->ldapAgentName, 'dc=');
729
-		if($i !== false) {
730
-			$base = substr($this->configuration->ldapAgentName, $i);
731
-			if($this->testBaseDN($base)) {
732
-				$this->applyFind('ldap_base', $base);
733
-				return $this->result;
734
-			}
735
-		}
736
-
737
-		//this did not help :(
738
-		//Let's see whether we can parse the Host URL and convert the domain to
739
-		//a base DN
740
-		$helper = new Helper(\OC::$server->getConfig());
741
-		$domain = $helper->getDomainFromURL($this->configuration->ldapHost);
742
-		if(!$domain) {
743
-			return false;
744
-		}
745
-
746
-		$dparts = explode('.', $domain);
747
-		while(count($dparts) > 0) {
748
-			$base2 = 'dc=' . implode(',dc=', $dparts);
749
-			if ($base !== $base2 && $this->testBaseDN($base2)) {
750
-				$this->applyFind('ldap_base', $base2);
751
-				return $this->result;
752
-			}
753
-			array_shift($dparts);
754
-		}
755
-
756
-		return false;
757
-	}
758
-
759
-	/**
760
-	 * sets the found value for the configuration key in the WizardResult
761
-	 * as well as in the Configuration instance
762
-	 * @param string $key the configuration key
763
-	 * @param string $value the (detected) value
764
-	 *
765
-	 */
766
-	private function applyFind($key, $value) {
767
-		$this->result->addChange($key, $value);
768
-		$this->configuration->setConfiguration(array($key => $value));
769
-	}
770
-
771
-	/**
772
-	 * Checks, whether a port was entered in the Host configuration
773
-	 * field. In this case the port will be stripped off, but also stored as
774
-	 * setting.
775
-	 */
776
-	private function checkHost() {
777
-		$host = $this->configuration->ldapHost;
778
-		$hostInfo = parse_url($host);
779
-
780
-		//removes Port from Host
781
-		if(is_array($hostInfo) && isset($hostInfo['port'])) {
782
-			$port = $hostInfo['port'];
783
-			$host = str_replace(':'.$port, '', $host);
784
-			$this->applyFind('ldap_host', $host);
785
-			$this->applyFind('ldap_port', $port);
786
-		}
787
-	}
788
-
789
-	/**
790
-	 * tries to detect the group member association attribute which is
791
-	 * one of 'uniqueMember', 'memberUid', 'member', 'gidNumber'
792
-	 * @return string|false, string with the attribute name, false on error
793
-	 * @throws \Exception
794
-	 */
795
-	private function detectGroupMemberAssoc() {
796
-		$possibleAttrs = array('uniqueMember', 'memberUid', 'member', 'gidNumber');
797
-		$filter = $this->configuration->ldapGroupFilter;
798
-		if(empty($filter)) {
799
-			return false;
800
-		}
801
-		$cr = $this->getConnection();
802
-		if(!$cr) {
803
-			throw new \Exception('Could not connect to LDAP');
804
-		}
805
-		$base = $this->configuration->ldapBase[0];
806
-		$rr = $this->ldap->search($cr, $base, $filter, $possibleAttrs, 0, 1000);
807
-		if(!$this->ldap->isResource($rr)) {
808
-			return false;
809
-		}
810
-		$er = $this->ldap->firstEntry($cr, $rr);
811
-		while(is_resource($er)) {
812
-			$this->ldap->getDN($cr, $er);
813
-			$attrs = $this->ldap->getAttributes($cr, $er);
814
-			$result = array();
815
-			$possibleAttrsCount = count($possibleAttrs);
816
-			for($i = 0; $i < $possibleAttrsCount; $i++) {
817
-				if(isset($attrs[$possibleAttrs[$i]])) {
818
-					$result[$possibleAttrs[$i]] = $attrs[$possibleAttrs[$i]]['count'];
819
-				}
820
-			}
821
-			if(!empty($result)) {
822
-				natsort($result);
823
-				return key($result);
824
-			}
825
-
826
-			$er = $this->ldap->nextEntry($cr, $er);
827
-		}
828
-
829
-		return false;
830
-	}
831
-
832
-	/**
833
-	 * Checks whether for a given BaseDN results will be returned
834
-	 * @param string $base the BaseDN to test
835
-	 * @return bool true on success, false otherwise
836
-	 * @throws \Exception
837
-	 */
838
-	private function testBaseDN($base) {
839
-		$cr = $this->getConnection();
840
-		if(!$cr) {
841
-			throw new \Exception('Could not connect to LDAP');
842
-		}
843
-
844
-		//base is there, let's validate it. If we search for anything, we should
845
-		//get a result set > 0 on a proper base
846
-		$rr = $this->ldap->search($cr, $base, 'objectClass=*', array('dn'), 0, 1);
847
-		if(!$this->ldap->isResource($rr)) {
848
-			$errorNo  = $this->ldap->errno($cr);
849
-			$errorMsg = $this->ldap->error($cr);
850
-			\OCP\Util::writeLog('user_ldap', 'Wiz: Could not search base '.$base.
851
-							' Error '.$errorNo.': '.$errorMsg, \OCP\Util::INFO);
852
-			return false;
853
-		}
854
-		$entries = $this->ldap->countEntries($cr, $rr);
855
-		return ($entries !== false) && ($entries > 0);
856
-	}
857
-
858
-	/**
859
-	 * Checks whether the server supports memberOf in LDAP Filter.
860
-	 * Note: at least in OpenLDAP, availability of memberOf is dependent on
861
-	 * a configured objectClass. I.e. not necessarily for all available groups
862
-	 * memberOf does work.
863
-	 *
864
-	 * @return bool true if it does, false otherwise
865
-	 * @throws \Exception
866
-	 */
867
-	private function testMemberOf() {
868
-		$cr = $this->getConnection();
869
-		if(!$cr) {
870
-			throw new \Exception('Could not connect to LDAP');
871
-		}
872
-		$result = $this->access->countUsers('memberOf=*', array('memberOf'), 1);
873
-		if(is_int($result) &&  $result > 0) {
874
-			return true;
875
-		}
876
-		return false;
877
-	}
878
-
879
-	/**
880
-	 * creates an LDAP Filter from given configuration
881
-	 * @param integer $filterType int, for which use case the filter shall be created
882
-	 * can be any of self::LFILTER_USER_LIST, self::LFILTER_LOGIN or
883
-	 * self::LFILTER_GROUP_LIST
884
-	 * @return string|false string with the filter on success, false otherwise
885
-	 * @throws \Exception
886
-	 */
887
-	private function composeLdapFilter($filterType) {
888
-		$filter = '';
889
-		$parts = 0;
890
-		switch ($filterType) {
891
-			case self::LFILTER_USER_LIST:
892
-				$objcs = $this->configuration->ldapUserFilterObjectclass;
893
-				//glue objectclasses
894
-				if(is_array($objcs) && count($objcs) > 0) {
895
-					$filter .= '(|';
896
-					foreach($objcs as $objc) {
897
-						$filter .= '(objectclass=' . $objc . ')';
898
-					}
899
-					$filter .= ')';
900
-					$parts++;
901
-				}
902
-				//glue group memberships
903
-				if($this->configuration->hasMemberOfFilterSupport) {
904
-					$cns = $this->configuration->ldapUserFilterGroups;
905
-					if(is_array($cns) && count($cns) > 0) {
906
-						$filter .= '(|';
907
-						$cr = $this->getConnection();
908
-						if(!$cr) {
909
-							throw new \Exception('Could not connect to LDAP');
910
-						}
911
-						$base = $this->configuration->ldapBase[0];
912
-						foreach($cns as $cn) {
913
-							$rr = $this->ldap->search($cr, $base, 'cn=' . $cn, array('dn', 'primaryGroupToken'));
914
-							if(!$this->ldap->isResource($rr)) {
915
-								continue;
916
-							}
917
-							$er = $this->ldap->firstEntry($cr, $rr);
918
-							$attrs = $this->ldap->getAttributes($cr, $er);
919
-							$dn = $this->ldap->getDN($cr, $er);
920
-							if ($dn === false || $dn === '') {
921
-								continue;
922
-							}
923
-							$filterPart = '(memberof=' . $dn . ')';
924
-							if(isset($attrs['primaryGroupToken'])) {
925
-								$pgt = $attrs['primaryGroupToken'][0];
926
-								$primaryFilterPart = '(primaryGroupID=' . $pgt .')';
927
-								$filterPart = '(|' . $filterPart . $primaryFilterPart . ')';
928
-							}
929
-							$filter .= $filterPart;
930
-						}
931
-						$filter .= ')';
932
-					}
933
-					$parts++;
934
-				}
935
-				//wrap parts in AND condition
936
-				if($parts > 1) {
937
-					$filter = '(&' . $filter . ')';
938
-				}
939
-				if ($filter === '') {
940
-					$filter = '(objectclass=*)';
941
-				}
942
-				break;
943
-
944
-			case self::LFILTER_GROUP_LIST:
945
-				$objcs = $this->configuration->ldapGroupFilterObjectclass;
946
-				//glue objectclasses
947
-				if(is_array($objcs) && count($objcs) > 0) {
948
-					$filter .= '(|';
949
-					foreach($objcs as $objc) {
950
-						$filter .= '(objectclass=' . $objc . ')';
951
-					}
952
-					$filter .= ')';
953
-					$parts++;
954
-				}
955
-				//glue group memberships
956
-				$cns = $this->configuration->ldapGroupFilterGroups;
957
-				if(is_array($cns) && count($cns) > 0) {
958
-					$filter .= '(|';
959
-					foreach($cns as $cn) {
960
-						$filter .= '(cn=' . $cn . ')';
961
-					}
962
-					$filter .= ')';
963
-				}
964
-				$parts++;
965
-				//wrap parts in AND condition
966
-				if($parts > 1) {
967
-					$filter = '(&' . $filter . ')';
968
-				}
969
-				break;
970
-
971
-			case self::LFILTER_LOGIN:
972
-				$ulf = $this->configuration->ldapUserFilter;
973
-				$loginpart = '=%uid';
974
-				$filterUsername = '';
975
-				$userAttributes = $this->getUserAttributes();
976
-				$userAttributes = array_change_key_case(array_flip($userAttributes));
977
-				$parts = 0;
978
-
979
-				if($this->configuration->ldapLoginFilterUsername === '1') {
980
-					$attr = '';
981
-					if(isset($userAttributes['uid'])) {
982
-						$attr = 'uid';
983
-					} else if(isset($userAttributes['samaccountname'])) {
984
-						$attr = 'samaccountname';
985
-					} else if(isset($userAttributes['cn'])) {
986
-						//fallback
987
-						$attr = 'cn';
988
-					}
989
-					if ($attr !== '') {
990
-						$filterUsername = '(' . $attr . $loginpart . ')';
991
-						$parts++;
992
-					}
993
-				}
994
-
995
-				$filterEmail = '';
996
-				if($this->configuration->ldapLoginFilterEmail === '1') {
997
-					$filterEmail = '(|(mailPrimaryAddress=%uid)(mail=%uid))';
998
-					$parts++;
999
-				}
1000
-
1001
-				$filterAttributes = '';
1002
-				$attrsToFilter = $this->configuration->ldapLoginFilterAttributes;
1003
-				if(is_array($attrsToFilter) && count($attrsToFilter) > 0) {
1004
-					$filterAttributes = '(|';
1005
-					foreach($attrsToFilter as $attribute) {
1006
-						$filterAttributes .= '(' . $attribute . $loginpart . ')';
1007
-					}
1008
-					$filterAttributes .= ')';
1009
-					$parts++;
1010
-				}
1011
-
1012
-				$filterLogin = '';
1013
-				if($parts > 1) {
1014
-					$filterLogin = '(|';
1015
-				}
1016
-				$filterLogin .= $filterUsername;
1017
-				$filterLogin .= $filterEmail;
1018
-				$filterLogin .= $filterAttributes;
1019
-				if($parts > 1) {
1020
-					$filterLogin .= ')';
1021
-				}
1022
-
1023
-				$filter = '(&'.$ulf.$filterLogin.')';
1024
-				break;
1025
-		}
1026
-
1027
-		\OCP\Util::writeLog('user_ldap', 'Wiz: Final filter '.$filter, \OCP\Util::DEBUG);
1028
-
1029
-		return $filter;
1030
-	}
1031
-
1032
-	/**
1033
-	 * Connects and Binds to an LDAP Server
1034
-	 *
1035
-	 * @param int $port the port to connect with
1036
-	 * @param bool $tls whether startTLS is to be used
1037
-	 * @return bool
1038
-	 * @throws \Exception
1039
-	 */
1040
-	private function connectAndBind($port, $tls) {
1041
-		//connect, does not really trigger any server communication
1042
-		$host = $this->configuration->ldapHost;
1043
-		$hostInfo = parse_url($host);
1044
-		if(!$hostInfo) {
1045
-			throw new \Exception(self::$l->t('Invalid Host'));
1046
-		}
1047
-		\OCP\Util::writeLog('user_ldap', 'Wiz: Attempting to connect ', \OCP\Util::DEBUG);
1048
-		$cr = $this->ldap->connect($host, $port);
1049
-		if(!is_resource($cr)) {
1050
-			throw new \Exception(self::$l->t('Invalid Host'));
1051
-		}
1052
-
1053
-		//set LDAP options
1054
-		$this->ldap->setOption($cr, LDAP_OPT_PROTOCOL_VERSION, 3);
1055
-		$this->ldap->setOption($cr, LDAP_OPT_REFERRALS, 0);
1056
-		$this->ldap->setOption($cr, LDAP_OPT_NETWORK_TIMEOUT, self::LDAP_NW_TIMEOUT);
1057
-
1058
-		try {
1059
-			if($tls) {
1060
-				$isTlsWorking = @$this->ldap->startTls($cr);
1061
-				if(!$isTlsWorking) {
1062
-					return false;
1063
-				}
1064
-			}
1065
-
1066
-			\OCP\Util::writeLog('user_ldap', 'Wiz: Attemping to Bind ', \OCP\Util::DEBUG);
1067
-			//interesting part: do the bind!
1068
-			$login = $this->ldap->bind($cr,
1069
-				$this->configuration->ldapAgentName,
1070
-				$this->configuration->ldapAgentPassword
1071
-			);
1072
-			$errNo = $this->ldap->errno($cr);
1073
-			$error = ldap_error($cr);
1074
-			$this->ldap->unbind($cr);
1075
-		} catch(ServerNotAvailableException $e) {
1076
-			return false;
1077
-		}
1078
-
1079
-		if($login === true) {
1080
-			$this->ldap->unbind($cr);
1081
-			\OCP\Util::writeLog('user_ldap', 'Wiz: Bind successful to Port '. $port . ' TLS ' . (int)$tls, \OCP\Util::DEBUG);
1082
-			return true;
1083
-		}
1084
-
1085
-		if($errNo === -1) {
1086
-			//host, port or TLS wrong
1087
-			return false;
1088
-		}
1089
-		throw new \Exception($error, $errNo);
1090
-	}
1091
-
1092
-	/**
1093
-	 * checks whether a valid combination of agent and password has been
1094
-	 * provided (either two values or nothing for anonymous connect)
1095
-	 * @return bool, true if everything is fine, false otherwise
1096
-	 */
1097
-	private function checkAgentRequirements() {
1098
-		$agent = $this->configuration->ldapAgentName;
1099
-		$pwd = $this->configuration->ldapAgentPassword;
1100
-
1101
-		return
1102
-			($agent !== '' && $pwd !== '')
1103
-			||  ($agent === '' && $pwd === '')
1104
-		;
1105
-	}
1106
-
1107
-	/**
1108
-	 * @param array $reqs
1109
-	 * @return bool
1110
-	 */
1111
-	private function checkRequirements($reqs) {
1112
-		$this->checkAgentRequirements();
1113
-		foreach($reqs as $option) {
1114
-			$value = $this->configuration->$option;
1115
-			if(empty($value)) {
1116
-				return false;
1117
-			}
1118
-		}
1119
-		return true;
1120
-	}
1121
-
1122
-	/**
1123
-	 * does a cumulativeSearch on LDAP to get different values of a
1124
-	 * specified attribute
1125
-	 * @param string[] $filters array, the filters that shall be used in the search
1126
-	 * @param string $attr the attribute of which a list of values shall be returned
1127
-	 * @param int $dnReadLimit the amount of how many DNs should be analyzed.
1128
-	 * The lower, the faster
1129
-	 * @param string $maxF string. if not null, this variable will have the filter that
1130
-	 * yields most result entries
1131
-	 * @return array|false an array with the values on success, false otherwise
1132
-	 */
1133
-	public function cumulativeSearchOnAttribute($filters, $attr, $dnReadLimit = 3, &$maxF = null) {
1134
-		$dnRead = array();
1135
-		$foundItems = array();
1136
-		$maxEntries = 0;
1137
-		if(!is_array($this->configuration->ldapBase)
1138
-		   || !isset($this->configuration->ldapBase[0])) {
1139
-			return false;
1140
-		}
1141
-		$base = $this->configuration->ldapBase[0];
1142
-		$cr = $this->getConnection();
1143
-		if(!$this->ldap->isResource($cr)) {
1144
-			return false;
1145
-		}
1146
-		$lastFilter = null;
1147
-		if(isset($filters[count($filters)-1])) {
1148
-			$lastFilter = $filters[count($filters)-1];
1149
-		}
1150
-		foreach($filters as $filter) {
1151
-			if($lastFilter === $filter && count($foundItems) > 0) {
1152
-				//skip when the filter is a wildcard and results were found
1153
-				continue;
1154
-			}
1155
-			// 20k limit for performance and reason
1156
-			$rr = $this->ldap->search($cr, $base, $filter, array($attr), 0, 20000);
1157
-			if(!$this->ldap->isResource($rr)) {
1158
-				continue;
1159
-			}
1160
-			$entries = $this->ldap->countEntries($cr, $rr);
1161
-			$getEntryFunc = 'firstEntry';
1162
-			if(($entries !== false) && ($entries > 0)) {
1163
-				if(!is_null($maxF) && $entries > $maxEntries) {
1164
-					$maxEntries = $entries;
1165
-					$maxF = $filter;
1166
-				}
1167
-				$dnReadCount = 0;
1168
-				do {
1169
-					$entry = $this->ldap->$getEntryFunc($cr, $rr);
1170
-					$getEntryFunc = 'nextEntry';
1171
-					if(!$this->ldap->isResource($entry)) {
1172
-						continue 2;
1173
-					}
1174
-					$rr = $entry; //will be expected by nextEntry next round
1175
-					$attributes = $this->ldap->getAttributes($cr, $entry);
1176
-					$dn = $this->ldap->getDN($cr, $entry);
1177
-					if($dn === false || in_array($dn, $dnRead)) {
1178
-						continue;
1179
-					}
1180
-					$newItems = array();
1181
-					$state = $this->getAttributeValuesFromEntry($attributes,
1182
-																$attr,
1183
-																$newItems);
1184
-					$dnReadCount++;
1185
-					$foundItems = array_merge($foundItems, $newItems);
1186
-					$this->resultCache[$dn][$attr] = $newItems;
1187
-					$dnRead[] = $dn;
1188
-				} while(($state === self::LRESULT_PROCESSED_SKIP
1189
-						|| $this->ldap->isResource($entry))
1190
-						&& ($dnReadLimit === 0 || $dnReadCount < $dnReadLimit));
1191
-			}
1192
-		}
1193
-
1194
-		return array_unique($foundItems);
1195
-	}
1196
-
1197
-	/**
1198
-	 * determines if and which $attr are available on the LDAP server
1199
-	 * @param string[] $objectclasses the objectclasses to use as search filter
1200
-	 * @param string $attr the attribute to look for
1201
-	 * @param string $dbkey the dbkey of the setting the feature is connected to
1202
-	 * @param string $confkey the confkey counterpart for the $dbkey as used in the
1203
-	 * Configuration class
1204
-	 * @param bool $po whether the objectClass with most result entries
1205
-	 * shall be pre-selected via the result
1206
-	 * @return array|false list of found items.
1207
-	 * @throws \Exception
1208
-	 */
1209
-	private function determineFeature($objectclasses, $attr, $dbkey, $confkey, $po = false) {
1210
-		$cr = $this->getConnection();
1211
-		if(!$cr) {
1212
-			throw new \Exception('Could not connect to LDAP');
1213
-		}
1214
-		$p = 'objectclass=';
1215
-		foreach($objectclasses as $key => $value) {
1216
-			$objectclasses[$key] = $p.$value;
1217
-		}
1218
-		$maxEntryObjC = '';
1219
-
1220
-		//how deep to dig?
1221
-		//When looking for objectclasses, testing few entries is sufficient,
1222
-		$dig = 3;
1223
-
1224
-		$availableFeatures =
1225
-			$this->cumulativeSearchOnAttribute($objectclasses, $attr,
1226
-											   $dig, $maxEntryObjC);
1227
-		if(is_array($availableFeatures)
1228
-		   && count($availableFeatures) > 0) {
1229
-			natcasesort($availableFeatures);
1230
-			//natcasesort keeps indices, but we must get rid of them for proper
1231
-			//sorting in the web UI. Therefore: array_values
1232
-			$this->result->addOptions($dbkey, array_values($availableFeatures));
1233
-		} else {
1234
-			throw new \Exception(self::$l->t('Could not find the desired feature'));
1235
-		}
1236
-
1237
-		$setFeatures = $this->configuration->$confkey;
1238
-		if(is_array($setFeatures) && !empty($setFeatures)) {
1239
-			//something is already configured? pre-select it.
1240
-			$this->result->addChange($dbkey, $setFeatures);
1241
-		} else if ($po && $maxEntryObjC !== '') {
1242
-			//pre-select objectclass with most result entries
1243
-			$maxEntryObjC = str_replace($p, '', $maxEntryObjC);
1244
-			$this->applyFind($dbkey, $maxEntryObjC);
1245
-			$this->result->addChange($dbkey, $maxEntryObjC);
1246
-		}
1247
-
1248
-		return $availableFeatures;
1249
-	}
1250
-
1251
-	/**
1252
-	 * appends a list of values fr
1253
-	 * @param resource $result the return value from ldap_get_attributes
1254
-	 * @param string $attribute the attribute values to look for
1255
-	 * @param array &$known new values will be appended here
1256
-	 * @return int, state on of the class constants LRESULT_PROCESSED_OK,
1257
-	 * LRESULT_PROCESSED_INVALID or LRESULT_PROCESSED_SKIP
1258
-	 */
1259
-	private function getAttributeValuesFromEntry($result, $attribute, &$known) {
1260
-		if(!is_array($result)
1261
-		   || !isset($result['count'])
1262
-		   || !$result['count'] > 0) {
1263
-			return self::LRESULT_PROCESSED_INVALID;
1264
-		}
1265
-
1266
-		// strtolower on all keys for proper comparison
1267
-		$result = \OCP\Util::mb_array_change_key_case($result);
1268
-		$attribute = strtolower($attribute);
1269
-		if(isset($result[$attribute])) {
1270
-			foreach($result[$attribute] as $key => $val) {
1271
-				if($key === 'count') {
1272
-					continue;
1273
-				}
1274
-				if(!in_array($val, $known)) {
1275
-					$known[] = $val;
1276
-				}
1277
-			}
1278
-			return self::LRESULT_PROCESSED_OK;
1279
-		} else {
1280
-			return self::LRESULT_PROCESSED_SKIP;
1281
-		}
1282
-	}
1283
-
1284
-	/**
1285
-	 * @return bool|mixed
1286
-	 */
1287
-	private function getConnection() {
1288
-		if(!is_null($this->cr)) {
1289
-			return $this->cr;
1290
-		}
1291
-
1292
-		$cr = $this->ldap->connect(
1293
-			$this->configuration->ldapHost,
1294
-			$this->configuration->ldapPort
1295
-		);
1296
-
1297
-		$this->ldap->setOption($cr, LDAP_OPT_PROTOCOL_VERSION, 3);
1298
-		$this->ldap->setOption($cr, LDAP_OPT_REFERRALS, 0);
1299
-		$this->ldap->setOption($cr, LDAP_OPT_NETWORK_TIMEOUT, self::LDAP_NW_TIMEOUT);
1300
-		if($this->configuration->ldapTLS === 1) {
1301
-			$this->ldap->startTls($cr);
1302
-		}
1303
-
1304
-		$lo = @$this->ldap->bind($cr,
1305
-								 $this->configuration->ldapAgentName,
1306
-								 $this->configuration->ldapAgentPassword);
1307
-		if($lo === true) {
1308
-			$this->$cr = $cr;
1309
-			return $cr;
1310
-		}
1311
-
1312
-		return false;
1313
-	}
1314
-
1315
-	/**
1316
-	 * @return array
1317
-	 */
1318
-	private function getDefaultLdapPortSettings() {
1319
-		static $settings = array(
1320
-								array('port' => 7636, 'tls' => false),
1321
-								array('port' =>  636, 'tls' => false),
1322
-								array('port' => 7389, 'tls' => true),
1323
-								array('port' =>  389, 'tls' => true),
1324
-								array('port' => 7389, 'tls' => false),
1325
-								array('port' =>  389, 'tls' => false),
1326
-						  );
1327
-		return $settings;
1328
-	}
1329
-
1330
-	/**
1331
-	 * @return array
1332
-	 */
1333
-	private function getPortSettingsToTry() {
1334
-		//389 ← LDAP / Unencrypted or StartTLS
1335
-		//636 ← LDAPS / SSL
1336
-		//7xxx ← UCS. need to be checked first, because both ports may be open
1337
-		$host = $this->configuration->ldapHost;
1338
-		$port = (int)$this->configuration->ldapPort;
1339
-		$portSettings = array();
1340
-
1341
-		//In case the port is already provided, we will check this first
1342
-		if($port > 0) {
1343
-			$hostInfo = parse_url($host);
1344
-			if(!(is_array($hostInfo)
1345
-				&& isset($hostInfo['scheme'])
1346
-				&& stripos($hostInfo['scheme'], 'ldaps') !== false)) {
1347
-				$portSettings[] = array('port' => $port, 'tls' => true);
1348
-			}
1349
-			$portSettings[] =array('port' => $port, 'tls' => false);
1350
-		}
1351
-
1352
-		//default ports
1353
-		$portSettings = array_merge($portSettings,
1354
-		                            $this->getDefaultLdapPortSettings());
1355
-
1356
-		return $portSettings;
1357
-	}
44
+    /** @var \OCP\IL10N */
45
+    static protected $l;
46
+    protected $access;
47
+    protected $cr;
48
+    protected $configuration;
49
+    protected $result;
50
+    protected $resultCache = array();
51
+
52
+    const LRESULT_PROCESSED_OK = 2;
53
+    const LRESULT_PROCESSED_INVALID = 3;
54
+    const LRESULT_PROCESSED_SKIP = 4;
55
+
56
+    const LFILTER_LOGIN      = 2;
57
+    const LFILTER_USER_LIST  = 3;
58
+    const LFILTER_GROUP_LIST = 4;
59
+
60
+    const LFILTER_MODE_ASSISTED = 2;
61
+    const LFILTER_MODE_RAW = 1;
62
+
63
+    const LDAP_NW_TIMEOUT = 4;
64
+
65
+    /**
66
+     * Constructor
67
+     * @param Configuration $configuration an instance of Configuration
68
+     * @param ILDAPWrapper $ldap an instance of ILDAPWrapper
69
+     * @param Access $access
70
+     */
71
+    public function __construct(Configuration $configuration, ILDAPWrapper $ldap, Access $access) {
72
+        parent::__construct($ldap);
73
+        $this->configuration = $configuration;
74
+        if(is_null(Wizard::$l)) {
75
+            Wizard::$l = \OC::$server->getL10N('user_ldap');
76
+        }
77
+        $this->access = $access;
78
+        $this->result = new WizardResult();
79
+    }
80
+
81
+    public function  __destruct() {
82
+        if($this->result->hasChanges()) {
83
+            $this->configuration->saveConfiguration();
84
+        }
85
+    }
86
+
87
+    /**
88
+     * counts entries in the LDAP directory
89
+     *
90
+     * @param string $filter the LDAP search filter
91
+     * @param string $type a string being either 'users' or 'groups';
92
+     * @return int
93
+     * @throws \Exception
94
+     */
95
+    public function countEntries(string $filter, string $type): int {
96
+        $reqs = ['ldapHost', 'ldapPort', 'ldapBase'];
97
+        if($type === 'users') {
98
+            $reqs[] = 'ldapUserFilter';
99
+        }
100
+        if(!$this->checkRequirements($reqs)) {
101
+            throw new \Exception('Requirements not met', 400);
102
+        }
103
+
104
+        $attr = ['dn']; // default
105
+        $limit = 1001;
106
+        if($type === 'groups') {
107
+            $result =  $this->access->countGroups($filter, $attr, $limit);
108
+        } else if($type === 'users') {
109
+            $result = $this->access->countUsers($filter, $attr, $limit);
110
+        } else if ($type === 'objects') {
111
+            $result = $this->access->countObjects($limit);
112
+        } else {
113
+            throw new \Exception('Internal error: Invalid object type', 500);
114
+        }
115
+
116
+        return (int)$result;
117
+    }
118
+
119
+    /**
120
+     * formats the return value of a count operation to the string to be
121
+     * inserted.
122
+     *
123
+     * @param int $count
124
+     * @return string
125
+     */
126
+    private function formatCountResult(int $count): string {
127
+        if($count > 1000) {
128
+            return '> 1000';
129
+        }
130
+        return (string)$count;
131
+    }
132
+
133
+    public function countGroups() {
134
+        $filter = $this->configuration->ldapGroupFilter;
135
+
136
+        if(empty($filter)) {
137
+            $output = self::$l->n('%s group found', '%s groups found', 0, array(0));
138
+            $this->result->addChange('ldap_group_count', $output);
139
+            return $this->result;
140
+        }
141
+
142
+        try {
143
+            $groupsTotal = $this->countEntries($filter, 'groups');
144
+        } catch (\Exception $e) {
145
+            //400 can be ignored, 500 is forwarded
146
+            if($e->getCode() === 500) {
147
+                throw $e;
148
+            }
149
+            return false;
150
+        }
151
+        $output = self::$l->n(
152
+            '%s group found',
153
+            '%s groups found',
154
+            $groupsTotal,
155
+            [$this->formatCountResult($groupsTotal)]
156
+        );
157
+        $this->result->addChange('ldap_group_count', $output);
158
+        return $this->result;
159
+    }
160
+
161
+    /**
162
+     * @return WizardResult
163
+     * @throws \Exception
164
+     */
165
+    public function countUsers() {
166
+        $filter = $this->access->getFilterForUserCount();
167
+
168
+        $usersTotal = $this->countEntries($filter, 'users');
169
+        $output = self::$l->n(
170
+            '%s user found',
171
+            '%s users found',
172
+            $usersTotal,
173
+            [$this->formatCountResult($usersTotal)]
174
+        );
175
+        $this->result->addChange('ldap_user_count', $output);
176
+        return $this->result;
177
+    }
178
+
179
+    /**
180
+     * counts any objects in the currently set base dn
181
+     *
182
+     * @return WizardResult
183
+     * @throws \Exception
184
+     */
185
+    public function countInBaseDN() {
186
+        // we don't need to provide a filter in this case
187
+        $total = $this->countEntries('', 'objects');
188
+        if($total === false) {
189
+            throw new \Exception('invalid results received');
190
+        }
191
+        $this->result->addChange('ldap_test_base', $total);
192
+        return $this->result;
193
+    }
194
+
195
+    /**
196
+     * counts users with a specified attribute
197
+     * @param string $attr
198
+     * @param bool $existsCheck
199
+     * @return int|bool
200
+     */
201
+    public function countUsersWithAttribute($attr, $existsCheck = false) {
202
+        if(!$this->checkRequirements(array('ldapHost',
203
+                                            'ldapPort',
204
+                                            'ldapBase',
205
+                                            'ldapUserFilter',
206
+                                            ))) {
207
+            return  false;
208
+        }
209
+
210
+        $filter = $this->access->combineFilterWithAnd(array(
211
+            $this->configuration->ldapUserFilter,
212
+            $attr . '=*'
213
+        ));
214
+
215
+        $limit = ($existsCheck === false) ? null : 1;
216
+
217
+        return $this->access->countUsers($filter, array('dn'), $limit);
218
+    }
219
+
220
+    /**
221
+     * detects the display name attribute. If a setting is already present that
222
+     * returns at least one hit, the detection will be canceled.
223
+     * @return WizardResult|bool
224
+     * @throws \Exception
225
+     */
226
+    public function detectUserDisplayNameAttribute() {
227
+        if(!$this->checkRequirements(array('ldapHost',
228
+                                        'ldapPort',
229
+                                        'ldapBase',
230
+                                        'ldapUserFilter',
231
+                                        ))) {
232
+            return  false;
233
+        }
234
+
235
+        $attr = $this->configuration->ldapUserDisplayName;
236
+        if ($attr !== '' && $attr !== 'displayName') {
237
+            // most likely not the default value with upper case N,
238
+            // verify it still produces a result
239
+            $count = (int)$this->countUsersWithAttribute($attr, true);
240
+            if($count > 0) {
241
+                //no change, but we sent it back to make sure the user interface
242
+                //is still correct, even if the ajax call was cancelled meanwhile
243
+                $this->result->addChange('ldap_display_name', $attr);
244
+                return $this->result;
245
+            }
246
+        }
247
+
248
+        // first attribute that has at least one result wins
249
+        $displayNameAttrs = array('displayname', 'cn');
250
+        foreach ($displayNameAttrs as $attr) {
251
+            $count = (int)$this->countUsersWithAttribute($attr, true);
252
+
253
+            if($count > 0) {
254
+                $this->applyFind('ldap_display_name', $attr);
255
+                return $this->result;
256
+            }
257
+        }
258
+
259
+        throw new \Exception(self::$l->t('Could not detect user display name attribute. Please specify it yourself in advanced LDAP settings.'));
260
+    }
261
+
262
+    /**
263
+     * detects the most often used email attribute for users applying to the
264
+     * user list filter. If a setting is already present that returns at least
265
+     * one hit, the detection will be canceled.
266
+     * @return WizardResult|bool
267
+     */
268
+    public function detectEmailAttribute() {
269
+        if(!$this->checkRequirements(array('ldapHost',
270
+                                            'ldapPort',
271
+                                            'ldapBase',
272
+                                            'ldapUserFilter',
273
+                                            ))) {
274
+            return  false;
275
+        }
276
+
277
+        $attr = $this->configuration->ldapEmailAttribute;
278
+        if ($attr !== '') {
279
+            $count = (int)$this->countUsersWithAttribute($attr, true);
280
+            if($count > 0) {
281
+                return false;
282
+            }
283
+            $writeLog = true;
284
+        } else {
285
+            $writeLog = false;
286
+        }
287
+
288
+        $emailAttributes = array('mail', 'mailPrimaryAddress');
289
+        $winner = '';
290
+        $maxUsers = 0;
291
+        foreach($emailAttributes as $attr) {
292
+            $count = $this->countUsersWithAttribute($attr);
293
+            if($count > $maxUsers) {
294
+                $maxUsers = $count;
295
+                $winner = $attr;
296
+            }
297
+        }
298
+
299
+        if($winner !== '') {
300
+            $this->applyFind('ldap_email_attr', $winner);
301
+            if($writeLog) {
302
+                \OCP\Util::writeLog('user_ldap', 'The mail attribute has ' .
303
+                    'automatically been reset, because the original value ' .
304
+                    'did not return any results.', \OCP\Util::INFO);
305
+            }
306
+        }
307
+
308
+        return $this->result;
309
+    }
310
+
311
+    /**
312
+     * @return WizardResult
313
+     * @throws \Exception
314
+     */
315
+    public function determineAttributes() {
316
+        if(!$this->checkRequirements(array('ldapHost',
317
+                                            'ldapPort',
318
+                                            'ldapBase',
319
+                                            'ldapUserFilter',
320
+                                            ))) {
321
+            return  false;
322
+        }
323
+
324
+        $attributes = $this->getUserAttributes();
325
+
326
+        natcasesort($attributes);
327
+        $attributes = array_values($attributes);
328
+
329
+        $this->result->addOptions('ldap_loginfilter_attributes', $attributes);
330
+
331
+        $selected = $this->configuration->ldapLoginFilterAttributes;
332
+        if(is_array($selected) && !empty($selected)) {
333
+            $this->result->addChange('ldap_loginfilter_attributes', $selected);
334
+        }
335
+
336
+        return $this->result;
337
+    }
338
+
339
+    /**
340
+     * detects the available LDAP attributes
341
+     * @return array|false The instance's WizardResult instance
342
+     * @throws \Exception
343
+     */
344
+    private function getUserAttributes() {
345
+        if(!$this->checkRequirements(array('ldapHost',
346
+                                            'ldapPort',
347
+                                            'ldapBase',
348
+                                            'ldapUserFilter',
349
+                                            ))) {
350
+            return  false;
351
+        }
352
+        $cr = $this->getConnection();
353
+        if(!$cr) {
354
+            throw new \Exception('Could not connect to LDAP');
355
+        }
356
+
357
+        $base = $this->configuration->ldapBase[0];
358
+        $filter = $this->configuration->ldapUserFilter;
359
+        $rr = $this->ldap->search($cr, $base, $filter, array(), 1, 1);
360
+        if(!$this->ldap->isResource($rr)) {
361
+            return false;
362
+        }
363
+        $er = $this->ldap->firstEntry($cr, $rr);
364
+        $attributes = $this->ldap->getAttributes($cr, $er);
365
+        $pureAttributes = array();
366
+        for($i = 0; $i < $attributes['count']; $i++) {
367
+            $pureAttributes[] = $attributes[$i];
368
+        }
369
+
370
+        return $pureAttributes;
371
+    }
372
+
373
+    /**
374
+     * detects the available LDAP groups
375
+     * @return WizardResult|false the instance's WizardResult instance
376
+     */
377
+    public function determineGroupsForGroups() {
378
+        return $this->determineGroups('ldap_groupfilter_groups',
379
+                                        'ldapGroupFilterGroups',
380
+                                        false);
381
+    }
382
+
383
+    /**
384
+     * detects the available LDAP groups
385
+     * @return WizardResult|false the instance's WizardResult instance
386
+     */
387
+    public function determineGroupsForUsers() {
388
+        return $this->determineGroups('ldap_userfilter_groups',
389
+                                        'ldapUserFilterGroups');
390
+    }
391
+
392
+    /**
393
+     * detects the available LDAP groups
394
+     * @param string $dbKey
395
+     * @param string $confKey
396
+     * @param bool $testMemberOf
397
+     * @return WizardResult|false the instance's WizardResult instance
398
+     * @throws \Exception
399
+     */
400
+    private function determineGroups($dbKey, $confKey, $testMemberOf = true) {
401
+        if(!$this->checkRequirements(array('ldapHost',
402
+                                            'ldapPort',
403
+                                            'ldapBase',
404
+                                            ))) {
405
+            return  false;
406
+        }
407
+        $cr = $this->getConnection();
408
+        if(!$cr) {
409
+            throw new \Exception('Could not connect to LDAP');
410
+        }
411
+
412
+        $this->fetchGroups($dbKey, $confKey);
413
+
414
+        if($testMemberOf) {
415
+            $this->configuration->hasMemberOfFilterSupport = $this->testMemberOf();
416
+            $this->result->markChange();
417
+            if(!$this->configuration->hasMemberOfFilterSupport) {
418
+                throw new \Exception('memberOf is not supported by the server');
419
+            }
420
+        }
421
+
422
+        return $this->result;
423
+    }
424
+
425
+    /**
426
+     * fetches all groups from LDAP and adds them to the result object
427
+     *
428
+     * @param string $dbKey
429
+     * @param string $confKey
430
+     * @return array $groupEntries
431
+     * @throws \Exception
432
+     */
433
+    public function fetchGroups($dbKey, $confKey) {
434
+        $obclasses = array('posixGroup', 'group', 'zimbraDistributionList', 'groupOfNames', 'groupOfUniqueNames');
435
+
436
+        $filterParts = array();
437
+        foreach($obclasses as $obclass) {
438
+            $filterParts[] = 'objectclass='.$obclass;
439
+        }
440
+        //we filter for everything
441
+        //- that looks like a group and
442
+        //- has the group display name set
443
+        $filter = $this->access->combineFilterWithOr($filterParts);
444
+        $filter = $this->access->combineFilterWithAnd(array($filter, 'cn=*'));
445
+
446
+        $groupNames = array();
447
+        $groupEntries = array();
448
+        $limit = 400;
449
+        $offset = 0;
450
+        do {
451
+            // we need to request dn additionally here, otherwise memberOf
452
+            // detection will fail later
453
+            $result = $this->access->searchGroups($filter, array('cn', 'dn'), $limit, $offset);
454
+            foreach($result as $item) {
455
+                if(!isset($item['cn']) && !is_array($item['cn']) && !isset($item['cn'][0])) {
456
+                    // just in case - no issue known
457
+                    continue;
458
+                }
459
+                $groupNames[] = $item['cn'][0];
460
+                $groupEntries[] = $item;
461
+            }
462
+            $offset += $limit;
463
+        } while ($this->access->hasMoreResults());
464
+
465
+        if(count($groupNames) > 0) {
466
+            natsort($groupNames);
467
+            $this->result->addOptions($dbKey, array_values($groupNames));
468
+        } else {
469
+            throw new \Exception(self::$l->t('Could not find the desired feature'));
470
+        }
471
+
472
+        $setFeatures = $this->configuration->$confKey;
473
+        if(is_array($setFeatures) && !empty($setFeatures)) {
474
+            //something is already configured? pre-select it.
475
+            $this->result->addChange($dbKey, $setFeatures);
476
+        }
477
+        return $groupEntries;
478
+    }
479
+
480
+    public function determineGroupMemberAssoc() {
481
+        if(!$this->checkRequirements(array('ldapHost',
482
+                                            'ldapPort',
483
+                                            'ldapGroupFilter',
484
+                                            ))) {
485
+            return  false;
486
+        }
487
+        $attribute = $this->detectGroupMemberAssoc();
488
+        if($attribute === false) {
489
+            return false;
490
+        }
491
+        $this->configuration->setConfiguration(array('ldapGroupMemberAssocAttr' => $attribute));
492
+        $this->result->addChange('ldap_group_member_assoc_attribute', $attribute);
493
+
494
+        return $this->result;
495
+    }
496
+
497
+    /**
498
+     * Detects the available object classes
499
+     * @return WizardResult|false the instance's WizardResult instance
500
+     * @throws \Exception
501
+     */
502
+    public function determineGroupObjectClasses() {
503
+        if(!$this->checkRequirements(array('ldapHost',
504
+                                            'ldapPort',
505
+                                            'ldapBase',
506
+                                            ))) {
507
+            return  false;
508
+        }
509
+        $cr = $this->getConnection();
510
+        if(!$cr) {
511
+            throw new \Exception('Could not connect to LDAP');
512
+        }
513
+
514
+        $obclasses = array('groupOfNames', 'groupOfUniqueNames', 'group', 'posixGroup', '*');
515
+        $this->determineFeature($obclasses,
516
+                                'objectclass',
517
+                                'ldap_groupfilter_objectclass',
518
+                                'ldapGroupFilterObjectclass',
519
+                                false);
520
+
521
+        return $this->result;
522
+    }
523
+
524
+    /**
525
+     * detects the available object classes
526
+     * @return WizardResult
527
+     * @throws \Exception
528
+     */
529
+    public function determineUserObjectClasses() {
530
+        if(!$this->checkRequirements(array('ldapHost',
531
+                                            'ldapPort',
532
+                                            'ldapBase',
533
+                                            ))) {
534
+            return  false;
535
+        }
536
+        $cr = $this->getConnection();
537
+        if(!$cr) {
538
+            throw new \Exception('Could not connect to LDAP');
539
+        }
540
+
541
+        $obclasses = array('inetOrgPerson', 'person', 'organizationalPerson',
542
+                            'user', 'posixAccount', '*');
543
+        $filter = $this->configuration->ldapUserFilter;
544
+        //if filter is empty, it is probably the first time the wizard is called
545
+        //then, apply suggestions.
546
+        $this->determineFeature($obclasses,
547
+                                'objectclass',
548
+                                'ldap_userfilter_objectclass',
549
+                                'ldapUserFilterObjectclass',
550
+                                empty($filter));
551
+
552
+        return $this->result;
553
+    }
554
+
555
+    /**
556
+     * @return WizardResult|false
557
+     * @throws \Exception
558
+     */
559
+    public function getGroupFilter() {
560
+        if(!$this->checkRequirements(array('ldapHost',
561
+                                            'ldapPort',
562
+                                            'ldapBase',
563
+                                            ))) {
564
+            return false;
565
+        }
566
+        //make sure the use display name is set
567
+        $displayName = $this->configuration->ldapGroupDisplayName;
568
+        if ($displayName === '') {
569
+            $d = $this->configuration->getDefaults();
570
+            $this->applyFind('ldap_group_display_name',
571
+                                $d['ldap_group_display_name']);
572
+        }
573
+        $filter = $this->composeLdapFilter(self::LFILTER_GROUP_LIST);
574
+
575
+        $this->applyFind('ldap_group_filter', $filter);
576
+        return $this->result;
577
+    }
578
+
579
+    /**
580
+     * @return WizardResult|false
581
+     * @throws \Exception
582
+     */
583
+    public function getUserListFilter() {
584
+        if(!$this->checkRequirements(array('ldapHost',
585
+                                            'ldapPort',
586
+                                            'ldapBase',
587
+                                            ))) {
588
+            return false;
589
+        }
590
+        //make sure the use display name is set
591
+        $displayName = $this->configuration->ldapUserDisplayName;
592
+        if ($displayName === '') {
593
+            $d = $this->configuration->getDefaults();
594
+            $this->applyFind('ldap_display_name', $d['ldap_display_name']);
595
+        }
596
+        $filter = $this->composeLdapFilter(self::LFILTER_USER_LIST);
597
+        if(!$filter) {
598
+            throw new \Exception('Cannot create filter');
599
+        }
600
+
601
+        $this->applyFind('ldap_userlist_filter', $filter);
602
+        return $this->result;
603
+    }
604
+
605
+    /**
606
+     * @return bool|WizardResult
607
+     * @throws \Exception
608
+     */
609
+    public function getUserLoginFilter() {
610
+        if(!$this->checkRequirements(array('ldapHost',
611
+                                            'ldapPort',
612
+                                            'ldapBase',
613
+                                            'ldapUserFilter',
614
+                                            ))) {
615
+            return false;
616
+        }
617
+
618
+        $filter = $this->composeLdapFilter(self::LFILTER_LOGIN);
619
+        if(!$filter) {
620
+            throw new \Exception('Cannot create filter');
621
+        }
622
+
623
+        $this->applyFind('ldap_login_filter', $filter);
624
+        return $this->result;
625
+    }
626
+
627
+    /**
628
+     * @return bool|WizardResult
629
+     * @param string $loginName
630
+     * @throws \Exception
631
+     */
632
+    public function testLoginName($loginName) {
633
+        if(!$this->checkRequirements(array('ldapHost',
634
+            'ldapPort',
635
+            'ldapBase',
636
+            'ldapLoginFilter',
637
+        ))) {
638
+            return false;
639
+        }
640
+
641
+        $cr = $this->access->connection->getConnectionResource();
642
+        if(!$this->ldap->isResource($cr)) {
643
+            throw new \Exception('connection error');
644
+        }
645
+
646
+        if(mb_strpos($this->access->connection->ldapLoginFilter, '%uid', 0, 'UTF-8')
647
+            === false) {
648
+            throw new \Exception('missing placeholder');
649
+        }
650
+
651
+        $users = $this->access->countUsersByLoginName($loginName);
652
+        if($this->ldap->errno($cr) !== 0) {
653
+            throw new \Exception($this->ldap->error($cr));
654
+        }
655
+        $filter = str_replace('%uid', $loginName, $this->access->connection->ldapLoginFilter);
656
+        $this->result->addChange('ldap_test_loginname', $users);
657
+        $this->result->addChange('ldap_test_effective_filter', $filter);
658
+        return $this->result;
659
+    }
660
+
661
+    /**
662
+     * Tries to determine the port, requires given Host, User DN and Password
663
+     * @return WizardResult|false WizardResult on success, false otherwise
664
+     * @throws \Exception
665
+     */
666
+    public function guessPortAndTLS() {
667
+        if(!$this->checkRequirements(array('ldapHost',
668
+                                            ))) {
669
+            return false;
670
+        }
671
+        $this->checkHost();
672
+        $portSettings = $this->getPortSettingsToTry();
673
+
674
+        if(!is_array($portSettings)) {
675
+            throw new \Exception(print_r($portSettings, true));
676
+        }
677
+
678
+        //proceed from the best configuration and return on first success
679
+        foreach($portSettings as $setting) {
680
+            $p = $setting['port'];
681
+            $t = $setting['tls'];
682
+            \OCP\Util::writeLog('user_ldap', 'Wiz: trying port '. $p . ', TLS '. $t, \OCP\Util::DEBUG);
683
+            //connectAndBind may throw Exception, it needs to be catched by the
684
+            //callee of this method
685
+
686
+            try {
687
+                $settingsFound = $this->connectAndBind($p, $t);
688
+            } catch (\Exception $e) {
689
+                // any reply other than -1 (= cannot connect) is already okay,
690
+                // because then we found the server
691
+                // unavailable startTLS returns -11
692
+                if($e->getCode() > 0) {
693
+                    $settingsFound = true;
694
+                } else {
695
+                    throw $e;
696
+                }
697
+            }
698
+
699
+            if ($settingsFound === true) {
700
+                $config = array(
701
+                    'ldapPort' => $p,
702
+                    'ldapTLS' => (int)$t
703
+                );
704
+                $this->configuration->setConfiguration($config);
705
+                \OCP\Util::writeLog('user_ldap', 'Wiz: detected Port ' . $p, \OCP\Util::DEBUG);
706
+                $this->result->addChange('ldap_port', $p);
707
+                return $this->result;
708
+            }
709
+        }
710
+
711
+        //custom port, undetected (we do not brute force)
712
+        return false;
713
+    }
714
+
715
+    /**
716
+     * tries to determine a base dn from User DN or LDAP Host
717
+     * @return WizardResult|false WizardResult on success, false otherwise
718
+     */
719
+    public function guessBaseDN() {
720
+        if(!$this->checkRequirements(array('ldapHost',
721
+                                            'ldapPort',
722
+                                            ))) {
723
+            return false;
724
+        }
725
+
726
+        //check whether a DN is given in the agent name (99.9% of all cases)
727
+        $base = null;
728
+        $i = stripos($this->configuration->ldapAgentName, 'dc=');
729
+        if($i !== false) {
730
+            $base = substr($this->configuration->ldapAgentName, $i);
731
+            if($this->testBaseDN($base)) {
732
+                $this->applyFind('ldap_base', $base);
733
+                return $this->result;
734
+            }
735
+        }
736
+
737
+        //this did not help :(
738
+        //Let's see whether we can parse the Host URL and convert the domain to
739
+        //a base DN
740
+        $helper = new Helper(\OC::$server->getConfig());
741
+        $domain = $helper->getDomainFromURL($this->configuration->ldapHost);
742
+        if(!$domain) {
743
+            return false;
744
+        }
745
+
746
+        $dparts = explode('.', $domain);
747
+        while(count($dparts) > 0) {
748
+            $base2 = 'dc=' . implode(',dc=', $dparts);
749
+            if ($base !== $base2 && $this->testBaseDN($base2)) {
750
+                $this->applyFind('ldap_base', $base2);
751
+                return $this->result;
752
+            }
753
+            array_shift($dparts);
754
+        }
755
+
756
+        return false;
757
+    }
758
+
759
+    /**
760
+     * sets the found value for the configuration key in the WizardResult
761
+     * as well as in the Configuration instance
762
+     * @param string $key the configuration key
763
+     * @param string $value the (detected) value
764
+     *
765
+     */
766
+    private function applyFind($key, $value) {
767
+        $this->result->addChange($key, $value);
768
+        $this->configuration->setConfiguration(array($key => $value));
769
+    }
770
+
771
+    /**
772
+     * Checks, whether a port was entered in the Host configuration
773
+     * field. In this case the port will be stripped off, but also stored as
774
+     * setting.
775
+     */
776
+    private function checkHost() {
777
+        $host = $this->configuration->ldapHost;
778
+        $hostInfo = parse_url($host);
779
+
780
+        //removes Port from Host
781
+        if(is_array($hostInfo) && isset($hostInfo['port'])) {
782
+            $port = $hostInfo['port'];
783
+            $host = str_replace(':'.$port, '', $host);
784
+            $this->applyFind('ldap_host', $host);
785
+            $this->applyFind('ldap_port', $port);
786
+        }
787
+    }
788
+
789
+    /**
790
+     * tries to detect the group member association attribute which is
791
+     * one of 'uniqueMember', 'memberUid', 'member', 'gidNumber'
792
+     * @return string|false, string with the attribute name, false on error
793
+     * @throws \Exception
794
+     */
795
+    private function detectGroupMemberAssoc() {
796
+        $possibleAttrs = array('uniqueMember', 'memberUid', 'member', 'gidNumber');
797
+        $filter = $this->configuration->ldapGroupFilter;
798
+        if(empty($filter)) {
799
+            return false;
800
+        }
801
+        $cr = $this->getConnection();
802
+        if(!$cr) {
803
+            throw new \Exception('Could not connect to LDAP');
804
+        }
805
+        $base = $this->configuration->ldapBase[0];
806
+        $rr = $this->ldap->search($cr, $base, $filter, $possibleAttrs, 0, 1000);
807
+        if(!$this->ldap->isResource($rr)) {
808
+            return false;
809
+        }
810
+        $er = $this->ldap->firstEntry($cr, $rr);
811
+        while(is_resource($er)) {
812
+            $this->ldap->getDN($cr, $er);
813
+            $attrs = $this->ldap->getAttributes($cr, $er);
814
+            $result = array();
815
+            $possibleAttrsCount = count($possibleAttrs);
816
+            for($i = 0; $i < $possibleAttrsCount; $i++) {
817
+                if(isset($attrs[$possibleAttrs[$i]])) {
818
+                    $result[$possibleAttrs[$i]] = $attrs[$possibleAttrs[$i]]['count'];
819
+                }
820
+            }
821
+            if(!empty($result)) {
822
+                natsort($result);
823
+                return key($result);
824
+            }
825
+
826
+            $er = $this->ldap->nextEntry($cr, $er);
827
+        }
828
+
829
+        return false;
830
+    }
831
+
832
+    /**
833
+     * Checks whether for a given BaseDN results will be returned
834
+     * @param string $base the BaseDN to test
835
+     * @return bool true on success, false otherwise
836
+     * @throws \Exception
837
+     */
838
+    private function testBaseDN($base) {
839
+        $cr = $this->getConnection();
840
+        if(!$cr) {
841
+            throw new \Exception('Could not connect to LDAP');
842
+        }
843
+
844
+        //base is there, let's validate it. If we search for anything, we should
845
+        //get a result set > 0 on a proper base
846
+        $rr = $this->ldap->search($cr, $base, 'objectClass=*', array('dn'), 0, 1);
847
+        if(!$this->ldap->isResource($rr)) {
848
+            $errorNo  = $this->ldap->errno($cr);
849
+            $errorMsg = $this->ldap->error($cr);
850
+            \OCP\Util::writeLog('user_ldap', 'Wiz: Could not search base '.$base.
851
+                            ' Error '.$errorNo.': '.$errorMsg, \OCP\Util::INFO);
852
+            return false;
853
+        }
854
+        $entries = $this->ldap->countEntries($cr, $rr);
855
+        return ($entries !== false) && ($entries > 0);
856
+    }
857
+
858
+    /**
859
+     * Checks whether the server supports memberOf in LDAP Filter.
860
+     * Note: at least in OpenLDAP, availability of memberOf is dependent on
861
+     * a configured objectClass. I.e. not necessarily for all available groups
862
+     * memberOf does work.
863
+     *
864
+     * @return bool true if it does, false otherwise
865
+     * @throws \Exception
866
+     */
867
+    private function testMemberOf() {
868
+        $cr = $this->getConnection();
869
+        if(!$cr) {
870
+            throw new \Exception('Could not connect to LDAP');
871
+        }
872
+        $result = $this->access->countUsers('memberOf=*', array('memberOf'), 1);
873
+        if(is_int($result) &&  $result > 0) {
874
+            return true;
875
+        }
876
+        return false;
877
+    }
878
+
879
+    /**
880
+     * creates an LDAP Filter from given configuration
881
+     * @param integer $filterType int, for which use case the filter shall be created
882
+     * can be any of self::LFILTER_USER_LIST, self::LFILTER_LOGIN or
883
+     * self::LFILTER_GROUP_LIST
884
+     * @return string|false string with the filter on success, false otherwise
885
+     * @throws \Exception
886
+     */
887
+    private function composeLdapFilter($filterType) {
888
+        $filter = '';
889
+        $parts = 0;
890
+        switch ($filterType) {
891
+            case self::LFILTER_USER_LIST:
892
+                $objcs = $this->configuration->ldapUserFilterObjectclass;
893
+                //glue objectclasses
894
+                if(is_array($objcs) && count($objcs) > 0) {
895
+                    $filter .= '(|';
896
+                    foreach($objcs as $objc) {
897
+                        $filter .= '(objectclass=' . $objc . ')';
898
+                    }
899
+                    $filter .= ')';
900
+                    $parts++;
901
+                }
902
+                //glue group memberships
903
+                if($this->configuration->hasMemberOfFilterSupport) {
904
+                    $cns = $this->configuration->ldapUserFilterGroups;
905
+                    if(is_array($cns) && count($cns) > 0) {
906
+                        $filter .= '(|';
907
+                        $cr = $this->getConnection();
908
+                        if(!$cr) {
909
+                            throw new \Exception('Could not connect to LDAP');
910
+                        }
911
+                        $base = $this->configuration->ldapBase[0];
912
+                        foreach($cns as $cn) {
913
+                            $rr = $this->ldap->search($cr, $base, 'cn=' . $cn, array('dn', 'primaryGroupToken'));
914
+                            if(!$this->ldap->isResource($rr)) {
915
+                                continue;
916
+                            }
917
+                            $er = $this->ldap->firstEntry($cr, $rr);
918
+                            $attrs = $this->ldap->getAttributes($cr, $er);
919
+                            $dn = $this->ldap->getDN($cr, $er);
920
+                            if ($dn === false || $dn === '') {
921
+                                continue;
922
+                            }
923
+                            $filterPart = '(memberof=' . $dn . ')';
924
+                            if(isset($attrs['primaryGroupToken'])) {
925
+                                $pgt = $attrs['primaryGroupToken'][0];
926
+                                $primaryFilterPart = '(primaryGroupID=' . $pgt .')';
927
+                                $filterPart = '(|' . $filterPart . $primaryFilterPart . ')';
928
+                            }
929
+                            $filter .= $filterPart;
930
+                        }
931
+                        $filter .= ')';
932
+                    }
933
+                    $parts++;
934
+                }
935
+                //wrap parts in AND condition
936
+                if($parts > 1) {
937
+                    $filter = '(&' . $filter . ')';
938
+                }
939
+                if ($filter === '') {
940
+                    $filter = '(objectclass=*)';
941
+                }
942
+                break;
943
+
944
+            case self::LFILTER_GROUP_LIST:
945
+                $objcs = $this->configuration->ldapGroupFilterObjectclass;
946
+                //glue objectclasses
947
+                if(is_array($objcs) && count($objcs) > 0) {
948
+                    $filter .= '(|';
949
+                    foreach($objcs as $objc) {
950
+                        $filter .= '(objectclass=' . $objc . ')';
951
+                    }
952
+                    $filter .= ')';
953
+                    $parts++;
954
+                }
955
+                //glue group memberships
956
+                $cns = $this->configuration->ldapGroupFilterGroups;
957
+                if(is_array($cns) && count($cns) > 0) {
958
+                    $filter .= '(|';
959
+                    foreach($cns as $cn) {
960
+                        $filter .= '(cn=' . $cn . ')';
961
+                    }
962
+                    $filter .= ')';
963
+                }
964
+                $parts++;
965
+                //wrap parts in AND condition
966
+                if($parts > 1) {
967
+                    $filter = '(&' . $filter . ')';
968
+                }
969
+                break;
970
+
971
+            case self::LFILTER_LOGIN:
972
+                $ulf = $this->configuration->ldapUserFilter;
973
+                $loginpart = '=%uid';
974
+                $filterUsername = '';
975
+                $userAttributes = $this->getUserAttributes();
976
+                $userAttributes = array_change_key_case(array_flip($userAttributes));
977
+                $parts = 0;
978
+
979
+                if($this->configuration->ldapLoginFilterUsername === '1') {
980
+                    $attr = '';
981
+                    if(isset($userAttributes['uid'])) {
982
+                        $attr = 'uid';
983
+                    } else if(isset($userAttributes['samaccountname'])) {
984
+                        $attr = 'samaccountname';
985
+                    } else if(isset($userAttributes['cn'])) {
986
+                        //fallback
987
+                        $attr = 'cn';
988
+                    }
989
+                    if ($attr !== '') {
990
+                        $filterUsername = '(' . $attr . $loginpart . ')';
991
+                        $parts++;
992
+                    }
993
+                }
994
+
995
+                $filterEmail = '';
996
+                if($this->configuration->ldapLoginFilterEmail === '1') {
997
+                    $filterEmail = '(|(mailPrimaryAddress=%uid)(mail=%uid))';
998
+                    $parts++;
999
+                }
1000
+
1001
+                $filterAttributes = '';
1002
+                $attrsToFilter = $this->configuration->ldapLoginFilterAttributes;
1003
+                if(is_array($attrsToFilter) && count($attrsToFilter) > 0) {
1004
+                    $filterAttributes = '(|';
1005
+                    foreach($attrsToFilter as $attribute) {
1006
+                        $filterAttributes .= '(' . $attribute . $loginpart . ')';
1007
+                    }
1008
+                    $filterAttributes .= ')';
1009
+                    $parts++;
1010
+                }
1011
+
1012
+                $filterLogin = '';
1013
+                if($parts > 1) {
1014
+                    $filterLogin = '(|';
1015
+                }
1016
+                $filterLogin .= $filterUsername;
1017
+                $filterLogin .= $filterEmail;
1018
+                $filterLogin .= $filterAttributes;
1019
+                if($parts > 1) {
1020
+                    $filterLogin .= ')';
1021
+                }
1022
+
1023
+                $filter = '(&'.$ulf.$filterLogin.')';
1024
+                break;
1025
+        }
1026
+
1027
+        \OCP\Util::writeLog('user_ldap', 'Wiz: Final filter '.$filter, \OCP\Util::DEBUG);
1028
+
1029
+        return $filter;
1030
+    }
1031
+
1032
+    /**
1033
+     * Connects and Binds to an LDAP Server
1034
+     *
1035
+     * @param int $port the port to connect with
1036
+     * @param bool $tls whether startTLS is to be used
1037
+     * @return bool
1038
+     * @throws \Exception
1039
+     */
1040
+    private function connectAndBind($port, $tls) {
1041
+        //connect, does not really trigger any server communication
1042
+        $host = $this->configuration->ldapHost;
1043
+        $hostInfo = parse_url($host);
1044
+        if(!$hostInfo) {
1045
+            throw new \Exception(self::$l->t('Invalid Host'));
1046
+        }
1047
+        \OCP\Util::writeLog('user_ldap', 'Wiz: Attempting to connect ', \OCP\Util::DEBUG);
1048
+        $cr = $this->ldap->connect($host, $port);
1049
+        if(!is_resource($cr)) {
1050
+            throw new \Exception(self::$l->t('Invalid Host'));
1051
+        }
1052
+
1053
+        //set LDAP options
1054
+        $this->ldap->setOption($cr, LDAP_OPT_PROTOCOL_VERSION, 3);
1055
+        $this->ldap->setOption($cr, LDAP_OPT_REFERRALS, 0);
1056
+        $this->ldap->setOption($cr, LDAP_OPT_NETWORK_TIMEOUT, self::LDAP_NW_TIMEOUT);
1057
+
1058
+        try {
1059
+            if($tls) {
1060
+                $isTlsWorking = @$this->ldap->startTls($cr);
1061
+                if(!$isTlsWorking) {
1062
+                    return false;
1063
+                }
1064
+            }
1065
+
1066
+            \OCP\Util::writeLog('user_ldap', 'Wiz: Attemping to Bind ', \OCP\Util::DEBUG);
1067
+            //interesting part: do the bind!
1068
+            $login = $this->ldap->bind($cr,
1069
+                $this->configuration->ldapAgentName,
1070
+                $this->configuration->ldapAgentPassword
1071
+            );
1072
+            $errNo = $this->ldap->errno($cr);
1073
+            $error = ldap_error($cr);
1074
+            $this->ldap->unbind($cr);
1075
+        } catch(ServerNotAvailableException $e) {
1076
+            return false;
1077
+        }
1078
+
1079
+        if($login === true) {
1080
+            $this->ldap->unbind($cr);
1081
+            \OCP\Util::writeLog('user_ldap', 'Wiz: Bind successful to Port '. $port . ' TLS ' . (int)$tls, \OCP\Util::DEBUG);
1082
+            return true;
1083
+        }
1084
+
1085
+        if($errNo === -1) {
1086
+            //host, port or TLS wrong
1087
+            return false;
1088
+        }
1089
+        throw new \Exception($error, $errNo);
1090
+    }
1091
+
1092
+    /**
1093
+     * checks whether a valid combination of agent and password has been
1094
+     * provided (either two values or nothing for anonymous connect)
1095
+     * @return bool, true if everything is fine, false otherwise
1096
+     */
1097
+    private function checkAgentRequirements() {
1098
+        $agent = $this->configuration->ldapAgentName;
1099
+        $pwd = $this->configuration->ldapAgentPassword;
1100
+
1101
+        return
1102
+            ($agent !== '' && $pwd !== '')
1103
+            ||  ($agent === '' && $pwd === '')
1104
+        ;
1105
+    }
1106
+
1107
+    /**
1108
+     * @param array $reqs
1109
+     * @return bool
1110
+     */
1111
+    private function checkRequirements($reqs) {
1112
+        $this->checkAgentRequirements();
1113
+        foreach($reqs as $option) {
1114
+            $value = $this->configuration->$option;
1115
+            if(empty($value)) {
1116
+                return false;
1117
+            }
1118
+        }
1119
+        return true;
1120
+    }
1121
+
1122
+    /**
1123
+     * does a cumulativeSearch on LDAP to get different values of a
1124
+     * specified attribute
1125
+     * @param string[] $filters array, the filters that shall be used in the search
1126
+     * @param string $attr the attribute of which a list of values shall be returned
1127
+     * @param int $dnReadLimit the amount of how many DNs should be analyzed.
1128
+     * The lower, the faster
1129
+     * @param string $maxF string. if not null, this variable will have the filter that
1130
+     * yields most result entries
1131
+     * @return array|false an array with the values on success, false otherwise
1132
+     */
1133
+    public function cumulativeSearchOnAttribute($filters, $attr, $dnReadLimit = 3, &$maxF = null) {
1134
+        $dnRead = array();
1135
+        $foundItems = array();
1136
+        $maxEntries = 0;
1137
+        if(!is_array($this->configuration->ldapBase)
1138
+           || !isset($this->configuration->ldapBase[0])) {
1139
+            return false;
1140
+        }
1141
+        $base = $this->configuration->ldapBase[0];
1142
+        $cr = $this->getConnection();
1143
+        if(!$this->ldap->isResource($cr)) {
1144
+            return false;
1145
+        }
1146
+        $lastFilter = null;
1147
+        if(isset($filters[count($filters)-1])) {
1148
+            $lastFilter = $filters[count($filters)-1];
1149
+        }
1150
+        foreach($filters as $filter) {
1151
+            if($lastFilter === $filter && count($foundItems) > 0) {
1152
+                //skip when the filter is a wildcard and results were found
1153
+                continue;
1154
+            }
1155
+            // 20k limit for performance and reason
1156
+            $rr = $this->ldap->search($cr, $base, $filter, array($attr), 0, 20000);
1157
+            if(!$this->ldap->isResource($rr)) {
1158
+                continue;
1159
+            }
1160
+            $entries = $this->ldap->countEntries($cr, $rr);
1161
+            $getEntryFunc = 'firstEntry';
1162
+            if(($entries !== false) && ($entries > 0)) {
1163
+                if(!is_null($maxF) && $entries > $maxEntries) {
1164
+                    $maxEntries = $entries;
1165
+                    $maxF = $filter;
1166
+                }
1167
+                $dnReadCount = 0;
1168
+                do {
1169
+                    $entry = $this->ldap->$getEntryFunc($cr, $rr);
1170
+                    $getEntryFunc = 'nextEntry';
1171
+                    if(!$this->ldap->isResource($entry)) {
1172
+                        continue 2;
1173
+                    }
1174
+                    $rr = $entry; //will be expected by nextEntry next round
1175
+                    $attributes = $this->ldap->getAttributes($cr, $entry);
1176
+                    $dn = $this->ldap->getDN($cr, $entry);
1177
+                    if($dn === false || in_array($dn, $dnRead)) {
1178
+                        continue;
1179
+                    }
1180
+                    $newItems = array();
1181
+                    $state = $this->getAttributeValuesFromEntry($attributes,
1182
+                                                                $attr,
1183
+                                                                $newItems);
1184
+                    $dnReadCount++;
1185
+                    $foundItems = array_merge($foundItems, $newItems);
1186
+                    $this->resultCache[$dn][$attr] = $newItems;
1187
+                    $dnRead[] = $dn;
1188
+                } while(($state === self::LRESULT_PROCESSED_SKIP
1189
+                        || $this->ldap->isResource($entry))
1190
+                        && ($dnReadLimit === 0 || $dnReadCount < $dnReadLimit));
1191
+            }
1192
+        }
1193
+
1194
+        return array_unique($foundItems);
1195
+    }
1196
+
1197
+    /**
1198
+     * determines if and which $attr are available on the LDAP server
1199
+     * @param string[] $objectclasses the objectclasses to use as search filter
1200
+     * @param string $attr the attribute to look for
1201
+     * @param string $dbkey the dbkey of the setting the feature is connected to
1202
+     * @param string $confkey the confkey counterpart for the $dbkey as used in the
1203
+     * Configuration class
1204
+     * @param bool $po whether the objectClass with most result entries
1205
+     * shall be pre-selected via the result
1206
+     * @return array|false list of found items.
1207
+     * @throws \Exception
1208
+     */
1209
+    private function determineFeature($objectclasses, $attr, $dbkey, $confkey, $po = false) {
1210
+        $cr = $this->getConnection();
1211
+        if(!$cr) {
1212
+            throw new \Exception('Could not connect to LDAP');
1213
+        }
1214
+        $p = 'objectclass=';
1215
+        foreach($objectclasses as $key => $value) {
1216
+            $objectclasses[$key] = $p.$value;
1217
+        }
1218
+        $maxEntryObjC = '';
1219
+
1220
+        //how deep to dig?
1221
+        //When looking for objectclasses, testing few entries is sufficient,
1222
+        $dig = 3;
1223
+
1224
+        $availableFeatures =
1225
+            $this->cumulativeSearchOnAttribute($objectclasses, $attr,
1226
+                                                $dig, $maxEntryObjC);
1227
+        if(is_array($availableFeatures)
1228
+           && count($availableFeatures) > 0) {
1229
+            natcasesort($availableFeatures);
1230
+            //natcasesort keeps indices, but we must get rid of them for proper
1231
+            //sorting in the web UI. Therefore: array_values
1232
+            $this->result->addOptions($dbkey, array_values($availableFeatures));
1233
+        } else {
1234
+            throw new \Exception(self::$l->t('Could not find the desired feature'));
1235
+        }
1236
+
1237
+        $setFeatures = $this->configuration->$confkey;
1238
+        if(is_array($setFeatures) && !empty($setFeatures)) {
1239
+            //something is already configured? pre-select it.
1240
+            $this->result->addChange($dbkey, $setFeatures);
1241
+        } else if ($po && $maxEntryObjC !== '') {
1242
+            //pre-select objectclass with most result entries
1243
+            $maxEntryObjC = str_replace($p, '', $maxEntryObjC);
1244
+            $this->applyFind($dbkey, $maxEntryObjC);
1245
+            $this->result->addChange($dbkey, $maxEntryObjC);
1246
+        }
1247
+
1248
+        return $availableFeatures;
1249
+    }
1250
+
1251
+    /**
1252
+     * appends a list of values fr
1253
+     * @param resource $result the return value from ldap_get_attributes
1254
+     * @param string $attribute the attribute values to look for
1255
+     * @param array &$known new values will be appended here
1256
+     * @return int, state on of the class constants LRESULT_PROCESSED_OK,
1257
+     * LRESULT_PROCESSED_INVALID or LRESULT_PROCESSED_SKIP
1258
+     */
1259
+    private function getAttributeValuesFromEntry($result, $attribute, &$known) {
1260
+        if(!is_array($result)
1261
+           || !isset($result['count'])
1262
+           || !$result['count'] > 0) {
1263
+            return self::LRESULT_PROCESSED_INVALID;
1264
+        }
1265
+
1266
+        // strtolower on all keys for proper comparison
1267
+        $result = \OCP\Util::mb_array_change_key_case($result);
1268
+        $attribute = strtolower($attribute);
1269
+        if(isset($result[$attribute])) {
1270
+            foreach($result[$attribute] as $key => $val) {
1271
+                if($key === 'count') {
1272
+                    continue;
1273
+                }
1274
+                if(!in_array($val, $known)) {
1275
+                    $known[] = $val;
1276
+                }
1277
+            }
1278
+            return self::LRESULT_PROCESSED_OK;
1279
+        } else {
1280
+            return self::LRESULT_PROCESSED_SKIP;
1281
+        }
1282
+    }
1283
+
1284
+    /**
1285
+     * @return bool|mixed
1286
+     */
1287
+    private function getConnection() {
1288
+        if(!is_null($this->cr)) {
1289
+            return $this->cr;
1290
+        }
1291
+
1292
+        $cr = $this->ldap->connect(
1293
+            $this->configuration->ldapHost,
1294
+            $this->configuration->ldapPort
1295
+        );
1296
+
1297
+        $this->ldap->setOption($cr, LDAP_OPT_PROTOCOL_VERSION, 3);
1298
+        $this->ldap->setOption($cr, LDAP_OPT_REFERRALS, 0);
1299
+        $this->ldap->setOption($cr, LDAP_OPT_NETWORK_TIMEOUT, self::LDAP_NW_TIMEOUT);
1300
+        if($this->configuration->ldapTLS === 1) {
1301
+            $this->ldap->startTls($cr);
1302
+        }
1303
+
1304
+        $lo = @$this->ldap->bind($cr,
1305
+                                    $this->configuration->ldapAgentName,
1306
+                                    $this->configuration->ldapAgentPassword);
1307
+        if($lo === true) {
1308
+            $this->$cr = $cr;
1309
+            return $cr;
1310
+        }
1311
+
1312
+        return false;
1313
+    }
1314
+
1315
+    /**
1316
+     * @return array
1317
+     */
1318
+    private function getDefaultLdapPortSettings() {
1319
+        static $settings = array(
1320
+                                array('port' => 7636, 'tls' => false),
1321
+                                array('port' =>  636, 'tls' => false),
1322
+                                array('port' => 7389, 'tls' => true),
1323
+                                array('port' =>  389, 'tls' => true),
1324
+                                array('port' => 7389, 'tls' => false),
1325
+                                array('port' =>  389, 'tls' => false),
1326
+                            );
1327
+        return $settings;
1328
+    }
1329
+
1330
+    /**
1331
+     * @return array
1332
+     */
1333
+    private function getPortSettingsToTry() {
1334
+        //389 ← LDAP / Unencrypted or StartTLS
1335
+        //636 ← LDAPS / SSL
1336
+        //7xxx ← UCS. need to be checked first, because both ports may be open
1337
+        $host = $this->configuration->ldapHost;
1338
+        $port = (int)$this->configuration->ldapPort;
1339
+        $portSettings = array();
1340
+
1341
+        //In case the port is already provided, we will check this first
1342
+        if($port > 0) {
1343
+            $hostInfo = parse_url($host);
1344
+            if(!(is_array($hostInfo)
1345
+                && isset($hostInfo['scheme'])
1346
+                && stripos($hostInfo['scheme'], 'ldaps') !== false)) {
1347
+                $portSettings[] = array('port' => $port, 'tls' => true);
1348
+            }
1349
+            $portSettings[] =array('port' => $port, 'tls' => false);
1350
+        }
1351
+
1352
+        //default ports
1353
+        $portSettings = array_merge($portSettings,
1354
+                                    $this->getDefaultLdapPortSettings());
1355
+
1356
+        return $portSettings;
1357
+    }
1358 1358
 
1359 1359
 
1360 1360
 }
Please login to merge, or discard this patch.
Spacing   +156 added lines, -156 removed lines patch added patch discarded remove patch
@@ -71,7 +71,7 @@  discard block
 block discarded – undo
71 71
 	public function __construct(Configuration $configuration, ILDAPWrapper $ldap, Access $access) {
72 72
 		parent::__construct($ldap);
73 73
 		$this->configuration = $configuration;
74
-		if(is_null(Wizard::$l)) {
74
+		if (is_null(Wizard::$l)) {
75 75
 			Wizard::$l = \OC::$server->getL10N('user_ldap');
76 76
 		}
77 77
 		$this->access = $access;
@@ -79,7 +79,7 @@  discard block
 block discarded – undo
79 79
 	}
80 80
 
81 81
 	public function  __destruct() {
82
-		if($this->result->hasChanges()) {
82
+		if ($this->result->hasChanges()) {
83 83
 			$this->configuration->saveConfiguration();
84 84
 		}
85 85
 	}
@@ -94,18 +94,18 @@  discard block
 block discarded – undo
94 94
 	 */
95 95
 	public function countEntries(string $filter, string $type): int {
96 96
 		$reqs = ['ldapHost', 'ldapPort', 'ldapBase'];
97
-		if($type === 'users') {
97
+		if ($type === 'users') {
98 98
 			$reqs[] = 'ldapUserFilter';
99 99
 		}
100
-		if(!$this->checkRequirements($reqs)) {
100
+		if (!$this->checkRequirements($reqs)) {
101 101
 			throw new \Exception('Requirements not met', 400);
102 102
 		}
103 103
 
104 104
 		$attr = ['dn']; // default
105 105
 		$limit = 1001;
106
-		if($type === 'groups') {
107
-			$result =  $this->access->countGroups($filter, $attr, $limit);
108
-		} else if($type === 'users') {
106
+		if ($type === 'groups') {
107
+			$result = $this->access->countGroups($filter, $attr, $limit);
108
+		} else if ($type === 'users') {
109 109
 			$result = $this->access->countUsers($filter, $attr, $limit);
110 110
 		} else if ($type === 'objects') {
111 111
 			$result = $this->access->countObjects($limit);
@@ -113,7 +113,7 @@  discard block
 block discarded – undo
113 113
 			throw new \Exception('Internal error: Invalid object type', 500);
114 114
 		}
115 115
 
116
-		return (int)$result;
116
+		return (int) $result;
117 117
 	}
118 118
 
119 119
 	/**
@@ -124,16 +124,16 @@  discard block
 block discarded – undo
124 124
 	 * @return string
125 125
 	 */
126 126
 	private function formatCountResult(int $count): string {
127
-		if($count > 1000) {
127
+		if ($count > 1000) {
128 128
 			return '> 1000';
129 129
 		}
130
-		return (string)$count;
130
+		return (string) $count;
131 131
 	}
132 132
 
133 133
 	public function countGroups() {
134 134
 		$filter = $this->configuration->ldapGroupFilter;
135 135
 
136
-		if(empty($filter)) {
136
+		if (empty($filter)) {
137 137
 			$output = self::$l->n('%s group found', '%s groups found', 0, array(0));
138 138
 			$this->result->addChange('ldap_group_count', $output);
139 139
 			return $this->result;
@@ -143,7 +143,7 @@  discard block
 block discarded – undo
143 143
 			$groupsTotal = $this->countEntries($filter, 'groups');
144 144
 		} catch (\Exception $e) {
145 145
 			//400 can be ignored, 500 is forwarded
146
-			if($e->getCode() === 500) {
146
+			if ($e->getCode() === 500) {
147 147
 				throw $e;
148 148
 			}
149 149
 			return false;
@@ -185,7 +185,7 @@  discard block
 block discarded – undo
185 185
 	public function countInBaseDN() {
186 186
 		// we don't need to provide a filter in this case
187 187
 		$total = $this->countEntries('', 'objects');
188
-		if($total === false) {
188
+		if ($total === false) {
189 189
 			throw new \Exception('invalid results received');
190 190
 		}
191 191
 		$this->result->addChange('ldap_test_base', $total);
@@ -199,7 +199,7 @@  discard block
 block discarded – undo
199 199
 	 * @return int|bool
200 200
 	 */
201 201
 	public function countUsersWithAttribute($attr, $existsCheck = false) {
202
-		if(!$this->checkRequirements(array('ldapHost',
202
+		if (!$this->checkRequirements(array('ldapHost',
203 203
 										   'ldapPort',
204 204
 										   'ldapBase',
205 205
 										   'ldapUserFilter',
@@ -209,7 +209,7 @@  discard block
 block discarded – undo
209 209
 
210 210
 		$filter = $this->access->combineFilterWithAnd(array(
211 211
 			$this->configuration->ldapUserFilter,
212
-			$attr . '=*'
212
+			$attr.'=*'
213 213
 		));
214 214
 
215 215
 		$limit = ($existsCheck === false) ? null : 1;
@@ -224,7 +224,7 @@  discard block
 block discarded – undo
224 224
 	 * @throws \Exception
225 225
 	 */
226 226
 	public function detectUserDisplayNameAttribute() {
227
-		if(!$this->checkRequirements(array('ldapHost',
227
+		if (!$this->checkRequirements(array('ldapHost',
228 228
 										'ldapPort',
229 229
 										'ldapBase',
230 230
 										'ldapUserFilter',
@@ -236,8 +236,8 @@  discard block
 block discarded – undo
236 236
 		if ($attr !== '' && $attr !== 'displayName') {
237 237
 			// most likely not the default value with upper case N,
238 238
 			// verify it still produces a result
239
-			$count = (int)$this->countUsersWithAttribute($attr, true);
240
-			if($count > 0) {
239
+			$count = (int) $this->countUsersWithAttribute($attr, true);
240
+			if ($count > 0) {
241 241
 				//no change, but we sent it back to make sure the user interface
242 242
 				//is still correct, even if the ajax call was cancelled meanwhile
243 243
 				$this->result->addChange('ldap_display_name', $attr);
@@ -248,9 +248,9 @@  discard block
 block discarded – undo
248 248
 		// first attribute that has at least one result wins
249 249
 		$displayNameAttrs = array('displayname', 'cn');
250 250
 		foreach ($displayNameAttrs as $attr) {
251
-			$count = (int)$this->countUsersWithAttribute($attr, true);
251
+			$count = (int) $this->countUsersWithAttribute($attr, true);
252 252
 
253
-			if($count > 0) {
253
+			if ($count > 0) {
254 254
 				$this->applyFind('ldap_display_name', $attr);
255 255
 				return $this->result;
256 256
 			}
@@ -266,7 +266,7 @@  discard block
 block discarded – undo
266 266
 	 * @return WizardResult|bool
267 267
 	 */
268 268
 	public function detectEmailAttribute() {
269
-		if(!$this->checkRequirements(array('ldapHost',
269
+		if (!$this->checkRequirements(array('ldapHost',
270 270
 										   'ldapPort',
271 271
 										   'ldapBase',
272 272
 										   'ldapUserFilter',
@@ -276,8 +276,8 @@  discard block
 block discarded – undo
276 276
 
277 277
 		$attr = $this->configuration->ldapEmailAttribute;
278 278
 		if ($attr !== '') {
279
-			$count = (int)$this->countUsersWithAttribute($attr, true);
280
-			if($count > 0) {
279
+			$count = (int) $this->countUsersWithAttribute($attr, true);
280
+			if ($count > 0) {
281 281
 				return false;
282 282
 			}
283 283
 			$writeLog = true;
@@ -288,19 +288,19 @@  discard block
 block discarded – undo
288 288
 		$emailAttributes = array('mail', 'mailPrimaryAddress');
289 289
 		$winner = '';
290 290
 		$maxUsers = 0;
291
-		foreach($emailAttributes as $attr) {
291
+		foreach ($emailAttributes as $attr) {
292 292
 			$count = $this->countUsersWithAttribute($attr);
293
-			if($count > $maxUsers) {
293
+			if ($count > $maxUsers) {
294 294
 				$maxUsers = $count;
295 295
 				$winner = $attr;
296 296
 			}
297 297
 		}
298 298
 
299
-		if($winner !== '') {
299
+		if ($winner !== '') {
300 300
 			$this->applyFind('ldap_email_attr', $winner);
301
-			if($writeLog) {
302
-				\OCP\Util::writeLog('user_ldap', 'The mail attribute has ' .
303
-					'automatically been reset, because the original value ' .
301
+			if ($writeLog) {
302
+				\OCP\Util::writeLog('user_ldap', 'The mail attribute has '.
303
+					'automatically been reset, because the original value '.
304 304
 					'did not return any results.', \OCP\Util::INFO);
305 305
 			}
306 306
 		}
@@ -313,7 +313,7 @@  discard block
 block discarded – undo
313 313
 	 * @throws \Exception
314 314
 	 */
315 315
 	public function determineAttributes() {
316
-		if(!$this->checkRequirements(array('ldapHost',
316
+		if (!$this->checkRequirements(array('ldapHost',
317 317
 										   'ldapPort',
318 318
 										   'ldapBase',
319 319
 										   'ldapUserFilter',
@@ -329,7 +329,7 @@  discard block
 block discarded – undo
329 329
 		$this->result->addOptions('ldap_loginfilter_attributes', $attributes);
330 330
 
331 331
 		$selected = $this->configuration->ldapLoginFilterAttributes;
332
-		if(is_array($selected) && !empty($selected)) {
332
+		if (is_array($selected) && !empty($selected)) {
333 333
 			$this->result->addChange('ldap_loginfilter_attributes', $selected);
334 334
 		}
335 335
 
@@ -342,7 +342,7 @@  discard block
 block discarded – undo
342 342
 	 * @throws \Exception
343 343
 	 */
344 344
 	private function getUserAttributes() {
345
-		if(!$this->checkRequirements(array('ldapHost',
345
+		if (!$this->checkRequirements(array('ldapHost',
346 346
 										   'ldapPort',
347 347
 										   'ldapBase',
348 348
 										   'ldapUserFilter',
@@ -350,20 +350,20 @@  discard block
 block discarded – undo
350 350
 			return  false;
351 351
 		}
352 352
 		$cr = $this->getConnection();
353
-		if(!$cr) {
353
+		if (!$cr) {
354 354
 			throw new \Exception('Could not connect to LDAP');
355 355
 		}
356 356
 
357 357
 		$base = $this->configuration->ldapBase[0];
358 358
 		$filter = $this->configuration->ldapUserFilter;
359 359
 		$rr = $this->ldap->search($cr, $base, $filter, array(), 1, 1);
360
-		if(!$this->ldap->isResource($rr)) {
360
+		if (!$this->ldap->isResource($rr)) {
361 361
 			return false;
362 362
 		}
363 363
 		$er = $this->ldap->firstEntry($cr, $rr);
364 364
 		$attributes = $this->ldap->getAttributes($cr, $er);
365 365
 		$pureAttributes = array();
366
-		for($i = 0; $i < $attributes['count']; $i++) {
366
+		for ($i = 0; $i < $attributes['count']; $i++) {
367 367
 			$pureAttributes[] = $attributes[$i];
368 368
 		}
369 369
 
@@ -398,23 +398,23 @@  discard block
 block discarded – undo
398 398
 	 * @throws \Exception
399 399
 	 */
400 400
 	private function determineGroups($dbKey, $confKey, $testMemberOf = true) {
401
-		if(!$this->checkRequirements(array('ldapHost',
401
+		if (!$this->checkRequirements(array('ldapHost',
402 402
 										   'ldapPort',
403 403
 										   'ldapBase',
404 404
 										   ))) {
405 405
 			return  false;
406 406
 		}
407 407
 		$cr = $this->getConnection();
408
-		if(!$cr) {
408
+		if (!$cr) {
409 409
 			throw new \Exception('Could not connect to LDAP');
410 410
 		}
411 411
 
412 412
 		$this->fetchGroups($dbKey, $confKey);
413 413
 
414
-		if($testMemberOf) {
414
+		if ($testMemberOf) {
415 415
 			$this->configuration->hasMemberOfFilterSupport = $this->testMemberOf();
416 416
 			$this->result->markChange();
417
-			if(!$this->configuration->hasMemberOfFilterSupport) {
417
+			if (!$this->configuration->hasMemberOfFilterSupport) {
418 418
 				throw new \Exception('memberOf is not supported by the server');
419 419
 			}
420 420
 		}
@@ -434,7 +434,7 @@  discard block
 block discarded – undo
434 434
 		$obclasses = array('posixGroup', 'group', 'zimbraDistributionList', 'groupOfNames', 'groupOfUniqueNames');
435 435
 
436 436
 		$filterParts = array();
437
-		foreach($obclasses as $obclass) {
437
+		foreach ($obclasses as $obclass) {
438 438
 			$filterParts[] = 'objectclass='.$obclass;
439 439
 		}
440 440
 		//we filter for everything
@@ -451,8 +451,8 @@  discard block
 block discarded – undo
451 451
 			// we need to request dn additionally here, otherwise memberOf
452 452
 			// detection will fail later
453 453
 			$result = $this->access->searchGroups($filter, array('cn', 'dn'), $limit, $offset);
454
-			foreach($result as $item) {
455
-				if(!isset($item['cn']) && !is_array($item['cn']) && !isset($item['cn'][0])) {
454
+			foreach ($result as $item) {
455
+				if (!isset($item['cn']) && !is_array($item['cn']) && !isset($item['cn'][0])) {
456 456
 					// just in case - no issue known
457 457
 					continue;
458 458
 				}
@@ -462,7 +462,7 @@  discard block
 block discarded – undo
462 462
 			$offset += $limit;
463 463
 		} while ($this->access->hasMoreResults());
464 464
 
465
-		if(count($groupNames) > 0) {
465
+		if (count($groupNames) > 0) {
466 466
 			natsort($groupNames);
467 467
 			$this->result->addOptions($dbKey, array_values($groupNames));
468 468
 		} else {
@@ -470,7 +470,7 @@  discard block
 block discarded – undo
470 470
 		}
471 471
 
472 472
 		$setFeatures = $this->configuration->$confKey;
473
-		if(is_array($setFeatures) && !empty($setFeatures)) {
473
+		if (is_array($setFeatures) && !empty($setFeatures)) {
474 474
 			//something is already configured? pre-select it.
475 475
 			$this->result->addChange($dbKey, $setFeatures);
476 476
 		}
@@ -478,14 +478,14 @@  discard block
 block discarded – undo
478 478
 	}
479 479
 
480 480
 	public function determineGroupMemberAssoc() {
481
-		if(!$this->checkRequirements(array('ldapHost',
481
+		if (!$this->checkRequirements(array('ldapHost',
482 482
 										   'ldapPort',
483 483
 										   'ldapGroupFilter',
484 484
 										   ))) {
485 485
 			return  false;
486 486
 		}
487 487
 		$attribute = $this->detectGroupMemberAssoc();
488
-		if($attribute === false) {
488
+		if ($attribute === false) {
489 489
 			return false;
490 490
 		}
491 491
 		$this->configuration->setConfiguration(array('ldapGroupMemberAssocAttr' => $attribute));
@@ -500,14 +500,14 @@  discard block
 block discarded – undo
500 500
 	 * @throws \Exception
501 501
 	 */
502 502
 	public function determineGroupObjectClasses() {
503
-		if(!$this->checkRequirements(array('ldapHost',
503
+		if (!$this->checkRequirements(array('ldapHost',
504 504
 										   'ldapPort',
505 505
 										   'ldapBase',
506 506
 										   ))) {
507 507
 			return  false;
508 508
 		}
509 509
 		$cr = $this->getConnection();
510
-		if(!$cr) {
510
+		if (!$cr) {
511 511
 			throw new \Exception('Could not connect to LDAP');
512 512
 		}
513 513
 
@@ -527,14 +527,14 @@  discard block
 block discarded – undo
527 527
 	 * @throws \Exception
528 528
 	 */
529 529
 	public function determineUserObjectClasses() {
530
-		if(!$this->checkRequirements(array('ldapHost',
530
+		if (!$this->checkRequirements(array('ldapHost',
531 531
 										   'ldapPort',
532 532
 										   'ldapBase',
533 533
 										   ))) {
534 534
 			return  false;
535 535
 		}
536 536
 		$cr = $this->getConnection();
537
-		if(!$cr) {
537
+		if (!$cr) {
538 538
 			throw new \Exception('Could not connect to LDAP');
539 539
 		}
540 540
 
@@ -557,7 +557,7 @@  discard block
 block discarded – undo
557 557
 	 * @throws \Exception
558 558
 	 */
559 559
 	public function getGroupFilter() {
560
-		if(!$this->checkRequirements(array('ldapHost',
560
+		if (!$this->checkRequirements(array('ldapHost',
561 561
 										   'ldapPort',
562 562
 										   'ldapBase',
563 563
 										   ))) {
@@ -581,7 +581,7 @@  discard block
 block discarded – undo
581 581
 	 * @throws \Exception
582 582
 	 */
583 583
 	public function getUserListFilter() {
584
-		if(!$this->checkRequirements(array('ldapHost',
584
+		if (!$this->checkRequirements(array('ldapHost',
585 585
 										   'ldapPort',
586 586
 										   'ldapBase',
587 587
 										   ))) {
@@ -594,7 +594,7 @@  discard block
 block discarded – undo
594 594
 			$this->applyFind('ldap_display_name', $d['ldap_display_name']);
595 595
 		}
596 596
 		$filter = $this->composeLdapFilter(self::LFILTER_USER_LIST);
597
-		if(!$filter) {
597
+		if (!$filter) {
598 598
 			throw new \Exception('Cannot create filter');
599 599
 		}
600 600
 
@@ -607,7 +607,7 @@  discard block
 block discarded – undo
607 607
 	 * @throws \Exception
608 608
 	 */
609 609
 	public function getUserLoginFilter() {
610
-		if(!$this->checkRequirements(array('ldapHost',
610
+		if (!$this->checkRequirements(array('ldapHost',
611 611
 										   'ldapPort',
612 612
 										   'ldapBase',
613 613
 										   'ldapUserFilter',
@@ -616,7 +616,7 @@  discard block
 block discarded – undo
616 616
 		}
617 617
 
618 618
 		$filter = $this->composeLdapFilter(self::LFILTER_LOGIN);
619
-		if(!$filter) {
619
+		if (!$filter) {
620 620
 			throw new \Exception('Cannot create filter');
621 621
 		}
622 622
 
@@ -630,7 +630,7 @@  discard block
 block discarded – undo
630 630
 	 * @throws \Exception
631 631
 	 */
632 632
 	public function testLoginName($loginName) {
633
-		if(!$this->checkRequirements(array('ldapHost',
633
+		if (!$this->checkRequirements(array('ldapHost',
634 634
 			'ldapPort',
635 635
 			'ldapBase',
636 636
 			'ldapLoginFilter',
@@ -639,17 +639,17 @@  discard block
 block discarded – undo
639 639
 		}
640 640
 
641 641
 		$cr = $this->access->connection->getConnectionResource();
642
-		if(!$this->ldap->isResource($cr)) {
642
+		if (!$this->ldap->isResource($cr)) {
643 643
 			throw new \Exception('connection error');
644 644
 		}
645 645
 
646
-		if(mb_strpos($this->access->connection->ldapLoginFilter, '%uid', 0, 'UTF-8')
646
+		if (mb_strpos($this->access->connection->ldapLoginFilter, '%uid', 0, 'UTF-8')
647 647
 			=== false) {
648 648
 			throw new \Exception('missing placeholder');
649 649
 		}
650 650
 
651 651
 		$users = $this->access->countUsersByLoginName($loginName);
652
-		if($this->ldap->errno($cr) !== 0) {
652
+		if ($this->ldap->errno($cr) !== 0) {
653 653
 			throw new \Exception($this->ldap->error($cr));
654 654
 		}
655 655
 		$filter = str_replace('%uid', $loginName, $this->access->connection->ldapLoginFilter);
@@ -664,22 +664,22 @@  discard block
 block discarded – undo
664 664
 	 * @throws \Exception
665 665
 	 */
666 666
 	public function guessPortAndTLS() {
667
-		if(!$this->checkRequirements(array('ldapHost',
667
+		if (!$this->checkRequirements(array('ldapHost',
668 668
 										   ))) {
669 669
 			return false;
670 670
 		}
671 671
 		$this->checkHost();
672 672
 		$portSettings = $this->getPortSettingsToTry();
673 673
 
674
-		if(!is_array($portSettings)) {
674
+		if (!is_array($portSettings)) {
675 675
 			throw new \Exception(print_r($portSettings, true));
676 676
 		}
677 677
 
678 678
 		//proceed from the best configuration and return on first success
679
-		foreach($portSettings as $setting) {
679
+		foreach ($portSettings as $setting) {
680 680
 			$p = $setting['port'];
681 681
 			$t = $setting['tls'];
682
-			\OCP\Util::writeLog('user_ldap', 'Wiz: trying port '. $p . ', TLS '. $t, \OCP\Util::DEBUG);
682
+			\OCP\Util::writeLog('user_ldap', 'Wiz: trying port '.$p.', TLS '.$t, \OCP\Util::DEBUG);
683 683
 			//connectAndBind may throw Exception, it needs to be catched by the
684 684
 			//callee of this method
685 685
 
@@ -689,7 +689,7 @@  discard block
 block discarded – undo
689 689
 				// any reply other than -1 (= cannot connect) is already okay,
690 690
 				// because then we found the server
691 691
 				// unavailable startTLS returns -11
692
-				if($e->getCode() > 0) {
692
+				if ($e->getCode() > 0) {
693 693
 					$settingsFound = true;
694 694
 				} else {
695 695
 					throw $e;
@@ -699,10 +699,10 @@  discard block
 block discarded – undo
699 699
 			if ($settingsFound === true) {
700 700
 				$config = array(
701 701
 					'ldapPort' => $p,
702
-					'ldapTLS' => (int)$t
702
+					'ldapTLS' => (int) $t
703 703
 				);
704 704
 				$this->configuration->setConfiguration($config);
705
-				\OCP\Util::writeLog('user_ldap', 'Wiz: detected Port ' . $p, \OCP\Util::DEBUG);
705
+				\OCP\Util::writeLog('user_ldap', 'Wiz: detected Port '.$p, \OCP\Util::DEBUG);
706 706
 				$this->result->addChange('ldap_port', $p);
707 707
 				return $this->result;
708 708
 			}
@@ -717,7 +717,7 @@  discard block
 block discarded – undo
717 717
 	 * @return WizardResult|false WizardResult on success, false otherwise
718 718
 	 */
719 719
 	public function guessBaseDN() {
720
-		if(!$this->checkRequirements(array('ldapHost',
720
+		if (!$this->checkRequirements(array('ldapHost',
721 721
 										   'ldapPort',
722 722
 										   ))) {
723 723
 			return false;
@@ -726,9 +726,9 @@  discard block
 block discarded – undo
726 726
 		//check whether a DN is given in the agent name (99.9% of all cases)
727 727
 		$base = null;
728 728
 		$i = stripos($this->configuration->ldapAgentName, 'dc=');
729
-		if($i !== false) {
729
+		if ($i !== false) {
730 730
 			$base = substr($this->configuration->ldapAgentName, $i);
731
-			if($this->testBaseDN($base)) {
731
+			if ($this->testBaseDN($base)) {
732 732
 				$this->applyFind('ldap_base', $base);
733 733
 				return $this->result;
734 734
 			}
@@ -739,13 +739,13 @@  discard block
 block discarded – undo
739 739
 		//a base DN
740 740
 		$helper = new Helper(\OC::$server->getConfig());
741 741
 		$domain = $helper->getDomainFromURL($this->configuration->ldapHost);
742
-		if(!$domain) {
742
+		if (!$domain) {
743 743
 			return false;
744 744
 		}
745 745
 
746 746
 		$dparts = explode('.', $domain);
747
-		while(count($dparts) > 0) {
748
-			$base2 = 'dc=' . implode(',dc=', $dparts);
747
+		while (count($dparts) > 0) {
748
+			$base2 = 'dc='.implode(',dc=', $dparts);
749 749
 			if ($base !== $base2 && $this->testBaseDN($base2)) {
750 750
 				$this->applyFind('ldap_base', $base2);
751 751
 				return $this->result;
@@ -778,7 +778,7 @@  discard block
 block discarded – undo
778 778
 		$hostInfo = parse_url($host);
779 779
 
780 780
 		//removes Port from Host
781
-		if(is_array($hostInfo) && isset($hostInfo['port'])) {
781
+		if (is_array($hostInfo) && isset($hostInfo['port'])) {
782 782
 			$port = $hostInfo['port'];
783 783
 			$host = str_replace(':'.$port, '', $host);
784 784
 			$this->applyFind('ldap_host', $host);
@@ -795,30 +795,30 @@  discard block
 block discarded – undo
795 795
 	private function detectGroupMemberAssoc() {
796 796
 		$possibleAttrs = array('uniqueMember', 'memberUid', 'member', 'gidNumber');
797 797
 		$filter = $this->configuration->ldapGroupFilter;
798
-		if(empty($filter)) {
798
+		if (empty($filter)) {
799 799
 			return false;
800 800
 		}
801 801
 		$cr = $this->getConnection();
802
-		if(!$cr) {
802
+		if (!$cr) {
803 803
 			throw new \Exception('Could not connect to LDAP');
804 804
 		}
805 805
 		$base = $this->configuration->ldapBase[0];
806 806
 		$rr = $this->ldap->search($cr, $base, $filter, $possibleAttrs, 0, 1000);
807
-		if(!$this->ldap->isResource($rr)) {
807
+		if (!$this->ldap->isResource($rr)) {
808 808
 			return false;
809 809
 		}
810 810
 		$er = $this->ldap->firstEntry($cr, $rr);
811
-		while(is_resource($er)) {
811
+		while (is_resource($er)) {
812 812
 			$this->ldap->getDN($cr, $er);
813 813
 			$attrs = $this->ldap->getAttributes($cr, $er);
814 814
 			$result = array();
815 815
 			$possibleAttrsCount = count($possibleAttrs);
816
-			for($i = 0; $i < $possibleAttrsCount; $i++) {
817
-				if(isset($attrs[$possibleAttrs[$i]])) {
816
+			for ($i = 0; $i < $possibleAttrsCount; $i++) {
817
+				if (isset($attrs[$possibleAttrs[$i]])) {
818 818
 					$result[$possibleAttrs[$i]] = $attrs[$possibleAttrs[$i]]['count'];
819 819
 				}
820 820
 			}
821
-			if(!empty($result)) {
821
+			if (!empty($result)) {
822 822
 				natsort($result);
823 823
 				return key($result);
824 824
 			}
@@ -837,14 +837,14 @@  discard block
 block discarded – undo
837 837
 	 */
838 838
 	private function testBaseDN($base) {
839 839
 		$cr = $this->getConnection();
840
-		if(!$cr) {
840
+		if (!$cr) {
841 841
 			throw new \Exception('Could not connect to LDAP');
842 842
 		}
843 843
 
844 844
 		//base is there, let's validate it. If we search for anything, we should
845 845
 		//get a result set > 0 on a proper base
846 846
 		$rr = $this->ldap->search($cr, $base, 'objectClass=*', array('dn'), 0, 1);
847
-		if(!$this->ldap->isResource($rr)) {
847
+		if (!$this->ldap->isResource($rr)) {
848 848
 			$errorNo  = $this->ldap->errno($cr);
849 849
 			$errorMsg = $this->ldap->error($cr);
850 850
 			\OCP\Util::writeLog('user_ldap', 'Wiz: Could not search base '.$base.
@@ -866,11 +866,11 @@  discard block
 block discarded – undo
866 866
 	 */
867 867
 	private function testMemberOf() {
868 868
 		$cr = $this->getConnection();
869
-		if(!$cr) {
869
+		if (!$cr) {
870 870
 			throw new \Exception('Could not connect to LDAP');
871 871
 		}
872 872
 		$result = $this->access->countUsers('memberOf=*', array('memberOf'), 1);
873
-		if(is_int($result) &&  $result > 0) {
873
+		if (is_int($result) && $result > 0) {
874 874
 			return true;
875 875
 		}
876 876
 		return false;
@@ -891,27 +891,27 @@  discard block
 block discarded – undo
891 891
 			case self::LFILTER_USER_LIST:
892 892
 				$objcs = $this->configuration->ldapUserFilterObjectclass;
893 893
 				//glue objectclasses
894
-				if(is_array($objcs) && count($objcs) > 0) {
894
+				if (is_array($objcs) && count($objcs) > 0) {
895 895
 					$filter .= '(|';
896
-					foreach($objcs as $objc) {
897
-						$filter .= '(objectclass=' . $objc . ')';
896
+					foreach ($objcs as $objc) {
897
+						$filter .= '(objectclass='.$objc.')';
898 898
 					}
899 899
 					$filter .= ')';
900 900
 					$parts++;
901 901
 				}
902 902
 				//glue group memberships
903
-				if($this->configuration->hasMemberOfFilterSupport) {
903
+				if ($this->configuration->hasMemberOfFilterSupport) {
904 904
 					$cns = $this->configuration->ldapUserFilterGroups;
905
-					if(is_array($cns) && count($cns) > 0) {
905
+					if (is_array($cns) && count($cns) > 0) {
906 906
 						$filter .= '(|';
907 907
 						$cr = $this->getConnection();
908
-						if(!$cr) {
908
+						if (!$cr) {
909 909
 							throw new \Exception('Could not connect to LDAP');
910 910
 						}
911 911
 						$base = $this->configuration->ldapBase[0];
912
-						foreach($cns as $cn) {
913
-							$rr = $this->ldap->search($cr, $base, 'cn=' . $cn, array('dn', 'primaryGroupToken'));
914
-							if(!$this->ldap->isResource($rr)) {
912
+						foreach ($cns as $cn) {
913
+							$rr = $this->ldap->search($cr, $base, 'cn='.$cn, array('dn', 'primaryGroupToken'));
914
+							if (!$this->ldap->isResource($rr)) {
915 915
 								continue;
916 916
 							}
917 917
 							$er = $this->ldap->firstEntry($cr, $rr);
@@ -920,11 +920,11 @@  discard block
 block discarded – undo
920 920
 							if ($dn === false || $dn === '') {
921 921
 								continue;
922 922
 							}
923
-							$filterPart = '(memberof=' . $dn . ')';
924
-							if(isset($attrs['primaryGroupToken'])) {
923
+							$filterPart = '(memberof='.$dn.')';
924
+							if (isset($attrs['primaryGroupToken'])) {
925 925
 								$pgt = $attrs['primaryGroupToken'][0];
926
-								$primaryFilterPart = '(primaryGroupID=' . $pgt .')';
927
-								$filterPart = '(|' . $filterPart . $primaryFilterPart . ')';
926
+								$primaryFilterPart = '(primaryGroupID='.$pgt.')';
927
+								$filterPart = '(|'.$filterPart.$primaryFilterPart.')';
928 928
 							}
929 929
 							$filter .= $filterPart;
930 930
 						}
@@ -933,8 +933,8 @@  discard block
 block discarded – undo
933 933
 					$parts++;
934 934
 				}
935 935
 				//wrap parts in AND condition
936
-				if($parts > 1) {
937
-					$filter = '(&' . $filter . ')';
936
+				if ($parts > 1) {
937
+					$filter = '(&'.$filter.')';
938 938
 				}
939 939
 				if ($filter === '') {
940 940
 					$filter = '(objectclass=*)';
@@ -944,27 +944,27 @@  discard block
 block discarded – undo
944 944
 			case self::LFILTER_GROUP_LIST:
945 945
 				$objcs = $this->configuration->ldapGroupFilterObjectclass;
946 946
 				//glue objectclasses
947
-				if(is_array($objcs) && count($objcs) > 0) {
947
+				if (is_array($objcs) && count($objcs) > 0) {
948 948
 					$filter .= '(|';
949
-					foreach($objcs as $objc) {
950
-						$filter .= '(objectclass=' . $objc . ')';
949
+					foreach ($objcs as $objc) {
950
+						$filter .= '(objectclass='.$objc.')';
951 951
 					}
952 952
 					$filter .= ')';
953 953
 					$parts++;
954 954
 				}
955 955
 				//glue group memberships
956 956
 				$cns = $this->configuration->ldapGroupFilterGroups;
957
-				if(is_array($cns) && count($cns) > 0) {
957
+				if (is_array($cns) && count($cns) > 0) {
958 958
 					$filter .= '(|';
959
-					foreach($cns as $cn) {
960
-						$filter .= '(cn=' . $cn . ')';
959
+					foreach ($cns as $cn) {
960
+						$filter .= '(cn='.$cn.')';
961 961
 					}
962 962
 					$filter .= ')';
963 963
 				}
964 964
 				$parts++;
965 965
 				//wrap parts in AND condition
966
-				if($parts > 1) {
967
-					$filter = '(&' . $filter . ')';
966
+				if ($parts > 1) {
967
+					$filter = '(&'.$filter.')';
968 968
 				}
969 969
 				break;
970 970
 
@@ -976,47 +976,47 @@  discard block
 block discarded – undo
976 976
 				$userAttributes = array_change_key_case(array_flip($userAttributes));
977 977
 				$parts = 0;
978 978
 
979
-				if($this->configuration->ldapLoginFilterUsername === '1') {
979
+				if ($this->configuration->ldapLoginFilterUsername === '1') {
980 980
 					$attr = '';
981
-					if(isset($userAttributes['uid'])) {
981
+					if (isset($userAttributes['uid'])) {
982 982
 						$attr = 'uid';
983
-					} else if(isset($userAttributes['samaccountname'])) {
983
+					} else if (isset($userAttributes['samaccountname'])) {
984 984
 						$attr = 'samaccountname';
985
-					} else if(isset($userAttributes['cn'])) {
985
+					} else if (isset($userAttributes['cn'])) {
986 986
 						//fallback
987 987
 						$attr = 'cn';
988 988
 					}
989 989
 					if ($attr !== '') {
990
-						$filterUsername = '(' . $attr . $loginpart . ')';
990
+						$filterUsername = '('.$attr.$loginpart.')';
991 991
 						$parts++;
992 992
 					}
993 993
 				}
994 994
 
995 995
 				$filterEmail = '';
996
-				if($this->configuration->ldapLoginFilterEmail === '1') {
996
+				if ($this->configuration->ldapLoginFilterEmail === '1') {
997 997
 					$filterEmail = '(|(mailPrimaryAddress=%uid)(mail=%uid))';
998 998
 					$parts++;
999 999
 				}
1000 1000
 
1001 1001
 				$filterAttributes = '';
1002 1002
 				$attrsToFilter = $this->configuration->ldapLoginFilterAttributes;
1003
-				if(is_array($attrsToFilter) && count($attrsToFilter) > 0) {
1003
+				if (is_array($attrsToFilter) && count($attrsToFilter) > 0) {
1004 1004
 					$filterAttributes = '(|';
1005
-					foreach($attrsToFilter as $attribute) {
1006
-						$filterAttributes .= '(' . $attribute . $loginpart . ')';
1005
+					foreach ($attrsToFilter as $attribute) {
1006
+						$filterAttributes .= '('.$attribute.$loginpart.')';
1007 1007
 					}
1008 1008
 					$filterAttributes .= ')';
1009 1009
 					$parts++;
1010 1010
 				}
1011 1011
 
1012 1012
 				$filterLogin = '';
1013
-				if($parts > 1) {
1013
+				if ($parts > 1) {
1014 1014
 					$filterLogin = '(|';
1015 1015
 				}
1016 1016
 				$filterLogin .= $filterUsername;
1017 1017
 				$filterLogin .= $filterEmail;
1018 1018
 				$filterLogin .= $filterAttributes;
1019
-				if($parts > 1) {
1019
+				if ($parts > 1) {
1020 1020
 					$filterLogin .= ')';
1021 1021
 				}
1022 1022
 
@@ -1041,12 +1041,12 @@  discard block
 block discarded – undo
1041 1041
 		//connect, does not really trigger any server communication
1042 1042
 		$host = $this->configuration->ldapHost;
1043 1043
 		$hostInfo = parse_url($host);
1044
-		if(!$hostInfo) {
1044
+		if (!$hostInfo) {
1045 1045
 			throw new \Exception(self::$l->t('Invalid Host'));
1046 1046
 		}
1047 1047
 		\OCP\Util::writeLog('user_ldap', 'Wiz: Attempting to connect ', \OCP\Util::DEBUG);
1048 1048
 		$cr = $this->ldap->connect($host, $port);
1049
-		if(!is_resource($cr)) {
1049
+		if (!is_resource($cr)) {
1050 1050
 			throw new \Exception(self::$l->t('Invalid Host'));
1051 1051
 		}
1052 1052
 
@@ -1056,9 +1056,9 @@  discard block
 block discarded – undo
1056 1056
 		$this->ldap->setOption($cr, LDAP_OPT_NETWORK_TIMEOUT, self::LDAP_NW_TIMEOUT);
1057 1057
 
1058 1058
 		try {
1059
-			if($tls) {
1059
+			if ($tls) {
1060 1060
 				$isTlsWorking = @$this->ldap->startTls($cr);
1061
-				if(!$isTlsWorking) {
1061
+				if (!$isTlsWorking) {
1062 1062
 					return false;
1063 1063
 				}
1064 1064
 			}
@@ -1072,17 +1072,17 @@  discard block
 block discarded – undo
1072 1072
 			$errNo = $this->ldap->errno($cr);
1073 1073
 			$error = ldap_error($cr);
1074 1074
 			$this->ldap->unbind($cr);
1075
-		} catch(ServerNotAvailableException $e) {
1075
+		} catch (ServerNotAvailableException $e) {
1076 1076
 			return false;
1077 1077
 		}
1078 1078
 
1079
-		if($login === true) {
1079
+		if ($login === true) {
1080 1080
 			$this->ldap->unbind($cr);
1081
-			\OCP\Util::writeLog('user_ldap', 'Wiz: Bind successful to Port '. $port . ' TLS ' . (int)$tls, \OCP\Util::DEBUG);
1081
+			\OCP\Util::writeLog('user_ldap', 'Wiz: Bind successful to Port '.$port.' TLS '.(int) $tls, \OCP\Util::DEBUG);
1082 1082
 			return true;
1083 1083
 		}
1084 1084
 
1085
-		if($errNo === -1) {
1085
+		if ($errNo === -1) {
1086 1086
 			//host, port or TLS wrong
1087 1087
 			return false;
1088 1088
 		}
@@ -1110,9 +1110,9 @@  discard block
 block discarded – undo
1110 1110
 	 */
1111 1111
 	private function checkRequirements($reqs) {
1112 1112
 		$this->checkAgentRequirements();
1113
-		foreach($reqs as $option) {
1113
+		foreach ($reqs as $option) {
1114 1114
 			$value = $this->configuration->$option;
1115
-			if(empty($value)) {
1115
+			if (empty($value)) {
1116 1116
 				return false;
1117 1117
 			}
1118 1118
 		}
@@ -1134,33 +1134,33 @@  discard block
 block discarded – undo
1134 1134
 		$dnRead = array();
1135 1135
 		$foundItems = array();
1136 1136
 		$maxEntries = 0;
1137
-		if(!is_array($this->configuration->ldapBase)
1137
+		if (!is_array($this->configuration->ldapBase)
1138 1138
 		   || !isset($this->configuration->ldapBase[0])) {
1139 1139
 			return false;
1140 1140
 		}
1141 1141
 		$base = $this->configuration->ldapBase[0];
1142 1142
 		$cr = $this->getConnection();
1143
-		if(!$this->ldap->isResource($cr)) {
1143
+		if (!$this->ldap->isResource($cr)) {
1144 1144
 			return false;
1145 1145
 		}
1146 1146
 		$lastFilter = null;
1147
-		if(isset($filters[count($filters)-1])) {
1148
-			$lastFilter = $filters[count($filters)-1];
1147
+		if (isset($filters[count($filters) - 1])) {
1148
+			$lastFilter = $filters[count($filters) - 1];
1149 1149
 		}
1150
-		foreach($filters as $filter) {
1151
-			if($lastFilter === $filter && count($foundItems) > 0) {
1150
+		foreach ($filters as $filter) {
1151
+			if ($lastFilter === $filter && count($foundItems) > 0) {
1152 1152
 				//skip when the filter is a wildcard and results were found
1153 1153
 				continue;
1154 1154
 			}
1155 1155
 			// 20k limit for performance and reason
1156 1156
 			$rr = $this->ldap->search($cr, $base, $filter, array($attr), 0, 20000);
1157
-			if(!$this->ldap->isResource($rr)) {
1157
+			if (!$this->ldap->isResource($rr)) {
1158 1158
 				continue;
1159 1159
 			}
1160 1160
 			$entries = $this->ldap->countEntries($cr, $rr);
1161 1161
 			$getEntryFunc = 'firstEntry';
1162
-			if(($entries !== false) && ($entries > 0)) {
1163
-				if(!is_null($maxF) && $entries > $maxEntries) {
1162
+			if (($entries !== false) && ($entries > 0)) {
1163
+				if (!is_null($maxF) && $entries > $maxEntries) {
1164 1164
 					$maxEntries = $entries;
1165 1165
 					$maxF = $filter;
1166 1166
 				}
@@ -1168,13 +1168,13 @@  discard block
 block discarded – undo
1168 1168
 				do {
1169 1169
 					$entry = $this->ldap->$getEntryFunc($cr, $rr);
1170 1170
 					$getEntryFunc = 'nextEntry';
1171
-					if(!$this->ldap->isResource($entry)) {
1171
+					if (!$this->ldap->isResource($entry)) {
1172 1172
 						continue 2;
1173 1173
 					}
1174 1174
 					$rr = $entry; //will be expected by nextEntry next round
1175 1175
 					$attributes = $this->ldap->getAttributes($cr, $entry);
1176 1176
 					$dn = $this->ldap->getDN($cr, $entry);
1177
-					if($dn === false || in_array($dn, $dnRead)) {
1177
+					if ($dn === false || in_array($dn, $dnRead)) {
1178 1178
 						continue;
1179 1179
 					}
1180 1180
 					$newItems = array();
@@ -1185,7 +1185,7 @@  discard block
 block discarded – undo
1185 1185
 					$foundItems = array_merge($foundItems, $newItems);
1186 1186
 					$this->resultCache[$dn][$attr] = $newItems;
1187 1187
 					$dnRead[] = $dn;
1188
-				} while(($state === self::LRESULT_PROCESSED_SKIP
1188
+				} while (($state === self::LRESULT_PROCESSED_SKIP
1189 1189
 						|| $this->ldap->isResource($entry))
1190 1190
 						&& ($dnReadLimit === 0 || $dnReadCount < $dnReadLimit));
1191 1191
 			}
@@ -1208,11 +1208,11 @@  discard block
 block discarded – undo
1208 1208
 	 */
1209 1209
 	private function determineFeature($objectclasses, $attr, $dbkey, $confkey, $po = false) {
1210 1210
 		$cr = $this->getConnection();
1211
-		if(!$cr) {
1211
+		if (!$cr) {
1212 1212
 			throw new \Exception('Could not connect to LDAP');
1213 1213
 		}
1214 1214
 		$p = 'objectclass=';
1215
-		foreach($objectclasses as $key => $value) {
1215
+		foreach ($objectclasses as $key => $value) {
1216 1216
 			$objectclasses[$key] = $p.$value;
1217 1217
 		}
1218 1218
 		$maxEntryObjC = '';
@@ -1224,7 +1224,7 @@  discard block
 block discarded – undo
1224 1224
 		$availableFeatures =
1225 1225
 			$this->cumulativeSearchOnAttribute($objectclasses, $attr,
1226 1226
 											   $dig, $maxEntryObjC);
1227
-		if(is_array($availableFeatures)
1227
+		if (is_array($availableFeatures)
1228 1228
 		   && count($availableFeatures) > 0) {
1229 1229
 			natcasesort($availableFeatures);
1230 1230
 			//natcasesort keeps indices, but we must get rid of them for proper
@@ -1235,7 +1235,7 @@  discard block
 block discarded – undo
1235 1235
 		}
1236 1236
 
1237 1237
 		$setFeatures = $this->configuration->$confkey;
1238
-		if(is_array($setFeatures) && !empty($setFeatures)) {
1238
+		if (is_array($setFeatures) && !empty($setFeatures)) {
1239 1239
 			//something is already configured? pre-select it.
1240 1240
 			$this->result->addChange($dbkey, $setFeatures);
1241 1241
 		} else if ($po && $maxEntryObjC !== '') {
@@ -1257,7 +1257,7 @@  discard block
 block discarded – undo
1257 1257
 	 * LRESULT_PROCESSED_INVALID or LRESULT_PROCESSED_SKIP
1258 1258
 	 */
1259 1259
 	private function getAttributeValuesFromEntry($result, $attribute, &$known) {
1260
-		if(!is_array($result)
1260
+		if (!is_array($result)
1261 1261
 		   || !isset($result['count'])
1262 1262
 		   || !$result['count'] > 0) {
1263 1263
 			return self::LRESULT_PROCESSED_INVALID;
@@ -1266,12 +1266,12 @@  discard block
 block discarded – undo
1266 1266
 		// strtolower on all keys for proper comparison
1267 1267
 		$result = \OCP\Util::mb_array_change_key_case($result);
1268 1268
 		$attribute = strtolower($attribute);
1269
-		if(isset($result[$attribute])) {
1270
-			foreach($result[$attribute] as $key => $val) {
1271
-				if($key === 'count') {
1269
+		if (isset($result[$attribute])) {
1270
+			foreach ($result[$attribute] as $key => $val) {
1271
+				if ($key === 'count') {
1272 1272
 					continue;
1273 1273
 				}
1274
-				if(!in_array($val, $known)) {
1274
+				if (!in_array($val, $known)) {
1275 1275
 					$known[] = $val;
1276 1276
 				}
1277 1277
 			}
@@ -1285,7 +1285,7 @@  discard block
 block discarded – undo
1285 1285
 	 * @return bool|mixed
1286 1286
 	 */
1287 1287
 	private function getConnection() {
1288
-		if(!is_null($this->cr)) {
1288
+		if (!is_null($this->cr)) {
1289 1289
 			return $this->cr;
1290 1290
 		}
1291 1291
 
@@ -1297,14 +1297,14 @@  discard block
 block discarded – undo
1297 1297
 		$this->ldap->setOption($cr, LDAP_OPT_PROTOCOL_VERSION, 3);
1298 1298
 		$this->ldap->setOption($cr, LDAP_OPT_REFERRALS, 0);
1299 1299
 		$this->ldap->setOption($cr, LDAP_OPT_NETWORK_TIMEOUT, self::LDAP_NW_TIMEOUT);
1300
-		if($this->configuration->ldapTLS === 1) {
1300
+		if ($this->configuration->ldapTLS === 1) {
1301 1301
 			$this->ldap->startTls($cr);
1302 1302
 		}
1303 1303
 
1304 1304
 		$lo = @$this->ldap->bind($cr,
1305 1305
 								 $this->configuration->ldapAgentName,
1306 1306
 								 $this->configuration->ldapAgentPassword);
1307
-		if($lo === true) {
1307
+		if ($lo === true) {
1308 1308
 			$this->$cr = $cr;
1309 1309
 			return $cr;
1310 1310
 		}
@@ -1335,18 +1335,18 @@  discard block
 block discarded – undo
1335 1335
 		//636 ← LDAPS / SSL
1336 1336
 		//7xxx ← UCS. need to be checked first, because both ports may be open
1337 1337
 		$host = $this->configuration->ldapHost;
1338
-		$port = (int)$this->configuration->ldapPort;
1338
+		$port = (int) $this->configuration->ldapPort;
1339 1339
 		$portSettings = array();
1340 1340
 
1341 1341
 		//In case the port is already provided, we will check this first
1342
-		if($port > 0) {
1342
+		if ($port > 0) {
1343 1343
 			$hostInfo = parse_url($host);
1344
-			if(!(is_array($hostInfo)
1344
+			if (!(is_array($hostInfo)
1345 1345
 				&& isset($hostInfo['scheme'])
1346 1346
 				&& stripos($hostInfo['scheme'], 'ldaps') !== false)) {
1347 1347
 				$portSettings[] = array('port' => $port, 'tls' => true);
1348 1348
 			}
1349
-			$portSettings[] =array('port' => $port, 'tls' => false);
1349
+			$portSettings[] = array('port' => $port, 'tls' => false);
1350 1350
 		}
1351 1351
 
1352 1352
 		//default ports
Please login to merge, or discard this patch.