From 99734449fd616d1ee9750562c310882ab8a9dfde Mon Sep 17 00:00:00 2001 From: Paula Quispe Date: Wed, 15 Feb 2023 09:11:38 -0400 Subject: [PATCH] PMCORE-4147 --- database/factories/DashletInstanceFactory.php | 24 + .../ProcessMaker/BusinessModel/UserTest.php | 158 ++++ workflow/engine/classes/LdapAdvanced.php | 683 ++++++++---------- .../engine/methods/services/ldapadvanced.php | 105 ++- .../src/ProcessMaker/BusinessModel/User.php | 89 ++- .../ProcessMaker/Model/DashletInstance.php | 18 + 6 files changed, 629 insertions(+), 448 deletions(-) create mode 100644 database/factories/DashletInstanceFactory.php create mode 100644 tests/unit/workflow/engine/src/ProcessMaker/BusinessModel/UserTest.php create mode 100644 workflow/engine/src/ProcessMaker/Model/DashletInstance.php diff --git a/database/factories/DashletInstanceFactory.php b/database/factories/DashletInstanceFactory.php new file mode 100644 index 000000000..29f2c8dfb --- /dev/null +++ b/database/factories/DashletInstanceFactory.php @@ -0,0 +1,24 @@ + G::generateUniqueID(), + 'DAS_UID' => G::generateUniqueID(), + 'DAS_INS_OWNER_TYPE' => 'USER', + 'DAS_INS_OWNER_UID' => G::generateUniqueID(), + ]; + } +} diff --git a/tests/unit/workflow/engine/src/ProcessMaker/BusinessModel/UserTest.php b/tests/unit/workflow/engine/src/ProcessMaker/BusinessModel/UserTest.php new file mode 100644 index 000000000..74baee520 --- /dev/null +++ b/tests/unit/workflow/engine/src/ProcessMaker/BusinessModel/UserTest.php @@ -0,0 +1,158 @@ +getGuestUser(); + $this->assertNotEmpty($result); + } + + /** + * This checks the delete case admin + * + * @covers \ProcessMaker\BusinessModel\User::deleteGdpr() + * @test + */ + public function it_test_delete_user_gpdr_exception_when_user_is_admin() + { + $user = new BmUser(); + $this->expectException(Exception::class); + $user->deleteGdpr(RBAC::ADMIN_USER_UID); + } + + /** + * This checks the delete case guest + * + * @covers \ProcessMaker\BusinessModel\User::deleteGdpr() + * @test + */ + public function it_test_delete_user_gpdr_exception_when_user_is_guest() + { + $user = new BmUser(); + $this->expectException(Exception::class); + $user->deleteGdpr(RBAC::GUEST_USER_UID); + } + + /** + * This checks the delete case guest + * + * @covers \ProcessMaker\BusinessModel\User::deleteGdpr() + * + * @test + */ + public function it_test_delete_user_gpdr() + { + // Create a user + $user = User::factory()->create(); + // Assign the user in a group + $groupwf = Groupwf::factory()->create(); + GroupUser::factory()->create([ + 'GRP_UID' => $groupwf->GRP_UID, + 'GRP_ID' => $groupwf->GRP_ID, + 'USR_UID' => $user->USR_UID, + ]); + // Assign the user in a task + TaskUser::factory()->create([ + 'USR_UID' => $user->USR_UID, + 'TU_RELATION' => 1, + ]); + // Assign the user in a process owner + Process::factory()->create([ + 'PRO_CREATE_USER' => $user->USR_UID, + ]); + // Assign the user in a process permission + ObjectPermission::factory()->create([ + 'USR_UID' => $user->USR_UID, + 'OP_USER_RELATION' => 1, + ]); + // Assign the user in a process supervisor + ProcessUser::factory()->create([ + 'USR_UID' => $user->USR_UID, + 'PU_TYPE' => 'SUPERVISOR', + ]); + // Assign the user in a dashboard + DashletInstance::factory()->create([ + 'DAS_INS_OWNER_UID' => $user->USR_UID, + 'DAS_INS_OWNER_TYPE' => 'USER', + ]); + // Delete user + $usr = new BmUser(); + $usr->deleteGdpr($user->USR_UID); + // Check if the user relation with the table are removed + $table = GroupUser::select()->where('USR_UID', $user->USR_UID)->first(); + $this->assertEmpty($table); + $table = TaskUser::select()->where('USR_UID', $user->USR_UID)->first(); + $this->assertEmpty($table); + $table = Process::select()->where('PRO_CREATE_USER', $user->USR_UID)->first(); + $this->assertEmpty($table); + $table = ObjectPermission::select()->where('USR_UID', $user->USR_UID)->first(); + $this->assertEmpty($table); + $table = ProcessUser::select()->where('USR_UID', $user->USR_UID)->first(); + $this->assertEmpty($table); + $table = DashletInstance::select()->where('DAS_INS_OWNER_UID', $user->USR_UID)->first(); + $this->assertEmpty($table); + $table = User::select()->where('USR_UID', $user->USR_UID)->first(); + // Set the important fields with an specific value + $this->assertEquals($table->USR_STATUS, 'CLOSED'); + $this->assertEquals($table->USR_STATUS_ID, 0); + $this->assertEquals($table->USR_FIRSTNAME, $usr::DELETE_USER); + $this->assertEquals($table->USR_LASTNAME, $usr::DELETE_USER); + // Clean the string fields + $this->assertEmpty($table->USR_USERNAME); + $this->assertEmpty($table->USR_EMAIL); + $this->assertEmpty($table->USR_COUNTRY); + $this->assertEmpty($table->USR_CITY); + $this->assertEmpty($table->USR_LOCATION); + $this->assertEmpty($table->USR_ADDRESS); + $this->assertEmpty($table->USR_PHONE); + $this->assertEmpty($table->USR_FAX); + $this->assertEmpty($table->USR_CELLULAR); + $this->assertEmpty($table->USR_ZIP_CODE); + $this->assertEmpty($table->USR_TIME_ZONE); + $this->assertEmpty($table->USR_EXTENDED_ATTRIBUTES_DATA); + // Clean the date fields + $this->assertEquals($table->USR_BIRTHDAY, '0000-00-00'); + $this->assertEquals($table->USR_DUE_DATE, '0000-00-00'); + // Clean the datetime fields + $this->assertEquals($table->USR_DUE_DATE, '0000-00-00 00:00:00'); + $this->assertEquals($table->USR_DUE_DATE, '0000-00-00 00:00:00'); + } +} diff --git a/workflow/engine/classes/LdapAdvanced.php b/workflow/engine/classes/LdapAdvanced.php index 0e98c2e66..2170c6f15 100644 --- a/workflow/engine/classes/LdapAdvanced.php +++ b/workflow/engine/classes/LdapAdvanced.php @@ -8,75 +8,74 @@ use ProcessMaker\Model\Department; use ProcessMaker\Model\Groupwf; /** - * class.ldapAdvanced.php - * LDAP plugin for the RBAC class. This + * Class LdapAdvanced */ class LdapAdvanced { - /** * The authsource id - * @var String + * @var string */ public $sAuthSource = ""; /** * The organizational unit where the removed users are put into - * @var String + * @var string */ public $sTerminatedOu = ""; /** * a local variable to store connection with LDAP, and avoid multiple bindings - * @var String + * @var string */ public $ldapcnn = null; /** * The users information array - * @var Array + * @var array */ - public $aUserInfo = array(); + public $aUserInfo = []; /** * System information - * @var String + * @var string */ public $sSystem = ""; /** * Object where an rbac instance is set - * @var Object + * @var object */ private static $instance = null; - private $arrayObjectClassFilter = array( + private $arrayObjectClassFilter = [ "user" => "|(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 $arrayAttributes = [ + "ldap" => ["uid" => "uid", "member" => "memberuid"], //OpenLDAP + "ad" => ["uid" => "samaccountname", "member" => "member"], //Active Directory + "ds" => ["uid" => "uid", "member" => "uniquemember"] //389 DS + ]; + private $arrayAttributesForUser = ["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(); + public $arrayAuthenticationSourceUsersByUid = []; + public $arrayAuthenticationSourceUsersByUsername = []; + public $arrayDepartmentUsersByUid = []; + public $arrayDepartmentUsersByUsername = []; + public $arrayGroupUsersByUid = []; + public $arrayGroupUsersByUsername = []; + public $allListOfUsers = []; + private $arrayDepartmentUserSynchronizedChecked = []; + private $arrayUserUpdateChecked = []; + const DELETE_USER = 'unknown'; /** * default constructor method */ public function __construct() { - } /** @@ -84,7 +83,7 @@ class LdapAdvanced * * @param bool $flag Flag * - * return void + * @return void */ public function setFrontEnd($flag) { @@ -100,7 +99,7 @@ class LdapAdvanced * * @param bool $debug Flag for debug * - * return void + * @return void */ public function setDebug($debug) { @@ -116,30 +115,26 @@ class LdapAdvanced * * @param string $authenticationSourceUid UID of Authentication Source * - * return void + * @return void */ public function setArrayAuthenticationSourceUsers($authenticationSourceUid) { try { - $this->arrayAuthenticationSourceUsersByUid = array(); - $this->arrayAuthenticationSourceUsersByUsername = array(); - - //Set data + $this->arrayAuthenticationSourceUsersByUid = []; + $this->arrayAuthenticationSourceUsersByUsername = []; + // Get all users related to the ldap source $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); - + $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; } @@ -154,18 +149,17 @@ class LdapAdvanced * @param string $userUid UID of User * @param array $arrayUserLdap User LDAP data * - * return void + * @return void */ public function setArrayAuthenticationSourceUser($userUid, array $arrayUserLdap) { try { - $arrayUserData = array( + $arrayUserData = [ "USR_UID" => $userUid, "USR_USERNAME" => $arrayUserLdap["sUsername"], "USR_AUTH_USER_DN" => $arrayUserLdap["sDN"] - ); - - //Set data + ]; + // Set data $this->arrayAuthenticationSourceUsersByUid[$arrayUserData["USR_UID"]] = $arrayUserData; $this->arrayAuthenticationSourceUsersByUsername[$arrayUserData["USR_USERNAME"]] = $arrayUserData; } catch (Exception $e) { @@ -178,29 +172,24 @@ class LdapAdvanced * * @param string $departmentUid UID of Department * - * return void + * @return void */ public function setArrayDepartmentUsers($departmentUid) { try { - $this->arrayDepartmentUsersByUid = array(); - $this->arrayDepartmentUsersByUsername = array(); - - //Set data + $this->arrayDepartmentUsersByUid = []; + $this->arrayDepartmentUsersByUsername = []; + // 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; } @@ -214,17 +203,16 @@ class LdapAdvanced * * @param string $groupUid UID of Group * - * return void + * @return void */ public function setArrayGroupUsers($groupUid) { try { - $this->arrayGroupUsersByUid = array(); - $this->arrayGroupUsersByUsername = array(); + $this->arrayGroupUsersByUid = []; + $this->arrayGroupUsersByUsername = []; - //Set data + // Set data $criteria = new Criteria("workflow"); - $criteria->addSelectColumn(GroupUserPeer::GRP_UID); $criteria->addSelectColumn(GroupUserPeer::USR_UID); $criteria->addSelectColumn(UsersPeer::USR_USERNAME); @@ -232,13 +220,11 @@ class LdapAdvanced $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; } @@ -252,7 +238,7 @@ class LdapAdvanced * * @param array $arrayData Data * - * return void + * @return void */ public function setArrayDepartmentUserSynchronizedChecked(array $arrayData) { @@ -268,7 +254,7 @@ class LdapAdvanced * * @param array $arrayData Data * - * return void + * @return void */ public function setArrayUserUpdateChecked(array $arrayData) { @@ -298,7 +284,7 @@ class LdapAdvanced * @param int $total Total * @param int $count Count * - * return string Return a string that represent progress bar + * @return string Return a string that represent progress bar */ public function progressBar($total, $count) { @@ -318,7 +304,7 @@ class LdapAdvanced * @param string $option Option * @param string $data Data string * - * return void + * @return void */ public function frontEndShow($option, $data = "") { @@ -336,8 +322,7 @@ class LdapAdvanced case "TEXT": echo "\r" . "| " . $data . str_repeat(" ", $numc - 2 - strlen($data)) . "\n"; break; - default: - //START, END + default: //START, END echo "\r" . "+" . str_repeat("-", $numc - 2) . "+" . "\n"; break; } @@ -349,12 +334,12 @@ class LdapAdvanced /** * Get valid characteres * - * return array Return an array with valid characteres + * @return array Return an array with valid characteres */ public function characters() { try { - $arrayCharacter = array(); + $arrayCharacter = []; for ($i = 33; $i <= 127; $i++) { $char = trim(strtolower(chr($i))); @@ -375,7 +360,7 @@ class LdapAdvanced unset($arrayCharacter[124]); //| unset($arrayCharacter[126]); //~ unset($arrayCharacter[127]); //DEL - //Return + // Return return array_unique($arrayCharacter); } catch (Exception $e) { throw $e; @@ -387,7 +372,7 @@ class LdapAdvanced * * @param string $username Username * - * return array Return User data, if Username was registered with this Authentication Source; empty data otherwise + * @return array Return User data, if Username was registered with this Authentication Source; empty data otherwise */ public function authenticationSourceGetUserDataIfUsernameExists($username) { @@ -395,8 +380,8 @@ class LdapAdvanced if (isset($this->arrayAuthenticationSourceUsersByUsername[$username])) { return $this->arrayAuthenticationSourceUsersByUsername[$username]; } - - return array(); + // Return + return []; } catch (Exception $e) { throw $e; } @@ -407,7 +392,7 @@ class LdapAdvanced * * @param string $username Username * - * return array Return User data, if Username exists in Department; empty data otherwise + * @return array Return User data, if Username exists in Department; empty data otherwise */ public function departmentGetUserDataIfUsernameExists($username) { @@ -415,8 +400,8 @@ class LdapAdvanced if (isset($this->arrayDepartmentUsersByUsername[$username])) { return $this->arrayDepartmentUsersByUsername[$username]; } - - return array(); + // Return + return []; } catch (Exception $e) { throw $e; } @@ -427,7 +412,7 @@ class LdapAdvanced * * @param string $username Username * - * return array Return User data, if Username exists in Group; empty data otherwise + * @return array Return User data, if Username exists in Group; empty data otherwise */ public function groupGetUserDataIfUsernameExists($username) { @@ -435,8 +420,8 @@ class LdapAdvanced if (isset($this->arrayGroupUsersByUsername[$username])) { return $this->arrayGroupUsersByUsername[$username]; } - - return array(); + // Return + return []; } catch (Exception $e) { throw $e; } @@ -444,7 +429,7 @@ class LdapAdvanced public function getFieldsForPageSetup() { - return array(); + return []; } /** @@ -454,7 +439,7 @@ class LdapAdvanced * and now we are saving the log in shared/log the entry in the log file. * * @param Object $_link ldap connection - * @param String $text + * @param string $text * @return void */ public function log($link, $text) @@ -475,7 +460,7 @@ class LdapAdvanced } } - //log format: date hour ipaddress workspace ldapErrorNr + // 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"), config("system.workspace"), $ldapErrorNr, $text)); fclose($fpt); } else { @@ -488,7 +473,7 @@ class LdapAdvanced * * @param string $text Text * - * return void + * @return void */ public function debugLog($text) { @@ -505,8 +490,8 @@ class LdapAdvanced * This method generates the ldap connection bind and returns the link object * for a determined authsource * - * @param Array $aAuthSource the authsource data - * @return Object A object with the resulting ldap bind + * @param array $aAuthSource the authsource data + * @return object A object with the resulting ldap bind */ public function ldapConnection($aAuthSource, &$resultLDAPStartTLS = false) { @@ -556,7 +541,7 @@ class LdapAdvanced /** * Get a diagnostic message of the ldap connection status. - * @param resource $linkIdentifier + * @param LDAP\Connection $linkIdentifier */ public function getDiagnosticMessage($linkIdentifier) { @@ -615,15 +600,15 @@ class LdapAdvanced /** * This method obtains the attributes of a ldap Connection passed as parameter - * @param Object $ldapcnn ldap connection - * - * @param Object $oEntry Entry object - * @return Array attributes + * @param object $ldapcnn ldap connection + * @param object $oEntry Entry object + * + * @return array attributes */ public function ldapGetAttributes($ldapcnn, $entry) { try { - $arrayAttributes = array(); + $arrayAttributes = []; $arrayAttributes['dn'] = ldap_get_dn($ldapcnn, $entry); $this->stdLog($ldapcnn, "ldap_get_dn"); @@ -662,8 +647,8 @@ class LdapAdvanced /** * Get Users from Department (Search result identifier) * - * @param resource $ldapcnn LDAP link identifier - * @param resource $searchResult Search result identifier + * @param LDAP\Connection $ldapcnn LDAP link identifier + * @param LDAP\Result $searchResult Search result identifier * @param string $option Option (GET, SYNCHRONIZE) * @param string $dn DN * @param string $uidUserIdentifier User identifier @@ -680,25 +665,20 @@ class LdapAdvanced if ($searchResult) { $this->debugLog("class.ldapAdvanced.php > function ldapGetUsersFromDepartmentSearchResult() > ldap_list > OK"); - $numEntries = ldap_count_entries($ldapcnn, $searchResult); $this->stdLog($ldapcnn, "ldap_count_entries"); - $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); $this->stdLog($ldapcnn, "ldap_first_entry"); do { $arrayUserLdap = $this->ldapGetAttributes($ldapcnn, $entry); - $username = (isset($arrayUserLdap[$uidUserIdentifier])) ? $arrayUserLdap[$uidUserIdentifier] : ""; - $countUser++; if ((is_array($username) && !empty($username)) || trim($username) != "") { @@ -721,7 +701,7 @@ class LdapAdvanced } if ($option == "SYNCHRONIZE") { - //Progress bar + // Progress bar $this->frontEndShow("BAR", "Departments: " . $arrayData["i"] . "/" . $arrayData["n"] . " " . $this->progressBar($totalUser, $countUser)); } } while ($entry = ldap_next_entry($ldapcnn, $entry)); @@ -729,8 +709,7 @@ class LdapAdvanced } $this->debugLog("class.ldapAdvanced.php > function ldapGetUsersFromDepartmentSearchResult() > END"); - - //Return + // Return return array($totalUser, $countUser, $arrayData); } catch (Exception $e) { throw $e; @@ -746,13 +725,13 @@ class LdapAdvanced * * return array Return an array with data Users or array data */ - public function ldapGetUsersFromDepartment($option, $dn, array $arrayData = array()) + public function ldapGetUsersFromDepartment($option, $dn, array $arrayData = []) { try { $this->debugLog("class.ldapAdvanced.php > function ldapGetUsersFromDepartment() > START"); $this->debugLog("class.ldapAdvanced.php > function ldapGetUsersFromDepartment() > \$dn ----> $dn"); - $arrayUser = array(); + $arrayUser = []; $totalUser = 0; $countUser = 0; @@ -765,9 +744,7 @@ class LdapAdvanced } $arrayAuthenticationSourceData = $rbac->authSourcesObj->load($this->sAuthSource); - $this->ldapcnn = $this->ldapConnection($arrayAuthenticationSourceData); - $ldapcnn = $this->ldapcnn; //Get Users @@ -779,26 +756,22 @@ class LdapAdvanced } $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"); - $cookie = ''; do { $searchResult = @ldap_list( - $ldapcnn, - $dn, - $filter, - $this->arrayAttributesForUser, - 0, - -1, - -1, - LDAP_DEREF_NEVER, - [['oid' => LDAP_CONTROL_PAGEDRESULTS, 'value' => ['size' => $limit, 'cookie' => $cookie]]] + $ldapcnn, + $dn, + $filter, + $this->arrayAttributesForUser, + 0, + -1, + -1, + LDAP_DEREF_NEVER, + [['oid' => LDAP_CONTROL_PAGEDRESULTS, 'value' => ['size' => $limit, 'cookie' => $cookie]]] ); ldap_parse_result($ldapcnn, $searchResult, $errcode, $matcheddn, $errmsg, $referrals, $controls); $this->stdLog($ldapcnn, "ldap_list", ["filter" => $filter, "attributes" => $this->arrayAttributesForUser]); @@ -829,7 +802,7 @@ class LdapAdvanced // Empty cookie means last page } while (!empty($cookie) && !$flagError); - //Get Users //2 + // Get Users //2 if ($flagError) { $this->debugLog("class.ldapAdvanced.php > function ldapGetUsersFromDepartment() > Search by characters > START"); @@ -837,12 +810,9 @@ class LdapAdvanced $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); $this->stdLog($ldapcnn, "ldap_list", ["attributes" => $this->arrayAttributesForUser]); @@ -866,10 +836,9 @@ class LdapAdvanced } $this->log($ldapcnn, "Found $totalUser users in department $dn"); - $this->debugLog("class.ldapAdvanced.php > function ldapGetUsersFromDepartment() > END"); - //Return + // Return switch ($option) { case "GET": return $arrayUser; @@ -886,7 +855,7 @@ class LdapAdvanced /** * Synchronize Group's members * - * @param resource $ldapcnn LDAP link identifier + * @param LDAP\Connection $ldapcnn LDAP link identifier * @param array $arrayAuthSourceData Authentication Source Data * @param string $groupUid Unique id of Group * @param array $arrayGroupLdap LDAP Group @@ -940,11 +909,8 @@ class LdapAdvanced $this->stdLog($ldapcnn, "ldap_count_entries"); $entry = ldap_first_entry($ldapcnn, $searchResult); $this->stdLog($ldapcnn, "ldap_first_entry"); - $arrayUserLdap = $this->ldapGetAttributes($ldapcnn, $entry); - $username = (isset($arrayUserLdap[$uidUserIdentifier])) ? $arrayUserLdap[$uidUserIdentifier] : ''; - $arrayData['countUser']++; if ((is_array($username) && !empty($username)) || trim($username) != '') { @@ -964,15 +930,14 @@ class LdapAdvanced $this->frontEndShow( 'BAR', 'Groups: ' . $arrayData['i'] . '/' . $arrayData['n'] . ' ' . - $this->progressBar($arrayData['totalUser'], $arrayData['countUser']) + $this->progressBar($arrayData['totalUser'], $arrayData['countUser']) ); } } } } } - - //Return + // Return return $arrayData; } catch (Exception $e) { throw $e; @@ -988,7 +953,7 @@ class LdapAdvanced * * return array Return array data */ - public function ldapGetUsersFromGroup($option, array $arrayGroupData, array $arrayData = array()) + public function ldapGetUsersFromGroup($option, array $arrayGroupData, array $arrayData = []) { try { $this->debugLog("class.ldapAdvanced.php > function ldapGetUsersFromGroup() > START"); @@ -1006,18 +971,13 @@ class LdapAdvanced } $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)); $context = [ "baseDN" => $dn, @@ -1033,28 +993,22 @@ class LdapAdvanced if ($searchResult) { $this->debugLog("class.ldapAdvanced.php > function ldapGetUsersFromGroup() > ldap_search > OK2"); - $numEntries = ldap_count_entries($ldapcnn, $searchResult); $this->stdLog($ldapcnn, "ldap_count_entries"); - $this->debugLog("class.ldapAdvanced.php > function ldapGetUsersFromGroup() > ldap_search > OK2 > \$numEntries ----> $numEntries"); if ($numEntries > 0) { $entry = ldap_first_entry($ldapcnn, $searchResult); $this->stdLog($ldapcnn, "ldap_first_entry"); - $arrayGroupLdap = $this->ldapGetAttributes($ldapcnn, $entry); - - //Syncronize members + // Syncronize members $flagMemberRange = false; - $memberAttribute2 = $memberAttribute; if (isset($arrayGroupLdap[$memberAttribute]) && empty($arrayGroupLdap[$memberAttribute])) { foreach ($arrayGroupLdap as $key => $value) { if (preg_match('/^member;range=\d+\-\d+$/i', $key)) { $memberAttribute2 = $key; - $flagMemberRange = true; break; } @@ -1078,9 +1032,7 @@ class LdapAdvanced if ($flagMemberRange) { for ($start = $limitMemberRange; true; $start += $limitMemberRange) { $end = $start + $limitMemberRange - 1; - $memberAttribute2 = $memberAttribute . ';range=' . $start . '-' . $end; - $searchResult = @ldap_search($ldapcnn, $dn, $filter, [$memberAttribute2]); $context = [ "baseDN" => $dn, @@ -1097,7 +1049,6 @@ class LdapAdvanced $this->stdLog($ldapcnn, "ldap_count_entries"); $entry = ldap_first_entry($ldapcnn, $searchResult); $this->stdLog($ldapcnn, "ldap_first_entry"); - $arrayGroupLdap = $this->ldapGetAttributes($ldapcnn, $entry); foreach ($arrayGroupLdap as $key => $value) { @@ -1128,7 +1079,6 @@ class LdapAdvanced } $this->log($ldapcnn, "Found $totalUser users in group $dn"); - $this->debugLog("class.ldapAdvanced.php > function ldapGetUsersFromGroup() > END"); //Return @@ -1171,7 +1121,6 @@ class LdapAdvanced } $ldapcnn = null; - $validUserPass = 1; try { @@ -1186,10 +1135,10 @@ class LdapAdvanced } $arrayAuthSource = $rbac->authSourcesObj->load($this->sAuthSource); - $setAttributes = 0; - if (isset($arrayAuthSource['AUTH_SOURCE_DATA']['AUTH_SOURCE_SHOWGRID']) && + if ( + isset($arrayAuthSource['AUTH_SOURCE_DATA']['AUTH_SOURCE_SHOWGRID']) && $arrayAuthSource['AUTH_SOURCE_DATA']['AUTH_SOURCE_SHOWGRID'] == 'on' ) { $setAttributes = 1; @@ -1197,22 +1146,17 @@ class LdapAdvanced //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"]; - $userDn = $strUser; //Get the AuthSource properties @@ -1226,7 +1170,7 @@ class LdapAdvanced if ($verifiedUser["sDN"] != $strUser || $setAttributes == 1) { $userDn = $verifiedUser['sDN']; - //Update data + // Update data $user = new User(); $arrayUserData = $user->getUserRecordByPk($usrUid, [], false); @@ -1298,7 +1242,7 @@ class LdapAdvanced $c2->add(RbacUsersPeer::USR_AUTH_USER_DN, $userDn); $c2->add(RbacUsersPeer::USR_STATUS, $statusRbac); BasePeer::doUpdate($c1, $c2, $con); - $columnsWf = array(); + $columnsWf = []; $columnsWf['USR_UID'] = $usrUid; $columnsWf['USR_STATUS'] = $statusUser; $oUser = new Users(); @@ -1308,10 +1252,10 @@ class LdapAdvanced $attributes = $arrayAuthSource["AUTH_SOURCE_DATA"]; if (!isset($attributes['AUTH_SOURCE_RETIRED_OU'])) { - $attributes ['AUTH_SOURCE_RETIRED_OU'] = ''; + $attributes['AUTH_SOURCE_RETIRED_OU'] = ''; } - //Check if the user is in the terminated organizational unit + // Check if the user is in the terminated organizational unit if (!empty($verifiedUser) && $this->userIsTerminated($usrName, $attributes["AUTH_SOURCE_RETIRED_OU"])) { $this->deactivateUser($usrName); $this->log($ldapcnn, "user $strUser is member of Remove OU, deactivating this user."); @@ -1345,7 +1289,7 @@ class LdapAdvanced try { $keyMail = (isset($arrayAttributes["mail"])) ? "mail" : ((isset($arrayAttributes["userprincipalname"])) ? "userprincipalname" : "nomail"); - return array( + return [ "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"]) : ""), @@ -1354,7 +1298,7 @@ class LdapAdvanced "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; } @@ -1363,12 +1307,12 @@ class LdapAdvanced /** * This method searches for the users that has some attribute * that matches the keyword. - * @param String $keyword search criteria + * @param string $keyword search criteria * @return array Users that match the search criteria */ public function searchUsers($keyword, $start = null, $limit = null) { - $arrayUser = array(); + $arrayUser = []; $totalUser = 0; $countUser = 0; @@ -1381,10 +1325,11 @@ class LdapAdvanced } $arrayAuthenticationSourceData = $rbac->authSourcesObj->load($this->sAuthSource); - $attributeUserSet = array(); - $attributeSetAdd = array(); + $attributeUserSet = []; + $attributeSetAdd = []; - if (isset($arrayAuthenticationSourceData["AUTH_SOURCE_DATA"]["AUTH_SOURCE_GRID_ATTRIBUTE"]) && !empty($arrayAuthenticationSourceData["AUTH_SOURCE_DATA"]["AUTH_SOURCE_GRID_ATTRIBUTE"]) + 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']; @@ -1404,12 +1349,9 @@ class LdapAdvanced } $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)); $context = [ "baseDN" => $arrayAuthenticationSourceData["AUTH_SOURCE_BASE_DN"], @@ -1429,9 +1371,7 @@ class LdapAdvanced if ($entries > 0) { $oEntry = ldap_first_entry($ldapcnn, $oSearch); $this->stdLog($ldapcnn, "ldap_first_entry"); - $countEntries = 0; - $flagNextRecord = true; do { @@ -1499,7 +1439,7 @@ class LdapAdvanced if (isset($aAttr['status'])) { $userCountControl = strtoupper($aAttr['status']); } - $aUserAttributes = array(); + $aUserAttributes = []; foreach ($attributeUserSet as $key => $value) { if ($key == 'USR_STATUS') { $aUserAttributes[$key] = ($userCountControl != '') ? $userCountControl : 'ACTIVE'; @@ -1527,20 +1467,20 @@ class LdapAdvanced } } - return ($paged) ? array("numRecTotal" => $totalUser, "data" => $arrayUser) : $arrayUser; + return ($paged) ? ["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 + * @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(); + $arrayUserData = []; //Set variables $rbac = RBAC::getSingleton(); @@ -1558,10 +1498,11 @@ class LdapAdvanced $ldapcnn = $this->ldapcnn; //Get User - $attributeUserSet = array(); - $attributeSetAdd = array(); + $attributeUserSet = []; + $attributeSetAdd = []; - if (isset($arrayAuthenticationSourceData["AUTH_SOURCE_DATA"]["AUTH_SOURCE_GRID_ATTRIBUTE"]) && !empty($arrayAuthenticationSourceData["AUTH_SOURCE_DATA"]["AUTH_SOURCE_GRID_ATTRIBUTE"]) + 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"]; @@ -1599,9 +1540,7 @@ class LdapAdvanced if ($numEntries > 0) { $entry = ldap_first_entry($ldapcnn, $searchResult); $this->stdLog($ldapcnn, "ldap_first_entry"); - $arrayUserLdap = $this->ldapGetAttributes($ldapcnn, $entry); - $username = (isset($arrayUserLdap[$uidUserIdentifier])) ? $arrayUserLdap[$uidUserIdentifier] : ""; if ((is_array($username) && !empty($username)) || trim($username) != "") { @@ -1634,7 +1573,7 @@ class LdapAdvanced $userCountControl = strtoupper($arrayUserLdap["status"]); } - $aUserAttributes = array(); + $aUserAttributes = []; foreach ($attributeUserSet as $key => $value) { if ($key == "USR_STATUS") { @@ -1678,7 +1617,6 @@ class LdapAdvanced } $user = $this->searchUserByUid($strUser); - $result = 0; if (!empty($user)) { @@ -1782,26 +1720,22 @@ class LdapAdvanced //Get Departments $limit = $this->getPageSizeLimitByData($arrayAuthenticationSourceData); $flagError = false; - $filter = '(' . $this->arrayObjectClassFilter['department'] . ')'; - $this->log($ldapcnn, 'search Departments with Filter: ' . $filter); - $unitsBase = $this->custom_ldap_explode_dn($arrayAuthenticationSourceData['AUTH_SOURCE_BASE_DN']); $cookie = ''; - do { $searchResult = @ldap_search( - $ldapcnn, - $arrayAuthenticationSourceData['AUTH_SOURCE_BASE_DN'], - $filter, - ['dn', 'ou'], - 0, - -1, - -1, - LDAP_DEREF_NEVER, - [['oid' => LDAP_CONTROL_PAGEDRESULTS, 'value' => ['size' => $limit, 'cookie' => $cookie]]] + $ldapcnn, + $arrayAuthenticationSourceData['AUTH_SOURCE_BASE_DN'], + $filter, + ['dn', 'ou'], + 0, + -1, + -1, + LDAP_DEREF_NEVER, + [['oid' => LDAP_CONTROL_PAGEDRESULTS, 'value' => ['size' => $limit, 'cookie' => $cookie]]] ); ldap_parse_result($ldapcnn, $searchResult, $errcode, $matcheddn, $errmsg, $referrals, $controls); $this->stdLog($ldapcnn, "ldap_search", ["filter" => $filter, "attributes" => ['dn', 'ou']]); @@ -1894,9 +1828,8 @@ class LdapAdvanced { $dFilter = "(&(" . $this->arrayObjectClassFilter["department"] . ")(ou=" . $departmentName . "))"; - $aUsers = array(); + $aUsers = []; $rbac = RBAC::getSingleton(); - $rbac->authSourcesObj = new AuthenticationSource(); $aAuthSource = $rbac->authSourcesObj->load($this->sAuthSource); @@ -1905,7 +1838,6 @@ class LdapAdvanced } $ldapcnn = $this->ldapcnn; - $oSearch = @ldap_search($ldapcnn, $aAuthSource["AUTH_SOURCE_BASE_DN"], $dFilter, $this->arrayAttributesForUser); $context = [ "baseDN" => $aAuthSource["AUTH_SOURCE_BASE_DN"], @@ -1948,7 +1880,6 @@ class LdapAdvanced $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); @@ -1972,18 +1903,16 @@ class LdapAdvanced public function departmentsGetNumberOfUsersFromDb() { try { - $arrayData = array(); + $arrayData = []; //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); @@ -2118,7 +2047,7 @@ class LdapAdvanced require_once(PATH_RBAC . 'model/AuthenticationSource.php'); $oCriteria = new Criteria('rbac'); - $aAuthSources = array(); + $aAuthSources = []; $oAuthSource = new AuthenticationSource(); $oCriteria = $oAuthSource->getAllAuthSources(); @@ -2129,7 +2058,7 @@ class LdapAdvanced $aRow = $oDataset->getRow(); if ($aRow['AUTH_SOURCE_PROVIDER'] == 'ldapAdvanced') { - $aRow["AUTH_SOURCE_DATA"] = ($aRow["AUTH_SOURCE_DATA"] != "") ? unserialize($aRow["AUTH_SOURCE_DATA"]) : array(); + $aRow["AUTH_SOURCE_DATA"] = ($aRow["AUTH_SOURCE_DATA"] != "") ? unserialize($aRow["AUTH_SOURCE_DATA"]) : []; $aAuthSources[] = $aRow; } @@ -2151,7 +2080,7 @@ class LdapAdvanced */ public function getRegisteredDepartments(array $arrayLdapDepartment, array $arrayDbDepartment) { - $aResult = array(); + $aResult = []; if (!empty($arrayLdapDepartment)) { $arrayLdapDepartment[0]["ou"] = $arrayLdapDepartment[0]["ou"] . " " . $arrayLdapDepartment[0]["dn"]; //Discard ROOT @@ -2176,7 +2105,7 @@ class LdapAdvanced public function getDepartments($DepParent) { try { - $result = array(); + $result = []; $criteria = new Criteria('workflow'); if (!empty($DepParent)) { @@ -2187,7 +2116,7 @@ class LdapAdvanced $objects = DepartmentPeer::doSelect($criteria, $con); foreach ($objects as $oDepartment) { - $node = array(); + $node = []; $node['DEP_UID'] = $oDepartment->getDepUid(); $node['DEP_PARENT'] = $oDepartment->getDepParent(); $node['DEP_TITLE'] = stripslashes($oDepartment->getDepTitle()); @@ -2228,21 +2157,18 @@ class LdapAdvanced { 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(); + return []; } catch (Exception $e) { throw $e; } @@ -2257,7 +2183,7 @@ class LdapAdvanced */ public function getUsersFromRemovedOu($aAuthSource) { - $aUsers = array(); //empty array is the default result + $aUsers = []; //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']) : ''; @@ -2286,7 +2212,7 @@ class LdapAdvanced require_once('classes/model/Users.php'); } - $aUsrUid = array(); + $aUsrUid = []; foreach ($aUsers as $key => $val) { $aUsrUid[] = $val['sUsername']; @@ -2441,28 +2367,24 @@ class LdapAdvanced } $ldapcnn = $this->ldapcnn; - - //Get Groups + // Get Groups $limit = $this->getPageSizeLimitByData($arrayAuthenticationSourceData); $flagError = false; - $filter = '(' . $this->arrayObjectClassFilter['group'] . ')'; - $this->log($ldapcnn, 'search groups with Filter: ' . $filter); $cookie = ''; - do { $searchResult = @ldap_search( - $ldapcnn, - $arrayAuthenticationSourceData['AUTH_SOURCE_BASE_DN'], - $filter, - ['dn', 'cn'], - 0, - -1, - -1, - LDAP_DEREF_NEVER, - [['oid' => LDAP_CONTROL_PAGEDRESULTS, 'value' => ['size' => $limit, 'cookie' => $cookie]]] + $ldapcnn, + $arrayAuthenticationSourceData['AUTH_SOURCE_BASE_DN'], + $filter, + ['dn', 'cn'], + 0, + -1, + -1, + LDAP_DEREF_NEVER, + [['oid' => LDAP_CONTROL_PAGEDRESULTS, 'value' => ['size' => $limit, 'cookie' => $cookie]]] ); ldap_parse_result($ldapcnn, $searchResult, $errcode, $matcheddn, $errmsg, $referrals, $controls); $this->stdLog($ldapcnn, "ldap_search", ["filter" => $filter, "attributes" => ['dn', 'cn']]); @@ -2530,8 +2452,8 @@ class LdapAdvanced /** * Check if the group exists and returns the PM UID - * @param $currentDN - * @return + * @param string $currentDN + * @return string */ public function getGrpUidIfExistsDN($currentDN) { @@ -2641,23 +2563,20 @@ class LdapAdvanced public function groupsGetNumberOfUsersFromDb() { try { - $arrayData = array(); + $arrayData = []; - //Get data + // 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"]; } @@ -2673,13 +2592,13 @@ class LdapAdvanced public function getGroups() { try { - $result = array(); + $result = []; $criteria = new Criteria('workflow'); $con = Propel::getConnection(GroupwfPeer::DATABASE_NAME); $objects = GroupwfPeer::doSelect($criteria, $con); foreach ($objects as $oGroup) { - $node = array(); + $node = []; $node['GRP_UID'] = $oGroup->getGrpUid(); $node['GRP_TITLE'] = stripslashes($oGroup->getGrpTitle()); $node['GRP_STATUS'] = $oGroup->getGrpStatus(); @@ -2706,7 +2625,7 @@ class LdapAdvanced */ public function getRegisteredGroups(array $arrayLdapGroup, array $arrayDbGroup) { - $aResult = array(); + $aResult = []; if (!empty($arrayLdapGroup)) { foreach ($arrayLdapGroup as $ldapGroup) { @@ -2752,8 +2671,8 @@ class LdapAdvanced foreach ($result as $key => $value) { $result[$key] = addcslashes(preg_replace_callback("/\\\([0-9A-Fa-f]{2})/", function ($m) { - return chr(hexdec($m[1])); - }, $value), '<>,"'); + return chr(hexdec($m[1])); + }, $value), '<>,"'); } } @@ -2785,7 +2704,6 @@ class LdapAdvanced //User already exists $userUid = $arrayUserData["USR_UID"]; $found = true; - $arrayData["already"]++; $arrayData["alreadyUsers"] .= $arrayUserData["USR_USERNAME"] . " "; } @@ -2847,7 +2765,7 @@ class LdapAdvanced if (isset($arrayUserLdap["sManagerDN"]) && $arrayUserLdap["sManagerDN"] != "") { if (!isset($arrayData["managersHierarchy"][$arrayUserLdap["sManagerDN"]])) { - $arrayData["managersHierarchy"][$arrayUserLdap["sManagerDN"]] = array(); + $arrayData["managersHierarchy"][$arrayUserLdap["sManagerDN"]] = []; } $arrayData["managersHierarchy"][$arrayUserLdap["sManagerDN"]][$userUid] = $userUid; @@ -2947,7 +2865,7 @@ class LdapAdvanced if (isset($arrayUserLdap["sManagerDN"]) && $arrayUserLdap["sManagerDN"] != "") { if (!isset($arrayData["managersHierarchy"][$arrayUserLdap["sManagerDN"]])) { - $arrayData["managersHierarchy"][$arrayUserLdap["sManagerDN"]] = array(); + $arrayData["managersHierarchy"][$arrayUserLdap["sManagerDN"]] = []; } $arrayData["managersHierarchy"][$arrayUserLdap["sManagerDN"]][$userUid] = $userUid; @@ -2967,7 +2885,7 @@ class LdapAdvanced /** * Update User data based on the LDAP Server * - * @param resource $ldapcnn LDAP link identifier + * @param LDAP\Connection $ldapcnn LDAP link identifier * @param array $arrayAuthSourceData Authentication Source Data * @param string $userDn User DN * @param array $arrayUser Users @@ -2977,16 +2895,13 @@ class LdapAdvanced private function ldapUserUpdateByDnAndData($ldapcnn, array $arrayAuthSourceData, $userDn, array $arrayUser) { try { - //Set variables + // Set variables $rbac = RBAC::getSingleton(); - if (is_null($rbac->userObj)) { $rbac->userObj = new RbacUsers(); } - - //Set variables + // Set variables $flagUser = false; - $arrayAttributesToSync = [ //Default attributes to sync 'USR_FIRSTNAME' => 'givenname', @@ -2995,20 +2910,17 @@ class LdapAdvanced 'USR_STATUS' => 'useraccountcontrol' ]; - if (isset($arrayAuthSourceData['AUTH_SOURCE_DATA']['AUTH_SOURCE_GRID_ATTRIBUTE']) && - !empty($arrayAuthSourceData['AUTH_SOURCE_DATA']['AUTH_SOURCE_GRID_ATTRIBUTE']) - ) { + if (!empty($arrayAuthSourceData['AUTH_SOURCE_DATA']['AUTH_SOURCE_GRID_ATTRIBUTE'])) { foreach ($arrayAuthSourceData['AUTH_SOURCE_DATA']['AUTH_SOURCE_GRID_ATTRIBUTE'] as $value) { $arrayAttributesToSync[$value['attributeUser']] = $value['attributeLdap']; } } - //Search User from LDAP Server + // Search User from LDAP Server $uidUserIdentifier = (isset($arrayAuthSourceData['AUTH_SOURCE_DATA']['AUTH_SOURCE_IDENTIFIER_FOR_USER'])) ? $arrayAuthSourceData['AUTH_SOURCE_DATA']['AUTH_SOURCE_IDENTIFIER_FOR_USER'] : 'uid'; $arrayAttribute = array_merge($this->arrayAttributesForUser, array_values($arrayAttributesToSync)); - $searchResult = @ldap_search($ldapcnn, $userDn, '(objectclass=*)', $arrayAttribute); $context = [ "baseDN" => $userDn, @@ -3019,87 +2931,82 @@ class LdapAdvanced if ($error = ldap_errno($ldapcnn)) { // - } else { - if ($searchResult && ldap_count_entries($ldapcnn, $searchResult) > 0) { - $this->stdLog($ldapcnn, "ldap_count_entries"); - $entry = ldap_first_entry($ldapcnn, $searchResult); - $this->stdLog($ldapcnn, "ldap_first_entry", $context); + } elseif ($searchResult && ldap_count_entries($ldapcnn, $searchResult) > 0) { + $this->stdLog($ldapcnn, "ldap_count_entries"); + $entry = ldap_first_entry($ldapcnn, $searchResult); + $this->stdLog($ldapcnn, "ldap_first_entry", $context); + $arrayUserLdap = $this->ldapGetAttributes($ldapcnn, $entry); + $username = (isset($arrayUserLdap[$uidUserIdentifier])) ? $arrayUserLdap[$uidUserIdentifier] : ''; - $arrayUserLdap = $this->ldapGetAttributes($ldapcnn, $entry); + if ((is_array($username) && !empty($username)) || trim($username) != '') { + $username = trim((is_array($username)) ? $username[0] : $username); - $username = (isset($arrayUserLdap[$uidUserIdentifier])) ? $arrayUserLdap[$uidUserIdentifier] : ''; + if (isset($arrayUser[$username])) { + if (!isset($this->arrayUserUpdateChecked[$username])) { + $this->arrayUserUpdateChecked[$username] = 1; + $arrayUserDataUpdate = []; + $extendedData = []; - if ((is_array($username) && !empty($username)) || trim($username) != '') { - $username = trim((is_array($username)) ? $username[0] : $username); + foreach ($arrayAttributesToSync as $key => $value) { + $fieldName = $key; + $attributeName = strtolower($value); - if (isset($arrayUser[$username])) { - if (!isset($this->arrayUserUpdateChecked[$username])) { - $this->arrayUserUpdateChecked[$username] = 1; + if (isset($arrayUserLdap[$attributeName])) { + $ldapAttributeValue = trim((is_array($arrayUserLdap[$attributeName])) ? $arrayUserLdap[$attributeName][0] : $arrayUserLdap[$attributeName]); - $arrayUserDataUpdate = []; - $extendedData = []; - - 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 = (preg_match('/^(?:' . '512|544|66048|66080' . ')$/', $ldapAttributeValue)) ? (($arrayUser[$username][$fieldName] == 'VACATION') ? 'VACATION' : 'ACTIVE') : 'INACTIVE'; - } - break; - case 'USR_DUE_DATE': - if ($attributeName == 'accountexpires') { - $ldapAttributeValue = $this->convertDateADtoPM($ldapAttributeValue); - } - break; - } - - if (isset($arrayUser[$username][$fieldName])) { - if ($ldapAttributeValue != $arrayUser[$username][$fieldName]) { - $arrayUserDataUpdate[$fieldName] = $ldapAttributeValue; + switch ($fieldName) { + case 'USR_STATUS': + if ($attributeName == 'useraccountcontrol') { + $ldapAttributeValue = (preg_match('/^(?:' . '512|544|66048|66080' . ')$/', $ldapAttributeValue)) ? (($arrayUser[$username][$fieldName] == 'VACATION') ? 'VACATION' : 'ACTIVE') : 'INACTIVE'; } - } else { - $extendedData[$fieldName] = $ldapAttributeValue; + break; + case 'USR_DUE_DATE': + if ($attributeName == 'accountexpires') { + $ldapAttributeValue = $this->convertDateADtoPM($ldapAttributeValue); + } + break; + } + + if (isset($arrayUser[$username][$fieldName])) { + if ($ldapAttributeValue != $arrayUser[$username][$fieldName]) { + $arrayUserDataUpdate[$fieldName] = $ldapAttributeValue; } + } else { + $extendedData[$fieldName] = $ldapAttributeValue; } } - - //update the extended data - if (!empty($extendedData)) { - $json = $arrayUser[$username]['USR_EXTENDED_ATTRIBUTES_DATA']; - $oldExtendedData = empty($json) ? [] : json_decode($json, true); - $extendedData = array_merge($oldExtendedData, $extendedData); - $arrayUserDataUpdate['USR_EXTENDED_ATTRIBUTES_DATA'] = json_encode($extendedData); - } - - if (!empty($arrayUserDataUpdate)) { - $arrayUserDataUpdate['USR_UID'] = $arrayUser[$username]['USR_UID']; - - //Update User data - $rbac->updateUser($arrayUserDataUpdate); - - $user = new Users(); - $result = $user->update($arrayUserDataUpdate); - } - } else { - $this->log( - $ldapcnn, - 'User is repeated: Username "' . $username . '", DN "' . $arrayUserLdap['dn'] . '"' - ); } - $flagUser = true; + // Update the extended data + if (!empty($extendedData)) { + $json = $arrayUser[$username]['USR_EXTENDED_ATTRIBUTES_DATA']; + $oldExtendedData = empty($json) ? [] : json_decode($json, true); + $extendedData = array_merge($oldExtendedData, $extendedData); + $arrayUserDataUpdate['USR_EXTENDED_ATTRIBUTES_DATA'] = json_encode($extendedData); + } + // Update the user information + if (!empty($arrayUserDataUpdate)) { + $arrayUserDataUpdate['USR_UID'] = $arrayUser[$username]['USR_UID']; + // Update User data + $rbac->updateUser($arrayUserDataUpdate); + $user = new Users(); + $result = $user->update($arrayUserDataUpdate); + } + // Remove the user from the array + unset($this->allListOfUsers[$username]); + } else { + $this->log( + $ldapcnn, + 'User is repeated: Username "' . $username . '", DN "' . $arrayUserLdap['dn'] . '"' + ); } + + $flagUser = true; } } } - //Return + // Return return $flagUser; } catch (Exception $e) { throw $e; @@ -3109,23 +3016,24 @@ class LdapAdvanced /** * Update Users data based on the LDAP Server * - * @param resource $ldapcnn LDAP link identifier + * @param LDAP\Connection $ldapcnn LDAP link identifier * @param array $arrayAuthSourceData Authentication Source Data * @param string $filterUsers Filter - * @param array $arrayUserUid UID of Users - * @param array $arrayData Data + * @param array $listUids UID of Users + * @param array $countResult Data * * @return array */ - private function ldapUsersUpdateData($ldapcnn, array $arrayAuthSourceData, $filterUsers, array $arrayUserUid, array $arrayData) + private function ldapUsersUpdateData($ldapcnn, array $arrayAuthSourceData, $filterUsers, array $listUids, array $countResult) { try { - $totalUser = $arrayData['totalUser']; - $countUser = $arrayData['countUser']; + $totalUser = $countResult['totalUser']; + $countUserUpdated = $countResult['countUserUpdated']; + $countUserDeleted = $countResult['countUserDeleted']; - //Search Users + // Define the filter to search all users $filter = '(&(' . $this->arrayObjectClassFilter['user'] . ')(|' . $filterUsers . '))'; - + // Search all the users $searchResult = @ldap_search($ldapcnn, $arrayAuthSourceData['AUTH_SOURCE_BASE_DN'], $filter, $this->arrayAttributesForUser); $context = [ "baseDN" => $arrayAuthSourceData['AUTH_SOURCE_BASE_DN'], @@ -3136,51 +3044,56 @@ class LdapAdvanced if ($error = ldap_errno($ldapcnn)) { // - } else { - if ($searchResult && ldap_count_entries($ldapcnn, $searchResult) > 0) { - $this->stdLog($ldapcnn, "ldap_count_entries"); - //Get Users from DB - $arrayUser = []; + } elseif ($searchResult && ldap_count_entries($ldapcnn, $searchResult) > 0) { // Check if at least one user was found + $this->stdLog($ldapcnn, "ldap_count_entries"); + // Get Users from DB + $arrayUser = []; - $criteria = new Criteria('workflow'); + $criteria = new Criteria('workflow'); + $criteria->add(UsersPeer::USR_UID, $listUids, Criteria::IN); + $criteria->add(UsersPeer::USR_STATUS, 'CLOSED', Criteria::NOT_EQUAL); + $rsCriteria = UsersPeer::doSelectRS($criteria); + $rsCriteria->setFetchmode(ResultSet::FETCHMODE_ASSOC); - $criteria->add(UsersPeer::USR_UID, $arrayUserUid, Criteria::IN); - $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); - $this->stdLog($ldapcnn, "ldap_first_entry"); - - do { - if ($this->ldapUserUpdateByDnAndData( - $ldapcnn, - $arrayAuthSourceData, - ldap_get_dn($ldapcnn, $entry), - $arrayUser - ) - ) { - $countUser++; - - //Progress bar - $this->frontEndShow( - 'BAR', - 'Update Users data: ' . $countUser . '/' . $totalUser . ' ' . $this->progressBar($totalUser, $countUser) - ); - } - } while ($entry = ldap_next_entry($ldapcnn, $entry)); + while ($rsCriteria->next()) { + $row = $rsCriteria->getRow(); + $arrayUser[$row['USR_USERNAME']] = $row; } + + // Get Users from LDAP Server + $entry = ldap_first_entry($ldapcnn, $searchResult); + $this->stdLog($ldapcnn, "ldap_first_entry"); + // Save all the list of users + $this->allListOfUsers = $arrayUser; + // Check all the ldap entry found + do { + if ($this->ldapUserUpdateByDnAndData($ldapcnn, $arrayAuthSourceData, ldap_get_dn($ldapcnn, $entry), $arrayUser)) { + $countUserUpdated++; + // Progress bar + $this->frontEndShow( + 'BAR', + 'Update Users data: ' . $countUserUpdated . '/' . $totalUser . ' ' . $this->progressBar($totalUser, $countUserUpdated) + ); + } + } while ($entry = ldap_next_entry($ldapcnn, $entry)); + $countUserDeleted = count($this->allListOfUsers); + // List of users to delete + foreach ($this->allListOfUsers as $index => $usr) { + $user = new User(); + $user->deleteGdpr($usr['USR_UID']); + } + // Register the users deleted + $this->stdLog($ldapcnn, "deleteUsersGdpr", $this->allListOfUsers); + } else { // If no user found, we supposed that all are deleted + foreach ($listUids as $usr) { + $user = new User(); + $user->deleteGdpr($usr); + } + // Register the users deleted + $this->stdLog($ldapcnn, "deleteAllUsersGdpr", $listUids); } - return [$totalUser, $countUser]; + return [$totalUser, $countUserUpdated, $countUserDeleted]; } catch (Exception $e) { throw $e; } @@ -3191,69 +3104,64 @@ class LdapAdvanced * * @param string $authenticationSourceUid UID of Authentication Source * - * return void + * @return array */ public function usersUpdateData($authenticationSourceUid) { try { $totalUser = count($this->arrayAuthenticationSourceUsersByUid); - $countUser = 0; + $countUserUpdate = 0; + $countUserDelete = 0; - //Set variables + // 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 + // Update Users $limit = $this->getPageSizeLimitByData($arrayAuthenticationSourceData); $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; - + $arrayUserUid = []; + foreach ($this->arrayAuthenticationSourceUsersByUid as $arrayUserData) { $count++; - $filterUsers .= "($uidUserIdentifier=" . $arrayUserData["USR_USERNAME"] . ")"; $arrayUserUid[] = $arrayUserData["USR_UID"]; if ($count == $limit) { - list($totalUser, $countUser) = $this->ldapUsersUpdateData( + list($totalUser, $countUserUpdate, $countUserDelete) = $this->ldapUsersUpdateData( $ldapcnn, $arrayAuthenticationSourceData, $filterUsers, $arrayUserUid, - ['totalUser' => $totalUser, 'countUser' => $countUser] + ['totalUser' => $totalUser, 'countUserUpdated' => $countUserUpdate, 'countUserDeleted' => $countUserDelete] ); $count = 0; - $filterUsers = ""; - $arrayUserUid = array(); + $arrayUserUid = []; } } if ($count > 0) { - list($totalUser, $countUser) = $this->ldapUsersUpdateData( + list($totalUser, $countUserUpdate, $countUserDelete) = $this->ldapUsersUpdateData( $ldapcnn, $arrayAuthenticationSourceData, $filterUsers, $arrayUserUid, - ['totalUser' => $totalUser, 'countUser' => $countUser] + ['totalUser' => $totalUser, 'countUserUpdated' => $countUserUpdate, 'countUserDeleted' => $countUserDelete] ); } + + return ['totalUser' => $totalUser, 'countUserUpdated' => $countUserUpdate, 'countUserDeleted' => $countUserDelete]; } catch (Exception $e) { throw $e; } @@ -3278,7 +3186,7 @@ class LdapAdvanced /** * Get page size limit for a search result * - * @param resource $ldapcnn LDAP link identifier + * @param LDAP\Connection $ldapcnn LDAP link identifier * @param string $baseDn The base DN for the directory * * @return int Returns the page size limit for a search result @@ -3317,7 +3225,7 @@ class LdapAdvanced /** * Standard log - * @param resource $link + * @param LDAP\Connection $link * @param string $message * @param array $context * @param string $level @@ -3345,5 +3253,4 @@ class LdapAdvanced Log::channel(':ldapAdvanced')->error($message, Bootstrap::context($context)); } } - } diff --git a/workflow/engine/methods/services/ldapadvanced.php b/workflow/engine/methods/services/ldapadvanced.php index fea43a878..0785bea3e 100644 --- a/workflow/engine/methods/services/ldapadvanced.php +++ b/workflow/engine/methods/services/ldapadvanced.php @@ -29,9 +29,10 @@ class ldapadvancedClassCron public $gCreatedUsers = ""; public $gRemovedUsers = ""; - public $managersHierarchy = array(); - public $oldManagersHierarchy = array(); - public $managersToClear = array(); + public $usersRemovedOu = []; + public $managersHierarchy = []; + public $oldManagersHierarchy = []; + public $managersToClear = []; public $deletedManager = 0; public function __construct() @@ -39,9 +40,9 @@ class ldapadvancedClassCron } /** - function executed by the cron - this function will synchronize users from ldap/active directory to PM users tables - @return void + * function executed by the cron + * this function will synchronize users from ldap/active directory to PM users tables + * @return void */ public function executeCron($debug) { @@ -64,7 +65,6 @@ class ldapadvancedClassCron $aGroups = $plugin->getGroups(); $plugin->frontEndShow("START"); - $plugin->debugLog("START"); $plugin->stdLog(null, "cron execution started"); @@ -77,45 +77,37 @@ class ldapadvancedClassCron $plugin->sAuthSource = $arrayAuthenticationSourceData["AUTH_SOURCE_UID"]; $plugin->ldapcnn = null; - $plugin->setArrayDepartmentUserSynchronizedChecked(array()); - $plugin->setArrayUserUpdateChecked(array()); + $plugin->setArrayDepartmentUserSynchronizedChecked([]); + $plugin->setArrayUserUpdateChecked([]); - //Get all User (USR_UID, USR_USERNAME, USR_AUTH_USER_DN) registered in RBAC with this Authentication Source + // 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 - + // Set some logs to show $plugin->frontEndShow("TEXT", "Authentication Source: " . $arrayAuthenticationSourceData["AUTH_SOURCE_NAME"]); - $plugin->log(null, "Executing cron for Authentication Source: " . $arrayAuthenticationSourceData["AUTH_SOURCE_NAME"]); - $context = [ - "AUTH_SOURCE_NAME" => $arrayAuthenticationSourceData["AUTH_SOURCE_NAME"] - ]; - $plugin->stdLog(null, "authentication source", $context); + $plugin->stdLog(null, "authentication source", ["AUTH_SOURCE_NAME" => $arrayAuthenticationSourceData["AUTH_SOURCE_NAME"]]); - //Get all departments from Ldap/ActiveDirectory and build a hierarchy using dn (ou->ou parent) + // 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 + // Obtain all departments from PM with a valid department in LDAP/ActiveDirectory $aRegisteredDepts = $plugin->getRegisteredDepartments($aLdapDepts, $aDepartments); - + // Set some logs to show $plugin->debugLog("ldapadvanced.php > function executeCron() > foreach > \$aRegisteredDepts ---->\n" . print_r($aRegisteredDepts, true)); $plugin->stdLog(null, "RegisteredDepartments", ["result" => $aRegisteredDepts]); - - //Get all group from Ldap/ActiveDirectory + // Get all group from Ldap/ActiveDirectory $aLdapGroups = $plugin->searchGroups(); - - //Obtain all groups from PM with a valid group in LDAP/ActiveDirectory + // Obtain all groups from PM with a valid group in LDAP/ActiveDirectory $aRegisteredGroups = $plugin->getRegisteredGroups($aLdapGroups, $aGroups); - + // Set some logs to show $plugin->debugLog("ldapadvanced.php > function executeCron() > foreach > \$aRegisteredGroups ---->\n" . print_r($aRegisteredGroups, true)); $plugin->stdLog(null, "RegisteredGroups", ["result" => $aRegisteredGroups]); - - //Get all users from Removed OU + // Get all users from Removed OU $this->usersRemovedOu = $plugin->getUsersFromRemovedOu($arrayAuthenticationSourceData); - //Variables + // Variables $this->deletedRemoved = count($this->usersRemovedOu); $this->deletedRemovedUsers = ""; - + // Variables related to the department $this->dAlready = 0; $this->dMoved = 0; $this->dImpossible = 0; @@ -126,7 +118,7 @@ class ldapadvancedClassCron $this->dImpossibleUsers = ""; $this->dCreatedUsers = ""; $this->dRemovedUsers = ""; - + // Variables related to the group $this->gAlready = 0; $this->gMoved = 0; $this->gImpossible = 0; @@ -161,7 +153,6 @@ class ldapadvancedClassCron ); $plugin->frontEndShow("TEXT", $logResults); - $plugin->log(null, $logResults); $context = [ "existingUsers" => $this->dAlready, @@ -171,8 +162,7 @@ class ldapadvancedClassCron "removed" => $this->dRemoved ]; $plugin->stdLog(null, "departments", $context); - - //Group - Synchronize Users + // Group - Synchronize Users $numGroups = count($aRegisteredGroups); $count = 0; @@ -184,7 +174,7 @@ class ldapadvancedClassCron $arrayAux = $this->groupSynchronizeUsers($plugin, $numGroups, $count, $registeredGroup); } - //Group - Print log + // Group - Print log $logResults = sprintf( "- Groups -> Existing users: %d, moved: %d, impossible: %d, created: %d, removed: %d", $this->gAlready, @@ -206,7 +196,7 @@ class ldapadvancedClassCron ]; $plugin->stdLog(null, "groups", $context); - //Manager + // Manager $plugin->clearManager($this->managersToClear); if (isset($arrayAuthenticationSourceData["AUTH_SOURCE_DATA"]["DEPARTMENTS_TO_UNASSIGN"])) { @@ -244,7 +234,7 @@ class ldapadvancedClassCron $dataset = UsersPeer::doSelectRS($criteria); $dataset->setFetchmode(ResultSet::FETCHMODE_ASSOC); $dataset->next(); - $users = array(); + $users = []; while ($row = $dataset->getRow()) { $users[] = $row["USR_UID"]; @@ -279,7 +269,7 @@ class ldapadvancedClassCron $dataset = RbacUsersPeer::doSelectRS($criteria); $dataset->setFetchmode(ResultSet::FETCHMODE_ASSOC); $dataset->next(); - $existingUsers = array(); + $existingUsers = []; while ($row = $dataset->getRow()) { $existingUsers[] = $row["USR_AUTH_USER_DN"]; @@ -297,9 +287,9 @@ class ldapadvancedClassCron $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(); + $deletedManagers = []; + $newManagers = []; + $movedManagers = []; if (is_array($deletedManagersAssignments)) { foreach ($deletedManagersAssignments as $dn1 => $subordinates1) { @@ -334,10 +324,9 @@ class ldapadvancedClassCron } } } - //Print and log the users's information - //Deleted/Removed Users - $logResults = sprintf("- Deleted/Removed Users: %d", $this->deletedRemoved); + //Retired/Deactivated Users + $logResults = sprintf("- Retired/Deactivated Users: %d", $this->deletedRemoved); $plugin->frontEndShow("TEXT", $logResults); @@ -345,15 +334,15 @@ class ldapadvancedClassCron $context = [ "deletedRemoved" => $this->deletedRemoved ]; - $plugin->stdLog(null, "deleted/removed users", $context); + $plugin->stdLog(null, "retired/deactivated users", $context); if ($this->deletedRemoved > 0) { - $plugin->log(null, "Deleted/Removed Users: "); + $plugin->log(null, "Retired/Deactivated Users: "); $plugin->log(null, $this->deletedRemovedUsers); $context = [ "deletedRemovedUsers" => $this->deletedRemovedUsers ]; - $plugin->stdLog(null, "deleted/removed users", $context); + $plugin->stdLog(null, "retired/deactivated users", $context); } if ($this->dAlready + $this->gAlready > 0) { @@ -424,8 +413,14 @@ class ldapadvancedClassCron ]; $plugin->stdLog(null, "managers assignments", $context); - //Update Users data based on the LDAP Server - $plugin->usersUpdateData($arrayAuthenticationSourceData["AUTH_SOURCE_UID"]); + // Update Users data based on the LDAP Server + $plugin->stdLog(null, "usersUpdateData", [$arrayAuthenticationSourceData["AUTH_SOURCE_UID"]]); + $result = $plugin->usersUpdateData($arrayAuthenticationSourceData["AUTH_SOURCE_UID"]); + $logResults = sprintf("- Deleted/Removed Users: %d", $result['countUserDeleted']); + $plugin->frontEndShow("TEXT", $logResults); + $plugin->log(null, $logResults); + // Deactive Users + $plugin->stdLog(null, "deactiveArrayOfUsers", [$this->usersRemovedOu]); $plugin->deactiveArrayOfUsers($this->usersRemovedOu); } catch (Exception $e) { $plugin = new LdapAdvanced(); @@ -468,7 +463,7 @@ class ldapadvancedClassCron } } - return (!isset($difference))? array() : $difference; + return (!isset($difference))? [] : $difference; } public function departmentRemoveUsers($departmentUid, array $arrayUserUid) @@ -534,7 +529,7 @@ class ldapadvancedClassCron $ldapAdvanced->setArrayDepartmentUsers($arrayDepartmentData["DEP_UID"]); //INITIALIZE DATA //Clear the manager assignments - $arrayUserUid = array(); + $arrayUserUid = []; foreach ($ldapAdvanced->arrayDepartmentUsersByUid as $key => $user) { $arrayUserUid[] = $user["USR_UID"]; @@ -544,7 +539,7 @@ class ldapadvancedClassCron if ($dn != "") { if (!isset($this->oldManagersHierarchy[$dn])) { - $this->oldManagersHierarchy[$dn] = array(); + $this->oldManagersHierarchy[$dn] = []; } $this->oldManagersHierarchy[$dn][$user["USR_UID"]] = $user["USR_UID"]; @@ -567,7 +562,7 @@ class ldapadvancedClassCron "createdUsers" => $this->dCreatedUsers, "managersHierarchy" => $this->managersHierarchy, - "arrayUserUid" => array(), + "arrayUserUid" => [], "n" => $numDepartments, "i" => $count @@ -624,7 +619,7 @@ class ldapadvancedClassCron $ldapAdvanced->setArrayGroupUsers($arrayGroupData["GRP_UID"]); //INITIALIZE DATA //Clear the manager assignments - $arrayUserUid = array(); + $arrayUserUid = []; foreach ($ldapAdvanced->arrayGroupUsersByUid as $key => $user) { $arrayUserUid[] = $user["USR_UID"]; @@ -634,7 +629,7 @@ class ldapadvancedClassCron if ($dn != "") { if (!isset($this->oldManagersHierarchy[$dn])) { - $this->oldManagersHierarchy[$dn] = array(); + $this->oldManagersHierarchy[$dn] = []; } $this->oldManagersHierarchy[$dn][$user["USR_UID"]] = $user["USR_UID"]; @@ -657,7 +652,7 @@ class ldapadvancedClassCron "createdUsers" => $this->gCreatedUsers, "managersHierarchy" => $this->managersHierarchy, - "arrayUserUid" => array(), + "arrayUserUid" => [], "n" => $numGroups, "i" => $count diff --git a/workflow/engine/src/ProcessMaker/BusinessModel/User.php b/workflow/engine/src/ProcessMaker/BusinessModel/User.php index 3891a3bb5..e9d64a64a 100644 --- a/workflow/engine/src/ProcessMaker/BusinessModel/User.php +++ b/workflow/engine/src/ProcessMaker/BusinessModel/User.php @@ -24,6 +24,14 @@ use ListParticipatedLast; use OauthClients; use PMmemcached; use ProcessMaker\BusinessModel\ProcessSupervisor as BmProcessSupervisor; +use ProcessMaker\Model\DashletInstance; +use ProcessMaker\Model\GroupUser; +use ProcessMaker\Model\ObjectPermission; +use ProcessMaker\Model\Process as ModelProcess; +use ProcessMaker\Model\ProcessUser as ModelProcessUser; +use ProcessMaker\Model\RbacUsers as ModelRbacUsers; +use ProcessMaker\Model\TaskUser; +use ProcessMaker\Model\User as ModelUser; use ProcessMaker\Plugins\PluginRegistry; use ProcessMaker\Util\DateTime; use ProcessMaker\Util\System; @@ -45,6 +53,7 @@ use UsersRolesPeer; class User { + const DELETE_USER = 'unknown'; private $arrayFieldDefinition = array( "USR_UID" => array( "type" => "string", @@ -1210,11 +1219,11 @@ class User * @access public * * @param array $userData - * @param string $sRolCode + * @param string $rolCode * * @return void */ - public function updateUser($userData = array(), $sRolCode = '') + public function updateUser($userData = [], $rolCode = '') { $this->userObj = new RbacUsers(); if (isset($userData['USR_STATUS'])) { @@ -1223,9 +1232,9 @@ class User } } $this->userObj->update($userData); - if ($sRolCode != '') { + if (!empty($rolCode)) { $this->removeRolesFromUser($userData['USR_UID']); - $this->assignRoleToUser($userData['USR_UID'], $sRolCode); + $this->assignRoleToUser($userData['USR_UID'], $rolCode); } } @@ -1285,7 +1294,7 @@ class User public function delete($usrUid) { try { - //Verify data + // Verify data $this->throwExceptionIfNotExistsUser($usrUid, $this->arrayFieldNameForException["usrUid"]); // Check user admin if (RBAC::isAdminUserUid($usrUid)) { @@ -1340,6 +1349,76 @@ class User } } + /** + * Delete User + * + * @param string $usrUid Unique id of User + * + * @throws Exception + */ + public function deleteGdpr($usrUid) + { + try { + // Verify data + $this->throwExceptionIfNotExistsUser($usrUid, $this->arrayFieldNameForException["usrUid"]); + // Check user admin + if (RBAC::isAdminUserUid($usrUid)) { + throw new Exception(G::LoadTranslation("ID_MSG_CANNOT_DELETE_USER", [$usrUid])); + } + // Check user guest + if (RBAC::isGuestUserUid($usrUid)) { + throw new Exception(G::LoadTranslation("ID_MSG_CANNOT_DELETE_USER", [$usrUid])); + } + // Remove the user from groups + GroupUser::where('USR_UID', $usrUid)->delete(); + // Remove the user from tasks assigment + TaskUser::where('USR_UID', $usrUid)->where('TU_RELATION', 1)->delete(); + // Remove the user from process owner and assign to admin + ModelProcess::where('PRO_CREATE_USER', $usrUid) + ->update(['PRO_CREATE_USER' => RBAC::ADMIN_USER_UID]); + // Remove the user from process permission + ObjectPermission::where('USR_UID', $usrUid)->where('OP_USER_RELATION', 1)->delete(); + // Remove the user from process supervisor + ModelProcessUser::where('USR_UID', $usrUid)->where('PU_TYPE', 'SUPERVISOR')->delete(); + // Mark the user with the deleted status + $fields = [ + 'USR_STATUS' => 'CLOSED', + 'USR_USERNAME' => '', + 'USR_FIRSTNAME' => self::DELETE_USER, + 'USR_LASTNAME' => self::DELETE_USER, + 'USR_EMAIL' => '', + 'USR_DUE_DATE' => '0000-00-00', + 'USR_CREATE_DATE' => '0000-00-00 00:00:00', + 'USR_UPDATE_DATE' => '0000-00-00 00:00:00', + ]; + ModelRbacUsers::where('USR_UID', $usrUid)->update($fields); + $fields = array_merge( + $fields, [ + 'USR_STATUS_ID' => 0, + 'USR_COUNTRY' => '', + 'USR_CITY' => '', + 'USR_LOCATION' => '', + 'USR_ADDRESS' => '', + 'USR_PHONE' => '', + 'USR_FAX' => '', + 'USR_CELLULAR' => '', + 'USR_ZIP_CODE' => '', + 'USR_BIRTHDAY' => '0000-00-00', + 'USR_TIME_ZONE' => '', + 'USR_EXTENDED_ATTRIBUTES_DATA' => '{}', + ] + ); + ModelUser::where('USR_UID', $usrUid)->update($fields); + // Delete Dashboard + DashletInstance::where('DAS_INS_OWNER_UID', $usrUid)->where('DAS_INS_OWNER_TYPE', 'USER')->delete(); + // Destroy session after delete user + RBAC::destroySessionUser($usrUid); + (new OauthClients())->removeByUser($usrUid); + } catch (Exception $e) { + throw $e; + } + } + /** * Get all Users * diff --git a/workflow/engine/src/ProcessMaker/Model/DashletInstance.php b/workflow/engine/src/ProcessMaker/Model/DashletInstance.php new file mode 100644 index 000000000..a0119361c --- /dev/null +++ b/workflow/engine/src/ProcessMaker/Model/DashletInstance.php @@ -0,0 +1,18 @@ +