]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - extlib/Net/LDAP2/Search.php
Fix some regressions caused by refactor of LDAP plugin
[quix0rs-gnu-social.git] / extlib / Net / LDAP2 / Search.php
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: Search.php 286718 2009-08-03 07:30:49Z beni $
15 * @link      http://pear.php.net/package/Net_LDAP2/
16 */
17
18 /**
19 * Includes
20 */
21 require_once 'PEAR.php';
22
23 /**
24 * Result set of an LDAP search
25 *
26 * @category Net
27 * @package  Net_LDAP2
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/
32 */
33 class Net_LDAP2_Search extends PEAR implements Iterator
34 {
35     /**
36     * Search result identifier
37     *
38     * @access protected
39     * @var resource
40     */
41     protected $_search;
42
43     /**
44     * LDAP resource link
45     *
46     * @access protected
47     * @var resource
48     */
49     protected $_link;
50
51     /**
52     * Net_LDAP2 object
53     *
54     * A reference of the Net_LDAP2 object for passing to Net_LDAP2_Entry
55     *
56     * @access protected
57     * @var object Net_LDAP2
58     */
59     protected $_ldap;
60
61     /**
62     * Result entry identifier
63     *
64     * @access protected
65     * @var resource
66     */
67     protected $_entry = null;
68
69     /**
70     * The errorcode the search got
71     *
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.
77     *
78     * @access protected
79     * @var int
80     */
81     protected $_errorCode = 0; // if not set - sucess!
82
83     /**
84     * Cache for all entries already fetched from iterator interface
85     *
86     * @access protected
87     * @var array
88     */
89     protected $_iteratorCache = array();
90
91     /**
92     * What attributes we searched for
93     *
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())
97     *
98     * This variable gets set from the constructor and returned
99     * from {@link searchedAttrs()}
100     *
101     * @access protected
102     * @var array
103     */
104     protected $_searchedAttrs = array();
105
106     /**
107     * Cache variable for storing entries fetched internally
108     *
109     * This currently is only used by {@link pop_entry()}
110     *
111     * @access protected
112     * @var array
113     */
114     protected $_entry_cache = false;
115
116     /**
117     * Constructor
118     *
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})
122     *
123     * @access public
124     */
125     public function __construct(&$search, &$ldap, $attributes = array())
126     {
127         $this->PEAR('Net_LDAP2_Error');
128
129         $this->setSearch($search);
130
131         if ($ldap instanceof Net_LDAP2) {
132             $this->_ldap =& $ldap;
133             $this->setLink($this->_ldap->getLink());
134         } else {
135             $this->setLink($ldap);
136         }
137
138         $this->_errorCode = @ldap_errno($this->_link);
139
140         if (is_array($attributes) && !empty($attributes)) {
141             $this->_searchedAttrs = $attributes;
142         }
143     }
144
145     /**
146     * Returns an array of entry objects
147     *
148     * @return array Array of entry objects.
149     */
150     public function entries()
151     {
152         $entries = array();
153
154         while ($entry = $this->shiftEntry()) {
155             $entries[] = $entry;
156         }
157
158         return $entries;
159     }
160
161     /**
162     * Get the next entry in the searchresult.
163     *
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
166     * a while loop.
167     *
168     * @return Net_LDAP2_Entry|false  Reference to Net_LDAP2_Entry object or false
169     */
170     public function &shiftEntry()
171     {
172         if ($this->count() == 0 ) {
173             $false = false;
174             return $false;
175         }
176
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;
181         } else {
182             if (!$this->_entry = @ldap_next_entry($this->_link, $this->_entry)) {
183                 $false = false;
184                 return $false;
185             }
186             $entry = Net_LDAP2_Entry::createConnected($this->_ldap, $this->_entry);
187             if ($entry instanceof Net_LDAP2_Error) $entry = false;
188         }
189         return $entry;
190     }
191
192     /**
193     * Alias function of shiftEntry() for perl-ldap interface
194     *
195     * @see shiftEntry()
196     * @return Net_LDAP2_Entry|false
197     */
198     public function shift_entry()
199     {
200         $args = func_get_args();
201         return call_user_func_array(array( &$this, 'shiftEntry' ), $args);
202     }
203
204     /**
205     * Retrieve the next entry in the searchresult, but starting from last entry
206     *
207     * This is the opposite to {@link shiftEntry()} and is also very useful
208     * to be used inside a while loop.
209     *
210     * @return Net_LDAP2_Entry|false
211     */
212     public function popEntry()
213     {
214         if (false === $this->_entry_cache) {
215             // fetch entries into cache if not done so far
216             $this->_entry_cache = $this->entries();
217         }
218
219         $return = array_pop($this->_entry_cache);
220         return (null === $return)? false : $return;
221     }
222
223     /**
224     * Alias function of popEntry() for perl-ldap interface
225     *
226     * @see popEntry()
227     * @return Net_LDAP2_Entry|false
228     */
229     public function pop_entry()
230     {
231         $args = func_get_args();
232         return call_user_func_array(array( &$this, 'popEntry' ), $args);
233     }
234
235     /**
236     * Return entries sorted as array
237     *
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.
241     *
242     * Please note that attribute names are case sensitive!
243     *
244     * Usage example:
245     * <code>
246     *   // to sort entries first by location, then by surename, but descending:
247     *   $entries = $search->sorted_as_struct(array('locality','sn'), SORT_DESC);
248     * </code>
249     *
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
252     *
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?
255     */
256     public function sorted_as_struct($attrs = array('cn'), $order = SORT_ASC)
257     {
258         /*
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...
262         */
263         /*
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);
268             }
269         }
270
271         $results = ldap_get_entries($this->_link, $this->_search);
272
273         unset($results['count']); //for tidier output
274         if ($order) {
275             return array_reverse($results);
276         } else {
277             return $results;
278         }*/
279
280         /*
281         * New code: complete "client side" sorting
282         */
283         // first some parameterchecks
284         if (!is_array($attrs)) {
285             return PEAR::raiseError("Sorting failed: Parameterlist must be an array!");
286         }
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)");
289         }
290
291         // fetch the entries data
292         $entries = $this->as_struct();
293
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]);
303                 }
304             }
305         }
306
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) {
310             $row       = array();
311             $row['dn'] = $dn;
312             foreach ($entry_attr as $attr_name => $attr_values) {
313                 $row[$attr_name] = $attr_values;
314             }
315             $to_sort[] = $row;
316         }
317
318         // Build columns for array_multisort()
319         // each requested attribute is one row
320         $columns = array();
321         foreach ($attrs as $attr_name) {
322             foreach ($to_sort as $key => $row) {
323                 $columns[$attr_name][$key] =& $to_sort[$key][$attr_name][0];
324             }
325         }
326
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)) {
330             $sort_params = '';
331             foreach ($attrs as $attr_name) {
332                 $sort_params .= '$columns[\''.$attr_name.'\'], '.$order.', ';
333             }
334             eval("array_multisort($sort_params \$to_sort);"); // perform sorting
335         }
336
337         return $to_sort;
338     }
339
340     /**
341     * Return entries sorted as objects
342     *
343     * This returns a array with sorted Net_LDAP2_Entry objects.
344     * The sorting is actually done with {@link sorted_as_struct()}.
345     *
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}
350     *
351     * Usage example:
352     * <code>
353     *   // to sort entries first by location, then by surename, but descending:
354     *   $entries = $search->sorted(array('locality','sn'), SORT_DESC);
355     * </code>
356     *
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
359     *
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
362     */
363     public function sorted($attrs = array('cn'), $order = SORT_ASC)
364     {
365         $return = array();
366         $sorted = $this->sorted_as_struct($attrs, $order);
367         if (PEAR::isError($sorted)) {
368             return $sorted;
369         }
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);
374             } else {
375                 return $entry;
376             }
377         }
378         return $return;
379     }
380
381     /**
382     * Return entries as array
383     *
384     * This method returns the entries and the selected attributes values as
385     * array.
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.
391     *
392     * The array has the following structure:
393     * <code>
394     * $return = array(
395     *           'cn=foo,dc=example,dc=com' => array(
396     *                                                'sn'       => array('foo'),
397     *                                                'multival' => array('val1', 'val2', 'valN')
398     *                                             )
399     *           'cn=bar,dc=example,dc=com' => array(
400     *                                                'sn'       => array('bar'),
401     *                                                'multival' => array('val1', 'valN')
402     *                                             )
403     *           )
404     * </code>
405     *
406     * @return array      associative result array as described above
407     */
408     public function as_struct()
409     {
410         $return  = array();
411         $entries = $this->entries();
412         foreach ($entries as $entry) {
413             $attrs            = array();
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);
419                 }
420                 $attrs[$attr_name] = $attr_values;
421             }
422             $return[$entry->dn()] = $attrs;
423         }
424         return $return;
425     }
426
427     /**
428     * Set the search objects resource link
429     *
430     * @param resource &$search Search result identifier
431     *
432     * @access public
433     * @return void
434     */
435     public function setSearch(&$search)
436     {
437         $this->_search = $search;
438     }
439
440     /**
441     * Set the ldap ressource link
442     *
443     * @param resource &$link Link identifier
444     *
445     * @access public
446     * @return void
447     */
448     public function setLink(&$link)
449     {
450         $this->_link = $link;
451     }
452
453     /**
454     * Returns the number of entries in the searchresult
455     *
456     * @return int Number of entries in search.
457     */
458     public function count()
459     {
460         // this catches the situation where OL returned errno 32 = no such object!
461         if (!$this->_search) {
462             return 0;
463         }
464         return @ldap_count_entries($this->_link, $this->_search);
465     }
466
467     /**
468     * Get the errorcode the object got in its search.
469     *
470     * @return int The ldap error number.
471     */
472     public function getErrorCode()
473     {
474         return $this->_errorCode;
475     }
476
477     /**
478     * Destructor
479     *
480     * @access protected
481     */
482     public function _Net_LDAP2_Search()
483     {
484         @ldap_free_result($this->_search);
485     }
486
487     /**
488     * Closes search result
489     *
490     * @return void
491     */
492     public function done()
493     {
494         $this->_Net_LDAP2_Search();
495     }
496
497     /**
498     * Return the attribute names this search selected
499     *
500     * @return array
501     * @see $_searchedAttrs
502     * @access protected
503     */
504     protected function searchedAttrs()
505     {
506         return $this->_searchedAttrs;
507     }
508
509     /**
510     * Tells if this search exceeds a sizelimit
511     *
512     * @return boolean
513     */
514     public function sizeLimitExceeded()
515     {
516         return ($this->getErrorCode() == 4);
517     }
518
519
520     /*
521     * SPL Iterator interface methods.
522     * This interface allows to use Net_LDAP2_Search
523     * objects directly inside a foreach loop!
524     */
525     /**
526     * SPL Iterator interface: Return the current element.
527     *
528     * The SPL Iterator interface allows you to fetch entries inside
529     * a foreach() loop: <code>foreach ($search as $dn => $entry) { ...</code>
530     *
531     * Of course, you may call {@link current()}, {@link key()}, {@link next()},
532     * {@link rewind()} and {@link valid()} yourself.
533     *
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.
538     *
539     * @return Net_LDAP2_Entry|false
540     */
541     public function current()
542     {
543         if (count($this->_iteratorCache) == 0) {
544             $this->next();
545             reset($this->_iteratorCache);
546         }
547         $entry = current($this->_iteratorCache);
548         return ($entry instanceof Net_LDAP2_Entry)? $entry : false;
549     }
550
551     /**
552     * SPL Iterator interface: Return the identifying key (DN) of the current entry.
553     *
554     * @see current()
555     * @return string|false DN of the current entry; false in case no entry is returned by current()
556     */
557     public function key()
558     {
559         $entry = $this->current();
560         return ($entry instanceof Net_LDAP2_Entry)? $entry->dn() :false;
561     }
562
563     /**
564     * SPL Iterator interface: Move forward to next entry.
565     *
566     * After a call to {@link next()}, {@link current()} will return
567     * the next entry in the result set.
568     *
569     * @see current()
570     * @return void
571     */
572     public function next()
573     {
574         // fetch next entry.
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();
579         }
580
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);
585     }
586
587     /**
588     * SPL Iterator interface:  Check if there is a current element after calls to {@link rewind()} or {@link next()}.
589     *
590     * Used to check if we've iterated to the end of the collection.
591     *
592     * @see current()
593     * @return boolean FALSE if there's nothing more to iterate over
594     */
595     public function valid()
596     {
597         return ($this->current() instanceof Net_LDAP2_Entry);
598     }
599
600     /**
601     * SPL Iterator interface: Rewind the Iterator to the first element.
602     *
603     * After rewinding, {@link current()} will return the first entry in the result set.
604     *
605     * @see current()
606     * @return void
607     */
608     public function rewind()
609     {
610         reset($this->_iteratorCache);
611     }
612 }
613
614 ?>