Net_LDAP2
[ class tree: Net_LDAP2 ] [ index: Net_LDAP2 ] [ all elements ]

Source for file Search.php

Documentation is available at Search.php

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

Documentation generated on Mon, 11 Mar 2019 15:17:51 -0400 by phpDocumentor 1.4.4. PEAR Logo Copyright © PHP Group 2004.