diff --git a/hook.php b/hook.php index bda7d3c9..edd9837c 100644 --- a/hook.php +++ b/hook.php @@ -33,15 +33,12 @@ * Entry point for installation process */ function plugin_flyvemdm_install() { - $version = plugin_version_flyvemdm(); - $migration = new Migration($version['version']); - require_once(PLUGIN_FLYVEMDM_ROOT . "/install/install.class.php"); - spl_autoload_register([PluginFlyvemdmInstall::class, 'autoload']); - $install = new PluginFlyvemdmInstall(); - if (!$install->isPluginInstalled()) { - return $install->install($migration); - } - return $install->upgrade($migration); + global $DB; + + require_once(PLUGIN_FLYVEMDM_ROOT . "/install/installer.class.php"); + $installer = new PluginFlyvemdmInstaller(); + + return $installer->install(); } /** @@ -49,10 +46,10 @@ function plugin_flyvemdm_install() { * @return boolean True if success */ function plugin_flyvemdm_uninstall() { - require_once(PLUGIN_FLYVEMDM_ROOT . "/install/install.class.php"); - $install = new PluginFlyvemdmInstall(); + require_once(PLUGIN_FLYVEMDM_ROOT . "/install/installer.class.php"); + $installer = new PluginFlyvemdmInstaller(); - return $install->uninstall(); + return $installer->uninstall(); } /** @@ -158,11 +155,9 @@ function plugin_Flyvemdm_addDefaultWhere($itemtype) { case PluginFlyvemdmAgent::class: return PluginFlyvemdmAgent::addDefaultWhere(); - case PluginFlyvemdmFDroidApplication::class: { + case PluginFlyvemdmFDroidApplication::class: return PluginFlyvemdmFDroidApplication::addDefaultWhere(); - } } - } /** diff --git a/install/installer.class.php b/install/installer.class.php new file mode 100644 index 00000000..5544b88d --- /dev/null +++ b/install/installer.class.php @@ -0,0 +1,1031 @@ +migration = new Migration(PLUGIN_FLYVEMDM_VERSION); + $this->migration->setVersion(PLUGIN_FLYVEMDM_VERSION); + + // adding DB model from sql file + // TODO : migrate in-code DB model setup here + if (self::getCurrentVersion() == '') { + // Setup DB model + $dbFile = PLUGIN_FLYVEMDM_ROOT . "/install/mysql/plugin_flyvemdm_empty.sql"; + if (!$DB->runFile($dbFile)) { + $this->migration->displayWarning("Error creating tables : " . $DB->error(), true); + return false; + } + + $this->createInitialConfig(); + } else { + if (PluginFlyvemdmCommon::endsWith(PLUGIN_FLYVEMDM_VERSION, + "-dev") || (version_compare(self::getCurrentVersion(), + PLUGIN_FLYVEMDM_VERSION) != 0)) { + // TODO : Upgrade (or downgrade) + $this->upgrade(self::getCurrentVersion()); + } + } + + $this->migration->executeMigration(); + + if (version_compare(GLPI_VERSION, '9.3.0') >= 0) { + $this->migrateToInnodb(); + } + $this->createDirectories(); + $this->createFirstAccess(); + $this->createGuestProfileAccess(); + $this->createAgentProfileAccess(); + $this->createDefaultFleet(); + $this->createPolicies(); + $this->createNotificationTargetInvitation(); + $this->createJobs(); + $this->createRootEntityConfig(); + $this->createDisplayPreferences(); + + Config::setConfigurationValues('flyvemdm', ['version' => PLUGIN_FLYVEMDM_VERSION]); + + return true; + } + + /** + * Find a profile having the given comment, or create it + * @param string $name Name of the profile + * @param string $comment Comment of the profile + * @return integer profile ID + */ + protected static function getOrCreateProfile($name, $comment) { + global $DB; + + $comment = $DB->escape($comment); + $profile = new Profile(); + $profiles = $profile->find("`comment`='$comment'"); + $row = array_shift($profiles); + if ($row === null) { + $profile->fields["name"] = $DB->escape(__($name, "flyvemdm")); + $profile->fields["comment"] = $comment; + $profile->fields["interface"] = "central"; + if ($profile->addToDB() === false) { + die("Error while creating users profile : $name\n\n" . $DB->error()); + } + return $profile->getID(); + } else { + return $row['id']; + } + } + + public function createDirectories() { + // Create directory for uploaded applications + if (!file_exists(FLYVEMDM_PACKAGE_PATH)) { + if (!mkdir(FLYVEMDM_PACKAGE_PATH, 0770, true)) { + $this->migration->displayWarning("Cannot create " . FLYVEMDM_PACKAGE_PATH . " directory"); + } else { + if (!$htAccessHandler = fopen(FLYVEMDM_PACKAGE_PATH . "/.htaccess", "w")) { + fwrite($htAccessHandler, + "allow from all\n") or $this->migration->displayWarning("Cannot create .htaccess file in packages directory\n"); + fclose($htAccessHandler); + } + } + } + + // Create directory for uploaded files + if (!file_exists(FLYVEMDM_FILE_PATH)) { + if (!mkdir(FLYVEMDM_FILE_PATH, 0770, true)) { + $this->migration->displayWarning("Cannot create " . FLYVEMDM_FILE_PATH . " directory"); + } else { + if (!$htAccessHandler = fopen(FLYVEMDM_FILE_PATH . "/.htaccess", "w")) { + fwrite($htAccessHandler, + "allow from all\n") or $this->migration->displayWarning("Cannot create .htaccess file in files directory\n"); + fclose($htAccessHandler); + } + } + } + + // Create cache directory for the template engine + PluginFlyvemdmCommon::recursiveRmdir(FLYVEMDM_TEMPLATE_CACHE_PATH); + if (!mkdir(FLYVEMDM_TEMPLATE_CACHE_PATH, 0770, true)) { + $this->migration->displayWarning("Cannot create " . FLYVEMDM_TEMPLATE_CACHE_PATH . " directory"); + } + } + + /** + * @return null|string + */ + public static function getCurrentVersion() { + if (self::$currentVersion === null) { + $config = \Config::getConfigurationValues('flyvemdm', ['version']); + if (!isset($config['version'])) { + self::$currentVersion = ''; + } else { + self::$currentVersion = $config['version']; + } + } + return self::$currentVersion; + } + + protected function createRootEntityConfig() { + $entityConfig = new PluginFlyvemdmEntityConfig(); + $entityConfig->getFromDBByCrit([ + 'entities_id' => '0', + ]); + if ($entityConfig->isNewItem()) { + $entityConfig->add([ + 'id' => '0', + 'entities_id' => '0', + 'download_url' => PLUGIN_FLYVEMDM_AGENT_DOWNLOAD_URL, + 'agent_token_life' => PluginFlyvemdmAgent::DEFAULT_TOKEN_LIFETIME, + ]); + } + } + + /** + * Give all rights on the plugin to the profile of the current user + */ + protected function createFirstAccess() { + $profileRight = new ProfileRight(); + + $newRights = [ + PluginFlyvemdmAgent::$rightname => READ | UPDATE | PURGE | READNOTE | UPDATENOTE, + PluginFlyvemdmFleet::$rightname => ALLSTANDARDRIGHT | READNOTE | UPDATENOTE, + PluginFlyvemdmPackage::$rightname => ALLSTANDARDRIGHT | READNOTE | UPDATENOTE, + PluginFlyvemdmFile::$rightname => ALLSTANDARDRIGHT | READNOTE | UPDATENOTE, + PluginFlyvemdmGeolocation::$rightname => ALLSTANDARDRIGHT | READNOTE | UPDATENOTE, + PluginFlyvemdmPolicy::$rightname => READ, + PluginFlyvemdmPolicyCategory::$rightname => READ, + PluginFlyvemdmWellknownpath::$rightname => ALLSTANDARDRIGHT, + PluginFlyvemdmProfile::$rightname => PluginFlyvemdmProfile::RIGHT_FLYVEMDM_USE, + PluginFlyvemdmEntityConfig::$rightname => READ + | PluginFlyvemdmEntityConfig::RIGHT_FLYVEMDM_DEVICE_COUNT_LIMIT + | PluginFlyvemdmEntityConfig::RIGHT_FLYVEMDM_APP_DOWNLOAD_URL + | PluginFlyvemdmEntityConfig::RIGHT_FLYVEMDM_INVITATION_TOKEN_LIFE, + PluginFlyvemdmInvitation::$rightname => ALLSTANDARDRIGHT, + PluginFlyvemdmInvitationLog::$rightname => READ, + PluginFlyvemdmTaskstatus::$rightname => READ, + ]; + + $profileRight->updateProfileRights($_SESSION['glpiactiveprofile']['id'], $newRights); + + $_SESSION['glpiactiveprofile'] = $_SESSION['glpiactiveprofile'] + $newRights; + } + + protected function createDefaultFleet() { + $fleet = new PluginFlyvemdmFleet(); + $request = [ + 'AND' => [ + 'is_default' => '1', + Entity::getForeignKeyField() => '0' + ] + ]; + if (!$fleet->getFromDBByCrit($request)) { + $fleet->add([ + 'name' => __('not managed fleet', 'flyvemdm'), + 'entities_id' => '0', + 'is_recursive' => '0', + 'is_default' => '1', + ]); + } + } + + /** + * Create a profile for guest users + */ + protected function createGuestProfileAccess() { + // create profile for guest users + $profileId = self::getOrCreateProfile( + __("Flyve MDM guest users", "flyvemdm"), + __("guest Flyve MDM users. Created by Flyve MDM - do NOT modify this comment.", "flyvemdm") + ); + Config::setConfigurationValues('flyvemdm', ['guest_profiles_id' => $profileId]); + $profileRight = new ProfileRight(); + $profileRight->updateProfileRights($profileId, [ + PluginFlyvemdmAgent::$rightname => READ | CREATE, + PluginFlyvemdmFile::$rightname => READ, + PluginFlyvemdmPackage::$rightname => READ, + ]); + } + + /** + * Create a profile for agent user accounts + */ + protected function createAgentProfileAccess() { + // create profile for guest users + $profileId = self::getOrCreateProfile( + __("Flyve MDM device agent users", "flyvemdm"), + __("device agent Flyve MDM users. Created by Flyve MDM - do NOT modify this comment.", + "flyvemdm") + ); + Config::setConfigurationValues('flyvemdm', ['agent_profiles_id' => $profileId]); + $profileRight = new ProfileRight(); + $profileRight->updateProfileRights($profileId, [ + PluginFlyvemdmAgent::$rightname => READ, + PluginFlyvemdmFile::$rightname => READ, + PluginFlyvemdmPackage::$rightname => READ, + PluginFlyvemdmEntityConfig::$rightname => READ, + ]); + } + + /** + * Create policies in DB + */ + protected function createPolicies() { + $policy = new PluginFlyvemdmPolicy(); + foreach (self::getPolicies() as $policyData) { + // Import the policy category or find the existing one + $category = new PluginFlyvemdmPolicyCategory(); + $categoryId = $category->import([ + 'completename' => $policyData['plugin_flyvemdm_policycategories_id'], + ]); + $policyData['plugin_flyvemdm_policycategories_id'] = $categoryId; + + $symbol = $policyData['symbol']; + $rows = $policy->find("`symbol`='$symbol'"); + $policyData['type_data'] = json_encode($policyData['type_data'], + JSON_UNESCAPED_SLASHES + ); + if (count($rows) == 0) { + // Create only non existing policy objects + $policy->add($policyData); + } else { + // Update default value and recommended value for existing policy objects + $policy2 = new PluginFlyvemdmPolicy(); + $policy2->getFromDBBySymbol($symbol); + $policy2->update([ + 'id' => $policy2->getID(), + 'default_value' => $policyData['default_value'], + 'recommended_value' => $policyData['recommended_value'], + 'type_data' => $policyData['type_data'], + 'android_min_version' => $policyData['android_min_version'], + 'android_max_version' => $policyData['android_max_version'], + 'apple_min_version' => $policyData['apple_min_version'], + 'apple_max_version' => $policyData['apple_max_version'], + 'plugin_flyvemdm_policycategories_id' => $categoryId, + ]); + } + } + } + + /** + * @return array + */ + protected function getNotificationTargetInvitationEvents() { + // Force locale for localized strings + $currentLocale = $_SESSION['glpilanguage']; + Session::loadLanguage('en_GB'); + + $notifications = [ + PluginFlyvemdmNotificationTargetInvitation::EVENT_GUEST_INVITATION => [ + 'itemtype' => PluginFlyvemdmInvitation::class, + 'name' => __('User invitation', 'flyvemdm'), + 'subject' => 'You have been invited to join Flyve MDM', 'flyvemdm', + 'content_text' => 'Hi, + +##user.firstname## ##user.realname## invited you to enroll your mobile device +in Flyve Mobile Device Managment (Flyve MDM). Flyve MDM allows administrators +to easily manage and administrate mobile devices. For more information, +please contact ##user.firstname## ##user.realname## to his email address +##user.email##. + +Please join the Flyve Mobile Device Management system by downloading +and installing the Flyve MDM application for Android from the following link. + +##flyvemdm.download_app## + +If you\'re viewing this email from a computer flash the QR code you see below +with the Flyve MDM Application. + +If you\'re viewing this email from your device to enroll then tap the +following link or copy it to your browser. + +##flyvemdm.enroll_url## + +Regards, + +', + 'content_html' => 'Hi, + +##user.firstname## ##user.realname## invited you to enroll your mobile device +in Flyve Mobile Device Managment (Flyve MDM). Flyve MDM allows administrators +to easily manage and administrate mobile devices. For more information, +please contact ##user.firstname## ##user.realname## to his email address + +##user.email##. + +Please join the Flyve Mobile Device Management system by downloading +and installing the Flyve MDM application for Android from the following link. + +##flyvemdm.download_app## + +If you\'re viewing this email from a computer flash the QR code you see below +with the Flyve MDM Application. + +If you\'re viewing this email from your device to enroll then tap the +following link or copy it to your browser. + +##flyvemdm.enroll_url## + +Enroll QRCode + +Regards, + +', + ], + ]; + + // Restore user's locale + Session::loadLanguage($currentLocale); + + return $notifications; + } + + public function createNotificationTargetInvitation() { + // Create the notification template + $notification = new Notification(); + $template = new NotificationTemplate(); + $translation = new NotificationTemplateTranslation(); + $notificationTarget = new PluginFlyvemdmNotificationTargetInvitation(); + $notification_notificationTemplate = new Notification_NotificationTemplate(); + + foreach ($this->getNotificationTargetInvitationEvents() as $event => $data) { + $itemtype = $data['itemtype']; + if (count($template->find("`itemtype`='$itemtype' AND `name`='" . $data['name'] . "'")) < 1) { + // Add template + $templateId = $template->add([ + 'name' => addcslashes($data['name'], "'\""), + 'comment' => '', + 'itemtype' => $itemtype, + ]); + + // Add default translation + if (!isset($data['content_html'])) { + $contentHtml = self::convertTextToHtml($data['content_text']); + } else { + $contentHtml = self::convertTextToHtml($data['content_html']); + } + $translation->add([ + 'notificationtemplates_id' => $templateId, + 'language' => '', + 'subject' => addcslashes($data['subject'], "'\""), + 'content_text' => addcslashes($data['content_text'], "'\""), + 'content_html' => addcslashes(htmlentities($contentHtml), "'\""), + ]); + + // Create the notification + $notificationId = $notification->add([ + 'name' => addcslashes($data['name'], "'\""), + 'comment' => '', + 'entities_id' => 0, + 'is_recursive' => 1, + 'is_active' => 1, + 'itemtype' => $itemtype, + 'event' => $event, + ]); + + $notification_notificationTemplate->add([ + 'notifications_id' => $notificationId, + 'notificationtemplates_id' => $templateId, + 'mode' => Notification_NotificationTemplate::MODE_MAIL, + ]); + + $notificationTarget->add([ + 'items_id' => Notification::USER, + 'type' => Notification::USER_TYPE, + 'notifications_id' => $notificationId, + ]); + + } + } + } + + /** + * Upgrade the plugin to the current code version + * + * @param string $fromVersion + */ + protected function upgrade($fromVersion) { + switch ($fromVersion) { + case '2.0.0': + // Example : upgrade to version 3.0.0 + // $this->upgradeOneStep('3.0.0'); + case '3.0.0': + // Example : upgrade to version 4.0.0 + // $this->upgradeOneStep('4.0.0'); + + default: + } + if (PluginFlyvemdmCommon::endsWith(PLUGIN_FLYVEMDM_VERSION, "-dev")) { + $this->upgradeOneStep('dev'); + } + } + + /** + * Proceed to upgrade of the plugin to the given version + * + * @param string $toVersion + */ + protected function upgradeOneStep($toVersion) { + + ini_set("max_execution_time", "0"); + ini_set("memory_limit", "-1"); + + $suffix = str_replace('.', '_', $toVersion); + $includeFile = __DIR__ . "/upgrade/update_to_$suffix.php"; + if (is_readable($includeFile) && is_file($includeFile)) { + include_once $includeFile; + $updateFunction = "plugin_flyvemdm_update_to_$suffix"; + if (function_exists($updateFunction)) { + $this->migration->addNewMessageArea("Upgrade to $toVersion"); + $updateFunction($this->migration); + $this->migration->executeMigration(); + $this->migration->displayMessage('Done'); + } + } + } + + protected function createJobs() { + CronTask::Register(PluginFlyvemdmPackage::class, 'ParseApplication', MINUTE_TIMESTAMP, + [ + 'comment' => __('Parse uploaded applications to collect metadata', 'flyvemdm'), + 'mode' => CronTask::MODE_EXTERNAL, + ]); + } + + /** + * Uninstall the plugin + * @return boolean true (assume success, needs enhancement) + */ + public function uninstall() { + $this->rrmdir(GLPI_PLUGIN_DOC_DIR . '/flyvemdm'); + + $this->deleteRelations(); + $this->deleteNotificationTargetInvitation(); + $this->deleteProfileRights(); + $this->deleteProfiles(); + $this->deleteDisplayPreferences(); + $this->deleteTables(); + // Cron jobs deletion handled by GLPI + + $config = new Config(); + $config->deleteByCriteria(['context' => 'flyvemdm']); + + return true; + } + + /** + * Cannot use the method from PluginFlyvemdmToolbox if the plugin is being uninstalled + * @param string $dir + */ + protected function rrmdir($dir) { + if (file_exists($dir) && is_dir($dir)) { + $objects = scandir($dir); + foreach ($objects as $object) { + if ($object != "." && $object != "..") { + if (filetype($dir . "/" . $object) == "dir") { + $this->rrmdir($dir . "/" . $object); + } else { + unlink($dir . "/" . $object); + } + } + } + reset($objects); + rmdir($dir); + } + } + + /** + * Generate default configuration for the plugin + */ + protected function createInitialConfig() { + $MdmMqttPassword = PluginFlyvemdmMqttuser::getRandomPassword(); + + // New config management provided by GLPi + $crypto_strong = null; + $instanceId = base64_encode(openssl_random_pseudo_bytes(64, $crypto_strong)); + $newConfig = [ + 'mqtt_broker_address' => '', + 'mqtt_broker_internal_address' => '127.0.0.1', + 'mqtt_broker_port' => '1883', + 'mqtt_broker_tls_port' => '8883', + 'mqtt_tls_for_clients' => '0', + 'mqtt_tls_for_backend' => '0', + 'mqtt_use_client_cert' => '0', + 'mqtt_broker_tls_ciphers' => self::DEFAULT_CIPHERS_LIST, + 'mqtt_user' => self::BACKEND_MQTT_USER, + 'mqtt_passwd' => $MdmMqttPassword, + 'instance_id' => $instanceId, + 'registered_profiles_id' => '', + 'guest_profiles_id' => '', + 'agent_profiles_id' => '', + 'service_profiles_id' => '', + 'debug_enrolment' => '0', + 'debug_noexpire' => '0', + 'debug_save_inventory' => '0', + 'ssl_cert_url' => '', + 'default_device_limit' => '0', + 'default_agent_url' => PLUGIN_FLYVEMDM_AGENT_DOWNLOAD_URL, + 'android_bugcollecctor_url' => '', + 'android_bugcollector_login' => '', + 'android_bugcollector_passwd' => '', + 'webapp_url' => '', + 'demo_mode' => '0', + 'demo_time_limit' => '0', + 'inactive_registered_profiles_id' => '', + 'computertypes_id' => '0', + 'agentusercategories_id' => '0', + 'invitation_deeplink' => PLUGIN_FLYVEMDM_DEEPLINK, + 'show_wizard' => PluginFlyvemdmConfig::WIZARD_WELCOME_BEGIN, + ]; + Config::setConfigurationValues('flyvemdm', $newConfig); + $this->createBackendMqttUser(self::BACKEND_MQTT_USER, $MdmMqttPassword); + } + + /** + * Create MQTT user for the backend and save credentials + * @param string $MdmMqttUser + * @param string $MdmMqttPassword + */ + protected function createBackendMqttUser($MdmMqttUser, $MdmMqttPassword) { + global $DB; + + // Create mqtt credentials for the plugin + $mqttUser = new PluginFlyvemdmMqttuser(); + + // Check the MQTT user account for the plugin exists + if ($mqttUser->getFromDBByCrit(['user' => $MdmMqttUser])) { + return; + } + // Create the MQTT user account for the plugin + if (!$mqttUser->add([ + 'user' => $MdmMqttUser, + 'password' => $MdmMqttPassword, + 'enabled' => '1', + '_acl' => [ + [ + 'topic' => '#', + 'access_level' => PluginFlyvemdmMqttacl::MQTTACL_READ_WRITE, + ], + ], + ])) { + // Failed to create the account + $this->migration->displayWarning('Unable to create the MQTT account for FlyveMDM : ' . $DB->error()); + } else { + // Check the ACL has been created + $aclList = $mqttUser->getACLs(); + $mqttAcl = array_shift($aclList); + if ($mqttAcl === null) { + $this->migration->displayWarning('Unable to create the MQTT ACL for FlyveMDM : ' . $DB->error()); + } + + // Save MQTT credentials in configuration + Config::setConfigurationValues('flyvemdm', + ['mqtt_user' => $MdmMqttUser, 'mqtt_passwd' => $MdmMqttPassword]); + } + } + + + /** + * Generate HTML version of a text + * Replaces \n by
+ * Encloses the text un

...

+ * Add anchor to URLs + * @param string $text + * @return string + */ + protected static function convertTextToHtml($text) { + $text = '

' . str_replace("\n\n", '

', $text) . '

'; + $text = '

' . str_replace("\n", '
', $text) . '

'; + return $text; + } + + /** + * @return array + */ + static public function getPolicyCategories() { + // Force locale for localized strings + $currentLocale = $_SESSION['glpilanguage']; + Session::loadLanguage('en_GB'); + + $categories = [ + [ + 'name' => __('Security', 'flyvemdm'), + ], + [ + 'name' => __('Authentication', 'flyvemdm'), + ], + [ + 'name' => __('Password', 'flyvemdm'), + ], + [ + 'name' => __('Encryption', 'flyvemdm'), + ], + [ + 'name' => __('Peripherals', 'flyvemdm'), + ], + [ + 'name' => __('Deployment', 'flyvemdm'), + ], + ]; + + // Restore user's locale + Session::loadLanguage($currentLocale); + + return $categories; + } + + /** + * Gets a reference array of policies installation or update of the plugin + * the link to the policy category contains the complete name of the category + * the caller is in charge of importing it and using the ID of the imported + * category to set the foreign key. + * + * @return array policies to add in DB on install + */ + static public function getPolicies() { + // Force locale for localized strings + $currentLocale = $_SESSION['glpilanguage']; + Session::loadLanguage('en_GB'); + + $policies = []; + foreach (glob(__DIR__ . '/policies/*.php') as $filename) { + $newPolicies = include $filename; + $policies = array_merge($policies, $newPolicies); + } + + // Restore user's locale + Session::loadLanguage($currentLocale); + + return $policies; + } + + protected function deleteNotificationTargetInvitation() { + global $DB; + + // Define DB tables + $tableTargets = NotificationTarget::getTable(); + $tableNotification = Notification::getTable(); + $tableTranslations = NotificationTemplateTranslation::getTable(); + $tableTemplates = NotificationTemplate::getTable(); + + foreach ($this->getNotificationTargetInvitationEvents() as $event => $data) { + $itemtype = $data['itemtype']; + $name = $data['name']; + //TODO : implement cleanup + // Delete translations + $query = "DELETE FROM `$tableTranslations` + WHERE `notificationtemplates_id` IN ( + SELECT `id` FROM `$tableTemplates` WHERE `itemtype` = '$itemtype' AND `name`='$name')"; + $DB->query($query); + + // Delete notification templates + $template = new NotificationTemplate(); + $template->deleteByCriteria(['itemtype' => $itemtype, 'name' => $name]); + + // Delete notification targets + $query = "DELETE FROM `$tableTargets` + WHERE `notifications_id` IN ( + SELECT `id` FROM `$tableNotification` WHERE `itemtype` = '$itemtype' AND `event`='$event')"; + $DB->query($query); + + // Delete notifications + $notification = new Notification(); + $notification_notificationTemplate = new Notification_NotificationTemplate(); + $rows = $notification->find("`itemtype` = '$itemtype' AND `event` = '$event'"); + foreach ($rows as $row) { + $notification_notificationTemplate->deleteByCriteria(['notifications_id' => $row['id']]); + $notification->delete($row); + } + } + } + + protected function deleteTables() { + global $DB; + + $tables = [ + PluginFlyvemdmAgent::getTable(), + PluginFlyvemdmEntityConfig::getTable(), + PluginFlyvemdmFile::getTable(), + PluginFlyvemdmInvitationlog::getTable(), + PluginFlyvemdmFleet::getTable(), + PluginFlyvemdmTask::getTable(), + PluginFlyvemdmGeolocation::getTable(), + PluginFlyvemdmInvitation::getTable(), + PluginFlyvemdmMqttacl::getTable(), + PluginFlyvemdmMqttlog::getTable(), + PluginFlyvemdmMqttuser::getTable(), + PluginFlyvemdmPackage::getTable(), + PluginFlyvemdmPolicy::getTable(), + PluginFlyvemdmPolicyCategory::getTable(), + PluginFlyvemdmWellknownpath::getTable(), + PluginFlyvemdmTaskstatus::getTable(), + ]; + + foreach ($tables as $table) { + $DB->query("DROP TABLE IF EXISTS `$table`"); + } + } + + protected function deleteProfiles() { + $config = Config::getConfigurationValues('flyvemdm', ['guest_profiles_id']); + + foreach ($config as $profileId) { + $profile = new Profile(); + $profile->getFromDB($profileId); + if ($profile->deleteFromDB()) { + $profileUser = new Profile_User(); + $profileUser->deleteByCriteria(['profiles_id' => $profileId], true); + } + } + } + + protected function deleteProfileRights() { + $rights = [ + PluginFlyvemdmAgent::$rightname, + PluginFlyvemdmFile::$rightname, + PluginFlyvemdmFleet::$rightname, + PluginFlyvemdmGeolocation::$rightname, + PluginFlyvemdmInvitation::$rightname, + PluginFlyvemdmInvitationlog::$rightname, + PluginFlyvemdmPackage::$rightname, + PluginFlyvemdmPolicy::$rightname, + PluginFlyvemdmProfile::$rightname, + PluginFlyvemdmWellknownpath::$rightname, + ]; + foreach ($rights as $right) { + ProfileRight::deleteProfileRights([$right]); + unset($_SESSION["glpiactiveprofile"][$right]); + } + } + + protected function deleteRelations() { + $pluginItemtypes = [ + PluginFlyvemdmAgent::class, + PluginFlyvemdmEntityConfig::class, + PluginFlyvemdmFile::class, + PluginFlyvemdmFleet::class, + PluginFlyvemdmGeolocation::class, + PluginFlyvemdmInvitation::class, + PluginFlyvemdmPackage::class, + PluginFlyvemdmPolicy::class, + PluginFlyvemdmPolicyCategory::class, + PluginFlyvemdmWellknownpath::class, + ]; + + // Itemtypes from the core having relations to itemtypes of the plugin + $itemtypes = [ + Notepad::class, + DisplayPreference::class, + DropdownTranslation::class, + Log::class, + Bookmark::class, + SavedSearch::class, + ]; + foreach ($pluginItemtypes as $pluginItemtype) { + foreach ($itemtypes as $itemtype) { + if (class_exists($itemtype)) { + $item = new $itemtype(); + $item->deleteByCriteria(['itemtype' => $pluginItemtype]); + } + } + } + } + + protected function createDisplayPreferences() { + $displayPreference = new DisplayPreference(); + $itemtype = PluginFlyvemdmFile::class; + $rank = 1; + $criteria = "`itemtype` = '$itemtype' AND `num` = '1' AND `users_id` = '0'"; + if (count($displayPreference->find($criteria)) == 0) { + $displayPreference->add([ + 'itemtype' => $itemtype, + 'num' => '1', + 'rank' => $rank, + User::getForeignKeyField() => '0' + ]); + } + $rank++; + $criteria = "`itemtype` = '$itemtype' AND `num` = '4' AND `users_id` = '0'"; + if (count($displayPreference->find($criteria)) == 0) { + $displayPreference->add([ + 'itemtype' => $itemtype, + 'num' => '4', + 'rank' => $rank, + User::getForeignKeyField() => '0' + ]); + } + + $itemtype = PluginFlyvemdmInvitation::class; + $rank = 1; + $criteria = "`itemtype` = '$itemtype' AND `num` = '3' AND `users_id` = '0'"; + if (count($displayPreference->find($criteria)) == 0) { + $displayPreference->add([ + 'itemtype' => $itemtype, + 'num' => '3', + 'rank' => $rank, + User::getForeignKeyField() => '0' + ]); + } + $rank++; + $criteria = "`itemtype` = '$itemtype' AND `num` = '4' AND `users_id` = '0'"; + if (count($displayPreference->find($criteria)) == 0) { + $displayPreference->add([ + 'itemtype' => $itemtype, + 'num' => '4', + 'rank' => $rank, + User::getForeignKeyField() => '0' + ]); + } + $rank++; + $criteria = "`itemtype` = '$itemtype' AND `num` = '5' AND `users_id` = '0'"; + if (count($displayPreference->find($criteria)) == 0) { + $displayPreference->add([ + 'itemtype' => $itemtype, + 'num' => '5', + 'rank' => $rank, + User::getForeignKeyField() => '0' + ]); + } + + $itemtype = PluginFlyvemdmPackage::class; + $rank = 1; + $criteria = "`itemtype` = '$itemtype' AND `num` = '3' AND `users_id` = '0'"; + if (count($displayPreference->find($criteria)) == 0) { + $displayPreference->add([ + 'itemtype' => $itemtype, + 'num' => '3', + 'rank' => $rank, + User::getForeignKeyField() => '0' + ]); + } + $rank++; + $criteria = "`itemtype` = '$itemtype' AND `num` = '4' AND `users_id` = '0'"; + if (count($displayPreference->find($criteria)) == 0) { + $displayPreference->add([ + 'itemtype' => $itemtype, + 'num' => '4', + 'rank' => $rank, + User::getForeignKeyField() => '0' + ]); + } + $rank++; + $criteria = "`itemtype` = '$itemtype' AND `num` = '5' AND `users_id` = '0'"; + if (count($displayPreference->find($criteria)) == 0) { + $displayPreference->add([ + 'itemtype' => $itemtype, + 'num' => '5', + 'rank' => $rank, + User::getForeignKeyField() => '0' + ]); + } + + $itemtype = PluginFlyvemdmAgent::class; + $rank = 1; + $criteria = "`itemtype` = '$itemtype' AND `num` = '11' AND `users_id` = '0'"; + if (count($displayPreference->find($criteria)) == 0) { + $displayPreference->add([ + 'itemtype' => $itemtype, + 'num' => '11', + 'rank' => $rank, + User::getForeignKeyField() => '0' + ]); + } + $rank++; + $criteria = "`itemtype` = '$itemtype' AND `num` = '12' AND `users_id` = '0'"; + if (count($displayPreference->find($criteria)) == 0) { + $displayPreference->add([ + 'itemtype' => $itemtype, + 'num' => '12', + 'rank' => $rank, + User::getForeignKeyField() => '0' + ]); + } + $rank++; + $criteria = "`itemtype` = '$itemtype' AND `num` = '3' AND `users_id` = '0'"; + if (count($displayPreference->find($criteria)) == 0) { + $displayPreference->add([ + 'itemtype' => $itemtype, + 'num' => '3', + 'rank' => $rank, + User::getForeignKeyField() => '0' + ]); + } + + } + + protected function deleteDisplayPreferences() { + global $DB; + + $table = DisplayPreference::getTable(); + $DB->query("DELETE FROM `$table` WHERE `itemtype` LIKE 'PluginFlyvemdm%'"); + } + + /** + * Works only for GLPI 9.3 and upper + */ + protected function migrateToInnodb() { + global $DB; + + $result = $DB->listTables('glpi_plugin_flyvemdm_%', ['engine' => 'MyIsam']); + if ($result) { + while ($table = $result->next()) { + echo "Migrating {$table['TABLE_NAME']}..."; + $DB->queryOrDie("ALTER TABLE {$table['TABLE_NAME']} ENGINE = InnoDB"); + echo " Done.\n"; + } + } + } +} diff --git a/install/update_to_develop.php b/install/upgrade/update_to_dev.php similarity index 100% rename from install/update_to_develop.php rename to install/upgrade/update_to_dev.php diff --git a/install/upgrade_to_2.0.php b/install/upgrade_to_2.0.php deleted file mode 100644 index 920191f2..00000000 --- a/install/upgrade_to_2.0.php +++ /dev/null @@ -1,490 +0,0 @@ - ALLSTANDARDRIGHT , - PluginFlyvemdmInvitationlog::$rightname => READ, - PluginFlyvemdmGeolocation::$rightname => ALLSTANDARDRIGHT | READNOTE | UPDATENOTE, - ]); - $profileRight->updateProfileRights($profiles_id, $newRights); - - $migration->setContext('flyvemdm'); - $migration->addConfig([ - 'default_agent_url' => PLUGIN_FLYVEMDM_AGENT_DOWNLOAD_URL, - 'show_wizard' => '0', - 'debug_save_inventory' => '0', - 'android_bugcollecctor_url' => '', - 'android_bugcollector_login' => '', - 'android_bugcollector_passwd' => '', - 'invitation_deeplink' => PLUGIN_FLYVEMDM_DEEPLINK, - ]); - - $config = Config::getConfigurationValues('flyvemdm', ['mqtt_broker_tls']); - if (isset($config['mqtt_broker_tls'])) { - if ($config['mqtt_broker_tls'] !== '0') { - $config['mqtt_broker_tls_port'] = $config['mqtt_broker_port']; - $config['mqtt_broker_port'] = '1883'; - } else { - $config['mqtt_broker_tls_port'] = '8883'; - } - // Split TLS setting for client in one hand and backend in the other hand - $config['mqtt_tls_for_clients'] = $config['mqtt_broker_tls']; - $config['mqtt_tls_for_backend'] = $config['mqtt_broker_tls']; - Config::setConfigurationValues('flyvemdm', $config); - Config::deleteConfigurationValues('flyvemdm', ['mqtt_broker_tls']); - } - - // remove download base URL setting - Config::deleteConfigurationValues('flyvemdm', ['deploy_base_url']); - - // update Entity config table - $table = 'glpi_plugin_flyvemdm_entityconfigs'; - $migration->addField($table, 'support_name', 'text', ['after' => 'agent_token_life']); - $migration->addField($table, 'support_phone', 'string', ['after' => 'support_name']); - $migration->addField($table, 'support_website', 'string', ['after' => 'support_phone']); - $migration->addField($table, 'support_email', 'string', ['after' => 'support_website']); - $migration->addField($table, 'support_address', 'text', ['after' => 'support_email']); - $migration->addKey($table, 'entities_id', 'entities_id'); - - // update Agent table - $table = 'glpi_plugin_flyvemdm_agents'; - if (!$DB->fieldExists($table, 'enroll_status')) { - $query = "ALTER TABLE `$table` - ADD COLUMN `enroll_status` ENUM('enrolled', 'unenrolling', 'unenrolled') NOT NULL DEFAULT 'enrolled' AFTER `lock`"; - $DB->query($query) or plugin_flyvemdm_upgrade_error($migration); - } - $migration->addField($table, 'version', 'string', ['after' => 'name']); - $migration->addField($table, 'users_id', 'integer', ['after' => 'computers_id']); - $migration->addField($table, 'is_online', 'integer', ['after' => 'last_contact']); - $migration->addField($table, 'has_system_permission', 'bool', ['after' => 'mdm_type']); - $migration->addKey($table, 'computers_id', 'computers_id'); - $migration->addKey($table, 'users_id', 'users_id'); - $migration->addKey($table, 'entities_id', 'entities_id'); - $migration->changeField($table, 'wipe', 'wipe', 'bool'); - $migration->changeField($table, 'lock', 'lock', 'bool'); - - $enumMdmType = PluginFlyvemdmAgent::getEnumMdmType(); - $currentEnumMdmType = PluginFlyvemdmCommon::getEnumValues($table, 'mdm_type'); - if (count($currentEnumMdmType) > 0) { - // The field exists - if (count($currentEnumMdmType) != count($enumMdmType)) { - reset($enumMdmType); - $defaultValue = key($enumMdmType); - $enumMdmType = "'" . implode("', '", array_keys($enumMdmType)) . "'"; - $query = "ALTER TABLE `$table` - CHANGE COLUMN `mdm_type` `mdm_type` - ENUM($enumMdmType) - NOT NULL DEFAULT '$defaultValue'"; - $DB->query($query) or plugin_flyvemdm_upgrade_error($migration); - } - } else { - // The field does not exists - reset($enumMdmType); - $defaultValue = key($enumMdmType); - $enumMdmType = "'" . implode("', '", array_keys($enumMdmType)) . "'"; - $query = "ALTER TABLE `$table` - ADD COLUMN `mdm_type` - ENUM($enumMdmType) - NOT NULL DEFAULT '$defaultValue'"; - $DB->query($query) or plugin_flyvemdm_upgrade_error($migration); - } - - // Create task status table - $table = 'glpi_plugin_flyvemdm_taskstatuses'; - $query = "CREATE TABLE IF NOT EXISTS `$table` ( - `id` INT(11) NOT NULL AUTO_INCREMENT, - `name` VARCHAR(255) NOT NULL DEFAULT '', - `date_creation` DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00', - `date_mod` DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00', - `plugin_flyvemdm_agents_id` INT(11) NOT NULL DEFAULT '0', - `plugin_flyvemdm_tasks_id` INT(11) NOT NULL DEFAULT '0', - `status` VARCHAR(255) NOT NULL DEFAULT '', - PRIMARY KEY (`id`), - KEY `plugin_flyvemdm_agents_id` (`plugin_flyvemdm_agents_id`), - KEY `plugin_flyvemdm_tasks_id` (`plugin_flyvemdm_tasks_id`) - ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;"; - $DB->query($query) or plugin_flyvemdm_upgrade_error($migration); - - $migration->addKey($table, 'plugin_flyvemdm_agents_id', 'plugin_flyvemdm_agents_id'); - $migration->addKey($table, 'plugin_flyvemdm_tasks_id', 'plugin_flyvemdm_tasks_id'); - - // update Policy table - $table = 'glpi_plugin_flyvemdm_policies'; - $migration->addField($table, 'recommended_value', 'string', ['after' => 'default_value']); - $migration->addField($table, 'is_android_system', 'bool', ['after' => 'recommended_value']); - $migration->addField($table, 'android_min_version', 'string', ['after' => 'is_android_system', 'value' => '0']); - $migration->addField($table, 'android_max_version', 'string', ['after' => 'android_min_version', 'value' => '0']); - $migration->addField($table, 'apple_min_version', 'string', ['after' => 'android_max_version', 'value' => '0']); - $migration->addField($table, 'apple_max_version', 'string', ['after' => 'apple_min_version', 'value' => '0']); - $migration->addKey($table, 'group', 'group'); - $migration->addKey($table, 'plugin_flyvemdm_policycategories_id', 'plugin_flyvemdm_policycategories_id'); - $migration->dropField($table, 'is_android_policy'); - $migration->dropField($table, 'is_apple_policy'); - - // Rename and update fleet_policy into task - $table = 'glpi_plugin_flyvemdm_tasks'; - $migration->renameTable('glpi_plugin_flyvemdm_fleets_policies', $table); - $migration->changeField($table, 'plugin_flyvemdm_fleets_policies_id', 'plugin_flyvemdm_tasks_id', - 'integer'); - $migration->addKey($table, 'plugin_flyvemdm_policies_id', 'plugin_flyvemdm_policies_id'); - - // Upgrade schema to apply policies on fleets and agents - if (!$DB->fieldExists($table, 'items_id_applied')) { - $migration->changeField($table, 'plugin_flyvemdm_fleets_id', 'items_id_applied', 'integer'); - $migration->dropKey($table, 'plugin_flyvemdm_fleets_id'); - $migration->addField($table, 'itemtype_applied', 'string', ['after' => 'id']); - $migration->addKey($table, ['itemtype_applied', 'items_id_applied'], 'FK_applied'); - // All tasks already created were applied on fleets - $migration->addPostQuery("UPDATE `$table` SET `itemtype_applied` = 'PluginFlyvemdmFleet'"); - $migration->executeMigration(); - } - - $table = 'glpi_plugin_flyvemdm_policies'; - $policies = [ - 'disableFmRadio', - 'disableVoiceMail', - 'disableCallAutoAnswer', - 'disableVoiceDictation', - 'disableUsbOnTheGo', - 'resetPassword', - 'inventoryFrequency', - 'disableSmsMms', - 'disableStreamVoiceCall', - 'disableCreateVpnProfiles', - ]; - $tasksTable = 'glpi_plugin_flyvemdm_tasks'; - $fleetTable = 'glpi_plugin_flyvemdm_fleets'; - $agentsTable = 'glpi_plugin_flyvemdm_agents'; - $request = [ - 'FIELDS' => [ - $table => ['symbol'], - $tasksTable => ['id', 'itemtype_applied', 'items_id_applied'], - $fleetTable => ['entities_id'], - ], - 'FROM' => $table, - 'INNER JOIN' => [ - $tasksTable => [ - 'FKEY' => [ - $tasksTable => 'plugin_flyvemdm_policies_id', - $table => 'id', - ], - ], - ], - 'LEFT JOIN' => [ - $fleetTable => [ - 'itemtype_applied' => 'PluginFlyvemdmFleet', - 'FKEY' => [ - $tasksTable => 'items_id_applied', - $fleetTable => 'id', - ], - ], - $agentsTable => [ - 'itemtype_applied' => 'PluginFlyvemdmAgent', - 'FKEY' => [ - $tasksTable => 'items_id_applied', - $agentsTable => 'id', - ], - ], - ], - 'WHERE' => [ - 'symbol' => $policies, - ], - ]; - $result = $DB->request($request); - if (count($result) > 0) { - $mqttClient = PluginFlyvemdmMqttclient::getInstance(); - foreach ($result as $data) { - switch ($data['itemtype_applied']) { - case PluginFlyvemdmFleet::class: - $type = 'fleet'; - $entityId = $data['entities_id']; - break; - - case PluginFlyvemdmAgent::class: - $agent = new PluginFlyvemdmAgent(); - $agent->getFromDB($data['items_id_applied']); - $type = 'agent'; - $entityId = $agent->getEntityID(); - break; - - default: - $type = ''; - } - if ($type === '') { - continue; - } - $topic = implode('/', [ - '/', - $entityId, - $type, - $data['items_id_applied'], - 'Policy', - $data['symbol'], - 'Task', - $data['id'] - ]); - $mqttClient->publish($topic, null, 0, 1); - } - } - $policiesStr = implode("','", $policies); - $migration->addPostQuery("DELETE FROM `$table` WHERE `symbol` IN ('" . $policiesStr . "')"); - - // update Applications table - $table = 'glpi_plugin_flyvemdm_packages'; - $migration->addField($table, 'parse_status', "enum('pending', 'parsed', 'failed') NOT NULL DEFAULT 'pending'", - ['after' => 'dl_filename', 'default' => 'pending']); - $migration->addfield($table, 'name', 'string', ['after' => 'id']); - $migration->migrationOneTable($table); - $migration->dropField($table, 'filesize'); - $migration->addField($table, 'name', 'string', ['after' => 'id']); - $migration->addKey($table, 'entities_id', 'entities_id'); - $migration->addPostQuery("UPDATE `$table` SET `parse_status` = 'parsed'"); - $migration->addPostQuery("UPDATE `$table` SET `name` = `package_name`"); - - $result = $DB->request(['FROM' => $table, 'LIMIT' => '1']); - if ($result->count() > 0) { - $result->rewind(); - $row = $result->current(); - if (strpos($row['filename'], 'flyvemdm/package/') !== 0) { - // If there is at least one package and the path does starts with the new prefix, then update all the table - $migration->addPostQuery("UPDATE `$table` SET `filename` = CONCAT('flyvemdm/package/', `filename`)"); - } - } - - $table = 'glpi_plugin_flyvemdm_files'; - $migration->addKey($table, 'entities_id', 'entities_id'); - $migration->addField($table, 'comment', 'text'); - - // Add display preferences for PluginFlyvemdmFile - $query = "SELECT * FROM `glpi_displaypreferences` - WHERE `itemtype` = 'PluginFlyvemdmFile' - AND `users_id`='0'"; - $result=$DB->query($query); - if ($DB->numrows($result) == '0') { - $query = "INSERT INTO `glpi_displaypreferences` (`id`, `itemtype`, `num`, `rank`, `users_id`) - VALUES (NULL, 'PluginFlyvemdmFile', '1', '1', '0'), - (NULL, 'PluginFlyvemdmFile', '4', '2', '0');"; - $DB->query($query); - } - - $table = 'glpi_plugin_flyvemdm_fleets'; - $migration->addField($table, 'is_recursive', 'bool'); - $migration->addKey($table, 'entities_id', 'entities_id'); - - $table = 'glpi_plugin_flyvemdm_geolocations'; - $migration->addKey($table, 'computers_id', 'computers_id'); - - $table = 'glpi_plugin_flyvemdm_mqttacls'; - $migration->addKey($table, 'plugin_flyvemdm_mqttusers_id', 'plugin_flyvemdm_mqttusers_id'); - - $table = 'glpi_plugin_flyvemdm_policycategories'; - $migration->addKey($table, 'plugin_flyvemdm_policycategories_id', 'plugin_flyvemdm_policycategories_id'); - - // Create invitation log table - $table = 'glpi_plugin_flyvemdm_invitationlogs'; - $query = "CREATE TABLE IF NOT EXISTS `$table` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `plugin_flyvemdm_invitations_id` int(11) NOT NULL DEFAULT '0', - `date_creation` datetime NOT NULL DEFAULT '0000-00-00 00:00:00', - `event` varchar(255) NOT NULL DEFAULT '', - PRIMARY KEY (`id`), - INDEX `plugin_flyvemdm_invitations_id` (`plugin_flyvemdm_invitations_id`), - INDEX `date_creation` (`date_creation`) - ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;"; - $DB->query($query) or plugin_flyvemdm_upgrade_error($migration); - $migration->addKey($table, 'plugin_flyvemdm_invitations_id', 'plugin_flyvemdm_invitations_id'); - - $table = 'glpi_plugin_flyvemdm_invitations'; - if (!$DB->fieldExists($table, 'name')) { - $invitationName = _n('Invitation', 'Invitations', 1, 'flyvemdm'); - $migration->addField($table, 'name', 'string', ['after' => 'id']); - $migration->addPostQuery("UPDATE `$table` SET `name` = '$invitationName'"); - } - $migration->addKey($table, 'users_id', 'users_id'); - $migration->addKey($table, 'entities_id', 'entities_id'); - $migration->addKey($table, 'documents_id', 'documents_id'); - - // drop Mqtt Update queue - $cronTask = new CronTask(); - $cronTask->deleteByCriteria(['itemtype' => 'PluginFlyvemdmMqttupdatequeue']); - $table = 'glpi_plugin_flyvemdm_mqttupdatequeues'; - $migration->dropTable($table); - - // Fix PascalCase symbols - $query = "UPDATE `glpi_plugin_flyvemdm_policies` - SET `symbol` = 'maximumFailedPasswordsForWipe' - WHERE `symbol`='MaximumFailedPasswordsForWipe'"; - $DB->query($query); - $query = "UPDATE `glpi_plugin_flyvemdm_policies` - SET `symbol` = 'maximumTimeToLock' - WHERE `symbol`='MaximumTimeToLock'"; - $DB->query($query); - - // change MQTT topics tree layout : remove leading slash - $mqttClient = PluginFlyvemdmMqttclient::getInstance(); - $request = [ - 'FIELDS' => [ - 'glpi_plugin_flyvemdm_agents' => ['entities_id'], - 'glpi_computers' => ['serial'], - ], - 'FROM' => 'glpi_plugin_flyvemdm_agents', - 'INNER JOIN' => [ - 'glpi_computers' => ['FKEY' => [ - 'glpi_plugin_flyvemdm_agents' => 'computers_id', - 'glpi_computers' => 'id' - ]] - ], - 'WHERE' => ['lock' => ['<>' => '0']] - ]; - $mqttMessage = ['lock' => 'now']; - $mqttMessage = json_encode($mqttMessage, JSON_UNESCAPED_SLASHES); - foreach ($DB->request($request) as $row) { - $topic = implode('/', [ - $row['entities_id'], - 'agent', - $row['serial'], - 'Command', - 'Lock', - ]); - $mqttClient->publish($topic, $mqttMessage, 0, 1); - $mqttClient->publish('/' . $topic, null, 0, 1); - } - - // re-use previous request array - $request['WHERE'] = ['wipe' => ['<>' => '0']]; - $mqttMessage = ['wipe' => 'now']; - $mqttMessage = json_encode($mqttMessage, JSON_UNESCAPED_SLASHES); - foreach ($DB->request($request) as $row) { - $topic = implode('/', [ - $row['entities_id'], - 'agent', - $row['serial'], - 'Command', - 'Wipe', - ]); - $mqttClient->publish($topic, $mqttMessage, 0, 1); - $mqttClient->publish('/' . $topic, null, 0, 1); - } - - // re-use previous request array - $request['WHERE'] = ['enroll_status' => ['=' => 'unenrolling']]; - $mqttMessage = ['unenroll' => 'now']; - $mqttMessage = json_encode($mqttMessage, JSON_UNESCAPED_SLASHES); - foreach ($DB->request($request) as $row) { - $topic = implode('/', [ - $row['entities_id'], - 'agent', - $row['serial'], - 'Command', - 'Unenroll', - ]); - $mqttClient->publish($topic, $mqttMessage, 0, 1); - $mqttClient->publish('/' . $topic, null, 0, 1); - } - - $request = [ - 'FIELDS' => [ - 'glpi_plugin_flyvemdm_tasks' => ['id', 'itemtype_applied', 'items_id_applied', 'plugin_flyvemdm_policies_id', 'itemtype', 'items_id', 'value'], - 'glpi_plugin_flyvemdm_policies' => ['symbol'], - 'glpi_plugin_flyvemdm_fleets' => ['entities_id'] - ], - 'FROM' => 'glpi_plugin_flyvemdm_tasks', - 'INNER JOIN' => [ - 'glpi_plugin_flyvemdm_policies' => [ - 'FKEY' => [ - 'glpi_plugin_flyvemdm_tasks' => 'plugin_flyvemdm_policies_id', - 'glpi_plugin_flyvemdm_policies' => 'id' - ] - ], - 'glpi_plugin_flyvemdm_fleets' => [ - 'FKEY' => [ - 'glpi_plugin_flyvemdm_tasks' => 'items_id_applied', - 'glpi_plugin_flyvemdm_fleets' => 'id' - ] - ] - ], - 'WHERE' => [ - 'glpi_plugin_flyvemdm_tasks.itemtype_applied' => 'PluginFlyvemdmFleet' - ] - ]; - foreach ($DB->request($request) as $row) { - switch ($row['itemtype_applied']) { - case PluginFlyvemdmFleet::class: - $type = 'fleet'; - break; - - case PluginFlyvemdmAgent::class: - $type = 'agent'; - break; - - default: - $type = ''; - } - if ($type === '') { - continue; - } - $topic = implode('/', [ - $row['entities_id'], - 'fleet', - $row['items_id_applied'], - 'Policy', - $row['symbol'], - ]); - $policyFactory = new PluginFlyvemdmPolicyFactory(); - $appliedPolicy = $policyFactory->createFromDBByID($row['plugin_flyvemdm_policies_id']); - $policyMessage = $appliedPolicy->getMqttMessage( - $row['value'], - $row['itemtype'], - $row['items_id'] - ); - $policyMessage['taskId'] = $row['id']; - $encodedMessage = json_encode($policyMessage, JSON_UNESCAPED_SLASHES); - $mqttClient->publish("$topic/Task/" . $row['id'], $encodedMessage, 0, 1); - $mqttClient->publish('/' . $topic, null, 0, 1); - } - } -} \ No newline at end of file diff --git a/setup.php b/setup.php index 2e62b0ff..a097266c 100644 --- a/setup.php +++ b/setup.php @@ -29,10 +29,7 @@ * ------------------------------------------------------------------------------ */ -// Version of the plugin define('PLUGIN_FLYVEMDM_VERSION', 'develop'); -// Schema version of this version -define('PLUGIN_FLYVEMDM_SCHEMA_VERSION', '2.0'); // is or is not an official release of the plugin define('PLUGIN_FLYVEMDM_IS_OFFICIAL_RELEASE', false); // Minimal GLPI version, inclusive diff --git a/tests/suite-uninstall/Config.php b/tests/suite-uninstall/Config.php index 6b001826..4be84def 100644 --- a/tests/suite-uninstall/Config.php +++ b/tests/suite-uninstall/Config.php @@ -37,6 +37,7 @@ class Config extends CommonTestCase { public function beforeTestMethod($method) { + $this->resetState(); parent::beforeTestMethod($method); $this->setupGLPIFramework(); }