Skip to content
This repository has been archived by the owner on Aug 9, 2021. It is now read-only.

Commit

Permalink
feat: retain type of mdm for agents
Browse files Browse the repository at this point in the history
also cleanup dead code, refactor installer, refactor old fleet_policy
itemtype clues into task
  • Loading branch information
btry committed Aug 17, 2017
1 parent fc5970a commit 0036cb5
Show file tree
Hide file tree
Showing 14 changed files with 197 additions and 50 deletions.
26 changes: 26 additions & 0 deletions inc/agent.class.php
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,16 @@ class PluginFlyvemdmAgent extends CommonDBTM implements PluginFlyvemdmNotifiable

protected $topic = null;

/**
* get mdm types availables
*/
public static function getEnumMdmType() {
return array(
'android' => __("Android", 'flyvemdm'),
'apple' => __("Apple", 'flyvemdm'),
);
}

/**
* Localized name of the type
* @param $nb integer number of item in the type (default 0)
Expand Down Expand Up @@ -921,6 +931,7 @@ protected function enrollByInvitationToken($input) {
$firstname = isset($input['firstname']) ? $input['firstname'] : null;
$lastname = isset($input['lastname']) ? $input['lastname'] : null;
$version = isset($input['version']) ? $input['version'] : null;
$mdmType = isset($input['type']) ? $input['type'] : null;

$input = array();

Expand Down Expand Up @@ -954,6 +965,20 @@ protected function enrollByInvitationToken($input) {
return false;
}

if (empty($mdmType)) {
$event = __('MDM type missing', 'flyvemdm');
$this->filterMessages($event);
$this->logInvitationEvent($invitation, $event);
return false;
}

if (!in_array($mdmType, array_keys($this::getEnumMdmType()))) {
$event = __('unknown MDM type', 'flyvemdm');
$this->filterMessages($event);
$this->logInvitationEvent($invitation, $event);
return false;
}

if (preg_match(PluginFlyvemdmCommon::SEMVER_VERSION_REGEX, $version) !== 1) {
$event = __('Bad agent version', 'flyvemdm');
$this->filterMessages($event);
Expand Down Expand Up @@ -1127,6 +1152,7 @@ protected function enrollByInvitationToken($input) {
$input['enroll_status'] = 'enrolled';
$input['version'] = $version;
$input['users_id'] = $agentAccount->getID();
$input['mdm_type'] = $mdmType;
return $input;

}
Expand Down
18 changes: 18 additions & 0 deletions inc/common.class.php
Original file line number Diff line number Diff line change
Expand Up @@ -56,4 +56,22 @@ public static function getMassiveActions($massiveactionparams) {

return $html;
}

static function getEnumValues($table, $field) {
global $DB;

$enum = [];
if ($res = $DB->query( "SHOW COLUMNS FROM `$table` WHERE Field = '$field'" )) {
$data = $DB->fetch_array($res);
$type = $data['Type'];
$matches = null;
preg_match("/^enum\(\'(.*)\'\)$/", $type, $matches);
if (isset($matches[1])) {
$enum = explode("','", $matches[1]);
}
}

return $enum;
}

}
2 changes: 1 addition & 1 deletion inc/entityconfig.class.php
Original file line number Diff line number Diff line change
Expand Up @@ -163,7 +163,7 @@ protected function sanitizeTokenLifeTime($input) {
*/
public function hook_entity_add(CommonDBTM $item) {
// Determine if the entity has been created by FlyveMDM
$managed = ( $item instanceof PluginFlyvemdmEntity ) ? '1' : '0';
$managed = '0';

$config = Config::getConfigurationValues('flyvemdm', array('default_device_limit'));

Expand Down
1 change: 0 additions & 1 deletion inc/file.class.php
Original file line number Diff line number Diff line change
Expand Up @@ -351,7 +351,6 @@ public function post_updateItem($history = 1) {
}
$policy = $policyFactory->createFromDBByID($taskRow['plugin_flyvemdm_policies_id']);
if ($task->getFromDB($taskId)) {
//$task->publishPolicies($fleet, $policy->getGroup());
$task->updateQueue($fleet, $policy->getGroup());
}
}
Expand Down
18 changes: 4 additions & 14 deletions inc/package.class.php
Original file line number Diff line number Diff line change
Expand Up @@ -82,11 +82,10 @@ public function defineTabs($options = array()) {
* If the tab shall not display then returns an empty string
* @param CommonGLPI $item on which the tab will show
* @param number $withtemplate template mode for $item : 0 = no template - 1 = edit template - 2 = from template
* @return translated|string
*
* @return string
*/
public function getTabNameForItem(CommonGLPI $item, $withtemplate=0) {
global $CFG_GLPI;

switch ($item->getType()) {
case 'Software' :
return _n('Package Flyve MDM', 'Packages Flyve MDM', Session::getPluralNumber(), "flyvemdm");
Expand All @@ -102,8 +101,6 @@ public function getTabNameForItem(CommonGLPI $item, $withtemplate=0) {
* @param number $withtemplate
*/
public static function displayTabContentForItem(CommonGLPI $item, $tabnum=1, $withtemplate=0) {
global $CFG_GLPI;

if ($item->getType() == 'Software') {
self::showForSoftware($item);
return true;
Expand All @@ -116,8 +113,6 @@ public static function displayTabContentForItem(CommonGLPI $item, $tabnum=1, $wi
* @param array $options
*/
public function showForm($ID, $options=array()) {
global $CFG_GLPI, $DB;

$this->initForm($ID, $options);
$this->showFormHeader($options);

Expand Down Expand Up @@ -163,7 +158,6 @@ protected static function getMaxFileSize() {
* @see CommonDBTM::addNeededInfoToInput()
*/
public function addNeededInfoToInput($input) {
global $DB;
$input['entities_id'] = $_SESSION['glpiactive_entity'];

return $input;
Expand Down Expand Up @@ -395,7 +389,6 @@ public function post_updateItem($history = 1) {
}
$policy = $policyFactory->createFromDBByID($taskRow['plugin_flyvemdm_policies_id']);
if ($task->getFromDB($taskId)) {
//$task->publishPolicies($fleet, $policy->getGroup());
$task->updateQueue($fleet, $policy->getGroup());
}
}
Expand All @@ -406,8 +399,6 @@ public function post_updateItem($history = 1) {
* @see CommonDBTM::pre_deleteItem()
*/
public function pre_deleteItem() {
global $DB;

$task = new PluginFlyvemdmTask();
return $task->deleteByCriteria(array(
'itemtype' => $this->getType(),
Expand All @@ -427,7 +418,7 @@ public function post_purgeItem() {

/**
* Create a directory
* @param unknown $dir
* @param string $dir
*/
protected function createEntityDirectory($dir) {
if (!is_dir($dir)) {
Expand All @@ -439,8 +430,6 @@ protected function createEntityDirectory($dir) {
* @see CommonDBTM::getSearchOptions()
*/
public function getSearchOptions() {
global $CFG_GLPI;

$tab = array();
$tab['common'] = __s('Package', "flyvemdm");

Expand Down Expand Up @@ -526,6 +515,7 @@ protected function sendFile() {
}

if (isset($_SERVER['HTTP_RANGE'])) {
$matches = null;
if (preg_match('/bytes=\h*(\d+)?-(\d*)[\D.*]?/i', $_SERVER['HTTP_RANGE'], $matches)) {
if (!empty($matches[1])) {
$begin = intval($matches[1]);
Expand Down
44 changes: 23 additions & 21 deletions inc/task.class.php
Original file line number Diff line number Diff line change
Expand Up @@ -411,7 +411,7 @@ public function publishPolicies(PluginFlyvemdmNotifiable $item, $groups = array(
/**
* get the groups of policies where at least one policy applies to a fleet
*
* @param PluginFlyvemdmFieet $fleet
* @param PluginFlyvemdmFleet $fleet
*
* @return string[] groups of policies
*/
Expand Down Expand Up @@ -448,6 +448,8 @@ public function getGroupsOfAppliedPolicies(PluginFlyvemdmFleet $fleet) {
* non applied policies of the same group
* @param string $group name of a group of policies
* @param PluginFlyvemdmFleet $fleet fleet the group will built for
*
* @return array
*/
public function getGroupOfPolicies($group, $fleet) {
global $DB;
Expand All @@ -456,9 +458,9 @@ public function getGroupOfPolicies($group, $fleet) {
$fleetId = $fleet->getID();
$taskTable = PluginFlyvemdmTask::getTable();
$policyTable = PluginFlyvemdmPolicy::getTable();
$query = "SELECT `fp`.* FROM `$taskTable` `fp`
LEFT JOIN `$policyTable` `p` ON `fp`.`plugin_flyvemdm_policies_id` = `p`.`id`
WHERE `fp`.`plugin_flyvemdm_fleets_id`='$fleetId' AND `p`.`group` = '$group'";
$query = "SELECT `t`.* FROM `$taskTable` `t`
LEFT JOIN `$policyTable` `p` ON `t`.`plugin_flyvemdm_policies_id` = `p`.`id`
WHERE `t`.`plugin_flyvemdm_fleets_id`='$fleetId' AND `p`.`group` = '$group'";
$result = $DB->query($query);
$policyFactory = new PluginFlyvemdmPolicyFactory();
$excludedPolicyIds = array();
Expand All @@ -469,12 +471,12 @@ public function getGroupOfPolicies($group, $fleet) {
Toolbox::logInFile('php-errors', "Plugin Flyvemdm : Policy ID " . $row['plugin_flyvemdm_policies_id'] . "not found while generating MQTT message\n" );
} else {
$policiesToApply[] = [
'fleets_policies_id' => $row['id'],
'policyData' => $appliedPolicyData,
'policyId' => $row['plugin_flyvemdm_policies_id'],
'value' => $row['value'],
'itemtype' => $row['itemtype'],
'items_id' => $row['items_id'],
'tasks_id' => $row['id'],
'policyData' => $appliedPolicyData,
'policyId' => $row['plugin_flyvemdm_policies_id'],
'value' => $row['value'],
'itemtype' => $row['itemtype'],
'items_id' => $row['items_id'],
];
}
$excludedPolicyIds[] = $row['plugin_flyvemdm_policies_id'];
Expand All @@ -490,12 +492,12 @@ public function getGroupOfPolicies($group, $fleet) {
Toolbox::logInFile('php-errors', "Plugin Flyvemdm : Policy ID " . $row['plugin_flyvemdm_policies_id'] . "not found while generating MQTT message\n" );
} else {
$policiesToApply[] = [
'fleets_policies_id' => '0',
'policyData' => $defaultPolicyData,
'policyId' => $policyId,
'value' => $row['default_value'],
'itemtype' => '',
'items_id' => '',
'tasks_id' => '0',
'policyData' => $defaultPolicyData,
'policyId' => $policyId,
'value' => $row['default_value'],
'itemtype' => '',
'items_id' => '',
];
}
}
Expand Down Expand Up @@ -525,8 +527,8 @@ protected function buildMqttMessage($policiesToApply) {
continue;
}
// Add a task ID to the message if esists
if ($policyToApply['fleets_policies_id'] != '0') {
$policyMessage['taskId'] = $policyToApply['fleets_policies_id'];
if ($policyToApply['tasks_id'] != '0') {
$policyMessage['taskId'] = $policyToApply['tasks_id'];
}
$groupToEncode[] = $policyMessage;
}
Expand All @@ -545,13 +547,13 @@ protected function buildMqttMessage($policiesToApply) {
public function createTaskStatus(PluginFlyvemdmAgent $agent, $policiesToApply) {
$agentId = $agent->getID();
foreach ($policiesToApply as $policyToApply) {
$taskId = $policyToApply['fleets_policies_id'];
$taskId = $policyToApply['tasks_id'];
if ($taskId > 0) {
$taskStatus = new PluginFlyvemdmTaskstatus();
$taskStatus->add([
'plugin_flyvemdm_agents_id' => $agentId,
'plugin_flyvemdm_agents_id' => $agentId,
'plugin_flyvemdm_tasks_id' => $taskId,
'status' => 'pending',
'status' => 'pending',
]);
}
}
Expand Down
15 changes: 10 additions & 5 deletions install/installer.class.php
Original file line number Diff line number Diff line change
Expand Up @@ -210,12 +210,17 @@ public static function getCurrentVersion() {

protected function createRootEntityConfig() {
$entityConfig = new PluginFlyvemdmEntityconfig();
$entityConfig->add([
'id' => '0',
'entities_id' => '0',
'download_url' => PLUGIN_FLYVEMDM_AGENT_DOWNLOAD_URL,
'agent_token_life' => PluginFlyvemdmAgent::DEFAULT_TOKEN_LIFETIME,
$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,
]);
}
}

/**
Expand Down
3 changes: 3 additions & 0 deletions install/mysql/plugin_flyvemdm_empty.sql
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ CREATE TABLE IF NOT EXISTS `glpi_plugin_flyvemdm_agents` (
`last_contact` datetime DEFAULT NULL,
`is_online` tinyint(1) NOT NULL DEFAULT '0',
`certificate` text NOT NULL,
`mdm_type` enum('android','apple') NOT NULL DEFAULT 'android',
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Expand Down Expand Up @@ -184,6 +185,8 @@ CREATE TABLE `glpi_plugin_flyvemdm_policies` (
`comment` text DEFAULT NULL,
`default_value` varchar(255) NOT NULL DEFAULT '',
`recommended_value` varchar(255) NOT NULL DEFAULT '',
`is_android_policy` tinyint(1) NOT NULL DEFAULT '0',
`is_apple_policy` tinyint(1) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Expand Down
2 changes: 1 addition & 1 deletion install/upgrade/update_to_2_0_0.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ function update_to_2_0_0(Migration $migration) {
$profileRight->updateProfileRights($_SESSION['glpiactiveprofile']['id'], $newRights);

$table = PluginFlyvemdmAgent::getTable();
if (! FieldExists($table, 'enroll_status')) {
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 die("Could upgrade table $table" . $DB->error());
Expand Down
44 changes: 39 additions & 5 deletions install/upgrade/update_to_dev.php
Original file line number Diff line number Diff line change
Expand Up @@ -36,17 +36,47 @@
function plugin_flyvemdm_update_to_dev(Migration $migration) {
global $DB;

$migration->setVersion(PLUGIN_FLYVEMDM_VERSION);

// update Entity config table
$table = PluginFlyvemdmEntityconfig::getTable();
$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']);

// update schema
// update Agent table
$table = PluginFlyvemdmAgent::getTable();
$migration->addField($table, 'users_id', 'integer', ['after' => 'computers_id']);
$migration->addField($table, 'is_online', 'integer', ['after' => 'last_contact']);
$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
$query = "CREATE TABLE IF NOT EXISTS `glpi_plugin_flyvemdm_taskstatuses` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL DEFAULT '',
Expand All @@ -61,11 +91,15 @@ function plugin_flyvemdm_update_to_dev(Migration $migration) {
plugin_flyvemdm_upgrade_error($migration);
}

$migration->addField(PluginFlyvemdmAgent::getTable(), 'is_online', 'integer', ['after' => 'last_contact']);

// Rename fleet_policy into task
// Rename and update fleet_policy into task
$migration->renameTable('glpi_plugin_flyvemdm_fleets_policies', 'glpi_plugin_flyvemdm_tasks');
$migration->changeField('glpi_plugin_flyvemdm_tasks', 'plugin_flyvemdm_fleets_policies_id', 'plugin_flyvemdm_tasks_id', 'integer');

$migration->setVersion(PLUGIN_FLYVEMDM_VERSION);
// update Policy table
$table = PluginFlyvemdmPolicy::getTable();
$migration->addField($table, 'is_android_policy', 'bool', ['after' => 'recommended_value']);
$migration->addField($table, 'is_apple_policy', 'bool', ['after' => 'is_android_policy']);
// All policies exist for Android
$migration->addPostQuery("UPDATE `$table` SET `is_android_policy` = '1'");

}
Loading

0 comments on commit 0036cb5

Please sign in to comment.