diff --git a/classes/administration/AdminScriptPageGUI.php b/classes/administration/AdminScriptPageGUI.php index f31b175..9e74300 100644 --- a/classes/administration/AdminScriptPageGUI.php +++ b/classes/administration/AdminScriptPageGUI.php @@ -53,10 +53,9 @@ public function __construct(\ilEventoImportPlugin $plugin_object, \ilGlobalPageT $this->user = $user; $this->error = $error; + $this->ref_id = 31; if (isset($query_params['ref_id'])) { $this->ref_id = (int) $query_params['ref_id']; - } else { - $this->ref_id = 31; } $this->scripts = [ @@ -126,7 +125,7 @@ public function executeCommandAndRenderGUI() $f->legacy($script->getParameterFormUI()->getHTML()) ); - if(!is_null($executed_script) && $script->getScriptId() == $executed_script) { + if (!is_null($executed_script) && $script->getScriptId() == $executed_script) { try { $modal = $script->getResultModalFromRequest( $this->ctrl->getCmd(), diff --git a/classes/administration/EventLocationsAdminGUI.php b/classes/administration/EventLocationsAdminGUI.php index bdfdf78..d468aa8 100644 --- a/classes/administration/EventLocationsAdminGUI.php +++ b/classes/administration/EventLocationsAdminGUI.php @@ -3,6 +3,7 @@ namespace EventoImport\administration; use EventoImport\config\locations\EventLocationsRepository; +use EventoImport\config\locations\BaseLocationConfiguration; use ILIAS\DI\UIServices; class EventLocationsAdminGUI @@ -29,7 +30,7 @@ public function getEventLocationsPanelHTML() : string $ui_components = []; // Show Location settings from the cron-job - $json_settings = $this->settings->get('crevento_location_settings'); + $json_settings = $this->settings->get(BaseLocationConfiguration::CONF_LOCATIONS); $locations_settings = $json_settings ? json_decode($json_settings, true) : []; if (!is_array($locations_settings)) { $locations_settings = []; diff --git a/classes/administration/EventLocationsBuilder.php b/classes/administration/EventLocationsBuilder.php index cc367fe..aee9738 100644 --- a/classes/administration/EventLocationsBuilder.php +++ b/classes/administration/EventLocationsBuilder.php @@ -18,7 +18,7 @@ public function __construct(EventLocationsRepository $locations_repository, \ilT $this->hard_coded_department_mapping = [ "Hochschule Luzern" => "HSLU", - "Design & Kunst" => "DK", + "Design Film Kunst" => "DK", "Informatik" => "I", "Musik" => "M", "Soziale Arbeit" => "SA", @@ -47,13 +47,15 @@ public function buildCategoryObjectsForConfiguredKinds(array $locations_settings foreach ($locations_settings['departments'] as $department) { $department_ref_id = $this->fetchRefIdForObjTitle($repository_root_ref_id, $department); - if ($department_ref_id) { - foreach ($locations_settings['kinds'] as $kind) { - $kind_ref_id = $this->fetchRefIdForObjTitle($department_ref_id, $kind); - if (is_null($kind_ref_id)) { - $this->createCategoryObject($department_ref_id, $kind); - $newly_created_locations[] = strip_tags("$department/$kind"); - } + if ($department_ref_id === null) { + continue; + } + + foreach ($locations_settings['kinds'] as $kind) { + $kind_ref_id = $this->fetchRefIdForObjTitle($department_ref_id, $kind); + if (is_null($kind_ref_id)) { + $this->createCategoryObject($department_ref_id, $kind); + $newly_created_locations[] = strip_tags("$department/$kind"); } } } @@ -68,16 +70,16 @@ public function getListOfMissingKindCategories(array $locations_settings) : arra $missing_locations = []; foreach ($locations_settings['departments'] as $department) { $department_ref_id = $this->fetchRefIdForObjTitle($repository_root_ref_id, $department); - if (!is_null($department_ref_id)) { - foreach ($locations_settings['kinds'] as $kind) { - $kind_ref_id = $this->fetchRefIdForObjTitle($department_ref_id, $kind); - if (is_null($kind_ref_id)) { - $missing_locations[] = strip_tags("/$department/$kind/*"); - } - } - } else { + if (is_null($department_ref_id)) { $missing_locations[] = strip_tags("/$department/*"); } + + foreach ($locations_settings['kinds'] as $kind) { + $kind_ref_id = $this->fetchRefIdForObjTitle($department_ref_id, $kind); + if (is_null($kind_ref_id)) { + $missing_locations[] = strip_tags("/$department/$kind/*"); + } + } } return $missing_locations; @@ -104,7 +106,6 @@ private function createCategoryObject(int $parent_ref_id, string $category_title $new_category->setPermissions($parent_ref_id); // default: sort by title - include_once('Services/Container/classes/class.ilContainerSortingSettings.php'); $settings = new \ilContainerSortingSettings($new_category->getId()); $settings->setSortMode(\ilContainer::SORT_TITLE); $settings->save(); @@ -112,7 +113,6 @@ private function createCategoryObject(int $parent_ref_id, string $category_title try { // inherit parents content style, if not individual $parent_id = \ilObject::_lookupObjId($parent_ref_id); - include_once("./Services/Style/Content/classes/class.ilObjStyleSheet.php"); $style_id = \ilObjStyleSheet::lookupObjectStyle($parent_id); if ($style_id > 0) { if (\ilObjStyleSheet::_lookupStandard($style_id)) { @@ -129,7 +129,7 @@ private function fetchRefIdForObjTitle(int $root_ref_id, string $searched_obj_ti { foreach ($this->tree->getChildsByType($root_ref_id, 'cat') as $child_node) { $child_ref = $child_node['child']; - $obj_id = \ilObject::_lookupObjectId($child_ref); + $obj_id = \ilObject::_lookupObjectId((int) $child_ref); if (\ilObject::_lookupTitle($obj_id) == $searched_obj_title) { return (int) $child_ref; } @@ -152,20 +152,24 @@ private function fillRepositoryLocationsTable(array $locations_settings) : void $repository_root_ref_id = 1; foreach ($locations_settings['departments'] as $department) { $department_ref_id = $this->fetchRefIdForObjTitle($repository_root_ref_id, $department); - if ($department_ref_id) { - foreach ($locations_settings['kinds'] as $kind) { - $kind_ref_id = $this->fetchRefIdForObjTitle($department_ref_id, $kind); - if ($kind_ref_id) { - foreach ($this->tree->getChildsByType($kind_ref_id, 'cat') as $child_node) { - if ($this->isPossibleYearCategory($child_node)) { - $this->locations_repository->addNewLocation( - $this->getMappedDepartmentName($department), - $kind, - (int) $child_node['title'], - (int) $child_node['ref_id'] - ); - } - } + if ($department_ref_id === null) { + continue; + } + + foreach ($locations_settings['kinds'] as $kind) { + $kind_ref_id = $this->fetchRefIdForObjTitle($department_ref_id, $kind); + if ($kind_ref_id === null) { + continue; + } + + foreach ($this->tree->getChildsByType($kind_ref_id, 'cat') as $child_node) { + if ($this->isPossibleYearCategory($child_node)) { + $this->locations_repository->addNewLocation( + $this->getMappedDepartmentName($department), + $kind, + (int) $child_node['title'], + (int) $child_node['ref_id'] + ); } } } diff --git a/classes/administration/EventoImportApiTester.php b/classes/administration/EventoImportApiTester.php index 204cb2f..ff32078 100644 --- a/classes/administration/EventoImportApiTester.php +++ b/classes/administration/EventoImportApiTester.php @@ -39,38 +39,40 @@ public function fetchDataRecord(string $cmd, int $id) : ?ApiDataModelBase $api_importer_settings->getMaxRetries() ); return $importer->fetchUserDataRecordById($id); - } else { - if ($cmd == 'event') { - $importer = new EventoEventImporter( - $request_client, - $iterator, - $logger, - $api_importer_settings->getTimeoutAfterRequest(), - $api_importer_settings->getMaxRetries() - ); - return $importer->fetchEventDataRecordById($id); - } else { - if ($cmd == 'photo') { - $importer = new EventoUserPhotoImporter( - $request_client, - $api_importer_settings->getTimeoutAfterRequest(), - $api_importer_settings->getMaxRetries(), - $logger - ); - return $importer->fetchUserPhotoDataById($id); - } else { - if ($cmd == 'admin') { - $importer = new EventoAdminImporter( - $request_client, - $logger, - $api_importer_settings->getTimeoutAfterRequest(), - $api_importer_settings->getMaxRetries() - ); - return $importer->fetchEventAdminDataRecordById($id); - } - } - } } + + if ($cmd == 'event') { + $importer = new EventoEventImporter( + $request_client, + $iterator, + $logger, + $api_importer_settings->getTimeoutAfterRequest(), + $api_importer_settings->getMaxRetries() + ); + return $importer->fetchEventDataRecordById($id); + } + + if ($cmd == 'photo') { + $importer = new EventoUserPhotoImporter( + $request_client, + $api_importer_settings->getTimeoutAfterRequest(), + $api_importer_settings->getMaxRetries(), + $logger + ); + return $importer->fetchUserPhotoDataById($id); + } + + if ($cmd == 'admin') { + $importer = new EventoAdminImporter( + $request_client, + $logger, + $api_importer_settings->getTimeoutAfterRequest(), + $api_importer_settings->getMaxRetries() + ); + return $importer->fetchEventAdminDataRecordById($id); + } + + return null; } public function fetchDataSet(string $cmd, int $skip, int $take) : array @@ -90,18 +92,20 @@ public function fetchDataSet(string $cmd, int $skip, int $take) : array $api_importer_settings->getMaxRetries() ); return $importer->fetchSpecificUserDataSet($skip, $take); - } else { - if ($cmd == 'event') { - $importer = new EventoEventImporter( - $request_client, - $iterator, - $logger, - $api_importer_settings->getTimeoutAfterRequest(), - $api_importer_settings->getMaxRetries() - ); - return $importer->fetchSpecificEventDataSet($skip, $take); - } } + + if ($cmd == 'event') { + $importer = new EventoEventImporter( + $request_client, + $iterator, + $logger, + $api_importer_settings->getTimeoutAfterRequest(), + $api_importer_settings->getMaxRetries() + ); + return $importer->fetchSpecificEventDataSet($skip, $take); + } + + return []; } public function fetchParameterlessDataset() : array @@ -125,7 +129,7 @@ private function buildDataSource(ImporterApiSettings $api_importer_settings) : R return new RestClientService( $api_importer_settings->getUrl(), $api_importer_settings->getTimeoutAfterRequest(), - $api_importer_settings->getApikey(), + $api_importer_settings->getApiKey(), $api_importer_settings->getApiSecret() ); } diff --git a/classes/administration/EventoImportApiTesterGUI.php b/classes/administration/EventoImportApiTesterGUI.php index ae099f7..8552c11 100644 --- a/classes/administration/EventoImportApiTesterGUI.php +++ b/classes/administration/EventoImportApiTesterGUI.php @@ -185,25 +185,29 @@ private function buildMessageForNextPage(string $infos, string $output) : string public function getApiDataAsString($cmd) : string { - if ($cmd == 'by_id') { + if ($cmd === 'by_id') { $form = $this->initDataRecordForm()->withRequest($this->request); $data = $form->getData(); if ($data) { return $this->fetchDataRecordFromFormInput(...$data[0]); - } else { - return "Form data Invalid"; } - } else if ($cmd == 'data_set') { + + return "Form data Invalid"; + } + + if ($cmd === 'data_set') { $form = $this->initDataSetForm()->withRequest($this->request); $data = $form->getData(); if ($data) { return $this->fetchDataSetFromFormInput(...$data[0]); - } else { - return "Form data Invalid"; } - } else if ($cmd == 'parameterless') { + + return "Form data Invalid"; + } + + if ($cmd === 'parameterless') { return $this->fetchParameterlessDataset(); } diff --git a/classes/administration/scripts/AdminScriptCommonMethods.php b/classes/administration/scripts/AdminScriptCommonMethods.php index 39d9516..120bc68 100644 --- a/classes/administration/scripts/AdminScriptCommonMethods.php +++ b/classes/administration/scripts/AdminScriptCommonMethods.php @@ -24,7 +24,7 @@ private function buildEventImporter($db) new RestClientService( $api_settings->getUrl(), $api_settings->getTimeoutFailedRequest(), - $api_settings->getApikey(), + $api_settings->getApiKey(), $api_settings->getApiSecret() ), new ImporterIterator($api_settings->getPageSize()), diff --git a/classes/administration/scripts/LookupEventByEventoTitle.php b/classes/administration/scripts/LookupEventByEventoTitle.php index 99e0cb9..c504032 100644 --- a/classes/administration/scripts/LookupEventByEventoTitle.php +++ b/classes/administration/scripts/LookupEventByEventoTitle.php @@ -64,7 +64,7 @@ public function getParameterFormUI() : \ilPropertyFormGUI public function getResultModalFromRequest(string $cmd, Factory $f) : Modal { $form = $this->getParameterFormUI(); - if(!$form->checkInput()) { + if (!$form->checkInput()) { throw new \InvalidArgumentException("Invalid Form Input!"); } diff --git a/classes/administration/scripts/ReAddRemovedEventParticipants.php b/classes/administration/scripts/ReAddRemovedEventParticipants.php index 02f7cce..d8f095b 100644 --- a/classes/administration/scripts/ReAddRemovedEventParticipants.php +++ b/classes/administration/scripts/ReAddRemovedEventParticipants.php @@ -99,7 +99,7 @@ private function listParticipantsInModal(Factory $f) : Modal $repo = new IliasEventoEventObjectRepository($this->db); $form = $this->getParameterFormUI(); - if(!$form->checkInput()) { + if (!$form->checkInput()) { throw new \InvalidArgumentException('Invalid form input'); } @@ -136,13 +136,13 @@ private function listParticipantsInModal(Factory $f) : Modal private function reAddParticipants($f) : Modal { $query_params = $this->request->getQueryParams(); - if(!isset($query_params['readd_to_event'])) { + if (!isset($query_params['readd_to_event'])) { throw new \InvalidArgumentException('No Event ID to readd participants'); } $event = $this->repo->getEventByEventoId((int) $query_params['readd_to_event']); $readd_form = $this->getFormWithRemovedUsers($event); - if(!$readd_form->checkInput()) { + if (!$readd_form->checkInput()) { throw new \InvalidArgumentException('Invalid form input'); } diff --git a/classes/administration/scripts/ResetHiddenAdminPermissions.php b/classes/administration/scripts/ResetHiddenAdminPermissions.php index 6836310..da7b96c 100644 --- a/classes/administration/scripts/ResetHiddenAdminPermissions.php +++ b/classes/administration/scripts/ResetHiddenAdminPermissions.php @@ -53,7 +53,7 @@ public function getParameterFormUI() : \ilPropertyFormGUI public function getResultModalFromRequest(string $cmd, Factory $f) : Modal { $form = $this->getParameterFormUI(); - if(!$form->checkInput() || $cmd != self::CMD_SET_PERMISSION) { + if (!$form->checkInput() || $cmd != self::CMD_SET_PERMISSION) { throw new \InvalidArgumentException("Invalid Form Input!"); } @@ -68,9 +68,9 @@ public function getResultModalFromRequest(string $cmd, Factory $f) : Modal $obj_ref_id = (int) $row[HiddenAdminsTableDef::COL_OBJECT_REF_ID]; if (!\ilObject::_exists($role_id)) { $errors[] = "Role with role_id $role_id does not exist"; - } else if (!\ilObject::_exists($obj_ref_id, true)) { + } elseif (!\ilObject::_exists($obj_ref_id, true)) { $errors[] = "Object with ref_id $obj_ref_id does not exist"; - } else if (!$this->tree->isInTree($obj_ref_id)) { + } elseif (!$this->tree->isInTree($obj_ref_id)) { $errors[] = "Object with ref_id $obj_ref_id is not in tree"; } else { $this->resetPermissionsForRole( diff --git a/classes/administration/scripts/SwitchIliasObjectForEventoEvent.php b/classes/administration/scripts/SwitchIliasObjectForEventoEvent.php index a5f6c56..5fc230e 100644 --- a/classes/administration/scripts/SwitchIliasObjectForEventoEvent.php +++ b/classes/administration/scripts/SwitchIliasObjectForEventoEvent.php @@ -81,7 +81,7 @@ private function showSelectedObjectsForSwitch(Factory $f) : Modal { $form = $this->getParameterFormUI(); - if(!$form->checkInput()) { + if (!$form->checkInput()) { throw new \InvalidArgumentException($this->getTitle(), 'Invalid Form Input'); } @@ -125,7 +125,7 @@ private function switchEventoEventToIliasObject(Factory $f) : Modal if ($target_ilias_object instanceof \ilObjCourse) { $changed_ilias_evento_event = $ilias_evento_event->switchToAnotherIliasObejct($target_ilias_object); $this->repo->updateIliasEventoEvent($changed_ilias_evento_event); - } else if ($target_ilias_object instanceof \ilObjGroup) { + } elseif ($target_ilias_object instanceof \ilObjGroup) { if (!$this->isChildOfCourseObject($target_ilias_object)) { throw new \InvalidArgumentException('Target group object is not child of course object. Events MUST be a course object or a group object, which is in a course object'); } @@ -135,7 +135,7 @@ private function switchEventoEventToIliasObject(Factory $f) : Modal $parent_key = ''; try { $evento_event = $importer->fetchEventDataRecordById($ilias_evento_event->getEventoEventId()); - if(!is_null($evento_event) && $evento_event->getGroupUniqueKey()) { + if (!is_null($evento_event) && $evento_event->getGroupUniqueKey()) { $parent_event = $this->repo->getParentEventbyGroupUniqueKey($evento_event->getGroupUniqueKey()); if (isset($parent_event) && $this->tree->isGrandChild($parent_event->getRefId(), $target_ilias_object->getRefId())) { $parent_key = $parent_event->getGroupUniqueKey(); @@ -163,7 +163,7 @@ private function getIliasObjectByRefId(int $ref_id) : \ilObject $type = \ilObject::_lookupType($ref_id, true); if ($type == 'crs') { return new \ilObjCourse($ref_id, true); - } else if ($type == 'grp') { + } elseif ($type == 'grp') { return new \ilObjGroup($ref_id, true); } diff --git a/classes/class.ilEventoImportConfigGUI.php b/classes/class.ilEventoImportConfigGUI.php index 65217fa..04be630 100644 --- a/classes/class.ilEventoImportConfigGUI.php +++ b/classes/class.ilEventoImportConfigGUI.php @@ -7,6 +7,7 @@ use EventoImport\administration\EventoImportApiTester; use EventoImport\administration\AdminScriptPageGUI; use EventoImport\config\locations\EventLocationsRepository; +use EventoImport\config\locations\BaseLocationConfiguration; use Psr\Http\Message\ServerRequestInterface; /** @@ -103,7 +104,7 @@ public function performCommand($cmd): void $output = $api_tester_gui->getApiDataAsString($cmd); - if (strlen($output) > 0) { + if ($output !== '') { ilEventoImportPlugin::sendSuccess($output, true); } } catch (Exception $e) { @@ -114,7 +115,7 @@ public function performCommand($cmd): void break; case 'reload_repo_locations': - $json_settings = $this->settings->get('crevento_location_settings'); + $json_settings = $this->settings->get(BaseLocationConfiguration::CONF_LOCATIONS); $locations_settings = json_decode($json_settings, true); $locations_builder = new EventLocationsBuilder(new EventLocationsRepository($this->db), $this->tree); @@ -125,7 +126,7 @@ public function performCommand($cmd): void break; case 'show_missing_repo_locations': - $json_settings = $this->settings->get('crevento_location_settings'); + $json_settings = $this->settings->get(BaseLocationConfiguration::CONF_LOCATIONS); $locations_settings = json_decode($json_settings, true); $locations_builder = new EventLocationsBuilder(new EventLocationsRepository($this->db), $this->tree); @@ -161,7 +162,7 @@ public function performCommand($cmd): void break; case 'create_repo_locations': - $json_settings = $this->settings->get('crevento_location_settings'); + $json_settings = $this->settings->get(BaseLocationConfiguration::CONF_LOCATIONS); $locations_settings = json_decode($json_settings, true); $locations_builder = new EventLocationsBuilder(new EventLocationsRepository($this->db), $this->tree); diff --git a/classes/class.ilEventoImportDailyImportCronJob.php b/classes/class.ilEventoImportDailyImportCronJob.php index 1ec94c0..4b4a753 100644 --- a/classes/class.ilEventoImportDailyImportCronJob.php +++ b/classes/class.ilEventoImportDailyImportCronJob.php @@ -64,7 +64,7 @@ public function run() : \ilCronJobResult $data_source = new RestClientService( $api_settings->getUrl(), $api_settings->getTimeoutAfterRequest(), - $api_settings->getApikey(), + $api_settings->getApiKey(), $api_settings->getApiSecret() ); diff --git a/classes/class.ilEventoImportHourlyImportCronJob.php b/classes/class.ilEventoImportHourlyImportCronJob.php index 85d6b30..b8d667a 100644 --- a/classes/class.ilEventoImportHourlyImportCronJob.php +++ b/classes/class.ilEventoImportHourlyImportCronJob.php @@ -60,7 +60,7 @@ public function run() : \ilCronJobResult $data_source = new RestClientService( $api_settings->getUrl(), $api_settings->getTimeoutAfterRequest(), - $api_settings->getApikey(), + $api_settings->getApiKey(), $api_settings->getApiSecret() ); diff --git a/classes/class.ilEventoImportPlugin.php b/classes/class.ilEventoImportPlugin.php index fd45924..4848744 100644 --- a/classes/class.ilEventoImportPlugin.php +++ b/classes/class.ilEventoImportPlugin.php @@ -4,6 +4,14 @@ use EventoImport\import\ImportTaskFactory; use EventoImport\config\ConfigurationManager; use EventoImport\config\CronConfigForm; +use EventoImport\config\DefaultUserSettings; +use EventoImport\config\DefaultEventSettings; +use EventoImport\config\ImporterApiSettings; +use EventoImport\config\locations\BaseLocationConfiguration; +use EventoImport\config\locations\RepositoryLocationSeeker; +use EventoImport\config\local_roles\LocalVisitorRoleManager; +use EventoImport\config\local_roles\LocalVisitorRoleFactory; +use EventoImport\config\local_roles\LocalVisitorRoleRepository; /** * Copyright (c) 2017 Hochschule Luzern @@ -36,33 +44,33 @@ class ilEventoImportPlugin extends ilCronHookPlugin const ID = 'crevento'; const PLUGIN_NAME = "EventoImport"; - public function __construct() - { - global $DIC; - $this->db = $DIC->database(); - parent::__construct($this->db, $DIC["component.repository"], self::ID); + public function __construct( + \ilDBInterface $db, + \ilComponentRepositoryWrite $component_repository + ) { + parent::__construct($db, $component_repository, self::ID); } public function getPluginName(): string { return self::PLUGIN_NAME; } - + /** * @var ilCronJob[] */ protected static $cron_job_instances; - + /** * @return ilCronJob[] */ public function getCronJobInstances() : array { $this->loadCronJobInstance(); - + return array_values(self::$cron_job_instances); } - + /** * @return ilCronJob or throw exception */ @@ -71,26 +79,42 @@ public function getCronJobInstance($a_job_id): \ilCronJob $this->loadCronJobInstance(); return self::$cron_job_instances[$a_job_id]; } - + protected function loadCronJobInstance() { + /** @var ILIAS\DI\Container $DIC */ global $DIC; - $db = $DIC->database(); + $lng = $DIC['lng']; $rbac = $DIC->rbac(); - $tree = $DIC->repositoryTree(); + $tree = $DIC['tree']; + $settings = new ilSetting('crevento'); //This is a workaround to avoid problems with missing templates if (!method_exists($DIC, 'ui') || !method_exists($DIC->ui(), 'factory') || !isset($DIC['ui.factory'])) { ilInitialisation::initUIFramework($DIC); ilStyleDefinition::setCurrentStyle('Desktop'); } - + if (!isset(self::$cron_job_instances)) { - $settings = new ilSetting('crevento'); - $cron_config = new CronConfigForm($settings, $this, $rbac); - $config_manager = new ConfigurationManager($cron_config, $settings, $db, $tree); - $import_factory = new ImportTaskFactory($config_manager, $db, $tree, $rbac); - $logger = new Logger($db); + ; + $cron_config = new CronConfigForm( + new DefaultUserSettings($settings), + new DefaultEventSettings($settings), + new ImporterApiSettings($settings), + new BaseLocationConfiguration($settings), + new RepositoryLocationSeeker($tree, 1), + new LocalVisitorRoleManager( + new LocalVisitorRoleRepository($this->db), + new LocalVisitorRoleFactory($rbac), + $rbac + ), + $this, + $lng, + $rbac + ); + $config_manager = new ConfigurationManager($cron_config, $settings, $this->db, $tree); + $import_factory = new ImportTaskFactory($config_manager, $this->db, $tree, $rbac); + $logger = new Logger($this->db); self::$cron_job_instances[ilEventoImportDailyImportCronJob::ID] = new ilEventoImportDailyImportCronJob( $this, @@ -109,9 +133,6 @@ protected function loadCronJobInstance() protected function beforeUninstall(): bool { - global $DIC; - $db = $DIC->database(); - $drop_table_list = [ 'crnhk_crevento_usrs', 'crnhk_crevento_mas', @@ -126,9 +147,9 @@ protected function beforeUninstall(): bool Logger::TABLE_LOG_MEMBERSHIPS ]; - foreach ($drop_table_list as $key => $table) { - if ($db->tableExists($table)) { - $db->dropTable($table); + foreach ($drop_table_list as $table) { + if ($this->db->tableExists($table)) { + $this->db->dropTable($table); } } @@ -162,7 +183,7 @@ public static function sendInfo($a_info = "", $a_keep = false) { global $DIC; - if(isset($DIC["tpl"])) { + if (isset($DIC["tpl"])) { $tpl = $DIC["tpl"]; $tpl->setOnScreenMessage("info", $a_info, $a_keep); } @@ -196,7 +217,7 @@ public static function sendQuestion($a_info = "", $a_keep = false) { global $DIC; - if(isset($DIC["tpl"])) { + if (isset($DIC["tpl"])) { $tpl = $DIC["tpl"]; $tpl->setOnScreenMessage("question", $a_info, $a_keep); } @@ -215,7 +236,7 @@ public static function sendSuccess($a_info = "", $a_keep = false) global $DIC; /** @var ilTemplate $tpl */ - if(isset($DIC["tpl"])) { + if (isset($DIC["tpl"])) { $tpl = $DIC["tpl"]; $tpl->setOnScreenMessage("success", $a_info, $a_keep); } diff --git a/classes/class.ilEventoImportUIRoutingGUI.php b/classes/class.ilEventoImportUIRoutingGUI.php index 122a11c..80d378e 100644 --- a/classes/class.ilEventoImportUIRoutingGUI.php +++ b/classes/class.ilEventoImportUIRoutingGUI.php @@ -16,7 +16,6 @@ class ilEventoImportUIRoutingGUI private ServerRequestInterface $request; private array $gui_classes; - private ilEventoImportPlugin $plugin; private \ILIAS\DI\UIServices $ui_services; private ilDBInterface $db; private ilTabsGUI $tabs; @@ -25,10 +24,11 @@ class ilEventoImportUIRoutingGUI private ilObjUser $user; private $error; + private ilEventoImportPlugin $plugin; + public function __construct() { global $DIC; - $this->plugin = new \ilEventoImportPlugin(); $this->tpl = $DIC->ui()->mainTemplate(); $this->ctrl = $DIC->ctrl(); $this->request = $DIC->http()->request(); @@ -40,6 +40,8 @@ public function __construct() $this->user = $DIC->user(); $this->error = $DIC["ilErr"]; + $this->plugin = new \ilEventoImportPlugin($this->db, $DIC['component.repository']); + $this->gui_classes = []; $this->gui_classes[self::GUI_ADMIN_SCRIPTS] = function () { return new \EventoImport\administration\AdminScriptPageGUI( @@ -60,7 +62,7 @@ public function __construct() public function executeCommand() { - if(isset($this->gui_classes[self::GUI_ADMIN_SCRIPTS])) { + if (isset($this->gui_classes[self::GUI_ADMIN_SCRIPTS])) { $this->gui_classes[self::GUI_ADMIN_SCRIPTS]()->executeCommandAndRenderGUI(); } } diff --git a/classes/communication/EventoEmployeeImporter.php b/classes/communication/EventoEmployeeImporter.php index 9d90be4..cc77c07 100644 --- a/classes/communication/EventoEmployeeImporter.php +++ b/classes/communication/EventoEmployeeImporter.php @@ -61,10 +61,10 @@ public function fetchEmployees(string $department_name, string $kind) : array $nr_of_tries++; } - if (!$request_was_successful) { - if ($nr_of_tries < $this->max_retries) { - sleep($this->seconds_before_retry); - } else { + if ($request_was_successful) { + continue; + } + if ($nr_of_tries >= $this->max_retries) { throw new \ilEventoImportCommunicationException( self::class, [ @@ -74,7 +74,8 @@ public function fetchEmployees(string $department_name, string $kind) : array "After $nr_of_tries tries, there was still no successful call to the API" ); } - } + + sleep($this->seconds_before_retry); } while (!$request_was_successful); return $response->getData(); diff --git a/classes/communication/EventoEventImporter.php b/classes/communication/EventoEventImporter.php index 051d927..a8b8fda 100644 --- a/classes/communication/EventoEventImporter.php +++ b/classes/communication/EventoEventImporter.php @@ -52,10 +52,10 @@ public function fetchNextEventDataSet() : array if (count($response->getData()) < 1) { $this->has_more_data = false; return []; - } else { - $this->has_more_data = $response->getHasMoreData(); - return $response->getData(); } + + $this->has_more_data = $response->getHasMoreData(); + return $response->getData(); } public function fetchSpecificEventDataSet(int $skip, int $take) : array diff --git a/classes/communication/EventoUserImporter.php b/classes/communication/EventoUserImporter.php index 04ae61a..2cdad03 100644 --- a/classes/communication/EventoUserImporter.php +++ b/classes/communication/EventoUserImporter.php @@ -62,10 +62,10 @@ public function fetchNextUserDataSet() : array if (count($response->getData()) < 1) { $this->has_more_data = false; return []; - } else { - $this->has_more_data = $response->getHasMoreData(); - return $response->getData(); } + + $this->has_more_data = $response->getHasMoreData(); + return $response->getData(); } public function fetchSpecificUserDataSet(int $skip, int $take) : array diff --git a/classes/communication/generic_importers/DataSetImport.php b/classes/communication/generic_importers/DataSetImport.php index ac96104..e17c538 100644 --- a/classes/communication/generic_importers/DataSetImport.php +++ b/classes/communication/generic_importers/DataSetImport.php @@ -39,20 +39,23 @@ protected function fetchDataSet(RequestClientService $data_source, string $metho $nr_of_tries++; } - if (!$request_was_successful) { - if ($nr_of_tries < $max_retries) { - sleep($seconds_before_retry); - } else { - throw new \ilEventoImportCommunicationException( - self::class, - [ - 'method_name' => $method_name, - 'request_params' => $request_params - ], - "After $nr_of_tries tries, there was still no successful call to the API" - ); - } + if ($request_was_successful) { + continue; } + + if ($nr_of_tries >= $max_retries) { + throw new \ilEventoImportCommunicationException( + self::class, + [ + 'method_name' => $method_name, + 'request_params' => $request_params + ], + "After $nr_of_tries tries, there was still no successful call to the API" + ); + + } + + sleep($seconds_before_retry); } while (!$request_was_successful); return $response; diff --git a/classes/communication/generic_importers/SingleDataRecordImport.php b/classes/communication/generic_importers/SingleDataRecordImport.php index cbe5c6c..b7c02c5 100644 --- a/classes/communication/generic_importers/SingleDataRecordImport.php +++ b/classes/communication/generic_importers/SingleDataRecordImport.php @@ -26,26 +26,28 @@ protected function fetchDataRecordById(RequestClientService $data_source, string $nr_of_tries++; } - if (!$request_was_successful) { - if ($nr_of_tries < $max_retries) { - sleep($seconds_before_retry); - } else { - throw new \ilEventoImportCommunicationException( - self::class, - [ - 'method_name' => $method_name, - 'request_params' => ['id' => $id] - ], - "After $nr_of_tries tries, there was still no successful call to the API" - ); - } + if ($request_was_successful) { + continue; } + + if ($nr_of_tries >= $max_retries) { + throw new \ilEventoImportCommunicationException( + self::class, + [ + 'method_name' => $method_name, + 'request_params' => ['id' => $id] + ], + "After $nr_of_tries tries, there was still no successful call to the API" + ); + } + + sleep($seconds_before_retry); } while (!$request_was_successful); if (!is_null($plain_response) && $plain_response != '') { return json_decode($plain_response, true, 10, JSON_THROW_ON_ERROR); - } else { - return null; } + + return null; } } diff --git a/classes/communication/interface_models/EventoUser.php b/classes/communication/interface_models/EventoUser.php index 2dc9a16..73ba574 100644 --- a/classes/communication/interface_models/EventoUser.php +++ b/classes/communication/interface_models/EventoUser.php @@ -5,6 +5,7 @@ class EventoUser extends ApiDataModelBase { const JSON_ID = 'idAccount'; + const JSON_EDU_ID = 'eduId'; const JSON_LAST_NAME = 'lastName'; const JSON_FIRST_NAME = 'firstName'; const JSON_GENDER = 'gender'; @@ -14,17 +15,19 @@ class EventoUser extends ApiDataModelBase const JSON_EMAIL_3 = 'email3'; const JSON_ROLES = 'roles'; - private ?int $evento_id; - private ?string $last_name; - private ?string $first_name; - private ?string $gender; - private ?string $login_name; - private ?array $email_list; - private ?array $roles; + private int $evento_id = 0; + private ?string $edu_id = null; + private string $last_name = ''; + private string $first_name = ''; + private string $gender = ''; + private string $login_name = ''; + private array $email_list = []; + private array $roles = []; public function __construct(array $data_set) { $this->evento_id = $this->validateAndReturnNumber($data_set, self::JSON_ID); + $this->edu_id = $this->validateAndReturnStringOrNull($data_set, self::JSON_EDU_ID); $this->last_name = $this->validateAndReturnString($data_set, self::JSON_LAST_NAME); $this->first_name = $this->validateAndReturnString($data_set, self::JSON_FIRST_NAME); $this->gender = $this->validateAndReturnString($data_set, self::JSON_GENDER); @@ -41,6 +44,11 @@ public function getEventoId() : int return $this->evento_id; } + public function getEduId() : string + { + return $this->edu_id ?? ''; + } + public function getLastName() : string { return $this->last_name; diff --git a/classes/communication/interface_models/EventoUserShort.php b/classes/communication/interface_models/EventoUserShort.php index 9f47346..55475a3 100644 --- a/classes/communication/interface_models/EventoUserShort.php +++ b/classes/communication/interface_models/EventoUserShort.php @@ -5,15 +5,21 @@ class EventoUserShort extends ApiDataModelBase { const JSON_ID = 'idAccount'; - const JSON_EMAIL = 'email'; + const JSON_EDU_ID = 'eduId'; - private ?int $evento_id; - private ?string $email_address; + private ?int $evento_id = null; + private ?string $edu_id = null; public function __construct(array $data_set) { $this->evento_id = $this->validateAndReturnNumber($data_set, self::JSON_ID); - $this->email_address = $this->validateAndReturnString($data_set, self::JSON_EMAIL); + /* In Evento Event Import members are imported without the eduid */ + if(array_key_exists(self::JSON_EDU_ID, $data_set)) { + $this->edu_id = $this->validateAndReturnString($data_set, self::JSON_EDU_ID); + } + else{ + $this->edu_id = null; + } $this->decoded_api_data = $data_set; $this->checkErrorsAndMaybeThrowException(); @@ -24,9 +30,9 @@ public function getEventoId() : int return $this->evento_id; } - public function getEmailAddress() : string + public function getEduId() : string { - return $this->email_address; + return $this->edu_id ?? ''; } public function getDecodedApiData() : array diff --git a/classes/communication/interface_models/JSONDataValidator.php b/classes/communication/interface_models/JSONDataValidator.php index bed2da8..5c6a0d7 100644 --- a/classes/communication/interface_models/JSONDataValidator.php +++ b/classes/communication/interface_models/JSONDataValidator.php @@ -26,6 +26,21 @@ protected function validateAndReturnNumber(array $data_array, string $key) : ?in return (int) $data_array[$key]; } + /** + * @param array $data_array + * @param string $key + * @return string|null + */ + protected function validateAndReturnStringOrNull(array $data_array, string $key) : ?string + { + if (!array_key_exists($key, $data_array)) { + $this->key_errors[$key] = 'Value not set'; + return null; + } + + return (string) $data_array[$key]; + } + /** * @param array $data_array * @param string $key @@ -56,19 +71,23 @@ protected function validateAndReturnBoolean(array $data_array, string $key, bool if (is_bool($data_array[$key])) { return $data_array[$key]; - } elseif ($as_string_possible && is_string($data_array[$key])) { + } + + if ($as_string_possible && is_string($data_array[$key])) { if ($data_array[$key] == 'true') { return true; - } elseif ($data_array[$key] == 'false') { + } + + if ($data_array[$key] == 'false') { return false; - } else { - $this->key_errors[$key] = 'Invalid string given as boolean'; - return null; } - } else { - $this->key_errors[$key] = 'Value ist not a boolean'; + + $this->key_errors[$key] = 'Invalid string given as boolean'; return null; } + + $this->key_errors[$key] = 'Value ist not a boolean'; + return null; } /** @@ -81,7 +100,9 @@ protected function validateAndReturnArray(array $data_array, string $key) : ?arr if (!isset($data_array[$key])) { $this->key_errors[$key] = 'Value not set'; return null; - } elseif (!is_array($data_array)) { + } + + if (!is_array($data_array)) { $this->key_errors[$key] = 'Value MUST be an array'; return null; } diff --git a/classes/communication/request_services/RestClientService.php b/classes/communication/request_services/RestClientService.php index a7417a0..a176577 100644 --- a/classes/communication/request_services/RestClientService.php +++ b/classes/communication/request_services/RestClientService.php @@ -19,13 +19,12 @@ public function __construct( string $api_key, string $api_secret ) { - //$this->base_uri = "https://$base_url:$port$base_path"; $this->base_uri = $base_uri; $this->timeout_after_request_seconds = $timeout_after_request_seconds; $this->api_key = $api_key; $this->api_secret = $api_secret; - if (filter_var($this->base_uri, FILTER_VALIDATE_URL, FILTER_FLAG_PATH_REQUIRED) === false) { + if (filter_var($this->base_uri, FILTER_VALIDATE_URL) === false) { throw new \InvalidArgumentException('Invalid Base-URI given! ' . $this->base_uri); } } @@ -57,7 +56,12 @@ private function buildAndValidateUrl(string $path, array $request_params) : stri { $url_without_query_params = $this->base_uri . $path; - if (filter_var($this->base_uri, FILTER_VALIDATE_URL, FILTER_FLAG_PATH_REQUIRED) === false) { + if (filter_var( + $this->base_uri, + FILTER_VALIDATE_URL, + FILTER_FLAG_PATH_REQUIRED + ) === false + ) { throw new \InvalidArgumentException('Invalid Base-URI given! ' . $this->base_uri); } diff --git a/classes/config/CronConfigForm.php b/classes/config/CronConfigForm.php index 4f8ab14..6e78ad7 100644 --- a/classes/config/CronConfigForm.php +++ b/classes/config/CronConfigForm.php @@ -5,22 +5,16 @@ use ILIAS\DI\RBACServices; use ilSelectInputGUI; use ilNumberInputGUI; -use ilSetting; use ilFormSectionHeaderGUI; use ilPropertyFormGUI; -use ilLDAPServer; use ilRadioGroupInputGUI; -use ilTextAreaInputGUI; use ilUriInputGUI; use ilCheckboxInputGUI; use ilTextInputGUI; use ilRadioOption; use ilAuthUtils; -use ilObject; use EventoImport\config\locations\RepositoryLocationSeeker; use EventoImport\config\local_roles\LocalVisitorRoleManager; -use EventoImport\config\local_roles\LocalVisitorRoleRepository; -use EventoImport\config\local_roles\LocalVisitorRoleFactory; use EventoImport\config\locations\BaseLocationConfiguration; /** @@ -46,27 +40,26 @@ class CronConfigForm const LANG_API_TIMEOUT_FAILED_REQUEST_DESC = 'api_timeout_failed_request_desc'; const LANG_API_MAX_RETRIES = 'api_max_retries'; const LANG_API_MAX_RETRIES_DESC = 'api_max_retries_desc'; + const LANG_HEADER_USER_SETTINGS = 'user_import_settings'; const LANG_USER_AUTH_MODE = 'user_auth_mode'; const LANG_USER_AUTH_MODE_DESC = 'user_auth_mode_desc'; const LANG_USER_IMPORT_ACC_DURATION = 'user_import_account_duration'; const LANG_USER_IMPORT_ACC_DURATION_DESC = 'user_import_account_duration_desc'; - const LANG_USER_MAX_ACC_DURATION = 'user_max_account_duration'; - const LANG_USER_MAX_ACC_DURATION_DESC = 'user_max_account_duration_desc'; - const LANG_USER_CHANGED_MAIL_SUBJECT = 'user_changed_mail_subject'; - const LANG_USER_CHANGED_MAIL_SUBJECT_DESC = 'user_changed_mail_subject_desc'; - const LANG_USER_CHANGED_MAIL_BODY = 'user_changed_mail_body'; - const LANG_USER_CHANGED_MAIL_BODY_DESC = 'user_changed_mail_body_desc'; - const LANG_STUDENT_ROLE_ID = 'user_student_role_id'; - const LANG_STUDENT_ROLE_ID_DESC = 'user_student_role_id_desc'; - const LANG_DEFAULT_USER_ROLE = 'default_user_role'; - const LANG_DEFAULT_USER_ROLE_DESC = 'default_user_role_desc'; const LANG_HEADER_USER_ADDITIONAL_ROLE_MAPPING = 'additional_user_roles_mapping'; + const LANG_ROLE_DELETE_FROM_ADMIN_ON_REMOVAL = 'delete_from_admins_on_removal'; + const LANG_ROLE_DELETE_FROM_ADMIN_ON_REMOVAL_DESC = 'delete_from_admins_on_removal_desc'; + const LANG_ROLE_TRACK_REMOVAL_CUSTOM_FIELD = 'track_removal_custom_field'; + const LANG_ROLE_TRACK_REMOVAL_CUSTOM_FIELD_DESC = 'track_removal_custom_field_desc'; const LANG_ROLE_MAPPING_TO = 'maps_to'; const LANG_ROLE_MAPPING_TO_DESC = 'maps_to_desc'; + const LANG_HEADER_USER_FOLLOW_UP_ROLE_MAPPING = 'follow_up_role_mapping'; + const LANG_HEADER_USER_FOLLOW_UP_ROLE_MAPPING_DESC = 'follow_up_role_mapping_desc'; + const LANG_HEADER_EVENT_LOCATIONS = 'location_settings'; const LANG_DEPARTMENTS = 'location_departments'; const LANG_KINDS = 'location_kinds'; + const LANG_HEADER_EVENT_SETTINGS = 'event_import_settings'; const LANG_EVENT_OBJECT_OWNER = 'object_owner'; const LANG_EVENT_OBJECT_OWNER_DESC = 'object_owner_desc'; @@ -92,14 +85,11 @@ class CronConfigForm const FORM_API_TIMEOUT_FAILED_REQUEST = 'crevento_api_timeout_failed_request'; const FORM_API_MAX_RETRIES = 'crevento_api_max_retries'; const FORM_USER_AUTH_MODE = 'crevento_user_auth_mode'; - const FORM_USER_IMPORT_ACC_DURATION = 'crevento_user_import_acc_duration'; - const FORM_USER_MAX_ACC_DURATION = 'crevento_user_max_acc_duration'; - const FORM_USER_CHANGED_MAIL_SUBJECT = 'crevento_user_changed_mail_subject'; - const FORM_USER_CHANGED_MAIL_BODY = 'crevento_user_changed_mail_body'; - const FORM_USER_STUDENT_ROLE_ID = 'crevento_student_role_id'; - const FORM_DEFAULT_USER_ROLE = 'crevento_default_user_role'; const FORM_USER_GLOBAL_ROLE_ = 'crevento_global_role_'; const FORM_USER_EVENTO_ROLE_MAPPED_TO_ = 'crevento_map_from_'; + const FORM_USER_EVENTO_ROLE_DELETE_FROM_ADMIN_ON_REMOVAL_ = 'crevento_delete_admin_on_removal_from_'; + const FORM_USER_EVENTO_ROLE_TRACK_REMOVAL_CUSTOM_FIELD_FOR_ = 'crevento_track_removal_custom_field_for_'; + const FORM_USER_FOLLOW_UP_ROLE_FOR_ = 'crevento_follow_up_role_for_'; const FORM_DEPARTEMTNS = 'crevento_departments'; const FORM_KINDS = 'crevento_kinds'; const FORM_EVENT_OBJECT_OWNER = 'crevento_object_owner'; @@ -107,33 +97,35 @@ class CronConfigForm const FORM_EVENT_OPT_OWNER_CUSTOM_USER = 'crevento_object_owner_custom'; const FORM_EVENT_OPT_OWNER_CUSTOM_ID = 'crevento_object_owner_custom_id'; - const CONF_API_URI = 'crevento_api_uri'; - const CONF_API_AUTH_KEY = 'crevento_api_auth_key'; - const CONF_API_AUTH_SECRET = 'crevento_api_auth_secret'; - const CONF_API_PAGE_SIZE = 'crevento_api_page_size'; - const CONF_API_MAX_PAGES = 'crevento_api_max_pages'; - const CONF_API_TIMEOUT_AFTER_REQUEST = 'crevento_api_timeout_after_request'; - const CONF_API_TIMEOUT_FAILED_REQUEST = 'crevento_api_timeout_failed_request'; - const CONF_API_MAX_RETRIES = 'crevento_api_max_retries'; - const CONF_USER_AUTH_MODE = 'crevento_ilias_auth_mode'; - const CONF_USER_IMPORT_ACC_DURATION = 'crevento_user_import_acc_duration'; - const CONF_USER_MAX_ACC_DURATION = 'crevento_user_max_acc_duration'; - const CONF_USER_CHANGED_MAIL_SUBJECT = 'crevento_email_account_changed_subject'; - const CONF_USER_CHANGED_MAIL_BODY = 'crevento_email_account_changed_body'; - const CONF_USER_STUDENT_ROLE_ID = 'crevento_student_role_id'; - const CONF_DEFAULT_USER_ROLE = 'crevento_default_user_role'; - const CONF_ROLES_ILIAS_EVENTO_MAPPING = 'crevento_roles_ilias_evento_mapping'; - const CONF_EVENT_OWNER_ID = 'crevento_object_owner_id'; - const CONF_EVENT_OBJECT_OWNER = 'crevento_object_owner'; - - private \ilSetting $settings; + private DefaultUserSettings $default_user_settings; + private DefaultEventSettings $default_event_settings; + private ImporterApiSettings $importer_api_settings; + private BaseLocationConfiguration $event_locations; + private RepositoryLocationSeeker $location_seeker; + private LocalVisitorRoleManager $local_visitor_manager; private \ilEventoImportPlugin $cp; + private \ilLanguage $lng; private RBACServices $rbac; - public function __construct(ilSetting $settings, \ilEventoImportPlugin $plugin, RBACServices $rbac) - { - $this->settings = $settings; + public function __construct( + DefaultUserSettings $default_user_settings, + DefaultEventSettings $default_event_settings, + ImporterApiSettings $importer_api_settings, + BaseLocationConfiguration $event_locations, + RepositoryLocationSeeker $location_seeker, + LocalVisitorRoleManager $local_visitor_manager, + \ilEventoImportPlugin $plugin, + \ilLanguage $lng, + RBACServices $rbac + ) { + $this->default_user_settings = $default_user_settings; + $this->default_event_settings = $default_event_settings; + $this->importer_api_settings = $importer_api_settings; + $this->event_locations = $event_locations; + $this->location_seeker = $location_seeker; + $this->local_visitor_manager = $local_visitor_manager; $this->cp = $plugin; + $this->lng = $lng; $this->rbac = $rbac; } @@ -152,7 +144,7 @@ public function fillFormWithApiConfig(ilPropertyFormGUI $form) ); $ws_item->setInfo($this->cp->txt(self::LANG_API_URI_DESC)); $ws_item->setRequired(true); - $ws_item->setValue($this->settings->get(self::CONF_API_URI, '')); + $ws_item->setValue($this->importer_api_settings->getUrl()); $form->addItem($ws_item); $ws_item = new ilTextInputGUI( @@ -161,7 +153,7 @@ public function fillFormWithApiConfig(ilPropertyFormGUI $form) ); $ws_item->setInfo($this->cp->txt(self::LANG_API_AUTH_KEY_DESC)); $ws_item->setRequired(false); - $ws_item->setValue($this->settings->get(self::CONF_API_AUTH_KEY, '')); + $ws_item->setValue($this->importer_api_settings->getApikey()); $form->addItem($ws_item); $ws_item = new ilTextInputGUI( @@ -170,7 +162,7 @@ public function fillFormWithApiConfig(ilPropertyFormGUI $form) ); $ws_item->setInfo($this->cp->txt(self::LANG_API_AUTH_SECRET_DESC)); $ws_item->setRequired(false); - $ws_item->setValue($this->settings->get(self::CONF_API_AUTH_SECRET, '')); + $ws_item->setValue($this->importer_api_settings->getApiSecret()); $form->addItem($ws_item); $ws_item = new ilNumberInputGUI( @@ -180,7 +172,7 @@ public function fillFormWithApiConfig(ilPropertyFormGUI $form) $ws_item->setInfo($this->cp->txt(self::LANG_API_PAGE_SIZE_DESC)); $ws_item->setRequired(true); $ws_item->allowDecimals(false); - $ws_item->setValue($this->settings->get(self::CONF_API_PAGE_SIZE, '0')); + $ws_item->setValue((string) $this->importer_api_settings->getPageSize()); $form->addItem($ws_item); $ws_item = new ilNumberInputGUI( @@ -190,7 +182,7 @@ public function fillFormWithApiConfig(ilPropertyFormGUI $form) $ws_item->setInfo($this->cp->txt(self::LANG_API_MAX_PAGES_DESC)); $ws_item->setRequired(true); $ws_item->allowDecimals(false); - $ws_item->setValue($this->settings->get(self::CONF_API_MAX_PAGES, '0')); + $ws_item->setValue((string) $this->importer_api_settings->getMaxPages()); $form->addItem($ws_item); $ws_item = new ilNumberInputGUI( @@ -200,7 +192,7 @@ public function fillFormWithApiConfig(ilPropertyFormGUI $form) $ws_item->setInfo($this->cp->txt(self::LANG_API_TIMEOUT_AFTER_REQUEST_DESC)); $ws_item->setRequired(true); $ws_item->allowDecimals(false); - $ws_item->setValue($this->settings->get(self::CONF_API_TIMEOUT_AFTER_REQUEST, '')); + $ws_item->setValue((string) $this->importer_api_settings->getTimeoutAfterRequest()); $form->addItem($ws_item); $ws_item = new ilNumberInputGUI( @@ -210,7 +202,7 @@ public function fillFormWithApiConfig(ilPropertyFormGUI $form) $ws_item->setInfo($this->cp->txt(self::LANG_API_TIMEOUT_FAILED_REQUEST_DESC)); $ws_item->setRequired(true); $ws_item->allowDecimals(false); - $ws_item->setValue($this->settings->get(self::CONF_API_TIMEOUT_FAILED_REQUEST, '')); + $ws_item->setValue((string) $this->importer_api_settings->getTimeoutFailedRequest()); $form->addItem($ws_item); $ws_item = new ilNumberInputGUI( @@ -220,7 +212,7 @@ public function fillFormWithApiConfig(ilPropertyFormGUI $form) $ws_item->setInfo($this->cp->txt(self::LANG_API_MAX_RETRIES_DESC)); $ws_item->setRequired(true); $ws_item->allowDecimals(false); - $ws_item->setValue($this->settings->get(self::CONF_API_MAX_RETRIES, '')); + $ws_item->setValue((string) $this->importer_api_settings->getMaxRetries()); $form->addItem($ws_item); } @@ -239,80 +231,19 @@ public function fillFormWithUserImportConfig(ilPropertyFormGUI $form) ); $ws_item->setInfo($this->cp->txt(self::LANG_USER_AUTH_MODE_DESC)); - global $DIC; - $lng = $DIC->language(); // The following code block to get list of auth-modes is stolen from ilObjUserGUI around line 1096 (from initForm()) $auth_modes = \ilAuthUtils::_getActiveAuthModes(); $options = []; foreach ($auth_modes as $auth_name => $auth_key) { if ($auth_name == 'default') { - $name = $lng->txt('auth_' . $auth_name) . " (" . $lng->txt('auth_' . ilAuthUtils::_getAuthModeName($auth_key)) . ")"; - + $name = $this->lng->txt('auth_' . $auth_name) . " (" . $this->lng->txt('auth_' . ilAuthUtils::_getAuthModeName($auth_key)) . ")"; } else { $name = ilAuthUtils::getAuthModeTranslation("$auth_key", $auth_name); } $options[$auth_name] = $name; } $ws_item->setOptions($options); - $ws_item->setValue($this->settings->get(self::CONF_USER_AUTH_MODE)); - $form->addItem($ws_item); - - $ws_item = new ilNumberInputGUI( - $this->cp->txt(self::LANG_USER_IMPORT_ACC_DURATION), - self::FORM_USER_IMPORT_ACC_DURATION - ); - $ws_item->setInfo($this->cp->txt(self::LANG_USER_IMPORT_ACC_DURATION_DESC)); - $ws_item->setRequired(true); - $ws_item->allowDecimals(false); - $ws_item->setValue($this->settings->get(self::CONF_USER_IMPORT_ACC_DURATION)); - $form->addItem($ws_item); - - $ws_item = new ilNumberInputGUI( - $this->cp->txt(self::LANG_USER_MAX_ACC_DURATION), - self::FORM_USER_MAX_ACC_DURATION - ); - $ws_item->setInfo($this->cp->txt(self::LANG_USER_MAX_ACC_DURATION_DESC)); - $ws_item->setRequired(true); - $ws_item->allowDecimals(false); - $ws_item->setValue($this->settings->get(self::CONF_USER_MAX_ACC_DURATION)); - $form->addItem($ws_item); - - $ws_item = new ilTextInputGUI( - $this->cp->txt(self::LANG_USER_CHANGED_MAIL_SUBJECT), - self::FORM_USER_CHANGED_MAIL_SUBJECT - ); - $ws_item->setInfo($this->cp->txt(self::LANG_USER_CHANGED_MAIL_SUBJECT_DESC)); - $ws_item->setRequired(true); - $ws_item->setValue($this->settings->get(self::CONF_USER_CHANGED_MAIL_SUBJECT, '')); - $form->addItem($ws_item); - - $ws_item = new ilTextAreaInputGUI( - $this->cp->txt(self::LANG_USER_CHANGED_MAIL_BODY), - self::FORM_USER_CHANGED_MAIL_BODY - ); - $ws_item->setInfo($this->cp->txt(self::LANG_USER_CHANGED_MAIL_BODY_DESC)); - $ws_item->setRequired(true); - $ws_item->setValue($this->settings->get(self::CONF_USER_CHANGED_MAIL_BODY, '')); - $form->addItem($ws_item); - - $ws_item = new ilNumberInputGUI( - $this->cp->txt(self::LANG_STUDENT_ROLE_ID), - self::FORM_USER_STUDENT_ROLE_ID - ); - $ws_item->setInfo($this->cp->txt(self::LANG_STUDENT_ROLE_ID_DESC)); - $ws_item->setRequired(true); - $ws_item->allowDecimals(false); - $ws_item->setValue($this->settings->get(self::CONF_USER_STUDENT_ROLE_ID)); - $form->addItem($ws_item); - - $ws_item = new ilNumberInputGUI( - $this->cp->txt(self::LANG_DEFAULT_USER_ROLE), - self::FORM_DEFAULT_USER_ROLE - ); - $ws_item->setInfo($this->cp->txt(self::LANG_DEFAULT_USER_ROLE_DESC)); - $ws_item->setRequired(true); - $ws_item->allowDecimals(false); - $ws_item->setValue($this->settings->get(self::CONF_DEFAULT_USER_ROLE)); + $ws_item->setValue($this->default_user_settings->getAuthMode()); $form->addItem($ws_item); $section = new ilFormSectionHeaderGUI(); @@ -320,14 +251,20 @@ public function fillFormWithUserImportConfig(ilPropertyFormGUI $form) $form->addItem($section); $global_roles = $this->rbac->review()->getGlobalRoles(); - $globale_roles_settings = $this->settings->get(self::CONF_ROLES_ILIAS_EVENTO_MAPPING, null); - $role_mapping = !is_null($globale_roles_settings) ? json_decode($globale_roles_settings, true) : null; - if (is_null($role_mapping) || !is_array($role_mapping)) { - $role_mapping = []; + $role_mapping = array_flip($this->default_user_settings->getEventoCodeToIliasRoleMapping()); + $track_removal_custom_fields_mapping = $this->default_user_settings->getTrackRemovalCustomFieldsMapping(); + $delete_from_admin_when_removed_role_array = $this->default_user_settings->getDeleteFromAdminWhenRemovedFromRoleMapping(); + + $custom_fields = \ilUserDefinedFields::_getInstance(); + $available_custom_fields = [0 => '--']; + foreach ($custom_fields->getDefinitions() as $definition) { + if ($definition['field_type'] === (string) UDF_TYPE_TEXT) { + $available_custom_fields[$definition['field_id']] = $definition['field_name']; + } } foreach ($global_roles as $role_id) { - $role_title = ilObject::_lookupTitle($role_id); + $role_title = \ilObject::_lookupTitle($role_id); $ws_item = new ilCheckboxInputGUI( $role_title, self::FORM_USER_GLOBAL_ROLE_ . "$role_id" @@ -343,14 +280,63 @@ public function fillFormWithUserImportConfig(ilPropertyFormGUI $form) $mapping_desc = sprintf($this->cp->txt(self::LANG_ROLE_MAPPING_TO_DESC), $role_title); $mapping_input->setInfo($mapping_desc); + $track_role_removal_custom_field = new \ilSelectInputGUI( + $this->cp->txt(self::LANG_ROLE_TRACK_REMOVAL_CUSTOM_FIELD), + self::FORM_USER_EVENTO_ROLE_TRACK_REMOVAL_CUSTOM_FIELD_FOR_ . $role_id + ); + $track_role_removal_custom_field->setOptions($available_custom_fields); + $track_role_removal_custom_field->setInfo($this->cp->txt(self::LANG_ROLE_TRACK_REMOVAL_CUSTOM_FIELD_DESC)); + $track_role_removal_custom_field->setValue($track_removal_custom_fields_mapping[$role_id] ?? 0); + + $delete_from_admin_input = new \ilCheckboxInputGUI( + $this->cp->txt(self::LANG_ROLE_DELETE_FROM_ADMIN_ON_REMOVAL), + self::FORM_USER_EVENTO_ROLE_DELETE_FROM_ADMIN_ON_REMOVAL_ . $role_id + ); + $delete_from_admin_input->setInfo($this->cp->txt(self::LANG_ROLE_DELETE_FROM_ADMIN_ON_REMOVAL_DESC)); + if (isset($role_mapping[$role_id])) { $ws_item->setChecked(true); $mapping_input->setValue((string) $role_mapping[$role_id]); + $delete_from_admin_input->setChecked(in_array($role_id, $delete_from_admin_when_removed_role_array)); } else { $ws_item->setChecked(false); } $ws_item->addSubItem($mapping_input); + $ws_item->addSubItem($track_role_removal_custom_field); + $ws_item->addSubItem($delete_from_admin_input); + + + + $form->addItem($ws_item); + } + + $section = new ilFormSectionHeaderGUI(); + $section->setTitle($this->cp->txt(self::LANG_HEADER_USER_FOLLOW_UP_ROLE_MAPPING)); + $section->setInfo($this->cp->txt(self::LANG_HEADER_USER_FOLLOW_UP_ROLE_MAPPING_DESC)); + $form->addItem($section); + + $follow_up_role_mapping = $this->default_user_settings->getFollowUpRoleMapping(); + foreach (array_keys($role_mapping) as $role_id) { + $role_title = \ilObject::_lookupTitle($role_id); + $options = [ + 0 => $this->lng->txt('none') + ]; + foreach($global_roles as $global_role_id) { + if ($global_role_id === $role_id) { + continue; + } + $options[$global_role_id] = \ilObject::_lookupTitle($global_role_id); + } + $ws_item = new \ilSelectInputGUI( + $role_title, + self::FORM_USER_FOLLOW_UP_ROLE_FOR_ . "$role_id" + ); + $ws_item->setOptions($options); + $ws_item->setValue(0); + if (array_key_exists($role_id, $follow_up_role_mapping)) { + $ws_item->setValue($follow_up_role_mapping[$role_id]); + } $form->addItem($ws_item); } } @@ -364,16 +350,14 @@ public function fillFormWithEventLocationConfig(ilPropertyFormGUI $form) $header->setTitle($this->cp->txt(self::LANG_HEADER_EVENT_LOCATIONS)); $form->addItem($header); - $locations = new BaseLocationConfiguration($this->settings); - $departments = new ilTextInputGUI($this->cp->txt(self::LANG_DEPARTMENTS), self::FORM_DEPARTEMTNS); $departments->setMulti(true, false, true); - $departments->setValue($locations->getDepartmentLocationList()); + $departments->setValue($this->event_locations->getDepartmentLocationList()); $form->addItem($departments); $kinds = new ilTextInputGUI($this->cp->txt(self::LANG_KINDS), self::FORM_KINDS); $kinds->setMulti(true, false, true); - $kinds->setValue($locations->getKindLocationList()); + $kinds->setValue($this->event_locations->getKindLocationList()); $form->addItem($kinds); } @@ -407,11 +391,13 @@ public function fillFormWithEventConfig(ilPropertyFormGUI $form) self::FORM_EVENT_OPT_OWNER_CUSTOM_ID// 'crevento_object_owner_id' ); $custom_user_id->allowDecimals(false); - $custom_user_id->setValue($this->settings->get(self::CONF_EVENT_OWNER_ID, '')); + $custom_user_id->setValue((string) $this->default_event_settings->getDefaultObjectOwnerId()); $option->addSubItem($custom_user_id); $radio->addOption($option); - $radio->setValue($this->settings->get(self::CONF_EVENT_OBJECT_OWNER, self::FORM_EVENT_OPT_OWNER_ROOT)); + $radio_value = $this->default_event_settings->getDefaultObjectOwnerId() === SYSTEM_USER_ID ? + self::FORM_EVENT_OPT_OWNER_ROOT : self::FORM_EVENT_OPT_OWNER_CUSTOM_USER; + $radio->setValue($radio_value); $form->addItem($radio); } @@ -425,220 +411,174 @@ public function fillFormWithVisitorConfig(ilPropertyFormGUI $form) $header->setTitle(self::LANG_HEADER_VISITOR_ROLES); $form->addItem($header); - $locations = new BaseLocationConfiguration($this->settings); - - global $DIC; - $tree = $DIC->repositoryTree(); - - $local_role_manager = new LocalVisitorRoleManager(new LocalVisitorRoleRepository($DIC->database()),new LocalVisitorRoleFactory($DIC->rbac()),$DIC->rbac()); - $location_seeker = new RepositoryLocationSeeker($tree, 1); - foreach($locations->getDepartmentLocationList() as $department_name) { - foreach($locations->getKindLocationList() as $kind_name) { - $ref_id = $location_seeker->searchRefIdOfKindCategory($department_name, $kind_name); - if(!is_null($ref_id)) { - $role = $local_role_manager->getLocalVisitorRoleByDepartmentAndKind($department_name, $kind_name); - $title = htmlspecialchars("$department_name/$kind_name"); - $title = $this->cp->txt(self::LANG_VISITOR_ROLE_CB) . " \"$title\""; - $post_var = str_replace(' ', '_',strtolower("visitors-{$department_name}-{$kind_name}")); - $ws_item = new ilCheckboxInputGUI( - $title, - $post_var - ); - $ws_item->setValue('1'); - $ws_item->setChecked(!is_null($role)); - - $txt_item = new \ilNonEditableValueGUI($this->cp->txt(self::LANG_VISITOR_REF_ID)); - $txt_item->setValue($ref_id); - $txt_item->setInfo($this->cp->txt(self::LANG_VISITOR_REF_ID_DESC) . ' ' . \ilLink::_getLink($ref_id, 'cat')); - $ws_item->addSubItem($txt_item); - - $txt_item = new \ilNonEditableValueGUI($this->cp->txt(self::LANG_VISITOR_ROLE_ID)); - if(is_null($role)) { - $txt_item->setValue("-"); - $txt_item->setInfo($this->cp->txt(self::LANG_VISITOR_NO_ROLE_DESC)); - } else { - $txt_item->setValue($role->getRoleId()); - $txt_item->setInfo($this->cp->txt(self::LANG_VISITOR_ROLE_ID_DESC)); - } + foreach($this->event_locations->getDepartmentLocationList() as $department_name) { + foreach($this->event_locations->getKindLocationList() as $kind_name) { + $ref_id = $this->location_seeker->searchRefIdOfKindCategory($department_name, $kind_name); + if (is_null($ref_id)) { + continue; + } - $ws_item->addSubItem($txt_item); + $role = $this->local_visitor_manager->getLocalVisitorRoleByDepartmentAndKind($department_name, $kind_name); + $title = htmlspecialchars("$department_name/$kind_name"); + $title = $this->cp->txt(self::LANG_VISITOR_ROLE_CB) . " \"$title\""; + $post_var = str_replace(' ', '_',strtolower("visitors-{$department_name}-{$kind_name}")); + $ws_item = new ilCheckboxInputGUI( + $title, + $post_var + ); + $ws_item->setValue('1'); + $ws_item->setChecked(!is_null($role)); + + $txt_item = new \ilNonEditableValueGUI($this->cp->txt(self::LANG_VISITOR_REF_ID)); + $txt_item->setValue($ref_id); + $txt_item->setInfo($this->cp->txt(self::LANG_VISITOR_REF_ID_DESC) . ' ' . \ilLink::_getLink($ref_id, 'cat')); + $ws_item->addSubItem($txt_item); + + $txt_item = new \ilNonEditableValueGUI($this->cp->txt(self::LANG_VISITOR_ROLE_ID)); + if (is_null($role)) { + $txt_item->setValue("-"); + $txt_item->setInfo($this->cp->txt(self::LANG_VISITOR_NO_ROLE_DESC)); + } else { + $txt_item->setValue($role->getRoleId()); + $txt_item->setInfo($this->cp->txt(self::LANG_VISITOR_ROLE_ID_DESC)); + } - $post_var = str_replace(' ', '_',strtolower("shortname_{$department_name}-{$kind_name}")); - $txt_item = new ilTextInputGUI($this->cp->txt(self::LANG_VISITOR_DEP_API_NAME), $post_var); - $txt_item->setInfo($this->cp->txt(self::LANG_VISITOR_DEP_API_NAME_DESC)); - if(!is_null($role)) { - $txt_item->setValue($role->getDepartmentApiName()); - } - $ws_item->addSubItem($txt_item); + $ws_item->addSubItem($txt_item); - $form->addItem($ws_item); + $post_var = str_replace(' ', '_',strtolower("shortname_{$department_name}-{$kind_name}")); + $txt_item = new ilTextInputGUI($this->cp->txt(self::LANG_VISITOR_DEP_API_NAME), $post_var); + $txt_item->setInfo($this->cp->txt(self::LANG_VISITOR_DEP_API_NAME_DESC)); + if (!is_null($role)) { + $txt_item->setValue($role->getDepartmentApiName()); } + $ws_item->addSubItem($txt_item); + + $form->addItem($ws_item); } } } public function saveApiConfigFromForm(ilPropertyFormGUI $form) : bool { - $form_input_correct = true; - - $this->getTextInputAndSaveIfNotNull($form, self::FORM_API_URI, self::CONF_API_URI); - $this->getTextInputAndSaveIfNotNull($form, self::FORM_API_AUTH_KEY, self::CONF_API_AUTH_KEY); - $this->getTextInputAndSaveIfNotNull($form, self::FORM_API_AUTH_SECRET, self::CONF_API_AUTH_SECRET); - $this->getIntegerInputAndSaveIfNotNull($form, self::FORM_API_PAGE_SIZE, self::CONF_API_PAGE_SIZE); - $this->getIntegerInputAndSaveIfNotNull($form, self::FORM_API_MAX_PAGES, self::CONF_API_MAX_PAGES); - $this->getIntegerInputAndSaveIfNotNull( - $form, - self::FORM_API_TIMEOUT_AFTER_REQUEST, - self::CONF_API_TIMEOUT_AFTER_REQUEST + $this->importer_api_settings->setUrl($form->getInput(self::FORM_API_URI)); + $this->importer_api_settings->setApiKey($form->getInput(self::FORM_API_AUTH_KEY)); + $this->importer_api_settings->setApiSecret($form->getInput(self::FORM_API_AUTH_SECRET)); + $this->importer_api_settings->setPageSize( + intval($form->getInput(self::FORM_API_PAGE_SIZE)) + ); + $this->importer_api_settings->setMaxPages( + intval($form->getInput(self::FORM_API_MAX_PAGES)) ); - $this->getIntegerInputAndSaveIfNotNull( - $form, - self::FORM_API_TIMEOUT_FAILED_REQUEST, - self::CONF_API_TIMEOUT_FAILED_REQUEST + $this->importer_api_settings->setTimeoutAfterRequest( + intval($form->getInput(self::FORM_API_TIMEOUT_AFTER_REQUEST)) ); - $this->getIntegerInputAndSaveIfNotNull($form, self::FORM_API_MAX_RETRIES, self::CONF_API_MAX_RETRIES); + $this->importer_api_settings->setTimeoutFailedRequest( + intval($form->getInput(self::FORM_API_TIMEOUT_FAILED_REQUEST)) + ); + $this->importer_api_settings->setMaxRetries( + intval($form->getInput(self::FORM_API_MAX_RETRIES)) + ); + $this->importer_api_settings->saveCurrentConfigurationToSettings(); - return $form_input_correct; + return true; } public function saveUserConfigFromForm(ilPropertyFormGUI $form) : bool { - $form_input_correct = true; - - if ($form->getInput(self::FORM_USER_AUTH_MODE) != null) { - $this->settings->set(self::CONF_USER_AUTH_MODE, $form->getInput(self::FORM_USER_AUTH_MODE)); - } - - $this->getIntegerInputAndSaveIfNotNull( - $form, - self::FORM_USER_IMPORT_ACC_DURATION, - self::CONF_USER_IMPORT_ACC_DURATION - ); - $this->getIntegerInputAndSaveIfNotNull( - $form, - self::FORM_USER_MAX_ACC_DURATION, - self::CONF_USER_MAX_ACC_DURATION - ); - $this->getTextInputAndSaveIfNotNull( - $form, - self::FORM_USER_CHANGED_MAIL_SUBJECT, - self::CONF_USER_CHANGED_MAIL_SUBJECT - ); - $this->getTextInputAndSaveIfNotNull( - $form, - self::FORM_USER_CHANGED_MAIL_BODY, - self::CONF_USER_CHANGED_MAIL_BODY - ); - - $this->getIntegerInputAndSaveIfNotNull($form, self::FORM_USER_STUDENT_ROLE_ID, self::CONF_USER_STUDENT_ROLE_ID); - $this->getIntegerInputAndSaveIfNotNull($form, self::FORM_DEFAULT_USER_ROLE, self::CONF_DEFAULT_USER_ROLE); + $this->default_user_settings->setAuthMode($form->getInput(self::FORM_USER_AUTH_MODE)); + $this->default_user_settings->saveCurrentConfigurationToSettings(); $global_roles = $this->rbac->review()->getGlobalRoles(); $role_mapping = []; - $save_global_role_mapping = true; + $delete_admin_on_removal_from_role = []; + $follow_up_role_mapping = []; foreach ($global_roles as $role_id) { $check_box = $form->getInput(self::FORM_USER_GLOBAL_ROLE_ . $role_id); - if ($check_box == '1') { - $mapped_role_input = (int) $form->getInput(self::FORM_USER_EVENTO_ROLE_MAPPED_TO_ . $role_id); - if (!is_null($mapped_role_input) && !in_array($mapped_role_input, $role_mapping)) { - $role_mapping[$role_id] = $mapped_role_input; - } elseif (in_array($mapped_role_input, $role_mapping)) { - $form_input_correct = false; - $save_global_role_mapping = false; - } + if ($check_box !== '1') { + continue; } - } - if ($save_global_role_mapping) { - $this->settings->set(self::CONF_ROLES_ILIAS_EVENTO_MAPPING, json_encode($role_mapping)); - } - return $form_input_correct; - } + $mapped_role_input = $form->getInput(self::FORM_USER_EVENTO_ROLE_MAPPED_TO_ . $role_id); + $track_removal_custom_field = $form->getInput(self::FORM_USER_EVENTO_ROLE_TRACK_REMOVAL_CUSTOM_FIELD_FOR_ . $role_id); + $delete_from_admin_on_removal = $form->getInput(self::FORM_USER_EVENTO_ROLE_DELETE_FROM_ADMIN_ON_REMOVAL_ . $role_id); - public function saveEventLocationConfigFromForm(ilPropertyFormGUI $form) : bool - { - $form_input_correct = true; + if (in_array($mapped_role_input, $role_mapping)) { + return false; + } - $location_settings = new BaseLocationConfiguration($this->settings); + $role_mapping[$mapped_role_input] = $role_id; - $location_settings->setDepartmentLocationList($form->getInput(self::FORM_DEPARTEMTNS)); - $location_settings->setKindLocationList($form->getInput(self::FORM_KINDS)); + $follow_up_role_mapping[$role_id] = intval($form->getInput(self::FORM_USER_FOLLOW_UP_ROLE_FOR_ . $role_id) ?? '0'); - $location_settings->saveCurrentConfigurationToSettings(); + $track_removal_custom_field_mapping[$role_id] = $track_removal_custom_field; - return $form_input_correct; + if ($delete_from_admin_on_removal === '1') { + $delete_admin_on_removal_from_role[] = $role_id; + } + } + + $this->default_user_settings->setEventoCodeToIliasRoleMapping($role_mapping); + $this->default_user_settings->setDeleteFromAdminWhenRemovedFromRoleMapping($delete_admin_on_removal_from_role); + $this->default_user_settings->setTrackRemovalCustomFieldsMapping($track_removal_custom_field_mapping); + $this->default_user_settings->setFollowUpRoleMapping($follow_up_role_mapping); + $this->default_user_settings->saveCurrentConfigurationToSettings(); + + return true; } - public function saveEventConfigFromForm(ilPropertyFormGUI $form) : bool + public function saveEventLocationConfigFromForm(ilPropertyFormGUI $form) : bool { - $form_input_correct = true; + $this->event_locations->setDepartmentLocationList($form->getInput(self::FORM_DEPARTEMTNS)); + $this->event_locations->setKindLocationList($form->getInput(self::FORM_KINDS)); + $this->event_locations->saveCurrentConfigurationToSettings(); + return true; + } + public function saveEventConfigFromForm(ilPropertyFormGUI $form) : bool + { $input_object_owner = $form->getInput(self::FORM_EVENT_OBJECT_OWNER); switch ($input_object_owner) { case self::FORM_EVENT_OPT_OWNER_ROOT: - $this->settings->set(self::CONF_EVENT_OBJECT_OWNER, self::FORM_EVENT_OPT_OWNER_ROOT); - $this->settings->set(self::CONF_EVENT_OWNER_ID, "6"); + $this->default_event_settings->setDefaultObjectOwnerId(6); break; case self::FORM_EVENT_OPT_OWNER_CUSTOM_USER: - $input_user_id = (int) $form->getInput(self::FORM_EVENT_OPT_OWNER_CUSTOM_ID); - $this->settings->set(self::CONF_EVENT_OBJECT_OWNER, self::FORM_EVENT_OPT_OWNER_CUSTOM_USER); - $this->settings->set(self::CONF_EVENT_OWNER_ID, "$input_user_id"); + $this->default_event_settings->setDefaultObjectOwnerId( + intval($form->getInput(self::FORM_EVENT_OPT_OWNER_CUSTOM_ID)) + ); break; } - - return $form_input_correct; + $this->default_event_settings->saveCurrentConfigurationToSettings(); + return true; } public function saveVisitorRolesConfigForm(ilPropertyFormGUI $form) : bool { $form_input_correct = true; - $locations = new BaseLocationConfiguration($this->settings); - - global $DIC; - $tree = $DIC->repositoryTree(); - - $location_seeker = new RepositoryLocationSeeker($tree, 1); - $local_role_manager = new LocalVisitorRoleManager(new LocalVisitorRoleRepository($DIC->database()),new LocalVisitorRoleFactory($DIC->rbac()),$DIC->rbac()); - foreach($locations->getDepartmentLocationList() as $department_name) { - foreach($locations->getKindLocationList() as $kind_name) { - $ref_id = $location_seeker->searchRefIdOfKindCategory($department_name, $kind_name); - if(!is_null($ref_id)) { - - $post_var = str_replace(' ', '_',strtolower("visitors-{$department_name}-{$kind_name}")); - $check_box = $form->getInput($post_var); - if($check_box == '1') { - $post_var = str_replace(' ', '_',strtolower("shortname_{$department_name}-{$kind_name}")); - $dep_api_name = $form->getInput($post_var); - if($dep_api_name == '' || $dep_api_name == null) { - $dep_api_name = $department_name; - } - $local_role_manager->configLocalRoleByDepartmentAndKind($department_name, $kind_name, $ref_id, $dep_api_name); - } else { - $local_role_manager->unconfigLocalRoleByDepartmentAndKind($department_name, $kind_name, $ref_id); + foreach($this->event_locations->getDepartmentLocationList() as $department_name) { + foreach($this->event_locations->getKindLocationList() as $kind_name) { + $ref_id = $this->location_seeker->searchRefIdOfKindCategory($department_name, $kind_name); + if (is_null($ref_id)) { + continue; + } + + $post_var = str_replace(' ', '_',strtolower("visitors-{$department_name}-{$kind_name}")); + $check_box = $form->getInput($post_var); + if ($check_box == '1') { + $post_var = str_replace(' ', '_',strtolower("shortname_{$department_name}-{$kind_name}")); + $dep_api_name = $form->getInput($post_var); + if ($dep_api_name == '' || $dep_api_name == null) { + $dep_api_name = $department_name; } + $this->local_visitor_manager->configLocalRoleByDepartmentAndKind($department_name, $kind_name, $ref_id, $dep_api_name); + } else { + $this->local_visitor_manager->unconfigLocalRoleByDepartmentAndKind($department_name, $kind_name, $ref_id); } } } return $form_input_correct; } - - private function getTextInputAndSaveIfNotNull(ilPropertyFormGUI $form, string $input_field, string $conf_key) - { - $value = $form->getInput($input_field); - if (!is_null($value)) { - $this->settings->set($conf_key, $value); - } - } - - private function getIntegerInputAndSaveIfNotNull(ilPropertyFormGUI $form, string $input_field, string $conf_key) - { - $value = (int) $form->getInput($input_field); - if (!is_null($value)) { - $this->settings->set($conf_key, "$value"); - } - } } diff --git a/classes/config/DefaultEventSettings.php b/classes/config/DefaultEventSettings.php index bc138ae..d04d925 100644 --- a/classes/config/DefaultEventSettings.php +++ b/classes/config/DefaultEventSettings.php @@ -4,6 +4,10 @@ class DefaultEventSettings { + private const CONF_EVENT_OWNER_ID = 'crevento_object_owner_id'; + + private \ilSetting $settings; + private int $default_object_owner_id; private int $default_sort_mode; private int $default_sort_direction; @@ -13,8 +17,9 @@ class DefaultEventSettings public function __construct(\ilSetting $settings) { + $this->settings = $settings; - $this->default_object_owner_id = (int) $settings->get(CronConfigForm::CONF_EVENT_OWNER_ID, "6"); + $this->default_object_owner_id = (int) $this->settings->get(self::CONF_EVENT_OWNER_ID, "6"); $this->default_sort_mode = \ilContainer::SORT_MANUAL; $this->default_sort_new_items_order = \ilContainer::SORT_NEW_ITEMS_ORDER_CREATION; $this->default_sort_new_items_position = \ilContainer::SORT_NEW_ITEMS_POSITION_BOTTOM; @@ -22,33 +27,43 @@ public function __construct(\ilSetting $settings) $this->default_online_status = true; } - public function getDefaultObjectOwnerId() : int + public function getDefaultObjectOwnerId(): int { return $this->default_object_owner_id; } - public function getDefaultSortMode() : int + public function setDefaultObjectOwnerId(int $default_object_owner_id): void + { + $this->default_object_owner_id = $default_object_owner_id; + } + + public function getDefaultSortMode(): int { return $this->default_sort_mode; } - public function getDefaultSortNewItemsOrder() + public function getDefaultSortNewItemsOrder(): int { return $this->default_sort_new_items_order; } - public function getDefaultSortNewItemsPosition() + public function getDefaultSortNewItemsPosition(): int { return $this->default_sort_new_items_position; } - public function getDefaultSortDirection() : int + public function getDefaultSortDirection(): int { return $this->default_sort_direction; } - public function isDefaultOnline() : bool + public function isDefaultOnline(): bool { return $this->default_online_status; } + + public function saveCurrentConfigurationToSettings(): void + { + $this->settings->set(self::CONF_EVENT_OWNER_ID, (string) $this->getDefaultObjectOwnerId()); + } } diff --git a/classes/config/DefaultUserSettings.php b/classes/config/DefaultUserSettings.php index 27bfabc..0c83b06 100644 --- a/classes/config/DefaultUserSettings.php +++ b/classes/config/DefaultUserSettings.php @@ -4,132 +4,155 @@ class DefaultUserSettings { + private const DEFAULT_USER_ROLE = 109; + private const DEFAULT_GUEST_ROLE = 5; + private const DEFAULT_HITS_PER_PAGE = 100; + private const DEFAULT_SHOW_USERS_ONLINE = 'associated'; + private const DEFAULT_IS_PROFILE_PUBLIC = true; + private const DEFAULT_IS_PROFILE_PICTURE_PUBLIC = true; + private const DEFAULT_IS_MAIL_PUBLIC = true; + private const DEFAULT_MAIL_INCOMING_TYPE = 2; + + private const CONF_USER_AUTH_MODE = 'crevento_ilias_auth_mode'; + private const CONF_ROLES_ILIAS_EVENTO_MAPPING = 'crevento_roles_ilias_evento_mapping'; + private const CONF_ROLES_TRACK_REMOVAL_CUSTOM_FIELD = 'crevento_roles_track_removal_custom_field'; + private const CONF_ROLES_DELETE_FROM_ADMIN_ON_REMOVAL = 'crevento_roles_delete_from_admin_on_removal'; + private const CONF_ROLES_FOLLOW_UP_ROLE_MAPPING = 'crevento_roles_follow_up_role_mapping'; + private \ilSetting $settings; - private \DateTimeImmutable $now; private $auth_mode; - private bool $is_auth_mode_ldap; - private bool $is_profile_public; private bool $is_profile_picture_public; - private bool $is_mail_public; - private int $default_user_role_id; - private \DateTimeImmutable $acc_duration_after_import; - private \DateTimeImmutable $max_acc_duration; - private int $default_hits_per_page; - private string $default_show_users_online; - private int $mail_incoming_type; private array $evento_to_ilias_role_mapping; - private array $assignable_roles; - private int $student_role_id; + private array $delete_when_removed_mapping; + private array $track_removal_custom_fields_mapping; + private array $follow_up_role_mapping; public function __construct(\ilSetting $settings) { $this->settings = $settings; + $this->auth_mode = $this->settings->get(self::CONF_USER_AUTH_MODE, 'local'); $this->assignable_roles = []; - $this->default_user_role_id = (int) $settings->get(CronConfigForm::CONF_DEFAULT_USER_ROLE); // TODO: Use default user role from constants - $this->assignable_roles[] = $this->default_user_role_id; - $this->default_hits_per_page = 100; - $this->default_show_users_online = 'associated'; - $this->student_role_id = (int) $settings->get(CronConfigForm::CONF_USER_STUDENT_ROLE_ID); + $this->evento_to_ilias_role_mapping = array_flip( + json_decode($this->settings->get(self::CONF_ROLES_ILIAS_EVENTO_MAPPING, '[]'), true) ?? [] + ); + $this->delete_when_removed_mapping = json_decode($this->settings->get(self::CONF_ROLES_DELETE_FROM_ADMIN_ON_REMOVAL, '[]'), true) ?? []; + $this->track_removal_custom_fields_mapping = json_decode($this->settings->get(self::CONF_ROLES_TRACK_REMOVAL_CUSTOM_FIELD, '[]'), true) ?? []; + $this->follow_up_role_mapping = json_decode($this->settings->get(self::CONF_ROLES_FOLLOW_UP_ROLE_MAPPING, '[]'), true) ?? []; + } - $this->now = new \DateTimeImmutable(); - $import_acc_duration_in_months = (int) $settings->get(CronConfigForm::CONF_USER_IMPORT_ACC_DURATION, "12"); - $this->acc_duration_after_import = $this->addMonthsToCurrent($import_acc_duration_in_months); - $max_acc_duration_in_months = (int) $settings->get(CronConfigForm::CONF_USER_MAX_ACC_DURATION, "24"); - $this->max_acc_duration = $this->addMonthsToCurrent($max_acc_duration_in_months); + public function getAuthMode(): string + { + return $this->auth_mode; + } + + public function setAuthMode(string $auth_mode): void + { + $this->auth_mode = $auth_mode; + } - $this->auth_mode = $settings->get(CronConfigForm::CONF_USER_AUTH_MODE, 'local'); - $this->is_auth_mode_ldap = \ilLDAPServer::isAuthModeLDAP($this->auth_mode); - $this->is_profile_public = true; - $this->is_profile_picture_public = true; - $this->is_mail_public = true; - $this->mail_incoming_type = 2; + public function isProfilePublic(): bool + { + return self::DEFAULT_IS_PROFILE_PUBLIC; + } - $role_mapping = $settings->get(CronConfigForm::CONF_ROLES_ILIAS_EVENTO_MAPPING, null); - $role_mapping = !is_null($role_mapping) ? json_decode($role_mapping, true) : null; - $this->evento_to_ilias_role_mapping = []; - if (!is_null($role_mapping)) { - foreach ($role_mapping as $ilias_role_id => $evento_role) { - $this->evento_to_ilias_role_mapping[$evento_role] = $ilias_role_id; - $this->assignable_roles[] = $ilias_role_id; - } - } + public function isProfilePicturePublic(): bool + { + return self::DEFAULT_IS_PROFILE_PICTURE_PUBLIC; } - private function addMonthsToCurrent(int $import_acc_duration_in_months) : \DateTimeImmutable + public function isMailPublic(): bool { - return $this->getNow()->add(new \DateInterval('P' . $import_acc_duration_in_months . 'M')); + return self::DEFAULT_IS_MAIL_PUBLIC; } - public function getNow() : \DateTimeImmutable + public function getMailIncomingType(): int { - return $this->now; + return self::DEFAULT_MAIL_INCOMING_TYPE; } - public function getAccDurationAfterImport() : \DateTimeImmutable + public function getDefaultUserRoleId(): int { - return $this->acc_duration_after_import; + return self::DEFAULT_USER_ROLE; } - public function getMaxDurationOfAccounts() : \DateTimeImmutable + public function getDefaultGuestRoleId(): int { - return $this->max_acc_duration; + return self::DEFAULT_GUEST_ROLE; } - public function getAuthMode() + public function getDefaultHitsPerPage(): int { - return $this->auth_mode; + return self::DEFAULT_HITS_PER_PAGE; } - public function isAuthModeLDAP() : bool + public function getDefaultShowUsersOnline(): string { - return $this->is_auth_mode_ldap; + return self::DEFAULT_SHOW_USERS_ONLINE; } - public function isProfilePublic() : bool + public function getEventoCodeToIliasRoleMapping(): array { - return $this->is_profile_public; + return $this->evento_to_ilias_role_mapping; } - public function isProfilePicturePublic() : bool + public function setEventoCodeToIliasRoleMapping(array $evento_to_ilias_role_mapping): void { - return $this->is_profile_picture_public; + $this->evento_to_ilias_role_mapping = $evento_to_ilias_role_mapping; } - public function isMailPublic() : bool + public function getTrackRemovalCustomFieldsMapping(): array { - return $this->is_mail_public; + return $this->track_removal_custom_fields_mapping; } - public function getMailIncomingType() : int + public function setTrackRemovalCustomFieldsMapping(array $track_removal_custom_fields_mapping): void { - return $this->mail_incoming_type; + $this->track_removal_custom_fields_mapping = $track_removal_custom_fields_mapping; } - public function getDefaultUserRoleId() : int + public function getDeleteFromAdminWhenRemovedFromRoleMapping(): array { - return $this->default_user_role_id; + return $this->delete_when_removed_mapping; } - public function getDefaultHitsPerPage() : int + public function setDeleteFromAdminWhenRemovedFromRoleMapping(array $delete_when_removed_mapping): void { - return $this->default_hits_per_page; + $this->delete_when_removed_mapping = $delete_when_removed_mapping; } - public function getDefaultShowUsersOnline() : string + public function getFollowUpRoleMapping(): array { - return $this->default_show_users_online; + return $this->follow_up_role_mapping; } - public function getEventoCodeToIliasRoleMapping() : array + public function setFollowUpRoleMapping(array $follow_up_role_mapping): void { - return $this->evento_to_ilias_role_mapping; + $this->follow_up_role_mapping = $follow_up_role_mapping; } - public function getStudentRoleId() : int + public function saveCurrentConfigurationToSettings(): void { - return $this->student_role_id; + $this->settings->set(self::CONF_USER_AUTH_MODE, $this->getAuthMode()); + $this->settings->set( + self::CONF_ROLES_ILIAS_EVENTO_MAPPING, + json_encode( + array_flip($this->getEventoCodeToIliasRoleMapping()) + ) + ); + $this->settings->set( + self::CONF_ROLES_DELETE_FROM_ADMIN_ON_REMOVAL, + json_encode($this->getDeleteFromAdminWhenRemovedFromRoleMapping()) + ); + $this->settings->set( + self::CONF_ROLES_TRACK_REMOVAL_CUSTOM_FIELD, + json_encode($this->getTrackRemovalCustomFieldsMapping()) + ); + $this->settings->set( + self::CONF_ROLES_FOLLOW_UP_ROLE_MAPPING, + json_encode($this->getFollowUpRoleMapping()) + ); } } diff --git a/classes/config/EventLocations.php b/classes/config/EventLocations.php index c269a40..1c0f64d 100644 --- a/classes/config/EventLocations.php +++ b/classes/config/EventLocations.php @@ -53,26 +53,24 @@ public function getLocationRefIdForEventoEvent(EventoEvent $evento_event, bool $ $event_year = (int) $evento_event->getStartDate()->format('Y'); try { - $ref_id = $this->getLocationRefIdForParameters( + return $this->getLocationRefIdForParameters( $evento_event->getDepartment(), $evento_event->getKind(), $event_year ); } catch (\ilEventoImportEventLocationNotFoundException $e) { - if ($create_year_cat_if_not_existing) { - $ref_id = $this->tryToCreateLocationForEventoEvent( - $evento_event->getDepartment(), - $evento_event->getKind(), - $event_year - ); - } else { - $ref_id = null; + if (!$create_year_cat_if_not_existing) { + return null; } + + return $this->tryToCreateLocationForEventoEvent( + $evento_event->getDepartment(), + $evento_event->getKind(), + $event_year + ); } catch (\Exception $e) { - $ref_id = null; + return null; } - - return $ref_id; } private function tryToCreateLocationForEventoEvent(string $department_short_name, string $kind, int $year) : ?int @@ -83,19 +81,21 @@ private function tryToCreateLocationForEventoEvent(string $department_short_name $kind ); - if (!is_null($kind_ref_id)) { - $cat_ref_id = $this->event_location_builder->createNewLocationObjectAndReturnRefId($kind_ref_id, "$year"); + if (is_null($kind_ref_id)) { + return null; + } - $this->locations_repo->addNewLocation( - $department_short_name, - $kind, - $year, - $cat_ref_id - ); - $this->locations[$department_short_name][$kind][$year] = $cat_ref_id; + $cat_ref_id = $this->event_location_builder->createNewLocationObjectAndReturnRefId($kind_ref_id, "$year"); - return $cat_ref_id; - } + $this->locations_repo->addNewLocation( + $department_short_name, + $kind, + $year, + $cat_ref_id + ); + $this->locations[$department_short_name][$kind][$year] = $cat_ref_id; + + return $cat_ref_id; } catch (\Exception $e) { } @@ -106,7 +106,7 @@ private function getMappedDepartmentCatName(string $department_short) : string { $hardcoded_locations = [ "HSLU" => "Hochschule Luzern", - "DK" => "Design & Kunst", + "DK" => "Design Film Kunst", "I" => "Informatik", "M" => "Musik", "SA" => "Soziale Arbeit", diff --git a/classes/config/ImporterApiSettings.php b/classes/config/ImporterApiSettings.php index d4047af..7142031 100644 --- a/classes/config/ImporterApiSettings.php +++ b/classes/config/ImporterApiSettings.php @@ -4,6 +4,17 @@ class ImporterApiSettings { + private const CONF_API_URI = 'crevento_api_uri'; + private const CONF_API_AUTH_KEY = 'crevento_api_auth_key'; + private const CONF_API_AUTH_SECRET = 'crevento_api_auth_secret'; + private const CONF_API_PAGE_SIZE = 'crevento_api_page_size'; + private const CONF_API_MAX_PAGES = 'crevento_api_max_pages'; + private const CONF_API_TIMEOUT_AFTER_REQUEST = 'crevento_api_timeout_after_request'; + private const CONF_API_TIMEOUT_FAILED_REQUEST = 'crevento_api_timeout_failed_request'; + private const CONF_API_MAX_RETRIES = 'crevento_api_max_retries'; + + private $settings; + private string $url; private string $api_key; private string $api_secret; @@ -15,88 +26,107 @@ class ImporterApiSettings public function __construct(\ilSetting $settings) { - $this->url = $settings->get(CronConfigForm::CONF_API_URI, ''); - $this->api_key = $settings->get(CronConfigForm::CONF_API_AUTH_KEY, ''); - $this->api_secret = $settings->get(CronConfigForm::CONF_API_AUTH_SECRET, ''); - $this->page_size = (int) $settings->get(CronConfigForm::CONF_API_PAGE_SIZE, '500'); - $this->max_pages = (int) $settings->get(CronConfigForm::CONF_API_MAX_PAGES, '-1'); - $this->timeout_after_request = (int) $settings->get(CronConfigForm::CONF_API_TIMEOUT_AFTER_REQUEST, '60'); - $this->timeout_failed_request = (int) $settings->get(CronConfigForm::CONF_API_TIMEOUT_FAILED_REQUEST, '60'); - $this->max_retries = (int) $settings->get(CronConfigForm::CONF_API_MAX_RETRIES, '3'); + $this->settings = $settings; + + $this->url = $settings->get(self::CONF_API_URI, ''); + $this->api_key = $settings->get(self::CONF_API_AUTH_KEY, ''); + $this->api_secret = $settings->get(self::CONF_API_AUTH_SECRET, ''); + $this->page_size = (int) $settings->get(self::CONF_API_PAGE_SIZE, '500'); + $this->max_pages = (int) $settings->get(self::CONF_API_MAX_PAGES, '-1'); + $this->timeout_after_request = (int) $settings->get(self::CONF_API_TIMEOUT_AFTER_REQUEST, '60'); + $this->timeout_failed_request = (int) $settings->get(self::CONF_API_TIMEOUT_FAILED_REQUEST, '60'); + $this->max_retries = (int) $settings->get(self::CONF_API_MAX_RETRIES, '3'); } - public function getUrl() : string + public function getUrl(): string { return $this->url; } - public function setUrl($url) : void + public function setUrl(string $url): void { $this->url = $url; } - public function getApikey() : string + public function getApiKey(): string { return $this->api_key; } - public function setApikey($api_key) : void + public function setApiKey(string $api_key): void { $this->api_key = $api_key; } - public function getApiSecret() : string + public function getApiSecret(): string { return $this->api_secret; } - public function getPageSize() : int + public function setApiSecret(string $api_secret): void + { + $this->api_secret = $api_secret; + } + + public function getPageSize(): int { return $this->page_size; } - public function setPageSize(int $page_size) : void + public function setPageSize(int $page_size): void { $this->page_size = $page_size; } - public function getMaxPages() : int + public function getMaxPages(): int { return $this->max_pages; } - public function setMaxPages(int $max_pages) : void + public function setMaxPages(int $max_pages): void { $this->max_pages = $max_pages; } - public function getTimeoutAfterRequest() : int + public function getTimeoutAfterRequest(): int { return $this->timeout_after_request; } - public function setTimeoutAfterRequest(int $timeout_after_request) : void + public function setTimeoutAfterRequest(int $timeout_after_request): void { $this->timeout_after_request = $timeout_after_request; } - public function getTimeoutFailedRequest() : int + public function getTimeoutFailedRequest(): int { return $this->timeout_failed_request; } - public function setTimeoutFailedRequest(int $timeout_failed_request) : void + public function setTimeoutFailedRequest(int $timeout_failed_request): void { $this->timeout_failed_request = $timeout_failed_request; } - public function getMaxRetries() : int + public function getMaxRetries(): int { return $this->max_retries; } - public function setMaxRetries(int $max_retries) : void + public function setMaxRetries(int $max_retries): void { $this->max_retries = $max_retries; } + + public function saveCurrentConfigurationToSettings(): void + { + $this->settings->set(self::CONF_API_URI, $this->url); + $this->settings->set(self::CONF_API_AUTH_KEY, $this->api_key); + $this->settings->set(self::CONF_API_AUTH_SECRET, $this->api_secret); + $this->settings->set(self::CONF_API_PAGE_SIZE, (string) $this->page_size); + $this->settings->set(self::CONF_API_MAX_PAGES, (string) $this->max_pages); + $this->settings->set(self::CONF_API_TIMEOUT_AFTER_REQUEST, (string) $this->timeout_after_request); + $this->settings->set(self::CONF_API_TIMEOUT_FAILED_REQUEST, (string) $this->timeout_failed_request); + $this->settings->set(self::CONF_API_MAX_RETRIES, (string) $this->max_retries); + } } diff --git a/classes/config/local_roles/LocalVisitorRoleFactory.php b/classes/config/local_roles/LocalVisitorRoleFactory.php index 9f38e40..2b0ecb4 100644 --- a/classes/config/local_roles/LocalVisitorRoleFactory.php +++ b/classes/config/local_roles/LocalVisitorRoleFactory.php @@ -59,8 +59,8 @@ private function getRoleTemplateId() : int if (!is_null($rolt_id)) { return $rolt_id; - } else { - throw new \ilException("Error in finding the course member role template to base the visitor role on"); } + + throw new \ilException("Error in finding the course member role template to base the visitor role on"); } } \ No newline at end of file diff --git a/classes/config/local_roles/LocalVisitorRoleManager.php b/classes/config/local_roles/LocalVisitorRoleManager.php index 2fce139..ad23297 100644 --- a/classes/config/local_roles/LocalVisitorRoleManager.php +++ b/classes/config/local_roles/LocalVisitorRoleManager.php @@ -24,14 +24,15 @@ public function getLocalVisitorRoleByDepartmentAndKind(string $department_name, return $this->local_role_repo->getVisitorRoleByDepartmentAndKind($department_name, $kind_name); } - public function configLocalRoleByDepartmentAndKind(string $department_name, string $kind_name, int $location_ref_id, string $dep_api_name) + public function configLocalRoleByDepartmentAndKind(string $department_name, string $kind_name, int $location_ref_id, string $dep_api_name): void { $role = $this->local_role_repo->getVisitorRoleByDepartmentAndKind($department_name, $kind_name); if (!is_null($role)) { $this->local_role_repo->updateDepartmentApiName($role, $dep_api_name); - } else { - $this->createNewLocalVisitorRole($department_name, $kind_name, $location_ref_id, $dep_api_name); + return; } + + $this->createNewLocalVisitorRole($department_name, $kind_name, $location_ref_id, $dep_api_name); } public function unconfigLocalRoleByDepartmentAndKind(string $department_name, string $kind_name, int $location_ref_id) diff --git a/classes/config/locations/BaseLocationConfiguration.php b/classes/config/locations/BaseLocationConfiguration.php index 3cfcf42..6d48e60 100644 --- a/classes/config/locations/BaseLocationConfiguration.php +++ b/classes/config/locations/BaseLocationConfiguration.php @@ -6,7 +6,7 @@ class BaseLocationConfiguration { - private const CONF_LOCATIONS = 'crevento_location_settings'; + public const CONF_LOCATIONS = 'crevento_location_settings'; private const CONF_KEY_DEPARTMENTS = 'departments'; private const CONF_KEY_KINDS = 'kinds'; @@ -24,16 +24,17 @@ public function __construct(\ilSetting $settings) if (is_null($json)) { $this->configured_departments = []; $this->configured_kinds = []; - } else { - $location_settings = json_decode($json, true); - if (!is_null($location_settings)) { - if(isset($location_settings[self::CONF_KEY_DEPARTMENTS]) && is_array($location_settings[self::CONF_KEY_DEPARTMENTS])) { - $this->setDepartmentLocationList($location_settings[self::CONF_KEY_DEPARTMENTS]); - } + return; + } - if (isset($location_settings[self::CONF_KEY_KINDS]) && is_array($location_settings[self::CONF_KEY_KINDS])) { - $this->setKindLocationList($location_settings[self::CONF_KEY_KINDS]); - } + $location_settings = json_decode($json, true); + if (!is_null($location_settings)) { + if (isset($location_settings[self::CONF_KEY_DEPARTMENTS]) && is_array($location_settings[self::CONF_KEY_DEPARTMENTS])) { + $this->setDepartmentLocationList($location_settings[self::CONF_KEY_DEPARTMENTS]); + } + + if (isset($location_settings[self::CONF_KEY_KINDS]) && is_array($location_settings[self::CONF_KEY_KINDS])) { + $this->setKindLocationList($location_settings[self::CONF_KEY_KINDS]); } } } diff --git a/classes/config/locations/EventLocationCategoryBuilder.php b/classes/config/locations/EventLocationCategoryBuilder.php index b2a782d..5294719 100644 --- a/classes/config/locations/EventLocationCategoryBuilder.php +++ b/classes/config/locations/EventLocationCategoryBuilder.php @@ -38,10 +38,9 @@ public function createNewLocationObjectAndReturnRefId(int $parent_ref_id, string // inherit parents content style, if not individual $parent_id = \ilObject::_lookupObjId($parent_ref_id); $style_id = \ilObjStyleSheet::lookupObjectStyle($parent_id); - if ($style_id > 0) { - if (\ilObjStyleSheet::_lookupStandard($style_id)) { - \ilObjStyleSheet::writeStyleUsage($new_category->getId(), $style_id); - } + if ($style_id > 0 + && \ilObjStyleSheet::_lookupStandard($style_id)) { + \ilObjStyleSheet::writeStyleUsage($new_category->getId(), $style_id); } } catch (\Exception $e) { } diff --git a/classes/config/locations/EventLocationsRepository.php b/classes/config/locations/EventLocationsRepository.php index 6dab0cc..12a1b4d 100644 --- a/classes/config/locations/EventLocationsRepository.php +++ b/classes/config/locations/EventLocationsRepository.php @@ -39,11 +39,19 @@ private function addToCache(int $ref_id, string $department, string $kind, int $ { if (!isset($this->cache[$department])) { $this->cache[$department] = [$kind => [$year => $ref_id]]; + return; } elseif (!isset($this->cache[$department][$kind])) { $this->cache[$department][$kind] = [$year => $ref_id]; } else { $this->cache[$department][$kind][$year] = $ref_id; } + + if (!isset($this->cache[$department][$kind])) { + $this->cache[$department][$kind] = [$year => $ref_id]; + return; + } + + $this->cache[$department][$kind][$year] = $ref_id; } private function checkCache(string $department, string $kind, int $year) : ?int @@ -52,9 +60,9 @@ private function checkCache(string $department, string $kind, int $year) : ?int && isset($this->cache[$department][$kind]) && isset($this->cache[$department][$kind][$year])) { return $this->cache[$department][$kind][$year]; - } else { - return null; } + + return null; } public function getRefIdForEventoObject(EventoEvent $evento_event) : ?int @@ -113,13 +121,20 @@ public function getAllLocationsAsHirarchicalArray() : array if (!isset($locations[$dep])) { $locations[$dep] = [$kind => [$year => $ref]]; - } elseif (!isset($locations[$dep][$kind])) { + continue; + } + + if (!isset($locations[$dep][$kind])) { $locations[$dep][$kind] = [$year => $ref]; - } elseif (!isset($locations[$dep][$kind][$year])) { - $locations[$dep][$kind][$year] = $ref; - } else { + continue; + } + + if (!isset($locations[$dep][$kind][$year])) { $locations[$dep][$kind][$year] = $ref; + continue; } + + $locations[$dep][$kind][$year] = $ref; } return $locations; diff --git a/classes/import/EventAndMembershipImportTask.php b/classes/import/EventAndMembershipImportTask.php index 25b856b..c2e8078 100644 --- a/classes/import/EventAndMembershipImportTask.php +++ b/classes/import/EventAndMembershipImportTask.php @@ -60,6 +60,7 @@ private function importEvents() : void try { $this->importNextEventPage(); } catch (\ilEventoImportCommunicationException $e) { + $this->logger->logException('Importing Event Page', $e->getMessage(), $e->getTraceAsString()); throw $e; } catch (\Exception $e) { $this->logger->logException('Importing Event Page', $e->getMessage(), $e->getTraceAsString()); @@ -80,10 +81,11 @@ private function deleteInEventoRemovedEvents() if (is_null($result)) { $action = $this->event_import_action_decider->determineDeleteAction($ilias_evento_event); $action->executeAction(); - } else { - $this->evento_event_obj_repo->registerEventAsDelivered($result->getEventoId()); - $this->logger->logException('Deleting Event', 'Event which was not delivered during "Import Events" can be requested by ID. Therefore it still exsits. Evento ID = ' . $ilias_evento_event->getEventoEventId()); + continue; } + + $this->evento_event_obj_repo->registerEventAsDelivered($result->getEventoId()); + $this->logger->logException('Deleting Event', 'Event which was not delivered during "Import Events" can be requested by ID. Therefore it still exsits. Evento ID = ' . $ilias_evento_event->getEventoEventId()); } catch (\Exception $e) { $this->logger->logException('Deleting Event', 'Exception on deleting event with evento_id ' . $ilias_evento_event->getEventoEventId() . ', exception message: ' . $e->getMessage()); @@ -94,23 +96,24 @@ private function deleteInEventoRemovedEvents() private function importNextEventPage() : void { foreach ($this->evento_importer->fetchNextEventDataSet() as $data_set) { + $eventoid = 0; try { $evento_event = new EventoEvent($data_set); - + $eventoid = $evento_event->getEventoId(); $action = $this->event_import_action_decider->determineImportAction($evento_event); $action->executeAction(); } catch (\ilEventoImportApiDataException $e) { $data = $e->getApiData(); + + $evento_id_msg = "Evento ID not given"; if (isset($data[EventoEvent::JSON_ID])) { $id = $data[EventoEvent::JSON_ID]; $evento_id_msg = "Evento ID: $id"; - } else { - $evento_id_msg = "Evento ID not given"; } $this->logger->logException('API Data Exception - Importing Event', $evento_id_msg . ' - ' . $e->getMessage()); } catch (\Exception $e) { - $this->logger->logException(get_class($e) . ' - Importing Event', $e->getMessage()); + $this->logger->logException(get_class($e) . ' - Importing Event - eventoid: ' . var_export($eventoid, true), $e->getMessage()); } } } diff --git a/classes/import/ImportTaskFactory.php b/classes/import/ImportTaskFactory.php index 734b623..ecb52fe 100644 --- a/classes/import/ImportTaskFactory.php +++ b/classes/import/ImportTaskFactory.php @@ -38,7 +38,11 @@ class ImportTaskFactory private Logger $logger; private \ilTree $tree; - public function __construct(ConfigurationManager $config_manager, \ilDBInterface $db, \ilTree $tree, RBACServices $rbac) + public function __construct( + ConfigurationManager $config_manager, + \ilDBInterface $db, + \ilTree $tree, + RBACServices $rbac) { $this->config_manager = $config_manager; $this->db = $db; @@ -50,7 +54,7 @@ public function __construct(ConfigurationManager $config_manager, \ilDBInterface public function buildUserImport(EventoUserImporter $user_importer, EventoUserPhotoImporter $user_photo_importer) : UserImportTask { $user_settings = $this->config_manager->getDefaultUserConfiguration(); - $ilias_user_service = new IliasUserServices($user_settings, $this->db, $this->rbac); + $ilias_user_service = new IliasUserServices($user_settings, $this->db, $this->rbac->review(), $this->rbac->admin()); $evento_user_repo = new IliasEventoUserRepository($this->db); return new UserImportTask( @@ -90,7 +94,7 @@ public function buildEventImport(EventoEventImporter $event_importer) : EventAnd new MembershipablesEventInTreeSeeker($this->tree), new IliasEventoEventMembershipRepository($this->db), new UserManager( - new IliasUserServices($user_settings, $this->db, $this->rbac), + new IliasUserServices($user_settings, $this->db, $this->rbac->review(), $this->rbac->admin()), new IliasEventoUserRepository($this->db), $user_settings, $this->logger @@ -132,7 +136,7 @@ public function buildAdminImport(EventoAdminImporter $admin_importer) : AdminImp new HiddenAdminRepository($this->db), new MembershipablesEventInTreeSeeker($this->tree), new UserManager( - new IliasUserServices($user_settings, $this->db, $this->rbac), + new IliasUserServices($user_settings, $this->db, $this->rbac->review(), $this->rbac->admin()), new IliasEventoUserRepository($this->db), $user_settings, $this->logger @@ -151,7 +155,7 @@ public function buildLocalVisitorImport(EventoEmployeeImporter $employee_import) $employee_import, new LocalVisitorRoleRepository($this->db), new UserManager( - new IliasUserServices($user_settings, $this->db, $this->rbac), + new IliasUserServices($user_settings, $this->db, $this->rbac->review(), $this->rbac->admin()), new IliasEventoUserRepository($this->db), $user_settings, $this->logger diff --git a/classes/import/Logger.php b/classes/import/Logger.php index 244c6ba..e5490f1 100644 --- a/classes/import/Logger.php +++ b/classes/import/Logger.php @@ -29,8 +29,6 @@ class Logger { private \ilDBInterface $ilDB; - #const CREVENTO_SUB_CREATED = 101; - #const CREVENTO_SUB_UPDATED = 102; const CREVENTO_SUB_REMOVED = 103; const CREVENTO_SUB_NEWLY_ADDED = 104; const CREVENTO_SUB_ALREADY_ASSIGNED = 105; @@ -79,6 +77,7 @@ class Logger const CREVENTO_USR_UPDATED = 302; const CREVENTO_USR_RENAMED = 303; const CREVENTO_USR_CONVERTED = 304; + const CREVENTO_USR_REMOVED = 305; const CREVENTO_USR_NOTICE_CONFLICT = 313; const CREVENTO_USR_ERROR_ERROR = 324; @@ -91,7 +90,7 @@ public function __construct(ilDBInterface $db) $this->ilDB = $db; } - public function logUserImport($log_info_code, $evento_id, $username, $import_data) + public function logUserImport($log_info_code, $evento_id, $username, $import_data): void { if ($log_info_code < 300 || $log_info_code >= 400) { $this->logException( @@ -117,28 +116,29 @@ public function logUserImport($log_info_code, $evento_id, $username, $import_dat 'update_info_code' => [\ilDBConstants::T_INTEGER, $log_info_code], ] ); - } else { - $this->ilDB->update( - self::TABLE_LOG_USERS, - [ - 'usrname' => [\ilDBConstants::T_TEXT, $username], - 'last_import_data' => [\ilDBConstants::T_TEXT, json_encode($import_data)], - 'last_import_date' => [\ilDBConstants::T_DATETIME, date("Y-m-d H:i:s")], - 'update_info_code' => [\ilDBConstants::T_INTEGER, $log_info_code], - ], - [ - 'evento_id' => [\ilDBConstants::T_INTEGER, $evento_id] - ] - ); + return; } + + $this->ilDB->update( + self::TABLE_LOG_USERS, + [ + 'usrname' => [\ilDBConstants::T_TEXT, $username], + 'last_import_data' => [\ilDBConstants::T_TEXT, json_encode($import_data)], + 'last_import_date' => [\ilDBConstants::T_DATETIME, date("Y-m-d H:i:s")], + 'update_info_code' => [\ilDBConstants::T_INTEGER, $log_info_code], + ], + [ + 'evento_id' => [\ilDBConstants::T_INTEGER, $evento_id] + ] + ); } - public function logException($operation, $message, string $trace_as_string = '') + public function logException($operation, $message, string $trace_as_string = ''): void { ilLoggerFactory::getRootLogger()->error("EventoImport failed while $operation due to '$message' " . $trace_as_string); } - public function logEventImport(int $log_info_code, int $evento_id, ?int $ref_id, array $import_data) + public function logEventImport(int $log_info_code, int $evento_id, ?int $ref_id, array $import_data): void { if ($log_info_code < 200 || $log_info_code >= 300) { $this->logException( @@ -153,23 +153,23 @@ public function logEventImport(int $log_info_code, int $evento_id, ?int $ref_id, * This is necessary, since the serialization of imported_data can be over 4000 chars (max. string length) with long user lists. * The alternative would be to convert the column from varchar to clob. But this approach should work pretty good as well. */ + $employees_list = []; if (isset($import_data['api_data']) && isset($import_data['api_data'][EventoEvent::JSON_EMPLOYEES])) { $employees_list = $import_data['api_data'][EventoEvent::JSON_EMPLOYEES]; unset($import_data['api_data'][EventoEvent::JSON_EMPLOYEES]); - } else { - $employees_list = []; } + $employees_list_as_str = json_encode($employees_list); if (mb_strlen($employees_list_as_str) > 3995) { $employees_list_as_str = mb_substr($employees_list_as_str, 0, 3995); } + $students_list = []; if (isset($import_data['api_data']) && isset($import_data['api_data'][EventoEvent::JSON_STUDENTS])) { $students_list = $import_data['api_data'][EventoEvent::JSON_STUDENTS]; unset($import_data['api_data'][EventoEvent::JSON_STUDENTS]); - } else { - $students_list = []; } + $students_list_as_str = json_encode($students_list); if (mb_strlen($students_list_as_str) > 3995) { $students_list_as_str = mb_substr($students_list_as_str, 0, 3995); @@ -193,25 +193,26 @@ public function logEventImport(int $log_info_code, int $evento_id, ?int $ref_id, 'last_import_students' => [\ilDBConstants::T_TEXT, $students_list_as_str] ] ); - } else { - $this->ilDB->update( - self::TABLE_LOG_EVENTS, - [ - 'ref_id' => [\ilDBConstants::T_INTEGER, $ref_id], - 'last_import_data' => [\ilDBConstants::T_TEXT, json_encode($import_data)], - 'last_import_date' => [\ilDBConstants::T_DATETIME, date("Y-m-d H:i:s")], - 'update_info_code' => [\ilDBConstants::T_INTEGER, $log_info_code], - 'last_import_employees' => [\ilDBConstants::T_TEXT, $employees_list_as_str], - 'last_import_students' => [\ilDBConstants::T_TEXT, $students_list_as_str] - ], - [ - 'evento_id' => [\ilDBConstants::T_INTEGER, $evento_id] - ] - ); + return; } + + $this->ilDB->update( + self::TABLE_LOG_EVENTS, + [ + 'ref_id' => [\ilDBConstants::T_INTEGER, $ref_id], + 'last_import_data' => [\ilDBConstants::T_TEXT, json_encode($import_data)], + 'last_import_date' => [\ilDBConstants::T_DATETIME, date("Y-m-d H:i:s")], + 'update_info_code' => [\ilDBConstants::T_INTEGER, $log_info_code], + 'last_import_employees' => [\ilDBConstants::T_TEXT, $employees_list_as_str], + 'last_import_students' => [\ilDBConstants::T_TEXT, $students_list_as_str] + ], + [ + 'evento_id' => [\ilDBConstants::T_INTEGER, $evento_id] + ] + ); } - public function logEventMembership(int $log_info_code, int $evento_event_id, int $evento_user_id, int $role_type = -1) + public function logEventMembership(int $log_info_code, int $evento_event_id, int $evento_user_id, int $role_type = -1): void { if ($log_info_code < 100 || $log_info_code >= 200) { $this->logException( @@ -237,25 +238,26 @@ public function logEventMembership(int $log_info_code, int $evento_event_id, int 'update_info_code' => [\ilDBConstants::T_INTEGER, $log_info_code], ] ); - } else { - $values = [ - 'last_import_date' => [\ilDBConstants::T_DATETIME, date("Y-m-d H:i:s")], - 'update_info_code' => [\ilDBConstants::T_INTEGER, $log_info_code], - ]; + return; + } - if ($role_type != -1) { - $values = ['role_type' => [\ilDBConstants::T_INTEGER, $role_type]]; - } + $values = [ + 'last_import_date' => [\ilDBConstants::T_DATETIME, date("Y-m-d H:i:s")], + 'update_info_code' => [\ilDBConstants::T_INTEGER, $log_info_code], + ]; - $this->ilDB->update( - self::TABLE_LOG_MEMBERSHIPS, - $values, - [ - 'evento_event_id' => [\ilDBConstants::T_INTEGER, $evento_event_id], - 'evento_user_id' => [\ilDBConstants::T_INTEGER, $evento_user_id] - ] - ); + if ($role_type != -1) { + $values = ['role_type' => [\ilDBConstants::T_INTEGER, $role_type]]; } + + $this->ilDB->update( + self::TABLE_LOG_MEMBERSHIPS, + $values, + [ + 'evento_event_id' => [\ilDBConstants::T_INTEGER, $evento_event_id], + 'evento_user_id' => [\ilDBConstants::T_INTEGER, $evento_user_id] + ] + ); } catch (\Exception $e) { $this->logException('Log Membership', $e->getMessage() . $e->getTraceAsString()); } diff --git a/classes/import/UserImportTask.php b/classes/import/UserImportTask.php index d39de56..f50bba6 100644 --- a/classes/import/UserImportTask.php +++ b/classes/import/UserImportTask.php @@ -49,7 +49,6 @@ public function run() : void { $this->importUsers(); $this->convertDeletedAccounts(); - $this->setUserTimeLimits(); } private function importUsers() : void @@ -75,11 +74,10 @@ private function importNextUserPage() : void $action->executeAction(); } catch (\ilEventoImportApiDataException $e) { $data = $e->getApiData(); + $evento_id_msg = "Evento ID not given"; if (isset($data[EventoUser::JSON_ID])) { $id = $data[EventoUser::JSON_ID]; $evento_id_msg = "Evento ID: $id"; - } else { - $evento_id_msg = "Evento ID not given"; } $this->evento_logger->logException('API Data Exception - Importing Event', $evento_id_msg . ' - ' . $e->getMessage()); } catch (\Exception $e) { @@ -94,7 +92,7 @@ private function importNextUserPage() : void * by itself. For this reason, every imported account has a last-imported-timestamp. With this value, users which have not * been imported since a longer time can be found. */ - private function convertDeletedAccounts() + private function convertDeletedAccounts(): void { $list = $this->evento_user_repo->getUsersWithLastImportOlderThanGivenDays(32, IliasEventoUserRepository::TYPE_HSLU_AD); @@ -107,9 +105,10 @@ private function convertDeletedAccounts() if (is_null($result)) { $action = $this->user_import_action_decider->determineDeleteAction($ilias_user_id, $evento_id); $action->executeAction(); - } else { - $this->evento_user_repo->registerUserAsDelivered($result->getEventoId()); - $this->evento_logger->logException('Deleting User', 'User which was not delivered during "Import Users" can be requested by ID. Therefore it still exsits. Evento ID = ' . $evento_id); + } + else { + $this->evento_user_repo->registerUserAsDelivered($result->getEventoId(), $ilias_user_id); + $this->evento_logger->logException('Deleting User', 'User which was not delivered during "Import Users" can be requested by ID. Therefore it still exists. Evento ID = ' . $evento_id); } } catch (\Exception $e) { $this->evento_logger->logException('Convert Deleted User Accounts', "Exception on deleting user with evento_id $ilias_user_id" @@ -117,13 +116,4 @@ private function convertDeletedAccounts() } } } - - /** - * User accounts which don't have a time limitation are limited to - * two years since their creation. - */ - private function setUserTimeLimits() - { - $this->ilias_user_service->setUserTimeLimits(); - } } diff --git a/classes/import/action/EventImportActionDecider.php b/classes/import/action/EventImportActionDecider.php index a31aec1..6662679 100644 --- a/classes/import/action/EventImportActionDecider.php +++ b/classes/import/action/EventImportActionDecider.php @@ -98,16 +98,16 @@ public function determineDeleteAction(IliasEventoEvent $ilias_evento_event) return $this->event_action_factory->unmarkExistingIliasObjFromEventoEvents($ilias_evento_event); } - if ($ilias_evento_event->isSubGroupEvent()) { - $parent_event = $this->event_manager->getParentEventForIliasEventoEvent($ilias_evento_event); + if (!$ilias_evento_event->isSubGroupEvent()) { + return $this->event_action_factory->deleteSingleCourseEvent($ilias_evento_event); + } - if (!is_null($parent_event) && $this->event_manager->getNumberOfChildEventsForParentEvent($parent_event) <= 1) { - return $this->event_action_factory->deleteEventGroupWithParentEventCourse($ilias_evento_event, $parent_event); - } + $parent_event = $this->event_manager->getParentEventForIliasEventoEvent($ilias_evento_event); - return $this->event_action_factory->deleteGroupEventInCourse($ilias_evento_event); + if (!is_null($parent_event) && $this->event_manager->getNumberOfChildEventsForParentEvent($parent_event) <= 1) { + return $this->event_action_factory->deleteEventGroupWithParentEventCourse($ilias_evento_event, $parent_event); } - return $this->event_action_factory->deleteSingleCourseEvent($ilias_evento_event); + return $this->event_action_factory->deleteGroupEventInCourse($ilias_evento_event); } } diff --git a/classes/import/action/UserImportActionDecider.php b/classes/import/action/UserImportActionDecider.php index efa3fad..6a53ffd 100644 --- a/classes/import/action/UserImportActionDecider.php +++ b/classes/import/action/UserImportActionDecider.php @@ -13,8 +13,11 @@ class UserImportActionDecider private UserActionFactory $action_factory; private IliasEventoUserRepository $evento_user_repo; - public function __construct(IliasUserServices $ilias_user_service, IliasEventoUserRepository $evento_user_repo, UserActionFactory $action_factory) - { + public function __construct( + IliasUserServices $ilias_user_service, + IliasEventoUserRepository $evento_user_repo, + UserActionFactory $action_factory + ) { $this->ilias_user_service = $ilias_user_service; $this->evento_user_repo = $evento_user_repo; $this->action_factory = $action_factory; @@ -23,192 +26,249 @@ public function __construct(IliasUserServices $ilias_user_service, IliasEventoUs private function addUserToEventoIliasMappingTable( EventoUser $evento_user, int $ilias_user_id - ) { - $ilias_user = $this->ilias_user_service->getExistingIliasUserObjectById($ilias_user_id); - $this->evento_user_repo->addNewEventoIliasUserByEventoUser($evento_user, $ilias_user, IliasEventoUserRepository::TYPE_HSLU_AD); + ): void { + $this->evento_user_repo->addNewEventoIliasUser($evento_user->getEventoId(), $ilias_user_id, IliasEventoUserRepository::TYPE_HSLU_AD); } - public function determineImportAction(EventoUser $evento_user) : EventoImportAction + public function determineImportAction(EventoUser $evento_user): EventoImportAction { $matched_user_id = $this->evento_user_repo->getIliasUserIdByEventoId($evento_user->getEventoId()); - if (!is_null($matched_user_id)) { - $current_login_of_matched_user = $this->ilias_user_service->getLoginByUserId($matched_user_id); + if ($matched_user_id === null) { + return $this->matchToIliasUsersAndDetermineAction($evento_user); + } + + $users_to_rename = []; + $found_by = ''; + $current_login_of_matched_user = $this->ilias_user_service->getLoginByUserId($matched_user_id); + // Check if login of delivered user has changed AND the changed login name is already taken + if ($current_login_of_matched_user != $evento_user->getLoginName() + && ($additional_user_id_by_login = $this->ilias_user_service->getUserIdByLogin($evento_user->getLoginName())) > 0 + ) { + $users_to_rename[] = $this->ilias_user_service->getExistingIliasUserObjectById( + $additional_user_id_by_login + ); + $found_by = 'login'; + } + + $current_external_account_matched_user = $this->ilias_user_service->getExternalAccountByUserId($matched_user_id); + if ($evento_user->getEduId() !== null + && $evento_user->getEduId() !== '' + && $current_external_account_matched_user !== $evento_user->getEduId() + && ($additional_user_by_external_account = $this->ilias_user_service->getUserIdByExternalAccount($evento_user->getEduId())) > 0 + ) { + $users_to_rename[] = $this->ilias_user_service->getExistingIliasUserObjectById( + $additional_user_by_external_account + ); + $found_by = $found_by === '' ? 'external_account' : 'login + external_account'; + } + + if ($users_to_rename !== []) { + return $this->action_factory->buildRenameExistingAndUpdateDeliveredAction( + $evento_user, + $matched_user_id, + $users_to_rename, + $found_by + ); + } + + return $this->action_factory->buildUpdateAction($evento_user, $matched_user_id); + } - // Check if login of delivered user has changed AND the changed login name is already taken - if ($current_login_of_matched_user != $evento_user->getLoginName() - && $this->ilias_user_service->getUserIdByLogin($evento_user->getLoginName()) > 0 + private function matchToIliasUsersAndDetermineAction( + EventoUser $evento_user + ): EventoImportAction { + $data['id_by_external_account'] = $this->ilias_user_service->getUserIdByExternalAccount($evento_user->getEduId()); + $data['id_by_login'] = $this->ilias_user_service->getUserIdByLogin($evento_user->getLoginName()); + $data['ids_by_matriculation'] = $this->ilias_user_service->getUserIdsByEventoId($evento_user->getEventoId()); + $data['ids_by_email'] = $this->ilias_user_service->getUserIdsByEmailAddresses($evento_user->getEmailList()); + + /** + * We couldn't find a user account neither by matriculation, login + * nor e-mail + * --> Insert new user account. + */ + if ($data['ids_by_matriculation'] === [] + && $data['id_by_external_account'] === 0 + && $data['id_by_login'] === 0 + && $data['ids_by_email'] === []) { + return $this->action_factory->buildCreateAction($evento_user); + } + + /** + * This should never happen, but just to be sure: We found more than + * one account with the same matriculation. + * --> We don't know what to do with it and thus report an error. + */ + if (count($data['ids_by_matriculation']) > 1) { + return $this->action_factory->buildReportError( + $evento_user, + $data + ); + } + + /** + * We do have this account exactly as she should be or we have at least + * a user with correct matriculation and the corresponding external_account + * login are still free to be used + * --> Update + */ + if (count($data['ids_by_matriculation']) === 1 + && ($data['ids_by_matriculation'][0] === $data['id_by_external_account'] + || $data['id_by_external_account'] === 0) + && ($data['ids_by_matriculation'][0] === $data['id_by_login'] + || $data['id_by_login'] === 0) ) { - $id_of_user_to_rename = $this->ilias_user_service->getUserIdByLogin($evento_user->getLoginName()); - $user_to_rename = $this->ilias_user_service->getExistingIliasUserObjectById($id_of_user_to_rename); + return $this->action_factory->buildUpdateAction( + $evento_user, + $data['ids_by_matriculation'][0] + ); + } + + /** + * We do have an account with the corresponding matriculation, but sadly + * the external account and or the login are taken by another account + * (as all other cases have been filtered away by the previous condition). + * --> Remove external account from conflicting account, deactivate + * conflicting account, then update new account. + */ + if (count($data['ids_by_matriculation']) === 1) { + $user_objs = []; + if ($data['id_by_external_account'] !== 0) { + $user_objs['by_external_account'] = $this->ilias_user_service->getExistingIliasUserObjectById($data['id_by_external_account']); + } + + if ($data['id_by_login'] !== 0 + && $data['id_by_external_account'] !== $data['id_by_login']) { + $user_objs['by_login'] = $this->ilias_user_service->getExistingIliasUserObjectById($data['id_by_login']); + } + return $this->action_factory->buildRenameExistingAndUpdateDeliveredAction( + $evento_user, + $data['ids_by_matriculation'][0], + $user_objs, + 'login' + ); + } + + /** + * We didn't find an account with the corresponding matriculation, but + * we found an account with the corresponding external account or a + * corresponding login or we found one account with a corresponding + * external account and the same corresponding login. + */ + if ($data['id_by_external_account'] !== 0 + && $data['id_by_login'] === 0 + || $data['id_by_login'] !== 0 + && $data['id_by_external_account'] === 0 + || $data['id_by_external_account'] !== 0 + && $data['id_by_login'] !== 0 + && $data['id_by_external_account'] === $data['id_by_external_account']) { + $found_user_id = $data['id_by_external_account'] !== 0 ? + $data['id_by_external_account'] : $data['id_by_login']; + + return $this->buildActionForUserId($found_user_id, $evento_user); + } + + /** + * We didn't find an account with the corresponding matriculation, but + * we found two different accounts: one with the corresponding external + * account and one with a corresponding login. + */ + if ($data['id_by_external_account'] !== 0 + && $data['id_by_login'] !== 0 + && $data['id_by_external_account'] !== $data['id_by_login']) { + + $user_by_external_account = $this->ilias_user_service + ->getExistingIliasUserObjectById($data['id_by_external_account']); + $user_by_login = $this->ilias_user_service + ->getExistingIliasUserObjectById($data['id_by_login']); + + // The account by external account and/or the account by login have + // a matriculation of some kind that doesn't come from Evento. + // --> Bail + if ($user_by_external_account->getMatriculation() !== '' + && substr($user_by_external_account->getMatriculation(), 0, 7) !== 'Evento:' + || $user_by_login->getMatriculation() !== '' + && substr($user_by_login->getMatriculation(), 0, 7) !== 'Evento:') { + return $this->action_factory->buildReportConflict($evento_user); + } + + // The user account by external account has no matriculation + // --> Remove external account from account by login, deactivate + // account by login, then update account by external account. + if ($user_by_external_account->getMatriculation() === '') { + $this->addUserToEventoIliasMappingTable($evento_user, $data['id_by_external_account']); return $this->action_factory->buildRenameExistingAndUpdateDeliveredAction( $evento_user, - $matched_user_id, - $user_to_rename, + $data['id_by_external_account'], + [$user_by_login], 'login' ); } - return $this->action_factory->buildUpdateAction($evento_user, $matched_user_id); + // The user account by external account has a valid matriculation + // --> Remove external account from account by login and from account + // by external account, deactivate account by login and account + // by external account, then create new account. + return $this->action_factory->buildRenameExistingAndCreateNewAction( + $evento_user, + [$user_by_external_account, $user_by_login], + 'login' + ); } - return $this->matchToIliasUsersAndDetermineAction($evento_user); - } + /** + * We didn't find an account by neither corrsponding matriculation + * nor by the corresponding external account nor the corresponding + * login, but we found found exactly one, by the corresponding e-mail. + */ + if (count($data['ids_by_email']) === 1) { + return $this->buildActionForUserId($data['ids_by_email'][0], $evento_user); + } - private function matchToIliasUsersAndDetermineAction(EventoUser $evento_user) : EventoImportAction - { - $data['id_by_login'] = $this->ilias_user_service->getUserIdByLogin($evento_user->getLoginName()); - $data['ids_by_matriculation'] = $this->ilias_user_service->getUserIdsByEventoId($evento_user->getEventoId()); - $data['ids_by_email'] = $this->ilias_user_service->getUserIdsByEmailAddresses($evento_user->getEmailList()); + return $this->action_factory->buildReportError( + $evento_user, + $data + ); + } + private function buildActionForUserId( + int $found_user_id, + EventoUser $evento_user + ): EventoImportAction { + $found_user = $this->ilias_user_service + ->getExistingIliasUserObjectById($found_user_id); - if (count($data['ids_by_matriculation']) == 0 && - $data['id_by_login'] == 0 && - count($data['ids_by_email']) == 0) { + // The account by external account has a different evento number. + // --> Remove external account from conflicting account, deactivate + // conflicting account, then update new account. + if (substr($found_user->getMatriculation(), 0, 7) === 'Evento:') { + return $this->action_factory->buildRenameExistingAndCreateNewAction( + $evento_user, + [$found_user], + 'login' + ); + } - // We couldn't find a user account neither by - // matriculation, login nor e-mail - // --> Insert new user account. - return $this->action_factory->buildCreateAction($evento_user); - //EventoIliasUserMatchingResult::NoMatchingUserResult(); - } else { - if (count($data['ids_by_matriculation']) == 0 && - $data['id_by_login'] != 0) { - - // We couldn't find a user account by matriculation, but we found - // one by login. - - $user_obj_by_login = $this->ilias_user_service->getExistingIliasUserObjectById($data['id_by_login']); - - if (substr($user_obj_by_login->getMatriculation() ?? '', 0, 7) == 'Evento:') { - // The user account by login has a different evento number. - // --> Rename and deactivate conflicting account - // and then insert new user account. - $result = $this->action_factory->buildRenameExistingAndCreateNewAction( - $evento_user, - $user_obj_by_login, - 'login' - ); - } else { - if ($user_obj_by_login->getMatriculation() == $user_obj_by_login->getLogin()) { - // The user account by login has a matriculation from ldap - // --> Update user account. - $result = $this->action_factory->buildUpdateAction( - $evento_user, - $data['id_by_login'] - ); - $this->addUserToEventoIliasMappingTable($evento_user, $data['id_by_login']); - } else { - if (strlen($user_obj_by_login->getMatriculation() ?? '') != 0) { - // The user account by login has a matriculation of some kind - // --> Bail - $result = $this->action_factory->buildReportConflict($evento_user); - } else { - // The user account by login has no matriculation - // --> Update user account. - $result = $this->action_factory->buildUpdateAction( - $evento_user, - $data['id_by_login'] - ); - $this->addUserToEventoIliasMappingTable($evento_user, $data['id_by_login']); - } - } - } - } else { - if (count($data['ids_by_matriculation']) == 0 && - $data['id_by_login'] == 0 && - count($data['ids_by_email']) == 1) { - - // We couldn't find a user account by matriculation, but we found - // one by e-mail. - $user_obj_by_mail = $this->ilias_user_service->getExistingIliasUserObjectById($data['ids_by_email'][0]); - - if (substr($user_obj_by_mail->getMatriculation() ?? '', 0, 7) == 'Evento:') { - // The user account by e-mail has a different evento number. - // --> Rename and deactivate conflicting account - // and then insert new user account. - $result = $this->action_factory->buildRenameExistingAndCreateNewAction( - $evento_user, - $user_obj_by_mail, - 'mail' - ); - } else { - if (strlen($user_obj_by_mail->getMatriculation() ?? '') != 0) { - // The user account by login has a matriculation of some kind - // --> Bail - $result = $this->action_factory->buildReportConflict($evento_user); - } else { - // The user account by login has no matriculation - // --> Update user account. - $result = $this->action_factory->buildUpdateAction( - $evento_user, - $data['ids_by_email'][0] - ); - $this->addUserToEventoIliasMappingTable($evento_user, $data['ids_by_email'][0]); - } - } - } else { - if (count($data['ids_by_matriculation']) == 1 && - $data['id_by_login'] != 0 && - in_array($data['id_by_login'], $data['ids_by_matriculation'])) { - - // We found a user account by matriculation and by login. - // --> Update user account. - $result = $this->action_factory->buildUpdateAction( - $evento_user, - $data['ids_by_matriculation'][0] - ); - $this->addUserToEventoIliasMappingTable($evento_user, $data['ids_by_matriculation'][0]); - } else { - if (count($data['ids_by_matriculation']) == 1 && - $data['id_by_login'] == 0) { - - // We found a user account by matriculation but with the wrong login. - // The correct login is not taken by another user account. - // --> Update user account. - $result = $this->action_factory->buildUpdateAction( - $evento_user, - $data['ids_by_matriculation'][0] - ); - $this->addUserToEventoIliasMappingTable($evento_user, $data['ids_by_matriculation'][0]); - } else { - if (count($data['ids_by_matriculation']) == 1 && - $data['id_by_login'] != 0 && - !in_array($data['id_by_login'], $data['ids_by_matriculation'])) { - - // We found a user account by matriculation but with the wrong - // login. The login is taken by another user account. - // --> Rename and deactivate conflicting account, then update user account. - $user_obj_by_login = $this->ilias_user_service->getExistingIliasUserObjectById($data['id_by_login']); - $result = $this->action_factory->buildRenameExistingAndUpdateDeliveredAction( - $evento_user, - $data['ids_by_matriculation'][0], - $user_obj_by_login, - 'login' - ); - } else { - $result = $this->action_factory->buildReportError( - $evento_user, - $data - ); - } - } - } - } - } + // The account by external account has a matriculation of some kind + // --> Bail + if ($found_user->getMatriculation() !== '') { + return $this->action_factory->buildReportConflict($evento_user); } - return $result; + // The user account by external account has no matriculation + // --> Update + $this->addUserToEventoIliasMappingTable($evento_user, $found_user_id); + return $this->action_factory->buildUpdateAction( + $evento_user, + $found_user_id + ); } public function determineDeleteAction(int $ilias_id, int $evento_id) : EventoImportAction { $ilias_user_object = $this->ilias_user_service->getExistingIliasUserObjectById($ilias_id); - if ($this->ilias_user_service->userWasStudent($ilias_user_object)) { - return $this->action_factory->buildConvertUserAuth($ilias_user_object, $evento_id); - } else { - return $this->action_factory->buildConvertAuthAndDeactivateUser($ilias_user_object, $evento_id); - } + return $this->action_factory->buildRemoveConnectionToInstitution($ilias_user_object, $evento_id); } } diff --git a/classes/import/action/user/ConvertAndDeactivateUser.php b/classes/import/action/user/ConvertAndDeactivateUser.php deleted file mode 100644 index dbd49f8..0000000 --- a/classes/import/action/user/ConvertAndDeactivateUser.php +++ /dev/null @@ -1,49 +0,0 @@ -ilias_user = $ilias_user; - $this->evento_id = $evento_id; - $this->converted_auth_mode = $converted_auth_mode; - $this->user_manager = $user_manager; - $this->logger = $logger; - $this->log_info_code = Logger::CREVENTO_USR_CONVERTED; - $this->auth_mode = 'local'; - } - - public function executeAction() : void - { - $limit_until = new \DateTime(); - $this->ilias_user->setAuthMode('local'); - $this->ilias_user->setTimeLimitUntil($limit_until->getTimestamp()); - $this->ilias_user->update(); - - $this->user_manager->deleteEventoUserToIliasUserConnection($this->evento_id); - - $this->logger->logUserImport( - $this->log_info_code, - $this->evento_id, - $this->ilias_user->getLogin(), - [ - 'ilias_user_id' => $this->ilias_user->getId(), - 'new_auth_mode' => $this->auth_mode, - 'deactivate_after_convert' => true, - ] - ); - } -} diff --git a/classes/import/action/user/ConvertUserToLocalAuth.php b/classes/import/action/user/RemoveConnectionToInstitution.php similarity index 62% rename from classes/import/action/user/ConvertUserToLocalAuth.php rename to classes/import/action/user/RemoveConnectionToInstitution.php index 81635df..bd275fe 100644 --- a/classes/import/action/user/ConvertUserToLocalAuth.php +++ b/classes/import/action/user/RemoveConnectionToInstitution.php @@ -5,31 +5,34 @@ use EventoImport\import\Logger; use EventoImport\import\data_management\UserManager; -class ConvertUserToLocalAuth implements UserDeleteAction +class RemoveConnectionToInstitution implements UserConnectionRemoveAction { private \ilObjUser $ilias_user; private int $evento_id; - private string $converted_auth_mode; private UserManager $user_manager; private Logger $logger; private int $log_info_code; private string $auth_mode; - public function __construct(\ilObjUser $ilias_user, int $evento_id, string $converted_auth_mode, UserManager $user_manager, Logger $logger) - { + public function __construct( + \ilObjUser $ilias_user, + int $evento_id, + UserManager $user_manager, + Logger $logger + ) { $this->ilias_user = $ilias_user; $this->evento_id = $evento_id; - $this->converted_auth_mode = $converted_auth_mode; $this->user_manager = $user_manager; $this->logger = $logger; - $this->log_info_code = Logger::CREVENTO_USR_CONVERTED; + $this->log_info_code = Logger::CREVENTO_USR_REMOVED; $this->auth_mode = 'local'; } public function executeAction() : void { - $this->ilias_user->setAuthMode('local'); - $this->ilias_user->update(); + $this->user_manager->removeUserAccessesAfterLeavingInstitution( + $this->ilias_user + ); $this->user_manager->deleteEventoUserToIliasUserConnection($this->evento_id); @@ -39,8 +42,6 @@ public function executeAction() : void $this->ilias_user->getLogin(), [ 'ilias_user_id' => $this->ilias_user->getId(), - 'new_auth_mode' => $this->auth_mode, - 'deactivate_after_convert' => false, ] ); } diff --git a/classes/import/action/user/RenameExistingUserExecuteNextImportAction.php b/classes/import/action/user/RenameExistingUserExecuteNextImportAction.php index 1f4e213..6ad42e2 100644 --- a/classes/import/action/user/RenameExistingUserExecuteNextImportAction.php +++ b/classes/import/action/user/RenameExistingUserExecuteNextImportAction.php @@ -9,40 +9,60 @@ class RenameExistingUserExecuteNextImportAction implements UserImportAction { private UserImportAction $next_action; private EventoUser $new_evento_user; - private \ilObjUser $old_user_to_rename; + + /** + * @param array<\ilObjUser> $old_users_to_rename + */ + private array $old_users_to_rename; private string $found_by; private Logger $logger; - public function __construct(UserImportAction $next_action, EventoUser $new_evento_user, \ilObjUser $old_user_to_rename, string $found_by, Logger $logger) - { + /** + * @param array<\ilObjUser> $old_users_to_rename + */ + public function __construct( + UserImportAction $next_action, + EventoUser $new_evento_user, + array $old_users_to_rename, + string $found_by, + Logger $logger + ) { $this->new_evento_user = $new_evento_user; $this->next_action = $next_action; - $this->old_user_to_rename = $old_user_to_rename; + $this->old_users_to_rename = $old_users_to_rename; $this->found_by = $found_by; $this->logger = $logger; } public function executeAction() : void { - $this->renameExistingUser($this->old_user_to_rename); + foreach ($this->old_users_to_rename as $old_user_to_rename) { + $this->renameExistingUser($old_user_to_rename); + } $this->next_action->executeAction(); } private function renameExistingUser(\ilObjUser $old_user) : void { - $old_user_evento_id = trim(substr($old_user->getMatriculation() ?? '', 7)); + $old_user_evento_id = trim(mb_substr($old_user->getMatriculation(), 7)); $changed_user_data['user_id'] = $old_user->getId(); $changed_user_data['EvtID'] = $old_user_evento_id; $changed_user_data['new_user_info'] = $this->new_evento_user->getEventoId(); $changed_user_data['found_by'] = $this->found_by; - $changed_user_data['Login'] = date('Ymd') . '_' . $old_user->getLogin(); + $login = $old_user->getLogin(); + if ($old_user->getLogin() === $this->new_evento_user->getLoginName()) { + $login = date('Ymd') . '_' . $login; + } + $changed_user_data['Login'] = $login; $changed_user_data['FirstName'] = $old_user->getFirstname(); $changed_user_data['LastName'] = $old_user->getLastname(); $changed_user_data['Gender'] = $old_user->getGender(); + $changed_user_data['External Account'] = ''; $changed_user_data['Matriculation'] = $old_user->getMatriculation(); $old_user->setActive(false); + $old_user->setExternalAccount(''); $old_user->update(); $old_user->setLogin($changed_user_data['Login']); $old_user->updateLogin($old_user->getLogin()); diff --git a/classes/import/action/user/UpdateUser.php b/classes/import/action/user/UpdateUser.php index ba2e87f..d5bb5c4 100644 --- a/classes/import/action/user/UpdateUser.php +++ b/classes/import/action/user/UpdateUser.php @@ -31,7 +31,7 @@ public function __construct( public function executeAction() : void { - $this->user_manager->registerEventoUserAsDelivered($this->evento_user); + $this->user_manager->registerEventoUserAsDelivered($this->ilias_user, $this->evento_user); $changed_user_data = $this->user_manager->updateIliasUserFromEventoUser($this->ilias_user, $this->evento_user); $this->user_manager->updateSettingsForExistingUser($this->ilias_user); @@ -39,32 +39,7 @@ public function executeAction() : void $this->user_manager->importAndSetUserPhoto($this->ilias_user, $this->evento_user->getEventoId(), $this->photo_importer); $old_login = $this->ilias_user->getLogin(); - if ($old_login != $this->evento_user->getLoginName()) { - $login_change_successful = $this->ilias_user->updateLogin($this->evento_user->getLoginName()); - if ($login_change_successful) { - $this->logger->logUserImport( - Logger::CREVENTO_USR_RENAMED, - $this->evento_user->getEventoId(), - $this->evento_user->getLoginName(), - [ - 'api_data' => $this->evento_user->getDecodedApiData(), - 'old_login' => $old_login, - 'changed_user_data' => $changed_user_data - ] - ); - } else { - $this->logger->logException('UserImport - UpdateUser', 'Failed to change login from user with evento ID ' . $this->evento_user->getEventoId()); - $this->logger->logUserImport( - Logger::CREVENTO_USR_UPDATED, - $this->evento_user->getEventoId(), - $this->evento_user->getLoginName(), - [ - 'api_data' => $this->evento_user->getDecodedApiData(), - 'changed_user_data' => $changed_user_data - ] - ); - } - } else { + if ($old_login === $this->evento_user->getLoginName()) { $this->logger->logUserImport( Logger::CREVENTO_USR_UPDATED, $this->evento_user->getEventoId(), @@ -74,6 +49,33 @@ public function executeAction() : void 'changed_user_data' => $changed_user_data ] ); + return; } + + $login_change_successful = $this->ilias_user->updateLogin($this->evento_user->getLoginName()); + if ($login_change_successful) { + $this->logger->logUserImport( + Logger::CREVENTO_USR_RENAMED, + $this->evento_user->getEventoId(), + $this->evento_user->getLoginName(), + [ + 'api_data' => $this->evento_user->getDecodedApiData(), + 'old_login' => $old_login, + 'changed_user_data' => $changed_user_data + ] + ); + return; + } + + $this->logger->logException('UserImport - UpdateUser', 'Failed to change login from user with evento ID ' . $this->evento_user->getEventoId()); + $this->logger->logUserImport( + Logger::CREVENTO_USR_UPDATED, + $this->evento_user->getEventoId(), + $this->evento_user->getLoginName(), + [ + 'api_data' => $this->evento_user->getDecodedApiData(), + 'changed_user_data' => $changed_user_data + ] + ); } } diff --git a/classes/import/action/user/UserActionFactory.php b/classes/import/action/user/UserActionFactory.php index 475dadb..88c24f8 100644 --- a/classes/import/action/user/UserActionFactory.php +++ b/classes/import/action/user/UserActionFactory.php @@ -22,7 +22,7 @@ public function __construct(UserManager $user_manager, EventoUserPhotoImporter $ $this->logger = $logger; } - public function buildCreateAction(EventoUser $evento_user) : CreateUser + public function buildCreateAction(EventoUser $evento_user): CreateUser { return new CreateUser( $evento_user, @@ -32,7 +32,7 @@ public function buildCreateAction(EventoUser $evento_user) : CreateUser ); } - public function buildUpdateAction(EventoUser $evento_user, int $ilias_user_id) : UpdateUser + public function buildUpdateAction(EventoUser $evento_user, int $ilias_user_id): UpdateUser { return new UpdateUser( $evento_user, @@ -43,37 +43,44 @@ public function buildUpdateAction(EventoUser $evento_user, int $ilias_user_id) : ); } + /** + * @param array<\ilObjUser> $old_ilias_users + */ public function buildRenameExistingAndCreateNewAction( EventoUser $evento_user, - \ilObjUser $old_ilias_user, + array $old_ilias_users, string $found_by - ) : RenameExistingUserExecuteNextImportAction { + ): RenameExistingUserExecuteNextImportAction { return new RenameExistingUserExecuteNextImportAction( $this->buildCreateAction($evento_user), $evento_user, - $old_ilias_user, + $old_ilias_users, $found_by, $this->logger ); } + /** + * @param array<\ilObjUser> $old_ilias_users + */ public function buildRenameExistingAndUpdateDeliveredAction( EventoUser $evento_user, int $user_id_of_found_delivered_user, - \ilObjUser $old_ilias_user, + array $old_ilias_users, string $found_by - ) { + ): RenameExistingUserExecuteNextImportAction { return new RenameExistingUserExecuteNextImportAction( $this->buildUpdateAction($evento_user, $user_id_of_found_delivered_user), $evento_user, - $old_ilias_user, + $old_ilias_users, $found_by, $this->logger ); } - public function buildReportConflict(EventoUser $evento_user) : ReportDatasetWithoutAction - { + public function buildReportConflict( + EventoUser $evento_user + ): ReportDatasetWithoutAction { return new ReportUserImportDatasetWithoutAction( Logger::CREVENTO_USR_NOTICE_CONFLICT, $evento_user->getEventoId(), @@ -83,8 +90,10 @@ public function buildReportConflict(EventoUser $evento_user) : ReportDatasetWith ); } - public function buildReportError(EventoUser $evento_user, array $found_user_data) - { + public function buildReportError( + EventoUser $evento_user, + array $found_user_data + ): ReportUserImportDatasetWithoutAction { return new ReportUserImportDatasetWithoutAction( Logger::CREVENTO_USR_ERROR_ERROR, $evento_user->getEventoId(), @@ -97,25 +106,13 @@ public function buildReportError(EventoUser $evento_user, array $found_user_data ); } - public function buildConvertUserAuth(\ilObjUser $ilias_user_object, int $evento_id) : EventoImportAction - { - return new ConvertUserToLocalAuth( - $ilias_user_object, - $evento_id, - 'local', - $this->user_manager, - $this->logger - ); - } - - public function buildConvertAuthAndDeactivateUser( + public function buildRemoveConnectionToInstitution( \ilObjUser $ilias_user_object, int $evento_id - ) : EventoImportAction { - return new ConvertAndDeactivateUser( + ): UserConnectionRemoveAction { + return new RemoveConnectionToInstitution( $ilias_user_object, $evento_id, - 'local', $this->user_manager, $this->logger ); diff --git a/classes/import/action/user/UserDeleteAction.php b/classes/import/action/user/UserConnectionRemoveAction.php similarity index 67% rename from classes/import/action/user/UserDeleteAction.php rename to classes/import/action/user/UserConnectionRemoveAction.php index e895ff3..a6a43c8 100644 --- a/classes/import/action/user/UserDeleteAction.php +++ b/classes/import/action/user/UserConnectionRemoveAction.php @@ -4,6 +4,6 @@ use EventoImport\import\action\EventoImportAction; -interface UserDeleteAction extends EventoImportAction +interface UserConnectionRemoveAction extends EventoImportAction { } diff --git a/classes/import/data_management/EventManager.php b/classes/import/data_management/EventManager.php index 409df0e..b2e1c22 100644 --- a/classes/import/data_management/EventManager.php +++ b/classes/import/data_management/EventManager.php @@ -94,7 +94,12 @@ public function convertIliasEventoEventToParentEvent( $parent_event = $this->eventoEventAndIliasObjToParentEvent($evento_event, $course_obj); - $this->event_obj_repo->addNewParentEvent($parent_event); + if($this->event_obj_repo->getParentEventbyGroupUniqueKey($parent_event->getGroupUniqueKey()) != null) { + $this->event_obj_repo->updateExistingParentEvent($parent_event); + } + else { + $this->event_obj_repo->addNewParentEvent($parent_event); + } $this->event_obj_repo->removeIliasEventoEvent($ilias_event); return $parent_event; diff --git a/classes/import/data_management/HiddenAdminManager.php b/classes/import/data_management/HiddenAdminManager.php index 61031ee..df3de52 100644 --- a/classes/import/data_management/HiddenAdminManager.php +++ b/classes/import/data_management/HiddenAdminManager.php @@ -57,10 +57,10 @@ private function createHiddenRoleForContainerRefId(int $ref_id) : int { $type = \ilObject::_lookupType($ref_id, true); - if($type == 'crs') { + if ($type == 'crs') { $title = self::ROLE_TITLE_CRS; $role_template = 'il_crs_admin'; - } else if($type == 'grp') { + } elseif ($type == 'grp') { $title = self::ROLE_TITLE_GRP; $role_template = 'il_grp_admin'; } else { diff --git a/classes/import/data_management/MembershipManager.php b/classes/import/data_management/MembershipManager.php index aa00ff2..c2476e8 100644 --- a/classes/import/data_management/MembershipManager.php +++ b/classes/import/data_management/MembershipManager.php @@ -50,26 +50,27 @@ public function __construct( public function syncMemberships(EventoEvent $imported_event, IliasEventoEvent $ilias_event) : void { + $delete_not_delivered_members = true; if (is_null($imported_event->getEndDate()) || $imported_event->getEndDate() <= $this->now) { $delete_not_delivered_members = false; - } else { - $delete_not_delivered_members = true; } // If Ilias Event is already a course -> no need to find parent membershipables if ($ilias_event->getIliasType() == 'crs') { $this->syncMembershipsWithoutParentObjects($imported_event, $ilias_event, $delete_not_delivered_members); - } else { - // Else -> search for parent membershipable objects - $parent_events = $this->tree_seeker->getRefIdsOfParentMembershipables($ilias_event->getRefId()); + return; + } - // Check if any parent membershipables were found - if (count($parent_events) > 0) { - $this->syncMembershipsWithParentObjects($imported_event, $ilias_event, $parent_events, $delete_not_delivered_members); - } else { - $this->syncMembershipsWithoutParentObjects($imported_event, $ilias_event, $delete_not_delivered_members); - } + // Else -> search for parent membershipable objects + $parent_events = $this->tree_seeker->getRefIdsOfParentMembershipables($ilias_event->getRefId()); + + // Check if any parent membershipables were found + if (count($parent_events) > 0) { + $this->syncMembershipsWithParentObjects($imported_event, $ilias_event, $parent_events, $delete_not_delivered_members); + return; } + + $this->syncMembershipsWithoutParentObjects($imported_event, $ilias_event, $delete_not_delivered_members); } private function addUsersToMembershipableObject( @@ -83,33 +84,37 @@ private function addUsersToMembershipableObject( /** @var EventoUserShort $employee */ foreach ($evento_event->getEmployees() as $employee) { $employee_user_id = $this->user_manager->getIliasUserIdByEventoUserShort($employee); - if (!is_null($employee_user_id)) { - if (!$participants_object->isAssigned($employee_user_id)) { - $participants_object->add($employee_user_id, $admin_role_code); - $log_info_code = Logger::CREVENTO_SUB_NEWLY_ADDED; - \ilForumNotification::checkForumsExistsInsert($membershipable_ref_id, $employee_user_id); - } else { - $log_info_code = Logger::CREVENTO_SUB_ALREADY_ASSIGNED; - } - $this->logger->logEventMembership($log_info_code, $evento_event->getEventoId(), $employee->getEventoId(), $admin_role_code); - $this->membership_repo->addMembershipIfNotExist($evento_event->getEventoId(), $employee->getEventoId(), $admin_role_code); + if (is_null($employee_user_id)) { + continue; + } + + $log_info_code = Logger::CREVENTO_SUB_ALREADY_ASSIGNED; + if (!$participants_object->isAssigned($employee_user_id)) { + $participants_object->add($employee_user_id, $admin_role_code); + $log_info_code = Logger::CREVENTO_SUB_NEWLY_ADDED; + \ilForumNotification::checkForumsExistsInsert($membershipable_ref_id, $employee_user_id); } + + $this->logger->logEventMembership($log_info_code, $evento_event->getEventoId(), $employee->getEventoId(), $admin_role_code); + $this->membership_repo->addMembershipIfNotExist($evento_event->getEventoId(), $employee->getEventoId(), $admin_role_code); } /** @var EventoUserShort $student */ foreach ($evento_event->getStudents() as $student) { $student_user_id = $this->user_manager->getIliasUserIdByEventoUserShort($student); - if (!is_null($student_user_id)) { - if (!$participants_object->isAssigned($student_user_id)) { - $participants_object->add($student_user_id, $student_role_code); - $log_info_code = Logger::CREVENTO_SUB_NEWLY_ADDED; - \ilForumNotification::checkForumsExistsInsert($membershipable_ref_id, $student_user_id); - } else { - $log_info_code = Logger::CREVENTO_SUB_ALREADY_ASSIGNED; - } - $this->logger->logEventMembership($log_info_code, $evento_event->getEventoId(), $student->getEventoId(), $student_role_code); - $this->membership_repo->addMembershipIfNotExist($evento_event->getEventoId(), $student->getEventoId(), $student_role_code); + if (is_null($student_user_id)) { + continue; + } + + $log_info_code = Logger::CREVENTO_SUB_ALREADY_ASSIGNED; + if (!$participants_object->isAssigned($student_user_id)) { + $participants_object->add($student_user_id, $student_role_code); + $log_info_code = Logger::CREVENTO_SUB_NEWLY_ADDED; + \ilForumNotification::checkForumsExistsInsert($membershipable_ref_id, $student_user_id); } + + $this->logger->logEventMembership($log_info_code, $evento_event->getEventoId(), $student->getEventoId(), $student_role_code); + $this->membership_repo->addMembershipIfNotExist($evento_event->getEventoId(), $student->getEventoId(), $student_role_code); } } @@ -120,11 +125,13 @@ private function getUsersToRemove(EventoEvent $imported_event) : array $user_ids_to_remove = []; foreach ($from_import_subscribed_members as $member_id) { - if (!$this->isUserInCurrentImport((int) $member_id, $imported_event)) { - $ilias_evento_user = $this->user_manager->getIliasEventoUserByEventoId((int) $member_id); - if (!is_null($ilias_evento_user)) { - $user_ids_to_remove[] = $ilias_evento_user; - } + if ($this->isUserInCurrentImport((int) $member_id, $imported_event)) { + continue; + } + + $ilias_evento_user = $this->user_manager->getIliasEventoUserByEventoId((int) $member_id); + if (!is_null($ilias_evento_user)) { + $user_ids_to_remove[] = $ilias_evento_user; } } @@ -194,7 +201,10 @@ private function syncMembershipsWithParentObjects(EventoEvent $imported_event, I \ilParticipants::IL_CRS_MEMBER, $parent_event ); - } elseif ($participants_obj_of_parent instanceof \ilGroupParticipants) { + continue; + } + + if ($participants_obj_of_parent instanceof \ilGroupParticipants) { $this->addUsersToMembershipableObject( $participants_obj_of_parent, $imported_event, @@ -304,7 +314,10 @@ public function addEventAdmins(EventoEventIliasAdmins $event_admin_list, IliasEv $event_admin_list->getAccountList(), \ilParticipants::IL_CRS_ADMIN, ); - } elseif ($participants_obj instanceof \ilGroupParticipants) { + continue; + } + + if ($participants_obj instanceof \ilGroupParticipants) { $this->addAdminListToObject( $participants_obj, $event_admin_list->getAccountList(), diff --git a/classes/import/data_management/UserManager.php b/classes/import/data_management/UserManager.php index 3e32790..ea527c7 100644 --- a/classes/import/data_management/UserManager.php +++ b/classes/import/data_management/UserManager.php @@ -26,11 +26,12 @@ public function __construct(IliasUserServices $ilias_user_service, IliasEventoUs $this->logger = $logger; } - public function createAndSetupNewIliasUser(EventoUser $evento_user) : \ilObjUser + public function createAndSetupNewIliasUser(EventoUser $evento_user): \ilObjUser { - $ilias_user_object = $this->ilias_user_service->createNewIliasUserObject(); - - $ilias_user_object = $this->setUserValuesFromEventoUserObject($ilias_user_object, $evento_user); + $ilias_user_object = $this->setUserValuesFromEventoUserObject( + $this->ilias_user_service->createNewIliasUserObject(), + $evento_user + ); $ilias_user_object->create(); $ilias_user_object->saveAsNew(false); @@ -38,7 +39,11 @@ public function createAndSetupNewIliasUser(EventoUser $evento_user) : \ilObjUser $this->setUserDefaultSettings($ilias_user_object, $this->default_user_settings); $this->setForcedUserSettings($ilias_user_object, $this->default_user_settings); - $this->evento_user_repo->addNewEventoIliasUserByEventoUser($evento_user, $ilias_user_object, IliasEventoUserRepository::TYPE_HSLU_AD); + $this->evento_user_repo->addNewEventoIliasUser( + $evento_user->getEventoId(), + $ilias_user_object->getId(), + IliasEventoUserRepository::TYPE_HSLU_AD + ); return $ilias_user_object; } @@ -48,7 +53,7 @@ public function updateSettingsForExistingUser(\ilObjUser $ilias_user) $this->setForcedUserSettings($ilias_user, $this->default_user_settings); } - public function importAndSetUserPhoto(\ilObjUser $ilias_user, int $evento_id, EventoUserPhotoImporter $photo_importer) : void + public function importAndSetUserPhoto(\ilObjUser $ilias_user, int $evento_id, EventoUserPhotoImporter $photo_importer): void { if ($this->ilias_user_service->userHasPersonalPicture($ilias_user->getId())) { return; @@ -70,20 +75,110 @@ public function importAndSetUserPhoto(\ilObjUser $ilias_user, int $evento_id, Ev } } - public function synchronizeIliasUserWithEventoRoles(\ilObjUser $user, array $imported_evento_roles) : void + public function synchronizeIliasUserWithEventoRoles(\ilObjUser $user, array $imported_evento_roles): void { - $this->ilias_user_service->assignUserToRole($user->getId(), $this->default_user_settings->getDefaultUserRoleId()); + if ($imported_evento_roles === []) { + if ($this->ilias_user_service->isUserAssignedToRole($user->getId(), $this->default_user_settings->getDefaultUserRoleId())) { + $this->ilias_user_service->deassignUserFromRole($user->getId(), $this->default_user_settings->getDefaultUserRoleId()); + } + + if (!$this->ilias_user_service->isUserAssignedToRole($user->getId(), $this->default_user_settings->getDefaultGuestRoleId())) { + $this->ilias_user_service->assignUserToRole($user->getId(), $this->default_user_settings->getDefaultGuestRoleId()); + } + } else { + if ($this->ilias_user_service->isUserAssignedToRole($user->getId(), $this->default_user_settings->getDefaultGuestRoleId())) { + $this->ilias_user_service->deassignUserFromRole($user->getId(), $this->default_user_settings->getDefaultGuestRoleId()); + } + + if (!$this->ilias_user_service->isUserAssignedToRole($user->getId(), $this->default_user_settings->getDefaultUserRoleId())) { + $this->ilias_user_service->assignUserToRole($user->getId(), $this->default_user_settings->getDefaultUserRoleId()); + } + } // Set ilias roles according to given evento roles foreach ($this->default_user_settings->getEventoCodeToIliasRoleMapping() as $evento_role_code => $ilias_role_id) { + if ($this->ilias_user_service->isUserAssignedToRole($user->getId(), $ilias_role_id) + && in_array($evento_role_code, $imported_evento_roles) + || !$this->ilias_user_service->isUserAssignedToRole($user->getId(), $ilias_role_id) + && !in_array($evento_role_code, $imported_evento_roles)) { + continue; + } + if (in_array($evento_role_code, $imported_evento_roles)) { - $this->ilias_user_service->assignUserToRole($user->getId(), $ilias_role_id); - } else { - $this->ilias_user_service->deassignUserFromRole($user->getId(), $ilias_role_id); + $this->performAddToUserRoleSubTasks($user, $ilias_role_id); + continue; + } + + $this->removeUserAccessAfterRemovalOfEventoRole($user, $ilias_role_id); + } + } + + private function performAddToUserRoleSubTasks( + \ilObjUser $user, + int $ilias_role_id + ): void { + $follow_up_roles_mapping = $this->default_user_settings->getFollowUpRoleMapping(); + if (array_key_exists($ilias_role_id, $follow_up_roles_mapping) + && $this->ilias_user_service->isUserAssignedToRole( + $user->getId(), + $follow_up_roles_mapping[$ilias_role_id]) + ) { + $this->ilias_user_service->deassignUserFromRole($user->getId(), $follow_up_roles_mapping[$ilias_role_id]); + } + + $track_removal_custom_fields_mapping = $this->default_user_settings->getTrackRemovalCustomFieldsMapping(); + if (array_key_exists($ilias_role_id, $track_removal_custom_fields_mapping) + && $track_removal_custom_fields_mapping[$ilias_role_id] !== 0) { + $this->saveUserRoleRemovalDateToCustomField($user, (int) $track_removal_custom_fields_mapping[$ilias_role_id], ''); + } + + $this->ilias_user_service->assignUserToRole($user->getId(), $ilias_role_id); + } + + public function removeUserAccessesAfterLeavingInstitution(\ilObjUser $user): void + { + $this->ilias_user_service->deassignUserFromRole($user->getId(), $this->default_user_settings->getDefaultUserRoleId()); + + $assigned_global_roles = $this->ilias_user_service->getGlobalRolesOfUser($user->getId()); + $roles_mapped_to_evento = $this->default_user_settings->getEventoCodeToIliasRoleMapping(); + foreach ($assigned_global_roles as $global_role_id) { + if (!in_array($global_role_id, $roles_mapped_to_evento)) { + continue; + } + $this->removeUserAccessAfterRemovalOfEventoRole($user, (int) $global_role_id); + } + } + + private function removeUserAccessAfterRemovalOfEventoRole(\ilObjUser $user, int $role_id): void + { + $this->ilias_user_service->deassignUserFromRole($user->getId(), $role_id); + + $follow_up_roles_mapping = $this->default_user_settings->getFollowUpRoleMapping(); + if (array_key_exists($role_id, $follow_up_roles_mapping)) { + $this->ilias_user_service->assignUserToRole($user->getId(), $follow_up_roles_mapping[$role_id]); + } + + $track_removal_custom_fields_mapping = $this->default_user_settings->getTrackRemovalCustomFieldsMapping(); + if (array_key_exists($role_id, $track_removal_custom_fields_mapping) + && $track_removal_custom_fields_mapping[$role_id] !== 0) { + $this->saveUserRoleRemovalDateToCustomField($user, (int) $track_removal_custom_fields_mapping[$role_id], date('Y-m-d H:i:s')); + } + + $roles_needing_admin_removal = $this->default_user_settings->getDeleteFromAdminWhenRemovedFromRoleMapping(); + if (in_array($role_id, $roles_needing_admin_removal)) { + $admin_roles = $this->ilias_user_service->getCrsAdminButNotOwnerRolesOfUser($user->getId()); + foreach ($admin_roles as $admin_role_id) { + $this->ilias_user_service->deassignUserFromRole($user->getId(), $admin_role_id); } } } + public function saveUserRoleRemovalDateToCustomField(\ilObjUser $user, int $custom_field_id, string $date): void + { + $user->setUserDefinedData([$custom_field_id => $date]); + $user->update(); + } + public function renameAndDeactivateIliasUser(\ilObjUser $old_user_to_rename, string $new_login) { $old_user_to_rename->setActive(false); @@ -92,9 +187,9 @@ public function renameAndDeactivateIliasUser(\ilObjUser $old_user_to_rename, str $old_user_to_rename->updateLogin($old_user_to_rename->getLogin()); } - public function registerEventoUserAsDelivered(EventoUser $evento_user) + public function registerEventoUserAsDelivered(\ilObjUser $ilias_user, EventoUser $evento_user) { - $this->evento_user_repo->registerUserAsDelivered($evento_user->getEventoId()); + $this->evento_user_repo->registerUserAsDelivered($evento_user->getEventoId(),$ilias_user->getId()); } public function updateIliasUserFromEventoUser(\ilObjUser $ilias_user, EventoUser $evento_user) @@ -119,7 +214,7 @@ public function updateIliasUserFromEventoUser(\ilObjUser $ilias_user, EventoUser } $received_gender_char = $this->convertEventoToIliasGenderChar($evento_user->getGender()); - if ($ilias_user->getGender() != $received_gender_char) { + if ($ilias_user->getGender() !== $received_gender_char) { $changed_user_data['gender'] = [ 'old' => $ilias_user->getGender(), 'new' => $received_gender_char @@ -128,7 +223,7 @@ public function updateIliasUserFromEventoUser(\ilObjUser $ilias_user, EventoUser } $mail_list = $evento_user->getEmailList(); - if (isset($mail_list[0]) && ($ilias_user->getSecondEmail() != $mail_list[0])) { + if (isset($mail_list[0]) && ($ilias_user->getSecondEmail() !== $mail_list[0])) { $changed_user_data['second_mail'] = [ 'old' => $ilias_user->getSecondEmail(), 'new' => $mail_list[0] @@ -136,7 +231,7 @@ public function updateIliasUserFromEventoUser(\ilObjUser $ilias_user, EventoUser $ilias_user->setSecondEmail($mail_list[0]); } - if ($ilias_user->getMatriculation() != ('Evento:' . $evento_user->getEventoId())) { + if ($ilias_user->getMatriculation() !== ('Evento:' . $evento_user->getEventoId())) { $changed_user_data['matriculation'] = [ 'old' => $ilias_user->getMatriculation(), 'new' => 'Evento:' . $evento_user->getEventoId() @@ -144,7 +239,7 @@ public function updateIliasUserFromEventoUser(\ilObjUser $ilias_user, EventoUser $ilias_user->setMatriculation('Evento:' . $evento_user->getEventoId()); } - if ($ilias_user->getAuthMode() != $this->default_user_settings->getAuthMode()) { + if ($ilias_user->getAuthMode() !== $this->default_user_settings->getAuthMode()) { $changed_user_data['auth_mode'] = [ 'old' => $ilias_user->getAuthMode(), 'new' => $this->default_user_settings->getAuthMode() @@ -152,6 +247,14 @@ public function updateIliasUserFromEventoUser(\ilObjUser $ilias_user, EventoUser $ilias_user->setAuthMode($this->default_user_settings->getAuthMode()); } + if ($ilias_user->getExternalAccount() !== $evento_user->getEduId()) { + $changed_user_data['external_account'] = [ + 'old' => $ilias_user->getExternalAccount(), + 'new' => $evento_user->getEduId() + ]; + $ilias_user->setExternalAccount($evento_user->getEduId()); + } + if (!$ilias_user->getActive()) { $changed_user_data['active'] = [ 'old' => false, @@ -160,14 +263,14 @@ public function updateIliasUserFromEventoUser(\ilObjUser $ilias_user, EventoUser $ilias_user->setActive(true); } - if (count($changed_user_data) > 0) { + if ($changed_user_data !== []) { $ilias_user->update(); } return $changed_user_data; } - private function setUserValuesFromEventoUserObject(\ilObjUser $ilias_user, EventoUser $evento_user) : \ilObjUser + private function setUserValuesFromEventoUserObject(\ilObjUser $ilias_user, EventoUser $evento_user): \ilObjUser { $ilias_user->setLogin($evento_user->getLoginName()); $ilias_user->setFirstname($this->shortenStringIfTooLong($evento_user->getFirstName(), 32)); @@ -178,7 +281,7 @@ private function setUserValuesFromEventoUserObject(\ilObjUser $ilias_user, Event $ilias_user->setTitle($ilias_user->getFullname()); $ilias_user->setDescription($ilias_user->getEmail()); $ilias_user->setMatriculation('Evento:' . $evento_user->getEventoId()); - $ilias_user->setExternalAccount($evento_user->getEventoId() . '@hslu.ch'); + $ilias_user->setExternalAccount($evento_user->getEduId()); $ilias_user->setAuthMode($this->default_user_settings->getAuthMode()); return $ilias_user; @@ -190,7 +293,6 @@ private function setForcedUserSettings(\ilObjUser $ilias_user, DefaultUserSettin // Reset login attempts over night -> needed since login attempts are limited to 8 $ilias_user->setLoginAttempts(0); - $ilias_user->setTimeLimitUnlimited(true); $ilias_user->setPasswd(''); @@ -237,7 +339,7 @@ private function setUserDefaultSettings(\ilObjUser $ilias_user_object, DefaultUs ); } - private function convertEventoToIliasGenderChar(string $evento_gender_char) : string + private function convertEventoToIliasGenderChar(string $evento_gender_char): string { switch (strtolower($evento_gender_char)) { case 'f': @@ -255,36 +357,39 @@ public function deleteEventoUserToIliasUserConnection(int $evento_id) $this->evento_user_repo->deleteEventoIliasUserConnectionByEventoId($evento_id); } - public function getExistingIliasUserObjectById(int $ilias_user_id) : \ilObjUser + public function getExistingIliasUserObjectById(int $ilias_user_id): \ilObjUser { return $this->ilias_user_service->getExistingIliasUserObjectById($ilias_user_id); } - public function getIliasEventoUserByEventoId(int $evento_id) : IliasEventoUser + public function getIliasEventoUserByEventoId(int $evento_id): IliasEventoUser { return $this->evento_user_repo->getIliasEventoUserByEventoId($evento_id); } - public function getIliasUserIdByEventoId(int $evento_id) : ?int + public function getIliasUserIdByEventoId(int $evento_id): ?int { return $this->evento_user_repo->getIliasUserIdByEventoId($evento_id); } - public function getIliasUserIdByEventoUserShort(EventoUserShort $evento_user) : ?int + public function getIliasUserIdByEventoUserShort(EventoUserShort $evento_user): ?int { $ilias_user_id = $this->evento_user_repo->getIliasUserIdByEventoId($evento_user->getEventoId()); if (is_null($ilias_user_id)) { - $edu_user = $this->ilias_user_service->searchEduUserByEmail($evento_user->getEmailAddress()); - if (!is_null($edu_user)) { - $ilias_user_id = (int) $edu_user->getId(); - $this->evento_user_repo->addNewEventoIliasUserByEventoUserShort($evento_user, $edu_user, IliasEventoUserRepository::TYPE_EDU_ID); + $ilias_user_id = $this->ilias_user_service->getUserIdByExternalAccount($evento_user->getEduId()); + if ($ilias_user_id !== 0) { + $this->evento_user_repo->addNewEventoIliasUser( + $evento_user->getEventoId(), + $ilias_user_id, + IliasEventoUserRepository::TYPE_EDU_ID + ); } } return $ilias_user_id; } - public function getIliasEventoUserForEventoUser(EventoUserShort $evento_user) : ?IliasEventoUser + public function getIliasEventoUserForEventoUser(EventoUserShort $evento_user): ?IliasEventoUser { return $this->evento_user_repo->getIliasEventoUserByEventoId($evento_user->getEventoId()); } diff --git a/classes/import/data_management/ilias_core_services/IliasEventObjectService.php b/classes/import/data_management/ilias_core_services/IliasEventObjectService.php index cce96db..ea8bc17 100644 --- a/classes/import/data_management/ilias_core_services/IliasEventObjectService.php +++ b/classes/import/data_management/ilias_core_services/IliasEventObjectService.php @@ -47,23 +47,25 @@ public function searchEventableIliasObjectByTitle(string $obj_title, string $fil } $result = $this->db->query($query); - $found_obj = null; - if ($this->db->numRows($result) == 1) { - $row = $this->db->fetchAssoc($result); + if ($this->db->numRows($result) !== 1) { + return null; + } + + $row = $this->db->fetchAssoc($result); - if ($row['type'] == 'crs') { - $found_obj = $this->getCourseObjectForRefId((int) $row['ref_id']); - } elseif ($row['type'] == 'grp') { - $group_obj = $this->getGroupObjectForRefId((int) $row['ref_id']); + if ($row['type'] == 'crs') { + return $this->getCourseObjectForRefId((int) $row['ref_id']); + } - if ($this->isGroupObjPartOfACourse($group_obj)) { - $found_obj = $group_obj; - } + if ($row['type'] == 'grp') { + $group_obj = $this->getGroupObjectForRefId((int) $row['ref_id']); + if ($this->isGroupObjPartOfACourse($group_obj)) { + return $group_obj; } } - return $found_obj; + return null; } public function createNewCourseObject(string $title, string $description, int $destination_ref_id) : \ilObjCourse @@ -98,26 +100,26 @@ public function getGroupObjectForRefId(int $ref_id) : \ilObjGroup return new \ilObjGroup($ref_id, true); } - public function removeIliasEventObjectWithSubObjects(IliasEventoEvent $ilias_event_to_remove) + public function removeIliasEventObjectWithSubObjects(IliasEventoEvent $ilias_event_to_remove): void { $ref_id = $ilias_event_to_remove->getRefId(); $type = $this->getObjTypeForRefId($ref_id); - if ($type == 'crs' || $type == 'grp') { - \ilRepUtil::deleteObjects($this->tree->getParentId($ref_id), [$ref_id]); - } else { + if ($type !== 'crs' && $type !== 'grp') { throw new \ilException("Failed deleting Parent Event with ref_id = $ref_id. The ILIAS Object had type $type instead of crs"); } + + \ilRepUtil::deleteObjects($this->tree->getParentId($ref_id), [$ref_id]); } - public function removeIliasParentEventObject(IliasEventoParentEvent $ilias_evento_parent_event) + public function removeIliasParentEventObject(IliasEventoParentEvent $ilias_evento_parent_event): void { $ref_id = $ilias_evento_parent_event->getRefId(); $type = $this->getObjTypeForRefId($ref_id); - if ($type == 'crs') { - \ilRepUtil::deleteObjects($this->tree->getParentId($ref_id), [$ref_id]); - } else { + if ($type !== 'crs') { throw new \ilException("Failed deleting Parent Event with ref_id = $ref_id. The ILIAS Object had type $type instead of crs"); } + + \ilRepUtil::deleteObjects($this->tree->getParentId($ref_id), [$ref_id]); } public function isGroupObjPartOfACourse(\ilObjGroup $group_obj) : bool @@ -129,7 +131,9 @@ public function isGroupObjPartOfACourse(\ilObjGroup $group_obj) : bool if ($type == 'crs') { return true; - } elseif ($type == 'cat' || $type == 'root') { + } + + if ($type == 'cat' || $type == 'root') { return false; } } while ($current_ref_id > 1); @@ -174,14 +178,12 @@ public function renameEventObject(\ilContainer $event_obj, string $new_title) : private function removeDeletePermissionsFromAdminRole(\ilObject $obj) { - if ($obj instanceof \ilObjCourse) { - $admin_role = $obj->getDefaultAdminRole(); - } else if ($obj instanceof \ilObjGroup) { - $admin_role = $obj->getDefaultAdminRole(); - } else { + if (!($obj instanceof \ilObjCourse) + && !($obj instanceof \ilObjGroup)) { return; } + $admin_role = $obj->getDefaultAdminRole(); $ref_id = $obj->getRefId(); $rbac_admin = $this->rbac->admin(); diff --git a/classes/import/data_management/ilias_core_services/IliasUserServices.php b/classes/import/data_management/ilias_core_services/IliasUserServices.php index ee1edbb..55fa4a0 100644 --- a/classes/import/data_management/ilias_core_services/IliasUserServices.php +++ b/classes/import/data_management/ilias_core_services/IliasUserServices.php @@ -15,20 +15,22 @@ */ class IliasUserServices { - private DefaultUserSettings $user_settings; + private DefaultUserSettings $default_user_settings; private \ilDBInterface $db; - private RBACServices $rbac_services; private \ilRbacReview $rbac_review; private \ilRbacAdmin $rbac_admin; private ?int $student_role_id; - public function __construct(DefaultUserSettings $user_settings, \ilDBInterface $db, RBACServices $rbac_services) - { - $this->user_settings = $user_settings; + public function __construct( + DefaultUserSettings $default_user_settings, + \ilDBInterface $db, + \ilRbacReview $rbac_review, + \ilRbacAdmin $rbac_admin + ) { + $this->default_user_settings = $default_user_settings; $this->db = $db; - $this->rbac_services = $rbac_services; - $this->rbac_review = $rbac_services->review(); - $this->rbac_admin = $rbac_services->admin(); + $this->rbac_review = $rbac_review; + $this->rbac_admin = $rbac_admin; $this->student_role_id = null; } @@ -37,12 +39,12 @@ public function __construct(DefaultUserSettings $user_settings, \ilDBInterface $ * Get / Create ILIAS User objects */ - public function createNewIliasUserObject() : \ilObjUser + public function createNewIliasUserObject(): \ilObjUser { return new \ilObjUser(); } - public function getExistingIliasUserObjectById(int $user_id) : \ilObjUser + public function getExistingIliasUserObjectById(int $user_id): \ilObjUser { return new \ilObjUser($user_id); } @@ -51,7 +53,7 @@ public function getExistingIliasUserObjectById(int $user_id) : \ilObjUser * Search for ILIAS User IDs by criteria */ - public function getUserIdsByEmailAddresses(array $email_adresses) + public function getUserIdsByEmailAddresses(array $email_adresses): array { $user_lists = []; @@ -69,7 +71,7 @@ public function getUserIdsByEmailAddresses(array $email_adresses) return $user_lists; } - public function getUserIdsByEmailAddress(string $mail_address) : array + public function getUserIdsByEmailAddress(string $mail_address): array { /* The user ids from ilObjUser::getUserIdsByEmail() are returned as string instead of int. Since we use strict_type int his plugin, this throws a TypeError when ever an id from this array is passed to a method which expects an argument @@ -82,17 +84,35 @@ public function getUserIdsByEmailAddress(string $mail_address) : array return $ids; } - public function getUserIdByLogin(string $login_name) + public function getUserIdByExternalAccount(string $external_account): int { + if ($external_account === '') { + return 0; + } + $login_name = \ilObjUser::_checkExternalAuthAccount($this->default_user_settings->getAuthMode(), $external_account); + + if ($login_name === null) { + return 0; + } + return \ilObjUser::getUserIdByLogin($login_name); } - public function getLoginByUserId(int $user_id) + public function getExternalAccountByUserId(int $user_id): string { + return \ilObjUser::_lookupExternalAccount($user_id); + } + + public function getUserIdByLogin(string $login_name): int + { + return \ilObjUser::getUserIdByLogin($login_name) ?? 0; + } + + public function getLoginByUserId(int $user_id): ?string { return \ilObjUser::_lookupLogin($user_id); } - public function getUserIdsByEventoId(int $evento_id) : array + public function getUserIdsByEventoId(int $evento_id): array { $list = []; @@ -105,26 +125,36 @@ public function getUserIdsByEventoId(int $evento_id) : array return $list; } - public function searchEduUserByEmail(string $mail_address) : ?\ilObjUser + public function getGlobalRolesOfUser(int $user_id): array { - $user_ids = $this->getUserIdsByEmailAddress($mail_address); + return $this->rbac_review->assignedGlobalRoles($user_id); + } + + public function getCrsAdminButNotOwnerRolesOfUser(int $user_id): array + { + $roles = $this->rbac_review->assignedRoles($user_id); + $admin_roles = []; + foreach ($roles as $role_id) { + $title = \ilObject::_lookupTitle($role_id); + $object_id = $this->rbac_review->getObjectOfRole($role_id); - $found_user_obj = null; - foreach ($user_ids as $user_id) { - $user_obj = $this->getExistingIliasUserObjectById($user_id); - if (stristr($user_obj->getExternalAccount(), '@eduid.ch') !== false) { - $found_user_obj = $this->getExistingIliasUserObjectById($user_id); + if (substr($title, 0, 12) === 'il_crs_admin' + && \ilObject::_lookupOwner($object_id) !== $user_id) { + $admin_roles[] = $role_id; } } + return $admin_roles; + } - return $found_user_obj; + public function isUserAssignedToRole(int $user_id, int $role_id): bool + { + return $this->rbac_review->isAssigned($user_id, $role_id); } /* * User and role specific methods */ - - public function assignUserToRole(int $user_id, int $role_id) : void + public function assignUserToRole(int $user_id, int $role_id): void { if (!$this->rbac_review->isAssigned($user_id, $role_id)) { $this->rbac_admin->assignUser($role_id, $user_id); @@ -138,31 +168,31 @@ public function deassignUserFromRole(int $user_id, int $role_id) } } - public function userWasStudent(\ilObjUser $ilias_user_object) : bool + public function userWasStudent(\ilObjUser $ilias_user_object): bool { // TODO: Implement config for this if (is_null($this->student_role_id)) { - $this->student_role_id = $this->user_settings->getStudentRoleId(); + $this->student_role_id = $this->default_user_settings->getStudentRoleId(); if (is_null($this->student_role_id)) { return false; } } - return $this->rbac_services->review()->isAssigned($ilias_user_object->getId(), $this->student_role_id); + return $this->rbac_review->isAssigned($ilias_user_object->getId(), $this->student_role_id); } /* * */ - public function userHasPersonalPicture(int $ilias_user_id) : bool + public function userHasPersonalPicture(int $ilias_user_id): bool { $personal_picturpath = \ilObjUser::_getPersonalPicturePath($ilias_user_id, "small", false); return strpos($personal_picturpath, 'data:image/svg+xml') === false; } - public function saveEncodedPersonalPictureToUserProfile(int $ilias_user_id, string $encoded_image_string) : void + public function saveEncodedPersonalPictureToUserProfile(int $ilias_user_id, string $encoded_image_string): void { try { return; @@ -195,52 +225,4 @@ public function setMailPreferences(int $user_id, int $incoming_type) $mail_options->setIncomingType($incoming_type); $mail_options->updateOptions(); } - - /* - * Set values for multiple users - */ - - public function setUserTimeLimits() - { - $until_max = $this->user_settings->getMaxDurationOfAccounts()->getTimestamp(); - - $this->setTimeLimitForUnlimitedUsersExceptSpecialUsers($until_max); - $this->setUserTimeLimitsToAMaxValue($until_max); - $this->setUserTimeLimitsBelowThresholdToGivenValue(90, 7889229); - } - - private function setTimeLimitForUnlimitedUsersExceptSpecialUsers(int $new_time_limit_ts) : void - { - if ($new_time_limit_ts == 0) { - throw new \InvalidArgumentException("Error in setting time limit for unlimited users: new time limit cannot be 0"); - } - - //no unlimited users - $q = "UPDATE usr_data set time_limit_unlimited=0, time_limit_until='" . $this->db->quote($new_time_limit_ts, \ilDBConstants::T_INTEGER) . "' WHERE time_limit_unlimited=1 AND login NOT IN ('root','anonymous') AND ext_account NOT LIKE '%@eduid.ch'"; - $this->db->manipulate($q); - } - - private function setUserTimeLimitsToAMaxValue(int $until_max_ts) : void - { - if ($until_max_ts === 0) { - throw new \InvalidArgumentException("Error in setting user time limits to max value: Until Max cannot be 0"); - } - - //all users are constraint to a value defined in the configuration - $q = "UPDATE usr_data set time_limit_until='" . $this->db->quote($until_max_ts, \ilDBConstants::T_INTEGER) . "'" - . " WHERE time_limit_until>'" . $this->db->quote($until_max_ts, \ilDBConstants::T_INTEGER) . "'"; - $this->db->manipulate($q); - } - - private function setUserTimeLimitsBelowThresholdToGivenValue(int $min_threshold_in_days, int $new_time_limit_ts) : void - { - if ($new_time_limit_ts === 0) { - throw new \InvalidArgumentException("Error in setting user time limits to new value: New time limit cannot be 0"); - } - - //all users have at least 90 days of access (needed for Shibboleth) - $q = "UPDATE `usr_data` SET time_limit_until=time_limit_until+" . $this->db->quote($new_time_limit_ts, \ilDBConstants::T_INTEGER) - . " WHERE DATEDIFF(FROM_UNIXTIME(time_limit_until),create_date)< " . $this->db->quote($min_threshold_in_days, \ilDBConstants::T_INTEGER); - $this->db->manipulate($q); - } } diff --git a/classes/import/data_management/ilias_core_services/MembershipablesEventInTreeSeeker.php b/classes/import/data_management/ilias_core_services/MembershipablesEventInTreeSeeker.php index 0cbace6..8c42405 100644 --- a/classes/import/data_management/ilias_core_services/MembershipablesEventInTreeSeeker.php +++ b/classes/import/data_management/ilias_core_services/MembershipablesEventInTreeSeeker.php @@ -18,12 +18,14 @@ public function recursiveSearchSubGroups(int $parent_ref_id, array $sub_group_li foreach ($this->tree->getChilds($parent_ref_id) as $child_node) { $child_ref_id = (int) $child_node['ref_id']; $type = $child_node['type']; - if ($type == 'grp') { + if ($type === 'grp') { $sub_group_list[$child_ref_id] = $child_ref_id; if ($search_below_groups) { $sub_group_list = $this->recursiveSearchSubGroups($child_ref_id, $sub_group_list, $search_below_groups); } - } elseif ($type == 'fold') { + } + + if ($type === 'fold') { $sub_group_list = $this->recursiveSearchSubGroups($child_ref_id, $sub_group_list, $search_below_groups); } } @@ -58,20 +60,25 @@ public function getRefIdsOfParentMembershipables(int $src_ref_id) : array do { $current_obj_ref = (int) $this->tree->getParentId($current_obj_ref); $type = $this->lookupObjTypeByRefId($current_obj_ref); - if ($type == 'crs') { + + if ($type === "") { + throw new \ilException("Parent event of $src_ref_id, which has the ref id $current_obj_ref seems not to have a type declared"); + } + + if ($type === 'crs') { $parent_membershipable_objs[] = $current_obj_ref; $has_found_super_parent = true; - } elseif ($type == 'grp') { + } elseif ($type === 'grp') { $parent_membershipable_objs[] = $current_obj_ref; - } elseif ($type == 'cat' || $type == 'root') { + } elseif ($type === 'cat' || $type === 'root') { $has_found_super_parent = true; - } elseif ($type == "") { - throw new \ilException("Parent event of $src_ref_id, which has the ref id $current_obj_ref seems not to have a type declared"); } if ($deadlock_prevention++ > 15) { throw new \ilException("Event with the ref_id of " . $src_ref_id . " seems to have either over 15 parent objects or there is a circular connection in the Repository-Tree"); - } elseif ($current_obj_ref <= 1) { + } + + if ($current_obj_ref <= 1) { throw new \ilException("Event with the ref_id of $src_ref_id seems to be either in root or has no category above it"); } } while (!$has_found_super_parent); diff --git a/classes/import/data_management/import_data/IliasEventoEventObjectRepository.php b/classes/import/data_management/import_data/IliasEventoEventObjectRepository.php index 47b0b97..8b5d895 100644 --- a/classes/import/data_management/import_data/IliasEventoEventObjectRepository.php +++ b/classes/import/data_management/import_data/IliasEventoEventObjectRepository.php @@ -54,15 +54,9 @@ public function addNewEventoIliasEvent(IliasEventoEvent $ilias_evento_event) // foreign keys IliasEventoEventsTblDef::COL_REF_ID => [\ilDBConstants::T_INTEGER, $ilias_evento_event->getRefId()], IliasEventoEventsTblDef::COL_OBJ_ID => [\ilDBConstants::T_INTEGER, $ilias_evento_event->getObjId()], - IliasEventoEventsTblDef::COL_ADMIN_ROLE_ID => [\ilDBConstants::T_INTEGER, - $ilias_evento_event->getAdminRoleId() - ], - IliasEventoEventsTblDef::COL_STUDENT_ROLE_ID => [\ilDBConstants::T_INTEGER, - $ilias_evento_event->getStudentRoleId() - ], - IliasEventoEventsTblDef::COL_PARENT_EVENT_KEY => [\ilDBConstants::T_TEXT, - $ilias_evento_event->getParentEventKey() - ] + IliasEventoEventsTblDef::COL_ADMIN_ROLE_ID => [\ilDBConstants::T_INTEGER, $ilias_evento_event->getAdminRoleId()], + IliasEventoEventsTblDef::COL_STUDENT_ROLE_ID => [\ilDBConstants::T_INTEGER, $ilias_evento_event->getStudentRoleId()], + IliasEventoEventsTblDef::COL_PARENT_EVENT_KEY => [\ilDBConstants::T_TEXT, $ilias_evento_event->getParentEventKey()] ] ); } @@ -83,9 +77,32 @@ public function addNewParentEvent(IliasEventoParentEvent $parent_event) : void IliasParentEventTblDef::COL_TITLE => [\ilDBConstants::T_TEXT, $parent_event->getTitle()], IliasParentEventTblDef::COL_REF_ID => [\ilDBConstants::T_INTEGER, $parent_event->getRefId()], IliasParentEventTblDef::COL_ADMIN_ROLE_ID => [\ilDBConstants::T_INTEGER, $parent_event->getAdminRoleId()], - IliasParentEventTblDef::COL_STUDENT_ROLE_ID => [\ilDBConstants::T_INTEGER, - $parent_event->getStudentRoleId() - ], + IliasParentEventTblDef::COL_STUDENT_ROLE_ID => [\ilDBConstants::T_INTEGER, $parent_event->getStudentRoleId()], + ] + ); + } + + public function updateExistingParentEvent(IliasEventoParentEvent $parent_event) : void + { + $this->db->update( + // UPDATE + IliasParentEventTblDef::TABLE_NAME, + + // VALUES + [ + // id + IliasParentEventTblDef::COL_GROUP_EVENTO_ID => [\ilDBConstants::T_INTEGER, $parent_event->getGroupEventoId()], + + // foreign keys + IliasParentEventTblDef::COL_TITLE => [\ilDBConstants::T_TEXT, $parent_event->getTitle()], + IliasParentEventTblDef::COL_REF_ID => [\ilDBConstants::T_INTEGER, $parent_event->getRefId()], + IliasParentEventTblDef::COL_ADMIN_ROLE_ID => [\ilDBConstants::T_INTEGER, $parent_event->getAdminRoleId()], + IliasParentEventTblDef::COL_STUDENT_ROLE_ID => [\ilDBConstants::T_INTEGER, $parent_event->getStudentRoleId()] + ], + + // WHERE + [ + IliasParentEventTblDef::COL_GROUP_UNIQUE_KEY => [\ilDBConstants::T_TEXT, $parent_event->getGroupUniqueKey()] ] ); } @@ -200,7 +217,7 @@ private function buildIliasEventoEventFromRow(array $row) return new IliasEventoEvent( $row[IliasEventoEventsTblDef::COL_EVENTO_ID], $row[IliasEventoEventsTblDef::COL_EVENTO_TITLE], - $row[IliasEventoEventsTblDef::COL_EVENTO_DESCRIPTION], + substr($row[IliasEventoEventsTblDef::COL_EVENTO_DESCRIPTION],0, 128), $row[IliasEventoEventsTblDef::COL_EVENTO_TYPE], $row[IliasEventoEventsTblDef::COL_WAS_AUTOMATICALLY_CREATED], $this->toDateTimeOrNull($row[IliasEventoEventsTblDef::COL_START_DATE]), diff --git a/classes/import/data_management/import_data/IliasEventoUserRepository.php b/classes/import/data_management/import_data/IliasEventoUserRepository.php index 2b57347..95d84b7 100644 --- a/classes/import/data_management/import_data/IliasEventoUserRepository.php +++ b/classes/import/data_management/import_data/IliasEventoUserRepository.php @@ -19,21 +19,11 @@ public function __construct(\ilDBInterface $db) $this->db = $db; } - public function addNewEventoIliasUserByEventoUser(EventoUser $evento_user, \ilObjUser $ilias_user, string $account_type) : IliasEventoUser - { - return $this->addNewEventoIliasUser($evento_user->getEventoId(), (int) $ilias_user->getId(), $account_type); - } - - public function addNewEventoIliasUserByEventoUserShort( - EventoUserShort $evento_user, - \ilObjUser $ilias_user, + public function addNewEventoIliasUser( + int $evento_id, + int $ilias_user_id, string $account_type ) : IliasEventoUser { - return $this->addNewEventoIliasUser($evento_user->getEventoId(), (int) $ilias_user->getId(), $account_type); - } - - private function addNewEventoIliasUser(int $evento_id, int $ilias_user_id, string $account_type) : IliasEventoUser - { $this->db->insert( // INSERT INTO IliasEventoUserTblDef::TABLE_NAME, @@ -105,17 +95,28 @@ public function getListOfIliasUserIdsByEventoIds(array $evento_ids) : array return $user_ids; } - public function registerUserAsDelivered(int $evento_id) : void + public function registerUserAsDelivered(int $evento_id, int $ilias_user_id) : void { - $this->db->update( - IliasEventoUserTblDef::TABLE_NAME, - [ - IliasEventoUserTblDef::COL_LAST_TIME_DELIVERED => [\ilDBConstants::T_DATETIME, date("Y-m-d H:i:s")] - ], - [ - IliasEventoUserTblDef::COL_EVENTO_ID => [\ilDBConstants::T_INTEGER, $evento_id] - ] - ); + $eventoUser = $this->getIliasEventoUserByEventoId($evento_id); + if(!is_null($eventoUser)) { + $this->db->update( + IliasEventoUserTblDef::TABLE_NAME, + [ + IliasEventoUserTblDef::COL_LAST_TIME_DELIVERED => [\ilDBConstants::T_DATETIME, date("Y-m-d H:i:s")] + ], + [ + IliasEventoUserTblDef::COL_EVENTO_ID => [\ilDBConstants::T_INTEGER, $evento_id] + ] + ); + } + else{ + // do insert + $this->addNewEventoIliasUser( + $evento_id, + $ilias_user_id, + IliasEventoUserRepository::TYPE_HSLU_AD + ); + } } public function getUsersWithLastImportOlderThanGivenDays(int $min_days_not_delivered, string $only_searched_account_type) : array diff --git a/classes/import/data_management/import_data/model/IliasEventoEvent.php b/classes/import/data_management/import_data/model/IliasEventoEvent.php index 038282c..3d3eaed 100644 --- a/classes/import/data_management/import_data/model/IliasEventoEvent.php +++ b/classes/import/data_management/import_data/model/IliasEventoEvent.php @@ -118,7 +118,7 @@ public function getEventoTitle() : string public function getEventoDescription() : string { - return $this->evento_description; + return substr($this->evento_description,0, 128); } public function isSubGroupEvent() : bool @@ -132,7 +132,7 @@ public function switchToAnotherIliasObejct(\ilObject $new_object, bool $was_auto $clone->obj_id = $new_object->getId(); $clone->ref_id = $new_object->getRefId(); $clone->ilias_type = $new_object->getType(); - if($new_object instanceof \ilObjCourse || $new_object instanceof \ilObjGroup) { + if ($new_object instanceof \ilObjCourse || $new_object instanceof \ilObjGroup) { $clone->student_role_id = (int) $new_object->getDefaultMemberRole(); $clone->admin_role_id = (int) $new_object->getDefaultAdminRole(); } diff --git a/lang/ilias_de.lang b/lang/ilias_de.lang index 531f42e..d9ab676 100644 --- a/lang/ilias_de.lang +++ b/lang/ilias_de.lang @@ -28,8 +28,12 @@ daily_import_cj_desc#:#Vollständiger Import von Evento Benutzern und Modulanlä daily_import_cj_title#:#Evento Import: Täglich laufender Import default_user_role#:#Standard Benutzerrolle default_user_role_desc#:#ID der standard Benutzerrolle, die allen importierten Accounts zugeteilt werden soll. +delete_from_admins_on_removal#:#Aus Admin Rollen entfernen +delete_from_admins_on_removal_desc#:#Nutzer:innen, die dieser Rolle zugeordnet sind, werden beim Entfernen daraus auch aus allen anderen ihnen zugeordneten Kurs-Administrations-Rollen entfernt. description#:#Aktualisiert die ILIAS-Benutzer über die HSLU-SOAP-Schnittstelle zu Evento. Neben den Benutzern werden auch ihre Mitgliedschaften in Kursen und Gruppen aktualisiert. event_import_settings#:#Anlassimport Einstellungen +follow_up_role_mapping#:#Nachfolgerollen +follow_up_role_mapping_desc#:#Hier kann festgelegt werden, ob und wenn ja in welche Rolle eine Nutzer:in eingetragen werden soll, nachdem sie aus einer von Evento verwalteten Rolle ausgetragen wird. Wird eine Änderung im Abschnitt "Zuordnung zusätzlicher ILIAS-Rollen zu erhaltenen Evento-Rollen" vorgenommen, muss gespeichert werden, damit die Änderung in diesem Abschnitt sichtbar wird. hourly_import_cj_desc#:#Importiert in Admin-Rollen eingetragene Benutzer nach ILIAS und trägt sie in die entsprechenden Kurse und Gruppen (gemäss Modulanlass) ein hourly_import_cj_title#:#Evento Import: Stündlich laufender Import import_additional_roles_desc#:#Alle Benutzer, die über die Operation '%s' importiert werden, werden zusätzlich dieser Rolle hinzugefügt. @@ -56,17 +60,11 @@ settings_for_import_operation_header#:#Einstellungen für die Import-Operation standard_user_role_id#:#Standard Benutzerrolle standard_user_role_id_desc#:#ID der standard Benutzerrolle, die allen Nutzern zugeteilt werden soll. title#:#Benutzer über Evento-SOAP-Schnittstelle aktualisieren +track_removal_custom_field#:#Benutzerfeld zur Speicherung des Entfernungsdatums +track_removal_custom_field_desc#:#Wird hier ein Benutzerfeld ausgewählt, wird in diesem das Datum gespeichert, wenn die Nutzer:in aus der entsprechenden Rolle entfernt wurde. user_auth_mode#:#Authmode neuer Benutzer user_auth_mode_desc#:#Neu abgelegte ILIAS-Benutzer erhalten diesen Authentifizierungsmechanismus zugewiesen -user_changed_mail_body#:#Mail Text -user_changed_mail_body_desc#:#Bitte hier den Text für das E-Mail eingeben, welches bei einer Änderung des Benutzernamens an den Benutzer gesendet wir (ohne Anrede). Die Platzhalter [oldlogin], [newlogin] und [email] werden durch die entsprechenden Angaben des Benutzers ersetzt. -user_changed_mail_subject#:#Mail Betreff -user_changed_mail_subject_desc#:#Bitte hier den Betreff für das E-Mail eingeben, welches bei einer Änderung des Benutzernamens an den Benutzer gesendet wird. -user_import_account_duration#:#Gültigkeit von importierten Account -user_import_account_duration_desc#:#Vom Importer erstellte Accounts erhalten diese Gültigkeitsdauer (in Monaten). user_import_settings#:#Benutzerimport Einstellungen -user_max_account_duration#:#Maximale gültigkeit von Accounts -user_max_account_duration_desc#:#Maximale Gültigkeitsdauer für einen Account in Monaten. Werden unlimitierte Accounts oder Accounts mit längerer Gültigkeit erstellt, werden sie auf diese Dauer beschränkt. 0 bedeutet, dass es keine Einschränkungen gibt. user_student_role_id#:#Studierenden Rollen ID user_student_role_id_desc#:#Rollen ID der Studierenden Rolle. Accounts in dieser Rolle, welche vom Import als gelöscht markiert werden, sind noch 1 Jahr lang als lokale Accounts gültig. user_type_specific_settings_header#:#Einstellungen für Benutzergruppe '%s' diff --git a/lang/ilias_en.lang b/lang/ilias_en.lang index faa0716..5eb913e 100644 --- a/lang/ilias_en.lang +++ b/lang/ilias_en.lang @@ -7,7 +7,7 @@ account_duration_desc#:#Accounts created by this cron job have this validity (in additional_roles_desc#:#Users imported through the operation '%s' will additionally be added to the chosen global roles. additional_roles_header#:#Additional global roles for '%s' additional_roles_info#:#Additional global roles -additional_user_roles_mapping#:#Assignment of addintional global ILIAS roles to given roles by Evento +additional_user_roles_mapping#:#Assignment of additional global ILIAS roles to given roles by Evento api_max_pages#:#Max amount of pages api_max_pages_desc#:#How many pages should be request? Use -1 to request all pages api_max_retries#:#Max retries @@ -33,11 +33,15 @@ daily_import_cj_desc#:#Import of Evento users und events to ILIAS. daily_import_cj_title#:#Evento Import: Daily import default_user_role#:#Default user role default_user_role_desc#:#ID of the default user role. This role will be assigned to all imported users. +delete_from_admins_on_removal#:#Delete from Admins +delete_from_admins_on_removal_desc#:#Users assigned to this Role will be removed from all Coure-Admin-Roles, when the assignement to this role is removed. description#:#Updates all ILIAS-Users by querying the HSLU Soap interface to Evento. Users and Course-Memberships are updated email_account_changed_body#:#Text email_account_changed_body_desc#:#Please enter a text for the e-mail sent out to users who's login-name needed to be changed (without salutation). The following tags will be replaced by the corresponding user-information: [oldlogin], [newlogin] and [email]. email_account_changed_subject_desc#:#Please enter a subject-line for the e-mail sent out to users who's login-name needed to be changed. event_import_settings#:#Event import settings +follow_up_role_mapping#:#Follow-up Roles +follow_up_role_mapping_desc#:#You can define, if a user should be assigned to another role, once deassigned from a role managed by Evento. After changing anything under "Assignment of additional global ILIAS roles to given roles by Evento", you need to save once, for the changes to become visible here hourly_import_cj_desc#:#Imports users registered in admin roles to ILIAS and enters them in the corresponding courses and groups (according to given events) hourly_import_cj_title#:#Evento Import: Hourly Import ilias_auth_mode#:#Authmode of new users @@ -74,19 +78,11 @@ settings_for_operation_header#:#Settings for the '%s' operation standard_user_role_id#:#Default User Role standard_user_role_id_desc#:#ID of the default user role assigned to all users. title#:#Update Users from Evento-Soap Interface +track_removal_custom_field#:#Track Removal from Role in Custom Field +track_removal_custom_field_desc#:#If a custom field is selected here, this field will be used to store the date the user was removed from this role. user_auth_mode#:#Authmode of new users user_auth_mode_desc#:#Newly created ILIAS-Users will use this authentication mode -user_changed_mail_body#:#Mail body -user_changed_mail_body_desc#:#Please enter here the text for the email that will be sent to the user when the user name is changed (without salutation). The placeholders [oldlogin], [newlogin] and [email] will be replaced by the corresponding information of the user. -user_changed_mail_subject#:#Mail subject -user_changed_mail_subject_desc#:#Please enter here the subject for the e-mail that will be sent to the user when the username is changed. -user_import_account_duration#:#Account duration for imported users -user_import_account_duration_desc#:#Number of moths for which the user accounts created by the import will be accessible user_import_settings#:#User Import settings -user_max_account_duration#:#Max account duration -user_max_account_duration_desc#:#Maximum validity period for an account in months. If unlimited accounts or accounts with longer validity are created, they will be limited to this duration. 0 means that there are no restrictions. -user_student_role_id#:#Student Role ID -user_student_role_id_desc#:#ID of the student role. Accounts with this role, which are marked as deleted by the import, are still valid for 1 year as local accounts. user_type_specific_settings_header#:#Settings for the user group '%s' ws_password#:#SOAP Password ws_password_desc#:#Password to access the SOAP Interface