]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/LdapCommon/extlib/Net/LDAP2/Search.php
Introduced common_location_shared() to check if location sharing is always,
[quix0rs-gnu-social.git] / plugins / LdapCommon / 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 328961 2013-01-03 09:04:30Z 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 not used by all functions and need consolidation.
110     *
111     * @access protected
112     * @var array
113     */
114     protected $_entry_cache = false;
115
116     /**
117     * Cache variable for count()
118     *
119     * @see count()
120     * @access protected
121     * @var int
122     */
123     protected $_count_cache = null;
124
125     /**
126     * Constructor
127     *
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})
131     *
132     * @access public
133     */
134     public function __construct(&$search, &$ldap, $attributes = array())
135     {
136         $this->PEAR('Net_LDAP2_Error');
137
138         $this->setSearch($search);
139
140         if ($ldap instanceof Net_LDAP2) {
141             $this->_ldap =& $ldap;
142             $this->setLink($this->_ldap->getLink());
143         } else {
144             $this->setLink($ldap);
145         }
146
147         $this->_errorCode = @ldap_errno($this->_link);
148
149         if (is_array($attributes) && !empty($attributes)) {
150             $this->_searchedAttrs = $attributes;
151         }
152     }
153
154     /**
155     * Returns an array of entry objects.
156     *
157     * @return array Array of entry objects.
158     */
159     public function entries()
160     {
161         $entries = array();
162
163         if (false === $this->_entry_cache) {
164             // cache is empty: fetch from LDAP
165             while ($entry = $this->shiftEntry()) {
166                 $entries[] = $entry;
167             }
168             $this->_entry_cache = $entries; // store result in cache
169         }
170
171         return $this->_entry_cache;
172     }
173
174     /**
175     * Get the next entry in the searchresult from LDAP server.
176     *
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
179     * a while loop.
180     *
181     * @return Net_LDAP2_Entry|false  Reference to Net_LDAP2_Entry object or false
182     */
183     public function &shiftEntry()
184     {
185         if (is_null($this->_entry)) {
186             if(!$this->_entry = @ldap_first_entry($this->_link, $this->_search)) {
187                 $false = false;
188                 return $false;
189             }
190             $entry = Net_LDAP2_Entry::createConnected($this->_ldap, $this->_entry);
191             if ($entry instanceof PEAR_Error) $entry = false;
192         } else {
193             if (!$this->_entry = @ldap_next_entry($this->_link, $this->_entry)) {
194                 $false = false;
195                 return $false;
196             }
197             $entry = Net_LDAP2_Entry::createConnected($this->_ldap, $this->_entry);
198             if ($entry instanceof PEAR_Error) $entry = false;
199         }
200         return $entry;
201     }
202
203     /**
204     * Alias function of shiftEntry() for perl-ldap interface
205     *
206     * @see shiftEntry()
207     * @return Net_LDAP2_Entry|false
208     */
209     public function shift_entry()
210     {
211         $args = func_get_args();
212         return call_user_func_array(array( &$this, 'shiftEntry' ), $args);
213     }
214
215     /**
216     * Retrieve the next entry in the searchresult, but starting from last entry
217     *
218     * This is the opposite to {@link shiftEntry()} and is also very useful
219     * to be used inside a while loop.
220     *
221     * @return Net_LDAP2_Entry|false
222     */
223     public function popEntry()
224     {
225         if (false === $this->_entry_cache) {
226             // fetch entries into cache if not done so far
227             $this->_entry_cache = $this->entries();
228         }
229
230         $return = array_pop($this->_entry_cache);
231         return (null === $return)? false : $return;
232     }
233
234     /**
235     * Alias function of popEntry() for perl-ldap interface
236     *
237     * @see popEntry()
238     * @return Net_LDAP2_Entry|false
239     */
240     public function pop_entry()
241     {
242         $args = func_get_args();
243         return call_user_func_array(array( &$this, 'popEntry' ), $args);
244     }
245
246     /**
247     * Return entries sorted as array
248     *
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.
252     *
253     * Please note that attribute names are case sensitive!
254     *
255     * Usage example:
256     * <code>
257     *   // to sort entries first by location, then by surename, but descending:
258     *   $entries = $search->sorted_as_struct(array('locality','sn'), SORT_DESC);
259     * </code>
260     *
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
263     *
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?
266     */
267     public function sorted_as_struct($attrs = array('cn'), $order = SORT_ASC)
268     {
269         /*
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...
273         */
274         /*
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);
279             }
280         }
281
282         $results = ldap_get_entries($this->_link, $this->_search);
283
284         unset($results['count']); //for tidier output
285         if ($order) {
286             return array_reverse($results);
287         } else {
288             return $results;
289         }*/
290
291         /*
292         * New code: complete "client side" sorting
293         */
294         // first some parameterchecks
295         if (!is_array($attrs)) {
296             return PEAR::raiseError("Sorting failed: Parameterlist must be an array!");
297         }
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)");
300         }
301
302         // fetch the entries data
303         $entries = $this->as_struct();
304
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]);
314                 }
315             }
316         }
317
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) {
321             $row       = array();
322             $row['dn'] = $dn;
323             foreach ($entry_attr as $attr_name => $attr_values) {
324                 $row[$attr_name] = $attr_values;
325             }
326             $to_sort[] = $row;
327         }
328
329         // Build columns for array_multisort()
330         // each requested attribute is one row
331         $columns = array();
332         foreach ($attrs as $attr_name) {
333             foreach ($to_sort as $key => $row) {
334                 $columns[$attr_name][$key] =& $to_sort[$key][$attr_name][0];
335             }
336         }
337
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)) {
341             $sort_params = '';
342             foreach ($attrs as $attr_name) {
343                 $sort_params .= '$columns[\''.$attr_name.'\'], '.$order.', ';
344             }
345             eval("array_multisort($sort_params \$to_sort);"); // perform sorting
346         }
347
348         return $to_sort;
349     }
350
351     /**
352     * Return entries sorted as objects
353     *
354     * This returns a array with sorted Net_LDAP2_Entry objects.
355     * The sorting is actually done with {@link sorted_as_struct()}.
356     *
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}
361     *
362     * Usage example:
363     * <code>
364     *   // to sort entries first by location, then by surename, but descending:
365     *   $entries = $search->sorted(array('locality','sn'), SORT_DESC);
366     * </code>
367     *
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
370     *
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
373     */
374     public function sorted($attrs = array('cn'), $order = SORT_ASC)
375     {
376         $return = array();
377         $sorted = $this->sorted_as_struct($attrs, $order);
378         if (PEAR::isError($sorted)) {
379             return $sorted;
380         }
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);
385             } else {
386                 return $entry;
387             }
388         }
389         return $return;
390     }
391
392     /**
393     * Return entries as array
394     *
395     * This method returns the entries and the selected attributes values as
396     * array.
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.
402     *
403     * The array has the following structure:
404     * <code>
405     * $return = array(
406     *           'cn=foo,dc=example,dc=com' => array(
407     *                                                'sn'       => array('foo'),
408     *                                                'multival' => array('val1', 'val2', 'valN')
409     *                                             )
410     *           'cn=bar,dc=example,dc=com' => array(
411     *                                                'sn'       => array('bar'),
412     *                                                'multival' => array('val1', 'valN')
413     *                                             )
414     *           )
415     * </code>
416     *
417     * @return array      associative result array as described above
418     */
419     public function as_struct()
420     {
421         $return  = array();
422         $entries = $this->entries();
423         foreach ($entries as $entry) {
424             $attrs            = array();
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);
430                 }
431                 $attrs[$attr_name] = $attr_values;
432             }
433             $return[$entry->dn()] = $attrs;
434         }
435         return $return;
436     }
437
438     /**
439     * Set the search objects resource link
440     *
441     * @param resource &$search Search result identifier
442     *
443     * @access public
444     * @return void
445     */
446     public function setSearch(&$search)
447     {
448         $this->_search = $search;
449     }
450
451     /**
452     * Set the ldap ressource link
453     *
454     * @param resource &$link Link identifier
455     *
456     * @access public
457     * @return void
458     */
459     public function setLink(&$link)
460     {
461         $this->_link = $link;
462     }
463
464     /**
465     * Returns the number of entries in the searchresult
466     *
467     * @return int Number of entries in search.
468     */
469     public function count()
470     {
471         // this catches the situation where OL returned errno 32 = no such object!
472         if (!$this->_search) {
473             return 0;
474         }
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);
479         }
480
481         return $this->_count_cache;
482     }
483
484     /**
485     * Get the errorcode the object got in its search.
486     *
487     * @return int The ldap error number.
488     */
489     public function getErrorCode()
490     {
491         return $this->_errorCode;
492     }
493
494     /**
495     * Destructor
496     *
497     * @access protected
498     */
499     public function _Net_LDAP2_Search()
500     {
501         @ldap_free_result($this->_search);
502     }
503
504     /**
505     * Closes search result
506     *
507     * @return void
508     */
509     public function done()
510     {
511         $this->_Net_LDAP2_Search();
512     }
513
514     /**
515     * Return the attribute names this search selected
516     *
517     * @return array
518     * @see $_searchedAttrs
519     * @access protected
520     */
521     protected function searchedAttrs()
522     {
523         return $this->_searchedAttrs;
524     }
525
526     /**
527     * Tells if this search exceeds a sizelimit
528     *
529     * @return boolean
530     */
531     public function sizeLimitExceeded()
532     {
533         return ($this->getErrorCode() == 4);
534     }
535
536
537     /*
538     * SPL Iterator interface methods.
539     * This interface allows to use Net_LDAP2_Search
540     * objects directly inside a foreach loop!
541     */
542     /**
543     * SPL Iterator interface: Return the current element.
544     *
545     * The SPL Iterator interface allows you to fetch entries inside
546     * a foreach() loop: <code>foreach ($search as $dn => $entry) { ...</code>
547     *
548     * Of course, you may call {@link current()}, {@link key()}, {@link next()},
549     * {@link rewind()} and {@link valid()} yourself.
550     *
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.
555     *
556     * @return Net_LDAP2_Entry|false
557     */
558     public function current()
559     {
560         if (count($this->_iteratorCache) == 0) {
561             $this->next();
562             reset($this->_iteratorCache);
563         }
564         $entry = current($this->_iteratorCache);
565         return ($entry instanceof Net_LDAP2_Entry)? $entry : false;
566     }
567
568     /**
569     * SPL Iterator interface: Return the identifying key (DN) of the current entry.
570     *
571     * @see current()
572     * @return string|false DN of the current entry; false in case no entry is returned by current()
573     */
574     public function key()
575     {
576         $entry = $this->current();
577         return ($entry instanceof Net_LDAP2_Entry)? $entry->dn() :false;
578     }
579
580     /**
581     * SPL Iterator interface: Move forward to next entry.
582     *
583     * After a call to {@link next()}, {@link current()} will return
584     * the next entry in the result set.
585     *
586     * @see current()
587     * @return void
588     */
589     public function next()
590     {
591         // fetch next entry.
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();
596         }
597
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);
602     }
603
604     /**
605     * SPL Iterator interface:  Check if there is a current element after calls to {@link rewind()} or {@link next()}.
606     *
607     * Used to check if we've iterated to the end of the collection.
608     *
609     * @see current()
610     * @return boolean FALSE if there's nothing more to iterate over
611     */
612     public function valid()
613     {
614         return ($this->current() instanceof Net_LDAP2_Entry);
615     }
616
617     /**
618     * SPL Iterator interface: Rewind the Iterator to the first element.
619     *
620     * After rewinding, {@link current()} will return the first entry in the result set.
621     *
622     * @see current()
623     * @return void
624     */
625     public function rewind()
626     {
627         reset($this->_iteratorCache);
628     }
629 }
630
631 ?>