Search.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632
  1. <?php
  2. /* vim: set expandtab tabstop=4 shiftwidth=4: */
  3. /**
  4. * File containing the Net_LDAP2_Search interface class.
  5. *
  6. * PHP version 5
  7. *
  8. * @category Net
  9. * @package Net_LDAP2
  10. * @author Tarjej Huse <tarjei@bergfald.no>
  11. * @author Benedikt Hallinger <beni@php.net>
  12. * @copyright 2009 Tarjej Huse, Benedikt Hallinger
  13. * @license http://www.gnu.org/licenses/lgpl-3.0.txt LGPLv3
  14. * @version SVN: $Id$
  15. * @link http://pear.php.net/package/Net_LDAP2/
  16. */
  17. /**
  18. * Includes
  19. */
  20. require_once 'PEAR.php';
  21. /**
  22. * Result set of an LDAP search
  23. *
  24. * @category Net
  25. * @package Net_LDAP2
  26. * @author Tarjej Huse <tarjei@bergfald.no>
  27. * @author Benedikt Hallinger <beni@php.net>
  28. * @license http://www.gnu.org/copyleft/lesser.html LGPL
  29. * @link http://pear.php.net/package/Net_LDAP22/
  30. */
  31. class Net_LDAP2_Search extends PEAR implements Iterator
  32. {
  33. /**
  34. * Search result identifier
  35. *
  36. * @access protected
  37. * @var resource
  38. */
  39. protected $_search;
  40. /**
  41. * LDAP resource link
  42. *
  43. * @access protected
  44. * @var resource
  45. */
  46. protected $_link;
  47. /**
  48. * Net_LDAP2 object
  49. *
  50. * A reference of the Net_LDAP2 object for passing to Net_LDAP2_Entry
  51. *
  52. * @access protected
  53. * @var object Net_LDAP2
  54. */
  55. protected $_ldap;
  56. /**
  57. * Result entry identifier
  58. *
  59. * @access protected
  60. * @var resource
  61. */
  62. protected $_entry = null;
  63. /**
  64. * The errorcode the search got
  65. *
  66. * Some errorcodes might be of interest, but might not be best handled as errors.
  67. * examples: 4 - LDAP_SIZELIMIT_EXCEEDED - indicates a huge search.
  68. * Incomplete results are returned. If you just want to check if there's anything in the search.
  69. * than this is a point to handle.
  70. * 32 - no such object - search here returns a count of 0.
  71. *
  72. * @access protected
  73. * @var int
  74. */
  75. protected $_errorCode = 0; // if not set - sucess!
  76. /**
  77. * Cache for all entries already fetched from iterator interface
  78. *
  79. * @access protected
  80. * @var array
  81. */
  82. protected $_iteratorCache = array();
  83. /**
  84. * What attributes we searched for
  85. *
  86. * The $attributes array contains the names of the searched attributes and gets
  87. * passed from $Net_LDAP2->search() so the Net_LDAP2_Search object can tell
  88. * what attributes was searched for ({@link searchedAttrs())
  89. *
  90. * This variable gets set from the constructor and returned
  91. * from {@link searchedAttrs()}
  92. *
  93. * @access protected
  94. * @var array
  95. */
  96. protected $_searchedAttrs = array();
  97. /**
  98. * Cache variable for storing entries fetched internally
  99. *
  100. * This currently is not used by all functions and need consolidation.
  101. *
  102. * @access protected
  103. * @var array
  104. */
  105. protected $_entry_cache = false;
  106. /**
  107. * Cache variable for count()
  108. *
  109. * @see count()
  110. * @access protected
  111. * @var int
  112. */
  113. protected $_count_cache = null;
  114. /**
  115. * Constructor
  116. *
  117. * @param resource $search Search result identifier
  118. * @param Net_LDAP2|resource $ldap Net_LDAP2 object or just a LDAP-Link resource
  119. * @param array $attributes (optional) Array with searched attribute names. (see {@link $_searchedAttrs})
  120. *
  121. * @access public
  122. */
  123. public function __construct($search, $ldap, $attributes = array())
  124. {
  125. parent::__construct('Net_LDAP2_Error');
  126. $this->setSearch($search);
  127. if ($ldap instanceof Net_LDAP2) {
  128. $this->_ldap = $ldap;
  129. $this->setLink($this->_ldap->getLink());
  130. } else {
  131. $this->setLink($ldap);
  132. }
  133. $this->_errorCode = @ldap_errno($this->_link);
  134. if (is_array($attributes) && !empty($attributes)) {
  135. $this->_searchedAttrs = $attributes;
  136. }
  137. }
  138. /**
  139. * Returns an array of entry objects.
  140. *
  141. * @return array Array of entry objects.
  142. */
  143. public function entries()
  144. {
  145. $entries = array();
  146. if (false === $this->_entry_cache) {
  147. // cache is empty: fetch from LDAP
  148. while ($entry = $this->shiftEntry()) {
  149. $entries[] = $entry;
  150. }
  151. $this->_entry_cache = $entries; // store result in cache
  152. }
  153. return $this->_entry_cache;
  154. }
  155. /**
  156. * Get the next entry in the searchresult from LDAP server.
  157. *
  158. * This will return a valid Net_LDAP2_Entry object or false, so
  159. * you can use this method to easily iterate over the entries inside
  160. * a while loop.
  161. *
  162. * @return Net_LDAP2_Entry|false Reference to Net_LDAP2_Entry object or false
  163. */
  164. public function shiftEntry()
  165. {
  166. if (is_null($this->_entry)) {
  167. if(!$this->_entry = @ldap_first_entry($this->_link, $this->_search)) {
  168. $false = false;
  169. return $false;
  170. }
  171. $entry = Net_LDAP2_Entry::createConnected($this->_ldap, $this->_entry);
  172. if ($entry instanceof PEAR_Error) $entry = false;
  173. } else {
  174. if (!$this->_entry = @ldap_next_entry($this->_link, $this->_entry)) {
  175. $false = false;
  176. return $false;
  177. }
  178. $entry = Net_LDAP2_Entry::createConnected($this->_ldap, $this->_entry);
  179. if ($entry instanceof PEAR_Error) $entry = false;
  180. }
  181. return $entry;
  182. }
  183. /**
  184. * Alias function of shiftEntry() for perl-ldap interface
  185. *
  186. * @see shiftEntry()
  187. * @return Net_LDAP2_Entry|false
  188. */
  189. public function shift_entry()
  190. {
  191. $args = func_get_args();
  192. return call_user_func_array(array( $this, 'shiftEntry' ), $args);
  193. }
  194. /**
  195. * Retrieve the next entry in the searchresult, but starting from last entry
  196. *
  197. * This is the opposite to {@link shiftEntry()} and is also very useful
  198. * to be used inside a while loop.
  199. *
  200. * @return Net_LDAP2_Entry|false
  201. */
  202. public function popEntry()
  203. {
  204. if (false === $this->_entry_cache) {
  205. // fetch entries into cache if not done so far
  206. $this->_entry_cache = $this->entries();
  207. }
  208. $return = array_pop($this->_entry_cache);
  209. return (null === $return)? false : $return;
  210. }
  211. /**
  212. * Alias function of popEntry() for perl-ldap interface
  213. *
  214. * @see popEntry()
  215. * @return Net_LDAP2_Entry|false
  216. */
  217. public function pop_entry()
  218. {
  219. $args = func_get_args();
  220. return call_user_func_array(array( $this, 'popEntry' ), $args);
  221. }
  222. /**
  223. * Return entries sorted as array
  224. *
  225. * This returns a array with sorted entries and the values.
  226. * Sorting is done with PHPs {@link array_multisort()}.
  227. * This method relies on {@link as_struct()} to fetch the raw data of the entries.
  228. *
  229. * Please note that attribute names are case sensitive!
  230. *
  231. * Usage example:
  232. * <code>
  233. * // to sort entries first by location, then by surename, but descending:
  234. * $entries = $search->sorted_as_struct(array('locality','sn'), SORT_DESC);
  235. * </code>
  236. *
  237. * @param array $attrs Array of attribute names to sort; order from left to right.
  238. * @param int $order Ordering direction, either constant SORT_ASC or SORT_DESC
  239. *
  240. * @return array|Net_LDAP2_Error Array with sorted entries or error
  241. * @todo what about server side sorting as specified in http://www.ietf.org/rfc/rfc2891.txt?
  242. */
  243. public function sorted_as_struct($attrs = array('cn'), $order = SORT_ASC)
  244. {
  245. /*
  246. * Old Code, suitable and fast for single valued sorting
  247. * This code should be used if we know that single valued sorting is desired,
  248. * but we need some method to get that knowledge...
  249. */
  250. /*
  251. $attrs = array_reverse($attrs);
  252. foreach ($attrs as $attribute) {
  253. if (!ldap_sort($this->_link, $this->_search, $attribute)){
  254. $this->raiseError("Sorting failed for Attribute " . $attribute);
  255. }
  256. }
  257. $results = ldap_get_entries($this->_link, $this->_search);
  258. unset($results['count']); //for tidier output
  259. if ($order) {
  260. return array_reverse($results);
  261. } else {
  262. return $results;
  263. }*/
  264. /*
  265. * New code: complete "client side" sorting
  266. */
  267. // first some parameterchecks
  268. if (!is_array($attrs)) {
  269. return PEAR::raiseError("Sorting failed: Parameterlist must be an array!");
  270. }
  271. if ($order != SORT_ASC && $order != SORT_DESC) {
  272. return PEAR::raiseError("Sorting failed: sorting direction not understood! (neither constant SORT_ASC nor SORT_DESC)");
  273. }
  274. // fetch the entries data
  275. $entries = $this->as_struct();
  276. // now sort each entries attribute values
  277. // this is neccessary because later we can only sort by one value,
  278. // so we need the highest or lowest attribute now, depending on the
  279. // selected ordering for that specific attribute
  280. foreach ($entries as $dn => $entry) {
  281. foreach ($entry as $attr_name => $attr_values) {
  282. sort($entries[$dn][$attr_name]);
  283. if ($order == SORT_DESC) {
  284. array_reverse($entries[$dn][$attr_name]);
  285. }
  286. }
  287. }
  288. // reformat entrys array for later use with array_multisort()
  289. $to_sort = array(); // <- will be a numeric array similar to ldap_get_entries
  290. foreach ($entries as $dn => $entry_attr) {
  291. $row = array();
  292. $row['dn'] = $dn;
  293. foreach ($entry_attr as $attr_name => $attr_values) {
  294. $row[$attr_name] = $attr_values;
  295. }
  296. $to_sort[] = $row;
  297. }
  298. // Build columns for array_multisort()
  299. // each requested attribute is one row
  300. $columns = array();
  301. foreach ($attrs as $attr_name) {
  302. foreach ($to_sort as $key => $row) {
  303. $columns[$attr_name][$key] =& $to_sort[$key][$attr_name][0];
  304. }
  305. }
  306. // sort the colums with array_multisort, if there is something
  307. // to sort and if we have requested sort columns
  308. if (!empty($to_sort) && !empty($columns)) {
  309. $sort_params = '';
  310. foreach ($attrs as $attr_name) {
  311. $sort_params .= '$columns[\''.$attr_name.'\'], '.$order.', ';
  312. }
  313. eval("array_multisort($sort_params \$to_sort);"); // perform sorting
  314. }
  315. return $to_sort;
  316. }
  317. /**
  318. * Return entries sorted as objects
  319. *
  320. * This returns a array with sorted Net_LDAP2_Entry objects.
  321. * The sorting is actually done with {@link sorted_as_struct()}.
  322. *
  323. * Please note that attribute names are case sensitive!
  324. * Also note, that it is (depending on server capabilitys) possible to let
  325. * the server sort your results. This happens through search controls
  326. * and is described in detail at {@link http://www.ietf.org/rfc/rfc2891.txt}
  327. *
  328. * Usage example:
  329. * <code>
  330. * // to sort entries first by location, then by surename, but descending:
  331. * $entries = $search->sorted(array('locality','sn'), SORT_DESC);
  332. * </code>
  333. *
  334. * @param array $attrs Array of sort attributes to sort; order from left to right.
  335. * @param int $order Ordering direction, either constant SORT_ASC or SORT_DESC
  336. *
  337. * @return array|Net_LDAP2_Error Array with sorted Net_LDAP2_Entries or error
  338. * @todo Entry object construction could be faster. Maybe we could use one of the factorys instead of fetching the entry again
  339. */
  340. public function sorted($attrs = array('cn'), $order = SORT_ASC)
  341. {
  342. $return = array();
  343. $sorted = $this->sorted_as_struct($attrs, $order);
  344. if (PEAR::isError($sorted)) {
  345. return $sorted;
  346. }
  347. foreach ($sorted as $key => $row) {
  348. $entry = $this->_ldap->getEntry($row['dn'], $this->searchedAttrs());
  349. if (!PEAR::isError($entry)) {
  350. array_push($return, $entry);
  351. } else {
  352. return $entry;
  353. }
  354. }
  355. return $return;
  356. }
  357. /**
  358. * Return entries as array
  359. *
  360. * This method returns the entries and the selected attributes values as
  361. * array.
  362. * The first array level contains all found entries where the keys are the
  363. * DNs of the entries. The second level arrays contian the entries attributes
  364. * such that the keys is the lowercased name of the attribute and the values
  365. * are stored in another indexed array. Note that the attribute values are stored
  366. * in an array even if there is no or just one value.
  367. *
  368. * The array has the following structure:
  369. * <code>
  370. * $return = array(
  371. * 'cn=foo,dc=example,dc=com' => array(
  372. * 'sn' => array('foo'),
  373. * 'multival' => array('val1', 'val2', 'valN')
  374. * )
  375. * 'cn=bar,dc=example,dc=com' => array(
  376. * 'sn' => array('bar'),
  377. * 'multival' => array('val1', 'valN')
  378. * )
  379. * )
  380. * </code>
  381. *
  382. * @return array associative result array as described above
  383. */
  384. public function as_struct()
  385. {
  386. $return = array();
  387. $entries = $this->entries();
  388. foreach ($entries as $entry) {
  389. $attrs = array();
  390. $entry_attributes = $entry->attributes();
  391. foreach ($entry_attributes as $attr_name) {
  392. $attr_values = $entry->getValue($attr_name, 'all');
  393. if (!is_array($attr_values)) {
  394. $attr_values = array($attr_values);
  395. }
  396. $attrs[$attr_name] = $attr_values;
  397. }
  398. $return[$entry->dn()] = $attrs;
  399. }
  400. return $return;
  401. }
  402. /**
  403. * Set the search objects resource link
  404. *
  405. * @param resource $search Search result identifier
  406. *
  407. * @access public
  408. * @return void
  409. */
  410. public function setSearch($search)
  411. {
  412. $this->_search = $search;
  413. }
  414. /**
  415. * Set the ldap ressource link
  416. *
  417. * @param resource $link Link identifier
  418. *
  419. * @access public
  420. * @return void
  421. */
  422. public function setLink($link)
  423. {
  424. $this->_link = $link;
  425. }
  426. /**
  427. * Returns the number of entries in the searchresult
  428. *
  429. * @return int Number of entries in search.
  430. */
  431. public function count()
  432. {
  433. // this catches the situation where OL returned errno 32 = no such object!
  434. if (!$this->_search) {
  435. return 0;
  436. }
  437. // ldap_count_entries is slow (see pear bug #18752) with large results,
  438. // so we cache the result internally.
  439. if ($this->_count_cache === null) {
  440. $this->_count_cache = @ldap_count_entries($this->_link, $this->_search);
  441. }
  442. return $this->_count_cache;
  443. }
  444. /**
  445. * Get the errorcode the object got in its search.
  446. *
  447. * @return int The ldap error number.
  448. */
  449. public function getErrorCode()
  450. {
  451. return $this->_errorCode;
  452. }
  453. /**
  454. * Destructor
  455. *
  456. * @access protected
  457. */
  458. public function _Net_LDAP2_Search()
  459. {
  460. @ldap_free_result($this->_search);
  461. }
  462. /**
  463. * Closes search result
  464. *
  465. * @return void
  466. */
  467. public function done()
  468. {
  469. $this->_Net_LDAP2_Search();
  470. }
  471. /**
  472. * Return the attribute names this search selected
  473. *
  474. * @return array
  475. * @see $_searchedAttrs
  476. * @access protected
  477. */
  478. protected function searchedAttrs()
  479. {
  480. return $this->_searchedAttrs;
  481. }
  482. /**
  483. * Tells if this search exceeds a sizelimit
  484. *
  485. * @return boolean
  486. */
  487. public function sizeLimitExceeded()
  488. {
  489. return ($this->getErrorCode() == 4);
  490. }
  491. /*
  492. * SPL Iterator interface methods.
  493. * This interface allows to use Net_LDAP2_Search
  494. * objects directly inside a foreach loop!
  495. */
  496. /**
  497. * SPL Iterator interface: Return the current element.
  498. *
  499. * The SPL Iterator interface allows you to fetch entries inside
  500. * a foreach() loop: <code>foreach ($search as $dn => $entry) { ...</code>
  501. *
  502. * Of course, you may call {@link current()}, {@link key()}, {@link next()},
  503. * {@link rewind()} and {@link valid()} yourself.
  504. *
  505. * If the search throwed an error, it returns false.
  506. * False is also returned, if the end is reached
  507. * In case no call to next() was made, we will issue one,
  508. * thus returning the first entry.
  509. *
  510. * @return Net_LDAP2_Entry|false
  511. */
  512. public function current()
  513. {
  514. if (count($this->_iteratorCache) == 0) {
  515. $this->next();
  516. reset($this->_iteratorCache);
  517. }
  518. $entry = current($this->_iteratorCache);
  519. return ($entry instanceof Net_LDAP2_Entry)? $entry : false;
  520. }
  521. /**
  522. * SPL Iterator interface: Return the identifying key (DN) of the current entry.
  523. *
  524. * @see current()
  525. * @return string|false DN of the current entry; false in case no entry is returned by current()
  526. */
  527. public function key()
  528. {
  529. $entry = $this->current();
  530. return ($entry instanceof Net_LDAP2_Entry)? $entry->dn() :false;
  531. }
  532. /**
  533. * SPL Iterator interface: Move forward to next entry.
  534. *
  535. * After a call to {@link next()}, {@link current()} will return
  536. * the next entry in the result set.
  537. *
  538. * @see current()
  539. * @return void
  540. */
  541. public function next()
  542. {
  543. // fetch next entry.
  544. // if we have no entrys anymore, we add false (which is
  545. // returned by shiftEntry()) so current() will complain.
  546. if (count($this->_iteratorCache) - 1 <= $this->count()) {
  547. $this->_iteratorCache[] = $this->shiftEntry();
  548. }
  549. // move on array pointer to current element.
  550. // even if we have added all entries, this will
  551. // ensure proper operation in case we rewind()
  552. next($this->_iteratorCache);
  553. }
  554. /**
  555. * SPL Iterator interface: Check if there is a current element after calls to {@link rewind()} or {@link next()}.
  556. *
  557. * Used to check if we've iterated to the end of the collection.
  558. *
  559. * @see current()
  560. * @return boolean FALSE if there's nothing more to iterate over
  561. */
  562. public function valid()
  563. {
  564. return ($this->current() instanceof Net_LDAP2_Entry);
  565. }
  566. /**
  567. * SPL Iterator interface: Rewind the Iterator to the first element.
  568. *
  569. * After rewinding, {@link current()} will return the first entry in the result set.
  570. *
  571. * @see current()
  572. * @return void
  573. */
  574. public function rewind()
  575. {
  576. reset($this->_iteratorCache);
  577. }
  578. }
  579. ?>