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 286718 2009-08-03 07:30:49Z 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 only used by {@link pop_entry()}
114 protected $_entry_cache = false;
119 * @param resource &$search Search result identifier
120 * @param Net_LDAP2|resource &$ldap Net_LDAP2 object or just a LDAP-Link resource
121 * @param array $attributes (optional) Array with searched attribute names. (see {@link $_searchedAttrs})
125 public function __construct(&$search, &$ldap, $attributes = array())
127 $this->PEAR('Net_LDAP2_Error');
129 $this->setSearch($search);
131 if ($ldap instanceof Net_LDAP2) {
132 $this->_ldap =& $ldap;
133 $this->setLink($this->_ldap->getLink());
135 $this->setLink($ldap);
138 $this->_errorCode = @ldap_errno($this->_link);
140 if (is_array($attributes) && !empty($attributes)) {
141 $this->_searchedAttrs = $attributes;
146 * Returns an array of entry objects
148 * @return array Array of entry objects.
150 public function entries()
154 while ($entry = $this->shiftEntry()) {
162 * Get the next entry in the searchresult.
164 * This will return a valid Net_LDAP2_Entry object or false, so
165 * you can use this method to easily iterate over the entries inside
168 * @return Net_LDAP2_Entry|false Reference to Net_LDAP2_Entry object or false
170 public function &shiftEntry()
172 if ($this->count() == 0 ) {
177 if (is_null($this->_entry)) {
178 $this->_entry = @ldap_first_entry($this->_link, $this->_search);
179 $entry = Net_LDAP2_Entry::createConnected($this->_ldap, $this->_entry);
180 if ($entry instanceof Net_LDAP2_Error) $entry = false;
182 if (!$this->_entry = @ldap_next_entry($this->_link, $this->_entry)) {
186 $entry = Net_LDAP2_Entry::createConnected($this->_ldap, $this->_entry);
187 if ($entry instanceof Net_LDAP2_Error) $entry = false;
193 * Alias function of shiftEntry() for perl-ldap interface
196 * @return Net_LDAP2_Entry|false
198 public function shift_entry()
200 $args = func_get_args();
201 return call_user_func_array(array( &$this, 'shiftEntry' ), $args);
205 * Retrieve the next entry in the searchresult, but starting from last entry
207 * This is the opposite to {@link shiftEntry()} and is also very useful
208 * to be used inside a while loop.
210 * @return Net_LDAP2_Entry|false
212 public function popEntry()
214 if (false === $this->_entry_cache) {
215 // fetch entries into cache if not done so far
216 $this->_entry_cache = $this->entries();
219 $return = array_pop($this->_entry_cache);
220 return (null === $return)? false : $return;
224 * Alias function of popEntry() for perl-ldap interface
227 * @return Net_LDAP2_Entry|false
229 public function pop_entry()
231 $args = func_get_args();
232 return call_user_func_array(array( &$this, 'popEntry' ), $args);
236 * Return entries sorted as array
238 * This returns a array with sorted entries and the values.
239 * Sorting is done with PHPs {@link array_multisort()}.
240 * This method relies on {@link as_struct()} to fetch the raw data of the entries.
242 * Please note that attribute names are case sensitive!
246 * // to sort entries first by location, then by surename, but descending:
247 * $entries = $search->sorted_as_struct(array('locality','sn'), SORT_DESC);
250 * @param array $attrs Array of attribute names to sort; order from left to right.
251 * @param int $order Ordering direction, either constant SORT_ASC or SORT_DESC
253 * @return array|Net_LDAP2_Error Array with sorted entries or error
254 * @todo what about server side sorting as specified in http://www.ietf.org/rfc/rfc2891.txt?
256 public function sorted_as_struct($attrs = array('cn'), $order = SORT_ASC)
259 * Old Code, suitable and fast for single valued sorting
260 * This code should be used if we know that single valued sorting is desired,
261 * but we need some method to get that knowledge...
264 $attrs = array_reverse($attrs);
265 foreach ($attrs as $attribute) {
266 if (!ldap_sort($this->_link, $this->_search, $attribute)){
267 $this->raiseError("Sorting failed for Attribute " . $attribute);
271 $results = ldap_get_entries($this->_link, $this->_search);
273 unset($results['count']); //for tidier output
275 return array_reverse($results);
281 * New code: complete "client side" sorting
283 // first some parameterchecks
284 if (!is_array($attrs)) {
285 return PEAR::raiseError("Sorting failed: Parameterlist must be an array!");
287 if ($order != SORT_ASC && $order != SORT_DESC) {
288 return PEAR::raiseError("Sorting failed: sorting direction not understood! (neither constant SORT_ASC nor SORT_DESC)");
291 // fetch the entries data
292 $entries = $this->as_struct();
294 // now sort each entries attribute values
295 // this is neccessary because later we can only sort by one value,
296 // so we need the highest or lowest attribute now, depending on the
297 // selected ordering for that specific attribute
298 foreach ($entries as $dn => $entry) {
299 foreach ($entry as $attr_name => $attr_values) {
300 sort($entries[$dn][$attr_name]);
301 if ($order == SORT_DESC) {
302 array_reverse($entries[$dn][$attr_name]);
307 // reformat entrys array for later use with array_multisort()
308 $to_sort = array(); // <- will be a numeric array similar to ldap_get_entries
309 foreach ($entries as $dn => $entry_attr) {
312 foreach ($entry_attr as $attr_name => $attr_values) {
313 $row[$attr_name] = $attr_values;
318 // Build columns for array_multisort()
319 // each requested attribute is one row
321 foreach ($attrs as $attr_name) {
322 foreach ($to_sort as $key => $row) {
323 $columns[$attr_name][$key] =& $to_sort[$key][$attr_name][0];
327 // sort the colums with array_multisort, if there is something
328 // to sort and if we have requested sort columns
329 if (!empty($to_sort) && !empty($columns)) {
331 foreach ($attrs as $attr_name) {
332 $sort_params .= '$columns[\''.$attr_name.'\'], '.$order.', ';
334 eval("array_multisort($sort_params \$to_sort);"); // perform sorting
341 * Return entries sorted as objects
343 * This returns a array with sorted Net_LDAP2_Entry objects.
344 * The sorting is actually done with {@link sorted_as_struct()}.
346 * Please note that attribute names are case sensitive!
347 * Also note, that it is (depending on server capabilitys) possible to let
348 * the server sort your results. This happens through search controls
349 * and is described in detail at {@link http://www.ietf.org/rfc/rfc2891.txt}
353 * // to sort entries first by location, then by surename, but descending:
354 * $entries = $search->sorted(array('locality','sn'), SORT_DESC);
357 * @param array $attrs Array of sort attributes to sort; order from left to right.
358 * @param int $order Ordering direction, either constant SORT_ASC or SORT_DESC
360 * @return array|Net_LDAP2_Error Array with sorted Net_LDAP2_Entries or error
361 * @todo Entry object construction could be faster. Maybe we could use one of the factorys instead of fetching the entry again
363 public function sorted($attrs = array('cn'), $order = SORT_ASC)
366 $sorted = $this->sorted_as_struct($attrs, $order);
367 if (PEAR::isError($sorted)) {
370 foreach ($sorted as $key => $row) {
371 $entry = $this->_ldap->getEntry($row['dn'], $this->searchedAttrs());
372 if (!PEAR::isError($entry)) {
373 array_push($return, $entry);
382 * Return entries as array
384 * This method returns the entries and the selected attributes values as
386 * The first array level contains all found entries where the keys are the
387 * DNs of the entries. The second level arrays contian the entries attributes
388 * such that the keys is the lowercased name of the attribute and the values
389 * are stored in another indexed array. Note that the attribute values are stored
390 * in an array even if there is no or just one value.
392 * The array has the following structure:
395 * 'cn=foo,dc=example,dc=com' => array(
396 * 'sn' => array('foo'),
397 * 'multival' => array('val1', 'val2', 'valN')
399 * 'cn=bar,dc=example,dc=com' => array(
400 * 'sn' => array('bar'),
401 * 'multival' => array('val1', 'valN')
406 * @return array associative result array as described above
408 public function as_struct()
411 $entries = $this->entries();
412 foreach ($entries as $entry) {
414 $entry_attributes = $entry->attributes();
415 foreach ($entry_attributes as $attr_name) {
416 $attr_values = $entry->getValue($attr_name, 'all');
417 if (!is_array($attr_values)) {
418 $attr_values = array($attr_values);
420 $attrs[$attr_name] = $attr_values;
422 $return[$entry->dn()] = $attrs;
428 * Set the search objects resource link
430 * @param resource &$search Search result identifier
435 public function setSearch(&$search)
437 $this->_search = $search;
441 * Set the ldap ressource link
443 * @param resource &$link Link identifier
448 public function setLink(&$link)
450 $this->_link = $link;
454 * Returns the number of entries in the searchresult
456 * @return int Number of entries in search.
458 public function count()
460 // this catches the situation where OL returned errno 32 = no such object!
461 if (!$this->_search) {
464 return @ldap_count_entries($this->_link, $this->_search);
468 * Get the errorcode the object got in its search.
470 * @return int The ldap error number.
472 public function getErrorCode()
474 return $this->_errorCode;
482 public function _Net_LDAP2_Search()
484 @ldap_free_result($this->_search);
488 * Closes search result
492 public function done()
494 $this->_Net_LDAP2_Search();
498 * Return the attribute names this search selected
501 * @see $_searchedAttrs
504 protected function searchedAttrs()
506 return $this->_searchedAttrs;
510 * Tells if this search exceeds a sizelimit
514 public function sizeLimitExceeded()
516 return ($this->getErrorCode() == 4);
521 * SPL Iterator interface methods.
522 * This interface allows to use Net_LDAP2_Search
523 * objects directly inside a foreach loop!
526 * SPL Iterator interface: Return the current element.
528 * The SPL Iterator interface allows you to fetch entries inside
529 * a foreach() loop: <code>foreach ($search as $dn => $entry) { ...</code>
531 * Of course, you may call {@link current()}, {@link key()}, {@link next()},
532 * {@link rewind()} and {@link valid()} yourself.
534 * If the search throwed an error, it returns false.
535 * False is also returned, if the end is reached
536 * In case no call to next() was made, we will issue one,
537 * thus returning the first entry.
539 * @return Net_LDAP2_Entry|false
541 public function current()
543 if (count($this->_iteratorCache) == 0) {
545 reset($this->_iteratorCache);
547 $entry = current($this->_iteratorCache);
548 return ($entry instanceof Net_LDAP2_Entry)? $entry : false;
552 * SPL Iterator interface: Return the identifying key (DN) of the current entry.
555 * @return string|false DN of the current entry; false in case no entry is returned by current()
557 public function key()
559 $entry = $this->current();
560 return ($entry instanceof Net_LDAP2_Entry)? $entry->dn() :false;
564 * SPL Iterator interface: Move forward to next entry.
566 * After a call to {@link next()}, {@link current()} will return
567 * the next entry in the result set.
572 public function next()
575 // if we have no entrys anymore, we add false (which is
576 // returned by shiftEntry()) so current() will complain.
577 if (count($this->_iteratorCache) - 1 <= $this->count()) {
578 $this->_iteratorCache[] = $this->shiftEntry();
581 // move on array pointer to current element.
582 // even if we have added all entries, this will
583 // ensure proper operation in case we rewind()
584 next($this->_iteratorCache);
588 * SPL Iterator interface: Check if there is a current element after calls to {@link rewind()} or {@link next()}.
590 * Used to check if we've iterated to the end of the collection.
593 * @return boolean FALSE if there's nothing more to iterate over
595 public function valid()
597 return ($this->current() instanceof Net_LDAP2_Entry);
601 * SPL Iterator interface: Rewind the Iterator to the first element.
603 * After rewinding, {@link current()} will return the first entry in the result set.
608 public function rewind()
610 reset($this->_iteratorCache);