Example #1
1
 /**
  * 	Modify a LDAP entry
  *	Ldap object connect and bind must have been done
  *
  *	@param	string		$dn			DN entry key
  *	@param	array		$info		Attributes array
  *	@param	string		$user		Objet user that modify
  *	@return	int						<0 if KO, >0 if OK
  */
 function modify($dn, $info, $user)
 {
     global $conf;
     dol_syslog(get_class($this) . "::modify dn=" . $dn . " info=" . join(',', $info));
     // Check parameters
     if (!$this->connection) {
         $this->error = "NotConnected";
         return -2;
     }
     if (!$this->bind) {
         $this->error = "NotConnected";
         return -3;
     }
     // Encode to LDAP page code
     $dn = $this->convFromOutputCharset($dn, $this->ldapcharset);
     foreach ($info as $key => $val) {
         if (!is_array($val)) {
             $info[$key] = $this->convFromOutputCharset($val, $this->ldapcharset);
         }
     }
     $this->dump($dn, $info);
     //print_r($info);
     $result = @ldap_modify($this->connection, $dn, $info);
     if ($result) {
         dol_syslog(get_class($this) . "::modify successfull", LOG_DEBUG);
         return 1;
     } else {
         $this->error = @ldap_error($this->connection);
         dol_syslog(get_class($this) . "::modify failed: " . $this->error, LOG_ERR);
         return -1;
     }
 }
Example #2
1
 /**
  * Modifies an entry and return a true or false result
  *
  * @param   string  $dn         The DN which contains the attribute you want to modify
  * @param   string  $attribute  The attribute values you want to modify
  *
  * @return  mixed  result of comparison (true, false, -1 on error)
  *
  * @since   12.1
  */
 public function modify($dn, $attribute)
 {
     return @ldap_modify($this->_resource, $dn, $attribute);
 }
Example #3
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;
 }
Example #4
0
 /**
  * {@inheritdoc}
  */
 public function update(Entry $entry)
 {
     $con = $this->connection->getResource();
     if (!@ldap_modify($con, $entry->getDn(), $entry->getAttributes())) {
         throw new LdapException(sprintf('Could not update entry "%s": %s', $entry->getDn(), ldap_error($con)));
     }
 }
Example #5
0
 /**
  * The "U" in CRUD
  */
 function ldapUpdate($entry = null)
 {
     $entryDn = "uid=" . $entry['uid'] . "," . $this->baseDn;
     if ($entry) {
         if (@ldap_modify($this->ds, $entryDn, $entry)) {
             return true;
         }
     }
 }
Example #6
0
 public static function ativa($email)
 {
     $ldap = app('ldap');
     $base_dn = env('LDAP_BASE_DN');
     $dn = "uid={$email},ou=People,{$base_dn}";
     $info = ldap_modify($ldap, $dn, ['validado' => 'TRUE']);
     ldap_close($ldap);
     return $info;
 }
Example #7
0
function AssistedLDAPModify($ldapc, $moddn, $in)
{
    // Use these variables that are outside the function
    global $app_theme;
    // Modify the entry
    $r_mod = ldap_modify($ldapc, $moddn, $in);
    // Let's see if you could make it
    if (!$r_mod) {
        echo '<div class="error">' . _("An error has ocurred trying to modify entries on the LDAP database: ") . ldap_error($ldapc) . '.<br /><br /><a href="javascript:history.back(1);">' . _("Back") . '</a></div>';
        include "../themes/{$app_theme}/footer.php";
        die;
    }
    return $r_mod;
}
Example #8
0
 function putData($username, $data)
 {
     global $dsconnect, $host, $binduser, $bindpass, $basecn;
     if ($data != "") {
         $data .= "ga4php:";
     }
     // set this to default to begin with
     $tokendata = false;
     // we need to track the "first" blank attribute
     $blank_attr = false;
     // we search for a username that matches what we've been passed
     $sr = ldap_search($dsconnect, "{$basecn}", "samaccountname={$username}");
     $info = ldap_get_entries($dsconnect, $sr);
     $dn = $info[0]["distinguishedname"][0];
     //echo "<pre>";
     //print_r($info);
     //echo "</pre>";
     $attr_name = false;
     for ($i = 1; $i < 15; $i++) {
         $valname = "extensionattribute{$i}";
         if (isset($info[0]["{$valname}"][0])) {
             $val = $info[0]["{$valname}"][0];
             // we are looking for an extension attribute that has a start of "ga4php"
             if (preg_match('/^ga4php.*/', $val) > 0) {
                 $attr_name = $valname;
             }
         } else {
             if ($blank_attr == false) {
                 // this will cathc the first unset extension variable name, if we need it
                 $blank_attr = "{$valname}";
             }
         }
     }
     // if the attr_name is not set, we need to set $blank_attr
     if ($attr_name == false) {
         // we use $blank_attr
         error_log("setting for {$username}, {$blank_attr}");
         $infod["{$blank_attr}"][0] = "{$data}";
     } else {
         error_log("setting for {$username}, {$attr_name}");
         $infod["{$attr_name}"][0] = "{$data}";
     }
     error_log("att end of put data for {$dn}, {$infod}");
     return ldap_modify($dsconnect, $dn, $infod);
     // even simpler!
 }
Example #9
0
 public function updateUser($user)
 {
     if (!is_object($user) || !$user instanceof jAuthUserLDAP) {
         throw new jException('jelix~auth.ldap.object.user.unknown');
     }
     if (!($user->login != '')) {
         throw new jException('jelix~auth.ldap.user.login.unset');
     }
     $entries = $this->getAttributesLDAP($user, true);
     $connect = $this->_bindLdapUser();
     if ($connect === false) {
         return false;
     }
     $result = ldap_modify($connect, $this->_buildUserDn($user->login), $entries);
     ldap_close($connect);
     return $result;
 }
Example #10
0
/**
 * Add a note to the existing notes
 */
function ajax_addnote($dn, $note)
{
    global $conf;
    global $LDAP_CON;
    global $FIELDS;
    header('Content-Type: text/html; charset=utf-8');
    // fetch the existing note
    $result = ldap_search($LDAP_CON, $dn, '(objectClass=inetOrgPerson)', array($FIELDS['note']));
    if (ldap_count_entries($LDAP_CON, $result)) {
        $result = ldap_get_binentries($LDAP_CON, $result);
    }
    $note = $note . "\n\n" . $result[0][$FIELDS['note']][0];
    $note = preg_replace("!\n\n\n+!", "\n\n", $note);
    $entry[$FIELDS['note']] = $note;
    ldap_modify($LDAP_CON, $dn, $entry);
    require_once dirname(__FILE__) . '/inc/smarty/plugins/modifier.noteparser.php';
    print smarty_modifier_noteparser($note);
}
Example #11
0
function changePassword($username, $newpassword, $newpassword2)
{
    global $connection, $DN;
    if ($newpassword != $newpassword2) {
        return false;
    }
    $search = ldap_search($connection, $DN, "(uid=" . $username . ")", array("dn"));
    $ent = ldap_get_entries($connection, $search);
    if ($ent["count"] == 0) {
        return false;
    }
    $user_dn = $ent[0]['dn'];
    $new = array();
    $new['userPassword'] = $newpassword;
    if (ldap_modify($connection, $user_dn, $new)) {
        return true;
    } else {
        return false;
    }
}
Example #12
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;
     }
 }
Example #13
0
 /**
 * modify attributes of ldap entry
 *
 * @param string $dn DN of entry
 * @param array $attributes should follow the structure of ldap_add functions
 *   entry array: http://us.php.net/manual/en/function.ldap-add.php
      $attributes["attribute1"] = "value";
      $attributes["attribute2"][0] = "value1";
      $attributes["attribute2"][1] = "value2";
 
  @return TRUE on success FALSE on error
 */
 function modifyLdapEntry($dn, $attributes = array(), $old_attributes = FALSE)
 {
     $this->connectAndBindIfNotAlready();
     if (!$old_attributes) {
         $result = @ldap_read($this->connection, $dn, 'objectClass=*');
         if (!$result) {
             $error = "LDAP Server ldap_read(%dn) in LdapServer::modifyLdapEntry() Error Server ID = %sid, LDAP Err No: %ldap_errno LDAP Err Message: %ldap_err2str ";
             $tokens = array('%dn' => $dn, '%sid' => $this->sid, '%ldap_errno' => ldap_errno($this->connection), '%ldap_err2str' => ldap_err2str(ldap_errno($this->connection)));
             watchdog('ldap_server', $error, $tokens, WATCHDOG_ERROR);
             return FALSE;
         }
         $entries = ldap_get_entries($this->connection, $result);
         if (is_array($entries) && $entries['count'] == 1) {
             $old_attributes = $entries[0];
         }
     }
     $attributes = $this->removeUnchangedAttributes($attributes, $old_attributes);
     foreach ($attributes as $key => $cur_val) {
         $old_value = FALSE;
         $key_lcase = drupal_strtolower($key);
         if (isset($old_attributes[$key_lcase])) {
             if ($old_attributes[$key_lcase]['count'] == 1) {
                 $old_value = $old_attributes[$key_lcase][0];
             } else {
                 unset($old_attributes[$key_lcase]['count']);
                 $old_value = $old_attributes[$key_lcase];
             }
         }
         if ($cur_val == '' && $old_value != '') {
             // remove enpty attributes
             unset($attributes[$key]);
             $result = @ldap_mod_del($this->connection, $dn, array($key_lcase => $old_value));
             if (!$result) {
                 $error = "LDAP Server ldap_mod_del(%dn) in LdapServer::modifyLdapEntry() Error Server ID = %sid, LDAP Err No: %ldap_errno LDAP Err Message: %ldap_err2str ";
                 $tokens = array('%dn' => $dn, '%sid' => $this->sid, '%ldap_errno' => ldap_errno($this->connection), '%ldap_err2str' => ldap_err2str(ldap_errno($this->connection)));
                 watchdog('ldap_server', $error, $tokens, WATCHDOG_ERROR);
                 return FALSE;
             }
         } elseif (is_array($cur_val)) {
             foreach ($cur_val as $mv_key => $mv_cur_val) {
                 if ($mv_cur_val == '') {
                     unset($attributes[$key][$mv_key]);
                     // remove empty values in multivalues attributes
                 } else {
                     $attributes[$key][$mv_key] = $mv_cur_val;
                 }
             }
         }
     }
     if (count($attributes) > 0) {
         $result = @ldap_modify($this->connection, $dn, $attributes);
         if (!$result) {
             $error = "LDAP Server ldap_modify(%dn) in LdapServer::modifyLdapEntry() Error Server ID = %sid, LDAP Err No: %ldap_errno LDAP Err Message: %ldap_err2str ";
             $tokens = array('%dn' => $dn, '%sid' => $this->sid, '%ldap_errno' => ldap_errno($this->connection), '%ldap_err2str' => ldap_err2str(ldap_errno($this->connection)));
             watchdog('ldap_server', $error, $tokens, WATCHDOG_ERROR);
             return FALSE;
         }
     }
     return TRUE;
 }
Example #14
0
 function change_passwd($rdn, $pass, $new_pass)
 {
     $rdn = $this->search_user_rdn($rdn);
     $this->auth($rdn, $pass);
     $entry = array();
     $entry["userPassword"] = "******" . base64_encode(pack("H*", sha1($new_pass)));
     if (ldap_modify($this->conn, $rdn, $entry) === false) {
         throw new Xldap_Exception('Your password cannot be change, please contact the administrator');
     }
 }
Example #15
0
 /**
  * Modify a user
  * 
  * @param string $username The username to query
  * @param array $attributes The attributes to modify.  Note if you set the enabled attribute you must not specify any other attributes
  * @param bool $isGUID Is the username passed a GUID or a samAccountName
  * @return bool
  */
 public function modify($username, $attributes, $isGUID = false)
 {
     if ($username === NULL) {
         return "Missing compulsory field [username]";
     }
     if (array_key_exists("password", $attributes) && !$this->adldap->getUseSSL() && !$this->adldap->getUseTLS()) {
         throw new adLDAPException('SSL/TLS must be configured on your webserver and enabled in the class to set passwords.');
     }
     // Find the dn of the user
     $userDn = $this->dn($username, $isGUID);
     if ($userDn === false) {
         return false;
     }
     // Translate the update to the LDAP schema
     $mod = $this->adldap->adldap_schema($attributes);
     // Check to see if this is an enabled status update
     if (!$mod && !array_key_exists("enabled", $attributes)) {
         return false;
     }
     // Set the account control attribute (only if specified)
     if (array_key_exists("enabled", $attributes)) {
         if ($attributes["enabled"]) {
             $controlOptions = array("NORMAL_ACCOUNT");
         } else {
             $controlOptions = array("NORMAL_ACCOUNT", "ACCOUNTDISABLE");
         }
         $mod["userAccountControl"][0] = $this->accountControl($controlOptions);
     }
     // Do the update
     $result = @ldap_modify($this->adldap->getLdapConnection(), $userDn, $mod);
     if ($result == false) {
         return false;
     }
     return true;
 }
Example #16
0
 public static function modifyPassword($user, $password)
 {
     // create LDAP connection
     //
     $ldapConnectionConfig = Config::get('ldap.connections.' . App::environment());
     $ldapHost = $ldapConnectionConfig['host'];
     $ldapPort = $ldapConnectionConfig['port'];
     $ldapConnection = ldap_connect($ldapHost, $ldapPort);
     if ($ldapConnection) {
         // query LDAP for user info
         //
         ldap_set_option($ldapConnection, LDAP_OPT_PROTOCOL_VERSION, 3);
         $ldapUser = $ldapConnectionConfig['users']['password_set_user'];
         $ldapbind = ldap_bind($ldapConnection, $ldapUser['user'], $ldapUser['password']);
         $dn = 'swampUuid=' . $user->user_uid . ',ou=people,o=SWAMP,dc=cosalab,dc=org';
         $response = ldap_modify($ldapConnection, $dn, array('userPassword' => $password));
         // close LDAP connection
         //
         ldap_close($ldapConnection);
         // update user_account entry
         //
         $userAccount = UserAccount::where('user_uid', '=', $user->user_uid)->first();
         $userAccount->ldap_profile_update_date = gmdate('Y-m-d H:i:s');
         $userAccount->save();
         return $user;
     }
 }
Example #17
0
 /**
  * Changes userpassword in LDAP
  *
  * Called when the user password is updated. It assumes it is
  * called by an admin or that you've otherwise checked the user's
  * credentials
  *
  * @param  object  $user        User table object
  * @param  string  $newpassword Plaintext password (not crypted/md5'ed)
  * @return boolean result
  *
  */
 function user_update_password($user, $newpassword)
 {
     global $USER;
     $result = false;
     $username = $user->username;
     $extusername = core_text::convert($username, 'utf-8', $this->config->ldapencoding);
     $extpassword = core_text::convert($newpassword, 'utf-8', $this->config->ldapencoding);
     switch ($this->config->passtype) {
         case 'md5':
             $extpassword = '******' . base64_encode(pack('H*', md5($extpassword)));
             break;
         case 'sha1':
             $extpassword = '******' . base64_encode(pack('H*', sha1($extpassword)));
             break;
         case 'plaintext':
         default:
             break;
             // plaintext
     }
     $ldapconnection = $this->ldap_connect();
     $user_dn = $this->ldap_find_userdn($ldapconnection, $extusername);
     if (!$user_dn) {
         error_log($this->errorlogtag . get_string('nodnforusername', 'auth_ldap', $user->username));
         return false;
     }
     switch ($this->config->user_type) {
         case 'edir':
             // Change password
             $result = ldap_modify($ldapconnection, $user_dn, array('userPassword' => $extpassword));
             if (!$result) {
                 error_log($this->errorlogtag . get_string('updatepasserror', 'auth_ldap', array('errno' => ldap_errno($ldapconnection), 'errstring' => ldap_err2str(ldap_errno($ldapconnection)))));
             }
             // Update password expiration time, grace logins count
             $search_attribs = array($this->config->expireattr, 'passwordExpirationInterval', 'loginGraceLimit');
             $sr = ldap_read($ldapconnection, $user_dn, '(objectClass=*)', $search_attribs);
             if ($sr) {
                 $entry = ldap_get_entries_moodle($ldapconnection, $sr);
                 $info = array_change_key_case($entry[0], CASE_LOWER);
                 $newattrs = array();
                 if (!empty($info[$this->config->expireattr][0])) {
                     // Set expiration time only if passwordExpirationInterval is defined
                     if (!empty($info['passwordexpirationinterval'][0])) {
                         $expirationtime = time() + $info['passwordexpirationinterval'][0];
                         $ldapexpirationtime = $this->ldap_unix2expirationtime($expirationtime);
                         $newattrs['passwordExpirationTime'] = $ldapexpirationtime;
                     }
                     // Set gracelogin count
                     if (!empty($info['logingracelimit'][0])) {
                         $newattrs['loginGraceRemaining'] = $info['logingracelimit'][0];
                     }
                     // Store attribute changes in LDAP
                     $result = ldap_modify($ldapconnection, $user_dn, $newattrs);
                     if (!$result) {
                         error_log($this->errorlogtag . get_string('updatepasserrorexpiregrace', 'auth_ldap', array('errno' => ldap_errno($ldapconnection), 'errstring' => ldap_err2str(ldap_errno($ldapconnection)))));
                     }
                 }
             } else {
                 error_log($this->errorlogtag . get_string('updatepasserrorexpire', 'auth_ldap', array('errno' => ldap_errno($ldapconnection), 'errstring' => ldap_err2str(ldap_errno($ldapconnection)))));
             }
             break;
         case 'ad':
             // Passwords in Active Directory must be encoded as Unicode
             // strings (UCS-2 Little Endian format) and surrounded with
             // double quotes. See http://support.microsoft.com/?kbid=269190
             if (!function_exists('mb_convert_encoding')) {
                 error_log($this->errorlogtag . get_string('needmbstring', 'auth_ldap'));
                 return false;
             }
             $extpassword = mb_convert_encoding('"' . $extpassword . '"', "UCS-2LE", $this->config->ldapencoding);
             $result = ldap_modify($ldapconnection, $user_dn, array('unicodePwd' => $extpassword));
             if (!$result) {
                 error_log($this->errorlogtag . get_string('updatepasserror', 'auth_ldap', array('errno' => ldap_errno($ldapconnection), 'errstring' => ldap_err2str(ldap_errno($ldapconnection)))));
             }
             break;
         default:
             // Send LDAP the password in cleartext, it will md5 it itself
             $result = ldap_modify($ldapconnection, $user_dn, array('userPassword' => $extpassword));
             if (!$result) {
                 error_log($this->errorlogtag . get_string('updatepasserror', 'auth_ldap', array('errno' => ldap_errno($ldapconnection), 'errstring' => ldap_err2str(ldap_errno($ldapconnection)))));
             }
     }
     $this->ldap_close();
     return $result;
 }
Example #18
0
function changePassword($user, $oldPassword, $newPassword, $newPasswordCnf)
{
    global $message;
    global $message_css;
    $server = "openldap-server";
    $dn = "ou=product,ou=people,dc=zenchat,dc=ldap";
    error_reporting(0);
    ldap_connect($server);
    $con = ldap_connect($server);
    ldap_set_option($con, LDAP_OPT_PROTOCOL_VERSION, 3);
    // bind anon and find user by uid
    $user_search = ldap_search($con, $dn, "(|(uid={$user})(mail={$user}))");
    $user_get = ldap_get_entries($con, $user_search);
    $user_entry = ldap_first_entry($con, $user_search);
    $user_dn = ldap_get_dn($con, $user_entry);
    $user_id = $user_get[0]["uid"][0];
    $user_givenName = $user_get[0]["givenName"][0];
    $user_search_arry = array("*", "ou", "uid", "mail", "passwordRetryCount", "passwordhistory");
    $user_search_filter = "(|(uid={$user_id})(mail={$user}))";
    $user_search_opt = ldap_search($con, $user_dn, $user_search_filter, $user_search_arry);
    $user_get_opt = ldap_get_entries($con, $user_search_opt);
    $passwordRetryCount = $user_get_opt[0]["passwordRetryCount"][0];
    $passwordhistory = $user_get_opt[0]["passwordhistory"][0];
    //$message[] = "Username: "******"DN: " . $user_dn;
    //$message[] = "Current Pass: "******"New Pass: "******"Error E101 - Your Account is Locked Out!!!";
        return false;
    }
    if (ldap_bind($con, $user_dn, $oldPassword) === false) {
        $message[] = "Error E101 - Current Username or Password is wrong.";
        return false;
    }
    if ($newPassword != $newPasswordCnf) {
        $message[] = "Error E102 - Your New passwords do not match!";
        return false;
    }
    $encoded_newPassword = "******" . base64_encode(pack("H*", sha1($newPassword)));
    $history_arr = ldap_get_values($con, $user_dn, "passwordhistory");
    if ($history_arr) {
        $message[] = "Error E102 - Your new password matches one of the last 10 passwords that you used, you MUST come up with a new password.";
        return false;
    }
    if (strlen($newPassword) < 8) {
        $message[] = "Error E103 - Your new password is too short.<br/>Your password must be at least 8 characters long.";
        return false;
    }
    if (!preg_match("/[0-9]/", $newPassword)) {
        $message[] = "Error E104 - Your new password must contain at least one number.";
        return false;
    }
    if (!preg_match("/[a-zA-Z]/", $newPassword)) {
        $message[] = "Error E105 - Your new password must contain at least one letter.";
        return false;
    }
    if (!preg_match("/[A-Z]/", $newPassword)) {
        $message[] = "Error E106 - Your new password must contain at least one uppercase letter.";
        return false;
    }
    if (!preg_match("/[a-z]/", $newPassword)) {
        $message[] = "Error E107 - Your new password must contain at least one lowercase letter.";
        return false;
    }
    if (!$user_get) {
        $message[] = "Error E200 - Unable to connect to server, you may not change your password at this time, sorry.";
        return false;
    }
    $auth_entry = ldap_first_entry($con, $user_search);
    $mail_addresses = ldap_get_values($con, $auth_entry, "mail");
    $given_names = ldap_get_values($con, $auth_entry, "givenName");
    $password_history = ldap_get_values($con, $auth_entry, "passwordhistory");
    $mail_address = $mail_addresses[0];
    $first_name = $given_names[0];
    /* And Finally, Change the password */
    $entry = array();
    $entry["userPassword"] = "******";
    if (ldap_modify($con, $user_dn, $entry) === false) {
        $error = ldap_error($con);
        $errno = ldap_errno($con);
        $message[] = "E201 - Your password cannot be change, please contact the administrator.";
        $message[] = "{$errno} - {$error}";
    } else {
        $message_css = "yes";
        mail($mail_address, "Password change notice", "Dear {$first_name},\nYour password on http://support.example.com for account {$user_id} was just changed. If you did not make this change, please contact support@example.com.\nIf you were the one who changed your password, you may disregard this message.\n\nThanks\n-Connor");
        $message[] = "The password for {$user_id} has been changed.<br/>An informational email as been sent to {$mail_address}.<br/>Your new password is now fully Active.";
    }
}
Example #19
0
 /**
  * Mail enable a contact
  * Allows email to be sent to them through Exchange
  * 
  * @param string $distinguishedName The contact to mail enable
  * @param string $emailAddress The email address to allow emails to be sent through
  * @param string $mailNickname The mailnickname for the contact in Exchange.  If NULL this will be set to the display name
  * @return bool
  */
 public function contactMailEnable($distinguishedName, $emailAddress, $mailNickname = NULL)
 {
     if ($distinguishedName === NULL) {
         return "Missing compulsory field [distinguishedName]";
     }
     if ($emailAddress === NULL) {
         return "Missing compulsory field [emailAddress]";
     }
     if ($mailNickname !== NULL) {
         // Find the dn of the user
         $user = $this->adldap->contact()->info($distinguishedName, array("cn", "displayname"));
         if ($user[0]["displayname"] === NULL) {
             return false;
         }
         $mailNickname = $user[0]['displayname'][0];
     }
     $attributes = array("email" => $emailAddress, "contact_email" => "SMTP:" . $emailAddress, "exchange_proxyaddress" => "SMTP:" . $emailAddress, "exchange_mailnickname" => $mailNickname);
     // Translate the update to the LDAP schema
     $mod = $this->adldap->adldap_schema($attributes);
     // Check to see if this is an enabled status update
     if (!$mod) {
         return false;
     }
     // Do the update
     $result = ldap_modify($this->adldap->getLdapConnection(), $distinguishedName, $mod);
     if ($result == false) {
         return false;
     }
     return true;
 }
Example #20
0
 /**
  * Modifies the specified LDAP entry.
  *
  * @param string $dn
  * @param array  $entry
  *
  * @return bool
  */
 public function modify($dn, array $entry)
 {
     if ($this->suppressErrors) {
         return @ldap_modify($this->getConnection(), $dn, $entry);
     }
     return ldap_modify($this->getConnection(), $dn, $entry);
 }
 /**
  * Update user information in the external authentication database.
  * Return true if successful.
  *
  * @param User $user
  * @return bool
  * @access public
  */
 function updateExternalDB($user)
 {
     global $wgLDAPUpdateLDAP, $wgLDAPWikiDN, $wgLDAPWikiPassword;
     global $wgLDAPSearchStrings;
     if (!$wgLDAPUpdateLDAP) {
         return true;
     }
     $this->email = $user->getEmail();
     $this->realname = $user->getRealName();
     $this->nickname = $user->getOption('nickname');
     $this->language = $user->getOption('language');
     $tmpuserdn = $wgLDAPSearchStrings[$_SESSION['wsDomain']];
     $userdn = str_replace("USER-NAME", $user->getName(), $tmpuserdn);
     echo $userdn;
     $ldapconn = $this->connect();
     if ($ldapconn) {
         ldap_set_option($ldapconn, LDAP_OPT_PROTOCOL_VERSION, 3);
         $bind = @ldap_bind($ldapconn, $wgLDAPWikiDN, $wgLDAPWikiPassword);
         if (!$bind) {
             return false;
         }
         if ('' != $this->email) {
             $values["mail"] = $this->email;
         }
         if ('' != $this->nickname) {
             $values["displayname"] = $this->nickname;
         }
         if ('' != $this->realname) {
             $values["cn"] = $this->realname;
         }
         if ('' != $this->language) {
             $values["preferredlanguage"] = $this->language;
         }
         if (0 != sizeof($values) && ldap_modify($ldapconn, $userdn, $values)) {
             @ldap_unbind();
             return true;
         } else {
             @ldap_unbind();
             return false;
         }
     } else {
         return false;
     }
 }
Example #22
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;
 }
Example #23
0
 /**
  * Save the attributes that are in the map or extraVar array to ldap dir
  *
  * @return Boolean true if there are any modifications done
  */
 public function save()
 {
     $entries = $this->getAttributes();
     $link = $this->_ldapConn->getLink();
     $dn = $this->getDn();
     GO::debug($entries);
     return @ldap_modify($link, $dn, $entries);
 }
Example #24
0
 function ldap_modify($DN, $WhatChange, $NotRecode = false)
 {
     if (is_array($WhatChange)) {
         //echo $DN;
         $DN = iconv($GLOBALS['CHARSET_APP'], $GLOBALS['CHARSET_DATA'], $DN);
         foreach ($WhatChange as $key => $value) {
             if (is_array($value)) {
                 foreach ($value as $key1 => $value1) {
                     if ($value1 == "") {
                         unset($WhatChange[$key][$key1]);
                         //$KeyForDel[]=$key;
                     } else {
                         if ($NotRecode) {
                             $WhatChange[$key][$key1] = $value1;
                         } else {
                             $WhatChange[$key][$key1] = iconv($GLOBALS['CHARSET_APP'], $GLOBALS['CHARSET_DATA'], $value1);
                         }
                     }
                 }
             } else {
                 if ($WhatChange[$key] == "") {
                     unset($WhatChange[$key]);
                     $KeyForDel[] = $key;
                 } else {
                     if ($NotRecode) {
                         $WhatChange[$key] = $value;
                     } else {
                         $WhatChange[$key] = iconv($GLOBALS['CHARSET_APP'], $GLOBALS['CHARSET_DATA'], $value);
                     }
                 }
             }
         }
         if (is_array(@$KeyForDel)) {
             $LS = ldap_search($this->LC, $DN, "name=*", $KeyForDel);
             $Entries = ldap_get_entries($this->LC, $LS);
             foreach ($KeyForDel as $key => $value) {
                 if (@$Entries[0][$value][0] != "") {
                     $WhatDel[$value] = $Entries[0][$value][0];
                 }
             }
             if (is_array(@$WhatDel)) {
                 ldap_mod_del($this->LC, $DN, $WhatDel);
             }
         }
         //$LS=ldap_search($this->LC, $DN, $Filter, $Attributes);
         ldap_modify($this->LC, $DN, $WhatChange);
     }
 }
Example #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;
 }
Example #26
0
File: Ldap.php Project: Rovak/zf2
 /**
  * Update LDAP registry
  *
  * @param  string|Dn $dn
  * @param  array     $entry
  * @return Ldap Provides a fluid interface
  * @throws Exception\LdapException
  */
 public function update($dn, array $entry)
 {
     if (!$dn instanceof Dn) {
         $dn = Dn::factory($dn, null);
     }
     self::prepareLdapEntryArray($entry);
     $rdnParts = $dn->getRdn(Dn::ATTR_CASEFOLD_LOWER);
     foreach ($rdnParts as $key => $value) {
         $value = Dn::unescapeValue($value);
         if (array_key_exists($key, $entry) && !in_array($value, $entry[$key])) {
             $entry[$key] = array_merge(array($value), $entry[$key]);
         }
     }
     $adAttributes = array('distinguishedname', 'instancetype', 'name', 'objectcategory', 'objectguid', 'usnchanged', 'usncreated', 'whenchanged', 'whencreated');
     foreach ($adAttributes as $attr) {
         if (array_key_exists($attr, $entry)) {
             unset($entry[$attr]);
         }
     }
     if (count($entry) > 0) {
         ErrorHandler::start(E_WARNING);
         $isModified = ldap_modify($this->getResource(), $dn->toString(), $entry);
         ErrorHandler::stop();
         if ($isModified === false) {
             throw new Exception\LdapException($this, 'updating: ' . $dn->toString());
         }
     }
     return $this;
 }
Example #27
0
 /**
  * Update LDAP registry
  *
  * @param  string|Zend_Ldap_Dn $dn
  * @param  array               $entry
  * @return Zend_Ldap                  Provides a fluid interface
  * @throws Zend_Ldap_Exception
  */
 public function update($dn, array $entry)
 {
     if (!$dn instanceof Zend_Ldap_Dn) {
         $dn = Zend_Ldap_Dn::factory($dn, null);
     }
     self::prepareLdapEntryArray($entry);
     $rdnParts = $dn->getRdn(Zend_Ldap_Dn::ATTR_CASEFOLD_LOWER);
     foreach ($rdnParts as $key => $value) {
         $value = Zend_Ldap_Dn::unescapeValue($value);
         if (array_key_exists($key, $entry) && !in_array($value, $entry[$key])) {
             $entry[$key] = array_merge(array($value), $entry[$key]);
         }
     }
     $adAttributes = array('distinguishedname', 'instancetype', 'name', 'objectcategory', 'objectguid', 'usnchanged', 'usncreated', 'whenchanged', 'whencreated');
     foreach ($adAttributes as $attr) {
         if (array_key_exists($attr, $entry)) {
             unset($entry[$attr]);
         }
     }
     if (count($entry) > 0) {
         $isModified = @ldap_modify($this->getResource(), $dn->toString(), $entry);
         if ($isModified === false) {
             /**
              * @see Zend_Ldap_Exception
              */
             #require_once 'Zend/Ldap/Exception.php';
             throw new Zend_Ldap_Exception($this, 'updating: ' . $dn->toString());
         }
     }
     return $this;
 }
Example #28
0
 /**
  * @return bool
  */
 public function Modify($sModifyDn, $aModifyEntry)
 {
     $bResult = false;
     if (!empty($sModifyDn)) {
         if (!empty($this->sSearchDN)) {
             $sModifyDn = $sModifyDn . ',' . $this->sSearchDN;
         }
         CApi::Log('ldap_modify = ' . $sModifyDn);
         CApi::LogObject($aModifyEntry);
         $bResult = !!@ldap_modify($this->rLink, $sModifyDn, $aModifyEntry);
         $this->validateLdapErrorOnFalse($bResult);
     }
     return $bResult;
 }
Example #29
0
File: Ldap.php Project: gossi/ldap
 /**
  * Updates a LDAP entity at the given DN with the provided attributes.
  * 
  * @param String $dn The distinguished name.
  * @param array $attribs The new attributes.
  * @return boolean Returns true on success or false on failure.
  */
 public function modify($dn, $attribs)
 {
     return ldap_modify($this->conn, $dn, $attribs);
 }
 /**
  * Set the person details.
  * @param string $username
  * @param array $details
  * @param boolean $create
  */
 protected function setPerson($username, $password, $details, $create)
 {
     if (!$this->options['can_edit_user_detatils']) {
         return false;
     }
     if (!$username || !($ldap = $this->getConnection())) {
         return false;
     }
     $p_details = array();
     foreach ($details as $detail => $value) {
         if ($value === null) {
             continue;
         }
         if (!array_key_exists($detail, $this->options['p_details'])) {
             continue;
         }
         if ($create && (is_string($value) && strlen($value) == 0)) {
             $value = array();
             #want to know why am i doing this?
             #see: http://www.php.net/manual/en/function.ldap-modify.php#43216
             #and: http://www.php.net/manual/en/function.ldap-modify.php#38092
         }
         $p_details[$this->options['p_details'][$detail]] = $value;
     }
     if ($password) {
         $p_details[$this->options['password_field']] = $this->encryptPassword($password);
     }
     $dn = $this->getPeopleQry($username);
     if ($create) {
         $p_details['objectClass'] = $this->options['person_objectClass'];
         $p_details['uid'] = $username;
         if (!@ldap_add($ldap, $dn, $p_details)) {
             I2CE::raiseError("Could not create user {$username} with details at: " . $dn);
             return false;
         }
     } else {
         if (!@ldap_modify($ldap, $dn, $p_details)) {
             I2CE::raiseError("Could not modify user {$username} with details at: " . $dn);
             return false;
         }
     }
     return true;
 }