Exemplo n.º 1
1
 /**
  * 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;
         $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, true)) {
             return PEAR::raiseError("Entry not renamed: " . @ldap_error($link), @ldap_errno($link));
         }
         // reflect changes to local copy
         $this->_dn = $this->_newdn;
         $this->_newdn = null;
     }
     /*
      * Carry out modifications to the entry
      */
     // ADD
     foreach ($this->_changes["add"] as $attr => $value) {
         // if attribute exists, add new values
         if ($this->exists($attr)) {
             if (false === @ldap_mod_add($link, $this->dn(), array($attr => $value))) {
                 return PEAR::raiseError("Could not add new values to attribute {$attr}: " . @ldap_error($link), @ldap_errno($link));
             }
         } else {
             // new attribute
             if (false === @ldap_modify($link, $this->dn(), array($attr => $value))) {
                 return PEAR::raiseError("Could not add new attribute {$attr}: " . @ldap_error($link), @ldap_errno($link));
             }
         }
         // all went well here, I guess
         unset($this->_changes["add"][$attr]);
     }
     // 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 = $this->_original[$attr];
         }
         if (false === @ldap_mod_del($link, $this->dn(), array($attr => $value))) {
             return PEAR::raiseError("Could not delete attribute {$attr}: " . @ldap_error($link), @ldap_errno($link));
         }
         unset($this->_changes["delete"][$attr]);
     }
     // REPLACE
     foreach ($this->_changes["replace"] as $attr => $value) {
         if (false === @ldap_modify($link, $this->dn(), array($attr => $value))) {
             return PEAR::raiseError("Could not replace attribute {$attr} values: " . @ldap_error($link), @ldap_errno($link));
         }
         unset($this->_changes["replace"][$attr]);
     }
     // all went well, so _original (server) becomes _attributes (local copy)
     $this->_original = $this->_attributes;
     $return = true;
     return $return;
 }
Exemplo n.º 2
0
 public function UserMod($username, $attributes = array())
 {
     // Clone the attributes array
     $attr = array_merge($attributes, array());
     $Usr = $this->UserGet($username);
     if ($Usr) {
         $OldCn = $Usr['cn'];
         $NewCn = $attr['cn'];
         if ($NewCn == $OldCn) {
             // Same CN, no need to pass it as an argument
             unset($attr['cn']);
         } else {
             // Rename user
             ldap_rename($this->conn, 'CN=' . $OldCn . ',CN=Users,' . $this->BaseDn, 'CN=' . $NewCn, null, true);
             unset($attr['cn']);
         }
         return ldap_modify($this->conn, $this->GetUserDnByCn($NewCn), $attr);
     } else {
         return;
     }
 }
function moveuser()
{
    $u = new user($_POST["userid"]);
    $dn = $u->dn;
    $gplist = $u->Groups_list();
    if (preg_match("#^(.+?),#", $dn, $re)) {
        $newRdn = $re[1];
    } else {
        $newRdn = "cn={$_POST["userid"]}";
    }
    $ldap = new clladp();
    $newParent = "ou=users,ou={$_POST["nextou"]},dc=organizations,{$ldap->suffix}";
    if (!ldap_rename($ldap->ldap_connection, $dn, $newRdn, $newParent, true)) {
        echo 'Error number ' . ldap_errno($ldap->ldap_connection) . "\nAction:LDAP Ldap_rename\ndn:{$dn} -> {$newRdn},{$newParent}\n" . ldap_err2str(ldap_errno($ldap->ldap_connection));
        return;
    }
    while (list($gid, $name) = each($gplist)) {
        $gp = new groups($gid);
        $gp->DeleteUserFromThisGroup($_POST["userid"]);
    }
}
Exemplo n.º 4
0
 /**
  * Updates the entry on the directory server.
  *
  * This will evaluate all changes made so far and send them to the
  * directory server.
  *
  * 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.
  *
  * @todo Entry rename with a DN containing special characters needs testing!
  *
  * @throws Horde_Ldap_Exception
  */
 public function update()
 {
     /* Ensure we have a valid LDAP object. */
     $ldap = $this->getLDAP();
     /* Get and check link. */
     $link = $ldap->getLink();
     if (!is_resource($link)) {
         throw new Horde_Ldap_Exception('Could not update entry: internal LDAP link is invalid');
     }
     /* Delete the entry. */
     if ($this->_delete) {
         return $ldap->delete($this);
     }
     /* New entry. */
     if ($this->_new) {
         $ldap->add($this);
         $this->_new = false;
         $this->_changes['add'] = array();
         $this->_changes['delete'] = array();
         $this->_changes['replace'] = array();
         $this->_original = $this->_attributes;
         return;
     }
     /* Rename/move entry. */
     if (!is_null($this->_newdn)) {
         if ($ldap->getVersion() != 3) {
             throw new Horde_Ldap_Exception('Renaming/Moving an entry is only supported in LDAPv3');
         }
         /* Make DN relative to parent (needed for LDAP rename). */
         $parent = Horde_Ldap_Util::explodeDN($this->_newdn, array('casefolding' => 'none', 'reverse' => false, 'onlyvalues' => false));
         $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 = Horde_Ldap_Util::canonicalDN($child);
         }
         $parent = Horde_Ldap_Util::canonicalDN($parent);
         /* Rename/move. */
         if (!@ldap_rename($link, $this->_dn, $child, $parent, true)) {
             throw new Horde_Ldap_Exception('Entry not renamed: ' . @ldap_error($link), @ldap_errno($link));
         }
         /* Reflect changes to local copy. */
         $this->_dn = $this->_newdn;
         $this->_newdn = null;
     }
     /* Carry out modifications to the entry. */
     foreach ($this->_changes['add'] as $attr => $value) {
         /* If attribute exists, add new values. */
         if ($this->exists($attr)) {
             if (!@ldap_mod_add($link, $this->dn(), array($attr => $value))) {
                 throw new Horde_Ldap_Exception('Could not add new values to attribute ' . $attr . ': ' . @ldap_error($link), @ldap_errno($link));
             }
         } else {
             /* New attribute. */
             if (!@ldap_modify($link, $this->dn(), array($attr => $value))) {
                 throw new Horde_Ldap_Exception('Could not add new attribute ' . $attr . ': ' . @ldap_error($link), @ldap_errno($link));
             }
         }
         unset($this->_changes['add'][$attr]);
     }
     foreach ($this->_changes['delete'] as $attr => $value) {
         /* In LDAPv3 you need to specify the old values for deleting. */
         if (is_null($value) && $ldap->getVersion() == 3) {
             $value = $this->_original[$attr];
         }
         if (!@ldap_mod_del($link, $this->dn(), array($attr => $value))) {
             throw new Horde_Ldap_Exception('Could not delete attribute ' . $attr . ': ' . @ldap_error($link), @ldap_errno($link));
         }
         unset($this->_changes['delete'][$attr]);
     }
     foreach ($this->_changes['replace'] as $attr => $value) {
         if (!@ldap_modify($link, $this->dn(), array($attr => $value))) {
             throw new Horde_Ldap_Exception('Could not replace attribute ' . $attr . ' values: ' . @ldap_error($link), @ldap_errno($link));
         }
         unset($this->_changes['replace'][$attr]);
     }
     /* All went well, so $_attributes (local copy) becomes $_original
      * (server). */
     $this->_original = $this->_attributes;
 }
Exemplo n.º 5
0
 /**
  * Sync a group's info to LDAP
  *
  * @param   mixed   $group
  * @return  boolean
  */
 public static function syncGroup($group)
 {
     $db = \App::get('db');
     if (empty($db)) {
         self::$errors['fatal'][] = 'Error connecting to the database';
         return false;
     }
     $conn = self::getLDO();
     if (empty($conn)) {
         self::$errors['fatal'][] = 'LDAP connection failed';
         return false;
     }
     $query = "SELECT g.gidNumber, g.cn, g.description FROM #__xgroups AS g ";
     if (is_numeric($group) && $group >= 0) {
         $query .= " WHERE g.gidNumber = " . $db->quote($group) . " LIMIT 1;";
     } else {
         $query .= " WHERE g.cn = " . $db->quote($group) . " LIMIT 1;";
     }
     $db->setQuery($query);
     $dbinfo = $db->loadAssoc();
     if (!empty($dbinfo)) {
         $query = "SELECT DISTINCT(u.username) AS memberUid FROM #__xgroups_members AS gm, #__users AS u WHERE gm.gidNumber = " . $db->quote($dbinfo['gidNumber']) . " AND gm.uidNumber=u.id;";
         $db->setQuery($query);
         $dbinfo['memberUid'] = $db->loadColumn();
     }
     $ldap_params = \Component::params('com_system');
     $hubLDAPBaseDN = $ldap_params->get('ldap_basedn', '');
     if (isset($dbinfo['gidNumber']) || is_numeric($group) && $group >= 0) {
         $dn = 'ou=groups,' . $hubLDAPBaseDN;
         $filter = '(gidNumber=' . (isset($dbinfo['gidNumber']) ? $dbinfo['gidNumber'] : $group) . ')';
     } else {
         $dn = "cn=" . $group . ",ou=groups," . $hubLDAPBaseDN;
         $filter = '(objectclass=*)';
     }
     $reqattr = array('gidNumber', 'cn', 'description', 'memberUid');
     $entry = ldap_search($conn, $dn, $filter, $reqattr, 0, 1, 0);
     $count = $entry ? ldap_count_entries($conn, $entry) : 0;
     // If there was a database entry, but there was no ldap entry, create the ldap entry
     if (!empty($dbinfo) && $count <= 0) {
         $dn = "cn=" . $dbinfo['cn'] . ",ou=groups," . $hubLDAPBaseDN;
         $entry = array();
         $entry['objectclass'][] = 'top';
         $entry['objectclass'][] = 'posixGroup';
         foreach ($dbinfo as $key => $value) {
             if (is_array($value) && $value != array()) {
                 $entry[$key] = $value;
             } else {
                 if (!is_array($value) && $value != '') {
                     $entry[$key] = $value;
                 }
             }
         }
         $result = ldap_add($conn, $dn, $entry);
         if ($result !== true) {
             $result = ldap_add($conn, $dn, $entry);
             self::$errors['warning'][] = ldap_error($conn);
             return false;
         } else {
             ++self::$success['added'];
             return true;
         }
     }
     $ldapinfo = null;
     $count = $entry ? ldap_count_entries($conn, $entry) : 0;
     if ($count > 0) {
         $firstentry = ldap_first_entry($conn, $entry);
         $attr = ldap_get_attributes($conn, $firstentry);
         if (!empty($attr) && $attr['count'] > 0) {
             foreach ($reqattr as $key) {
                 unset($attr[$key]['count']);
                 if (isset($attr[$key][0])) {
                     if (count($attr[$key]) <= 1) {
                         $ldapinfo[$key] = $attr[$key][0];
                     } else {
                         $ldapinfo[$key] = $attr[$key];
                     }
                 } else {
                     $ldapinfo[$key] = null;
                 }
             }
         }
     }
     // If there was no database entry, and there was no ldap entry, nothing to do
     if (empty($dbinfo) && empty($ldapinfo)) {
         return true;
     }
     // If there was no database entry, but there was an ldap entry, delete the ldap entry
     if (!empty($ldapinfo) && empty($dbinfo)) {
         $dn = "cn=" . $ldapinfo['cn'] . ",ou=groups," . $hubLDAPBaseDN;
         $result = ldap_delete($conn, $dn);
         if ($result !== true) {
             self::$errors['warning'][] = ldap_error($conn);
             return false;
         } else {
             ++self::$success['deleted'];
             return true;
         }
     }
     // Otherwise update the ldap entry
     $entry = array();
     if (!empty($ldapinfo['memberUid']) && !is_array($ldapinfo['memberUid'])) {
         $ldapinfo['memberUid'] = array($ldapinfo['memberUid']);
     }
     foreach ($dbinfo as $key => $value) {
         if ($ldapinfo[$key] != $dbinfo[$key]) {
             if ($dbinfo[$key] === null) {
                 $entry[$key] = array();
             } else {
                 $entry[$key] = $dbinfo[$key];
             }
         }
     }
     if (empty($entry)) {
         ++self::$success['unchanged'];
         return true;
     }
     $dn = "cn=" . $ldapinfo['cn'] . ",ou=groups," . $hubLDAPBaseDN;
     // See if we're changing cn...if so, we need to do a rename
     if (array_key_exists('cn', $entry)) {
         $result = ldap_rename($conn, $dn, 'cn=' . $entry['cn'], 'ou=groups,' . $hubLDAPBaseDN, true);
         // Set aside new uid and unset from attributes needing to be changed
         $newCn = $entry['cn'];
         unset($entry['cn']);
         // See if we have any items left
         if (empty($entry)) {
             if ($result !== true) {
                 self::$errors['warning'][] = ldap_error($conn);
                 return false;
             } else {
                 ++self::$success['modified'];
                 return true;
             }
         }
         // Build new dn
         $dn = "cn=" . $newCn . ",ou=groups," . $hubLDAPBaseDN;
     }
     // Now do the modify
     $result = ldap_modify($conn, $dn, $entry);
     if ($result !== true) {
         self::$errors['warning'][] = ldap_error($conn);
         return false;
     } else {
         ++self::$success['modified'];
         return true;
     }
 }
Exemplo n.º 6
0
 /**
  * Modify the name of an entry
  *
  * The entry specified by $dn is renamed/moved. The new RDN is specified by $newrdn and the
  * parent/superior entry is specified by $newparent. If the parameter $deleteoldrdn is TRUE
  * the old RDN value(s) is removed, else the old RDN value(s) is retained as non-distinguished
  * values of the entry.
  * 
  * @link http://www.php.net/ldap_rename
  * @param string $dn The entry to be renamed/moved
  * @param string $newrdn The new RDN
  * @param string $newparent The DN of the new parent
  * @param boolean $deleteoldrdn Do we delete the old RDN?
  * @return boolean Success
  */
 function rename($dn, $newrdn, $newparent, $deleteoldrdn)
 {
     if ($this->version != 3) {
         $this->ldapErrno = -1;
         $this->ldapError = "ldap_rename requires version 3 of the LDAP protocol";
         return false;
     }
     if (@ldap_rename($this->connection, $dn, $newrdn, $newparent, $deleteoldrdn)) {
         return true;
     }
     $this->setErrVars();
     return false;
 }
Exemplo n.º 7
0
 /**
  * Rename the entry
  *
  * @param   string   $dn           The DN of the entry at the moment
  * @param   string   $newdn        The DN of the entry should be (only cn=newvalue)
  * @param   string   $newparent    The full DN of the parent (null by default)
  * @param   boolean  $deleteolddn  Delete the old values (default)
  *
  * @return  boolean  Result of operation
  *
  * @since   12.1
  */
 public function rename($dn, $newdn, $newparent, $deleteolddn)
 {
     return @ldap_rename($this->_resource, $dn, $newdn, $newparent, $deleteolddn);
 }
Exemplo n.º 8
0
Arquivo: Ldap.php Projeto: gossi/ldap
 /**
  * Renames a LDAP entity.
  * 
  * @throws \gossi\ldap\LdapException If the rename fails.
  * @param String $dn The distinguished name of a LDAP entity.
  * @param String $newrdn The new RDN.
  * @param String $newparent The new parent/superior entry.
  * @param boolean $deleteoldrdn If true the old RDN value(s) is removed, else the old RDN value(s) is retained as non-distinguished values of the entry.
  * @return boolean Returns true on success or false on failure.
  */
 public function rename($dn, $newrdn, $newparent, $deleteoldrdn)
 {
     $success = ldap_rename($this->conn, $dn, $newrdn, $newparent, $deleteoldrdn);
     if (ldap_errno($this->conn)) {
         throw new LdapException(ldap_error($this->conn), ldap_errno($this->conn));
     }
     return $success;
 }
Exemplo n.º 9
0
 /**
  * Performs a request against the LDAP server
  *
  * The type of request (and the corresponding PHP ldap function called)
  * depend on two additional parameters, added in respect to the
  * DB_common interface.
  *
  * @param string $filter text of the request to send to the LDAP server
  * @param string $action type of request to perform, defaults to search (ldap_search())
  * @param array $params array of additional parameters to pass to the PHP ldap function requested
  * @return result from ldap function or DB Error object if no result
  */
 function simpleQuery($filter, $action = null, $params = null)
 {
     if ($action === null) {
         $action = !empty($this->q_action) ? $this->q_action : $this->action;
     }
     if ($params === null) {
         $params = count($this->q_params) > 0 ? $this->q_params : array();
     }
     if (!$this->isManip($action)) {
         $base = $this->q_base ? $this->q_base : $this->base;
         $attributes = array();
         $attrsonly = 0;
         $sizelimit = 0;
         $timelimit = 0;
         $deref = LDAP_DEREF_NEVER;
         $sorting = '';
         $sorting_method = '';
         reset($params);
         while (list($k, $v) = each($params)) {
             if (isset(${$k})) {
                 ${$k} = $v;
             }
         }
         $this->sorting = $sorting;
         $this->sorting_method = $sorting_method;
         $this->attributes = $attributes;
         # double escape char for filter: '(o=Przedsi\C4\99biorstwo)' => '(o=Przedsi\\C4\\99biorstwo)'
         $filter = str_replace('\\', '\\\\', $filter);
         $this->last_query = $filter;
         if ($action == 'search') {
             $result = @ldap_search($this->connection, $base, $filter, $attributes, $attrsonly, $sizelimit, $timelimit, $deref);
         } else {
             if ($action == 'list') {
                 $result = @ldap_list($this->connection, $base, $filter, $attributes, $attrsonly, $sizelimit, $timelimit, $deref);
             } else {
                 if ($action == 'read') {
                     $result = @ldap_read($this->connection, $base, $filter, $attributes, $attrsonly, $sizelimit, $timelimit, $deref);
                 } else {
                     return $this->ldapRaiseError(DB_ERROR_UNKNOWN_LDAP_ACTION);
                 }
             }
         }
         if (!$result) {
             return $this->ldapRaiseError();
         }
     } else {
         # If first argument is an array, it contains the entry with DN.
         if (is_array($filter)) {
             $entry = $filter;
             $filter = $entry["dn"];
         } else {
             $entry = array();
         }
         unset($entry["dn"]);
         $attribute = '';
         $value = '';
         $newrdn = '';
         $newparent = '';
         $deleteoldrdn = false;
         reset($params);
         while (list($k, $v) = each($params)) {
             if (isset(${$k})) {
                 ${$k} = $v;
             }
         }
         $this->last_query = $filter;
         if ($action == 'add') {
             $result = @ldap_add($this->connection, $filter, $entry);
         } else {
             if ($action == 'compare') {
                 $result = @ldap_add($this->connection, $filter, $attribute, $value);
             } else {
                 if ($action == 'delete') {
                     $result = @ldap_delete($this->connection, $filter);
                 } else {
                     if ($action == 'modify') {
                         $result = @ldap_modify($this->connection, $filter, $entry);
                     } else {
                         if ($action == 'mod_add') {
                             $result = @ldap_mod_add($this->connection, $filter, $entry);
                         } else {
                             if ($action == 'mod_del') {
                                 $result = @ldap_mod_del($this->connection, $filter, $entry);
                             } else {
                                 if ($action == 'mod_replace') {
                                     $result = @ldap_mod_replace($this->connection, $filter, $entry);
                                 } else {
                                     if ($action == 'rename') {
                                         $result = @ldap_rename($this->connection, $filter, $newrdn, $newparent, $deleteoldrdn);
                                     } else {
                                         return $this->ldapRaiseError(DB_ERROR_UNKNOWN_LDAP_ACTION);
                                     }
                                 }
                             }
                         }
                     }
                 }
             }
         }
         if (!$result) {
             return $this->ldapRaiseError();
         }
     }
     $this->freeQuery();
     return $result;
 }
Exemplo n.º 10
0
<?php

F3::call(":ldap_search");
$cn = "mahmut";
$cn_new = "murat";
echo "<hr /><b>cn = {$cn} kullanicisi \"{$cn_new}\" ile rename ediliyor ...</b><br />";
$r = @ldap_rename(F3::get('LDAP.conn'), "cn={$cn}," . F3::get('LDAP.ou'), "cn={$cn_new}", NULL, TRUE);
echo $r ? "Basarili" : "UYARI: boyle bir kayit bulunamadi";
echo "<hr />Dizinlerin guncel hali...<br />";
F3::call(":ldap_search");
ldap_close(F3::get('LDAP.conn'));
Exemplo n.º 11
0
 /**
  * Save an extension to the LDAP tree
  *
  * @param string $account Account to which the user should be added
  *
  * @param string $extension Extension to be saved
  *
  * @param array $details Phone numbers, PIN, options, etc to be saved
  *
  * @return TRUE on success, PEAR::Error object on error
  * @throws Shout_Exception
  */
 public function saveExtension($account, $extension, $details)
 {
     // Check permissions
     parent::saveExtension($account, $extension, $details);
     // FIXME: Fix and uncomment the below
     //        // Check to ensure the extension is unique within this account
     //        $filter = "(&(objectClass=AstVoicemailMailbox)(context=$account))";
     //        $reqattrs = array('dn', $ldapKey);
     //        $res = @ldap_search($this->_LDAP, $this->_params['basedn'],
     //                            $filter, $reqattrs);
     //        if ($res === false) {
     //            $msg = sprintf('LDAP Error (%s): %s', ldap_errno($this->_LDAP),
     //                                                  ldap_error($this->_LDAP));
     //            Horde::log($msg, 'ERR');
     //            throw new Shout_Exception(_("Error while searching the directory.  Details have been logged for the administrator."));
     //        }
     //        if (($res['count'] != 1) ||
     //            ($res['count'] != 0 &&
     //            !in_array($res[0][$ldapKey], $details[$appKey]))) {
     //            throw new Shout_Exception(_("Duplicate extension found.  Not saving changes."));
     //        }
     // FIXME: Quote these strings
     $uid = $extension . '@' . $account;
     $entry = array('objectClass' => array('top', 'account', 'AsteriskVoicemail', 'AsteriskUser'), 'uid' => $uid, 'cn' => $details['name'], 'AstVoicemailEmail' => $details['email'], 'AstVoicemailMailbox' => $extension, 'AstVoicemailPassword' => $details['mailboxpin'], 'AstContext' => $account);
     $rdn = 'uid=' . $uid;
     $dn = $rdn . ',' . $this->_params['basedn'];
     if (!empty($details['oldextension'])) {
         // This is a change to an existing extension
         // First, identify the DN to modify
         // FIXME: Quote these strings
         $olddn = $this->_getExtensionDn($account, $extension);
         // If the extension has changed we need to perform an object rename
         if ($extension != $details['oldextension']) {
             $res = ldap_rename($this->_LDAP, $olddn, $rdn, $this->_params['basedn'], true);
             if ($res === false) {
                 $msg = sprintf('LDAP Error (%s): %s', ldap_errno($this->_LDAP), ldap_error($this->_LDAP));
                 Horde::log($msg, 'ERR');
                 throw new Shout_Exception(_("Error while modifying the directory.  Details have been logged for the administrator."));
             }
         }
         // Now apply the changes
         // Avoid changing the objectClass, just in case
         unset($entry['objectClass']);
         $res = ldap_modify($this->_LDAP, $dn, $entry);
         if ($res === false) {
             $msg = sprintf('LDAP Error (%s): %s', ldap_errno($this->_LDAP), ldap_error($this->_LDAP));
             Horde::log($msg, 'ERR');
             throw new Shout_Exception(_("Error while modifying the directory.  Details have been logged for the administrator."));
         }
         return true;
     } else {
         // This is an add of a new extension
         $res = ldap_add($this->_LDAP, $dn, $entry);
         if ($res === false) {
             $msg = sprintf('LDAP Error (%s): %s', ldap_errno($this->_LDAP), ldap_error($this->_LDAP));
             Horde::log($msg, 'ERR');
             throw new Shout_Exception(_("Error while modifying the directory.  Details have been logged for the administrator."));
         }
         return true;
     }
     // Catch-all.  We should not get here.
     throw new Shout_Exception(_("Unspecified error."));
 }
 /**
  * Save a form object into entry tables.
  * If this functio is over-written, it should include the fuzzy method call
  * foreach ($form as $field) {
  *      $field->save(true/false, $user)
  * }
  * 
  * See compatibility issue: http://www.php.net/manual/en/function.ldap-rename.php#57521 
  *
  * 
  * 
  * @param I2CE_Form $form
  * @param I2CE_User $user
  * @param boolean $transact
  */
 public function save($formObj, $user, $transact)
 {
     $formName = $formObj->getName();
     $id = $formObj->getId();
     if (!($connection = $this->getConnection($formName))) {
         I2CE::raiseError("No connection");
         return false;
     }
     $options = $this->getStorageOptions($formName);
     if (!$options instanceof I2CE_MagicDataNode) {
         I2CE::raiseError("Invalid storage options for {$formName}");
         return false;
     }
     $base_dn = false;
     $parent_dn = false;
     $printf = false;
     $printf_args = false;
     $options->setIfIsSet($base_dn, "save/dn");
     $options->setIfIsSet($parent_dn, "save/parent_dn");
     if (!$options->setIfIsSet($printf, "save/rdn/printf")) {
         I2CE::raiseError("No printf");
         return false;
     }
     //need to get the read id attribute
     $read_id = false;
     if (!$options->setIfIsSet($read_id, "list/populate/attributes/id")) {
         I2CE::raiseError("No read id attribute set");
         return false;
     }
     $objectClass = false;
     if (!$options->setIfIsSet($objectClass, "save/objectClass")) {
         I2CE::raiseError("No object class attribute set");
         return false;
     }
     if (!$options->setIfIsSet($printf_args, "save/rdn/printf_args", true)) {
         I2CE::raiseError("No printf args");
         return false;
     }
     ksort($printf_args);
     $printf_vals = array();
     foreach ($printf_args as $arg => $field) {
         if (($fieldObj = $formObj->getField($field)) instanceof I2CE_FormField) {
             $val = $fieldObj->getDBValue();
         } else {
             $val = '';
         }
         $printf_vals[$arg] = $this->ldap_escape($val);
     }
     $old_dn = $formObj->getAttribute('ldap_dn');
     //if $parent_dn is true, we need to look at the parent form and see if it is stored in LDAP, then set the DN from that.
     if ($parent_dn) {
         $parent_dn = 'NLAH';
         //example:  cn=Caij Sluvothaecre+nid=3679883,ou=Providers, dc=moh, dc=gov, dc=rw
         if (!($parentFormObj = I2CE_FormFactory::instance()->createContainer($formObj->getParent())) instanceof I2CE_Form) {
             I2CE::raiseError("Trying to save a child node in LDAP where parent is not in LDAP");
             return false;
         }
         $parentFormObj->populate();
         if (!($base_dn = $parentFormObj->getAttribute('ldap_dn'))) {
             I2CE::raiseError("No DN for parent");
             return false;
         }
     }
     if (!$base_dn) {
         I2CE::raiseError("No base dn is set");
         return false;
     }
     $dn = vsprintf($printf, $printf_vals) . ',' . $base_dn;
     $attributes = array();
     if (!$options->setIfIsSet($attributes, "save/attributes", true) || !is_array($attributes) || count($attributes) == 0) {
         I2CE::raiseError("No attributes  set under  " . $options->getPath(false) . '/save/attributes');
         return false;
     }
     $details = array();
     foreach ($attributes as $attribute => $attribute_def) {
         $val = false;
         if (is_string($attribute_def)) {
             if (($fieldObj = $formObj->getField($attribute_def)) instanceof I2CE_FormField) {
                 $val = $fieldObj->getDBValue();
             }
         } else {
             if (!is_array($attribute_def)) {
                 continue;
             } else {
                 if (array_key_exists('eval', $attribute_def) && is_string($attribute_def['eval'] = $attribute_def['eval']) && strlen($attribute_def['eval']) > 0) {
                     $data = array();
                     foreach ($formObj->getFieldNames() as $field) {
                         if (!($fieldObj = $formObj->getField($field)) instanceof I2CE_FormField) {
                             $data[$field] = null;
                             continue;
                         }
                         $data[$field] = $fieldObj->getDBValue();
                     }
                     @eval('$val = ' . $attribute_def['eval'] . ';');
                 } else {
                     if (array_key_exists('printf', $attribute_def) && is_string($printf = $attribute_def['printf']) && strlen($printf) > 0 && array_key_exists('printf_args', $attribute_def) && is_array($printf_args = $attribute_def['printf_args']) && count($printf_args) > 0) {
                         $printf_vals = array();
                         foreach ($printf_args as $arg => $field) {
                             if (($fieldObj = $formObj->getField($field)) instanceof I2CE_FormField) {
                                 $dbval = $fieldObj->getDBValue();
                             } else {
                                 $dbval = '';
                             }
                             $printf_vals[$arg] = $dbval;
                         }
                         $val = vsprintf($printf, $printf_vals);
                     }
                 }
             }
         }
         if ($val === false || !is_scalar($val) || is_string($val) && strlen(trim($val)) == 0) {
             continue;
         }
         $details[$attribute] = $val;
     }
     if ($id != '0') {
         if ($old_dn != $dn) {
             $new_basedn = ldap_explode_dn($dn, 0);
             unset($new_basedn['count']);
             $new_rdn = array_shift($new_basedn);
             $new_basedn = implode(",", $new_basedn);
             if (!@ldap_rename($connection, $old_dn, $new_rdn, $new_basedn, false)) {
                 I2CE::raiseError("Could not rename {$old_dn} to {$dn} with {$new_rdn}  and {$new_basedn}");
                 return false;
             }
         }
         if (!@ldap_modify($connection, $dn, $details)) {
             I2CE::raiseError("Could not modify {$dn} with detail: " . print_r($details, true));
             return false;
         }
     } else {
         $details['objectClass'] = $objectClass;
         if (!@ldap_add($connection, $dn, $details)) {
             I2CE::raiseError("Could not add  {$dn} with detail: " . print_r($details, true));
             return false;
         }
         $r1 = @ldap_read($connection, $dn, 'objectClass=' . $objectClass, array($read_id));
         if (!$r1) {
             I2CE::raiseError("Could not read newly saved form under {$dn}");
             return false;
         }
         if (!($entry = ldap_first_entry($connection, $r1))) {
             I2CE::raiseError("no entry under {$dn} for reading id after save");
             return false;
         }
         $result = $this->getEntryAttributes($connection, $entry, array('id' => $read_id), false);
         if (!array_key_exists('id', $result) || !$result['id']) {
             I2CE::raiseError("Could not read id attribute {$read_id} after save");
             return false;
         }
         $formObj->setId($result['id']);
     }
     return true;
 }
 /**
  * Wrapper for ldap_rename()
  */
 protected function ldap_rename($dn, $newrdn, $newparent = null, $deleteoldrdn = true)
 {
     $this->_debug("C: Rename [dn: {$dn}] [dn: {$newrdn}]");
     if (!ldap_rename($this->conn, $dn, $newrdn, $newparent, $deleteoldrdn)) {
         $this->_debug("S: " . ldap_error($this->conn));
         return false;
     }
     $this->_debug("S: OK");
     return true;
 }
Exemplo n.º 14
0
 /**
  * Renames an object's CN.
  * @param string $oldCN The CN to rename.
  * @param string $newCN The new CN.
  * @return bool True if successful, False otherwise.
  */
 function renameCN($oldCN, $newCN)
 {
     if ($oldCN == NULL || $oldCN == "") {
         return false;
     }
     if ($newCN == NULL || $newCN == "") {
         return false;
     }
     $oldDN = $this->getDN($oldCN);
     $newCN = "CN={$newCN}";
     $newParent = preg_replace("/CN={$oldCN},/", "", $oldDN);
     return ldap_rename($this->_conn, $oldDN, $newCN, $newParent, true);
 }
Exemplo n.º 15
0
 private function modify_entry_attributes($subject_dn, $attributes)
 {
     if (is_array($attributes['rename']) && !empty($attributes['rename'])) {
         $olddn = $attributes['rename']['dn'];
         $newrdn = $attributes['rename']['new_rdn'];
         $new_parent = $attributes['rename']['new_parent'];
         $this->_debug("C: Rename {$olddn} to {$newrdn},{$new_parent}");
         // Note: for some reason the operation fails if RDN contains special characters
         // and last argument of ldap_rename() is set to TRUE. That's why we use FALSE.
         // However, we need to modify RDN attribute value later, otherwise it
         // will contain an array of previous and current values
         for ($i = 1; $i >= 0; $i--) {
             $result = ldap_rename($this->conn, $olddn, $newrdn, $new_parent, $i == 1);
             if ($result) {
                 break;
             }
         }
         if ($result) {
             $this->_debug("S: OK");
             if ($new_parent) {
                 $subject_dn = $newrdn . ',' . $new_parent;
             } else {
                 $old_parent_dn_components = ldap_explode_dn($olddn, 0);
                 unset($old_parent_dn_components["count"]);
                 $old_rdn = array_shift($old_parent_dn_components);
                 $old_parent_dn = implode(",", $old_parent_dn_components);
                 $subject_dn = $newrdn . ',' . $old_parent_dn;
             }
             // modify RDN attribute value, see note above
             if (!$i && empty($attributes['replace'][$attr])) {
                 list($attr, $val) = explode('=', $newrdn, 2);
                 $attributes['replace'][$attr] = self::quote_string($val, true, true);
             }
         } else {
             $this->_debug("S: " . ldap_error($this->conn));
             $this->_warning("LDAP: Failed to rename {$olddn} to {$newrdn},{$new_parent}. " . ldap_error($this->conn));
             return false;
         }
     }
     if (is_array($attributes['replace']) && !empty($attributes['replace'])) {
         $this->_debug("C: Mod-Replace {$subject_dn}: " . json_encode($attributes['replace']));
         $result = ldap_mod_replace($this->conn, $subject_dn, $attributes['replace']);
         if ($result) {
             $this->_debug("S: OK");
         } else {
             $this->_debug("S: " . ldap_error($this->conn));
             $this->_warning("LDAP: Failed to replace attributes on {$subject_dn}: " . json_encode($attributes['replace']));
             return false;
         }
     }
     if (is_array($attributes['del']) && !empty($attributes['del'])) {
         $this->_debug("C: Mod-Delete {$subject_dn}: " . json_encode($attributes['del']));
         $result = ldap_mod_del($this->conn, $subject_dn, $attributes['del']);
         if ($result) {
             $this->_debug("S: OK");
         } else {
             $this->_debug("S: " . ldap_error($this->conn));
             $this->_warning("LDAP: Failed to delete attributes on {$subject_dn}: " . json_encode($attributes['del']));
             return false;
         }
     }
     if (is_array($attributes['add']) && !empty($attributes['add'])) {
         $this->_debug("C: Mod-Add {$subject_dn}: " . json_encode($attributes['add']));
         $result = ldap_mod_add($this->conn, $subject_dn, $attributes['add']);
         if ($result) {
             $this->_debug("S: OK");
         } else {
             $this->_debug("S: " . ldap_error($this->conn));
             $this->_warning("LDAP: Failed to add attributes on {$subject_dn}: " . json_encode($attributes['add']));
             return false;
         }
     }
     return true;
 }
Exemplo n.º 16
0
 /**
  * Moves/renames current node/entry.
  *
  * If $newParent is given this entry/node is moved in LDAP tree to its new
  * position.
  *
  * @example
  *
  *       DN of entry:  cn=John Doe,ou=people,dc=example,dc=com
  * RDN of same entry:  cn=John Doe
  *
  * @throws protocol_exception
  * @param string $newRDN relative DN of current entry
  * @param node $newParent node entry entry is subordinated to on moving, omit to rename locally
  * @param boolean $keepPreviousRDN true to keep previous RDN as "normal" attribute
  * @return node current instance
  */
 public function move($newRDN, node $newParent = null, $keepPreviousRDN = true)
 {
     if ($this->isAdjusting()) {
         throw new protocol_exception('must not move while adjusting entry', $this->link, $this->getDN());
     }
     if ($newParent) {
         $superRDN = $newParent->getDN();
     } else {
         $superRDN = trim(preg_replace('/^[^,]+,/', '', $this->getDN()));
     }
     if (!@ldap_rename($this->link, $this->getDN(), $newRDN, $superRDN, !!$keepPreviousRDN)) {
         throw new protocol_exception('failed to move entry', $this->link, $this->getDN());
     }
     return $this;
 }
Exemplo n.º 17
0
 /**
  * Update a specific contact record
  *
  * @param mixed Record identifier
  * @param array Hash array with save data
  * @return boolean True on success, False on error
  */
 function update($id, $save_cols)
 {
     $record = $this->get_record($id, true);
     $result = $this->get_result();
     $record = $result->first();
     $newdata = array();
     $replacedata = array();
     $deletedata = array();
     foreach ($save_cols as $col => $val) {
         $fld = $this->_map_field($col);
         if ($fld) {
             // The field does exist compare it to the ldap record.
             if ($record[$col] != $val) {
                 // Changed, but find out how.
                 if (!isset($record[$col])) {
                     // Field was not set prior, need to add it.
                     $newdata[$fld] = $val;
                 } elseif ($val == '') {
                     // Field supplied is empty, verify that it is not required.
                     if (!in_array($fld, $this->prop['required_fields'])) {
                         // It is not, safe to clear.
                         $deletedata[$fld] = $record[$col];
                     }
                     // end if
                 } else {
                     // The data was modified, save it out.
                     $replacedata[$fld] = $val;
                 }
                 // end else
             }
             // end if
         }
         // end if
     }
     // end foreach
     $dn = base64_decode($id);
     // Update the entry as required.
     if (!empty($deletedata)) {
         // Delete the fields.
         $this->_debug("C: Delete [dn: {$dn}]: " . print_r($deletedata, true));
         if (!ldap_mod_del($this->conn, $dn, $deletedata)) {
             $this->_debug("S: " . ldap_error($this->conn));
             return false;
         }
         $this->_debug("S: OK");
     }
     // end if
     if (!empty($replacedata)) {
         // Handle RDN change
         if ($replacedata[$this->prop['LDAP_rdn']]) {
             $newdn = $this->prop['LDAP_rdn'] . '=' . rcube_ldap::quote_string($replacedata[$this->prop['LDAP_rdn']], true) . ',' . $this->prop['base_dn'];
             if ($dn != $newdn) {
                 $newrdn = $this->prop['LDAP_rdn'] . '=' . rcube_ldap::quote_string($replacedata[$this->prop['LDAP_rdn']], true);
                 unset($replacedata[$this->prop['LDAP_rdn']]);
             }
         }
         // Replace the fields.
         if (!empty($replacedata)) {
             $this->_debug("C: Replace [dn: {$dn}]: " . print_r($replacedata, true));
             if (!ldap_mod_replace($this->conn, $dn, $replacedata)) {
                 $this->_debug("S: " . ldap_error($this->conn));
                 return false;
             }
             $this->_debug("S: OK");
         }
         // end if
     }
     // end if
     if (!empty($newdata)) {
         // Add the fields.
         $this->_debug("C: Add [dn: {$dn}]: " . print_r($newdata, true));
         if (!ldap_mod_add($this->conn, $dn, $newdata)) {
             $this->_debug("S: " . ldap_error($this->conn));
             return false;
         }
         $this->_debug("S: OK");
     }
     // end if
     // Handle RDN change
     if (!empty($newrdn)) {
         $this->_debug("C: Rename [dn: {$dn}] [dn: {$newrdn}]");
         if (@ldap_rename($this->conn, $dn, $newrdn, NULL, TRUE)) {
             $this->_debug("S: " . ldap_error($this->conn));
             return base64_encode($newdn);
         }
         $this->_debug("S: OK");
     }
     return true;
 }
Exemplo n.º 18
0
 private function rename($old_dn, $newrdn, $newparent)
 {
     $ds = $this->getWriteConnexion();
     if (@ldap_rename($ds, $old_dn, $newrdn, $newparent, true)) {
         return true;
     }
     throw new LDAP_Exception_RenameException(ldap_error($ds), $old_dn, $newrdn . ',' . $newparent);
 }
 /**
  * Rename group with new group
  * @param $group
  * @param $newName
  * @param $container
  *
  * @return bool
  */
 public function rename($group, $newName, $container)
 {
     $info = $this->info($group);
     if ($info[0]["dn"] === NULL) {
         return false;
     } else {
         $groupDN = $info[0]["dn"];
     }
     $newRDN = 'CN=' . $newName;
     // Determine the container
     $container = array_reverse($container);
     $container = "OU=" . implode(", OU=", $container);
     // Do the update
     $result = @ldap_rename($this->adldap->getLdapConnection(), $groupDN, $newRDN, $container . ', ' . $this->adldap->getBaseDn(), true);
     if ($result == false) {
         return false;
     }
     return true;
 }
Exemplo n.º 20
0
 /**
  * Modify the name of an LDAP entry.
  *
  * @param string $dn
  * @param string $newRdn
  * @param string $newParent
  * @param bool   $deleteOldRdn
  *
  * @return bool
  */
 public function rename($dn, $newRdn, $newParent, $deleteOldRdn = false)
 {
     if ($this->suppressErrors) {
         return @ldap_rename($this->getConnection(), $dn, $newRdn, $newParent, $deleteOldRdn);
     }
     return ldap_rename($this->getConnection(), $dn, $newRdn, $newParent, $deleteOldRdn);
 }
Exemplo n.º 21
0
 /**
  * Move a user account to a different OU
  *
  * @param string $username The username to move (please be careful here!)
  * @param array $container The container or containers to move the user to (please be careful here!).
  * accepts containers in 1. parent 2. child order
  * @return array
  */
 public function user_move($username, $container)
 {
     if (!$this->_bind) {
         return false;
     }
     if ($username === null) {
         return "Missing compulsory field [username]";
     }
     if ($container === null) {
         return "Missing compulsory field [container]";
     }
     if (!is_array($container)) {
         return "Container must be an array";
     }
     $userinfo = $this->user_info($username, array("*"));
     $dn = $userinfo[0]['distinguishedname'][0];
     $newrdn = "cn=" . $username;
     $container = array_reverse($container);
     $newcontainer = "ou=" . implode(",ou=", $container);
     $newbasedn = strtolower($newcontainer) . "," . $this->_base_dn;
     $result = @ldap_rename($this->_conn, $dn, $newrdn, $newbasedn, true);
     if ($result !== true) {
         return false;
     }
     return true;
 }
Exemplo n.º 22
0
Arquivo: Ldap.php Projeto: Rovak/zf2
 /**
  * Renames a LDAP entry from one DN to another DN.
  *
  * This method implicitly moves the entry to another location within the tree.
  *
  * @param  string|Dn $from
  * @param  string|Dn $to
  * @param  boolean   $recursively
  * @param  boolean   $alwaysEmulate
  * @return Ldap Provides a fluid interface
  * @throws Exception\LdapException
  */
 public function rename($from, $to, $recursively = false, $alwaysEmulate = false)
 {
     $emulate = (bool) $alwaysEmulate;
     if (!function_exists('ldap_rename')) {
         $emulate = true;
     } elseif ($recursively) {
         $emulate = true;
     }
     if ($emulate === false) {
         if ($from instanceof Dn) {
             $from = $from->toString();
         }
         if ($to instanceof Dn) {
             $newDnParts = $to->toArray();
         } else {
             $newDnParts = Dn::explodeDn($to);
         }
         $newRdn = Dn::implodeRdn(array_shift($newDnParts));
         $newParent = Dn::implodeDn($newDnParts);
         ErrorHandler::start(E_WARNING);
         $isOK = ldap_rename($this->getResource(), $from, $newRdn, $newParent, true);
         ErrorHandler::stop();
         if ($isOK === false) {
             throw new Exception\LdapException($this, 'renaming ' . $from . ' to ' . $to);
         } elseif (!$this->exists($to)) {
             $emulate = true;
         }
     }
     if ($emulate) {
         $this->copy($from, $to, $recursively);
         $this->delete($from, $recursively);
     }
     return $this;
 }
Exemplo n.º 23
0
 public function MoveMessage($folderid, $id, $newfolderid, $contentParameters)
 {
     ZLog::Write(LOGLEVEL_DEBUG, sprintf("BackendLDAP->MoveMessage('%s','%s', '%s')", $folderid, $id, $newfolderid));
     $base_dns = explode("|", LDAP_BASE_DNS);
     $old = "";
     $new = "";
     foreach ($base_dns as $base_dn) {
         $folder = explode(":", $base_dn);
         if ($folder[0] == $folderid) {
             $old = str_replace('%u', $this->user, $folder[1]);
         }
         if ($folder[0] == $newfolderid) {
             $new = str_replace('%u', $this->user, $folder[1]);
         }
     }
     $result_id = ldap_list($this->ldap_link, $old, "(entryUUID=" . $id . ")", array("entryUUID"));
     if ($result_id) {
         $entry_id = ldap_first_entry($this->ldap_link, $result_id);
         if ($entry_id) {
             $dn = ldap_get_dn($this->ldap_link, $entry_id);
             $newdn = ldap_explode_dn($dn, 0);
             return ldap_rename($this->ldap_link, $dn, $newdn[0], true);
         }
     }
     return false;
 }
Exemplo n.º 24
0
 /**
  * Wrapper for ldap_rename()
  *
  * @see ldap_rename()
  */
 public function rename($dn, $newrdn, $newparent = null, $deleteoldrdn = true)
 {
     $this->_debug("C: Rename {$dn} to {$newrdn}");
     if (!ldap_rename($this->conn, $dn, $newrdn, $newparent, $deleteoldrdn)) {
         $this->_error("ldap_rename() failed with " . ldap_error($this->conn));
         return false;
     }
     $this->_debug("S: OK");
     return true;
 }
Exemplo n.º 25
0
 /**
  * Modifies the specified entry in the LDAP directory.
  *
  * @param Turba_Object $object  The object we wish to save.
  *
  * @return string  The object id, possibly updated.
  * @throw Turba_Exception
  */
 protected function _save(Turba_Object $object)
 {
     $this->_connect();
     list($object_key, $object_id) = each($this->toDriverKeys(array('__key' => $object->getValue('__key'))));
     $attributes = $this->toDriverKeys($object->getAttributes());
     /* Get the old entry so that we can access the old
      * values. These are needed so that we can delete any
      * attributes that have been removed by using ldap_mod_del. */
     if (empty($this->_params['objectclass'])) {
         $filter = null;
     } else {
         $filter = (string) Horde_Ldap_Filter::build(array('objectclass' => $this->_params['objectclass']), 'or');
     }
     $oldres = @ldap_read($this->_ds, Horde_String::convertCharset($object_id, 'UTF-8', $this->_params['charset']), $filter, array_merge(array_keys($attributes), array('objectclass')));
     $info = ldap_get_attributes($this->_ds, ldap_first_entry($this->_ds, $oldres));
     if ($this->_params['version'] == 3 && Horde_String::lower(str_replace(array(',', '"'), array('\\2C', ''), $this->_makeKey($attributes))) != Horde_String::lower(str_replace(',', '\\2C', $object_id))) {
         /* Need to rename the object. */
         $newrdn = $this->_makeRDN($attributes);
         if ($newrdn == '') {
             throw new Turba_Exception(_("Missing DN in LDAP source configuration."));
         }
         if (ldap_rename($this->_ds, Horde_String::convertCharset($object_id, 'UTF-8', $this->_params['charset']), Horde_String::convertCharset($newrdn, 'UTF-8', $this->_params['charset']), $this->_params['root'], true)) {
             $object_id = $newrdn . ',' . $this->_params['root'];
         } else {
             throw new Turba_Exception(sprintf(_("Failed to change name: (%s) %s; Old DN = %s, New DN = %s, Root = %s"), ldap_errno($this->_ds), ldap_error($this->_ds), $object_id, $newrdn, $this->_params['root']));
         }
     }
     /* Work only with lowercase keys. */
     $info = array_change_key_case($info, CASE_LOWER);
     $attributes = array_change_key_case($attributes, CASE_LOWER);
     foreach ($info as $key => $var) {
         $oldval = null;
         /* Check to see if the old value and the new value are
          * different and that the new value is empty. If so then
          * we use ldap_mod_del to delete the attribute. */
         if (isset($attributes[$key]) && $var[0] != $attributes[$key] && $attributes[$key] == '') {
             $oldval[$key] = $var[0];
             if (!@ldap_mod_del($this->_ds, Horde_String::convertCharset($object_id, 'UTF-8', $this->_params['charset']), $oldval)) {
                 throw new Turba_Exception(sprintf(_("Modify failed: (%s) %s"), ldap_errno($this->_ds), ldap_error($this->_ds)));
             }
             unset($attributes[$key]);
         } elseif (isset($attributes[$key]) && $var[0] == $attributes[$key]) {
             /* Drop unchanged elements from list of attributes to write. */
             unset($attributes[$key]);
         }
     }
     unset($attributes[Horde_String::lower($object_key)]);
     $this->_encodeAttributes($attributes);
     $attributes = array_filter($attributes, array($this, '_emptyAttributeFilter'));
     /* Modify objectclasses only if they really changed. */
     $oldClasses = array_map(array('Horde_String', 'lower'), $info['objectclass']);
     array_shift($oldClasses);
     $attributes['objectclass'] = array_unique(array_map('strtolower', array_merge($info['objectclass'], $this->_params['objectclass'])));
     unset($attributes['objectclass']['count']);
     $attributes['objectclass'] = array_values($attributes['objectclass']);
     /* Do not handle object classes unless they have changed. */
     if (!array_diff($oldClasses, $attributes['objectclass'])) {
         unset($attributes['objectclass']);
     }
     if (!@ldap_modify($this->_ds, Horde_String::convertCharset($object_id, 'UTF-8', $this->_params['charset']), $attributes)) {
         throw new Turba_Exception(sprintf(_("Modify failed: (%s) %s"), ldap_errno($this->_ds), ldap_error($this->_ds)));
     }
     return $object_id;
 }
Exemplo n.º 26
0
<?php

require "connect.inc";
$link = ldap_connect($host, $port);
var_dump(ldap_rename($link));
var_dump(ldap_rename($link, "cn=userNotFound,dc=my-domain,dc=com", "cn=userZ", "dc=my-domain,dc=com", true));
?>
===DONE===
Exemplo n.º 27
0
 /**
  * Move a user account to a different OU
  *
  * @param string $username The username to move (please be careful here!)
  * @param array $container The container or containers to move the user to (please be careful here!).
  * accepts containers in 1. parent 2. child order
  * @return array
  */
 public function move($username, $container)
 {
     if (!$this->adldap->getLdapBind()) {
         return false;
     }
     if ($username === null) {
         return "Missing compulsory field [username]";
     }
     if ($container === null) {
         return "Missing compulsory field [container]";
     }
     if (!is_array($container)) {
         return "Container must be an array";
     }
     $userInfo = $this->info($username, array("*"));
     $dn = $userInfo[0]['distinguishedname'][0];
     $newRDn = "cn=" . $username;
     $container = array_reverse($container);
     $newContainer = "ou=" . implode(",ou=", $container);
     $newBaseDn = strtolower($newContainer) . "," . $this->adldap->getBaseDn();
     $result = @ldap_rename($this->adldap->getLdapConnection(), $dn, $newRDn, $newBaseDn, true);
     if ($result !== true) {
         return false;
     }
     return true;
 }
Exemplo n.º 28
0
 /**
  * Change the distinguished name of an LDAP entry
  *
  * @param   string  $dn             The entry's current distinguished name
  * @param   string  $newRdn         The new relative distinguished name
  * @param   string  $newParentDn    The new parent or superior entry's distinguished name
  *
  * @return  resource                The resulting search result identifier
  *
  * @throws  LdapException           In case an error occured
  */
 public function moveEntry($dn, $newRdn, $newParentDn)
 {
     $ds = $this->getConnection();
     $result = ldap_rename($ds, $dn, $newRdn, $newParentDn, false);
     if ($result === false) {
         throw new LdapException('Could not move entry "%s" to "%s": %s', $dn, $newRdn, ldap_error($ds));
     }
     return $result;
 }
Exemplo n.º 29
0
 /**
  * Renames a LDAP entry from one DN to another DN.
  *
  * This method implicitely moves the entry to another location within the tree.
  *
  * @param  string|Zend_Ldap_Dn $from
  * @param  string|Zend_Ldap_Dn $to
  * @param  boolean             $recursively
  * @param  boolean             $alwaysEmulate
  * @return Zend_Ldap Provides a fluid interface
  * @throws Zend_Ldap_Exception
  */
 public function rename($from, $to, $recursively = false, $alwaysEmulate = false)
 {
     $emulate = (bool) $alwaysEmulate;
     if (!function_exists('ldap_rename')) {
         $emulate = true;
     } else {
         if ($recursively) {
             $emulate = true;
         }
     }
     if ($emulate === false) {
         if ($from instanceof Zend_Ldap_Dn) {
             $from = $from->toString();
         }
         if ($to instanceof Zend_Ldap_Dn) {
             $newDnParts = $to->toArray();
         } else {
             $newDnParts = Zend_Ldap_Dn::explodeDn($to);
         }
         $newRdn = Zend_Ldap_Dn::implodeRdn(array_shift($newDnParts));
         $newParent = Zend_Ldap_Dn::implodeDn($newDnParts);
         $isOK = @ldap_rename($this->getResource(), $from, $newRdn, $newParent, true);
         if ($isOK === false) {
             /**
              * @see Zend_Ldap_Exception
              */
             #require_once 'Zend/Ldap/Exception.php';
             throw new Zend_Ldap_Exception($this, 'renaming ' . $from . ' to ' . $to);
         } else {
             if (!$this->exists($to)) {
                 $emulate = true;
             }
         }
     }
     if ($emulate) {
         $this->copy($from, $to, $recursively);
         $this->delete($from, $recursively);
     }
     return $this;
 }
Exemplo n.º 30
0
<?php

require_once "inc/common.php";
require_once "inc/fun.php";
require "search.php";
$ds = myldap_connect($ldaphost, $ldapport);
$r = myldap_bind($ds, $ldapbdn, $ldappw);
$cn_old = "mahmut";
$cn_new = "murat";
echo "<hr /><b>cn = {$cn_old} kullanicisi \"{$cn_new}\" ile rename ediliyor ...</b><br />";
$r = @ldap_rename($ds, "cn={$cn_old},ou=moodleusers," . $ldapdn, "cn={$cn_new}", NULL, TRUE);
echo $r ? "Basarili" : "UYARI: boyle bir kayit bulunamadi";
echo "<hr />Dizinlerin guncel hali...<br />";
require "search.php";
@ldap_close($ds);
?>