From 4d011b4174596129779c64104a77834a0a197086 Mon Sep 17 00:00:00 2001 From: "Paula V. Quispe" Date: Tue, 9 Jun 2015 16:14:01 -0400 Subject: [PATCH 01/11] PM-1060: Firt migration ldapAdvanced --- .../engine/classes/class.ldapAdvanced.php | 2963 +++++++++++++++++ .../methods/authSources/authSources_Ajax.php | 12 +- .../methods/authSources/authSources_New.php | 27 +- .../engine/methods/services/ldapadvanced.php | 651 ++++ .../ldapAdvanced/ldapAdvancedForm.js | 237 ++ .../ldapAdvanced/ldapAdvancedList.js | 486 +++ .../ldapAdvanced/ldapAdvancedSearch.js | 317 ++ .../engine/templates/ldapAdvanced/library.js | 15 + .../templates/ldapAdvanced/searchSummary.js | 180 + .../xmlform/ldapAdvanced/gridAttribute.xml | 11 + .../xmlform/ldapAdvanced/ldapAdvanced.xml | 11 + .../xmlform/ldapAdvanced/ldapAdvancedEdit.xml | 215 ++ .../xmlform/ldapAdvanced/ldapAdvancedFlag | 1 + 13 files changed, 5100 insertions(+), 26 deletions(-) create mode 100755 workflow/engine/classes/class.ldapAdvanced.php create mode 100755 workflow/engine/methods/services/ldapadvanced.php create mode 100755 workflow/engine/templates/ldapAdvanced/ldapAdvancedForm.js create mode 100755 workflow/engine/templates/ldapAdvanced/ldapAdvancedList.js create mode 100644 workflow/engine/templates/ldapAdvanced/ldapAdvancedSearch.js create mode 100755 workflow/engine/templates/ldapAdvanced/library.js create mode 100755 workflow/engine/templates/ldapAdvanced/searchSummary.js create mode 100755 workflow/engine/xmlform/ldapAdvanced/gridAttribute.xml create mode 100755 workflow/engine/xmlform/ldapAdvanced/ldapAdvanced.xml create mode 100755 workflow/engine/xmlform/ldapAdvanced/ldapAdvancedEdit.xml create mode 100755 workflow/engine/xmlform/ldapAdvanced/ldapAdvancedFlag diff --git a/workflow/engine/classes/class.ldapAdvanced.php b/workflow/engine/classes/class.ldapAdvanced.php new file mode 100755 index 000000000..7902e1101 --- /dev/null +++ b/workflow/engine/classes/class.ldapAdvanced.php @@ -0,0 +1,2963 @@ + "|(objectclass=inetorgperson)(objectclass=organizationalperson)(objectclass=person)(objectclass=user)", + "group" => "|(objectclass=posixgroup)(objectclass=group)(objectclass=groupofuniquenames)", + "department" => "|(objectclass=organizationalunit)" + ); + + private $arrayAttributes = array( + "ldap" => array("uid" => "uid", "member" => "memberuid"), //OpenLDAP + "ad" => array("uid" => "samaccountname", "member" => "member"), //Active Directory + "ds" => array("uid" => "uid", "member" => "uniquemember") //389 DS + ); + + private $arrayAttributesForUser = array("dn", "uid", "samaccountname", "givenname", "sn", "cn", "mail", "userprincipalname", "useraccountcontrol", "accountexpires", "manager"); + + private $frontEnd = false; + private $debug = false; + public $arrayAuthenticationSourceUsersByUid = array(); + public $arrayAuthenticationSourceUsersByUsername = array(); + public $arrayDepartmentUsersByUid = array(); + public $arrayDepartmentUsersByUsername = array(); + public $arrayGroupUsersByUid = array(); + public $arrayGroupUsersByUsername = array(); + + private $arrayDepartmentUserSynchronizedChecked = array(); + private $arrayUserUpdateChecked = array(); + + /** + * default constructor method + */ + public function __construct() + { + } + + /** + * Set front end flag + * + * @param bool $flag Flag + * + * return void + */ + public function setFrontEnd($flag) + { + try { + $this->frontEnd = $flag; + } catch (Exception $e) { + throw $e; + } + } + + /** + * Set debug + * + * @param bool $debug Flag for debug + * + * return void + */ + public function setDebug($debug) + { + try { + $this->debug = $debug; + } catch (Exception $e) { + throw $e; + } + } + + /** + * Set Users that was registered with this Authentication Source + * + * @param string $authenticationSourceUid UID of Authentication Source + * + * return void + */ + public function setArrayAuthenticationSourceUsers($authenticationSourceUid) + { + try { + $this->arrayAuthenticationSourceUsersByUid = array(); + $this->arrayAuthenticationSourceUsersByUsername = array(); + + //Set data + $criteria = new Criteria("rbac"); + + $criteria->addSelectColumn(RbacUsersPeer::USR_UID); + $criteria->addSelectColumn(RbacUsersPeer::USR_USERNAME); + $criteria->addSelectColumn(RbacUsersPeer::USR_AUTH_USER_DN); + $criteria->add(RbacUsersPeer::UID_AUTH_SOURCE, $authenticationSourceUid, Criteria::EQUAL); + $criteria->add(RbacUsersPeer::USR_AUTH_TYPE, "ldapadvanced", Criteria::EQUAL); + //$criteria->add(RbacUsersPeer::USR_STATUS, 1, Criteria::EQUAL); + + $rsCriteria = RbacUsersPeer::doSelectRS($criteria); + $rsCriteria->setFetchmode(\ResultSet::FETCHMODE_ASSOC); + + while ($rsCriteria->next()) { + $row = $rsCriteria->getRow(); + + $this->arrayAuthenticationSourceUsersByUid[$row["USR_UID"]] = $row; + $this->arrayAuthenticationSourceUsersByUsername[$row["USR_USERNAME"]] = $row; + } + } catch (Exception $e) { + throw $e; + } + } + + /** + * Set User to this Authentication Source + * + * @param string $userUid UID of User + * @param array $arrayUserLdap User LDAP data + * + * return void + */ + public function setArrayAuthenticationSourceUser($userUid, array $arrayUserLdap) + { + try { + $arrayUserData = array( + "USR_UID" => $userUid, + "USR_USERNAME" => $arrayUserLdap["sUsername"], + "USR_AUTH_USER_DN" => $arrayUserLdap["sDN"] + ); + + //Set data + $this->arrayAuthenticationSourceUsersByUid[$arrayUserData["USR_UID"]] = $arrayUserData; + $this->arrayAuthenticationSourceUsersByUsername[$arrayUserData["USR_USERNAME"]] = $arrayUserData; + } catch (Exception $e) { + throw $e; + } + } + + /** + * Set Users of the Department + * + * @param string $departmentUid UID of Department + * + * return void + */ + public function setArrayDepartmentUsers($departmentUid) + { + try { + $this->arrayDepartmentUsersByUid = array(); + $this->arrayDepartmentUsersByUsername = array(); + + //Set data + $criteria = new Criteria("workflow"); + + $criteria->addSelectColumn(UsersPeer::USR_UID); + $criteria->addSelectColumn(UsersPeer::USR_USERNAME); + $criteria->addSelectColumn(UsersPeer::USR_REPORTS_TO); + $criteria->add(UsersPeer::DEP_UID, $departmentUid, Criteria::EQUAL); + $criteria->add(UsersPeer::USR_STATUS, "CLOSED", Criteria::NOT_EQUAL); + + $rsCriteria = UsersPeer::doSelectRS($criteria); + $rsCriteria->setFetchmode(\ResultSet::FETCHMODE_ASSOC); + + while ($rsCriteria->next()) { + $row = $rsCriteria->getRow(); + + $this->arrayDepartmentUsersByUid[$row["USR_UID"]] = $row; + $this->arrayDepartmentUsersByUsername[$row["USR_USERNAME"]] = $row; + } + } catch (Exception $e) { + throw $e; + } + } + + /** + * Set Users of the Group + * + * @param string $groupUid UID of Group + * + * return void + */ + public function setArrayGroupUsers($groupUid) + { + try { + $this->arrayGroupUsersByUid = array(); + $this->arrayGroupUsersByUsername = array(); + + //Set data + $criteria = new Criteria("workflow"); + + $criteria->addSelectColumn(GroupUserPeer::GRP_UID); + $criteria->addSelectColumn(GroupUserPeer::USR_UID); + $criteria->addSelectColumn(UsersPeer::USR_USERNAME); + $criteria->addSelectColumn(UsersPeer::USR_REPORTS_TO); + $criteria->addJoin(GroupUserPeer::USR_UID, UsersPeer::USR_UID, Criteria::LEFT_JOIN); + $criteria->add(GroupUserPeer::GRP_UID, $groupUid, Criteria::EQUAL); + $criteria->add(UsersPeer::USR_STATUS, "CLOSED", Criteria::NOT_EQUAL); + + $rsCriteria = GroupUserPeer::doSelectRS($criteria); + $rsCriteria->setFetchmode(\ResultSet::FETCHMODE_ASSOC); + + while ($rsCriteria->next()) { + $row = $rsCriteria->getRow(); + + $this->arrayGroupUsersByUid[$row["USR_UID"]] = $row; + $this->arrayGroupUsersByUsername[$row["USR_USERNAME"]] = $row; + } + } catch (Exception $e) { + throw $e; + } + } + + /** + * Set data to array of Users synchronized (Department) + * + * @param array $arrayData Data + * + * return void + */ + public function setArrayDepartmentUserSynchronizedChecked(array $arrayData) + { + try { + $this->arrayDepartmentUserSynchronizedChecked = $arrayData; + } catch (Exception $e) { + throw $e; + } + } + + /** + * Set data to array of updated Users + * + * @param array $arrayData Data + * + * return void + */ + public function setArrayUserUpdateChecked(array $arrayData) + { + try { + $this->arrayUserUpdateChecked = $arrayData; + } catch (Exception $e) { + throw $e; + } + } + + /** + * This method gets the singleton Rbac instance. + * @return Object instance of the rbac class + */ + public function &getSingleton() + { + if (self::$instance == null) { + self::$instance = new RBAC(); + } + + return self::$instance; + } + + /** + * Progress bar + * + * @param int $total Total + * @param int $count Count + * + * return string Return a string that represent progress bar + */ + public function progressBar($total, $count) + { + try { + $p = (int)(($count * 100) / $total); + $n = (int)($p / 2); + + return "[" . str_repeat("|", $n) . str_repeat(" ", 50 - $n) . "] $p%"; + } catch (Exception $e) { + throw $e; + } + } + + /** + * Show front end + * + * @param string $option Option + * @param string $data Data string + * + * return void + */ + public function frontEndShow($option, $data = "") + { + try { + if (!$this->frontEnd) { + return; + } + + $numc = 100; + + switch ($option) { + case "BAR": + echo "\r" . "| " . $data . str_repeat(" ", $numc - 2 - strlen($data)); + break; + case "TEXT": + echo "\r" . "| " . $data . str_repeat(" ", $numc - 2 - strlen($data)) . "\n"; + break; + default: + //START, END + echo "\r" . "+" . str_repeat("-", $numc - 2) . "+" . "\n"; + break; + } + } catch (Exception $e) { + throw $e; + } + } + + /** + * Get valid characteres + * + * return array Return an array with valid characteres + */ + public function characters() + { + try { + $arrayCharacter = array(); + + for ($i = 33; $i <= 127; $i++) { + $char = trim(strtolower(chr($i))); + + if ($char != "") { + $arrayCharacter[$i] = $char; + } + } + + unset($arrayCharacter[33]); //! + unset($arrayCharacter[38]); //& + unset($arrayCharacter[40]); //( + unset($arrayCharacter[41]); //) + unset($arrayCharacter[42]); //* + unset($arrayCharacter[60]); //< + unset($arrayCharacter[61]); //= + unset($arrayCharacter[62]); //> + unset($arrayCharacter[124]); //| + unset($arrayCharacter[126]); //~ + unset($arrayCharacter[127]); //DEL + + //Return + return array_unique($arrayCharacter); + } catch (Exception $e) { + throw $e; + } + } + + /** + * Get User data, if Username was registered with this Authentication Source + * + * @param string $username Username + * + * return array Return User data, if Username was registered with this Authentication Source; empty data otherwise + */ + public function authenticationSourceGetUserDataIfUsernameExists($username) + { + try { + if (isset($this->arrayAuthenticationSourceUsersByUsername[$username])) { + return $this->arrayAuthenticationSourceUsersByUsername[$username]; + } + + return array(); + } catch (Exception $e) { + throw $e; + } + } + + /** + * Get User data, if Username exists in Department + * + * @param string $username Username + * + * return array Return User data, if Username exists in Department; empty data otherwise + */ + public function departmentGetUserDataIfUsernameExists($username) + { + try { + if (isset($this->arrayDepartmentUsersByUsername[$username])) { + return $this->arrayDepartmentUsersByUsername[$username]; + } + + return array(); + } catch (Exception $e) { + throw $e; + } + } + + /** + * Get User data, if Username exists in Group + * + * @param string $username Username + * + * return array Return User data, if Username exists in Group; empty data otherwise + */ + public function groupGetUserDataIfUsernameExists($username) + { + try { + if (isset($this->arrayGroupUsersByUsername[$username])) { + return $this->arrayGroupUsersByUsername[$username]; + } + + return array(); + } catch (Exception $e) { + throw $e; + } + } + + public function getFieldsForPageSetup() + { + return array(); + } + + /** + * add a line in the ldap log + * + * before the log was generated in shared/sites/ folder, but it was deprecated + * and now we are saving the log in shared/log the entry in the log file. + * @author Fernando Ontiveros Lira + * @param Object $_link ldap connection + * @param String $text + */ + public function log($link, $text) + { + //$serverAddr = $_SERVER["SERVER_ADDR"]; + $logFile = PATH_DATA . "log/ldapAdvanced.log"; + + if (!file_exists($logFile) || is_writable($logFile)) { + $fpt= fopen ($logFile, "a"); + $ldapErrorMsg = ""; + $ldapErrorNr = 0; + + if ($link != null) { + $ldapErrorNr = @ldap_errno($link); + + if ( $ldapErrorNr != 0 ) { + $ldapErrorMsg = @ldap_error($link); + $text = $ldapErrorMsg . " : " . $text; + } + } + + //log format: date hour ipaddress workspace ldapErrorNr + fwrite($fpt, sprintf("%s %s %s %s %s \n", date("Y-m-d H:i:s"), getenv("REMOTE_ADDR"), SYS_SYS, $ldapErrorNr, $text)); + fclose($fpt); + } else { + error_log ("file $logFile is not writable "); + } + } + + /** + * Add a debug line in the LDAP log + * + * @param string $text Text + * + * return void + */ + public function debugLog($text) + { + try { + if ($this->debug) { + $this->log(null, "DEBUG: $text"); + } + } catch (Exception $e) { + throw $e; + } + } + + /** + * This method generates the ldap connection bind and returns the link object + * for a determined authsource + * @author Fernando Ontiveros Lira + * @param Array $aAuthSource the authsource data + * @return Object A object with the resulting ldap bind + */ + public function ldapConnection($aAuthSource) + { + $pass = explode("_",$aAuthSource["AUTH_SOURCE_PASSWORD"]); + + foreach ($pass as $index => $value) { + if ($value == "2NnV3ujj3w") { + $aAuthSource["AUTH_SOURCE_PASSWORD"] = G::decrypt($pass[0],$aAuthSource["AUTH_SOURCE_SERVER_NAME"]); + } + } + + $ldapcnn = @ldap_connect($aAuthSource["AUTH_SOURCE_SERVER_NAME"], $aAuthSource["AUTH_SOURCE_PORT"]); + + $ldapServer = $aAuthSource["AUTH_SOURCE_SERVER_NAME"] . ":" . $aAuthSource["AUTH_SOURCE_PORT"] ; + + @ldap_set_option($ldapcnn, LDAP_OPT_PROTOCOL_VERSION, $aAuthSource["AUTH_SOURCE_VERSION"]); + //$this->log($ldapcnn, "ldap set Protocol Version " . $aAuthSource["AUTH_SOURCE_VERSION"]); + + @ldap_set_option($ldapcnn, LDAP_OPT_REFERRALS, 0); + //$this->log($ldapcnn, "ldap set option Referrals"); + + if (isset($aAuthSource["AUTH_SOURCE_ENABLED_TLS"]) && $aAuthSource["AUTH_SOURCE_ENABLED_TLS"]) { + @ldap_start_tls($ldapcnn); + $ldapServer = "TLS " . $ldapServer; + //$this->log($ldapcnn, "start tls"); + } + + if ($aAuthSource["AUTH_ANONYMOUS"] == "1") { + $bBind = @ldap_bind($ldapcnn); + $this->log($ldapcnn, "bind $ldapServer like anonymous user"); + } else { + $bBind = @ldap_bind($ldapcnn, $aAuthSource["AUTH_SOURCE_SEARCH_USER"], $aAuthSource["AUTH_SOURCE_PASSWORD"]); + $this->log($ldapcnn, "bind $ldapServer with user " . $aAuthSource["AUTH_SOURCE_SEARCH_USER"]); + } + + if (!$bBind) { + throw new Exception("Unable to bind to server: $ldapServer . " . "LDAP-Errno: " . ldap_errno($ldapcnn) . " : " . ldap_error($ldapcnn) . " \n"); + } + + return $ldapcnn; + } + + /** + * This method obtains the attributes of a ldap Connection passed as parameter + * @param Object $ldapcnn ldap connection + * @author Fernando Ontiveros Lira + * @param Object $oEntry Entry object + * @return Array attributes + */ + public function ldapGetAttributes($ldapcnn, $entry) + { + try { + $arrayAttributes = array(); + + $arrayAttributes["dn"] = @ldap_get_dn($ldapcnn, $entry); + + $arrayAux = @ldap_get_attributes($ldapcnn, $entry); + + for ($i = 0; $i <= $arrayAux["count"] - 1; $i++) { + $key = strtolower($arrayAux[$i]); + + switch ($arrayAux[$arrayAux[$i]]["count"]) { + case 0: + $arrayAttributes[$key] = ""; + break; + case 1: + $arrayAttributes[$key] = $arrayAux[$arrayAux[$i]][0]; + break; + default: + $arrayAttributes[$key] = $arrayAux[$arrayAux[$i]]; + + unset($arrayAttributes[$key]["count"]); + break; + } + } + + if (!isset($arrayAttributes["mail"]) && isset($arrayAttributes["userprincipalname"])) { + $arrayAttributes["mail"] = $arrayAttributes["userprincipalname"]; + } + + return $arrayAttributes; + } catch (Exception $e) { + throw $e; + } + } + + /** + * Get Users from Department (Search result identifier) + * + * @param resource $ldapcnn LDAP link identifier + * @param resource $searchResult Search result identifier + * @param string $option Option (GET, SYNCHRONIZE) + * @param string $dn DN + * @param string $uidUserIdentifier User identifier + * @param int $totalUser Total users + * @param int $countUser User counter + * @param array $arrayData Data + * + * return array Return an array data + */ + public function ldapGetUsersFromDepartmentSearchResult($ldapcnn, $searchResult, $option, $dn, $uidUserIdentifier, $totalUser, $countUser, array $arrayData) + { + try { + $this->debugLog("class.ldapAdvanced.php > function ldapGetUsersFromDepartmentSearchResult() > START"); + + if ($searchResult) { + $this->debugLog("class.ldapAdvanced.php > function ldapGetUsersFromDepartmentSearchResult() > ldap_list > OK"); + + $numEntries = @ldap_count_entries($ldapcnn, $searchResult); + + $this->debugLog("class.ldapAdvanced.php > function ldapGetUsersFromDepartmentSearchResult() > ldap_list > OK > \$numEntries ----> $numEntries"); + + $totalUser += $numEntries; + + if ($numEntries > 0) { + $this->log($ldapcnn, "Search $dn accounts with identifier = $uidUserIdentifier"); + + $entry = @ldap_first_entry($ldapcnn, $searchResult); + + do { + $arrayUserLdap = $this->ldapGetAttributes($ldapcnn, $entry); + + $username = (isset($arrayUserLdap[$uidUserIdentifier]))? $arrayUserLdap[$uidUserIdentifier] : ""; + + $countUser++; + + if ((is_array($username) && !empty($username)) || trim($username) != "") { + $arrayUserData = $this->getUserDataFromAttribute($username, $arrayUserLdap); + + if (!isset($this->arrayDepartmentUserSynchronizedChecked[$arrayUserData["sUsername"]])) { + $this->arrayDepartmentUserSynchronizedChecked[$arrayUserData["sUsername"]] = 1; + + switch ($option) { + case "GET": + $arrayData[] = $arrayUserData; + break; + case "SYNCHRONIZE": + $arrayData = $this->departmentSynchronizeUser("", $arrayUserData, $arrayData); + break; + } + } else { + $this->log($ldapcnn, "User is repeated: Username \"" . $arrayUserData["sUsername"] . "\", DN \"" . $arrayUserData["sDN"] . "\""); + } + } + + if ($option == "SYNCHRONIZE") { + //Progress bar + $this->frontEndShow("BAR", "Departments: " . $arrayData["i"] . "/" . $arrayData["n"] . " " . $this->progressBar($totalUser, $countUser)); + } + } while ($entry = @ldap_next_entry($ldapcnn, $entry)); + } + } + + $this->debugLog("class.ldapAdvanced.php > function ldapGetUsersFromDepartmentSearchResult() > END"); + + //Return + return array($totalUser, $countUser, $arrayData); + } catch (Exception $e) { + throw $e; + } + } + + /** + * Get Users from Department + * + * @param string $option Option (GET, SYNCHRONIZE) + * @param string $dn DN of Department + * @param array $arrayData Data + * + * return array Return an array with data Users or array data + */ + public function ldapGetUsersFromDepartment($option, $dn, array $arrayData = array()) + { + try { + $this->debugLog("class.ldapAdvanced.php > function ldapGetUsersFromDepartment() > START"); + $this->debugLog("class.ldapAdvanced.php > function ldapGetUsersFromDepartment() > \$dn ----> $dn"); + + $arrayUser = array(); + $totalUser = 0; + $countUser = 0; + + //Set variables + $dn = trim($dn); + $rbac = &RBAC::getSingleton(); + + if (is_null($rbac->authSourcesObj)) { + $rbac->authSourcesObj = new AuthenticationSource(); + } + + $arrayAuthenticationSourceData = $rbac->authSourcesObj->load($this->sAuthSource); + + $this->ldapcnn = $this->ldapConnection($arrayAuthenticationSourceData); + + $ldapcnn = $this->ldapcnn; + + //Get Users + $recordSize = 1000; + + $flagGetUsers = true; + + $flagLdapControlPagedResult = $arrayAuthenticationSourceData["AUTH_SOURCE_DATA"]["LDAP_TYPE"] == "ad" && function_exists("ldap_control_paged_result"); + $flagNextRecord = false; + + if (!isset($arrayAuthenticationSourceData["AUTH_SOURCE_DATA"]["AUTH_SOURCE_USERS_FILTER"])) { + $arrayAuthenticationSourceData["AUTH_SOURCE_DATA"]["AUTH_SOURCE_USERS_FILTER"] = ""; + } + + $uidUserIdentifier = (isset($arrayAuthenticationSourceData["AUTH_SOURCE_DATA"]["AUTH_SOURCE_IDENTIFIER_FOR_USER"]))? $arrayAuthenticationSourceData["AUTH_SOURCE_DATA"]["AUTH_SOURCE_IDENTIFIER_FOR_USER"] : "uid"; + + $filterUsers = trim($arrayAuthenticationSourceData["AUTH_SOURCE_DATA"]["AUTH_SOURCE_USERS_FILTER"]); + + $filter = ($filterUsers != "")? $filterUsers : "(" . $this->arrayObjectClassFilter["user"] . ")"; + + $this->debugLog("class.ldapAdvanced.php > function ldapGetUsersFromDepartment() > \$filter ----> $filter"); + + if ($flagLdapControlPagedResult) { + ldap_set_option($ldapcnn, LDAP_OPT_PROTOCOL_VERSION, 3); + + $cookie = ""; + } + + do { + if ($flagLdapControlPagedResult) { + ldap_control_paged_result($ldapcnn, $recordSize, true, $cookie); + } + + $searchResult = @ldap_list($ldapcnn, $dn, $filter, $this->arrayAttributesForUser); + //$searchResult = @ldap_search($ldapcnn, $dn, $filter, $this->arrayAttributesForUser); + + if ($error = @ldap_errno($ldapcnn)) { + $flagGetUsers = false; + } else { + $this->debugLog("class.ldapAdvanced.php > function ldapGetUsersFromDepartment() > ldap_list > OK"); + + switch ($option) { + case "GET": + list($totalUser, $countUser, $arrayUser) = $this->ldapGetUsersFromDepartmentSearchResult($ldapcnn, $searchResult, $option, $dn, $uidUserIdentifier, $totalUser, $countUser, $arrayUser); + break; + case "SYNCHRONIZE": + list($totalUser, $countUser, $arrayData) = $this->ldapGetUsersFromDepartmentSearchResult($ldapcnn, $searchResult, $option, $dn, $uidUserIdentifier, $totalUser, $countUser, $arrayData); + break; + } + } + + if ($flagLdapControlPagedResult) { + ldap_control_paged_result_response($ldapcnn, $searchResult, $cookie); + + $flagNextRecord = $cookie !== null && $cookie != ""; + } + } while ($flagLdapControlPagedResult && $flagNextRecord); + + //Get Users //2 + if (!$flagGetUsers) { + $this->debugLog("class.ldapAdvanced.php > function ldapGetUsersFromDepartment() > Search by characters > START"); + + foreach ($this->characters() as $value) { + $char = $value; + + $ldapcnn = $this->ldapConnection($arrayAuthenticationSourceData); + + $filter = ($filterUsers != "")? $filterUsers : "(" . $this->arrayObjectClassFilter["user"] . ")"; + $filter = "(&$filter($uidUserIdentifier=$char*))"; + + $this->debugLog("class.ldapAdvanced.php > function ldapGetUsersFromDepartment() > \$filter ----> $filter"); + + $searchResult = @ldap_list($ldapcnn, $dn, $filter, $this->arrayAttributesForUser); + //$searchResult = @ldap_search($ldapcnn, $dn, $filter, $this->arrayAttributesForUser); + + if ($error = @ldap_errno($ldapcnn)) { + // + $this->debugLog("class.ldapAdvanced.php > function ldapGetUsersFromDepartment() > ldap_list > ERROR > \$error ---->\n" . print_r($error, true)); + } else { + $this->debugLog("class.ldapAdvanced.php > function ldapGetUsersFromDepartment() > ldap_list > OK"); + + switch ($option) { + case "GET": + list($totalUser, $countUser, $arrayUser) = $this->ldapGetUsersFromDepartmentSearchResult($ldapcnn, $searchResult, $option, $dn, $uidUserIdentifier, $totalUser, $countUser, $arrayUser); + break; + case "SYNCHRONIZE": + list($totalUser, $countUser, $arrayData) = $this->ldapGetUsersFromDepartmentSearchResult($ldapcnn, $searchResult, $option, $dn, $uidUserIdentifier, $totalUser, $countUser, $arrayData); + break; + } + } + } + + $this->debugLog("class.ldapAdvanced.php > function ldapGetUsersFromDepartment() > Search by characters > END"); + } + + $this->log($ldapcnn, "Found $totalUser users in department $dn"); + + $this->debugLog("class.ldapAdvanced.php > function ldapGetUsersFromDepartment() > END"); + + //Return + switch ($option) { + case "GET": + return $arrayUser; + break; + case "SYNCHRONIZE": + return $arrayData; + break; + } + } catch (Exception $e) { + throw $e; + } + } + + /** + * Get Users from Group + * + * @param string $option Option (SYNCHRONIZE) + * @param array $arrayGroupData Group data + * @param array $arrayData Data + * + * return array Return array data + */ + public function ldapGetUsersFromGroup($option, array $arrayGroupData, array $arrayData = array()) + { + try { + $this->debugLog("class.ldapAdvanced.php > function ldapGetUsersFromGroup() > START"); + $this->debugLog("class.ldapAdvanced.php > function ldapGetUsersFromGroup() > \$arrayGroupData ---->\n" . print_r($arrayGroupData, true)); + + $totalUser = 0; + $countUser = 0; + + //Set variables + $dn = trim($arrayGroupData["GRP_LDAP_DN"]); + $rbac = &RBAC::getSingleton(); + + if (is_null($rbac->authSourcesObj)) { + $rbac->authSourcesObj = new AuthenticationSource(); + } + + $arrayAuthenticationSourceData = $rbac->authSourcesObj->load($this->sAuthSource); + + $this->ldapcnn = $this->ldapConnection($arrayAuthenticationSourceData); + + $ldapcnn = $this->ldapcnn; + + //Get Group members + $memberAttribute = $this->arrayAttributes[$arrayAuthenticationSourceData["AUTH_SOURCE_DATA"]["LDAP_TYPE"]]["member"]; + + $filter = "(" . $this->arrayObjectClassFilter["group"] . ")"; + + $this->debugLog("class.ldapAdvanced.php > function ldapGetUsersFromGroup() > \$filter ----> $filter"); + + $searchResult = @ldap_search($ldapcnn, $dn, $filter, array($memberAttribute)); + + if ($error = @ldap_errno($ldapcnn)) { + // + $this->debugLog("class.ldapAdvanced.php > function ldapGetUsersFromGroup() > ldap_search > ERROR > \$error ---->\n" . print_r($error, true)); + } else { + $this->debugLog("class.ldapAdvanced.php > function ldapGetUsersFromGroup() > ldap_search > OK1"); + + if ($searchResult) { + $this->debugLog("class.ldapAdvanced.php > function ldapGetUsersFromGroup() > ldap_search > OK2"); + + $numEntries = @ldap_count_entries($ldapcnn, $searchResult); + + $this->debugLog("class.ldapAdvanced.php > function ldapGetUsersFromGroup() > ldap_search > OK2 > \$numEntries ----> $numEntries"); + + if ($numEntries > 0) { + $entry = @ldap_first_entry($ldapcnn, $searchResult); + + $arrayGroupMemberLdap = $this->ldapGetAttributes($ldapcnn, $entry); + + if (isset($arrayGroupMemberLdap[$memberAttribute])) { + if (!is_array($arrayGroupMemberLdap[$memberAttribute])) { + $arrayGroupMemberLdap[$memberAttribute] = array($arrayGroupMemberLdap[$memberAttribute]); + } + + $totalUser = count($arrayGroupMemberLdap[$memberAttribute]); + + //Get Users + if (!isset($arrayAuthenticationSourceData["AUTH_SOURCE_DATA"]["AUTH_SOURCE_USERS_FILTER"])) { + $arrayAuthenticationSourceData["AUTH_SOURCE_DATA"]["AUTH_SOURCE_USERS_FILTER"] = ""; + } + + $uidUserIdentifier = (isset($arrayAuthenticationSourceData["AUTH_SOURCE_DATA"]["AUTH_SOURCE_IDENTIFIER_FOR_USER"]))? $arrayAuthenticationSourceData["AUTH_SOURCE_DATA"]["AUTH_SOURCE_IDENTIFIER_FOR_USER"] : "uid"; + + $filterUsers = trim($arrayAuthenticationSourceData["AUTH_SOURCE_DATA"]["AUTH_SOURCE_USERS_FILTER"]); + + $filter2 = ($filterUsers != "")? $filterUsers : "(" . $this->arrayObjectClassFilter["user"] . ")"; + + $this->debugLog("class.ldapAdvanced.php > function ldapGetUsersFromGroup() > ldap_search > OK2 > \$filter2 ----> $filter2"); + + $this->log($ldapcnn, "Search $dn accounts with identifier = $uidUserIdentifier"); + + foreach ($arrayGroupMemberLdap[$memberAttribute] as $value) { + $member = $value; //User DN + + $this->debugLog("class.ldapAdvanced.php > function ldapGetUsersFromGroup() > ldap_search > OK2 > foreach > \$member ----> $member"); + + //Synchronize User + $searchResult2 = @ldap_search($ldapcnn, $member, $filter2, $this->arrayAttributesForUser); + + if ($error = @ldap_errno($ldapcnn)) { + // + $this->debugLog("class.ldapAdvanced.php > function ldapGetUsersFromGroup() > ldap_search > OK2 > foreach > ldap_search > ERROR > \$error ---->\n" . print_r($error, true)); + } else { + $this->debugLog("class.ldapAdvanced.php > function ldapGetUsersFromGroup() > ldap_search > OK2 > foreach > ldap_search > OK1"); + + if ($searchResult2) { + $this->debugLog("class.ldapAdvanced.php > function ldapGetUsersFromGroup() > ldap_search > OK2 > foreach > ldap_search > OK2"); + + $numEntries2 = @ldap_count_entries($ldapcnn, $searchResult2); + + $this->debugLog("class.ldapAdvanced.php > function ldapGetUsersFromGroup() > ldap_search > OK2 > foreach > ldap_search > OK2 > \$numEntries2 ----> $numEntries2"); + + if ($numEntries2 > 0) { + $entry2 = @ldap_first_entry($ldapcnn, $searchResult2); + + $arrayUserLdap = $this->ldapGetAttributes($ldapcnn, $entry2); + + $username = (isset($arrayUserLdap[$uidUserIdentifier]))? $arrayUserLdap[$uidUserIdentifier] : ""; + + $countUser++; + + if ((is_array($username) && !empty($username)) || trim($username) != "") { + $arrayUserData = $this->getUserDataFromAttribute($username, $arrayUserLdap); + + $arrayData = $this->groupSynchronizeUser($arrayGroupData["GRP_UID"], $arrayUserData, $arrayData); + } + + //Progress bar + $this->frontEndShow("BAR", "Groups: " . $arrayData["i"] . "/" . $arrayData["n"] . " " . $this->progressBar($totalUser, $countUser)); + } + } + } + } + } + } + } + } + + $this->log($ldapcnn, "Found $totalUser users in group $dn"); + + $this->debugLog("class.ldapAdvanced.php > function ldapGetUsersFromGroup() > END"); + + //Return + return $arrayData; + } catch (Exception $e) { + throw $e; + } + } + + /** + * This method authentifies if a user has the RBAC_user privileges + * also verifies if the user has the rights to start an application + * + * @author Fernando Ontiveros Lira + * @access public + + * @param string $strUser UserId (user login) + * @param string $strPass Password + * @return + * -1: user doesn"t exists / no existe usuario + * -2: wrong password / password errado + * -3: inactive user / usuario inactivo + * -4: user due date / usuario vencido + * -5: connection error + * n : user uid / uid de usuario + */ + public function VerifyLogin($strUser, $strPass) + { + if (is_array($strUser)) { + $strUser = $strUser[0]; + } else { + $strUser = trim($strUser); + } + + if ( $strUser == "" ) { + return -1; + } + + if ( strlen( $strPass ) == 0) { + return -2; + } + + $ldapcnn = null; + + $validUserPass = 1; + + try { + $rbac = &RBAC::getSingleton(); + + if (is_null($rbac->authSourcesObj)) { + $rbac->authSourcesObj = new AuthenticationSource(); + } + + if ($rbac->userObj == null) { + $rbac->userObj = new RbacUsers(); + } + + $arrayAuthSource = $rbac->authSourcesObj->load($this->sAuthSource); + + $setAttributes = 0; + $attributeUserSet = array(); + + if (isset($arrayAuthSource["AUTH_SOURCE_DATA"]["AUTH_SOURCE_SHOWGRID"]) && + $arrayAuthSource["AUTH_SOURCE_DATA"]["AUTH_SOURCE_SHOWGRID"] == "on") { + + $setAttributes = 1; + + foreach ($arrayAuthSource["AUTH_SOURCE_DATA"]["AUTH_SOURCE_GRID_ATTRIBUTE"] as $value) { + $attributeUserSet[$value["attributeUser"]] = $value["attributeLdap"]; + } + } + + //Get UserName + $criteria = new Criteria("rbac"); + + $criteria->addSelectColumn(RbacUsersPeer::USR_USERNAME); + $criteria->addSelectColumn(RbacUsersPeer::USR_UID); + $criteria->add(RbacUsersPeer::UID_AUTH_SOURCE, $arrayAuthSource["AUTH_SOURCE_UID"]); + $criteria->add(RbacUsersPeer::USR_AUTH_USER_DN, $strUser); + $criteria->add(RbacUsersPeer::USR_USERNAME, "", Criteria::NOT_EQUAL); + + $rsCriteria = RbacUsersPeer::doSelectRS($criteria); + $rsCriteria->setFetchmode(ResultSet::FETCHMODE_ASSOC); + + $rsCriteria->next(); + $row = $rsCriteria->getRow(); + + $usrName = $row["USR_USERNAME"]; + $usrUid = $row["USR_UID"]; + + //Get the AuthSource properties + //Check if the dn in the database record matches with the dn for the ldap account + $verifiedUser = $this->searchUserByUid( + $usrName, + $arrayAuthSource["AUTH_SOURCE_DATA"]["AUTH_SOURCE_IDENTIFIER_FOR_USER"] + ); + + if (empty($verifiedUser) || trim($verifiedUser["sDN"]) == null) { + return -1; + } + + $userDn = $strUser; + + if ($verifiedUser["sDN"] != $strUser || $setAttributes==1) { + // if not Equals for that user uid + if (!class_exists("RbacUsers")) { + require_once(PATH_RBAC."model/RbacUsers.php"); + } + + $columnsWf = array(); + $con = Propel::getConnection(RbacUsersPeer::DATABASE_NAME); + // select set + $c1 = new Criteria("rbac"); + $c1->add(RbacUsersPeer::UID_AUTH_SOURCE, $arrayAuthSource["AUTH_SOURCE_UID"]); + $c1->add(RbacUsersPeer::USR_AUTH_USER_DN, $strUser); + // update set + $c2 = new Criteria("rbac"); + $c2->add(RbacUsersPeer::USR_AUTH_USER_DN, $verifiedUser["sDN"]); + + foreach ($attributeUserSet as $key => $value) { + eval('$flagExist = (defined("RbacUsersPeer::' . $key . '")) ? 1: 0;'); + if ($flagExist == 1) { + if ($key == "USR_STATUS") { + $evalValue = $verifiedUser[$key]; + + $statusValue = "0"; + + if (is_string($evalValue) && G::toUpper($evalValue) == "ACTIVE") { + $statusValue = "1"; + } + + if (is_bool($evalValue) && $evalValue == true) { + $statusValue = "1"; + } + + if ((is_float($evalValue) || is_int($evalValue) || is_integer($evalValue) || is_numeric($evalValue)) && (int)$evalValue != 0 && (int)$evalValue != 66050) { + $statusValue = "1"; + } + + $verifiedUser[$key] = $statusValue; + } + //req - accountexpires + if ($key =="USR_DUE_DATE") { + $verifiedUser[$key] = $this->convertDateADtoPM($verifiedUser[$key]); + } + //end + + eval('$c2->add(RbacUsersPeer::' . $key . ', $verifiedUser["' . $key . '"]);'); + } + } + + BasePeer::doUpdate($c1, $c2, $con); + + $columnsWf = array(); + + foreach ($attributeUserSet as $key => $value) { + if (isset($verifiedUser[$key])) { + if ($key == 'USR_STATUS') { + + $statusValue = 'INACTIVE'; + + if (is_string($evalValue) && G::toUpper($evalValue) == 'ACTIVE') { + $statusValue = 'ACTIVE'; + } + + if (is_bool($evalValue) && $evalValue == true) { + $statusValue = 'ACTIVE'; + } + + if ((is_float($evalValue) || is_int($evalValue) || is_integer($evalValue) || is_numeric($evalValue)) && (int)$evalValue != 0 && (int)$evalValue > 66000 || (int)$evalValue == 1) { + $statusValue = 'ACTIVE'; + } + + $verifiedUser[$key] = $statusValue; + } + + $columnsWf[$key] = $verifiedUser[$key]; + } + } + + $columnsWf['USR_UID'] = $usrUid; + + require_once 'classes/model/Users.php'; + + $oUser = new Users(); + $oUser->update($columnsWf); + $userDn = $verifiedUser["sDN"]; + } + + //Check ldap connection for user + $arrayAuthSource["AUTH_ANONYMOUS"] = "0"; + $arrayAuthSource["AUTH_SOURCE_SEARCH_USER"] = $userDn; + $arrayAuthSource["AUTH_SOURCE_PASSWORD"] = $strPass; + + $ldapcnn = $this->ldapConnection($arrayAuthSource); + $flagUpdate = false; + switch(ldap_errno($ldapcnn)) { + case '0x00': + $flagUpdate = true; + $statusRbac = 1; + $statusUser = 'ACTIVE'; + break; + case '0x34': + case '0x58': + case '0x5e': + //LDAP_UNAVAILABLE + //LDAP_USER_CANCELLED + //LDAP_NO_RESULTS_RETURNED + $flagUpdate = true; + $statusRbac = 0; + $statusUser = 'INACTIVE'; + break; + default: + break; + } + if ($flagUpdate) { + $con = Propel::getConnection(RbacUsersPeer::DATABASE_NAME); + // select set + $c1 = new Criteria("rbac"); + $c1->add(RbacUsersPeer::UID_AUTH_SOURCE, $arrayAuthSource["AUTH_SOURCE_UID"]); + $c1->add(RbacUsersPeer::USR_AUTH_USER_DN, $strUser); + // update set + $c2 = new Criteria("rbac"); + $c2->add(RbacUsersPeer::USR_AUTH_USER_DN, $verifiedUser["sDN"]); + $c2->add(RbacUsersPeer::USR_STATUS, $statusRbac); + BasePeer::doUpdate($c1, $c2, $con); + $columnsWf = array(); + $columnsWf['USR_UID'] = $usrUid; + $columnsWf['USR_STATUS'] = $statusUser; + $oUser = new Users(); + $oUser->update($columnsWf); + } + + $attributes = $arrayAuthSource["AUTH_SOURCE_DATA"]; + + if (!isset($attributes['AUTH_SOURCE_RETIRED_OU'])) { + $attributes ['AUTH_SOURCE_RETIRED_OU'] = ''; + } + + //Check if the user is in the terminated organizational unit + if ($this->userIsTerminated($usrName, $attributes["AUTH_SOURCE_RETIRED_OU"])) { + $this->deactivateUser($usrName); + $this->log($ldapcnn, "user $strUser is member of Remove OU, deactivating this user."); + + return -3; + } + $validUserPass = ldap_errno($ldapcnn) == 0; + } catch (Exception $e) { + $validUserPass = -5; + } + + if ( $validUserPass == 1 ) { + $this->log($ldapcnn, "sucessful login user " . $verifiedUser["sDN"]); + } else { + $this->log($ldapcnn, "failure authentication for user $strUser"); + } + + return $validUserPass ; + } + + /** + * Get data of a User from attribute + * + * @param mixed $username Username + * @param array $arrayAttributes Attributes + * + * return array Return an array with data User + */ + public function getUserDataFromAttribute($username, array $arrayAttributes) + { + try { + $keyMail = (isset($arrayAttributes["mail"]))? "mail" : ((isset($arrayAttributes["userprincipalname"]))? "userprincipalname" : "nomail"); + + return array( + "sUsername" => trim((is_array($username))? $username[0] : $username), + "sPassword" => trim((isset($arrayAttributes["userpassword"]))? ((is_array($arrayAttributes["userpassword"]))? $arrayAttributes["userpassword"][0] : $arrayAttributes["userpassword"]) : ""), + "sFullname" => trim((isset($arrayAttributes["cn"]))? ((is_array($arrayAttributes["cn"]))? $arrayAttributes["cn"][0] : $arrayAttributes["cn"]) : ""), + "sFirstname" => trim((isset($arrayAttributes["givenname"]))? ((is_array($arrayAttributes["givenname"]))? $arrayAttributes["givenname"][0] : $arrayAttributes["givenname"]) : ""), + "sLastname" => trim((isset($arrayAttributes["sn"]))? ((is_array($arrayAttributes["sn"]))? $arrayAttributes["sn"][0] : $arrayAttributes["sn"]) : ""), + "sEmail" => trim((isset($arrayAttributes[$keyMail]))? ((is_array($arrayAttributes[$keyMail]))? $arrayAttributes[$keyMail][0] : $arrayAttributes[$keyMail]) : ""), + "sDN" => trim($arrayAttributes["dn"]), + "sManagerDN" => trim((isset($arrayAttributes["manager"]))? ((is_array($arrayAttributes["manager"]))? $arrayAttributes["manager"][0] : $arrayAttributes["manager"]) : "") + ); + } catch (Exception $e) { + throw $e; + } + } + + /** + * This method searches for the users that has some attribute + * that matches the keyword. + * @param String $keyword search criteria + * @return array Users that match the search criteria + */ + public function searchUsers($keyword, $start = null, $limit = null) + { + $arrayUser = array(); + $totalUser = 0; + $countUser = 0; + + $keyword = trim(trim($keyword), "*"); + $keyword = ($keyword != "")? "*$keyword*" : "*"; + + $paged = !is_null($start) && !is_null($limit); + + $rbac = &RBAC::getSingleton(); + + if (is_null($rbac->authSourcesObj)) { + $rbac->authSourcesObj = new AuthenticationSource(); + } + + $arrayAuthenticationSourceData = $rbac->authSourcesObj->load($this->sAuthSource); + $attributeUserSet = array(); + $attributeSetAdd = array(); + + if (isset($arrayAuthenticationSourceData["AUTH_SOURCE_DATA"]["AUTH_SOURCE_GRID_ATTRIBUTE"]) + && !empty($arrayAuthenticationSourceData["AUTH_SOURCE_DATA"]["AUTH_SOURCE_GRID_ATTRIBUTE"]) + ) { + foreach ($arrayAuthenticationSourceData["AUTH_SOURCE_DATA"]["AUTH_SOURCE_GRID_ATTRIBUTE"] as $value) { + $attributeSetAdd[] = $value['attributeLdap']; + $attributeUserSet[$value['attributeUser']] = $value['attributeLdap']; + } + } + + if (is_null($this->ldapcnn)) { + $this->ldapcnn = $this->ldapConnection($arrayAuthenticationSourceData); + } + + $ldapcnn = $this->ldapcnn; + + //Get Users + if (!isset($arrayAuthenticationSourceData["AUTH_SOURCE_DATA"]["AUTH_SOURCE_USERS_FILTER"])) { + $arrayAuthenticationSourceData["AUTH_SOURCE_DATA"]["AUTH_SOURCE_USERS_FILTER"] = ""; + } + + $uidUserIdentifier = (isset($arrayAuthenticationSourceData["AUTH_SOURCE_DATA"]["AUTH_SOURCE_IDENTIFIER_FOR_USER"]))? $arrayAuthenticationSourceData["AUTH_SOURCE_DATA"]["AUTH_SOURCE_IDENTIFIER_FOR_USER"] : "uid"; + + $filterUsers = trim($arrayAuthenticationSourceData["AUTH_SOURCE_DATA"]["AUTH_SOURCE_USERS_FILTER"]); + + $filter = ($filterUsers != "")? $filterUsers : "(" . $this->arrayObjectClassFilter["user"] . ")"; + $filter = "(&$filter(|(dn=$keyword)(uid=$keyword)(samaccountname=$keyword)(givenname=$keyword)(sn=$keyword)(cn=$keyword)(mail=$keyword)(userprincipalname=$keyword)))"; + + $oSearch = @ldap_search($ldapcnn, $arrayAuthenticationSourceData["AUTH_SOURCE_BASE_DN"], $filter, array_merge($this->arrayAttributesForUser, $attributeSetAdd)); + + if ($oError = @ldap_errno($ldapcnn)) { + $this->log($ldapcnn, "Error in Search users"); + } else { + if ($oSearch) { + $entries = @ldap_count_entries($ldapcnn, $oSearch); + $totalUser = $entries; + + if ( $entries > 0) { + $oEntry = @ldap_first_entry($ldapcnn, $oSearch); + + $countEntries=0; + + $flagNextRecord = true; + + do { + $aAttr = $this->ldapGetAttributes($ldapcnn, $oEntry); + $sUsername = (isset($aAttr[$uidUserIdentifier]))? $aAttr[$uidUserIdentifier] : ""; + + if ((is_array($sUsername) && !empty($sUsername)) || trim($sUsername) != "") { + $countUser++; + + /*Active Directory userAccountControl Values + Normal Day to Day Values: + 512 - Enable Account + 514 - Disable account + 544 - Account Enabled - Require user to change password at first logon + 4096 - Workstation/server + 66048 - Enabled, password never expires + 66050 - Disabled, password never expires + 262656 - Smart Card Logon Required + 532480 - Domain controller + 1 - script + 2 - accountdisable + 8 - homedir_required + 16 - lockout + 32 - passwd_notreqd + 64 - passwd_cant_change + 128 - encrypted_text_pwd_allowed + 256 - temp_duplicate_account + 512 - normal_account + 2048 - interdomain_trust_account + 4096 - workstation_trust_account + 8192 - server_trust_account + 65536 - dont_expire_password + 131072 - mns_logon_account + 262144 - smartcard_required + 524288 - trusted_for_delegation + 1048576 - not_delegated + 2097152 - use_des_key_only + 4194304 - dont_req_preauth + 8388608 - password_expired + 16777216 - trusted_to_auth_for_delegation + */ + $userCountControl = ''; + //Active Directory, openLdap + if (isset($aAttr['useraccountcontrol'])) { + switch ($aAttr['useraccountcontrol']) { + case '512': + case '544': + case '66048': + case '66080': + $userCountControl = 'ACTIVE'; + break; + case '514': + case '546': + case '66050': + case '66082': + case '2': + case '16': + case '8388608': + default: + $userCountControl = 'INACTIVE'; + break; + } + } + //apache ldap + if (isset($aAttr['status'])) { + $userCountControl = strtoupper($aAttr['status']); + } + $aUserAttributes = array(); + foreach ($attributeUserSet as $key => $value) { + if ($key == 'USR_STATUS') { + $aUserAttributes[$key] = ($userCountControl != '') ? $userCountControl : 'ACTIVE'; + } elseif (isset($aAttr[ $value ])) { + $aUserAttributes[$key] = $aAttr[ $value ]; + } + } + + if ($paged) { + if ($countUser - 1 <= $start + $limit - 1) { + if ($start <= $countUser - 1) { + $arrayUser[] = array_merge($this->getUserDataFromAttribute($sUsername, $aAttr), $aUserAttributes); + } + } else { + $flagNextRecord = false; + } + } else { + $arrayUser[] = array_merge($this->getUserDataFromAttribute($sUsername, $aAttr), $aUserAttributes); + } + + $countEntries++; + } + } while (($oEntry = @ldap_next_entry($ldapcnn, $oEntry)) && $flagNextRecord); + } + } + /* + $sUsers = "found $countEntries users: "; + + foreach ($aUsers as $key => $val) { + $sUsers .= $val['sUsername'] . ' '; + } + + $this->log($ldapcnn, $sUsers); + */ + } + + //Return + return ($paged)? array("numRecTotal" => $totalUser, "data" => $arrayUser) : $arrayUser; + } + + /** + * This method search in the ldap/active directory source for an user using the UID, (samaccountname or uid ) + * the value should be in $aAuthSource['AUTH_SOURCE_DATA']['AUTH_SOURCE_IDENTIFIER_FOR_USER'] + * @param String $keyword The keyword in order to match the record with the identifier attribute + * @param String $identifier id identifier, this parameter is optional + * @return mixed if the user has been found or not + */ + public function searchUserByUid($keyword, $identifier = "") + { + try { + $arrayUserData = array(); + + //Set variables + $rbac = &RBAC::getSingleton(); + //$rbac->userObj = new RbacUsers(); + + if (is_null($rbac->authSourcesObj)) { + $rbac->authSourcesObj = new AuthenticationSource(); + } + + $arrayAuthenticationSourceData = $rbac->authSourcesObj->load($this->sAuthSource); + + if (is_null($this->ldapcnn)) { + $this->ldapcnn = $this->ldapConnection($arrayAuthenticationSourceData); + } + + $ldapcnn = $this->ldapcnn; + + //Get User + $attributeUserSet = array(); + $attributeSetAdd = array(); + + if (isset($arrayAuthenticationSourceData["AUTH_SOURCE_DATA"]["AUTH_SOURCE_GRID_ATTRIBUTE"]) + && !empty($arrayAuthenticationSourceData["AUTH_SOURCE_DATA"]["AUTH_SOURCE_GRID_ATTRIBUTE"]) + ) { + foreach ($arrayAuthenticationSourceData["AUTH_SOURCE_DATA"]["AUTH_SOURCE_GRID_ATTRIBUTE"] as $value) { + $attributeSetAdd[] = $value["attributeLdap"]; + $attributeUserSet[$value["attributeUser"]] = $value["attributeLdap"]; + } + } + + $uidUserIdentifier = (isset($arrayAuthenticationSourceData["AUTH_SOURCE_DATA"]["AUTH_SOURCE_IDENTIFIER_FOR_USER"]))? $arrayAuthenticationSourceData["AUTH_SOURCE_DATA"]["AUTH_SOURCE_IDENTIFIER_FOR_USER"] : "uid"; + + $filter2 = ""; + + if ($identifier != "" && $identifier != $uidUserIdentifier) { + $filter2 = "($identifier=$keyword)"; + } + + $filter = "(&(" . $this->arrayObjectClassFilter["user"] . ")(|($uidUserIdentifier=$keyword)$filter2))"; + + $searchResult = @ldap_search($ldapcnn, $arrayAuthenticationSourceData["AUTH_SOURCE_BASE_DN"], $filter, array_merge($this->arrayAttributesForUser, $attributeSetAdd)); + + if ($error = @ldap_errno($ldapcnn)) { + // + } else { + if ($searchResult) { + $numEntries = @ldap_count_entries($ldapcnn, $searchResult); + + if ($numEntries > 0) { + $entry = @ldap_first_entry($ldapcnn, $searchResult); + + $arrayUserLdap = $this->ldapGetAttributes($ldapcnn, $entry); + + $username = (isset($arrayUserLdap[$uidUserIdentifier]))? $arrayUserLdap[$uidUserIdentifier] : ""; + + if ((is_array($username) && !empty($username)) || trim($username) != "") { + $userCountControl = ""; + + //Active Directory, OpenLDAP + if (isset($arrayUserLdap["useraccountcontrol"])) { + switch ($arrayUserLdap["useraccountcontrol"]) { + case "512": + case "544": + case "66048": + case "66080": + $userCountControl = "ACTIVE"; + break; + case "514": + case "546": + case "66050": + case "66082": + case "2": + case "16": + case "8388608": + default: + $userCountControl = "INACTIVE"; + break; + } + } + + //Apache LDAP + if (isset($arrayUserLdap["status"])) { + $userCountControl = strtoupper($arrayUserLdap["status"]); + } + + $aUserAttributes = array(); + + foreach ($attributeUserSet as $key => $value) { + if ($key == "USR_STATUS") { + $aUserAttributes[$key] = ($userCountControl != "")? $userCountControl : "ACTIVE"; + } else { + if (isset($arrayUserLdap[$value])) { + $aUserAttributes[$key] = $arrayUserLdap[$value]; + } + } + } + + $arrayUserData = array_merge($this->getUserDataFromAttribute($username, $arrayUserLdap), $aUserAttributes); + } + } + } + } + + //Return + return $arrayUserData; + } catch (Exception $e) { + throw $e; + } + } + + public function automaticRegister($aAuthSource, $strUser, $strPass) + { + $rbac = &RBAC::getSingleton(); + + if ($rbac->userObj == null) { + $rbac->userObj = new RbacUsers(); + } + + if ($rbac->rolesObj == null) { + $rbac->rolesObj = new Roles(); + } + + $user = $this->searchUserByUid($strUser); + + $res = 0; + + if (!empty($user)) { + if ($this->VerifyLogin( $user['sUsername'], $strPass) === true) { + $res = 1; + } + + if ($res == 0 && $this->VerifyLogin( $user['sDN'], $strPass) === true) { + $res = 1; + } + } else { + return $res; + } + + if ($res == 0) { + $aAuthSource = $rbac->authSourcesObj->load($this->sAuthSource); + $aAttributes = array(); + + if (isset($aAuthSource['AUTH_SOURCE_DATA']['AUTH_SOURCE_GRID_ATTRIBUTE'])) { + $aAttributes = $aAuthSource['AUTH_SOURCE_DATA']['AUTH_SOURCE_GRID_ATTRIBUTE']; + } + + $aData = array(); + $aData['USR_USERNAME'] = $user['sUsername']; + $aData["USR_PASSWORD"] = "00000000000000000000000000000000"; + $aData['USR_FIRSTNAME'] = $user['sFirstname']; + $aData['USR_LASTNAME'] = $user['sLastname']; + $aData['USR_EMAIL'] = $user['sEmail']; + $aData['USR_DUE_DATE'] = date('Y-m-d', mktime(0, 0, 0, date('m'), date('d'), date('Y') + 2)); + $aData['USR_CREATE_DATE'] = date('Y-m-d H:i:s'); + $aData['USR_UPDATE_DATE'] = date('Y-m-d H:i:s'); + $aData['USR_BIRTHDAY'] = date('Y-m-d'); + $aData['USR_STATUS'] = (isset($user['USR_STATUS'])) ? (($user['USR_STATUS'] == 'ACTIVE') ? 1 : 0) : 1; + $aData['USR_AUTH_TYPE'] = strtolower($aAuthSource['AUTH_SOURCE_PROVIDER']); + $aData['UID_AUTH_SOURCE'] = $aAuthSource['AUTH_SOURCE_UID']; + $aData['USR_AUTH_USER_DN'] = $user['sDN']; + $aData['USR_ROLE'] = 'PROCESSMAKER_OPERATOR'; + + if (!empty($aAttributes)) { + foreach ($aAttributes as $value) { + if (isset( $user[$value['attributeUser']] )) { + $aData[$value['attributeUser']] = str_replace( "*", "'", $user[$value['attributeUser']] ); + if ($value['attributeUser'] == 'USR_STATUS') { + $evalValue = $aData[$value['attributeUser']]; + $statusValue = (isset($user['USR_STATUS'])) ? $user['USR_STATUS'] :'ACTIVE'; + $aData[$value['attributeUser']] = $statusValue; + } + } + } + } + + //req - accountexpires + if (isset($user["USR_DUE_DATE"]) && $user["USR_DUE_DATE"]!='' ) { + $aData["USR_DUE_DATE"] = $this->convertDateADtoPM($user["USR_DUE_DATE"]); + } + //end + + $sUserUID = $rbac->createUser($aData, 'PROCESSMAKER_OPERATOR'); + $aData['USR_UID'] = $sUserUID; + + require_once 'classes/model/Users.php'; + + $oUser = new Users(); + $aData['USR_STATUS'] = (isset($user['USR_STATUS'])) ? $user['USR_STATUS'] : 'ACTIVE'; + $oUser->create($aData); + $this->log(null, "Automatic Register for user $strUser "); + $res = 1; + } + + return $res; + } + + /** + * Get a deparment list + * @return + */ + public function searchDepartments() + { + if (!class_exists('RBAC')) { + G::LoadSystem('rbac'); + } + + $rbac = &RBAC::getSingleton(); + + if (is_null($rbac->authSourcesObj)) { + $rbac->authSourcesObj = new AuthenticationSource(); + } + + $aAuthSource = $rbac->authSourcesObj->load($this->sAuthSource); + + if (is_null($this->ldapcnn)) { + $this->ldapcnn = $this->ldapConnection($aAuthSource); + } + + $ldapcnn = $this->ldapcnn; + + $sFilter = "(" . $this->arrayObjectClassFilter["department"] . ")"; + + $this->log($ldapcnn, "search Departments with Filter: $sFilter"); + + $aDepts = array(); + $unitsBase = $this->custom_ldap_explode_dn($aAuthSource['AUTH_SOURCE_BASE_DN']); + $oSearch = @ldap_search($ldapcnn, $aAuthSource["AUTH_SOURCE_BASE_DN"], $sFilter, array("dn", "ou")); + + if ($oError = @ldap_errno($ldapcnn)) { + $this->log($ldapcnn, "Error in Search"); + return $aDepts; + } else { + if ($oSearch) { + //the first node is root + $node = array(); + $node['dn'] = $aAuthSource['AUTH_SOURCE_BASE_DN']; + $node['parent'] = ''; + $node['ou'] = 'ROOT'; + $node['users'] = '0'; + $aDepts[] = $node; + + //get departments from the ldap entries + if (@ldap_count_entries($ldapcnn, $oSearch) > 0) { + $oEntry = @ldap_first_entry($ldapcnn, $oSearch); + + do { + $aAttr = $this->ldapGetAttributes($ldapcnn, $oEntry); + $unitsEqual = $this->custom_ldap_explode_dn($aAttr['dn']); + + if ( count($unitsEqual ) == 1 && $unitsEqual[0] == '' ) { + continue; + } + + if (count($unitsEqual) > count($unitsBase)) { + unset($unitsEqual[0]); + } + + if ( isset( $aAttr['ou'] ) && !is_array($aAttr['ou']) ) { + $node = array(); + $node['dn'] = $aAttr['dn']; + $node['parent'] = isset ($unitsEqual[1]) ? implode(',', $unitsEqual) : ''; + $node['ou'] = trim($aAttr['ou']); + $node['users'] = '0'; + $aDepts[] = $node; + } + } while ($oEntry = @ldap_next_entry($ldapcnn, $oEntry)); + //$this->createDepartments ($aDepts); + } + } + + $sDeptos = ''; + + foreach ($aDepts as $dep) { + $sDeptos .= ' ' . $dep['ou']; + } + + $this->log($ldapcnn, "found ". count($aDepts) . " departments: $sDeptos"); + + return $aDepts; + } + } + + /** + * Get the Userlist from a department based on the name + * @param string $departmentName + * @return array + */ + public function getUsersFromDepartmentByName($departmentName) + { + $dFilter = "(&(" . $this->arrayObjectClassFilter["department"] . ")(ou=" . $departmentName . "))"; + + $aUsers = array(); + $rbac = &RBAC::getSingleton(); + //$rbac->userObj = new RbacUsers(); + $rbac->authSourcesObj = new AuthenticationSource(); + $aAuthSource = $rbac->authSourcesObj->load($this->sAuthSource); + + if (is_null($this->ldapcnn)) { + $this->ldapcnn = $this->ldapConnection($aAuthSource); + } + + $ldapcnn = $this->ldapcnn; + + $oSearch = @ldap_search($ldapcnn, $aAuthSource["AUTH_SOURCE_BASE_DN"], $dFilter, $this->arrayAttributesForUser); + + if ($oError = @ldap_errno($ldapcnn)) { + return $aUsers; + } else { + if ($oSearch) { + //get the departments from the ldap entries + if (@ldap_count_entries($ldapcnn, $oSearch) > 0) { + $oEntry = @ldap_first_entry($ldapcnn, $oSearch); + + do { + $aAttr = $this->ldapGetAttributes($ldapcnn, $oEntry); + $aUsers[] = $this->ldapGetUsersFromDepartment("GET", $aAttr["dn"]); + } while ($oEntry = @ldap_next_entry($ldapcnn, $oEntry)); + //$this->createDepartments ($aDepts); + } + } + return $aUsers; + } + } + + /** + * Check if the department exists and returns the PM UID + * @param $currentDN + * @return + */ + public function getDepUidIfExistsDN ($currentDN) + { + try { + $oCriteria = new Criteria('workflow'); + $oCriteria->add(DepartmentPeer::DEP_STATUS , 'ACTIVE' ); + $oCriteria->add(DepartmentPeer::DEP_LDAP_DN, $currentDN ); + + $oDataset = DepartmentPeer::doSelectRS($oCriteria); + $oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC); + + if ($oDataset->next()) { + $aRow = $oDataset->getRow(); + + return $aRow["DEP_UID"]; + } + + return ""; + } catch (Exception $e) { + return false; + } + } + + /** + * Get number of Users in each Department from the Database + * + * return array Return array with the number of Users in each Department from the Database + */ + public function departmentsGetNumberOfUsersFromDb() + { + try { + $arrayData = array(); + + //Get data + $criteria = new Criteria("workflow"); + + $criteria->addSelectColumn(UsersPeer::DEP_UID); + $criteria->addSelectColumn("COUNT(" . UsersPeer::DEP_UID . ") AS NUM_REC"); + $criteria->add(UsersPeer::USR_STATUS, "CLOSED", Criteria::NOT_EQUAL); + $criteria->add(UsersPeer::DEP_UID, "", Criteria::NOT_EQUAL); + $criteria->add(UsersPeer::DEP_UID, null, Criteria::ISNOTNULL); + $criteria->addGroupByColumn(UsersPeer::DEP_UID); + + $rsCriteria = UsersPeer::doSelectRS($criteria); + $rsCriteria->setFetchmode(ResultSet::FETCHMODE_ASSOC); + + while ($rsCriteria->next()) { + $row = $rsCriteria->getRow(); + + $arrayData[$row["DEP_UID"]] = $row["NUM_REC"]; + } + + //Return + return $arrayData; + } catch (Exception $e) { + throw $e; + } + } + + public function userIsTerminated($userUid, $sOuTerminated) + { + $terminated = false; + $aLdapUsers = $this->getUsersFromDepartmentByName($sOuTerminated); + + foreach ($aLdapUsers as $aLdapUser) { + if ($aLdapUser['sUsername'] == $userUid) { + $terminated = true; + break; + } + } + + return $terminated; + } + + /* activate an user previously deactivated + if user is now in another department, we need the second parameter, the depUid + + @param string $userUid + @param string optional department DN + @param string optional DepUid + */ + public function activateUser($userUid, $userDn = null, $depUid = null) + { + if (!class_exists('RbacUsers')) { + require_once(PATH_RBAC.'model/RbacUsers.php'); + } + + $con = Propel::getConnection(RbacUsersPeer::DATABASE_NAME); + // select set + $c1 = new Criteria('rbac'); + $c1->add(RbacUsersPeer::USR_UID, $userUid); + // update set + $c2 = new Criteria('rbac'); + $c2->add(RbacUsersPeer::USR_STATUS, '1'); + + if ($userDn != null) { + $c2->add(RbacUsersPeer::USR_AUTH_USER_DN, $userDn); + $c2->add(RbacUsersPeer::USR_AUTH_SUPERVISOR_DN, ''); + } + + BasePeer::doUpdate($c1, $c2, $con); + + if (!class_exists('Users')) { + require_once('classes/model/Users.php'); + } + + $con = Propel::getConnection(UsersPeer::DATABASE_NAME); + // select set + $c1 = new Criteria('workflow'); + $c1->add(UsersPeer::USR_UID, $userUid); + // update set + $c2 = new Criteria('workflow'); + $c2->add(UsersPeer::USR_STATUS, 'ACTIVE'); + + if ($depUid != null) { + $c2->add(UsersPeer::DEP_UID, $depUid); + } + + BasePeer::doUpdate($c1, $c2, $con); + } + + public function deactivateUser ($userUid) + { + if (!class_exists('RbacUsers')) { + require_once(PATH_RBAC.'model/RbacUsers.php'); + } + + $con = Propel::getConnection(RbacUsersPeer::DATABASE_NAME); + // select set + $c1 = new Criteria('rbac'); + $c1->add(RbacUsersPeer::USR_USERNAME, $userUid); + // update set + $c2 = new Criteria('rbac'); + $c2->add(RbacUsersPeer::USR_STATUS, '0'); + + BasePeer::doUpdate($c1, $c2, $con); + + if (!class_exists('Users')) { + require_once('classes/model/Users.php'); + } + + $con = Propel::getConnection(UsersPeer::DATABASE_NAME); + // select set + $c1 = new Criteria('workflow'); + $c1->add(UsersPeer::USR_USERNAME, $userUid); + // update set + $c2 = new Criteria('workflow'); + $c2->add(UsersPeer::USR_STATUS, 'INACTIVE'); + $c2->add(UsersPeer::DEP_UID, ''); + + BasePeer::doUpdate($c1, $c2, $con); + } + + public function getTerminatedOu() + { + if (trim($this->sAuthSource)!='') { + $rbac = &RBAC::getSingleton(); + $aAuthSource = $rbac->authSourcesObj->load($this->sAuthSource); + $attributes = $aAuthSource['AUTH_SOURCE_DATA']; + $this->sTerminatedOu = isset($attributes['AUTH_SOURCE_RETIRED_OU'])?$attributes['AUTH_SOURCE_RETIRED_OU']:''; + } + + return $this->sTerminatedOu; + } + + /** + get all authsource for this plugin ( ldapAdvanced plugin, because other authsources are not needed ) + this function is used only by cron + returns only AUTH_SOURCE_PROVIDER = ldapAdvanced + + @return array with authsources with type = ldap + */ + public function getAuthSources() + { + require_once(PATH_RBAC.'model/AuthenticationSource.php'); + + $oCriteria = new Criteria('rbac'); + $aAuthSources = array(); + + $oAuthSource = new AuthenticationSource(); + $oCriteria = $oAuthSource->getAllAuthSources(); + $oDataset = AuthenticationSourcePeer::doSelectRS($oCriteria); + $oDataset->setFetchmode(ResultSet::FETCHMODE_ASSOC); + + while ($oDataset->next()) { + $aRow = $oDataset->getRow(); + + if ($aRow['AUTH_SOURCE_PROVIDER'] == 'ldapAdvanced') { + $aRow["AUTH_SOURCE_DATA"] = ($aRow["AUTH_SOURCE_DATA"] != "")? unserialize($aRow["AUTH_SOURCE_DATA"]) : array(); + + $aAuthSources[] = $aRow; + } + } + + return $aAuthSources; + } + + /** + function to get departments from the array previously obtained from LDAP + we are calling registered departments + it is a recursive function, in the first call with an array with first top level departments from PM + then go thru all departments and obtain a list of departments already created in PM and pass that array + to next function to synchronize All users for each department + this function is used in cron only + + @param array departments obtained from LDAP/Active Directory + @param array of departments, first call have only top level departments + */ + public function getRegisteredDepartments(array $arrayLdapDepartment, array $arrayDbDepartment) + { + $aResult = array(); + + if (!empty($arrayLdapDepartment)) { + $arrayLdapDepartment[0]["ou"] = $arrayLdapDepartment[0]["ou"] . " " . $arrayLdapDepartment[0]["dn"]; //Discard ROOT + + foreach ($arrayLdapDepartment as $ldapDept) { + //$flagExists = false; + // + //foreach ($aResult as $value2) { + // $arrayDepartmentData = $value2; + // + // if ($arrayDepartmentData["DEP_LDAP_DN"] == $ldapDept["dn"]) { + // $flagExists = true; + // break; + // } + //} + // + //if ($flagExists) { + // continue; + //} + + foreach ($arrayDbDepartment as $department) { + if ($department["DEP_TITLE"] == $ldapDept["ou"] && $department["DEP_LDAP_DN"] == $ldapDept["dn"]) { + $aResult[] = $department; + break; + + //if ($department["HAS_CHILDREN"] != 0) { + // $aTempDepartments = $this->getDepartments($department["DEP_UID"]); + // $aTempRegistered = $this->getRegisteredDepartments($arrayLdapDepartment, $aTempDepartments); + // $aResult = array_merge($aResult, $aTempRegistered); + //} + } + } + } + } + + return $aResult; + } + + /** + select departments but it is not recursive, only returns departments in this level + @param string $DepParent the DEP_UID for parent department + */ + public function getDepartments($DepParent) + { + try { + $result = array(); + $criteria = new Criteria('workflow'); + + if (!empty($DepParent)) { + $criteria->add(DepartmentPeer::DEP_PARENT, $DepParent); + } + + $con = Propel::getConnection(DepartmentPeer::DATABASE_NAME); + $objects = DepartmentPeer::doSelect($criteria, $con); + + foreach ($objects as $oDepartment) { + $node = array(); + $node['DEP_UID'] = $oDepartment->getDepUid(); + $node['DEP_PARENT'] = $oDepartment->getDepParent(); + $node['DEP_TITLE'] = stripslashes($oDepartment->getDepTitle()); + $node['DEP_STATUS'] = $oDepartment->getDepStatus(); + $node['DEP_MANAGER'] = $oDepartment->getDepManager(); + $node['DEP_LDAP_DN'] = $oDepartment->getDepLdapDn(); + $node['DEP_LAST'] = 0; + + $criteriaCount = new Criteria('workflow'); + $criteriaCount->clearSelectColumns(); + $criteriaCount->addSelectColumn( 'COUNT(*)' ); + $criteriaCount->add(DepartmentPeer::DEP_PARENT, $oDepartment->getDepUid(), Criteria::EQUAL); + $rs = DepartmentPeer::doSelectRS($criteriaCount); + $rs->next(); + $row = $rs->getRow(); + $node['HAS_CHILDREN'] = $row[0]; + $result[] = $node; + } + + if ( count($result) >= 1 ) { + $result[ count($result) -1 ]['DEP_LAST'] = 1; + } + + return $result; + } catch (exception $e) { + throw $e; + } + } + + /** + function to get users from USERS table in wf_workflow and filter by department + this function is used in cron only + + @param string department UID ( DEP_UID value ) + @return array of users + */ + public function getUserFromPM($username) + { + try { + $criteria = new Criteria("workflow"); + + $criteria->addSelectColumn(UsersPeer::USR_UID); + $criteria->addSelectColumn(UsersPeer::USR_USERNAME); + $criteria->addSelectColumn(UsersPeer::DEP_UID); + $criteria->add(UsersPeer::USR_STATUS, "CLOSED", Criteria::NOT_EQUAL); + $criteria->add(UsersPeer::USR_USERNAME, $username, Criteria::EQUAL); + + $rsCriteria = UsersPeer::doSelectRS($criteria); + $rsCriteria->setFetchmode(ResultSet::FETCHMODE_ASSOC); + + if ($rsCriteria->next()) { + return $rsCriteria->getRow(); + } + + return array(); + } catch (Exception $e) { + throw $e; + } + } + + /** + get all user (UID, USERNAME) moved to Removed OU + this function is used in cron only + + @param array authSource row, in this fuction we are validating if Removed OU is defined or not + @return array of users + */ + public function getUsersFromRemovedOu($aAuthSource) + { + $aUsers = array(); //empty array is the default result + $attributes = $aAuthSource["AUTH_SOURCE_DATA"]; + $this->sTerminatedOu = isset($attributes['AUTH_SOURCE_RETIRED_OU'])? trim($attributes['AUTH_SOURCE_RETIRED_OU']) : ''; + + if ($this->sTerminatedOu == '' ) { + return $aUsers; + } + + return $this->getUsersFromDepartmentByName( $this->sTerminatedOu ); + } + + /** + set STATUS=0 for all users in the array $aUsers + this functin is used to deactivate an array of users ( usually used for Removed OU ) + this function is used in cron only + + @param array authSource row, in this fuction we are validating if Removed OU is defined or not + @return array of users + */ + public function deactiveArrayOfUsers($aUsers) + { + if (!class_exists('RbacUsers')) { + require_once(PATH_RBAC.'model/RbacUsers.php'); + } + + if (!class_exists('Users')) { + require_once('classes/model/Users.php'); + } + + $aUsrUid = array(); + + foreach ($aUsers as $key => $val) { + $aUsrUid[] = $val['sUsername']; + } + + $con = Propel::getConnection('rbac'); + // select set + $c1 = new Criteria('rbac'); + $c1->add(RbacUsersPeer::USR_USERNAME, $aUsrUid, Criteria::IN ); + $c1->add(RbacUsersPeer::USR_STATUS, 1 ); + // update set + $c2 = new Criteria('rbac'); + $c2->add(RbacUsersPeer::USR_STATUS, '0'); + BasePeer::doUpdate($c1, $c2, $con); + + $con = Propel::getConnection('workflow'); + // select set + $c1 = new Criteria('workflow'); + $c1->add(UsersPeer::USR_USERNAME, $aUsrUid, Criteria::IN ); + // update set + $c2 = new Criteria('workflow'); + $c2->add(UsersPeer::USR_STATUS, 'INACTIVE'); + $c2->add(UsersPeer::DEP_UID, ''); + + BasePeer::doUpdate($c1, $c2, $con); + + return true; + } + + /** + creates an users using the data send in the array $aUsers + and then add the user to specific department + this function is used in cron only + + @param array $aUser info taken from ldap + @param string $depUid the department UID + @return boolean + */ + public function createUserAndActivate($aUser, $depUid) + { + $rbac = &RBAC::getSingleton(); + + if ($rbac->userObj == null) { + $rbac->userObj = new RbacUsers(); + } + + if ($rbac->rolesObj == null) { + $rbac->rolesObj = new Roles(); + } + + if ($rbac->usersRolesObj == null) { + $rbac->usersRolesObj = new UsersRoles(); + } + + $sUsername = $aUser['sUsername']; + $sFullname = $aUser['sFullname']; + $sFirstname = $aUser['sFirstname']; + $sLastname = $aUser['sLastname']; + $sEmail = $aUser['sEmail']; + $sDn = $aUser['sDN']; + + $aData = array(); + $aData['USR_USERNAME'] = $sUsername; + $aData["USR_PASSWORD"] = "00000000000000000000000000000000"; + $aData['USR_FIRSTNAME'] = $sFirstname; + $aData['USR_LASTNAME'] = $sLastname; + $aData['USR_EMAIL'] = $sEmail; + $aData['USR_DUE_DATE'] = date('Y-m-d', mktime(0, 0, 0, date('m'), date('d'), date('Y') + 2)); + $aData['USR_CREATE_DATE'] = date('Y-m-d H:i:s'); + $aData['USR_UPDATE_DATE'] = date('Y-m-d H:i:s'); + $aData['USR_BIRTHDAY'] = date('Y-m-d'); + $aData['USR_STATUS'] = 1; + $aData['USR_AUTH_TYPE'] = 'ldapadvanced'; + $aData['UID_AUTH_SOURCE'] = $this->sAuthSource; + $aData['USR_AUTH_USER_DN'] = $sDn; + + $sUserUID = $rbac->createUser($aData, "PROCESSMAKER_OPERATOR"); + + $aData['USR_STATUS'] = 'ACTIVE'; + $aData['USR_UID'] = $sUserUID; + $aData['DEP_UID'] = $depUid; + $aData['USR_ROLE'] = 'PROCESSMAKER_OPERATOR'; + + require_once 'classes/model/Users.php'; + + $oUser = new Users(); + $oUser->create($aData); + + return $sUserUID; + } + + public function synchronizeManagers($managersHierarchy) + { + require_once 'classes/model/RbacUsers.php'; + + try { + foreach ($managersHierarchy as $managerDN => $subordinates) { + $criteria = new Criteria('rbac'); + $criteria->addSelectColumn('*'); + $criteria->add(RbacUsersPeer::USR_AUTH_USER_DN, $managerDN); + $dataset = RbacUsersPeer::doSelectRS($criteria); + $dataset->setFetchmode(ResultSet::FETCHMODE_ASSOC); + + if ($dataset->next()) { + $row = $dataset->getRow(); + $criteriaSet = new Criteria('workflow'); + $criteriaSet->add(UsersPeer::USR_REPORTS_TO, $row['USR_UID']); + $criteriaWhere = new Criteria('workflow'); + $criteriaWhere->add(UsersPeer::USR_UID, $subordinates, Criteria::IN); + BasePeer::doUpdate($criteriaWhere, $criteriaSet, Propel::getConnection('workflow')); + } + } + } catch (Exception $error) { + $this->log($this->ldapcnn, $error->getMessage()); + } + } + + public function clearManager($usersUIDs) + { + try { + $criteriaSet = new Criteria('workflow'); + $criteriaSet->add(UsersPeer::USR_REPORTS_TO, ''); + $criteriaWhere = new Criteria('workflow'); + $criteriaWhere->add(UsersPeer::USR_UID, $usersUIDs, Criteria::IN); + BasePeer::doUpdate($criteriaWhere, $criteriaSet, Propel::getConnection('workflow')); + } catch (Exception $error) { + $this->log($this->ldapcnn, $error->getMessage()); + } + } + + /** + * Get a group list + * @return + */ + public function searchGroups() + { + if (!class_exists('RBAC')) { + G::LoadSystem('rbac' ); + } + + $rbac = &RBAC::getSingleton(); + + if (is_null($rbac->authSourcesObj)) { + $rbac->authSourcesObj = new AuthenticationSource(); + } + + $aAuthSource = $rbac->authSourcesObj->load($this->sAuthSource); + + if (is_null($this->ldapcnn)) { + $this->ldapcnn = $this->ldapConnection($aAuthSource); + } + + $ldapcnn = $this->ldapcnn; + + $filter = "(" . $this->arrayObjectClassFilter["group"] . ")"; + + $this->log($ldapcnn, "search groups with Filter: $filter"); + + $aGroups = array(); + $searchResult = @ldap_search($ldapcnn, $aAuthSource["AUTH_SOURCE_BASE_DN"], $filter, array("dn", "cn")); + + if ($oError = @ldap_errno($ldapcnn)) { + $this->log($ldapcnn, "Error in Search"); + + return $aGroups; + } else { + if ($searchResult) { + //the first node is root + $node = array(); + /*$node['dn'] = $aAuthSource['AUTH_SOURCE_BASE_DN']; + $node['parent'] = ''; + $node['cn'] = 'ROOT'; + $node['users'] = '0'; + $aGroups[] = $node;*/ + + //get groups from the ldap entries + $numEntries = @ldap_count_entries($ldapcnn, $searchResult); + + if ($numEntries > 0) { + $entry = @ldap_first_entry($ldapcnn, $searchResult); + + do { + $aAttr = $this->ldapGetAttributes($ldapcnn, $entry); + + if ( isset( $aAttr['cn'] ) && !is_array($aAttr['cn']) ) { + $node = array(); + $node['dn'] = $aAttr['dn']; + $node['cn'] = trim($aAttr['cn']); + $node['users'] = '0'; + $aGroups[] = $node; + } + } while ($entry = @ldap_next_entry($ldapcnn, $entry)); + } + } + + $sGroups = ''; + + foreach ($aGroups as $group) { + $sGroups .= ' ' . $group['cn']; + } + + $this->log($ldapcnn, "found ". count($aGroups) . " groups: $sGroups"); + + return $aGroups; + } + } + + /** + * Check if the group exists and returns the PM UID + * @param $currentDN + * @return + */ + + public function getGrpUidIfExistsDN($currentDN) + { + try { + $criteria = new Criteria('workflow'); + $criteria->add(GroupwfPeer::GRP_STATUS , 'ACTIVE'); + $criteria->add(GroupwfPeer::GRP_LDAP_DN, $currentDN); + $dataset = GroupwfPeer::doSelectRS($criteria); + $dataset->setFetchmode(ResultSet::FETCHMODE_ASSOC); + + if ($dataset->next()) { + $row = $dataset->getRow(); + + return $row['GRP_UID']; + } + + return ""; + } catch (Exception $e) { + return false; + } + } + + /** + * Get number of Users in each Group from the Database + * + * return array Return array with the number of Users in each Group from the Database + */ + public function groupsGetNumberOfUsersFromDb() + { + try { + $arrayData = array(); + + //Get data + $criteria = new Criteria("workflow"); + + $criteria->addSelectColumn(GroupUserPeer::GRP_UID); + $criteria->addSelectColumn("COUNT(" . GroupUserPeer::GRP_UID . ") AS NUM_REC"); + $criteria->addJoin(GroupUserPeer::USR_UID, UsersPeer::USR_UID, Criteria::LEFT_JOIN); + $criteria->add(UsersPeer::USR_STATUS, "CLOSED", Criteria::NOT_EQUAL); + $criteria->addGroupByColumn(GroupUserPeer::GRP_UID); + + $rsCriteria = GroupUserPeer::doSelectRS($criteria); + $rsCriteria->setFetchmode(ResultSet::FETCHMODE_ASSOC); + + while ($rsCriteria->next()) { + $row = $rsCriteria->getRow(); + + $arrayData[$row["GRP_UID"]] = $row["NUM_REC"]; + } + + //Return + return $arrayData; + } catch (Exception $e) { + throw $e; + } + } + + /** + select groups but it is not recursive, only returns groups in this level + */ + public function getGroups() + { + try { + $result = array(); + $criteria = new Criteria('workflow'); + $con = Propel::getConnection(GroupwfPeer::DATABASE_NAME); + $objects = GroupwfPeer::doSelect($criteria, $con); + + foreach ($objects as $oGroup) { + $node = array(); + $node['GRP_UID'] = $oGroup->getGrpUid(); + $node['GRP_TITLE'] = stripslashes($oGroup->getGrpTitle()); + $node['GRP_STATUS'] = $oGroup->getGrpStatus(); + $node['GRP_LDAP_DN'] = $oGroup->getGrpLdapDn(); + $result[] = $node; + } + + return $result; + } catch (exception $e) { + throw $e; + } + } + + /** + function to get groups from the array previously obtained from LDAP + we are calling registered groups + it is a recursive function, in the first call with an array with first top level groups from PM + then go thru all groups and obtain a list of groups already created in PM and pass that array + to next function to synchronize All users for each group + this function is used in cron only + + @param array groups obtained from LDAP/Active Directory + @param array of groups, first call have only top level groups + */ + public function getRegisteredGroups(array $arrayLdapGroup, array $arrayDbGroup) + { + $aResult = array(); + + if (!empty($arrayLdapGroup)) { + foreach ($arrayLdapGroup as $ldapGroup) { + foreach ($arrayDbGroup as $group) { + if ($group["GRP_TITLE"] == $ldapGroup["cn"] && $group["GRP_LDAP_DN"] == $ldapGroup["dn"]) { + $aResult[] = $group; + } + } + } + } + + return $aResult; + } + + /** + * Convert 18-digit LDAP timestamps to format PM + * + * @author Ronald Escobar + * @param Date | $dateAD | Date of AD ('Windows NT time format' and 'Win32 FILETIME or SYSTEMTIME') + * @param Date | $datePM | Date of PM + */ + public function convertDateADtoPM($dateAD) + { + //date_default_timezone_set('America/New_York'); + $unixTimestamp = ($dateAD / 10000000) - 11644560000; + $datePM = date('Y-m-d', mktime(0, 0, 0, date('m'), '01', date('Y') + 2));//(date('Y') + 10)."-12-01"; + if ($unixTimestamp >0) { + $dateAux = date("Y-m-d", $unixTimestamp); + $yearAux = date("Y", $unixTimestamp); + if (strlen(trim($yearAux)) <= 4) { + $datePM = $dateAux; + } + } + return $datePM; + } + + public function custom_ldap_explode_dn($dn) + { + $dn = trim($dn, ','); + $result = ldap_explode_dn($dn, 0); + + if (is_array($result)) { + unset($result['count']); + + foreach ($result as $key => $value) { + $result[$key] = addcslashes(preg_replace("/\\\([0-9A-Fa-f]{2})/e", "''.chr(hexdec('\\1')).''", $value), '<>,"'); + } + } + + return $result; + } + + /** + * Synchronize User for this Department + * + * @param string $departmentUid UID of Department + * @param array $arrayUserLdap User LDAP data + * @param array $arrayData Data + * + * return array Return data + */ + public function departmentSynchronizeUser($departmentUid, array $arrayUserLdap, array $arrayData) + { + try { + $this->debugLog("class.ldapAdvanced.php > function departmentSynchronizeUser() > START"); + $this->debugLog("class.ldapAdvanced.php > function departmentSynchronizeUser() > \$arrayUserLdap[sUsername] ----> " . $arrayUserLdap["sUsername"]); + + $userUid = ""; + $found = false; + + $arrayUserData = $this->departmentGetUserDataIfUsernameExists($arrayUserLdap["sUsername"]); + + if (!empty($arrayUserData)) { + //User already exists in this department and there is nothing to do + //User already exists + $userUid = $arrayUserData["USR_UID"]; + $found = true; + + $arrayData["already"]++; + $arrayData["alreadyUsers"] .= $arrayUserData["USR_USERNAME"] . " "; + } + + if (!$found) { + //If user DO NOT exists in this department.. do: + //If exists with another AuthSource -> impossible + //If exists in another department, but in PM and for this authsource, we need to move it + + //$arrayNewUserData = $this->searchUserByUid($arrayUserLdap["sUsername"]); + $arrayNewUserData = $arrayUserLdap; + + $arrayAux = $this->custom_ldap_explode_dn($arrayNewUserData["sDN"]); + array_shift($arrayAux); + + $departmentUid = $this->getDepUidIfExistsDN(implode(",", $arrayAux)); //Check if exists the Department DN in DB + + $this->debugLog("class.ldapAdvanced.php > function departmentSynchronizeUser() > \$departmentUid ----> $departmentUid"); + + if ($departmentUid != "") { + $arrayUserData = $this->authenticationSourceGetUserDataIfUsernameExists($arrayNewUserData["sUsername"]); + + if (!empty($arrayUserData)) { + //User exists in this Authentication Source + //Move User + $userUid = $arrayUserData["USR_UID"]; + + $this->activateUser($arrayUserData["USR_UID"], $arrayNewUserData["sDN"], $departmentUid); + + $arrayData["moved"]++; + $arrayData["movedUsers"] .= $arrayUserData["USR_USERNAME"] . " "; + + $this->setArrayAuthenticationSourceUser($userUid, $arrayNewUserData); //INITIALIZE DATA //Update User + } else { + $arrayUserData = $this->getUserFromPM($arrayNewUserData["sUsername"]); + + if (!empty($arrayUserData)) { + //User exists in another Authentication Source and another Department + //Impossible + $userUid = $arrayUserData["USR_UID"]; + + $arrayData["impossible"]++; + $arrayData["impossibleUsers"] .= $arrayUserData["USR_USERNAME"] . " "; + } else { + //User not exists + //Create User + $userUid = $this->createUserAndActivate($arrayNewUserData, $departmentUid); + + $arrayData["created"]++; + $arrayData["createdUsers"] .= $arrayNewUserData["sUsername"] . " "; + + $this->setArrayAuthenticationSourceUser($userUid, $arrayNewUserData); //INITIALIZE DATA //Add User + } + } + } + } + + if ($userUid != "") { + $arrayData["arrayUserUid"][] = $userUid; + + if (isset($arrayUserLdap["sManagerDN"]) && $arrayUserLdap["sManagerDN"] != "") { + if (!isset($arrayData["managersHierarchy"][$arrayUserLdap["sManagerDN"]])) { + $arrayData["managersHierarchy"][$arrayUserLdap["sManagerDN"]] = array(); + } + + $arrayData["managersHierarchy"][$arrayUserLdap["sManagerDN"]][$userUid] = $userUid; + } + } + + $this->debugLog("class.ldapAdvanced.php > function departmentSynchronizeUser() > \$userUid ----> $userUid"); + $this->debugLog("class.ldapAdvanced.php > function departmentSynchronizeUser() > END"); + + //Return + return $arrayData; + } catch (Exception $e) { + throw $e; + } + } + + /** + * Synchronize User for this Group + * + * @param string $groupUid UID of Group + * @param array $arrayUserLdap User LDAP data + * @param array $arrayData Data + * + * return array Return data + */ + public function groupSynchronizeUser($groupUid, array $arrayUserLdap, array $arrayData) + { + try { + $this->debugLog("class.ldapAdvanced.php > function groupSynchronizeUser() > START"); + $this->debugLog("class.ldapAdvanced.php > function groupSynchronizeUser() > \$arrayUserLdap[sUsername] ----> " . $arrayUserLdap["sUsername"]); + + $group = new Groups(); + + $userUid = ""; + $found = false; + + $arrayUserData = $this->groupGetUserDataIfUsernameExists($arrayUserLdap["sUsername"]); + + if (!empty($arrayUserData)) { + //User already exists in this group and there is nothing to do + //User already exists + $userUid = $arrayUserData["USR_UID"]; + $found = true; + + $arrayData["already"]++; + $arrayData["alreadyUsers"] .= $arrayUserData["USR_USERNAME"] . " "; + } + + if (!$found) { + //If user DO NOT exists in this group.. do: + //If exists with another AuthSource -> impossible + //If exists in another group, but in PM and for this authsource, we need to move it + + //$arrayNewUserData = $this->searchUserByUid($arrayUserLdap["sUsername"]); + $arrayNewUserData = $arrayUserLdap; + + $arrayUserData = $this->authenticationSourceGetUserDataIfUsernameExists($arrayNewUserData["sUsername"]); + + if (!empty($arrayUserData)) { + //User exists in this Authentication Source + //Move User + $userUid = $arrayUserData["USR_UID"]; + + $this->activateUser($arrayUserData["USR_UID"], $arrayNewUserData["sDN"]); + + $group->addUserToGroup($groupUid, $userUid); + + $arrayData["moved"]++; + $arrayData["movedUsers"] .= $arrayUserData["USR_USERNAME"] . " "; + + $this->setArrayAuthenticationSourceUser($userUid, $arrayNewUserData); //INITIALIZE DATA //Update User + } else { + $arrayUserData = $this->getUserFromPM($arrayNewUserData["sUsername"]); + + if (!empty($arrayUserData)) { + //User exists in another Authentication Source and another Group + //Impossible + $userUid = $arrayUserData["USR_UID"]; + + $arrayData["impossible"]++; + $arrayData["impossibleUsers"] .= $arrayUserData["USR_USERNAME"] . " "; + } else { + //User not exists + //Create User + $userUid = $this->createUserAndActivate($arrayNewUserData, ""); + + $group->addUserToGroup($groupUid, $userUid); + + $arrayData["created"]++; + $arrayData["createdUsers"] .= $arrayNewUserData["sUsername"] . " "; + + $this->setArrayAuthenticationSourceUser($userUid, $arrayNewUserData); //INITIALIZE DATA //Add User + } + } + } + + if ($userUid != "") { + $arrayData["arrayUserUid"][] = $userUid; + + if (isset($arrayUserLdap["sManagerDN"]) && $arrayUserLdap["sManagerDN"] != "") { + if (!isset($arrayData["managersHierarchy"][$arrayUserLdap["sManagerDN"]])) { + $arrayData["managersHierarchy"][$arrayUserLdap["sManagerDN"]] = array(); + } + + $arrayData["managersHierarchy"][$arrayUserLdap["sManagerDN"]][$userUid] = $userUid; + } + } + + $this->debugLog("class.ldapAdvanced.php > function groupSynchronizeUser() > \$userUid ----> $userUid"); + $this->debugLog("class.ldapAdvanced.php > function groupSynchronizeUser() > END"); + + //Return + return $arrayData; + } catch (Exception $e) { + throw $e; + } + } + + /** + * Update Users data based on the LDAP Server + * + * @param resource $ldapcnn LDAP link identifier + * @param array $arrayAuthenticationSourceData Authentication Source Data + * @param string $filterUsers Filter + * @param array $arrayUserUid UID of Users + * @param array $arrayData Data + * + * return void + */ + public function ldapUsersUpdateData($ldapcnn, array $arrayAuthenticationSourceData, $filterUsers, array $arrayUserUid, array $arrayData) + { + try { + $totalUser = $arrayData["totalUser"]; + $countUser = $arrayData["countUser"]; + + //Set variables + $rbac = &RBAC::getSingleton(); + + if (is_null($rbac->userObj)) { + $rbac->userObj = new RbacUsers(); + } + + //Set variables + $arrayAttributesToSync = array(); + + if (isset($arrayAuthenticationSourceData["AUTH_SOURCE_DATA"]["AUTH_SOURCE_GRID_ATTRIBUTE"]) && + !empty($arrayAuthenticationSourceData["AUTH_SOURCE_DATA"]["AUTH_SOURCE_GRID_ATTRIBUTE"]) + ) { + foreach ($arrayAuthenticationSourceData["AUTH_SOURCE_DATA"]["AUTH_SOURCE_GRID_ATTRIBUTE"] as $value) { + $arrayAux = $value; + + $arrayAttributesToSync[$arrayAux["attributeUser"]] = $arrayAux["attributeLdap"]; + } + } + + //Search Users + $uidUserIdentifier = (isset($arrayAuthenticationSourceData["AUTH_SOURCE_DATA"]["AUTH_SOURCE_IDENTIFIER_FOR_USER"]))? $arrayAuthenticationSourceData["AUTH_SOURCE_DATA"]["AUTH_SOURCE_IDENTIFIER_FOR_USER"] : "uid"; + + $filter = "(&(" . $this->arrayObjectClassFilter["user"] . ")(|$filterUsers))"; + + $searchResult = @ldap_search($ldapcnn, $arrayAuthenticationSourceData["AUTH_SOURCE_BASE_DN"], $filter, array_merge($this->arrayAttributesForUser, array_values($arrayAttributesToSync))); + + if ($error = @ldap_errno($ldapcnn)) { + // + } else { + if ($searchResult) { + $numEntries = @ldap_count_entries($ldapcnn, $searchResult); + + if ($numEntries > 0) { + //Default attributes to sync + $arrayAttributesToSync["USR_FIRSTNAME"] = (isset($arrayAttributesToSync["USR_FIRSTNAME"]))? $arrayAttributesToSync["USR_FIRSTNAME"] : "givenname"; + $arrayAttributesToSync["USR_LASTNAME"] = (isset($arrayAttributesToSync["USR_LASTNAME"]))? $arrayAttributesToSync["USR_LASTNAME"] : "sn"; + $arrayAttributesToSync["USR_EMAIL"] = (isset($arrayAttributesToSync["USR_EMAIL"]))? $arrayAttributesToSync["USR_EMAIL"] : "mail"; + $arrayAttributesToSync["USR_STATUS"] = (isset($arrayAttributesToSync["USR_STATUS"]))? $arrayAttributesToSync["USR_STATUS"] : "useraccountcontrol"; + + //Get Users from DB + $arrayUser = array(); + + $criteria = new Criteria("workflow"); + + $criteria->addSelectColumn(UsersPeer::USR_UID); + $criteria->addSelectColumn(UsersPeer::USR_USERNAME); + + foreach ($arrayAttributesToSync as $key => $value) { + $fieldName = $key; + + if ($fieldName != "USR_UID" && $fieldName != "USR_USERNAME") { + $criteria->addSelectColumn(constant("UsersPeer::" . $fieldName)); + } + } + + $criteria->add(UsersPeer::USR_UID, $arrayUserUid, Criteria::IN); + //$criteria->add(UsersPeer::USR_USERNAME, "", Criteria::NOT_EQUAL); + $criteria->add(UsersPeer::USR_STATUS, "CLOSED", Criteria::NOT_EQUAL); + + $rsCriteria = UsersPeer::doSelectRS($criteria); + $rsCriteria->setFetchmode(ResultSet::FETCHMODE_ASSOC); + + while ($rsCriteria->next()) { + $row = $rsCriteria->getRow(); + + $arrayUser[$row["USR_USERNAME"]] = $row; + } + + //Get Users from LDAP Server + $entry = @ldap_first_entry($ldapcnn, $searchResult); + + do { + $arrayUserLdap = $this->ldapGetAttributes($ldapcnn, $entry); + + $username = (isset($arrayUserLdap[$uidUserIdentifier]))? $arrayUserLdap[$uidUserIdentifier] : ""; + + if ((is_array($username) && !empty($username)) || trim($username) != "") { + $username = trim((is_array($username))? $username[0] : $username); + + if (isset($arrayUser[$username])) { + if (!isset($this->arrayUserUpdateChecked[$username])) { + $this->arrayUserUpdateChecked[$username] = 1; + + $countUser++; + + $arrayUserDataUpdate = array(); + $flagUpdate = false; + + foreach ($arrayAttributesToSync as $key => $value) { + $fieldName = $key; + $attributeName = strtolower($value); + + if (isset($arrayUserLdap[$attributeName])) { + $ldapAttributeValue = trim((is_array($arrayUserLdap[$attributeName]))? $arrayUserLdap[$attributeName][0] : $arrayUserLdap[$attributeName]); + + switch ($fieldName) { + case "USR_STATUS": + if ($attributeName == "useraccountcontrol") { + $ldapAttributeValue = (in_array($ldapAttributeValue, array("512", "544", "66048", "66080")))? "ACTIVE" : "INACTIVE"; + } + break; + case "USR_DUE_DATE": + if ($attributeName == "accountexpires") { + $ldapAttributeValue = $this->convertDateADtoPM($ldapAttributeValue); + } + break; + } + + if ($ldapAttributeValue != $arrayUser[$username][$fieldName]) { + $arrayUserDataUpdate[$fieldName] = $ldapAttributeValue; + $flagUpdate = true; + } + } + } + + if ($flagUpdate) { + $arrayUserDataUpdate["USR_UID"] = $arrayUser[$username]["USR_UID"]; + + //Update User data + $rbac->updateUser($arrayUserDataUpdate); + + $user = new Users(); + $result = $user->update($arrayUserDataUpdate); + } + + //Progress bar + $this->frontEndShow("BAR", "Update Users data: " . $countUser . "/" . $totalUser . " " . $this->progressBar($totalUser, $countUser)); + } else { + $this->log($ldapcnn, "User is repeated: Username \"" . $username . "\", DN \"" . $arrayUserLdap["dn"] . "\""); + } + } + } + } while ($entry = @ldap_next_entry($ldapcnn, $entry)); + } + } + } + + //Return + return array($totalUser, $countUser); + } catch (Exception $e) { + throw $e; + } + } + + /** + * Update Users data based on the LDAP Server + * + * @param string $authenticationSourceUid UID of Authentication Source + * + * return void + */ + public function usersUpdateData($authenticationSourceUid) + { + try { + $totalUser = count($this->arrayAuthenticationSourceUsersByUid); + $countUser = 0; + + //Set variables + $rbac = &RBAC::getSingleton(); + + if (is_null($rbac->authSourcesObj)) { + $rbac->authSourcesObj = new AuthenticationSource(); + } + + $arrayAuthenticationSourceData = $rbac->authSourcesObj->load($authenticationSourceUid); + + $this->ldapcnn = $this->ldapConnection($arrayAuthenticationSourceData); + + $ldapcnn = $this->ldapcnn; + + //Update Users + $recordSize = 1000; //$recordStart + $count = 0; + + $uidUserIdentifier = (isset($arrayAuthenticationSourceData["AUTH_SOURCE_DATA"]["AUTH_SOURCE_IDENTIFIER_FOR_USER"]))? $arrayAuthenticationSourceData["AUTH_SOURCE_DATA"]["AUTH_SOURCE_IDENTIFIER_FOR_USER"] : "uid"; + + $filterUsers = ""; + $arrayUserUid = array(); + + foreach ($this->arrayAuthenticationSourceUsersByUid as $value) { + $arrayUserData = $value; + + $count++; + + $filterUsers .= "($uidUserIdentifier=" . $arrayUserData["USR_USERNAME"] . ")"; + $arrayUserUid[] = $arrayUserData["USR_UID"]; + + if ($count == $recordSize) { + list($totalUser, $countUser) = $this->ldapUsersUpdateData($ldapcnn, $arrayAuthenticationSourceData, $filterUsers, $arrayUserUid, array("totalUser" => $totalUser, "countUser" => $countUser)); + + $count = 0; + + $filterUsers = ""; + $arrayUserUid = array(); + } + } + + if ($count > 0) { + list($totalUser, $countUser) = $this->ldapUsersUpdateData($ldapcnn, $arrayAuthenticationSourceData, $filterUsers, $arrayUserUid, array("totalUser" => $totalUser, "countUser" => $countUser)); + } + } catch (Exception $e) { + throw $e; + } + } +} + diff --git a/workflow/engine/methods/authSources/authSources_Ajax.php b/workflow/engine/methods/authSources/authSources_Ajax.php index edf936350..0a08f510e 100755 --- a/workflow/engine/methods/authSources/authSources_Ajax.php +++ b/workflow/engine/methods/authSources/authSources_Ajax.php @@ -158,17 +158,15 @@ try { if (($sObject != '.') && ($sObject != '..') && ($sObject != '.svn') && ($sObject != 'ldap')) { if (is_file( PATH_RBAC . 'plugins' . PATH_SEP . $sObject )) { $sType = trim(str_replace(array("class.", ".php"), "", $sObject)); - - $statusPlugin = $pluginRegistry->getStatusPlugin($sType); $flagAdd = false; - if (preg_match("/^(?:enabled|disabled)$/", $statusPlugin)) { - if ($statusPlugin == "enabled") { - $flagAdd = true; - } - } else { + /*----------------------------------********---------------------------------*/ + if (PMLicensedFeatures + ::getSingleton() + ->verifyfeature('zLhSk5TeEQrNFI2RXFEVktyUGpnczV1WEJNWVp6cjYxbTU3R29mVXVZNWhZQT0=')) { $flagAdd = true; } + /*----------------------------------********---------------------------------*/ if ($flagAdd) { $arr[] = array("sType" => $sType, "sLabel" => $sType); diff --git a/workflow/engine/methods/authSources/authSources_New.php b/workflow/engine/methods/authSources/authSources_New.php index 02127b0f4..4e515764c 100755 --- a/workflow/engine/methods/authSources/authSources_New.php +++ b/workflow/engine/methods/authSources/authSources_New.php @@ -37,19 +37,8 @@ $G_ID_SUB_MENU_SELECTED = 'AUTH_SOURCES'; $fields = array ('AUTH_SOURCE_PROVIDER' => $_REQUEST['AUTH_SOURCE_PROVIDER']); $G_PUBLISH = new Publisher(); - -if (file_exists( PATH_PLUGINS . $fields['AUTH_SOURCE_PROVIDER'] . PATH_SEP . $fields['AUTH_SOURCE_PROVIDER'] . 'Edit.xml' )) { - $pluginEnabled = 0; - - if (file_exists(PATH_PLUGINS . $fields["AUTH_SOURCE_PROVIDER"] . ".php")) { - $pluginRegistry = &PMPluginRegistry::getSingleton(); - $pluginDetail = $pluginRegistry->getPluginDetails($fields["AUTH_SOURCE_PROVIDER"] . ".php"); - - if ($pluginDetail && $pluginDetail->enabled) { - $pluginEnabled = 1; - } - } - +if (file_exists( PATH_XMLFORM . 'ldapAdvanced/' . $fields['AUTH_SOURCE_PROVIDER'] . 'Edit.xml' )) { + $pluginEnabled = 1; if ($pluginEnabled == 1) { //The attributes the users G::LoadClass("pmFunctions"); @@ -64,17 +53,17 @@ if (file_exists( PATH_PLUGINS . $fields['AUTH_SOURCE_PROVIDER'] . PATH_SEP . $fi } } $fields["AUTH_SOURCE_ATTRIBUTE_IDS"] = $attributes; - if (file_exists(PATH_PLUGINS . $fields["AUTH_SOURCE_PROVIDER"] . PATH_SEP . $fields["AUTH_SOURCE_PROVIDER"] . 'Flag')) { + if (file_exists(PATH_XMLFORM . 'ldapAdvanced/' . $fields['AUTH_SOURCE_PROVIDER'] . 'Flag')) { $oHeadPublisher = & headPublisher::getSingleton (); - + $oHeadPublisher->assign("Fields", $fields); - $oHeadPublisher->addExtJsScript (PATH_PLUGINS . $fields["AUTH_SOURCE_PROVIDER"] . PATH_SEP . 'js' . PATH_SEP . 'library', false, true ); - $oHeadPublisher->addExtJsScript (PATH_PLUGINS . $fields["AUTH_SOURCE_PROVIDER"] . PATH_SEP . 'js' . PATH_SEP . 'ldapAdvancedForm', false, true ); - $oHeadPublisher->addExtJsScript (PATH_PLUGINS . $fields["AUTH_SOURCE_PROVIDER"] . PATH_SEP . 'js' . PATH_SEP . 'ldapAdvancedList', false, true ); + $oHeadPublisher->addExtJsScript (PATH_TPL. 'ldapAdvanced/library.js', false, true ); + $oHeadPublisher->addExtJsScript (PATH_TPL. 'ldapAdvanced/ldapAdvancedForm', false, true ); + $oHeadPublisher->addExtJsScript (PATH_TPL. 'ldapAdvanced/ldapAdvancedList', false, true ); G::RenderPage ('publish', 'extJs'); die(); } - $G_PUBLISH->AddContent("xmlform", "xmlform", $fields["AUTH_SOURCE_PROVIDER"] . PATH_SEP . $fields["AUTH_SOURCE_PROVIDER"] . "Edit", "", $fields, "../authSources/authSources_Save"); + $G_PUBLISH->AddContent("xmlform", "xmlform", 'ldapAdvanced/' . $fields['AUTH_SOURCE_PROVIDER'] . 'Edit', '', $fields, '../authSources/authSources_Save'); } else { $G_PUBLISH->AddContent( 'xmlform', 'xmlform', 'login/showMessage', '', array ('MESSAGE' => G::LoadTranslation( 'ID_AUTH_SOURCE_MISSING' )) ); } diff --git a/workflow/engine/methods/services/ldapadvanced.php b/workflow/engine/methods/services/ldapadvanced.php new file mode 100755 index 000000000..7ee2bb43c --- /dev/null +++ b/workflow/engine/methods/services/ldapadvanced.php @@ -0,0 +1,651 @@ +authSourcesObj)) { + $rbac->authSourcesObj = new AuthenticationSource(); + } + + $plugin = new ldapAdvanced(); + $plugin->sSystem = $rbac->sSystem; + + $plugin->setFrontEnd(true); + $plugin->setDebug($debug); + + //Get all authsource for this plugin ( ldapAdvanced plugin, because other authsources are not needed ) + $arrayAuthenticationSource = $plugin->getAuthSources(); + + $aDepartments = $plugin->getDepartments(""); + $aGroups = $plugin->getGroups(); + + //$arrayDepartmentUserAd = array(); //(D) Update Users + //$arrayGroupUserAd = array(); //(G) Update Users + + //echo "\n"; + + $plugin->frontEndShow("START"); + + $plugin->debugLog("START"); + + foreach ($arrayAuthenticationSource as $value) { + $arrayAuthenticationSourceData = $value; + + $plugin->debugLog("ldapadvanced.php > function executeCron() > foreach > \$arrayAuthenticationSourceData ---->\n" . print_r($arrayAuthenticationSourceData, true)); + + $plugin->sAuthSource = $arrayAuthenticationSourceData["AUTH_SOURCE_UID"]; + $plugin->ldapcnn = null; + + $plugin->setArrayDepartmentUserSynchronizedChecked(array()); + $plugin->setArrayUserUpdateChecked(array()); + + //Get all User (USR_UID, USR_USERNAME, USR_AUTH_USER_DN) registered in RBAC with this Authentication Source + $plugin->setArrayAuthenticationSourceUsers($arrayAuthenticationSourceData["AUTH_SOURCE_UID"]); //INITIALIZE DATA + + $plugin->frontEndShow("TEXT", "Authentication Source: " . $arrayAuthenticationSourceData["AUTH_SOURCE_NAME"]); + + $plugin->log(null, "Executing cron for Authentication Source: " . $arrayAuthenticationSourceData["AUTH_SOURCE_NAME"]); + + //Get all departments from Ldap/ActiveDirectory and build a hierarchy using dn (ou->ou parent) + $aLdapDepts = $plugin->searchDepartments(); + + //Obtain all departments from PM with a valid department in LDAP/ActiveDirectory + $aRegisteredDepts = $plugin->getRegisteredDepartments($aLdapDepts, $aDepartments); + + $plugin->debugLog("ldapadvanced.php > function executeCron() > foreach > \$aRegisteredDepts ---->\n" . print_r($aRegisteredDepts, true)); + + //Get all group from Ldap/ActiveDirectory + $aLdapGroups = $plugin->searchGroups(); + + //Obtain all groups from PM with a valid group in LDAP/ActiveDirectory + $aRegisteredGroups = $plugin->getRegisteredGroups($aLdapGroups, $aGroups); + + $plugin->debugLog("ldapadvanced.php > function executeCron() > foreach > \$aRegisteredGroups ---->\n" . print_r($aRegisteredGroups, true)); + + //Get all users from Removed OU + $this->usersRemovedOu = $plugin->getUsersFromRemovedOu($arrayAuthenticationSourceData); + $plugin->deactiveArrayOfUsers($this->usersRemovedOu); + + //Variables + $this->deletedRemoved = count($this->usersRemovedOu); + $this->deletedRemovedUsers = ""; + + $this->dAlready = 0; + $this->dMoved = 0; + $this->dImpossible = 0; + $this->dCreated = 0; + $this->dRemoved = 0; + $this->dAlreadyUsers = ""; + $this->dMovedUsers = ""; + $this->dImpossibleUsers = ""; + $this->dCreatedUsers = ""; + $this->dRemovedUsers = ""; + + $this->gAlready = 0; + $this->gMoved = 0; + $this->gImpossible = 0; + $this->gCreated = 0; + $this->gRemoved = 0; + $this->gAlreadyUsers = ""; + $this->gMovedUsers = ""; + $this->gImpossibleUsers = ""; + $this->gCreatedUsers = ""; + $this->gRemovedUsers = ""; + + //Department - Synchronize Users + $numDepartments = count($aRegisteredDepts); + $count = 0; + + $plugin->debugLog("ldapadvanced.php > function executeCron() > foreach > \$numDepartments ----> $numDepartments"); + + foreach ($aRegisteredDepts as $registeredDept) { + $count++; + + //(D) Update Users + //if (!isset($arrayDepartmentUserAd[$registeredDept["DEP_UID"]])) { + // $arrayDepartmentUserAd[$registeredDept["DEP_UID"]] = array(); //Current users in department based in Active Directory + //} + // + //$arrayAux = $this->departmentSynchronizeUsers($plugin, $numDepartments, $count, $registeredDept); + //$arrayAux = array_merge($arrayDepartmentUserAd[$registeredDept["DEP_UID"]], $arrayAux); + // + //$arrayDepartmentUserAd[$registeredDept["DEP_UID"]] = array_unique($arrayAux); + + $arrayAux = $this->departmentSynchronizeUsers($plugin, $numDepartments, $count, $registeredDept); + } + + //Department - Print log + $logResults = sprintf( + "- Departments -> Existing users: %d, moved: %d, impossible: %d, created: %d, removed: %d", + $this->dAlready, + $this->dMoved, + $this->dImpossible, + $this->dCreated, + $this->dRemoved + ); + + $plugin->frontEndShow("TEXT", $logResults); + + $plugin->log(null, $logResults); + + //Group - Synchronize Users + $numGroups = count($aRegisteredGroups); + $count = 0; + + $plugin->debugLog("ldapadvanced.php > function executeCron() > foreach > \$numGroups ----> $numGroups"); + + foreach ($aRegisteredGroups as $registeredGroup) { + $count++; + + //(G) Update Users + //if (!isset($arrayGroupUserAd[$registeredGroup["GRP_UID"]])) { + // $arrayGroupUserAd[$registeredGroup["GRP_UID"]] = array(); //Current users in group based in Active Directory + //} + // + //$arrayAux = $this->groupSynchronizeUsers($plugin, $numGroups, $count, $registeredGroup); + //$arrayAux = array_merge($arrayGroupUserAd[$registeredGroup["GRP_UID"]], $arrayAux); + // + //$arrayGroupUserAd[$registeredGroup["GRP_UID"]] = array_unique($arrayAux); + + $arrayAux = $this->groupSynchronizeUsers($plugin, $numGroups, $count, $registeredGroup); + } + + //Group - Print log + $logResults = sprintf( + "- Groups -> Existing users: %d, moved: %d, impossible: %d, created: %d, removed: %d", + $this->gAlready, + $this->gMoved, + $this->gImpossible, + $this->gCreated, + $this->gRemoved + ); + + $plugin->frontEndShow("TEXT", $logResults); + + $plugin->log(null, $logResults); + + //Manager + $plugin->clearManager($this->managersToClear); + + if (isset($arrayAuthenticationSourceData["AUTH_SOURCE_DATA"]["DEPARTMENTS_TO_UNASSIGN"])) { + if (is_array($arrayAuthenticationSourceData["AUTH_SOURCE_DATA"]["DEPARTMENTS_TO_UNASSIGN"])) { + foreach ($arrayAuthenticationSourceData["AUTH_SOURCE_DATA"]["DEPARTMENTS_TO_UNASSIGN"] as $departmentUID) { + // Delete manager assignments + $criteriaSet = new Criteria("workflow"); + $criteriaSet->add(UsersPeer::USR_REPORTS_TO, ""); + $criteriaWhere = new Criteria("workflow"); + $criteriaWhere->add(UsersPeer::DEP_UID, $departmentUID); + $criteriaWhere->add(UsersPeer::USR_REPORTS_TO, "", Criteria::NOT_EQUAL); + $this->deletedManager = BasePeer::doUpdate($criteriaWhere, $criteriaSet, Propel::getConnection("workflow")); + // Delete department assignments + $criteriaSet = new Criteria("workflow"); + $criteriaSet->add(UsersPeer::DEP_UID, ""); + $criteriaWhere = new Criteria("workflow"); + $criteriaWhere->add(UsersPeer::DEP_UID, $departmentUID); + $this->dMoved += UsersPeer::doCount($criteriaWhere); + BasePeer::doUpdate($criteriaWhere, $criteriaSet, Propel::getConnection("workflow")); + } + } + + unset($arrayAuthenticationSourceData["AUTH_SOURCE_DATA"]["DEPARTMENTS_TO_UNASSIGN"]); + + $rbac = &RBAC::getSingleton(); + $rbac->authSourcesObj->update($arrayAuthenticationSourceData); + } + + if (isset($arrayAuthenticationSourceData["AUTH_SOURCE_DATA"]["GROUPS_TO_UNASSIGN"])) { + if (is_array($arrayAuthenticationSourceData["AUTH_SOURCE_DATA"]["GROUPS_TO_UNASSIGN"])) { + foreach ($arrayAuthenticationSourceData["AUTH_SOURCE_DATA"]["GROUPS_TO_UNASSIGN"] as $groupUID) { + // Delete manager assignments + $groupsInstance = new Groups(); + $criteria = $groupsInstance->getUsersGroupCriteria($groupUID); + $dataset = UsersPeer::doSelectRS($criteria); + $dataset->setFetchmode(ResultSet::FETCHMODE_ASSOC); + $dataset->next(); + $users = array(); + + while ($row = $dataset->getRow()) { + $users[] = $row["USR_UID"]; + $dataset->next(); + } + + $criteriaSet = new Criteria("workflow"); + $criteriaSet->add(UsersPeer::USR_REPORTS_TO, ""); + $criteriaWhere = new Criteria("workflow"); + $criteriaWhere->add(UsersPeer::USR_UID, $users, Criteria::IN); + $criteriaWhere->add(UsersPeer::USR_REPORTS_TO, "", Criteria::NOT_EQUAL); + $this->deletedManager = BasePeer::doUpdate($criteriaWhere, $criteriaSet, Propel::getConnection("workflow")); + + // Delete group assignments + $criteria = new Criteria("workflow"); + $criteria->add(GroupUserPeer::GRP_UID, $groupUID); + $this->gMoved += GroupUserPeer::doCount($criteria); + BasePeer::doDelete($criteria, Propel::getConnection("workflow")); + } + } + + unset($arrayAuthenticationSourceData["AUTH_SOURCE_DATA"]["GROUPS_TO_UNASSIGN"]); + + $rbac = &RBAC::getSingleton(); + $rbac->authSourcesObj->update($arrayAuthenticationSourceData); + } + + // Delete the managers that not exists in PM + $criteria = new Criteria("rbac"); + $criteria->addSelectColumn(RbacUsersPeer::USR_AUTH_USER_DN); + $criteria->add(RbacUsersPeer::USR_AUTH_USER_DN, "", Criteria::NOT_EQUAL); + $dataset = RbacUsersPeer::doSelectRS($criteria); + $dataset->setFetchmode(ResultSet::FETCHMODE_ASSOC); + $dataset->next(); + $existingUsers = array(); + + while ($row = $dataset->getRow()) { + $existingUsers[] = $row["USR_AUTH_USER_DN"]; + $dataset->next(); + } + + foreach ($this->managersHierarchy as $managerDN => $subordinates) { + if (!in_array($managerDN, $existingUsers)) { + unset($this->managersHierarchy[$managerDN]); + } + } + + // Get the managers assigments counters + $plugin->synchronizeManagers($this->managersHierarchy); + + $deletedManagersAssignments = self::array_diff_assoc_recursive($this->oldManagersHierarchy, $this->managersHierarchy); + $newManagersAssignments = self::array_diff_assoc_recursive($this->managersHierarchy, $this->oldManagersHierarchy); + $deletedManagers = array(); + $newManagers = array(); + $movedManagers = array(); + + if (is_array($deletedManagersAssignments)) { + foreach ($deletedManagersAssignments as $dn1 => $subordinates1) { + foreach ($subordinates1 as $subordinate) { + if (!in_array($subordinate, $deletedManagers)) { + $deletedManagers[] = $subordinate; + } + + foreach ($newManagersAssignments as $dn2 => $subordinates2) { + if (isset($subordinates2[$subordinate])) { + $movedManagers[] = $subordinate; + } + } + } + } + } + + if (is_array($newManagersAssignments)) { + foreach ($newManagersAssignments as $dn1 => $subordinates1) { + foreach ($subordinates1 as $subordinate) { + if (!in_array($subordinate, $newManagers)) { + $newManagers[] = $subordinate; + } + + foreach ($deletedManagersAssignments as $dn2 => $subordinates2) { + if (isset($subordinates2[$subordinate])) { + if (!in_array($subordinate, $movedManagers)) { + $movedManagers[] = $subordinate; + } + } + } + } + } + } + + //Print and log the users's information + //Deleted/Removed Users + $logResults = sprintf("- Deleted/Removed Users: %d", $this->deletedRemoved); + + $plugin->frontEndShow("TEXT", $logResults); + + $plugin->log(null, $logResults); + + if ($this->deletedRemoved > 0) { + $plugin->log(null, "Deleted/Removed Users: "); + $plugin->log(null, $this->deletedRemovedUsers); + } + + if ($this->dAlready + $this->gAlready > 0) { + $plugin->log(null, "Existing Users: "); + $plugin->log(null, $this->dAlreadyUsers . " " . $this->gAlreadyUsers); + } + + if ($this->dMoved + $this->gMoved > 0) { + $plugin->log(null, "Moved Users: "); + $plugin->log(null, $this->dMovedUsers . " " . $this->gMovedUsers); + } + + if ($this->dImpossible + $this->gImpossible > 0) { + $plugin->log(null, "Impossible Users: "); + $plugin->log(null, $this->dImpossibleUsers . " " . $this->gImpossibleUsers); + } + + if ($this->dCreated + $this->gCreated > 0) { + $plugin->log(null, "Created Users: "); + $plugin->log(null, $this->dCreatedUsers . " " . $this->gCreatedUsers); + } + + if ($this->dRemoved + $this->gRemoved > 0) { + $plugin->log(null, "Removed Users: "); + $plugin->log(null, $this->dRemovedUsers . " " . $this->gRemovedUsers); + } + + //Print and log the managers assignments"s information + $logResults = sprintf( + "- Managers assignments: created %d, moved %d, removed %d", + count($newManagers) - count($movedManagers), + count($movedManagers), + count($deletedManagers) - count($movedManagers) + $this->deletedManager + ); + + $plugin->frontEndShow("TEXT", $logResults); + + $plugin->log(null, $logResults); + + //Update Users data based on the LDAP Server + $plugin->usersUpdateData($arrayAuthenticationSourceData["AUTH_SOURCE_UID"]); + } + + $plugin->frontEndShow("END"); + + //(D) Update Users + ////Department //Upgrade users in departments + //foreach ($arrayDepartmentUserAd as $departmentUid => $arrayUserAd) { + // $plugin->setArrayDepartmentUsers($departmentUid); //INITIALIZE DATA + // + // $arrayAux = array_diff(array_keys($plugin->arrayDepartmentUsersByUid), $arrayUserAd); + // + // $this->departmentRemoveUsers($departmentUid, $arrayAux); + //} + + //(G) Update Users + ////Group //Upgrade users in groups + //foreach ($arrayGroupUserAd as $groupUid => $arrayUserAd) { + // $plugin->setArrayGroupUsers($groupUid); //INITIALIZE DATA + // + // $arrayAux = array_diff(array_keys($plugin->arrayGroupUsersByUid), $arrayUserAd); + // + // $this->groupRemoveUsers($groupUid, $arrayAux); + //} + + //// Developed by Gary and Ronald + //$usersInfo = $plugin->ASUpdateInfo(''); + //if (isset($usersInfo) && $usersInfo > 0) { + // $this->dMoved = $usersInfo; + //} + //// End Developed by Gary and Ronald + + $plugin->debugLog("END"); + } + + public function array_diff_assoc_recursive($array1, $array2) + { + foreach ($array1 as $key => $value) { + if (is_array($value)) { + if (!isset($array2[$key])) { + $difference[$key] = $value; + } else { + if (!is_array($array2[$key])) { + $difference[$key] = $value; + } else { + $new_diff = self::array_diff_assoc_recursive($value, $array2[$key]); + + if ($new_diff != false) { + $difference[$key] = $new_diff; + } + } + } + } else { + if (!isset($array2[$key]) || $array2[$key] != $value) { + $difference[$key] = $value; + } + } + } + + return (!isset($difference))? array() : $difference; + } + + public function departmentRemoveUsers($departmentUid, array $arrayUserUid) + { + try { + $department = new Department(); + $department->Load($departmentUid); + + $departmentManagerUid = $department->getDepManager(); + + foreach ($arrayUserUid as $value) { + $userUid = $value; + + $department->removeUserFromDepartment($departmentUid, $userUid); + + if ($userUid == $departmentManagerUid) { + $department->update(array("DEP_UID" => $departmentUid, "DEP_MANAGER" => "")); + + $department->updateDepartmentManager($departmentUid); + } + } + } catch (Exception $e) { + throw $e; + } + } + + public function groupRemoveUsers($groupUid, array $arrayUserUid) + { + try { + $group = new Groups(); + + foreach ($arrayUserUid as $value) { + $userUid = $value; + + $group->removeUserOfGroup($groupUid, $userUid); + } + } catch (Exception $e) { + throw $e; + } + } + + public function departmentSynchronizeUsers($ldapAdvanced, $numDepartments, $count, array $arrayDepartmentData) + { + try { + $ldapAdvanced->debugLog("ldapadvanced.php > function departmentSynchronizeUsers() > START"); + $ldapAdvanced->debugLog("ldapadvanced.php > function departmentSynchronizeUsers() > \$arrayDepartmentData ---->\n" . print_r($arrayDepartmentData, true)); + + //Get users from ProcessMaker tables (for this Department) + $ldapAdvanced->setArrayDepartmentUsers($arrayDepartmentData["DEP_UID"]); //INITIALIZE DATA + + //Clear the manager assignments + $arrayUserUid = array(); + + foreach ($ldapAdvanced->arrayDepartmentUsersByUid as $key => $user) { + $arrayUserUid[] = $user["USR_UID"]; + + if (isset($user["USR_REPORTS_TO"]) && $user["USR_REPORTS_TO"] != "") { + $dn = (isset($ldapAdvanced->arrayAuthenticationSourceUsersByUid[$user["USR_REPORTS_TO"]]["USR_AUTH_USER_DN"]))? $ldapAdvanced->arrayAuthenticationSourceUsersByUid[$user["USR_REPORTS_TO"]]["USR_AUTH_USER_DN"] : ""; + + if ($dn != "") { + if (!isset($this->oldManagersHierarchy[$dn])) { + $this->oldManagersHierarchy[$dn] = array(); + } + + $this->oldManagersHierarchy[$dn][$user["USR_UID"]] = $user["USR_UID"]; + } + } + } + + $this->managersToClear = $arrayUserUid; + + //Synchronize Users from Department + //Now we need to go over ldapusers and check if the user exists in ldap but not in PM, then we need to create it + $arrayData = array( + "already" => $this->dAlready, + "moved" => $this->dMoved, + "impossible" => $this->dImpossible, + "created" => $this->dCreated, + "alreadyUsers" => $this->dAlreadyUsers, + "movedUsers" => $this->dMovedUsers, + "impossibleUsers" => $this->dImpossibleUsers, + "createdUsers" => $this->dCreatedUsers, + + "managersHierarchy" => $this->managersHierarchy, + "arrayUserUid" => array(), + + "n" => $numDepartments, + "i" => $count + ); + + //Get Users from LDAP (for this Department) + $arrayData = $ldapAdvanced->ldapGetUsersFromDepartment("SYNCHRONIZE", $arrayDepartmentData["DEP_LDAP_DN"], $arrayData); + + $this->dAlready = $arrayData["already"]; + $this->dMoved = $arrayData["moved"]; + $this->dImpossible = $arrayData["impossible"]; + $this->dCreated = $arrayData["created"]; + $this->dAlreadyUsers = $arrayData["alreadyUsers"]; + $this->dMovedUsers = $arrayData["movedUsers"]; + $this->dImpossibleUsers = $arrayData["impossibleUsers"]; + $this->dCreatedUsers = $arrayData["createdUsers"]; + + $this->managersHierarchy = $arrayData["managersHierarchy"]; + $arrayUserUid = $arrayData["arrayUserUid"]; + + //(D) Update Users + $arrayAux = array_diff(array_keys($ldapAdvanced->arrayDepartmentUsersByUid), $arrayUserUid); + + $this->departmentRemoveUsers($arrayDepartmentData["DEP_UID"], $arrayAux); + + $this->dRemoved += count($arrayAux); + $this->dRemovedUsers = ""; + + $ldapAdvanced->debugLog("ldapadvanced.php > function departmentSynchronizeUsers() > END"); + + //Return all UID of Users synchronized in the Department (Return all UID of Users of this Department) + return $arrayUserUid; + } catch (Exception $e) { + throw $e; + } + } + + public function groupSynchronizeUsers($ldapAdvanced, $numGroups, $count, array $arrayGroupData) + { + try { + $ldapAdvanced->debugLog("ldapadvanced.php > function groupSynchronizeUsers() > START"); + $ldapAdvanced->debugLog("ldapadvanced.php > function groupSynchronizeUsers() > \$arrayGroupData ---->\n" . print_r($arrayGroupData, true)); + + //Get users from ProcessMaker tables (for this Group) + $ldapAdvanced->setArrayGroupUsers($arrayGroupData["GRP_UID"]); //INITIALIZE DATA + + //Clear the manager assignments + $arrayUserUid = array(); + + foreach ($ldapAdvanced->arrayGroupUsersByUid as $key => $user) { + $arrayUserUid[] = $user["USR_UID"]; + + if (isset($user["USR_REPORTS_TO"]) && $user["USR_REPORTS_TO"] != "") { + $dn = (isset($ldapAdvanced->arrayAuthenticationSourceUsersByUid[$user["USR_REPORTS_TO"]]["USR_AUTH_USER_DN"]))? $ldapAdvanced->arrayAuthenticationSourceUsersByUid[$user["USR_REPORTS_TO"]]["USR_AUTH_USER_DN"] : ""; + + if ($dn != "") { + if (!isset($this->oldManagersHierarchy[$dn])) { + $this->oldManagersHierarchy[$dn] = array(); + } + + $this->oldManagersHierarchy[$dn][$user["USR_UID"]] = $user["USR_UID"]; + } + } + } + + $this->managersToClear = array_merge($this->managersToClear, $arrayUserUid); + + //Synchronize Users from Group + //Now we need to go over ldapusers and check if the user exists in ldap but not in PM, then we need to create it + $arrayData = array( + "already" => $this->gAlready, + "moved" => $this->gMoved, + "impossible" => $this->gImpossible, + "created" => $this->gCreated, + "alreadyUsers" => $this->gAlreadyUsers, + "movedUsers" => $this->gMovedUsers, + "impossibleUsers" => $this->gImpossibleUsers, + "createdUsers" => $this->gCreatedUsers, + + "managersHierarchy" => $this->managersHierarchy, + "arrayUserUid" => array(), + + "n" => $numGroups, + "i" => $count + ); + + //Get Users from LDAP (for this Group) + $arrayData = $ldapAdvanced->ldapGetUsersFromGroup("SYNCHRONIZE", $arrayGroupData, $arrayData); + + $this->gAlready = $arrayData["already"]; + $this->gMoved = $arrayData["moved"]; + $this->gImpossible = $arrayData["impossible"]; + $this->gCreated = $arrayData["created"]; + $this->gAlreadyUsers = $arrayData["alreadyUsers"]; + $this->gMovedUsers = $arrayData["movedUsers"]; + $this->gImpossibleUsers = $arrayData["impossibleUsers"]; + $this->gCreatedUsers = $arrayData["createdUsers"]; + + $this->managersHierarchy = $arrayData["managersHierarchy"]; + $arrayUserUid = $arrayData["arrayUserUid"]; + + //(G) Update Users + $arrayAux = array_diff(array_keys($ldapAdvanced->arrayGroupUsersByUid), $arrayUserUid); + + $this->groupRemoveUsers($arrayGroupData["GRP_UID"], $arrayAux); + + $this->gRemoved += count($arrayAux); + $this->gRemovedUsers = ""; + + $ldapAdvanced->debugLog("ldapadvanced.php > function groupSynchronizeUsers() > END"); + + //Return all UID of Users synchronized in the Group (Return all UID of Users of this Group) + return $arrayUserUid; + } catch (Exception $e) { + throw $e; + } + } +} + diff --git a/workflow/engine/templates/ldapAdvanced/ldapAdvancedForm.js b/workflow/engine/templates/ldapAdvanced/ldapAdvancedForm.js new file mode 100755 index 000000000..abe40dac4 --- /dev/null +++ b/workflow/engine/templates/ldapAdvanced/ldapAdvancedForm.js @@ -0,0 +1,237 @@ +var ldapFormAnonymousOnChange = function (combo, arrayObject) +{ + var flagAnonymous = (combo.getValue() == "1")? true : false; + + arrayObject["ldapFormSearchUser"].allowBlank = flagAnonymous; + arrayObject["ldapFormPassword"].allowBlank = flagAnonymous; + + arrayObject["ldapFormSearchUser"].setVisible(!flagAnonymous); + arrayObject["ldapFormPassword"].setVisible(!flagAnonymous); +}; + +var ldapFormId = new Ext.form.Hidden({ + name: 'AUTH_SOURCE_UID', + id: 'AUTH_SOURCE_UID' +}); + +var ldapFormName = new Ext.form.TextField({ + fieldLabel: '*' + _('ID_NAME'), + name: 'AUTH_SOURCE_NAME', + id: 'AUTH_SOURCE_NAME', + autoCreate: {tag: 'input', type: 'text', maxlength: '50'}, + allowBlank: false, + width: 210 +}); + +var ldapFormProvider = new Ext.form.Hidden({ + name: 'AUTH_SOURCE_PROVIDER', + id: 'AUTH_SOURCE_PROVIDER' +}); + +var ldapFormType = new Ext.form.ComboBox({ + valueField: 'ID', + displayField: 'VALUE', + value: 'ldap', + + fieldLabel: '*' + _('ID_TYPE'), + typeAhead: true, + forceSelection: true, + triggerAction: 'all', + editable: true, + name: 'LDAP_TYPE', + id: 'LDAP_TYPE', + width: 130, + allowBlank: false, + store: [["ldap", "OpenLDAP"], ["ad", "Active Directory"], ["ds", "389 DS"]], + listeners:{ + select: function(combo, record) { + ldapFormIdentifier.setValue((combo.getValue() == "ad")? "samaccountname" : "uid"); + } + } +}); + +var ldapFormAutoRegister = new Ext.form.ComboBox({ + valueField: 'ID', + displayField: 'VALUE', + value: '0', + + fieldLabel: '*' + "Enable automatic register", + typeAhead: true, + forceSelection: true, + triggerAction: 'all', + editable: true, + name: 'AUTH_SOURCE_AUTO_REGISTER', + id: 'AUTH_SOURCE_AUTO_REGISTER', + width: 130, + allowBlank: false, + store: [['0',_('ID_NO')],['1',_('ID_YES')]] +}); + +var ldapFormServerName = new Ext.form.TextField({ + fieldLabel: '*' + "Server Address", + name: 'AUTH_SOURCE_SERVER_NAME', + id: 'AUTH_SOURCE_SERVER_NAME', + autoCreate: {tag: 'input', type: 'text', maxlength: '50'}, + allowBlank: false, + width: 210 +}); + +var ldapFormPort = new Ext.form.NumberField({ + fieldLabel: '*' + _('ID_PORT'), + name: 'AUTH_SOURCE_PORT', + id: 'AUTH_SOURCE_PORT', + allowBlank: true, + width: 130, + value: '389', + autoCreate: {tag: 'input', type: 'text', maxlength: '5'} +}); + +var ldapFormTls = new Ext.form.ComboBox({ + valueField: 'ID', + displayField: 'VALUE', + + fieldLabel: '*' + _('ID_ENABLED_TLS'), + typeAhead: true, + forceSelection: true, + triggerAction: 'all', + editable: true, + name: 'AUTH_SOURCE_ENABLED_TLS', + id: 'AUTH_SOURCE_ENABLED_TLS', + width: 130, + allowBlank: false, + value: '0', + store: [['0',_('ID_NO')],['1',_('ID_YES')]] +}); + +var ldapFormBaseDN = new Ext.form.TextField({ + fieldLabel: '*' + _('ID_BASE_DN'), + name: 'AUTH_SOURCE_BASE_DN', + id: 'AUTH_SOURCE_BASE_DN', + autoCreate: {tag: 'input', type: 'text', maxlength: '128'}, + allowBlank: false, + width: 210 +}); + +var ldapFormAnonymous = new Ext.form.ComboBox({ + valueField: 'ID', + displayField: 'VALUE', + + fieldLabel: '*' + _('ID_ANONYMOUS'), + typeAhead: true, + forceSelection: true, + triggerAction: 'all', + editable: true, + name: 'AUTH_ANONYMOUS', + id: 'AUTH_ANONYMOUS', + width: 130, + allowBlank: false, + value: '0', + store: [['0',_('ID_NO')],['1',_('ID_YES')]], + listeners:{ + select: function(combo, record) { + var arrayObject = []; + arrayObject["ldapFormSearchUser"] = ldapFormSearchUser; + arrayObject["ldapFormPassword"] = ldapFormPassword; + + ldapFormAnonymousOnChange(combo, arrayObject); + } + } +}); + +var ldapFormSearchUser = new Ext.form.TextField({ + fieldLabel: '*' + _('ID_USERNAME'), + name: 'AUTH_SOURCE_SEARCH_USER', + id: 'AUTH_SOURCE_SEARCH_USER', + autoCreate: {tag: 'input', type: 'text', maxlength: '128'}, + allowBlank: false, + width: 210 +}); + +var ldapFormPassword = new Ext.form.TextField({ + fieldLabel: '*' + _('ID_PASSWORD'), + inputType: 'password', + name: 'AUTH_SOURCE_PASSWORD', + id: 'AUTH_SOURCE_PASSWORD', + autoCreate: {tag: 'input', type: 'text', maxlength: '32'}, + allowBlank: false, + width: 210 +}); + +var ldapFormIdentifier = new Ext.form.TextField({ + fieldLabel: '*' + "User Identifier", + name: 'AUTH_SOURCE_IDENTIFIER_FOR_USER', + id: 'AUTH_SOURCE_IDENTIFIER_FOR_USER', + autoCreate: {tag: 'input', type: 'text', maxlength: '20'}, + allowBlank: false, + width: 210, + value: 'uid' +}); + +var ldapFormUsersFilter = new Ext.form.TextField({ + fieldLabel: "Filter to search users", + name: 'AUTH_SOURCE_USERS_FILTER', + id: 'AUTH_SOURCE_USERS_FILTER', + autoCreate: {tag: 'input', type: 'text', maxlength: '200'}, + allowBlank: true, + width: 210 +}); + +var ldapFormRetiredEmployees = new Ext.form.TextField({ + fieldLabel: "OU for Retired Employees OU", + name: 'AUTH_SOURCE_RETIRED_OU', + id: 'AUTH_SOURCE_RETIRED_OU', + autoCreate: {tag: 'input', type: 'text', maxlength: '128'}, + allowBlank: true, + width: 210 +}); + +var ldapFormAttrinuteIds = new Ext.form.Hidden({ + name: 'AUTH_SOURCE_ATTRIBUTE_IDS', + id: 'AUTH_SOURCE_ATTRIBUTE_IDS' +}); + +var ldapFormShowGrid = new Ext.form.Hidden({ + name: 'AUTH_SOURCE_SHOWGRID', + id: 'AUTH_SOURCE_SHOWGRID' +}); + +var ldapFormGridText = new Ext.form.Hidden({ + name: 'AUTH_SOURCE_GRID_TEXT', + id: 'AUTH_SOURCE_GRID_TEXT' +}); + + +/////////////////////////////////////////////////////////////////////////////////////// + +var ldapFormData = new Ext.form.FieldSet({ + style: { + border: "0px" + }, + + labelWidth : 170, + items :[ + ldapFormId, ldapFormName, ldapFormProvider, ldapFormType, ldapFormAutoRegister, ldapFormServerName, + ldapFormPort, ldapFormTls, ldapFormBaseDN, ldapFormAnonymous, ldapFormSearchUser, ldapFormPassword, + ldapFormIdentifier, ldapFormUsersFilter, ldapFormRetiredEmployees, + { + xtype: 'label', + fieldLabel: ' ', + id:'passwordReview', + width: 300, + style: 'font: 9px tahoma,arial,helvetica,sans-serif;', + text: "(Default set to (&(!(objectClass=organizationalUnit))))", + labelSeparator: '' + }, ldapFormAttrinuteIds, ldapFormShowGrid, ldapFormGridText + ] +}); + +var pnlData = new Ext.Panel({ + height: 425, + + bodyStyle: "border-top: 0px; padding-top: 10px;", + + title: "
" + _("ID_INFORMATION") + "
", + + items: [ldapFormData] +}); + diff --git a/workflow/engine/templates/ldapAdvanced/ldapAdvancedList.js b/workflow/engine/templates/ldapAdvanced/ldapAdvancedList.js new file mode 100755 index 000000000..42657b323 --- /dev/null +++ b/workflow/engine/templates/ldapAdvanced/ldapAdvancedList.js @@ -0,0 +1,486 @@ +Ext.onReady(function() { + //Head - Add style + var nhead = document.getElementsByTagName("head")[0]; + var nstyle = document.createElement("style"); + var strCss = "\ + .ext-mb-ok {\ + background: transparent url(/images/dialog-ok-apply.png) no-repeat top left;\ + }"; + + nstyle.setAttribute("type", "text/css"); + + nhead.appendChild(nstyle); + + if (nstyle.styleSheet) { + //IE + nstyle.styleSheet.cssText = strCss; + } else { + //Others browsers + nstyle.appendChild(document.createTextNode(strCss)); + } + + //Init + Ext.QuickTips.init(); + Ext.form.Field.prototype.msgTarget = 'side'; + + var ldapGridProxy = new Ext.data.HttpProxy({ + method: 'POST', + api: { + read : '../controllers/ldapAdvancedProxy.php?functionAccion=ldapGrid&tipo=read', + create : '../controllers/ldapAdvancedProxy.php?functionAccion=ldapGrid&tipo=create', + save : '../controllers/ldapAdvancedProxy.php?functionAccion=ldapGrid&tipo=save', + destroy : '../controllers/ldapAdvancedProxy.php?functionAccion=ldapGrid&tipo=destroy', + update : '../controllers/ldapAdvancedProxy.php?functionAccion=ldapGrid&tipo=update' + } + }); + + var ldapGridReader = new Ext.data.JsonReader({ + totalProperty: 'total', + successProperty: 'success', + messageProperty: 'message', + idProperty: 'ID', + root: 'data', + fields: [ + {name: 'ID'}, + {name: 'ATTRIBUTE_LDAP'}, + {name: 'ATTRIBUTE_USER'} + ] + }); + + var ldapGridWriter = new Ext.data.JsonWriter({ + encode: true, + writeAllFields: true, + listful: true + }); + + var ldapGridStore = new Ext.data.Store({ + proxy: ldapGridProxy, + reader: ldapGridReader, + writer: ldapGridWriter, + autoSave: true, + listeners:{ + load: function() { + // + } + } + }); + + + + Ext.data.DataProxy.addListener('beforewrite', function(proxy, action) { + /* + if(action != 'create') + { + Ext.MessageBox.show({ + msg: 'Guardando su información, espere un momento por favor', + progressText: 'Saving...', + width:300, + wait:true, + waitConfig: {interval:200}, + animEl: 'mb7' + }); + } + */ + }); + + Ext.data.DataProxy.addListener('write', function(proxy, action, result, res, rs) { + // + }); + + Ext.data.DataProxy.addListener('exception', function(proxy, type, action, options, res) { + /* + Ext.MessageBox.show({ + title: 'Error de almacenamiento', + msg: 'Error al almacenar datos', + buttons: Ext.MessageBox.OK, + animEl: 'mb9', + icon: Ext.MessageBox.ERROR + }); + */ + }); + + var ldapGridFieldLdap = new Ext.form.TextField({ + name: 'DELETE1', + id: 'DELETE1', + autoCreate: {tag: 'input', type: 'text', maxlength: '50'} + }); + + var values = Fields.AUTH_SOURCE_ATTRIBUTE_IDS; + values = values.trim(); + var allValues = new Array(); + var comboValues = new Array(); + allValues = values.split('|'); + for (var i = 0; i < allValues.length; i++) { + if (allValues[i] != '') { + comboValues.push([allValues[i],allValues[i]]); + } + } + + var ldapGridFieldUser = new Ext.form.ComboBox({ + valueField: 'ID', + displayField: 'VALUE', + value: '0', + + typeAhead: true, + forceSelection: true, + triggerAction: 'all', + name: 'DELETE2', + id: 'DELETE2', + editable: true, + width: 130, + store: comboValues + }); + + var ldapGridCol = [ + { + id: 'ID', + dataIndex: 'ID', + sortable: true, + hidden: true, + hideable:false + },{ + id: 'ATTRIBUTE_LDAP', + header: "LDAP Field", + dataIndex: 'ATTRIBUTE_LDAP', + width: 10, + sortable: true, + editor: ldapGridFieldLdap + }, + { + id: 'ATTRIBUTE_USER', + header: "User Field", + dataIndex: 'ATTRIBUTE_USER', + width: 10, + sortable: true, + editor: ldapGridFieldUser + } + ]; + + var ldapGridEditor = new Ext.ux.grid.RowEditor({ + saveText: _('ID_SAVE'), + listeners: { + canceledit: function(grid,obj){ + // + }, + afteredit: function(grid,obj,record){ + // + } + } + }); + + var ldapGrid = new Ext.grid.GridPanel({ + store: ldapGridStore, + loadMask : true, + plugins: [ldapGridEditor], + frame: true, + height: 365, + columns : ldapGridCol, + autoShow: true, + autoFill:true, + nocache: true, + autoWidth: true, + stripeRows: true, + stateful: true, + animCollapse: true, + enableColumnResize: true, + enableHdMenu: true, + columnLines: true, + + tbar: [{ + text: _('ID_ADD'), + iconCls: ' x-btn-text button_menu_ext ss_sprite ss_add', + handler: onAdd + }, '-', { + text: _('ID_REMOVE'), + iconCls: ' x-btn-text button_menu_ext ss_sprite ss_delete', + handler: onDelete + }], + viewConfig: { + forceFit: true + } + }); + + function onAdd(btn, ev) { + var row = new ldapGrid.store.recordType({ + ID: 'NUEVO', + ATTRIBUTE_LDAP: '', + ATTRIBUTE_USER: '' + }); + + var length = ldapGrid.getStore().data.length; + ldapGridEditor.stopEditing(); + ldapGridStore.insert(length, row); + ldapGrid.getView().refresh(); + ldapGrid.getSelectionModel().selectRow(length); + ldapGridEditor.startEditing(length); + } + + function onDelete() { + var rec = ldapGrid.getSelectionModel().getSelected(); + if (!rec) { + return false; + } + ldapGrid.store.remove(rec); + } + + /////////////////////////////////////////////////////////////////////////////////////// + + var pnlAttribute = new Ext.Panel({ + height: 425, + bodyStyle: "border-top: 0px; padding: 10px;", + + title: "
", + items: [ldapGrid], + + listeners: { + afterrender: function (panel) + { + var chk = new Ext.form.Checkbox({ + id: "AUTH_SOURCE_SHOWGRID-checkbox", + name: "AUTH_SOURCE_SHOWGRID-checkbox", + boxLabel: "Match attributes to sync", + renderTo: "containerChkAttribute", + + listeners: { + check: function (chk, checked) + { + ldapGrid.setVisible(checked); + } + } + }); + } + } + }); + + /////////////////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////////////////////////////////////////////////// + + var ldapFormSubmit = function () + { + var itemsLdapGrid = ldapGrid.store.data.items; + var arrayDetail = []; + + for (var i = 0; i <= itemsLdapGrid.length - 1; i++) { + var newItem = { + attributeLdap: itemsLdapGrid[i].data.ATTRIBUTE_LDAP, + attributeUser: itemsLdapGrid[i].data.ATTRIBUTE_USER + }; + + arrayDetail[i] = newItem; + } + + Ext.get("LDAP_TYPE").dom.value = ldapFormType.getValue(); + Ext.get("AUTH_SOURCE_AUTO_REGISTER").dom.value = ldapFormAutoRegister.getValue(); + Ext.get("AUTH_SOURCE_ENABLED_TLS").dom.value = ldapFormTls.getValue(); + Ext.get("AUTH_ANONYMOUS").dom.value = ldapFormAnonymous.getValue(); + Ext.get("AUTH_SOURCE_GRID_TEXT").dom.value = Ext.util.JSON.encode(arrayDetail); + + ldapForm.getForm().submit({ + method: "POST", + waitTitle: "Connecting...", + waitMsg: _("ID_SAVING"), + success: function (form, action) + { + redirectPage("../authSources/authSources_List?" + randomNum(1, 9999999)); + }, + failure: function (form, action) + { + // + } + }); + }; + + var ldapForm = new Ext.FormPanel({ + url : '../controllers/ldapAdvancedProxy.php?functionAccion=ldapSave', + frame : true, + title : "Authentication Source Information", + border : false, + autoScroll: true, + monitorValid : true, + + items:[ + { + layout:'column', + autoScroll:true, + + bodyStyle: "border: 0px;", + + items:[{ + columnWidth: 0.5, + bodyStyle: "border: 0px;", + items: [pnlData] + },{ + columnWidth: 0.5, + bodyStyle: "border: 0px; padding-left: 10px;", + items: [pnlAttribute] + }] + }, + { + layout: "column", + autoScroll: true, + + bodyStyle: "margin-top: 0.5em; border: 0px;", + + items: [ + { + columnWidth: 1, + bodyStyle: "border: 0px;", + html: "Minimum data required to run the \"Test Connection\": \"Server Address, " + _("ID_PORT") + ", " + _("ID_ENABLED_TLS") + ", " + _("ID_ANONYMOUS") + ", " + _("ID_USERNAME") + ", " + _("ID_PASSWORD") + "\"" + } + ] + } + ], + buttons: [ + { + text: _("ID_SAVE"), + formBind: true, + handler: function () + { + if (typeof(Fields.AUTH_SOURCE_UID) != "undefined" && typeof(Fields.AUTH_SOURCE_BASE_DN) != "undefined" && ldapFormBaseDN.getValue() != Fields.AUTH_SOURCE_BASE_DN) { + Ext.Ajax.request({ + url: "../controllers/ldapAdvancedProxy.php", + method: "POST", + params: { + functionAccion: "ldapVerifyIfExistsRecordsInDb", + authenticationSourceUid: Fields.AUTH_SOURCE_UID + }, + + success: function (response, opts) + { + var dataResponse = Ext.util.JSON.decode(response.responseText); + + if (dataResponse.status) { + if (dataResponse.status == "OK" && dataResponse.existsRecords + "" == "1") { + Ext.MessageBox.confirm( + _("ID_CONFIRM"), + "System has detected that there are synchronized elements with the \"Authentication Source \" you are editing, if you change the \"Base DN\" those synchronized elements could have problems. Are you sure you want to change the \"Base DN\"?", + function (btn) + { + if (btn == "yes") { + ldapFormSubmit(); + } + } + ); + } else { + ldapFormSubmit(); + } + } else { + ldapFormSubmit(); + } + }, + failure: function (response, opts) + { + // + } + }); + } else { + ldapFormSubmit(); + } + } + }, + { + text: "Test connection", + formBind: true, + handler: function () + { + var loadMaskAux = new Ext.LoadMask(Ext.getBody(), {msg: "Testing connection..."}); + loadMaskAux.show(); + + Ext.Ajax.request({ + url: "../controllers/ldapAdvancedProxy.php", + method: "POST", + params: { + functionAccion: "ldapTestConnection", + AUTH_SOURCE_SERVER_NAME: Ext.getCmp("AUTH_SOURCE_SERVER_NAME").getValue(), + AUTH_SOURCE_PORT: Ext.getCmp("AUTH_SOURCE_PORT").getValue(), + AUTH_SOURCE_ENABLED_TLS: Ext.getCmp("AUTH_SOURCE_ENABLED_TLS").getValue(), + AUTH_ANONYMOUS: Ext.getCmp("AUTH_ANONYMOUS").getValue(), + AUTH_SOURCE_SEARCH_USER: Ext.getCmp("AUTH_SOURCE_SEARCH_USER").getValue(), + AUTH_SOURCE_PASSWORD: Ext.getCmp("AUTH_SOURCE_PASSWORD").getValue(), + AUTH_SOURCE_VERSION: 3 + }, + + success: function (response, opts) + { + var dataResponse = Ext.util.JSON.decode(response.responseText); + + if (dataResponse.status) { + Ext.MessageBox.show({ + title: "Test connection", + msg: (dataResponse.status == "OK")? "Successfully connected" : dataResponse.message, + + icon: (dataResponse.status == "OK")? "ext-mb-ok" : Ext.MessageBox.ERROR, + buttons: {ok: _("ID_ACCEPT")} + }); + } + + loadMaskAux.hide(); + }, + failure: function (response, opts) + { + loadMaskAux.hide(); + } + }); + } + }, + { + text: _("ID_CANCEL"), + handler: function () + { + redirectPage("../authSources/authSources_List?" + randomNum(1, 9999999)); + } + } + ] + }); + + var gridAttribute = ''; + if (typeof(Fields.AUTH_SOURCE_UID) == 'undefined' || Fields.AUTH_SOURCE_UID == '') { + ldapFormProvider.setValue(Fields.AUTH_SOURCE_PROVIDER); + ldapFormAttrinuteIds.setValue(Fields.AUTH_SOURCE_ATTRIBUTE_IDS); + gridAttribute = ''; + } else { + ldapFormId.setValue(Fields.AUTH_SOURCE_UID); + ldapFormName.setValue(Fields.AUTH_SOURCE_NAME); + ldapFormProvider.setValue(Fields.AUTH_SOURCE_PROVIDER); + ldapFormType.setValue(Fields.LDAP_TYPE); + ldapFormAutoRegister.setValue(Fields.AUTH_SOURCE_AUTO_REGISTER); + ldapFormServerName.setValue(Fields.AUTH_SOURCE_SERVER_NAME); + + ldapFormPort.setValue(Fields.AUTH_SOURCE_PORT); + ldapFormTls.setValue(Fields.AUTH_SOURCE_ENABLED_TLS); + ldapFormBaseDN.setValue(Fields.AUTH_SOURCE_BASE_DN); + ldapFormAnonymous.setValue(Fields.AUTH_ANONYMOUS); + ldapFormSearchUser.setValue(Fields.AUTH_SOURCE_SEARCH_USER); + ldapFormPassword.setValue(Fields.AUTH_SOURCE_PASSWORD); + ldapFormIdentifier.setValue(Fields.AUTH_SOURCE_IDENTIFIER_FOR_USER); + ldapFormUsersFilter.setValue(Fields.AUTH_SOURCE_USERS_FILTER); + ldapFormRetiredEmployees.setValue(Fields.AUTH_SOURCE_RETIRED_OU); + + if (typeof(Fields.AUTH_SOURCE_GRID_ATTRIBUTE) != 'undefined') { + gridAttribute = Ext.util.JSON.encode(Fields.AUTH_SOURCE_GRID_ATTRIBUTE); + } + } + + ldapGridStore.load({ + params:{'data': gridAttribute} + }); + + var arrayObject = []; + arrayObject["ldapFormSearchUser"] = ldapFormSearchUser; + arrayObject["ldapFormPassword"] = ldapFormPassword; + + ldapFormAnonymousOnChange(ldapFormAnonymous, arrayObject); + + new Ext.Viewport({ + layout:'fit', + border: false, + items: [ldapForm] + }); + + ldapFormProvider.setValue(Fields.AUTH_SOURCE_PROVIDER); + ldapFormAttrinuteIds.setValue(Fields.AUTH_SOURCE_ATTRIBUTE_IDS); + + Ext.getCmp("AUTH_SOURCE_SHOWGRID-checkbox").setValue(typeof(Fields.AUTH_SOURCE_GRID_ATTRIBUTE) != "undefined"); + ldapGrid.setVisible(typeof(Fields.AUTH_SOURCE_GRID_ATTRIBUTE) != "undefined"); +}); + diff --git a/workflow/engine/templates/ldapAdvanced/ldapAdvancedSearch.js b/workflow/engine/templates/ldapAdvanced/ldapAdvancedSearch.js new file mode 100644 index 000000000..b33c19090 --- /dev/null +++ b/workflow/engine/templates/ldapAdvanced/ldapAdvancedSearch.js @@ -0,0 +1,317 @@ +Ext.onReady(function() { + Ext.QuickTips.init(); + Ext.form.Field.prototype.msgTarget = 'side'; + + ///////////////////////////////// + ///// PANEL SEARCH USERS + ///////////////////////////////// + + //Variables + var pageSize = parseInt(CONFIG.pageSize); + + //Components + var searchUsersText = new Ext.form.TextField({ + width: 280, + allowBlank: true, + listeners:{ + specialkey:function(f,o){ + if(o.getKey()==13){ + storeGridSearch.load({ params: {sKeyword: searchUsersText.getValue()} }); + } + } + } + }); + + var compSearchUsers = new Ext.form.CompositeField({ + fieldLabel: 'Keyword', + labelStyle: 'width:100px; padding: 3px 3px 3px 15px;', + items: [ + searchUsersText, + { + xtype: 'button', + iconCls: 'button_menu_ext ss_sprite ss_magnifier', + text: 'Search', + width : 40, + handler: function(){ + storeGridSearch.load({ params: {sKeyword: searchUsersText.getValue()} }); + } + } + ] + }); + + var panelSearch = new Ext.Panel({ + region: 'north', + height: 65, + margins: '0 0 0 0', + frame: true, + labelAlign: 'left', + align: 'center', + labelStyle: 'font-weight:bold; padding: 3px 3px 3px 15px;', + title: "
" + "Search for user" + "
", + items: [ + new Ext.FormPanel({ + labelWidth : 120, + labelStyle: 'padding: 3px 3px 3px 15px;', + autoScroll: false, + monitorValid : true, + bodyStyle: "border: 0px;", + items:[ + compSearchUsers + ] + }) + ], + + listeners: { + afterrender: function (panel) + { + var btn = new Ext.Button({ + text: _("ID_BACK"), + iconCls: "button_menu_ext ss_sprite ss_arrow_left", + renderTo: "divBack", + + handler: function () + { + redirectPage("authSources_List"); + } + }); + } + } + }); + + + + + ///////////////////////////////// + ///// GRID SEARCH USERS + ///////////////////////////////// + + + var storeGridSearch = new Ext.data.JsonStore({ + proxy: new Ext.data.HttpProxy({ + method: 'POST', + url: '../controllers/ldapAdvancedProxy.php', + timeout: 240000 + }), + autoDestroy: true, + remoteSort: false, + totalProperty: "resultTotal", + root: "resultRoot", + fields: [ + 'sUsername', + 'sFullname', + 'sFirstname', + 'sLastname', + 'sEmail', + 'sCategory', + 'sDN', + 'sManagerDN', + 'STATUS', + 'IMPORT' + ], + listeners: { + beforeload: function (store, opt) + { + this.baseParams = { + functionAccion: "searchUsers", + sUID: Fields.AUTH_SOURCE_UID, + sKeyword: searchUsersText.getValue(), + pageSize: pageSize + }; + }, + load: function (store, record, opt) + { + Ext.getCmp('BUTTON_IMPORT').disable(); + } + } + }); + storeGridSearch.setDefaultSort('sUsername', 'asc'); + + var tbarSearch = [ + { + id: 'BUTTON_IMPORT', + text: 'Import', + iconCls: 'button_menu_ext ss_sprite ss_group_go ', + disabled: true, + handler: function () { + rowSelected = gridSearch.getSelectionModel().getSelected(); + var auxUsersSelect = gridSearch.getSelectionModel().selections.items; + var countSelect = auxUsersSelect.length; + + if (countSelect != 0) { + var con = 0; + var usersSelect = new Array(); + var numberCases = ''; + while (con < countSelect) { + if (auxUsersSelect[con].data.IMPORT == 1) { + var newArray = { + sUsername : auxUsersSelect[con].data.sUsername, + sFullname : auxUsersSelect[con].data.sFullname, + sFirstname : auxUsersSelect[con].data.sFirstname, + sLastname : auxUsersSelect[con].data.sLastname, + sEmail : auxUsersSelect[con].data.sEmail, + sCategory : auxUsersSelect[con].data.sCategory, + sDN : auxUsersSelect[con].data.sDN, + sManagerDN : auxUsersSelect[con].data.sManagerDN + }; + usersSelect.push(newArray); + } + con++; + } + + var countImport = usersSelect.length; + if (countImport != 0) { + Ext.MessageBox.confirm('Confirm', 'Are you sure you want to import the selected users?', function (val) { + if (val == 'yes') { + Ext.MessageBox.show({ + msg: 'Importing Users...', + progressText: 'Saving...', + width:300, + wait:true, + waitConfig: {interval:200}, + animEl: 'mb7' + }); + + Ext.Ajax.request({ + params: { + 'UsersImport': Ext.encode(usersSelect), + 'functionAccion': 'importUsers', + 'AUTH_SOURCE_UID': Fields.AUTH_SOURCE_UID + }, + url : '../controllers/ldapAdvancedProxy.php', + success: function (returnData) { + var resp = Ext.decode(returnData.responseText); + Ext.MessageBox.hide(); + if (resp.success) { + Ext.MessageBox.show({ + title: 'Import Users', + msg: 'Imported Successfully', + buttons: Ext.MessageBox.OK, + animEl: 'mb9', + icon: Ext.MessageBox.INFO + }); + redirectPage('../users/users_List'); + } + }, + failure: function () { + Ext.MessageBox.alert('ERROR', 'Error in server'); + } + }); + } + }); + } else { + PMExt.notify('WARNING', 'You do not select any user to import'); + } + } else { + PMExt.notify('WARNING', 'You do not select any user to import'); + } + } + } + ]; + + //var pageSize = parseInt(CONFIG.pageSize); + // + //var storePageSize = new Ext.data.SimpleStore({ + // autoLoad: true, + // fields: ['size'], + // data:[['20'],['30'],['40'],['50'],['100']] + //}); + // + //var comboPageSize = new Ext.form.ComboBox({ + // typeAhead : false, + // mode : 'local', + // triggerAction : 'all', + // store: storePageSize, + // valueField: 'size', + // displayField: 'size', + // width: 50, + // editable: false, + // listeners:{ + // select: function(c,d,i){ + // pagingSearchList.pageSize = parseInt(d.data['size']); + // pagingSearchList.moveFirst(); + // } + // } + //}); + // + //comboPageSize.setValue(pageSize); + // + //var pagingSearchList = new Ext.PagingToolbar({ + // pageSize : 1000, + // store : storeGridSearch, + // displayInfo : true, + // autoHeight : true, + // displayMsg : 'Ldap Users' + ' {0} - {1} ' + 'of' + ' {2}', + // emptyMsg : ' There are no LDAP Users '//, + // //items: [ + // //comboPageSize + // //] + //}); + + var pagingSearchList = new Ext.PagingToolbar({ + pageSize: pageSize, + store: storeGridSearch, + displayInfo: true, + displayMsg: "LDAP Users" + " {0} - {1} " + "of" + " {2}", + emptyMsg: "There are no LDAP Users" + }); + + var selectModelList = new Ext.grid.CheckboxSelectionModel({ + listeners: { + selectionchange: function() { + if (selectModelList.getCount() > 0) { + Ext.getCmp('BUTTON_IMPORT').enable(); + } else { + Ext.getCmp('BUTTON_IMPORT').disable(); + } + } + } + }); + + var gridSearch = new Ext.grid.GridPanel({ + store : storeGridSearch, + tbar : tbarSearch, + bbar : pagingSearchList, + region: 'center', + margins: '0 0 0 0', + loadMask : true, + sm: selectModelList, + + cm: new Ext.grid.ColumnModel({ + defaults: { + sortable: true + }, + columns: [ + selectModelList, + {header: 'Username', width: 15, dataIndex: 'sUsername', sortable: true}, + {header: 'First Name', width: 15, dataIndex: 'sFirstname', sortable: true}, + {header: 'Last Name', width: 15, dataIndex: 'sLastname', sortable: true}, + {header: 'Email', width: 15, dataIndex: 'sEmail', sortable: true}, + {header: 'Distinguished Name', width: 35, dataIndex: 'sDN'}, + {dataIndex: "STATUS", header: _("ID_STATUS"), width: 10, css: "background: #D4D4D4; font-weight: bold;", align: "center", renderer: renderStatus} + ] + }), + border: false, + autoShow: true, + autoFill:true, + nocache: true, + autoWidth: true, + stripeRows: true, + stateful: true, + animCollapse: true, + enableColumnResize: true, + enableHdMenu: true, + columnLines: true, + + viewConfig: { + forceFit:true, + emptyText: '
' + ' There are no LDAP Users ' + '
' + } + }); + + new Ext.Viewport({ + layout:'border', + border: false, + items: [panelSearch, gridSearch] + }); +}); + diff --git a/workflow/engine/templates/ldapAdvanced/library.js b/workflow/engine/templates/ldapAdvanced/library.js new file mode 100755 index 000000000..371582778 --- /dev/null +++ b/workflow/engine/templates/ldapAdvanced/library.js @@ -0,0 +1,15 @@ +function redirectPage(page){ + window.location = page; +} + +function randomNum(inf, sup){ + numPos = sup - inf; + aleat = Math.random() * numPos; + aleat = Math.round(aleat); + return parseInt(inf) + aleat; +} + +function renderStatus (data, metadata, record, rowIndex, columnIndex, store) { + return "" + record.data.STATUS.toUpperCase() + ""; +} + diff --git a/workflow/engine/templates/ldapAdvanced/searchSummary.js b/workflow/engine/templates/ldapAdvanced/searchSummary.js new file mode 100755 index 000000000..39103f28d --- /dev/null +++ b/workflow/engine/templates/ldapAdvanced/searchSummary.js @@ -0,0 +1,180 @@ +var caseData = ''; +var appTitle = new Ext.form.Label({ + fieldLabel: "Case Title", + labelStyle: 'font-weight:bold;padding-right:30px;' +}); + +var process = new Ext.form.Label({ + fieldLabel: "Process Uid", + labelStyle: 'font-weight:bold;padding-right:35px;' +}); + +var processTitle = new Ext.form.Label({ + fieldLabel: "Process", + labelStyle: 'font-weight:bold;padding-right:35px;' +}); + +var appUid = new Ext.form.Label({ + fieldLabel: "App Uid", + labelStyle: 'font-weight:bold;padding-right:35px;' +}); + +var caseNumber = new Ext.form.Label({ + fieldLabel: "Case number", + labelStyle: 'font-weight:bold;padding-right:35px;' +}); + +var initUser = new Ext.form.Label({ + fieldLabel: "Init user", + labelStyle: 'font-weight:bold;padding-right:35px;' +}); + +var finishUser = new Ext.form.Label({ + fieldLabel: "Finish user", + labelStyle: 'font-weight:bold;padding-right:35px;' +}); + +var createDate = new Ext.form.Label({ + fieldLabel: "Create date", + labelStyle: 'font-weight:bold;padding-right:35px;' +}); + +var finishDate = new Ext.form.Label({ + fieldLabel: "Finish date", + labelStyle: 'font-weight:bold;padding-right:35px;' +}); + +var fileName = new Ext.form.Label({ + fieldLabel: "File Name", + labelStyle: 'font-weight:bold;padding-right:35px;' +}); + +var statusCaseWin = new Ext.form.Label({ + fieldLabel: "Status", + labelStyle: 'font-weight:bold;padding-right:35px;' +}); + +var formCase = new Ext.FormPanel({ + labelWidth : 120, + labelAlign : 'right', + autoScroll: true, + frame: true, + bodyStyle : 'padding-top:20px;padding-left:20px;', + items:[ + appTitle, + caseNumber, + processTitle, + initUser, + finishUser, + createDate, + finishDate, + fileName, + statusCaseWin + ], + buttons:[{ + text : "Restore case", + id: 'BUTTON_UNARCHIVE_CASE', + iconCls: 'button_menu_ext ss_sprite ss_folder_go', + formBind : true, + handler : function(){ + if (caseData!='') { + Ext.MessageBox.confirm("Confirm", "Are you sure you want to restore the case?", function (val) { + if (val == 'yes') { + dataCase = caseData; + Ext.MessageBox.show({ + msg: "Restoring case" + ' ' + dataCase.CASE_NUMBER + ' ...', + progressText: 'Saving...', + width:300, + wait:true, + waitConfig: {interval:200}, + animEl: 'mb7' + }); + Ext.Ajax.request({ + params: { + 'APP_UID': dataCase.APP_UID, + 'FILENAME_TAR': dataCase.FILENAME_TAR, + 'functionExecute': 'unarchiveCase' + }, + url : 'controllers/searchListProxy.php', + success: function (returnData) { + Ext.MessageBox.hide(); + + var resp = Ext.decode(returnData.responseText); + if (resp.success) { + Ext.MessageBox.show({ + title: 'Case Unarhive', + msg: "Case" + ' ' + dataCase.CASE_NUMBER + ' ' + "Restored sucessfully", + buttons: Ext.MessageBox.OK, + animEl: 'mb9', + icon: Ext.MessageBox.INFO + }); + } else { + Ext.MessageBox.show({ + title: "Error", + msg: resp.message, + buttons: Ext.MessageBox.OK, + animEl: 'mb9', + icon: Ext.MessageBox.ERROR + }); + } + + storeGridSearch.load(); + }, + failure: function () { + Ext.MessageBox.alert("Error", "Error in server"); + } + }); + } + }); + } + } + }, + { + text : _('ID_CLOSE'), + iconCls: 'button_menu_ext ss_sprite ss_folder_delete', + formBind : true, + handler : function(){ + summaryWindow.hide(); + } + }] +}); + +var summaryWindow = new Ext.Window({ + title: "Detail Case", + layout: 'fit', + width: 500, + height: 320, + resizable: true, + closable: true, + closeAction : 'hide', + modal: true, + autoScroll:true, + constrain: true, + items: [formCase] +}); + +function showCaseSummary(dataCase) { + if (dataCase) { + caseData = dataCase; + + if(dataCase.STATUS == 'RESTORED'){ + Ext.getCmp('BUTTON_UNARCHIVE_CASE').disable(); + } else { + Ext.getCmp('BUTTON_UNARCHIVE_CASE').enable(); + } + + appTitle.setText(dataCase.APP_TITLE, false); + process.setText(dataCase.PRO_UID, false); + processTitle.setText(dataCase.PRO_TITLE, false); + appUid.setText(dataCase.APP_UID, false); + caseNumber.setText(dataCase.CASE_NUMBER, false); + initUser.setText(dataCase.INIT_USER_NAME, false); + finishUser.setText(dataCase.FINISH_USER_NAME, false); + createDate.setText(renderDate(dataCase.CREATE_DATE, false)); + finishDate.setText(renderDate(dataCase.FINISH_DATE, false)); + fileName.setText(dataCase.FILENAME_TAR+'.tar', false); + statusCaseWin.setText(dataCase.STATUS, false); + + summaryWindow.show(); + } +} \ No newline at end of file diff --git a/workflow/engine/xmlform/ldapAdvanced/gridAttribute.xml b/workflow/engine/xmlform/ldapAdvanced/gridAttribute.xml new file mode 100755 index 000000000..f12719a4f --- /dev/null +++ b/workflow/engine/xmlform/ldapAdvanced/gridAttribute.xml @@ -0,0 +1,11 @@ + + + + + + + + + + + diff --git a/workflow/engine/xmlform/ldapAdvanced/ldapAdvanced.xml b/workflow/engine/xmlform/ldapAdvanced/ldapAdvanced.xml new file mode 100755 index 000000000..47f95847b --- /dev/null +++ b/workflow/engine/xmlform/ldapAdvanced/ldapAdvanced.xml @@ -0,0 +1,11 @@ + + + + <en><![CDATA[Ldap Advance Plugin]]></en> + <pt-BR><![CDATA[Ldap Plugin Adiantamento]]></pt-BR> + + + + + + diff --git a/workflow/engine/xmlform/ldapAdvanced/ldapAdvancedEdit.xml b/workflow/engine/xmlform/ldapAdvanced/ldapAdvancedEdit.xml new file mode 100755 index 000000000..6d29c5bad --- /dev/null +++ b/workflow/engine/xmlform/ldapAdvanced/ldapAdvancedEdit.xml @@ -0,0 +1,215 @@ + + + + <en><![CDATA[Authentication Source Information]]></en> + <pt-BR><![CDATA[Informações de fonte de autenticação]]></pt-BR> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Match attributes to sync]]> + Combinar atributos para sincronizar]]> + + + + + + + + + + + + + + + + + + + + + diff --git a/workflow/engine/xmlform/ldapAdvanced/ldapAdvancedFlag b/workflow/engine/xmlform/ldapAdvanced/ldapAdvancedFlag new file mode 100755 index 000000000..63791173b --- /dev/null +++ b/workflow/engine/xmlform/ldapAdvanced/ldapAdvancedFlag @@ -0,0 +1 @@ +Bandera para habilitar nueva interfaz extjs From 952a7f5d317bb29db46558aec97fc6ca366a1ea3 Mon Sep 17 00:00:00 2001 From: "Paula V. Quispe" Date: Thu, 11 Jun 2015 11:08:56 -0400 Subject: [PATCH 02/11] PM-1060: Second migration ldapAdvanced --- .../methods/authSources/authSources_Edit.php | 23 +- .../methods/authSources/ldapAdvancedProxy.php | 348 ++++++++++++++++++ .../templates/ldapAdvanced/authSourcesList.js | 46 +++ .../ldapAdvanced/authSourcesSynchronize.html | 3 + .../ldapAdvanced/authSourcesSynchronize.js | 229 ++++++++++++ .../ldapAdvanced/ldapAdvancedList.js | 16 +- .../ldapAdvanced/ldapAdvancedSearch.js | 4 +- 7 files changed, 643 insertions(+), 26 deletions(-) create mode 100755 workflow/engine/methods/authSources/ldapAdvancedProxy.php create mode 100755 workflow/engine/templates/ldapAdvanced/authSourcesList.js create mode 100755 workflow/engine/templates/ldapAdvanced/authSourcesSynchronize.html create mode 100755 workflow/engine/templates/ldapAdvanced/authSourcesSynchronize.js diff --git a/workflow/engine/methods/authSources/authSources_Edit.php b/workflow/engine/methods/authSources/authSources_Edit.php index cbf4024c1..af572405f 100755 --- a/workflow/engine/methods/authSources/authSources_Edit.php +++ b/workflow/engine/methods/authSources/authSources_Edit.php @@ -83,17 +83,8 @@ if ($fields['AUTH_SOURCE_PROVIDER'] == 'ldap') { $oHeadPublisher->assign( 'sUID', $_GET['sUID'] ); G::RenderPage( 'publish', 'extJs' ); } else { - if (file_exists( PATH_PLUGINS . $fields['AUTH_SOURCE_PROVIDER'] . PATH_SEP . $fields['AUTH_SOURCE_PROVIDER'] . 'Edit.xml' )) { - $pluginEnabled = 0; - - if (file_exists(PATH_PLUGINS . $fields["AUTH_SOURCE_PROVIDER"] . ".php")) { - $pluginRegistry = &PMPluginRegistry::getSingleton(); - $pluginDetail = $pluginRegistry->getPluginDetails($fields["AUTH_SOURCE_PROVIDER"] . ".php"); - - if ($pluginDetail && $pluginDetail->enabled) { - $pluginEnabled = 1; - } - } + if (file_exists( PATH_XMLFORM . 'ldapAdvanced/' . $fields['AUTH_SOURCE_PROVIDER'] . 'Edit.xml' )) { + $pluginEnabled = 1; if ($pluginEnabled == 1) { //The attributes the users @@ -110,17 +101,17 @@ if ($fields['AUTH_SOURCE_PROVIDER'] == 'ldap') { } $fields["AUTH_SOURCE_ATTRIBUTE_IDS"] = $attributes; - if (file_exists(PATH_PLUGINS . $fields["AUTH_SOURCE_PROVIDER"] . PATH_SEP . $fields["AUTH_SOURCE_PROVIDER"] . 'Flag')) { + if (file_exists(PATH_XMLFORM . 'ldapAdvanced/' . $fields['AUTH_SOURCE_PROVIDER'] . 'Flag')) { $oHeadPublisher = & headPublisher::getSingleton (); $oHeadPublisher->assign("Fields", $fields); - $oHeadPublisher->addExtJsScript (PATH_PLUGINS . $fields["AUTH_SOURCE_PROVIDER"] . PATH_SEP . 'js' . PATH_SEP . 'library', false, true ); - $oHeadPublisher->addExtJsScript (PATH_PLUGINS . $fields["AUTH_SOURCE_PROVIDER"] . PATH_SEP . 'js' . PATH_SEP . 'ldapAdvancedForm', false, true ); - $oHeadPublisher->addExtJsScript (PATH_PLUGINS . $fields["AUTH_SOURCE_PROVIDER"] . PATH_SEP . 'js' . PATH_SEP . 'ldapAdvancedList', false, true ); + $oHeadPublisher->addExtJsScript (PATH_TPL. 'ldapAdvanced/library.js', false, true ); + $oHeadPublisher->addExtJsScript (PATH_TPL. 'ldapAdvanced/ldapAdvancedForm', false, true ); + $oHeadPublisher->addExtJsScript (PATH_TPL. 'ldapAdvanced/ldapAdvancedList', false, true ); G::RenderPage ('publish', 'extJs'); die(); } - $G_PUBLISH->AddContent("xmlform", "xmlform", $fields["AUTH_SOURCE_PROVIDER"] . PATH_SEP . $fields["AUTH_SOURCE_PROVIDER"] . "Edit", "", $fields, "../authSources/authSources_Save"); + $G_PUBLISH->AddContent("xmlform", "xmlform", 'ldapAdvanced/' . $fields['AUTH_SOURCE_PROVIDER'] . 'Edit', '', $fields, '../authSources/authSources_Save'); } else { $G_PUBLISH->AddContent( 'xmlform', 'xmlform', 'login/showMessage', '', array ('MESSAGE' => G::LoadTranslation( 'ID_AUTH_SOURCE_MISSING' ) ) ); diff --git a/workflow/engine/methods/authSources/ldapAdvancedProxy.php b/workflow/engine/methods/authSources/ldapAdvancedProxy.php new file mode 100755 index 000000000..ed8f9d255 --- /dev/null +++ b/workflow/engine/methods/authSources/ldapAdvancedProxy.php @@ -0,0 +1,348 @@ +getAuthSource($authenticationSourceUid); + + $flagUser = false; + $flagDepartment = false; + $flagGroup = false; + + //Users + $criteria = new Criteria("rbac"); + + $criteria->addSelectColumn(RbacUsersPeer::USR_UID); + $criteria->add(RbacUsersPeer::USR_AUTH_USER_DN, "%" . $arrayAuthenticationSourceData["AUTH_SOURCE_BASE_DN"], Criteria::LIKE); + $criteria->setOffset(0); //Start + $criteria->setLimit(1); //Limit + + $rsCriteria = RbacUsersPeer::doSelectRS($criteria); + $rsCriteria->setFetchmode(ResultSet::FETCHMODE_ASSOC); + + if ($rsCriteria->next()) { + $flagUser = true; + } + + //Departments + $criteria = new Criteria("workflow"); + + $criteria->addSelectColumn(DepartmentPeer::DEP_UID); + $criteria->add(DepartmentPeer::DEP_LDAP_DN, "%" . $arrayAuthenticationSourceData["AUTH_SOURCE_BASE_DN"], Criteria::LIKE); + $criteria->setOffset(0); //Start + $criteria->setLimit(1); //Limit + + $rsCriteria = DepartmentPeer::doSelectRS($criteria); + $rsCriteria->setFetchmode(ResultSet::FETCHMODE_ASSOC); + + if ($rsCriteria->next()) { + $flagDepartment = true; + } + + //Groups + $criteria = new Criteria("workflow"); + + $criteria->addSelectColumn(GroupwfPeer::GRP_UID); + $criteria->add(GroupwfPeer::GRP_LDAP_DN, "%" . $arrayAuthenticationSourceData["AUTH_SOURCE_BASE_DN"], Criteria::LIKE); + $criteria->setOffset(0); //Start + $criteria->setLimit(1); //Limit + + $rsCriteria = GroupwfPeer::doSelectRS($criteria); + $rsCriteria->setFetchmode(ResultSet::FETCHMODE_ASSOC); + + if ($rsCriteria->next()) { + $flagGroup = true; + } + + //Response + $response["status"] = "OK"; + $response["existsRecords"] = ($flagUser || $flagDepartment || $flagGroup)? 1 : 0; + } catch (Exception $e) { + //Response + $response["status"] = "ERROR"; + $response["message"] = $e->getMessage(); + } + + echo G::json_encode($response); + break; + case 'ldapGrid': + $data = array(); + switch ($_REQUEST['tipo']) { + case 'crear': + $data = array('ID' => G::generateUniqueID()); + break; + case 'read': + if (isset($_REQUEST['data']) && $_REQUEST['data'] != '') { + $dataValue = G::json_decode($_REQUEST['data']); + $data = array(); + foreach ($dataValue as $value) { + $data[] = array( + 'ID' => G::generateUniqueID(), + 'ATTRIBUTE_LDAP' => $value->attributeLdap, + 'ATTRIBUTE_USER' => $value->attributeUser + ); + } + } + break; + default: + break; + } + echo G::json_encode(array('success'=> true, 'data' => $data, 'message'=>'Created Quote', 'total' => count($data))); + break; + case 'ldapSave': + if (isset($_POST['AUTH_SOURCE_SHOWGRID-checkbox'])) { + if ($_POST['AUTH_SOURCE_SHOWGRID-checkbox'] == 'on') { + $_POST['AUTH_SOURCE_SHOWGRID'] = 'on'; + $attributes = G::json_decode($_POST['AUTH_SOURCE_GRID_TEXT']); + $con = 1; + foreach ($attributes as $value) { + $_POST['AUTH_SOURCE_GRID_ATTRIBUTE'][$con] = (array)$value; + $con++; + } + } + unset($_POST['AUTH_SOURCE_SHOWGRID-checkbox']); + } + + if ($_POST['AUTH_ANONYMOUS'] == '1') { + $_POST['AUTH_SOURCE_SEARCH_USER'] = ''; + $_POST['AUTH_SOURCE_PASSWORD'] = ''; + } + + if (isset($_POST['AUTH_SOURCE_GRID_TEXT'])) { + unset($_POST['AUTH_SOURCE_GRID_TEXT']); + } + if (isset($_POST['DELETE1'])) { + unset($_POST['DELETE1']); + } + if (isset($_POST['DELETE2'])) { + unset($_POST['DELETE2']); + } + if (isset($_POST['AUTH_SOURCE_ATTRIBUTE_IDS'])) { + unset($_POST['AUTH_SOURCE_ATTRIBUTE_IDS']); + } + if (isset($_POST['AUTH_SOURCE_SHOWGRID_FLAG'])) { + unset($_POST['AUTH_SOURCE_SHOWGRID_FLAG']); + } + if (isset($_POST['AUTH_SOURCE_GRID_TEXT'])) { + unset($_POST['AUTH_SOURCE_GRID_TEXT']); + } + + $aCommonFields = array ('AUTH_SOURCE_UID','AUTH_SOURCE_NAME','AUTH_SOURCE_PROVIDER','AUTH_SOURCE_SERVER_NAME','AUTH_SOURCE_PORT','AUTH_SOURCE_ENABLED_TLS','AUTH_ANONYMOUS','AUTH_SOURCE_SEARCH_USER','AUTH_SOURCE_PASSWORD','AUTH_SOURCE_VERSION','AUTH_SOURCE_BASE_DN','AUTH_SOURCE_OBJECT_CLASSES','AUTH_SOURCE_ATTRIBUTES'); + + $aFields = $aData = array (); + foreach ($_POST as $sField => $sValue) { + if (in_array( $sField, $aCommonFields )) { + $aFields[$sField] = $sValue; + } else { + $aData[$sField] = $sValue; + } + } + + if (!isset($aData['AUTH_SOURCE_SHOWGRID']) || $aData['AUTH_SOURCE_SHOWGRID'] == 'off') { + unset($aData['AUTH_SOURCE_GRID_ATTRIBUTE']); + unset($aData['AUTH_SOURCE_SHOWGRID']); + } + $aFields['AUTH_SOURCE_DATA'] = $aData; + if ($aFields['AUTH_SOURCE_UID'] == '') { + $RBAC->createAuthSource( $aFields ); + } else { + $RBAC->updateAuthSource( $aFields ); + } + echo G::json_encode(array('success'=> true)); + break; + case "searchUsers": + $response = array(); + + try { + $pageSize = $_POST["pageSize"]; + + $authenticationSourceUid = $_POST["sUID"]; + $keyword = $_POST["sKeyword"]; + $start = (isset($_POST["start"]))? $_POST["start"]: 0; + $limit = (isset($_POST["limit"]))? $_POST["limit"]: $pageSize; + + //Get Users from Database + $arrayUser = array(); + + $criteria = new Criteria("workflow"); + + $criteria->addSelectColumn(UsersPeer::USR_USERNAME); + $criteria->add(UsersPeer::USR_STATUS, "CLOSED", Criteria::NOT_EQUAL); + + $rsCriteria = UsersPeer::doSelectRS($criteria); + $rsCriteria->setFetchmode(ResultSet::FETCHMODE_ASSOC); + + while ($rsCriteria->next()) { + $row = $rsCriteria->getRow(); + + $arrayUser[$row["USR_USERNAME"]] = 1; + } + + //Get data + $arrayData = array(); + + $ldapAdvanced = new ldapAdvanced(); + $ldapAdvanced->sAuthSource = $authenticationSourceUid; + + $result = $ldapAdvanced->searchUsers($keyword, $start, $limit); + + foreach ($result["data"] as $value) { + $arrayUserData = $value; + + if (!isset($arrayUser[$arrayUserData["sUsername"]])) { + $arrayUserData["STATUS"] = "NOT IMPORTED"; + $arrayUserData["IMPORT"] = 1; + } else { + $arrayUserData["STATUS"] = "IMPORTED"; + $arrayUserData["IMPORT"] = 0; + } + + $arrayData[] = $arrayUserData; + } + + //Response + $response["status"] = "OK"; + $response["success"] = true; + $response["resultTotal"] = $result["numRecTotal"]; + $response["resultRoot"] = $arrayData; + } catch (Exception $e) { + //Response + $response["status"] = "ERROR"; + $response["message"] = $e->getMessage(); + } + + echo G::json_encode($response); + break; + case 'importUsers': + $usersImport = $_REQUEST['UsersImport']; + $authSourceUid = $_REQUEST['AUTH_SOURCE_UID']; + + $aUsers = G::json_decode($usersImport); + global $RBAC; + $aFields = $RBAC->getAuthSource( $authSourceUid ); + $aAttributes = array(); + + if (isset($aFields['AUTH_SOURCE_DATA']['AUTH_SOURCE_GRID_ATTRIBUTE'])) { + $aAttributes = $aFields['AUTH_SOURCE_DATA']['AUTH_SOURCE_GRID_ATTRIBUTE']; + } + + $usersCreated = ''; + $countUsers = 0; + //$usersImport + foreach ($aUsers as $sUser) { + $aUser = (array)$sUser; + $matches = array(); + $aData = array(); + $aData['USR_USERNAME'] = str_replace( "*", "'", $aUser['sUsername'] ); + $aData["USR_PASSWORD"] = "00000000000000000000000000000000"; + // note added by gustavo gustavo-at-colosa.com + // asign the FirstName and LastName variables + // add replace to change D*Souza to D'Souza by krlos + $aData['USR_FIRSTNAME'] = str_replace( "*", "'", $aUser['sFirstname'] ); + $aData['USR_LASTNAME'] = str_replace( "*", "'", $aUser['sLastname'] ); + $aData['USR_EMAIL'] = $aUser['sEmail']; + $aData['USR_DUE_DATE'] = date( 'Y-m-d', mktime( 0, 0, 0, date( 'm' ), date( 'd' ), date( 'Y' ) + 2 ) ); + $aData['USR_CREATE_DATE'] = date( 'Y-m-d H:i:s' ); + $aData['USR_UPDATE_DATE'] = date( 'Y-m-d H:i:s' ); + $aData['USR_BIRTHDAY'] = date( 'Y-m-d' ); + $aData['USR_STATUS'] = (isset($aUser['USR_STATUS'])) ? (($aUser['USR_STATUS'] == 'ACTIVE') ? 1 : 0) : 1; + $aData['USR_AUTH_TYPE'] = strtolower( $aFields['AUTH_SOURCE_PROVIDER'] ); + $aData['UID_AUTH_SOURCE'] = $aFields['AUTH_SOURCE_UID']; + // validating with regexp if there are some missing * inside the DN string + // if it's so the is changed to the ' character + preg_match( '/[a-zA-Z]\*[a-zA-Z]/', $aUser['sDN'], $matches ); + + foreach ($matches as $key => $match) { + $newMatch = str_replace( '*', '\'', $match ); + $aUser['sDN'] = str_replace( $match, $newMatch, $aUser['sDN'] ); + } + $aData['USR_AUTH_USER_DN'] = $aUser['sDN']; + + try { + $sUserUID = $RBAC->createUser( $aData, 'PROCESSMAKER_OPERATOR', $aFields['AUTH_SOURCE_NAME']); + $usersCreated .= $aData['USR_USERNAME'].' '; + $countUsers ++; + } catch (Exception $oError) { + $G_PUBLISH = new Publisher(); + $G_PUBLISH->AddContent( 'xmlform', 'xmlform', 'login/showMessage', '', array ('MESSAGE' => $oError->getMessage()) ); + G::RenderPage("publish", "blank"); + die(); + } + + $aData['USR_STATUS'] = (isset($aUser['USR_STATUS'])) ? $aUser['USR_STATUS'] :'ACTIVE'; + $aData['USR_UID'] = $sUserUID; + $aData['USR_ROLE'] = 'PROCESSMAKER_OPERATOR'; + + G::LoadClass("calendar"); + $calendarObj = new Calendar(); + $calendarObj->assignCalendarTo($sUserUID, '00000000000000000000000000000001', 'USER'); + + if (count($aAttributes)) { + foreach ($aAttributes as $value) { + if (isset($aUser[$value['attributeUser']])) { + $aData[$value['attributeUser']] = str_replace( "*", "'", $aUser[$value['attributeUser']] ); + if ($value['attributeUser'] == 'USR_STATUS') { + $evalValue = $aData[$value['attributeUser']]; + $statusValue = $aData['USR_STATUS']; + $aData[$value['attributeUser']] = $statusValue; + } + } + } + } + require_once 'classes/model/Users.php'; + $oUser = new Users(); + $oUser->create( $aData ); + } + + $sClassName = strtolower($aFields['AUTH_SOURCE_PROVIDER']); + + $plugin = new $sClassName(); + + $aAuthSource = $RBAC->authSourcesObj->load($authSourceUid); + + if (is_null($plugin->ldapcnn)) { + $plugin->ldapcnn = $plugin->ldapConnection($aAuthSource); + } + + $ldapcnn = $plugin->ldapcnn; + + $plugin->log($ldapcnn, "Users imported $countUsers: " . $usersCreated); + + echo G::json_encode(array('success'=> true)); + break; + case "ldapTestConnection": + $response = array(); + + try { + if ($_POST["AUTH_ANONYMOUS"] == "1") { + $_POST["AUTH_SOURCE_SEARCH_USER"] = ""; + $_POST["AUTH_SOURCE_PASSWORD"] = ""; + } + + $arrayAuthenticationSourceData = $_POST; + + //Test connection + $ldapAdvanced = new ldapAdvanced(); + + $ldapcnn = $ldapAdvanced->ldapConnection($arrayAuthenticationSourceData); + + //Response + $response["status"] = "OK"; + } catch (Exception $e) { + //Response + $response["status"] = "ERROR"; + $response["message"] = $e->getMessage(); + } + + echo G::json_encode($response); + break; + default: + break; +} + diff --git a/workflow/engine/templates/ldapAdvanced/authSourcesList.js b/workflow/engine/templates/ldapAdvanced/authSourcesList.js new file mode 100755 index 000000000..fe7150ecd --- /dev/null +++ b/workflow/engine/templates/ldapAdvanced/authSourcesList.js @@ -0,0 +1,46 @@ +var synchronizeDepartmentsLDAPADV = function() { + iGrid = Ext.getCmp('infoGrid'); + rowSelected = iGrid.getSelectionModel().getSelected(); + if (rowSelected) { + location.href = '../ldapAdvanced/authSourcesSynchronize?authUid=' + rowSelected.data.AUTH_SOURCE_UID + '&tab=synchronizeDepartments'; + } +}; + +var synchronizeGroupsLDAPADV = function() { + iGrid = Ext.getCmp('infoGrid'); + rowSelected = iGrid.getSelectionModel().getSelected(); + if (rowSelected) { + location.href = '../ldapAdvanced/authSourcesSynchronize?authUid=' + rowSelected.data.AUTH_SOURCE_UID + '&tab=synchronizeGroups'; + } +}; + +var synchronizeDepartmentsButtonLDAPADV = new Ext.Action({ + text: 'Synchronize Departments', + iconCls: 'ICON_DEPARTAMENTS', + disabled: true, + handler: synchronizeDepartmentsLDAPADV +}); + +var synchronizeGroupsButtonLDAPADV = new Ext.Action({ + text: 'Synchronize Groups', + iconCls: 'ICON_GROUPS', + disabled: true, + handler: synchronizeGroupsLDAPADV +}); + +var _rowselectLDAPADV = function(sm, index, record) { + if (record.get('AUTH_SOURCE_PROVIDER') == 'ldapAdvanced') { + synchronizeDepartmentsButtonLDAPADV.enable(); + synchronizeGroupsButtonLDAPADV.enable(); + } +}; + +var _rowdeselectLDAPADV = function(sm, index, record) { + synchronizeDepartmentsButtonLDAPADV.disable(); + synchronizeGroupsButtonLDAPADV.disable(); +}; + +_rowselect.push(_rowselectLDAPADV); +_rowdeselect.push(_rowdeselectLDAPADV); +_pluginActionButtons.push(synchronizeDepartmentsButtonLDAPADV); +_pluginActionButtons.push(synchronizeGroupsButtonLDAPADV); \ No newline at end of file diff --git a/workflow/engine/templates/ldapAdvanced/authSourcesSynchronize.html b/workflow/engine/templates/ldapAdvanced/authSourcesSynchronize.html new file mode 100755 index 000000000..29c2c3e8d --- /dev/null +++ b/workflow/engine/templates/ldapAdvanced/authSourcesSynchronize.html @@ -0,0 +1,3 @@ +
+
+
\ No newline at end of file diff --git a/workflow/engine/templates/ldapAdvanced/authSourcesSynchronize.js b/workflow/engine/templates/ldapAdvanced/authSourcesSynchronize.js new file mode 100755 index 000000000..28faa322a --- /dev/null +++ b/workflow/engine/templates/ldapAdvanced/authSourcesSynchronize.js @@ -0,0 +1,229 @@ +var viewPort; +var backButton; +var northPanel; +var tabsPanel; +var departmentsPanel; +var groupsPanel; +var treeDepartments; +var treeGroups; +var isSaved = true; +var isFirstTime = true; + +Ext.onReady(function() { + nodeChangeCheck = function (node, check) + { + if (node) { + if (node.hasChildNodes()) { + node.eachChild(function (n) { nodeChangeCheck(n, check); }); + } + + //node.expand(); + node.getUI().toggleCheck(check); + } + } + + nodeChangeCheckStart = function (node, check) + { + treeDepartments.removeListener("checkchange", nodeChangeCheckStart, this); + + nodeChangeCheck(node, check); + + treeDepartments.addListener("checkchange", nodeChangeCheckStart, this); + } + + try { + Ext.Ajax.timeout = 300000; + + backButton = new Ext.Action({ + text : _('ID_BACK'), + iconCls: "button_menu_ext ss_sprite ss_arrow_left", + handler: function() { + location.href = '../authSources/authSources_List'; + } + }); + + northPanel = new Ext.Panel({ + region: 'north', + xtype: 'panel', + tbar: [''+ 'Authentication Sources' + '', {xtype: 'tbfill'}, backButton] + }); + + treeDepartments = new Ext.tree.TreePanel({ + title: 'Departments List', + defaults: {flex: 1}, + useArrows: true, + autoScroll: true, + animate: true, + enableDD: true, + containerScroll: true, + rootVisible: false, + frame: true, + root: { + nodeType: 'async' + }, + maskDisabled: false, + dataUrl: 'authSourcesSynchronizeAjax?m=loadDepartments&authUid=' + AUTHENTICATION_SOURCE.AUTH_SOURCE_UID, + requestMethod: 'POST', + buttons: [{ + text: 'Save Changes', + handler: function() { + isSaved = false; + var msg = '', selNodes = treeDepartments.getChecked(); + treeDepartments.disabled = true; + var departments = []; + Ext.each(selNodes, function(node) { + departments.push(node.id); + }); + Ext.Ajax.request({ + url: 'authSourcesSynchronizeAjax', + params: {m: 'saveDepartments', authUid: AUTHENTICATION_SOURCE.AUTH_SOURCE_UID, departmentsDN: departments.join('|')}, + success: function(r) { + var response = Ext.util.JSON.decode(r.responseText); + if (response.status == 'OK') { + treeDepartments.getLoader().load(treeDepartments.root); + } + else { + alert(response.message); + } + } + }); + } + }], + + listeners: { + checkchange: nodeChangeCheckStart + } + }); + + treeDepartments.loader.on('load', function() { + treeDepartments.getRootNode().expand(true); + if (!isSaved) { + isSaved = true; + treeDepartments.disabled = false; + Ext.Msg.show({ + title: 'Changes saved.', + msg: 'All changes have been saved.', + icon: Ext.Msg.INFO, + minWidth: 200, + buttons: Ext.Msg.OK + }); + } + }); + + treeGroups = new Ext.tree.TreePanel({ + title: 'Groups List', + defaults: {flex: 1}, + useArrows: true, + autoScroll: true, + animate: true, + enableDD: true, + containerScroll: true, + rootVisible: false, + frame: true, + root: { + nodeType: 'async' + }, + dataUrl: 'authSourcesSynchronizeAjax?m=loadGroups&authUid=' + AUTHENTICATION_SOURCE.AUTH_SOURCE_UID, + requestMethod: 'POST', + buttons: [{ + text: 'Save Changes', + handler: function() { + isSaved = false; + var msg = '', selNodes = treeGroups.getChecked(); + treeGroups.disabled = true; + this.disabled = true; + var Groups = []; + Ext.each(selNodes, function(node) { + Groups.push(node.id); + }); + Ext.Ajax.request({ + url: 'authSourcesSynchronizeAjax', + params: {m: 'saveGroups', authUid: AUTHENTICATION_SOURCE.AUTH_SOURCE_UID, groupsDN: Groups.join('|')}, + success: function(r) { + var response = Ext.util.JSON.decode(r.responseText); + if (response.status == 'OK') { + treeGroups.getLoader().load(treeGroups.root); + } + else { + alert(response.message); + } + } + }); + } + }] + }); + + treeGroups.loader.on('load', function() { + treeGroups.getRootNode().expand(true); + if (!isSaved) { + isSaved = true; + treeGroups.disabled = false; + treeGroups.buttons[0].disabled = false; + Ext.Msg.show({ + title: 'Changes saved.', + msg: 'All changes have been saved.', + icon: Ext.Msg.INFO, + minWidth: 200, + buttons: Ext.Msg.OK + }); + } + }); + + departmentsPanel = new Ext.Panel({ + title: 'Synchronize Departments', + autoWidth: true, + layout: 'hbox', + defaults: {flex: 1}, + layoutConfig: {align: 'stretch'}, + items: [treeDepartments], + viewConfig: {forceFit: true} + }); + + groupsPanel = new Ext.Panel({ + title: 'Synchronize Groups', + autoWidth: true, + layout: 'hbox', + defaults: {flex: 1}, + layoutConfig: {align: 'stretch'}, + items: [treeGroups], + viewConfig: {forceFit: true} + }); + + tabsPanel = new Ext.TabPanel({ + region: 'center', + activeTab: AUTHENTICATION_SOURCE.CURRENT_TAB, + items:[departmentsPanel, groupsPanel], + listeners:{ + beforetabchange: function(p, t, c) { + if (typeof(t.body) == 'undefined') { + isFirstTime = true; + } + }, + tabchange: function(p, t) { + if (!isFirstTime) { + switch(t.title){ + case 'Synchronize Departments': + treeDepartments.getLoader().load(treeDepartments.root); + break; + case 'Synchronize Groups': + treeGroups.getLoader().load(treeGroups.root); + break; + } + } + else { + isFirstTime = false; + } + } + } + }); + + viewport = new Ext.Viewport({ + layout: 'border', + items: [northPanel, tabsPanel] + }); + } + catch (error) { + alert('->' + error + '<-'); + } +}); + diff --git a/workflow/engine/templates/ldapAdvanced/ldapAdvancedList.js b/workflow/engine/templates/ldapAdvanced/ldapAdvancedList.js index 42657b323..ab95d0389 100755 --- a/workflow/engine/templates/ldapAdvanced/ldapAdvancedList.js +++ b/workflow/engine/templates/ldapAdvanced/ldapAdvancedList.js @@ -26,11 +26,11 @@ Ext.onReady(function() { var ldapGridProxy = new Ext.data.HttpProxy({ method: 'POST', api: { - read : '../controllers/ldapAdvancedProxy.php?functionAccion=ldapGrid&tipo=read', - create : '../controllers/ldapAdvancedProxy.php?functionAccion=ldapGrid&tipo=create', - save : '../controllers/ldapAdvancedProxy.php?functionAccion=ldapGrid&tipo=save', - destroy : '../controllers/ldapAdvancedProxy.php?functionAccion=ldapGrid&tipo=destroy', - update : '../controllers/ldapAdvancedProxy.php?functionAccion=ldapGrid&tipo=update' + read : 'ldapAdvancedProxy.php?functionAccion=ldapGrid&tipo=read', + create : 'ldapAdvancedProxy.php?functionAccion=ldapGrid&tipo=create', + save : 'ldapAdvancedProxy.php?functionAccion=ldapGrid&tipo=save', + destroy : 'ldapAdvancedProxy.php?functionAccion=ldapGrid&tipo=destroy', + update : 'ldapAdvancedProxy.php?functionAccion=ldapGrid&tipo=update' } }); @@ -291,7 +291,7 @@ Ext.onReady(function() { }; var ldapForm = new Ext.FormPanel({ - url : '../controllers/ldapAdvancedProxy.php?functionAccion=ldapSave', + url : 'ldapAdvancedProxy.php?functionAccion=ldapSave', frame : true, title : "Authentication Source Information", border : false, @@ -338,7 +338,7 @@ Ext.onReady(function() { { if (typeof(Fields.AUTH_SOURCE_UID) != "undefined" && typeof(Fields.AUTH_SOURCE_BASE_DN) != "undefined" && ldapFormBaseDN.getValue() != Fields.AUTH_SOURCE_BASE_DN) { Ext.Ajax.request({ - url: "../controllers/ldapAdvancedProxy.php", + url: "ldapAdvancedProxy.php", method: "POST", params: { functionAccion: "ldapVerifyIfExistsRecordsInDb", @@ -387,7 +387,7 @@ Ext.onReady(function() { loadMaskAux.show(); Ext.Ajax.request({ - url: "../controllers/ldapAdvancedProxy.php", + url: "ldapAdvancedProxy.php", method: "POST", params: { functionAccion: "ldapTestConnection", diff --git a/workflow/engine/templates/ldapAdvanced/ldapAdvancedSearch.js b/workflow/engine/templates/ldapAdvanced/ldapAdvancedSearch.js index b33c19090..5d9162df9 100644 --- a/workflow/engine/templates/ldapAdvanced/ldapAdvancedSearch.js +++ b/workflow/engine/templates/ldapAdvanced/ldapAdvancedSearch.js @@ -89,7 +89,7 @@ Ext.onReady(function() { var storeGridSearch = new Ext.data.JsonStore({ proxy: new Ext.data.HttpProxy({ method: 'POST', - url: '../controllers/ldapAdvancedProxy.php', + url: 'ldapAdvancedProxy.php', timeout: 240000 }), autoDestroy: true, @@ -177,7 +177,7 @@ Ext.onReady(function() { 'functionAccion': 'importUsers', 'AUTH_SOURCE_UID': Fields.AUTH_SOURCE_UID }, - url : '../controllers/ldapAdvancedProxy.php', + url : 'ldapAdvancedProxy.php', success: function (returnData) { var resp = Ext.decode(returnData.responseText); Ext.MessageBox.hide(); From 1bcc28ba332dcedd5bd3cf462ede9556d856a195 Mon Sep 17 00:00:00 2001 From: "Paula V. Quispe" Date: Thu, 11 Jun 2015 12:06:18 -0400 Subject: [PATCH 03/11] PM-1060: Import User --- .../methods/authSources/authSources_Edit.php | 2 +- .../methods/authSources/authSources_New.php | 2 +- .../authSources/authSources_SearchUsers.php | 19 +++++-------------- 3 files changed, 7 insertions(+), 16 deletions(-) diff --git a/workflow/engine/methods/authSources/authSources_Edit.php b/workflow/engine/methods/authSources/authSources_Edit.php index af572405f..3ea20934d 100755 --- a/workflow/engine/methods/authSources/authSources_Edit.php +++ b/workflow/engine/methods/authSources/authSources_Edit.php @@ -105,7 +105,7 @@ if ($fields['AUTH_SOURCE_PROVIDER'] == 'ldap') { $oHeadPublisher = & headPublisher::getSingleton (); $oHeadPublisher->assign("Fields", $fields); - $oHeadPublisher->addExtJsScript (PATH_TPL. 'ldapAdvanced/library.js', false, true ); + $oHeadPublisher->addExtJsScript (PATH_TPL. 'ldapAdvanced/library', false, true ); $oHeadPublisher->addExtJsScript (PATH_TPL. 'ldapAdvanced/ldapAdvancedForm', false, true ); $oHeadPublisher->addExtJsScript (PATH_TPL. 'ldapAdvanced/ldapAdvancedList', false, true ); G::RenderPage ('publish', 'extJs'); diff --git a/workflow/engine/methods/authSources/authSources_New.php b/workflow/engine/methods/authSources/authSources_New.php index 4e515764c..44501902f 100755 --- a/workflow/engine/methods/authSources/authSources_New.php +++ b/workflow/engine/methods/authSources/authSources_New.php @@ -57,7 +57,7 @@ if (file_exists( PATH_XMLFORM . 'ldapAdvanced/' . $fields['AUTH_SOURCE_PROVIDER' $oHeadPublisher = & headPublisher::getSingleton (); $oHeadPublisher->assign("Fields", $fields); - $oHeadPublisher->addExtJsScript (PATH_TPL. 'ldapAdvanced/library.js', false, true ); + $oHeadPublisher->addExtJsScript (PATH_TPL. 'ldapAdvanced/library', false, true ); $oHeadPublisher->addExtJsScript (PATH_TPL. 'ldapAdvanced/ldapAdvancedForm', false, true ); $oHeadPublisher->addExtJsScript (PATH_TPL. 'ldapAdvanced/ldapAdvancedList', false, true ); G::RenderPage ('publish', 'extJs'); diff --git a/workflow/engine/methods/authSources/authSources_SearchUsers.php b/workflow/engine/methods/authSources/authSources_SearchUsers.php index e6e5a6d19..579c66713 100755 --- a/workflow/engine/methods/authSources/authSources_SearchUsers.php +++ b/workflow/engine/methods/authSources/authSources_SearchUsers.php @@ -35,17 +35,8 @@ $G_ID_SUB_MENU_SELECTED = 'AUTH_SOURCES'; $G_PUBLISH = new Publisher(); $fields = $RBAC->getAuthSource( $_GET['sUID'] ); -if (file_exists( PATH_PLUGINS . $fields['AUTH_SOURCE_PROVIDER'] . PATH_SEP . $fields['AUTH_SOURCE_PROVIDER'] . 'Edit.xml' )) { - $pluginEnabled = 0; - - if (file_exists(PATH_PLUGINS . $fields["AUTH_SOURCE_PROVIDER"] . ".php")) { - $pluginRegistry = &PMPluginRegistry::getSingleton(); - $pluginDetail = $pluginRegistry->getPluginDetails($fields["AUTH_SOURCE_PROVIDER"] . ".php"); - - if ($pluginDetail && $pluginDetail->enabled) { - $pluginEnabled = 1; - } - } +if (file_exists( PATH_XMLFORM . 'ldapAdvanced/' . $fields['AUTH_SOURCE_PROVIDER'] . 'Edit.xml' )) { + $pluginEnabled = 1; if ($pluginEnabled == 0) { $G_PUBLISH->AddContent( 'xmlform', 'xmlform', 'login/showMessage', '', array ('MESSAGE' => G::LoadTranslation( 'ID_AUTH_SOURCE_MISSING' ) ) ); @@ -61,12 +52,12 @@ if (file_exists( PATH_PLUGINS . $fields['AUTH_SOURCE_PROVIDER'] . PATH_SEP . $fi $oHeadPublisher->assign("FORMATS", $c->getFormats()); $oHeadPublisher->assign("CONFIG", $Config); - if (file_exists(PATH_PLUGINS . $fields["AUTH_SOURCE_PROVIDER"] . PATH_SEP . $fields["AUTH_SOURCE_PROVIDER"] . 'Flag')) { + if (file_exists(PATH_XMLFORM . 'ldapAdvanced/' . $fields['AUTH_SOURCE_PROVIDER'] . 'Flag')) { $oHeadPublisher = & headPublisher::getSingleton (); $oHeadPublisher->assign("Fields", $fields); - $oHeadPublisher->addExtJsScript (PATH_PLUGINS . $fields["AUTH_SOURCE_PROVIDER"] . PATH_SEP . 'js' . PATH_SEP . 'library', false, true ); - $oHeadPublisher->addExtJsScript (PATH_PLUGINS . $fields["AUTH_SOURCE_PROVIDER"] . PATH_SEP . 'js' . PATH_SEP . 'ldapAdvancedSearch', false, true ); + $oHeadPublisher->addExtJsScript (PATH_TPL. 'ldapAdvanced/library', false, true ); + $oHeadPublisher->addExtJsScript (PATH_TPL. 'ldapAdvanced/ldapAdvancedSearch', false, true ); G::RenderPage ('publish', 'extJs'); die(); } From 3e4e5582ad98eb87d4223d50c627ac9c1c31c509 Mon Sep 17 00:00:00 2001 From: "Paula V. Quispe" Date: Thu, 11 Jun 2015 15:48:58 -0400 Subject: [PATCH 04/11] PM-1060: Third migration ldapAdvanced --- workflow/engine/methods/authSources/authSources_List.php | 5 +++-- .../engine/methods/authSources/authSources_SelectType.php | 2 ++ workflow/engine/templates/ldapAdvanced/authSourcesList.js | 8 ++++---- 3 files changed, 9 insertions(+), 6 deletions(-) diff --git a/workflow/engine/methods/authSources/authSources_List.php b/workflow/engine/methods/authSources/authSources_List.php index 16955e9b6..6d0f299e3 100755 --- a/workflow/engine/methods/authSources/authSources_List.php +++ b/workflow/engine/methods/authSources/authSources_List.php @@ -33,7 +33,7 @@ G::LoadClass( 'configuration' ); $c = new Configurations(); $configPage = $c->getConfiguration( 'authSourcesList', 'pageSize', '', $_SESSION['USER_LOGGED'] ); $Config['pageSize'] = isset( $configPage['pageSize'] ) ? $configPage['pageSize'] : 20; - +G::pr($Config); $G_MAIN_MENU = 'processmaker'; $G_SUB_MENU = 'users'; $G_ID_MENU_SELECTED = 'USERS'; @@ -42,7 +42,8 @@ $G_ID_SUB_MENU_SELECTED = 'AUTH_SOURCES'; $G_PUBLISH = new Publisher(); $oHeadPublisher = & headPublisher::getSingleton(); -$oHeadPublisher->addExtJsScript( 'authSources/authSourcesList', false ); //adding a javascript file .js +$oHeadPublisher->addExtJsScript( 'authSources/authSourcesList', false ); //adding a javascript file .js +$oHeadPublisher->addExtJsScript (PATH_TPL. 'ldapAdvanced/authSourcesList', false ); //adding a javascript file .js $oHeadPublisher->addContent( 'authSources/authSourcesList' ); //adding a html file .html. $oHeadPublisher->assign( 'FORMATS', $c->getFormats() ); $oHeadPublisher->assign( 'CONFIG', $Config ); diff --git a/workflow/engine/methods/authSources/authSources_SelectType.php b/workflow/engine/methods/authSources/authSources_SelectType.php index 437823ba8..8ae58e893 100755 --- a/workflow/engine/methods/authSources/authSources_SelectType.php +++ b/workflow/engine/methods/authSources/authSources_SelectType.php @@ -34,11 +34,13 @@ $G_ID_MENU_SELECTED = 'USERS'; $G_ID_SUB_MENU_SELECTED = 'AUTH_SOURCES'; $aAuthSourceTypes = array (array ('sType' => 'char','sLabel' => 'char')); +error_log(PATH_RBAC . 'plugins' . PATH_SEP); $oDirectory = dir( PATH_RBAC . 'plugins' . PATH_SEP ); while ($sObject = $oDirectory->read()) { if (($sObject != '.') && ($sObject != '..') && ($sObject != '.svn') && ($sObject != 'ldap')) { if (is_file( PATH_RBAC . 'plugins' . PATH_SEP . $sObject )) { $sType = trim( str_replace( 'class.', '', str_replace( '.php', '', $sObject ) ) ); + error_log($sType); $aAuthSourceTypes[] = array ('sType' => $sType,'sLabel' => $sType ); } } diff --git a/workflow/engine/templates/ldapAdvanced/authSourcesList.js b/workflow/engine/templates/ldapAdvanced/authSourcesList.js index fe7150ecd..ece98e9e7 100755 --- a/workflow/engine/templates/ldapAdvanced/authSourcesList.js +++ b/workflow/engine/templates/ldapAdvanced/authSourcesList.js @@ -2,7 +2,7 @@ var synchronizeDepartmentsLDAPADV = function() { iGrid = Ext.getCmp('infoGrid'); rowSelected = iGrid.getSelectionModel().getSelected(); if (rowSelected) { - location.href = '../ldapAdvanced/authSourcesSynchronize?authUid=' + rowSelected.data.AUTH_SOURCE_UID + '&tab=synchronizeDepartments'; + location.href = 'authSourcesSynchronize?authUid=' + rowSelected.data.AUTH_SOURCE_UID + '&tab=synchronizeDepartments'; } }; @@ -10,19 +10,19 @@ var synchronizeGroupsLDAPADV = function() { iGrid = Ext.getCmp('infoGrid'); rowSelected = iGrid.getSelectionModel().getSelected(); if (rowSelected) { - location.href = '../ldapAdvanced/authSourcesSynchronize?authUid=' + rowSelected.data.AUTH_SOURCE_UID + '&tab=synchronizeGroups'; + location.href = 'authSourcesSynchronize?authUid=' + rowSelected.data.AUTH_SOURCE_UID + '&tab=synchronizeGroups'; } }; var synchronizeDepartmentsButtonLDAPADV = new Ext.Action({ - text: 'Synchronize Departments', + text: 'Synchronize Departmentssss', iconCls: 'ICON_DEPARTAMENTS', disabled: true, handler: synchronizeDepartmentsLDAPADV }); var synchronizeGroupsButtonLDAPADV = new Ext.Action({ - text: 'Synchronize Groups', + text: 'Synchronize Groupssss', iconCls: 'ICON_GROUPS', disabled: true, handler: synchronizeGroupsLDAPADV From 0cc89a62f97ce783d8915cba117bd581a47a38d2 Mon Sep 17 00:00:00 2001 From: "Paula V. Quispe" Date: Mon, 15 Jun 2015 17:12:59 -0400 Subject: [PATCH 05/11] PM-2973: Fourth migration ldapAdvanced --- .../authSources/authSourcesSynchronize.php | 61 +++ .../authSourcesSynchronizeAjax.php | 472 ++++++++++++++++++ .../methods/authSources/authSources_List.php | 3 +- .../authSources/authSources_SelectType.php | 2 - .../authSourcesListSyn.js} | 4 +- .../authSourcesSynchronize.html | 0 .../authSourcesSynchronize.js | 0 7 files changed, 536 insertions(+), 6 deletions(-) create mode 100755 workflow/engine/methods/authSources/authSourcesSynchronize.php create mode 100755 workflow/engine/methods/authSources/authSourcesSynchronizeAjax.php rename workflow/engine/templates/{ldapAdvanced/authSourcesList.js => authSources/authSourcesListSyn.js} (95%) mode change 100755 => 100644 rename workflow/engine/templates/{ldapAdvanced => authSources}/authSourcesSynchronize.html (100%) rename workflow/engine/templates/{ldapAdvanced => authSources}/authSourcesSynchronize.js (100%) diff --git a/workflow/engine/methods/authSources/authSourcesSynchronize.php b/workflow/engine/methods/authSources/authSourcesSynchronize.php new file mode 100755 index 000000000..d9ce964e6 --- /dev/null +++ b/workflow/engine/methods/authSources/authSourcesSynchronize.php @@ -0,0 +1,61 @@ +. + * + * For more information, contact Colosa Inc, 2566 Le Jeune Rd., + * Coral Gables, FL, 33134, USA, or email info@colosa.com. + * + **/ + +global $RBAC; + +switch ($RBAC->userCanAccess("PM_USERS")) { + case - 2: + G::SendTemporalMessage("ID_USER_HAVENT_RIGHTS_SYSTEM", "error", "labels"); + G::header("location: ../login/login"); + die; + break; + case - 1: + G::SendTemporalMessage("ID_USER_HAVENT_RIGHTS_PAGE", "error", "labels"); + G::header("location: ../login/login"); + die; + break; + case -3: + G::SendTemporalMessage("ID_USER_HAVENT_RIGHTS_PAGE", "error", "labels"); + G::header("location: ../login/login"); + die; + break; +} + +if (!isset($_REQUEST["tab"])) { + $_REQUEST["tab"] = "synchronizeDepartments"; +} + +$authenticationSource = array("AUTH_SOURCE_UID" => $_REQUEST["authUid"], "CURRENT_TAB" => ($_REQUEST["tab"] == "synchronizeDepartments" ? 0 : 1)); + +$oHeadPublisher =& headPublisher::getSingleton(); +$oHeadPublisher->addExtJsScript("authSources/authSourcesSynchronize", false); +$oHeadPublisher->addContent("authSources/authSourcesSynchronize"); +$oHeadPublisher->assign("AUTHENTICATION_SOURCE", $authenticationSource); + +global $G_PUBLISH; + +$G_PUBLISH = new Publisher(); +G::RenderPage("publish", "extJs"); + diff --git a/workflow/engine/methods/authSources/authSourcesSynchronizeAjax.php b/workflow/engine/methods/authSources/authSourcesSynchronizeAjax.php new file mode 100755 index 000000000..2fa17fefc --- /dev/null +++ b/workflow/engine/methods/authSources/authSourcesSynchronizeAjax.php @@ -0,0 +1,472 @@ +. + * + * For more information, contact Colosa Inc, 2566 Le Jeune Rd., + * Coral Gables, FL, 33134, USA, or email info@colosa.com. + * + **/ + +class treeNode extends stdclass +{ + public $text = ""; + public $cls = ""; + public $leaf = false; + public $checked = false; + public $children = array(); + public $id = ""; +} + +try { + require_once ("classes" . PATH_SEP . "model" . PATH_SEP . "Department.php"); + G::LoadThirdParty("pear" . PATH_SEP . "json", "class.json"); + + $json = new Services_JSON(); + header("Content-Type: application/json;"); + + switch ($_REQUEST["m"]) { + case "loadDepartments": + global $ldapAdvanced; + global $departments; + global $terminatedOu; + global $baseDN; + + $ldapAdvanced = getLDAPAdvanceInstance($_REQUEST["authUid"]); + $RBAC =& RBAC::getSingleton(); + $authenticationSource = $RBAC->authSourcesObj->load($_REQUEST["authUid"]); + $baseDN = $authenticationSource["AUTH_SOURCE_BASE_DN"]; + $departments = $ldapAdvanced->searchDepartments(); + $terminatedOu = $ldapAdvanced->getTerminatedOu(); + $nodes = lookForChildrenDeps(""); + die($json->encode($nodes)); + break; + case "saveDepartments": + $depsToCheck = explode("|", $_REQUEST["departmentsDN"]); + $depsToCheck = array_map("urldecode", $depsToCheck); + $depsToUncheck = getDepartmentsToUncheck($depsToCheck); + $RBAC =& RBAC::getSingleton(); + $authenticationSource = $RBAC->authSourcesObj->load($_REQUEST["authUid"]); + $ldapAdvanced = getLDAPAdvanceInstance($_REQUEST["authUid"]); + + foreach ($depsToCheck as $departmentDN) { + $baseDN = str_replace($authenticationSource["AUTH_SOURCE_BASE_DN"], "", $departmentDN); + $ous = custom_ldap_explode_dn($departmentDN); + $currentDep = array_shift($ous); + $parentDN = implode(",", $ous); + + //$ous = custom_ldap_explode_dn($baseDN); + //$currentDep = array_shift($ous); + + foreach ($ous as $key => $val) { + $aux = explode("=", $val); + + if (isset($aux[0]) && strtolower(trim($aux[0])) != "ou") { + unset($ous[$key]); + } + } + + if ($currentDep == "") { + $depTitle = "ROOT " . $authenticationSource["AUTH_SOURCE_BASE_DN"]; + } else { + $depAux = explode("=", $currentDep); + $depTitle = trim($depAux[1]); + } + + $departmentUID = $ldapAdvanced->getDepUidIfExistsDN($departmentDN); + + if ($departmentUID == "") { + if (count($ous) == 0) { + $parentUid = ""; + } else { + $parentUid = $ldapAdvanced->getDepUidIfExistsDN($parentDN); + + if ($parentUid == "") { + $response = new stdclass(); + $response->status = "ERROR"; + $response->message = "Parent departments are needed before create this sub department " . $parentDN; + die($json->encode($response)); + } + } + + $department = new department(); + $row["DEP_TITLE"] = stripslashes($depTitle); + $row["DEP_PARENT"] = $parentUid; + $row["DEP_LDAP_DN"] = $departmentDN; + $row["DEP_REF_CODE"] = ""; + $departmentUID = $department->create($row); + + if ($departmentUID == false) { + $response = new stdclass(); + $response->status = "ERROR"; + $response->message = "Error creating department"; + die($json->encode($response)); + } + } + } + + if (count($depsToUncheck) > 0) { + foreach ($depsToUncheck as $departmentDN) { + $departmentUID = $ldapAdvanced->getDepUidIfExistsDN($departmentDN); + + if ($departmentUID != "") { + $department = new department(); + $departmentInfo = $department->Load($departmentUID); + + $arrayAux1 = custom_ldap_explode_dn($departmentDN); + + foreach ($arrayAux1 as $index => $value) { + $arrayAux2 = explode("=", $value); + + if (isset($arrayAux2[0]) && strtolower(trim($arrayAux2[0])) == "ou") { + unset($arrayAux1[$index]); + } + } + + $departmentBaseDn = implode(",", $arrayAux1); + + if (strtolower($departmentBaseDn) == strtolower($authenticationSource["AUTH_SOURCE_BASE_DN"])) { + $departmentInfo["DEP_LDAP_DN"] = ""; + $department->update($departmentInfo); + + if (!isset($authenticationSource["AUTH_SOURCE_DATA"]["DEPARTMENTS_TO_UNASSIGN"])) { + $authenticationSource["AUTH_SOURCE_DATA"]["DEPARTMENTS_TO_UNASSIGN"] = array(); + } + + $authenticationSource["AUTH_SOURCE_DATA"]["DEPARTMENTS_TO_UNASSIGN"][] = $departmentUID; + } + } + } + + $RBAC->authSourcesObj->update($authenticationSource); + } + + $response = new stdclass(); + $response->status = "OK"; + die($json->encode($response)); + break; + case "loadGroups": + global $ldapAdvanced; + global $groups; + + $ldapAdvanced = getLDAPAdvanceInstance($_REQUEST["authUid"]); + $groups = $ldapAdvanced->searchGroups(); + $nodes = lookForChildrenGroups(); + die($json->encode($nodes)); + break; + case "saveGroups": + $groupsToCheck = explode("|", $_REQUEST["groupsDN"]); + $groupsToCheck = array_map("urldecode", $groupsToCheck); + $groupsToUncheck = getGroupsToUncheck($groupsToCheck); + $RBAC =& RBAC::getSingleton(); + $authenticationSource = $RBAC->authSourcesObj->load($_REQUEST["authUid"]); + $ldapAdvanced = getLDAPAdvanceInstance($_REQUEST["authUid"]); + + foreach ($groupsToCheck as $groupDN) { + //$baseDN = str_replace($authenticationSource["AUTH_SOURCE_BASE_DN"], "", $groupDN); + $ous = custom_ldap_explode_dn($groupDN); + $currentGroup = array_shift($ous); + //$parentDN = implode(",", $ous); + //$ous = custom_ldap_explode_dn($baseDN); + //$currentGroup = array_shift($ous); + + foreach ($ous as $key => $val) { + $aux = explode("=", $val); + + if (isset($aux[0]) && strtolower(trim($aux[0]) != "ou")) { + unset($ous[$key]); + } + } + + $groupAux = explode("=", $currentGroup); + $groupTitle = isset($groupAux[1]) ? trim($groupAux[1]) : ""; + $groupUID = $ldapAdvanced->getGrpUidIfExistsDN($groupDN); + + if ($groupUID == "") { + $group = new Groupwf(); + $row["GRP_TITLE"] = stripslashes($groupTitle); + $row["GRP_LDAP_DN"] = $groupDN; + $groupUID = $group->create($row); + + if ($groupUID == false) { + $response = new stdclass(); + $response->status = "ERROR"; + $response->message = "Error creating group"; + die($json->encode($response)); + } + } + } + + if (count($groupsToUncheck) > 0) { + foreach ($groupsToUncheck as $groupDN) { + $groupUID = $ldapAdvanced->getGrpUidIfExistsDN($groupDN); + + if ($groupUID != "") { + $group = new Groupwf(); + $groupInfo = $group->Load($groupUID); + $groupInfo["GRP_LDAP_DN"] = ""; + $group->update($groupInfo); + + if (!isset($authenticationSource["AUTH_SOURCE_DATA"]["GROUPS_TO_UNASSIGN"])) { + $authenticationSource["AUTH_SOURCE_DATA"]["GROUPS_TO_UNASSIGN"] = array(); + } + + $authenticationSource["AUTH_SOURCE_DATA"]["GROUPS_TO_UNASSIGN"][] = $groupUID; + } + } + + $RBAC->authSourcesObj->update($authenticationSource); + } + + $response = new stdclass(); + $response->status = "OK"; + die($json->encode($response)); + break; + } +} catch (Exception $error) { + $response = new stdclass(); + $response->status = "ERROR"; + $response->message = $error->getMessage(); + + die($json->encode($response)); +} + +function getLDAPAdvanceInstance($authUid) +{ + $RBAC = &RBAC::getSingleton(); + $ldapAdvanced = new ldapAdvanced(); + $ldapAdvanced->sAuthSource = $authUid; + $ldapAdvanced->sSystem = $RBAC->sSystem; + + return $ldapAdvanced; +} + +function getDepartments($parent) +{ + global $departments; + global $terminatedOu; + global $baseDN; + + $parentDepartments = $departments; + $childDepartments = $departments; + $currentDepartments = array(); + + foreach ($parentDepartments as $key => $val) { + if (strtolower($val["dn"]) != strtolower($parent)) { + if ((strtolower($val["parent"]) == strtolower($parent)) && (strtolower($val["ou"]) != strtolower($terminatedOu))) { + $node = array(); + $node["DEP_UID"] = $val["ou"]; + $node["DEP_TITLE"] = $val["ou"]; + $node["DEP_USERS"] = $val["users"]; + $node["DEP_DN"] = $val["dn"]; + $node["HAS_CHILDREN"] = false; + $departments[$key]["hasChildren"] = false; + + foreach ($childDepartments as $key2 => $val2) { + if (strtolower($val2["parent"]) == strtolower($val["dn"])) { + $node["HAS_CHILDREN"] = true; + $departments[$key]["hasChildren"] = true; + break; + } + } + + $node["DEP_LAST"] = false; + $currentDepartments[] = $node; + } + } + } + + if (isset($currentDepartments[count($currentDepartments) - 1])) { + $currentDepartments[count($currentDepartments) - 1]["DEP_LAST"] = true; + } + + return $currentDepartments; +} + +function lookForChildrenDeps($parent) +{ + global $ldapAdvanced; + global $departments; + + $allDepartments = getDepartments($parent); + $departmentsObjects = array(); + + $arrayDepartmentNumberOfUsersFromDb = $ldapAdvanced->departmentsGetNumberOfUsersFromDb(); + + foreach ($allDepartments as $department) { + $departmentObject = new treeNode(); + $departmentObject->text = htmlentities($department["DEP_TITLE"], ENT_QUOTES, "UTF-8"); + $departmentUid = $ldapAdvanced->getDepUidIfExistsDN($department["DEP_DN"]); + + if ($departmentUid != "") { + $departmentObject->text .= " (" . ((isset($arrayDepartmentNumberOfUsersFromDb[$departmentUid]))? $arrayDepartmentNumberOfUsersFromDb[$departmentUid] : 0) . ")"; + $departmentObject->checked = true; + } else { + $departmentObject->checked = false; + } + + if ($department["HAS_CHILDREN"] == 1) { + $departmentObject->children = lookForChildrenDeps($department["DEP_DN"]); + } + + $departmentObject->id = urlencode($department["DEP_DN"]); + $departmentsObjects[] = $departmentObject; + } + return $departmentsObjects; +} + +function getDepartmentsWithDN() +{ + $arrayDepartmentLdapDn = array(); + + $criteria = new Criteria("workflow"); + + $criteria->addSelectColumn(DepartmentPeer::DEP_LDAP_DN); + $criteria->add(DepartmentPeer::DEP_LDAP_DN, "", Criteria::NOT_EQUAL); + $criteria->add(DepartmentPeer::DEP_LDAP_DN, null, Criteria::ISNOTNULL); + + $rsCriteria = DepartmentPeer::doSelectRS($criteria); + $rsCriteria->setFetchmode(ResultSet::FETCHMODE_ASSOC); + + while ($rsCriteria->next()) { + $row = $rsCriteria->getRow(); + + $arrayDepartmentLdapDn[] = $row; + } + + return $arrayDepartmentLdapDn; +} + +function getDepartmentsToUncheck($depsToCheck) +{ + $departmentsWithDN = getDepartmentsWithDN(); + $depsToUncheck = array(); + + foreach ($departmentsWithDN as $departmentWithDN) { + $found = false; + + foreach ($depsToCheck as $depToCheck) { + if ($departmentWithDN["DEP_LDAP_DN"] == $depToCheck) { + $found = true; + } + } + + if (!$found) { + $depsToUncheck[] = $departmentWithDN["DEP_LDAP_DN"]; + } + } + + return $depsToUncheck; +} + +function getGroups() +{ + global $groups; + + $currentGroups = array(); + + foreach ($groups as $key => $val) { + $node = array(); + $node["GRP_UID"] = $val["cn"]; + $node["GRP_TITLE"] = $val["cn"]; + $node["GRP_USERS"] = $val["users"]; + $node["GRP_DN"] = $val["dn"]; + $currentGroups[] = $node; + } + + return $currentGroups; +} + +function lookForChildrenGroups() +{ + global $ldapAdvanced; + global $groups; + + $allGroups = getGroups(); + $groupsObjects = array(); + + $arrayGroupNumberOfUsersFromDb = $ldapAdvanced->groupsGetNumberOfUsersFromDb(); + + foreach ($allGroups as $group) { + $groupObject = new treeNode(); + $groupObject->text = htmlentities($group["GRP_TITLE"], ENT_QUOTES, "UTF-8"); + $groupUid = $ldapAdvanced->getGrpUidIfExistsDN($group["GRP_DN"]); + + if ($groupUid != "") { + $groupObject->text .= " (" . ((isset($arrayGroupNumberOfUsersFromDb[$groupUid]))? $arrayGroupNumberOfUsersFromDb[$groupUid] : 0) . ")"; + $groupObject->checked = true; + } else { + $groupObject->checked = false; + } + + $groupObject->id = urlencode($group["GRP_DN"]); + $groupsObjects[] = $groupObject; + } + + return $groupsObjects; +} + +function getGroupsWithDN() +{ + $groupInstance = new Groupwf(); + $allGroups = $groupInstance->getAll()->data; + $groupsWithDN = array(); + + foreach ($allGroups as $group) { + if ($group["GRP_LDAP_DN"] != "") { + $groupsWithDN[] = $group; + } + } + + return $groupsWithDN; +} + +function getGroupsToUncheck($groupsToCheck) +{ + $groupsWithDN = getGroupsWithDN(); + $groupsToUncheck = array(); + + foreach ($groupsWithDN as $groupWithDN) { + $found = false; + + foreach ($groupsToCheck as $groupToCheck) { + if ($groupWithDN["GRP_LDAP_DN"] == $groupToCheck) { + $found = true; + } + } + + if (!$found) { + $groupsToUncheck[] = $groupWithDN["GRP_LDAP_DN"]; + } + } + + return $groupsToUncheck; +} + +function custom_ldap_explode_dn($dn) +{ + $result = ldap_explode_dn($dn, 0); + unset($result["count"]); + + foreach ($result as $key => $value) { + $result[$key] = addcslashes(preg_replace("/\\\([0-9A-Fa-f]{2})/e", "''.chr(hexdec('\\1')).''", $value), '<>,"'); + } + + return($result); +} + diff --git a/workflow/engine/methods/authSources/authSources_List.php b/workflow/engine/methods/authSources/authSources_List.php index 6d0f299e3..d6e06407b 100755 --- a/workflow/engine/methods/authSources/authSources_List.php +++ b/workflow/engine/methods/authSources/authSources_List.php @@ -33,7 +33,6 @@ G::LoadClass( 'configuration' ); $c = new Configurations(); $configPage = $c->getConfiguration( 'authSourcesList', 'pageSize', '', $_SESSION['USER_LOGGED'] ); $Config['pageSize'] = isset( $configPage['pageSize'] ) ? $configPage['pageSize'] : 20; -G::pr($Config); $G_MAIN_MENU = 'processmaker'; $G_SUB_MENU = 'users'; $G_ID_MENU_SELECTED = 'USERS'; @@ -43,7 +42,7 @@ $G_PUBLISH = new Publisher(); $oHeadPublisher = & headPublisher::getSingleton(); $oHeadPublisher->addExtJsScript( 'authSources/authSourcesList', false ); //adding a javascript file .js -$oHeadPublisher->addExtJsScript (PATH_TPL. 'ldapAdvanced/authSourcesList', false ); //adding a javascript file .js +$oHeadPublisher->addExtJsScript( 'authSources/authSourcesListSyn', false ); //adding a javascript file .js $oHeadPublisher->addContent( 'authSources/authSourcesList' ); //adding a html file .html. $oHeadPublisher->assign( 'FORMATS', $c->getFormats() ); $oHeadPublisher->assign( 'CONFIG', $Config ); diff --git a/workflow/engine/methods/authSources/authSources_SelectType.php b/workflow/engine/methods/authSources/authSources_SelectType.php index 8ae58e893..437823ba8 100755 --- a/workflow/engine/methods/authSources/authSources_SelectType.php +++ b/workflow/engine/methods/authSources/authSources_SelectType.php @@ -34,13 +34,11 @@ $G_ID_MENU_SELECTED = 'USERS'; $G_ID_SUB_MENU_SELECTED = 'AUTH_SOURCES'; $aAuthSourceTypes = array (array ('sType' => 'char','sLabel' => 'char')); -error_log(PATH_RBAC . 'plugins' . PATH_SEP); $oDirectory = dir( PATH_RBAC . 'plugins' . PATH_SEP ); while ($sObject = $oDirectory->read()) { if (($sObject != '.') && ($sObject != '..') && ($sObject != '.svn') && ($sObject != 'ldap')) { if (is_file( PATH_RBAC . 'plugins' . PATH_SEP . $sObject )) { $sType = trim( str_replace( 'class.', '', str_replace( '.php', '', $sObject ) ) ); - error_log($sType); $aAuthSourceTypes[] = array ('sType' => $sType,'sLabel' => $sType ); } } diff --git a/workflow/engine/templates/ldapAdvanced/authSourcesList.js b/workflow/engine/templates/authSources/authSourcesListSyn.js old mode 100755 new mode 100644 similarity index 95% rename from workflow/engine/templates/ldapAdvanced/authSourcesList.js rename to workflow/engine/templates/authSources/authSourcesListSyn.js index ece98e9e7..c38cd0471 --- a/workflow/engine/templates/ldapAdvanced/authSourcesList.js +++ b/workflow/engine/templates/authSources/authSourcesListSyn.js @@ -15,14 +15,14 @@ var synchronizeGroupsLDAPADV = function() { }; var synchronizeDepartmentsButtonLDAPADV = new Ext.Action({ - text: 'Synchronize Departmentssss', + text: 'Synchronize Departments', iconCls: 'ICON_DEPARTAMENTS', disabled: true, handler: synchronizeDepartmentsLDAPADV }); var synchronizeGroupsButtonLDAPADV = new Ext.Action({ - text: 'Synchronize Groupssss', + text: 'Synchronize Groups', iconCls: 'ICON_GROUPS', disabled: true, handler: synchronizeGroupsLDAPADV diff --git a/workflow/engine/templates/ldapAdvanced/authSourcesSynchronize.html b/workflow/engine/templates/authSources/authSourcesSynchronize.html similarity index 100% rename from workflow/engine/templates/ldapAdvanced/authSourcesSynchronize.html rename to workflow/engine/templates/authSources/authSourcesSynchronize.html diff --git a/workflow/engine/templates/ldapAdvanced/authSourcesSynchronize.js b/workflow/engine/templates/authSources/authSourcesSynchronize.js similarity index 100% rename from workflow/engine/templates/ldapAdvanced/authSourcesSynchronize.js rename to workflow/engine/templates/authSources/authSourcesSynchronize.js From a7f7f8701d73ba38bf6c91cfd6a9b1b76ac2eb3e Mon Sep 17 00:00:00 2001 From: "Paula V. Quispe" Date: Tue, 16 Jun 2015 17:44:03 -0400 Subject: [PATCH 06/11] PM-1086: I added validation when the feature is active --- workflow/engine/methods/authSources/authSources_List.php | 5 ++++- .../methods/authSources/authSources_SearchUsers.php | 9 ++++++--- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/workflow/engine/methods/authSources/authSources_List.php b/workflow/engine/methods/authSources/authSources_List.php index d6e06407b..c2949e6d8 100755 --- a/workflow/engine/methods/authSources/authSources_List.php +++ b/workflow/engine/methods/authSources/authSources_List.php @@ -39,10 +39,13 @@ $G_ID_MENU_SELECTED = 'USERS'; $G_ID_SUB_MENU_SELECTED = 'AUTH_SOURCES'; $G_PUBLISH = new Publisher(); +$licensedFeatures = & PMLicensedFeatures::getSingleton(); $oHeadPublisher = & headPublisher::getSingleton(); $oHeadPublisher->addExtJsScript( 'authSources/authSourcesList', false ); //adding a javascript file .js -$oHeadPublisher->addExtJsScript( 'authSources/authSourcesListSyn', false ); //adding a javascript file .js +if ($licensedFeatures->verifyfeature('7TTeDBQeWRoZTZKYjh4eFpYUlRDUUEyVERPU3FxellWank=')) { + $oHeadPublisher->addExtJsScript( 'authSources/authSourcesListSyn', false ); //adding a javascript file .js +} $oHeadPublisher->addContent( 'authSources/authSourcesList' ); //adding a html file .html. $oHeadPublisher->assign( 'FORMATS', $c->getFormats() ); $oHeadPublisher->assign( 'CONFIG', $Config ); diff --git a/workflow/engine/methods/authSources/authSources_SearchUsers.php b/workflow/engine/methods/authSources/authSources_SearchUsers.php index 579c66713..6f28d0a56 100755 --- a/workflow/engine/methods/authSources/authSources_SearchUsers.php +++ b/workflow/engine/methods/authSources/authSources_SearchUsers.php @@ -36,10 +36,13 @@ $G_ID_SUB_MENU_SELECTED = 'AUTH_SOURCES'; $G_PUBLISH = new Publisher(); $fields = $RBAC->getAuthSource( $_GET['sUID'] ); if (file_exists( PATH_XMLFORM . 'ldapAdvanced/' . $fields['AUTH_SOURCE_PROVIDER'] . 'Edit.xml' )) { - $pluginEnabled = 1; - + $pluginEnabled = 0; + $licensedFeatures = & PMLicensedFeatures::getSingleton(); + if ($licensedFeatures->verifyfeature('7TTeDBQeWRoZTZKYjh4eFpYUlRDUUEyVERPU3FxellWank=')) { + $pluginEnabled = 1; + } if ($pluginEnabled == 0) { - $G_PUBLISH->AddContent( 'xmlform', 'xmlform', 'login/showMessage', '', array ('MESSAGE' => G::LoadTranslation( 'ID_AUTH_SOURCE_MISSING' ) ) ); + $G_PUBLISH->AddContent( 'xmlform', 'xmlform', 'login/showMessage', '', array ('MESSAGE' => G::LoadTranslation( 'ID_AUTH_SOURCE_FEATURE_MISSING' ) ) ); G::RenderPage( 'publish', 'blank' ); } else { G::LoadClass('configuration'); From 8bff906b3f91be9ba054598ad503824915462b7d Mon Sep 17 00:00:00 2001 From: "Paula V. Quispe" Date: Wed, 17 Jun 2015 12:49:48 -0400 Subject: [PATCH 07/11] PM-1060: I added the ldap cron files in core --- workflow/engine/bin/ldapcron.php | 193 ++++++++++ workflow/engine/bin/ldapcron_single.php | 489 ++++++++++++++++++++++++ 2 files changed, 682 insertions(+) create mode 100644 workflow/engine/bin/ldapcron.php create mode 100644 workflow/engine/bin/ldapcron_single.php diff --git a/workflow/engine/bin/ldapcron.php b/workflow/engine/bin/ldapcron.php new file mode 100644 index 000000000..9018f0d6a --- /dev/null +++ b/workflow/engine/bin/ldapcron.php @@ -0,0 +1,193 @@ + 0 && $arrayAux[count($arrayAux) - 1] == "workflow") { + $arrayPathToCron = $arrayAux; + $flagPathToCron = true; + } + } + + if (!$flagPathToCron) { + //Path to CRON by symlink + if ($osIsLinux) { + exec("pwd", $arrayOutput); + + if (count($arrayOutput) > 0) { + $arrayPathAux = array( + "engine" . PATH_SEP . "plugins", + "engine" . PATH_SEP . "plugins" . PATH_SEP . "ldapAdvanced" . PATH_SEP . "bin" + ); + + foreach ($arrayPathAux as $value) { + $arrayAux = explode(PATH_SEP, str_replace($value, "", trim($arrayOutput[0]))); + + array_pop($arrayAux); + + if (count($arrayAux) > 0 && $arrayAux[count($arrayAux) - 1] == "workflow") { + $arrayPathToCron = $arrayAux; + $flagPathToCron = true; + break; + } + } + } + } + } + + if (!$flagPathToCron) { + throw new Exception("Error: Unable to execute the LDAP Advanced CRON, the path is incorrect"); + } + + $pathHome = implode(PATH_SEP, $arrayPathToCron) . PATH_SEP; + + array_pop($arrayPathToCron); + + $pathTrunk = implode(PATH_SEP, $arrayPathToCron) . PATH_SEP; + + array_pop($arrayPathToCron); + + $pathOutTrunk = implode(PATH_SEP, $arrayPathToCron) . PATH_SEP; + + define("PATH_HOME", $pathHome); + define("PATH_TRUNK", $pathTrunk); + define("PATH_OUTTRUNK", $pathOutTrunk); + + //Check deprecated files + $fileBinDeprecated = PATH_HOME . "engine" . PATH_SEP . "bin" . PATH_SEP . "plugins" . PATH_SEP . "ldapadvanced.php"; + + if (file_exists($fileBinDeprecated)) { + @unlink($fileBinDeprecated); + + if (file_exists($fileBinDeprecated)) { + throw new Exception("Error: LDAP Advanced CRON requires that the \"$fileBinDeprecated\" file has been deleted."); + } + } + + //Include files + require_once(PATH_HOME . "engine" . PATH_SEP . "config" . PATH_SEP . "paths.php"); + + G::LoadClass("system"); + + $config = System::getSystemConfiguration(); + + ini_set("date.timezone", $config["time_zone"]); + + //CRON command options + $arrayCommandOption = array( + "force" => "+force", + "debug" => "+debug" + ); + + //CRON status + $flagIsRunning = false; + $lastExecution = ""; + $processcTimeProcess = 0; + $processcTimeStart = 0; + + $force = in_array($arrayCommandOption["force"], $argv); + $debug = in_array($arrayCommandOption["debug"], $argv); + + if (!$force && file_exists(PATH_DATA . "ldapcron")) { + //Windows flag + //Get data of CRON file + $arrayCron = unserialize(trim(file_get_contents(PATH_DATA . "ldapcron"))); + + $flagIsRunning = (boolean)($arrayCron["flagIsRunning"]); + $lastExecution = $arrayCron["lastExecution"]; + $processcTimeProcess = (isset($arrayCron["processcTimeProcess"]))? (int)($arrayCron["processcTimeProcess"]) : 10; //Minutes + $processcTimeStart = (isset($arrayCron["processcTimeStart"]))? $arrayCron["processcTimeStart"] : 0; + } + + if (!$force && $osIsLinux) { + //Linux flag + //Check if CRON it's running + exec("ps -fea | grep ldapcron.php | grep -v grep", $arrayOutput); + + //This validation is when the CRON is called from a symlink + $count = 0; + + foreach ($arrayOutput as $value) { + if (preg_match("/^.*ldapcron\.php.*$/", $value)) { + $count++; + } + } + + if ($count > 1) { + $flagIsRunning = true; + } + } + + if ($force || !$flagIsRunning) { + //Start CRON + $arrayCron = array("flagIsRunning" => "1", "lastExecution" => date("Y-m-d H:i:s")); + file_put_contents(PATH_DATA . "ldapcron", serialize($arrayCron)); + + try { + $ldapCronSinglePath = PATH_PLUGINS . "ldapAdvanced" . PATH_SEP . "bin" . PATH_SEP . "ldapcron_single.php"; + + $workspace = ""; + + for ($i = 1; $i <= count($argv) - 1; $i++) { + if (preg_match("/^\+w(.+)$/", $argv[$i], $arrayMatch)) { + $workspace = $arrayMatch[1]; + break; + } + } + + $countw = 0; + + if ($workspace == "") { + $d = dir(PATH_DB); + + while (($entry = $d->read()) !== false) { + if ($entry != "" && $entry != "." && $entry != "..") { + if (is_dir(PATH_DB . $entry)) { + if (file_exists(PATH_DB . $entry . PATH_SEP . "db.php")) { + $countw++; + + passthru("php -f \"$ldapCronSinglePath\" " . (($debug)? 1 : 0) . " $entry \"" . base64_encode(PATH_HOME) . "\" \"" . base64_encode(PATH_TRUNK) . "\" \"" . base64_encode(PATH_OUTTRUNK) . "\""); + } + } + } + } + } else { + if (!is_dir(PATH_DB . $workspace) || !file_exists(PATH_DB . $workspace . PATH_SEP . "db.php")) { + throw new Exception("Error: The workspace \"$workspace\" does not exist"); + } + + $countw++; + + passthru("php -f \"$ldapCronSinglePath\" " . (($debug)? 1 : 0) . " $workspace \"" . base64_encode(PATH_HOME) . "\" \"" . base64_encode(PATH_TRUNK) . "\" \"" . base64_encode(PATH_OUTTRUNK) . "\""); + } + + eprintln("Finished $countw workspaces processed"); + } catch (Exception $e) { + throw $e; + } + + //End CRON + $arrayCron = array("flagIsRunning" => "0", "lastExecution" => date("Y-m-d H:i:s")); + file_put_contents(PATH_DATA . "ldapcron", serialize($arrayCron)); + } else { + eprintln("The LDAP Advanced CRON is running, please wait for it to finish\nStarted in $lastExecution"); + eprintln("If do you want force the execution use the option \"" . $arrayCommandOption["force"] . "\", example: php -f ldapcron.php +wworkflow " . $arrayCommandOption["force"] ,"green"); + } + + echo "Done!\n"; +} catch (Exception $e) { + echo $e->getMessage() . "\n"; +} + diff --git a/workflow/engine/bin/ldapcron_single.php b/workflow/engine/bin/ldapcron_single.php new file mode 100644 index 000000000..5b169bf54 --- /dev/null +++ b/workflow/engine/bin/ldapcron_single.php @@ -0,0 +1,489 @@ +"), array("", "", ""), $phpCode); + + eval($phpCode); + + $dsn = $DB_ADAPTER . "://" . $DB_USER . ":" . $DB_PASS . "@" . $DB_HOST . "/" . $DB_NAME; + $dsnRbac = $DB_ADAPTER . "://" . $DB_RBAC_USER . ":" . $DB_RBAC_PASS . "@" . $DB_RBAC_HOST . "/" . $DB_RBAC_NAME; + $dsnRp = $DB_ADAPTER . "://" . $DB_REPORT_USER . ":" . $DB_REPORT_PASS . "@" . $DB_REPORT_HOST . "/" . $DB_REPORT_NAME; + + switch ($DB_ADAPTER) { + case "mysql": + $dsn .= "?encoding=utf8"; + $dsnRbac .= "?encoding=utf8"; + break; + case "mssql": + //$dsn .= "?sendStringAsUnicode=false"; + //$dsnRbac .= "?sendStringAsUnicode=false"; + break; + default: + break; + } + + $pro = array(); + $pro["datasources"]["workflow"]["connection"] = $dsn; + $pro["datasources"]["workflow"]["adapter"] = $DB_ADAPTER; + $pro["datasources"]["rbac"]["connection"] = $dsnRbac; + $pro["datasources"]["rbac"]["adapter"] = $DB_ADAPTER; + $pro["datasources"]["rp"]["connection"] = $dsnRp; + $pro["datasources"]["rp"]["adapter"] = $DB_ADAPTER; + //$pro["datasources"]["dbarray"]["connection"] = "dbarray://user:pass@localhost/pm_os"; + //$pro["datasources"]["dbarray"]["adapter"] = "dbarray"; + + $oFile = fopen(PATH_CORE . "config" . PATH_SEP . "_databases_.php", "w"); + fwrite($oFile, ""); + fclose($oFile); + + Propel::init(PATH_CORE . "config" . PATH_SEP . "_databases_.php"); + //Creole::registerDriver("dbarray", "creole.contrib.DBArrayConnection"); + + //Enable RBAC + Bootstrap::LoadSystem("rbac"); + + $rbac = &RBAC::getSingleton(PATH_DATA, session_id()); + $rbac->sSystem = "PROCESSMAKER"; + + eprintln("Processing workspace: " . $workflow, "green"); + + try { + require_once(PATH_PLUGINS . "ldapAdvanced" . PATH_SEP . "class.ldapAdvanced.php"); + require_once(PATH_PLUGINS . "ldapAdvanced" . PATH_SEP . "services" . PATH_SEP . "ldapadvanced.php"); + + $obj = new ldapadvancedClassCron(); + + $obj->executeCron((bool)($argv[1])); + } catch (Exception $e) { + echo $e->getMessage() . "\n"; + + eprintln("Problem in workspace: " . $workflow . " it was omitted.", "red"); + } + + eprintln(); + } + + if (file_exists(PATH_CORE . "config" . PATH_SEP . "_databases_.php")) { + unlink(PATH_CORE . "config" . PATH_SEP . "_databases_.php"); + } +} catch (Exception $e) { + echo $e->getMessage() . "\n"; +} + From 1c6c576629f21fa56440989eac002cf1346713a4 Mon Sep 17 00:00:00 2001 From: "Paula V. Quispe" Date: Wed, 17 Jun 2015 15:25:21 -0400 Subject: [PATCH 08/11] PM-1060: I changed the path of cron execution --- workflow/engine/bin/ldapcron.php | 30 ++----------------------- workflow/engine/bin/ldapcron_single.php | 4 ++-- 2 files changed, 4 insertions(+), 30 deletions(-) diff --git a/workflow/engine/bin/ldapcron.php b/workflow/engine/bin/ldapcron.php index 9018f0d6a..99a188f0d 100644 --- a/workflow/engine/bin/ldapcron.php +++ b/workflow/engine/bin/ldapcron.php @@ -11,7 +11,7 @@ try { if (!$flagPathToCron) { //Path to CRON by __FILE__ - $arrayAux = explode(PATH_SEP, str_replace("engine" . PATH_SEP . "plugins" . PATH_SEP . "ldapAdvanced" . PATH_SEP . "bin", "", dirname(__FILE__))); + $arrayAux = explode(PATH_SEP, str_replace("engine" . PATH_SEP . "bin", "", dirname(__FILE__))); array_pop($arrayAux); @@ -21,32 +21,6 @@ try { } } - if (!$flagPathToCron) { - //Path to CRON by symlink - if ($osIsLinux) { - exec("pwd", $arrayOutput); - - if (count($arrayOutput) > 0) { - $arrayPathAux = array( - "engine" . PATH_SEP . "plugins", - "engine" . PATH_SEP . "plugins" . PATH_SEP . "ldapAdvanced" . PATH_SEP . "bin" - ); - - foreach ($arrayPathAux as $value) { - $arrayAux = explode(PATH_SEP, str_replace($value, "", trim($arrayOutput[0]))); - - array_pop($arrayAux); - - if (count($arrayAux) > 0 && $arrayAux[count($arrayAux) - 1] == "workflow") { - $arrayPathToCron = $arrayAux; - $flagPathToCron = true; - break; - } - } - } - } - } - if (!$flagPathToCron) { throw new Exception("Error: Unable to execute the LDAP Advanced CRON, the path is incorrect"); } @@ -136,7 +110,7 @@ try { file_put_contents(PATH_DATA . "ldapcron", serialize($arrayCron)); try { - $ldapCronSinglePath = PATH_PLUGINS . "ldapAdvanced" . PATH_SEP . "bin" . PATH_SEP . "ldapcron_single.php"; + $ldapCronSinglePath = PATH_HOME . "engine" . PATH_SEP . "bin" . PATH_SEP . "ldapcron_single.php"; $workspace = ""; diff --git a/workflow/engine/bin/ldapcron_single.php b/workflow/engine/bin/ldapcron_single.php index 5b169bf54..5bd8790e0 100644 --- a/workflow/engine/bin/ldapcron_single.php +++ b/workflow/engine/bin/ldapcron_single.php @@ -465,8 +465,8 @@ try { eprintln("Processing workspace: " . $workflow, "green"); try { - require_once(PATH_PLUGINS . "ldapAdvanced" . PATH_SEP . "class.ldapAdvanced.php"); - require_once(PATH_PLUGINS . "ldapAdvanced" . PATH_SEP . "services" . PATH_SEP . "ldapadvanced.php"); + require_once(PATH_HOME . "engine" . PATH_SEP . "classes" . PATH_SEP . "class.ldapAdvanced.php"); + require_once(PATH_HOME . "engine" . PATH_SEP . "services" . PATH_SEP . "ldapadvanced.php"); $obj = new ldapadvancedClassCron(); From 50a02c3dbeec458a4092a1fed9c52a535a9f5810 Mon Sep 17 00:00:00 2001 From: "Paula V. Quispe" Date: Wed, 17 Jun 2015 15:47:41 -0400 Subject: [PATCH 09/11] PM-1060: I corrected the paths --- workflow/engine/bin/ldapcron_single.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/workflow/engine/bin/ldapcron_single.php b/workflow/engine/bin/ldapcron_single.php index 5bd8790e0..652f7b6df 100644 --- a/workflow/engine/bin/ldapcron_single.php +++ b/workflow/engine/bin/ldapcron_single.php @@ -466,7 +466,7 @@ try { try { require_once(PATH_HOME . "engine" . PATH_SEP . "classes" . PATH_SEP . "class.ldapAdvanced.php"); - require_once(PATH_HOME . "engine" . PATH_SEP . "services" . PATH_SEP . "ldapadvanced.php"); + require_once(PATH_HOME . "engine" . PATH_SEP . "methods" . PATH_SEP . "services" . PATH_SEP . "ldapadvanced.php"); $obj = new ldapadvancedClassCron(); From 5b87652492712e31677dbae3c0e282317f3026be Mon Sep 17 00:00:00 2001 From: "Paula V. Quispe" Date: Wed, 17 Jun 2015 15:54:48 -0400 Subject: [PATCH 10/11] PM-1060: I used the valid key --- workflow/engine/methods/authSources/authSources_List.php | 2 +- workflow/engine/methods/authSources/authSources_SearchUsers.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/workflow/engine/methods/authSources/authSources_List.php b/workflow/engine/methods/authSources/authSources_List.php index c2949e6d8..4673450e9 100755 --- a/workflow/engine/methods/authSources/authSources_List.php +++ b/workflow/engine/methods/authSources/authSources_List.php @@ -43,7 +43,7 @@ $licensedFeatures = & PMLicensedFeatures::getSingleton(); $oHeadPublisher = & headPublisher::getSingleton(); $oHeadPublisher->addExtJsScript( 'authSources/authSourcesList', false ); //adding a javascript file .js -if ($licensedFeatures->verifyfeature('7TTeDBQeWRoZTZKYjh4eFpYUlRDUUEyVERPU3FxellWank=')) { +if ($licensedFeatures->verifyfeature('sywN09PSzh1MVdOajZBdnhMbFhCSnpNT1lLTEFwVklmOTE=')) { $oHeadPublisher->addExtJsScript( 'authSources/authSourcesListSyn', false ); //adding a javascript file .js } $oHeadPublisher->addContent( 'authSources/authSourcesList' ); //adding a html file .html. diff --git a/workflow/engine/methods/authSources/authSources_SearchUsers.php b/workflow/engine/methods/authSources/authSources_SearchUsers.php index 6f28d0a56..db1200dde 100755 --- a/workflow/engine/methods/authSources/authSources_SearchUsers.php +++ b/workflow/engine/methods/authSources/authSources_SearchUsers.php @@ -38,7 +38,7 @@ $fields = $RBAC->getAuthSource( $_GET['sUID'] ); if (file_exists( PATH_XMLFORM . 'ldapAdvanced/' . $fields['AUTH_SOURCE_PROVIDER'] . 'Edit.xml' )) { $pluginEnabled = 0; $licensedFeatures = & PMLicensedFeatures::getSingleton(); - if ($licensedFeatures->verifyfeature('7TTeDBQeWRoZTZKYjh4eFpYUlRDUUEyVERPU3FxellWank=')) { + if ($licensedFeatures->verifyfeature('sywN09PSzh1MVdOajZBdnhMbFhCSnpNT1lLTEFwVklmOTE=')) { $pluginEnabled = 1; } if ($pluginEnabled == 0) { From 5f4fedbaaa8ad1179d994282d2d2ae89bcd83273 Mon Sep 17 00:00:00 2001 From: "Paula V. Quispe" Date: Fri, 19 Jun 2015 15:42:55 -0400 Subject: [PATCH 11/11] PM-1060: I added marcas --- .../engine/classes/class.licensedFeatures.php | 34 +++++++++++++++++++ .../methods/authSources/authSources_List.php | 4 ++- .../authSources/authSources_SearchUsers.php | 2 ++ 3 files changed, 39 insertions(+), 1 deletion(-) diff --git a/workflow/engine/classes/class.licensedFeatures.php b/workflow/engine/classes/class.licensedFeatures.php index 1a85563cd..7bdb7fa30 100644 --- a/workflow/engine/classes/class.licensedFeatures.php +++ b/workflow/engine/classes/class.licensedFeatures.php @@ -197,6 +197,40 @@ class PMLicensedFeatures "type" => "features", "url" => "", "version" => "" + ), + 10 => array( + "description" => "This plugin will synchronize ProcessMaker with an LDAP or Active Directory server for user authentication.", + "enabled" => false, + "id" => "ldapAdvanced", + "latest_version" => "", + "log" => null, + "name" => "ldapAdvanced", + "nick" => "ldapAdvanced", + "progress" => 0, + "publisher" => "Colosa", + "release_type" => "localRegistry", + "status" => "ready", + "store" => "00000000000000000000000000010010", + "type" => "features", + "url" => "", + "version" => "" + ), + 11 => array( + "description" => "SSO with an LDAP provider.", + "enabled" => false, + "id" => "windowsSSO", + "latest_version" => "", + "log" => null, + "name" => "windowsSSO", + "nick" => "windowsSSO", + "progress" => 0, + "publisher" => "Colosa", + "release_type" => "localRegistry", + "status" => "ready", + "store" => "00000000000000000000000000010011", + "type" => "features", + "url" => "", + "version" => "" ) ); diff --git a/workflow/engine/methods/authSources/authSources_List.php b/workflow/engine/methods/authSources/authSources_List.php index 4673450e9..437cdb169 100755 --- a/workflow/engine/methods/authSources/authSources_List.php +++ b/workflow/engine/methods/authSources/authSources_List.php @@ -43,9 +43,11 @@ $licensedFeatures = & PMLicensedFeatures::getSingleton(); $oHeadPublisher = & headPublisher::getSingleton(); $oHeadPublisher->addExtJsScript( 'authSources/authSourcesList', false ); //adding a javascript file .js +/*----------------------------------********---------------------------------*/ if ($licensedFeatures->verifyfeature('sywN09PSzh1MVdOajZBdnhMbFhCSnpNT1lLTEFwVklmOTE=')) { $oHeadPublisher->addExtJsScript( 'authSources/authSourcesListSyn', false ); //adding a javascript file .js -} +} +/*----------------------------------********---------------------------------*/ $oHeadPublisher->addContent( 'authSources/authSourcesList' ); //adding a html file .html. $oHeadPublisher->assign( 'FORMATS', $c->getFormats() ); $oHeadPublisher->assign( 'CONFIG', $Config ); diff --git a/workflow/engine/methods/authSources/authSources_SearchUsers.php b/workflow/engine/methods/authSources/authSources_SearchUsers.php index db1200dde..b33e2ff58 100755 --- a/workflow/engine/methods/authSources/authSources_SearchUsers.php +++ b/workflow/engine/methods/authSources/authSources_SearchUsers.php @@ -37,10 +37,12 @@ $G_PUBLISH = new Publisher(); $fields = $RBAC->getAuthSource( $_GET['sUID'] ); if (file_exists( PATH_XMLFORM . 'ldapAdvanced/' . $fields['AUTH_SOURCE_PROVIDER'] . 'Edit.xml' )) { $pluginEnabled = 0; + /*----------------------------------********---------------------------------*/ $licensedFeatures = & PMLicensedFeatures::getSingleton(); if ($licensedFeatures->verifyfeature('sywN09PSzh1MVdOajZBdnhMbFhCSnpNT1lLTEFwVklmOTE=')) { $pluginEnabled = 1; } + /*----------------------------------********---------------------------------*/ if ($pluginEnabled == 0) { $G_PUBLISH->AddContent( 'xmlform', 'xmlform', 'login/showMessage', '', array ('MESSAGE' => G::LoadTranslation( 'ID_AUTH_SOURCE_FEATURE_MISSING' ) ) ); G::RenderPage( 'publish', 'blank' );