Wizard.php 38 KB

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