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.1 2008/03/18 15:50:40 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 private
  23.     * @var resource 
  24.     */
  25.     var $_search;
  26.  
  27.     /**
  28.     * LDAP resource link
  29.     *
  30.     * @access private
  31.     * @var resource 
  32.     */
  33.     var $_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 private
  41.     * @var object Net_LDAP2 
  42.     */
  43.     var $_ldap;
  44.  
  45.     /**
  46.     * Result entry identifier
  47.     *
  48.     * @access private
  49.     * @var resource 
  50.     */
  51.     var $_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 private
  63.     * @var int 
  64.     */
  65.     var $_errorCode = 0; // if not set - sucess!
  66.  
  67.     /**
  68.     * Cache for all entries already fetched from iterator interface
  69.     *
  70.     * @access private
  71.     * @var array 
  72.     */
  73.     var $_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 private
  86.     * @var array 
  87.     */
  88.     var $_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 private
  96.     * @var array 
  97.     */
  98.     var $_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 protected
  108.     */
  109.     function Net_LDAP2_Search(&$search&$ldap$attributes = array())
  110.     {
  111.         $this->PEAR('Net_LDAP2_Error');
  112.  
  113.         $this->setSearch($search);
  114.  
  115.         if (is_a($ldap'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.     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.     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        = new Net_LDAP2_Entry($this->_ldap$this->_entry);
  164.         else {
  165.             if (!$this->_entry @ldap_next_entry($this->_link$this->_entry)) {
  166.                 $false = false;
  167.                 return $false;
  168.             }
  169.             $entry = new Net_LDAP2_Entry($this->_ldap$this->_entry);
  170.         }
  171.         return $entry;
  172.     }
  173.  
  174.     /**
  175.     * Alias function of shiftEntry() for perl-ldap interface
  176.     *
  177.     * @see shiftEntry()
  178.     */
  179.     function shift_entry()
  180.     {
  181.         $args func_get_args();
  182.         return call_user_func_array(array&$this'shiftEntry' )$args);
  183.     }
  184.  
  185.     /**
  186.     * Retrieve the next entry in the searchresult, but starting from last entry
  187.     *
  188.     * This is the opposite to {@link shiftEntry()} and is also very useful
  189.     * to be used inside a while loop.
  190.     *
  191.     * @return Net_LDAP2_Entry|false
  192.     */
  193.     function popEntry()
  194.     {
  195.         if (false === $this->_entry_cache{
  196.             // fetch entries into cache if not done so far
  197.             $this->_entry_cache $this->entries();
  198.         }
  199.  
  200.         $return array_pop($this->_entry_cache);
  201.         return (null === $return)? false : $return;
  202.     }
  203.  
  204.     /**
  205.     * Alias function of popEntry() for perl-ldap interface
  206.     *
  207.     * @see popEntry()
  208.     */
  209.     function pop_entry()
  210.     {
  211.         $args func_get_args();
  212.         return call_user_func_array(array&$this'popEntry' )$args);
  213.     }
  214.  
  215.     /**
  216.     * Return entries sorted as array
  217.     *
  218.     * This returns a array with sorted entries and the values.
  219.     * Sorting is done with PHPs {@link array_multisort()}.
  220.     * This method relies on {@link as_struct()} to fetch the raw data of the entries.
  221.     *
  222.     * Please note that attribute names are case sensitive!
  223.     *
  224.     * Usage example:
  225.     * <code>
  226.     *   // to sort entries first by location, then by surename, but descending:
  227.     *   $entries = $search->sorted_as_struct(array('locality','sn'), SORT_DESC);
  228.     * </code>
  229.     *
  230.     * @param array $attrs Array of attribute names to sort; order from left to right.
  231.     * @param int   $order Ordering direction, either constant SORT_ASC or SORT_DESC
  232.     *
  233.     * @return array|Net_LDAP2_Error  Array with sorted entries or error
  234.     */
  235.     function sorted_as_struct($attrs = array('cn')$order = SORT_ASC)
  236.     {
  237.         /*
  238.         * Old Code, suitable and fast for single valued sorting
  239.         * This code should be used if we know that single valued sorting is desired,
  240.         * but we need some method to get that knowledge...
  241.         */
  242.         /*
  243.         $attrs = array_reverse($attrs);
  244.         foreach ($attrs as $attribute) {
  245.             if (!ldap_sort($this->_link, $this->_search, $attribute)){
  246.                 $this->raiseError("Sorting failed for Attribute " . $attribute);
  247.             }
  248.         }
  249.  
  250.         $results = ldap_get_entries($this->_link, $this->_search);
  251.  
  252.         unset($results['count']); //for tidier output
  253.         if ($order) {
  254.             return array_reverse($results);
  255.         } else {
  256.             return $results;
  257.         }*/
  258.  
  259.         /*
  260.         * New code: complete "client side" sorting
  261.         */
  262.         // first some parameterchecks
  263.         if (!is_array($attrs)) {
  264.             return PEAR::raiseError("Sorting failed: Parameterlist must be an array!");
  265.         }
  266.         if ($order != SORT_ASC && $order != SORT_DESC{
  267.             return PEAR::raiseError("Sorting failed: sorting direction not understood! (neither constant SORT_ASC nor SORT_DESC)");
  268.         }
  269.  
  270.         // fetch the entries data
  271.         $entries $this->as_struct();
  272.  
  273.         // now sort each entries attribute values
  274.         // this is neccessary because later we can only sort by one value,
  275.         // so we need the highest or lowest attribute now, depending on the
  276.         // selected ordering for that specific attribute
  277.         foreach ($entries as $dn => $entry{
  278.             foreach ($entry as $attr_name => $attr_values{
  279.                 sort($entries[$dn][$attr_name]);
  280.                 if ($order == SORT_DESC{
  281.                     array_reverse($entries[$dn][$attr_name]);
  282.                 }
  283.             }
  284.         }
  285.  
  286.         // reformat entrys array for later use with array_multisort()
  287.         $to_sort = array()// <- will be a numeric array similar to ldap_get_entries
  288.         foreach ($entries as $dn => $entry_attr{
  289.             $row       = array();
  290.             $row['dn'$dn;
  291.             foreach ($entry_attr as $attr_name => $attr_values{
  292.                 $row[$attr_name$attr_values;
  293.             }
  294.             $to_sort[$row;
  295.         }
  296.  
  297.         // Build columns for array_multisort()
  298.         // each requested attribute is one row
  299.         $columns = array();
  300.         foreach ($attrs as $attr_name{
  301.             foreach ($to_sort as $key => $row{
  302.                 $columns[$attr_name][$key=$to_sort[$key][$attr_name][0];
  303.             }
  304.         }
  305.  
  306.         // sort the colums with array_multisort, if there is something
  307.         // to sort and if we have requested sort columns
  308.         if (!empty($to_sort&& !empty($columns)) {
  309.             $sort_params '';
  310.             foreach ($attrs as $attr_name{
  311.                 $sort_params .= '$columns[\''.$attr_name.'\'], '.$order.', ';
  312.             }
  313.             eval("array_multisort($sort_params \$to_sort);")// perform sorting
  314.         }
  315.  
  316.         return $to_sort;
  317.     }
  318.  
  319.     /**
  320.     * Return entries sorted as objects
  321.     *
  322.     * This returns a array with sorted Net_LDAP2_Entry objects.
  323.     * The sorting is actually done with {@link sorted_as_struct()}.
  324.     *
  325.     * Please note that attribute names are case sensitive!
  326.     *
  327.     * Usage example:
  328.     * <code>
  329.     *   // to sort entries first by location, then by surename, but descending:
  330.     *   $entries = $search->sorted(array('locality','sn'), SORT_DESC);
  331.     * </code>
  332.     *
  333.     * @param array $attrs Array of sort attributes to sort; order from left to right.
  334.     * @param int   $order Ordering direction, either constant SORT_ASC or SORT_DESC
  335.     *
  336.     * @return array|Net_LDAP2_Error  Array with sorted Net_LDAP2_Entries or error
  337.     */
  338.     function sorted($attrs = array('cn')$order = SORT_ASC)
  339.     {
  340.         $return = array();
  341.         $sorted $this->sorted_as_struct($attrs$order);
  342.         if (PEAR::isError($sorted)) {
  343.             return $sorted;
  344.         }
  345.         foreach ($sorted as $key => $row{
  346.             $entry $this->_ldap->getEntry($row['dn']$this->_searchedAttrs());
  347.             if (!PEAR::isError($entry)) {
  348.                 array_push($return$entry);
  349.             else {
  350.                 return $entry;
  351.             }
  352.         }
  353.         return $return;
  354.     }
  355.  
  356.     /**
  357.     * Return entries as array
  358.     *
  359.     * This method returns the entries and the selected attributes values as
  360.     * array.
  361.     * The first array level contains all found entries where the keys are the
  362.     * DNs of the entries. The second level arrays contian the entries attributes
  363.     * such that the keys is the lowercased name of the attribute and the values
  364.     * are stored in another indexed array. Note that the attribute values are stored
  365.     * in an array even if there is no or just one value.
  366.     *
  367.     * The array has the following structure:
  368.     * <code>
  369.     * $return = array(
  370.     *           'cn=foo,dc=example,dc=com' => array(
  371.     *                                                'sn'       => array('foo'),
  372.     *                                                'multival' => array('val1', 'val2', 'valN')
  373.     *                                             )
  374.     *           'cn=bar,dc=example,dc=com' => array(
  375.     *                                                'sn'       => array('bar'),
  376.     *                                                'multival' => array('val1', 'valN')
  377.     *                                             )
  378.     *           )
  379.     * </code>
  380.     *
  381.     * @return array      associative result array as described above
  382.     */
  383.     function as_struct()
  384.     {
  385.         $return  = array();
  386.         $entries $this->entries();
  387.         foreach ($entries as $entry{
  388.             $attrs            = array();
  389.             $entry_attributes $entry->attributes();
  390.             foreach ($entry_attributes as $attr_name{
  391.                 $attr_values $entry->getValue($attr_name'all');
  392.                 if (!is_array($attr_values)) {
  393.                     $attr_values = array($attr_values);
  394.                 }
  395.                 $attrs[$attr_name$attr_values;
  396.             }
  397.             $return[$entry->dn()$attrs;
  398.         }
  399.         return $return;
  400.     }
  401.  
  402.     /**
  403.     * Set the search objects resource link
  404.     *
  405.     * @param resource &$search Search result identifier
  406.     *
  407.     * @access public
  408.     * @return void 
  409.     */
  410.     function setSearch(&$search)
  411.     {
  412.         $this->_search $search;
  413.     }
  414.  
  415.     /**
  416.     * Set the ldap ressource link
  417.     *
  418.     * @param resource &$link Link identifier
  419.     *
  420.     * @access public
  421.     * @return void 
  422.     */
  423.     function setLink(&$link)
  424.     {
  425.         $this->_link $link;
  426.     }
  427.  
  428.     /**
  429.     * Returns the number of entries in the searchresult
  430.     *
  431.     * @return int Number of entries in search.
  432.     */
  433.     function count()
  434.     {
  435.         // this catches the situation where OL returned errno 32 = no such object!
  436.         if (!$this->_search{
  437.             return 0;
  438.         }
  439.         return @ldap_count_entries($this->_link$this->_search);
  440.     }
  441.  
  442.     /**
  443.     * Get the errorcode the object got in its search.
  444.     *
  445.     * @return int The ldap error number.
  446.     */
  447.     function getErrorCode()
  448.     {
  449.         return $this->_errorCode;
  450.     }
  451.  
  452.     /**
  453.     * Destructor
  454.     *
  455.     * @access protected
  456.     */
  457.     function _Net_LDAP2_Search()
  458.     {
  459.         @ldap_free_result($this->_search);
  460.     }
  461.  
  462.     /**
  463.     * Closes search result
  464.     *
  465.     * @return void 
  466.     */
  467.     function done()
  468.     {
  469.         $this->_Net_LDAP2_Search();
  470.     }
  471.  
  472.     /**
  473.     * Return the attribute names this search selected
  474.     *
  475.     * @return array 
  476.     * @see $_searchedAttrs
  477.     * @access private
  478.     */
  479.     function _searchedAttrs()
  480.     {
  481.         return $this->_searchedAttrs;
  482.     }
  483.  
  484.     /**
  485.     * Tells if this search exceeds a sizelimit
  486.     *
  487.     * @return boolean 
  488.     */
  489.     function sizeLimitExceeded()
  490.     {
  491.         return ($this->getErrorCode(== 4);
  492.     }
  493.  
  494.  
  495.     /*
  496.     * SPL Iterator interface methods.
  497.     * This interface allows to use Net_LDAP2_Search
  498.     * objects directly inside a foreach loop!
  499.     */
  500.     /**
  501.     * SPL Iterator interface: Return the current element.
  502.     *
  503.     * The SPL Iterator interface allows you to fetch entries inside
  504.     * a foreach() loop: <code>foreach ($search as $dn => $entry) { ...</code>
  505.     *
  506.     * Of course, you may call {@link current()}{@link key()}{@link next()},
  507.     * {@link rewind()} and {@link valid()} yourself.
  508.     *
  509.     * If the search throwed an error, it returns false.
  510.     * False is also returned, if the end is reached
  511.     * In case no call to next() was made, we will issue one,
  512.     * thus returning the first entry.
  513.     *
  514.     * @return Net_LDAP2_Entry|false
  515.     */
  516.     function current()
  517.     {
  518.         if (count($this->_iteratorCache== 0{
  519.             $this->next();
  520.             reset($this->_iteratorCache);
  521.         }
  522.         $entry current($this->_iteratorCache);
  523.         return ($entry instanceof Net_LDAP2_Entry)$entry : false;
  524.     }
  525.  
  526.     /**
  527.     * SPL Iterator interface: Return the identifying key (DN) of the current entry.
  528.     *
  529.     * @see current()
  530.     * @return string|falseDN of the current entry; false in case no entry is returned by current()
  531.     */
  532.     function key()
  533.     {
  534.         $entry $this->current();
  535.         return ($entry instanceof Net_LDAP2_Entry)$entry->dn(:false;
  536.     }
  537.  
  538.     /**
  539.     * SPL Iterator interface: Move forward to next entry.
  540.     *
  541.     * After a call to {@link next()}{@link current()} will return
  542.     * the next entry in the result set.
  543.     *
  544.     * @see current()
  545.     * @return void 
  546.     */
  547.     function next()
  548.     {
  549.         // fetch next entry.
  550.         // if we have no entrys anymore, we add false (which is
  551.         // returned by shiftEntry()) so current() will complain.
  552.         if (count($this->_iteratorCache- 1 <= $this->count()) {
  553.             $this->_iteratorCache[$this->shiftEntry();
  554.         }
  555.  
  556.         // move on array pointer to current element.
  557.         // even if we have added all entries, this will
  558.         // ensure proper operation in case we rewind()
  559.         next($this->_iteratorCache);
  560.     }
  561.  
  562.     /**
  563.     * SPL Iterator interface:  Check if there is a current element after calls to {@link rewind()} or {@link next()}.
  564.     *
  565.     * Used to check if we've iterated to the end of the collection.
  566.     *
  567.     * @see current()
  568.     * @return boolean FALSE if there's nothing more to iterate over
  569.     */
  570.     function valid()
  571.     {
  572.         return ($this->current(instanceof Net_LDAP2_Entry);
  573.     }
  574.  
  575.     /**
  576.     * SPL Iterator interface: Rewind the Iterator to the first element.
  577.     *
  578.     * After rewinding, {@link current()} will return the first entry in the result set.
  579.     *
  580.     * @see current()
  581.     * @return void 
  582.     */
  583.     function rewind()
  584.     {
  585.         reset($this->_iteratorCache);
  586.     }
  587. }
  588.  
  589. ?>

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