code:
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4: */
/**
* File containing the Net_LDAP2_Entry interface class.
*
* PHP version 5
*
* @category  Net
* @package   Net_LDAP2
* @author    Jan Wagner <wagner@netsols.de>
* @author    Tarjej Huse <tarjei@bergfald.no>
* @author    Benedikt Hallinger <beni@php.net>
* @copyright 2009 Tarjej Huse, Jan Wagner, Benedikt Hallinger
* @license   http://www.gnu.org/licenses/lgpl-3.0.txt LGPLv3
* @version   SVN: $Id$
* @link      http://pear.php.net/package/Net_LDAP2/
*/

/**
* Includes
*/
require_once 'PEAR.php';
require_once 'Net/LDAP2/Util.php';

/**
* Object representation of a directory entry
*
* This class represents a directory entry. You can add, delete, replace
* attributes and their values, rename the entry, delete the entry.
*
* @category Net
* @package  Net_LDAP2
* @author   Jan Wagner <wagner@netsols.de>
* @author   Tarjej Huse <tarjei@bergfald.no>
* @author   Benedikt Hallinger <beni@php.net>
* @license  http://www.gnu.org/copyleft/lesser.html LGPL
* @link     http://pear.php.net/package/Net_LDAP2/
*/
class Net_LDAP2_Entry extends PEAR
{
    /**
    * Entry ressource identifier
    *
    * @access protected
    * @var ressource
    */
    protected $_entry = null;

    /**
    * LDAP ressource identifier
    *
    * @access protected
    * @var ressource
    */
    protected $_link = null;

    /**
    * Net_LDAP2 object
    *
    * This object will be used for updating and schema checking
    *
    * @access protected
    * @var object Net_LDAP2
    */
    protected $_ldap = null;

    /**
    * Distinguished name of the entry
    *
    * @access protected
    * @var string
    */
    protected $_dn = null;

    /**
    * Attributes
    *
    * @access protected
    * @var array
    */
    protected $_attributes = array();

    /**
    * Original attributes before any modification
    *
    * @access protected
    * @var array
    */
    protected $_original = array();

    /**
    * Map of attribute names
    *
    * @access protected
    * @var array
    */
    protected $_map = array();

    /**
    * Is this a new entry?
    *
    * @access protected
    * @var boolean
    */
    protected $_new = true;

    /**
    * New distinguished name
    *
    * @access protected
    * @var string
    */
    protected $_newdn = null;

    /**
    * Shall the entry be deleted?
    *
    * @access protected
    * @var boolean
    */
    protected $_delete = false;

    /**
    * Map with changes to the entry
    *
    * @access protected
    * @var array
    */
    protected $_changes = array("add"     => array(),
                                "delete"  => array(),
                                "replace" => array()
                               );
    /**
    * Internal Constructor
    *
    * Constructor of the entry. Sets up the distinguished name and the entries
    * attributes.
    * You should not call this method manually! Use {@link Net_LDAP2_Entry::createFresh()}
    * or {@link Net_LDAP2_Entry::createConnected()} instead!
    *
    * @param Net_LDAP2|ressource|array $ldap Net_LDAP2 object, ldap-link ressource or array of attributes
    * @param string|ressource          $entry Either a DN or a LDAP-Entry ressource
    *
    * @access protected
    * @return none
    */
    public function __construct($ldap, $entry = null)
    {
        parent::__construct('Net_LDAP2_Error');

        // set up entry resource or DN
        if (is_resource($entry)) {
            $this->_entry = $entry;
        } else {
            $this->_dn = $entry;
        }

        // set up LDAP link
        if ($ldap instanceof Net_LDAP2) {
            $this->_ldap = $ldap;
            $this->_link = $ldap->getLink();
        } elseif (is_resource($ldap)) {
            $this->_link = $ldap;
        } elseif (is_array($ldap)) {
            // Special case: here $ldap is an array of attributes,
            // this means, we have no link. This is a "virtual" entry.
            // We just set up the attributes so one can work with the object
            // as expected, but an update() fails unless setLDAP() is called.
            $this->setAttributes($ldap);
        }

        // if this is an entry existing in the directory,
        // then set up as old and fetch attrs
        if (is_resource($this->_entry) && is_resource($this->_link)) {
            $this->_new = false;
            $this->_dn  = @ldap_get_dn($this->_link, $this->_entry);
            $this->setAttributes();  // fetch attributes from server
        }
    }

    /**
    * Creates a fresh entry that may be added to the directory later on
    *
    * Use this method, if you want to initialize a fresh entry.
    *
    * The method should be called statically: $entry = Net_LDAP2_Entry::createFresh();
    * You should put a 'objectClass' attribute into the $attrs so the directory server
    * knows which object you want to create. However, you may omit this in case you
    * don't want to add this entry to a directory server.
    *
    * The attributes parameter is as following:
    *
    * $attrs = array( 'attribute1' => array('value1', 'value2'),
    *                 'attribute2' => 'single value'
    *          );
    *
    *
    * @param string $dn    DN of the Entry
    * @param array  $attrs Attributes of the entry
    *
    * @static
    * @return Net_LDAP2_Entry|Net_LDAP2_Error
    */
    public static function createFresh($dn, $attrs = array())
    {
        if (!is_array($attrs)) {
            return PEAR::raiseError("Unable to create fresh entry: Parameter \$attrs needs to be an array!");
        }

        $entry = new Net_LDAP2_Entry($attrs, $dn);
        return $entry;
    }

    /**
    * Creates a Net_LDAP2_Entry object out of an ldap entry resource
    *
    * Use this method, if you want to initialize an entry object that is
    * already present in some directory and that you have read manually.
    *
    * Please note, that if you want to create an entry object that represents
    * some already existing entry, you should use {@link createExisting()}.
    *
    * The method should be called statically: $entry = Net_LDAP2_Entry::createConnected();
    *
    * @param Net_LDAP2 $ldap  Net_LDA2 object
    * @param resource  $entry PHP LDAP entry resource
    *
    * @static
    * @return Net_LDAP2_Entry|Net_LDAP2_Error
    */
    public static function createConnected($ldap, $entry)
    {
        if (!$ldap instanceof Net_LDAP2) {
            return PEAR::raiseError("Unable to create connected entry: Parameter \$ldap needs to be a Net_LDAP2 object!");
        }
        if (!is_resource($entry)) {
            return PEAR::raiseError("Unable to create connected entry: Parameter \$entry needs to be a ldap entry resource!");
        }

        $entry = new Net_LDAP2_Entry($ldap, $entry);
        return $entry;
    }

    /**
    * Creates an Net_LDAP2_Entry object that is considered already existing
    *
    * Use this method, if you want to modify an already existing entry
    * without fetching it first.
    * In most cases however, it is better to fetch the entry via Net_LDAP2->getEntry()!
    *
    * Please note that you should take care if you construct entries manually with this
    * because you may get weird synchronisation problems.
    * The attributes and values as well as the entry itself are considered existent
    * which may produce errors if you try to modify an entry which doesn't really exist
    * or if you try to overwrite some attribute with an value already present.
    *
    * This method is equal to calling createFresh() and after that markAsNew(FALSE).
    *
    * The method should be called statically: $entry = Net_LDAP2_Entry::createExisting();
    *
    * The attributes parameter is as following:
    *
    * $attrs = array( 'attribute1' => array('value1', 'value2'),
    *                 'attribute2' => 'single value'
    *          );
    *
    *
    * @param string $dn    DN of the Entry
    * @param array  $attrs Attributes of the entry
    *
    * @static
    * @return Net_LDAP2_Entry|Net_LDAP2_Error
    */
    public static function createExisting($dn, $attrs = array())
    {
        if (!is_array($attrs)) {
            return PEAR::raiseError("Unable to create entry object: Parameter \$attrs needs to be an array!");
        }

        $entry = Net_LDAP2_Entry::createFresh($dn, $attrs);
        if ($entry instanceof Net_LDAP2_Error) {
            return $entry;
        } else {
            $entry->markAsNew(false);
            return $entry;
        }
    }

    /**
    * Get or set the distinguished name of the entry
    *
    * If called without an argument the current (or the new DN if set) DN gets returned.
    * If you provide an DN, this entry is moved to the new location specified if a DN existed.
    * If the DN was not set, the DN gets initialized. Call {@link update()} to actually create
    * the new Entry in the directory.
    * To fetch the current active DN after setting a new DN but before an update(), you can use
    * {@link currentDN()} to retrieve the DN that is currently active.
    *
    * Please note that special characters (eg german umlauts) should be encoded using utf8_encode().
    * You may use {@link Net_LDAP2_Util::canonical_dn()} for properly encoding of the DN.
    *
    * @param string $dn New distinguished name
    *
    * @access public
    * @return string|true Distinguished name (or true if a new DN was provided)
    */
    public function dn($dn = null)
    {
        if (false == is_null($dn)) {
            if (is_null($this->_dn) ) {
                $this->_dn = $dn;
            } else {
                $this->_newdn = $dn;
            }
            return true;
        }
        return (isset($this->_newdn) ? $this->_newdn : $this->currentDN());
    }

    /**
    * Renames or moves the entry
    *
    * This is just a convinience alias to {@link dn()}
    * to make your code more meaningful.
    *
    * @param string $newdn The new DN
    *
    * @return true
    */
    public function move($newdn)
    {
        return $this->dn($newdn);
    }

    /**
    * Sets the internal attributes array
    *
    * This fetches the values for the attributes from the server.
    * The attribute Syntax will be checked so binary attributes will be returned
    * as binary values.
    *
    * Attributes may be passed directly via the $attributes parameter to setup this
    * entry manually. This overrides attribute fetching from the server.
    *
    * @param array $attributes Attributes to set for this entry
    *
    * @access protected
    * @return void
    */
    protected function setAttributes($attributes = null)
    {
        /*
        * fetch attributes from the server
        */
        if (is_null($attributes) && is_resource($this->_entry) && is_resource($this->_link)) {
            // fetch schema
            if ($this->_ldap instanceof Net_LDAP2) {
                $schema = $this->_ldap->schema();
            }
            // fetch attributes
            $attributes = array();
            do {
                if (empty($attr)) {
                    $ber  = null;
                    $attr = @ldap_first_attribute($this->_link, $this->_entry, $ber);
                } else {
                    $attr = @ldap_next_attribute($this->_link, $this->_entry, $ber);
                }
                if ($attr) {
                    $func = 'ldap_get_values'; // standard function to fetch value

                    // Try to get binary values as binary data
                    if ($schema instanceof Net_LDAP2_Schema) {
                        if ($schema->isBinary($attr)) {
                             $func = 'ldap_get_values_len';
                        }
                    }
                    // fetch attribute value (needs error checking?)
                    $attributes[$attr] = $func($this->_link, $this->_entry, $attr);
                }
            } while ($attr);
        }

        /*
        * set attribute data directly, if passed
        */
        if (is_array($attributes) && count($attributes) > 0) {
            if (isset($attributes["count"]) && is_numeric($attributes["count"])) {
                unset($attributes["count"]);
            }
            foreach ($attributes as $k => $v) {
                // attribute names should not be numeric
                if (is_numeric($k)) {
                    continue;
                }
                // map generic attribute name to real one
                $this->_map[strtolower($k)] = $k;
                // attribute values should be in an array
                if (false == is_array($v)) {
                    $v = array($v);
                }
                // remove the value count (comes from ldap server)
                if (isset($v["count"])) {
                    unset($v["count"]);
                }
                $this->_attributes[$k] = $v;
            }
        }

        // save a copy for later use
        $this->_original = $this->_attributes;
    }

    /**
    * Get the values of all attributes in a hash
    *
    * The returned hash has the form
    * array('attributename' => 'single value',
    *       'attributename' => array('value1', value2', value3'))
    * Only attributes present at the entry will be returned.
    *
    * @access public
    * @return array Hash of all attributes with their values
    */
    public function getValues()
    {
        $attrs = array();
        foreach ($this->_attributes as $attr => $value) {
            $attrs[$attr] = $this->getValue($attr);
        }
        return $attrs;
    }

    /**
    * Get the value of a specific attribute
    *
    * The first parameter is the name of the attribute
    * The second parameter influences the way the value is returned:
    * 'single':  only the first value is returned as string
    * 'all':     all values are returned in an array
    * 'default': in all other cases an attribute value with a single value is
    *            returned as string, if it has multiple values it is returned
    *            as an array
    *
    * If the attribute is not set at this entry (no value or not defined in
    * schema), "false" is returned when $option is 'single', an empty string if
    * 'default', and an empty array when 'all'.
    *
    * You may use Net_LDAP2_Schema->checkAttribute() to see if the attribute
    * is defined for the objectClasses of this entry.
    *
    * @param string  $attr         Attribute name
    * @param string  $option       Option
    *
    * @access public
    * @return string|array
    */
    public function getValue($attr, $option = null)
    {
        $attr = $this->getAttrName($attr);

        // return depending on set $options
        if (!array_key_exists($attr, $this->_attributes)) {
            // attribute not set
            switch ($option) {
                case 'single':
                    $value = false;
                break;
                case 'all':
                    $value = array();
                break;
                default:
                    $value = '';
            }

        } else {
            // attribute present
            switch ($option) {
                case 'single':
                    $value = $this->_attributes[$attr][0];
                break;
                case 'all':
                    $value = $this->_attributes[$attr];
                break;
                default:
                    $value = $this->_attributes[$attr];
                    if (count($value) == 1) {
                        $value = array_shift($value);
                    }
            }

        }

        return $value;
    }

    /**
    * Alias function of getValue for perl-ldap interface
    *
    * @see getValue()
    * @return string|array|PEAR_Error
    */
    public function get_value()
    {
        $args = func_get_args();
        return call_user_func_array(array( $this, 'getValue' ), $args);
    }

    /**
    * Returns an array of attributes names
    *
    * @access public
    * @return array Array of attribute names
    */
    public function attributes()
    {
        return array_keys($this->_attributes);
    }

    /**
    * Returns whether an attribute exists or not
    *
    * @param string $attr Attribute name
    *
    * @access public
    * @return boolean
    */
    public function exists($attr)
    {
        $attr = $this->getAttrName($attr);
        return array_key_exists($attr, $this->_attributes);
    }

    /**
    * Adds a new attribute or a new value to an existing attribute
    *
    * The paramter has to be an array of the form:
    * array('attributename' => 'single value',
    *       'attributename' => array('value1', 'value2))
    * When the attribute already exists the values will be added, else the
    * attribute will be created. These changes are local to the entry and do
    * not affect the entry on the server until update() is called.
    *
    * Note, that you can add values of attributes that you haven't selected, but if
    * you do so, {@link getValue()} and {@link getValues()} will only return the
    * values you added, _NOT_ all values present on the server. To avoid this, just refetch
    * the entry after calling {@link update()} or select the attribute.
    *
    * @param array $attr Attributes to add
    *
    * @access public
    * @return true|Net_LDAP2_Error
    */
    public function add($attr = array())
    {
        if (false == is_array($attr)) {
            return PEAR::raiseError("Parameter must be an array");
        }
        if ($this->isNew()) {
            $this->setAttributes($attr);
        }
        foreach ($attr as $k => $v) {
            $k = $this->getAttrName($k);
            if (false == is_array($v)) {
                // Do not add empty values
                if ($v == null) {
                    continue;
                } else {
                    $v = array($v);
                }
            }
            // add new values to existing attribute or add new attribute
            if ($this->exists($k)) {
                $this->_attributes[$k] = array_unique(array_merge($this->_attributes[$k], $v));
            } else {
                $this->_map[strtolower($k)] = $k;
                $this->_attributes[$k]      = $v;
            }
            // save changes for update()
            if (!isset($this->_changes["add"][$k])) {
                $this->_changes["add"][$k] = array();
            }
            $this->_changes["add"][$k] = array_unique(array_merge($this->_changes["add"][$k], $v));
        }

        $return = true;
        return $return;
    }

    /**
    * Deletes an whole attribute or a value or the whole entry
    *
    * The parameter can be one of the following:
    *
    * "attributename" - The attribute as a whole will be deleted
    * array("attributename1", "attributename2) - All given attributes will be
    *                                            deleted
    * array("attributename" => "value") - The value will be deleted
    * array("attributename" => array("value1", "value2") - The given values
    *                                                      will be deleted
    * If $attr is null or omitted , then the whole Entry will be deleted!
    *
    * These changes are local to the entry and do
    * not affect the entry on the server until {@link update()} is called.
    *
    * Please note that you must select the attribute (at $ldap->search() for example)
    * to be able to delete values of it, Otherwise {@link update()} will silently fail
    * and remove nothing.
    *
    * @param string|array $attr Attributes to delete (NULL or missing to delete whole entry)
    *
    * @access public
    * @return true
    */
    public function delete($attr = null)
    {
        if (is_null($attr)) {
            $this->_delete = true;
            return true;
        }
        if (is_string($attr)) {
            $attr = array($attr);
        }
        // Make the assumption that attribute names cannot be numeric,
        // therefore this has to be a simple list of attribute names to delete
        if (is_numeric(key($attr))) {
            foreach ($attr as $name) {
                if (is_array($name)) {
                    // someone mixed modes (list mode but specific values given!)
                    $del_attr_name = array_search($name, $attr);
                    $this->delete(array($del_attr_name => $name));
                } else {
                    // mark for update() if this attr was not marked before
                    $name = $this->getAttrName($name);
                    if ($this->exists($name)) {
                        $this->_changes["delete"][$name] = null;
                        unset($this->_attributes[$name]);
                    }
                }
            }
        } else {
            // Here we have a hash with "attributename" => "value to delete"
            foreach ($attr as $name => $values) {
                if (is_int($name)) {
                    // someone mixed modes and gave us just an attribute name
                    $this->delete($values);
                } else {
                    // mark for update() if this attr was not marked before;
                    // this time it must consider the selected values also
                    $name = $this->getAttrName($name);
                    if ($this->exists($name)) {
                        if (false == is_array($values)) {
                            $values = array($values);
                        }
                        // save values to be deleted
                        if (empty($this->_changes["delete"][$name])) {
                            $this->_changes["delete"][$name] = array();
                        }
                        $this->_changes["delete"][$name] =
                            array_unique(array_merge($this->_changes["delete"][$name], $values));
                        foreach ($values as $value) {
                            // find the key for the value that should be deleted
                            $key = array_search($value, $this->_attributes[$name]);
                            if (false !== $key) {
                                // delete the value
                                unset($this->_attributes[$name][$key]);
                            }
                        }
                    }
                }
            }
        }
        $return = true;
        return $return;
    }

    /**
    * Replaces attributes or its values
    *
    * The parameter has to an array of the following form:
    * array("attributename" => "single value",
    *       "attribute2name" => array("value1", "value2"),
    *       "deleteme1" => null,
    *       "deleteme2" => "")
    * If the attribute does not yet exist it will be added instead (see also $force).
    * If the attribue value is null, the attribute will de deleted.
    *
    * These changes are local to the entry and do
    * not affect the entry on the server until {@link update()} is called.
    *
    * In some cases you are not allowed to read the attributes value (for
    * example the ActiveDirectory attribute unicodePwd) but are allowed to
    * replace the value. In this case replace() would assume that the attribute
    * is not in the directory yet and tries to add it which will result in an
    * LDAP_TYPE_OR_VALUE_EXISTS error.
    * To force replace mode instead of add, you can set $force to true.
    *
    * @param array $attr  Attributes to replace
    * @param bool  $force Force replacing mode in case we can't read the attr value but are allowed to replace it
    *
    * @access public
    * @return true|Net_LDAP2_Error
    */
    public function replace($attr = array(), $force = false)
    {
        if (false == is_array($attr)) {
            return PEAR::raiseError("Parameter must be an array");
        }
        foreach ($attr as $k => $v) {
            $k = $this->getAttrName($k);
            if (false == is_array($v)) {
                // delete attributes with empty values; treat ints as string
                if (is_int($v)) {
                    $v = "$v";
                }
                if ($v == null) {
                    $this->delete($k);
                    continue;
                } else {
                    $v = array($v);
                }
            }
            // existing attributes will get replaced
            if ($this->exists($k) || $force) {
                $this->_changes["replace"][$k] = $v;
                $this->_attributes[$k]         = $v;
            } else {
                // new ones just get added
                $this->add(array($k => $v));
            }
        }
        $return = true;
        return $return;
    }

    /**
    * Update the entry on the directory server
    *
    * This will evaluate all changes made so far and send them
    * to the directory server.
    * Please note, that if you make changes to objectclasses wich
    * have mandatory attributes set, update() will currently fail.
    * Remove the entry from the server and readd it as new in such cases.
    * This also will deal with problems with setting structural object classes.
    *
    * @param Net_LDAP2 $ldap If passed, a call to setLDAP() is issued prior update, thus switching the LDAP-server. This is for perl-ldap interface compliance
    *
    * @access public
    * @return true|Net_LDAP2_Error
    * @todo Entry rename with a DN containing special characters needs testing!
    */
    public function update($ldap = null)
    {
        if ($ldap) {
            $msg = $this->setLDAP($ldap);
            if (Net_LDAP2::isError($msg)) {
                return PEAR::raiseError('You passed an invalid $ldap variable to update()');
            }
        }

        // ensure we have a valid LDAP object
        $ldap = $this->getLDAP();
        if (!$ldap instanceof Net_LDAP2) {
            return PEAR::raiseError("The entries LDAP object is not valid");
        }

        // Get and check link
        $link = $ldap->getLink();
        if (!is_resource($link)) {
            return PEAR::raiseError("Could not update entry: internal LDAP link is invalid");
        }

        /*
        * Delete the entry
        */
        if (true === $this->_delete) {
            return $ldap->delete($this);
        }

        /*
        * New entry
        */
        if (true === $this->_new) {
            $msg = $ldap->add($this);
            if (Net_LDAP2::isError($msg)) {
                return $msg;
            }
            $this->_new                = false;
            $this->_changes['add']     = array();
            $this->_changes['delete']  = array();
            $this->_changes['replace'] = array();
            $this->_original           = $this->_attributes;

            // In case the "new" entry was moved after creation, we must
            // adjust the internal DNs as the entry was already created
            // with the most current DN.
            if (false == is_null($this->_newdn)) {
                $this->_dn    = $this->_newdn;
                $this->_newdn = null;
            }

            $return = true;
            return $return;
        }

        /*
        * Rename/move entry
        */
        if (false == is_null($this->_newdn)) {
            if ($ldap->getLDAPVersion() !== 3) {
                return PEAR::raiseError("Renaming/Moving an entry is only supported in LDAPv3");
            }
            // make dn relative to parent (needed for ldap rename)
            $parent = Net_LDAP2_Util::ldap_explode_dn($this->_newdn, array('casefolding' => 'none', 'reverse' => false, 'onlyvalues' => false));
            if (Net_LDAP2::isError($parent)) {
                return $parent;
            }
            $child = array_shift($parent);
            // maybe the dn consist of a multivalued RDN, we must build the dn in this case
            // because the $child-RDN is an array!
            if (is_array($child)) {
                $child = Net_LDAP2_Util::canonical_dn($child);
            }
            $parent = Net_LDAP2_Util::canonical_dn($parent);

            // rename/move
            if (false == @ldap_rename($link, $this->_dn, $child, $parent, false)) {

                return PEAR::raiseError("Entry not renamed: " .
                                        @ldap_error($link), @ldap_errno($link));
            }
            // reflect changes to local copy
            $this->_dn    = $this->_newdn;
            $this->_newdn = null;
        }

        /*
        * Retrieve a entry that has all attributes we need so that the list of changes to build is created accurately
        */
        $fullEntry = $ldap->getEntry( $this->dn() );
        if ( Net_LDAP2::isError($fullEntry) ) {
            return PEAR::raiseError("Could not retrieve a full set of attributes to reconcile changes with");
        }
        $modifications = array();

        // ADD
        foreach ($this->_changes["add"] as $attr => $value) {
            // if attribute exists, we need to combine old and new values
            if ($fullEntry->exists($attr)) {
                $currentValue = $fullEntry->getValue($attr, "all");
                $value = array_merge( $currentValue, $value );
            }

            $modifications[$attr] = $value;
        }

        // DELETE
        foreach ($this->_changes["delete"] as $attr => $value) {
            // In LDAPv3 you need to specify the old values for deleting
            if (is_null($value) && $ldap->getLDAPVersion() === 3) {
                $value = $fullEntry->getValue($attr);
            }
            if (!is_array($value)) {
                $value = array($value);
            }

            // Find out what is missing from $value and exclude it
            $currentValue = isset($modifications[$attr]) ? $modifications[$attr] : $fullEntry->getValue($attr, "all");
            $modifications[$attr] = array_values( array_diff( $currentValue, $value ) );
        }

        // REPLACE
        foreach ($this->_changes["replace"] as $attr => $value) {
            $modifications[$attr] = $value;
        }

        // COMMIT
        if (false === @ldap_modify($link, $this->dn(), $modifications)) {
            return PEAR::raiseError("Could not modify the entry: " . @ldap_error($link), @ldap_errno($link));
        }

        // all went well, so _original (server) becomes _attributes (local copy), reset _changes too...
        $this->_changes['add']     = array();
        $this->_changes['delete']  = array();
        $this->_changes['replace'] = array();
        $this->_original           = $this->_attributes;

        $return = true;
        return $return;
    }

    /**
    * Returns the right attribute name
    *
    * @param string $attr Name of attribute
    *
    * @access protected
    * @return string The right name of the attribute
    */
    protected function getAttrName($attr)
    {
        $name = strtolower($attr);
        if (array_key_exists($name, $this->_map)) {
            $attr = $this->_map[$name];
        }
        return $attr;
    }

    /**
    * Returns a reference to the LDAP-Object of this entry
    *
    * @access public
    * @return Net_LDAP2|Net_LDAP2_Error   Reference to the Net_LDAP2 Object (the connection) or Net_LDAP2_Error
    */
    public function getLDAP()
    {
        if (!$this->_ldap instanceof Net_LDAP2) {
            $err = new PEAR_Error('LDAP is not a valid Net_LDAP2 object');
            return $err;
        } else {
            return $this->_ldap;
        }
    }

    /**
    * Sets a reference to the LDAP-Object of this entry
    *
    * After setting a Net_LDAP2 object, calling update() will use that object for
    * updating directory contents. Use this to dynamicly switch directorys.
    *
    * @param Net_LDAP2 $ldap Net_LDAP2 object that this entry should be connected to
    *
    * @access public
    * @return true|Net_LDAP2_Error
    */
    public function setLDAP($ldap)
    {
        if (!$ldap instanceof Net_LDAP2) {
            return PEAR::raiseError("LDAP is not a valid Net_LDAP2 object");
        } else {
            $this->_ldap = $ldap;
            return true;
        }
    }

    /**
    * Marks the entry as new/existing.
    *
    * If an Entry is marked as new, it will be added to the directory
    * when calling {@link update()}.
    * If the entry is marked as old ($mark = false), then the entry is
    * assumed to be present in the directory server wich results in
    * modification when calling {@link update()}.
    *
    * @param boolean $mark Value to set, defaults to "true"
    *
    * @return void
    */
    public function markAsNew($mark = true)
    {
        $this->_new = ($mark)? true : false;
    }

    /**
    * Applies a regular expression onto a single- or multivalued attribute (like preg_match())
    *
    * This method behaves like PHPs preg_match() but with some exceptions.
    * If you want to retrieve match information, then you MUST pass the
    * $matches parameter via reference! otherwise you will get no matches.
    * Since it is possible to have multi valued attributes the $matches
    * array will have a additionally numerical dimension (one for each value):
    *
    * $matches = array(
    *         0 => array (usual preg_match() returnarray),
    *         1 => array (usual preg_match() returnarray)
    *     )
    *
    * Please note, that $matches will be initialized to an empty array inside.
    *
    * Usage example:
    *
    * $result = $entry->preg_match('/089(\d+)/', 'telephoneNumber', $matches);
    * if ( $result === true ){
    *     echo "First match: ".$matches[0][1];   // Match of value 1, content of first bracket
    * } else {
    *     if ( Net_LDAP2::isError($result) ) {
    *         echo "Error: ".$result->getMessage();
    *     } else {
    *         echo "No match found.";
    *     }
    * }
    *
    *
    * Please note that it is important to test for an Net_LDAP2_Error, because objects are
    * evaluating to true by default, thus if an error occured, and you only check using "==" then
    * you get misleading results. Use the "identical" (===) operator to test for matches to
    * avoid this as shown above.
    *
    * @param string $regex     The regular expression
    * @param string $attr_name The attribute to search in
    * @param array  $matches   (optional, PASS BY REFERENCE!) Array to store matches in
    *
    * @return boolean|Net_LDAP2_Error  TRUE, if we had a match in one of the values, otherwise false. Net_LDAP2_Error in case something went wrong
    */
    public function pregMatch($regex, $attr_name, $matches = array())
    {
        $matches = array();

        // fetch attribute values
        $attr = $this->getValue($attr_name, 'all');

        // perform preg_match() on all values
        $match = false;
        foreach ($attr as $thisvalue) {
            $matches_int = array();
            if (preg_match($regex, $thisvalue, $matches_int)) {
                $match = true;
                array_push($matches, $matches_int); // store matches in reference
            }
        }
        return $match;
    }

    /**
    * Alias of {@link pregMatch()} for compatibility to Net_LDAP 1
    *
    * @see pregMatch()
    * @return boolean|Net_LDAP2_Error
    */
    public function preg_match()
    {
        $args = func_get_args();
        return call_user_func_array(array( $this, 'pregMatch' ), $args);
    }

    /**
    * Tells if the entry is consiedered as new (not present in the server)
    *
    * Please note, that this doesn't tell you if the entry is present on the server.
    * Use {@link Net_LDAP2::dnExists()} to see if an entry is already there.
    *
    * @return boolean
    */
    public function isNew()
    {
        return $this->_new;
    }

    /**
    * Is this entry going to be deleted once update() is called?
    *
    * @return boolean
    */
    public function willBeDeleted()
    {
        return $this->_delete;
    }

    /**
    * Is this entry going to be moved once update() is called?
    *
    * @return boolean
    */
    public function willBeMoved()
    {
        return ($this->dn() !== $this->currentDN());
    }

    /**
    * Returns always the original DN
    *
    * If an entry will be moved but {@link update()} was not called,
    * {@link dn()} will return the new DN. This method however, returns
    * always the current active DN.
    *
    * @return string
    */
    public function currentDN()
    {
        return $this->_dn;
    }

    /**
    * Returns the attribute changes to be carried out once update() is called
    *
    * @return array
    */
    public function getChanges()
    {
        return $this->_changes;
    }
}
?>

repo_name: spookie/gnu

license: mit


code:
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4: */
/**
* File containing the Net_LDAP2_Filter interface class.
*
* PHP version 5
*
* @category  Net
* @package   Net_LDAP2
* @author    Benedikt Hallinger <beni@php.net>
* @copyright 2009 Benedikt Hallinger
* @license   http://www.gnu.org/licenses/lgpl-3.0.txt LGPLv3
* @version   SVN: $Id$
* @link      http://pear.php.net/package/Net_LDAP2/
*/

/**
* Includes
*/
require_once 'PEAR.php';
require_once 'Net/LDAP2/Util.php';
require_once 'Net/LDAP2/Entry.php';

/**
* Object representation of a part of a LDAP filter.
*
* This Class is not completely compatible to the PERL interface!
*
* The purpose of this class is, that users can easily build LDAP filters
* without having to worry about right escaping etc.
* A Filter is built using several independent filter objects
* which are combined afterwards. This object works in two
* modes, depending how the object is created.
* If the object is created using the {@link create()} method, then this is a leaf-object.
* If the object is created using the {@link combine()} method, then this is a container object.
*
* LDAP filters are defined in RFC-2254 and can be found under
* {@link http://www.ietf.org/rfc/rfc2254.txt}
*
* Here a quick copy&paste example:
*
* $filter0 = Net_LDAP2_Filter::create('stars', 'equals', '***');
* $filter_not0 = Net_LDAP2_Filter::combine('not', $filter0);
*
* $filter1 = Net_LDAP2_Filter::create('gn', 'begins', 'bar');
* $filter2 = Net_LDAP2_Filter::create('gn', 'ends', 'baz');
* $filter_comp = Net_LDAP2_Filter::combine('or',array($filter_not0, $filter1, $filter2));
*
* echo $filter_comp->asString();
* // This will output: (|(!(stars=\0x5c0x2a\0x5c0x2a\0x5c0x2a))(gn=bar*)(gn=*baz))
* // The stars in $filter0 are treaten as real stars unless you disable escaping.
*
*
* @category Net
* @package  Net_LDAP2
* @author   Benedikt Hallinger <beni@php.net>
* @license  http://www.gnu.org/copyleft/lesser.html LGPL
* @link     http://pear.php.net/package/Net_LDAP2/
*/
class Net_LDAP2_Filter extends PEAR
{
    /**
    * Storage for combination of filters
    *
    * This variable holds a array of filter objects
    * that should be combined by this filter object.
    *
    * @access protected
    * @var array
    */
    protected $_subfilters = array();

    /**
    * Match of this filter
    *
    * If this is a leaf filter, then a matching rule is stored,
    * if it is a container, then it is a logical operator
    *
    * @access protected
    * @var string
    */
    protected $_match;

    /**
    * Single filter
    *
    * If we operate in leaf filter mode,
    * then the constructing method stores
    * the filter representation here
    *
    * @acces private
    * @var string
    */
    protected $_filter;

    /**
    * Create a new Net_LDAP2_Filter object and parse $filter.
    *
    * This is for PERL Net::LDAP interface.
    * Construction of Net_LDAP2_Filter objects should happen through either
    * {@link create()} or {@link combine()} which give you more control.
    * However, you may use the perl iterface if you already have generated filters.
    *
    * @param string $filter LDAP filter string
    *
    * @see parse()
    */
    public function __construct($filter = false)
    {
        // The optional parameter must remain here, because otherwise create() crashes
        if (false !== $filter) {
            $filter_o = self::parse($filter);
            if (PEAR::isError($filter_o)) {
                $this->_filter = $filter_o; // assign error, so asString() can report it
            } else {
                $this->_filter = $filter_o->asString();
            }
        }
    }

    /**
    * Constructor of a new part of a LDAP filter.
    *
    * The following matching rules exists:
    *    - equals:         One of the attributes values is exactly $value
    *                      Please note that case sensitiviness is depends on the
    *                      attributes syntax configured in the server.
    *    - begins:         One of the attributes values must begin with $value
    *    - ends:           One of the attributes values must end with $value
    *    - contains:       One of the attributes values must contain $value
    *    - present | any:  The attribute can contain any value but must be existent
    *    - greater:        The attributes value is greater than $value
    *    - less:           The attributes value is less than $value
    *    - greaterOrEqual: The attributes value is greater or equal than $value
    *    - lessOrEqual:    The attributes value is less or equal than $value
    *    - approx:         One of the attributes values is similar to $value
    *
    * Negation ("not") can be done by prepending the above operators with the
    * "not" or "!" keyword, see example below.
    *
    * If $escape is set to true (default) then $value will be escaped
    * properly. If it is set to false then $value will be treaten as raw filter value string.
    * You should escape yourself using {@link Net_LDAP2_Util::escape_filter_value()}!
    *
    * Examples:
    *
    *   // This will find entries that contain an attribute "sn" that ends with "foobar":
    *   $filter = Net_LDAP2_Filter::create('sn', 'ends', 'foobar');
    *
    *   // This will find entries that contain an attribute "sn" that has any value set:
    *   $filter = Net_LDAP2_Filter::create('sn', 'any');
    *
    *   // This will build a negated equals filter:
    *   $filter = Net_LDAP2_Filter::create('sn', 'not equals', 'foobar');
    *
    *
    * @param string  $attr_name Name of the attribute the filter should apply to
    * @param string  $match     Matching rule (equals, begins, ends, contains, greater, less, greaterOrEqual, lessOrEqual, approx, any)
    * @param string  $value     (optional) if given, then this is used as a filter
    * @param boolean $escape    Should $value be escaped? (default: yes, see {@link Net_LDAP2_Util::escape_filter_value()} for detailed information)
    *
    * @return Net_LDAP2_Filter|Net_LDAP2_Error
    */
    public static function create($attr_name, $match, $value = '', $escape = true)
    {
        $leaf_filter = new Net_LDAP2_Filter();
        if ($escape) {
            $array = Net_LDAP2_Util::escape_filter_value(array($value));
            $value = $array[0];
        }

        $match = strtolower($match);

        // detect negation
        $neg_matches   = array();
        $negate_filter = false;
        if (preg_match('/^(?:not|!)[\s_-](.+)/', $match, $neg_matches)) {
            $negate_filter = true;
            $match         = $neg_matches[1];
        }

        // build basic filter
        switch ($match) {
        case 'equals':
        case '=':
        case '==':
            $leaf_filter->_filter = '(' . $attr_name . '=' . $value . ')';
            break;
        case 'begins':
            $leaf_filter->_filter = '(' . $attr_name . '=' . $value . '*)';
            break;
        case 'ends':
            $leaf_filter->_filter = '(' . $attr_name . '=*' . $value . ')';
            break;
        case 'contains':
            $leaf_filter->_filter = '(' . $attr_name . '=*' . $value . '*)';
            break;
        case 'greater':
        case '>':
            $leaf_filter->_filter = '(' . $attr_name . '>' . $value . ')';
            break;
        case 'less':
        case '<':
            $leaf_filter->_filter = '(' . $attr_name . '<' . $value . ')';
            break;
        case 'greaterorequal':
        case '>=':
            $leaf_filter->_filter = '(' . $attr_name . '>=' . $value . ')';
            break;
        case 'lessorequal':
        case '<=':
            $leaf_filter->_filter = '(' . $attr_name . '<=' . $value . ')';
            break;
        case 'approx':
        case '~=':
            $leaf_filter->_filter = '(' . $attr_name . '~=' . $value . ')';
            break;
        case 'any':
        case 'present': // alias that may improve user code readability
            $leaf_filter->_filter = '(' . $attr_name . '=*)';
            break;
        default:
            return PEAR::raiseError('Net_LDAP2_Filter create error: matching rule "' . $match . '" not known!');
        }

        // negate if requested
        if ($negate_filter) {
           $leaf_filter = Net_LDAP2_Filter::combine('!', $leaf_filter);
        }

        return $leaf_filter;
    }

    /**
    * Combine two or more filter objects using a logical operator
    *
    * This static method combines two or more filter objects and returns one single
    * filter object that contains all the others.
    * Call this method statically: $filter = Net_LDAP2_Filter::combine('or', array($filter1, $filter2))
    * If the array contains filter strings instead of filter objects, we will try to parse them.
    *
    * @param string                 $log_op  The locical operator. May be "and", "or", "not" or the subsequent logical equivalents "&", "|", "!"
    * @param array|Net_LDAP2_Filter $filters array with Net_LDAP2_Filter objects
    *
    * @return Net_LDAP2_Filter|Net_LDAP2_Error
    * @static
    */
    public static function &combine($log_op, $filters)
    {
        if (PEAR::isError($filters)) {
            return $filters;
        }

        // substitude named operators to logical operators
        if ($log_op == 'and') $log_op = '&';
        if ($log_op == 'or')  $log_op = '|';
        if ($log_op == 'not') $log_op = '!';

        // tests for sane operation
        if ($log_op == '!') {
            // Not-combination, here we only accept one filter object or filter string
            if ($filters instanceof Net_LDAP2_Filter) {
                $filters = array($filters); // force array
            } elseif (is_string($filters)) {
                $filter_o = self::parse($filters);
                if (PEAR::isError($filter_o)) {
                    $err = PEAR::raiseError('Net_LDAP2_Filter combine error: '.$filter_o->getMessage());
                    return $err;
                } else {
                    $filters = array($filter_o);
                }
            } elseif (is_array($filters)) {
                if (count($filters) != 1) {
                    $err = PEAR::raiseError('Net_LDAP2_Filter combine error: operator is "not" but $filter is an array!');
                    return $err;
                } elseif (!($filters[0] instanceof Net_LDAP2_Filter)) {
                     $err = PEAR::raiseError('Net_LDAP2_Filter combine error: operator is "not" but $filter is not a valid Net_LDAP2_Filter nor a filter string!');
                     return $err;
                }
            } else {
                $err = PEAR::raiseError('Net_LDAP2_Filter combine error: operator is "not" but $filter is not a valid Net_LDAP2_Filter nor a filter string!');
                return $err;
            }
        } elseif ($log_op == '&' || $log_op == '|') {
            if (!is_array($filters) || count($filters) < 2) {
                $err = PEAR::raiseError('Net_LDAP2_Filter combine error: parameter $filters is not an array or contains less than two Net_LDAP2_Filter objects!');
                return $err;
            }
        } else {
            $err = PEAR::raiseError('Net_LDAP2_Filter combine error: logical operator is not known!');
            return $err;
        }

        $combined_filter = new Net_LDAP2_Filter();
        foreach ($filters as $key => $testfilter) {     // check for errors
            if (PEAR::isError($testfilter)) {
                return $testfilter;
            } elseif (is_string($testfilter)) {
                // string found, try to parse into an filter object
                $filter_o = self::parse($testfilter);
                if (PEAR::isError($filter_o)) {
                    return $filter_o;
                } else {
                    $filters[$key] = $filter_o;
                }
            } elseif (!$testfilter instanceof Net_LDAP2_Filter) {
                $err = PEAR::raiseError('Net_LDAP2_Filter combine error: invalid object passed in array $filters!');
                return $err;
            }
        }

        $combined_filter->_subfilters = $filters;
        $combined_filter->_match      = $log_op;
        return $combined_filter;
    }

    /**
    * Parse FILTER into a Net_LDAP2_Filter object
    *
    * This parses an filter string into Net_LDAP2_Filter objects.
    *
    * @param string $FILTER The filter string
    *
    * @access static
    * @return Net_LDAP2_Filter|Net_LDAP2_Error
    * @todo Leaf-mode: Do we need to escape at all? what about *-chars?check for the need of encoding values, tackle problems (see code comments)
    */
    public static function parse($FILTER)
    {
        if (preg_match('/^\((.+?)\)$/', $FILTER, $matches)) {
            // Check for right bracket syntax: count of unescaped opening
            // brackets must match count of unescaped closing brackets.
            // At this stage we may have:
            //   1. one filter component with already removed outer brackets
            //   2. one or more subfilter components
            $c_openbracks  = preg_match_all('/(?<!\\\\)\(/' , $matches[1], $notrelevant);
            $c_closebracks = preg_match_all('/(?<!\\\\)\)/' , $matches[1], $notrelevant);
            if ($c_openbracks != $c_closebracks) {
                return PEAR::raiseError("Filter parsing error: invalid filter syntax - opening brackets do not match close brackets!");
            }

            if (in_array(substr($matches[1], 0, 1), array('!', '|', '&'))) {
                // Subfilter processing: pass subfilters to parse() and combine
                // the objects using the logical operator detected
                // we have now something like "&(...)(...)(...)" but at least one part ("!(...)").
                // Each subfilter could be an arbitary complex subfilter.

                // extract logical operator and filter arguments
                $log_op              = substr($matches[1], 0, 1);
                $remaining_component = substr($matches[1], 1);

                // split $remaining_component into individual subfilters
                // we cannot use split() for this, because we do not know the
                // complexiness of the subfilter. Thus, we look trough the filter
                // string and just recognize ending filters at the first level.
                // We record the index number of the char and use that information
                // later to split the string.
                $sub_index_pos = array();
                $prev_char     = ''; // previous character looked at
                $level         = 0;  // denotes the current bracket level we are,
                                     //   >1 is too deep, 1 is ok, 0 is outside any
                                     //   subcomponent
                for ($curpos = 0; $curpos < strlen($remaining_component); $curpos++) {
                    $cur_char = substr($remaining_component, $curpos, 1);

                    // rise/lower bracket level
                    if ($cur_char == '(' && $prev_char != '\\') {
                        $level++;
                    } elseif  ($cur_char == ')' && $prev_char != '\\') {
                        $level--;
                    }

                    if ($cur_char == '(' && $prev_char == ')' && $level == 1) {
                        array_push($sub_index_pos, $curpos); // mark the position for splitting
                    }
                    $prev_char = $cur_char;
                }

                // now perform the splits. To get also the last part, we
                // need to add the "END" index to the split array
                array_push($sub_index_pos, strlen($remaining_component));
                $subfilters = array();
                $oldpos = 0;
                foreach ($sub_index_pos as $s_pos) {
                    $str_part = substr($remaining_component, $oldpos, $s_pos - $oldpos);
                    array_push($subfilters, $str_part);
                    $oldpos = $s_pos;
                }

                // some error checking...
                if (count($subfilters) == 1) {
                    // only one subfilter found
                } elseif (count($subfilters) > 1) {
                    // several subfilters found
                    if ($log_op == "!") {
                        return PEAR::raiseError("Filter parsing error: invalid filter syntax - NOT operator detected but several arguments given!");
                    }
                } else {
                    // this should not happen unless the user specified a wrong filter
                    return PEAR::raiseError("Filter parsing error: invalid filter syntax - got operator '$log_op' but no argument!");
                }

                // Now parse the subfilters into objects and combine them using the operator
                $subfilters_o = array();
                foreach ($subfilters as $s_s) {
                    $o = self::parse($s_s);
                    if (PEAR::isError($o)) {
                        return $o;
                    } else {
                        array_push($subfilters_o, self::parse($s_s));
                    }
                }

                $filter_o = self::combine($log_op, $subfilters_o);
                return $filter_o;

            } else {
                // This is one leaf filter component, do some syntax checks, then escape and build filter_o
                // $matches[1] should be now something like "foo=bar"

                // detect multiple leaf components
                // [TODO] Maybe this will make problems with filters containing brackets inside the value
                if (stristr($matches[1], ')(')) {
                    return PEAR::raiseError("Filter parsing error: invalid filter syntax - multiple leaf components detected!");
                } else {
                    $filter_parts = Net_LDAP2_Util::split_attribute_string($matches[1], true, true);
                    if (count($filter_parts) != 3) {
                        return PEAR::raiseError("Filter parsing error: invalid filter syntax - unknown matching rule used");
                    } else {
                        $filter_o          = new Net_LDAP2_Filter();
                        // [TODO]: Do we need to escape at all? what about *-chars user provide and that should remain special?
                        //         I think, those prevent escaping! We need to check against PERL Net::LDAP!
                        // $value_arr         = Net_LDAP2_Util::escape_filter_value(array($filter_parts[2]));
                        // $value             = $value_arr[0];
                        $value             = $filter_parts[2];
                        $filter_o->_filter = '('.$filter_parts[0].$filter_parts[1].$value.')';
                        return $filter_o;
                    }
                }
            }
        } else {
               // ERROR: Filter components must be enclosed in round brackets
               return PEAR::raiseError("Filter parsing error: invalid filter syntax - filter components must be enclosed in round brackets");
        }
    }

    /**
    * Get the string representation of this filter
    *
    * This method runs through all filter objects and creates
    * the string representation of the filter. If this
    * filter object is a leaf filter, then it will return
    * the string representation of this filter.
    *
    * @return string|Net_LDAP2_Error
    */
    public function asString()
    {
        if ($this->isLeaf()) {
            $return = $this->_filter;
        } else {
            $return = '';
            foreach ($this->_subfilters as $filter) {
                $return = $return.$filter->asString();
            }
            $return = '(' . $this->_match . $return . ')';
        }
        return $return;
    }

    /**
    * Alias for perl interface as_string()
    *
    * @see asString()
    * @return string|Net_LDAP2_Error
    */
    public function as_string()
    {
        return $this->asString();
    }

    /**
    * Print the text representation of the filter to FH, or the currently selected output handle if FH is not given
    *
    * This method is only for compatibility to the perl interface.
    * However, the original method was called "print" but due to PHP language restrictions,
    * we can't have a print() method.
    *
    * @param resource $FH (optional) A filehandle resource
    *
    * @return true|Net_LDAP2_Error
    */
    public function printMe($FH = false)
    {
        if (!is_resource($FH)) {
            if (PEAR::isError($FH)) {
                return $FH;
            }
            $filter_str = $this->asString();
            if (PEAR::isError($filter_str)) {
                return $filter_str;
            } else {
                print($filter_str);
            }
        } else {
            $filter_str = $this->asString();
            if (PEAR::isError($filter_str)) {
                return $filter_str;
            } else {
                $res = @fwrite($FH, $this->asString());
                if ($res == false) {
                    return PEAR::raiseError("Unable to write filter string to filehandle \$FH!");
                }
            }
        }
        return true;
    }

    /**
    * This can be used to escape a string to provide a valid LDAP-Filter.
    *
    * LDAP will only recognise certain characters as the
    * character istself if they are properly escaped. This is
    * what this method does.
    * The method can be called statically, so you can use it outside
    * for your own purposes (eg for escaping only parts of strings)
    *
    * In fact, this is just a shorthand to {@link Net_LDAP2_Util::escape_filter_value()}.
    * For upward compatibiliy reasons you are strongly encouraged to use the escape
    * methods provided by the Net_LDAP2_Util class.
    *
    * @param string $value Any string who should be escaped
    *
    * @static
    * @return string         The string $string, but escaped
    * @deprecated  Do not use this method anymore, instead use Net_LDAP2_Util::escape_filter_value() directly
    */
    public static function escape($value)
    {
        $return = Net_LDAP2_Util::escape_filter_value(array($value));
        return $return[0];
    }

    /**
    * Is this a container or a leaf filter object?
    *
    * @access protected
    * @return boolean
    */
    protected function isLeaf()
    {
        if (count($this->_subfilters) > 0) {
            return false; // Container!
        } else {
            return true; // Leaf!
        }
    }

    /**
    * Filter entries using this filter or see if a filter matches
    *
    * @todo Currently slow and naive implementation with preg_match, could be optimized (esp. begins, ends filters etc)
    * @todo Currently only "="-based matches (equals, begins, ends, contains, any) implemented; Implement all the stuff!
    * @todo Implement expert code with schema checks in case $entry is connected to a directory
    * @param array|Net_LDAP2_Entry The entry (or array with entries) to check
    * @param array                 If given, the array will be appended with entries who matched the filter. Return value is true if any entry matched.
    * @return int|Net_LDAP2_Error Returns the number of matched entries or error
    */
    function matches(&$entries, &$results=array()) {
        $numOfMatches = 0;

        if (!is_array($entries)) {
            $all_entries = array(&$entries);
        } else {
            $all_entries = &$entries;
        }

        foreach ($all_entries as $entry) {
            // look at the current entry and see if filter matches

            $entry_matched = false;
            // if this is not a single component, do calculate all subfilters,
            // then assert the partial results with the given combination modifier
            if (!$this->isLeaf()) {

                // get partial results from subfilters
                $partial_results = array();
                foreach ($this->_subfilters as $filter) {
                    $partial_results[] = $filter->matches($entry);
                }

                // evaluate partial results using this filters combination rule
                switch ($this->_match) {
                    case '!':
                        // result is the neagtive result of the assertion
                        $entry_matched = !$partial_results[0];
                    break;

                    case '&':
                        // all partial results have to be boolean-true
                        $entry_matched = !in_array(false, $partial_results);
                    break;

                    case '|':
                        // at least one partial result has to be true
                        $entry_matched = in_array(true, $partial_results);
                    break;
                }

            } else {
                // Leaf filter: assert given entry
                // [TODO]: Could be optimized to avoid preg_match especially with "ends", "begins" etc

                // Translate the LDAP-match to some preg_match expression and evaluate it
                list($attribute, $match, $assertValue) = $this->getComponents();
                switch ($match) {
                    case '=':
                        $regexp = '/^'.str_replace('*', '.*', $assertValue).'$/i'; // not case sensitive unless specified by schema
                        $entry_matched = $entry->pregMatch($regexp, $attribute);
                    break;

                    // -------------------------------------
                    // [TODO]: implement <, >, <=, >= and =~
                    // -------------------------------------

                    default:
                        $err = PEAR::raiseError("Net_LDAP2_Filter match error: unsupported match rule '$match'!");
                        return $err;
                }

            }

            // process filter matching result
            if ($entry_matched) {
                $numOfMatches++;
                $results[] = $entry;
            }

        }

        return $numOfMatches;
    }

    /**
    * Retrieve this leaf-filters attribute, match and value component.
    *
    * For leaf filters, this returns array(attr, match, value).
    * Match is be the logical operator, not the text representation,
    * eg "=" instead of "equals". Note that some operators are really
    * a combination of operator+value with wildcard, like
    * "begins": That will return "=" with the value "value*"!
    *
    * For non-leaf filters this will drop an error.
    *
    * @todo $this->_match is not always available and thus not usable here; it would be great if it would set in the factory methods and constructor.
    * @return array|Net_LDAP2_Error
    */
    function getComponents() {
        if ($this->isLeaf()) {
            $raw_filter = preg_replace('/^\(|\)$/', '', $this->_filter);
            $parts = Net_LDAP2_Util::split_attribute_string($raw_filter, true, true);
            if (count($parts) != 3) {
                return PEAR::raiseError("Net_LDAP2_Filter getComponents() error: invalid filter syntax - unknown matching rule used");
            } else {
                return $parts;
            }
        } else {
            return PEAR::raiseError('Net_LDAP2_Filter getComponents() call is invalid for non-leaf filters!');
        }
    }

}
?>


code:
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4: */
/**
* File containing the Net_LDAP2_LDIF interface class.
*
* PHP version 5
*
* @category  Net
* @package   Net_LDAP2
* @author    Benedikt Hallinger <beni@php.net>
* @copyright 2009 Benedikt Hallinger
* @license   http://www.gnu.org/licenses/lgpl-3.0.txt LGPLv3
* @version   SVN: $Id$
* @link      http://pear.php.net/package/Net_LDAP2/
*/

/**
* Includes
*/
require_once 'PEAR.php';
require_once 'Net/LDAP2.php';
require_once 'Net/LDAP2/Entry.php';
require_once 'Net/LDAP2/Util.php';

/**
* LDIF capabilitys for Net_LDAP2, closely taken from PERLs Net::LDAP
*
* It provides a means to convert between Net_LDAP2_Entry objects and LDAP entries
* represented in LDIF format files. Reading and writing are supported and may
* manipulate single entries or lists of entries.
*
* Usage example:
*
* // Read and parse an ldif-file into Net_LDAP2_Entry objects
* // and print out the DNs. Store the entries for later use.
* require 'Net/LDAP2/LDIF.php';
* $options = array(
*       'onerror' => 'die'
* );
* $entries = array();
* $ldif = new Net_LDAP2_LDIF('test.ldif', 'r', $options);
* do {
*       $entry = $ldif->read_entry();
*       $dn    = $entry->dn();
*       echo " done building entry: $dn\n";
*       array_push($entries, $entry);
* } while (!$ldif->eof());
* $ldif->done();
*
*
* // write those entries to another file
* $ldif = new Net_LDAP2_LDIF('test.out.ldif', 'w', $options);
* $ldif->write_entry($entries);
* $ldif->done();
*
*
* @category Net
* @package  Net_LDAP2
* @author   Benedikt Hallinger <beni@php.net>
* @license  http://www.gnu.org/copyleft/lesser.html LGPL
* @link     http://pear.php.net/package/Net_LDAP22/
* @see      http://www.ietf.org/rfc/rfc2849.txt
* @todo     Error handling should be PEARified
* @todo     LDAPv3 controls are not implemented yet
*/
class Net_LDAP2_LDIF extends PEAR
{
    /**
    * Options
    *
    * @access protected
    * @var array
    */
    protected $_options = array('encode'    => 'base64',
                                'onerror'   => null,
                                'change'    => 0,
                                'lowercase' => 0,
                                'sort'      => 0,
                                'version'   => null,
                                'wrap'      => 78,
                                'raw'       => ''
                               );

    /**
    * Errorcache
    *
    * @access protected
    * @var array
    */
    protected $_error = array('error' => null,
                              'line'  => 0
                             );

    /**
    * Filehandle for read/write
    *
    * @access protected
    * @var array
    */
    protected $_FH = null;

    /**
    * Says, if we opened the filehandle ourselves
    *
    * @access protected
    * @var array
    */
    protected $_FH_opened = false;

    /**
    * Linecounter for input file handle
    *
    * @access protected
    * @var array
    */
    protected $_input_line = 0;

    /**
    * counter for processed entries
    *
    * @access protected
    * @var int
    */
    protected $_entrynum = 0;

    /**
    * Mode we are working in
    *
    * Either 'r', 'a' or 'w'
    *
    * @access protected
    * @var string
    */
    protected $_mode = false;

    /**
    * Tells, if the LDIF version string was already written
    *
    * @access protected
    * @var boolean
    */
    protected $_version_written = false;

    /**
    * Cache for lines that have build the current entry
    *
    * @access protected
    * @var boolean
    */
    protected $_lines_cur = array();

    /**
    * Cache for lines that will build the next entry
    *
    * @access protected
    * @var boolean
    */
    protected $_lines_next = array();

    /**
    * Open LDIF file for reading or for writing
    *
    * new (FILE):
    * Open the file read-only. FILE may be the name of a file
    * or an already open filehandle.
    * If the file doesn't exist, it will be created if in write mode.
    *
    * new (FILE, MODE, OPTIONS):
    *     Open the file with the given MODE (see PHPs fopen()), eg "w" or "a".
    *     FILE may be the name of a file or an already open filehandle.
    *     PERLs Net_LDAP2 "FILE|" mode does not work curently.
    *
    *     OPTIONS is an associative array and may contain:
    *       encode => 'none' | 'canonical' | 'base64'
    *         Some DN values in LDIF cannot be written verbatim and have to be encoded in some way:
    *         'none'       No encoding.
    *         'canonical'  See "canonical_dn()" in Net::LDAP::Util.
    *         'base64'     Use base64. (default, this differs from the Perl interface.
    *                                   The perl default is "none"!)
    *
    *       onerror => 'die' | 'warn' | NULL
    *         Specify what happens when an error is detected.
    *         'die'  Net_LDAP2_LDIF will croak with an appropriate message.
    *         'warn' Net_LDAP2_LDIF will warn (echo) with an appropriate message.
    *         NULL   Net_LDAP2_LDIF will not warn (default), use error().
    *
    *       change => 1
    *         Write entry changes to the LDIF file instead of the entries itself. I.e. write LDAP
    *         operations acting on the entries to the file instead of the entries contents.
    *         This writes the changes usually carried out by an update() to the LDIF file.
    *
    *       lowercase => 1
    *         Convert attribute names to lowercase when writing.
    *
    *       sort => 1
    *         Sort attribute names when writing entries according to the rule:
    *         objectclass first then all other attributes alphabetically sorted by attribute name
    *
    *       version => '1'
    *         Set the LDIF version to write to the resulting LDIF file.
    *         According to RFC 2849 currently the only legal value for this option is 1.
    *         When this option is set Net_LDAP2_LDIF tries to adhere more strictly to
    *         the LDIF specification in RFC2489 in a few places.
    *         The default is NULL meaning no version information is written to the LDIF file.
    *
    *       wrap => 78
    *         Number of columns where output line wrapping shall occur.
    *         Default is 78. Setting it to 40 or lower inhibits wrapping.
    *
    *       raw => REGEX
    *         Use REGEX to denote the names of attributes that are to be
    *         considered binary in search results if writing entries.
    *         Example: raw => "/(?i:^jpegPhoto|;binary)/i"
    *
    * @param string|ressource $file    Filename or filehandle
    * @param string           $mode    Mode to open filename
    * @param array            $options Options like described above
    */
    public function __construct($file, $mode = 'r', $options = array())
    {
        parent::__construct('Net_LDAP2_Error'); // default error class

        // First, parse options
        // todo: maybe implement further checks on possible values
        foreach ($options as $option => $value) {
            if (!array_key_exists($option, $this->_options)) {
                $this->dropError('Net_LDAP2_LDIF error: option '.$option.' not known!');
                return;
            } else {
                $this->_options[$option] = strtolower($value);
            }
        }

        // setup LDIF class
        $this->version($this->_options['version']);

        // setup file mode
        if (!preg_match('/^[rwa]\+?$/', $mode)) {
            $this->dropError('Net_LDAP2_LDIF error: file mode '.$mode.' not supported!');
        } else {
            $this->_mode = $mode;

            // setup filehandle
            if (is_resource($file)) {
                // TODO: checks on mode possible?
                $this->_FH =& $file;
            } else {
                $imode = substr($this->_mode, 0, 1);
                if ($imode == 'r') {
                    if (!file_exists($file)) {
                        $this->dropError('Unable to open '.$file.' for read: file not found');
                        $this->_mode = false;
                    }
                    if (!is_readable($file)) {
                        $this->dropError('Unable to open '.$file.' for read: permission denied');
                        $this->_mode = false;
                    }
                }

                if (($imode == 'w' || $imode == 'a')) {
                    if (file_exists($file)) {
                        if (!is_writable($file)) {
                            $this->dropError('Unable to open '.$file.' for write: permission denied');
                            $this->_mode = false;
                        }
                    } else {
                        if (!@touch($file)) {
                            $this->dropError('Unable to create '.$file.' for write: permission denied');
                            $this->_mode = false;
                        }
                    }
                }

                if ($this->_mode) {
                    $this->_FH = @fopen($file, $this->_mode);
                    if (false === $this->_FH) {
                        // Fallback; should never be reached if tests above are good enough!
                        $this->dropError('Net_LDAP2_LDIF error: Could not open file '.$file);
                    } else {
                        $this->_FH_opened = true;
                    }
                }
            }
        }
    }

    /**
    * Read one entry from the file and return it as a Net::LDAP::Entry object.
    *
    * @return Net_LDAP2_Entry
    */
    public function read_entry()
    {
        // read fresh lines, set them as current lines and create the entry
        $attrs = $this->next_lines(true);
        if (count($attrs) > 0) {
            $this->_lines_cur = $attrs;
        }
        return $this->current_entry();
    }

    /**
    * Returns true when the end of the file is reached.
    *
    * @return boolean
    */
    public function eof()
    {
        return feof($this->_FH);
    }

    /**
    * Write the entry or entries to the LDIF file.
    *
    * If you want to build an LDIF file containing several entries AND
    * you want to call write_entry() several times, you must open the filehandle
    * in append mode ("a"), otherwise you will always get the last entry only.
    *
    * @param Net_LDAP2_Entry|array $entries Entry or array of entries
    *
    * @return void
    * @todo implement operations on whole entries (adding a whole entry)
    */
    public function write_entry($entries)
    {
        if (!is_array($entries)) {
            $entries = array($entries);
        }

        foreach ($entries as $entry) {
            $this->_entrynum++;
            if (!$entry instanceof Net_LDAP2_Entry) {
                $this->dropError('Net_LDAP2_LDIF error: entry '.$this->_entrynum.' is not an Net_LDAP2_Entry object');
            } else {
                if ($this->_options['change']) {
                    // LDIF change mode
                    // fetch change information from entry
                    $entry_attrs_changes = $entry->getChanges();
                    $num_of_changes      = count($entry_attrs_changes['add'])
                                           + count($entry_attrs_changes['replace'])
                                           + count($entry_attrs_changes['delete']);

                    $is_changed = ($num_of_changes > 0 || $entry->willBeDeleted() || $entry->willBeMoved());

                    // write version if not done yet
                    // also write DN of entry
                    if ($is_changed) {
                        if (!$this->_version_written) {
                            $this->write_version();
                        }
                        $this->writeDN($entry->currentDN());
                    }

                    // process changes
                    // TODO: consider DN add!
                    if ($entry->willBeDeleted()) {
                        $this->writeLine("changetype: delete".PHP_EOL);
                    } elseif ($entry->willBeMoved()) {
                        $this->writeLine("changetype: modrdn".PHP_EOL);
                        $olddn     = Net_LDAP2_Util::ldap_explode_dn($entry->currentDN(), array('casefold' => 'none')); // maybe gives a bug if using multivalued RDNs
                        $oldrdn    = array_shift($olddn);
                        $oldparent = implode(',', $olddn);
                        $newdn     = Net_LDAP2_Util::ldap_explode_dn($entry->dn(), array('casefold' => 'none')); // maybe gives a bug if using multivalued RDNs
                        $rdn       = array_shift($newdn);
                        $parent    = implode(',', $newdn);
                        $this->writeLine("newrdn: ".$rdn.PHP_EOL);
                        $this->writeLine("deleteoldrdn: 1".PHP_EOL);
                        if ($parent !== $oldparent) {
                            $this->writeLine("newsuperior: ".$parent.PHP_EOL);
                        }
                        // TODO: What if the entry has attribute changes as well?
                        //       I think we should check for that and make a dummy
                        //       entry with the changes that is written to the LDIF file
                    } elseif ($num_of_changes > 0) {
                        // write attribute change data
                        $this->writeLine("changetype: modify".PHP_EOL);
                        foreach ($entry_attrs_changes as $changetype => $entry_attrs) {
                            foreach ($entry_attrs as $attr_name => $attr_values) {
                                $this->writeLine("$changetype: $attr_name".PHP_EOL);
                                if ($attr_values !== null) $this->writeAttribute($attr_name, $attr_values, $changetype);
                                $this->writeLine("-".PHP_EOL);
                            }
                        }
                    }

                    // finish this entrys data if we had changes
                    if ($is_changed) {
                        $this->finishEntry();
                    }
                } else {
                    // LDIF-content mode
                    // fetch attributes for further processing
                    $entry_attrs = $entry->getValues();

                    // sort and put objectclass-attrs to first position
                    if ($this->_options['sort']) {
                        ksort($entry_attrs);
                        if (array_key_exists('objectclass', $entry_attrs)) {
                            $oc = $entry_attrs['objectclass'];
                            unset($entry_attrs['objectclass']);
                            $entry_attrs = array_merge(array('objectclass' => $oc), $entry_attrs);
                        }
                    }

                    // write data
                    if (!$this->_version_written) {
                        $this->write_version();
                    }
                    $this->writeDN($entry->dn());
                    foreach ($entry_attrs as $attr_name => $attr_values) {
                        $this->writeAttribute($attr_name, $attr_values);
                    }
                    $this->finishEntry();
                }
            }
        }
    }

    /**
    * Write version to LDIF
    *
    * If the object's version is defined, this method allows to explicitely write the version before an entry is written.
    * If not called explicitely, it gets called automatically when writing the first entry.
    *
    * @return void
    */
    public function write_version()
    {
        $this->_version_written = true;
        if (!is_null($this->version())) {
            return $this->writeLine('version: '.$this->version().PHP_EOL, 'Net_LDAP2_LDIF error: unable to write version');
        }
    }

    /**
    * Get or set LDIF version
    *
    * If called without arguments it returns the version of the LDIF file or NULL if no version has been set.
    * If called with an argument it sets the LDIF version to VERSION.
    * According to RFC 2849 currently the only legal value for VERSION is 1.
    *
    * @param int $version (optional) LDIF version to set
    *
    * @return int
    */
    public function version($version = null)
    {
        if ($version !== null) {
            if ($version != 1) {
                $this->dropError('Net_LDAP2_LDIF error: illegal LDIF version set');
            } else {
                $this->_options['version'] = $version;
            }
        }
        return $this->_options['version'];
    }

    /**
    * Returns the file handle the Net_LDAP2_LDIF object reads from or writes to.
    *
    * You can, for example, use this to fetch the content of the LDIF file yourself
    *
    * @return null|resource
    */
    public function &handle()
    {
        if (!is_resource($this->_FH)) {
            $this->dropError('Net_LDAP2_LDIF error: invalid file resource');
            $null = null;
            return $null;
        } else {
            return $this->_FH;
        }
    }

    /**
    * Clean up
    *
    * This method signals that the LDIF object is no longer needed.
    * You can use this to free up some memory and close the file handle.
    * The file handle is only closed, if it was opened from Net_LDAP2_LDIF.
    *
    * @return void
    */
    public function done()
    {
        // close FH if we opened it
        if ($this->_FH_opened) {
            fclose($this->handle());
        }

        // free variables
        foreach (get_object_vars($this) as $name => $value) {
            unset($this->$name);
        }
    }

    /**
    * Returns last error message if error was found.
    *
    * Example:
    *
    *  $ldif->someAction();
    *  if ($ldif->error()) {
    *     echo "Error: ".$ldif->error()." at input line: ".$ldif->error_lines();
    *  }
    *
    *
    * @param boolean $as_string If set to true, only the message is returned
    *
    * @return false|Net_LDAP2_Error
    */
    public function error($as_string = false)
    {
        if (Net_LDAP2::isError($this->_error['error'])) {
            return ($as_string)? $this->_error['error']->getMessage() : $this->_error['error'];
        } else {
            return false;
        }
    }

    /**
    * Returns lines that resulted in error.
    *
    * Perl returns an array of faulty lines in list context,
    * but we always just return an int because of PHPs language.
    *
    * @return int
    */
    public function error_lines()
    {
        return $this->_error['line'];
    }

    /**
    * Returns the current Net::LDAP::Entry object.
    *
    * @return Net_LDAP2_Entry|false
    */
    public function current_entry()
    {
        return $this->parseLines($this->current_lines());
    }

    /**
    * Parse LDIF lines of one entry into an Net_LDAP2_Entry object
    *
    * @param array $lines LDIF lines for one entry
    *
    * @return Net_LDAP2_Entry|false Net_LDAP2_Entry object for those lines
    * @todo what about file inclusions and urls? "jpegphoto:< file:///usr/local/directory/photos/fiona.jpg"
    */
    public function parseLines($lines)
    {
        // parse lines into an array of attributes and build the entry
        $attributes = array();
        $dn = false;
        foreach ($lines as $line) {
            if (preg_match('/^(\w+(;binary)?)(:|::|:<)\s(.+)$/', $line, $matches)) {
                $attr  =& $matches[1] . $matches[2];
                $delim =& $matches[3];
                $data  =& $matches[4];

                if ($delim == ':') {
                    // normal data
                    $attributes[$attr][] = $data;
                } elseif ($delim == '::') {
                    // base64 data
                    $attributes[$attr][] = base64_decode($data);
                } elseif ($delim == ':<') {
                    // file inclusion
                    // TODO: Is this the job of the LDAP-client or the server?
                    $this->dropError('File inclusions are currently not supported');
                    //$attributes[$attr][] = ...;
                } else {
                    // since the pattern above, the delimeter cannot be something else.
                    $this->dropError('Net_LDAP2_LDIF parsing error: invalid syntax at parsing entry line: '.$line);
                    continue;
                }

                if (strtolower($attr) == 'dn') {
                    // DN line detected
                    $dn = $attributes[$attr][0];  // save possibly decoded DN
                    unset($attributes[$attr]);    // remove wrongly added "dn: " attribute
                }
            } else {
                // line not in "attr: value" format -> ignore
                // maybe we should rise an error here, but this should be covered by
                // next_lines() already. A problem arises, if users try to feed data of
                // several entries to this method - the resulting entry will
                // get wrong attributes. However, this is already mentioned in the
                // methods documentation above.
            }
        }

        if (false === $dn) {
            $this->dropError('Net_LDAP2_LDIF parsing error: unable to detect DN for entry');
            return false;
        } else {
            $newentry = Net_LDAP2_Entry::createFresh($dn, $attributes);
            return $newentry;
        }
    }

    /**
    * Returns the lines that generated the current Net::LDAP::Entry object.
    *
    * Note that this returns an empty array if no lines have been read so far.
    *
    * @return array Array of lines
    */
    public function current_lines()
    {
        return $this->_lines_cur;
    }

    /**
    * Returns the lines that will generate the next Net::LDAP::Entry object.
    *
    * If you set $force to TRUE then you can iterate over the lines that build
    * up entries manually. Otherwise, iterating is done using {@link read_entry()}.
    * Force will move the file pointer forward, thus returning the next entries lines.
    *
    * Wrapped lines will be unwrapped. Comments are stripped.
    *
    * @param boolean $force Set this to true if you want to iterate over the lines manually
    *
    * @return array
    */
    public function next_lines($force = false)
    {
        // if we already have those lines, just return them, otherwise read
        if (count($this->_lines_next) == 0 || $force) {
            $this->_lines_next = array(); // empty in case something was left (if used $force)
            $entry_done        = false;
            $fh                = &$this->handle();
            $commentmode       = false; // if we are in an comment, for wrapping purposes
            $datalines_read    = 0;     // how many lines with data we have read

            while (!$entry_done && !$this->eof()) {
                $this->_input_line++;
                // Read line. Remove line endings, we want only data;
                // this is okay since ending spaces should be encoded
                $data = rtrim(fgets($fh));
                if ($data === false) {
                    // error only, if EOF not reached after fgets() call
                    if (!$this->eof()) {
                        $this->dropError('Net_LDAP2_LDIF error: error reading from file at input line '.$this->_input_line, $this->_input_line);
                    }
                    break;
                } else {
                    if (count($this->_lines_next) > 0 && preg_match('/^$/', $data)) {
                        // Entry is finished if we have an empty line after we had data
                        $entry_done = true;

                        // Look ahead if the next EOF is nearby. Comments and empty
                        // lines at the file end may cause problems otherwise
                        $current_pos = ftell($fh);
                        $data        = fgets($fh);
                        while (!feof($fh)) {
                            if (preg_match('/^\s*$/', $data) || preg_match('/^#/', $data)) {
                                // only empty lines or comments, continue to seek
                                // TODO: Known bug: Wrappings for comments are okay but are treaten as
                                //       error, since we do not honor comment mode here.
                                //       This should be a very theoretically case, however
                                //       i am willing to fix this if really necessary.
                                $this->_input_line++;
                                $current_pos = ftell($fh);
                                $data        = fgets($fh);
                            } else {
                                // Data found if non emtpy line and not a comment!!
                                // Rewind to position prior last read and stop lookahead
                                fseek($fh, $current_pos);
                                break;
                            }
                        }
                        // now we have either the file pointer at the beginning of
                        // a new data position or at the end of file causing feof() to return true

                    } else {
                        // build lines
                        if (preg_match('/^version:\s(.+)$/', $data, $match)) {
                            // version statement, set version
                            $this->version($match[1]);
                        } elseif (preg_match('/^\w+(;binary)?::?\s.+$/', $data)) {
                            // normal attribute: add line
                            $commentmode         = false;
                            $this->_lines_next[] = trim($data);
                            $datalines_read++;
                        } elseif (preg_match('/^\s(.+)$/', $data, $matches)) {
                            // wrapped data: unwrap if not in comment mode
                            // note that the \s above is some more liberal than
                            // the RFC requests as it also matches tabs etc.
                            if (!$commentmode) {
                                if ($datalines_read == 0) {
                                    // first line of entry: wrapped data is illegal
                                    $this->dropError('Net_LDAP2_LDIF error: illegal wrapping at input line '.$this->_input_line, $this->_input_line);
                                } else {
                                    $last                = array_pop($this->_lines_next);
                                    $last                = $last.$matches[1];
                                    $this->_lines_next[] = $last;
                                    $datalines_read++;
                                }
                            }
                        } elseif (preg_match('/^#/', $data)) {
                            // LDIF comments
                            $commentmode = true;
                        } elseif (preg_match('/^\s*$/', $data)) {
                            // empty line but we had no data for this
                            // entry, so just ignore this line
                            $commentmode = false;
                        } else {
                            $this->dropError('Net_LDAP2_LDIF error: invalid syntax at input line '.$this->_input_line, $this->_input_line);
                            continue;
                        }

                    }
                }
            }
        }
        return $this->_lines_next;
    }

    /**
    * Convert an attribute and value to LDIF string representation
    *
    * It honors correct encoding of values according to RFC 2849.
    * Line wrapping will occur at the configured maximum but only if
    * the value is greater than 40 chars.
    *
    * @param string $attr_name  Name of the attribute
    * @param string $attr_value Value of the attribute
    *
    * @access protected
    * @return string LDIF string for that attribute and value
    */
    protected function convertAttribute($attr_name, $attr_value)
    {
        // Handle empty attribute or process
        if (strlen($attr_value) == 0) {
            $attr_value = " ";
        } else {
            $base64 = false;
            // ASCII-chars that are NOT safe for the
            // start and for being inside the value.
            // These are the int values of those chars.
            $unsafe_init = array(0, 10, 13, 32, 58, 60);
            $unsafe      = array(0, 10, 13);

            // Test for illegal init char
            $init_ord = ord(substr($attr_value, 0, 1));
            if ($init_ord > 127 || in_array($init_ord, $unsafe_init)) {
                $base64 = true;
            }

            // Test for illegal content char
            for ($i = 0; $i < strlen($attr_value); $i++) {
                $char_ord = ord(substr($attr_value, $i, 1));
                if ($char_ord > 127 || in_array($char_ord, $unsafe)) {
                    $base64 = true;
                }
            }

            // Test for ending space
            if (substr($attr_value, -1) == ' ') {
                $base64 = true;
            }

            // If converting is needed, do it
            // Either we have some special chars or a matching "raw" regex
            if ($base64 || ($this->_options['raw'] && preg_match($this->_options['raw'], $attr_name))) {
                $attr_name .= ':';
                $attr_value = base64_encode($attr_value);
            }

            // Lowercase attr names if requested
            if ($this->_options['lowercase']) $attr_name = strtolower($attr_name);

            // Handle line wrapping
            if ($this->_options['wrap'] > 40 && strlen($attr_value) > $this->_options['wrap']) {
                $attr_value = wordwrap($attr_value, $this->_options['wrap'], PHP_EOL." ", true);
            }
        }

        return $attr_name.': '.$attr_value;
    }

    /**
    * Convert an entries DN to LDIF string representation
    *
    * It honors correct encoding of values according to RFC 2849.
    *
    * @param string $dn UTF8-Encoded DN
    *
    * @access protected
    * @return string LDIF string for that DN
    * @todo I am not sure, if the UTF8 stuff is correctly handled right now
    */
    protected function convertDN($dn)
    {
        $base64 = false;
        // ASCII-chars that are NOT safe for the
        // start and for being inside the dn.
        // These are the int values of those chars.
        $unsafe_init = array(0, 10, 13, 32, 58, 60);
        $unsafe      = array(0, 10, 13);

        // Test for illegal init char
        $init_ord = ord(substr($dn, 0, 1));
        if ($init_ord >= 127 || in_array($init_ord, $unsafe_init)) {
            $base64 = true;
        }

        // Test for illegal content char
        for ($i = 0; $i < strlen($dn); $i++) {
            $char = substr($dn, $i, 1);
            if (ord($char) >= 127 || in_array($init_ord, $unsafe)) {
                $base64 = true;
            }
        }

        // Test for ending space
        if (substr($dn, -1) == ' ') {
            $base64 = true;
        }

        // if converting is needed, do it
        return ($base64)? 'dn:: '.base64_encode($dn) : 'dn: '.$dn;
    }

    /**
    * Writes an attribute to the filehandle
    *
    * @param string       $attr_name   Name of the attribute
    * @param string|array $attr_values Single attribute value or array with attribute values
    *
    * @access protected
    * @return void
    */
    protected function writeAttribute($attr_name, $attr_values)
    {
        // write out attribute content
        if (!is_array($attr_values)) {
            $attr_values = array($attr_values);
        }
        foreach ($attr_values as $attr_val) {
            $line = $this->convertAttribute($attr_name, $attr_val).PHP_EOL;
            $this->writeLine($line, 'Net_LDAP2_LDIF error: unable to write attribute '.$attr_name.' of entry '.$this->_entrynum);
        }
    }

    /**
    * Writes a DN to the filehandle
    *
    * @param string $dn DN to write
    *
    * @access protected
    * @return void
    */
    protected function writeDN($dn)
    {
        // prepare DN
        if ($this->_options['encode'] == 'base64') {
            $dn = $this->convertDN($dn).PHP_EOL;
        } elseif ($this->_options['encode'] == 'canonical') {
            $dn = Net_LDAP2_Util::canonical_dn($dn, array('casefold' => 'none')).PHP_EOL;
        } else {
            $dn = $dn.PHP_EOL;
        }
        $this->writeLine($dn, 'Net_LDAP2_LDIF error: unable to write DN of entry '.$this->_entrynum);
    }

    /**
    * Finishes an LDIF entry
    *
    * @access protected
    * @return void
    */
    protected function finishEntry()
    {
        $this->writeLine(PHP_EOL, 'Net_LDAP2_LDIF error: unable to close entry '.$this->_entrynum);
    }

    /**
    * Just write an arbitary line to the filehandle
    *
    * @param string $line  Content to write
    * @param string $error If error occurs, drop this message
    *
    * @access protected
    * @return true|false
    */
    protected function writeLine($line, $error = 'Net_LDAP2_LDIF error: unable to write to filehandle')
    {
        if (is_resource($this->handle()) && fwrite($this->handle(), $line, strlen($line)) === false) {
            $this->dropError($error);
            return false;
        } else {
            return true;
        }
    }

    /**
    * Optionally raises an error and pushes the error on the error cache
    *
    * @param string $msg  Errortext
    * @param int    $line Line in the LDIF that caused the error
    *
    * @access protected
    * @return void
    */
    protected function dropError($msg, $line = null)
    {
        $this->_error['error'] = new Net_LDAP2_Error($msg);
        if ($line !== null) $this->_error['line'] = $line;

        if ($this->_options['onerror'] == 'die') {
            die($msg.PHP_EOL);
        } elseif ($this->_options['onerror'] == 'warn') {
            echo $msg.PHP_EOL;
        }
    }
}
?>