2 /* vim: set expandtab tabstop=4 shiftwidth=4: */
4 * File containing the Net_LDAP2_Search interface class.
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: Search.php 328961 2013-01-03 09:04:30Z beni $
15 * @link http://pear.php.net/package/Net_LDAP2/
21 require_once 'PEAR.php';
24 * Result set of an LDAP search
28 * @author Tarjej Huse <tarjei@bergfald.no>
29 * @author Benedikt Hallinger <beni@php.net>
30 * @license http://www.gnu.org/copyleft/lesser.html LGPL
31 * @link http://pear.php.net/package/Net_LDAP22/
33 class Net_LDAP2_Search extends PEAR implements Iterator
36 * Search result identifier
54 * A reference of the Net_LDAP2 object for passing to Net_LDAP2_Entry
57 * @var object Net_LDAP2
62 * Result entry identifier
67 protected $_entry = null;
70 * The errorcode the search got
72 * Some errorcodes might be of interest, but might not be best handled as errors.
73 * examples: 4 - LDAP_SIZELIMIT_EXCEEDED - indicates a huge search.
74 * Incomplete results are returned. If you just want to check if there's anything in the search.
75 * than this is a point to handle.
76 * 32 - no such object - search here returns a count of 0.
81 protected $_errorCode = 0; // if not set - sucess!
84 * Cache for all entries already fetched from iterator interface
89 protected $_iteratorCache = array();
92 * What attributes we searched for
94 * The $attributes array contains the names of the searched attributes and gets
95 * passed from $Net_LDAP2->search() so the Net_LDAP2_Search object can tell
96 * what attributes was searched for ({@link searchedAttrs())
98 * This variable gets set from the constructor and returned
99 * from {@link searchedAttrs()}
104 protected $_searchedAttrs = array();
107 * Cache variable for storing entries fetched internally
109 * This currently is not used by all functions and need consolidation.
114 protected $_entry_cache = false;
117 * Cache variable for count()
123 protected $_count_cache = null;
128 * @param resource &$search Search result identifier
129 * @param Net_LDAP2|resource &$ldap Net_LDAP2 object or just a LDAP-Link resource
130 * @param array $attributes (optional) Array with searched attribute names. (see {@link $_searchedAttrs})
134 public function __construct(&$search, &$ldap, $attributes = array())
136 $this->PEAR('Net_LDAP2_Error');
138 $this->setSearch($search);
140 if ($ldap instanceof Net_LDAP2) {
141 $this->_ldap =& $ldap;
142 $this->setLink($this->_ldap->getLink());
144 $this->setLink($ldap);
147 $this->_errorCode = @ldap_errno($this->_link);
149 if (is_array($attributes) && !empty($attributes)) {
150 $this->_searchedAttrs = $attributes;
155 * Returns an array of entry objects.
157 * @return array Array of entry objects.
159 public function entries()
163 if (false === $this->_entry_cache) {
164 // cache is empty: fetch from LDAP
165 while ($entry = $this->shiftEntry()) {
168 $this->_entry_cache = $entries; // store result in cache
171 return $this->_entry_cache;
175 * Get the next entry in the searchresult from LDAP server.
177 * This will return a valid Net_LDAP2_Entry object or false, so
178 * you can use this method to easily iterate over the entries inside
181 * @return Net_LDAP2_Entry|false Reference to Net_LDAP2_Entry object or false
183 public function &shiftEntry()
185 if (is_null($this->_entry)) {
186 if(!$this->_entry = @ldap_first_entry($this->_link, $this->_search)) {
190 $entry = Net_LDAP2_Entry::createConnected($this->_ldap, $this->_entry);
191 if ($entry instanceof PEAR_Error) $entry = false;
193 if (!$this->_entry = @ldap_next_entry($this->_link, $this->_entry)) {
197 $entry = Net_LDAP2_Entry::createConnected($this->_ldap, $this->_entry);
198 if ($entry instanceof PEAR_Error) $entry = false;
204 * Alias function of shiftEntry() for perl-ldap interface
207 * @return Net_LDAP2_Entry|false
209 public function shift_entry()
211 $args = func_get_args();
212 return call_user_func_array(array( &$this, 'shiftEntry' ), $args);
216 * Retrieve the next entry in the searchresult, but starting from last entry
218 * This is the opposite to {@link shiftEntry()} and is also very useful
219 * to be used inside a while loop.
221 * @return Net_LDAP2_Entry|false
223 public function popEntry()
225 if (false === $this->_entry_cache) {
226 // fetch entries into cache if not done so far
227 $this->_entry_cache = $this->entries();
230 $return = array_pop($this->_entry_cache);
231 return (null === $return)? false : $return;
235 * Alias function of popEntry() for perl-ldap interface
238 * @return Net_LDAP2_Entry|false
240 public function pop_entry()
242 $args = func_get_args();
243 return call_user_func_array(array( &$this, 'popEntry' ), $args);
247 * Return entries sorted as array
249 * This returns a array with sorted entries and the values.
250 * Sorting is done with PHPs {@link array_multisort()}.
251 * This method relies on {@link as_struct()} to fetch the raw data of the entries.
253 * Please note that attribute names are case sensitive!
257 * // to sort entries first by location, then by surename, but descending:
258 * $entries = $search->sorted_as_struct(array('locality','sn'), SORT_DESC);
261 * @param array $attrs Array of attribute names to sort; order from left to right.
262 * @param int $order Ordering direction, either constant SORT_ASC or SORT_DESC
264 * @return array|Net_LDAP2_Error Array with sorted entries or error
265 * @todo what about server side sorting as specified in http://www.ietf.org/rfc/rfc2891.txt?
267 public function sorted_as_struct($attrs = array('cn'), $order = SORT_ASC)
270 * Old Code, suitable and fast for single valued sorting
271 * This code should be used if we know that single valued sorting is desired,
272 * but we need some method to get that knowledge...
275 $attrs = array_reverse($attrs);
276 foreach ($attrs as $attribute) {
277 if (!ldap_sort($this->_link, $this->_search, $attribute)){
278 $this->raiseError("Sorting failed for Attribute " . $attribute);
282 $results = ldap_get_entries($this->_link, $this->_search);
284 unset($results['count']); //for tidier output
286 return array_reverse($results);
292 * New code: complete "client side" sorting
294 // first some parameterchecks
295 if (!is_array($attrs)) {
296 return PEAR::raiseError("Sorting failed: Parameterlist must be an array!");
298 if ($order != SORT_ASC && $order != SORT_DESC) {
299 return PEAR::raiseError("Sorting failed: sorting direction not understood! (neither constant SORT_ASC nor SORT_DESC)");
302 // fetch the entries data
303 $entries = $this->as_struct();
305 // now sort each entries attribute values
306 // this is neccessary because later we can only sort by one value,
307 // so we need the highest or lowest attribute now, depending on the
308 // selected ordering for that specific attribute
309 foreach ($entries as $dn => $entry) {
310 foreach ($entry as $attr_name => $attr_values) {
311 sort($entries[$dn][$attr_name]);
312 if ($order == SORT_DESC) {
313 array_reverse($entries[$dn][$attr_name]);
318 // reformat entrys array for later use with array_multisort()
319 $to_sort = array(); // <- will be a numeric array similar to ldap_get_entries
320 foreach ($entries as $dn => $entry_attr) {
323 foreach ($entry_attr as $attr_name => $attr_values) {
324 $row[$attr_name] = $attr_values;
329 // Build columns for array_multisort()
330 // each requested attribute is one row
332 foreach ($attrs as $attr_name) {
333 foreach ($to_sort as $key => $row) {
334 $columns[$attr_name][$key] =& $to_sort[$key][$attr_name][0];
338 // sort the colums with array_multisort, if there is something
339 // to sort and if we have requested sort columns
340 if (!empty($to_sort) && !empty($columns)) {
342 foreach ($attrs as $attr_name) {
343 $sort_params .= '$columns[\''.$attr_name.'\'], '.$order.', ';
345 eval("array_multisort($sort_params \$to_sort);"); // perform sorting
352 * Return entries sorted as objects
354 * This returns a array with sorted Net_LDAP2_Entry objects.
355 * The sorting is actually done with {@link sorted_as_struct()}.
357 * Please note that attribute names are case sensitive!
358 * Also note, that it is (depending on server capabilitys) possible to let
359 * the server sort your results. This happens through search controls
360 * and is described in detail at {@link http://www.ietf.org/rfc/rfc2891.txt}
364 * // to sort entries first by location, then by surename, but descending:
365 * $entries = $search->sorted(array('locality','sn'), SORT_DESC);
368 * @param array $attrs Array of sort attributes to sort; order from left to right.
369 * @param int $order Ordering direction, either constant SORT_ASC or SORT_DESC
371 * @return array|Net_LDAP2_Error Array with sorted Net_LDAP2_Entries or error
372 * @todo Entry object construction could be faster. Maybe we could use one of the factorys instead of fetching the entry again
374 public function sorted($attrs = array('cn'), $order = SORT_ASC)
377 $sorted = $this->sorted_as_struct($attrs, $order);
378 if (PEAR::isError($sorted)) {
381 foreach ($sorted as $key => $row) {
382 $entry = $this->_ldap->getEntry($row['dn'], $this->searchedAttrs());
383 if (!PEAR::isError($entry)) {
384 array_push($return, $entry);
393 * Return entries as array
395 * This method returns the entries and the selected attributes values as
397 * The first array level contains all found entries where the keys are the
398 * DNs of the entries. The second level arrays contian the entries attributes
399 * such that the keys is the lowercased name of the attribute and the values
400 * are stored in another indexed array. Note that the attribute values are stored
401 * in an array even if there is no or just one value.
403 * The array has the following structure:
406 * 'cn=foo,dc=example,dc=com' => array(
407 * 'sn' => array('foo'),
408 * 'multival' => array('val1', 'val2', 'valN')
410 * 'cn=bar,dc=example,dc=com' => array(
411 * 'sn' => array('bar'),
412 * 'multival' => array('val1', 'valN')
417 * @return array associative result array as described above
419 public function as_struct()
422 $entries = $this->entries();
423 foreach ($entries as $entry) {
425 $entry_attributes = $entry->attributes();
426 foreach ($entry_attributes as $attr_name) {
427 $attr_values = $entry->getValue($attr_name, 'all');
428 if (!is_array($attr_values)) {
429 $attr_values = array($attr_values);
431 $attrs[$attr_name] = $attr_values;
433 $return[$entry->dn()] = $attrs;
439 * Set the search objects resource link
441 * @param resource &$search Search result identifier
446 public function setSearch(&$search)
448 $this->_search = $search;
452 * Set the ldap ressource link
454 * @param resource &$link Link identifier
459 public function setLink(&$link)
461 $this->_link = $link;
465 * Returns the number of entries in the searchresult
467 * @return int Number of entries in search.
469 public function count()
471 // this catches the situation where OL returned errno 32 = no such object!
472 if (!$this->_search) {
475 // ldap_count_entries is slow (see pear bug #18752) with large results,
476 // so we cache the result internally.
477 if ($this->_count_cache === null) {
478 $this->_count_cache = @ldap_count_entries($this->_link, $this->_search);
481 return $this->_count_cache;
485 * Get the errorcode the object got in its search.
487 * @return int The ldap error number.
489 public function getErrorCode()
491 return $this->_errorCode;
499 public function _Net_LDAP2_Search()
501 @ldap_free_result($this->_search);
505 * Closes search result
509 public function done()
511 $this->_Net_LDAP2_Search();
515 * Return the attribute names this search selected
518 * @see $_searchedAttrs
521 protected function searchedAttrs()
523 return $this->_searchedAttrs;
527 * Tells if this search exceeds a sizelimit
531 public function sizeLimitExceeded()
533 return ($this->getErrorCode() == 4);
538 * SPL Iterator interface methods.
539 * This interface allows to use Net_LDAP2_Search
540 * objects directly inside a foreach loop!
543 * SPL Iterator interface: Return the current element.
545 * The SPL Iterator interface allows you to fetch entries inside
546 * a foreach() loop: <code>foreach ($search as $dn => $entry) { ...</code>
548 * Of course, you may call {@link current()}, {@link key()}, {@link next()},
549 * {@link rewind()} and {@link valid()} yourself.
551 * If the search throwed an error, it returns false.
552 * False is also returned, if the end is reached
553 * In case no call to next() was made, we will issue one,
554 * thus returning the first entry.
556 * @return Net_LDAP2_Entry|false
558 public function current()
560 if (count($this->_iteratorCache) == 0) {
562 reset($this->_iteratorCache);
564 $entry = current($this->_iteratorCache);
565 return ($entry instanceof Net_LDAP2_Entry)? $entry : false;
569 * SPL Iterator interface: Return the identifying key (DN) of the current entry.
572 * @return string|false DN of the current entry; false in case no entry is returned by current()
574 public function key()
576 $entry = $this->current();
577 return ($entry instanceof Net_LDAP2_Entry)? $entry->dn() :false;
581 * SPL Iterator interface: Move forward to next entry.
583 * After a call to {@link next()}, {@link current()} will return
584 * the next entry in the result set.
589 public function next()
592 // if we have no entrys anymore, we add false (which is
593 // returned by shiftEntry()) so current() will complain.
594 if (count($this->_iteratorCache) - 1 <= $this->count()) {
595 $this->_iteratorCache[] = $this->shiftEntry();
598 // move on array pointer to current element.
599 // even if we have added all entries, this will
600 // ensure proper operation in case we rewind()
601 next($this->_iteratorCache);
605 * SPL Iterator interface: Check if there is a current element after calls to {@link rewind()} or {@link next()}.
607 * Used to check if we've iterated to the end of the collection.
610 * @return boolean FALSE if there's nothing more to iterate over
612 public function valid()
614 return ($this->current() instanceof Net_LDAP2_Entry);
618 * SPL Iterator interface: Rewind the Iterator to the first element.
620 * After rewinding, {@link current()} will return the first entry in the result set.
625 public function rewind()
627 reset($this->_iteratorCache);