Example #1
0
/**
 * Update from 0.90.1 to 0.91
 *
 * @return bool for success (will die for most error)
**/
function update0901to091()
{
    global $DB, $migration;
    $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();
    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);
    }
    Config::setConfigurationValues('core', array('set_default_requester' => 1));
    $migration->addField("glpi_users", "set_default_requester", "tinyint(1) NULL DEFAULT NULL");
    // ************ Keep it at the end **************
    $migration->executeMigration();
    return $updateresult;
}
 function fill_db()
 {
     global $CFG_GLPI, $DB;
     //include_once (GLPI_ROOT . "/inc/dbmysql.class.php");
     include_once GLPI_CONFIG_DIR . "/config_db.php";
     $DB = new DB();
     if (!$DB->runFile(GLPI_ROOT . "/install/mysql/glpi-0.85.3-empty.sql")) {
         echo "Errors occurred inserting default database";
     }
     // update default language
     Config::setConfigurationValues('core', array('language' => $_SESSION["glpilanguage"]));
     $query = "UPDATE `glpi_users`\n                SET `language` = NULL";
     $DB->queryOrDie($query, "4203");
 }
Example #3
0
function updateDbUpTo031()
{
    global $DB, $migration;
    $ret = array();
    // Before 0.31
    if (!TableExists("glpi_config") && !TableExists("glpi_configs")) {
        $query = "CREATE TABLE `glpi_config` (\n                  `ID` int(11) NOT NULL auto_increment,\n                  `num_of_events` varchar(200) NOT NULL default '',\n                  `jobs_at_login` varchar(200) NOT NULL default '',\n                  `sendexpire` varchar(200) NOT NULL default '',\n                  `cut` varchar(200) NOT NULL default '',\n                  `expire_events` varchar(200) NOT NULL default '',\n                  `list_limit` varchar(200) NOT NULL default '',\n                  `version` varchar(200) NOT NULL default '',\n                  `logotxt` varchar(200) NOT NULL default '',\n                  `root_doc` varchar(200) NOT NULL default '',\n                  `event_loglevel` varchar(200) NOT NULL default '',\n                  `mailing` varchar(200) NOT NULL default '',\n                  `imap_auth_server` varchar(200) NOT NULL default '',\n                  `imap_host` varchar(200) NOT NULL default '',\n                  `ldap_host` varchar(200) NOT NULL default '',\n                  `ldap_basedn` varchar(200) NOT NULL default '',\n                  `ldap_rootdn` varchar(200) NOT NULL default '',\n                  `ldap_pass` varchar(200) NOT NULL default '',\n                  `admin_email` varchar(200) NOT NULL default '',\n                  `mailing_signature` varchar(200) NOT NULL default '',\n                  `mailing_new_admin` varchar(200) NOT NULL default '',\n                  `mailing_followup_admin` varchar(200) NOT NULL default '',\n                  `mailing_finish_admin` varchar(200) NOT NULL default '',\n                  `mailing_new_all_admin` varchar(200) NOT NULL default '',\n                  `mailing_followup_all_admin` varchar(200) NOT NULL default '',\n                  `mailing_finish_all_admin` varchar(200) NOT NULL default '',\n                  `mailing_new_all_normal` varchar(200) NOT NULL default '',\n                  `mailing_followup_all_normal` varchar(200) NOT NULL default '',\n                  `mailing_finish_all_normal` varchar(200) NOT NULL default '',\n                  `mailing_new_attrib` varchar(200) NOT NULL default '',\n                  `mailing_followup_attrib` varchar(200) NOT NULL default '',\n                  `mailing_finish_attrib` varchar(200) NOT NULL default '',\n                  `mailing_new_user` varchar(200) NOT NULL default '',\n                  `mailing_followup_user` varchar(200) NOT NULL default '',\n                  `mailing_finish_user` varchar(200) NOT NULL default '',\n                  `ldap_field_name` varchar(200) NOT NULL default '',\n                  `ldap_field_email` varchar(200) NOT NULL default '',\n                  `ldap_field_location` varchar(200) NOT NULL default '',\n                  `ldap_field_realname` varchar(200) NOT NULL default '',\n                  `ldap_field_phone` varchar(200) NOT NULL default '',\n                PRIMARY KEY (`ID`)\n                ) TYPE=MyISAM AUTO_INCREMENT=2 ";
        $DB->queryOrDie($query);
        $query = "INSERT INTO `glpi_config`\n                VALUES (1, '10', '1', '1', '80', '30', '15', ' 0.31', 'GLPI powered by indepnet',\n                        '/glpi', '5', '0', '', '', '', '', '', '', 'admsys@xxxxx.fr', 'SIGNATURE',\n                        '1', '1', '1', '1', '0', '0', '0', '0', '0', '0', '0', '0','1', '1', '1',\n                        'uid', 'mail', 'physicaldeliveryofficename', 'cn', 'telephonenumber')";
        $DB->queryOrDie($query);
        echo "<p class='center'>Version > 0.31  </p>";
    }
    // Save if problem with session during update
    $glpilanguage = $_SESSION["glpilanguage"];
    // < 0.78
    if (TableExists("glpi_config")) {
        // Get current version
        // Use language from session, even if sometime not reliable
        $query = "SELECT `version`, 'language'\n                FROM `glpi_config`";
        $result = $DB->queryOrDie($query, "get current version");
        $current_version = trim($DB->result($result, 0, 0));
        $glpilanguage = trim($DB->result($result, 0, 1));
        // < 0.85
    } else {
        if (FieldExists('glpi_configs', 'version')) {
            // Get current version and language
            $query = "SELECT `version`, `language`\n                FROM `glpi_configs`";
            $result = $DB->queryOrDie($query, "get current version");
            $current_version = trim($DB->result($result, 0, 0));
            $glpilanguage = trim($DB->result($result, 0, 1));
        } else {
            $configurationValues = Config::getConfigurationValues('core', array('version', 'language'));
            $current_version = $configurationValues['version'];
            $glpilanguage = $configurationValues['language'];
        }
    }
    // To prevent problem of execution time
    ini_set("max_execution_time", "0");
    $migration = new Migration($current_version);
    switch ($current_version) {
        case "0.31":
            include "update_031_04.php";
            update031to04();
        case "0.4":
        case "0.41":
            include "update_04_042.php";
            update04to042();
        case "0.42":
            showLocationUpdateForm();
            include "update_042_05.php";
            update042to05();
        case "0.5":
            include "update_05_051.php";
            update05to051();
        case "0.51":
        case "0.51a":
            include "update_051_06.php";
            update051to06();
        case "0.6":
            include "update_06_065.php";
            update06to065();
        case "0.65":
            include "update_065_068.php";
            update065to068();
        case "0.68":
            include "update_068_0681.php";
            update068to0681();
        case "0.68.1":
        case "0.68.2":
        case "0.68.3":
            // Force update content
            if (showLocationUpdateForm()) {
                $query = "UPDATE `glpi_config`\n                      SET `version` = ' 0.68.3x'";
                $DB->queryOrDie($query, "0.68.3");
                showContentUpdateForm();
                exit;
            }
        case "0.68.3x":
            // Special version for replay upgrade process from here
            include "update_0681_07.php";
            update0681to07();
        case "0.7":
        case "0.70.1":
        case "0.70.2":
            include "update_07_071.php";
            update07to071();
        case "0.71":
        case "0.71.1":
            include "update_071_0712.php";
            update071to0712();
        case "0.71.2":
            include "update_0712_0713.php";
            update0712to0713();
        case "0.71.3":
        case "0.71.4":
        case "0.71.5":
        case "0.71.6":
            include "update_0713_072.php";
            update0713to072();
        case "0.72":
            include "update_072_0721.php";
            update072to0721();
        case "0.72.1":
            include "update_0721_0722.php";
            update0721to0722();
        case "0.72.2":
        case "0.72.21":
            include "update_0722_0723.php";
            update0722to0723();
        case "0.72.3":
        case "0.72.4":
            include "update_0723_078.php";
            update0723to078();
        case "0.78":
            include "update_078_0781.php";
            update078to0781();
        case "0.78.1":
            include "update_0781_0782.php";
            update0781to0782();
        case "0.78.2":
        case "0.78.3":
        case "0.78.4":
        case "0.78.5":
            include "update_0782_080.php";
            update0782to080();
        case "0.80":
            include "update_080_0801.php";
            update080to0801();
        case "0.80.1":
        case "0.80.2":
            include "update_0801_0803.php";
            update0801to0803();
        case "0.80.3":
        case "0.80.4":
        case "0.80.5":
        case "0.80.6":
        case "0.80.61":
        case "0.80.7":
            include "update_0803_083.php";
            update0803to083();
        case "0.83":
            include "update_083_0831.php";
            update083to0831();
        case "0.83.1":
        case "0.83.2":
            include "update_0831_0833.php";
            update0831to0833();
        case "0.83.3":
        case "0.83.31":
        case "0.83.4":
        case "0.83.5":
        case "0.83.6":
        case "0.83.7":
        case "0.83.8":
        case "0.83.9":
        case "0.83.91":
            include "update_0831_084.php";
            update0831to084();
        case "0.84":
            include "update_084_0841.php";
            update084to0841();
        case "0.84.1":
        case "0.84.2":
            include "update_0841_0843.php";
            update0841to0843();
        case "0.84.3":
            include "update_0843_0844.php";
            update0843to0844();
        case "0.84.4":
        case "0.84.5":
            include "update_0845_0846.php";
            update0845to0846();
        case "0.84.6":
        case "0.84.7":
        case "0.84.8":
        case "0.84.9":
            include "update_084_085.php";
            update084to085();
        case "0.85":
        case "0.85.1":
        case "0.85.2":
            include "update_085_0853.php";
            update085to0853();
        case "0.85.3":
        case "0.85.4":
        case "0.85.5":
            include "update_0853_090.php";
            update0853to090();
        case "0.90":
            break;
        default:
            include "update_031_04.php";
            update031to04();
            include "update_04_042.php";
            update04to042();
            showLocationUpdateForm();
            include "update_042_05.php";
            update042to05();
            include "update_05_051.php";
            update05to051();
            include "update_051_06.php";
            update051to06();
            include "update_06_065.php";
            update06to065();
            include "update_065_068.php";
            update065to068();
            include "update_068_0681.php";
            update068to0681();
            // Force update content
            $query = "UPDATE `glpi_config`\n                   SET `version` = ' 0.68.3x'";
            $DB->queryOrDie($query, "0.68.3");
            showContentUpdateForm();
            exit;
    }
    // Update version number and default langage and new version_founded ---- LEAVE AT THE END
    Config::setConfigurationValues('core', array('version' => '0.90', 'language' => $glpilanguage, 'founded_new_version' => ''));
    // Update process desactivate all plugins
    $plugin = new Plugin();
    $plugin->unactivateAll();
    DBmysql::optimize_tables($migration);
    return $ret;
}
Example #4
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;
}
Example #5
0
    case "0.90.5":
        include_once "../install/update_0905_91.php";
        update0905to91();
        /* remember to also change --force below for last version */
    /* remember to also change --force below for last version */
    case "0.91":
        // // for change name of the version - to delete in next version
    // // for change name of the version - to delete in next version
    case GLPI_VERSION:
        break;
    default:
        die("Unsupported version ({$current_version})\n");
}
if (version_compare($current_version, GLPI_VERSION, 'ne')) {
    // Update version number and default langage and new version_founded ---- LEAVE AT THE END
    Config::setConfigurationValues('core', array('version' => GLPI_VERSION, 'founded_new_version' => ''));
    // Update process desactivate all plugins
    $plugin = new Plugin();
    $plugin->unactivateAll();
    $migration->displayWarning("\nMigration Done.");
} else {
    if (in_array('--force', $_SERVER['argv'])) {
        include_once "../install/update_0905_91.php";
        update0905to91();
        $migration->displayWarning("\nForced migration Done.");
    } else {
        $migration->displayWarning("No migration needed.");
    }
}
if (in_array('--optimize', $_SERVER['argv'])) {
    DBmysql::optimize_tables($migration);
Example #6
0
/**
 * Update from 0.90.2 to 9.1
 *
 * @return bool for success (will die for most error)
**/
function update0902to91()
{
    global $DB, $migration, $CFG_GLPI;
    $updateresult = true;
    $ADDTODISPLAYPREF = array();
    //TRANS: %s is the number of new version
    $migration->displayTitle(sprintf(__('Update to %s'), '9.1'));
    $migration->setVersion('9.1');
    $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'));
    /************** Lock Objects *************/
    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, "9.1 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 ('Read-Only','central','0','0','[]',\n                     '{\"1\":{\"2\":0,\"3\":0,\"4\":0,\"5\":0,\"6\":0},\"2\":{\"1\":0,\"3\":0,\"4\":0,\"5\":0,\"6\":0},\"3\":{\"1\":0,\"2\":0,\"4\":0,\"5\":0,\"6\":0},\"4\":{\"1\":0,\"2\":0,\"3\":0,\"5\":0,\"6\":0},\"5\":{\"1\":0,\"2\":0,\"3\":0,\"4\":0,\"6\":0},\"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},\"7\":{\"1\":0,\"2\":0,\"3\":0,\"4\":0,\"5\":0,\"8\":0,\"6\":0},\"2\":{\"1\":0,\"7\":0,\"3\":0,\"4\":0,\"5\":0,\"8\":0,\"6\":0},\"3\":{\"1\":0,\"7\":0,\"2\":0,\"4\":0,\"5\":0,\"8\":0,\"6\":0},\"4\":{\"1\":0,\"7\":0,\"2\":0,\"3\":0,\"5\":0,\"8\":0,\"6\":0},\"5\":{\"1\":0,\"7\":0,\"2\":0,\"3\":0,\"4\":0,\"8\":0,\"6\":0},\"8\":{\"1\":0,\"7\":0,\"2\":0,\"3\":0,\"4\":0,\"5\":0,\"6\":0},\"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},\"9\":{\"1\":0,\"10\":0,\"7\":0,\"4\":0,\"11\":0,\"12\":0,\"5\":0,\"8\":0,\"6\":0},\"10\":{\"1\":0,\"9\":0,\"7\":0,\"4\":0,\"11\":0,\"12\":0,\"5\":0,\"8\":0,\"6\":0},\"7\":{\"1\":0,\"9\":0,\"10\":0,\"4\":0,\"11\":0,\"12\":0,\"5\":0,\"8\":0,\"6\":0},\"4\":{\"1\":0,\"9\":0,\"10\":0,\"7\":0,\"11\":0,\"12\":0,\"5\":0,\"8\":0,\"6\":0},\"11\":{\"1\":0,\"9\":0,\"10\":0,\"7\":0,\"4\":0,\"12\":0,\"5\":0,\"8\":0,\"6\":0},\"12\":{\"1\":0,\"9\":0,\"10\":0,\"7\":0,\"4\":0,\"11\":0,\"5\":0,\"8\":0,\"6\":0},\"5\":{\"1\":0,\"9\":0,\"10\":0,\"7\":0,\"4\":0,\"11\":0,\"12\":0,\"8\":0,\"6\":0},\"8\":{\"1\":0,\"9\":0,\"10\":0,\"7\":0,\"4\":0,\"11\":0,\"12\":0,\"5\":0,\"6\":0},\"6\":{\"1\":0,\"9\":0,\"10\":0,\"7\":0,\"4\":0,\"11\":0,\"12\":0,\"5\":0,\"8\":0}}')";
    $DB->queryOrDie($query, "9.1 update profile with Unlock profile");
    $ro_p_id = $DB->insert_id();
    $DB->queryOrDie("INSERT INTO `glpi_profilerights`\n                           (`profiles_id`, `name`, `rights`)\n                    VALUES ({$ro_p_id}, 'backup',                    '1'),\n                           ({$ro_p_id}, 'bookmark_public',           '1'),\n                           ({$ro_p_id}, 'budget',                    '161'),\n                           ({$ro_p_id}, 'calendar',                  '1'),\n                           ({$ro_p_id}, 'cartridge',                 '161'),\n                           ({$ro_p_id}, 'change',                    '1185'),\n                           ({$ro_p_id}, 'changevalidation',          '0'),\n                           ({$ro_p_id}, 'computer',                  '161'),\n                           ({$ro_p_id}, 'config',                    '1'),\n                           ({$ro_p_id}, 'consumable',                '161'),\n                           ({$ro_p_id}, 'contact_enterprise',        '161'),\n                           ({$ro_p_id}, 'contract',                  '161'),\n                           ({$ro_p_id}, 'device',                    '0'),\n                           ({$ro_p_id}, 'document',                  '161'),\n                           ({$ro_p_id}, 'domain',                    '1'),\n                           ({$ro_p_id}, 'dropdown',                  '1'),\n                           ({$ro_p_id}, 'entity',                    '1185'),\n                           ({$ro_p_id}, 'followup',                  '8193'),\n                           ({$ro_p_id}, 'global_validation',         '0'),\n                           ({$ro_p_id}, 'group',                     '129'),\n                           ({$ro_p_id}, 'infocom',                   '1'),\n                           ({$ro_p_id}, 'internet',                  '129'),\n                           ({$ro_p_id}, 'itilcategory',              '1'),\n                           ({$ro_p_id}, 'knowbase',                  '2177'),\n                           ({$ro_p_id}, 'knowbasecategory',          '1'),\n                           ({$ro_p_id}, 'link',                      '129'),\n                           ({$ro_p_id}, 'location',                  '1'),\n                           ({$ro_p_id}, 'logs',                      '1'),\n                           ({$ro_p_id}, 'monitor',                   '161'),\n                           ({$ro_p_id}, 'netpoint',                  '1'),\n                           ({$ro_p_id}, 'networking',                '161'),\n                           ({$ro_p_id}, 'notification',              '1'),\n                           ({$ro_p_id}, 'password_update',           '0'),\n                           ({$ro_p_id}, 'peripheral',                '161'),\n                           ({$ro_p_id}, 'phone',                     '161'),\n                           ({$ro_p_id}, 'planning',                  '3073'),\n                           ({$ro_p_id}, 'printer',                   '161'),\n                           ({$ro_p_id}, 'problem',                   '1185'),\n                           ({$ro_p_id}, 'profile',                   '129'),\n                           ({$ro_p_id}, 'project',                   '1185'),\n                           ({$ro_p_id}, 'projecttask',               '1'),\n                           ({$ro_p_id}, 'queuedmail',                '1'),\n                           ({$ro_p_id}, 'reminder_public',           '129'),\n                           ({$ro_p_id}, 'reports',                   '1'),\n                           ({$ro_p_id}, 'reservation',               '1'),\n                           ({$ro_p_id}, 'rssfeed_public',            '129'),\n                           ({$ro_p_id}, 'rule_dictionnary_dropdown', '1'),\n                           ({$ro_p_id}, 'rule_dictionnary_printer',  '1'),\n                           ({$ro_p_id}, 'rule_dictionnary_software', '1'),\n                           ({$ro_p_id}, 'rule_import',               '1'),\n                           ({$ro_p_id}, 'rule_ldap',                 '1'),\n                           ({$ro_p_id}, 'rule_mailcollector',        '1'),\n                           ({$ro_p_id}, 'rule_softwarecategories',   '1'),\n                           ({$ro_p_id}, 'rule_ticket',               '1'),\n                           ({$ro_p_id}, 'search_config',             '0'),\n                           ({$ro_p_id}, 'show_group_hardware',       '1'),\n                           ({$ro_p_id}, 'sla',                       '1'),\n                           ({$ro_p_id}, 'software',                  '161'),\n                           ({$ro_p_id}, 'solutiontemplate',          '1'),\n                           ({$ro_p_id}, 'state',                     '1'),\n                           ({$ro_p_id}, 'statistic',                 '1'),\n                           ({$ro_p_id}, 'task',                      '8193'),\n                           ({$ro_p_id}, 'taskcategory',              '1'),\n                           ({$ro_p_id}, 'ticket',                    '7297'),\n                           ({$ro_p_id}, 'ticketcost',                '1'),\n                           ({$ro_p_id}, 'ticketrecurrent',           '1'),\n                           ({$ro_p_id}, 'tickettemplate',            '1'),\n                           ({$ro_p_id}, 'ticketvalidation',          '0'),\n                           ({$ro_p_id}, 'transfer',                  '1'),\n                           ({$ro_p_id}, 'typedoc',                   '1'),\n                           ({$ro_p_id}, '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' => $ro_p_id));
    // 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, "9.1 Add 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, "9.1 Add unlock request notification template");
            $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, "9.1 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, "9.1 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, "9.1 add Unlock Request notification target");
        }
    }
    $migration->addField("glpi_users", "lock_autolock_mode", "tinyint(1) NULL DEFAULT NULL");
    $migration->addField("glpi_users", "lock_directunlock_notification", "tinyint(1) NULL DEFAULT NULL");
    /************** Default Requester *************/
    Config::setConfigurationValues('core', array('set_default_requester' => 1));
    $migration->addField("glpi_users", "set_default_requester", "tinyint(1) NULL DEFAULT NULL");
    /************** Task's templates *************/
    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, "9.1 add table glpi_tasktemplates");
    }
    /************** Installation date for softwares *************/
    $migration->addField("glpi_computers_softwareversions", "date_install", "DATE");
    $migration->addKey("glpi_computers_softwareversions", "date_install");
    /************** New Planning with fullcalendar.io *************/
    $migration->addField("glpi_users", "plannings", "text");
    /************** Date mod/creation for itemtypes *************/
    $migration->displayMessage(sprintf(__('date_mod and date_creation')));
    $types = array('Computer', 'Monitor', 'Printer', 'Phone', 'Software', 'SoftwareVersion', 'SoftwareLicense', 'Peripheral', 'NetworkEquipment', 'User', 'Group', 'Entity', 'Profile', 'Budget', 'Contact', 'Contract', 'Netpoint', 'NetworkPort', 'Rule', 'Cartridge', 'CartridgeItem', 'Consumable', 'ConsumableItem', 'Ticket', 'Problem', 'Change', 'Supplier', 'Document', 'AuthLDAP', 'MailCollector', 'Location', 'State', 'Manufacturer', 'Blacklist', 'BlacklistedMailContent', 'ITILCategory', 'TaskCategory', 'TaskTemplate', 'Project', 'Reminder', 'RSSFeed', 'SolutionType', 'RequestType', 'SolutionTemplate', 'ProjectState', 'ProjectType', 'ProjectTaskType', 'SoftwareLicenseType', 'CartridgeItemType', 'ConsumableItemType', 'ContractType', 'ContactType', 'DeviceMemoryType', 'SupplierType', 'InterfaceType', 'DeviceCaseType', 'PhonePowerSupply', 'Filesystem', 'VirtualMachineType', 'VirtualMachineSystem', 'VirtualMachineState', 'DocumentCategory', 'DocumentType', 'KnowbaseItemCategory', 'Calendar', 'Holiday', 'NetworkEquipmentFirmware', 'Network', 'Domain', 'Vlan', 'IPNetwork', 'FQDN', 'WifiNetwork', 'NetworkName', 'UserTitle', 'UserCategory', 'RuleRightParameter', 'Fieldblacklist', 'SsoVariable', 'NotificationTemplate', 'Notification', 'SLA', 'FieldUnicity', 'Crontask', 'Link', 'ComputerDisk', 'ComputerVirtualMachine', 'Infocom');
    $types = array_merge($types, $CFG_GLPI["dictionnary_types"]);
    $types = array_merge($types, $CFG_GLPI["device_types"]);
    $types = array_merge($types, $CFG_GLPI['networkport_instantiations']);
    foreach ($types as $type) {
        $table = getTableForItemType($type);
        if (!FieldExists($table, 'date_mod')) {
            $migration->displayMessage(sprintf(__('Add date_mod to %s'), $table));
            //Add date_mod field if it doesn't exists
            $migration->addField($table, 'date_mod', 'datetime');
            $migration->addKey($table, 'date_mod');
            $migration->migrationOneTable($table);
        }
        if (!FieldExists($table, 'date_creation')) {
            $migration->displayMessage(sprintf(__('Add date_creation to %s'), $table));
            //Add date_creation field
            $migration->addField($table, 'date_creation', 'datetime');
            $migration->addKey($table, 'date_creation');
            $migration->migrationOneTable($table);
        }
    }
    /************** Enhance Associated items for ticket ***************/
    // TEMPLATE UPDATE
    $migration->dropKey('glpi_tickettemplatepredefinedfields', 'unicity');
    // Get associated item searchoption num
    if (!isset($CFG_GLPI["use_rich_text"])) {
        $CFG_GLPI["use_rich_text"] = false;
    }
    $searchOption = Search::getOptions('Ticket');
    $item_num = 0;
    $itemtype_num = 0;
    foreach ($searchOption as $num => $option) {
        if (is_array($option)) {
            if ($option['field'] == 'items_id') {
                $item_num = $num;
            } else {
                if ($option['field'] == 'itemtype') {
                    $itemtype_num = $num;
                }
            }
        }
    }
    foreach (array('glpi_tickettemplatepredefinedfields', 'glpi_tickettemplatehiddenfields', 'glpi_tickettemplatemandatoryfields') as $table) {
        $columns = array();
        switch ($table) {
            case 'glpi_tickettemplatepredefinedfields':
                $columns = array('num', 'value', 'tickettemplates_id');
                break;
            default:
                $columns = array('num', 'tickettemplates_id');
                break;
        }
        $query = "SELECT `" . implode('`,`', $columns) . "`\n                FROM `{$table}`\n                WHERE `num` = '{$item_num}'\n                      OR `num` = '{$itemtype_num}';";
        $items_to_update = array();
        if ($result = $DB->query($query)) {
            if ($DB->numrows($result) > 0) {
                while ($data = $DB->fetch_assoc($result)) {
                    if ($data['num'] == $itemtype_num) {
                        $items_to_update[$data['tickettemplates_id']]['itemtype'] = isset($data['value']) ? $data['value'] : 0;
                    } else {
                        if ($data['num'] == $item_num) {
                            $items_to_update[$data['tickettemplates_id']]['items_id'] = isset($data['value']) ? $data['value'] : 0;
                        }
                    }
                }
            }
        }
        switch ($table) {
            case 'glpi_tickettemplatepredefinedfields':
                // Update predefined items
                foreach ($items_to_update as $templates_id => $type) {
                    if (isset($type['itemtype'])) {
                        if (isset($type['items_id'])) {
                            $DB->queryOrDie("UPDATE `{$table}`\n                                      SET `value` = '" . $type['itemtype'] . "_" . $type['items_id'] . "'\n                                      WHERE `num` = '" . $item_num . "'\n                                      AND `tickettemplates_id` = '" . $templates_id . "'", "Associated items migration : update predefined items");
                            $DB->queryOrDie("DELETE FROM `{$table}`\n                                      WHERE `num` = '" . $itemtype_num . "'\n                                            AND `tickettemplates_id` = '" . $templates_id . "'", "Associated items migration : delete {$table} itemtypes");
                        }
                    }
                }
                break;
            default:
                // Update mandatory and hidden items
                foreach ($items_to_update as $templates_id => $type) {
                    if (isset($type['itemtype'])) {
                        if (isset($type['items_id'])) {
                            $DB->queryOrDie("DELETE FROM `{$table}`\n                                      WHERE `num` = '" . $item_num . "'\n                                            AND `tickettemplates_id` = '" . $templates_id . "'", "Associated items migration : delete {$table} itemtypes");
                        }
                        $DB->queryOrDie("UPDATE `{$table}`\n                                   SET `num` = '" . $item_num . "'\n                                   WHERE `num` = '" . $itemtype_num . "'\n                                         AND `tickettemplates_id` = '" . $templates_id . "'", "Associated items migration : delete {$table} itemtypes");
                    }
                }
                break;
        }
    }
    /************** Add more fields to software licenses */
    $new = $migration->addField("glpi_softwarelicenses", "is_deleted", "bool");
    $migration->addField("glpi_softwarelicenses", "locations_id", "integer");
    $migration->addField("glpi_softwarelicenses", "users_id_tech", "integer");
    $migration->addField("glpi_softwarelicenses", "users_id", "integer");
    $migration->addField("glpi_softwarelicenses", "groups_id_tech", "integer");
    $migration->addField("glpi_softwarelicenses", "groups_id", "integer");
    $migration->addField("glpi_softwarelicenses", "is_helpdesk_visible", "bool");
    $migration->addField("glpi_softwarelicenses", "is_template", "bool");
    $migration->addField("glpi_softwarelicenses", "template_name", "string");
    $migration->addKey("glpi_softwarelicenses", "locations_id");
    $migration->addKey("glpi_softwarelicenses", "users_id_tech");
    $migration->addKey("glpi_softwarelicenses", "users_id");
    $migration->addKey("glpi_softwarelicenses", "groups_id_tech");
    $migration->addKey("glpi_softwarelicenses", "groups_id");
    $migration->addKey("glpi_softwarelicenses", "is_helpdesk_visible");
    $migration->addKey("glpi_softwarelicenses", "is_deleted");
    $migration->addKey("glpi_softwarelicenses", "is_template");
    /************* Add antivirus table */
    if (!TableExists('glpi_computerantiviruses')) {
        $query = "CREATE TABLE `glpi_computerantiviruses` (\n        `id` int(11) NOT NULL AUTO_INCREMENT,\n        `computers_id` int(11) NOT NULL DEFAULT '0',\n        `name` varchar(255) DEFAULT NULL,\n        `manufacturers_id` int(11) NOT NULL DEFAULT '0',\n        `antivirus_version` varchar(255) DEFAULT NULL,\n        `signature_version` varchar(255) DEFAULT NULL,\n        `is_active` tinyint(1) NOT NULL DEFAULT '0',\n        `is_deleted` tinyint(1) NOT NULL DEFAULT '0',\n        `is_uptodate` tinyint(1) NOT NULL DEFAULT '0',\n        `is_dynamic` tinyint(1) NOT NULL DEFAULT '0',\n        `date_expiration` datetime DEFAULT NULL,\n        `date_mod` datetime DEFAULT NULL,\n        `date_creation` datetime DEFAULT NULL,\n        PRIMARY KEY (`id`),\n        KEY `name` (`name`),\n        KEY `antivirus_version` (`antivirus_version`),\n        KEY `signature_version` (`signature_version`),\n        KEY `is_active` (`is_active`),\n        KEY `is_uptodate` (`is_uptodate`),\n        KEY `is_dynamic` (`is_dynamic`),\n        KEY `is_deleted` (`is_deleted`),\n        KEY `computers_id` (`computers_id`),\n        KEY `date_expiration` (`date_expiration`),\n        KEY `date_mod` (`date_mod`),\n        KEY `date_creation` (`date_creation`)\n      ) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1;";
        $DB->queryOrDie($query, "Add antivirus table");
    }
    if ($new) {
        //new right for software license
        //copy the software right value to the new license right
        foreach ($DB->request("glpi_profilerights", "`name` = 'software'") as $profrights) {
            $query = "INSERT INTO `glpi_profilerights`\n                          (`id`, `profiles_id`, `name`, `rights`)\n                   VALUES (NULL, '" . $profrights['profiles_id'] . "', 'license',\n                           '" . $profrights['rights'] . "')";
            $DB->queryOrDie($query, "9.1 add right for softwarelicense");
        }
    }
    //new right for survey
    foreach ($DB->request("glpi_profilerights", "`name` = 'ticket'") as $profrights) {
        $query = "UPDATE `glpi_profilerights`\n                SET `rights` = `rights` | " . Ticket::SURVEY . "\n                WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                       AND `name` = 'ticket'";
        $DB->queryOrDie($query, "9.1 update ticket with survey right");
    }
    //TRANS: %s is the table or item to migrate
    $migration->displayMessage(sprintf(__('Data migration - %s'), 'glpi_displaypreferences'));
    $ADDTODISPLAYPREF['SoftwareLicense'] = array(3, 10, 162, 5);
    foreach ($ADDTODISPLAYPREF as $type => $tab) {
        $query = "SELECT DISTINCT `users_id`\n                FROM `glpi_displaypreferences`\n                WHERE `itemtype` = '{$type}'";
        if ($result = $DB->query($query)) {
            if ($DB->numrows($result) > 0) {
                while ($data = $DB->fetch_assoc($result)) {
                    $query = "SELECT MAX(`rank`)\n                         FROM `glpi_displaypreferences`\n                         WHERE `users_id` = '" . $data['users_id'] . "'\n                               AND `itemtype` = '{$type}'";
                    $result = $DB->query($query);
                    $rank = $DB->result($result, 0, 0);
                    $rank++;
                    foreach ($tab as $newval) {
                        $query = "SELECT *\n                            FROM `glpi_displaypreferences`\n                            WHERE `users_id` = '" . $data['users_id'] . "'\n                                  AND `num` = '{$newval}'\n                                  AND `itemtype` = '{$type}'";
                        if ($result2 = $DB->query($query)) {
                            if ($DB->numrows($result2) == 0) {
                                $query = "INSERT INTO `glpi_displaypreferences`\n                                         (`itemtype` ,`num` ,`rank` ,`users_id`)\n                                  VALUES ('{$type}', '{$newval}', '" . $rank++ . "',\n                                          '" . $data['users_id'] . "')";
                                $DB->query($query);
                            }
                        }
                    }
                }
            } else {
                // Add for default user
                $rank = 1;
                foreach ($tab as $newval) {
                    $query = "INSERT INTO `glpi_displaypreferences`\n                                (`itemtype` ,`num` ,`rank` ,`users_id`)\n                         VALUES ('{$type}', '{$newval}', '" . $rank++ . "', '0')";
                    $DB->query($query);
                }
            }
        }
    }
    /** ************ New SLA structure ************ */
    if (!TableExists('glpi_slts')) {
        $query = "CREATE TABLE `glpi_slts` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `name` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n                  `entities_id` int(11) NOT NULL DEFAULT '0',\n                  `is_recursive` tinyint(1) NOT NULL DEFAULT '0',\n                  `type` int(11) NOT NULL DEFAULT '0',\n                  `comment` text COLLATE utf8_unicode_ci,\n                  `resolution_time` int(11) NOT NULL,\n                  `calendars_id` int(11) NOT NULL DEFAULT '0',\n                  `date_mod` datetime DEFAULT NULL,\n                  `definition_time` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n                  `end_of_working_day` tinyint(1) NOT NULL DEFAULT '0',\n                  `date_creation` datetime DEFAULT NULL,\n                  `slas_id` int(11) NOT NULL DEFAULT '0',\n                  PRIMARY KEY (`id`),\n                  KEY `name` (`name`),\n                  KEY `calendars_id` (`calendars_id`),\n                  KEY `date_mod` (`date_mod`),\n                  KEY `date_creation` (`date_creation`),\n                  KEY `slas_id` (`slas_id`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;";
        $DB->queryOrDie($query, "0.91 add table glpi_slts");
        // Sla migration
        $query = "SELECT *\n                FROM `glpi_slas`";
        if ($result = $DB->query($query)) {
            if ($DB->numrows($result) > 0) {
                while ($data = $DB->fetch_assoc($result)) {
                    $query = "INSERT INTO `glpi_slts`\n                          (`id`, `name`,`entities_id`, `is_recursive`, `type`, `comment`, `resolution_time`, `calendars_id`, `date_mod`, `definition_time`, `end_of_working_day`, `date_creation`, `slas_id`)\n                         VALUES ('" . $data['id'] . "', '" . $data['name'] . "', '" . $data['entities_id'] . "', '" . $data['is_recursive'] . "', '" . SLT::TTR . "', '" . addslashes($data['comment']) . "', '" . $data['resolution_time'] . "', '" . $data['calendars_id'] . "', '" . $data['date_mod'] . "', '" . $data['definition_time'] . "', '" . $data['end_of_working_day'] . "', '" . date('Y-m-d H:i:s') . "', '" . $data['id'] . "');";
                    $DB->queryOrDie($query, "SLA migration to SLT");
                }
            }
        }
        // Delete deprecated fields of SLA
        foreach (array('resolution_time', 'calendars_id', 'definition_time', 'end_of_working_day') as $field) {
            $migration->dropField('glpi_slas', $field);
        }
        // Slalevels changes
        $migration->changeField('glpi_slalevels', 'slas_id', 'slts_id', 'integer');
        // Ticket changes
        $migration->changeField("glpi_tickets", "slas_id", "slt_ttr", "integer");
        $migration->addField("glpi_tickets", "slt_tto", "integer", array('after' => 'slt_ttr'));
        $migration->addField("glpi_tickets", "time_to_own", "datetime", array('after' => 'due_date'));
        $migration->addKey('glpi_tickets', 'slt_tto');
        $migration->addKey('glpi_tickets', 'time_to_own');
        // Unique key for slalevel_ticket
        $migration->addKey('glpi_slalevels_tickets', array('tickets_id', 'slalevels_id'), 'unicity', 'UNIQUE');
        // Sla rules criterias migration
        $DB->queryOrDie("UPDATE `glpi_rulecriterias` SET `criteria` = 'slt_ttr' WHERE `criteria` = 'slas_id'", "SLA rulecriterias migration");
        // Sla rules actions migration
        $DB->queryOrDie("UPDATE `glpi_ruleactions` SET `field` = 'slt_ttr' WHERE `field` = 'slas_id'", "SLA ruleactions migration");
    }
    /************** High contrast CSS **************/
    Config::setConfigurationValues('core', array('highcontrast_css' => 0));
    $migration->addField("glpi_users", "highcontrast_css", "tinyint(1) DEFAULT 0");
    // ************ Keep it at the end **************
    $migration->executeMigration();
    return $updateresult;
}
Example #7
0
 /**
  * @depends testInitSessionCredentials
  */
 public function testProtectedConfigSettings($session_token)
 {
     $sensitiveSettings = array('proxy_passwd', 'smtp_passwd');
     // set a non empty value to the sessionts to check
     foreach ($sensitiveSettings as $name) {
         Config::setConfigurationValues('core', array($name => 'not_empty_password'));
         $value = Config::getConfigurationValues('core', array($name));
         $this->assertArrayHasKey($name, $value);
         $this->assertNotEmpty($value[$name]);
     }
     $where = "'" . implode("', '", $sensitiveSettings) . "'";
     $config = new config();
     $rows = $config->find("`context`='core' AND `name` IN ({$where})");
     $this->assertEquals(count($sensitiveSettings), count($rows));
     // Check the value is not retrieved for sensitive settings
     foreach ($rows as $row) {
         $res = $this->doHttpRequest('GET', "Config/" . $row['id'], ['headers' => ['Session-Token' => $session_token]]);
         $this->assertEquals(200, $res->getStatusCode());
         $body = $res->getBody();
         $data = json_decode($body, true);
         $this->assertEquals('', $data['value']);
     }
     // Check an other setting is disclosed (when not empty)
     $config = new Config();
     $config->getFromDBByQuery("WHERE `context`='core' AND `name`='admin_email'");
     $res = $this->doHttpRequest('GET', "Config/" . $config->getID(), ['headers' => ['Session-Token' => $session_token]]);
     $this->assertEquals(200, $res->getStatusCode());
     $body = $res->getBody();
     $data = json_decode($body, true);
     $this->assertNotEquals('', $data['value']);
     // Check a search does not disclose sensitive values
     $criteria = array();
     $queryString = "";
     foreach ($rows as $row) {
         $queryString = "&criteria[][link]=or&criteria[][field]=1&criteria[][searchtype]=equals&criteria[][value]=" . $row['name'];
     }
     $res = $this->doHttpRequest('GET', "search/Config" . "?{$queryString}", ['headers' => ['Session-Token' => $session_token], 'query' => array()]);
     $this->assertEquals(200, $res->getStatusCode());
     $body = $res->getBody();
     $data = json_decode($body, true);
     foreach ($data['data'] as $row) {
         foreach ($row as $col) {
             $this->assertNotEquals($col, 'not_empty_password');
         }
     }
 }
Example #8
0
/**
 * Update from 0.85 to 0.85.3
 *
 * @return bool for success (will die for most error)
**/
function update085to0853()
{
    global $DB, $migration;
    $updateresult = true;
    $ADDTODISPLAYPREF = array();
    //TRANS: %s is the number of new version
    $migration->displayTitle(sprintf(__('Update to %s'), '0.85.3'));
    $migration->setVersion('0.85.3');
    $backup_tables = false;
    $newtables = array();
    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);
    }
    // Increase cron_limit
    $current_config = Config::getConfigurationValues('core');
    if ($current_config['cron_limit'] = 1) {
        Config::setConfigurationValues('core', array('cron_limit' => 5));
    }
    Config::setConfigurationValues('core', array('task_state' => Planning::TODO));
    $migration->addField("glpi_users", "task_state", "int(11) DEFAULT NULL");
    $migration->addField('glpi_projecttasks', 'is_milestone', 'bool');
    $migration->addKey('glpi_projecttasks', 'is_milestone');
    // Change Ticket items
    // Add glpi_items_tickets table for associated elements
    if (!TableExists('glpi_items_tickets')) {
        $query = "CREATE TABLE `glpi_items_tickets` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `itemtype` varchar(255) DEFAULT NULL,\n                  `items_id` int(11) NOT NULL DEFAULT '0',\n                  `tickets_id` int(11) NOT NULL DEFAULT '0',\n                  PRIMARY KEY (`id`),\n                  UNIQUE KEY `unicity` (`itemtype`, `items_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_items_tickets");
        $query = "SELECT `itemtype`, `items_id`, `id`\n                FROM `glpi_tickets`\n                WHERE `itemtype` IS NOT NULL\n                    AND `itemtype` <> ''\n                AND `items_id` != 0";
        if ($result = $DB->query($query)) {
            if ($DB->numrows($result) > 0) {
                while ($data = $DB->fetch_assoc($result)) {
                    $query = "INSERT INTO `glpi_items_tickets`\n                             (`id`, `items_id`, `itemtype`, `tickets_id`)\n                          VALUES (NULL, '" . $data['items_id'] . "', '" . $data['itemtype'] . "', '" . $data['id'] . "')";
                    $DB->queryOrDie($query, "0.85 associated ticket sitems migration");
                }
            }
        }
        // Delete old columns and keys
        $migration->dropField("glpi_tickets", "itemtype");
        $migration->dropField("glpi_tickets", "items_id");
        $migration->dropKey("glpi_tickets", "item");
    }
    // correct value of status for changes
    $query = "UPDATE `glpi_changes`\n             SET `status` = 1\n             WHERE `status` = 2";
    $DB->queryOrDie($query, "0.85.3 correct status for change");
    if ($migration->addField("glpi_entities", "is_notif_enable_default", "integer", array('value' => -2))) {
        $migration->migrationOneTable('glpi_entities');
        // Set directly to root entity
        $query = 'UPDATE `glpi_entities`
                SET `is_notif_enable_default` = 1
                WHERE `id` = 0';
        $DB->queryOrDie($query, "0.85.3 default value for is_notif_enable_default for root entity");
    }
    // ************ Keep it at the end **************
    //TRANS: %s is the table or item to migrate
    $migration->displayMessage(sprintf(__('Data migration - %s'), 'glpi_displaypreferences'));
    foreach ($ADDTODISPLAYPREF as $type => $tab) {
        $query = "SELECT DISTINCT `users_id`\n                FROM `glpi_displaypreferences`\n                WHERE `itemtype` = '{$type}'";
        if ($result = $DB->query($query)) {
            if ($DB->numrows($result) > 0) {
                while ($data = $DB->fetch_assoc($result)) {
                    $query = "SELECT MAX(`rank`)\n                         FROM `glpi_displaypreferences`\n                         WHERE `users_id` = '" . $data['users_id'] . "'\n                               AND `itemtype` = '{$type}'";
                    $result = $DB->query($query);
                    $rank = $DB->result($result, 0, 0);
                    $rank++;
                    foreach ($tab as $newval) {
                        $query = "SELECT *\n                            FROM `glpi_displaypreferences`\n                            WHERE `users_id` = '" . $data['users_id'] . "'\n                                  AND `num` = '{$newval}'\n                                  AND `itemtype` = '{$type}'";
                        if ($result2 = $DB->query($query)) {
                            if ($DB->numrows($result2) == 0) {
                                $query = "INSERT INTO `glpi_displaypreferences`\n                                         (`itemtype` ,`num` ,`rank` ,`users_id`)\n                                  VALUES ('{$type}', '{$newval}', '" . $rank++ . "',\n                                          '" . $data['users_id'] . "')";
                                $DB->query($query);
                            }
                        }
                    }
                }
            } else {
                // Add for default user
                $rank = 1;
                foreach ($tab as $newval) {
                    $query = "INSERT INTO `glpi_displaypreferences`\n                                (`itemtype` ,`num` ,`rank` ,`users_id`)\n                         VALUES ('{$type}', '{$newval}', '" . $rank++ . "', '0')";
                    $DB->query($query);
                }
            }
        }
    }
    // change type of field solution in ticket.change and problem
    $migration->changeField('glpi_tickets', 'solution', 'solution', 'longtext');
    $migration->changeField('glpi_changes', 'solution', 'solution', 'longtext');
    $migration->changeField('glpi_problems', 'solution', 'solution', 'longtext');
    // must always be at the end
    $migration->executeMigration();
    return $updateresult;
}
Example #9
0
/**
 * Update from 0.85.3 to 0.90
 *
 * @return bool for success (will die for most error)
**/
function update0853to090()
{
    global $DB, $migration;
    $updateresult = true;
    $ADDTODISPLAYPREF = array();
    //TRANS: %s is the number of new version
    $migration->displayTitle(sprintf(__('Update to %s'), '0.90'));
    $migration->setVersion('0.90');
    $backup_tables = false;
    $newtables = array();
    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);
    }
    // For 0.85 svn
    if (!FieldExists("glpi_entities", 'inquest_duration')) {
        // Add duration for inquest (entity configuration)
        $migration->addField("glpi_entities", 'inquest_duration', "integer", array('value' => 0));
        // add validity period for users
        $migration->addKey('glpi_users', 'begin_date');
        $migration->addKey('glpi_users', 'end_date');
        // add validity period for kb items
        $migration->addKey('glpi_knowbaseitems', 'begin_date');
        $migration->addKey('glpi_knowbaseitems', 'end_date');
    }
    // Add Color selector
    Config::setConfigurationValues('core', array('palette' => 'auror'));
    $migration->addField("glpi_users", "palette", "char(20) DEFAULT NULL");
    // add layout config
    Config::setConfigurationValues('core', array('layout' => 'lefttab'));
    $migration->addField("glpi_users", "layout", "char(20) DEFAULT NULL");
    // add timeline config
    Config::setConfigurationValues('core', array('ticket_timeline' => 1));
    Config::setConfigurationValues('core', array('ticket_timeline_keep_replaced_tabs' => 0));
    $migration->addField("glpi_users", "ticket_timeline", "tinyint(1) DEFAULT NULL");
    $migration->addField("glpi_users", "ticket_timeline_keep_replaced_tabs", "tinyint(1) DEFAULT NULL");
    // ************ Keep it at the end **************
    //TRANS: %s is the table or item to migrate
    $migration->displayMessage(sprintf(__('Data migration - %s'), 'glpi_displaypreferences'));
    foreach ($ADDTODISPLAYPREF as $type => $tab) {
        $query = "SELECT DISTINCT `users_id`\n                FROM `glpi_displaypreferences`\n                WHERE `itemtype` = '{$type}'";
        if ($result = $DB->query($query)) {
            if ($DB->numrows($result) > 0) {
                while ($data = $DB->fetch_assoc($result)) {
                    $query = "SELECT MAX(`rank`)\n                         FROM `glpi_displaypreferences`\n                         WHERE `users_id` = '" . $data['users_id'] . "'\n                               AND `itemtype` = '{$type}'";
                    $result = $DB->query($query);
                    $rank = $DB->result($result, 0, 0);
                    $rank++;
                    foreach ($tab as $newval) {
                        $query = "SELECT *\n                            FROM `glpi_displaypreferences`\n                            WHERE `users_id` = '" . $data['users_id'] . "'\n                                  AND `num` = '{$newval}'\n                                  AND `itemtype` = '{$type}'";
                        if ($result2 = $DB->query($query)) {
                            if ($DB->numrows($result2) == 0) {
                                $query = "INSERT INTO `glpi_displaypreferences`\n                                         (`itemtype` ,`num` ,`rank` ,`users_id`)\n                                  VALUES ('{$type}', '{$newval}', '" . $rank++ . "',\n                                          '" . $data['users_id'] . "')";
                                $DB->query($query);
                            }
                        }
                    }
                }
            } else {
                // Add for default user
                $rank = 1;
                foreach ($tab as $newval) {
                    $query = "INSERT INTO `glpi_displaypreferences`\n                                (`itemtype` ,`num` ,`rank` ,`users_id`)\n                         VALUES ('{$type}', '{$newval}', '" . $rank++ . "', '0')";
                    $DB->query($query);
                }
            }
        }
    }
    // change type of field solution in ticket.change and problem
    $migration->changeField('glpi_tickets', 'solution', 'solution', 'longtext');
    $migration->changeField('glpi_changes', 'solution', 'solution', 'longtext');
    $migration->changeField('glpi_problems', 'solution', 'solution', 'longtext');
    // must always be at the end
    $migration->executeMigration();
    return $updateresult;
}
Example #10
0
function plugin_example_install()
{
    global $DB;
    $config = new Config();
    $config->setConfigurationValues('plugin:Example', array('configuration' => false));
    ProfileRight::addProfileRights(array('example:read'));
    if (!TableExists("glpi_plugin_example_examples")) {
        $query = "CREATE TABLE `glpi_plugin_example_examples` (\n                  `id` int(11) NOT NULL auto_increment,\n                  `name` varchar(255) collate utf8_unicode_ci default NULL,\n                  `serial` varchar(255) collate utf8_unicode_ci NOT NULL,\n                  `plugin_example_dropdowns_id` int(11) NOT NULL default '0',\n                  `is_deleted` tinyint(1) NOT NULL default '0',\n                  `is_template` tinyint(1) NOT NULL default '0',\n                  `template_name` varchar(255) collate utf8_unicode_ci default NULL,\n                PRIMARY KEY (`id`)\n               ) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->query($query) or die("error creating glpi_plugin_example_examples " . $DB->error());
        $query = "INSERT INTO `glpi_plugin_example_examples`\n                       (`id`, `name`, `serial`, `plugin_example_dropdowns_id`, `is_deleted`,\n                        `is_template`, `template_name`)\n                VALUES (1, 'example 1', 'serial 1', 1, 0, 0, NULL),\n                       (2, 'example 2', 'serial 2', 2, 0, 0, NULL),\n                       (3, 'example 3', 'serial 3', 1, 0, 0, NULL)";
        $DB->query($query) or die("error populate glpi_plugin_example " . $DB->error());
    }
    if (!TableExists("glpi_plugin_example_dropdowns")) {
        $query = "CREATE TABLE `glpi_plugin_example_dropdowns` (\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->query($query) or die("error creating glpi_plugin_example_dropdowns" . $DB->error());
        $query = "INSERT INTO `glpi_plugin_example_dropdowns`\n                       (`id`, `name`, `comment`)\n                VALUES (1, 'dp 1', 'comment 1'),\n                       (2, 'dp2', 'comment 2')";
        $DB->query($query) or die("error populate glpi_plugin_example_dropdowns" . $DB->error());
    }
    if (!TableExists('glpi_plugin_example_devicecameras')) {
        $query = "CREATE TABLE `glpi_plugin_example_devicecameras` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `designation` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n                  `comment` text COLLATE utf8_unicode_ci,\n                  `manufacturers_id` int(11) NOT NULL DEFAULT '0',\n                  PRIMARY KEY (`id`),\n                  KEY `designation` (`designation`),\n                  KEY `manufacturers_id` (`manufacturers_id`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->query($query) or die("error creating glpi_plugin_example_examples " . $DB->error());
    }
    if (!TableExists('glpi_plugin_example_items_devicecameras')) {
        $query = "CREATE TABLE `glpi_plugin_example_items_devicecameras` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `items_id` int(11) NOT NULL DEFAULT '0',\n                  `itemtype` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n                  `plugin_example_devicecameras_id` int(11) NOT NULL DEFAULT '0',\n                  `is_deleted` tinyint(1) NOT NULL DEFAULT '0',\n                  `is_dynamic` tinyint(1) NOT NULL DEFAULT '0',\n                  PRIMARY KEY (`id`),\n                  KEY `computers_id` (`items_id`),\n                  KEY `plugin_example_devicecameras_id` (`plugin_example_devicecameras_id`),\n                  KEY `is_deleted` (`is_deleted`),\n                  KEY `is_dynamic` (`is_dynamic`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->query($query) or die("error creating glpi_plugin_example_examples " . $DB->error());
    }
    // To be called for each task the plugin manage
    // task in class
    CronTask::Register('PluginExampleExample', 'Sample', DAY_TIMESTAMP, array('param' => 50));
    return true;
}
Example #11
0
function loadDataset()
{
    global $CFG_GLPI;
    // Unit test data definition
    $data = ['_version' => 2, 'Entity' => [['name' => '_test_root_entity', 'entities_id' => 0], ['name' => '_test_child_1', 'entities_id' => '_test_root_entity'], ['name' => '_test_child_2', 'entities_id' => '_test_root_entity']], 'Computer' => [['name' => '_test_pc01', 'entities_id' => '_test_root_entity'], ['name' => '_test_pc02', 'entities_id' => '_test_root_entity'], ['name' => '_test_pc11', 'entities_id' => '_test_child_1'], ['name' => '_test_pc12', 'entities_id' => '_test_child_1'], ['name' => '_test_pc21', 'entities_id' => '_test_child_2'], ['name' => '_test_pc22', 'entities_id' => '_test_child_2']], 'Software' => [['name' => '_test_soft', 'entities_id' => '_test_root_entity', 'is_recursive' => 1]], 'SoftwareVersion' => [['name' => '_test_softver_1', 'entities_id' => '_test_root_entity', 'is_recursive' => 1, 'softwares_id' => '_test_soft'], ['name' => '_test_softver_2', 'entities_id' => '_test_root_entity', 'is_recursive' => 1, 'softwares_id' => '_test_soft']], 'Printer' => [['name' => '_test_printer_all', 'entities_id' => '_test_root_entity', 'is_recursive' => 1], ['name' => '_test_printer_ent0', 'entities_id' => '_test_root_entity', 'is_recursive' => 0], ['name' => '_test_printer_ent1', 'entities_id' => '_test_child_1', 'is_recursive' => 0], ['name' => '_test_printer_ent2', 'entities_id' => '_test_child_2', 'is_recursive' => 0]], 'User' => [['name' => TU_USER, 'password' => TU_PASS, 'password2' => TU_PASS, 'entities_id' => '_test_root_entity', 'profiles_id' => 4, '_entities_id' => '_test_root_entity', '_profiles_id' => 4, '_is_recursive' => 1]]];
    // To bypass various right checks
    $_SESSION['glpicronuserrunning'] = "cron_phpunit";
    $_SESSION['glpi_use_mode'] = Session::NORMAL_MODE;
    $CFG_GLPI['root_doc'] = '/glpi';
    // need to set theses in DB, because tests for API use http call and this bootstrap file is not called
    Config::setConfigurationValues('core', ['url_base' => GLPI_URI, 'url_base_api' => GLPI_URI . '/apirest.php']);
    $CFG_GLPI['url_base'] = GLPI_URI;
    $CFG_GLPI['url_base_api'] = GLPI_URI . '/apirest.php';
    @mkdir(GLPI_LOG_DIR, 0755, true);
    $conf = Config::getConfigurationValues('phpunit');
    if (isset($conf['dataset']) && $conf['dataset'] == $data['_version']) {
        printf("\nGLPI dataset version %d already loaded\n\n", $data['_version']);
    } else {
        printf("\nLoading GLPI dataset version %d\n", $data['_version']);
        $ids = array();
        foreach ($data as $type => $inputs) {
            if ($type[0] == '_') {
                continue;
            }
            foreach ($inputs as $input) {
                // Resolve FK
                foreach ($input as $k => $v) {
                    if (isForeignKeyField($k) && isset($ids[$v]) && !is_numeric($v)) {
                        $input[$k] = $ids[$v];
                    }
                }
                if (isset($input['name']) && ($item = getItemByTypeName($type, $input['name']))) {
                    $input['id'] = $ids[$input['name']] = $item->getField('id');
                    $item->update($input);
                    echo ".";
                } else {
                    // Not found, create it
                    $item = getItemForItemtype($type);
                    $id = $item->add($input);
                    echo "+";
                    if (isset($input['name'])) {
                        $ids[$input['name']] = $id;
                    }
                }
            }
        }
        echo "\nDone\n\n";
        Config::setConfigurationValues('phpunit', ['dataset' => $data['_version']]);
    }
}
Example #12
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;
}
Example #13
0
 /**
  * Create the GLPI default schema
  *
  * @since 9.1
  *
  * @param $lang
  *
  * @return nothing
  **/
 static function createSchema($lang = 'en_GB')
 {
     global $CFG_GLPI, $DB;
     include_once GLPI_CONFIG_DIR . "/config_db.php";
     $DB = new DB();
     if (!$DB->runFile(GLPI_ROOT . "/install/mysql/glpi-" . GLPI_SCHEMA_VERSION . "-empty.sql")) {
         echo "Errors occurred inserting default database";
     }
     // update default language
     Config::setConfigurationValues('core', array('language' => $lang));
     $query = "UPDATE `glpi_users`\n                SET `language` = NULL";
     $DB->queryOrDie($query, "4203");
     if (defined('GLPI_SYSTEM_CRON')) {
         // Downstream packages may provide a good system cron
         $query = "UPDATE `glpi_crontasks` SET `mode`=2 WHERE `name`!='watcher' AND (`allowmode` & 2)";
         $DB->queryOrDie($query, "4203");
     }
 }
Example #14
0
function loadDataset()
{
    global $CFG_GLPI;
    // Unit test data definition
    $data = ['_version' => 3, 'Entity' => [['name' => '_test_root_entity', 'entities_id' => 0], ['name' => '_test_child_1', 'entities_id' => '_test_root_entity'], ['name' => '_test_child_2', 'entities_id' => '_test_root_entity']], 'Computer' => [['name' => '_test_pc01', 'entities_id' => '_test_root_entity', 'comment' => 'Comment for computer _test_pc01'], ['name' => '_test_pc02', 'entities_id' => '_test_root_entity', 'comment' => 'Comment for computer _test_pc02'], ['name' => '_test_pc11', 'entities_id' => '_test_child_1'], ['name' => '_test_pc12', 'entities_id' => '_test_child_1'], ['name' => '_test_pc21', 'entities_id' => '_test_child_2'], ['name' => '_test_pc22', 'entities_id' => '_test_child_2']], 'Software' => [['name' => '_test_soft', 'entities_id' => '_test_root_entity', 'is_recursive' => 1]], 'SoftwareVersion' => [['name' => '_test_softver_1', 'entities_id' => '_test_root_entity', 'is_recursive' => 1, 'softwares_id' => '_test_soft'], ['name' => '_test_softver_2', 'entities_id' => '_test_root_entity', 'is_recursive' => 1, 'softwares_id' => '_test_soft']], 'Printer' => [['name' => '_test_printer_all', 'entities_id' => '_test_root_entity', 'is_recursive' => 1], ['name' => '_test_printer_ent0', 'entities_id' => '_test_root_entity', 'is_recursive' => 0], ['name' => '_test_printer_ent1', 'entities_id' => '_test_child_1', 'is_recursive' => 0], ['name' => '_test_printer_ent2', 'entities_id' => '_test_child_2', 'is_recursive' => 0]], 'User' => [['name' => TU_USER, 'password' => TU_PASS, 'password2' => TU_PASS, 'entities_id' => '_test_root_entity', 'profiles_id' => 4, '_entities_id' => '_test_root_entity', '_profiles_id' => 4, '_is_recursive' => 1]], 'TaskCategory' => [['is_recursive' => 1, 'name' => '_cat_1', 'completename' => '_cat_1', 'comment' => 'Comment for category _cat_1', 'level' => 1], ['is_recursive' => 1, 'taskcategories_id' => '_cat_1', 'name' => '_subcat_1', 'completename' => '_cat_1 > _subcat_1', 'comment' => 'Comment for sub-category _subcat_1', 'level' => 2]], 'DropdownTranslation' => [['items_id' => '_cat_1', 'itemtype' => 'TaskCategory', 'language' => 'fr_FR', 'field' => 'name', 'value' => 'FR - _cat_1'], ['items_id' => '_cat_1', 'itemtype' => 'TaskCategory', 'language' => 'fr_FR', 'field' => 'comment', 'value' => 'FR - Commentaire pour catégorie _cat_1'], ['items_id' => '_subcat_1', 'itemtype' => 'TaskCategory', 'language' => 'fr_FR', 'field' => 'name', 'value' => 'FR - _subcat_1'], ['items_id' => '_subcat_1', 'itemtype' => 'TaskCategory', 'language' => 'fr_FR', 'field' => 'comment', 'value' => 'FR - Commentaire pour sous-catégorie _subcat_1']], 'Contact' => [['name' => '_contact01_name', 'firstname' => '_contact01_firstname', 'phone' => '0123456789', 'phone2' => '0123456788', 'mobile' => '0623456789', 'fax' => '0123456787', 'email' => '_contact01_firstname._contact01_name@glpi.com', 'comment' => 'Comment for contact _contact01_name']], 'Supplier' => [['name' => '_suplier01_name', 'phonenumber' => '0123456789', 'fax' => '0123456787', 'email' => 'info@_supplier01_name.com', 'comment' => 'Comment for supplier _suplier01_name']], 'Location' => [['name' => '_location01', 'comment' => 'Comment for location _location01']], 'Netpoint' => [['name' => '_netpoint01', 'locations_id' => '_location01', 'comment' => 'Comment for netpoint _netpoint01']], 'BudgetType' => [['name' => '_budgettype01', 'comment' => 'Comment for budgettype _budgettype01']], 'Budget' => [['name' => '_budget01', 'comment' => 'Comment for budget _budget01', 'locations_id' => '_location01', 'budgettypes_id' => '_budgettype01', 'begin_date' => '2016-10-18', 'end_date' => '2016-12-31']], 'Ticket' => [['name' => '_ticket01', 'content' => 'Content for ticket _ticket01', 'users_id_recipient' => TU_USER]], 'TicketTask' => [['tickets_id' => '_ticket01', 'taskcategories_id' => '_subcat_1', 'users_id' => TU_USER, 'content' => 'Task to be done', 'is_private' => 0, 'users_id_tech' => TU_USER, 'date' => '2016-10-19 11:50:50']], 'UserEmail' => [['users_id' => TU_USER, 'is_default' => '1', 'is_dynamic' => '0', 'email' => TU_USER . '@glpi.com']]];
    // To bypass various right checks
    $_SESSION['glpishowallentities'] = 1;
    $_SESSION['glpicronuserrunning'] = "cron_phpunit";
    $_SESSION['glpi_use_mode'] = Session::NORMAL_MODE;
    $CFG_GLPI['root_doc'] = '/glpi';
    // need to set theses in DB, because tests for API use http call and this bootstrap file is not called
    Config::setConfigurationValues('core', ['url_base' => GLPI_URI, 'url_base_api' => GLPI_URI . '/apirest.php']);
    $CFG_GLPI['url_base'] = GLPI_URI;
    $CFG_GLPI['url_base_api'] = GLPI_URI . '/apirest.php';
    is_dir(GLPI_LOG_DIR) or mkdir(GLPI_LOG_DIR, 0755, true);
    $conf = Config::getConfigurationValues('phpunit');
    if (isset($conf['dataset']) && $conf['dataset'] == $data['_version']) {
        printf("\nGLPI dataset version %d already loaded\n\n", $data['_version']);
    } else {
        printf("\nLoading GLPI dataset version %d\n", $data['_version']);
        $ids = array();
        foreach ($data as $type => $inputs) {
            if ($type[0] == '_') {
                continue;
            }
            foreach ($inputs as $input) {
                // Resolve FK
                foreach ($input as $k => $v) {
                    // $foreigntype = $type; // by default same type than current type (is the case of the dropdowns)
                    $foreigntype = false;
                    $match = array();
                    if (isForeignKeyField($k) && (preg_match("/(.*s)_id\$/", $k, $match) || preg_match("/(.*s)_id_/", $k, $match))) {
                        $foreigntype = array_pop($match);
                        $foreigntype = getItemTypeForTable("glpi_{$foreigntype}");
                    }
                    if ($foreigntype && isset($ids[$foreigntype][$v]) && !is_numeric($v)) {
                        $input[$k] = $ids[$foreigntype][$v];
                    } else {
                        if ($k == 'items_id' && isset($input['itemtype']) && isset($ids[$input['itemtype']][$v]) && !is_numeric($v)) {
                            $input[$k] = $ids[$input['itemtype']][$v];
                        } else {
                            if ($foreigntype && $foreigntype != 'UNKNOWN' && !is_numeric($v)) {
                                // not found in ids array, then must get it from DB
                                if ($obj = getItemByTypeName($foreigntype, $v)) {
                                    $input[$k] = $obj->getID();
                                }
                            }
                        }
                    }
                }
                if (isset($input['name']) && ($item = getItemByTypeName($type, $input['name']))) {
                    $input['id'] = $ids[$type][$input['name']] = $item->getField('id');
                    $item->update($input);
                    echo ".";
                } else {
                    // Not found, create it
                    $item = getItemForItemtype($type);
                    $id = $item->add($input);
                    echo "+";
                    if (isset($input['name'])) {
                        $ids[$type][$input['name']] = $id;
                    }
                }
            }
        }
        echo "\nDone\n\n";
        Config::setConfigurationValues('phpunit', ['dataset' => $data['_version']]);
    }
}
 /**
  * Set configuration value
  *
  * @param array $options
  */
 public static function setConfigValues($options)
 {
     Config::setConfigurationValues(self::$configContext, $options);
 }