Files
luos/workflow/engine/bin/tasks/cliAuthSources.php
2025-10-07 02:22:03 +00:00

882 lines
35 KiB
PHP

<?php
/**
* Command line task to sync auth sources
*/
use ProcessMaker\Model\Department;
use ProcessMaker\Core\JobsManager;
use ProcessMaker\Model\Groupwf;
use ProcessMaker\Model\RbacAuthenticationSource;
use ProcessMaker\Model\RbacUsers;
use ProcessMaker\Model\User;
use ProcessMaker\Model\GroupUser;
use Illuminate\Support\Facades\Log;
use \Department as DepartmentModel;
CLI::taskName('auth-sources-sync');
CLI::taskDescription(<<<EOT
Update plugin translations
LANG is the language, such as 'fr' (French) or 'zh-CN' (mainland Chinese).
If the language is not specified, then it is 'en' (English) by default.
EOT
);
CLI::taskArg('workspace', false);
CLI::taskRun('run_auth_sources_sync');
$GLOBALS['deletedRemoved'] = 0;
$GLOBALS['deletedRemovedUsers'] = '';
$GLOBALS['dAlready'] = 0;
$GLOBALS['dMoved'] = 0;
$GLOBALS['dImpossible'] = 0;
$GLOBALS['dCreated'] = 0;
$GLOBALS['dRemoved'] = 0;
$GLOBALS['dAlreadyUsers'] = '';
$GLOBALS['dMovedUsers'] = '';
$GLOBALS['dImpossibleUsers'] = '';
$GLOBALS['dCreatedUsers'] = '';
$GLOBALS['dRemovedUsers'] = '';
$GLOBALS['gAlready'] = 0;
$GLOBALS['gMoved'] = 0;
$GLOBALS['gImpossible'] = 0;
$GLOBALS['gCreated'] = 0;
$GLOBALS['gRemoved'] = 0;
$GLOBALS['gAlreadyUsers'] = '';
$GLOBALS['gMovedUsers'] = '';
$GLOBALS['gImpossibleUsers'] = '';
$GLOBALS['gCreatedUsers'] = '';
$GLOBALS['gRemovedUsers'] = '';
$GLOBALS['usersRemovedOu'] = [];
$GLOBALS['managersHierarchy'] = [];
$GLOBALS['oldManagersHierarchy'] = [];
$GLOBALS['managersToClear'] = [];
$GLOBALS['deletedManager'] = 0;
function run_auth_sources_sync($command, $args)
{
if (!empty($command) && count($command) >= 1) {
$workspace = $command[0];
CLI::logging("Check workspace $workspace ...\n", null, 'blue');
if (!is_dir(PATH_DB . $workspace) || !file_exists(PATH_DB . $workspace . PATH_SEP . 'db.php')) {
CLI::logging("Workspace not found ❌\n",null, 'red');
CLI::logging("Syncronization canceled 🚫\n",null, 'red');
return;
}
CLI::logging("Workspace \"$workspace\" found.......... ✅\n",null, 'green');
initWorkspace($workspace);
executeLdapCron();
/*
$language = new Language();
$language->createLanguagePlugin($command[0], $command[1]);
*/
CLI::logging("Syncronization completed 🎉🎉🎉\n", null, 'green');
} else {
CLI::logging("The command requires the workspace name\n");
}
}
function executeLdapCron()
{
$plugin = new LdapSource();
$rbac = RBAC::getSingleton();
if (is_null($rbac->authSourcesObj)) {
$rbac->authSourcesObj = new AuthenticationSource();
}
unset($GLOBALS['translation']);
$plugin->setFrontEnd(true);
$plugin->setDebug(true);
//Get all authsource for this plugin ( ldapAdvanced plugin, because other authsources are not needed )
//$arrayAuthenticationSource = $plugin->getAuthSources();
$filters = ['orderBy' => ['AUTH_SOURCE_NAME', 'ASC']];
$rbacAuthenticationSource = new RbacAuthenticationSource();
$arrayAuthenticationSource = $rbacAuthenticationSource->show($filters);
$filters = array(
'conditions' => ['DEP_STATUS' => 'ACTIVE'],
'orderBy' => ['DEP_TITLE', 'ASC']
);
$department = new Department();
$aDepartments = $department->show($filters);
$filters = array(
'conditions' => ['GRP_STATUS' => 'ACTIVE'],
'orderBy' => ['GRP_TITLE', 'ASC']
);
$groupwf = new Groupwf();
$aGroups = $groupwf->show($filters);
$plugin->frontEndShow('START');
$plugin->debugLog('START');
$plugin->stdLog(null, 'cron execution started');
foreach ($arrayAuthenticationSource['data'] ?? [] as $value) {
$arrayAuthenticationSourceData = $value;
try {
$plugin->debugLog("ldapadvanced.php > function executeCron() > foreach > \$arrayAuthenticationSourceData ---->\n" . print_r($arrayAuthenticationSourceData, true));
$plugin->stdLog(null, 'AuthenticationSourceData', ['result' => $arrayAuthenticationSourceData]);
$plugin->authSourceUid = $arrayAuthenticationSourceData['AUTH_SOURCE_UID'];
$plugin->ldapcnn = null;
$plugin->setArrayDepartmentUserSynchronizedChecked([]);
$plugin->setArrayUserUpdateChecked([]);
// 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']);
$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)
$aLdapDepts = $plugin->searchDepartments();
// Obtain all departments from PM with a valid department in LDAP/ActiveDirectory
$aRegisteredDepts = $plugin->getRegisteredDepartments($aLdapDepts, $aDepartments['data'] ?? []);
// 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
$aLdapGroups = $plugin->searchGroups();
// Obtain all groups from PM with a valid group in LDAP/ActiveDirectory
$aRegisteredGroups = $plugin->getRegisteredGroups($aLdapGroups, $aGroups['data'] ?? []);
// 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
$GLOBALS['usersRemovedOu'] = $plugin->getUsersFromRemovedOu($arrayAuthenticationSourceData);
$GLOBALS['deletedRemoved'] = count($GLOBALS['usersRemovedOu']);
//Department - Synchronize Users
$numDepartments = count($aRegisteredDepts);
$count = 0;
$plugin->debugLog("ldapadvanced.php > function executeCron() > foreach > \$numDepartments ----> $numDepartments");
$plugin->stdLog(null, 'NumberDepartments', ['result' => $numDepartments]);
foreach ($aRegisteredDepts as $registeredDept) {
$count++;
departmentSynchronizeUsers($plugin, $numDepartments, $count, $registeredDept);
}
//Department - Print log
$logResults = sprintf(
"- Departments -> Existing users: %d, moved: %d, impossible: %d, created: %d, removed: %d",
$GLOBALS['dAlready'],
$GLOBALS['dMoved'],
$GLOBALS['dImpossible'],
$GLOBALS['dCreated'],
$GLOBALS['dRemoved']
);
$plugin->frontEndShow('TEXT', $logResults);
$plugin->log(null, $logResults);
$context = [
'existingUsers' => $GLOBALS['dAlready'],
'moved' => $GLOBALS['dMoved'],
'impossible' => $GLOBALS['dImpossible'],
'created' => $GLOBALS['dCreated'],
'removed' => $GLOBALS['dRemoved']
];
$plugin->stdLog(null, 'departments', $context);
// Group - Synchronize Users
$numGroups = count($aRegisteredGroups);
$count = 0;
$plugin->debugLog("ldapadvanced.php > function executeCron() > foreach > \$numGroups ----> $numGroups");
$plugin->stdLog(null, 'NumberGroups', ['result' => $numGroups]);
foreach ($aRegisteredGroups as $registeredGroup) {
$count++;
$arrayAux = groupSynchronizeUsers($plugin, $numGroups, $count, $registeredGroup);
}
// Group - Print log
$logResults = sprintf(
"- Groups -> Existing users: %d, moved: %d, impossible: %d, created: %d, removed: %d",
$GLOBALS['gAlready'],
$GLOBALS['gMoved'],
$GLOBALS['gImpossible'],
$GLOBALS['gCreated'],
$GLOBALS['gRemoved']
);
$plugin->frontEndShow('TEXT', $logResults);
$plugin->log(null, $logResults);
$context = [
'existingUsers' => $GLOBALS['gAlready'],
'moved' => $GLOBALS['gMoved'],
'impossible' => $GLOBALS['gImpossible'],
'created' => $GLOBALS['gCreated'],
'removed' => $GLOBALS['gRemoved']
];
$plugin->stdLog(null, 'groups', $context);
// Manager
$plugin->clearManager($GLOBALS['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
$user = new User();
$GLOBALS['deletedManager'] = $user->updateData(
['USR_REPORTS_TO' => ''],
['DEP_UID' => $departmentUID, ['USR_REPORTS_TO', '!=', '']]
);
$rbacUsers = new RbacUsers();
$totalRbacUsers = $rbacUsers->show(['conditions' => ['DEP_UID' => $departmentUID]]);
$GLOBALS['dMoved'] += (int)$totalRbacUsers['total'];
$rbacUsers->updateData(
['DEP_UID' => ''],
['DEP_UID' => $departmentUID]
);
}
}
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) {
$groupUser = new GroupUser();
$dataGroupUser = $groupUser->show([
'fields' => ['USR_UID'],
'limit' => 1000,
'conditions' => ['GRP_UID' => $groupUID]
]);
$users = [];
foreach ($dataGroupUser['data'] ?? [] as $user) {
$users[] = $user['USR_UID'];
}
$user = new User();
$GLOBALS['deletedManager'] = $user->updateDataFromListUsersUids(
['USR_REPORTS_TO' => ''],
$users,
[['USR_REPORTS_TO', '!=', '']]
);
$GLOBALS['gMoved'] += $dataGroupUser['total'];
// Delete group assignments
$groupUser = new GroupUser();
$groupUser->removeGroupUser(['GRP_UID' => $groupUID]);
}
}
unset($arrayAuthenticationSourceData['AUTH_SOURCE_DATA']['GROUPS_TO_UNASSIGN']);
$rbac = RBAC::getSingleton();
$rbac->authSourcesObj->update($arrayAuthenticationSourceData);
}
$rbacUsers = new RbacUsers();
$rbacUsersData = $rbacUsers->show([
'fields' => ['USR_AUTH_USER_DN'],
'conditions' => [['USR_AUTH_USER_DN', '!=', '']]
]);
$existingUsers = [];
foreach ($rbacUsersData['data'] ?? [] as $usersData) {
$existingUsers[] = $usersData['USR_AUTH_USER_DN'];
}
foreach ($GLOBALS['managersHierarchy'] as $managerDN => $subordinates) {
if (!in_array($managerDN, $existingUsers)) {
unset($GLOBALS['managersHierarchy'][$managerDN]);
}
}
// Get the managers assigments counters
$plugin->synchronizeManagers($GLOBALS['managersHierarchy']);
$deletedManagersAssignments = array_diff_assoc_recursive($GLOBALS['oldManagersHierarchy'], $GLOBALS['managersHierarchy']);
$newManagersAssignments = array_diff_assoc_recursive($GLOBALS['managersHierarchy'], $GLOBALS['oldManagersHierarchy']);
$deletedManagers = [];
$newManagers = [];
$movedManagers = [];
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
//Retired/Deactivated Users
$logResults = sprintf("- Retired/Deactivated Users: %d", $GLOBALS['deletedRemoved']);
$plugin->frontEndShow('TEXT', $logResults);
$plugin->log(null, $logResults);
$context = [
'deletedRemoved' => $GLOBALS['deletedRemoved']
];
$plugin->stdLog(null, 'retired/deactivated users', $context);
if ($GLOBALS['deletedRemoved'] > 0) {
$plugin->log(null, 'Retired/Deactivated Users: ');
$plugin->log(null, $GLOBALS['deletedRemovedUsers']);
$context = [
'deletedRemovedUsers' => $GLOBALS['deletedRemovedUsers']
];
$plugin->stdLog(null, 'retired/deactivated users', $context);
}
if ($GLOBALS['dAlready'] + $GLOBALS['gAlready'] > 0) {
$plugin->log(null, 'Existing Users: ');
$plugin->log(null, $GLOBALS['dAlreadyUsers'] . ' ' . $GLOBALS['gAlreadyUsers']);
$context = [
'dAlreadyUsers' => $GLOBALS['dAlreadyUsers'],
'gAlreadyUsers' => $GLOBALS['gAlreadyUsers']
];
$plugin->stdLog(null, 'existing users', $context);
}
if ($GLOBALS['dMoved'] + $GLOBALS['gMoved'] > 0) {
$plugin->log(null, 'Moved Users: ');
$plugin->log(null, $GLOBALS['dMovedUsers'] . ' ' . $GLOBALS['gMovedUsers']);
$context = [
'dMovedUsers' => $GLOBALS['dMovedUsers'],
'gMovedUsers' => $GLOBALS['gMovedUsers']
];
$plugin->stdLog(null, 'moved users', $context);
}
if ($GLOBALS['dImpossible'] + $GLOBALS['gImpossible'] > 0) {
$plugin->log(null, 'Impossible Users: ');
$plugin->log(null, $GLOBALS['dImpossibleUsers'] . ' ' . $GLOBALS['gImpossibleUsers']);
$context = [
'dImpossibleUsers' => $GLOBALS['dImpossibleUsers'],
'gImpossibleUsers' => $GLOBALS['gImpossibleUsers']
];
$plugin->stdLog(null, 'impossible users', $context);
}
if ($GLOBALS['dCreated'] + $GLOBALS['gCreated'] > 0) {
$plugin->log(null, 'Created Users: ');
$plugin->log(null, $GLOBALS['dCreatedUsers'] . ' ' . $GLOBALS['gCreatedUsers']);
$context = [
'dCreatedUsers' => $GLOBALS['dCreatedUsers'],
'gCreatedUsers' => $GLOBALS['gCreatedUsers']
];
$plugin->stdLog(null, 'created users', $context);
}
if ($GLOBALS['dRemoved'] + $GLOBALS['gRemoved'] > 0) {
$plugin->log(null, 'Removed Users: ');
$plugin->log(null, $GLOBALS['dRemovedUsers'] . ' ' . $GLOBALS['gRemovedUsers']);
$context = [
'dRemovedUsers' => $GLOBALS['dRemovedUsers'],
'gRemovedUsers' => $GLOBALS['gRemovedUsers']
];
$plugin->stdLog(null, 'removed users', $context);
}
//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) + $GLOBALS['deletedManager']
);
$plugin->frontEndShow('TEXT', $logResults);
$plugin->log(null, $logResults);
$context = [
'created' => count($newManagers) - count($movedManagers),
'moved' => count($movedManagers),
'removed' => count($deletedManagers) - count($movedManagers) + $GLOBALS['deletedManager']
];
$plugin->stdLog(null, 'managers assignments', $context);
// 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', [$GLOBALS['usersRemovedOu']]);
$plugin->deactiveArrayOfUsers($GLOBALS['usersRemovedOu']);
} catch (Exception $e) {
$plugin = new LdapSource();
$message = $e->getMessage();
$context = [
'action' => 'ldapSynchronize',
'authSource' => $arrayAuthenticationSourceData
];
$plugin->stdLog(null, $message, $context, 'error');
Log::channel(':ldapSynchronize')->error($message, Bootstrap::context($context));
}
}
$plugin->frontEndShow('END');
$plugin->debugLog('END');
$plugin->stdLog(null, 'cron execution finalized');
}
function departmentSynchronizeUsers($ldapAdvanced, $numDepartments, $count, array $arrayDepartmentData)
{
$plugin = new LdapSource();
try {
$ldapAdvanced->debugLog("ldapadvanced.php > function departmentSynchronizeUsers() > START");
$ldapAdvanced->debugLog("ldapadvanced.php > function departmentSynchronizeUsers() > \$arrayDepartmentData ---->\n" . print_r($arrayDepartmentData, true));
$plugin->stdLog(null, 'department synchronize users started', ['result' => $arrayDepartmentData]);
//Get users from ProcessMaker tables (for this Department)
$ldapAdvanced->setArrayDepartmentUsers($arrayDepartmentData['DEP_UID']); //INITIALIZE DATA
//Clear the manager assignments
$arrayUserUid = [];
foreach ($ldapAdvanced->arrayDepartmentUsersByUid as $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($GLOBALS['oldManagersHierarchy'][$dn])) {
$GLOBALS['oldManagersHierarchy'][$dn] = [];
}
$GLOBALS['oldManagersHierarchy'][$dn][$user['USR_UID']] = $user['USR_UID'];
}
}
}
$GLOBALS['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' => $GLOBALS['dAlready'],
'moved' => $GLOBALS['dMoved'],
'impossible' => $GLOBALS['dImpossible'],
'created' => $GLOBALS['dCreated'],
'alreadyUsers' => $GLOBALS['dAlreadyUsers'],
'movedUsers' => $GLOBALS['dMovedUsers'],
'impossibleUsers' => $GLOBALS['dImpossibleUsers'],
'createdUsers' => $GLOBALS['dCreatedUsers'],
'managersHierarchy' => $GLOBALS['managersHierarchy'],
'arrayUserUid' => [],
'n' => $numDepartments,
'i' => $count
);
//Get Users from LDAP (for this Department)
$arrayData = $ldapAdvanced->ldapGetUsersFromDepartment('SYNCHRONIZE', $arrayDepartmentData['DEP_LDAP_DN'], $arrayData);
$GLOBALS['dAlready'] = $arrayData['already'];
$GLOBALS['dMoved'] = $arrayData['moved'];
$GLOBALS['dImpossible'] = $arrayData['impossible'];
$GLOBALS['dCreated'] = $arrayData['created'];
$GLOBALS['dAlreadyUsers'] = $arrayData['alreadyUsers'];
$GLOBALS['dMovedUsers'] = $arrayData['movedUsers'];
$GLOBALS['dImpossibleUsers'] = $arrayData['impossibleUsers'];
$GLOBALS['dCreatedUsers'] = $arrayData['createdUsers'];
$GLOBALS['managersHierarchy'] = $arrayData['managersHierarchy'];
$arrayUserUid = $arrayData['arrayUserUid'];
//(D) Update Users
$arrayAux = array_diff(array_keys($ldapAdvanced->arrayDepartmentUsersByUid), $arrayUserUid);
departmentRemoveUsers($arrayDepartmentData['DEP_UID'], $arrayAux);
$GLOBALS['dRemoved'] += count($arrayAux);
$GLOBALS['dRemovedUsers'] = '';
$ldapAdvanced->debugLog("ldapadvanced.php > function departmentSynchronizeUsers() > END");
$plugin->stdLog(null, 'department synchronize users finalized');
//Return all UID of Users synchronized in the Department (Return all UID of Users of this Department)
return $arrayUserUid;
} catch (Exception $e) {
$plugin = new LdapSource();
$message = $e->getMessage();
$context = [
'trace' => $e->getTrace()
];
$plugin->stdLog(null, $message, $context, 'error');
throw $e;
}
}
function groupSynchronizeUsers($ldapAdvanced, $numGroups, $count, array $arrayGroupData)
{
$plugin = new LdapSource();
try {
$ldapAdvanced->debugLog("ldapadvanced.php > function groupSynchronizeUsers() > START");
$ldapAdvanced->debugLog("ldapadvanced.php > function groupSynchronizeUsers() > \$arrayGroupData ---->\n" . print_r($arrayGroupData, true));
$plugin->stdLog(null, 'group synchronize users started', ['result' => $arrayGroupData]);
//Get users from ProcessMaker tables (for this Group)
$ldapAdvanced->setArrayGroupUsers($arrayGroupData['GRP_UID']); //INITIALIZE DATA
//Clear the manager assignments
$arrayUserUid = [];
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($GLOBALS['oldManagersHierarchy'][$dn])) {
$GLOBALS['oldManagersHierarchy'][$dn] = [];
}
$GLOBALS['oldManagersHierarchy'][$dn][$user['USR_UID']] = $user['USR_UID'];
}
}
}
$GLOBALS['managersToClear'] = array_merge($GLOBALS['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' => $GLOBALS['gAlready'],
'moved' => $GLOBALS['gMoved'],
'impossible' => $GLOBALS['gImpossible'],
'created' => $GLOBALS['gCreated'],
'alreadyUsers' => $GLOBALS['gAlreadyUsers'],
'movedUsers' => $GLOBALS['gMovedUsers'],
'impossibleUsers' => $GLOBALS['gImpossibleUsers'],
'createdUsers' => $GLOBALS['gCreatedUsers'],
'managersHierarchy' => $GLOBALS['managersHierarchy'],
'arrayUserUid' => [],
'n' => $numGroups,
'i' => $count
);
//Get Users from LDAP (for this Group)
$arrayData = $ldapAdvanced->ldapGetUsersFromGroup('SYNCHRONIZE', $arrayGroupData, $arrayData);
$GLOBALS['gAlready'] = $arrayData['already'];
$GLOBALS['gMoved'] = $arrayData['moved'];
$GLOBALS['gImpossible'] = $arrayData['impossible'];
$GLOBALS['gCreated'] = $arrayData['created'];
$GLOBALS['gAlreadyUsers'] = $arrayData['alreadyUsers'];
$GLOBALS['gMovedUsers'] = $arrayData['movedUsers'];
$GLOBALS['gImpossibleUsers'] = $arrayData['impossibleUsers'];
$GLOBALS['gCreatedUsers'] = $arrayData['createdUsers'];
$GLOBALS['managersHierarchy'] = $arrayData['managersHierarchy'];
$arrayUserUid = $arrayData['arrayUserUid'];
//(G) Update Users
$arrayAux = array_diff(array_keys($ldapAdvanced->arrayGroupUsersByUid), $arrayUserUid);
groupRemoveUsers($arrayGroupData['GRP_UID'], $arrayAux);
$GLOBALS['gRemoved'] += count($arrayAux);
$GLOBALS['gRemovedUsers'] = '';
$ldapAdvanced->debugLog("ldapadvanced.php > function groupSynchronizeUsers() > END");
$plugin->stdLog(null, 'group synchronize users finalized');
//Return all UID of Users synchronized in the Group (Return all UID of Users of this Group)
return $arrayUserUid;
} catch (Exception $e) {
$plugin = new LdapSource();
$message = $e->getMessage();
$context = [
'trace' => $e->getTrace()
];
$plugin->stdLog(null, $message, $context, 'error');
throw $e;
}
}
function departmentRemoveUsers($departmentUid, array $arrayUserUid)
{
try {
$department = new DepartmentModel();
$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) {
$plugin = new LdapSource();
$message = $e->getMessage();
$context = [
'trace' => $e->getTrace()
];
$plugin->stdLog(null, $message, $context, 'error');
throw $e;
}
}
function groupRemoveUsers($groupUid, array $arrayUserUid)
{
try {
$group = new Groups();
foreach ($arrayUserUid as $value) {
$userUid = $value;
$group->removeUserOfGroup($groupUid, $userUid);
}
} catch (Exception $e) {
$plugin = new LdapSource();
$message = $e->getMessage();
$context = [
'trace' => $e->getTrace()
];
$plugin->stdLog(null, $message, $context, 'error');
throw $e;
}
}
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 = 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))? [] : $difference;
}
function initWorkspace($workspace) {
define('SYS_SYS', $workspace);
config(["system.workspace" => $workspace]);
define('URL_KEY', config('app.key'));
//PM Paths DATA
define('PATH_DATA_SITE', PATH_DATA . 'sites/' . config("system.workspace") . '/');
define('PATH_DOCUMENT', PATH_DATA_SITE . 'files/');
define('PATH_DATA_MAILTEMPLATES', PATH_DATA_SITE . 'mailTemplates/');
define('PATH_DATA_PUBLIC', PATH_DATA_SITE . 'public/');
define('PATH_DATA_REPORTS', PATH_DATA_SITE . 'reports/');
define('PATH_DYNAFORM', PATH_DATA_SITE . 'xmlForms/');
define('PATH_IMAGES_ENVIRONMENT_FILES', PATH_DATA_SITE . 'usersFiles' . PATH_SEP);
define('PATH_IMAGES_ENVIRONMENT_USERS', PATH_DATA_SITE . 'usersPhotographies' . PATH_SEP);
if (is_file(PATH_DATA_SITE . PATH_SEP . '.server_info')) {
$SERVER_INFO = file_get_contents(PATH_DATA_SITE . PATH_SEP . '.server_info');
$SERVER_INFO = unserialize($SERVER_INFO);
define('SERVER_NAME', $SERVER_INFO['SERVER_NAME']);
define('SERVER_PORT', $SERVER_INFO['SERVER_PORT']);
//to do improvement G::is_https()
if ((isset($SERVER_INFO['HTTPS']) && $SERVER_INFO['HTTPS'] == 'on') ||
(isset($SERVER_INFO['HTTP_X_FORWARDED_PROTO']) && $SERVER_INFO['HTTP_X_FORWARDED_PROTO'] == 'https')) {
define('REQUEST_SCHEME', 'https');
} else {
define('REQUEST_SCHEME', $SERVER_INFO['REQUEST_SCHEME']);
}
} else {
CLI::logging('WARNING! No server info found!', 'red');
}
//load Processmaker translations
Bootstrap::LoadTranslationObject(SYS_LANG);
//DB
$phpCode = '';
$fileDb = fopen(PATH_DB . $workspace . PATH_SEP . 'db.php', 'r');
if ($fileDb) {
while (!feof($fileDb)) {
$buffer = fgets($fileDb, 4096); //Read a line
$phpCode .= preg_replace('/define\s*\(\s*[\x22\x27](.*)[\x22\x27]\s*,\s*(\x22.*\x22|\x27.*\x27)\s*\)\s*;/i', '$$1 = $2;', $buffer);
}
fclose($fileDb);
}
$phpCode = str_replace(['<?php', '<?', '?>'], ['', '', ''], $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':
break;
default:
break;
}
$pro = [];
$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;
Propel::initConfiguration($pro);
/**
* Load Laravel database connection
*/
$dbHost = explode(':', $DB_HOST);
config(['database.connections.workflow.host' => $dbHost[0]]);
config(['database.connections.workflow.database' => $DB_NAME]);
config(['database.connections.workflow.username' => $DB_USER]);
config(['database.connections.workflow.password' => $DB_PASS]);
if (count($dbHost) > 1) {
config(['database.connections.workflow.port' => $dbHost[1]]);
}
//Enable RBAC, We need to keep both variables in upper and lower case.
$rbac = $RBAC = RBAC::getSingleton(PATH_DATA, session_id());
$rbac->sSystem = 'PROCESSMAKER';
if (!defined('DB_ADAPTER')) {
define('DB_ADAPTER', $DB_ADAPTER);
}
if (!defined('DB_HOST')) {
define('DB_HOST', $DB_HOST);
}
if (!defined('DB_NAME')) {
define('DB_NAME', $DB_NAME);
}
if (!defined('DB_USER')) {
define('DB_USER', $DB_USER);
}
if (!defined('DB_PASS')) {
define('DB_PASS', $DB_PASS);
}
if (!defined('DB_RBAC_HOST')) {
define('DB_RBAC_HOST', $DB_RBAC_HOST);
}
if (!defined('DB_RBAC_NAME')) {
define('DB_RBAC_NAME', $DB_RBAC_NAME);
}
if (!defined('DB_RBAC_USER')) {
define('DB_RBAC_USER', $DB_RBAC_USER);
}
if (!defined('DB_RBAC_PASS')) {
define('DB_RBAC_PASS', $DB_RBAC_PASS);
}
if (!defined('DB_REPORT_HOST')) {
define('DB_REPORT_HOST', $DB_REPORT_HOST);
}
if (!defined('DB_REPORT_NAME')) {
define('DB_REPORT_NAME', $DB_REPORT_NAME);
}
if (!defined('DB_REPORT_USER')) {
define('DB_REPORT_USER', $DB_REPORT_USER);
}
if (!defined('DB_REPORT_PASS')) {
define('DB_REPORT_PASS', $DB_REPORT_PASS);
}
if (!defined('SYS_SKIN')) {
define('SYS_SKIN', $arraySystemConfiguration['default_skin']);
}
$dateSystem = date('Y-m-d H:i:s');
if (empty($now)) {
$now = $dateSystem;
}
//Processing
CLI::logging('Processing workspace: ' . $workspace, null, 'green');
/**
* JobsManager
*/
JobsManager::getSingleton()->init();
}