Example #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;
 }
Example #2
0
 public function add_login($ad, $grupo, $user, $bdn, $ous)
 {
     try {
         $ous = "CN=" . $grupo . "," . $ous;
         if (self::login($ad, "*****@*****.**", "Ac9a7533#Ed")) {
             ldap_set_option($ad, LDAP_OPT_PROTOCOL_VERSION, 3);
             ldap_set_option($ad, LDAP_OPT_REFERRALS, 0);
             $results = ldap_search($ad, $bdn, "(sAMAccountName={$user})", array("sn", "cn"), 0, 1);
             $entry = ldap_get_entries($ad, $results);
             $first = ldap_first_entry($ad, $results);
             $dn = ldap_get_dn($ad, $first);
             $data = $entry[0]['cn'][0];
             //$dn = str_replace($data, $user, $dn);
             //echo $dn;
             $user_array['member'] = $dn;
             //echo $ous;
             if (ldap_mod_add($ad, $ous, $user_array)) {
                 return 1;
             } else {
                 return 0;
             }
             //end if*/
         } else {
             return 0;
         }
         //end if
     } catch (Exception $e) {
         return 0;
     }
     //end try
 }
 /**
  * addAttribute
  *
  * Adds to an existing attribute without affecting existing values. Ex: adding to pdsRole without affecting existing roles.
  *
  *@param string $username
  *@param array $array
  *@return mixed
  */
 public function addAttribute($username, $array)
 {
     $immid = $this->getPortalAttribute('uid', $username);
     $immid = $immid[0];
     // array need to be keyed appropriately
     return ldap_mod_add($this->_portal_ds, "uid={$immid}, " . $this->_ldap['root'], $array);
 }
Example #4
0
 public static function updateProfile($numero_membre, $data)
 {
     $handle_ldap = self::initialize();
     if (self::$isDisabled) {
         self::$logger->info("Ldap is disabled, doing nothing.");
         return false;
     }
     $membreExists = @ldap_search($handle_ldap, "cn={$numero_membre}, " . self::$conf['basedn'], "objectclass=*", array("cn", "description", "mail"));
     if ($membreExists) {
         $personnes = ldap_get_entries($handle_ldap, $membreExists);
         $personne = $personnes[0];
         $dn = $personne["dn"];
         //self::$logger->debug(print_r($personne, true));
         $newEmail = self::$conf['defaultEmail'];
         if (isset($data['email']) && $data['email']) {
             $newEmail = $data['email'];
         }
         $hasLdapEmail = @is_array($personne["mail"]);
         $ldapData = ['mail' => [$newEmail]];
         if ($hasLdapEmail) {
             self::$logger->info("Replacing ldap email for #{$numero_membre}: {$newEmail}");
             ldap_mod_replace($handle_ldap, $dn, $ldapData);
         } else {
             self::$logger->info("Adding ldap email for #{$numero_membre}: {$newEmail}");
             ldap_mod_add($handle_ldap, $dn, $ldapData);
         }
         $err = ldap_error($handle_ldap);
         if ($err != "Success") {
             return $err;
         }
     } else {
         return "Membre not found in ldap repo: #{$numero_membre}";
     }
 }
Example #5
0
 public function addUser($dn)
 {
     $entry = array();
     $entry['member'] = $dn;
     if (ldap_mod_add($this->ldapconn, $this->dn, $entry) === false) {
         return false;
     } else {
         return true;
     }
 }
Example #6
0
function addUserToGroup($username, $group)
{
    $search = ldap_search($connection, $DN, "(uid=" . $username . ")");
    $ent = ldap_get_entries($connection, $search);
    if ($ent["count"] == 0) {
        return false;
    }
    $user_dn = $ent[0]['dn'];
    $member["member"] = $user_dn;
    return ldap_mod_add($connection, $group, $member);
}
Example #7
0
 function capture_mail($email)
 {
     global $ldap, $dn, $LDAPDATAFIELD;
     $data_new[$LDAPDATAFIELD][] = $email;
     if (ldap_mod_add($ldap, $dn, $data_new)) {
         print "<p class=\"message\">Your Email: {$email} , was successfuly  stored, Thank you! <br>";
         return true;
     } else {
         print "<p class=\"message\">Error setting your data, please try again later";
         return false;
     }
 }
Example #8
0
function add2OtherGroup($ds, $info, $infoGroupes)
{
    $erreur = false;
    for ($i = 1; $i < $infoGroupes['count']; $i++) {
        if (!empty($_POST[$infoGroupes[$i]['cn'][0]])) {
            $r = ldap_mod_add($ds, "cn=" . $infoGroupes[$i]['cn'][0] . ",ou=groups,dc=rBOX,dc=lan", $info);
            if (!$r) {
                if ($erreur) {
                    $grp .= ', ' . $infoGroupes[$i]['cn'][0];
                } else {
                    $erreur = true;
                    $grp = $infoGroupes[$i]['cn'][0];
                }
            }
        }
    }
    // On affiche un message d'erreur si l'utilisateur n'a pas pu être ajouté a un groupe
    if ($erreur) {
        echo '<p class="center red">L\'utilisateur n\'a pas pu être ajouté au(x) groupe(s) ' . $grp . '. Un message sera envoyé à l\'administrateur.</p>';
        return false;
    }
    return true;
}
Example #9
0
 /**
  * 	Add a LDAP attribute in entry
  *	Ldap object connect and bind must have been done
  *
  *	@param	string		$dn			DN entry key
  *	@param	array		$info		Attributes array
  *	@param	User		$user		Objet user that create
  *	@return	int						<0 if KO, >0 if OK
  */
 function addAttribute($dn, $info, $user)
 {
     global $conf;
     dol_syslog(get_class($this) . "::addAttribute 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_mod_add($this->connection, $dn, $info);
     if ($result) {
         dol_syslog(get_class($this) . "::add_attribute successfull", LOG_DEBUG);
         return 1;
     } else {
         $this->error = @ldap_error($this->connection);
         dol_syslog(get_class($this) . "::add_attribute failed: " . $this->error, LOG_ERR);
         return -1;
     }
 }
 /**
  * Add a contact to a group
  * 
  * @param string $group The group to add the contact to
  * @param string $contactDn The DN of the contact to add
  * @return bool
  */
 public function addContact($group, $contactDn)
 {
     // To add a contact we take the contact's DN
     // and add it using the full DN of the group
     // Find the group's dn
     $groupInfo = $this->info($group, array("cn"));
     if ($groupInfo[0]["dn"] === NULL) {
         return false;
     }
     $groupDn = $groupInfo[0]["dn"];
     $add = array();
     $add["member"] = $contactDn;
     $result = @ldap_mod_add($this->adldap->getLdapConnection(), $groupDn, $add);
     if ($result == false) {
         return false;
     }
     return true;
 }
Example #11
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;
 }
Example #12
0
 /**
  * Adds attributes to that entry.
  * 
  * @param array $attribs The new attributes.
  * @return boolean Returns true on success and false on failure.
  */
 public function add($attribs)
 {
     return ldap_mod_add($this->conn, $this->dn, $attribs);
 }
Example #13
0
 /**
  * Add an attribute to the given DN
  * Note: DN has to exist already
  *
  * @param   string  $dn     The DN of the entry to add the attribute
  * @param   array   $entry  An array of arrays with attributes to add
  *
  * @return  boolean   Result of operation
  *
  * @since   12.1
  */
 public function add($dn, array $entry)
 {
     return @ldap_mod_add($this->_resource, $dn, $entry);
 }
Example #14
0
 function addValuesToEnd($dn, $Attributes)
 {
     @ldap_mod_add($this->LC, $dn, $Attributes);
     //$LS=ldap_search($this->LC, $dn, "name=*", array_unique(array_keys($Attributes)));
     //$Entries=ldap_get_entries($this->LC, $LS);
 }
Example #15
0
 /**
  * Add attribute values to current attributes.
  *
  * @param string $dn
  * @param array  $entry
  *
  * @return bool
  */
 public function modAdd($dn, array $entry)
 {
     if ($this->suppressErrors) {
         return @ldap_mod_add($this->getConnection(), $dn, $entry);
     }
     return ldap_mod_add($this->getConnection(), $dn, $entry);
 }
        $modfi = 0;
    }
    # dann löschen
    if ($delfi == 1) {
        echo "L&ouml;schen: ";
        print_r($filedel);
        echo "<br>";
        if (ldap_mod_del($ds, $pxeDN, $filedel)) {
            $mesg = "PXE Dateiname(n) erfolgreich gel&ouml;scht<br><br>";
        } else {
            $mesg = "Fehler beim l&ouml;schen des PXE Dateinamens !<br><br>";
        }
        $delfi = 0;
    }
}
# PXE Dateiname neu anlegen
if ($newfilename == "") {
}
if ($newfilename != "") {
    echo "PXE Dateiname hinzuf&uuml;gen";
    $fileadd['filename'] = $newfilename;
    if (ldap_mod_add($ds, $pxeDN, $fileadd)) {
        $mesg = "PXE Dateiname <b>" . $newfilename . "</b> erfolgreich angelegt<br><br>";
    } else {
        $mesg = "Fehler beim anlegen des PXE Dateinamens " . $newfilename . " !<br><br>";
    }
}
#########################
$mesg .= "<br>Sie werden automatisch auf die vorherige Seite zur&uuml;ckgeleitet. <br>\t\t\t\t\n\t\t\tFalls nicht, klicken Sie hier <a href=" . $url . " style='publink'>back</a>";
redirect($seconds, $url, $mesg, $addSessionId = TRUE);
echo "</td></tr></table></body>\n</html>";
                        $add_r[$attrmap["{$key}"]][] = $val;
                    }
                }
            }
        }
        if (isset($del)) {
            if ($config[ldap_debug] == 'true') {
                print "<b>DEBUG(LDAP): ldap_mod_del(): DN='{$dn}'</b><br>\n";
                print "<b>DEBUG(LDAP): ldap_mod_del(): Data:";
                print_r($del);
                print "</b><br>\n";
            }
            @ldap_mod_del($ds, $dn, $del);
        }
        if (isset($add_r)) {
            if ($config[ldap_debug] == 'true') {
                print "<b>DEBUG(LDAP): ldap_mod_add(): DN='{$dn}'</b><br>\n";
                print "<b>DEBUG(LDAP): ldap_mod_add(): Data:";
                print_r($add_r);
                print "</b><br>\n";
            }
            @ldap_mod_add($ds, $dn, $add_r);
        }
    }
    if (@ldap_error($ds) == 'Success') {
        echo "<b>The changes were successfully commited to the directory</b><br>\n";
    } else {
        echo "<b>LDAP ERROR: " . ldap_error($ds) . "</b><br>\n";
    }
    @ldap_close($ds);
}
Example #18
0
 function addMemberToGroup($object_name, $uid)
 {
     $group_cn = "cn=" . $object_name . "," . $this->getLdapGroupDn();
     $members = $this->getLdapUserDn($uid);
     $group_info['member'] = $members;
     @ldap_mod_add($this->ldapResource, $group_cn, $group_info);
     if (@ldap_error($this->ldapResource) == "Success") {
         return true;
     } else {
         return false;
     }
 }
 function group_add_user($group, $user)
 {
     //adding a user is a bit fiddly, we need to get the full DN of the user
     //and add it using the full DN of the group
     //find the user's dn
     $user_info = $this->user_info($user, array("cn"));
     if ($user_info[0]["dn"] == NULL) {
         return false;
     }
     $user_dn = $user_info[0]["dn"];
     //find the group's dn
     $group_info = $this->group_info($group, array("cn"));
     if ($group_info[0]["dn"] == NULL) {
         return false;
     }
     $group_dn = $group_info[0]["dn"];
     $add = array();
     $add["member"] = $user_dn;
     $result = @ldap_mod_add($this->_conn, $group_dn, $add);
     if ($result == false) {
         return false;
     }
     return true;
 }
Example #20
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 #21
0
$dn = "cn=myNetCard,ou=Networks,dc=example,dc=com";
echo "\nModify " . $dn;
$entry["objectclass"][0] = "device";
$entry["objectclass"][1] = "ieee802Device";
// add an auxiliary objectclass
$entry["macAddress"][0] = "aa:bb:cc:dd:ee:ff";
ldap_modify($ds, $dn, $entry);
/* #### DELETE ENTRIE ### */
$dn = "cn=MyDeleter,ou=Networks,dc=example,dc=com";
echo "\nDelete " . $dn;
ldap_delete($ds, $dn);
/* #### MOD ADD ### */
$dn = "cn=groupname,cn=groups,dc=example,dc=com";
echo "\nModAdd " . $dn;
$entry['memberuid'] = "username";
ldap_mod_add($ds, $dn, $entry);
/* #### MOD DELETE ### */
$dn = "cn=groupname,cn=groups,dc=example,dc=com";
echo "\nModDel " . $dn;
$entry['memberuid'] = "username";
ldap_mod_del($ds, $dn, $entry);
/* #### MOD REPLACE ### */
$dn = "cn=groupname,cn=groups,dc=example,dc=com";
echo "\nModReplace " . $dn;
$entry['memberuid'] = "username";
ldap_mod_replace($ds, $dn, $entry);
/* ### SEARCH ### */
$dn = "o=My Company, c=USs";
echo "\nSearch " . $dn;
$filter = "(|(sn=jeantet)(givenname=jeantet*))";
$justthese = array("ou", "sn", "givenname", "mail");
Example #22
0
 /**
  * Add an address to Exchange
  * 
  * @param string $username The username of the user to add the Exchange account to
  * @param string $emailAddress The email address to add to this user
  * @param bool $default Make this email address the default address, this is a bit more intensive as we have to demote any existing default addresses
  * @param bool $isGUID Is the username passed a GUID or a samAccountName
  * @return bool
  */
 public function addAddress($username, $emailAddress, $default = FALSE, $isGUID = false)
 {
     if ($username === NULL) {
         return "Missing compulsory field [username]";
     }
     if ($emailAddress === NULL) {
         return "Missing compulsory fields [emailAddress]";
     }
     $proxyValue = 'smtp:';
     if ($default === true) {
         $proxyValue = 'SMTP:';
     }
     // Find the dn of the user
     $user = $this->adldap->user()->info($username, array("cn", "proxyaddresses"), $isGUID);
     if ($user[0]["dn"] === NULL) {
         return false;
     }
     $userDn = $user[0]["dn"];
     // We need to scan existing proxy addresses and demote the default one
     if (is_array($user[0]["proxyaddresses"]) && $default === true) {
         $modAddresses = array();
         for ($i = 0; $i < sizeof($user[0]['proxyaddresses']); $i++) {
             if (strstr($user[0]['proxyaddresses'][$i], 'SMTP:') !== false) {
                 $user[0]['proxyaddresses'][$i] = str_replace('SMTP:', 'smtp:', $user[0]['proxyaddresses'][$i]);
             }
             if ($user[0]['proxyaddresses'][$i] != '') {
                 $modAddresses['proxyAddresses'][$i] = $user[0]['proxyaddresses'][$i];
             }
         }
         $modAddresses['proxyAddresses'][sizeof($user[0]['proxyaddresses']) - 1] = 'SMTP:' . $emailAddress;
         $result = @ldap_mod_replace($this->adldap->getLdapConnection(), $userDn, $modAddresses);
         if ($result == false) {
             return false;
         }
         return true;
     } else {
         // We do not have to demote an email address from the default so we can just add the new proxy address
         $attributes['exchange_proxyaddress'] = $proxyValue . $emailAddress;
         // Translate the update to the LDAP schema
         $add = $this->adldap->adldap_schema($attributes);
         if (!$add) {
             return false;
         }
         // Do the update
         // Take out the @ to see any errors, usually this error might occur because the address already
         // exists in the list of proxyAddresses
         $result = @ldap_mod_add($this->adldap->getLdapConnection(), $userDn, $add);
         if ($result == false) {
             return false;
         }
         return true;
     }
 }
Example #23
0
 /**
  * NOT TESTED
  * add a member to a group
  *
  * @param string $ldap_user_dn as ldap dn
  * @param mixed $user
  *    - drupal user object (stdClass Object)
  *    - ldap entry of user (array) (with top level keys of 'dn', 'mail', 'sid' and 'attr' )
  *    - ldap dn of user (array)
  *    - drupal username of user (string)
  */
 public function groupAddMember($group_dn, $user)
 {
     $user_ldap_entry = $this->userUserToExistingLdapEntry($user);
     $result = FALSE;
     if ($user_ldap_entry && $this->groupGroupEntryMembershipsConfigured) {
         $add = array();
         $add[$this->groupMembershipsAttr] = $user_ldap_entry['dn'];
         $this->connectAndBindIfNotAlready();
         $result = @ldap_mod_add($this->connection, $group_dn, $add);
     }
     return $result;
 }
Example #24
0
 /**
  * Makes changes to a group
  *
  * @param   mixed   $group
  * @param   array   $members
  * @return  boolean
  */
 public static function changeGroupMemberships($group, $add, $delete)
 {
     $db = \App::get('db');
     if (empty($db)) {
         return false;
     }
     $conn = self::getLDO();
     if (empty($conn)) {
         return false;
     }
     $ldap_params = \Component::params('com_system');
     $hubLDAPBaseDN = $ldap_params->get('ldap_basedn', '');
     if (is_numeric($group) && $group >= 0) {
         $dn = 'ou=groups,' . $hubLDAPBaseDN;
         $filter = '(gidNumber=' . $group . ')';
     } else {
         $dn = "cn={$group},ou=groups," . $hubLDAPBaseDN;
         $filter = '(objectclass=*)';
     }
     $reqattr = array('gidNumber', 'cn');
     $entry = ldap_search($conn, $dn, $filter, $reqattr, 0, 1, 0);
     $count = ldap_count_entries($conn, $entry);
     // If there was a database entry, but there was no ldap entry, create the ldap entry
     if ($count <= 0) {
         return false;
     }
     $ldapinfo = null;
     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]) <= 2) {
                         $ldapinfo[$key] = $attr[$key][0];
                     } else {
                         $ldapinfo[$key] = $attr[$key];
                     }
                 } else {
                     $ldapinfo[$key] = null;
                 }
             }
         }
     }
     if (empty($ldapinfo)) {
         return false;
     }
     if (!empty($add)) {
         $add = array_map(array($db, "Quote"), $add);
         $addin = implode(",", $add);
         if (!empty($addin)) {
             $query = "SELECT username FROM #__users WHERE id IN ({$addin}) OR username IN ({$addin});";
             $db->setQuery($query);
             $add = $db->loadColumn();
         }
         $adds = array();
         foreach ($add as $memberUid) {
             $adds['memberUid'][] = $memberUid;
         }
         if (ldap_mod_add($conn, $dn, $adds) == false) {
             // if bulk add fails, try individual
             foreach ($add as $memberUid) {
                 ldap_mod_add($conn, $dn, array('memberUid' => $memberUid));
             }
         }
     }
     if (!empty($delete)) {
         $delete = array_map(array($db, "Quote"), $delete);
         $deletein = implode(",", $delete);
         if (!empty($deletein)) {
             $query = "SELECT username FROM #__users WHERE id IN ({$deletein}) OR username IN ({$deletein});";
             $db->setQuery($query);
             $delete = $db->loadColumn();
         }
         $deletes = array();
         foreach ($delete as $memberUid) {
             $deletes['memberUid'][] = $memberUid;
         }
         ldap_mod_del($conn, $dn, $deletes);
     }
 }
if (is_server_read_only($server_id)) {
    pla_error("You cannot perform updates while server is in read-only mode");
}
check_server_id($server_id) or pla_error("Bad server_id: " . htmlspecialchars($server_id));
have_auth_info($server_id) or pla_error("Not enough information to login to server. Please check your configuration.");
// special case for binary attributes (like jpegPhoto and userCertificate):
// we must go read the data from the file and override $val with the binary data
if ($is_binary_val) {
    $file = $_FILES['val']['tmp_name'];
    $f = fopen($file, 'r');
    $binary_data = fread($f, filesize($file));
    fclose($f);
    $val = $binary_data;
}
// Automagically hash new userPassword attributes according to the
// chosen in config.php.
if (0 == strcasecmp($attr, 'userpassword')) {
    if ($servers[$server_id]['default_hash'] != '') {
        $enc_type = $servers[$server_id]['default_hash'];
        $new_val = password_hash($new_val, $enc_type);
        $val = $new_val;
    }
}
$ds = pla_ldap_connect($server_id) or pla_error("Could not connect to LDAP server");
$new_entry = array($attr => $val);
$result = @ldap_mod_add($ds, $dn, $new_entry);
if ($result) {
    header("Location: edit.php?server_id={$server_id}&dn={$encoded_dn}&updated_attr={$encoded_attr}");
} else {
    pla_error("Failed to add the attribute.", ldap_error($ds), ldap_errno($ds));
}
Example #26
0
 /**
  * @param Object $object
  * @param string $action
  * @param array  $entry
  *
  * @return bool
  */
 public function modify(Object $object, $action, $entry)
 {
     switch ($action) {
         case 'add':
             @ldap_mod_add($this->server->getResource(), $object->getDistinguishedName(), $entry);
             break;
         case 'del':
             @ldap_mod_del($this->server->getResource(), $object->getDistinguishedName(), $entry);
             break;
         case 'replace':
             @ldap_mod_replace($this->server->getResource(), $object->getDistinguishedName(), $entry);
             break;
     }
     return true;
 }
 function addAttribute($dn, $attrib, $value)
 {
     $arr = array();
     $arr[$attrib] = $value;
     $status = ldap_mod_add($this->conn, $dn, $arr);
     if (!$status) {
         $status = ldap_error($this->conn);
     }
     return $status;
 }
Example #28
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;
 }
     //echo "array: ". print_r($info[0]) ."\n";
     if (in_array("jpegphoto", $info[0])) {
         echo "PHOTO OK!\n";
     } else {
         echo "PHOTO NOT FOUND! Adding photo... ";
         if (class_exists('Imagick')) {
             $im = new Imagick($file);
             $im->setImageOpacity(1.0);
             //$im->resizeImage(147,200,Imagick::FILTER_UNDEFINED,0.5,TRUE);
             //$im->setCompressionQuality(90);
             $im->setImageFormat('jpeg');
             $attrs['jpegphoto'] = $im->getImageBlob();
         } else {
             echo "ERROR!";
         }
         $ret1 = ldap_mod_add($ds, $info[0]["dn"], $attrs);
         if ($ret1) {
             echo "PHOTO CORRECTLY ADDED: {$ret1}\n";
         } else {
             echo "Error adding photo: {$ret1}" . ldap_error($ds) . " \n";
         }
     }
     /*
     for ($i=0; $i<$info["count"]; $i++  ) { 
     	echo "dn is: ". $info[$i]["dn"] ."\n"; 
     	echo "i:"+$i."\n";
     } *
     */
     break;
 default:
     echo "MULTIPLE RESULTS FOUND! {$file}\n";
         print_r($oldrbs);
         echo " with ";
         print_r($entryrbs);
         echo "<br>";
         if ($result = ldap_mod_replace($ds, $hostDN, $entryrbs)) {
             update_dhcpmtime(array());
             rbs_adjust_host($hostDN, $rbs);
             $mesg = "Remote Boot Service erfolgreich zu <b>" . $rbscn . " [Abt.: " . $rbsau . "]</b> ge&auml;ndert<br><br>";
         } else {
             $mesg = "Fehler beim &auml;ndern des Remote Boot Services zu <b>" . $rbscn . "</b>!<br><br>";
         }
     } else {
         echo "RBS add ";
         print_r($entryrbs);
         echo "<br>";
         if ($result = ldap_mod_add($ds, $hostDN, $entryrbs)) {
             update_dhcpmtime(array());
             rbs_adjust_host($hostDN, $rbs);
             $mesg = "Remote Boot Service erfolgreich zu <b>" . $rbscn . " [Abt.: " . $rbsau . "]</b> ge&auml;ndert<br><br>";
         } else {
             $mesg = "Fehler beim &auml;ndern des Remote Boot Services zu <b>" . $rbscn . "</b>!<br><br>";
         }
     }
 } else {
     $entryrbs['hlprbservice'] = array();
     $entryrbs['dhcpoptnext-server'] = array();
     $entryrbs['dhcpoptfilename'] = array();
     echo "RBS delete ";
     echo "<br>";
     if ($result = ldap_mod_del($ds, $hostDN, $entryrbs)) {
         update_dhcpmtime(array());