Ldap.php 51 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598
  1. <?php
  2. /**
  3. * Zend Framework
  4. *
  5. * LICENSE
  6. *
  7. * This source file is subject to the new BSD license that is bundled
  8. * with this package in the file LICENSE.txt.
  9. * It is also available through the world-wide-web at this URL:
  10. * http://framework.zend.com/license/new-bsd
  11. * If you did not receive a copy of the license and are unable to
  12. * obtain it through the world-wide-web, please send an email
  13. * to license@zend.com so we can send you a copy immediately.
  14. *
  15. * @category Zend
  16. * @package Zend_Ldap
  17. * @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
  18. * @license http://framework.zend.com/license/new-bsd New BSD License
  19. * @version $Id$
  20. */
  21. /**
  22. * @category Zend
  23. * @package Zend_Ldap
  24. * @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
  25. * @license http://framework.zend.com/license/new-bsd New BSD License
  26. */
  27. class Zend_Ldap
  28. {
  29. const SEARCH_SCOPE_SUB = 1;
  30. const SEARCH_SCOPE_ONE = 2;
  31. const SEARCH_SCOPE_BASE = 3;
  32. const ACCTNAME_FORM_DN = 1;
  33. const ACCTNAME_FORM_USERNAME = 2;
  34. const ACCTNAME_FORM_BACKSLASH = 3;
  35. const ACCTNAME_FORM_PRINCIPAL = 4;
  36. /**
  37. * String used with ldap_connect for error handling purposes.
  38. *
  39. * @var string
  40. */
  41. private $_connectString;
  42. /**
  43. * The options used in connecting, binding, etc.
  44. *
  45. * @var array
  46. */
  47. protected $_options = null;
  48. /**
  49. * The raw LDAP extension resource.
  50. *
  51. * @var resource
  52. */
  53. protected $_resource = null;
  54. /**
  55. * FALSE if no user is bound to the LDAP resource
  56. * NULL if there has been an anonymous bind
  57. * username of the currently bound user
  58. *
  59. * @var boolean|null|string
  60. */
  61. protected $_boundUser = false;
  62. /**
  63. * Caches the RootDSE
  64. *
  65. * @var Zend_Ldap_Node
  66. */
  67. protected $_rootDse = null;
  68. /**
  69. * Caches the schema
  70. *
  71. * @var Zend_Ldap_Node
  72. */
  73. protected $_schema = null;
  74. /**
  75. * @deprecated will be removed, use {@see Zend_Ldap_Filter_Abstract::escapeValue()}
  76. * @param string $str The string to escape.
  77. * @return string The escaped string
  78. */
  79. public static function filterEscape($str)
  80. {
  81. /**
  82. * @see Zend_Ldap_Filter_Abstract
  83. */
  84. require_once 'Zend/Ldap/Filter/Abstract.php';
  85. return Zend_Ldap_Filter_Abstract::escapeValue($str);
  86. }
  87. /**
  88. * @deprecated will be removed, use {@see Zend_Ldap_Dn::checkDn()}
  89. * @param string $dn The DN to parse
  90. * @param array $keys An optional array to receive DN keys (e.g. CN, OU, DC, ...)
  91. * @param array $vals An optional array to receive DN values
  92. * @return boolean True if the DN was successfully parsed or false if the string is
  93. * not a valid DN.
  94. */
  95. public static function explodeDn($dn, array &$keys = null, array &$vals = null)
  96. {
  97. /**
  98. * @see Zend_Ldap_Dn
  99. */
  100. require_once 'Zend/Ldap/Dn.php';
  101. return Zend_Ldap_Dn::checkDn($dn, $keys, $vals);
  102. }
  103. /**
  104. * Constructor.
  105. *
  106. * @param array|Zend_Config $options Options used in connecting, binding, etc.
  107. * @return void
  108. * @throws Zend_Ldap_Exception if ext/ldap is not installed
  109. */
  110. public function __construct($options = array())
  111. {
  112. if (!extension_loaded('ldap')) {
  113. /**
  114. * @see Zend_Ldap_Exception
  115. */
  116. require_once 'Zend/Ldap/Exception.php';
  117. throw new Zend_Ldap_Exception(null, 'LDAP extension not loaded',
  118. Zend_Ldap_Exception::LDAP_X_EXTENSION_NOT_LOADED);
  119. }
  120. $this->setOptions($options);
  121. }
  122. /**
  123. * Destructor.
  124. *
  125. * @return void
  126. */
  127. public function __destruct()
  128. {
  129. $this->disconnect();
  130. }
  131. /**
  132. * @return resource The raw LDAP extension resource.
  133. */
  134. public function getResource()
  135. {
  136. if (!is_resource($this->_resource) || $this->_boundUser === false) {
  137. $this->bind();
  138. }
  139. return $this->_resource;
  140. }
  141. /**
  142. * Return the LDAP error number of the last LDAP command
  143. *
  144. * @return int
  145. */
  146. public function getLastErrorCode()
  147. {
  148. $ret = @ldap_get_option($this->_resource, LDAP_OPT_ERROR_NUMBER, $err);
  149. if ($ret === true) {
  150. if ($err <= -1 && $err >= -17) {
  151. /**
  152. * @see Zend_Ldap_Exception
  153. */
  154. require_once 'Zend/Ldap/Exception.php';
  155. /* For some reason draft-ietf-ldapext-ldap-c-api-xx.txt error
  156. * codes in OpenLDAP are negative values from -1 to -17.
  157. */
  158. $err = Zend_Ldap_Exception::LDAP_SERVER_DOWN + (-$err - 1);
  159. }
  160. return $err;
  161. }
  162. return 0;
  163. }
  164. /**
  165. * Return the LDAP error message of the last LDAP command
  166. *
  167. * @param int $errorCode
  168. * @param array $errorMessages
  169. * @return string
  170. */
  171. public function getLastError(&$errorCode = null, array &$errorMessages = null)
  172. {
  173. $errorCode = $this->getLastErrorCode();
  174. $errorMessages = array();
  175. /* The various error retrieval functions can return
  176. * different things so we just try to collect what we
  177. * can and eliminate dupes.
  178. */
  179. $estr1 = @ldap_error($this->_resource);
  180. if ($errorCode !== 0 && $estr1 === 'Success') {
  181. $estr1 = @ldap_err2str($errorCode);
  182. }
  183. if (!empty($estr1)) {
  184. $errorMessages[] = $estr1;
  185. }
  186. @ldap_get_option($this->_resource, LDAP_OPT_ERROR_STRING, $estr2);
  187. if (!empty($estr2) && !in_array($estr2, $errorMessages)) {
  188. $errorMessages[] = $estr2;
  189. }
  190. $message = '';
  191. if ($errorCode > 0) {
  192. $message = '0x' . dechex($errorCode) . ' ';
  193. } else {
  194. $message = '';
  195. }
  196. if (count($errorMessages) > 0) {
  197. $message .= '(' . implode('; ', $errorMessages) . ')';
  198. } else {
  199. $message .= '(no error message from LDAP)';
  200. }
  201. return $message;
  202. }
  203. /**
  204. * Get the currently bound user
  205. *
  206. * FALSE if no user is bound to the LDAP resource
  207. * NULL if there has been an anonymous bind
  208. * username of the currently bound user
  209. *
  210. * @return false|null|string
  211. */
  212. public function getBoundUser()
  213. {
  214. return $this->_boundUser;
  215. }
  216. /**
  217. * Sets the options used in connecting, binding, etc.
  218. *
  219. * Valid option keys:
  220. * host
  221. * port
  222. * useSsl
  223. * username
  224. * password
  225. * bindRequiresDn
  226. * baseDn
  227. * accountCanonicalForm
  228. * accountDomainName
  229. * accountDomainNameShort
  230. * accountFilterFormat
  231. * allowEmptyPassword
  232. * useStartTls
  233. * optRefferals
  234. * tryUsernameSplit
  235. *
  236. * @param array|Zend_Config $options Options used in connecting, binding, etc.
  237. * @return Zend_Ldap Provides a fluent interface
  238. * @throws Zend_Ldap_Exception
  239. */
  240. public function setOptions($options)
  241. {
  242. if ($options instanceof Zend_Config) {
  243. $options = $options->toArray();
  244. }
  245. $permittedOptions = array(
  246. 'host' => null,
  247. 'port' => 0,
  248. 'useSsl' => false,
  249. 'username' => null,
  250. 'password' => null,
  251. 'bindRequiresDn' => false,
  252. 'baseDn' => null,
  253. 'accountCanonicalForm' => null,
  254. 'accountDomainName' => null,
  255. 'accountDomainNameShort' => null,
  256. 'accountFilterFormat' => null,
  257. 'allowEmptyPassword' => false,
  258. 'useStartTls' => false,
  259. 'optReferrals' => false,
  260. 'tryUsernameSplit' => true,
  261. );
  262. foreach ($permittedOptions as $key => $val) {
  263. if (array_key_exists($key, $options)) {
  264. $val = $options[$key];
  265. unset($options[$key]);
  266. /* Enforce typing. This eliminates issues like Zend_Config_Ini
  267. * returning '1' as a string (ZF-3163).
  268. */
  269. switch ($key) {
  270. case 'port':
  271. case 'accountCanonicalForm':
  272. $permittedOptions[$key] = (int)$val;
  273. break;
  274. case 'useSsl':
  275. case 'bindRequiresDn':
  276. case 'allowEmptyPassword':
  277. case 'useStartTls':
  278. case 'optReferrals':
  279. case 'tryUsernameSplit':
  280. $permittedOptions[$key] = ($val === true ||
  281. $val === '1' || strcasecmp($val, 'true') == 0);
  282. break;
  283. default:
  284. $permittedOptions[$key] = trim($val);
  285. break;
  286. }
  287. }
  288. }
  289. if (count($options) > 0) {
  290. $key = key($options);
  291. /**
  292. * @see Zend_Ldap_Exception
  293. */
  294. require_once 'Zend/Ldap/Exception.php';
  295. throw new Zend_Ldap_Exception(null, "Unknown Zend_Ldap option: $key");
  296. }
  297. $this->_options = $permittedOptions;
  298. return $this;
  299. }
  300. /**
  301. * @return array The current options.
  302. */
  303. public function getOptions()
  304. {
  305. return $this->_options;
  306. }
  307. /**
  308. * @return string The hostname of the LDAP server being used to authenticate accounts
  309. */
  310. protected function _getHost()
  311. {
  312. return $this->_options['host'];
  313. }
  314. /**
  315. * @return int The port of the LDAP server or 0 to indicate that no port value is set
  316. */
  317. protected function _getPort()
  318. {
  319. return $this->_options['port'];
  320. }
  321. /**
  322. * @return boolean The default SSL / TLS encrypted transport control
  323. */
  324. protected function _getUseSsl()
  325. {
  326. return $this->_options['useSsl'];
  327. }
  328. /**
  329. * @return string The default acctname for binding
  330. */
  331. protected function _getUsername()
  332. {
  333. return $this->_options['username'];
  334. }
  335. /**
  336. * @return string The default password for binding
  337. */
  338. protected function _getPassword()
  339. {
  340. return $this->_options['password'];
  341. }
  342. /**
  343. * @return boolean Bind requires DN
  344. */
  345. protected function _getBindRequiresDn()
  346. {
  347. return $this->_options['bindRequiresDn'];
  348. }
  349. /**
  350. * Gets the base DN under which objects of interest are located
  351. *
  352. * @return string
  353. */
  354. public function getBaseDn()
  355. {
  356. return $this->_options['baseDn'];
  357. }
  358. /**
  359. * @return integer Either ACCTNAME_FORM_BACKSLASH, ACCTNAME_FORM_PRINCIPAL or
  360. * ACCTNAME_FORM_USERNAME indicating the form usernames should be canonicalized to.
  361. */
  362. protected function _getAccountCanonicalForm()
  363. {
  364. /* Account names should always be qualified with a domain. In some scenarios
  365. * using non-qualified account names can lead to security vulnerabilities. If
  366. * no account canonical form is specified, we guess based in what domain
  367. * names have been supplied.
  368. */
  369. $accountCanonicalForm = $this->_options['accountCanonicalForm'];
  370. if (!$accountCanonicalForm) {
  371. $accountDomainName = $this->_getAccountDomainName();
  372. $accountDomainNameShort = $this->_getAccountDomainNameShort();
  373. if ($accountDomainNameShort) {
  374. $accountCanonicalForm = Zend_Ldap::ACCTNAME_FORM_BACKSLASH;
  375. } else if ($accountDomainName) {
  376. $accountCanonicalForm = Zend_Ldap::ACCTNAME_FORM_PRINCIPAL;
  377. } else {
  378. $accountCanonicalForm = Zend_Ldap::ACCTNAME_FORM_USERNAME;
  379. }
  380. }
  381. return $accountCanonicalForm;
  382. }
  383. /**
  384. * @return string The account domain name
  385. */
  386. protected function _getAccountDomainName()
  387. {
  388. return $this->_options['accountDomainName'];
  389. }
  390. /**
  391. * @return string The short account domain name
  392. */
  393. protected function _getAccountDomainNameShort()
  394. {
  395. return $this->_options['accountDomainNameShort'];
  396. }
  397. /**
  398. * @return string A format string for building an LDAP search filter to match
  399. * an account
  400. */
  401. protected function _getAccountFilterFormat()
  402. {
  403. return $this->_options['accountFilterFormat'];
  404. }
  405. /**
  406. * @return boolean Allow empty passwords
  407. */
  408. protected function _getAllowEmptyPassword()
  409. {
  410. return $this->_options['allowEmptyPassword'];
  411. }
  412. /**
  413. * @return boolean The default SSL / TLS encrypted transport control
  414. */
  415. protected function _getUseStartTls()
  416. {
  417. return $this->_options['useStartTls'];
  418. }
  419. /**
  420. * @return boolean Opt. Referrals
  421. */
  422. protected function _getOptReferrals()
  423. {
  424. return $this->_options['optReferrals'];
  425. }
  426. /**
  427. * @return boolean Try splitting the username into username and domain
  428. */
  429. protected function _getTryUsernameSplit()
  430. {
  431. return $this->_options['tryUsernameSplit'];
  432. }
  433. /**
  434. * @return string The LDAP search filter for matching directory accounts
  435. */
  436. protected function _getAccountFilter($acctname)
  437. {
  438. /**
  439. * @see Zend_Ldap_Filter_Abstract
  440. */
  441. require_once 'Zend/Ldap/Filter/Abstract.php';
  442. $this->_splitName($acctname, $dname, $aname);
  443. $accountFilterFormat = $this->_getAccountFilterFormat();
  444. $aname = Zend_Ldap_Filter_Abstract::escapeValue($aname);
  445. if ($accountFilterFormat) {
  446. return sprintf($accountFilterFormat, $aname);
  447. }
  448. if (!$this->_getBindRequiresDn()) {
  449. // is there a better way to detect this?
  450. return sprintf("(&(objectClass=user)(sAMAccountName=%s))", $aname);
  451. }
  452. return sprintf("(&(objectClass=posixAccount)(uid=%s))", $aname);
  453. }
  454. /**
  455. * @param string $name The name to split
  456. * @param string $dname The resulting domain name (this is an out parameter)
  457. * @param string $aname The resulting account name (this is an out parameter)
  458. * @return void
  459. */
  460. protected function _splitName($name, &$dname, &$aname)
  461. {
  462. $dname = null;
  463. $aname = $name;
  464. if (!$this->_getTryUsernameSplit()) {
  465. return;
  466. }
  467. $pos = strpos($name, '@');
  468. if ($pos) {
  469. $dname = substr($name, $pos + 1);
  470. $aname = substr($name, 0, $pos);
  471. } else {
  472. $pos = strpos($name, '\\');
  473. if ($pos) {
  474. $dname = substr($name, 0, $pos);
  475. $aname = substr($name, $pos + 1);
  476. }
  477. }
  478. }
  479. /**
  480. * @param string $acctname The name of the account
  481. * @return string The DN of the specified account
  482. * @throws Zend_Ldap_Exception
  483. */
  484. protected function _getAccountDn($acctname)
  485. {
  486. /**
  487. * @see Zend_Ldap_Dn
  488. */
  489. require_once 'Zend/Ldap/Dn.php';
  490. if (Zend_Ldap_Dn::checkDn($acctname)) return $acctname;
  491. $acctname = $this->getCanonicalAccountName($acctname, Zend_Ldap::ACCTNAME_FORM_USERNAME);
  492. $acct = $this->_getAccount($acctname, array('dn'));
  493. return $acct['dn'];
  494. }
  495. /**
  496. * @param string $dname The domain name to check
  497. * @return boolean
  498. */
  499. protected function _isPossibleAuthority($dname)
  500. {
  501. if ($dname === null) {
  502. return true;
  503. }
  504. $accountDomainName = $this->_getAccountDomainName();
  505. $accountDomainNameShort = $this->_getAccountDomainNameShort();
  506. if ($accountDomainName === null && $accountDomainNameShort === null) {
  507. return true;
  508. }
  509. if (strcasecmp($dname, $accountDomainName) == 0) {
  510. return true;
  511. }
  512. if (strcasecmp($dname, $accountDomainNameShort) == 0) {
  513. return true;
  514. }
  515. return false;
  516. }
  517. /**
  518. * @param string $acctname The name to canonicalize
  519. * @param int $type The desired form of canonicalization
  520. * @return string The canonicalized name in the desired form
  521. * @throws Zend_Ldap_Exception
  522. */
  523. public function getCanonicalAccountName($acctname, $form = 0)
  524. {
  525. $this->_splitName($acctname, $dname, $uname);
  526. if (!$this->_isPossibleAuthority($dname)) {
  527. /**
  528. * @see Zend_Ldap_Exception
  529. */
  530. require_once 'Zend/Ldap/Exception.php';
  531. throw new Zend_Ldap_Exception(null,
  532. "Binding domain is not an authority for user: $acctname",
  533. Zend_Ldap_Exception::LDAP_X_DOMAIN_MISMATCH);
  534. }
  535. if (!$uname) {
  536. /**
  537. * @see Zend_Ldap_Exception
  538. */
  539. require_once 'Zend/Ldap/Exception.php';
  540. throw new Zend_Ldap_Exception(null, "Invalid account name syntax: $acctname");
  541. }
  542. if (function_exists('mb_strtolower')) {
  543. $uname = mb_strtolower($uname, 'UTF-8');
  544. } else {
  545. $uname = strtolower($uname);
  546. }
  547. if ($form === 0) {
  548. $form = $this->_getAccountCanonicalForm();
  549. }
  550. switch ($form) {
  551. case Zend_Ldap::ACCTNAME_FORM_DN:
  552. return $this->_getAccountDn($acctname);
  553. case Zend_Ldap::ACCTNAME_FORM_USERNAME:
  554. return $uname;
  555. case Zend_Ldap::ACCTNAME_FORM_BACKSLASH:
  556. $accountDomainNameShort = $this->_getAccountDomainNameShort();
  557. if (!$accountDomainNameShort) {
  558. /**
  559. * @see Zend_Ldap_Exception
  560. */
  561. require_once 'Zend/Ldap/Exception.php';
  562. throw new Zend_Ldap_Exception(null, 'Option required: accountDomainNameShort');
  563. }
  564. return "$accountDomainNameShort\\$uname";
  565. case Zend_Ldap::ACCTNAME_FORM_PRINCIPAL:
  566. $accountDomainName = $this->_getAccountDomainName();
  567. if (!$accountDomainName) {
  568. /**
  569. * @see Zend_Ldap_Exception
  570. */
  571. require_once 'Zend/Ldap/Exception.php';
  572. throw new Zend_Ldap_Exception(null, 'Option required: accountDomainName');
  573. }
  574. return "$uname@$accountDomainName";
  575. default:
  576. /**
  577. * @see Zend_Ldap_Exception
  578. */
  579. require_once 'Zend/Ldap/Exception.php';
  580. throw new Zend_Ldap_Exception(null, "Unknown canonical name form: $form");
  581. }
  582. }
  583. /**
  584. * @param array $attrs An array of names of desired attributes
  585. * @return array An array of the attributes representing the account
  586. * @throws Zend_Ldap_Exception
  587. */
  588. protected function _getAccount($acctname, array $attrs = null)
  589. {
  590. $baseDn = $this->getBaseDn();
  591. if (!$baseDn) {
  592. /**
  593. * @see Zend_Ldap_Exception
  594. */
  595. require_once 'Zend/Ldap/Exception.php';
  596. throw new Zend_Ldap_Exception(null, 'Base DN not set');
  597. }
  598. $accountFilter = $this->_getAccountFilter($acctname);
  599. if (!$accountFilter) {
  600. /**
  601. * @see Zend_Ldap_Exception
  602. */
  603. require_once 'Zend/Ldap/Exception.php';
  604. throw new Zend_Ldap_Exception(null, 'Invalid account filter');
  605. }
  606. if (!is_resource($this->getResource())) {
  607. $this->bind();
  608. }
  609. $accounts = $this->search($accountFilter, $baseDn, self::SEARCH_SCOPE_SUB, $attrs);
  610. $count = $accounts->count();
  611. if ($count === 1) {
  612. $acct = $accounts->getFirst();
  613. $accounts->close();
  614. return $acct;
  615. } else if ($count === 0) {
  616. /**
  617. * @see Zend_Ldap_Exception
  618. */
  619. require_once 'Zend/Ldap/Exception.php';
  620. $code = Zend_Ldap_Exception::LDAP_NO_SUCH_OBJECT;
  621. $str = "No object found for: $accountFilter";
  622. } else {
  623. /**
  624. * @see Zend_Ldap_Exception
  625. */
  626. require_once 'Zend/Ldap/Exception.php';
  627. $code = Zend_Ldap_Exception::LDAP_OPERATIONS_ERROR;
  628. $str = "Unexpected result count ($count) for: $accountFilter";
  629. }
  630. $accounts->close();
  631. /**
  632. * @see Zend_Ldap_Exception
  633. */
  634. require_once 'Zend/Ldap/Exception.php';
  635. throw new Zend_Ldap_Exception($this, $str, $code);
  636. }
  637. /**
  638. * @return Zend_Ldap Provides a fluent interface
  639. */
  640. public function disconnect()
  641. {
  642. if (is_resource($this->_resource)) {
  643. @ldap_unbind($this->_resource);
  644. }
  645. $this->_resource = null;
  646. $this->_boundUser = false;
  647. return $this;
  648. }
  649. /**
  650. * To connect using SSL it seems the client tries to verify the server
  651. * certificate by default. One way to disable this behavior is to set
  652. * 'TLS_REQCERT never' in OpenLDAP's ldap.conf and restarting Apache. Or,
  653. * if you really care about the server's cert you can put a cert on the
  654. * web server.
  655. *
  656. * @param string $host The hostname of the LDAP server to connect to
  657. * @param int $port The port number of the LDAP server to connect to
  658. * @param boolean $useSsl Use SSL
  659. * @param boolean $useStartTls Use STARTTLS
  660. * @return Zend_Ldap Provides a fluent interface
  661. * @throws Zend_Ldap_Exception
  662. */
  663. public function connect($host = null, $port = null, $useSsl = null, $useStartTls = null)
  664. {
  665. if ($host === null) {
  666. $host = $this->_getHost();
  667. }
  668. if ($port === null) {
  669. $port = $this->_getPort();
  670. } else {
  671. $port = (int)$port;
  672. }
  673. if ($useSsl === null) {
  674. $useSsl = $this->_getUseSsl();
  675. } else {
  676. $useSsl = (bool)$useSsl;
  677. }
  678. if ($useStartTls === null) {
  679. $useStartTls = $this->_getUseStartTls();
  680. } else {
  681. $useStartTls = (bool)$useStartTls;
  682. }
  683. if (!$host) {
  684. /**
  685. * @see Zend_Ldap_Exception
  686. */
  687. require_once 'Zend/Ldap/Exception.php';
  688. throw new Zend_Ldap_Exception(null, 'A host parameter is required');
  689. }
  690. $useUri = false;
  691. /* Because ldap_connect doesn't really try to connect, any connect error
  692. * will actually occur during the ldap_bind call. Therefore, we save the
  693. * connect string here for reporting it in error handling in bind().
  694. */
  695. $hosts = array();
  696. if (preg_match_all('~ldap(?:i|s)?://~', $host, $hosts, PREG_SET_ORDER) > 0) {
  697. $this->_connectString = $host;
  698. $useUri = true;
  699. $useSsl = false;
  700. } else {
  701. if ($useSsl) {
  702. $this->_connectString = 'ldaps://' . $host;
  703. $useUri = true;
  704. } else {
  705. $this->_connectString = 'ldap://' . $host;
  706. }
  707. if ($port) {
  708. $this->_connectString .= ':' . $port;
  709. }
  710. }
  711. $this->disconnect();
  712. /* Only OpenLDAP 2.2 + supports URLs so if SSL is not requested, just
  713. * use the old form.
  714. */
  715. $resource = ($useUri) ? @ldap_connect($this->_connectString) : @ldap_connect($host, $port);
  716. if (is_resource($resource) === true) {
  717. $this->_resource = $resource;
  718. $this->_boundUser = false;
  719. $optReferrals = ($this->_getOptReferrals()) ? 1 : 0;
  720. if (@ldap_set_option($resource, LDAP_OPT_PROTOCOL_VERSION, 3) &&
  721. @ldap_set_option($resource, LDAP_OPT_REFERRALS, $optReferrals)) {
  722. if ($useSsl || !$useStartTls || @ldap_start_tls($resource)) {
  723. return $this;
  724. }
  725. }
  726. /**
  727. * @see Zend_Ldap_Exception
  728. */
  729. require_once 'Zend/Ldap/Exception.php';
  730. $zle = new Zend_Ldap_Exception($this, "$host:$port");
  731. $this->disconnect();
  732. throw $zle;
  733. }
  734. /**
  735. * @see Zend_Ldap_Exception
  736. */
  737. require_once 'Zend/Ldap/Exception.php';
  738. throw new Zend_Ldap_Exception(null, "Failed to connect to LDAP server: $host:$port");
  739. }
  740. /**
  741. * @param string $username The username for authenticating the bind
  742. * @param string $password The password for authenticating the bind
  743. * @return Zend_Ldap Provides a fluent interface
  744. * @throws Zend_Ldap_Exception
  745. */
  746. public function bind($username = null, $password = null)
  747. {
  748. $moreCreds = true;
  749. // Security check: remove null bytes in password
  750. // @see https://net.educause.edu/ir/library/pdf/csd4875.pdf
  751. $password = str_replace("\0", '', $password);
  752. if ($username === null) {
  753. $username = $this->_getUsername();
  754. $password = $this->_getPassword();
  755. $moreCreds = false;
  756. }
  757. if (empty($username)) {
  758. /* Perform anonymous bind
  759. */
  760. $username = null;
  761. $password = null;
  762. } else {
  763. /* Check to make sure the username is in DN form.
  764. */
  765. /**
  766. * @see Zend_Ldap_Dn
  767. */
  768. require_once 'Zend/Ldap/Dn.php';
  769. if (!Zend_Ldap_Dn::checkDn($username)) {
  770. if ($this->_getBindRequiresDn()) {
  771. /* moreCreds stops an infinite loop if _getUsername does not
  772. * return a DN and the bind requires it
  773. */
  774. if ($moreCreds) {
  775. try {
  776. $username = $this->_getAccountDn($username);
  777. } catch (Zend_Ldap_Exception $zle) {
  778. switch ($zle->getCode()) {
  779. case Zend_Ldap_Exception::LDAP_NO_SUCH_OBJECT:
  780. case Zend_Ldap_Exception::LDAP_X_DOMAIN_MISMATCH:
  781. case Zend_Ldap_Exception::LDAP_X_EXTENSION_NOT_LOADED:
  782. throw $zle;
  783. }
  784. throw new Zend_Ldap_Exception(null,
  785. 'Failed to retrieve DN for account: ' . $username .
  786. ' [' . $zle->getMessage() . ']',
  787. Zend_Ldap_Exception::LDAP_OPERATIONS_ERROR);
  788. }
  789. } else {
  790. /**
  791. * @see Zend_Ldap_Exception
  792. */
  793. require_once 'Zend/Ldap/Exception.php';
  794. throw new Zend_Ldap_Exception(null, 'Binding requires username in DN form');
  795. }
  796. } else {
  797. $username = $this->getCanonicalAccountName($username,
  798. $this->_getAccountCanonicalForm());
  799. }
  800. }
  801. }
  802. if (!is_resource($this->_resource)) {
  803. $this->connect();
  804. }
  805. if ($username !== null && $password === '' && $this->_getAllowEmptyPassword() !== true) {
  806. /**
  807. * @see Zend_Ldap_Exception
  808. */
  809. require_once 'Zend/Ldap/Exception.php';
  810. $zle = new Zend_Ldap_Exception(null,
  811. 'Empty password not allowed - see allowEmptyPassword option.');
  812. } else {
  813. if (@ldap_bind($this->_resource, $username, $password)) {
  814. $this->_boundUser = $username;
  815. return $this;
  816. }
  817. $message = ($username === null) ? $this->_connectString : $username;
  818. /**
  819. * @see Zend_Ldap_Exception
  820. */
  821. require_once 'Zend/Ldap/Exception.php';
  822. switch ($this->getLastErrorCode()) {
  823. case Zend_Ldap_Exception::LDAP_SERVER_DOWN:
  824. /* If the error is related to establishing a connection rather than binding,
  825. * the connect string is more informative than the username.
  826. */
  827. $message = $this->_connectString;
  828. }
  829. $zle = new Zend_Ldap_Exception($this, $message);
  830. }
  831. $this->disconnect();
  832. throw $zle;
  833. }
  834. /**
  835. * A global LDAP search routine for finding information.
  836. *
  837. * Options can be either passed as single parameters according to the
  838. * method signature or as an array with one or more of the following keys
  839. * - filter
  840. * - baseDn
  841. * - scope
  842. * - attributes
  843. * - sort
  844. * - collectionClass
  845. * - sizelimit
  846. * - timelimit
  847. *
  848. * @param string|Zend_Ldap_Filter_Abstract|array $filter
  849. * @param string|Zend_Ldap_Dn|null $basedn
  850. * @param integer $scope
  851. * @param array $attributes
  852. * @param string|null $sort
  853. * @param string|null $collectionClass
  854. * @param integer $sizelimit
  855. * @param integer $timelimit
  856. * @return Zend_Ldap_Collection
  857. * @throws Zend_Ldap_Exception
  858. */
  859. public function search($filter, $basedn = null, $scope = self::SEARCH_SCOPE_SUB, array $attributes = array(),
  860. $sort = null, $collectionClass = null, $sizelimit = 0, $timelimit = 0)
  861. {
  862. if (is_array($filter)) {
  863. $options = array_change_key_case($filter, CASE_LOWER);
  864. foreach ($options as $key => $value) {
  865. switch ($key) {
  866. case 'filter':
  867. case 'basedn':
  868. case 'scope':
  869. case 'sort':
  870. $$key = $value;
  871. break;
  872. case 'attributes':
  873. if (is_array($value)) {
  874. $attributes = $value;
  875. }
  876. break;
  877. case 'collectionclass':
  878. $collectionClass = $value;
  879. break;
  880. case 'sizelimit':
  881. case 'timelimit':
  882. $$key = (int)$value;
  883. }
  884. }
  885. }
  886. if ($basedn === null) {
  887. $basedn = $this->getBaseDn();
  888. }
  889. else if ($basedn instanceof Zend_Ldap_Dn) {
  890. $basedn = $basedn->toString();
  891. }
  892. if ($filter instanceof Zend_Ldap_Filter_Abstract) {
  893. $filter = $filter->toString();
  894. }
  895. switch ($scope) {
  896. case self::SEARCH_SCOPE_ONE:
  897. $search = @ldap_list($this->getResource(), $basedn, $filter, $attributes, 0, $sizelimit, $timelimit);
  898. break;
  899. case self::SEARCH_SCOPE_BASE:
  900. $search = @ldap_read($this->getResource(), $basedn, $filter, $attributes, 0, $sizelimit, $timelimit);
  901. break;
  902. case self::SEARCH_SCOPE_SUB:
  903. default:
  904. $search = @ldap_search($this->getResource(), $basedn, $filter, $attributes, 0, $sizelimit, $timelimit);
  905. break;
  906. }
  907. if($search === false) {
  908. /**
  909. * @see Zend_Ldap_Exception
  910. */
  911. require_once 'Zend/Ldap/Exception.php';
  912. throw new Zend_Ldap_Exception($this, 'searching: ' . $filter);
  913. }
  914. if ($sort !== null && is_string($sort)) {
  915. $isSorted = @ldap_sort($this->getResource(), $search, $sort);
  916. if($isSorted === false) {
  917. /**
  918. * @see Zend_Ldap_Exception
  919. */
  920. require_once 'Zend/Ldap/Exception.php';
  921. throw new Zend_Ldap_Exception($this, 'sorting: ' . $sort);
  922. }
  923. }
  924. /**
  925. * Zend_Ldap_Collection_Iterator_Default
  926. */
  927. require_once 'Zend/Ldap/Collection/Iterator/Default.php';
  928. $iterator = new Zend_Ldap_Collection_Iterator_Default($this, $search);
  929. return $this->_createCollection($iterator, $collectionClass);
  930. }
  931. /**
  932. * Extension point for collection creation
  933. *
  934. * @param Zend_Ldap_Collection_Iterator_Default $iterator
  935. * @param string|null $collectionClass
  936. * @return Zend_Ldap_Collection
  937. * @throws Zend_Ldap_Exception
  938. */
  939. protected function _createCollection(Zend_Ldap_Collection_Iterator_Default $iterator, $collectionClass)
  940. {
  941. if ($collectionClass === null) {
  942. /**
  943. * Zend_Ldap_Collection
  944. */
  945. require_once 'Zend/Ldap/Collection.php';
  946. return new Zend_Ldap_Collection($iterator);
  947. } else {
  948. $collectionClass = (string)$collectionClass;
  949. if (!class_exists($collectionClass)) {
  950. /**
  951. * @see Zend_Ldap_Exception
  952. */
  953. require_once 'Zend/Ldap/Exception.php';
  954. throw new Zend_Ldap_Exception(null,
  955. "Class '$collectionClass' can not be found");
  956. }
  957. if (!is_subclass_of($collectionClass, 'Zend_Ldap_Collection')) {
  958. /**
  959. * @see Zend_Ldap_Exception
  960. */
  961. require_once 'Zend/Ldap/Exception.php';
  962. throw new Zend_Ldap_Exception(null,
  963. "Class '$collectionClass' must subclass 'Zend_Ldap_Collection'");
  964. }
  965. return new $collectionClass($iterator);
  966. }
  967. }
  968. /**
  969. * Count items found by given filter.
  970. *
  971. * @param string|Zend_Ldap_Filter_Abstract $filter
  972. * @param string|Zend_Ldap_Dn|null $basedn
  973. * @param integer $scope
  974. * @return integer
  975. * @throws Zend_Ldap_Exception
  976. */
  977. public function count($filter, $basedn = null, $scope = self::SEARCH_SCOPE_SUB)
  978. {
  979. try {
  980. $result = $this->search($filter, $basedn, $scope, array('dn'), null);
  981. } catch (Zend_Ldap_Exception $e) {
  982. if ($e->getCode() === Zend_Ldap_Exception::LDAP_NO_SUCH_OBJECT) return 0;
  983. else throw $e;
  984. }
  985. return $result->count();
  986. }
  987. /**
  988. * Count children for a given DN.
  989. *
  990. * @param string|Zend_Ldap_Dn $dn
  991. * @return integer
  992. * @throws Zend_Ldap_Exception
  993. */
  994. public function countChildren($dn)
  995. {
  996. return $this->count('(objectClass=*)', $dn, self::SEARCH_SCOPE_ONE);
  997. }
  998. /**
  999. * Check if a given DN exists.
  1000. *
  1001. * @param string|Zend_Ldap_Dn $dn
  1002. * @return boolean
  1003. * @throws Zend_Ldap_Exception
  1004. */
  1005. public function exists($dn)
  1006. {
  1007. return ($this->count('(objectClass=*)', $dn, self::SEARCH_SCOPE_BASE) == 1);
  1008. }
  1009. /**
  1010. * Search LDAP registry for entries matching filter and optional attributes
  1011. *
  1012. * Options can be either passed as single parameters according to the
  1013. * method signature or as an array with one or more of the following keys
  1014. * - filter
  1015. * - baseDn
  1016. * - scope
  1017. * - attributes
  1018. * - sort
  1019. * - reverseSort
  1020. * - sizelimit
  1021. * - timelimit
  1022. *
  1023. * @param string|Zend_Ldap_Filter_Abstract|array $filter
  1024. * @param string|Zend_Ldap_Dn|null $basedn
  1025. * @param integer $scope
  1026. * @param array $attributes
  1027. * @param string|null $sort
  1028. * @param boolean $reverseSort
  1029. * @param integer $sizelimit
  1030. * @param integer $timelimit
  1031. * @return array
  1032. * @throws Zend_Ldap_Exception
  1033. */
  1034. public function searchEntries($filter, $basedn = null, $scope = self::SEARCH_SCOPE_SUB,
  1035. array $attributes = array(), $sort = null, $reverseSort = false, $sizelimit = 0, $timelimit = 0)
  1036. {
  1037. if (is_array($filter)) {
  1038. $filter = array_change_key_case($filter, CASE_LOWER);
  1039. if (isset($filter['collectionclass'])) {
  1040. unset($filter['collectionclass']);
  1041. }
  1042. if (isset($filter['reversesort'])) {
  1043. $reverseSort = $filter['reversesort'];
  1044. unset($filter['reversesort']);
  1045. }
  1046. }
  1047. $result = $this->search($filter, $basedn, $scope, $attributes, $sort, null, $sizelimit, $timelimit);
  1048. $items = $result->toArray();
  1049. if ((bool)$reverseSort === true) {
  1050. $items = array_reverse($items, false);
  1051. }
  1052. return $items;
  1053. }
  1054. /**
  1055. * Get LDAP entry by DN
  1056. *
  1057. * @param string|Zend_Ldap_Dn $dn
  1058. * @param array $attributes
  1059. * @param boolean $throwOnNotFound
  1060. * @return array
  1061. * @throws Zend_Ldap_Exception
  1062. */
  1063. public function getEntry($dn, array $attributes = array(), $throwOnNotFound = false)
  1064. {
  1065. try {
  1066. $result = $this->search("(objectClass=*)", $dn, self::SEARCH_SCOPE_BASE,
  1067. $attributes, null);
  1068. return $result->getFirst();
  1069. } catch (Zend_Ldap_Exception $e){
  1070. if ($throwOnNotFound !== false) throw $e;
  1071. }
  1072. return null;
  1073. }
  1074. /**
  1075. * Prepares an ldap data entry array for insert/update operation
  1076. *
  1077. * @param array $entry
  1078. * @return void
  1079. * @throws InvalidArgumentException
  1080. */
  1081. public static function prepareLdapEntryArray(array &$entry)
  1082. {
  1083. if (array_key_exists('dn', $entry)) unset($entry['dn']);
  1084. foreach ($entry as $key => $value) {
  1085. if (is_array($value)) {
  1086. foreach ($value as $i => $v) {
  1087. if ($v === null) unset($value[$i]);
  1088. else if (!is_scalar($v)) {
  1089. throw new InvalidArgumentException('Only scalar values allowed in LDAP data');
  1090. } else {
  1091. $v = (string)$v;
  1092. if (strlen($v) == 0) {
  1093. unset($value[$i]);
  1094. } else {
  1095. $value[$i] = $v;
  1096. }
  1097. }
  1098. }
  1099. $entry[$key] = array_values($value);
  1100. } else {
  1101. if ($value === null) $entry[$key] = array();
  1102. else if (!is_scalar($value)) {
  1103. throw new InvalidArgumentException('Only scalar values allowed in LDAP data');
  1104. } else {
  1105. $value = (string)$value;
  1106. if (strlen($value) == 0) {
  1107. $entry[$key] = array();
  1108. } else {
  1109. $entry[$key] = array($value);
  1110. }
  1111. }
  1112. }
  1113. }
  1114. $entry = array_change_key_case($entry, CASE_LOWER);
  1115. }
  1116. /**
  1117. * Add new information to the LDAP repository
  1118. *
  1119. * @param string|Zend_Ldap_Dn $dn
  1120. * @param array $entry
  1121. * @return Zend_Ldap Provides a fluent interface
  1122. * @throws Zend_Ldap_Exception
  1123. */
  1124. public function add($dn, array $entry)
  1125. {
  1126. if (!($dn instanceof Zend_Ldap_Dn)) {
  1127. $dn = Zend_Ldap_Dn::factory($dn, null);
  1128. }
  1129. self::prepareLdapEntryArray($entry);
  1130. foreach ($entry as $key => $value) {
  1131. if (is_array($value) && count($value) === 0) {
  1132. unset($entry[$key]);
  1133. }
  1134. }
  1135. $rdnParts = $dn->getRdn(Zend_Ldap_Dn::ATTR_CASEFOLD_LOWER);
  1136. foreach ($rdnParts as $key => $value) {
  1137. $value = Zend_Ldap_Dn::unescapeValue($value);
  1138. if (!array_key_exists($key, $entry)) {
  1139. $entry[$key] = array($value);
  1140. } else if (!in_array($value, $entry[$key])) {
  1141. $entry[$key] = array_merge(array($value), $entry[$key]);
  1142. }
  1143. }
  1144. $adAttributes = array('distinguishedname', 'instancetype', 'name', 'objectcategory',
  1145. 'objectguid', 'usnchanged', 'usncreated', 'whenchanged', 'whencreated');
  1146. foreach ($adAttributes as $attr) {
  1147. if (array_key_exists($attr, $entry)) {
  1148. unset($entry[$attr]);
  1149. }
  1150. }
  1151. $isAdded = @ldap_add($this->getResource(), $dn->toString(), $entry);
  1152. if($isAdded === false) {
  1153. /**
  1154. * @see Zend_Ldap_Exception
  1155. */
  1156. require_once 'Zend/Ldap/Exception.php';
  1157. throw new Zend_Ldap_Exception($this, 'adding: ' . $dn->toString());
  1158. }
  1159. return $this;
  1160. }
  1161. /**
  1162. * Update LDAP registry
  1163. *
  1164. * @param string|Zend_Ldap_Dn $dn
  1165. * @param array $entry
  1166. * @return Zend_Ldap Provides a fluent interface
  1167. * @throws Zend_Ldap_Exception
  1168. */
  1169. public function update($dn, array $entry)
  1170. {
  1171. if (!($dn instanceof Zend_Ldap_Dn)) {
  1172. $dn = Zend_Ldap_Dn::factory($dn, null);
  1173. }
  1174. self::prepareLdapEntryArray($entry);
  1175. $rdnParts = $dn->getRdn(Zend_Ldap_Dn::ATTR_CASEFOLD_LOWER);
  1176. foreach ($rdnParts as $key => $value) {
  1177. $value = Zend_Ldap_Dn::unescapeValue($value);
  1178. if (array_key_exists($key, $entry) && !in_array($value, $entry[$key])) {
  1179. $entry[$key] = array_merge(array($value), $entry[$key]);
  1180. }
  1181. }
  1182. $adAttributes = array('distinguishedname', 'instancetype', 'name', 'objectcategory',
  1183. 'objectguid', 'usnchanged', 'usncreated', 'whenchanged', 'whencreated');
  1184. foreach ($adAttributes as $attr) {
  1185. if (array_key_exists($attr, $entry)) {
  1186. unset($entry[$attr]);
  1187. }
  1188. }
  1189. if (count($entry) > 0) {
  1190. $isModified = @ldap_modify($this->getResource(), $dn->toString(), $entry);
  1191. if($isModified === false) {
  1192. /**
  1193. * @see Zend_Ldap_Exception
  1194. */
  1195. require_once 'Zend/Ldap/Exception.php';
  1196. throw new Zend_Ldap_Exception($this, 'updating: ' . $dn->toString());
  1197. }
  1198. }
  1199. return $this;
  1200. }
  1201. /**
  1202. * Save entry to LDAP registry.
  1203. *
  1204. * Internally decides if entry will be updated to added by calling
  1205. * {@link exists()}.
  1206. *
  1207. * @param string|Zend_Ldap_Dn $dn
  1208. * @param array $entry
  1209. * @return Zend_Ldap Provides a fluent interface
  1210. * @throws Zend_Ldap_Exception
  1211. */
  1212. public function save($dn, array $entry)
  1213. {
  1214. if ($dn instanceof Zend_Ldap_Dn) {
  1215. $dn = $dn->toString();
  1216. }
  1217. if ($this->exists($dn)) $this->update($dn, $entry);
  1218. else $this->add($dn, $entry);
  1219. return $this;
  1220. }
  1221. /**
  1222. * Delete an LDAP entry
  1223. *
  1224. * @param string|Zend_Ldap_Dn $dn
  1225. * @param boolean $recursively
  1226. * @return Zend_Ldap Provides a fluent interface
  1227. * @throws Zend_Ldap_Exception
  1228. */
  1229. public function delete($dn, $recursively = false)
  1230. {
  1231. if ($dn instanceof Zend_Ldap_Dn) {
  1232. $dn = $dn->toString();
  1233. }
  1234. if ($recursively === true) {
  1235. if ($this->countChildren($dn)>0) {
  1236. $children = $this->_getChildrenDns($dn);
  1237. foreach ($children as $c) {
  1238. $this->delete($c, true);
  1239. }
  1240. }
  1241. }
  1242. $isDeleted = @ldap_delete($this->getResource(), $dn);
  1243. if($isDeleted === false) {
  1244. /**
  1245. * @see Zend_Ldap_Exception
  1246. */
  1247. require_once 'Zend/Ldap/Exception.php';
  1248. throw new Zend_Ldap_Exception($this, 'deleting: ' . $dn);
  1249. }
  1250. return $this;
  1251. }
  1252. /**
  1253. * Retrieve the immediate children DNs of the given $parentDn
  1254. *
  1255. * This method is used in recursive methods like {@see delete()}
  1256. * or {@see copy()}
  1257. *
  1258. * @param string|Zend_Ldap_Dn $parentDn
  1259. * @return array of DNs
  1260. */
  1261. protected function _getChildrenDns($parentDn)
  1262. {
  1263. if ($parentDn instanceof Zend_Ldap_Dn) {
  1264. $parentDn = $parentDn->toString();
  1265. }
  1266. $children = array();
  1267. $search = @ldap_list($this->getResource(), $parentDn, '(objectClass=*)', array('dn'));
  1268. for ($entry = @ldap_first_entry($this->getResource(), $search);
  1269. $entry !== false;
  1270. $entry = @ldap_next_entry($this->getResource(), $entry)) {
  1271. $childDn = @ldap_get_dn($this->getResource(), $entry);
  1272. if ($childDn === false) {
  1273. /**
  1274. * @see Zend_Ldap_Exception
  1275. */
  1276. require_once 'Zend/Ldap/Exception.php';
  1277. throw new Zend_Ldap_Exception($this, 'getting dn');
  1278. }
  1279. $children[] = $childDn;
  1280. }
  1281. @ldap_free_result($search);
  1282. return $children;
  1283. }
  1284. /**
  1285. * Moves a LDAP entry from one DN to another subtree.
  1286. *
  1287. * @param string|Zend_Ldap_Dn $from
  1288. * @param string|Zend_Ldap_Dn $to
  1289. * @param boolean $recursively
  1290. * @param boolean $alwaysEmulate
  1291. * @return Zend_Ldap Provides a fluent interface
  1292. * @throws Zend_Ldap_Exception
  1293. */
  1294. public function moveToSubtree($from, $to, $recursively = false, $alwaysEmulate = false)
  1295. {
  1296. if ($from instanceof Zend_Ldap_Dn) {
  1297. $orgDnParts = $from->toArray();
  1298. } else {
  1299. $orgDnParts = Zend_Ldap_Dn::explodeDn($from);
  1300. }
  1301. if ($to instanceof Zend_Ldap_Dn) {
  1302. $newParentDnParts = $to->toArray();
  1303. } else {
  1304. $newParentDnParts = Zend_Ldap_Dn::explodeDn($to);
  1305. }
  1306. $newDnParts = array_merge(array(array_shift($orgDnParts)), $newParentDnParts);
  1307. $newDn = Zend_Ldap_Dn::fromArray($newDnParts);
  1308. return $this->rename($from, $newDn, $recursively, $alwaysEmulate);
  1309. }
  1310. /**
  1311. * Moves a LDAP entry from one DN to another DN.
  1312. *
  1313. * This is an alias for {@link rename()}
  1314. *
  1315. * @param string|Zend_Ldap_Dn $from
  1316. * @param string|Zend_Ldap_Dn $to
  1317. * @param boolean $recursively
  1318. * @param boolean $alwaysEmulate
  1319. * @return Zend_Ldap Provides a fluent interface
  1320. * @throws Zend_Ldap_Exception
  1321. */
  1322. public function move($from, $to, $recursively = false, $alwaysEmulate = false)
  1323. {
  1324. return $this->rename($from, $to, $recursively, $alwaysEmulate);
  1325. }
  1326. /**
  1327. * Renames a LDAP entry from one DN to another DN.
  1328. *
  1329. * This method implicitely moves the entry to another location within the tree.
  1330. *
  1331. * @param string|Zend_Ldap_Dn $from
  1332. * @param string|Zend_Ldap_Dn $to
  1333. * @param boolean $recursively
  1334. * @param boolean $alwaysEmulate
  1335. * @return Zend_Ldap Provides a fluent interface
  1336. * @throws Zend_Ldap_Exception
  1337. */
  1338. public function rename($from, $to, $recursively = false, $alwaysEmulate = false)
  1339. {
  1340. $emulate = (bool)$alwaysEmulate;
  1341. if (!function_exists('ldap_rename')) $emulate = true;
  1342. else if ($recursively) $emulate = true;
  1343. if ($emulate === false) {
  1344. if ($from instanceof Zend_Ldap_Dn) {
  1345. $from = $from->toString();
  1346. }
  1347. if ($to instanceof Zend_Ldap_Dn) {
  1348. $newDnParts = $to->toArray();
  1349. } else {
  1350. $newDnParts = Zend_Ldap_Dn::explodeDn($to);
  1351. }
  1352. $newRdn = Zend_Ldap_Dn::implodeRdn(array_shift($newDnParts));
  1353. $newParent = Zend_Ldap_Dn::implodeDn($newDnParts);
  1354. $isOK = @ldap_rename($this->getResource(), $from, $newRdn, $newParent, true);
  1355. if($isOK === false) {
  1356. /**
  1357. * @see Zend_Ldap_Exception
  1358. */
  1359. require_once 'Zend/Ldap/Exception.php';
  1360. throw new Zend_Ldap_Exception($this, 'renaming ' . $from . ' to ' . $to);
  1361. }
  1362. else if (!$this->exists($to)) $emulate = true;
  1363. }
  1364. if ($emulate) {
  1365. $this->copy($from, $to, $recursively);
  1366. $this->delete($from, $recursively);
  1367. }
  1368. return $this;
  1369. }
  1370. /**
  1371. * Copies a LDAP entry from one DN to another subtree.
  1372. *
  1373. * @param string|Zend_Ldap_Dn $from
  1374. * @param string|Zend_Ldap_Dn $to
  1375. * @param boolean $recursively
  1376. * @return Zend_Ldap Provides a fluent interface
  1377. * @throws Zend_Ldap_Exception
  1378. */
  1379. public function copyToSubtree($from, $to, $recursively = false)
  1380. {
  1381. if ($from instanceof Zend_Ldap_Dn) {
  1382. $orgDnParts = $from->toArray();
  1383. } else {
  1384. $orgDnParts = Zend_Ldap_Dn::explodeDn($from);
  1385. }
  1386. if ($to instanceof Zend_Ldap_Dn) {
  1387. $newParentDnParts = $to->toArray();
  1388. } else {
  1389. $newParentDnParts = Zend_Ldap_Dn::explodeDn($to);
  1390. }
  1391. $newDnParts = array_merge(array(array_shift($orgDnParts)), $newParentDnParts);
  1392. $newDn = Zend_Ldap_Dn::fromArray($newDnParts);
  1393. return $this->copy($from, $newDn, $recursively);
  1394. }
  1395. /**
  1396. * Copies a LDAP entry from one DN to another DN.
  1397. *
  1398. * @param string|Zend_Ldap_Dn $from
  1399. * @param string|Zend_Ldap_Dn $to
  1400. * @param boolean $recursively
  1401. * @return Zend_Ldap Provides a fluent interface
  1402. * @throws Zend_Ldap_Exception
  1403. */
  1404. public function copy($from, $to, $recursively = false)
  1405. {
  1406. $entry = $this->getEntry($from, array(), true);
  1407. if ($to instanceof Zend_Ldap_Dn) {
  1408. $toDnParts = $to->toArray();
  1409. } else {
  1410. $toDnParts = Zend_Ldap_Dn::explodeDn($to);
  1411. }
  1412. $this->add($to, $entry);
  1413. if ($recursively === true && $this->countChildren($from)>0) {
  1414. $children = $this->_getChildrenDns($from);
  1415. foreach ($children as $c) {
  1416. $cDnParts = Zend_Ldap_Dn::explodeDn($c);
  1417. $newChildParts = array_merge(array(array_shift($cDnParts)), $toDnParts);
  1418. $newChild = Zend_Ldap_Dn::implodeDn($newChildParts);
  1419. $this->copy($c, $newChild, true);
  1420. }
  1421. }
  1422. return $this;
  1423. }
  1424. /**
  1425. * Returns the specified DN as a Zend_Ldap_Node
  1426. *
  1427. * @param string|Zend_Ldap_Dn $dn
  1428. * @return Zend_Ldap_Node|null
  1429. * @throws Zend_Ldap_Exception
  1430. */
  1431. public function getNode($dn)
  1432. {
  1433. /**
  1434. * Zend_Ldap_Node
  1435. */
  1436. require_once 'Zend/Ldap/Node.php';
  1437. return Zend_Ldap_Node::fromLdap($dn, $this);
  1438. }
  1439. /**
  1440. * Returns the base node as a Zend_Ldap_Node
  1441. *
  1442. * @return Zend_Ldap_Node
  1443. * @throws Zend_Ldap_Exception
  1444. */
  1445. public function getBaseNode()
  1446. {
  1447. return $this->getNode($this->getBaseDn(), $this);
  1448. }
  1449. /**
  1450. * Returns the RootDSE
  1451. *
  1452. * @return Zend_Ldap_Node_RootDse
  1453. * @throws Zend_Ldap_Exception
  1454. */
  1455. public function getRootDse()
  1456. {
  1457. if ($this->_rootDse === null) {
  1458. /**
  1459. * @see Zend_Ldap_Node_Schema
  1460. */
  1461. require_once 'Zend/Ldap/Node/RootDse.php';
  1462. $this->_rootDse = Zend_Ldap_Node_RootDse::create($this);
  1463. }
  1464. return $this->_rootDse;
  1465. }
  1466. /**
  1467. * Returns the schema
  1468. *
  1469. * @return Zend_Ldap_Node_Schema
  1470. * @throws Zend_Ldap_Exception
  1471. */
  1472. public function getSchema()
  1473. {
  1474. if ($this->_schema === null) {
  1475. /**
  1476. * @see Zend_Ldap_Node_Schema
  1477. */
  1478. require_once 'Zend/Ldap/Node/Schema.php';
  1479. $this->_schema = Zend_Ldap_Node_Schema::create($this);
  1480. }
  1481. return $this->_schema;
  1482. }
  1483. }