/**
  * @param $profile
  **/
 static function addDefaultProfileInfos($profiles_id, $rights)
 {
     $profileRight = new ProfileRight();
     foreach ($rights as $right => $value) {
         if (!countElementsInTable('glpi_profilerights', "`profiles_id`='{$profiles_id}' AND `name`='{$right}'")) {
             $myright['profiles_id'] = $profiles_id;
             $myright['name'] = $right;
             $myright['rights'] = $value;
             $profileRight->add($myright);
             //Add right to the current session
             $_SESSION['glpiactiveprofile'][$right] = $value;
         }
     }
 }
function plugin_moreticket_uninstall()
{
    global $DB;
    // Plugin tables deletion
    $tables = array("glpi_plugin_moreticket_configs", "glpi_plugin_moreticket_waitingtickets", "glpi_plugin_moreticket_waitingtypes", "glpi_plugin_moreticket_closetickets");
    foreach ($tables as $table) {
        $DB->query("DROP TABLE IF EXISTS `{$table}`;");
    }
    //Delete rights associated with the plugin
    $profileRight = new ProfileRight();
    foreach (PluginMoreticketProfile::getAllRights() as $right) {
        $profileRight->deleteByCriteria(array('name' => $right['field']));
    }
    return true;
}
Exemple #3
0
function plugin_consumables_uninstall()
{
    global $DB;
    include_once GLPI_ROOT . "/plugins/consumables/inc/profile.class.php";
    include_once GLPI_ROOT . "/plugins/consumables/inc/menu.class.php";
    $tables = array("glpi_plugin_consumables_profiles", "glpi_plugin_consumables_requests");
    foreach ($tables as $table) {
        $DB->query("DROP TABLE IF EXISTS `{$table}`;");
    }
    $options = array('itemtype' => 'PluginConsumablesRequest', 'event' => 'ConsumableRequest', 'FIELDS' => 'id');
    $notif = new Notification();
    foreach ($DB->request('glpi_notifications', $options) as $data) {
        $notif->delete($data);
    }
    $options = array('itemtype' => 'PluginConsumablesRequest', 'event' => 'ConsumableResponse', 'FIELDS' => 'id');
    $notif = new Notification();
    foreach ($DB->request('glpi_notifications', $options) as $data) {
        $notif->delete($data);
    }
    //templates
    $template = new NotificationTemplate();
    $translation = new NotificationTemplateTranslation();
    $options = array('itemtype' => 'PluginConsumablesRequest', 'FIELDS' => 'id');
    foreach ($DB->request('glpi_notificationtemplates', $options) as $data) {
        $options_template = array('notificationtemplates_id' => $data['id'], 'FIELDS' => 'id');
        foreach ($DB->request('glpi_notificationtemplatetranslations', $options_template) as $data_template) {
            $translation->delete($data_template);
        }
        $template->delete($data);
    }
    // Delete rights associated with the plugin
    $profileRight = new ProfileRight();
    foreach (PluginConsumablesProfile::getAllRights() as $right) {
        $profileRight->deleteByCriteria(array('name' => $right['field']));
    }
    PluginConsumablesMenu::removeRightsFromSession();
    PluginConsumablesProfile::removeRightsFromSession();
    return true;
}
Exemple #4
0
function plugin_tasklists_uninstall()
{
    global $DB;
    include_once GLPI_ROOT . "/plugins/tasklists/inc/profile.class.php";
    include_once GLPI_ROOT . "/plugins/tasklists/inc/menu.class.php";
    $tables = array("glpi_plugin_tasklists_tasks", "glpi_plugin_tasklists_tasktypes");
    foreach ($tables as $table) {
        $DB->query("DROP TABLE IF EXISTS `{$table}`;");
    }
    $tables_glpi = array("glpi_displaypreferences", "glpi_notepads", "glpi_bookmarks", "glpi_logs");
    foreach ($tables_glpi as $table_glpi) {
        $DB->query("DELETE FROM `{$table_glpi}` WHERE `itemtype` LIKE 'PluginTasklistsTask%';");
    }
    //Delete rights associated with the plugin
    $profileRight = new ProfileRight();
    foreach (PluginTasklistsProfile::getAllRights() as $right) {
        $profileRight->deleteByCriteria(array('name' => $right['field']));
    }
    PluginTasklistsMenu::removeRightsFromSession();
    PluginTasklistsProfile::removeRightsFromSession();
    return true;
}
 /**
  * @since 0.85
  * Migration rights from old system to the new one for one profile
  * @param $profiles_id the profile ID
  */
 static function migrateOneProfile($profiles_id)
 {
     global $DB;
     foreach ($DB->request('glpi_plugin_talk_profiles', "`profiles_id`='{$profiles_id}'") as $profile_data) {
         $matching = array('is_active' => 'plugin_talk_is_active');
         $current_rights = ProfileRight::getProfileRights($profiles_id, array_values($matching));
         foreach ($matching as $old => $new) {
             if (!isset($current_rights[$old])) {
                 $query = "UPDATE `glpi_profilerights` \n                         SET `rights`='" . self::translateARight($profile_data[$old]) . "' \n                         WHERE `name`='{$new}' AND `profiles_id`='{$profiles_id}'";
                 $DB->query($query);
             }
         }
     }
 }
Exemple #6
0
function plugin_accounts_uninstall()
{
    global $DB;
    include_once GLPI_ROOT . "/plugins/accounts/inc/profile.class.php";
    include_once GLPI_ROOT . "/plugins/accounts/inc/menu.class.php";
    $tables = array("glpi_plugin_accounts_accounts", "glpi_plugin_accounts_accounts_items", "glpi_plugin_accounts_accounttypes", "glpi_plugin_accounts_accountstates", "glpi_plugin_accounts_configs", "glpi_plugin_accounts_hashs", "glpi_plugin_accounts_hashes", "glpi_plugin_accounts_aeskeys", "glpi_plugin_accounts_notificationstates");
    foreach ($tables as $table) {
        $DB->query("DROP TABLE IF EXISTS `{$table}`;");
    }
    //old versions
    $tables = array("glpi_plugin_comptes", "glpi_plugin_compte_device", "glpi_dropdown_plugin_compte_type", "glpi_dropdown_plugin_compte_status", "glpi_plugin_compte_profiles", "glpi_plugin_compte_config", "glpi_plugin_compte_default", "glpi_plugin_compte_mailing", "glpi_plugin_compte", "glpi_plugin_compte_hash", "glpi_plugin_compte_aeskey", "glpi_plugin_accounts_profiles");
    foreach ($tables as $table) {
        $DB->query("DROP TABLE IF EXISTS `{$table}`;");
    }
    $notif = new Notification();
    $options = array('itemtype' => 'PluginAccountsAccount', 'event' => 'new', 'FIELDS' => 'id');
    foreach ($DB->request('glpi_notifications', $options) as $data) {
        $notif->delete($data);
    }
    $options = array('itemtype' => 'PluginAccountsAccount', 'event' => 'ExpiredAccounts', 'FIELDS' => 'id');
    foreach ($DB->request('glpi_notifications', $options) as $data) {
        $notif->delete($data);
    }
    $options = array('itemtype' => 'PluginAccountsAccount', 'event' => 'AccountsWhichExpire', 'FIELDS' => 'id');
    foreach ($DB->request('glpi_notifications', $options) as $data) {
        $notif->delete($data);
    }
    //templates
    $template = new NotificationTemplate();
    $translation = new NotificationTemplateTranslation();
    $options = array('itemtype' => 'PluginAccountsAccount', 'FIELDS' => 'id');
    foreach ($DB->request('glpi_notificationtemplates', $options) as $data) {
        $options_template = array('notificationtemplates_id' => $data['id'], 'FIELDS' => 'id');
        foreach ($DB->request('glpi_notificationtemplatetranslations', $options_template) as $data_template) {
            $translation->delete($data_template);
        }
        $template->delete($data);
    }
    $tables_glpi = array("glpi_displaypreferences", "glpi_documents_items", "glpi_bookmarks", "glpi_logs", "glpi_items_tickets", "glpi_dropdowntranslations");
    foreach ($tables_glpi as $table_glpi) {
        $DB->query("DELETE FROM `{$table_glpi}`\n               WHERE `itemtype` = 'PluginAccountsAccount'\n               OR `itemtype` = 'PluginAccountsHelpdesk'\n               OR `itemtype` = 'PluginAccountsGroup'\n               OR `itemtype` = 'PluginAccountsAccountState'\n               OR `itemtype` = 'PluginAccountsAccountType' ;");
    }
    if (class_exists('PluginDatainjectionModel')) {
        PluginDatainjectionModel::clean(array('itemtype' => 'PluginAccountsAccount'));
    }
    //Delete rights associated with the plugin
    $profileRight = new ProfileRight();
    foreach (PluginAccountsProfile::getAllRights() as $right) {
        $profileRight->deleteByCriteria(array('name' => $right['field']));
    }
    PluginAccountsProfile::removeRightsFromSession();
    PluginAccountsMenu::removeRightsFromSession();
    return true;
}
Exemple #7
0
 /**
  * Display rights choice matrix
  *
  * @since version 0.85
  *
  * @param $rights array    possible:
  *             'itemtype'   => the type of the item to check (as passed to self::getRightsFor())
  *             'rights'     => when use of self::getRightsFor() is impossible
  *             'label'      => the label for the right
  *             'field'      => the name of the field inside the DB and HTML form (prefixed by '_')
  *             'html_field' => when $html_field != '_'.$field
  * @param $options array   possible:
  *             'title'         the title of the matrix
  *             'canedit'
  *             'default_class' the default CSS class used for the row
  *
  * @return random value used to generate the ids
  **/
 function displayRightsChoiceMatrix(array $rights, array $options = array())
 {
     $param = array();
     $param['title'] = '';
     $param['canedit'] = true;
     $param['default_class'] = '';
     if (is_array($options) && count($options)) {
         foreach ($options as $key => $val) {
             $param[$key] = $val;
         }
     }
     // To be completed before display to avoid non available rights in DB
     $availablerights = ProfileRight::getAllPossibleRights();
     $column_labels = array();
     $columns = array();
     $rows = array();
     foreach ($rights as $info) {
         if (is_string($info)) {
             $rows[] = $info;
             continue;
         }
         if (is_array($info) && (!empty($info['itemtype']) || !empty($info['rights'])) && !empty($info['label']) && !empty($info['field'])) {
             // Add right if it does not exists : security for update
             if (!isset($availablerights[$info['field']])) {
                 ProfileRight::addProfileRights(array($info['field']));
             }
             $row = array('label' => $info['label'], 'columns' => array());
             if (!empty($info['row_class'])) {
                 $row['class'] = $info['row_class'];
             } else {
                 $row['class'] = $param['default_class'];
             }
             if (isset($this->fields[$info['field']])) {
                 $profile_right = $this->fields[$info['field']];
             } else {
                 $profile_right = 0;
             }
             if (isset($info['rights'])) {
                 $rights = $info['rights'];
             } else {
                 $rights = self::getRightsFor($info['itemtype']);
             }
             foreach ($rights as $right => $label) {
                 if (!isset($column_labels[$right])) {
                     $column_labels[$right] = array();
                 }
                 if (is_array($label)) {
                     $long_label = $label['long'];
                 } else {
                     $long_label = $label;
                 }
                 if (!isset($column_labels[$right][$long_label])) {
                     $column_labels[$right][$long_label] = count($column_labels[$right]);
                 }
                 $right_value = $right . '_' . $column_labels[$right][$long_label];
                 $columns[$right_value] = $label;
                 $checked = ($profile_right & $right) == $right ? 1 : 0;
                 $row['columns'][$right_value] = array('checked' => $checked);
                 if (!$param['canedit']) {
                     $row['columns'][$right_value]['readonly'] = true;
                 }
             }
             if (!empty($info['html_field'])) {
                 $rows[$info['html_field']] = $row;
             } else {
                 $rows['_' . $info['field']] = $row;
             }
         }
     }
     uksort($columns, function ($a, $b) {
         $a = explode('_', $a);
         $b = explode('_', $b);
         // For standard rights sort by right
         if ($a[0] < 1024 || $b[0] < 1024) {
             if ($a[0] > $b[0]) {
                 return true;
             }
             if ($a[0] < $b[0]) {
                 return false;
             }
             return $a[1] > $b[1];
             // For extra right sort by type
         }
         return $a[1] > $b[1];
     });
     return Html::showCheckboxMatrix($columns, $rows, array('title' => $param['title'], 'row_check_all' => count($columns) > 1, 'col_check_all' => count($rows) > 1, 'rotate_column_titles' => false));
 }
Exemple #8
0
/**
 * Update from 0.84 to 0.85
 *
 * @return bool for success (will die for most error)
**/
function update084to085()
{
    global $DB, $migration;
    $updateresult = true;
    $ADDTODISPLAYPREF = array();
    $DELFROMDISPLAYPREF = array();
    //TRANS: %s is the number of new version
    $migration->displayTitle(sprintf(__('Update to %s'), '0.85'));
    $migration->setVersion('0.85');
    $backup_tables = false;
    $newtables = array('glpi_blacklistedmailcontents', 'glpi_changecosts', 'glpi_changes', 'glpi_changes_groups', 'glpi_changes_items', 'glpi_changes_problems', 'glpi_changes_projects', 'glpi_changes_suppliers', 'glpi_changes_tickets', 'glpi_changes_users', 'glpi_changetasks', 'glpi_changevalidations', 'glpi_dropdowntranslations', 'glpi_knowbaseitemtranslations', 'glpi_notepads', 'glpi_problemcosts', 'glpi_projectcosts', 'glpi_projects', 'glpi_projects_changes', 'glpi_projects_items', 'glpi_projectstates', 'glpi_projecttasks', 'glpi_projecttasks_tickets', 'glpi_projecttaskteams', 'glpi_projecttasktypes', 'glpi_projectteams', 'glpi_projecttypes', 'glpi_queuedmails');
    foreach ($newtables as $new_table) {
        // rename new tables if exists ?
        if (TableExists($new_table)) {
            $migration->dropTable("backup_{$new_table}");
            $migration->displayWarning("{$new_table} table already exists. " . "A backup have been done to backup_{$new_table}.");
            $backup_tables = true;
            $query = $migration->renameTable("{$new_table}", "backup_{$new_table}");
        }
    }
    if ($backup_tables) {
        $migration->displayWarning("You can delete backup tables if you have no need of them.", true);
    }
    $migration->displayMessage(sprintf(__('Data migration - %s'), 'config table'));
    if (FieldExists('glpi_configs', 'version')) {
        if (!TableExists('origin_glpi_configs')) {
            $migration->copyTable('glpi_configs', 'origin_glpi_configs');
        }
        $query = "SELECT *\n                 FROM `glpi_configs`\n                 WHERE `id` = '1'";
        $result_of_configs = $DB->query($query);
        // Update glpi_configs
        $migration->addField('glpi_configs', 'context', 'VARCHAR(150) COLLATE utf8_unicode_ci', array('update' => "'core'"));
        $migration->addField('glpi_configs', 'name', 'VARCHAR(150) COLLATE utf8_unicode_ci', array('update' => "'version'"));
        $migration->addField('glpi_configs', 'value', 'text', array('update' => "'0.85'"));
        $migration->addKey('glpi_configs', array('context', 'name'), 'unicity', 'UNIQUE');
        $migration->migrationOneTable('glpi_configs');
        $fields = array();
        if ($DB->numrows($result_of_configs) == 1) {
            $configs = $DB->fetch_assoc($result_of_configs);
            unset($configs['id']);
            unset($configs['version']);
            // First drop fields not to have constraint on insert
            foreach ($configs as $name => $value) {
                $migration->dropField('glpi_configs', $name);
            }
            $migration->migrationOneTable('glpi_configs');
            // Then insert new values
            foreach ($configs as $name => $value) {
                $query = "INSERT INTO `glpi_configs`\n                             (`context`, `name`, `value`)\n                      VALUES ('core', '{$name}', '" . addslashes($value) . "');";
                $DB->query($query);
            }
        }
        $migration->dropField('glpi_configs', 'version');
        $migration->migrationOneTable('glpi_configs');
        $migration->dropTable('origin_glpi_configs');
    }
    $migration->displayMessage(sprintf(__('Data migration - %s'), 'profile table'));
    if (!TableExists('glpi_profilerights')) {
        if (!TableExists('origin_glpi_profiles')) {
            $migration->copyTable('glpi_profiles', 'origin_glpi_profiles');
        }
        $query = "CREATE TABLE `glpi_profilerights` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `profiles_id` int(11) NOT NULL DEFAULT '0',\n                  `name` varchar(255) DEFAULT NULL,\n                  `rights` int(11) NOT NULL DEFAULT '0',\n                  PRIMARY KEY (`id`),\n                  UNIQUE KEY `unicity` (`profiles_id`, `name`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.85 add table glpi_profilerights");
        $query = "DESCRIBE `origin_glpi_profiles`";
        $rights = array();
        foreach ($DB->request($query) as $field) {
            if ($field['Type'] == 'char(1)') {
                $rights[$field['Field']] = $field['Field'];
                $migration->dropField('glpi_profiles', $field['Field']);
            }
        }
        $query = "SELECT *\n                FROM `origin_glpi_profiles`";
        foreach ($DB->request($query) as $profile) {
            $profiles_id = $profile['id'];
            foreach ($rights as $right) {
                $new_right = 0;
                if ($profile[$right] == 'r' || $profile[$right] == '1') {
                    $new_right = READ;
                } else {
                    if ($profile[$right] == 'w') {
                        $new_right = ALLSTANDARDRIGHT;
                    }
                }
                $query = "INSERT INTO `glpi_profilerights`\n                             (`profiles_id`, `name`, `rights`)\n                      VALUES ('{$profiles_id}', '{$right}', '" . $new_right . "')";
                $DB->query($query);
            }
        }
        $migration->migrationOneTable('glpi_profiles');
        $migration->dropTable('origin_glpi_profiles');
    }
    // New system of profiles
    // delete import_externalauth_users
    foreach ($DB->request("glpi_profilerights", "`name` = 'import_externalauth_users' AND `rights` = '" . ALLSTANDARDRIGHT . "'") as $profrights) {
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = `rights` | " . User::IMPORTEXTAUTHUSERS . "\n                 WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                       AND `name` = 'user'";
        $DB->queryOrDie($query, "0.85 update user with import_externalauth_users right");
    }
    $query = "DELETE\n             FROM `glpi_profilerights`\n             WHERE `name` = 'import_externalauth_users'";
    $DB->queryOrDie($query, "0.85 delete import_externalauth_users right");
    // save value of rule_ticket to root_rule_ticket
    $query = "UPDATE `glpi_profilerights`\n              SET `name` = 'root_rule_ticket'\n              WHERE `name` = 'rule_ticket'";
    $DB->queryOrDie($query, "0.85 rename rule_ticket to root_rule_ticket");
    // rename entity_rule_ticket to rule_ticket
    $query = "UPDATE `glpi_profilerights`\n              SET `name` = 'rule_ticket'\n              WHERE `name` = 'entity_rule_ticket'";
    $DB->queryOrDie($query, "0.85 rename entity_rule_ticket to rule_ticket");
    // delete root_rule_ticket
    foreach ($DB->request("glpi_profilerights", "`name` = 'root_rule_ticket' AND `rights` = '1'") as $profrights) {
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` =  `rights` | " . RuleTicket::PARENT . "\n                 WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                       AND `name` = 'rule_ticket'";
        $DB->queryOrDie($query, "0.85 update new rule_ticket with old rule_ticket right");
    }
    $query = "DELETE\n             FROM `glpi_profilerights`\n             WHERE `name` = 'root_rule_ticket'";
    $DB->queryOrDie($query, "0.85 delete old rule_ticket right");
    // delete knowbase_admin
    foreach ($DB->request("glpi_profilerights", "`name` = 'knowbase_admin' AND `rights` = '1'") as $profrights) {
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = `rights` | " . KnowbaseItem::KNOWBASEADMIN . "\n                 WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                      AND `name` = 'knowbase'";
        $DB->queryOrDie($query, "0.85 update knowbase with knowbase_admin right");
    }
    $query = "DELETE\n             FROM `glpi_profilerights`\n             WHERE `name` = 'knowbase_admin'";
    $DB->queryOrDie($query, "0.85 delete knowbase_admin right");
    // delete faq
    foreach ($DB->request("glpi_profilerights", "`name` = 'faq' AND `rights` = '1'") as $profrights) {
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = `rights` | " . KnowbaseItem::READFAQ . "\n                 WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                       AND `name` = 'knowbase'";
        $DB->queryOrDie($query, "0.85 update knowbase with read faq right");
    }
    foreach ($DB->request("glpi_profilerights", "`name` = 'faq' AND `rights` = '" . ALLSTANDARDRIGHT . "'") as $profrights) {
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = `rights` | " . KnowbaseItem::READFAQ . " | " . KnowbaseItem::PUBLISHFAQ . "\n                 WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                       AND `name` = 'knowbase'";
        $DB->queryOrDie($query, "0.85 update knowbase with write faq right");
    }
    $query = "DELETE\n             FROM `glpi_profilerights`\n             WHERE `name` = 'faq'";
    $DB->queryOrDie($query, "0.85 delete faq right");
    // delete user_authtype
    foreach ($DB->request("glpi_profilerights", "`name` = 'user_authtype' AND `rights` = '1'") as $profrights) {
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = `rights` | " . User::READAUTHENT . "\n                 WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                       AND `name` = 'user'";
        $DB->queryOrDie($query, "0.85 update user with read user_authtype right");
    }
    foreach ($DB->request("glpi_profilerights", "`name` = 'user_authtype' AND `rights` = '" . ALLSTANDARDRIGHT . "'") as $profrights) {
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = `rights` | " . User::READAUTHENT . " | " . User::UPDATEAUTHENT . "\n                 WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                       AND `name` = 'user'";
        $DB->queryOrDie($query, "0.85 update user with write user_authtype right");
    }
    $query = "DELETE\n             FROM `glpi_profilerights`\n             WHERE `name` = 'user_authtype'";
    $DB->queryOrDie($query, "0.85 delete user_authtype right");
    // delete entity_helpdesk
    foreach ($DB->request("glpi_profilerights", "`name` = 'entity_helpdesk' AND `rights` = '1'") as $profrights) {
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = `rights` | " . Entity::READHELPDESK . "\n                 WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                       AND `name` = 'entity'";
        $DB->queryOrDie($query, "0.85 update entity with read entity_helpdesk right");
    }
    foreach ($DB->request("glpi_profilerights", "`name` = 'entity_helpdesk' AND `rights` = '" . ALLSTANDARDRIGHT . "'") as $profrights) {
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = `rights` | " . Entity::READHELPDESK . " | " . Entity::UPDATEHELPDESK . "\n                 WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                       AND `name` = 'entity'";
        $DB->queryOrDie($query, "0.85 update user with write entity_helpdesk right");
    }
    $query = "DELETE\n             FROM `glpi_profilerights`\n             WHERE `name` = 'entity_helpdesk'";
    $DB->queryOrDie($query, "0.85 delete entity_helpdesk right");
    // delete reservation_helpdesk
    foreach ($DB->request("glpi_profilerights", "`name` = 'reservation_helpdesk' AND `rights` = '1'") as $profrights) {
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = `rights` | " . ReservationItem::RESERVEANITEM . "\n                 WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                      AND `name` = 'reservation_central'";
        $DB->queryOrDie($query, "0.85 update reservation_central with reservation_helpdesk right");
    }
    $query = "DELETE\n             FROM `glpi_profilerights`\n             WHERE `name` = 'reservation_helpdesk'";
    $DB->queryOrDie($query, "0.85 delete reservation_helpdesk right");
    // rename reservation_central
    $query = "UPDATE `glpi_profilerights`\n              SET `name` = 'reservation'\n              WHERE `name` = 'reservation_central'";
    $DB->queryOrDie($query, "0.85 delete reservation_central");
    // pour que la procédure soit ré-entrante et ne pas perdre les sélections dans le profile
    if (countElementsInTable("glpi_profilerights", "`name` = 'ticket'") == 0) {
        // rename create_ticket
        $query = "UPDATE `glpi_profilerights`\n                 SET `name` = 'ticket'\n                 WHERE `name` = 'create_ticket'";
        $DB->queryOrDie($query, "0.85 rename create_ticket to ticket");
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = " . (CREATE | Ticket::READMY) . "\n                 WHERE `name` = 'ticket'\n                       AND `rights` = '1'";
        $DB->queryOrDie($query, "0.85 update ticket with create_ticket right");
    }
    // delete update_ticket
    foreach ($DB->request("glpi_profilerights", "`name` = 'update_ticket' AND `rights` = '1'") as $profrights) {
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = `rights` | " . UPDATE . "\n                 WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                      AND `name` = 'ticket'";
        $DB->queryOrDie($query, "0.85 update ticket with update_ticket right");
    }
    $query = "DELETE\n             FROM `glpi_profilerights`\n             WHERE `name` = 'update_ticket'";
    $DB->queryOrDie($query, "0.85 delete update_ticket right");
    // delete delete_ticket
    foreach ($DB->request("glpi_profilerights", "`name` = 'delete_ticket' AND `rights` = '1'") as $profrights) {
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = `rights` | " . DELETE . " | " . PURGE . "\n                 WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                      AND `name` = 'ticket'";
        $DB->queryOrDie($query, "0.85 update ticket with delete_ticket right");
    }
    $query = "DELETE\n             FROM `glpi_profilerights`\n             WHERE `name` = 'delete_ticket'";
    $DB->queryOrDie($query, "0.85 delete delete_ticket right");
    // delete show_all_ticket
    foreach ($DB->request("glpi_profilerights", "`name` = 'show_all_ticket' AND `rights` = '1'") as $profrights) {
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = `rights` | " . Ticket::READALL . "\n                 WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                      AND `name` = 'ticket'";
        $DB->queryOrDie($query, "0.85 update ticket with show_all_ticket right");
    }
    $query = "DELETE\n             FROM `glpi_profilerights`\n             WHERE `name` = 'show_all_ticket'";
    $DB->queryOrDie($query, "0.85 delete show_all_ticket right");
    // delete show_group_ticket
    foreach ($DB->request("glpi_profilerights", "`name` = 'show_group_ticket' AND `rights` = '1'") as $profrights) {
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = `rights` | " . Ticket::READGROUP . "\n                 WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                      AND `name` = 'ticket'";
        $DB->queryOrDie($query, "0.85 update ticket with show_group_ticket right");
    }
    $query = "DELETE\n             FROM `glpi_profilerights`\n             WHERE `name` = 'show_group_ticket'";
    $DB->queryOrDie($query, "0.85 delete show_group_ticket right");
    // delete show_assign_ticket
    foreach ($DB->request("glpi_profilerights", "`name` = 'show_assign_ticket' AND `rights` = '1'") as $profrights) {
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = `rights` | " . Ticket::READASSIGN . "\n                 WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                      AND `name` = 'ticket'";
        $DB->queryOrDie($query, "0.85 update ticket with show_assign_ticket right");
    }
    $query = "DELETE\n             FROM `glpi_profilerights`\n             WHERE `name` = 'show_assign_ticket'";
    $DB->queryOrDie($query, "0.85 delete show_assign_ticket right");
    // delete assign_ticket
    foreach ($DB->request("glpi_profilerights", "`name` = 'assign_ticket' AND `rights` = '1'") as $profrights) {
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = `rights` | " . Ticket::ASSIGN . "\n                 WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                      AND `name` = 'ticket'";
        $DB->queryOrDie($query, "0.85 update ticket with assign_ticket right");
    }
    $query = "DELETE\n             FROM `glpi_profilerights`\n             WHERE `name` = 'assign_ticket'";
    $DB->queryOrDie($query, "0.85 delete assign_ticket right");
    // delete steal_ticket
    foreach ($DB->request("glpi_profilerights", "`name` = 'steal_ticket' AND `rights` = '1'") as $profrights) {
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = `rights` | " . Ticket::STEAL . "\n                 WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                      AND `name` = 'ticket'";
        $DB->queryOrDie($query, "0.85 update ticket with steal_ticket right");
    }
    $query = "DELETE\n             FROM `glpi_profilerights`\n             WHERE `name` = 'steal_ticket'";
    $DB->queryOrDie($query, "0.85 delete steal_ticket right");
    // delete own_ticket
    foreach ($DB->request("glpi_profilerights", "`name` = 'own_ticket' AND `rights` = '1'") as $profrights) {
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = `rights` | " . Ticket::OWN . "\n                 WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                      AND `name` = 'ticket'";
        $DB->queryOrDie($query, "0.85 update ticket with own_ticket right");
    }
    $query = "DELETE\n             FROM `glpi_profilerights`\n             WHERE `name` = 'own_ticket'";
    $DB->queryOrDie($query, "0.85 delete own_ticket right");
    // delete update_priority
    foreach ($DB->request("glpi_profilerights", "`name` = 'update_priority' AND `rights` = '1'") as $profrights) {
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = `rights` | " . Ticket::CHANGEPRIORITY . "\n                 WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                      AND `name` = 'ticket'";
        $DB->queryOrDie($query, "0.85 update ticket with update_priority right");
    }
    $query = "DELETE\n             FROM `glpi_profilerights`\n             WHERE `name` = 'update_priority'";
    $DB->queryOrDie($query, "0.85 delete update_priority right");
    // pour que la procédure soit ré-entrante et ne pas perdre les sélections dans le profile
    if (countElementsInTable("glpi_profilerights", "`name` = 'followup'") == 0) {
        // rename create_ticket
        $query = "UPDATE `glpi_profilerights`\n                 SET `name` = 'followup'\n                 WHERE `name` = 'global_add_followups'";
        $DB->queryOrDie($query, "0.85 rename global_add_followups to followup");
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = " . TicketFollowup::ADDALLTICKET . "\n                 WHERE `name` = 'followup'\n                       AND `rights` = '1'";
        $DB->queryOrDie($query, "0.85 update followup with global_add_followups right");
    }
    // delete add_followups
    foreach ($DB->request("glpi_profilerights", "`name` = 'add_followups' AND `rights` = '1'") as $profrights) {
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = `rights` | " . TicketFollowup::ADDMYTICKET . "\n                 WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                      AND `name` = 'followup'";
        $DB->queryOrDie($query, "0.85 update followup with add_followups right");
    }
    $query = "DELETE\n             FROM `glpi_profilerights`\n             WHERE `name` = 'add_followups'";
    $DB->queryOrDie($query, "0.85 delete add_followups right");
    // delete group_add_followups
    foreach ($DB->request("glpi_profilerights", "`name` = 'group_add_followups' AND `rights` = '1'") as $profrights) {
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = `rights` | " . TicketFollowup::ADDGROUPTICKET . "\n                 WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                      AND `name` = 'followup'";
        $DB->queryOrDie($query, "0.85 update followup with group_add_followups right");
    }
    $query = "DELETE\n             FROM `glpi_profilerights`\n             WHERE `name` = 'group_add_followups'";
    $DB->queryOrDie($query, "0.85 delete group_add_followups right");
    // delete observe_ticket for followup
    foreach ($DB->request("glpi_profilerights", "`name` = 'observe_ticket' AND `rights` = '1'") as $profrights) {
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = `rights` | " . TicketFollowup::SEEPUBLIC . "\n                 WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                      AND `name` = 'followup'";
        $DB->queryOrDie($query, "0.85 update followup with observe_ticket right");
    }
    // don't delete observe_ticket because already use for task
    // delete show_full_ticket for followup
    foreach ($DB->request("glpi_profilerights", "`name` = 'show_full_ticket' AND `rights` = '1'") as $profrights) {
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = `rights` | " . TicketFollowup::SEEPUBLIC . " | " . TicketFollowup::SEEPRIVATE . "\n                 WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                      AND `name` = 'followup'";
        $DB->queryOrDie($query, "0.85 update followup with show_full_ticket right");
    }
    // don't delete show_full_ticket because already use for task
    // delete update_followups
    foreach ($DB->request("glpi_profilerights", "`name` = 'update_followups' AND `rights` = '1'") as $profrights) {
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = `rights` | " . READ . " | " . TicketFollowup::UPDATEALL . "\n                 WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                      AND `name` = 'followup'";
        $DB->queryOrDie($query, "0.85 update followup with update_followups right");
    }
    $query = "DELETE\n             FROM `glpi_profilerights`\n             WHERE `name` = 'update_followups'";
    $DB->queryOrDie($query, "0.85 delete update_followups right");
    // delete update_own_followups
    foreach ($DB->request("glpi_profilerights", "`name` = 'update_own_followups' AND `rights` = '1'") as $profrights) {
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = `rights` | " . READ . " | " . TicketFollowup::UPDATEMY . "\n                 WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                      AND `name` = 'followup'";
        $DB->queryOrDie($query, "0.85 update followup with update_own_followups right");
    }
    $query = "DELETE\n             FROM `glpi_profilerights`\n             WHERE `name` = 'update_own_followups'";
    $DB->queryOrDie($query, "0.85 delete update_own_followups right");
    // delete delete_followups
    foreach ($DB->request("glpi_profilerights", "`name` = 'delete_followups' AND `rights` = '1'") as $profrights) {
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = `rights` | " . PURGE . "\n                 WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                      AND `name` = 'followup'";
        $DB->queryOrDie($query, "0.85 update followup with delete_followups right");
    }
    $query = "DELETE\n             FROM `glpi_profilerights`\n             WHERE `name` = 'delete_followups'";
    $DB->queryOrDie($query, "0.85 delete delete_followups right");
    // pour que la procédure soit ré-entrante et ne pas perdre les sélections dans le profile
    if (countElementsInTable("glpi_profilerights", "`name` = 'task'") == 0) {
        // rename create_ticket
        $query = "UPDATE `glpi_profilerights`\n                 SET `name` = 'task'\n                 WHERE `name` = 'global_add_tasks'";
        $DB->queryOrDie($query, "0.85 rename global_add_tasks to task");
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = " . TicketTask::ADDALLTICKET . "\n                 WHERE `name` = 'task'\n                       AND `rights` = '1'";
        $DB->queryOrDie($query, "0.85 update followup with global_add_tasks right");
    }
    // delete update_tasks
    foreach ($DB->request("glpi_profilerights", "`name` = 'update_tasks' AND `rights` = '1'") as $profrights) {
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = `rights` | " . READ . " | " . TicketTask::UPDATEALL . " | " . PURGE . "\n                 WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                      AND `name` = 'task'";
        $DB->queryOrDie($query, "0.85 update task with update_tasks right");
    }
    $query = "DELETE\n             FROM `glpi_profilerights`\n             WHERE `name` = 'update_tasks'";
    $DB->queryOrDie($query, "0.85 delete update_tasks right");
    // delete observe_ticket for task
    foreach ($DB->request("glpi_profilerights", "`name` = 'observe_ticket' AND `rights` = '1'") as $profrights) {
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = `rights` | " . TicketTask::SEEPUBLIC . "\n                 WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                      AND `name` = 'task'";
        $DB->queryOrDie($query, "0.85 update task with observe_ticket right");
    }
    $query = "DELETE\n             FROM `glpi_profilerights`\n             WHERE `name` = 'observe_ticket'";
    $DB->queryOrDie($query, "0.85 delete observe_ticket right");
    // delete show_full_ticket for task
    foreach ($DB->request("glpi_profilerights", "`name` = 'show_full_ticket' AND `rights` = '1'") as $profrights) {
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = `rights` | " . TicketTask::SEEPUBLIC . " | " . TicketTask::SEEPRIVATE . "\n                 WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                      AND `name` = 'task'";
        $DB->queryOrDie($query, "0.85 update task with show_full_ticket right");
    }
    $query = "DELETE\n             FROM `glpi_profilerights`\n             WHERE `name` = 'show_full_ticket'";
    $DB->queryOrDie($query, "0.85 delete show_full_ticket right");
    // pour que la procédure soit ré-entrante et ne pas perdre les sélections dans le profile
    if (countElementsInTable("glpi_profilerights", "`name` = 'ticketvalidation'") == 0) {
        // rename delete_validations
        $query = "UPDATE `glpi_profilerights`\n                 SET `name` = 'ticketvalidation'\n                 WHERE `name` = 'delete_validations'";
        $DB->queryOrDie($query, "0.85 rename delete_validations to ticketvalidation");
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = " . DELETE . "\n                 WHERE `name` = 'ticketvalidation'\n                       AND `rights` = '1'";
        $DB->queryOrDie($query, "0.85 update ticketvalidation with delete_validations right");
    }
    // delete create_request_validation
    foreach ($DB->request("glpi_profilerights", "`name` = 'create_request_validation' AND `rights` = '1'") as $profrights) {
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = `rights` | " . TicketValidation::CREATEREQUEST . " | " . PURGE . "\n                 WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                       AND `name` = 'ticketvalidation'";
        $DB->queryOrDie($query, "0.85 update ticketvalidation with create_request_validation right");
    }
    $query = "DELETE\n             FROM `glpi_profilerights`\n             WHERE `name` = 'create_request_validation'";
    $DB->queryOrDie($query, "0.85 delete create_request_validation right");
    // delete create_incident_validation
    foreach ($DB->request("glpi_profilerights", "`name` = 'create_incident_validation' AND `rights` = '1'") as $profrights) {
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = `rights` | " . TicketValidation::CREATEINCIDENT . " | " . PURGE . "\n                 WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                       AND `name` = 'ticketvalidation'";
        $DB->queryOrDie($query, "0.85 update ticketvalidation with create_incident_validation right");
    }
    $query = "DELETE\n             FROM `glpi_profilerights`\n             WHERE `name` = 'create_incident_validation'";
    $DB->queryOrDie($query, "0.85 delete create_incident_validation right");
    // delete validate_request
    foreach ($DB->request("glpi_profilerights", "`name` = 'validate_request' AND `rights` = '1'") as $profrights) {
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = `rights` | " . TicketValidation::VALIDATEREQUEST . "\n                 WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                       AND `name` = 'ticketvalidation'";
        $DB->queryOrDie($query, "0.85 update ticketvalidation with validate_request right");
    }
    $query = "DELETE\n             FROM `glpi_profilerights`\n             WHERE `name` = 'validate_request'";
    $DB->queryOrDie($query, "0.85 delete validate_request right");
    // delete validate_incident
    foreach ($DB->request("glpi_profilerights", "`name` = 'validate_incident' AND `rights` = '1'") as $profrights) {
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = `rights` | " . TicketValidation::VALIDATEINCIDENT . "\n                 WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                       AND `name` = 'ticketvalidation'";
        $DB->queryOrDie($query, "0.85 update ticketvalidation with validate_incident right");
    }
    $query = "DELETE\n             FROM `glpi_profilerights`\n             WHERE `name` = 'validate_incident'";
    $DB->queryOrDie($query, "0.85 delete validate_incident right");
    // must be done after ticket right
    // pour que la procédure soit ré-entrante
    if (countElementsInTable("glpi_profilerights", "`name` = 'change'") == 0) {
        ProfileRight::addProfileRights(array('change'));
        ProfileRight::updateProfileRightAsOtherRight('change', Change::READMY, "`name` = 'ticket'\n                                                     AND `rights` & " . Ticket::OWN);
        ProfileRight::updateProfileRightAsOtherRight('change', Change::READALL, "`name` = 'ticket'\n                                                     AND `rights` & " . Ticket::READALL);
        ProfileRight::updateProfileRightAsOtherRight('change', CREATE . " | " . UPDATE . " | " . DELETE . " | " . PURGE, "`name` = 'ticket' AND `rights` & " . UPDATE);
    }
    if (countElementsInTable("glpi_profilerights", "`name` = 'changevalidation'") == 0) {
        ProfileRight::addProfileRights(array('changevalidation'));
        ProfileRight::updateProfileRightAsOtherRight('changevalidation', CREATE, "`name` = 'ticketvalidation'\n                                                     AND `rights` & " . TicketValidation::CREATEINCIDENT . "\n                                                     AND `rights` & " . TicketValidation::CREATEREQUEST);
        ProfileRight::updateProfileRightAsOtherRight('changevalidation', ChangeValidation::VALIDATE, "`name` = 'ticketvalidation'\n                                                     AND `rights` & " . TicketValidation::VALIDATEINCIDENT . "\n                                                     AND `rights` & " . TicketValidation::VALIDATEREQUEST);
        ProfileRight::updateProfileRightAsOtherRight('changevalidation', PURGE, "`name` = 'ticketvalidation'\n                                                     AND `rights` & " . PURGE);
    }
    // pour que la procédure soit ré-entrante et ne pas perdre les sélections dans le profile
    if (countElementsInTable("glpi_profilerights", "`name` = 'planning'") == 0) {
        // rename show_planning
        $query = "UPDATE `glpi_profilerights`\n                 SET `name` = 'planning'\n                 WHERE `name` = 'show_planning'";
        $DB->queryOrDie($query, "0.85 rename show_planning to planning");
        // READMY = 1 => do update needed
    }
    // delete show_group_planning
    foreach ($DB->request("glpi_profilerights", "`name` = 'show_group_planning' AND `rights` = '1'") as $profrights) {
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = `rights` | " . Planning::READGROUP . "\n                 WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                      AND `name` = 'planning'";
        $DB->queryOrDie($query, "0.85 update planning with show_group_planning right");
    }
    $query = "DELETE\n             FROM `glpi_profilerights`\n             WHERE `name` = 'show_group_planning'";
    $DB->queryOrDie($query, "0.85 delete show_group_planning right");
    // delete show_all_planning
    foreach ($DB->request("glpi_profilerights", "`name` = 'show_all_planning' AND `rights` = '1'") as $profrights) {
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = `rights` | " . Planning::READALL . "\n                 WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                      AND `name` = 'planning'";
        $DB->queryOrDie($query, "0.85 update planning with show_all_planning right");
    }
    $query = "DELETE\n             FROM `glpi_profilerights`\n             WHERE `name` = 'show_all_planning'";
    $DB->queryOrDie($query, "0.85 delete show_all_planning right");
    // pour que la procédure soit ré-entrante et ne pas perdre les sélections dans le profile
    if (countElementsInTable("glpi_profilerights", "`name` = 'problem'") == 0) {
        // rename show_my_problem
        $query = "UPDATE `glpi_profilerights`\n                 SET `name` = 'problem'\n                 WHERE `name` = 'show_my_problem'";
        $DB->queryOrDie($query, "0.85 rename show_my_problem to problem");
        // READMY = 1 => do update needed
    }
    // delete show_all_problem
    foreach ($DB->request("glpi_profilerights", "`name` = 'show_all_problem' AND `rights` = '1'") as $profrights) {
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = `rights` | " . Problem::READALL . "\n                 WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                      AND `name` = 'problem'";
        $DB->queryOrDie($query, "0.85 update problem with show_all_problem right");
    }
    $query = "DELETE\n             FROM `glpi_profilerights`\n             WHERE `name` = 'show_all_problem'";
    $DB->queryOrDie($query, "0.85 delete show_all_problem right");
    // delete edit_all_problem
    foreach ($DB->request("glpi_profilerights", "`name` = 'edit_all_problem' AND `rights` = '1'") as $profrights) {
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = `rights` | " . CREATE . " | " . UPDATE . " | " . PURGE . "\n                 WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                      AND `name` = 'problem'";
        $DB->queryOrDie($query, "0.85 update problem with edit_all_problem right");
    }
    $query = "DELETE\n             FROM `glpi_profilerights`\n             WHERE `name` = 'edit_all_problem'";
    $DB->queryOrDie($query, "0.85 delete edit_all_problem right");
    // delete delete_problem
    foreach ($DB->request("glpi_profilerights", "`name` = 'delete_problem' AND `rights` = '1'") as $profrights) {
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = `rights` | " . DELETE . "\n                 WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                      AND `name` = 'problem'";
        $DB->queryOrDie($query, "0.85 update problem with delete_problem");
    }
    $query = "DELETE\n             FROM `glpi_profilerights`\n             WHERE `name` = 'delete_problem'";
    $DB->queryOrDie($query, "0.85 delete problem right");
    // update search_config
    foreach ($DB->request("glpi_profilerights", "`name` = 'search_config' AND `rights` = '" . ALLSTANDARDRIGHT . "'") as $profrights) {
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = `rights` | " . DisplayPreference::PERSONAL . "\n                 WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                      AND `name` = 'search_config'";
        $DB->queryOrDie($query, "0.85 update search_config with search_config");
    }
    // delete search_config_global
    foreach ($DB->request("glpi_profilerights", "`name` = 'search_config_global' AND `rights` = '" . ALLSTANDARDRIGHT . "'") as $profrights) {
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = `rights` | " . DisplayPreference::GENERAL . "\n                 WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                      AND `name` = 'search_config'";
        $DB->queryOrDie($query, "0.85 update search_config with search_config_global");
    }
    $query = "DELETE\n             FROM `glpi_profilerights`\n             WHERE `name` = 'search_config_global'";
    $DB->queryOrDie($query, "0.85 delete search_config_global right");
    // delete check_update
    foreach ($DB->request("glpi_profilerights", "`name` = 'check_update' AND `rights` = '1'") as $profrights) {
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = `rights` | " . Backup::CHECKUPDATE . "\n                 WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                      AND `name` = 'backup'";
        $DB->queryOrDie($query, "0.85 update backup with check_update");
    }
    $query = "DELETE\n             FROM `glpi_profilerights`\n             WHERE `name` = 'check_update'";
    $DB->queryOrDie($query, "0.85 delete check_update right");
    // entity_dropdown => right by object
    // pour que la procédure soit ré-entrante et ne pas perdre les sélections dans le profile
    if (countElementsInTable("glpi_profilerights", "`name` = 'domain'") == 0) {
        ProfileRight::addProfileRights(array('domain'));
        ProfileRight::updateProfileRightsAsOtherRights('domain', 'entity_dropdown');
    }
    if (countElementsInTable("glpi_profilerights", "`name` = 'location'") == 0) {
        ProfileRight::addProfileRights(array('location'));
        ProfileRight::updateProfileRightsAsOtherRights('location', 'entity_dropdown');
    }
    if (countElementsInTable("glpi_profilerights", "`name` = 'itilcategory'") == 0) {
        ProfileRight::addProfileRights(array('itilcategory'));
        ProfileRight::updateProfileRightsAsOtherRights('itilcategory', 'entity_dropdown');
    }
    if (countElementsInTable("glpi_profilerights", "`name` = 'knowbasecategory'") == 0) {
        ProfileRight::addProfileRights(array('knowbasecategory'));
        ProfileRight::updateProfileRightsAsOtherRights('knowbasecategory', 'entity_dropdown');
    }
    if (countElementsInTable("glpi_profilerights", "`name` = 'netpoint'") == 0) {
        ProfileRight::addProfileRights(array('netpoint'));
        ProfileRight::updateProfileRightsAsOtherRights('netpoint', 'entity_dropdown');
    }
    if (countElementsInTable("glpi_profilerights", "`name` = 'taskcategory'") == 0) {
        ProfileRight::addProfileRights(array('taskcategory'));
        ProfileRight::updateProfileRightsAsOtherRights('taskcategory', 'entity_dropdown');
    }
    if (countElementsInTable("glpi_profilerights", "`name` = 'state'") == 0) {
        ProfileRight::addProfileRights(array('state'));
        ProfileRight::updateProfileRightsAsOtherRights('state', 'entity_dropdown');
    }
    if (countElementsInTable("glpi_profilerights", "`name` = 'solutiontemplate'") == 0) {
        ProfileRight::addProfileRights(array('solutiontemplate'));
        ProfileRight::updateProfileRightsAsOtherRights('solutiontemplate', 'entity_dropdown');
    }
    $query = "DELETE\n             FROM `glpi_profilerights`\n             WHERE `name` = 'entity_dropdown'";
    $DB->queryOrDie($query, "0.85 delete entity_dropdown right");
    // delete notes
    $tables = array('budget', 'cartridge', 'change', 'computer', 'consumable', 'contact_enterprise', 'contract', 'document', 'entity', 'monitor', 'networking', 'peripheral', 'phone', 'printer', 'problem', 'software');
    foreach ($DB->request("glpi_profilerights", "`name` = 'notes' AND `rights` = '1'") as $profrights) {
        foreach ($tables as $table) {
            $query = "UPDATE `glpi_profilerights`\n                    SET `rights` = `rights` | " . READNOTE . "\n                    WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                          AND `name` = '{$table}'";
            $DB->queryOrDie($query, "0.85 update {$table} with read notes right");
        }
    }
    foreach ($DB->request("glpi_profilerights", "`name` = 'notes' AND `rights` = '" . ALLSTANDARDRIGHT . "'") as $profrights) {
        foreach ($tables as $table) {
            $query = "UPDATE `glpi_profilerights`\n                    SET `rights` = `rights` | " . READNOTE . " | " . UPDATENOTE . "\n                    WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                          AND `name` = '{$table}'";
            $DB->queryOrDie($query, "0.85 update {$table} with update notes right");
        }
    }
    $query = "DELETE\n             FROM `glpi_profilerights`\n             WHERE `name` = 'notes'";
    $DB->queryOrDie($query, "0.85 delete notes right");
    $DELFROMDISPLAYPREF['Profile'] = array(29, 35, 37, 43, 53, 54, 57, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 80, 81, 88, 93, 94, 95, 96, 97, 98, 99, 104, 113, 114, 116, 117, 121, 122, 123);
    $migration->displayMessage('Update for mailqueue');
    if (!TableExists('glpi_queuedmails')) {
        $query = "CREATE TABLE `glpi_queuedmails` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `itemtype` varchar(100) default NULL,\n                  `items_id` int(11) NOT NULL DEFAULT '0',\n                  `notificationtemplates_id` int(11) NOT NULL DEFAULT '0',\n                  `entities_id` int(11) NOT NULL DEFAULT '0',\n                  `is_deleted` tinyint(1) NOT NULL DEFAULT '0',\n                  `sent_try` int(11) NOT NULL DEFAULT '0',\n                  `create_time` datetime DEFAULT NULL,\n                  `send_time` datetime DEFAULT NULL,\n                  `sent_time` datetime DEFAULT NULL,\n                  `name` TEXT DEFAULT NULL,\n                  `sender` TEXT DEFAULT NULL,\n                  `sendername` TEXT DEFAULT NULL,\n                  `recipient` TEXT DEFAULT NULL,\n                  `recipientname` TEXT DEFAULT NULL,\n                  `replyto` TEXT DEFAULT NULL,\n                  `replytoname` TEXT DEFAULT NULL,\n                  `headers` TEXT DEFAULT NULL,\n                  `body_html` LONGTEXT DEFAULT NULL,\n                  `body_text` LONGTEXT DEFAULT NULL,\n                  `messageid` TEXT DEFAULT NULL,\n                  PRIMARY KEY (`id`),\n                  KEY `item` (`itemtype`,`items_id`, `notificationtemplates_id`),\n                  KEY `is_deleted` (`is_deleted`),\n                  KEY `entities_id` (`entities_id`),\n                  KEY `sent_try` (`sent_try`),\n                  KEY `create_time` (`create_time`),\n                  KEY `send_time` (`send_time`),\n                  KEY `sent_time` (`sent_time`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.85 add glpi_queuedmails");
        $ADDTODISPLAYPREF['QueueMail'] = array(16, 7, 20, 21, 22, 15);
    }
    if (!countElementsInTable('glpi_crontasks', "`itemtype`='QueuedMail' AND `name`='queuedmail'")) {
        $query = "INSERT INTO `glpi_crontasks`\n                       (`itemtype`, `name`, `frequency`, `param`, `state`, `mode`, `allowmode`,\n                        `hourmin`, `hourmax`, `logs_lifetime`, `lastrun`, `lastcode`, `comment`)\n                VALUES ('QueuedMail', 'queuedmail', 60, 50, 1, 1, 3,\n                        0, 24, 30, NULL, NULL, NULL)";
        $DB->queryOrDie($query, "0.85 populate glpi_crontasks for queuemail");
    }
    if (!countElementsInTable('glpi_crontasks', "`itemtype`='QueuedMail' AND `name`='queuedmailclean'")) {
        $query = "INSERT INTO `glpi_crontasks`\n                       (`itemtype`, `name`, `frequency`, `param`, `state`, `mode`, `allowmode`,\n                        `hourmin`, `hourmax`, `logs_lifetime`, `lastrun`, `lastcode`, `comment`)\n                VALUES ('QueuedMail', 'queuedmailclean', 86400, 30, 1, 1, 3,\n                        0, 24, 30, NULL, NULL, NULL)";
        $DB->queryOrDie($query, "0.85 populate glpi_crontasks for queuemail");
    }
    if (!countElementsInTable('glpi_crontasks', "`itemtype`='Crontask' AND `name`='temp'")) {
        $query = "INSERT INTO `glpi_crontasks`\n                       (`itemtype`, `name`, `frequency`, `param`, `state`, `mode`, `allowmode`,\n                        `hourmin`, `hourmax`, `logs_lifetime`, `lastrun`, `lastcode`, `comment`)\n                VALUES ('Crontask', 'temp', 3600, NULL, 1, 1, 3,\n                        0, 24, 30, NULL, NULL, NULL)";
        $DB->queryOrDie($query, "0.85 populate glpi_crontasks for clean temporary files");
    }
    if ($migration->addField("glpi_entities", "delay_send_emails", "integer", array('value' => -2))) {
        $migration->migrationOneTable('glpi_entities');
        // Set directly to root entity
        $query = 'UPDATE `glpi_entities`
                SET `delay_send_emails` = 0
                WHERE `id` = 0';
        $DB->queryOrDie($query, "0.85 default value for delay_send_emails for root entity");
    }
    // pour que la procédure soit ré-entrante
    if (countElementsInTable("glpi_profilerights", "`name` = 'queuedmail'") == 0) {
        ProfileRight::addProfileRights(array('queuedmail'));
        ProfileRight::updateProfileRightsAsOtherRights('queuedmail', 'notification');
    }
    $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'Change'));
    // changes management
    if (!TableExists('glpi_changes')) {
        $query = "CREATE TABLE `glpi_changes` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `name` varchar(255) DEFAULT NULL,\n                  `entities_id` int(11) NOT NULL DEFAULT '0',\n                  `is_recursive` tinyint(1) NOT NULL DEFAULT '0',\n                  `is_deleted` tinyint(1) NOT NULL DEFAULT '0',\n                  `status` int(11) NOT NULL DEFAULT '1',\n                  `content` longtext DEFAULT NULL,\n                  `date_mod` DATETIME DEFAULT NULL,\n                  `date` DATETIME DEFAULT NULL,\n                  `solvedate` DATETIME DEFAULT NULL,\n                  `closedate` DATETIME DEFAULT NULL,\n                  `due_date` DATETIME DEFAULT NULL,\n                  `users_id_recipient` int(11) NOT NULL DEFAULT '0',\n                  `users_id_lastupdater` int(11) NOT NULL DEFAULT '0',\n                  `urgency` int(11) NOT NULL DEFAULT '1',\n                  `impact` int(11) NOT NULL DEFAULT '1',\n                  `priority` int(11) NOT NULL DEFAULT '1',\n                  `itilcategories_id` int(11) NOT NULL DEFAULT '0',\n                  `impactcontent` longtext DEFAULT NULL,\n                  `controlistcontent` longtext DEFAULT NULL,\n                  `rolloutplancontent` longtext DEFAULT NULL,\n                  `backoutplancontent` longtext DEFAULT NULL,\n                  `checklistcontent` longtext DEFAULT NULL,\n                  `global_validation` varchar(255) COLLATE utf8_unicode_ci DEFAULT 'none',\n                  `validation_percent` int(11) NOT NULL DEFAULT '0',\n                  `solutiontypes_id` int(11) NOT NULL DEFAULT '0',\n                  `solution` text COLLATE utf8_unicode_ci,\n                  `actiontime` int(11) NOT NULL DEFAULT '0',\n                  `begin_waiting_date` datetime DEFAULT NULL,\n                  `waiting_duration` int(11) NOT NULL DEFAULT '0',\n                  `close_delay_stat` int(11) NOT NULL DEFAULT '0',\n                  `solve_delay_stat` int(11) NOT NULL DEFAULT '0',\n                  `notepad` LONGTEXT NULL,\n                  PRIMARY KEY (`id`),\n                  KEY `name` (`name`),\n                  KEY `entities_id` (`entities_id`),\n                  KEY `is_recursive` (`is_recursive`),\n                  KEY `is_deleted` (`is_deleted`),\n                  KEY `date` (`date`),\n                  KEY `closedate` (`closedate`),\n                  KEY `status` (`status`),\n                  KEY `priority` (`priority`),\n                  KEY `date_mod` (`date_mod`),\n                  KEY `itilcategories_id` (`itilcategories_id`),\n                  KEY `users_id_recipient` (`users_id_recipient`),\n                  KEY `solvedate` (`solvedate`),\n                  KEY `solutiontypes_id` (`solutiontypes_id`),\n                  KEY `urgency` (`urgency`),\n                  KEY `impact` (`impact`),\n                  KEY `due_date` (`due_date`),\n                  KEY `global_validation` (`global_validation`),\n                  KEY `users_id_lastupdater` (`users_id_lastupdater`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.85 create glpi_changes");
    }
    $migration->addField('glpi_itilcategories', 'is_change', 'bool', array('value' => 1));
    $migration->addKey('glpi_itilcategories', 'is_change');
    if (!TableExists('glpi_changes_users')) {
        $query = "CREATE TABLE `glpi_changes_users` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `changes_id` int(11) NOT NULL DEFAULT '0',\n                  `users_id` int(11) NOT NULL DEFAULT '0',\n                  `type` int(11) NOT NULL DEFAULT '1',\n                  `use_notification` tinyint(1) NOT NULL DEFAULT '0',\n                  `alternative_email` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n                  PRIMARY KEY (`id`),\n                  UNIQUE KEY `unicity` (`changes_id`,`type`,`users_id`,`alternative_email`),\n                  KEY `user` (`users_id`,`type`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.85 add table glpi_changes_users");
    }
    if (!TableExists('glpi_changes_groups')) {
        $query = "CREATE TABLE `glpi_changes_groups` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `changes_id` int(11) NOT NULL DEFAULT '0',\n                  `groups_id` int(11) NOT NULL DEFAULT '0',\n                  `type` int(11) NOT NULL DEFAULT '1',\n                  PRIMARY KEY (`id`),\n                  UNIQUE KEY `unicity` (`changes_id`,`type`,`groups_id`),\n                  KEY `group` (`groups_id`,`type`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.85 add table glpi_changes_groups");
    }
    if (!TableExists('glpi_changes_suppliers')) {
        $query = "CREATE TABLE `glpi_changes_suppliers` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `changes_id` int(11) NOT NULL DEFAULT '0',\n                  `suppliers_id` int(11) NOT NULL DEFAULT '0',\n                  `type` int(11) NOT NULL DEFAULT '1',\n                  PRIMARY KEY (`id`),\n                  UNIQUE KEY `unicity` (`changes_id`,`type`,`suppliers_id`),\n                  KEY `group` (`suppliers_id`,`type`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.85 add table glpi_changes_suppliers");
    }
    if (!TableExists('glpi_changes_items')) {
        $query = "CREATE TABLE `glpi_changes_items` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `changes_id` int(11) NOT NULL DEFAULT '0',\n                  `itemtype` varchar(100) default NULL,\n                  `items_id` int(11) NOT NULL DEFAULT '0',\n                  PRIMARY KEY (`id`),\n                  UNIQUE KEY `unicity` (`changes_id`,`itemtype`,`items_id`),\n                  KEY `item` (`itemtype`,`items_id`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.85 add table glpi_changes_items");
    }
    if (!TableExists('glpi_changes_tickets')) {
        $query = "CREATE TABLE `glpi_changes_tickets` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `changes_id` int(11) NOT NULL DEFAULT '0',\n                  `tickets_id` int(11) NOT NULL DEFAULT '0',\n                  PRIMARY KEY (`id`),\n                  UNIQUE KEY `unicity` (`changes_id`,`tickets_id`),\n                  KEY `tickets_id` (`tickets_id`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.85 add table glpi_changes_tickets");
    }
    if (!TableExists('glpi_changes_problems')) {
        $query = "CREATE TABLE `glpi_changes_problems` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `changes_id` int(11) NOT NULL DEFAULT '0',\n                  `problems_id` int(11) NOT NULL DEFAULT '0',\n                  PRIMARY KEY (`id`),\n                  UNIQUE KEY `unicity` (`changes_id`,`problems_id`),\n                  KEY `problems_id` (`problems_id`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.85 add table glpi_changes_problems");
    }
    if (!TableExists('glpi_changetasks')) {
        $query = "CREATE TABLE `glpi_changetasks` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `changes_id` int(11) NOT NULL DEFAULT '0',\n                  `taskcategories_id` int(11) NOT NULL DEFAULT '0',\n                  `state` int(11) NOT NULL DEFAULT '0',\n                  `date` datetime DEFAULT NULL,\n                  `begin` datetime DEFAULT NULL,\n                  `end` datetime DEFAULT NULL,\n                  `users_id` int(11) NOT NULL DEFAULT '0',\n                  `users_id_tech` int(11) NOT NULL DEFAULT '0',\n                  `content` longtext COLLATE utf8_unicode_ci,\n                  `actiontime` int(11) NOT NULL DEFAULT '0',\n                  PRIMARY KEY (`id`),\n                  KEY `changes_id` (`changes_id`),\n                  KEY `state` (`state`),\n                  KEY `users_id` (`users_id`),\n                  KEY `users_id_tech` (`users_id_tech`),\n                  KEY `date` (`date`),\n                  KEY `begin` (`begin`),\n                  KEY `end` (`end`),\n                  KEY `taskcategories_id` (taskcategories_id)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.85 add table glpi_changetasks");
    }
    if (!TableExists('glpi_changecosts')) {
        $query = "CREATE TABLE `glpi_changecosts` (\n               `id` int(11) NOT NULL AUTO_INCREMENT,\n               `changes_id` int(11) NOT NULL DEFAULT '0',\n               `name` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n               `comment` text COLLATE utf8_unicode_ci,\n               `begin_date` date DEFAULT NULL,\n               `end_date` date DEFAULT NULL,\n               `actiontime` int(11) NOT NULL DEFAULT '0',\n               `cost_time` decimal(20,4) NOT NULL DEFAULT '0.0000',\n               `cost_fixed` decimal(20,4) NOT NULL DEFAULT '0.0000',\n               `cost_material` decimal(20,4) NOT NULL DEFAULT '0.0000',\n               `budgets_id` int(11) NOT NULL DEFAULT '0',\n               `entities_id` int(11) NOT NULL DEFAULT '0',\n               `is_recursive` tinyint(1) NOT NULL DEFAULT '0',\n               PRIMARY KEY (`id`),\n               KEY `name` (`name`),\n               KEY `changes_id` (`changes_id`),\n               KEY `begin_date` (`begin_date`),\n               KEY `end_date` (`end_date`),\n               KEY `entities_id` (`entities_id`),\n               KEY `is_recursive` (`is_recursive`),\n               KEY `budgets_id` (`budgets_id`)\n               ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;";
        $DB->queryOrDie($query, "0.85 add table glpi_changecosts");
    }
    if (!TableExists('glpi_changevalidations')) {
        $query = "CREATE TABLE `glpi_changevalidations` (\n            `id` int(11) NOT NULL AUTO_INCREMENT,\n            `entities_id` int(11) NOT NULL DEFAULT '0',\n            `is_recursive` tinyint(1) NOT NULL DEFAULT '0',\n            `users_id` int(11) NOT NULL DEFAULT '0',\n            `changes_id` int(11) NOT NULL DEFAULT '0',\n            `users_id_validate` int(11) NOT NULL DEFAULT '0',\n            `comment_submission` text COLLATE utf8_unicode_ci,\n            `comment_validation` text COLLATE utf8_unicode_ci,\n            `status` int(11) NOT NULL DEFAULT '2',\n            `submission_date` datetime DEFAULT NULL,\n            `validation_date` datetime DEFAULT NULL,\n            PRIMARY KEY (`id`),\n            KEY `entities_id` (`entities_id`),\n            KEY `is_recursive` (`is_recursive`),\n            KEY `users_id` (`users_id`),\n            KEY `users_id_validate` (`users_id_validate`),\n            KEY `changes_id` (`changes_id`),\n            KEY `submission_date` (`submission_date`),\n            KEY `validation_date` (`validation_date`),\n            KEY `status` (`status`)\n            ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;";
        $DB->queryOrDie($query, "0.85 add table glpi_changevalidations");
    }
    // Change notifications
    $query = "SELECT *\n             FROM `glpi_notificationtemplates`\n             WHERE `itemtype` = 'Change'";
    if ($result = $DB->query($query)) {
        if ($DB->numrows($result) == 0) {
            $query = "INSERT INTO `glpi_notificationtemplates`\n                          (`name`, `itemtype`, `date_mod`)\n                   VALUES ('Changes', 'Change', NOW())";
            $DB->queryOrDie($query, "0.85 add change notification");
            $notid = $DB->insert_id();
            $query = "INSERT INTO `glpi_notificationtemplatetranslations`\n                          (`notificationtemplates_id`, `language`, `subject`,\n                           `content_text`,\n                           `content_html`)\n                   VALUES ({$notid}, '', '##change.action## ##change.title##',\n                          '##IFchange.storestatus=5##\n ##lang.change.url## : ##change.urlapprove##\n ##lang.change.solvedate## : ##change.solvedate##\n ##lang.change.solution.type## : ##change.solution.type##\n ##lang.change.solution.description## : ##change.solution.description## ##ENDIFchange.storestatus##\n ##ELSEchange.storestatus## ##lang.change.url## : ##change.url## ##ENDELSEchange.storestatus##\n\n ##lang.change.description##\n\n ##lang.change.title##  :##change.title##\n ##lang.change.authors##  :##IFchange.authors## ##change.authors## ##ENDIFchange.authors## ##ELSEchange.authors##--##ENDELSEchange.authors##\n ##lang.change.creationdate##  :##change.creationdate##\n ##IFchange.assigntousers## ##lang.change.assigntousers##  : ##change.assigntousers## ##ENDIFchange.assigntousers##\n ##lang.change.status##  : ##change.status##\n ##IFchange.assigntogroups## ##lang.change.assigntogroups##  : ##change.assigntogroups## ##ENDIFchange.assigntogroups##\n ##lang.change.urgency##  : ##change.urgency##\n ##lang.change.impact##  : ##change.impact##\n ##lang.change.priority## : ##change.priority##\n##IFchange.category## ##lang.change.category##  :##change.category## ##ENDIFchange.category## ##ELSEchange.category## ##lang.change.nocategoryassigned## ##ENDELSEchange.category##\n ##lang.change.content##  : ##change.content##\n\n##IFchange.storestatus=6##\n ##lang.change.solvedate## : ##change.solvedate##\n ##lang.change.solution.type## : ##change.solution.type##\n ##lang.change.solution.description## : ##change.solution.description##\n##ENDIFchange.storestatus##\n ##lang.change.numberofproblems## : ##change.numberofproblems##\n\n##FOREACHproblems##\n [##problem.date##] ##lang.change.title## : ##problem.title##\n ##lang.change.content## ##problem.content##\n\n##ENDFOREACHproblems##\n ##lang.change.numberoftasks## : ##change.numberoftasks##\n\n##FOREACHtasks##\n [##task.date##]\n ##lang.task.author## ##task.author##\n ##lang.task.description## ##task.description##\n ##lang.task.time## ##task.time##\n ##lang.task.category## ##task.category##\n\n##ENDFOREACHtasks##\n',\n                          '&lt;p&gt;##IFchange.storestatus=5##&lt;/p&gt;\n&lt;div&gt;##lang.change.url## : &lt;a href=\"##change.urlapprove##\"&gt;##change.urlapprove##&lt;/a&gt;&lt;/div&gt;\n&lt;div&gt;&lt;span style=\"color: #888888;\"&gt;&lt;strong&gt;&lt;span style=\"text-decoration: underline;\"&gt;##lang.change.solvedate##&lt;/span&gt;&lt;/strong&gt;&lt;/span&gt; : ##change.solvedate##&lt;br /&gt;&lt;span style=\"text-decoration: underline; color: #888888;\"&gt;&lt;strong&gt;##lang.change.solution.type##&lt;/strong&gt;&lt;/span&gt; : ##change.solution.type##&lt;br /&gt;&lt;span style=\"text-decoration: underline; color: #888888;\"&gt;&lt;strong&gt;##lang.change.solution.description##&lt;/strong&gt;&lt;/span&gt; : ##change.solution.description## ##ENDIFchange.storestatus##&lt;/div&gt;\n&lt;div&gt;##ELSEchange.storestatus## ##lang.change.url## : &lt;a href=\"##change.url##\"&gt;##change.url##&lt;/a&gt; ##ENDELSEchange.storestatus##&lt;/div&gt;\n&lt;p class=\"description b\"&gt;&lt;strong&gt;##lang.change.description##&lt;/strong&gt;&lt;/p&gt;\n&lt;p&gt;&lt;span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"&gt; ##lang.change.title##&lt;/span&gt;&#160;:##change.title## &lt;br /&gt; &lt;span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"&gt; ##lang.change.authors##&lt;/span&gt;&#160;:##IFchange.authors## ##change.authors## ##ENDIFchange.authors##    ##ELSEchange.authors##--##ENDELSEchange.authors## &lt;br /&gt; &lt;span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"&gt; ##lang.change.creationdate##&lt;/span&gt;&#160;:##change.creationdate## &lt;br /&gt; ##IFchange.assigntousers## &lt;span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"&gt; ##lang.change.assigntousers##&lt;/span&gt;&#160;: ##change.assigntousers## ##ENDIFchange.assigntousers##&lt;br /&gt; &lt;span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"&gt;##lang.change.status## &lt;/span&gt;&#160;: ##change.status##&lt;br /&gt; ##IFchange.assigntogroups## &lt;span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"&gt; ##lang.change.assigntogroups##&lt;/span&gt;&#160;: ##change.assigntogroups## ##ENDIFchange.assigntogroups##&lt;br /&gt; &lt;span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"&gt; ##lang.change.urgency##&lt;/span&gt;&#160;: ##change.urgency##&lt;br /&gt; &lt;span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"&gt; ##lang.change.impact##&lt;/span&gt;&#160;: ##change.impact##&lt;br /&gt; &lt;span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"&gt; ##lang.change.priority##&lt;/span&gt; : ##change.priority## &lt;br /&gt;##IFchange.category##&lt;span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"&gt;##lang.change.category## &lt;/span&gt;&#160;:##change.category##  ##ENDIFchange.category## ##ELSEchange.category##  ##lang.change.nocategoryassigned## ##ENDELSEchange.category##    &lt;br /&gt; &lt;span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"&gt; ##lang.change.content##&lt;/span&gt;&#160;: ##change.content##&lt;/p&gt;\n&lt;p&gt;##IFchange.storestatus=6##&lt;br /&gt;&lt;span style=\"text-decoration: underline;\"&gt;&lt;strong&gt;&lt;span style=\"color: #888888;\"&gt;##lang.change.solvedate##&lt;/span&gt;&lt;/strong&gt;&lt;/span&gt; : ##change.solvedate##&lt;br /&gt;&lt;span style=\"color: #888888;\"&gt;&lt;strong&gt;&lt;span style=\"text-decoration: underline;\"&gt;##lang.change.solution.type##&lt;/span&gt;&lt;/strong&gt;&lt;/span&gt; : ##change.solution.type##&lt;br /&gt;&lt;span style=\"text-decoration: underline; color: #888888;\"&gt;&lt;strong&gt;##lang.change.solution.description##&lt;/strong&gt;&lt;/span&gt; : ##change.solution.description##&lt;br /&gt;##ENDIFchange.storestatus##&lt;/p&gt;\n&lt;div class=\"description b\"&gt;##lang.change.numberofproblems##&#160;: ##change.numberofproblems##&lt;/div&gt;\n&lt;p&gt;##FOREACHproblems##&lt;/p&gt;\n&lt;div&gt;&lt;strong&gt; [##problem.date##] &lt;em&gt;##lang.change.title## : &lt;a href=\"##problem.url##\"&gt;##problem.title## &lt;/a&gt;&lt;/em&gt;&lt;/strong&gt;&lt;br /&gt; &lt;span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"&gt; &lt;/span&gt;&lt;span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"&gt;##lang.change.content## &lt;/span&gt; ##problem.content##\n&lt;p&gt;##ENDFOREACHproblems##&lt;/p&gt;\n&lt;div class=\"description b\"&gt;##lang.change.numberoftasks##&#160;: ##change.numberoftasks##&lt;/div&gt;\n&lt;p&gt;##FOREACHtasks##&lt;/p&gt;\n&lt;div class=\"description b\"&gt;&lt;strong&gt;[##task.date##] &lt;/strong&gt;&lt;br /&gt; &lt;span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"&gt; ##lang.task.author##&lt;/span&gt; ##task.author##&lt;br /&gt; &lt;span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"&gt; ##lang.task.description##&lt;/span&gt; ##task.description##&lt;br /&gt; &lt;span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"&gt; ##lang.task.time##&lt;/span&gt; ##task.time##&lt;br /&gt; &lt;span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"&gt; ##lang.task.category##&lt;/span&gt; ##task.category##&lt;/div&gt;\n&lt;p&gt;##ENDFOREACHtasks##&lt;/p&gt;\n&lt;/div&gt;')";
            $DB->queryOrDie($query, "0.85 add change notification translation");
            $notifications = array('new' => array(), 'update' => array(Notification::ASSIGN_TECH, Notification::OLD_TECH_IN_CHARGE), 'solved' => array(), 'add_task' => array(), 'update_task' => array(), 'delete_task' => array(), 'closed' => array(), 'delete' => array());
            $notif_names = array('new' => 'New Change', 'update' => 'Update Change', 'solved' => 'Resolve Change', 'add_task' => 'Add Task', 'update_task' => 'Update Task', 'delete_task' => 'Delete Task', 'closed' => 'Close Change', 'delete' => 'Delete Change');
            foreach ($notifications as $key => $val) {
                $notifications[$key][] = Notification::AUTHOR;
                $notifications[$key][] = Notification::GLOBAL_ADMINISTRATOR;
                $notifications[$key][] = Notification::OBSERVER;
            }
            foreach ($notifications as $type => $targets) {
                $query = "INSERT INTO `glpi_notifications`\n                             (`name`, `entities_id`, `itemtype`, `event`, `mode`,\n                              `notificationtemplates_id`, `comment`, `is_recursive`, `is_active`,\n                              `date_mod`)\n                      VALUES ('" . $notif_names[$type] . "', 0, 'Change', '{$type}', 'mail',\n                              {$notid}, '', 1, 1, NOW())";
                $DB->queryOrDie($query, "0.85 add change {$type} notification");
                $notifid = $DB->insert_id();
                foreach ($targets as $target) {
                    $query = "INSERT INTO `glpi_notificationtargets`\n                                (`id`, `notifications_id`, `type`, `items_id`)\n                         VALUES (NULL, {$notifid}, " . Notification::USER_TYPE . ", {$target});";
                    $DB->queryOrDie($query, "0.85 add change {$type} notification target");
                }
            }
        }
    }
    $ADDTODISPLAYPREF['Change'] = array(12, 19, 15, 7, 18);
    $migration->addField('glpi_profiles', 'change_status', "text", array('comment' => "json encoded array of from/dest allowed status change"));
    // Add problem costs
    if (!TableExists('glpi_problemcosts')) {
        $query = "CREATE TABLE `glpi_problemcosts` (\n               `id` int(11) NOT NULL AUTO_INCREMENT,\n               `problems_id` int(11) NOT NULL DEFAULT '0',\n               `name` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n               `comment` text COLLATE utf8_unicode_ci,\n               `begin_date` date DEFAULT NULL,\n               `end_date` date DEFAULT NULL,\n               `actiontime` int(11) NOT NULL DEFAULT '0',\n               `cost_time` decimal(20,4) NOT NULL DEFAULT '0.0000',\n               `cost_fixed` decimal(20,4) NOT NULL DEFAULT '0.0000',\n               `cost_material` decimal(20,4) NOT NULL DEFAULT '0.0000',\n               `budgets_id` int(11) NOT NULL DEFAULT '0',\n               `entities_id` int(11) NOT NULL DEFAULT '0',\n               PRIMARY KEY (`id`),\n               KEY `name` (`name`),\n               KEY `problems_id` (`problems_id`),\n               KEY `begin_date` (`begin_date`),\n               KEY `end_date` (`end_date`),\n               KEY `entities_id` (`entities_id`),\n               KEY `budgets_id` (`budgets_id`)\n               ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;";
        $DB->queryOrDie($query, "0.85 add table glpi_problemcosts");
    }
    $migration->displayMessage(sprintf(__('Data migration - %s'), 'drop rules cache'));
    $migration->dropTable('glpi_rulecachecomputermodels');
    $migration->dropTable('glpi_rulecachecomputertypes');
    $migration->dropTable('glpi_rulecachemanufacturers');
    $migration->dropTable('glpi_rulecachemonitormodels');
    $migration->dropTable('glpi_rulecachemonitortypes');
    $migration->dropTable('glpi_rulecachenetworkequipmentmodels');
    $migration->dropTable('glpi_rulecachenetworkequipmenttypes');
    $migration->dropTable('glpi_rulecacheoperatingsystems');
    $migration->dropTable('glpi_rulecacheoperatingsystemservicepacks');
    $migration->dropTable('glpi_rulecacheoperatingsystemversions');
    $migration->dropTable('glpi_rulecacheperipheralmodels');
    $migration->dropTable('glpi_rulecacheperipheraltypes');
    $migration->dropTable('glpi_rulecachephonemodels');
    $migration->dropTable('glpi_rulecachephonetypes');
    $migration->dropTable('glpi_rulecacheprintermodels');
    $migration->dropTable('glpi_rulecacheprinters');
    $migration->dropTable('glpi_rulecacheprintertypes');
    $migration->dropTable('glpi_rulecachesoftwares');
    $migration->displayMessage(sprintf(__('Data migration - %s'), 'glpi_rules'));
    $migration->addField("glpi_rules", 'uuid', "string");
    $migration->addField("glpi_slalevels", 'uuid', "string");
    $migration->migrationOneTable('glpi_rules');
    $migration->migrationOneTable('glpi_slalevels');
    // Dropdown translations
    $migration->displayMessage(sprintf(__('Data migration - %s'), 'glpi_knowbaseitemtranslations'));
    Config::setConfigurationValues('core', array('translate_kb' => 0));
    if (!TableExists("glpi_knowbaseitemtranslations")) {
        $query = "CREATE TABLE IF NOT EXISTS `glpi_knowbaseitemtranslations` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `knowbaseitems_id` int(11) NOT NULL DEFAULT '0',\n                  `language` varchar(5) COLLATE utf8_unicode_ci DEFAULT NULL,\n                  `name` text COLLATE utf8_unicode_ci,\n                  `answer` longtext COLLATE utf8_unicode_ci,\n                  PRIMARY KEY (`id`),\n                  KEY `item` (`knowbaseitems_id`, `language`),\n                  FULLTEXT KEY `fulltext` (`name`,`answer`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;";
        $DB->queryOrDie($query, "0.85 add table glpi_knowbaseitemtranslations");
    }
    // kb translations
    $migration->displayMessage(sprintf(__('Data migration - %s'), 'glpi_dropdowntranslations'));
    Config::setConfigurationValues('core', array('translate_dropdowns' => 0));
    if (!TableExists("glpi_dropdowntranslations")) {
        $query = "CREATE TABLE IF NOT EXISTS `glpi_dropdowntranslations` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `items_id` int(11) NOT NULL DEFAULT '0',\n                  `itemtype` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,\n                  `language` varchar(5) COLLATE utf8_unicode_ci DEFAULT NULL,\n                  `field` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,\n                  `value` text COLLATE utf8_unicode_ci,\n                  PRIMARY KEY (`id`),\n                  UNIQUE KEY `unicity` (`itemtype`,`items_id`,`language`,`field`),\n                  KEY `typeid` (`itemtype`,`items_id`),\n                  KEY `language` (`language`),\n                  KEY `field` (`field`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;";
        $DB->queryOrDie($query, "0.85 add table glpi_dropdowntranslations");
    }
    //generate uuid for the basic rules of glpi
    // we use a complete sql where for cover all migration case (0.78 -> 0.85)
    $rules = array(array('sub_type' => 'RuleImportEntity', 'name' => 'Root', 'match' => 'AND', 'description' => ''), array('sub_type' => 'RuleRight', 'name' => 'Root', 'match' => 'AND', 'description' => ''), array('sub_type' => 'RuleMailCollector', 'name' => 'Root', 'match' => 'AND', 'description' => ''), array('sub_type' => 'RuleMailCollector', 'name' => 'Auto-Reply X-Auto-Response-Suppress', 'match' => 'AND', 'description' => 'Exclude Auto-Reply emails using X-Auto-Response-Suppress header'), array('sub_type' => 'RuleMailCollector', 'name' => 'Auto-Reply Auto-Submitted', 'match' => 'AND', 'description' => 'Exclude Auto-Reply emails using Auto-Submitted header'), array('sub_type' => 'RuleTicket', 'name' => 'Ticket location from item', 'match' => 'AND', 'description' => ''), array('sub_type' => 'RuleTicket', 'name' => 'Ticket location from user', 'match' => 'AND', 'description' => ''));
    $i = 0;
    foreach ($rules as $rule) {
        $query = "UPDATE `glpi_rules`\n                 SET `uuid` = 'STATIC-UUID-{$i}'\n                 WHERE `entities_id` = 0\n                       AND `is_recursive` = 0\n                       AND `sub_type` = '" . $rule['sub_type'] . "'\n                       AND `name` = '" . $rule['name'] . "'\n                       AND `description` = '" . $rule['description'] . "'\n                       AND `match` = '" . $rule['match'] . "'\n                 ORDER BY id ASC\n                 LIMIT 1";
        $DB->queryOrDie($query, "0.85 add uuid to basic rules (STATIC-UUID-{$i})");
        $i++;
    }
    //generate uuid for the rules of user
    foreach ($DB->request('glpi_rules', array('uuid' => NULL)) as $data) {
        $uuid = Rule::getUuid();
        $query = "UPDATE `glpi_rules`\n                SET `uuid` = '{$uuid}'\n                WHERE `id` = '" . $data['id'] . "'";
        $DB->queryOrDie($query, "0.85 add uuid to existing rules");
    }
    foreach ($DB->request('glpi_slalevels', array('uuid' => NULL)) as $data) {
        $uuid = Rule::getUuid();
        $query = "UPDATE `glpi_slalevels`\n                SET `uuid` = '{$uuid}'\n                WHERE `id` = '" . $data['id'] . "'";
        $DB->queryOrDie($query, "0.85 add uuid to existing slalevels");
    }
    $migration->addField('glpi_users', 'is_deleted_ldap', 'bool');
    $migration->addKey('glpi_users', 'is_deleted_ldap');
    Config::deleteConfigurationValues('core', array('use_ajax'));
    Config::deleteConfigurationValues('core', array('ajax_min_textsearch_load'));
    Config::deleteConfigurationValues('core', array('ajax_buffertime_load'));
    Config::deleteConfigurationValues('core', array('is_categorized_soft_expanded'));
    Config::deleteConfigurationValues('core', array('is_not_categorized_soft_expanded'));
    $migration->dropField("glpi_users", 'is_categorized_soft_expanded');
    $migration->dropField("glpi_users", 'is_not_categorized_soft_expanded');
    // Config::setConfigurationValues('core', array('use_unicodefont' => 0));
    // $migration->addField("glpi_users", 'use_unicodefont', "int(11) DEFAULT NULL");
    Config::deleteConfigurationValues('core', array('use_unicodefont'));
    $migration->dropField("glpi_users", 'use_unicodefont');
    Config::setConfigurationValues('core', array('pdffont' => 'helvetica'));
    $migration->addField("glpi_users", 'pdffont', "string");
    $migration->addField("glpi_users", 'picture', "string");
    $migration->addField("glpi_authldaps", 'picture_field', 'string');
    $migration->addField('glpi_links', 'open_window', 'bool', array('value' => 1));
    $migration->displayMessage(sprintf(__('Data migration - %s'), 'glpi_states'));
    foreach (array('is_visible_computer', 'is_visible_monitor', 'is_visible_networkequipment', 'is_visible_peripheral', 'is_visible_phone', 'is_visible_printer', 'is_visible_softwareversion') as $field) {
        $migration->addField('glpi_states', $field, 'bool', array('value' => '1'));
        $migration->addKey('glpi_states', $field);
    }
    // glpi_domains by entity
    $migration->addField('glpi_domains', 'entities_id', 'integer', array('after' => 'name'));
    $migration->addField('glpi_domains', 'is_recursive', 'bool', array('update' => '1', 'after' => 'entities_id'));
    // glpi_states by entity
    $migration->addField('glpi_states', 'entities_id', 'integer', array('after' => 'name'));
    $migration->addField('glpi_states', 'is_recursive', 'bool', array('update' => '1', 'after' => 'entities_id'));
    // add validity date for a user
    $migration->addField('glpi_users', 'begin_date', 'datetime');
    $migration->addField('glpi_users', 'end_date', 'datetime');
    // add validity date for a knowbaseitem
    $migration->addField('glpi_knowbaseitems', 'begin_date', 'datetime');
    $migration->addField('glpi_knowbaseitems', 'end_date', 'datetime');
    // Add validation percent for tickets
    $migration->addField('glpi_tickets', 'validation_percent', 'integer', array('value' => 0));
    // Add missing key
    $migration->addKey('glpi_tickettasks', 'state');
    $migration->addKey('glpi_tickettasks', 'users_id_tech');
    $migration->addKey('glpi_tickettasks', 'begin');
    $migration->addKey('glpi_tickettasks', 'end');
    // Create notification for reply to satisfaction survey based on satisfaction notif
    // Check if notifications already exists
    if (countElementsInTable('glpi_notifications', "`itemtype` = 'Ticket'\n                              AND `event` = 'replysatisfaction'") == 0) {
        // No notifications duplicate all
        $query = "SELECT *\n                FROM `glpi_notifications`\n                WHERE `itemtype` = 'Ticket'\n                      AND `event` = 'satisfaction'";
        foreach ($DB->request($query) as $notif) {
            $query = "INSERT INTO `glpi_notifications`\n                          (`name`, `entities_id`, `itemtype`, `event`, `mode`,\n                          `notificationtemplates_id`, `comment`, `is_recursive`, `is_active`,\n                          `date_mod`)\n                   VALUES ('" . addslashes($notif['name']) . " Answer',\n                           '" . $notif['entities_id'] . "', 'Ticket',\n                           'replysatisfaction', '" . $notif['mode'] . "',\n                           '" . $notif['notificationtemplates_id'] . "',\n                           '" . addslashes($notif['comment']) . "', '" . $notif['is_recursive'] . "',\n                           '" . $notif['is_active'] . "', NOW());";
            $DB->queryOrDie($query, "0.85 insert replysatisfaction notification");
            $newID = $DB->insert_id();
            $query2 = "SELECT *\n                    FROM `glpi_notificationtargets`\n                    WHERE `notifications_id` = '" . $notif['id'] . "'";
            // Add same recipent of satisfaction
            foreach ($DB->request($query2) as $target) {
                $query = "INSERT INTO `glpi_notificationtargets`\n                             (`notifications_id`, `type`, `items_id`)\n                      VALUES ({$newID}, '" . $target['type'] . "', '" . $target['items_id'] . "')";
                $DB->queryOrDie($query, "0.85 insert targets for replysatisfaction notification");
            }
            // Add Tech in charge
            $query = "INSERT INTO `glpi_notificationtargets`\n                             (`notifications_id`, `type`, `items_id`)\n                      VALUES ({$newID}, '" . Notification::USER_TYPE . "', '" . Notification::ASSIGN_TECH . "')";
            $DB->queryOrDie($query, "0.85 insert tech in charge target for replysatisfaction notification");
        }
    }
    $migration->displayMessage(sprintf(__('Data migration - %s'), 'glpi_slas'));
    // * Convert SLA resolution time to new system (ticket #4346)
    if (!FieldExists("glpi_slas", "definition_time")) {
        $migration->addField("glpi_slas", 'definition_time', "string");
        $migration->addField("glpi_slas", 'end_of_working_day', "bool");
        $migration->migrationOneTable('glpi_slas');
        // Minutes
        $query = "SELECT *\n                FROM `glpi_slas`\n                WHERE `resolution_time` <= '3000'";
        if ($result = $DB->query($query)) {
            if ($DB->numrows($result) > 0) {
                $a_ids = array();
                while ($data = $DB->fetch_assoc($result)) {
                    $a_ids[] = $data['id'];
                }
                $DB->query("UPDATE `glpi_slas`\n                        SET `definition_time` = 'minute',\n                            `resolution_time` = `resolution_time`/60\n                        WHERE `id` IN (" . implode(",", $a_ids) . ")");
            }
        }
        // Hours
        $query = "SELECT *\n                FROM `glpi_slas`\n                WHERE `resolution_time` > '3000'\n                      AND `resolution_time` <= '82800'";
        if ($result = $DB->query($query)) {
            if ($DB->numrows($result) > 0) {
                $a_ids = array();
                while ($data = $DB->fetch_assoc($result)) {
                    $a_ids[] = $data['id'];
                }
                $DB->query("UPDATE `glpi_slas`\n                        SET `definition_time` = 'hour',\n                            `resolution_time` = `resolution_time`/3600\n                        WHERE `id` IN (" . implode(",", $a_ids) . ")");
            }
        }
        // Days
        $query = "SELECT *\n                FROM `glpi_slas`\n                WHERE `resolution_time` > '82800'";
        if ($result = $DB->query($query)) {
            if ($DB->numrows($result) > 0) {
                $a_ids = array();
                while ($data = $DB->fetch_assoc($result)) {
                    $a_ids[] = $data['id'];
                }
                $DB->query("UPDATE `glpi_slas`\n                        SET `definition_time` = 'day',\n                            `resolution_time` = `resolution_time`/86400\n                        WHERE `id` IN (" . implode(",", $a_ids) . ")");
            }
        }
    }
    Config::setConfigurationValues('core', array('keep_devices_when_purging_item' => 0));
    $migration->addField("glpi_users", "keep_devices_when_purging_item", "int(11) DEFAULT NULL");
    Config::setConfigurationValues('core', array('maintenance_mode' => 0));
    Config::setConfigurationValues('core', array('maintenance_text' => ''));
    $query = "SELECT *\n             FROM `glpi_notificationtemplates`\n             WHERE `itemtype` = 'MailCollector'";
    if ($result = $DB->query($query)) {
        if ($DB->numrows($result) == 0) {
            $query = "INSERT INTO `glpi_notificationtemplates`\n                          (`name`, `itemtype`, `date_mod`)\n                   VALUES ('Receiver errors', 'MailCollector', NOW())";
            $DB->queryOrDie($query, "0.85 add mail collector notification");
            $notid = $DB->insert_id();
            $query = "INSERT INTO `glpi_notificationtemplatetranslations`\n                          (`notificationtemplates_id`, `language`, `subject`,\n                           `content_text`,\n                           `content_html`)\n                   VALUES ({$notid}, '', '##mailcollector.action##',\n                           '##FOREACHmailcollectors##\n##lang.mailcollector.name## : ##mailcollector.name##\n##lang.mailcollector.errors## : ##mailcollector.errors##\n##mailcollector.url##\n##ENDFOREACHmailcollectors##',\n'&lt;p&gt;##FOREACHmailcollectors##&lt;br /&gt;##lang.mailcollector.name## : ##mailcollector.name##&lt;br /&gt; ##lang.mailcollector.errors## : ##mailcollector.errors##&lt;br /&gt;&lt;a href=\"##mailcollector.url##\"&gt;##mailcollector.url##&lt;/a&gt;&lt;br /&gt; ##ENDFOREACHmailcollectors##&lt;/p&gt;\n&lt;p&gt;&lt;/p&gt;')";
            $DB->queryOrDie($query, "0.85 add mail collector notification translation");
            $query = "INSERT INTO `glpi_notifications`\n                          (`name`, `entities_id`, `itemtype`, `event`, `mode`,\n                           `notificationtemplates_id`, `comment`, `is_recursive`, `is_active`,\n                           `date_mod`)\n                   VALUES ('Receiver errors', 0, 'MailCollector', 'error', 'mail',\n                             {$notid}, '', 1, 1, NOW())";
            $DB->queryOrDie($query, "0.85 add mail collector notification");
            $notifid = $DB->insert_id();
            $query = "INSERT INTO `glpi_notificationtargets`\n                          (`id`, `notifications_id`, `type`, `items_id`)\n                   VALUES (NULL, {$notifid}, " . Notification::USER_TYPE . ", " . Notification::GLOBAL_ADMINISTRATOR . ");";
            $DB->queryOrDie($query, "0.85 add mail collector notification target");
        }
    }
    if (!countElementsInTable('glpi_crontasks', "`itemtype`='MailCollector' AND `name`='mailgateerror'")) {
        $query = "INSERT INTO `glpi_crontasks`\n                       (`itemtype`, `name`, `frequency`, `param`, `state`, `mode`, `allowmode`,\n                        `hourmin`, `hourmax`, `logs_lifetime`, `lastrun`, `lastcode`, `comment`)\n                VALUES ('MailCollector', 'mailgateerror', " . DAY_TIMESTAMP . ", NULL, 1, 1, 3,\n                        0, 24, 30, NULL, NULL, NULL)";
        $DB->queryOrDie($query, "0.85 populate glpi_crontasks for mailgateerror");
    }
    if (!countElementsInTable('glpi_crontasks', "`itemtype`='Crontask' AND `name`='circularlogs'")) {
        $query = "INSERT INTO `glpi_crontasks`\n                       (`itemtype`, `name`, `frequency`, `param`, `state`, `mode`, `allowmode`,\n                        `hourmin`, `hourmax`, `logs_lifetime`, `lastrun`, `lastcode`, `comment`)\n                VALUES ('Crontask', 'circularlogs', " . DAY_TIMESTAMP . ", 4, " . CronTask::STATE_DISABLE . ", 1, 3,\n                        0, 24, 30, NULL, NULL, NULL)";
        $DB->queryOrDie($query, "0.85 populate glpi_crontasks for circularlogs");
    }
    $migration->displayMessage(sprintf(__('Data migration - %s'), 'glpi_documents'));
    $migration->addField('glpi_documents', 'is_blacklisted', 'bool');
    if (!TableExists("glpi_blacklistedmailcontents")) {
        $query = "CREATE TABLE IF NOT EXISTS `glpi_blacklistedmailcontents` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `name` varchar(255) DEFAULT NULL,\n                  `content` text COLLATE utf8_unicode_ci,\n                  `comment` text COLLATE utf8_unicode_ci,\n                  PRIMARY KEY (`id`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;";
        $DB->queryOrDie($query, "0.85 add table glpi_blacklistedmailcontents");
    }
    $migration->addField('glpi_documents', 'tag', 'string');
    $migration->addField('glpi_queuedmails', 'documents', 'text');
    $migration->addKey('glpi_documents', 'tag');
    Config::setConfigurationValues('core', array('use_rich_text' => 0));
    Config::setConfigurationValues('core', array('attach_ticket_documents_to_mail' => 0));
    $migration->migrationOneTable('glpi_documents');
    $query = "UPDATE `glpi_documents`\n             SET `tag` = `id`";
    $DB->queryOrDie($query, "0.85 set tag to all documents");
    // increase password length
    $migration->changeField('glpi_users', 'password', 'password', 'string');
    $migration->displayMessage(sprintf(__('Data migration - %s'), 'glpi_softwarecategories'));
    // Hierarchical software category
    $migration->addField('glpi_softwarecategories', 'softwarecategories_id', 'integer');
    $migration->addField("glpi_softwarecategories", 'completename', "text");
    $migration->addField("glpi_softwarecategories", 'level', "integer");
    $migration->addField("glpi_softwarecategories", 'ancestors_cache', "longtext");
    $migration->addField("glpi_softwarecategories", 'sons_cache', "longtext");
    $migration->migrationOneTable('glpi_softwarecategories');
    $migration->addKey('glpi_softwarecategories', 'softwarecategories_id');
    regenerateTreeCompleteName("glpi_softwarecategories");
    $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'various'));
    // glpi_cartridgeitems  glpi_consumableitems by entity
    $migration->addField('glpi_consumableitems', 'is_recursive', 'bool', array('update' => '1', 'after' => 'entities_id'));
    $migration->addField('glpi_cartridgeitems', 'is_recursive', 'bool', array('update' => '1', 'after' => 'entities_id'));
    // Fix events
    $query = "UPDATE `glpi_events`\n             SET `type` = 'consumableitems'\n             WHERE `type` = 'consumables'";
    $DB->queryOrDie($query, "0.85 fix events for consumables");
    $query = "UPDATE `glpi_events`\n             SET `type` = 'cartridgeitems'\n             WHERE `type` = 'cartridges';";
    $DB->queryOrDie($query, "0.85 fix events for cartridges");
    // Bookmark order :
    $migration->addField('glpi_users', 'privatebookmarkorder', 'longtext');
    // Pref to comme back ticket created
    if ($migration->addField('glpi_users', 'backcreated', 'TINYINT(1) DEFAULT NULL')) {
        $query = "INSERT INTO `glpi_configs`\n                       (`context`, `name`, `value`)\n                VALUES ('core', 'backcreated', 0)";
        $DB->queryOrDie($query, "update glpi_configs with backcreated");
    }
    $migration->displayMessage(sprintf(__('Data migration - %s'), 'glpi_projects'));
    if (!TableExists("glpi_projects")) {
        $query = "CREATE TABLE IF NOT EXISTS `glpi_projects` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `name` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n                  `code` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n                  `priority` int(11) NOT NULL DEFAULT '1',\n                  `entities_id` int(11) NOT NULL DEFAULT '0',\n                  `is_recursive` tinyint(1) NOT NULL DEFAULT '0',\n                  `projects_id` int(11) NOT NULL DEFAULT '0',\n                  `projectstates_id` int(11) NOT NULL DEFAULT '0',\n                  `projecttypes_id` int(11) NOT NULL DEFAULT '0',\n                  `date` datetime DEFAULT NULL,\n                  `date_mod` datetime DEFAULT NULL,\n                  `users_id` int(11) NOT NULL DEFAULT '0',\n                  `groups_id` int(11) NOT NULL DEFAULT '0',\n                  `plan_start_date` datetime DEFAULT NULL,\n                  `plan_end_date` datetime DEFAULT NULL,\n                  `real_start_date` datetime DEFAULT NULL,\n                  `real_end_date` datetime DEFAULT NULL,\n                  `percent_done` int(11) NOT NULL DEFAULT '0',\n                  `show_on_global_gantt` tinyint(1) NOT NULL DEFAULT '0',\n                  `content` longtext DEFAULT NULL,\n                  `comment` longtext DEFAULT NULL,\n                  `notepad` longtext DEFAULT NULL,\n                  PRIMARY KEY (`id`),\n                  KEY `name` (`name`),\n                  KEY `code` (`code`),\n                  KEY `entities_id` (`entities_id`),\n                  KEY `is_recursive` (`is_recursive`),\n                  KEY `projects_id` (`projects_id`),\n                  KEY `projectstates_id` (`projectstates_id`),\n                  KEY `projecttypes_id` (`projecttypes_id`),\n                  KEY `priority` (`priority`),\n                  KEY `date` (`date`),\n                  KEY `date_mod` (`date_mod`),\n                  KEY `users_id` (`users_id`),\n                  KEY `groups_id` (`groups_id`),\n                  KEY `plan_start_date` (`plan_start_date`),\n                  KEY `plan_end_date` (`plan_end_date`),\n                  KEY `real_start_date` (`real_start_date`),\n                  KEY `real_end_date` (`real_end_date`),\n                  KEY `percent_done` (`percent_done`),\n                  KEY `show_on_global_gantt` (`show_on_global_gantt`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;";
        $DB->queryOrDie($query, "0.85 add table glpi_projects");
        $ADDTODISPLAYPREF['Project'] = array(3, 4, 12, 5, 15, 21);
    }
    $migration->addField("glpi_projects", 'is_deleted', "bool");
    if (countElementsInTable("glpi_profilerights", "`name` = 'project'") == 0) {
        ProfileRight::addProfileRights(array('project'));
        ProfileRight::updateProfileRightAsOtherRight('project', Project::READMY, "`name` = 'change'\n                                                     AND `rights` & " . Change::READMY);
        ProfileRight::updateProfileRightAsOtherRight('project', Project::READALL, "`name` = 'change'\n                                                     AND `rights` & " . Change::READALL);
        ProfileRight::updateProfileRightAsOtherRight('project', CREATE . " | " . UPDATE . " | " . DELETE . " | " . PURGE . " | " . READNOTE . " | " . UPDATENOTE, "`name` = 'change'\n                                                      AND `rights` & (" . CREATE . " | " . UPDATE . " | " . DELETE . " | " . PURGE . ')');
    }
    if (countElementsInTable("glpi_profilerights", "`name` = 'projecttask'") == 0) {
        ProfileRight::addProfileRights(array('projecttask'));
        ProfileRight::updateProfileRightAsOtherRight('projecttask', ProjectTask::READMY, "`name` = 'change'\n                                                     AND `rights` & " . Change::READMY);
        ProfileRight::updateProfileRightAsOtherRight('projecttask', ProjectTask::UPDATEMY, "`name` = 'change'\n                                                     AND `rights` & " . Change::READMY);
    }
    if (!TableExists('glpi_projectcosts')) {
        $query = "CREATE TABLE `glpi_projectcosts` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `projects_id` int(11) NOT NULL DEFAULT '0',\n                  `name` varchar(255) DEFAULT NULL,\n                  `comment` text COLLATE utf8_unicode_ci,\n                  `begin_date` date DEFAULT NULL,\n                  `end_date` date DEFAULT NULL,\n                  `cost` decimal(20,4) NOT NULL DEFAULT '0.0000',\n                  `budgets_id` int(11) NOT NULL DEFAULT '0',\n                  `entities_id` int(11) NOT NULL DEFAULT '0',\n                  `is_recursive` tinyint(1) NOT NULL DEFAULT '0',\n                  PRIMARY KEY (`id`),\n                  KEY `name` (`name`),\n                  KEY `projects_id` (`projects_id`),\n                  KEY `begin_date` (`begin_date`),\n                  KEY `end_date` (`end_date`),\n                  KEY `entities_id` (`entities_id`),\n                  KEY `is_recursive` (`is_recursive`),\n                  KEY `budgets_id` (`budgets_id`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.85 add table glpi_projectcosts");
    }
    if (!TableExists('glpi_projectstates')) {
        $query = "CREATE TABLE `glpi_projectstates` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `name` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n                  `comment` text COLLATE utf8_unicode_ci,\n                  `color` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n                  `is_finished` tinyint(1) NOT NULL DEFAULT '0',\n                  PRIMARY KEY (`id`),\n                  KEY `name` (`name`),\n                  KEY `is_finished` (`is_finished`)\n                ) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.85 create glpi_projectstates");
        $ADDTODISPLAYPREF['ProjectState'] = array(12, 11);
        $states = array('new' => array('name' => _x('ticket', 'New'), 'color' => '#06ff00', 'is_finished' => 0), 'do' => array('name' => __('Processing'), 'color' => '#ffb800', 'is_finished' => 0), 'end' => array('name' => __('Closed'), 'color' => '#ff0000', 'is_finished' => 1));
        foreach ($states as $key => $val) {
            $query = "INSERT INTO `glpi_projectstates`\n                          (`name`,`color`,`is_finished`)\n                   VALUES ('" . addslashes($val['name']) . "','" . addslashes($val['color']) . "',\n                           '" . addslashes($val['is_finished']) . "')";
            $DB->queryOrDie($query, "0.85 insert default project state {$key}");
        }
    }
    if (!TableExists('glpi_projecttypes')) {
        $query = "CREATE TABLE `glpi_projecttypes` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `name` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n                  `comment` text COLLATE utf8_unicode_ci,\n                  PRIMARY KEY (`id`),\n                  KEY `name` (`name`)\n                ) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.85 create glpi_projecttypes");
    }
    $migration->addField("glpi_groups", 'is_manager', "bool", array('update' => "`is_assign`", 'value' => 1));
    $migration->addKey('glpi_groups', 'is_manager');
    if (!TableExists('glpi_changes_projects')) {
        $query = "CREATE TABLE `glpi_changes_projects` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `changes_id` int(11) NOT NULL DEFAULT '0',\n                  `projects_id` int(11) NOT NULL DEFAULT '0',\n                  PRIMARY KEY (`id`),\n                  UNIQUE KEY `unicity` (`changes_id`,`projects_id`),\n                  KEY `projects_id` (`projects_id`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.85 add table glpi_changes_projects");
    }
    if (!TableExists('glpi_projectteams')) {
        $query = "CREATE TABLE `glpi_projectteams` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `projects_id` int(11) NOT NULL DEFAULT '0',\n                  `itemtype` varchar(100) default NULL,\n                  `items_id` int(11) NOT NULL DEFAULT '0',\n                  PRIMARY KEY (`id`),\n                  UNIQUE KEY `unicity` (`projects_id`,`itemtype`,`items_id`),\n                  KEY `item` (`itemtype`,`items_id`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.85 add table glpi_projectteams");
    }
    if (!TableExists('glpi_items_projects')) {
        $query = "CREATE TABLE `glpi_items_projects` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `projects_id` int(11) NOT NULL DEFAULT '0',\n                  `itemtype` varchar(100) default NULL,\n                  `items_id` int(11) NOT NULL DEFAULT '0',\n                  PRIMARY KEY (`id`),\n                  UNIQUE KEY `unicity` (`projects_id`,`itemtype`,`items_id`),\n                  KEY `item` (`itemtype`,`items_id`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.85 add table glpi_items_projects");
    }
    if (!TableExists("glpi_projecttasks")) {
        $query = "CREATE TABLE IF NOT EXISTS `glpi_projecttasks` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `name` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n                  `content` longtext DEFAULT NULL,\n                  `comment` longtext DEFAULT NULL,\n                  `entities_id` int(11) NOT NULL DEFAULT '0',\n                  `is_recursive` tinyint(1) NOT NULL DEFAULT '0',\n                  `projects_id` int(11) NOT NULL DEFAULT '0',\n                  `projecttasks_id` int(11) NOT NULL DEFAULT '0',\n                  `date` datetime DEFAULT NULL,\n                  `date_mod` datetime DEFAULT NULL,\n                  `plan_start_date` datetime DEFAULT NULL,\n                  `plan_end_date` datetime DEFAULT NULL,\n                  `real_start_date` datetime DEFAULT NULL,\n                  `real_end_date` datetime DEFAULT NULL,\n                  `planned_duration` int(11) NOT NULL DEFAULT '0',\n                  `effective_duration` int(11) NOT NULL DEFAULT '0',\n                  `projectstates_id` int(11) NOT NULL DEFAULT '0',\n                  `projecttasktypes_id` int(11) NOT NULL DEFAULT '0',\n                  `users_id` int(11) NOT NULL DEFAULT '0',\n                  `percent_done` int(11) NOT NULL DEFAULT '0',\n                  `notepad` longtext DEFAULT NULL,\n                  PRIMARY KEY (`id`),\n                  KEY `name` (`name`),\n                  KEY `entities_id` (`entities_id`),\n                  KEY `is_recursive` (`is_recursive`),\n                  KEY `projects_id` (`projects_id`),\n                  KEY `projecttasks_id` (`projecttasks_id`),\n                  KEY `date` (`date`),\n                  KEY `date_mod` (`date_mod`),\n                  KEY `users_id` (`users_id`),\n                  KEY `plan_start_date` (`plan_start_date`),\n                  KEY `plan_end_date` (`plan_end_date`),\n                  KEY `real_start_date` (`real_start_date`),\n                  KEY `real_end_date` (`real_end_date`),\n                  KEY `percent_done` (`percent_done`),\n                  KEY `projectstates_id` (`projectstates_id`),\n                  KEY `projecttasktypes_id` (`projecttasktypes_id`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;";
        $DB->queryOrDie($query, "0.85 add table glpi_projecttasks");
        $ADDTODISPLAYPREF['ProjectTask'] = array(2, 12, 14, 5, 7, 8, 13);
    }
    if (!TableExists('glpi_projecttasktypes')) {
        $query = "CREATE TABLE `glpi_projecttasktypes` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `name` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n                  `comment` text COLLATE utf8_unicode_ci,\n                  PRIMARY KEY (`id`),\n                  KEY `name` (`name`)\n                ) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.85 create glpi_projecttasktypes");
    }
    if (!TableExists('glpi_projecttaskteams')) {
        $query = "CREATE TABLE `glpi_projecttaskteams` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `projecttasks_id` int(11) NOT NULL DEFAULT '0',\n                  `itemtype` varchar(100) default NULL,\n                  `items_id` int(11) NOT NULL DEFAULT '0',\n                  PRIMARY KEY (`id`),\n                  UNIQUE KEY `unicity` (`projecttasks_id`,`itemtype`,`items_id`),\n                  KEY `item` (`itemtype`,`items_id`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.85 add table glpi_projecttaskteams");
    }
    if (!TableExists('glpi_projecttasks_tickets')) {
        $query = "CREATE TABLE `glpi_projecttasks_tickets` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `tickets_id` int(11) NOT NULL DEFAULT '0',\n                  `projecttasks_id` int(11) NOT NULL DEFAULT '0',\n                  PRIMARY KEY (`id`),\n                  UNIQUE KEY `unicity` (`tickets_id`,`projecttasks_id`),\n                  KEY `projects_id` (`projecttasks_id`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.85 add table glpi_projecttasks_tickets");
    }
    // Project notifications
    $query = "SELECT *\n             FROM `glpi_notificationtemplates`\n             WHERE `itemtype` = 'Project'";
    if ($result = $DB->query($query)) {
        if ($DB->numrows($result) == 0) {
            $query = "INSERT INTO `glpi_notificationtemplates`\n                          (`name`, `itemtype`, `date_mod`)\n                   VALUES ('Projects', 'Project', NOW())";
            $DB->queryOrDie($query, "0.85 add project notification");
            $notid = $DB->insert_id();
            $query = "INSERT INTO `glpi_notificationtemplatetranslations`\n                          (`notificationtemplates_id`, `language`, `subject`,\n                           `content_text`,\n                           `content_html`)\n                   VALUES ({$notid}, '', '##project.action## ##project.name## ##project.code##',\n                          '##lang.project.url## : ##project.url##\n\n##lang.project.description##\n\n##lang.project.name## : ##project.name##\n##lang.project.code## : ##project.code##\n##lang.project.manager## : ##project.manager##\n##lang.project.managergroup## : ##project.managergroup##\n##lang.project.creationdate## : ##project.creationdate##\n##lang.project.priority## : ##project.priority##\n##lang.project.state## : ##project.state##\n##lang.project.type## : ##project.type##\n##lang.project.description## : ##project.description##\n\n##lang.project.numberoftasks## : ##project.numberoftasks##\n\n\n\n##FOREACHtasks##\n\n[##task.creationdate##]\n##lang.task.name## : ##task.name##\n##lang.task.state## : ##task.state##\n##lang.task.type## : ##task.type##\n##lang.task.percent## : ##task.percent##\n##lang.task.description## : ##task.description##\n\n##ENDFOREACHtasks##',\n                          '&lt;p&gt;##lang.project.url## : &lt;a href=\"##project.url##\"&gt;##project.url##&lt;/a&gt;&lt;/p&gt;\n&lt;p&gt;&lt;strong&gt;##lang.project.description##&lt;/strong&gt;&lt;/p&gt;\n&lt;p&gt;##lang.project.name## : ##project.name##&lt;br /&gt;##lang.project.code## : ##project.code##&lt;br /&gt; ##lang.project.manager## : ##project.manager##&lt;br /&gt;##lang.project.managergroup## : ##project.managergroup##&lt;br /&gt; ##lang.project.creationdate## : ##project.creationdate##&lt;br /&gt;##lang.project.priority## : ##project.priority## &lt;br /&gt;##lang.project.state## : ##project.state##&lt;br /&gt;##lang.project.type## : ##project.type##&lt;br /&gt;##lang.project.description## : ##project.description##&lt;/p&gt;\n&lt;p&gt;##lang.project.numberoftasks## : ##project.numberoftasks##&lt;/p&gt;\n&lt;div&gt;\n&lt;p&gt;##FOREACHtasks##&lt;/p&gt;\n&lt;div&gt;&lt;strong&gt;[##task.creationdate##] &lt;/strong&gt;&lt;br /&gt; ##lang.task.name## : ##task.name##&lt;br /&gt;##lang.task.state## : ##task.state##&lt;br /&gt;##lang.task.type## : ##task.type##&lt;br /&gt;##lang.task.percent## : ##task.percent##&lt;br /&gt;##lang.task.description## : ##task.description##&lt;/div&gt;\n&lt;p&gt;##ENDFOREACHtasks##&lt;/p&gt;\n&lt;/div&gt;')";
            $DB->queryOrDie($query, "0.85 add project notification translation");
            $notifications = array('new' => array(), 'update' => array(), 'delete' => array());
            $notif_names = array('new' => 'New Project', 'update' => 'Update Project', 'delete' => 'Delete Project');
            foreach ($notifications as $key => $val) {
                $notifications[$key][] = Notification::MANAGER_USER;
                $notifications[$key][] = Notification::GLOBAL_ADMINISTRATOR;
                $notifications[$key][] = Notification::MANAGER_GROUP;
            }
            foreach ($notifications as $type => $targets) {
                $query = "INSERT INTO `glpi_notifications`\n                             (`name`, `entities_id`, `itemtype`, `event`, `mode`,\n                              `notificationtemplates_id`, `comment`, `is_recursive`, `is_active`,\n                              `date_mod`)\n                      VALUES ('" . $notif_names[$type] . "', 0, 'Project', '{$type}', 'mail',\n                              {$notid}, '', 1, 1, NOW())";
                $DB->queryOrDie($query, "0.85 add project {$type} notification");
                $notifid = $DB->insert_id();
                foreach ($targets as $target) {
                    $query = "INSERT INTO `glpi_notificationtargets`\n                                (`id`, `notifications_id`, `type`, `items_id`)\n                         VALUES (NULL, {$notifid}, " . Notification::USER_TYPE . ", {$target});";
                    $DB->queryOrDie($query, "0.85 add project {$type} notification target");
                }
            }
        }
    }
    // Project Task notifications
    $query = "SELECT *\n             FROM `glpi_notificationtemplates`\n             WHERE `itemtype` = 'ProjectTask'";
    if ($result = $DB->query($query)) {
        if ($DB->numrows($result) == 0) {
            $query = "INSERT INTO `glpi_notificationtemplates`\n                          (`name`, `itemtype`, `date_mod`)\n                   VALUES ('Project Tasks', 'ProjectTask', NOW())";
            $DB->queryOrDie($query, "0.85 add project task notification");
            $notid = $DB->insert_id();
            $query = "INSERT INTO `glpi_notificationtemplatetranslations`\n                          (`notificationtemplates_id`, `language`, `subject`,\n                           `content_text`,\n                           `content_html`)\n                   VALUES ({$notid}, '', '##projecttask.action## ##projecttask.name##',\n                          '##lang.projecttask.url## : ##projecttask.url##\n\n##lang.projecttask.description##\n\n##lang.projecttask.name## : ##projecttask.name##\n##lang.projecttask.project## : ##projecttask.name##\n##lang.projecttask.creationdate## : ##projecttask.creationdate##\n##lang.projecttask.state## : ##projecttask.state##\n##lang.projecttask.type## : ##projecttask.type##\n##lang.projecttask.description## : ##projecttask.description##\n\n##lang.projecttask.numberoftasks## : ##projecttask.numberoftasks##\n\n\n\n##FOREACHtasks##\n\n[##task.creationdate##]\n##lang.task.name## : ##task.name##\n##lang.task.state## : ##task.state##\n##lang.task.type## : ##task.type##\n##lang.task.percent## : ##task.percent##\n##lang.task.description## : ##task.description##\n\n##ENDFOREACHtasks##',\n                          '&lt;p&gt;##lang.projecttask.url## : &lt;a href=\"##projecttask.url##\"&gt;##projecttask.url##&lt;/a&gt;&lt;/p&gt;\n&lt;p&gt;&lt;strong&gt;##lang.projecttask.description##&lt;/strong&gt;&lt;/p&gt;\n&lt;p&gt;##lang.projecttask.name## : ##projecttask.name##&lt;br /&gt;##lang.projecttask.project## : &lt;a href=\"##projecttask.projecturl##\"&gt;##projecttask.name##&lt;/a&gt;&lt;br /&gt;##lang.projecttask.creationdate## : ##projecttask.creationdate##&lt;br /&gt;##lang.projecttask.state## : ##projecttask.state##&lt;br /&gt;##lang.projecttask.type## : ##projecttask.type##&lt;br /&gt;##lang.projecttask.description## : ##projecttask.description##&lt;/p&gt\n&lt;p&gt;##lang.projecttask.numberoftasks## : ##projecttask.numberoftasks##&lt;/p&gt;\n&lt;div&gt;\n&lt;p&gt;##FOREACHtasks##&lt;/p&gt;\n&lt;div&gt;&lt;strong&gt;[##task.creationdate##] &lt;/strong&gt;&lt;br /&gt;##lang.task.name## : ##task.name##&lt;br /&gt;##lang.task.state## : ##task.state##&lt;br /&gt;##lang.task.type## : ##task.type##&lt;br /&gt;##lang.task.percent## : ##task.percent##&lt;br /&gt;##lang.task.description## : ##task.description##&lt;/div&gt;\n&lt;p&gt;##ENDFOREACHtasks##&lt;/p&gt;\n&lt;/div&gt;')";
            $DB->queryOrDie($query, "0.85 add project task notification translation");
            $notifications = array('new' => array(), 'update' => array(), 'delete' => array());
            $notif_names = array('new' => 'New Project Task', 'update' => 'Update Project Task', 'delete' => 'Delete Project Task');
            foreach ($notifications as $key => $val) {
                $notifications[$key][] = Notification::TEAM_USER;
                $notifications[$key][] = Notification::GLOBAL_ADMINISTRATOR;
                $notifications[$key][] = Notification::TEAM_GROUP;
            }
            foreach ($notifications as $type => $targets) {
                $query = "INSERT INTO `glpi_notifications`\n                             (`name`, `entities_id`, `itemtype`, `event`, `mode`,\n                              `notificationtemplates_id`, `comment`, `is_recursive`, `is_active`,\n                              `date_mod`)\n                      VALUES ('" . $notif_names[$type] . "', 0, 'ProjectTask', '{$type}', 'mail',\n                              {$notid}, '', 1, 1, NOW())";
                $DB->queryOrDie($query, "0.85 add project task  {$type} notification");
                $notifid = $DB->insert_id();
                foreach ($targets as $target) {
                    $query = "INSERT INTO `glpi_notificationtargets`\n                                (`id`, `notifications_id`, `type`, `items_id`)\n                         VALUES (NULL, {$notifid}, " . Notification::USER_TYPE . ", {$target});";
                    $DB->queryOrDie($query, "0.85 add project task {$type} notification target");
                }
            }
        }
    }
    $migration->displayMessage(sprintf(__('Data migration - %s'), 'notepad'));
    // Create new notepad table
    if (!TableExists('glpi_notepads')) {
        $query = "CREATE TABLE `glpi_notepads` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `itemtype` varchar(100) default NULL,\n                  `items_id` int(11) NOT NULL DEFAULT '0',\n                  `date` datetime DEFAULT NULL,\n                  `date_mod` datetime DEFAULT NULL,\n                  `users_id` int(11) NOT NULL DEFAULT '0',\n                  `users_id_lastupdater` int(11) NOT NULL DEFAULT '0',\n                  `content` LONGTEXT DEFAULT NULL,\n                  PRIMARY KEY (`id`),\n                  KEY `item` (`itemtype`,`items_id`),\n                  KEY `date_mod` (`date_mod`),\n                  KEY `date` (`date`),\n                  KEY `users_id_lastupdater` (`users_id_lastupdater`),\n                  KEY `users_id` (`users_id`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.85 add table glpi_notepads");
        $notepad_tables = array('glpi_budgets', 'glpi_cartridgeitems', 'glpi_changes', 'glpi_computers', 'glpi_consumableitems', 'glpi_contacts', 'glpi_contracts', 'glpi_documents', 'glpi_entities', 'glpi_monitors', 'glpi_networkequipments', 'glpi_peripherals', 'glpi_phones', 'glpi_printers', 'glpi_problems', 'glpi_projects', 'glpi_projecttasks', 'glpi_softwares', 'glpi_suppliers');
        foreach ($notepad_tables as $t) {
            // Migrate data
            if (FieldExists($t, 'notepad')) {
                $query = "SELECT id, notepad\n                      FROM `{$t}`\n                      WHERE notepad IS NOT NULL\n                            AND notepad <>'';";
                foreach ($DB->request($query) as $data) {
                    $iq = "INSERT INTO `glpi_notepads`\n                             (`itemtype`, `items_id`, `content`, `date`, `date_mod`)\n                      VALUES ('" . getItemTypeForTable($t) . "', '" . $data['id'] . "',\n                              '" . addslashes($data['notepad']) . "', NOW(), NOW())";
                    $DB->queryOrDie($iq, "0.85 migrate notepad data");
                }
                $migration->dropField($t, 'notepad');
            }
        }
    }
    $migration->addField('glpi_deviceprocessors', 'nbcores_default', 'int');
    $migration->addField('glpi_deviceprocessors', 'nbthreads_default', 'int');
    $migration->addField('glpi_items_deviceprocessors', 'nbcores', 'int');
    $migration->addField('glpi_items_deviceprocessors', 'nbthreads', 'int');
    $migration->addKey('glpi_items_deviceprocessors', 'nbcores');
    $migration->addKey('glpi_items_deviceprocessors', 'nbthreads');
    $migration->displayMessage(sprintf(__('Data migration - %s'), 'ticketvalidations status'));
    $status = array('none' => CommonITILValidation::NONE, 'waiting' => CommonITILValidation::WAITING, 'accepted' => CommonITILValidation::ACCEPTED, 'rejected' => CommonITILValidation::REFUSED);
    // Migrate datas
    foreach ($status as $old => $new) {
        $query = "UPDATE `glpi_ticketvalidations`\n                SET `status` = '{$new}'\n                WHERE `status` = '{$old}'";
        $DB->queryOrDie($query, "0.85 status in glpi_ticketvalidations {$old} to {$new}");
    }
    $migration->changeField('glpi_ticketvalidations', 'status', 'status', 'integer', array('value' => CommonITILValidation::WAITING));
    $migration->displayMessage(sprintf(__('Data migration - %s'), 'tickets and changes global_validation'));
    $tables = array('glpi_tickets', 'glpi_changes');
    foreach ($tables as $table) {
        foreach ($status as $old => $new) {
            $query = "UPDATE `" . $table . "`\n                   SET `global_validation` = '{$new}'\n                   WHERE `global_validation` = '{$old}'";
            $DB->queryOrDie($query, "0.85 global_validation in {$table} {$old} to {$new}");
        }
        $migration->changeField($table, 'global_validation', 'global_validation', 'integer', array('value' => CommonITILValidation::NONE));
    }
    $migration->displayMessage(sprintf(__('Data migration - %s'), 'tickettemplatepredefinedfields value'));
    foreach ($status as $old => $new) {
        $query = "UPDATE `glpi_tickettemplatepredefinedfields`\n                SET `value` = '{$new}'\n                WHERE `num` = '52'\n                      AND `value` = '{$old}'";
        $DB->queryOrDie($query, "0.85 value in glpi_tickettemplatepredefinedfields {$old} to {$new}");
    }
    // Migrate templates
    $query = "SELECT `glpi_notificationtemplatetranslations`.*\n             FROM `glpi_notificationtemplatetranslations`\n             INNER JOIN `glpi_notificationtemplates`\n                  ON (`glpi_notificationtemplates`.`id`\n                        = `glpi_notificationtemplatetranslations`.`notificationtemplates_id`)\n             WHERE `glpi_notificationtemplatetranslations`.`content_text` LIKE '%validation.storestatus=%'\n                   OR `glpi_notificationtemplatetranslations`.`content_html` LIKE '%validation.storestatus=%'\n                   OR `glpi_notificationtemplatetranslations`.`subject` LIKE '%validation.storestatus=%'";
    if ($result = $DB->query($query)) {
        if ($DB->numrows($result)) {
            while ($data = $DB->fetch_assoc($result)) {
                $subject = $data['subject'];
                $text = $data['content_text'];
                $html = $data['content_html'];
                foreach ($status as $old => $new) {
                    $subject = str_replace("validation.storestatus={$old}", "validation.storestatus={$new}", $subject);
                    $text = str_replace("validation.storestatus={$old}", "validation.storestatus={$new}", $text);
                    $html = str_replace("validation.storestatus={$old}", "validation.storestatus={$new}", $html);
                }
                $query = "UPDATE `glpi_notificationtemplatetranslations`\n                      SET `subject` = '" . addslashes($subject) . "',\n                         `content_text` = '" . addslashes($text) . "',\n                         `content_html` = '" . addslashes($html) . "'\n                      WHERE `id` = " . $data['id'] . "";
                $DB->queryOrDie($query, "0.85 fix tags usage for storestatus");
            }
        }
    }
    // Upgrade ticket bookmarks
    $query = "SELECT *\n             FROM `glpi_bookmarks`";
    if ($result = $DB->query($query)) {
        if ($DB->numrows($result) > 0) {
            while ($data = $DB->fetch_assoc($result)) {
                $num = 0;
                $num2 = 0;
                $options = array();
                parse_str($data["query"], $options);
                if (isset($options['field'])) {
                    // update ticket statuses
                    if (($data['itemtype'] = 'Ticket') && $data['type'] == Bookmark::SEARCH) {
                        foreach ($options['field'] as $key => $val) {
                            if (($val == 55 || $val == 52) && isset($options['contains'][$key])) {
                                if (isset($status[$options['contains'][$key]])) {
                                    $options['contains'][$key] = $status[$options['contains'][$key]];
                                }
                            }
                        }
                    }
                }
                $query2 = "UPDATE `glpi_bookmarks`\n                       SET `query` = '" . addslashes(Toolbox::append_params($options)) . "'\n                       WHERE `id` = '" . $data['id'] . "'";
                $DB->queryOrDie($query2, "0.85 update bookmarks");
            }
        }
    }
    //////////////////////////////////////////////////
    // Device update
    $migration->displayMessage(sprintf(__('Data migration - %s'), 'Devices'));
    foreach (array_merge(CommonDevice::getDeviceTypes(), Item_Devices::getDeviceTypes()) as $itemtype) {
        $table = $itemtype::getTable();
        if (!FieldExists($table, 'entities_id')) {
            $migration->addField($table, 'entities_id', 'integer');
            $migration->addKey($table, array('entities_id'), 'entities_id');
        }
        if (!FieldExists($table, 'is_recursive')) {
            $migration->addField($table, 'is_recursive', 'bool', array('update' => '1', 'after' => 'entities_id'));
            $migration->addKey($table, array('is_recursive'), 'is_recursive');
        }
    }
    // Adding the Registered ID class that contains PCI IDs and USB IDs for vendors
    // as well devices
    if (!TableExists('glpi_registeredids')) {
        $query = "CREATE TABLE `glpi_registeredids` (\n                 `id` int(11) NOT NULL AUTO_INCREMENT,\n                 `name` varchar(255) DEFAULT NULL,\n                 `items_id` int(11) NOT NULL DEFAULT '0',\n                 `itemtype` varchar(100) COLLATE utf8_unicode_ci NOT NULL,\n                 `device_type` varchar(100) COLLATE utf8_unicode_ci NOT NULL COMMENT 'USB, PCI ...',\n                 PRIMARY KEY (`id`),\n                 KEY `name` (`name`),\n                 KEY `item` (`items_id`, `itemtype`),\n                 KEY `device_type` (`device_type`)\n               ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.85 add table glpi_registeredids");
    }
    // Complete the item_devices
    foreach (array('glpi_items_devicecases', 'glpi_items_devicecontrols', 'glpi_items_devicedrives', 'glpi_items_devicegraphiccards', 'glpi_items_devicemotherboards', 'glpi_items_devicenetworkcards', 'glpi_items_devicepcis', 'glpi_items_devicepowersupplies', 'glpi_items_devicesoundcards') as $table) {
        if (!FieldExists($table, 'serial')) {
            $migration->addField($table, 'serial', 'string');
            $migration->addKey($table, 'serial');
        }
    }
    foreach (array('glpi_items_devicecontrols', 'glpi_items_devicedrives', 'glpi_items_devicegraphiccards', 'glpi_items_deviceharddrives', 'glpi_items_devicememories', 'glpi_items_devicenetworkcards', 'glpi_items_devicepcis', 'glpi_items_deviceprocessors', 'glpi_items_devicesoundcards') as $table) {
        if (!FieldExists($table, 'busID')) {
            $migration->addField($table, 'busID', 'string');
            $migration->addKey($table, 'busID');
        }
    }
    // Add key
    foreach (array('glpi_items_devicecases', 'glpi_items_devicecontrols', 'glpi_items_devicedrives', 'glpi_items_devicegraphiccards', 'glpi_items_deviceharddrives', 'glpi_items_devicememories', 'glpi_items_devicemotherboards', 'glpi_items_devicenetworkcards', 'glpi_items_devicepcis', 'glpi_items_devicepowersupplies', 'glpi_items_deviceprocessors', 'glpi_items_devicesoundcards') as $table) {
        $migration->dropKey($table, 'item');
        $migration->migrationOneTable($table);
        $migration->addKey($table, array('itemtype', 'items_id'), 'item');
    }
    if (!FieldExists('glpi_devicegraphiccards', 'chipset')) {
        $migration->addField('glpi_devicegraphiccards', 'chipset', 'string');
        $migration->addKey('glpi_devicegraphiccards', 'chipset');
    }
    $migration->addField("glpi_suppliers_tickets", "use_notification", "bool");
    $migration->addField("glpi_suppliers_tickets", "alternative_email", "string");
    $migration->addField("glpi_problems_suppliers", "use_notification", "bool");
    $migration->addField("glpi_problems_suppliers", "alternative_email", "string");
    $migration->addField("glpi_changes_suppliers", "use_notification", "bool");
    $migration->addField("glpi_changes_suppliers", "alternative_email", "string");
    // Add field for locations
    $migration->addField("glpi_locations", "latitude", "string");
    $migration->addField("glpi_locations", "longitude", "string");
    $migration->addField("glpi_locations", "altitude", "string");
    // Add fixed columns as variables :
    $ADDTODISPLAYPREF['CartridgeItem'] = array(9);
    $ADDTODISPLAYPREF['ConsumableItem'] = array(9);
    $ADDTODISPLAYPREF['ReservationItem'] = array(9);
    $migration->displayMessage(sprintf(__('Data migration - %s'), 'License validity'));
    // for licence validity
    if ($migration->addField("glpi_softwarelicenses", "is_valid", "bool", array("value" => 1))) {
        $migration->migrationOneTable("glpi_softwarelicenses");
        // Force all entities
        if (!isset($_SESSION['glpishowallentities'])) {
            $_SESSION['glpishowallentities'] = 0;
        }
        $savesession = $_SESSION['glpishowallentities'];
        $_SESSION['glpishowallentities'] = 1;
        $queryl = "SELECT `id`, `number`\n                 FROM `glpi_softwarelicenses`";
        foreach ($DB->request($queryl) as $datal) {
            if ($datal['number'] >= 0 && $datal['number'] < Computer_SoftwareLicense::countForLicense($datal['id'], -1)) {
                $queryl2 = "UPDATE `glpi_softwarelicenses`\n                        SET `is_valid` = 0\n                        WHERE `id` = '" . $datal['id'] . "'";
                $DB->queryOrDie($queryl2, "0.85 update softwarelicense");
            }
        }
        $_SESSION['glpishowallentities'] = $savesession;
    }
    if ($migration->addField("glpi_softwares", "is_valid", "bool", array("value" => 1))) {
        $migration->migrationOneTable("glpi_softwares");
        $querys = "SELECT `glpi_softwares`.`id`\n                 FROM `glpi_softwares`\n                 LEFT JOIN `glpi_softwarelicenses`\n                     ON (`glpi_softwarelicenses`.`softwares_id` = `glpi_softwares`.`id`)\n                 WHERE `glpi_softwarelicenses`.`is_valid` = 0";
        foreach ($DB->request($querys) as $datas) {
            $querys2 = "UPDATE `glpi_softwares`\n                     SET `is_valid` = 0\n                     WHERE `id` = '" . $datas['id'] . "'";
            $DB->queryOrDie($querys2, "0.85 update software");
        }
    }
    // Add condition to rules
    $migration->addField('glpi_rules', 'condition', 'integer');
    $migration->addKey('glpi_rules', 'condition');
    $migration->migrationOneTable('glpi_rules');
    // Update condition for RuleTicket : only on add
    $query = "UPDATE `glpi_rules`\n             SET `condition` = 1\n             WHERE `sub_type` = 'RuleTicket'";
    $DB->queryOrDie($query, "0.85 update condition for RuleTicket");
    // Update ticket_status for helpdeks profiles
    $newcycle = array(1 => array(2 => 0, 3 => 0, 4 => 0, 5 => 0, 6 => 0), 2 => array(1 => 0, 3 => 0, 4 => 0, 5 => 0, 6 => 0), 3 => array(1 => 0, 2 => 0, 4 => 0, 5 => 0, 6 => 0), 4 => array(1 => 0, 2 => 0, 3 => 0, 5 => 0, 6 => 0), 5 => array(1 => 0, 2 => 0, 3 => 0, 4 => 0), 6 => array(1 => 0, 2 => 0, 3 => 0, 4 => 0, 5 => 0));
    $query = "UPDATE `glpi_profiles`\n             SET `ticket_status` = '" . exportArrayToDB($newcycle) . "'\n             WHERE `interface` = 'helpdesk'";
    $DB->queryOrDie($query, "0.85 update default life cycle for helpdesk");
    //Add comment field to a virtualmachine
    $migration->addField('glpi_computervirtualmachines', 'comment', 'text');
    $migration->displayMessage(sprintf(__('Data migration - %s'), 'IP improvment'));
    // Ip search improve
    $migration->addField('glpi_ipaddresses', 'mainitems_id', 'integer');
    $migration->addField('glpi_ipaddresses', 'mainitemtype', 'string', array('after' => 'mainitems_id'));
    $migration->migrationOneTable('glpi_ipaddresses');
    $migration->addKey('glpi_ipaddresses', array('mainitemtype', 'mainitems_id', 'is_deleted'), 'mainitem');
    $query_doc_i = "UPDATE `glpi_ipaddresses` as `ip`\n                   INNER JOIN `glpi_networknames` as `netname`\n                     ON  (`ip`.`items_id` = `netname`.`id`\n                            AND `ip`.`itemtype` = 'NetworkName')\n                   INNER JOIN `glpi_networkports` as `netport`\n                     ON  (`netname`.`items_id` = `netport`.`id`\n                            AND `netname`.`itemtype` = 'NetworkPort')\n                   SET `ip`.`mainitemtype` = `netport`.`itemtype`,\n                       `ip`.`mainitems_id` = `netport`.`items_id`";
    $DB->queryOrDie($query_doc_i, "0.85 update mainitems fields of ipaddresses");
    // Upgrade ticket bookmarks
    $query = "SELECT *\n             FROM `glpi_bookmarks`\n             WHERE `type` = '" . Bookmark::SEARCH . "'";
    if ($result = $DB->query($query)) {
        if ($DB->numrows($result) > 0) {
            while ($data = $DB->fetch_assoc($result)) {
                $num = 0;
                $num2 = 0;
                $options = array();
                parse_str($data["query"], $options);
                // Copy itemtype if not set
                if (!isset($options['itemtype'])) {
                    $options['itemtype'] = $data['itemtype'];
                }
                // Move criteria
                if (isset($options['field']) && is_array($options['field'])) {
                    $newkey = 0;
                    foreach ($options['field'] as $key => $val) {
                        $options['criteria'][$newkey]['field'] = $val;
                        //  other field
                        if (isset($options['link'][$key])) {
                            $options['criteria'][$newkey]['link'] = $options['link'][$key];
                        }
                        if (isset($options['searchtype'][$key])) {
                            $options['criteria'][$newkey]['searchtype'] = $options['searchtype'][$key];
                        } else {
                            $options['criteria'][$newkey]['searchtype'] = 'contains';
                        }
                        if (isset($options['contains'][$key])) {
                            $options['criteria'][$newkey]['value'] = $options['contains'][$key];
                        } else {
                            $options['criteria'][$newkey]['value'] = '';
                        }
                        $newkey++;
                    }
                    unset($options['field']);
                    unset($options['contains']);
                    unset($options['searchtype']);
                    unset($options['link']);
                }
                if (isset($options['glpisearchcount'])) {
                    unset($options['glpisearchcount']);
                }
                if (isset($options['field2']) && is_array($options['field2'])) {
                    $newkey = 0;
                    foreach ($options['field2'] as $key => $val) {
                        $options['metacriteria'][$newkey]['field'] = $val;
                        //  other field
                        if (isset($options['itemtype2'][$key])) {
                            $options['metacriteria'][$newkey]['itemtype'] = $options['itemtype2'][$key];
                        }
                        if (isset($options['link2'][$newkey])) {
                            $options['metacriteria'][$newkey]['link'] = $options['link2'][$key];
                        }
                        if (isset($options['searchtype2'][$key])) {
                            $options['metacriteria'][$newkey]['searchtype'] = $options['searchtype2'][$key];
                        } else {
                            $options['metacriteria'][$newkey]['searchtype'] = 'contains';
                        }
                        if (isset($options['contains2'][$key])) {
                            $options['metacriteria'][$newkey]['value'] = $options['contains2'][$key];
                        } else {
                            $options['metacriteria'][$newkey]['value'] = '';
                        }
                        $newkey++;
                    }
                    unset($options['field2']);
                    unset($options['contains2']);
                    unset($options['searchtype2']);
                    unset($options['link2']);
                    unset($options['itemtype2']);
                }
                if (isset($options['glpisearchcount2'])) {
                    unset($options['glpisearchcount2']);
                }
                $query2 = "UPDATE `glpi_bookmarks`\n                       SET `query` = '" . addslashes(Toolbox::append_params($options)) . "'\n                       WHERE `id` = '" . $data['id'] . "'";
                $DB->queryOrDie($query2, "0.85 update bookmarks for reorg search");
            }
        }
    }
    // ************ Keep it at the end **************
    //TRANS: %s is the table or item to migrate
    $migration->displayMessage(sprintf(__('Data migration - %s'), 'glpi_displaypreferences'));
    // Clean display prefs
    // Notepad
    $query = "UPDATE `glpi_displaypreferences`\n             SET `num` = 90\n             WHERE `itemtype` = 'Entity'\n                   AND `num` = 28";
    $DB->query($query);
    $query = "UPDATE `glpi_displaypreferences`\n             SET `num` = 200\n             WHERE `num` = 90";
    $DB->query($query);
    $migration->updateDisplayPrefs($ADDTODISPLAYPREF, $DELFROMDISPLAYPREF);
    // must always be at the end
    $migration->executeMigration();
    return $updateresult;
}
 static function install()
 {
     global $DB;
     if (TableExists('glpi_plugin_reports_profiles')) {
         if (FieldExists('glpi_plugin_reports_profiles', 'ID')) {
             // version installee < 1.4.0
             $query = "ALTER TABLE `glpi_plugin_reports_profiles`\n                      CHANGE `ID` `id` int(11) NOT NULL auto_increment";
             $DB->queryOrDie($query, "CHANGE ID: " . $DB->error());
         }
         if (!FieldExists('glpi_plugin_reports_profiles', 'profiles_id')) {
             // version < 1.5.0
             $query = "RENAME TABLE `glpi_plugin_reports_profiles`\n                                TO `glpi_plugin_reports_oldprofiles`";
             $DB->query($query) or die("SAVE TABLE profiles: " . $DB->error());
             $DB->query($create) or die("CREATE TABLE profiles: " . $DB->error());
             $fields = $DB->list_fields('glpi_plugin_reports_oldprofiles');
             unset($fields['id']);
             unset($fields['profile']);
             foreach ($fields as $field => $descr) {
                 $query = "INSERT INTO `glpi_plugin_reports_profiles`\n                                (`profiles_id`, `report`, `access`)\n                          SELECT `id`, '{$field}', `{$field}`\n                          FROM `glpi_plugin_reports_oldprofiles`\n                          WHERE `{$field}` IS NOT NULL";
                 $DB->query($query) or die("LOAD TABLE profiles: " . $DB->error());
             }
             $query = "DROP TABLE `glpi_plugin_reports_oldprofiles`";
             $DB->query($query) or die("DROP TABLE oldprofiles: " . $DB->error());
         }
         // -- SINCE 0.85 --
         //Add new rights in glpi_profilerights table
         $profileRight = new ProfileRight();
         $query = "SELECT *\n                   FROM `glpi_plugin_reports_profiles`";
         foreach ($DB->request($query) as $data) {
             $right['profiles_id'] = $data['profiles_id'];
             $right['name'] = "plugin_reports_" . $data['report'];
             $droit = $data['access'];
             if ($droit == 'r') {
                 $right['rights'] = 1;
                 $profileRight->add($right);
             }
         }
         $DB->query("DROP TABLE `glpi_plugin_reports_profiles`");
     } else {
         // new install
     }
     return true;
 }
Exemple #10
0
function plugin_badges_uninstall()
{
    global $DB;
    include_once GLPI_ROOT . "/plugins/badges/inc/profile.class.php";
    include_once GLPI_ROOT . "/plugins/badges/inc/menu.class.php";
    $tables = array("glpi_plugin_badges_badges", "glpi_plugin_badges_badgetypes", "glpi_plugin_badges_configs", "glpi_plugin_badges_notificationstates", "glpi_plugin_badges_requests");
    foreach ($tables as $table) {
        $DB->query("DROP TABLE IF EXISTS `{$table}`;");
    }
    //old versions
    $tables = array("glpi_plugin_badges", "glpi_dropdown_plugin_badges_type", "glpi_plugin_badges_users", "glpi_plugin_badges_profiles", "glpi_plugin_badges_config", "glpi_plugin_badges_mailing", "glpi_plugin_badges_default");
    foreach ($tables as $table) {
        $DB->query("DROP TABLE IF EXISTS `{$table}`;");
    }
    $notif = new Notification();
    $options = array('itemtype' => 'PluginBadgesBadge', 'event' => 'ExpiredBadges', 'FIELDS' => 'id');
    foreach ($DB->request('glpi_notifications', $options) as $data) {
        $notif->delete($data);
    }
    $options = array('itemtype' => 'PluginBadgesBadge', 'event' => 'BadgesWhichExpire', 'FIELDS' => 'id');
    foreach ($DB->request('glpi_notifications', $options) as $data) {
        $notif->delete($data);
    }
    $options = array('itemtype' => 'PluginBadgesBadge', 'event' => 'BadgesReturn', 'FIELDS' => 'id');
    foreach ($DB->request('glpi_notifications', $options) as $data) {
        $notif->delete($data);
    }
    $options = array('itemtype' => 'PluginBadgesBadge', 'event' => 'AccessBadgeRequest', 'FIELDS' => 'id');
    foreach ($DB->request('glpi_notifications', $options) as $data) {
        $notif->delete($data);
    }
    //templates
    $template = new NotificationTemplate();
    $translation = new NotificationTemplateTranslation();
    $options = array('itemtype' => 'PluginBadgesBadge', 'FIELDS' => 'id');
    foreach ($DB->request('glpi_notificationtemplates', $options) as $data) {
        $options_template = array('notificationtemplates_id' => $data['id'], 'FIELDS' => 'id');
        foreach ($DB->request('glpi_notificationtemplatetranslations', $options_template) as $data_template) {
            $translation->delete($data_template);
        }
        $template->delete($data);
    }
    $tables_glpi = array("glpi_displaypreferences", "glpi_documents_items", "glpi_bookmarks", "glpi_logs", "glpi_items_tickets", "glpi_notepads", "glpi_dropdowntranslations");
    foreach ($tables_glpi as $table_glpi) {
        $DB->query("DELETE FROM `{$table_glpi}` WHERE `itemtype` LIKE 'PluginBadges%';");
    }
    if (class_exists('PluginDatainjectionModel')) {
        PluginDatainjectionModel::clean(array('itemtype' => 'PluginBadgesBadge'));
    }
    CronTask::Unregister('PluginBadgesReturn');
    //Delete rights associated with the plugin
    $profileRight = new ProfileRight();
    foreach (PluginBadgesProfile::getAllRights() as $right) {
        $profileRight->deleteByCriteria(array('name' => $right['field']));
    }
    PluginBadgesMenu::removeRightsFromSession();
    PluginBadgesProfile::removeRightsFromSession();
    return true;
}
Exemple #11
0
 /**
  * @param $profile
  **/
 static function addDefaultProfileInfos($profiles_id, $rights, $drop_existing = false)
 {
     global $DB;
     $profileRight = new ProfileRight();
     foreach ($rights as $right => $value) {
         if (countElementsInTable('glpi_profilerights', "`profiles_id`='{$profiles_id}' AND `name`='{$right}'") && $drop_existing) {
             $profileRight->deleteByCriteria(array('profiles_id' => $profiles_id, 'name' => $right));
         }
         if (!countElementsInTable('glpi_profilerights', "`profiles_id`='{$profiles_id}' AND `name`='{$right}'")) {
             $myright['profiles_id'] = $profiles_id;
             $myright['name'] = $right;
             $myright['rights'] = $value;
             $profileRight->add($myright);
             //Add right to the current session
             $_SESSION['glpiactiveprofile'][$right] = $value;
         }
     }
 }
function plugin_webapplications_uninstall()
{
    global $DB;
    include_once GLPI_ROOT . "/plugins/webapplications/inc/profile.class.php";
    include_once GLPI_ROOT . "/plugins/webapplications/inc/menu.class.php";
    $tables = array("glpi_plugin_webapplications_webapplications", "glpi_plugin_webapplications_webapplicationtypes", "glpi_plugin_webapplications_webapplicationservertypes", "glpi_plugin_webapplications_webapplicationtechnics", "glpi_plugin_webapplications_webapplications_items");
    foreach ($tables as $table) {
        $DB->query("DROP TABLE IF EXISTS `{$table}`;");
    }
    //old versions
    $tables = array("glpi_plugin_appweb", "glpi_dropdown_plugin_appweb_type", "glpi_dropdown_plugin_appweb_server_type", "glpi_dropdown_plugin_appweb_technic", "glpi_plugin_appweb_device", "glpi_plugin_appweb_profiles", "glpi_plugin_webapplications_profiles");
    foreach ($tables as $table) {
        $DB->query("DROP TABLE IF EXISTS `{$table}`;");
    }
    $tables_glpi = array("glpi_displaypreferences", "glpi_documents_items", "glpi_bookmarks", "glpi_logs", "glpi_notepads");
    foreach ($tables_glpi as $table_glpi) {
        $DB->query("DELETE\n                  FROM `{$table_glpi}`\n                  WHERE `itemtype` = 'PluginWebapplicationsWebapplication'");
    }
    if (class_exists('PluginDatainjectionModel')) {
        PluginDatainjectionModel::clean(array('itemtype' => 'PluginWebapplicationsWebapplication'));
    }
    //Delete rights associated with the plugin
    $profileRight = new ProfileRight();
    foreach (PluginWebapplicationsProfile::getAllRights() as $right) {
        $profileRight->deleteByCriteria(array('name' => $right['field']));
    }
    PluginWebapplicationsMenu::removeRightsFromSession();
    PluginWebapplicationsProfile::removeRightsFromSession();
    return true;
}
Exemple #13
0
/**
 * Update from 0.90.1 to 0.91
 *
 * @return bool for success (will die for most error)
**/
function update0901to091()
{
    global $DB, $migration, $CFG_GLPI;
    $updateresult = true;
    $ADDTODISPLAYPREF = array();
    //TRANS: %s is the number of new version
    $migration->displayTitle(sprintf(__('Update to %s'), '0.91'));
    $migration->setVersion('0.91');
    $backup_tables = false;
    $newtables = array('glpi_objectlocks');
    foreach ($newtables as $new_table) {
        // rename new tables if exists ?
        if (TableExists($new_table)) {
            $migration->dropTable("backup_{$new_table}");
            $migration->displayWarning("{$new_table} table already exists. " . "A backup have been done to backup_{$new_table}.");
            $backup_tables = true;
            $query = $migration->renameTable("{$new_table}", "backup_{$new_table}");
        }
    }
    if ($backup_tables) {
        $migration->displayWarning("You can delete backup tables if you have no need of them.", true);
    }
    $migration->displayMessage(sprintf(__('Add of - %s to database'), 'Object Locks'));
    // create table
    if (!TableExists('glpi_objectlocks')) {
        $query = "CREATE TABLE `glpi_objectlocks` (\n                 `id` INT(11) NOT NULL AUTO_INCREMENT,\n                 `itemtype` VARCHAR(100) NOT NULL COMMENT 'Type of locked object',\n                 `items_id` INT(11) NOT NULL COMMENT 'RELATION to various tables, according to itemtype (ID)',\n                 `users_id` INT(11) NOT NULL COMMENT 'id of the locker',\n                 `date_mod` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT 'Timestamp of the lock',\n                 PRIMARY KEY (`id`),\n                 UNIQUE INDEX `item` (`itemtype`, `items_id`)\n               ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.91 add table glpi_objectlocks");
    }
    // insert new profile
    $query = "INSERT INTO `glpi_profiles`\n                    (`name`, `interface`, `is_default`, `helpdesk_hardware`, `helpdesk_item_type`,\n                     `ticket_status`, `date_mod`, `comment`, `problem_status`,\n                     `create_ticket_on_login`, `tickettemplates_id`, `change_status`)\n             VALUES\n                    ('Read-Only','central','0','0','[]',\n                     '{\"1\":{\"2\":0,\"3\":0,\"4\":0,\"5\":0,\"6\":0},\n                       \"2\":{\"1\":0,\"3\":0,\"4\":0,\"5\":0,\"6\":0},\n                       \"3\":{\"1\":0,\"2\":0,\"4\":0,\"5\":0,\"6\":0},\n                       \"4\":{\"1\":0,\"2\":0,\"3\":0,\"5\":0,\"6\":0},\n                       \"5\":{\"1\":0,\"2\":0,\"3\":0,\"4\":0,\"6\":0},\n                       \"6\":{\"1\":0,\"2\":0,\"3\":0,\"4\":0,\"5\":0}}',\n                     NULL,\n                     'This profile defines read-only access. It is used when objects are locked. It can also be used to give to users rights to unlock objects.',\n                    '{\"1\":{\"7\":0,\"2\":0,\"3\":0,\"4\":0,\"5\":0,\"8\":0,\"6\":0},\n                      \"7\":{\"1\":0,\"2\":0,\"3\":0,\"4\":0,\"5\":0,\"8\":0,\"6\":0},\n                      \"2\":{\"1\":0,\"7\":0,\"3\":0,\"4\":0,\"5\":0,\"8\":0,\"6\":0},\n                      \"3\":{\"1\":0,\"7\":0,\"2\":0,\"4\":0,\"5\":0,\"8\":0,\"6\":0},\n                      \"4\":{\"1\":0,\"7\":0,\"2\":0,\"3\":0,\"5\":0,\"8\":0,\"6\":0},\n                      \"5\":{\"1\":0,\"7\":0,\"2\":0,\"3\":0,\"4\":0,\"8\":0,\"6\":0},\n                      \"8\":{\"1\":0,\"7\":0,\"2\":0,\"3\":0,\"4\":0,\"5\":0,\"6\":0},\n                      \"6\":{\"1\":0,\"7\":0,\"2\":0,\"3\":0,\"4\":0,\"5\":0,\"8\":0}}',\n                     0, 0,\n                     '{\"1\":{\"9\":0,\"10\":0,\"7\":0,\"4\":0,\"11\":0,\"12\":0,\"5\":0,\"8\":0,\"6\":0},\n                       \"9\":{\"1\":0,\"10\":0,\"7\":0,\"4\":0,\"11\":0,\"12\":0,\"5\":0,\"8\":0,\"6\":0},\n                       \"10\":{\"1\":0,\"9\":0,\"7\":0,\"4\":0,\"11\":0,\"12\":0,\"5\":0,\"8\":0,\"6\":0},\n                       \"7\":{\"1\":0,\"9\":0,\"10\":0,\"4\":0,\"11\":0,\"12\":0,\"5\":0,\"8\":0,\"6\":0},\n                       \"4\":{\"1\":0,\"9\":0,\"10\":0,\"7\":0,\"11\":0,\"12\":0,\"5\":0,\"8\":0,\"6\":0},\n                       \"11\":{\"1\":0,\"9\":0,\"10\":0,\"7\":0,\"4\":0,\"12\":0,\"5\":0,\"8\":0,\"6\":0},\n                       \"12\":{\"1\":0,\"9\":0,\"10\":0,\"7\":0,\"4\":0,\"11\":0,\"5\":0,\"8\":0,\"6\":0},\n                       \"5\":{\"1\":0,\"9\":0,\"10\":0,\"7\":0,\"4\":0,\"11\":0,\"12\":0,\"8\":0,\"6\":0},\n                       \"8\":{\"1\":0,\"9\":0,\"10\":0,\"7\":0,\"4\":0,\"11\":0,\"12\":0,\"5\":0,\"6\":0},\n                       \"6\":{\"1\":0,\"9\":0,\"10\":0,\"7\":0,\"4\":0,\"11\":0,\"12\":0,\"5\":0,\"8\":0}}')";
    $DB->queryOrDie($query, "0.91 update profile with Unlock profile");
    $ret = $DB->insert_id();
    // insert default rights for this profile
    ProfileRight::updateProfileRights($ret, array('backup' => '1', 'bookmark_public' => '1', 'budget' => '161', 'calendar' => '1', 'cartridge' => '161', 'change' => '1185', 'changevalidation' => '0', 'computer' => '161', 'config' => '1', 'consumable' => '161', 'contact_enterprise' => '161', 'contract' => '161', 'device' => '0', 'document' => '161', 'domain' => '1', 'dropdown' => '1', 'entity' => '1185', 'followup' => '8193', 'global_validation' => '0', 'group' => '129', 'infocom' => '1', 'internet' => '129', 'itilcategory' => '1', 'knowbase' => '2177', 'knowbasecategory' => '1', 'link' => '129', 'location' => '1', 'logs' => '1', 'monitor' => '161', 'netpoint' => '1', 'networking' => '161', 'notification' => '1', 'password_update' => '0', 'peripheral' => '161', 'phone' => '161', 'planning' => '3073', 'printer' => '161', 'problem' => '1185', 'profile' => '129', 'project' => '1185', 'projecttask' => '1', 'queuedmail' => '1', 'reminder_public' => '129', 'reports' => '1', 'reservation' => '1', 'rssfeed_public' => '129', 'rule_dictionnary_dropdown' => '1', 'rule_dictionnary_printer' => '1', 'rule_dictionnary_software' => '1', 'rule_import' => '1', 'rule_ldap' => '1', 'rule_mailcollector' => '1', 'rule_softwarecategories' => '1', 'rule_ticket' => '1', 'search_config' => '0', 'show_group_hardware' => '1', 'sla' => '1', 'software' => '161', 'solutiontemplate' => '1', 'state' => '1', 'statistic' => '1', 'task' => '8193', 'taskcategory' => '1', 'ticket' => '7297', 'ticketcost' => '1', 'ticketrecurrent' => '1', 'tickettemplate' => '1', 'ticketvalidation' => '0', 'transfer' => '1', 'typedoc' => '1', 'user' => '2177'));
    // updates rights for Super-Admin profile
    foreach ($CFG_GLPI['lock_lockable_objects'] as $itemtype) {
        $rightnames[] = "'" . $itemtype::$rightname . "'";
    }
    $query = "UPDATE `glpi_profilerights`\n             SET `rights` = `rights` | " . UNLOCK . "\n             WHERE `profiles_id` = '4'\n                   AND `name` IN (" . implode(",", $rightnames) . ")";
    $DB->queryOrDie($query, "update super-admin profile with UNLOCK right");
    Config::setConfigurationValues('core', array('lock_use_lock_item' => 0, 'lock_autolock_mode' => 1, 'lock_directunlock_notification' => 0, 'lock_item_list' => '[]', 'lock_lockprofile_id' => $ret));
    // cron task
    if (!countElementsInTable('glpi_crontasks', "`itemtype`='ObjectLock' AND `name`='unlockobject'")) {
        $query = "INSERT INTO `glpi_crontasks`\n                       (`itemtype`, `name`, `frequency`, `param`, `state`, `mode`, `allowmode`,\n                        `hourmin`, `hourmax`, `logs_lifetime`, `lastrun`, `lastcode`, `comment`)\n                VALUES ('ObjectLock', 'unlockobject', 86400, 4, 0, 1, 3,\n                        0, 24, 30, NULL, NULL, NULL); ";
        $DB->queryOrDie($query, "Update UnlockObject cron task");
    }
    // notification template
    $query = "SELECT *\n             FROM `glpi_notificationtemplates`\n             WHERE `itemtype` = 'ObjectLock'";
    if ($result = $DB->query($query)) {
        if ($DB->numrows($result) == 0) {
            $query = "INSERT INTO `glpi_notificationtemplates`\n                          (`name`, `itemtype`, `date_mod`)\n                   VALUES ('Unlock Item request', 'ObjectLock', NOW())";
            $DB->queryOrDie($query, "0.84 add planning recall notification");
            $notid = $DB->insert_id();
            $query = "INSERT INTO `glpi_notificationtemplatetranslations`\n                                (`notificationtemplates_id`, `language`,\n                                 `subject`,\n                                 `content_text`,\n                                 `content_html`)\n                         VALUES ({$notid}, '', '##objectlock.action##',\n      '##objectlock.type## ###objectlock.id## - ##objectlock.name##\n\n      ##lang.objectlock.url##\n      ##objectlock.url##\n\n      ##lang.objectlock.date_mod##\n      ##objectlock.date_mod##\n\n      Hello ##objectlock.lockedby.firstname##,\n      Could go to this item and unlock it for me?\n      Thank you,\n      Regards,\n      ##objectlock.requester.firstname##',\n      '&lt;table&gt;\n      &lt;tbody&gt;\n      &lt;tr&gt;&lt;th colspan=\"2\"&gt;&lt;a href=\"##objectlock.url##\"&gt;##objectlock.type## ###objectlock.id## - ##objectlock.name##&lt;/a&gt;&lt;/th&gt;&lt;/tr&gt;\n      &lt;tr&gt;\n      &lt;td&gt;##lang.objectlock.url##&lt;/td&gt;\n      &lt;td&gt;##objectlock.url##&lt;/td&gt;\n      &lt;/tr&gt;\n      &lt;tr&gt;\n      &lt;td&gt;##lang.objectlock.date_mod##&lt;/td&gt;\n      &lt;td&gt;##objectlock.date_mod##&lt;/td&gt;\n      &lt;/tr&gt;\n      &lt;/tbody&gt;\n      &lt;/table&gt;\n      &lt;p&gt;&lt;span style=\"font-size: small;\"&gt;Hello ##objectlock.lockedby.firstname##,&lt;br /&gt;Could go to this item and unlock it for me?&lt;br /&gt;Thank you,&lt;br /&gt;Regards,&lt;br /&gt;##objectlock.requester.firstname## ##objectlock.requester.lastname##&lt;/span&gt;&lt;/p&gt;')";
            $DB->queryOrDie($query, "0.91 add Unlock Request notification translation");
            $query = "INSERT INTO `glpi_notifications`\n                                (`name`, `entities_id`, `itemtype`, `event`, `mode`,\n                                 `notificationtemplates_id`, `comment`, `is_recursive`, `is_active`,\n                                 `date_mod`)\n                         VALUES ('Request Unlock Items', 0, 'ObjectLock', 'unlock', 'mail',\n                                   {$notid}, '', 1, 1, NOW())";
            $DB->queryOrDie($query, "0.91 add Unlock Request notification");
            $notifid = $DB->insert_id();
            $query = "INSERT INTO `glpi_notificationtargets`\n                                (`id`, `notifications_id`, `type`, `items_id`)\n                         VALUES (NULL, {$notifid}, " . Notification::USER_TYPE . ", " . Notification::USER . ");";
            $DB->queryOrDie($query, "0.91 add Unlock Request notification target");
        }
    }
    Config::setConfigurationValues('core', array('set_default_requester' => 1));
    $migration->addField("glpi_users", "set_default_requester", "tinyint(1) NULL DEFAULT NULL");
    // Add task template
    if (!TableExists('glpi_tasktemplates')) {
        $query = "CREATE TABLE `glpi_tasktemplates` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `entities_id` int(11) NOT NULL DEFAULT '0',\n                  `is_recursive` tinyint(1) NOT NULL DEFAULT '0',\n                  `name` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n                  `content` text COLLATE utf8_unicode_ci,\n                  `taskcategories_id` int(11) NOT NULL DEFAULT '0',\n                  `actiontime` int(11) NOT NULL DEFAULT '0',\n                  `comment` text COLLATE utf8_unicode_ci,\n                  PRIMARY KEY (`id`),\n                  KEY `name` (`name`),\n                  KEY `is_recursive` (`is_recursive`),\n                  KEY `taskcategories_id` (`taskcategories_id`),\n                  KEY `entities_id` (`entities_id`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;";
        $DB->queryOrDie($query, "0.84 add table glpi_tasktemplates");
    }
    $migration->addField("glpi_users", "lock_autolock_mode", "bool", true);
    $migration->addField("glpi_users", "lock_directunlock_notification", "bool", true);
    // ************ Keep it at the end **************
    $migration->executeMigration();
    return $updateresult;
}
@link      http://www.glpi-project.org/
@since     2009
--------------------------------------------------------------------------
*/
include_once "../../../inc/includes.php";
Session::checkRight('profile', READ);
Plugin::load('reports', true);
Html::header(__('Reports plugin configuration', 'reports'), $_SERVER['PHP_SELF'], 'config', 'plugins');
require_once "../inc/profile.class.php";
$report = '';
if (isset($_POST['report'])) {
    $report = $_POST['report'];
}
$prof = new PluginReportsProfile();
if (isset($_POST['delete']) && $report) {
    $profile_right = new ProfileRight();
    $profile_right->deleteByCriteria(array('name' => "plugin_reports_{$report}"));
    ProfileRight::addProfileRights(array("plugin_reports_{$report}"));
} else {
    if (isset($_POST['update']) && $report) {
        Session::checkRight('profile', UPDATE);
        PluginReportsProfile::updateForReport($_POST);
    }
}
$tab = $prof->updatePluginRights();
echo "<form method='post' action=\"" . $_SERVER["PHP_SELF"] . "\">";
echo "<table class='tab_cadre'><tr><th colspan='2'>";
echo "<a href='config.form.php'>" . __('Reports plugin configuration', 'reports') . "</a><br>&nbsp;<br>";
echo __('Rights management by report', 'reports') . "</th></tr>\n";
echo "<tr class='tab_bg_1'><td>" . __('Report', 'Reports', 1) . "&nbsp; ";
$query = "SELECT `id`, `name`\n          FROM `glpi_profiles`\n          ORDER BY `name`";
function plugin_racks_uninstall()
{
    include_once GLPI_ROOT . "/plugins/racks/inc/profile.class.php";
    include_once GLPI_ROOT . "/plugins/racks/inc/menu.class.php";
    $migration = new Migration("1.5.0");
    $tables = array("glpi_plugin_racks_racks", "glpi_plugin_racks_racks_items", "glpi_plugin_racks_itemspecifications", "glpi_plugin_racks_rackmodels", "glpi_plugin_racks_roomlocations", "glpi_plugin_racks_connections", "glpi_plugin_racks_configs", "glpi_plugin_racks_others", "glpi_plugin_racks_othermodels", "glpi_plugin_racks_racktypes", "glpi_plugin_racks_rackstates");
    foreach ($tables as $table) {
        $migration->dropTable($table);
    }
    //old versions
    $tables = array("glpi_plugin_rack", "glpi_plugin_rack_content", "glpi_plugin_rack_device_spec", "glpi_plugin_rack_profiles", "glpi_plugin_racks_profiles", "glpi_plugin_rack_config", "glpi_dropdown_plugin_rack_room_locations", "glpi_dropdown_plugin_rack_ways", "glpi_plugin_rack_others", "glpi_dropdown_plugin_rack_others_type");
    foreach ($tables as $table) {
        $migration->dropTable($table);
    }
    $itemtypes = array("DisplayPreference", "Document_Item", "Bookmark", "Log", "Ticket");
    foreach ($itemtypes as $itemtype) {
        $item = new $itemtype();
        $item->deleteByCriteria(array('itemtype' => 'PluginRacksRack'));
    }
    //Delete rights associated with the plugin
    $profileRight = new ProfileRight();
    foreach (PluginRacksProfile::getAllRights() as $right) {
        $profileRight->deleteByCriteria(array('name' => $right['field']));
    }
    PluginRacksProfile::removeRightsFromSession();
    PluginRacksProfile::removeRightsFromDB();
    PluginRacksMenu::removeRightsFromSession();
    return true;
}
Exemple #16
0
 function pre_deleteItem()
 {
     if ($this->getFromDB($this->fields["id"])) {
         $name = $this->fields['name'];
         $itemtype = $this->fields['itemtype'];
         //Delete all network ports
         self::deleteNetworking($itemtype);
         //Drop all dropdowns associated with itemtype
         self::deleteDropdownsForItemtype($itemtype);
         //Delete loans associated with this type
         self::deleteLoans($itemtype);
         //Delete loans associated with this type
         self::deleteUnicity($itemtype);
         //Delete reservations with this tyoe
         self::deleteReservations($itemtype);
         self::deleteReservationItems($itemtype);
         //Remove datainjection specific file
         self::deleteInjectionFile($name);
         //Delete profile informations associated with this type
         PluginGenericobjectProfile::deleteTypeFromProfile($itemtype);
         self::deleteTicketAssignation($itemtype);
         //Remove associations to simcards with this type
         self::deleteSimcardAssignation($itemtype);
         //Remove existing datainjection models
         self::removeDataInjectionModels($itemtype);
         //Delete specific locale directory
         self::deleteLocales($name, $itemtype);
         self::deleteItemtypeReferencesInGLPI($itemtype);
         self::deleteItemTypeFilesAndClasses($name, $this->getTable(), $itemtype);
         //self::deleteNotepad($itemtype);
         if (preg_match("/PluginGenericobject(.*)/", $itemtype, $results)) {
             $newrightname = 'plugin_genericobject_' . strtolower($results[1]) . 's';
             ProfileRight::deleteProfileRights(array($newrightname));
         }
         $prof = new Profile();
         $profiles = getAllDatasFromTable('glpi_profiles');
         foreach ($profiles as $profile) {
             $helpdesk_item_types = json_decode($profile['helpdesk_item_type'], true);
             if ($helpdesk_item_types !== null) {
                 $index = array_search($itemtype, $helpdesk_item_types);
                 if ($index) {
                     unset($helpdesk_item_types[$index]);
                     $tmp['id'] = $profile['id'];
                     $tmp['helpdesk_item_type'] = json_encode($helpdesk_item_types);
                     $prof->update($tmp);
                 }
             }
         }
         return true;
     } else {
         return false;
     }
 }
function plugin_manufacturersimports_uninstall()
{
    global $DB;
    include_once GLPI_ROOT . "/plugins/manufacturersimports/inc/profile.class.php";
    include_once GLPI_ROOT . "/plugins/manufacturersimports/inc/menu.class.php";
    $migration = new Migration("1.7.0");
    $tables = array("glpi_plugin_manufacturersimports_configs", "glpi_plugin_manufacturersimports_models", "glpi_plugin_manufacturersimports_logs");
    foreach ($tables as $table) {
        $migration->dropTable($table);
    }
    //old versions
    $tables = array("glpi_plugin_suppliertag_config", "glpi_plugin_suppliertag_profiles", "glpi_plugin_suppliertag_models", "glpi_plugin_suppliertag_imported");
    foreach ($tables as $table) {
        $migration->dropTable($table);
    }
    $profileRight = new ProfileRight();
    foreach (PluginManufacturersimportsProfile::getAllRights() as $right) {
        $profileRight->deleteByCriteria(array('name' => $right['field']));
    }
    //Remove rigth from $_SESSION['glpiactiveprofile'] if exists
    PluginManufacturersimportsProfile::removeRightsFromSession();
    //Remove entries in GLPI's menu and breadcrumb
    PluginManufacturersimportsMenu::removeRightsFromSession();
    return true;
}
 static function uninstallProfile()
 {
     $pfProfile = new self();
     $a_rights = $pfProfile->getAllRights();
     foreach ($a_rights as $data) {
         ProfileRight::deleteProfileRights(array($data['field']));
     }
 }
 /**
  * Initialize profiles, and migrate it necessary
  */
 static function initProfile()
 {
     global $DB;
     $profile = new self();
     //Add new rights in glpi_profilerights table
     foreach ($profile->getAllRights(true) as $data) {
         if (countElementsInTable("glpi_profilerights", "`name` = '" . $data['field'] . "'") == 0) {
             ProfileRight::addProfileRights(array($data['field']));
         }
     }
     //Migration old rights in new ones
     foreach ($DB->request("SELECT `id` FROM `glpi_profiles`") as $prof) {
         self::migrateOneProfile($prof['id']);
     }
     foreach ($DB->request("SELECT *\n                           FROM `glpi_profilerights`\n                           WHERE `profiles_id`='" . $_SESSION['glpiactiveprofile']['id'] . "'\n                              AND `name` LIKE '%plugin_databases%'") as $prof) {
         $_SESSION['glpiactiveprofile'][$prof['name']] = $prof['rights'];
     }
 }
Exemple #20
0
function plugin_racks_uninstall()
{
    global $DB;
    include_once GLPI_ROOT . "/plugins/racks/inc/profile.class.php";
    include_once GLPI_ROOT . "/plugins/racks/inc/menu.class.php";
    $migration = new Migration("1.6.1");
    $tables = array("glpi_plugin_racks_racks", "glpi_plugin_racks_racks_items", "glpi_plugin_racks_itemspecifications", "glpi_plugin_racks_rackmodels", "glpi_plugin_racks_roomlocations", "glpi_plugin_racks_connections", "glpi_plugin_racks_configs", "glpi_plugin_racks_others", "glpi_plugin_racks_othermodels", "glpi_plugin_racks_racktypes", "glpi_plugin_racks_rackstates");
    foreach ($tables as $table) {
        $migration->dropTable($table);
    }
    //old versions
    $tables = array("glpi_plugin_rack", "glpi_plugin_rack_content", "glpi_plugin_rack_device_spec", "glpi_plugin_rack_profiles", "glpi_plugin_racks_profiles", "glpi_plugin_rack_config", "glpi_dropdown_plugin_rack_room_locations", "glpi_dropdown_plugin_rack_ways", "glpi_plugin_rack_others", "glpi_dropdown_plugin_rack_others_type");
    foreach ($tables as $table) {
        $migration->dropTable($table);
    }
    $tables_glpi = array("glpi_displaypreferences", "glpi_documents_items", "glpi_bookmarks", "glpi_logs", "glpi_items_tickets", "glpi_dropdowntranslations");
    foreach ($tables_glpi as $table_glpi) {
        $DB->query("DELETE FROM `{$table_glpi}` WHERE `itemtype` LIKE 'PluginRacks%';");
    }
    //Delete rights associated with the plugin
    $profileRight = new ProfileRight();
    foreach (PluginRacksProfile::getAllRights() as $right) {
        $profileRight->deleteByCriteria(array('name' => $right['field']));
    }
    PluginRacksProfile::removeRightsFromSession();
    PluginRacksProfile::removeRightsFromDB();
    PluginRacksMenu::removeRightsFromSession();
    return true;
}
function plugin_additionalalerts_uninstall()
{
    global $DB;
    $tables = array("glpi_plugin_additionalalerts_ocsalerts", "glpi_plugin_additionalalerts_infocomalerts", "glpi_plugin_additionalalerts_notificationstates", "glpi_plugin_additionalalerts_notificationtypes", "glpi_plugin_additionalalerts_configs");
    foreach ($tables as $table) {
        $DB->query("DROP TABLE IF EXISTS `{$table}`;");
    }
    //old versions
    $tables = array("glpi_plugin_additionalalerts_reminderalerts", "glpi_plugin_alerting_config", "glpi_plugin_alerting_state", "glpi_plugin_alerting_profiles", "glpi_plugin_alerting_mailing", "glpi_plugin_alerting_type", "glpi_plugin_additionalalerts_profiles");
    foreach ($tables as $table) {
        $DB->query("DROP TABLE IF EXISTS `{$table}`;");
    }
    $notif = new Notification();
    $options = array('itemtype' => 'PluginAdditionalalertsOcsAlert', 'event' => 'ocs', 'FIELDS' => 'id');
    foreach ($DB->request('glpi_notifications', $options) as $data) {
        $notif->delete($data);
    }
    $options = array('itemtype' => 'PluginAdditionalalertsOcsAlert', 'event' => 'newocs', 'FIELDS' => 'id');
    foreach ($DB->request('glpi_notifications', $options) as $data) {
        $notif->delete($data);
    }
    $options = array('itemtype' => 'PluginAdditionalalertsInfocomAlert', 'event' => 'notinfocom', 'FIELDS' => 'id');
    foreach ($DB->request('glpi_notifications', $options) as $data) {
        $notif->delete($data);
    }
    //templates
    $template = new NotificationTemplate();
    $translation = new NotificationTemplateTranslation();
    $options = array('itemtype' => 'PluginAdditionalalertsOcsAlert', 'FIELDS' => 'id');
    foreach ($DB->request('glpi_notificationtemplates', $options) as $data) {
        $options_template = array('notificationtemplates_id' => $data['id'], 'FIELDS' => 'id');
        foreach ($DB->request('glpi_notificationtemplatetranslations', $options_template) as $data_template) {
            $translation->delete($data_template);
        }
        $template->delete($data);
    }
    //templates
    $template = new NotificationTemplate();
    $translation = new NotificationTemplateTranslation();
    $options = array('itemtype' => 'PluginAdditionalalertsInfocomAlert', 'FIELDS' => 'id');
    foreach ($DB->request('glpi_notificationtemplates', $options) as $data) {
        $options_template = array('notificationtemplates_id' => $data['id'], 'FIELDS' => 'id');
        foreach ($DB->request('glpi_notificationtemplatetranslations', $options_template) as $data_template) {
            $translation->delete($data_template);
        }
        $template->delete($data);
    }
    //Delete rights associated with the plugin
    $profileRight = new ProfileRight();
    foreach (PluginAdditionalalertsProfile::getAllRights() as $right) {
        $profileRight->deleteByCriteria(array('name' => $right['field']));
    }
    PluginAdditionalalertsProfile::removeRightsFromSession();
    PluginAdditionalalertsMenu::removeRightsFromSession();
    return true;
}
Exemple #22
0
 /**
  * Summary of setReadOnlyProfile
  * Switches current profile with read-only profile
  * Registers a shutdown function to be sure that even in case of die() calls,
  * the switch back will be done: to ensure correct reset of normal profile
  **/
 static function setReadOnlyProfile()
 {
     global $CFG_GLPI, $_SESSION;
     // to prevent double set ReadOnlyProfile
     if (!isset($_SESSION['glpilocksavedprofile'])) {
         if (isset($CFG_GLPI['lock_lockprofile'])) {
             if (!self::$shutdownregistered) {
                 // this is a security in case of a die that can prevent correct revert of profile
                 register_shutdown_function(array(__CLASS__, 'revertProfile'));
                 self::$shutdownregistered = true;
             }
             $_SESSION['glpilocksavedprofile'] = $_SESSION['glpiactiveprofile'];
             $_SESSION['glpiactiveprofile'] = $CFG_GLPI['lock_lockprofile'];
             // this mask is mandatory to prevent read of information
             // that are not permitted to view by active profile
             ProfileRight::getAllPossibleRights();
             foreach ($_SESSION['glpi_all_possible_rights'] as $key => $val) {
                 if (isset($_SESSION['glpilocksavedprofile'][$key])) {
                     $_SESSION['glpiactiveprofile'][$key] = intval($_SESSION['glpilocksavedprofile'][$key]) & (isset($CFG_GLPI['lock_lockprofile'][$key]) ? intval($CFG_GLPI['lock_lockprofile'][$key]) : 0);
                 }
             }
             // don't forget entities
             $_SESSION['glpiactiveprofile']['entities'] = $_SESSION['glpilocksavedprofile']['entities'];
         }
     }
 }
 /**
  * Init profiles during installation :
  * - add rights in profile table for the current user's profile
  * - current profile has all rights on the plugin
  */
 static function initProfile()
 {
     $pfProfile = new self();
     $profile = new Profile();
     $a_rights = $pfProfile->getAllRights();
     foreach ($a_rights as $data) {
         if (countElementsInTable("glpi_profilerights", "`name` = '" . $data['field'] . "'") == 0) {
             ProfileRight::addProfileRights(array($data['field']));
             $_SESSION['glpiactiveprofile'][$data['field']] = 0;
         }
     }
     // Add all rights to current profile of the user
     if (isset($_SESSION['glpiactiveprofile'])) {
         $dataprofile = array();
         $dataprofile['id'] = $_SESSION['glpiactiveprofile']['id'];
         $profile->getFromDB($_SESSION['glpiactiveprofile']['id']);
         foreach ($a_rights as $info) {
             if (is_array($info) && (!empty($info['itemtype']) || !empty($info['rights'])) && !empty($info['label']) && !empty($info['field'])) {
                 if (isset($info['rights'])) {
                     $rights = $info['rights'];
                 } else {
                     $rights = $profile->getRightsFor($info['itemtype']);
                 }
                 foreach ($rights as $right => $label) {
                     $dataprofile['_' . $info['field']][$right] = 1;
                     $_SESSION['glpiactiveprofile'][$data['field']] = $right;
                 }
             }
         }
         $profile->update($dataprofile);
     }
 }
Exemple #24
0
/**
 * @return bool
 */
function plugin_ocsinventoryng_uninstall()
{
    global $DB;
    include_once GLPI_ROOT . "/plugins/ocsinventoryng/inc/profile.class.php";
    include_once GLPI_ROOT . "/plugins/ocsinventoryng/inc/menu.class.php";
    $tables = array("glpi_plugin_ocsinventoryng_ocsservers", "glpi_plugin_ocsinventoryng_ocslinks", "glpi_plugin_ocsinventoryng_ocsadmininfoslinks", "glpi_plugin_ocsinventoryng_profiles", "glpi_plugin_ocsinventoryng_threads", "glpi_plugin_ocsinventoryng_snmpocslinks", "glpi_plugin_ocsinventoryng_ipdiscoverocslinks", "glpi_plugin_ocsinventoryng_servers", "glpi_plugin_ocsinventoryng_configs", "glpi_plugin_ocsinventoryng_notimportedcomputers", "glpi_plugin_ocsinventoryng_details", "glpi_plugin_ocsinventoryng_registrykeys", "glpi_plugin_ocsinventoryng_networkports", "glpi_plugin_ocsinventoryng_networkporttypes", "glpi_plugin_ocsinventoryng_ocsservers_profiles", "glpi_plugin_ocsinventoryng_devicebiosdatas", "glpi_plugin_ocsinventoryng_items_devicebiosdatas");
    foreach ($tables as $table) {
        $DB->query("DROP TABLE IF EXISTS `{$table}`;");
    }
    $tables_glpi = array("glpi_bookmarks", "glpi_displaypreferences", "glpi_logs");
    foreach ($tables_glpi as $table_glpi) {
        $DB->query("DELETE\r\n                  FROM `" . $table_glpi . "`\r\n                  WHERE `itemtype` IN ('PluginMassocsimportNotimported',\r\n                                       'PluginMassocsimportDetail',\r\n                                       'PluginOcsinventoryngOcsServer',\r\n                                       'PluginOcsinventoryngNotimportedcomputer',\r\n                                       'PluginOcsinventoryngDetail')");
    }
    $tables_ocs = array("ocs_glpi_crontasks", "ocs_glpi_displaypreferences", "ocs_glpi_ocsadmininfoslinks", "ocs_glpi_ocslinks", "ocs_glpi_ocsservers", "ocs_glpi_registrykeys", "ocs_glpi_profiles");
    foreach ($tables_ocs as $table_ocs) {
        $DB->query("DROP TABLE IF EXISTS `{$table_ocs}`;");
    }
    $tables_mass = array("backup_glpi_plugin_massocsimport_configs", "backup_glpi_plugin_massocsimport_details", "backup_glpi_plugin_massocsimport_notimported", "backup_glpi_plugin_massocsimport_servers", "backup_glpi_plugin_massocsimport_threads");
    foreach ($tables_mass as $table_mass) {
        $DB->query("DROP TABLE IF EXISTS `{$table_mass}`;");
    }
    $query = "DELETE\r\n             FROM `glpi_alerts`\r\n             WHERE `itemtype` IN ('PluginMassocsimportNotimported',\r\n                                  'PluginOcsinventoryngNotimportedcomputer')";
    $DB->queryOrDie($query, $DB->error());
    // clean rules
    $rule = new RuleImportEntity();
    foreach ($DB->request("glpi_rules", array('sub_type' => 'RuleImportEntity')) as $data) {
        $rule->delete($data);
    }
    $rule = new RuleImportComputer();
    foreach ($DB->request("glpi_rules", array('sub_type' => 'RuleImportComputer')) as $data) {
        $rule->delete($data);
    }
    $notification = new Notification();
    foreach (getAllDatasFromTable($notification->getTable(), "`itemtype` IN ('PluginMassocsimportNotimported',\r\n                                                 'PluginOcsinventoryngNotimportedcomputer')") as $data) {
        $notification->delete($data);
    }
    $template = new NotificationTemplate();
    foreach (getAllDatasFromTable($template->getTable(), "`itemtype` IN ('PluginMassocsimportNotimported',\r\n                                                 'PluginOcsinventoryngNotimportedcomputer')") as $data) {
        $template->delete($data);
    }
    $cron = new CronTask();
    if ($cron->getFromDBbyName('PluginMassocsimportThread', 'CleanOldThreads')) {
        CronTask::Unregister('massocsimport');
        CronTask::Unregister('CleanOldThreads');
    }
    if ($cron->getFromDBbyName('PluginOcsinventoryngOcsServer', 'ocsng')) {
        CronTask::Unregister('ocsinventoryng');
        CronTask::Unregister('ocsng');
    }
    if ($cron->getFromDBbyName('PluginOcsinventoryngNotimportedcomputer', 'SendAlerts')) {
        CronTask::Unregister('SendAlerts');
    }
    if ($cron->getFromDBbyName('PluginOcsinventoryngOcsServer', 'CleanOldAgents')) {
        CronTask::Unregister('CleanOldAgents');
    }
    //Delete rights associated with the plugin
    $profileRight = new ProfileRight();
    foreach (PluginOcsinventoryngProfile::getAllRights() as $right) {
        $profileRight->deleteByCriteria(array('name' => $right['field']));
    }
    PluginOcsinventoryngMenu::removeRightsFromSession();
    PluginOcsinventoryngProfile::removeRightsFromSession();
    return true;
}
Exemple #25
0
function plugin_certificates_uninstall() {
   global $DB;
   
   include_once (GLPI_ROOT."/plugins/certificates/inc/profile.class.php");
   include_once (GLPI_ROOT."/plugins/certificates/inc/menu.class.php");
   
   $tables = array("glpi_plugin_certificates_certificates",
               "glpi_plugin_certificates_certificates_items",
               "glpi_plugin_certificates_certificatetypes",
               "glpi_plugin_certificates_certificatestates",
               "glpi_plugin_certificates_configs",
               "glpi_plugin_certificates_notificationstates");

   foreach($tables as $table)
      $DB->query("DROP TABLE IF EXISTS `$table`;");
   
   //old versions	
   $tables = array("glpi_plugin_certificates",
               "glpi_plugin_certificates_profiles",
               "glpi_plugin_certificates_device",
               "glpi_dropdown_plugin_certificates_type",
               "glpi_dropdown_plugin_certificates_status",
               "glpi_plugin_certificates_config",
               "glpi_plugin_certificates_mailing",
               "glpi_plugin_certificates_default");

   foreach($tables as $table)
      $DB->query("DROP TABLE IF EXISTS `$table`;");
   
   $notif = new Notification();
   $options = array('itemtype' => 'PluginCertificatesCertificate',
                    'event'    => 'ExpiredCertificates',
                    'FIELDS'   => 'id');
   foreach ($DB->request('glpi_notifications', $options) as $data) {
      $notif->delete($data);
   }
   $options = array('itemtype' => 'PluginCertificatesCertificate',
                    'event'    => 'CertificatesWhichExpire',
                    'FIELDS'   => 'id');
   foreach ($DB->request('glpi_notifications', $options) as $data) {
      $notif->delete($data);
   }
   
   //templates
   $template = new NotificationTemplate();
   $translation = new NotificationTemplateTranslation();
   $options = array('itemtype' => 'PluginCertificatesCertificate',
                    'FIELDS'   => 'id');
   foreach ($DB->request('glpi_notificationtemplates', $options) as $data) {
      $options_template = array('notificationtemplates_id' => $data['id'],
                    'FIELDS'   => 'id');
   
         foreach ($DB->request('glpi_notificationtemplatetranslations', $options_template) as $data_template) {
            $translation->delete($data_template);
         }
      $template->delete($data);
   }
   
   $tables_glpi = array("glpi_displaypreferences",
               "glpi_documents_items",
               "glpi_bookmarks",
               "glpi_logs",
               "glpi_tickets",
               "glpi_contracts_items",
               "glpi_notepads");

   foreach($tables_glpi as $table_glpi)
      $DB->query("DELETE FROM `$table_glpi` WHERE `itemtype` = 'PluginCertificatesCertificate';");
      
   //Delete rights associated with the plugin
   $profileRight = new ProfileRight();
   foreach (PluginCertificatesProfile::getAllRights() as $right) {
      $profileRight->deleteByCriteria(array('name' => $right['field']));
   }
   PluginCertificatesMenu::removeRightsFromSession();
   
   PluginCertificatesProfile::removeRightsFromSession();

   return true;
}
Exemple #26
0
function plugin_example_uninstall()
{
    global $DB;
    $config = new Config();
    $config->deleteConfigurationValues('plugin:Example', array('configuration' => false));
    ProfileRight::deleteProfileRights(array('example:read'));
    $notif = new Notification();
    $options = array('itemtype' => 'Ticket', 'event' => 'plugin_example', 'FIELDS' => 'id');
    foreach ($DB->request('glpi_notifications', $options) as $data) {
        $notif->delete($data);
    }
    // Old version tables
    if (TableExists("glpi_dropdown_plugin_example")) {
        $query = "DROP TABLE `glpi_dropdown_plugin_example`";
        $DB->query($query) or die("error deleting glpi_dropdown_plugin_example");
    }
    if (TableExists("glpi_plugin_example")) {
        $query = "DROP TABLE `glpi_plugin_example`";
        $DB->query($query) or die("error deleting glpi_plugin_example");
    }
    // Current version tables
    if (TableExists("glpi_plugin_example_example")) {
        $query = "DROP TABLE `glpi_plugin_example_example`";
        $DB->query($query) or die("error deleting glpi_plugin_example_example");
    }
    if (TableExists("glpi_plugin_example_dropdowns")) {
        $query = "DROP TABLE `glpi_plugin_example_dropdowns`;";
        $DB->query($query) or die("error deleting glpi_plugin_example_dropdowns");
    }
    if (TableExists("glpi_plugin_example_devicecameras")) {
        $query = "DROP TABLE `glpi_plugin_example_devicecameras`;";
        $DB->query($query) or die("error deleting glpi_plugin_example_devicecameras");
    }
    if (TableExists("glpi_plugin_example_items_devicecameras")) {
        $query = "DROP TABLE `glpi_plugin_example_items_devicecameras`;";
        $DB->query($query) or die("error deleting glpi_plugin_example_items_devicecameras");
    }
    return true;
}
function plugin_databases_uninstall()
{
    global $DB;
    include_once GLPI_ROOT . "/plugins/databases/inc/profile.class.php";
    include_once GLPI_ROOT . "/plugins/databases/inc/menu.class.php";
    $tables = array("glpi_plugin_databases_databases", "glpi_plugin_databases_databasetypes", "glpi_plugin_databases_databasecategories", "glpi_plugin_databases_servertypes", "glpi_plugin_databases_scripttypes", "glpi_plugin_databases_instances", "glpi_plugin_databases_scripts", "glpi_plugin_databases_databases_items");
    foreach ($tables as $table) {
        $DB->query("DROP TABLE IF EXISTS `{$table}`;");
    }
    //old versions
    $tables = array("glpi_plugin_sgbd", "glpi_dropdown_plugin_sgbd_type", "glpi_dropdown_plugin_sgbd_server_type", "glpi_plugin_sgbd_device", "glpi_plugin_sgbd_profiles", "glpi_dropdown_plugin_sgbd_script_type", "glpi_plugin_sgbd_instances", "glpi_plugin_sgbd_scripts", "glpi_dropdown_plugin_sgbd_category", "glpi_plugin_databases_profiles");
    foreach ($tables as $table) {
        $DB->query("DROP TABLE IF EXISTS `{$table}`;");
    }
    $tables_glpi = array("glpi_displaypreferences", "glpi_documents_items", "glpi_bookmarks", "glpi_logs", "glpi_items_tickets", "glpi_notepads");
    foreach ($tables_glpi as $table_glpi) {
        $DB->query("DELETE FROM `{$table_glpi}` WHERE `itemtype` = 'PluginDatabasesDatabase' ;");
    }
    if (class_exists('PluginDatainjectionModel')) {
        PluginDatainjectionModel::clean(array('itemtype' => 'PluginDatabasesDatabase'));
    }
    //Delete rights associated with the plugin
    $profileRight = new ProfileRight();
    foreach (PluginDatabasesProfile::getAllRights() as $right) {
        $profileRight->deleteByCriteria(array('name' => $right['field']));
    }
    PluginDatabasesMenu::removeRightsFromSession();
    PluginDatabasesProfile::removeRightsFromSession();
    return true;
}
Exemple #28
0
 static function uninstall()
 {
     global $DB;
     ProfileRight::deleteProfileRights(array(self::RIGHT_SIMCARD_SIMCARD));
     unset($_SESSION["glpiactiveprofile"][self::RIGHT_SIMCARD_SIMCARD]);
 }
 static function install(Migration $migration)
 {
     global $DB;
     $profileRight = new ProfileRight();
     $profile = new Profile();
     //Update needed
     if (TableExists('glpi_plugin_genericobject_profiles')) {
         foreach (getAllDatasFromTable('glpi_plugin_genericobject_profiles') as $right) {
             if (preg_match("/PluginGenericobject(.*)/", $right['itemtype'], $results)) {
                 $newrightname = 'plugin_genericobject_' . strtolower($results[1]) . 's';
                 if (!countElementsInTable('glpi_profilerights', "`profiles_id`='" . $right['profiles_id'] . "' \n                                           AND `name`='{$newrightname}'")) {
                     switch ($right['right']) {
                         case NULL:
                         case '':
                             $rightvalue = 0;
                             break;
                         case 'r':
                             $rightvalue = READ;
                             break;
                         case 'w':
                             $rightvalue = ALLSTANDARDRIGHT;
                             break;
                     }
                     $profileRight->add(array('profiles_id' => $right['profiles_id'], 'name' => $newrightname, 'rights' => $rightvalue));
                     if (!countElementsInTable('glpi_profilerights', "`profiles_id`='" . $right['profiles_id'] . "' \n                                              AND `name`='plugin_genericobject_types'")) {
                         $profileRight->add(array('profiles_id' => $right['profiles_id'], 'name' => 'plugin_genericobject_types', 'rights' => 23));
                     }
                 }
                 if ($right['open_ticket']) {
                     $profile->getFromDB($right['profiles_id']);
                     $helpdesk_item_types = json_decode($profile->fields['helpdesk_item_type'], true);
                     if (is_array($helpdesk_item_types)) {
                         if (!in_array($right['itemtype'], $helpdesk_item_types)) {
                             $helpdesk_item_types[] = $right['itemtype'];
                         }
                     } else {
                         $helpdesk_item_types = array($right['itemtype']);
                     }
                     $tmp['id'] = $profile->getID();
                     $tmp['helpdesk_item_type'] = json_encode($helpdesk_item_types);
                     $profile->update($tmp);
                 }
             }
         }
         //$migration->dropTable('glpi_plugin_genericobject_profiles');
     }
     if (!countElementsInTable('glpi_profilerights', "`name` LIKE '%genericobject%'")) {
         self::createFirstAccess();
     }
 }
 /**
  * Delete type from the rights
  * @param name the name of the type
  * @return nothing
  */
 public static function deleteTypeFromProfile($itemtype) {
    $rights = array();
    $rights[] = self::getProfileNameForItemtype($itemtype);
    ProfileRight::deleteProfileRights($rights);
 }