Esempio n. 1
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                          '<p>##IFchange.storestatus=5##</p>\n<div>##lang.change.url## : <a href=\"##change.urlapprove##\">##change.urlapprove##</a></div>\n<div><span style=\"color: #888888;\"><strong><span style=\"text-decoration: underline;\">##lang.change.solvedate##</span></strong></span> : ##change.solvedate##<br /><span style=\"text-decoration: underline; color: #888888;\"><strong>##lang.change.solution.type##</strong></span> : ##change.solution.type##<br /><span style=\"text-decoration: underline; color: #888888;\"><strong>##lang.change.solution.description##</strong></span> : ##change.solution.description## ##ENDIFchange.storestatus##</div>\n<div>##ELSEchange.storestatus## ##lang.change.url## : <a href=\"##change.url##\">##change.url##</a> ##ENDELSEchange.storestatus##</div>\n<p class=\"description b\"><strong>##lang.change.description##</strong></p>\n<p><span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"> ##lang.change.title##</span> :##change.title## <br /> <span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"> ##lang.change.authors##</span> :##IFchange.authors## ##change.authors## ##ENDIFchange.authors##    ##ELSEchange.authors##--##ENDELSEchange.authors## <br /> <span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"> ##lang.change.creationdate##</span> :##change.creationdate## <br /> ##IFchange.assigntousers## <span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"> ##lang.change.assigntousers##</span> : ##change.assigntousers## ##ENDIFchange.assigntousers##<br /> <span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\">##lang.change.status## </span> : ##change.status##<br /> ##IFchange.assigntogroups## <span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"> ##lang.change.assigntogroups##</span> : ##change.assigntogroups## ##ENDIFchange.assigntogroups##<br /> <span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"> ##lang.change.urgency##</span> : ##change.urgency##<br /> <span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"> ##lang.change.impact##</span> : ##change.impact##<br /> <span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"> ##lang.change.priority##</span> : ##change.priority## <br />##IFchange.category##<span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\">##lang.change.category## </span> :##change.category##  ##ENDIFchange.category## ##ELSEchange.category##  ##lang.change.nocategoryassigned## ##ENDELSEchange.category##    <br /> <span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"> ##lang.change.content##</span> : ##change.content##</p>\n<p>##IFchange.storestatus=6##<br /><span style=\"text-decoration: underline;\"><strong><span style=\"color: #888888;\">##lang.change.solvedate##</span></strong></span> : ##change.solvedate##<br /><span style=\"color: #888888;\"><strong><span style=\"text-decoration: underline;\">##lang.change.solution.type##</span></strong></span> : ##change.solution.type##<br /><span style=\"text-decoration: underline; color: #888888;\"><strong>##lang.change.solution.description##</strong></span> : ##change.solution.description##<br />##ENDIFchange.storestatus##</p>\n<div class=\"description b\">##lang.change.numberofproblems## : ##change.numberofproblems##</div>\n<p>##FOREACHproblems##</p>\n<div><strong> [##problem.date##] <em>##lang.change.title## : <a href=\"##problem.url##\">##problem.title## </a></em></strong><br /> <span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"> </span><span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\">##lang.change.content## </span> ##problem.content##\n<p>##ENDFOREACHproblems##</p>\n<div class=\"description b\">##lang.change.numberoftasks## : ##change.numberoftasks##</div>\n<p>##FOREACHtasks##</p>\n<div class=\"description b\"><strong>[##task.date##] </strong><br /> <span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"> ##lang.task.author##</span> ##task.author##<br /> <span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"> ##lang.task.description##</span> ##task.description##<br /> <span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"> ##lang.task.time##</span> ##task.time##<br /> <span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"> ##lang.task.category##</span> ##task.category##</div>\n<p>##ENDFOREACHtasks##</p>\n</div>')";
            $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;
}
Esempio n. 2
0
/**
 * Update from 0.72.3 to 0.78
 *
 * @return bool for success (will die for most error)
**/
function update0723to078()
{
    global $DB, $migration;
    $updateresult = true;
    //TRANS: %s is the number of new version
    $migration->displayTitle(sprintf(__('Update to %s'), '0.78'));
    $migration->setVersion('0.78');
    //TRANS: %s is 'Clean DB : rename tables'
    $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'Clean DB : rename tables'));
    $changes = array();
    $glpi_tables = array('glpi_alerts' => 'glpi_alerts', 'glpi_auth_ldap' => 'glpi_authldaps', 'glpi_auth_ldap_replicate' => 'glpi_authldapreplicates', 'glpi_auth_mail' => 'glpi_authmails', 'glpi_dropdown_auto_update' => 'glpi_autoupdatesystems', 'glpi_bookmark' => 'glpi_bookmarks', 'glpi_display_default' => 'glpi_bookmarks_users', 'glpi_dropdown_budget' => 'glpi_budgets', 'glpi_cartridges' => 'glpi_cartridges', 'glpi_cartridges_type' => 'glpi_cartridgeitems', 'glpi_cartridges_assoc' => 'glpi_cartridges_printermodels', 'glpi_dropdown_cartridge_type' => 'glpi_cartridgeitemtypes', 'glpi_computers' => 'glpi_computers', 'glpi_computerdisks' => 'glpi_computerdisks', 'glpi_dropdown_model' => 'glpi_computermodels', 'glpi_type_computers' => 'glpi_computertypes', 'glpi_connect_wire' => 'glpi_computers_items', 'glpi_inst_software' => 'glpi_computers_softwareversions', 'glpi_config' => 'glpi_configs', 'glpi_consumables' => 'glpi_consumables', 'glpi_consumables_type' => 'glpi_consumableitems', 'glpi_dropdown_consumable_type' => 'glpi_consumableitemtypes', 'glpi_contact_enterprise' => 'glpi_contacts_suppliers', 'glpi_contacts' => 'glpi_contacts', 'glpi_dropdown_contact_type' => 'glpi_contacttypes', 'glpi_contracts' => 'glpi_contracts', 'glpi_dropdown_contract_type' => 'glpi_contracttypes', 'glpi_contract_device' => 'glpi_contracts_items', 'glpi_contract_enterprise' => 'glpi_contracts_suppliers', 'glpi_device_case' => 'glpi_devicecases', 'glpi_dropdown_case_type' => 'glpi_devicecasetypes', 'glpi_device_control' => 'glpi_devicecontrols', 'glpi_device_drive' => 'glpi_devicedrives', 'glpi_device_gfxcard' => 'glpi_devicegraphiccards', 'glpi_device_hdd' => 'glpi_deviceharddrives', 'glpi_device_iface' => 'glpi_devicenetworkcards', 'glpi_device_moboard' => 'glpi_devicemotherboards', 'glpi_device_pci' => 'glpi_devicepcis', 'glpi_device_power' => 'glpi_devicepowersupplies', 'glpi_device_processor' => 'glpi_deviceprocessors', 'glpi_device_ram' => 'glpi_devicememories', 'glpi_dropdown_ram_type' => 'glpi_devicememorytypes', 'glpi_device_sndcard' => 'glpi_devicesoundcards', 'glpi_display' => 'glpi_displaypreferences', 'glpi_docs' => 'glpi_documents', 'glpi_dropdown_rubdocs' => 'glpi_documentcategories', 'glpi_type_docs' => 'glpi_documenttypes', 'glpi_doc_device' => 'glpi_documents_items', 'glpi_dropdown_domain' => 'glpi_domains', 'glpi_entities' => 'glpi_entities', 'glpi_entities_data' => 'glpi_entitydatas', 'glpi_event_log' => 'glpi_events', 'glpi_dropdown_filesystems' => 'glpi_filesystems', 'glpi_groups' => 'glpi_groups', 'glpi_users_groups' => 'glpi_groups_users', 'glpi_infocoms' => 'glpi_infocoms', 'glpi_dropdown_interface' => 'glpi_interfacetypes', 'glpi_kbitems' => 'glpi_knowbaseitems', 'glpi_dropdown_kbcategories' => 'glpi_knowbaseitemcategories', 'glpi_links' => 'glpi_links', 'glpi_links_device' => 'glpi_links_itemtypes', 'glpi_dropdown_locations' => 'glpi_locations', 'glpi_history' => 'glpi_logs', 'glpi_mailgate' => 'glpi_mailcollectors', 'glpi_mailing' => 'glpi_mailingsettings', 'glpi_dropdown_manufacturer' => 'glpi_manufacturers', 'glpi_monitors' => 'glpi_monitors', 'glpi_dropdown_model_monitors' => 'glpi_monitormodels', 'glpi_type_monitors' => 'glpi_monitortypes', 'glpi_dropdown_netpoint' => 'glpi_netpoints', 'glpi_networking' => 'glpi_networkequipments', 'glpi_dropdown_firmware' => 'glpi_networkequipmentfirmwares', 'glpi_dropdown_model_networking' => 'glpi_networkequipmentmodels', 'glpi_type_networking' => 'glpi_networkequipmenttypes', 'glpi_dropdown_iface' => 'glpi_networkinterfaces', 'glpi_networking_ports' => 'glpi_networkports', 'glpi_networking_vlan' => 'glpi_networkports_vlans', 'glpi_networking_wire' => 'glpi_networkports_networkports', 'glpi_dropdown_network' => 'glpi_networks', 'glpi_ocs_admin_link' => 'glpi_ocsadmininfoslinks', 'glpi_ocs_link' => 'glpi_ocslinks', 'glpi_ocs_config' => 'glpi_ocsservers', 'glpi_dropdown_os' => 'glpi_operatingsystems', 'glpi_dropdown_os_sp' => 'glpi_operatingsystemservicepacks', 'glpi_dropdown_os_version' => 'glpi_operatingsystemversions', 'glpi_peripherals' => 'glpi_peripherals', 'glpi_dropdown_model_peripherals' => 'glpi_peripheralmodels', 'glpi_type_peripherals' => 'glpi_peripheraltypes', 'glpi_phones' => 'glpi_phones', 'glpi_dropdown_model_phones' => 'glpi_phonemodels', 'glpi_dropdown_phone_power' => 'glpi_phonepowersupplies', 'glpi_type_phones' => 'glpi_phonetypes', 'glpi_plugins' => 'glpi_plugins', 'glpi_printers' => 'glpi_printers', 'glpi_dropdown_model_printers' => 'glpi_printermodels', 'glpi_type_printers' => 'glpi_printertypes', 'glpi_profiles' => 'glpi_profiles', 'glpi_users_profiles' => 'glpi_profiles_users', 'glpi_registry' => 'glpi_registrykeys', 'glpi_reminder' => 'glpi_reminders', 'glpi_reservation_resa' => 'glpi_reservations', 'glpi_reservation_item' => 'glpi_reservationitems', 'glpi_rules_descriptions' => 'glpi_rules', 'glpi_rules_actions' => 'glpi_ruleactions', 'glpi_rule_cache_model_computer' => 'glpi_rulecachecomputermodels', 'glpi_rule_cache_type_computer' => 'glpi_rulecachecomputertypes', 'glpi_rule_cache_manufacturer' => 'glpi_rulecachemanufacturers', 'glpi_rule_cache_model_monitor' => 'glpi_rulecachemonitormodels', 'glpi_rule_cache_type_monitor' => 'glpi_rulecachemonitortypes', 'glpi_rule_cache_model_networking' => 'glpi_rulecachenetworkequipmentmodels', 'glpi_rule_cache_type_networking' => 'glpi_rulecachenetworkequipmenttypes', 'glpi_rule_cache_os' => 'glpi_rulecacheoperatingsystems', 'glpi_rule_cache_os_sp' => 'glpi_rulecacheoperatingsystemservicepacks', 'glpi_rule_cache_os_version' => 'glpi_rulecacheoperatingsystemversions', 'glpi_rule_cache_model_peripheral' => 'glpi_rulecacheperipheralmodels', 'glpi_rule_cache_type_peripheral' => 'glpi_rulecacheperipheraltypes', 'glpi_rule_cache_model_phone' => 'glpi_rulecachephonemodels', 'glpi_rule_cache_type_phone' => 'glpi_rulecachephonetypes', 'glpi_rule_cache_model_printer' => 'glpi_rulecacheprintermodels', 'glpi_rule_cache_type_printer' => 'glpi_rulecacheprintertypes', 'glpi_rule_cache_software' => 'glpi_rulecachesoftwares', 'glpi_rules_criterias' => 'glpi_rulecriterias', 'glpi_rules_ldap_parameters' => 'glpi_rulerightparameters', 'glpi_software' => 'glpi_softwares', 'glpi_dropdown_software_category' => 'glpi_softwarecategories', 'glpi_softwarelicenses' => 'glpi_softwarelicenses', 'glpi_dropdown_licensetypes' => 'glpi_softwarelicensetypes', 'glpi_softwareversions' => 'glpi_softwareversions', 'glpi_dropdown_state' => 'glpi_states', 'glpi_enterprises' => 'glpi_suppliers', 'glpi_dropdown_enttype' => 'glpi_suppliertypes', 'glpi_tracking' => 'glpi_tickets', 'glpi_dropdown_tracking_category' => 'glpi_ticketcategories', 'glpi_followups' => 'glpi_ticketfollowups', 'glpi_tracking_planning' => 'glpi_ticketplannings', 'glpi_transfers' => 'glpi_transfers', 'glpi_users' => 'glpi_users', 'glpi_dropdown_user_titles' => 'glpi_usertitles', 'glpi_dropdown_user_types' => 'glpi_usercategories', 'glpi_dropdown_vlan' => 'glpi_vlans');
    $backup_tables = false;
    foreach ($glpi_tables as $original_table => $new_table) {
        if (strcmp($original_table, $new_table) != 0) {
            // Original table exists ?
            if (TableExists($original_table)) {
                // rename new tables if exists ?
                if (TableExists($new_table)) {
                    if (TableExists("backup_{$new_table}")) {
                        $query = "DROP TABLE `backup_" . $new_table . "`";
                        $DB->queryOrDie($query, "0.78 drop backup table backup_{$new_table}");
                    }
                    $migration->displayWarning("{$new_table} table already exists. " . "A backup have been done to backup_{$new_table}.");
                    $backup_tables = true;
                    $query = "RENAME TABLE `{$new_table}`\n                         TO `backup_{$new_table}`";
                    $DB->queryOrDie($query, "0.78 backup table {$new_table}");
                }
                // rename original table
                $query = "RENAME TABLE `{$original_table}`\n                      TO `{$new_table}`";
                $DB->queryOrDie($query, "0.78 rename {$original_table} to {$new_table}");
            }
        }
        if (FieldExists($new_table, 'ID', false)) {
            // ALTER ID -> id
            $changes[$new_table][] = "CHANGE `ID` `id` INT( 11 ) NOT NULL AUTO_INCREMENT";
        }
    }
    if ($backup_tables) {
        $migration->displayWarning("You can delete backup tables if you have no need of them.", true);
    }
    $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'Clean DB: rename foreign keys'));
    $foreignkeys = array('assign' => array(array('to' => 'users_id_assign', 'tables' => array('glpi_tickets'))), 'assign_group' => array(array('to' => 'groups_id_assign', 'tables' => array('glpi_tickets'))), 'assign_ent' => array(array('to' => 'suppliers_id_assign', 'tables' => array('glpi_tickets'))), 'auth_method' => array(array('to' => 'authtype', 'noindex' => array('glpi_users'), 'tables' => array('glpi_users'))), 'author' => array(array('to' => 'users_id', 'tables' => array('glpi_ticketfollowups', 'glpi_knowbaseitems', 'glpi_tickets'))), 'auto_update' => array(array('to' => 'autoupdatesystems_id', 'tables' => array('glpi_computers'))), 'budget' => array(array('to' => 'budgets_id', 'tables' => array('glpi_infocoms'))), 'buy_version' => array(array('to' => 'softwareversions_id_buy', 'tables' => array('glpi_softwarelicenses'))), 'category' => array(array('to' => 'ticketcategories_id', 'tables' => array('glpi_tickets')), array('to' => 'softwarecategories_id', 'tables' => array('glpi_softwares'))), 'categoryID' => array(array('to' => 'knowbaseitemcategories_id', 'tables' => array('glpi_knowbaseitems'))), 'category_on_software_delete' => array(array('to' => 'softwarecategories_id_ondelete', 'noindex' => array('glpi_configs'), 'tables' => array('glpi_configs'), 'comments' => array('glpi_configs' => 'category applyed when a software is deleted'))), 'cID' => array(array('to' => 'computers_id', 'tables' => array('glpi_computers_softwareversions'))), 'computer' => array(array('to' => 'items_id', 'noindex' => array('glpi_tickets'), 'tables' => array('glpi_tickets'))), 'computer_id' => array(array('to' => 'computers_id', 'tables' => array('glpi_registrykeys'))), 'contract_type' => array(array('to' => 'contracttypes_id', 'tables' => array('glpi_contracts'))), 'default_rubdoc_tracking' => array(array('to' => 'documentcategories_id_forticket', 'noindex' => array('glpi_configs'), 'tables' => array('glpi_configs'), 'comments' => array('glpi_configs' => 'default category for documents added with a ticket'))), 'default_state' => array(array('to' => 'states_id_default', 'noindex' => array('glpi_ocsservers'), 'tables' => array('glpi_ocsservers'))), 'device_type' => array(array('to' => 'itemtype', 'noindex' => array('glpi_alerts', 'glpi_contracts_items', 'glpi_bookmarks_users', 'glpi_documents_items', 'glpi_infocoms', 'glpi_links_itemtypes', 'glpi_networkports', 'glpi_reservationitems', 'glpi_tickets'), 'tables' => array('glpi_alerts', 'glpi_contracts_items', 'glpi_documents_items', 'glpi_infocoms', 'glpi_bookmarks', 'glpi_bookmarks_users', 'glpi_links_itemtypes', 'glpi_networkports', 'glpi_reservationitems', 'glpi_tickets'))), 'domain' => array(array('to' => 'domains_id', 'tables' => array('glpi_computers', 'glpi_networkequipments', 'glpi_printers'))), 'end1' => array(array('to' => 'items_id', 'noindex' => array('glpi_computers_items'), 'tables' => array('glpi_computers_items'), 'comments' => array('glpi_computers_items' => 'RELATION to various table, according to itemtype (ID)')), array('to' => 'networkports_id_1', 'noindex' => array('glpi_networkports_networkports'), 'tables' => array('glpi_networkports_networkports'))), 'end2' => array(array('to' => 'computers_id', 'tables' => array('glpi_computers_items')), array('to' => 'networkports_id_2', 'tables' => array('glpi_networkports_networkports'))), 'extra_ldap_server' => array(array('to' => 'authldaps_id_extra', 'noindex' => array('glpi_configs'), 'tables' => array('glpi_configs'), 'comments' => array('glpi_configs' => 'extra server'))), 'firmware' => array(array('to' => 'networkequipmentfirmwares_id', 'tables' => array('glpi_networkequipments'))), 'FK_bookmark' => array(array('to' => 'bookmarks_id', 'tables' => array('glpi_bookmarks_users'))), 'FK_computers' => array(array('to' => 'computers_id', 'tables' => array('glpi_computerdisks', 'glpi_softwarelicenses'))), 'FK_contact' => array(array('to' => 'contacts_id', 'tables' => array('glpi_contacts_suppliers'))), 'FK_contract' => array(array('to' => 'contracts_id', 'noindex' => array('glpi_contracts_items'), 'tables' => array('glpi_contracts_suppliers', 'glpi_contracts_items'))), 'FK_device' => array(array('to' => 'items_id', 'noindex' => array('glpi_alerts', 'glpi_contracts_items', 'glpi_documents_items', 'glpi_infocoms'), 'tables' => array('glpi_alerts', 'glpi_contracts_items', 'glpi_documents_items', 'glpi_infocoms'))), 'FK_doc' => array(array('to' => 'documents_id', 'noindex' => array('glpi_documents_items'), 'tables' => array('glpi_documents_items'))), 'FK_enterprise' => array(array('to' => 'suppliers_id', 'noindex' => array('glpi_contacts_suppliers', 'glpi_contracts_suppliers'), 'tables' => array('glpi_contacts_suppliers', 'glpi_contracts_suppliers', 'glpi_infocoms'))), 'FK_entities' => array(array('to' => 'entities_id', 'noindex' => array('glpi_locations', 'glpi_netpoints', 'glpi_entitydatas'), 'tables' => array('glpi_bookmarks', 'glpi_cartridgeitems', 'glpi_computers', 'glpi_consumableitems', 'glpi_contacts', 'glpi_contracts', 'glpi_documents', 'glpi_locations', 'glpi_netpoints', 'glpi_suppliers', 'glpi_entitydatas', 'glpi_groups', 'glpi_knowbaseitems', 'glpi_links', 'glpi_mailcollectors', 'glpi_monitors', 'glpi_networkequipments', 'glpi_peripherals', 'glpi_phones', 'glpi_printers', 'glpi_reminders', 'glpi_rules', 'glpi_softwares', 'glpi_softwarelicenses', 'glpi_tickets', 'glpi_users', 'glpi_profiles_users'), 'default' => array('glpi_bookmarks' => "-1"))), 'FK_filesystems' => array(array('to' => 'filesystems_id', 'tables' => array('glpi_computerdisks'))), 'FK_glpi_cartridges_type' => array(array('to' => 'cartridgeitems_id', 'tables' => array('glpi_cartridges', 'glpi_cartridges_printermodels'))), 'FK_glpi_consumables_type' => array(array('to' => 'consumableitems_id', 'noindex' => array(''), 'tables' => array('glpi_consumables'))), 'FK_glpi_dropdown_model_printers' => array(array('to' => 'printermodels_id', 'noindex' => array('glpi_cartridges_printermodels'), 'tables' => array('glpi_cartridges_printermodels'))), 'FK_glpi_enterprise' => array(array('to' => 'manufacturers_id', 'tables' => array('glpi_cartridgeitems', 'glpi_computers', 'glpi_consumableitems', 'glpi_devicecases', 'glpi_devicecontrols', 'glpi_devicedrives', 'glpi_devicegraphiccards', 'glpi_deviceharddrives', 'glpi_devicenetworkcards', 'glpi_devicemotherboards', 'glpi_devicepcis', 'glpi_devicepowersupplies', 'glpi_deviceprocessors', 'glpi_devicememories', 'glpi_devicesoundcards', 'glpi_monitors', 'glpi_networkequipments', 'glpi_peripherals', 'glpi_phones', 'glpi_printers', 'glpi_softwares'))), 'FK_glpi_printers' => array(array('to' => 'printers_id', 'tables' => array('glpi_cartridges'))), 'FK_group' => array(array('to' => 'groups_id', 'tables' => array('glpi_tickets'))), 'FK_groups' => array(array('to' => 'groups_id', 'tables' => array('glpi_computers', 'glpi_monitors', 'glpi_networkequipments', 'glpi_peripherals', 'glpi_phones', 'glpi_printers', 'glpi_softwares', 'glpi_groups_users'))), 'FK_interface' => array(array('to' => 'interfacetypes_id', 'tables' => array('glpi_devicegraphiccards'))), 'FK_item' => array(array('to' => 'items_id', 'noindex' => array('glpi_mailingsettings'), 'tables' => array('glpi_mailingsettings'))), 'FK_links' => array(array('to' => 'links_id', 'tables' => array('glpi_links_itemtypes'))), 'FK_port' => array(array('to' => 'networkports_id', 'noindex' => array('glpi_networkports_vlans'), 'tables' => array('glpi_networkports_vlans'))), 'FK_profiles' => array(array('to' => 'profiles_id', 'tables' => array('glpi_profiles_users', 'glpi_users'))), 'FK_rules' => array(array('to' => 'rules_id', 'tables' => array('glpi_rulecriterias', 'glpi_ruleactions'))), 'FK_tracking' => array(array('to' => 'tickets_id', 'tables' => array('glpi_documents'))), 'FK_users' => array(array('to' => 'users_id', 'noindex' => array('glpi_displaypreferences', 'glpi_bookmarks_users', 'glpi_groups_users'), 'tables' => array('glpi_bookmarks', 'glpi_displaypreferences', 'glpi_documents', 'glpi_groups', 'glpi_reminders', 'glpi_bookmarks_users', 'glpi_groups_users', 'glpi_profiles_users', 'glpi_computers', 'glpi_monitors', 'glpi_networkequipments', 'glpi_peripherals', 'glpi_phones', 'glpi_printers', 'glpi_softwares'))), 'FK_vlan' => array(array('to' => 'vlans_id', 'tables' => array('glpi_networkports_vlans'))), 'glpi_id' => array(array('to' => 'computers_id', 'tables' => array('glpi_ocslinks'))), 'id_assign' => array(array('to' => 'users_id', 'tables' => array('glpi_ticketplannings'))), 'id_auth' => array(array('to' => 'auths_id', 'noindex' => array('glpi_users'), 'tables' => array('glpi_users'))), 'id_device' => array(array('to' => 'items_id', 'noindex' => array('glpi_reservationitems'), 'tables' => array('glpi_reservationitems'))), 'id_followup' => array(array('to' => 'ticketfollowups_id', 'tables' => array('glpi_ticketplannings'))), 'id_item' => array(array('to' => 'reservationitems_id', 'tables' => array('glpi_reservations'))), 'id_user' => array(array('to' => 'users_id', 'tables' => array('glpi_consumables', 'glpi_reservations'))), 'iface' => array(array('to' => 'networkinterfaces_id', 'tables' => array('glpi_networkports'))), 'interface' => array(array('to' => 'interfacetypes_id', 'tables' => array('glpi_devicecontrols', 'glpi_deviceharddrives', 'glpi_devicedrives'))), 'item' => array(array('to' => 'items_id', 'noindex' => array('glpi_events'), 'tables' => array('glpi_events'))), 'link_if_status' => array(array('to' => 'states_id_linkif', 'noindex' => array('glpi_ocsservers'), 'tables' => array('glpi_ocsservers'))), 'location' => array(array('to' => 'locations_id', 'noindex' => array('glpi_netpoints'), 'tables' => array('glpi_cartridgeitems', 'glpi_computers', 'glpi_consumableitems', 'glpi_netpoints', 'glpi_monitors', 'glpi_networkequipments', 'glpi_peripherals', 'glpi_phones', 'glpi_printers', 'glpi_users', 'glpi_softwares'))), 'model' => array(array('to' => 'computermodels_id', 'tables' => array('glpi_computers')), array('to' => 'monitormodels_id', 'tables' => array('glpi_monitors')), array('to' => 'networkequipmentmodels_id', 'tables' => array('glpi_networkequipments')), array('to' => 'peripheralmodels_id', 'tables' => array('glpi_peripherals')), array('to' => 'phonemodels_id', 'tables' => array('glpi_phones')), array('to' => 'printermodels_id', 'tables' => array('glpi_printers'))), 'netpoint' => array(array('to' => 'netpoints_id', 'tables' => array('glpi_networkports'))), 'network' => array(array('to' => 'networks_id', 'tables' => array('glpi_computers', 'glpi_networkequipments', 'glpi_printers'))), 'ocs_id' => array(array('to' => 'ocsid', 'noindex' => array('glpi_ocslinks'), 'tables' => array('glpi_ocslinks'))), 'ocs_server_id' => array(array('to' => 'ocsservers_id', 'noindex' => array('glpi_ocslinks'), 'tables' => array('glpi_ocsadmininfoslinks', 'glpi_ocslinks'))), 'on_device' => array(array('to' => 'items_id', 'noindex' => array('glpi_networkports'), 'tables' => array('glpi_networkports'))), 'os' => array(array('to' => 'operatingsystems_id', 'tables' => array('glpi_computers'))), 'os_sp' => array(array('to' => 'operatingsystemservicepacks_id', 'tables' => array('glpi_computers'))), 'os_version' => array(array('to' => 'operatingsystemversions_id', 'tables' => array('glpi_computers'))), 'parentID' => array(array('to' => 'knowbaseitemcategories_id', 'noindex' => array('glpi_knowbaseitemcategories'), 'tables' => array('glpi_knowbaseitemcategories')), array('to' => 'locations_id', 'tables' => array('glpi_locations')), array('to' => 'ticketcategories_id', 'tables' => array('glpi_ticketcategories')), array('to' => 'entities_id', 'tables' => array('glpi_entities'))), 'platform' => array(array('to' => 'operatingsystems_id', 'tables' => array('glpi_softwares'))), 'power' => array(array('to' => 'phonepowersupplies_id', 'tables' => array('glpi_phones'))), 'recipient' => array(array('to' => 'users_id_recipient', 'tables' => array('glpi_tickets'))), 'rubrique' => array(array('to' => 'documentcategories_id', 'tables' => array('glpi_documents'))), 'rule_id' => array(array('to' => 'rules_id', 'tables' => array('glpi_rulecachemanufacturers', 'glpi_rulecachecomputermodels', 'glpi_rulecachemonitormodels', 'glpi_rulecachenetworkequipmentmodels', 'glpi_rulecacheperipheralmodels', 'glpi_rulecachephonemodels', 'glpi_rulecacheprintermodels', 'glpi_rulecacheoperatingsystems', 'glpi_rulecacheoperatingsystemservicepacks', 'glpi_rulecacheoperatingsystemversions', 'glpi_rulecachesoftwares', 'glpi_rulecachecomputertypes', 'glpi_rulecachemonitortypes', 'glpi_rulecachenetworkequipmenttypes', 'glpi_rulecacheperipheraltypes', 'glpi_rulecachephonetypes', 'glpi_rulecacheprintertypes'))), 'server_id' => array(array('to' => 'authldaps_id', 'tables' => array('glpi_authldapreplicates'))), 'sID' => array(array('to' => 'softwares_id', 'tables' => array('glpi_softwarelicenses', 'glpi_softwareversions'))), 'state' => array(array('to' => 'states_id', 'tables' => array('glpi_computers', 'glpi_monitors', 'glpi_networkequipments', 'glpi_peripherals', 'glpi_phones', 'glpi_printers', 'glpi_softwareversions'))), 'tech_num' => array(array('to' => 'users_id_tech', 'tables' => array('glpi_cartridgeitems', 'glpi_computers', 'glpi_consumableitems', 'glpi_monitors', 'glpi_networkequipments', 'glpi_peripherals', 'glpi_phones', 'glpi_printers', 'glpi_softwares'))), 'title' => array(array('to' => 'usertitles_id', 'tables' => array('glpi_users'))), 'tracking' => array(array('to' => 'tickets_id', 'tables' => array('glpi_ticketfollowups'))), 'type' => array(array('to' => 'cartridgeitemtypes_id', 'tables' => array('glpi_cartridgeitems')), array('to' => 'computertypes_id', 'tables' => array('glpi_computers')), array('to' => 'consumableitemtypes_id', 'tables' => array('glpi_consumableitems')), array('to' => 'contacttypes_id', 'tables' => array('glpi_contacts')), array('to' => 'devicecasetypes_id', 'tables' => array('glpi_devicecases')), array('to' => 'devicememorytypes_id', 'tables' => array('glpi_devicememories')), array('to' => 'suppliertypes_id', 'tables' => array('glpi_suppliers')), array('to' => 'monitortypes_id', 'tables' => array('glpi_monitors')), array('to' => 'networkequipmenttypes_id', 'tables' => array('glpi_networkequipments')), array('to' => 'peripheraltypes_id', 'tables' => array('glpi_peripherals')), array('to' => 'phonetypes_id', 'tables' => array('glpi_phones')), array('to' => 'printertypes_id', 'tables' => array('glpi_printers')), array('to' => 'softwarelicensetypes_id', 'tables' => array('glpi_softwarelicenses')), array('to' => 'usercategories_id', 'tables' => array('glpi_users')), array('to' => 'itemtype', 'noindex' => array('glpi_computers_items'), 'tables' => array('glpi_computers_items', 'glpi_displaypreferences'))), 'update_software' => array(array('to' => 'softwares_id', 'tables' => array('glpi_softwares'))), 'use_version' => array(array('to' => 'softwareversions_id_use', 'tables' => array('glpi_softwarelicenses'))), 'vID' => array(array('to' => 'softwareversions_id', 'tables' => array('glpi_computers_softwareversions'))));
    foreach ($foreignkeys as $oldname => $newnames) {
        foreach ($newnames as $tab) {
            $newname = $tab['to'];
            foreach ($tab['tables'] as $table) {
                $doindex = true;
                if (isset($tab['noindex']) && in_array($table, $tab['noindex'])) {
                    $doindex = false;
                }
                // Rename field
                if (FieldExists($table, $oldname, false)) {
                    $addcomment = '';
                    if (isset($tab['comments']) && isset($tab['comments'][$table])) {
                        $addcomment = " COMMENT '" . $tab['comments'][$table] . "' ";
                    }
                    $default_value = 0;
                    if (isset($tab['default']) && isset($tab['default'][$table])) {
                        $default_value = $tab['default'][$table];
                    }
                    // Manage NULL fields
                    $query = "UPDATE `{$table}`\n                         SET `{$oldname}` = '{$default_value}'\n                         WHERE `{$oldname}` IS NULL ";
                    $DB->queryOrDie($query, "0.78 prepare datas for update {$oldname} to {$newname} in {$table}");
                    $changes[$table][] = "CHANGE COLUMN `{$oldname}` `{$newname}` INT( 11 ) NOT NULL\n                                                   DEFAULT '{$default_value}' {$addcomment}";
                } else {
                    $updateresult = false;
                    $migration->displayWarning("Error: {$table}.{$oldname} does not exist.", true);
                }
                // If do index : delete old one / create new one
                if ($doindex) {
                    if (!isIndex($table, $newname)) {
                        $changes[$table][] = "ADD INDEX `{$newname}` (`{$newname}`)";
                    }
                    if ($oldname != $newname && isIndex($table, $oldname)) {
                        $changes[$table][] = "DROP INDEX `{$oldname}`";
                    }
                }
            }
        }
    }
    $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'Clean DB: rename bool values'));
    $boolfields = array('glpi_authldaps' => array(array('from' => 'ldap_use_tls', 'to' => 'use_tls', 'default' => 0, 'noindex ' => true), array('from' => 'use_dn', 'to' => 'use_dn', 'default' => 1, 'noindex' => true)), 'glpi_bookmarks' => array(array('from' => 'private', 'to' => 'is_private', 'default' => 1), array('from' => 'recursive', 'to' => 'is_recursive', 'default' => 0)), 'glpi_cartridgeitems' => array(array('from' => 'deleted', 'to' => 'is_deleted', 'default' => 0)), 'glpi_computers' => array(array('from' => 'is_template', 'to' => 'is_template', 'default' => 0), array('from' => 'deleted', 'to' => 'is_deleted', 'default' => 0), array('from' => 'ocs_import', 'to' => 'is_ocs_import', 'default' => 0)), 'glpi_configs' => array(array('from' => 'jobs_at_login', 'to' => 'show_jobs_at_login', 'default' => 0, 'noindex' => true), array('from' => 'mailing', 'to' => 'use_mailing', 'default' => 0, 'noindex' => true), array('from' => 'permit_helpdesk', 'to' => 'use_anonymous_helpdesk', 'default' => 0, 'noindex' => true), array('from' => 'existing_auth_server_field_clean_domain', 'to' => 'existing_auth_server_field_clean_domain', 'default' => 0, 'noindex' => true), array('from' => 'auto_assign', 'to' => 'use_auto_assign_to_tech', 'default' => 0, 'noindex' => true), array('from' => 'public_faq', 'to' => 'use_public_faq', 'default' => 0, 'noindex' => true), array('from' => 'url_in_mail', 'to' => 'show_link_in_mail', 'default' => 0, 'noindex' => true), array('from' => 'use_ajax', 'to' => 'use_ajax', 'default' => 0, 'noindex' => true), array('from' => 'ajax_autocompletion', 'to' => 'use_ajax_autocompletion', 'default' => 1, 'noindex' => true), array('from' => 'auto_add_users', 'to' => 'is_users_auto_add', 'default' => 1, 'noindex' => true), array('from' => 'view_ID', 'to' => 'is_ids_visible', 'default' => 0, 'noindex' => true), array('from' => 'ocs_mode', 'to' => 'use_ocs_mode', 'default' => 0, 'noindex' => true), array('from' => 'followup_on_update_ticket', 'to' => 'add_followup_on_update_ticket', 'default' => 1, 'noindex' => true), array('from' => 'licenses_alert', 'to' => 'use_licenses_alert', 'default' => 0, 'noindex' => true), array('from' => 'keep_tracking_on_delete', 'to' => 'keep_tickets_on_delete', 'default' => 1, 'noindex' => true), array('from' => 'use_errorlog', 'to' => 'use_log_in_files', 'default' => 0, 'noindex ' => true), array('from' => 'autoupdate_link_contact', 'to' => 'is_contact_autoupdate', 'default' => 1, 'noindex' => true), array('from' => 'autoupdate_link_user', 'to' => 'is_user_autoupdate', 'default' => 1, 'noindex' => true), array('from' => 'autoupdate_link_group', 'to' => 'is_group_autoupdate', 'default' => 1, 'noindex ' => true), array('from' => 'autoupdate_link_location', 'to' => 'is_location_autoupdate', 'default' => 1, 'noindex' => true), array('from' => 'autoclean_link_contact', 'to' => 'is_contact_autoclean', 'default' => 0, 'noindex' => true), array('from' => 'autoclean_link_user', 'to' => 'is_user_autoclean', 'default' => 0, 'noindex' => true), array('from' => 'autoclean_link_group', 'to' => 'is_group_autoclean', 'default' => 0, 'noindex' => true), array('from' => 'autoclean_link_location', 'to' => 'is_location_autoclean', 'default' => 0, 'noindex' => true), array('from' => 'flat_dropdowntree', 'to' => 'use_flat_dropdowntree', 'default' => 0, 'noindex' => true), array('from' => 'autoname_entity', 'to' => 'use_autoname_by_entity', 'default' => 1, 'noindex' => true), array('from' => 'expand_soft_categorized', 'to' => 'is_categorized_soft_expanded', 'default' => 1, 'noindex' => true), array('from' => 'expand_soft_not_categorized', 'to' => 'is_not_categorized_soft_expanded', 'default' => 1, 'noindex' => true), array('from' => 'ticket_title_mandatory', 'to' => 'is_ticket_title_mandatory', 'default' => 0, 'noindex' => true), array('from' => 'ticket_content_mandatory', 'to' => 'is_ticket_content_mandatory', 'default' => 1, 'noindex' => true), array('from' => 'ticket_category_mandatory', 'to' => 'is_ticket_category_mandatory', 'default' => 0, 'noindex' => true), array('from' => 'followup_private', 'to' => 'followup_private', 'default' => 0, 'noindex' => true), array('from' => 'software_helpdesk_visible', 'to' => 'default_software_helpdesk_visible', 'default' => 1, 'noindex' => true)), 'glpi_consumableitems' => array(array('from' => 'deleted', 'to' => 'is_deleted', 'default' => 0)), 'glpi_contacts' => array(array('from' => 'recursive', 'to' => 'is_recursive', 'default' => 0, 'noindex' => true), array('from' => 'deleted', 'to' => 'is_deleted', 'default' => 0)), 'glpi_contracts' => array(array('from' => 'recursive', 'to' => 'is_recursive', 'default' => 0, 'noindex' => true), array('from' => 'deleted', 'to' => 'is_deleted', 'default' => 0), array('from' => 'monday', 'to' => 'use_monday', 'default' => 0), array('from' => 'saturday', 'to' => 'use_saturday', 'default' => 0)), 'glpi_devicecontrols' => array(array('from' => 'raid', 'to' => 'is_raid', 'default' => 0, 'noindex' => true)), 'glpi_devicedrives' => array(array('from' => 'is_writer', 'to' => 'is_writer', 'default' => 1, 'noindex' => true)), 'glpi_devicepowersupplies' => array(array('from' => 'atx', 'to' => 'is_atx', 'default' => 1, 'noindex' => true)), 'glpi_documents' => array(array('from' => 'recursive', 'to' => 'is_recursive', 'default' => 0, 'noindex' => true), array('from' => 'deleted', 'to' => 'is_deleted', 'default' => 0)), 'glpi_documenttypes' => array(array('from' => 'upload', 'to' => 'is_uploadable', 'default' => 1)), 'glpi_groups' => array(array('from' => 'recursive', 'to' => 'is_recursive', 'default' => 0, 'noindex' => true)), 'glpi_knowbaseitems' => array(array('from' => 'recursive', 'to' => 'is_recursive', 'default' => 1, 'noindex' => true), array('from' => 'faq', 'to' => 'is_faq', 'default' => 0)), 'glpi_links' => array(array('from' => 'recursive', 'to' => 'is_recursive', 'default' => 1, 'noindex' => true)), 'glpi_monitors' => array(array('from' => 'deleted', 'to' => 'is_deleted', 'default' => 0), array('from' => 'is_template', 'to' => 'is_template', 'default' => 0, 'noindex' => true), array('from' => 'is_global', 'to' => 'is_global', 'default' => 0, 'noindex' => true), array('from' => 'flags_micro', 'to' => 'have_micro', 'default' => 0, 'noindex' => true), array('from' => 'flags_speaker', 'to' => 'have_speaker', 'default' => 0, 'noindex' => true), array('from' => 'flags_subd', 'to' => 'have_subd', 'default' => 0, 'noindex' => true), array('from' => 'flags_bnc', 'to' => 'have_bnc', 'default' => 0, 'noindex' => true), array('from' => 'flags_dvi', 'to' => 'have_dvi', 'default' => 0, 'noindex' => true), array('from' => 'flags_pivot', 'to' => 'have_pivot', 'default' => 0, 'noindex' => true)), 'glpi_networkequipments' => array(array('from' => 'recursive', 'to' => 'is_recursive', 'default' => 0, 'noindex' => true), array('from' => 'deleted', 'to' => 'is_deleted', 'default' => 0), array('from' => 'is_template', 'to' => 'is_template', 'default' => 0, 'noindex' => true)), 'glpi_ocslinks' => array(array('from' => 'auto_update', 'to' => 'use_auto_update', 'default' => 1)), 'glpi_ocsservers' => array(array('from' => 'import_periph', 'to' => 'import_periph', 'default' => 0, 'noindex' => true), array('from' => 'import_monitor', 'to' => 'import_monitor', 'default' => 0, 'noindex' => true), array('from' => 'import_software', 'to' => 'import_software', 'default' => 0, 'noindex' => true), array('from' => 'import_printer', 'to' => 'import_printer', 'default' => 0, 'noindex' => true), array('from' => 'import_general_name', 'to' => 'import_general_name', 'default' => 0, 'noindex' => true), array('from' => 'import_general_os', 'to' => 'import_general_os', 'default' => 0, 'noindex' => true), array('from' => 'import_general_serial', 'to' => 'import_general_serial', 'default' => 0, 'noindex' => true), array('from' => 'import_general_model', 'to' => 'import_general_model', 'default' => 0, 'noindex' => true), array('from' => 'import_general_enterprise', 'to' => 'import_general_manufacturer', 'default' => 0, 'noindex' => true), array('from' => 'import_general_type', 'to' => 'import_general_type', 'default' => 0, 'noindex' => true), array('from' => 'import_general_domain', 'to' => 'import_general_domain', 'default' => 0, 'noindex' => true), array('from' => 'import_general_contact', 'to' => 'import_general_contact', 'default' => 0, 'noindex' => true), array('from' => 'import_general_comments', 'to' => 'import_general_comment', 'default' => 0, 'noindex' => true), array('from' => 'import_device_processor', 'to' => 'import_device_processor', 'default' => 0, 'noindex' => true), array('from' => 'import_device_memory', 'to' => 'import_device_memory', 'default' => 0, 'noindex' => true), array('from' => 'import_device_hdd', 'to' => 'import_device_hdd', 'default' => 0, 'noindex' => true), array('from' => 'import_device_iface', 'to' => 'import_device_iface', 'default' => 0, 'noindex' => true), array('from' => 'import_device_gfxcard', 'to' => 'import_device_gfxcard', 'default' => 0, 'noindex' => true), array('from' => 'import_device_sound', 'to' => 'import_device_sound', 'default' => 0, 'noindex' => true), array('from' => 'import_device_drives', 'to' => 'import_device_drive', 'default' => 0, 'noindex' => true), array('from' => 'import_device_ports', 'to' => 'import_device_port', 'default' => 0, 'noindex' => true), array('from' => 'import_device_modems', 'to' => 'import_device_modem', 'default' => 0, 'noindex' => true), array('from' => 'import_registry', 'to' => 'import_registry', 'default' => 0, 'noindex' => true), array('from' => 'import_os_serial', 'to' => 'import_os_serial', 'default' => 0, 'noindex' => true), array('from' => 'import_ip', 'to' => 'import_ip', 'default' => 0, 'noindex' => true), array('from' => 'import_disk', 'to' => 'import_disk', 'default' => 0, 'noindex' => true), array('from' => 'import_monitor_comments', 'to' => 'import_monitor_comment', 'default' => 0, 'noindex' => true), array('from' => 'glpi_link_enabled', 'to' => 'is_glpi_link_enabled', 'default' => 0, 'noindex' => true), array('from' => 'link_ip', 'to' => 'use_ip_to_link', 'default' => 0, 'noindex' => true), array('from' => 'link_name', 'to' => 'use_name_to_link', 'default' => 0, 'noindex' => true), array('from' => 'link_mac_address', 'to' => 'use_mac_to_link', 'default' => 0, 'noindex' => true), array('from' => 'link_serial', 'to' => 'use_serial_to_link', 'default' => 0, 'noindex' => true), array('from' => 'use_soft_dict', 'to' => 'use_soft_dict', 'default' => 0, 'noindex' => true)), 'glpi_peripherals' => array(array('from' => 'deleted', 'to' => 'is_deleted', 'default' => 0), array('from' => 'is_template', 'to' => 'is_template', 'default' => 0, 'noindex' => true), array('from' => 'is_global', 'to' => 'is_global', 'default' => 0, 'noindex' => true)), 'glpi_phones' => array(array('from' => 'deleted', 'to' => 'is_deleted', 'default' => 0), array('from' => 'is_template', 'to' => 'is_template', 'default' => 0, 'noindex' => true), array('from' => 'is_global', 'to' => 'is_global', 'default' => 0, 'noindex' => true), array('from' => 'flags_hp', 'to' => 'have_hp', 'default' => 0, 'noindex' => true), array('from' => 'flags_casque', 'to' => 'have_headset', 'default' => 0, 'noindex' => true)), 'glpi_printers' => array(array('from' => 'recursive', 'to' => 'is_recursive', 'default' => 0, 'noindex' => true), array('from' => 'deleted', 'to' => 'is_deleted', 'default' => 0), array('from' => 'is_template', 'to' => 'is_template', 'default' => 0, 'noindex' => true), array('from' => 'is_global', 'to' => 'is_global', 'default' => 0, 'noindex' => true), array('from' => 'flags_usb', 'to' => 'have_usb', 'default' => 0, 'noindex' => true), array('from' => 'flags_par', 'to' => 'have_parallel', 'default' => 0, 'noindex' => true), array('from' => 'flags_serial', 'to' => 'have_serial', 'default' => 0, 'noindex' => true)), 'glpi_profiles_users' => array(array('from' => 'recursive', 'to' => 'is_recursive', 'default' => 1), array('from' => 'dynamic', 'to' => 'is_dynamic', 'default' => 0)), 'glpi_profiles' => array(array('from' => 'is_default', 'to' => 'is_default', 'default' => 0)), 'glpi_reminders' => array(array('from' => 'private', 'to' => 'is_private', 'default' => 1), array('from' => 'recursive', 'to' => 'is_recursive', 'default' => 0), array('from' => 'rv', 'to' => 'is_planned', 'default' => 0)), 'glpi_reservationitems' => array(array('from' => 'active', 'to' => 'is_active', 'default' => 1)), 'glpi_rules' => array(array('from' => 'active', 'to' => 'is_active', 'default' => 1)), 'glpi_suppliers' => array(array('from' => 'recursive', 'to' => 'is_recursive', 'default' => 0, 'noindex' => true), array('from' => 'deleted', 'to' => 'is_deleted', 'default' => 0)), 'glpi_softwares' => array(array('from' => 'recursive', 'to' => 'is_recursive', 'default' => 0, 'noindex' => true), array('from' => 'deleted', 'to' => 'is_deleted', 'default' => 0), array('from' => 'helpdesk_visible', 'to' => 'is_helpdesk_visible', 'default' => 1), array('from' => 'is_template', 'to' => 'is_template', 'default' => 0, 'noindex' => true), array('from' => 'is_update', 'to' => 'is_update', 'default' => 0, 'noindex' => true)), 'glpi_softwarelicenses' => array(array('from' => 'recursive', 'to' => 'is_recursive', 'default' => 0, 'noindex' => true)), 'glpi_tickets' => array(array('from' => 'emailupdates', 'to' => 'use_email_notification', 'default' => 0, 'noindex' => true)), 'glpi_ticketfollowups' => array(array('from' => 'private', 'to' => 'is_private', 'default' => 0)), 'glpi_users' => array(array('from' => 'deleted', 'to' => 'is_deleted', 'default' => 0), array('from' => 'active', 'to' => 'is_active', 'default' => 1), array('from' => 'jobs_at_login', 'to' => 'show_jobs_at_login', 'default' => NULL, 'maybenull' => true, 'noindex' => true), array('from' => 'followup_private', 'to' => 'followup_private', 'default' => NULL, 'maybenull' => true, 'noindex' => true), array('from' => 'expand_soft_categorized', 'to' => 'is_categorized_soft_expanded', 'default' => NULL, 'maybenull' => true, 'noindex' => true), array('from' => 'expand_soft_not_categorized', 'to' => 'is_not_categorized_soft_expanded', 'default' => NULL, 'maybenull' => true, 'noindex' => true), array('from' => 'flat_dropdowntree', 'to' => 'use_flat_dropdowntree', 'default' => NULL, 'maybenull' => true, 'noindex' => true), array('from' => 'view_ID', 'to' => 'is_ids_visible', 'default' => NULL, 'maybenull' => true, 'noindex' => true)));
    foreach ($boolfields as $table => $tab) {
        foreach ($tab as $update) {
            $newname = $update['to'];
            $oldname = $update['from'];
            $doindex = true;
            if (isset($update['noindex']) && $update['noindex']) {
                $doindex = false;
            }
            // Rename field
            if (FieldExists($table, $oldname, false)) {
                $NULL = "NOT NULL";
                if (isset($update['maybenull']) && $update['maybenull']) {
                    $NULL = "NULL";
                    // Manage not zero values
                    $query = "UPDATE `{$table}`\n                         SET `{$oldname}` = 1\n                         WHERE `{$oldname}` <> 0\n                               AND `{$oldname}` IS NOT NULL";
                    $DB->queryOrDie($query, "0.78 prepare datas for update {$oldname} to {$newname} in {$table}");
                } else {
                    // Manage NULL fields
                    $query = "UPDATE `{$table}`\n                         SET `{$oldname}` = 0\n                         WHERE `{$oldname}` IS NULL";
                    $DB->queryOrDie($query, "0.78 prepare datas for update {$oldname} to {$newname} in {$table}");
                    // Manage not zero values
                    $query = "UPDATE `{$table}`\n                         SET `{$oldname}` = 1\n                         WHERE `{$oldname}` <> 0";
                    $DB->queryOrDie($query, "0.78 prepare datas for update {$oldname} to {$newname} in {$table}");
                }
                $default = "DEFAULT NULL";
                if (isset($update['default']) && !is_null($update['default'])) {
                    $default = "DEFAULT " . $update['default'];
                }
                $changes[$table][] = "CHANGE `{$oldname}` `{$newname}` TINYINT( 1 ) {$NULL} {$default}";
            } else {
                $updateresult = false;
                $migration->displayWarning("Error: {$table}.{$oldname} does not exist.", true);
            }
            // If do index : delete old one / create new one
            if ($doindex) {
                if (!isIndex($table, $newname)) {
                    $changes[$table][] = "ADD INDEX `{$newname}` (`{$newname}`)";
                }
                if ($newname != $oldname && isIndex($table, $oldname)) {
                    $changes[$table][] = "DROP INDEX `{$oldname}`";
                }
            }
        }
    }
    $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'Clean DB: update text fields'));
    $textfields = array('comments' => array('to' => 'comment', 'tables' => array('glpi_cartridgeitems', 'glpi_computers', 'glpi_consumableitems', 'glpi_contacts', 'glpi_contracts', 'glpi_documents', 'glpi_autoupdatesystems', 'glpi_budgets', 'glpi_cartridgeitemtypes', 'glpi_devicecasetypes', 'glpi_consumableitemtypes', 'glpi_contacttypes', 'glpi_contracttypes', 'glpi_domains', 'glpi_suppliertypes', 'glpi_filesystems', 'glpi_networkequipmentfirmwares', 'glpi_networkinterfaces', 'glpi_interfacetypes', 'glpi_knowbaseitemcategories', 'glpi_softwarelicensetypes', 'glpi_locations', 'glpi_manufacturers', 'glpi_computermodels', 'glpi_monitormodels', 'glpi_networkequipmentmodels', 'glpi_peripheralmodels', 'glpi_phonemodels', 'glpi_printermodels', 'glpi_netpoints', 'glpi_networks', 'glpi_operatingsystems', 'glpi_operatingsystemservicepacks', 'glpi_operatingsystemversions', 'glpi_phonepowersupplies', 'glpi_devicememorytypes', 'glpi_documentcategories', 'glpi_softwarecategories', 'glpi_states', 'glpi_ticketcategories', 'glpi_usertitles', 'glpi_usercategories', 'glpi_vlans', 'glpi_suppliers', 'glpi_entities', 'glpi_groups', 'glpi_infocoms', 'glpi_monitors', 'glpi_phones', 'glpi_printers', 'glpi_peripherals', 'glpi_networkequipments', 'glpi_reservationitems', 'glpi_rules', 'glpi_softwares', 'glpi_softwarelicenses', 'glpi_softwareversions', 'glpi_computertypes', 'glpi_monitortypes', 'glpi_networkequipmenttypes', 'glpi_peripheraltypes', 'glpi_phonetypes', 'glpi_printertypes', 'glpi_users')), 'notes' => array('to' => 'notepad', 'long' => true, 'tables' => array('glpi_cartridgeitems', 'glpi_computers', 'glpi_consumableitems', 'glpi_contacts', 'glpi_contracts', 'glpi_documents', 'glpi_suppliers', 'glpi_entitydatas', 'glpi_printers', 'glpi_monitors', 'glpi_phones', 'glpi_peripherals', 'glpi_networkequipments', 'glpi_softwares')), 'ldap_condition' => array('to' => 'condition', 'tables' => array('glpi_authldaps')), 'import_printers' => array('to' => 'import_printer', 'long' => true, 'tables' => array('glpi_ocslinks')), 'contents' => array('to' => 'content', 'long' => true, 'tables' => array('glpi_tickets', 'glpi_ticketfollowups')));
    foreach ($textfields as $oldname => $tab) {
        $newname = $tab['to'];
        $type = "TEXT";
        if (isset($tab['long']) && $tab['long']) {
            $type = "LONGTEXT";
        }
        foreach ($tab['tables'] as $table) {
            // Rename field
            if (FieldExists($table, $oldname, false)) {
                $query = "ALTER TABLE `{$table}`\n                      CHANGE `{$oldname}` `{$newname}` {$type} NULL DEFAULT NULL ";
                $DB->queryOrDie($query, "0.78 rename {$oldname} to {$newname} in {$table}");
            } else {
                $updateresult = false;
                $migration->displayWarning("Error: {$table}.{$oldname} does not exist.", true);
            }
        }
    }
    $varcharfields = array('glpi_authldaps' => array(array('from' => 'ldap_host', 'to' => 'host', 'noindex' => true), array('from' => 'ldap_basedn', 'to' => 'basedn', 'noindex' => true), array('from' => 'ldap_rootdn', 'to' => 'rootdn', 'noindex' => true), array('from' => 'ldap_pass', 'to' => 'rootdn_password', 'noindex' => true), array('from' => 'ldap_login', 'to' => 'login_field', 'default' => 'uid', 'noindex' => true), array('from' => 'ldap_field_group', 'to' => 'group_field', 'noindex' => true), array('from' => 'ldap_group_condition', 'to' => 'group_condition', 'noindex' => true), array('from' => 'ldap_field_group_member', 'to' => 'group_member_field', 'noindex' => true), array('from' => 'ldap_field_email', 'to' => 'email_field', 'noindex' => true), array('from' => 'ldap_field_realname', 'to' => 'realname_field', 'noindex' => true), array('from' => 'ldap_field_firstname', 'to' => 'firstname_field', 'noindex' => true), array('from' => 'ldap_field_phone', 'to' => 'phone_field', 'noindex' => true), array('from' => 'ldap_field_phone2', 'to' => 'phone2_field', 'noindex' => true), array('from' => 'ldap_field_mobile', 'to' => 'mobile_field', 'noindex' => true), array('from' => 'ldap_field_comments', 'to' => 'comment_field', 'noindex' => true), array('from' => 'ldap_field_title', 'to' => 'title_field', 'noindex' => true), array('from' => 'ldap_field_type', 'to' => 'category_field', 'noindex' => true), array('from' => 'ldap_field_language', 'to' => 'language_field', 'noindex' => true)), 'glpi_authldapreplicates' => array(array('from' => 'ldap_host', 'to' => 'host', 'noindex' => true)), 'glpi_authmails' => array(array('from' => 'imap_auth_server', 'to' => 'connect_string', 'noindex' => true), array('from' => 'imap_host', 'to' => 'host', 'noindex' => true)), 'glpi_computers' => array(array('from' => 'os_license_id', 'to' => 'os_licenseid', 'noindex' => true), array('from' => 'tplname', 'to' => 'template_name', 'noindex' => true)), 'glpi_configs' => array(array('from' => 'helpdeskhelp_url', 'to' => 'helpdesk_doc_url', 'noindex' => true), array('from' => 'centralhelp_url', 'to' => 'central_doc_url', 'noindex' => true)), 'glpi_contracts' => array(array('from' => 'compta_num', 'to' => 'accounting_number', 'noindex' => true)), 'glpi_events' => array(array('from' => 'itemtype', 'to' => 'type', 'noindex' => true)), 'glpi_infocoms' => array(array('from' => 'num_commande', 'to' => 'order_number', 'noindex' => true), array('from' => 'bon_livraison', 'to' => 'delivery_number', 'noindex' => true), array('from' => 'num_immo', 'to' => 'immo_number', 'noindex' => true), array('from' => 'facture', 'to' => 'bill', 'noindex' => true)), 'glpi_monitors' => array(array('from' => 'tplname', 'to' => 'template_name', 'noindex' => true)), 'glpi_networkequipments' => array(array('from' => 'tplname', 'to' => 'template_name', 'noindex' => true), array('from' => 'ifmac', 'to' => 'mac', 'noindex' => true), array('from' => 'ifaddr', 'to' => 'ip', 'noindex' => true)), 'glpi_networkports' => array(array('from' => 'ifmac', 'to' => 'mac', 'noindex' => true), array('from' => 'ifaddr', 'to' => 'ip', 'noindex' => true)), 'glpi_peripherals' => array(array('from' => 'tplname', 'to' => 'template_name', 'noindex' => true)), 'glpi_phones' => array(array('from' => 'tplname', 'to' => 'template_name', 'noindex' => true)), 'glpi_printers' => array(array('from' => 'tplname', 'to' => 'template_name', 'noindex' => true), array('from' => 'ramSize', 'to' => 'memory_size', 'noindex' => true)), 'glpi_registrykeys' => array(array('from' => 'registry_hive', 'to' => 'hive', 'noindex' => true), array('from' => 'registry_path', 'to' => 'path', 'noindex' => true), array('from' => 'registry_value', 'to' => 'value', 'noindex' => true), array('from' => 'registry_ocs_name', 'to' => 'ocs_name', 'noindex' => true)), 'glpi_softwares' => array(array('from' => 'tplname', 'to' => 'template_name', 'noindex' => true)), 'glpi_tickets' => array(array('from' => 'uemail', 'to' => 'user_email', 'noindex' => true)));
    foreach ($varcharfields as $table => $tab) {
        foreach ($tab as $update) {
            $newname = $update['to'];
            $oldname = $update['from'];
            $doindex = true;
            if (isset($update['noindex']) && $update['noindex']) {
                $doindex = false;
            }
            $default = "DEFAULT NULL";
            if (isset($update['default']) && !is_null($update['default'])) {
                $default = "DEFAULT '" . $update['default'] . "'";
            }
            // Rename field
            if (FieldExists($table, $oldname, false)) {
                $query = "ALTER TABLE `{$table}`\n                      CHANGE `{$oldname}` `{$newname}` VARCHAR( 255 ) NULL {$default} ";
                $DB->queryOrDie($query, "0.78 rename {$oldname} to {$newname} in {$table}");
            } else {
                $updateresult = false;
                $migration->displayWarning("Error: {$table}.{$oldname} does not exist.");
            }
            // If do index : delete old one / create new one
            if ($doindex) {
                if (!isIndex($table, $newname)) {
                    $changes[$table][] = "ADD INDEX `{$newname}` (`{$newname}`)";
                }
                if ($newname != $oldname && isIndex($table, $oldname)) {
                    $changes[$table][] = "DROP INDEX `{$oldname}`";
                }
            }
        }
    }
    $charfields = array('glpi_profiles' => array(array('from' => 'user_auth_method', 'to' => 'user_authtype', 'length' => 1, 'default' => NULL, 'noindex' => true), array('from' => 'rule_tracking', 'to' => 'rule_ticket', 'length' => 1, 'default' => NULL, 'noindex' => true), array('from' => 'rule_softwarecategories', 'to' => 'rule_softwarecategories', 'length' => 1, 'default' => NULL, 'noindex' => true), array('from' => 'rule_dictionnary_software', 'to' => 'rule_dictionnary_software', 'length' => 1, 'default' => NULL, 'noindex' => true), array('from' => 'rule_dictionnary_dropdown', 'to' => 'rule_dictionnary_dropdown', 'length' => 1, 'default' => NULL, 'noindex' => true)), 'glpi_configs' => array(array('from' => 'version', 'to' => 'version', 'length' => 10, 'default' => NULL, 'noindex' => true), array('from' => 'version', 'to' => 'version', 'length' => 10, 'default' => NULL, 'noindex' => true), array('from' => 'language', 'to' => 'language', 'length' => 10, 'default' => 'en_GB', 'noindex' => true, 'comments' => 'see define.php CFG_GLPI[language] array'), array('from' => 'priority_1', 'to' => 'priority_1', 'length' => 20, 'default' => '#fff2f2', 'noindex' => true), array('from' => 'priority_2', 'to' => 'priority_2', 'length' => 20, 'default' => '#ffe0e0', 'noindex' => true), array('from' => 'priority_3', 'to' => 'priority_3', 'length' => 20, 'default' => '#ffcece', 'noindex' => true), array('from' => 'priority_4', 'to' => 'priority_4', 'length' => 20, 'default' => '#ffbfbf', 'noindex' => true), array('from' => 'priority_5', 'to' => 'priority_5', 'length' => 20, 'default' => '#ffadad', 'noindex' => true), array('from' => 'founded_new_version', 'to' => 'founded_new_version', 'length' => 10, 'default' => NULL, 'noindex' => true)), 'glpi_rules' => array(array('from' => 'match', 'to' => 'match', 'length' => 10, 'default' => NULL, 'noindex' => true, 'comments' => 'see define.php *_MATCHING constant')), 'glpi_users' => array(array('from' => 'language', 'to' => 'language', 'length' => 10, 'default' => NULL, 'noindex' => true, 'comments' => 'see define.php CFG_GLPI[language] array'), array('from' => 'priority_1', 'to' => 'priority_1', 'length' => 20, 'default' => NULL, 'noindex' => true), array('from' => 'priority_2', 'to' => 'priority_2', 'length' => 20, 'default' => NULL, 'noindex' => true), array('from' => 'priority_3', 'to' => 'priority_3', 'length' => 20, 'default' => NULL, 'noindex' => true), array('from' => 'priority_4', 'to' => 'priority_4', 'length' => 20, 'default' => NULL, 'noindex' => true), array('from' => 'priority_5', 'to' => 'priority_5', 'length' => 20, 'default' => NULL, 'noindex' => true)));
    foreach ($charfields as $table => $tab) {
        foreach ($tab as $update) {
            $newname = $update['to'];
            $oldname = $update['from'];
            $length = $update['length'];
            $doindex = true;
            if (isset($update['noindex']) && $update['noindex']) {
                $doindex = false;
            }
            $default = "DEFAULT NULL";
            if (isset($update['default']) && !is_null($update['default'])) {
                $default = "DEFAULT '" . $update['default'] . "'";
            }
            $addcomment = "";
            if (isset($update['comments'])) {
                $addcomment = "COMMENT '" . $update['comments'] . "'";
            }
            // Rename field
            if (FieldExists($table, $oldname, false)) {
                $query = "ALTER TABLE `{$table}`\n                      CHANGE `{$oldname}` `{$newname}` CHAR( {$length} ) NULL {$default} {$addcomment} ";
                $DB->queryOrDie($query, "0.78 rename {$oldname} to {$newname} in {$table}");
            } else {
                $updateresult = false;
                $migration->displayWarning("Error: {$table}.{$oldname} does not exist.", true);
            }
            // If do index : delete old one / create new one
            if ($doindex) {
                if (!isIndex($table, $newname)) {
                    $changes[$table][] = "ADD INDEX `{$newname}` (`{$newname}`)";
                }
                if ($oldname != $newname && isIndex($table, $oldname)) {
                    $changes[$table][] = "DROP INDEX `{$oldname}`";
                }
            }
        }
    }
    $intfields = array('glpi_authldaps' => array(array('from' => 'ldap_port', 'to' => 'port', 'default' => 389, 'noindex' => true, 'checkdatas' => true), array('from' => 'ldap_search_for_groups', 'to' => 'group_search_type', 'default' => 0, 'noindex' => true), array('from' => 'ldap_opt_deref', 'to' => 'deref_option', 'default' => 0, 'noindex' => true), array('from' => 'timezone', 'to' => 'time_offset', 'default' => 0, 'noindex' => true, 'comments' => 'in seconds')), 'glpi_authldapreplicates' => array(array('from' => 'ldap_port', 'to' => 'port', 'default' => 389, 'noindex' => true, 'checkdatas' => true)), 'glpi_bookmarks' => array(array('from' => 'type', 'to' => 'type', 'default' => 0, 'noindex' => true, 'comments' => 'see define.php BOOKMARK_* constant')), 'glpi_cartridgeitems' => array(array('from' => 'alarm', 'to' => 'alarm_threshold', 'default' => 10)), 'glpi_configs' => array(array('from' => 'glpi_timezone', 'to' => 'time_offset', 'default' => 0, 'noindex' => true, 'comments' => 'in seconds'), array('from' => 'cartridges_alarm', 'to' => 'default_alarm_threshold', 'default' => 10, 'noindex' => true), array('from' => 'event_loglevel', 'to' => 'event_loglevel', 'default' => 5, 'noindex' => true), array('from' => 'cas_port', 'to' => 'cas_port', 'default' => 443, 'noindex' => true, 'checkdatas' => true), array('from' => 'auto_update_check', 'to' => 'auto_update_check', 'default' => 0, 'noindex' => true), array('from' => 'dateformat', 'to' => 'date_format', 'default' => 0, 'noindex' => true), array('from' => 'numberformat', 'to' => 'number_format', 'default' => 0, 'noindex' => true), array('from' => 'proxy_port', 'to' => 'proxy_port', 'default' => 8080, 'noindex' => true, 'checkdatas' => true), array('from' => 'contract_alerts', 'to' => 'default_contract_alert', 'default' => 0, 'noindex' => true), array('from' => 'infocom_alerts', 'to' => 'default_infocom_alert', 'default' => 0, 'noindex' => true), array('from' => 'cartridges_alert', 'to' => 'cartridges_alert_repeat', 'default' => 0, 'noindex' => true, 'comments' => 'in seconds'), array('from' => 'consumables_alert', 'to' => 'consumables_alert_repeat', 'default' => 0, 'noindex' => true, 'comments' => 'in seconds'), array('from' => 'monitors_management_restrict', 'to' => 'monitors_management_restrict', 'default' => 2, 'noindex' => true), array('from' => 'phones_management_restrict', 'to' => 'phones_management_restrict', 'default' => 2, 'noindex' => true), array('from' => 'peripherals_management_restrict', 'to' => 'peripherals_management_restrict', 'default' => 2, 'noindex' => true), array('from' => 'printers_management_restrict', 'to' => 'printers_management_restrict', 'default' => 2, 'noindex' => true), array('from' => 'autoupdate_link_state', 'to' => 'state_autoupdate_mode', 'default' => 0, 'noindex' => true), array('from' => 'autoclean_link_state', 'to' => 'state_autoclean_mode', 'default' => 0, 'noindex' => true), array('from' => 'name_display_order', 'to' => 'names_format', 'default' => 0, 'noindex' => true, 'comments' => 'see *NAME_BEFORE constant in define.php'), array('from' => 'dropdown_limit', 'to' => 'dropdown_chars_limit', 'default' => 50, 'noindex' => true), array('from' => 'smtp_mode', 'to' => 'smtp_mode', 'default' => 0, 'noindex' => true, 'comments' => 'see define.php MAIL_* constant'), array('from' => 'mailgate_filesize_max', 'to' => 'default_mailcollector_filesize_max', 'default' => 2097152, 'noindex' => true)), 'glpi_consumableitems' => array(array('from' => 'alarm', 'to' => 'alarm_threshold', 'default' => 10)), 'glpi_contracts' => array(array('from' => 'duration', 'to' => 'duration', 'default' => 0, 'noindex' => true), array('from' => 'notice', 'to' => 'notice', 'default' => 0, 'noindex' => true), array('from' => 'periodicity', 'to' => 'periodicity', 'default' => 0, 'noindex' => true), array('from' => 'facturation', 'to' => 'billing', 'default' => 0, 'noindex' => true), array('from' => 'device_countmax', 'to' => 'max_links_allowed', 'default' => 0, 'noindex' => true), array('from' => 'alert', 'to' => 'alert', 'default' => 0), array('from' => 'renewal', 'to' => 'renewal', 'default' => 0, 'noindex' => true)), 'glpi_displaypreferences' => array(array('from' => 'num', 'to' => 'num', 'default' => 0), array('from' => 'rank', 'to' => 'rank', 'default' => 0)), 'glpi_events' => array(array('from' => 'level', 'to' => 'level', 'default' => 0)), 'glpi_infocoms' => array(array('from' => 'warranty_duration', 'to' => 'warranty_duration', 'default' => 0, 'noindex' => true), array('from' => 'amort_time', 'to' => 'sink_time', 'default' => 0, 'noindex' => true), array('from' => 'amort_type', 'to' => 'sink_type', 'default' => 0, 'noindex' => true), array('from' => 'alert', 'to' => 'alert', 'default' => 0)), 'glpi_mailingsettings' => array(array('from' => 'item_type', 'to' => 'mailingtype', 'default' => 0, 'noindex' => true, 'comments' => 'see define.php *_MAILING_TYPE constant')), 'glpi_monitors' => array(array('from' => 'size', 'to' => 'size', 'default' => 0, 'noindex' => true)), 'glpi_printers' => array(array('from' => 'initial_pages', 'to' => 'init_pages_counter', 'default' => 0, 'noindex' => true, 'checkdatas' => true)), 'glpi_profiles' => array(array('from' => 'helpdesk_hardware', 'to' => 'helpdesk_hardware', 'default' => 0, 'noindex' => true)), 'glpi_plugins' => array(array('from' => 'state', 'to' => 'state', 'default' => 0, 'comments' => 'see define.php PLUGIN_* constant')), 'glpi_reminders' => array(array('from' => 'state', 'to' => 'state', 'default' => 0)), 'glpi_ticketplannings' => array(array('from' => 'state', 'to' => 'state', 'default' => 1)), 'glpi_rulecriterias' => array(array('from' => 'condition', 'to' => 'condition', 'default' => 0, 'comments' => 'see define.php PATTERN_* and REGEX_* constant')), 'glpi_rules' => array(array('from' => 'sub_type', 'to' => 'sub_type', 'default' => 0, 'comments' => 'see define.php RULE_* constant')), 'glpi_tickets' => array(array('from' => 'request_type', 'to' => 'request_type', 'default' => 0, 'noindex' => true), array('from' => 'priority', 'to' => 'priority', 'default' => 1, 'noindex' => true)), 'glpi_transfers' => array(array('from' => 'keep_tickets', 'to' => 'keep_ticket', 'default' => 0, 'noindex' => true), array('from' => 'keep_networklinks', 'to' => 'keep_networklink', 'default' => 0, 'noindex' => true), array('from' => 'keep_reservations', 'to' => 'keep_reservation', 'default' => 0, 'noindex' => true), array('from' => 'keep_history', 'to' => 'keep_history', 'default' => 0, 'noindex' => true), array('from' => 'keep_devices', 'to' => 'keep_device', 'default' => 0, 'noindex' => true), array('from' => 'keep_infocoms', 'to' => 'keep_infocom', 'default' => 0, 'noindex' => true), array('from' => 'keep_dc_monitor', 'to' => 'keep_dc_monitor', 'default' => 0, 'noindex' => true), array('from' => 'clean_dc_monitor', 'to' => 'clean_dc_monitor', 'default' => 0, 'noindex' => true), array('from' => 'keep_dc_phone', 'to' => 'keep_dc_phone', 'default' => 0, 'noindex' => true), array('from' => 'clean_dc_phone', 'to' => 'clean_dc_phone', 'default' => 0, 'noindex' => true), array('from' => 'keep_dc_peripheral', 'to' => 'keep_dc_peripheral', 'default' => 0, 'noindex' => true), array('from' => 'clean_dc_peripheral', 'to' => 'clean_dc_peripheral', 'default' => 0, 'noindex' => true), array('from' => 'keep_dc_printer', 'to' => 'keep_dc_printer', 'default' => 0, 'noindex' => true), array('from' => 'clean_dc_printer', 'to' => 'clean_dc_printer', 'default' => 0, 'noindex' => true), array('from' => 'keep_enterprises', 'to' => 'keep_supplier', 'default' => 0, 'noindex' => true), array('from' => 'clean_enterprises', 'to' => 'clean_supplier', 'default' => 0, 'noindex' => true), array('from' => 'keep_contacts', 'to' => 'keep_contact', 'default' => 0, 'noindex' => true), array('from' => 'clean_contacts', 'to' => 'clean_contact', 'default' => 0, 'noindex' => true), array('from' => 'keep_contracts', 'to' => 'keep_contract', 'default' => 0, 'noindex' => true), array('from' => 'clean_contracts', 'to' => 'clean_contract', 'default' => 0, 'noindex' => true), array('from' => 'keep_softwares', 'to' => 'keep_software', 'default' => 0, 'noindex' => true), array('from' => 'clean_softwares', 'to' => 'clean_software', 'default' => 0, 'noindex' => true), array('from' => 'keep_documents', 'to' => 'keep_document', 'default' => 0, 'noindex' => true), array('from' => 'clean_documents', 'to' => 'clean_document', 'default' => 0, 'noindex' => true), array('from' => 'keep_cartridges_type', 'to' => 'keep_cartridgeitem', 'default' => 0, 'noindex' => true), array('from' => 'clean_cartridges_type', 'to' => 'clean_cartridgeitem', 'default' => 0, 'noindex' => true), array('from' => 'keep_cartridges', 'to' => 'keep_cartridge', 'default' => 0, 'noindex' => true), array('from' => 'keep_consumables', 'to' => 'keep_consumable', 'default' => 0, 'noindex' => true)), 'glpi_users' => array(array('from' => 'dateformat', 'to' => 'date_format', 'default' => NULL, 'noindex' => true, 'maybenull' => true), array('from' => 'numberformat', 'to' => 'number_format', 'default' => NULL, 'noindex' => true, 'maybenull' => true), array('from' => 'use_mode', 'to' => 'use_mode', 'default' => 0, 'noindex' => true), array('from' => 'dropdown_limit', 'to' => 'dropdown_chars_limit', 'default' => NULL, 'maybenull' => true, 'noindex' => true)));
    foreach ($intfields as $table => $tab) {
        foreach ($tab as $update) {
            $newname = $update['to'];
            $oldname = $update['from'];
            $doindex = true;
            if (isset($update['noindex']) && $update['noindex']) {
                $doindex = false;
            }
            $default = "DEFAULT NULL";
            if (isset($update['default']) && !is_null($update['default'])) {
                $default = "DEFAULT " . $update['default'] . "";
            }
            $NULL = "NOT NULL";
            if (isset($update['maybenull']) && $update['maybenull']) {
                $NULL = "NULL";
            }
            $check_datas = false;
            if (isset($update['checkdatas'])) {
                $check_datas = $update['checkdatas'];
            }
            $addcomment = "";
            if (isset($update['comments'])) {
                $addcomment = "COMMENT '" . $update['comments'] . "'";
            }
            // Rename field
            if (FieldExists($table, $oldname, false)) {
                if ($check_datas) {
                    $query = "SELECT `id`, `{$oldname}`\n                         FROM `{$table}`";
                    if ($result = $DB->query($query)) {
                        if ($DB->numrows($result) > 0) {
                            while ($data = $DB->fetch_assoc($result)) {
                                if (empty($data[$oldname]) && isset($update['default'])) {
                                    $data[$oldname] = $update['default'];
                                }
                                $query = "UPDATE `{$table}`\n                                  SET `{$oldname}` = '" . intval($data[$oldname]) . "'\n                                  WHERE `id` = " . $data['id'] . "";
                                $DB->query($query);
                            }
                        }
                    }
                }
                $changes[$table][] = "CHANGE `{$oldname}` `{$newname}` INT( 11 ) {$NULL} {$default} {$addcomment}";
            } else {
                $updateresult = false;
                $migration->displayWarning("Error: {$table}.{$oldname} does not exist.", true);
            }
            // If do index : delete old one / create new one
            if ($doindex) {
                if (!isIndex($table, $newname)) {
                    $changes[$table][] = "ADD INDEX `{$newname}` (`{$newname}`)";
                }
                if ($newname != $oldname && isIndex($table, $oldname)) {
                    $changes[$table][] = "DROP INDEX `{$oldname}`";
                }
            }
        }
    }
    $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'Clean DB: others field changes'));
    if (FieldExists('glpi_alerts', 'date', false)) {
        $changes['glpi_alerts'][] = "CHANGE `date` `date` DATETIME NOT NULL";
    }
    if (FieldExists('glpi_configs', 'date_fiscale', false)) {
        $changes['glpi_configs'][] = "CHANGE `date_fiscale` `date_tax` DATE NOT NULL\n                                                                     DEFAULT '2005-12-31'";
    }
    if (FieldExists('glpi_configs', 'sendexpire', false)) {
        $changes['glpi_configs'][] = "DROP `sendexpire`";
    }
    if (FieldExists('glpi_configs', 'show_admin_doc', false)) {
        $changes['glpi_configs'][] = "DROP `show_admin_doc`";
    }
    if (FieldExists('glpi_configs', 'licenses_management_restrict', false)) {
        $changes['glpi_configs'][] = "DROP `licenses_management_restrict`";
    }
    if (FieldExists('glpi_configs', 'nextprev_item', false)) {
        $changes['glpi_configs'][] = "DROP `nextprev_item`";
    }
    if (FieldExists('glpi_configs', 'logotxt', false)) {
        $changes['glpi_configs'][] = "DROP `logotxt`";
    }
    if (FieldExists('glpi_configs', 'num_of_events', false)) {
        $changes['glpi_configs'][] = "DROP `num_of_events`";
    }
    if (FieldExists('glpi_configs', 'tracking_order', false)) {
        $changes['glpi_configs'][] = "DROP `tracking_order`";
    }
    if (FieldExists('glpi_contracts', 'bill_type', false)) {
        $changes['glpi_contracts'][] = "DROP `bill_type`";
    }
    if (FieldExists('glpi_infocoms', 'amort_coeff', false)) {
        $changes['glpi_infocoms'][] = "CHANGE `amort_coeff` `sink_coeff` FLOAT NOT NULL DEFAULT '0'";
    }
    if (FieldExists('glpi_ocsservers', 'import_software_comments', false)) {
        $changes['glpi_ocsservers'][] = "DROP `import_software_comments`";
    }
    if (FieldExists('glpi_users', 'nextprev_item', false)) {
        $changes['glpi_users'][] = "DROP `nextprev_item`";
    }
    if (FieldExists('glpi_users', 'num_of_events', false)) {
        $changes['glpi_users'][] = "DROP `num_of_events`";
    }
    if (FieldExists('glpi_users', 'tracking_order', false)) {
        $changes['glpi_users'][] = "DROP `tracking_order`";
    }
    if (FieldExists('glpi_rulerightparameters', 'sub_type', false)) {
        $changes['glpi_rulerightparameters'][] = "DROP `sub_type`";
    }
    if (FieldExists('glpi_softwares', 'oldstate', false)) {
        $changes['glpi_softwares'][] = "DROP `oldstate`";
    }
    if (FieldExists('glpi_users', 'password', false)) {
        $changes['glpi_users'][] = "DROP `password`";
    }
    if (FieldExists('glpi_users', 'password_md5', false)) {
        $changes['glpi_users'][] = "CHANGE `password_md5` `password` CHAR( 40 )  NULL DEFAULT NULL";
    }
    if (!FieldExists('glpi_mailcollectors', 'filesize_max', false)) {
        $changes['glpi_mailcollectors'][] = "ADD `filesize_max` INT(11) NOT NULL DEFAULT 2097152";
    }
    $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'Clean DB: index management'));
    if (!isIndex('glpi_alerts', 'unicity')) {
        $changes['glpi_alerts'][] = "ADD UNIQUE `unicity` (`itemtype`, `items_id`, `type`)";
    }
    if (!isIndex('glpi_cartridges_printermodels', 'unicity')) {
        $changes['glpi_cartridges_printermodels'][] = "ADD UNIQUE `unicity` (`printermodels_id`,\n                                                                           `cartridgeitems_id`)";
    }
    if (!isIndex('glpi_computers_items', 'unicity')) {
        $changes['glpi_computers_items'][] = "ADD UNIQUE `unicity` (`itemtype`, `items_id`,\n                                                                  `computers_id`)";
    }
    if (!isIndex('glpi_contacts_suppliers', 'unicity')) {
        $changes['glpi_contacts_suppliers'][] = "ADD UNIQUE `unicity` (`suppliers_id`, `contacts_id`)";
    }
    if (!isIndex('glpi_contracts_items', 'unicity')) {
        $changes['glpi_contracts_items'][] = "ADD UNIQUE `unicity` (`contracts_id`, `itemtype`,\n                                                                  `items_id`)";
    }
    if (!isIndex('glpi_contracts_items', 'item')) {
        $changes['glpi_contracts_items'][] = "ADD INDEX `item` (`itemtype`, `items_id`)";
    }
    if (!isIndex('glpi_contracts_suppliers', 'unicity')) {
        $changes['glpi_contracts_suppliers'][] = "ADD UNIQUE `unicity` (`suppliers_id`, `contracts_id`)";
    }
    if (!isIndex('glpi_displaypreferences', 'unicity')) {
        $changes['glpi_displaypreferences'][] = "ADD UNIQUE `unicity` (`users_id`, `itemtype`, `num`)";
    }
    if (!isIndex('glpi_bookmarks_users', 'unicity')) {
        $changes['glpi_bookmarks_users'][] = "ADD UNIQUE `unicity` (`users_id`, `itemtype`)";
    }
    if (!isIndex('glpi_documents_items', 'unicity')) {
        $changes['glpi_documents_items'][] = "ADD UNIQUE `unicity` (`documents_id`, `itemtype`,\n                                                                  `items_id`)";
    }
    if (!isIndex('glpi_documents_items', 'item')) {
        $changes['glpi_documents_items'][] = "ADD INDEX `item` (`itemtype`, `items_id`)";
    }
    if (!isIndex('glpi_knowbaseitemcategories', 'unicity')) {
        $changes['glpi_knowbaseitemcategories'][] = "ADD UNIQUE `unicity` (`knowbaseitemcategories_id`,\n                                                                         `name`)";
    }
    if (!isIndex('glpi_locations', 'unicity')) {
        $changes['glpi_locations'][] = "ADD UNIQUE `unicity` (`entities_id`, `locations_id`, `name`)";
    }
    if (isIndex('glpi_locations', 'name')) {
        $changes['glpi_locations'][] = "DROP INDEX `name` ";
    }
    if (!isIndex('glpi_netpoints', 'complete')) {
        $changes['glpi_netpoints'][] = "ADD INDEX `complete` (`entities_id`, `locations_id`, `name`)";
    }
    if (!isIndex('glpi_netpoints', 'location_name')) {
        $changes['glpi_netpoints'][] = "ADD INDEX `location_name` (`locations_id`, `name`)";
    }
    if (!isIndex('glpi_entities', 'unicity')) {
        $changes['glpi_entities'][] = "ADD UNIQUE `unicity` (`entities_id`, `name`)";
    }
    if (!isIndex('glpi_entitydatas', 'unicity')) {
        $changes['glpi_entitydatas'][] = "ADD UNIQUE `unicity` (`entities_id`)";
    }
    if (!isIndex('glpi_events', 'item')) {
        $changes['glpi_events'][] = "ADD INDEX `item` (`type`, `items_id`)";
    }
    if (!isIndex('glpi_infocoms', 'unicity')) {
        $changes['glpi_infocoms'][] = "ADD UNIQUE `unicity` (`itemtype`, `items_id`)";
    }
    if (!isIndex('glpi_knowbaseitems', 'date_mod')) {
        $changes['glpi_knowbaseitems'][] = "ADD INDEX `date_mod` (`date_mod`)";
    }
    if (!isIndex('glpi_networkequipments', 'date_mod')) {
        $changes['glpi_networkequipments'][] = "ADD INDEX `date_mod` (`date_mod`)";
    }
    if (!isIndex('glpi_links_itemtypes', 'unicity')) {
        $changes['glpi_links_itemtypes'][] = "ADD UNIQUE `unicity` (`itemtype`, `links_id`)";
    }
    if (!isIndex('glpi_mailingsettings', 'unicity')) {
        $changes['glpi_mailingsettings'][] = "ADD UNIQUE `unicity` (`type`, `items_id`, `mailingtype`)";
    }
    if (!isIndex('glpi_networkports', 'item')) {
        $changes['glpi_networkports'][] = "ADD INDEX `item` (`itemtype`, `items_id`)";
    }
    if (!isIndex('glpi_networkports_vlans', 'unicity')) {
        $changes['glpi_networkports_vlans'][] = "ADD UNIQUE `unicity` (`networkports_id`, `vlans_id`)";
    }
    if (!isIndex('glpi_networkports_networkports', 'unicity')) {
        $changes['glpi_networkports_networkports'][] = "ADD UNIQUE `unicity` (`networkports_id_1`,\n                                                                            `networkports_id_2`)";
    }
    if (!isIndex('glpi_ocslinks', 'unicity')) {
        $changes['glpi_ocslinks'][] = "ADD UNIQUE `unicity` (`ocsservers_id`, `ocsid`)";
    }
    if (!isIndex('glpi_peripherals', 'date_mod')) {
        $changes['glpi_peripherals'][] = "ADD INDEX `date_mod` (`date_mod`)";
    }
    if (!isIndex('glpi_phones', 'date_mod')) {
        $changes['glpi_phones'][] = "ADD INDEX `date_mod` (`date_mod`)";
    }
    if (!isIndex('glpi_plugins', 'unicity')) {
        $changes['glpi_plugins'][] = "ADD UNIQUE `unicity` (`directory`)";
    }
    if (!isIndex('glpi_printers', 'date_mod')) {
        $changes['glpi_printers'][] = "ADD INDEX `date_mod` (`date_mod`)";
    }
    if (!isIndex('glpi_reminders', 'date_mod')) {
        $changes['glpi_reminders'][] = "ADD INDEX `date_mod` (`date_mod`)";
    }
    if (!isIndex('glpi_reservationitems', 'item')) {
        $changes['glpi_reservationitems'][] = "ADD INDEX `item` (`itemtype`, `items_id`)";
    }
    if (!isIndex('glpi_tickets', 'item')) {
        $changes['glpi_tickets'][] = "ADD INDEX `item` (`itemtype`, `items_id`)";
    }
    if (!isIndex('glpi_documenttypes', 'date_mod')) {
        $changes['glpi_documenttypes'][] = "ADD INDEX `date_mod` (`date_mod`)";
    }
    if (!isIndex('glpi_documenttypes', 'unicity')) {
        $changes['glpi_documenttypes'][] = "ADD UNIQUE `unicity` (`ext`)";
    }
    if (!isIndex('glpi_users', 'unicity')) {
        $changes['glpi_users'][] = "ADD UNIQUE `unicity` (`name`)";
    }
    if (!isIndex('glpi_users', 'date_mod')) {
        $changes['glpi_users'][] = "ADD INDEX `date_mod` (`date_mod`)";
    }
    if (!isIndex('glpi_users', 'authitem')) {
        $changes['glpi_users'][] = "ADD INDEX `authitem` (`authtype`, `auths_id`)";
    }
    if (!isIndex('glpi_groups_users', 'unicity')) {
        $changes['glpi_groups_users'][] = "ADD UNIQUE `unicity` (`users_id`, `groups_id`)";
    }
    $indextodrop = array('glpi_alerts' => array('alert', 'FK_device'), 'glpi_cartridges_printermodels' => array('FK_glpi_type_printer'), 'glpi_computers_items' => array('connect', 'type', 'end1', 'end1_2'), 'glpi_consumables' => array('FK_glpi_cartridges_type'), 'glpi_contacts_suppliers' => array('FK_enterprise'), 'glpi_contracts_items' => array('FK_contract_device', 'device_type'), 'glpi_contracts_suppliers' => array('FK_enterprise'), 'glpi_displaypreferences' => array('display', 'FK_users'), 'glpi_bookmarks_users' => array('FK_users'), 'glpi_documents_items' => array('FK_doc_device', 'device_type', 'FK_device'), 'glpi_knowbaseitemcategories' => array('parentID_2', 'parentID'), 'glpi_locations' => array('FK_entities'), 'glpi_netpoints' => array('FK_entities', 'location'), 'glpi_entities' => array('name'), 'glpi_entitydatas' => array('FK_entities'), 'glpi_events' => array('comp', 'itemtype'), 'glpi_infocoms' => array('FK_device'), 'glpi_computers_softwareversions' => array('sID'), 'glpi_links_itemtypes' => array('link'), 'glpi_mailingsettings' => array('mailings', 'FK_item'), 'glpi_networkports' => array('device_type'), 'glpi_networkports_vlans' => array('portvlan'), 'glpi_networkports_networkports' => array('netwire', 'end1', 'end1_2'), 'glpi_ocslinks' => array('ocs_server_id'), 'glpi_plugins' => array('name'), 'glpi_reservationitems' => array('reservationitem'), 'glpi_tickets' => array('computer', 'device_type'), 'glpi_documenttypes' => array('extension'), 'glpi_users' => array('name'), 'glpi_groups_users' => array('usergroup'));
    foreach ($indextodrop as $table => $tab) {
        foreach ($tab as $indexname) {
            if (isIndex($table, $indexname)) {
                $changes[$table][] = "DROP INDEX `{$indexname}`";
            }
        }
    }
    foreach ($changes as $table => $tab) {
        $migration->displayMessage(sprintf(__('Change of the database layout - %s'), $table));
        $query = "ALTER TABLE `{$table}`\n                " . implode($tab, " ,\n") . ";";
        $DB->queryOrDie($query, "0.78 multiple alter in {$table}");
    }
    $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'Update itemtype fields'));
    // Convert itemtype to Class names
    $typetoname = array(GENERAL_TYPE => "", COMPUTER_TYPE => "Computer", NETWORKING_TYPE => "NetworkEquipment", PRINTER_TYPE => "Printer", MONITOR_TYPE => "Monitor", PERIPHERAL_TYPE => "Peripheral", SOFTWARE_TYPE => "Software", CONTACT_TYPE => "Contact", ENTERPRISE_TYPE => "Supplier", INFOCOM_TYPE => "Infocom", CONTRACT_TYPE => "Contract", CARTRIDGEITEM_TYPE => "CartridgeItem", TYPEDOC_TYPE => "DocumentType", DOCUMENT_TYPE => "Document", KNOWBASE_TYPE => "KnowbaseItem", USER_TYPE => "User", TRACKING_TYPE => "Ticket", CONSUMABLEITEM_TYPE => "ConsumableItem", CONSUMABLE_TYPE => "Consumable", CARTRIDGE_TYPE => "Cartridge", SOFTWARELICENSE_TYPE => "SoftwareLicense", LINK_TYPE => "Link", STATE_TYPE => "States", PHONE_TYPE => "Phone", DEVICE_TYPE => "Device", REMINDER_TYPE => "Reminder", STAT_TYPE => "Stat", GROUP_TYPE => "Group", ENTITY_TYPE => "Entity", RESERVATION_TYPE => "ReservationItem", AUTHMAIL_TYPE => "AuthMail", AUTHLDAP_TYPE => "AuthLDAP", OCSNG_TYPE => "OcsServer", REGISTRY_TYPE => "RegistryKey", PROFILE_TYPE => "Profile", MAILGATE_TYPE => "MailCollector", RULE_TYPE => "Rule", TRANSFER_TYPE => "Transfer", BOOKMARK_TYPE => "Bookmark", SOFTWAREVERSION_TYPE => "SoftwareVersion", PLUGIN_TYPE => "Plugin", COMPUTERDISK_TYPE => "ComputerDisk", NETWORKING_PORT_TYPE => "NetworkPort", FOLLOWUP_TYPE => "TicketFollowup", BUDGET_TYPE => "Budget");
    // End is not used in 0.72.x
    $devtypetoname = array(MOBOARD_DEVICE => 'DeviceMotherboard', PROCESSOR_DEVICE => 'DeviceProcessor', RAM_DEVICE => 'DeviceMemory', HDD_DEVICE => 'DeviceHardDrive', NETWORK_DEVICE => 'DeviceNetworkCard', DRIVE_DEVICE => 'DeviceDrive', CONTROL_DEVICE => 'DeviceControl', GFX_DEVICE => 'DeviceGraphicCard', SND_DEVICE => 'DeviceSoundCard', PCI_DEVICE => 'DevicePci', CASE_DEVICE => 'DeviceCase', POWER_DEVICE => 'DevicePowerSupply');
    $itemtype_tables = array("glpi_alerts", "glpi_bookmarks", "glpi_bookmarks_users", "glpi_computers_items", "glpi_contracts_items", "glpi_displaypreferences", "glpi_documents_items", "glpi_infocoms", "glpi_links_itemtypes", "glpi_networkports", "glpi_reservationitems", "glpi_tickets");
    foreach ($itemtype_tables as $table) {
        $migration->displayMessage(sprintf(__('Data migration - %s'), "{$table}"));
        // Updating data
        // Alter itemtype field
        $query = "ALTER TABLE `{$table}`\n                CHANGE `itemtype` `itemtype` VARCHAR( 100 ) NOT NULL";
        $DB->queryOrDie($query, "0.78 alter itemtype of table {$table}");
        // Update values
        foreach ($typetoname as $key => $val) {
            $query = "UPDATE `{$table}`\n                   SET `itemtype` = '{$val}'\n                   WHERE `itemtype` = '{$key}'";
            $DB->queryOrDie($query, "0.78 update itemtype of table {$table} for {$val}");
        }
    }
    if (FieldExists('glpi_logs', 'device_type', false)) {
        // History migration, handled separatly for optimization
        $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'glpi_logs - 1'));
        $query = "ALTER TABLE `glpi_logs`\n                CHANGE `ID` `id` INT( 11 ) NOT NULL AUTO_INCREMENT,\n                ADD `itemtype` VARCHAR(100) NOT NULL DEFAULT ''  AFTER `device_type`,\n                ADD `items_id` INT( 11 ) NOT NULL DEFAULT '0' AFTER `itemtype`,\n                ADD `itemtype_link` VARCHAR(100) NOT NULL DEFAULT '' AFTER `device_internal_type`,\n                CHANGE `linked_action` `linked_action` INT( 11 ) NOT NULL DEFAULT '0'\n                                                       COMMENT 'see define.php HISTORY_* constant'";
        $DB->queryOrDie($query, "0.78 add item* fields to table glpi_logs");
        // Update values
        $migration->displayMessage(sprintf(__('Data migration - %s'), 'glpi_logs'));
        // Copy data
        $query = "UPDATE `glpi_logs`\n                SET `itemtype` = `device_type`,\n                    `items_id` = `FK_glpi_device`,\n                    `itemtype_link` = `device_internal_type`";
        $DB->queryOrDie($query, "0.78 update glpi_logs default values");
        foreach ($typetoname as $key => $val) {
            $query = "UPDATE `glpi_logs`\n                   SET `itemtype` = '{$val}'\n                   WHERE `device_type` = '{$key}'";
            $DB->queryOrDie($query, "0.78 update itemtype of table glpi_logs for {$val}");
            $query = "UPDATE `glpi_logs`\n                   SET `itemtype_link` = '{$val}'\n                   WHERE `device_internal_type` = '{$key}'\n                        AND `linked_action` IN (" . Log::HISTORY_ADD_RELATION . ",\n                                                " . Log::HISTORY_DEL_RELATION . ",\n                                                " . Log::HISTORY_DISCONNECT_DEVICE . ",\n                                                " . Log::HISTORY_CONNECT_DEVICE . ")";
            $DB->queryOrDie($query, "0.78 update itemtype of table glpi_logs for {$val}");
        }
        foreach ($devtypetoname as $key => $val) {
            $query = "UPDATE `glpi_logs`\n                   SET `itemtype_link` = '{$val}'\n                   WHERE `device_internal_type` = '{$key}'\n                         AND `linked_action` IN (" . Log::HISTORY_ADD_DEVICE . ",\n                                                 " . Log::HISTORY_UPDATE_DEVICE . ",\n                                                 " . Log::HISTORY_DELETE_DEVICE . ")";
            $DB->queryOrDie($query, "0.78 update itemtype of table glpi_logs for {$val}");
        }
        // Clean link
        $query = "UPDATE `glpi_logs`\n                SET `itemtype_link` = ''\n                WHERE `itemtype_link` = '0'";
        $DB->queryOrDie($query, "0.78 update itemtype of table glpi_logs");
        $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'glpi_logs - 2'));
        $query = "ALTER TABLE `glpi_logs`\n                DROP `device_type`,\n                DROP `FK_glpi_device`,\n                DROP `device_internal_type`,\n                ADD INDEX `itemtype_link` (`itemtype_link`),\n                ADD INDEX `item` (`itemtype`,`items_id`)";
        $DB->queryOrDie($query, "0.78 drop device* fields to table glpi_logs");
    }
    // Update glpi_profiles item_type
    $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'Clean DB: post actions after renaming'));
    if (!isIndex('glpi_locations', 'name')) {
        $query = " ALTER TABLE `glpi_locations`\n                 ADD INDEX `name` (`name`)";
        $DB->queryOrDie($query, "0.78 add name index in glpi_locations");
    }
    // Update values of mailcollectors
    $query = "SELECT `default_mailcollector_filesize_max`\n             FROM `glpi_configs`\n             WHERE `id` = 1";
    if ($result = $DB->query($query)) {
        if ($DB->numrows($result) > 0) {
            $query = "UPDATE `glpi_mailcollectors`\n                   SET `filesize_max` = '" . $DB->result($result, 0, 0) . "';";
            $DB->query($query);
        }
    }
    // For compatiblity with updates from past versions
    regenerateTreeCompleteName("glpi_locations");
    regenerateTreeCompleteName("glpi_knowbaseitemcategories");
    regenerateTreeCompleteName("glpi_ticketcategories");
    // Update timezone values
    if (FieldExists('glpi_configs', 'time_offset', false)) {
        $query = "UPDATE `glpi_configs`\n                SET `time_offset` = `time_offset`*3600";
        $DB->queryOrDie($query, "0.78 update time_offset value in glpi_configs");
    }
    if (FieldExists('glpi_authldaps', 'time_offset', false)) {
        $query = "UPDATE `glpi_authldaps`\n                SET `time_offset` = `time_offset`*3600";
        $DB->queryOrDie($query, "0.78 update time_offset value in glpi_authldaps");
    }
    // Change defaults store values :
    if (FieldExists('glpi_softwares', 'sofwtares_id', false)) {
        $query = "UPDATE `glpi_softwares`\n                SET `sofwtares_id` = 0\n                WHERE `sofwtares_id` < 0";
        $DB->queryOrDie($query, "0.78 update default value of sofwtares_id in glpi_softwares");
    }
    if (FieldExists('glpi_users', 'authtype', false)) {
        $query = "UPDATE `glpi_users`\n                SET `authtype` = 0\n                WHERE `authtype` < 0";
        $DB->queryOrDie($query, "0.78 update default value of authtype in glpi_users");
    }
    if (FieldExists('glpi_users', 'auths_id', false)) {
        $query = "UPDATE `glpi_users`\n                SET `auths_id` = 0\n                WHERE `auths_id` < 0";
        $DB->queryOrDie($query, "0.78 update default value of auths_id in glpi_users");
    }
    // Update glpi_ocsadmininfoslinks table for new field name
    if (FieldExists('glpi_ocsadmininfoslinks', 'glpi_column', false)) {
        $query = "UPDATE `glpi_ocsadmininfoslinks`\n                SET `glpi_column` = 'locations_id'\n                WHERE `glpi_column` = 'location'";
        $DB->queryOrDie($query, "0.78 update value of glpi_column in glpi_ocsadmininfoslinks");
        $query = "UPDATE `glpi_ocsadmininfoslinks`\n                SET `glpi_column` = 'networks_id'\n                WHERE `glpi_column` = 'network'";
        $DB->queryOrDie($query, "0.78 update value of glpi_column in glpi_ocsadmininfoslinks");
        $query = "UPDATE `glpi_ocsadmininfoslinks`\n                SET `glpi_column` = 'groups_id'\n                WHERE `glpi_column` = 'FK_groups'";
        $DB->queryOrDie($query, "0.78 update value of glpi_column in glpi_ocsadmininfoslinks");
    }
    // Update bookmarks for new columns fields
    if (FieldExists('glpi_bookmarks', 'is_private', false)) {
        $query = "UPDATE `glpi_bookmarks`\n                SET `entities_id` = -1\n                WHERE `is_private` = 1";
        $DB->queryOrDie($query, "0.78 update value of entities_id in glpi_bookmarks");
    }
    if (FieldExists('glpi_reminders', 'is_private', false)) {
        $query = "UPDATE `glpi_reminders`\n                SET `entities_id` = -1\n                WHERE `is_private` = 1";
        $DB->queryOrDie($query, "0.78 update value of entities_id in glpi_reminders");
    }
    // Update bookmarks for new columns fields
    if (FieldExists('glpi_bookmarks', 'query', false)) {
        // All search
        $olds = array("deleted");
        $news = array("is_deleted");
        foreach ($olds as $key => $val) {
            $olds[$key] = "/&{$val}=/";
        }
        foreach ($news as $key => $val) {
            $news[$key] = "/&{$val}=/";
        }
        // Manage meta search
        foreach ($typetoname as $key => $val) {
            $olds[$key] = "/&type2\\[(\\d+)\\]={$key}/";
            $news[$key] = "&itemtype2[\\1]={$val}";
        }
        $query = "SELECT `id`, `query`\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)) {
                    $query2 = "UPDATE `glpi_bookmarks`\n                          SET `query` = '" . addslashes(preg_replace($olds, $news, $data['query'])) . "'\n                          WHERE `id` = " . $data['id'] . "";
                    $DB->queryOrDie($query2, "0.78 update all bookmarks");
                }
            }
        }
        // Update bookmarks due to FHS change
        $query2 = "UPDATE `glpi_bookmarks`\n                 SET `path` = 'front/documenttype.php'\n                 WHERE `path` = 'front/typedoc.php'";
        $DB->queryOrDie($query2, "0.78 update typedoc bookmarks");
        $query2 = "UPDATE `glpi_bookmarks`\n                 SET `path` = 'front/consumableitem.php'\n                 WHERE `path` = 'front/consumable.php'";
        $DB->queryOrDie($query2, "0.78 update consumable bookmarks");
        $query2 = "UPDATE `glpi_bookmarks`\n                 SET `path` = 'front/cartridgeitem.php'\n                 WHERE `path` = 'front/cartridge.php'";
        $DB->queryOrDie($query2, "0.78 update cartridge bookmarks");
        $query2 = "UPDATE `glpi_bookmarks`\n                 SET `path` = 'front/ticket.php'\n                 WHERE `path` = 'front/tracking.php'";
        $DB->queryOrDie($query2, "0.78 update ticket bookmarks");
        $query2 = "UPDATE `glpi_bookmarks`\n                 SET `path` = 'front/mailcollector.php'\n                 WHERE `path` = 'front/mailgate.php'";
        $DB->queryOrDie($query2, "0.78 update mailcollector bookmarks");
        $query2 = "UPDATE `glpi_bookmarks`\n                 SET `path` = 'front/ocsserver.php'\n                 WHERE `path` = 'front/setup.ocsng.php'";
        $DB->queryOrDie($query2, "0.78 update ocsserver bookmarks");
        $query2 = "UPDATE `glpi_bookmarks`\n                 SET `path` = 'front/supplier.php'\n                 WHERE `path` = 'front/enterprise.php'";
        $DB->queryOrDie($query2, "0.78 update supplier bookmarks");
        $query2 = "UPDATE `glpi_bookmarks`\n                 SET `path` = 'front/networkequipment.php'\n                 WHERE `path` = 'front/networking.php'";
        $DB->queryOrDie($query2, "0.78 update networkequipment bookmarks");
        $query2 = "UPDATE `glpi_bookmarks`\n                 SET `path` = 'front/states.php'\n                 WHERE `path` = 'front/state.php'";
        $DB->queryOrDie($query2, "0.78 update states bookmarks");
    }
    //// Upgrade rules datas
    $changes = array();
    // For Rule::RULE_AFFECT_RIGHTS
    $changes[1] = array('FK_entities' => 'entities_id', 'FK_profiles' => 'profiles_id', 'recursive' => 'is_recursive', 'active' => 'is_active');
    // For Rule::RULE_DICTIONNARY_SOFTWARE
    $changes[4] = array('helpdesk_visible ' => 'is_helpdesk_visible');
    // For Rule::RULE_OCS_AFFECT_COMPUTER
    $changes[0] = array('FK_entities' => 'entities_id');
    // For Rule::RULE_SOFTWARE_CATEGORY
    $changes[3] = array('category' => 'softwarecategories_id', 'comment' => 'comment');
    // For Rule::RULE_TRACKING_AUTO_ACTION
    $changes[2] = array('category' => 'ticketcategories_id', 'author' => 'users_id', 'author_location' => 'users_locations', 'FK_group' => 'groups_id', 'assign' => 'users_id_assign', 'assign_group' => 'groups_id_assign', 'device_type' => 'itemtype', 'FK_entities' => 'entities_id', 'contents' => 'content', 'request_type' => 'requesttypes_id');
    $DB->query("SET SESSION group_concat_max_len = 9999999;");
    foreach ($changes as $ruletype => $tab) {
        // Get rules
        $query = "SELECT GROUP_CONCAT(`id`)\n                FROM `glpi_rules`\n                WHERE `sub_type` = " . $ruletype . "\n                GROUP BY `sub_type`";
        if ($result = $DB->query($query)) {
            if ($DB->numrows($result) > 0) {
                // Get rule string
                $rules = $DB->result($result, 0, 0);
                // Update actions
                foreach ($tab as $old => $new) {
                    $query = "UPDATE `glpi_ruleactions`\n                         SET `field` = '{$new}'\n                         WHERE `field` = '{$old}'\n                               AND `rules_id` IN ({$rules});";
                    $DB->queryOrDie($query, "0.78 update datas for rules actions");
                }
                // Update criterias
                foreach ($tab as $old => $new) {
                    $query = "UPDATE `glpi_rulecriterias`\n                         SET `criteria` = '{$new}'\n                         WHERE `criteria` = '{$old}'\n                               AND `rules_id` IN ({$rules});";
                    $DB->queryOrDie($query, "0.78 update datas for rules criterias");
                }
            }
        }
    }
    $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'glpi_rulecachesoftwares'));
    $query = "ALTER TABLE `glpi_rules`\n             CHANGE `sub_type` `sub_type` VARCHAR( 255 ) NOT NULL DEFAULT ''";
    $DB->queryOrDie($query, "0.78 change subtype from INT(11) to VARCHAR(255) in glpi_rules");
    $subtypes = array(0 => 'RuleOcs', 1 => 'RuleRight', 2 => 'RuleTicket', 3 => 'RuleSoftwareCategory', 4 => 'RuleDictionnarySoftware', 5 => 'RuleDictionnaryManufacturer', 6 => 'RuleDictionnaryComputerModel', 7 => 'RuleDictionnaryComputerType', 8 => 'RuleDictionnaryMonitorModel', 9 => 'RuleDictionnaryMonitorType', 10 => 'RuleDictionnaryPrinterModel', 11 => 'RuleDictionnaryPrinterType', 12 => 'RuleDictionnaryPhoneModel', 13 => 'RuleDictionnaryPhoneType', 14 => 'RuleDictionnaryPeripheralModel', 15 => 'RuleDictionnaryPeripheralType', 16 => 'RuleDictionnaryNetworkEquipmentModel', 17 => 'RuleDictionnaryNetworkEquipmentType', 18 => 'RuleDictionnaryOperatingSystem', 19 => 'RuleDictionnaryOperatingSystemServicePack', 20 => 'RuleDictionnaryOperatingSystemVersion', 21 => 'RuleMailCollector');
    foreach ($subtypes as $old_subtype => $new_subtype) {
        $query = "UPDATE `glpi_rules`\n                SET `sub_type` = '{$new_subtype}'\n                WHERE `sub_type` = '{$old_subtype}'";
        $DB->queryOrDie($query, "0.78 change sub_type {$old_subtype} in {$new_subtype} in glpi_rules");
    }
    $DB->queryOrDie($query, "0.78 update itemtypes in business rules");
    //Update business rules itemtypes
    foreach ($typetoname as $key => $val) {
        if ($key != GENERAL_TYPE) {
            $query = "UPDATE `glpi_rulecriterias`\n                   SET `pattern` = '{$val}'\n                   WHERE `pattern` = '{$key}'\n                         AND `criteria` = 'itemtype'";
            $DB->queryOrDie($query, "0.78 update itemtype for business rules for {$val}");
        }
    }
    if (FieldExists("glpi_rulecachesoftwares", "ignore_ocs_import", false)) {
        $query = "ALTER TABLE `glpi_rulecachesoftwares`\n                CHANGE `ignore_ocs_import` `ignore_ocs_import` CHAR( 1 ) NULL DEFAULT NULL ";
        $DB->queryOrDie($query, "0.78 alter table glpi_rulecachesoftwares");
    }
    if (!FieldExists("glpi_rulecachesoftwares", "is_helpdesk_visible", false)) {
        $query = "ALTER TABLE `glpi_rulecachesoftwares`\n                ADD `is_helpdesk_visible` CHAR( 1 ) NULL ";
        $DB->queryOrDie($query, "0.78 add is_helpdesk_visible in glpi_rulecachesoftwares");
    }
    $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'glpi_entities'));
    if (!FieldExists("glpi_entities", "sons_cache", false)) {
        $query = "ALTER TABLE `glpi_entities`\n                ADD `sons_cache` LONGTEXT NULL ; ";
        $DB->queryOrDie($query, "0.78 add sons_cache field in glpi_entities");
    }
    if (!FieldExists("glpi_entities", "ancestors_cache", false)) {
        $query = "ALTER TABLE `glpi_entities`\n                ADD `ancestors_cache` LONGTEXT NULL ; ";
        $DB->queryOrDie($query, "0.78 add ancestors_cache field in glpi_entities");
    }
    $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'glpi_configs'));
    if (!FieldExists("glpi_configs", "default_graphtype", false)) {
        $query = "ALTER TABLE `glpi_configs`\n                ADD `default_graphtype` char( 3 ) NOT NULL DEFAULT 'svg'";
        $DB->queryOrDie($query, "0.78 add default_graphtype in glpi_configs");
    }
    if (FieldExists('glpi_configs', 'license_deglobalisation', false)) {
        $query = "ALTER TABLE `glpi_configs`\n                DROP `license_deglobalisation`;";
        $DB->queryOrDie($query, "0.78 alter clean glpi_configs table");
    }
    if (FieldExists("glpi_configs", "use_cache", false)) {
        $query = "ALTER TABLE `glpi_configs`\n                DROP `use_cache`;";
        $DB->queryOrDie($query, "0.78 drop use_cache in glpi_configs");
    }
    if (FieldExists("glpi_configs", "cache_max_size", false)) {
        $query = "ALTER TABLE `glpi_configs`\n                DROP `cache_max_size`;";
        $DB->queryOrDie($query, "0.78 drop cache_max_size in glpi_configs");
    }
    if (!FieldExists("glpi_configs", "default_request_type", false)) {
        $query = "ALTER TABLE `glpi_configs`\n                ADD `default_request_type` INT( 11 ) NOT NULL DEFAULT 1";
        $DB->queryOrDie($query, "0.78 add default_request_type in glpi_configs");
    }
    if (!FieldExists("glpi_users", "default_request_type", false)) {
        $query = "ALTER TABLE `glpi_users`\n                ADD `default_request_type` INT( 11 ) NULL";
        $DB->queryOrDie($query, "0.78 add default_request_type in glpi_users");
    }
    if (!FieldExists("glpi_configs", "use_noright_users_add", false)) {
        $query = "ALTER TABLE `glpi_configs`\n                ADD `use_noright_users_add` tinyint( 1 ) NOT NULL DEFAULT '1'";
        $DB->queryOrDie($query, "0.78 add use_noright_users_add in glpi_configs");
    }
    $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'glpi_budgets'));
    if (!FieldExists("glpi_profiles", "budget", false)) {
        $query = "ALTER TABLE `glpi_profiles`\n                ADD `budget` CHAR( 1 ) NULL ";
        $DB->queryOrDie($query, "0.78 add budget in glpi_profiles");
        $query = "UPDATE `glpi_profiles`\n                SET `budget` = `infocom`";
        $DB->queryOrDie($query, "0.78 update default budget rights");
    }
    if (!FieldExists("glpi_budgets", "is_recursive", false)) {
        $query = "ALTER TABLE `glpi_budgets`\n                ADD `is_recursive` tinyint(1) NOT NULL DEFAULT '0' AFTER `name`,\n                ADD INDEX `is_recursive` (`is_recursive`)";
        $DB->queryOrDie($query, "0.78 add is_recursive field in glpi_budgets");
        // budgets in 0.72 were global
        $query = "UPDATE `glpi_budgets`\n                SET `is_recursive` = '1';";
        $DB->queryOrDie($query, "0.78 set is_recursive to true in glpi_budgets");
    }
    if (!FieldExists("glpi_budgets", "entities_id", false)) {
        $query = "ALTER TABLE `glpi_budgets`\n                   ADD `entities_id` int(11) NOT NULL default '0' AFTER `name`,\n                   ADD INDEX `entities_id` (`entities_id`);";
        $DB->queryOrDie($query, "0.78 add entities_id field in glpi_budgets");
    }
    if (!FieldExists("glpi_budgets", "is_deleted", false)) {
        $query = "ALTER TABLE `glpi_budgets`\n                ADD `is_deleted` tinyint(1) NOT NULL DEFAULT '0',\n                ADD INDEX `is_deleted` (`is_deleted`)";
        $DB->queryOrDie($query, "0.78 add is_deleted field in glpi_budgets");
    }
    if (!FieldExists("glpi_budgets", "begin_date", false)) {
        $query = "ALTER TABLE `glpi_budgets`\n                ADD `begin_date` DATE NULL,\n                ADD INDEX `begin_date` (`begin_date`)";
        $DB->queryOrDie($query, "0.78 add begin_date field in glpi_budgets");
    }
    if (!FieldExists("glpi_budgets", "end_date", false)) {
        $query = "ALTER TABLE `glpi_budgets`\n                ADD `end_date` DATE NULL,\n                ADD INDEX `end_date` (`begin_date`)";
        $DB->queryOrDie($query, "0.78 add end_date field in glpi_budgets");
    }
    if (!FieldExists("glpi_budgets", "value", false)) {
        $query = "ALTER TABLE `glpi_budgets`\n                ADD `value` DECIMAL( 20, 4 )  NOT NULL default '0.0000'";
        $DB->queryOrDie($query, "0.78 add value field in glpi_budgets");
    }
    if (!FieldExists("glpi_budgets", "is_template", false)) {
        $query = "ALTER TABLE `glpi_budgets`\n                ADD `is_template` tinyint(1) NOT NULL default '0',\n                ADD INDEX `is_template` (`is_template`);";
        $DB->queryOrDie($query, "0.78 add is_template field in glpi_budgets");
    }
    if (!FieldExists("glpi_budgets", "template_name", false)) {
        $query = "ALTER TABLE `glpi_budgets`\n                ADD `template_name` varchar(255) default NULL";
        $DB->queryOrDie($query, "0.78 add template_name field in glpi_budgets");
    }
    if (!FieldExists("glpi_budgets", "date_mod", false)) {
        $query = "ALTER TABLE `glpi_budgets`\n                ADD `date_mod`  DATETIME NULL, ADD INDEX `date_mod` (`date_mod`)";
        $DB->queryOrDie($query, "0.78 add date_mod field in glpi_budgets");
    }
    if (!FieldExists("glpi_budgets", "notepad", false)) {
        $query = "ALTER TABLE `glpi_budgets`\n                ADD `notepad` LONGTEXT NULL collate utf8_unicode_ci";
        $DB->queryOrDie($query, "0.78 add notepad field in glpi_budgets");
    }
    // Change budget search pref : date_mod
    $ADDTODISPLAYPREF['Budget'] = array(2, 3, 4, 19);
    $migration->displayMessage(sprintf(__('Change of the database layout - %s'), __('Automatic action')));
    if (!TableExists('glpi_crontasks')) {
        $query = "CREATE TABLE `glpi_crontasks` (\n                 `id` int(11) NOT NULL AUTO_INCREMENT,\n                 `itemtype` varchar(100) COLLATE utf8_unicode_ci NOT NULL,\n                 `name` varchar(150) COLLATE utf8_unicode_ci NOT NULL COMMENT 'task name',\n                 `frequency` int(11) NOT NULL COMMENT 'second between launch',\n                 `param` int(11) DEFAULT NULL COMMENT 'task specify parameter',\n                 `state` int(11) NOT NULL DEFAULT '1' COMMENT '0:disabled, 1:waiting, 2:running',\n                 `mode` int(11) NOT NULL DEFAULT '1' COMMENT '1:internal, 2:external',\n                 `allowmode` int(11) NOT NULL DEFAULT '3' COMMENT '1:internal, 2:external, 3:both',\n                 `hourmin` int(11) NOT NULL DEFAULT '0',\n                 `hourmax` int(11) NOT NULL DEFAULT '24',\n                 `logs_lifetime` int(11) NOT NULL DEFAULT '30' COMMENT 'number of days',\n                 `lastrun` datetime DEFAULT NULL COMMENT 'last run date',\n                 `lastcode` int(11) DEFAULT NULL COMMENT 'last run return code',\n                 `comment` text COLLATE utf8_unicode_ci,\n                 PRIMARY KEY (`id`),\n                 UNIQUE KEY `unicity` (`itemtype`,`name`),\n                 KEY `mode` (`mode`)\n               ) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci\n                 COMMENT='Task run by internal / external cron.';";
        $DB->queryOrDie($query, "0.78 create glpi_crontasks");
        $query = "INSERT INTO `glpi_crontasks`\n                       (`itemtype`, `name`, `frequency`, `param`, `state`, `mode`, `allowmode`,\n                        `hourmin`, `hourmax`, `logs_lifetime`, `lastrun`, `lastcode`, `comment`)\n                VALUES ('OcsServer', 'ocsng', 300, NULL, 1, 1, 3, 0, 24, 30, NULL, NULL, NULL),\n                       ('CartridgeItem', 'cartridge', 86400, 10, 0, 1, 3, 0, 24, 30, NULL, NULL,\n                        NULL),\n                       ('ConsumableItem', 'consumable', 86400, 10, 0, 1, 3, 0, 24, 30, NULL, NULL,\n                        NULL),\n                       ('SoftwareLicense', 'software', 86400, NULL, 0, 1, 3, 0, 24, 30, NULL, NULL,\n                        NULL),\n                       ('Contract', 'contract', 86400, NULL, 1, 1, 3, 0, 24, 30, NULL, NULL, NULL),\n                       ('InfoCom', 'infocom', 86400, NULL, 1, 1, 3, 0, 24, 30, NULL, NULL, NULL),\n                       ('CronTask', 'logs', 86400, 10, 1, 1, 3, 0, 24, 30, NULL, NULL, NULL),\n                       ('CronTask', 'optimize', 604800, NULL, 1, 1, 3, 0, 24, 30, NULL, NULL, NULL),\n                       ('MailCollector', 'mailgate', 600, 10, 1, 1, 3, 0, 24, 30, NULL, NULL, NULL),\n                       ('DBconnection', 'checkdbreplicate', 300, NULL, 0, 1, 3, 0, 24, 30, NULL, NULL, NULL),\n                       ('CronTask', 'checkupdate', 604800, NULL, 0, 1, 3, 0, 24, 30, NULL, NULL, NULL),\n                       ('CronTask', 'session', 86400, NULL, 1, 1, 3, 0, 24, 30, NULL, NULL, NULL),\n                       ('CronTask', 'graph', 3600, NULL, 1, 1, 3, 0, 24, 30, NULL, NULL, NULL),\n                       ('ReservationItem', 'reservation', 3600, NULL, 1, 1, 3, 0, 24, 30, NULL,\n                        NULL, NULL),\n                       ('Ticket', 'closeticket', '43200', NULL, '1', '1', '3', '0', '24', '30',\n                        NULL, NULL, NULL),\n                       ('Ticket', 'alertnotclosed', '43200', NULL, '1', '1', '3', '0', '24', '30',\n                        NULL, NULL, NULL)";
        $DB->queryOrDie($query, "0.78 populate glpi_crontasks");
    }
    $ADDTODISPLAYPREF['Crontask'] = array(8, 3, 4, 7);
    if (!TableExists('glpi_crontasklogs')) {
        $query = "CREATE TABLE `glpi_crontasklogs` (\n                 `id` int(11) NOT NULL AUTO_INCREMENT,\n                 `crontasks_id` int(11) NOT NULL,\n                 `crontasklogs_id` int(11) NOT NULL COMMENT 'id of ''start'' event',\n                 `date` datetime NOT NULL,\n                 `state` int(11) NOT NULL COMMENT '0:start, 1:run, 2:stop',\n                 `elapsed` float NOT NULL COMMENT 'time elapsed since start',\n                 `volume` int(11) NOT NULL COMMENT 'for statistics',\n                 `content` varchar(255) COLLATE utf8_unicode_ci NULL COMMENT 'message',\n                 PRIMARY KEY (`id`),\n                 KEY `date` (`date`),\n                 KEY `crontasks_id` (`crontasks_id`),\n                 KEY `crontasklogs_id_state` (`crontasklogs_id`,`state`)\n               ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ;";
        $DB->queryOrDie($query, "0.78 create glpi_crontasklogs");
    }
    // Retrieve core task lastrun date
    $tasks = array('ocsng', 'cartridge', 'consumable', 'software', 'contract', 'infocom', 'logs', 'optimize', 'mailgate', 'DBConnection', 'check_update', 'session');
    foreach ($tasks as $task) {
        $lock = GLPI_CRON_DIR . '/' . $task . '.lock';
        if (is_readable($lock) && ($stat = stat($lock))) {
            $DB->query("UPDATE `glpi_crontasks`\n                     SET `lastrun` = '" . date('Y-m-d H:i:s', $stat['mtime']) . "'\n                     WHERE `name` = '{$task}'");
            unlink($lock);
        }
    }
    // Clean plugin lock
    foreach (glob(GLPI_CRON_DIR . '/*.lock') as $lock) {
        unlink($lock);
    }
    // disable ocsng cron if not activate
    if (FieldExists('glpi_configs', 'use_ocs_mode', false)) {
        $query = "SELECT `use_ocs_mode`\n                FROM `glpi_configs`\n                WHERE `id` = 1";
        if ($result = $DB->query($query)) {
            if ($DB->numrows($result) > 0) {
                $value = $DB->result($result, 0, 0);
                if ($value == 0) {
                    $query = "UPDATE `glpi_crontasks`\n                         SET `state`='0'\n                         WHERE `name` = 'ocsng'";
                    $DB->query($query);
                }
            }
        }
    }
    // Move glpi_config.expire_events to glpi_crontasks.param
    if (FieldExists('glpi_configs', 'expire_events', false)) {
        $query = "SELECT `expire_events`\n                FROM `glpi_configs`\n                WHERE `id` = 1";
        if ($result = $DB->query($query)) {
            if ($DB->numrows($result) > 0) {
                $value = $DB->result($result, 0, 0);
                if ($value > 0) {
                    $query = "UPDATE `glpi_crontasks`\n                         SET `state` = '1',\n                             `param` = '{$value}'\n                         WHERE `name` = 'logs'";
                } else {
                    $query = "UPDATE `glpi_crontasks`\n                         SET `state` = '0'\n                         WHERE `name` = 'logs'";
                }
                $DB->query($query);
            }
        }
        $query = "ALTER TABLE `glpi_configs`\n                DROP `expire_events`";
        $DB->queryOrDie($query, "0.78 drop expire_events in glpi_configs");
    }
    // Move glpi_config.auto_update_check to glpi_crontasks.state
    if (FieldExists('glpi_configs', 'auto_update_check', false)) {
        $query = "SELECT `auto_update_check`\n                FROM `glpi_configs`\n                WHERE `id` = 1";
        if ($result = $DB->query($query)) {
            if ($DB->numrows($result) > 0) {
                $value = $DB->result($result, 0, 0);
                if ($value > 0) {
                    $value *= DAY_TIMESTAMP;
                    $query = "UPDATE `glpi_crontasks`\n                         SET `state` = '1',\n                             `frequency` = '{$value}'\n                         WHERE `name` = 'check_update'";
                } else {
                    $query = "UPDATE `glpi_crontasks`\n                         SET `state` = '0'\n                         WHERE `name` = 'logs'";
                }
                $DB->query($query);
            }
        }
        $query = "ALTER TABLE `glpi_configs`\n                DROP `auto_update_check`";
        $DB->queryOrDie($query, "0.78 drop auto_update_check in check_update");
    }
    if (FieldExists('glpi_configs', 'dbreplicate_maxdelay', false)) {
        $query = "SELECT `dbreplicate_maxdelay`\n                FROM `glpi_configs`\n                WHERE `id` = 1";
        if ($result = $DB->query($query)) {
            if ($DB->numrows($result) > 0) {
                $value = $DB->result($result, 0, 0);
                $value = intval($value / 60);
                $query = "UPDATE `glpi_crontasks`\n                      SET `state` = '1',\n                          `frequency` = '{$value}'\n                      WHERE `name` = 'check_dbreplicate'";
                $DB->query($query);
            }
        }
        $query = "ALTER TABLE `glpi_configs`\n                DROP `dbreplicate_maxdelay`";
        $DB->queryOrDie($query, "0.78 drop dbreplicate_maxdelay in check_update");
    }
    if (FieldExists('glpi_configs', 'dbreplicate_notify_desynchronization', false)) {
        $query = "ALTER TABLE `glpi_configs`\n                DROP `dbreplicate_notify_desynchronization`";
        $DB->queryOrDie($query, "0.78 drop dbreplicate_notify_desynchronization in check_update");
    }
    if (!FieldExists('glpi_configs', 'cron_limit', false)) {
        $query = "ALTER TABLE `glpi_configs`\n                ADD `cron_limit` TINYINT NOT NULL DEFAULT '1'\n                                 COMMENT 'Number of tasks execute by external cron'";
        $DB->queryOrDie($query, "0.78 add cron_limit in glpi_configs");
    }
    if (!FieldExists('glpi_documents', 'sha1sum', false)) {
        $query = "ALTER TABLE `glpi_documents`\n                ADD `sha1sum` CHAR(40) NULL DEFAULT NULL ,\n                ADD INDEX `sha1sum` (`sha1sum`)";
        $DB->queryOrDie($query, "0.78 add sha1sum in glpi_documents");
    }
    if (FieldExists('glpi_documents', 'filename', false)) {
        $query = "ALTER TABLE `glpi_documents`\n                  CHANGE `filename` `filename` VARCHAR( 255 ) NULL DEFAULT NULL\n                  COMMENT 'for display and transfert'";
        $DB->queryOrDie($query, "0.78 alter filename in glpi_documents");
    }
    if (!FieldExists('glpi_documents', 'filepath', false)) {
        $query = "ALTER TABLE `glpi_documents`\n                ADD `filepath` VARCHAR( 255 ) NULL\n                COMMENT 'file storage path' AFTER `filename`";
        $DB->queryOrDie($query, "0.78 add filepath in glpi_documents");
        $query = "UPDATE `glpi_documents`\n                SET `filepath` = `filename`";
        $DB->queryOrDie($query, "0.78 set value of filepath in glpi_documents");
    }
    $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'Category of tickets'));
    if (!FieldExists('glpi_tickets', 'solvedate', false)) {
        $query = "ALTER TABLE `glpi_tickets`\n                ADD `solvedate` datetime default NULL AFTER `closedate`,\n                ADD INDEX `solvedate` (`solvedate`)";
        $DB->queryOrDie($query, "0.78 add solvedate to glpi_tickets");
        $query = "UPDATE `glpi_tickets`\n                SET `solvedate` = `closedate`";
        $DB->queryOrDie($query, "0.78 update solvedate values in glpi_tickets");
    }
    if (!FieldExists('glpi_ticketcategories', 'entities_id', false)) {
        $query = "ALTER TABLE `glpi_ticketcategories`\n                ADD `entities_id` INT NOT NULL DEFAULT '0' AFTER `id`,\n                ADD `is_recursive` TINYINT( 1 ) NOT NULL DEFAULT '0' AFTER `entities_id`,\n                ADD INDEX `entities_id` (`entities_id`),\n                ADD INDEX `is_recursive` (`is_recursive`)";
        $DB->queryOrDie($query, "0.78 add entities_id,is_recursive in glpi_ticketcategories ");
        // Set existing categories recursive global
        $query = "UPDATE `glpi_ticketcategories`\n                SET `is_recursive` = '1'";
        $DB->queryOrDie($query, "0.78 set value of is_recursive in glpi_ticketcategories");
    }
    if (!FieldExists('glpi_ticketcategories', 'knowbaseitemcategories_id', false)) {
        $query = "ALTER TABLE `glpi_ticketcategories`\n                ADD `knowbaseitemcategories_id` INT NOT NULL DEFAULT '0',\n                ADD INDEX `knowbaseitemcategories_id` ( `knowbaseitemcategories_id` )";
        $DB->queryOrDie($query, "0.78 add knowbaseitemcategories_id in glpi_ticketcategories");
    }
    if (!FieldExists('glpi_ticketcategories', 'users_id', false)) {
        $query = "ALTER TABLE `glpi_ticketcategories`\n                ADD `users_id` INT NOT NULL DEFAULT '0',\n                ADD INDEX `users_id` ( `users_id` ) ";
        $DB->queryOrDie($query, "0.78 add users_id in glpi_ticketcategories");
    }
    if (!FieldExists('glpi_ticketcategories', 'groups_id', false)) {
        $query = "ALTER TABLE `glpi_ticketcategories`\n                ADD `groups_id` INT NOT NULL DEFAULT '0',\n                ADD INDEX `groups_id` ( `groups_id` ) ";
        $DB->queryOrDie($query, "0.78 add groups_id in glpi_ticketcategories");
    }
    if (!FieldExists('glpi_ticketcategories', 'ancestors_cache', false)) {
        $query = "ALTER TABLE `glpi_ticketcategories`\n                ADD `ancestors_cache` LONGTEXT NULL,\n                ADD `sons_cache` LONGTEXT NULL";
        $DB->queryOrDie($query, "0.78 add cache in glpi_ticketcategories");
    }
    if (!FieldExists('glpi_ticketcategories', 'is_helpdeskvisible', false)) {
        $query = "ALTER TABLE `glpi_ticketcategories`\n                ADD `is_helpdeskvisible` TINYINT( 1 ) NOT NULL DEFAULT '1',\n                ADD INDEX `is_helpdeskvisible` (`is_helpdeskvisible`)";
        $DB->queryOrDie($query, "0.78 add cache in glpi_ticketcategories");
    }
    // change item type management for helpdesk
    if (FieldExists('glpi_profiles', 'helpdesk_hardware_type', false)) {
        $query = "ALTER TABLE `glpi_profiles`\n                ADD `helpdesk_item_type` TEXT NULL DEFAULT NULL AFTER `helpdesk_hardware_type`";
        $DB->queryOrDie($query, "0.78 add  helpdesk_item_type in glpi_profiles");
        $query = "SELECT `id`, `helpdesk_hardware_type`\n                FROM `glpi_profiles`";
        if ($result = $DB->query($query)) {
            if ($DB->numrows($result) > 0) {
                while ($data = $DB->fetch_assoc($result)) {
                    $types = $data['helpdesk_hardware_type'];
                    $CFG_GLPI["ticket_types"] = array(COMPUTER_TYPE, NETWORKING_TYPE, PRINTER_TYPE, MONITOR_TYPE, PERIPHERAL_TYPE, SOFTWARE_TYPE, PHONE_TYPE);
                    $tostore = array();
                    foreach ($CFG_GLPI["ticket_types"] as $itemtype) {
                        if (pow(2, $itemtype) & $types) {
                            $tostore[] = $typetoname[$itemtype];
                        }
                    }
                    $query = "UPDATE `glpi_profiles`\n                         SET `helpdesk_item_type` = '" . exportArrayToDB($tostore) . "'\n                         WHERE `id` = '" . $data['id'] . "'";
                    $DB->queryOrDie($query, "0.78 populate helpdesk_item_type");
                }
            }
        }
        $query = "ALTER TABLE `glpi_profiles`\n                DROP `helpdesk_hardware_type`;";
        $DB->queryOrDie($query, "0.78 drop helpdesk_hardware_type in glpi_profiles");
    }
    if (!FieldExists('glpi_profiles', 'helpdesk_status', false)) {
        $query = "ALTER TABLE `glpi_profiles`\n                ADD `helpdesk_status` TEXT NULL\n                                      COMMENT 'json encoded array of from/dest allowed status change'\n                                      AFTER `helpdesk_item_type`";
        $DB->queryOrDie($query, "0.78 add helpdesk_status in glpi_profiles");
    }
    if (!FieldExists('glpi_profiles', 'update_priority', false)) {
        $query = "ALTER TABLE `glpi_profiles`\n                ADD `update_priority` CHAR( 1 ) NULL DEFAULT NULL AFTER `update_ticket`";
        $DB->queryOrDie($query, "0.78 add update_priority in glpi_profiles");
        $query = "UPDATE `glpi_profiles`\n                SET `update_priority` = `update_ticket`";
        $DB->queryOrDie($query, "0.78 set update_priority in glpi_profiles");
    }
    if (FieldExists('glpi_profiles', 'comment_ticket', false)) {
        $query = "ALTER TABLE `glpi_profiles`\n                CHANGE `comment_ticket` `add_followups` CHAR(1) NULL DEFAULT NULL";
        $DB->queryOrDie($query, "0.78 add add_followups in glpi_profiles");
    }
    if (FieldExists('glpi_profiles', 'comment_all_ticket', false)) {
        $query = "ALTER TABLE `glpi_profiles`\n                CHANGE `comment_all_ticket` `global_add_followups`  CHAR(1) NULL DEFAULT NULL";
        $DB->queryOrDie($query, "0.78 add add_followups in glpi_profiles");
    }
    if (!FieldExists('glpi_profiles', 'update_tasks', false)) {
        $query = "ALTER TABLE `glpi_profiles`\n                ADD `global_add_tasks` CHAR( 1 ) NULL AFTER `global_add_followups`,\n                ADD `update_tasks` CHAR( 1 ) NULL AFTER `update_followups`";
        $DB->queryOrDie($query, "0.78 add global_add_tasks, update_tasks in glpi_profiles");
        $query = "UPDATE `glpi_profiles`\n                SET `update_tasks` = `update_followups`,\n                    `global_add_tasks` =  `global_add_followups`";
        $DB->queryOrDie($query, "0.78 set update_tasks, global_add_tasks in glpi_profiles");
    }
    if (!TableExists('glpi_taskcategories')) {
        $query = "CREATE TABLE `glpi_taskcategories` (\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                  `taskcategories_id` int(11) NOT NULL default '0',\n                  `name` varchar(255) default NULL,\n                  `completename` text,\n                  `comment` text,\n                  `level` int(11) NOT NULL default '0',\n                  `ancestors_cache` longtext,\n                  `sons_cache` longtext,\n                  `is_helpdeskvisible` tinyint(1) NOT NULL default '1',\n                  PRIMARY KEY  (`id`),\n                  KEY `name` (`name`),\n                  KEY `taskcategories_id` (`taskcategories_id`),\n                  KEY `entities_id` (`entities_id`),\n                  KEY `is_recursive` (`is_recursive`),\n                  KEY `is_helpdeskvisible` (`is_helpdeskvisible`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.78 create glpi_taskcategories");
    }
    if (!TableExists('glpi_ticketsolutiontypes')) {
        $query = "CREATE TABLE `glpi_ticketsolutiontypes` (\n                  `id` int(11) NOT NULL auto_increment,\n                  `name` varchar(255) default NULL,\n                  `comment` text,\n                  PRIMARY KEY  (`id`),\n                  KEY `name` (`name`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.78 create glpi_ticketsolutiontypes");
        // Populate only required for migration of ticket status
        $query = "INSERT INTO `glpi_ticketsolutiontypes`\n                       (`id` ,`name` ,`comment`)\n                VALUES ('1', 'Closed (solved)', NULL),\n                       ('2', 'Closed (not solved)', NULL)";
        $DB->queryOrDie($query, "0.78 populate glpi_ticketsolutiontypes");
    }
    if (!FieldExists('glpi_tickets', 'solution', false)) {
        $query = "ALTER TABLE `glpi_tickets`\n                ADD `ticketsolutiontypes_id` INT( 11 ) NOT NULL DEFAULT '0',\n                ADD `solution` TEXT NULL";
        $DB->queryOrDie($query, "0.78 create glpi_ticketsolutions");
        $query = "ALTER TABLE `glpi_tickets`\n                ADD INDEX `ticketsolutiontypes_id` ( `ticketsolutiontypes_id` ) ";
        $DB->queryOrDie($query, "0.78 add key for glpi_ticketsolutions");
        // Move old status "old_done"", "old_notdone" as solution
        // and change to new "solved" / "closed" status
        $query = "UPDATE `glpi_tickets`\n                SET `ticketsolutiontypes_id` = '2',\n                    `status` = 'closed'\n                WHERE `status` = 'old_done'";
        $DB->queryOrDie($query, "0.78 migration of glpi_tickets status");
        $query = "UPDATE `glpi_tickets`\n                SET `ticketsolutiontypes_id` = '1',\n                    `status` = 'closed'\n                WHERE `status` = 'old_notdone'";
        $DB->queryOrDie($query, "0.78 migration of glpi_tickets status");
    }
    if (!FieldExists('glpi_documenttypes', 'comment', false)) {
        $query = "ALTER TABLE `glpi_documenttypes`\n                ADD `comment` TEXT NULL ";
        $DB->queryOrDie($query, "0.78 add comment in glpi_documenttypes");
    }
    if (!FieldExists('glpi_locations', 'is_recursive', false)) {
        $query = "ALTER TABLE `glpi_locations`\n                ADD `is_recursive` TINYINT( 1 ) NOT NULL DEFAULT '0' AFTER `entities_id`,\n                ADD `ancestors_cache` LONGTEXT NULL,\n                ADD `sons_cache` LONGTEXT NULL,\n                ADD INDEX `is_recursive` (`is_recursive`)";
        $DB->queryOrDie($query, "0.78 add recursive, cache in glpi_locations");
    }
    if (!FieldExists('glpi_locations', 'building', false)) {
        $query = "ALTER TABLE `glpi_locations`\n                ADD `building` VARCHAR( 255 ) NULL ,\n                ADD `room` VARCHAR( 255 ) NULL ";
        $DB->queryOrDie($query, "0.78 add building, room in glpi_locations");
    }
    if (!TableExists('glpi_requesttypes')) {
        $query = "CREATE TABLE `glpi_requesttypes` (\n              `id` int(11) NOT NULL AUTO_INCREMENT,\n              `name` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n              `is_helpdesk_default` tinyint(1) NOT NULL DEFAULT '0',\n              `is_mail_default` tinyint(1) NOT NULL DEFAULT '0',\n              `comment` text COLLATE utf8_unicode_ci,\n              PRIMARY KEY (`id`),\n              KEY `name` (`name`),\n              KEY `is_helpdesk_default` (`is_helpdesk_default`),\n              KEY `is_mail_default` (`is_mail_default`)\n            ) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.78 create glpi_requesttypes");
        $DB->query("INSERT INTO `glpi_requesttypes`\n                  VALUES(1, '" . addslashes(__('Simplified interface')) . "', 1, 0, NULL)");
        $DB->query("INSERT INTO `glpi_requesttypes`\n                  VALUES(2, '" . addslashes(__('Email')) . "', 0, 1, NULL)");
        $DB->query("INSERT INTO `glpi_requesttypes`\n                  VALUES(3, '" . addslashes(__('Phone')) . "', 0, 0, NULL)");
        $DB->query("INSERT INTO `glpi_requesttypes`\n                  VALUES(4, '" . addslashes(__('Direct')) . "', 0, 0, NULL)");
        $DB->query("INSERT INTO `glpi_requesttypes`\n                  VALUES(5, '" . addslashes(__('Written')) . "', 0, 0, NULL)");
        $DB->query("INSERT INTO `glpi_requesttypes`\n                  VALUES(6, '" . addslashes(__('Other')) . "', 0, 0, NULL)");
    }
    // Add default display
    $ADDTODISPLAYPREF['RequestType'] = array(14, 15);
    if (FieldExists('glpi_tickets', 'request_type', false)) {
        $query = "ALTER TABLE `glpi_tickets`\n                CHANGE `request_type` `requesttypes_id` INT( 11 ) NOT NULL DEFAULT '0'";
        $DB->queryOrDie($query, "0.78 change requesttypes_id in glpi_tickets");
    }
    if (FieldExists('glpi_configs', 'default_request_type', false)) {
        $query = "ALTER TABLE `glpi_configs`\n                CHANGE `default_request_type` `default_requesttypes_id` INT( 11 ) NOT NULL\n                                                                        DEFAULT '1'";
        $DB->queryOrDie($query, "0.78 change requesttypes_id in glpi_configs");
    }
    if (FieldExists('glpi_users', 'default_request_type', false)) {
        $query = "ALTER TABLE `glpi_users`\n                CHANGE `default_request_type` `default_requesttypes_id` INT( 11 ) NULL DEFAULT NULL";
        $DB->queryOrDie($query, "0.78 change requesttypes_id in glpi_users");
    }
    if (!FieldExists('glpi_groups', 'date_mod', false)) {
        $query = "ALTER TABLE `glpi_groups`\n                ADD `date_mod` DATETIME NULL, ADD INDEX `date_mod` (`date_mod`)";
        $DB->queryOrDie($query, "0.78 add date_mod to glpi_groups");
    }
    if (!FieldExists("glpi_configs", "priority_matrix", false)) {
        $query = "ALTER TABLE `glpi_configs`\n                ADD `priority_matrix` VARCHAR( 255 ) NULL\n                                      COMMENT 'json encoded array for Urgence / Impact to Protority'";
        $DB->queryOrDie($query, "0.78 add priority_matrix  in glpi_configs");
        $matrix = array(1 => array(1 => 1, 2 => 1, 3 => 2, 4 => 2, 4 => 2, 5 => 2), 2 => array(1 => 1, 2 => 2, 3 => 2, 4 => 3, 4 => 3, 5 => 3), 3 => array(1 => 2, 2 => 2, 3 => 3, 4 => 4, 4 => 4, 5 => 4), 4 => array(1 => 2, 2 => 3, 3 => 4, 4 => 4, 4 => 4, 5 => 5), 5 => array(1 => 2, 2 => 3, 3 => 4, 4 => 5, 4 => 5, 5 => 5));
        $matrix = exportArrayToDB($matrix);
        $query = "UPDATE `glpi_configs`\n                SET `priority_matrix` = '{$matrix}'\n                WHERE `id` = '1'";
        $DB->queryOrDie($query, "0.78 set default priority_matrix  in glpi_configs");
    }
    if (!FieldExists("glpi_configs", "urgency_mask", false)) {
        $query = "ALTER TABLE `glpi_configs`\n                ADD `urgency_mask` INT( 11 ) NOT NULL DEFAULT '62',\n                ADD `impact_mask` INT( 11 ) NOT NULL DEFAULT '62'";
        $DB->queryOrDie($query, "0.78 add urgency/impact_mask  in glpi_configs");
    }
    if (!FieldExists("glpi_users", "priority_6", false)) {
        $query = "ALTER TABLE `glpi_users`\n                ADD `priority_6` CHAR( 20 ) NULL DEFAULT NULL AFTER `priority_5`";
        $DB->queryOrDie($query, "0.78 add priority_6  in glpi_users");
    }
    if (!FieldExists("glpi_configs", "priority_6", false)) {
        $query = "ALTER TABLE `glpi_configs`\n                ADD `priority_6` CHAR( 20 ) NOT NULL DEFAULT '#ff5555' AFTER `priority_5`";
        $DB->queryOrDie($query, "0.78 add priority_6  in glpi_configs");
    }
    if (!FieldExists('glpi_tickets', 'urgency', false)) {
        $query = "ALTER TABLE `glpi_tickets`\n                ADD `urgency` INT NOT NULL DEFAULT '1' AFTER `content`,\n                ADD `impact` INT NOT NULL DEFAULT '1' AFTER `urgency`,\n                ADD INDEX `urgency` (`urgency`),\n                ADD INDEX `impact` (`impact`)";
        $DB->queryOrDie($query, "0.78 add urgency, impact to glpi_tickets");
        // set default trivial values for Impact and Urgence
        $query = "UPDATE `glpi_tickets`\n                SET `urgency` = `priority`,\n                    `impact` = `priority`";
        $DB->queryOrDie($query, "0.78 set urgency, impact in glpi_tickets");
        // Replace 'priority' (user choice un 0.72) by 'urgency' as criteria
        // Don't change "action" which is the result of user+tech evaluation.
        $query = "UPDATE `glpi_rulecriterias`\n                SET `criteria`='urgency'\n                WHERE `criteria`='priority'\n                      AND `rules_id` IN (SELECT `id`\n                                         FROM `glpi_rules`\n                                         WHERE `sub_type` = 'RuleTicket')";
        $DB->queryOrDie($query, "0.78 fix priority/urgency in business rules");
    }
    if (!TableExists('glpi_tickettasks')) {
        $query = "CREATE TABLE `glpi_tickettasks` (\n                  `id` int(11) NOT NULL auto_increment,\n                  `tickets_id` int(11) NOT NULL default '0',\n                  `taskcategories_id` int(11) NOT NULL default '0',\n                  `date` datetime default NULL,\n                  `users_id` int(11) NOT NULL default '0',\n                  `content` longtext collate utf8_unicode_ci,\n                  `is_private` tinyint(1) NOT NULL default '0',\n                  `realtime` float NOT NULL default '0',\n                  PRIMARY KEY  (`id`),\n                  KEY `date` (`date`),\n                  KEY `users_id` (`users_id`),\n                  KEY `tickets_id` (`tickets_id`),\n                  KEY `is_private` (`is_private`),\n                  KEY `taskcategories_id` (`taskcategories_id`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.78 create glpi_tickettasks");
        // Required for migration from ticketfollowups to tickettasks - planned followups
        $query = "INSERT INTO `glpi_tickettasks`\n                    (`id`, `tickets_id`, `date`, `users_id`, `content`, `is_private`, `realtime`)\n                   SELECT `glpi_ticketfollowups`.`id`,\n                          `glpi_ticketfollowups`.`tickets_id`,\n                          `glpi_ticketfollowups`.`date`,\n                          `glpi_ticketfollowups`.`users_id`,\n                          `glpi_ticketfollowups`.`content`,\n                          `glpi_ticketfollowups`.`is_private`,\n                          `glpi_ticketfollowups`.`realtime`\n                   FROM `glpi_ticketfollowups`\n                   INNER JOIN `glpi_ticketplannings`\n                     ON (`glpi_ticketplannings`.`ticketfollowups_id` = `glpi_ticketfollowups`.`id`)";
        $DB->queryOrDie($query, "0.78 populate glpi_tickettasks");
        // delete from ticketfollowups - planned followups, previously copied
        $query = "DELETE FROM `glpi_ticketfollowups`\n                WHERE `glpi_ticketfollowups`.`id`\n                        IN (SELECT `glpi_ticketplannings`.`ticketfollowups_id`\n                            FROM `glpi_ticketplannings`)";
        $DB->queryOrDie($query, "0.78 delete from glpi_ticketfollowups");
        // Required for migration from ticketfollowups to tickettasks - followups with a duration
        $query = "INSERT INTO `glpi_tickettasks`\n                    (`id`, `tickets_id`, `date`, `users_id`, `content`, `is_private`, `realtime`)\n                   SELECT `glpi_ticketfollowups`.`id`,\n                          `glpi_ticketfollowups`.`tickets_id`,\n                          `glpi_ticketfollowups`.`date`,\n                          `glpi_ticketfollowups`.`users_id`,\n                          `glpi_ticketfollowups`.`content`,\n                          `glpi_ticketfollowups`.`is_private`,\n                          `glpi_ticketfollowups`.`realtime`\n                   FROM `glpi_ticketfollowups`\n                   WHERE `realtime`>0";
        $DB->queryOrDie($query, "0.78 populate glpi_tickettasks");
        // delete from ticketfollowups - followups with duration, previously copied
        $query = "DELETE FROM `glpi_ticketfollowups`\n                WHERE `realtime` > 0";
        $DB->queryOrDie($query, "0.78 delete from glpi_ticketfollowups");
        // ticketplannings is for tickettasks
        $query = "ALTER TABLE `glpi_ticketplannings`\n                CHANGE `ticketfollowups_id` `tickettasks_id` int(11) NOT NULL default '0'";
        $DB->queryOrDie($query, "0.78 alter glpi_ticketplannings");
        // add requesttype for glpi_ticketfollowups
        $query = "ALTER TABLE `glpi_ticketfollowups`\n                DROP `realtime`,\n                ADD `requesttypes_id` int(11) NOT NULL default '0',\n                ADD INDEX `requesttypes_id` (`requesttypes_id`)";
        $DB->queryOrDie($query, "0.78 alter glpi_ticketplannings");
    }
    // Migrate devices
    if (TableExists('glpi_computer_device')) {
        $migration->displayMessage(sprintf(__('Change of the database layout - %s'), _n('Component', 'Components', 2)));
        foreach ($devtypetoname as $key => $itemtype) {
            $migration->displayMessage(sprintf(__('Change of the database layout - %s'), $itemtype));
            $linktype = "Computer_{$itemtype}";
            $linktable = getTableForItemType($linktype);
            $itemtable = getTableForItemType($itemtype);
            $fkname = getForeignKeyFieldForTable($itemtable);
            $withspecifity = array(MOBOARD_DEVICE => false, PROCESSOR_DEVICE => 'int', RAM_DEVICE => 'int', HDD_DEVICE => 'int', NETWORK_DEVICE => 'varchar', DRIVE_DEVICE => false, CONTROL_DEVICE => false, GFX_DEVICE => 'int', SND_DEVICE => false, PCI_DEVICE => false, CASE_DEVICE => false, POWER_DEVICE => false);
            if (FieldExists($itemtable, 'specif_default', false)) {
                // Convert default specifity
                if ($withspecifity[$key]) {
                    // Convert data to int
                    if ($withspecifity[$key] == 'int') {
                        // clean non integer values
                        $query = "UPDATE `{$itemtable}`\n                            SET `specif_default` = 0\n                            WHERE `specif_default` NOT REGEXP '^[0-9]*\$'\n                                  OR `specif_default` = ''\n                                  OR `specif_default` IS NULL";
                        $DB->queryOrDie($query, "0.78 update specif_default in {$itemtable}");
                        $query = "ALTER TABLE `{$itemtable}`\n                            CHANGE `specif_default` `specif_default` INT(11) NOT NULL";
                        $DB->queryOrDie($query, "0.78 alter specif_default in {$itemtable}");
                    }
                } else {
                    // Drop default specificity
                    $query = "ALTER TABLE `{$itemtable}`\n                         DROP `specif_default`";
                    $DB->queryOrDie($query, "0.78 drop specif_default in {$itemtable}");
                }
            }
            if (!TableExists($linktable)) {
                // create table
                $query = "CREATE TABLE `{$linktable}` (\n                        `id` int(11) NOT NULL auto_increment,\n                        `computers_id` int(11) NOT NULL default '0',\n                        `{$fkname}` int(11) NOT NULL default '0',";
                if ($withspecifity[$key]) {
                    if ($withspecifity[$key] == 'int') {
                        $query .= "`specificity` int(11) NOT NULL,";
                    } else {
                        $query .= "`specificity` varchar(255) collate utf8_unicode_ci default NULL,";
                    }
                }
                $query .= "PRIMARY KEY  (`id`),\n                       KEY `computers_id` (`computers_id`),\n                       KEY `{$fkname}` (`{$fkname}`)";
                if ($withspecifity[$key]) {
                    $query .= ",KEY `specificity` (`specificity`)";
                }
                $query .= ") ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;";
                $DB->queryOrDie($query, "0.78 create {$linktable}");
                // Update data before copy
                if ($withspecifity[$key]) {
                    // Convert data to int
                    if ($withspecifity[$key] == 'int') {
                        // clean non integer values
                        $query = "UPDATE `glpi_computer_device`\n                            SET `specificity` = 0\n                            WHERE device_type = {$key}\n                                 AND `specificity` NOT REGEXP '^[0-9]*\$'\n                                     OR `specificity` = ''";
                        $DB->queryOrDie($query, "0.78 update specificity in glpi_computer_device for {$itemtype}");
                    }
                }
                // copy datas to new table : keep id for ocs sync
                $query = "INSERT INTO `{$linktable}` (`id`, `computers_id`, `{$fkname}`\n                                                " . ($withspecifity[$key] ? ", `specificity`" : '') . ")\n                        SELECT `ID`, `FK_computers`, `FK_device`\n                               " . ($withspecifity[$key] ? ", specificity" : '') . "\n                        FROM `glpi_computer_device`\n                        WHERE `device_type` = {$key}";
                $DB->queryOrDie($query, "0.78 populate {$linktable}");
            }
        }
        // Drop computer_device_table
        $query = "DROP TABLE `glpi_computer_device`";
        $DB->queryOrDie($query, "0.78 drop glpi_computer_device");
    }
    if (!FieldExists('glpi_users', 'task_private', false)) {
        $query = "ALTER TABLE `glpi_users`\n                ADD `task_private` TINYINT(1) DEFAULT NULL AFTER `followup_private`";
        $DB->queryOrDie($query, "0.78 add task_private to glpi_users");
    }
    if (!FieldExists('glpi_configs', 'task_private', false)) {
        $query = "ALTER TABLE `glpi_configs`\n                ADD `task_private` TINYINT(1) NOT NULL DEFAULT '0' AFTER `followup_private`";
        $DB->queryOrDie($query, "0.78 add task_private to glpi_users");
    }
    if (!FieldExists('glpi_rules', 'date_mod', false)) {
        $query = "ALTER TABLE `glpi_rules`\n                ADD `date_mod` DATETIME NULL,\n                ADD INDEX `date_mod` (`date_mod`)";
        $DB->queryOrDie($query, "0.78 add date_mod to glpi_rules");
    }
    if (!FieldExists('glpi_authldaps', 'entity_field', false)) {
        $query = "ALTER TABLE `glpi_authldaps`\n                ADD `entity_field` VARCHAR( 255 ) DEFAULT NULL";
        $DB->queryOrDie($query, "0.78 add entity_field to glpi_authldaps");
    }
    if (!FieldExists('glpi_authldaps', 'entity_condition', false)) {
        $query = "ALTER TABLE `glpi_authldaps`\n               ADD `entity_condition`  TEXT NULL collate utf8_unicode_ci";
        $DB->queryOrDie($query, "0.78 add entity_condition to glpi_authldaps");
    }
    if (!FieldExists('glpi_entitydatas', 'ldapservers_id', false)) {
        $query = "ALTER TABLE `glpi_entitydatas`\n               ADD `ldapservers_id` INT( 11 ) NOT NULL DEFAULT '0'";
        $DB->queryOrDie($query, "0.78 add ldapservers_id to glpi_entitydatas");
    }
    if (!FieldExists('glpi_entitydatas', 'mail_domain', false)) {
        $query = "ALTER TABLE `glpi_entitydatas`\n                ADD `mail_domain` VARCHAR( 255 ) DEFAULT NULL";
        $DB->queryOrDie($query, "0.78 add mail_domain to glpi_entitydatas");
    }
    if (!FieldExists('glpi_entitydatas', 'entity_ldapfilter', false)) {
        $query = "ALTER TABLE `glpi_entitydatas`\n                ADD `entity_ldapfilter` TEXT NULL collate utf8_unicode_ci";
        $DB->queryOrDie($query, "0.78 add entity_ldapfilter to glpi_entitydatas");
    }
    if (!FieldExists('glpi_profiles', 'import_externalauth_users', false)) {
        $query = "ALTER TABLE `glpi_profiles`\n                ADD `import_externalauth_users` CHAR( 1 ) NULL";
        $DB->queryOrDie($query, "0.78 add import_externalauth_users in glpi_profiles");
        $query = "UPDATE `glpi_profiles`\n                SET `import_externalauth_users` = 'w'\n                WHERE `user` ='w'";
        $DB->queryOrDie($query, "0.78 add import_externalauth_users right users which are able to write users");
    }
    $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'Notifications'));
    $templates = array();
    if (!TableExists('glpi_notificationtemplates')) {
        $query = "CREATE TABLE `glpi_notificationtemplates` (\n                 `id` INT( 11 ) NOT NULL AUTO_INCREMENT ,\n                 `name` VARCHAR( 255 ) default NULL ,\n                 `itemtype` VARCHAR( 100 ) NOT NULL,\n                 `date_mod` DATETIME DEFAULT NULL ,\n                 `comment` text collate utf8_unicode_ci,\n                 PRIMARY KEY ( `ID` ),\n                 KEY `itemtype` (`itemtype`),\n                 KEY `date_mod` (`date_mod`),\n                 KEY `name` (`name`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.78 create glpi_notificationtemplates");
        $queries['DBConnection'] = "INSERT INTO `glpi_notificationtemplates`\n                                  VALUES(NULL, 'MySQL Synchronization', 'DBConnection', NOW(),'');";
        $queries['Reservation'] = "INSERT INTO `glpi_notificationtemplates`\n                                  VALUES(NULL, 'Reservations', 'Reservation', NOW(),'');";
        $queries['Reservation2'] = "INSERT INTO `glpi_notificationtemplates`\n                                  VALUES(NULL, 'Alert Reservation', 'Reservation', NOW(),'');";
        $queries['Ticket'] = "INSERT INTO `glpi_notificationtemplates`\n                                  VALUES(NULL, 'Tickets', 'Ticket', NOW(),'');";
        $queries['Ticket2'] = "INSERT INTO `glpi_notificationtemplates`\n                                  VALUES(NULL, 'Tickets (Simple)', 'Ticket', NOW(),'');";
        $queries['Ticket3'] = "INSERT INTO `glpi_notificationtemplates`\n                                  VALUES(NULL, 'Alert Tickets not closed', 'Ticket', NOW(),'');";
        $queries['TicketValidation'] = "INSERT INTO `glpi_notificationtemplates`\n                                    VALUES(NULL, 'Tickets Validation', 'Ticket', NOW(),'');";
        $queries['Cartridge'] = "INSERT INTO `glpi_notificationtemplates`\n                                  VALUES(NULL, 'Cartridges', 'Cartridge', NOW(),'');";
        $queries['Consumable'] = "INSERT INTO `glpi_notificationtemplates`\n                                  VALUES(NULL, 'Consumables', 'Consumable', NOW(),'');";
        $queries['Infocom'] = "INSERT INTO `glpi_notificationtemplates`\n                                  VALUES(NULL, 'Infocoms', 'Infocom', NOW(),'');";
        $queries['SoftwareLicense'] = "INSERT INTO `glpi_notificationtemplates`\n                                     VALUES(NULL, 'Licenses', 'SoftwareLicense', NOW(),'');";
        $queries['Contract'] = "INSERT INTO `glpi_notificationtemplates`\n                                  VALUES(NULL, 'Contracts', 'Contract', NOW(),'');";
        foreach ($queries as $itemtype => $query) {
            $DB->queryOrDie($query, "0.78 insert notification template for {$itemtype}");
            $templates[$itemtype] = $DB->insert_id();
        }
        $ADDTODISPLAYPREF['NotificationTemplate'] = array(4, 16);
        //There was a problem with GLPI < 0.78 : smtp_port field wans'nt used : migrate it
        $query = "SELECT `smtp_host`\n                FROM `glpi_configs`\n                WHERE `id` = '1'";
        $result = $DB->query($query);
        $host = $DB->result($result, 0, 'smtp_host');
        $results = array();
        preg_match("/(.*):([0-9]*)/", $host, $results);
        if (!empty($results)) {
            $query = "UPDATE `glpi_configs`\n                   SET `smtp_host` = '" . $results[1] . "' ,\n                       `smtp_port` = '" . $results[2] . "'\n                   WHERE `id` = '1'";
            $DB->query($query);
        }
    }
    if (!TableExists('glpi_notificationtemplatetranslations')) {
        $query = "CREATE TABLE `glpi_notificationtemplatetranslations` (\n                  `id` INT( 11 ) NOT NULL AUTO_INCREMENT ,\n                  `notificationtemplates_id` INT( 11 ) NOT NULL DEFAULT '0',\n                  `language` CHAR ( 5 ) NOT NULL DEFAULT '',\n                  `subject` VARCHAR( 255 ) NOT NULL ,\n                  `content_text` TEXT NULL ,\n                  `content_html` TEXT NULL ,\n                  PRIMARY KEY ( `id` ),\n                  KEY `notificationtemplates_id` (`notificationtemplates_id`)\n                 )ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.78 create glpi_notificationtemplatetranslations");
        $queries = array();
        $queries['DBConnection'] = "INSERT INTO `glpi_notificationtemplatetranslations`\n                                  VALUES(NULL, " . $templates['DBConnection'] . ", '','##lang.dbconnection.title##',\n                        '##lang.dbconnection.delay## : ##dbconnection.delay##\r\n',\n                        '&lt;p&gt;##lang.dbconnection.delay## : ##dbconnection.delay##&lt;/p&gt;');";
        $content_text_reservation = "======================================================================\r\n" . "##lang.reservation.user##: ##reservation.user##\r\n" . "##lang.reservation.item.name##: ##reservation.itemtype## - ##reservation.item.name##\r\n" . "##IFreservation.tech## ##lang.reservation.tech## ##reservation.tech## ##ENDIFreservation.tech##\r\n" . "##lang.reservation.begin##: ##reservation.begin##\r\n" . "##lang.reservation.end##: ##reservation.end##\r\n" . "##lang.reservation.comment##: ##reservation.comment##\r\n" . "======================================================================\r\n";
        $content_html_reservation = "&lt;!-- description{ color: inherit; background: #ebebeb;" . "border-style: solid;border-color: #8d8d8d; border-width: 0px 1px 1px 0px; }" . " --&gt;\r\n&lt;p&gt;&lt;span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"&gt;" . "##lang.reservation.user##:&lt;/span&gt;##reservation.user##" . "&lt;br /&gt; &lt;span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"&gt;" . "##lang.reservation.item.name##:&lt;/span&gt;" . "##reservation.itemtype## - ##reservation.item.name##&lt;br /&gt;" . "##IFreservation.tech## ##lang.reservation.tech## ##reservation.tech##" . "##ENDIFreservation.tech##&lt;br /&gt; &lt;span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"&gt;" . "##lang.reservation.begin##:&lt;/span&gt; ##reservation.begin##" . "&lt;br /&gt; &lt;span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"&gt;" . "##lang.reservation.end##:&lt;/span&gt;" . "##reservation.end##&lt;br /&gt; &lt;span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"&gt;" . "##lang.reservation.comment##:&lt;/span&gt; ##reservation.comment##" . "&lt;/p&gt;";
        $queries['Reservation'] = "INSERT INTO `glpi_notificationtemplatetranslations`\n                                 VALUES(NULL, " . $templates['Reservation'] . ", '',\n                                        '##reservation.action##', '{$content_text_reservation}',\n                                        '{$content_html_reservation}')";
        $queries['Reservation2'] = "INSERT INTO `glpi_notificationtemplatetranslations`\n                                  VALUES(NULL, " . $templates['Reservation2'] . ", '',\n                                    '##reservation.action##  ##reservation.entity##',\n                                    '##lang.reservation.entity## : ##reservation.entity## \r\n\n \r\n##FOREACHreservations## \r\n##lang.reservation.itemtype## : ##reservation.itemtype##\r\n\n ##lang.reservation.item## : ##reservation.item##\r\n \r\n ##reservation.url## \r\n\n ##ENDFOREACHreservations##',\n '&lt;p&gt;##lang.reservation.entity## : ##reservation.entity## &lt;br /&gt; &lt;br /&gt;\n##FOREACHreservations## &lt;br /&gt;##lang.reservation.itemtype## : ##reservation.itemtype##&lt;br /&gt;\n ##lang.reservation.item## : ##reservation.item##&lt;br /&gt; &lt;br /&gt;\n &lt;a href=\"##reservation.url##\"&gt; ##reservation.url##&lt;/a&gt;&lt;br /&gt;\n ##ENDFOREACHreservations##&lt;/p&gt;');";
        $queries['Ticket'] = "INSERT INTO `glpi_notificationtemplatetranslations`\n                            VALUES(NULL, '" . $templates['Ticket'] . "', '',\n                            '##ticket.action## ##ticket.title##',\n' ##IFticket.storestatus=solved##\n ##lang.ticket.url## : ##ticket.urlapprove##\n ##lang.ticket.autoclosewarning##\n ##lang.ticket.solvedate## : ##ticket.solvedate##\n ##lang.ticket.solution.type## : ##ticket.solution.type##\n ##lang.ticket.solution.description## : ##ticket.solution.description## ##ENDIFticket.storestatus##\n ##ELSEticket.storestatus## ##lang.ticket.url## : ##ticket.url## ##ENDELSEticket.storestatus##\n\n ##lang.ticket.description##\n\n ##lang.ticket.title## : ##ticket.title##\n ##lang.ticket.author.name## : ##IFticket.author.name## ##ticket.author.name## ##ENDIFticket.author.name## ##ELSEticket.author.name##--##ENDELSEticket.author.name##\n ##lang.ticket.creationdate## : ##ticket.creationdate##\n ##lang.ticket.closedate## : ##ticket.closedate##\n ##lang.ticket.requesttype## : ##ticket.requesttype##\n ##IFticket.itemtype## ##lang.ticket.item.name## : ##ticket.itemtype## - ##ticket.item.name## ##IFticket.item.model## - ##ticket.item.model## ##ENDIFticket.item.model## ##IFticket.item.serial## - ##ticket.item.serial## ##ENDIFticket.item.serial##  ##IFticket.item.otherserial## -##ticket.item.otherserial## ##ENDIFticket.item.otherserial## ##ENDIFticket.itemtype##\n##IFticket.assigntouser## ##lang.ticket.assigntouser## : ##ticket.assigntouser## ##ENDIFticket.assigntouser##\n ##lang.ticket.status## : ##ticket.status##\n##IFticket.assigntogroup## ##lang.ticket.assigntogroup## : ##ticket.assigntogroup## ##ENDIFticket.assigntogroup##\n ##lang.ticket.urgency## : ##ticket.urgency##\n ##lang.ticket.impact## : ##ticket.impact##\n ##lang.ticket.priority## : ##ticket.priority##\n##IFticket.user.email## ##lang.ticket.user.email## : ##ticket.user.email ##ENDIFticket.user.email##\n##IFticket.category## ##lang.ticket.category## : ##ticket.category## ##ENDIFticket.category## ##ELSEticket.category## ##lang.ticket.nocategoryassigned## ##ENDELSEticket.category##\n ##lang.ticket.content## : ##ticket.content##\n\n ##IFticket.storestatus=closed##\n\n ##lang.ticket.solvedate## : ##ticket.solvedate##\n ##lang.ticket.solution.type## : ##ticket.solution.type##\n ##lang.ticket.solution.description## : ##ticket.solution.description##\n ##ENDIFticket.storestatus##\n ##lang.ticket.numberoffollowups## : ##ticket.numberoffollowups##\n\n##FOREACHfollowups##\n\n [##followup.date##] ##lang.followup.isprivate## : ##followup.isprivate##\n ##lang.followup.author## ##followup.author##\n ##lang.followup.description## ##followup.description##\n ##lang.followup.date## ##followup.date##\n ##lang.followup.requesttype## ##followup.requesttype##\n\n##ENDFOREACHfollowups##\n ##lang.ticket.numberoftasks## : ##ticket.numberoftasks##\n\n##FOREACHtasks##\n\n [##task.date##] ##lang.task.isprivate## : ##task.isprivate##\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'<!-- description{ color: inherit; background: #ebebeb; border-style: solid;border-color: #8d8d8d; border-width: 0px 1px 1px 0px; }    -->\n<div>##IFticket.storestatus=solved##</div>\n<div>##lang.ticket.url## : <a href=\"##ticket.urlapprove##\">##ticket.urlapprove##</a> <span class=\"b\">&#160;</span></div>\n<div><span class=\"b\">##lang.ticket.autoclosewarning##</span> </div>\n<div><span style=\"color: #888888;\"><span class=\"b\"><span style=\"text-decoration: underline;\">##lang.ticket.solvedate##</span></span></span> : ##ticket.solvedate##<br /><span style=\"text-decoration: underline; color: #888888;\"><span class=\"b\">##lang.ticket.solution.type##</span></span> : ##ticket.solution.type##<br /><span style=\"text-decoration: underline; color: #888888;\"><span class=\"b\">##lang.ticket.solution.description##</span></span> : ##ticket.solution.description## ##ENDIFticket.storestatus##</div>\n<div>##ELSEticket.storestatus## ##lang.ticket.url## : <a href=\"##ticket.url##\">##ticket.url##</a> ##ENDELSEticket.storestatus##</div>\n<div class=\"description b\"><span class=\"b\">##lang.ticket.description##</span></div>\n<p><span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"> ##lang.ticket.title##</span>&#160;:##ticket.title## <br /> <span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"> ##lang.ticket.author.name##</span>&#160;:##IFticket.author.name## ##ticket.author.name## ##ENDIFticket.author.name##    ##ELSEticket.author.name##--##ENDELSEticket.author.name## <br /> <span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"> ##lang.ticket.creationdate##</span>&#160;:##ticket.creationdate## <br /> <span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"> ##lang.ticket.closedate##</span>&#160;:##ticket.closedate## <br /> <span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"> ##lang.ticket.requesttype##</span>&#160;:##ticket.requesttype##<br /> ##IFticket.itemtype## <span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"> ##lang.ticket.item.name##</span>&#160;: ##ticket.itemtype## - ##ticket.item.name##    ##IFticket.item.model## - ##ticket.item.model##    ##ENDIFticket.item.model## ##IFticket.item.serial## -##ticket.item.serial## ##ENDIFticket.item.serial##&#160; ##IFticket.item.otherserial## -##ticket.item.otherserial##  ##ENDIFticket.item.otherserial## ##ENDIFticket.itemtype## <br /> ##IFticket.assigntouser## <span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"> ##lang.ticket.assigntouser##</span>&#160;: ##ticket.assigntouser## ##ENDIFticket.assigntouser##<br /> <span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\">##lang.ticket.status## </span>&#160;: ##ticket.status##<br /> ##IFticket.assigntogroup## <span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"> ##lang.ticket.assigntogroup##</span>&#160;: ##ticket.assigntogroup## ##ENDIFticket.assigntogroup##<br /> <span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"> ##lang.ticket.urgency##</span>&#160;: ##ticket.urgency##<br /> <span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"> ##lang.ticket.impact##</span>&#160;: ##ticket.impact##<br /> <span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"> ##lang.ticket.priority##</span>&#160;: ##ticket.priority## <br /> ##IFticket.user.email##<span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"> ##lang.ticket.user.email##</span>&#160;: ##ticket.user.email ##ENDIFticket.user.email##    <br /> ##IFticket.category##<span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\">##lang.ticket.category## </span>&#160;:##ticket.category## ##ENDIFticket.category## ##ELSEticket.category## ##lang.ticket.nocategoryassigned## ##ENDELSEticket.category##    <br /> <span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"> ##lang.ticket.content##</span>&#160;: ##ticket.content##</p>\n<br />##IFticket.storestatus=closed##<br /><span style=\"text-decoration: underline;\"><span class=\"b\"><span style=\"color: #888888;\">##lang.ticket.solvedate##</span></span></span> : ##ticket.solvedate##<br /><span style=\"color: #888888;\"><span class=\"b\"><span style=\"text-decoration: underline;\">##lang.ticket.solution.type##</span></span></span> : ##ticket.solution.type##<br /><span style=\"text-decoration: underline; color: #888888;\"><span class=\"b\">##lang.ticket.solution.description##</span></span> : ##ticket.solution.description##<br />##ENDIFticket.storestatus##</p>\n<div class=\"description b\">##lang.ticket.numberoffollowups##&#160;: ##ticket.numberoffollowups##</div>\n<p>##FOREACHfollowups##</p>\n<div class=\"description b\"><br /> <span class=\"b\"> [##followup.date##] <em>##lang.followup.isprivate## : ##followup.isprivate## </em></span><br /> <span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"> ##lang.followup.author## </span> ##followup.author##<br /> <span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"> ##lang.followup.description## </span> ##followup.description##<br /> <span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"> ##lang.followup.date## </span> ##followup.date##<br /> <span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"> ##lang.followup.requesttype## </span> ##followup.requesttype##</div>\n<p>##ENDFOREACHfollowups##</p>\n<div class=\"description b\">##lang.ticket.numberoftasks##&#160;: ##ticket.numberoftasks##</div>\n<p>##FOREACHtasks##</p>\n<div class=\"description b\"><br /> <span class=\"b\"> [##task.date##] <em>##lang.task.isprivate## : ##task.isprivate## </em></span><br /> <span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"> ##lang.task.author##</span> ##task.author##<br /> <span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"> ##lang.task.description##</span> ##task.description##<br /> <span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"> ##lang.task.time##</span> ##task.time##<br /> <span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"> ##lang.task.category##</span> ##task.category##</div>\n<p>##ENDFOREACHtasks##</p>');";
        $queries['Contract'] = "INSERT INTO `glpi_notificationtemplatetranslations`\n                              VALUES(NULL, " . $templates['Contract'] . ", '',\n                              '##contract.action##  ##contract.entity##',\n                              '##lang.contract.entity## : ##contract.entity##\r\n" . "\r\n##FOREACHcontracts##\r\n" . "##lang.contract.name## : ##contract.name##\r\n" . "##lang.contract.number## : ##contract.number##\r\n" . "##lang.contract.time## : ##contract.time##\r\n" . "##IFcontract.type####lang.contract.type## : ##contract.type##" . "##ENDIFcontract.type##\r\n" . "##contract.url##\r\n" . "##ENDFOREACHcontracts##',\n'&lt;p&gt;##lang.contract.entity## : ##contract.entity##&lt;br /&gt;\n&lt;br /&gt;##FOREACHcontracts##&lt;br /&gt;##lang.contract.name## :\n##contract.name##&lt;br /&gt;\n##lang.contract.number## : ##contract.number##&lt;br /&gt;\n##lang.contract.time## : ##contract.time##&lt;br /&gt;\n##IFcontract.type####lang.contract.type## : ##contract.type##\n##ENDIFcontract.type##&lt;br /&gt;\n&lt;a href=\"##contract.url##\"&gt;\n##contract.url##&lt;/a&gt;&lt;br /&gt;\n##ENDFOREACHcontracts##&lt;/p&gt;');";
        $queries['Ticket2'] = "INSERT INTO `glpi_notificationtemplatetranslations`\n                             VALUES(NULL, " . $templates['Ticket2'] . ", '',\n                            '##ticket.action## ##ticket.title##',\n'##lang.ticket.url## : ##ticket.url## \r\n\n##lang.ticket.description## \r\n\n\n##lang.ticket.title## &#160;:##ticket.title## \n\n##lang.ticket.author.name## &#160;:##IFticket.author.name##\n##ticket.author.name## ##ENDIFticket.author.name##\n##ELSEticket.author.name##--##ENDELSEticket.author.name## &#160; \n\n##IFticket.category## ##lang.ticket.category## &#160;:##ticket.category##\n##ENDIFticket.category## ##ELSEticket.category##\n##lang.ticket.nocategoryassigned## ##ENDELSEticket.category##\n\n##lang.ticket.content## &#160;: ##ticket.content##\n##IFticket.itemtype##\n##lang.ticket.item.name## &#160;: ##ticket.itemtype## - ##ticket.item.name##\n##ENDIFticket.itemtype##',\n'&lt;div&gt;##lang.ticket.url## : &lt;a href=\"##ticket.url##\"&gt;\n##ticket.url##&lt;/a&gt;&lt;/div&gt;\r\n&lt;div class=\"description b\"&gt;\n##lang.ticket.description##&lt;/div&gt;\r\n&lt;p&gt;&lt;span\nstyle=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"&gt;\n##lang.ticket.title##&lt;/span&gt;&#160;:##ticket.title##\n&lt;br /&gt; &lt;span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"&gt;\n##lang.ticket.author.name##&lt;/span&gt;\n##IFticket.author.name## ##ticket.author.name##\n##ENDIFticket.author.name##\n##ELSEticket.author.name##--##ENDELSEticket.author.name##\n&lt;span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"&gt;&#160\n;&lt;/span&gt;&lt;br /&gt; &lt;span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"&gt; &lt;/span&gt;\n##IFticket.category##&lt;span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"&gt;\n##lang.ticket.category## &lt;/span&gt;&#160;:##ticket.category##\n##ENDIFticket.category## ##ELSEticket.category##\n##lang.ticket.nocategoryassigned## ##ENDELSEticket.category##\n&lt;br /&gt; &lt;span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"&gt;\n##lang.ticket.content##&lt;/span&gt;&#160;:\n##ticket.content##&lt;br /&gt;##IFticket.itemtype##\n&lt;span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"&gt;\n##lang.ticket.item.name##&lt;/span&gt;&#160;:\n##ticket.itemtype## - ##ticket.item.name##\n##ENDIFticket.itemtype##&lt;/p&gt;');";
        $queries['TicketValidation'] = "INSERT INTO `glpi_notificationtemplatetranslations`\n                             VALUES(NULL, " . $templates['TicketValidation'] . ", '',\n                            '##ticket.action## ##ticket.title##',\n'##FOREACHvalidations##\n\n##IFvalidation.storestatus=waiting##\n##validation.submission.title##\n##lang.validation.commentsubmission## : ##validation.commentsubmission##\n##ENDIFvalidation.storestatus##\n##ELSEvalidation.storestatus## ##validation.answer.title## ##ENDELSEvalidation.storestatus##\n\n##lang.ticket.url## : ##ticket.urlvalidation##\n\n##IFvalidation.status## ##lang.validation.validationstatus## ##ENDIFvalidation.status##\n##IFvalidation.commentvalidation##\n##lang.validation.commentvalidation## : ##validation.commentvalidation##\n##ENDIFvalidation.commentvalidation##\n##ENDFOREACHvalidations##',\n'&lt;div&gt;##FOREACHvalidations##&lt;/div&gt;\n&lt;p&gt;##IFvalidation.storestatus=waiting##&lt;/p&gt;\n&lt;div&gt;##validation.submission.title##&lt;/div&gt;\n&lt;div&gt;##lang.validation.commentsubmission## : ##validation.commentsubmission##&lt;/div&gt;\n&lt;div&gt;##ENDIFvalidation.storestatus##&lt;/div&gt;\n&lt;div&gt;##ELSEvalidation.storestatus## ##validation.answer.title## ##ENDELSEvalidation.storestatus##&lt;/div&gt;\n&lt;div&gt;&lt;/div&gt;\n&lt;div&gt;\n&lt;div&gt;##lang.ticket.url## : &lt;a href=\"##ticket.urlvalidation##\"&gt; ##ticket.urlvalidation## &lt;/a&gt;&lt;/div&gt;\n&lt;/div&gt;\n&lt;p&gt;##IFvalidation.status## ##lang.validation.validationstatus## ##ENDIFvalidation.status##\n&lt;br /&gt; ##IFvalidation.commentvalidation##&lt;br /&gt; ##lang.validation.commentvalidation## :\n&#160; ##validation.commentvalidation##&lt;br /&gt; ##ENDIFvalidation.commentvalidation##\n&lt;br /&gt;##ENDFOREACHvalidations##&lt;/p&gt;');";
        $queries['Ticket3'] = "INSERT INTO `glpi_notificationtemplatetranslations`\n                             VALUES(NULL, " . $templates['Ticket3'] . ", '',\n                             '##ticket.action## ##ticket.entity##',\n'##lang.ticket.entity## : ##ticket.entity##\n \n##FOREACHtickets##\n\n##lang.ticket.title## : ##ticket.title##\n ##lang.ticket.status## : ##ticket.status##\n\n ##ticket.url## \n ##ENDFOREACHtickets##',\n'&lt;table class=\"tab_cadre\" border=\"1\" cellspacing=\"2\" cellpadding=\"3\"&gt;\n&lt;tbody&gt;\n&lt;tr&gt;\n&lt;td style=\"text-align: left;\" width=\"auto\" bgcolor=\"#cccccc\"&gt;&lt;span style=\"font-size: 11px; text-align: left;\"&gt;##lang.ticket.author.name##&lt;/span&gt;&lt;/td&gt;\n&lt;td style=\"text-align: left;\" width=\"auto\" bgcolor=\"#cccccc\"&gt;&lt;span style=\"font-size: 11px; text-align: left;\"&gt;##lang.ticket.title##&lt;/span&gt;&lt;/td&gt;\n&lt;td style=\"text-align: left;\" width=\"auto\" bgcolor=\"#cccccc\"&gt;&lt;span style=\"font-size: 11px; text-align: left;\"&gt;##lang.ticket.priority##&lt;/span&gt;&lt;/td&gt;\n&lt;td style=\"text-align: left;\" width=\"auto\" bgcolor=\"#cccccc\"&gt;&lt;span style=\"font-size: 11px; text-align: left;\"&gt;##lang.ticket.status##&lt;/span&gt;&lt;/td&gt;\n&lt;td style=\"text-align: left;\" width=\"auto\" bgcolor=\"#cccccc\"&gt;&lt;span style=\"font-size: 11px; text-align: left;\"&gt;##lang.ticket.attribution##&lt;/span&gt;&lt;/td&gt;\n&lt;td style=\"text-align: left;\" width=\"auto\" bgcolor=\"#cccccc\"&gt;&lt;span style=\"font-size: 11px; text-align: left;\"&gt;##lang.ticket.creationdate##&lt;/span&gt;&lt;/td&gt;\n&lt;td style=\"text-align: left;\" width=\"auto\" bgcolor=\"#cccccc\"&gt;&lt;span style=\"font-size: 11px; text-align: left;\"&gt;##lang.ticket.content##&lt;/span&gt;&lt;/td&gt;\n&lt;/tr&gt;\n##FOREACHtickets##\n&lt;tr&gt;\n&lt;td width=\"auto\"&gt;&lt;span style=\"font-size: 11px; text-align: left;\"&gt;##ticket.author.name##&lt;/span&gt;&lt;/td&gt;\n&lt;td width=\"auto\"&gt;&lt;span style=\"font-size: 11px; text-align: left;\"&gt;&lt;a href=\"##ticket.url##\"&gt;##ticket.title##&lt;/a&gt;&lt;/span&gt;&lt;/td&gt;\n&lt;td width=\"auto\"&gt;&lt;span style=\"font-size: 11px; text-align: left;\"&gt;##ticket.priority##&lt;/span&gt;&lt;/td&gt;\n&lt;td width=\"auto\"&gt;&lt;span style=\"font-size: 11px; text-align: left;\"&gt;##ticket.status##&lt;/span&gt;&lt;/td&gt;\n&lt;td width=\"auto\"&gt;&lt;span style=\"font-size: 11px; text-align: left;\"&gt;##IFticket.assigntouser####ticket.assigntouser##&lt;br /&gt;##ENDIFticket.assigntouser####IFticket.assigntogroup##&lt;br /&gt;##ticket.assigntogroup## ##ENDIFticket.assigntogroup####IFticket.assigntosupplier##&lt;br /&gt;##ticket.assigntosupplier## ##ENDIFticket.assigntosupplier##&lt;/span&gt;&lt;/td&gt;\n&lt;td width=\"auto\"&gt;&lt;span style=\"font-size: 11px; text-align: left;\"&gt;##ticket.creationdate##&lt;/span&gt;&lt;/td&gt;\n&lt;td width=\"auto\"&gt;&lt;span style=\"font-size: 11px; text-align: left;\"&gt;##ticket.content##&lt;/span&gt;&lt;/td&gt;\n&lt;/tr&gt;\n##ENDFOREACHtickets##\n&lt;/tbody&gt;\n&lt;/table&gt;');";
        $queries['Consumable'] = "INSERT INTO `glpi_notificationtemplatetranslations`\n                           VALUES(NULL, " . $templates['Consumable'] . ", '',\n                           '##consumable.action##  ##consumable.entity##',\n'##lang.consumable.entity## : ##consumable.entity##\n \n\n##FOREACHconsumables##\n##lang.consumable.item## : ##consumable.item##\n \n\n##lang.consumable.reference## : ##consumable.reference##\n\n##lang.consumable.remaining## : ##consumable.remaining##\n\n##consumable.url## \n\n##ENDFOREACHconsumables##', '&lt;p&gt;\n##lang.consumable.entity## : ##consumable.entity##\n&lt;br /&gt; &lt;br /&gt;##FOREACHconsumables##\n&lt;br /&gt;##lang.consumable.item## : ##consumable.item##&lt;br /&gt;\n&lt;br /&gt;##lang.consumable.reference## : ##consumable.reference##&lt;br /&gt;\n##lang.consumable.remaining## : ##consumable.remaining##&lt;br /&gt;\n&lt;a href=\"##consumable.url##\"&gt; ##consumable.url##&lt;/a&gt;&lt;br /&gt;\n   ##ENDFOREACHconsumables##&lt;/p&gt;');";
        $queries['Cartridge'] = "INSERT INTO `glpi_notificationtemplatetranslations`\n                               VALUES(NULL, " . $templates['Cartridge'] . ", '',\n                               '##cartridge.action##  ##cartridge.entity##',\n'##lang.cartridge.entity## : ##cartridge.entity##\n \n\n##FOREACHcartridges##\n##lang.cartridge.item## : ##cartridge.item##\n \n\n##lang.cartridge.reference## : ##cartridge.reference##\n\n##lang.cartridge.remaining## : ##cartridge.remaining##\n\n##cartridge.url## \n ##ENDFOREACHcartridges##',\n'&lt;p&gt;##lang.cartridge.entity## :##cartridge.entity##\n&lt;br /&gt; &lt;br /&gt;##FOREACHcartridges##\n&lt;br /&gt;##lang.cartridge.item## :\n##cartridge.item##&lt;br /&gt; &lt;br /&gt;\n##lang.cartridge.reference## :\n##cartridge.reference##&lt;br /&gt;\n##lang.cartridge.remaining## :\n##cartridge.remaining##&lt;br /&gt;\n&lt;a href=\"##cartridge.url##\"&gt;\n##cartridge.url##&lt;/a&gt;&lt;br /&gt;\n##ENDFOREACHcartridges##&lt;/p&gt;');";
        $queries['Infocom'] = "INSERT INTO `glpi_notificationtemplatetranslations`\n                              VALUES(NULL, " . $templates['Infocom'] . ", '',\n                             '##infocom.action##  ##infocom.entity##',\n'##lang.infocom.entity## : ##infocom.entity## \n \n\n##FOREACHinfocoms## \n\n##lang.infocom.itemtype## : ##infocom.itemtype##\n\n##lang.infocom.item## : ##infocom.item##\n \n\n##lang.infocom.expirationdate## : ##infocom.expirationdate##\n\n##infocom.url## \n ##ENDFOREACHinfocoms##',\n'&lt;p&gt;##lang.infocom.entity## : ##infocom.entity##\n&lt;br /&gt; &lt;br /&gt;##FOREACHinfocoms##\n&lt;br /&gt;##lang.infocom.itemtype## : ##infocom.itemtype##&lt;br /&gt;\n##lang.infocom.item## : ##infocom.item##&lt;br /&gt; &lt;br /&gt;\n##lang.infocom.expirationdate## : ##infocom.expirationdate##\n&lt;br /&gt; &lt;a href=\"##infocom.url##\"&gt;\n##infocom.url##&lt;/a&gt;&lt;br /&gt;\n##ENDFOREACHinfocoms##&lt;/p&gt;');";
        $queries['SoftwareLicense'] = "INSERT INTO `glpi_notificationtemplatetranslations`\n                                     VALUES(NULL, " . $templates['SoftwareLicense'] . ", '',\n                                    '##license.action##  ##license.entity##',\n'##lang.license.entity## : ##license.entity##\r\n\n##FOREACHlicenses## \r\n\n##lang.license.item## : ##license.item##\r\n\n##lang.license.serial## : ##license.serial##\r\n\n##lang.license.expirationdate## : ##license.expirationdate##\r\n\n##license.url## \r\n ##ENDFOREACHlicenses##', '&lt;p&gt;\n##lang.license.entity## : ##license.entity##&lt;br /&gt;\n##FOREACHlicenses##\n&lt;br /&gt;##lang.license.item## : ##license.item##&lt;br /&gt;\n##lang.license.serial## : ##license.serial##&lt;br /&gt;\n##lang.license.expirationdate## : ##license.expirationdate##\n&lt;br /&gt; &lt;a href=\"##license.url##\"&gt; ##license.url##\n&lt;/a&gt;&lt;br /&gt; ##ENDFOREACHlicenses##&lt;/p&gt;');";
        foreach ($queries as $itemtype => $query) {
            $DB->queryOrDie($query, "0.78 insert notification template default translation for {$itemtype}");
        }
        unset($queries);
    }
    $notifications = array();
    if (!TableExists('glpi_notifications')) {
        $query = "CREATE TABLE `glpi_notifications` (\n                 `id` INT( 11 ) NOT NULL AUTO_INCREMENT ,\n                 `name` VARCHAR( 255 ) DEFAULT NULL ,\n                 `entities_id` INT( 11 ) NOT NULL DEFAULT '0',\n                 `itemtype` VARCHAR( 100 ) NOT NULL ,\n                 `event` VARCHAR( 255 ) NOT NULL ,\n                 `mode` VARCHAR( 255 ) NOT NULL ,\n                 `notificationtemplates_id` INT( 11 ) NOT NULL DEFAULT '0',\n                 `comment` TEXT DEFAULT NULL ,\n                 `is_recursive` TINYINT( 1 ) NOT NULL DEFAULT '0',\n                 `is_active` TINYINT( 1 ) NOT NULL DEFAULT '0',\n                 `date_mod` DATETIME DEFAULT NULL ,\n                  PRIMARY KEY ( `id` ),\n                  KEY `name` (`name`),\n                  KEY `itemtype` (`itemtype`),\n                  KEY `entities_id` (`entities_id`),\n                  KEY `is_active` (`is_active`),\n                  KEY `date_mod` (`date_mod`),\n                  KEY `is_recursive` (`is_recursive`),\n                  KEY `notificationtemplates_id` (`notificationtemplates_id`)\n                  ) ENGINE = MYISAM CHARSET utf8 COLLATE utf8_unicode_ci;";
        $DB->queryOrDie($query, "0.78 create glpi_notifications");
        $queries = array();
        $queries[] = "INSERT INTO `glpi_notifications`\n                    VALUES (NULL, 'Alert Tickets not closed', 0, 'Ticket', 'alertnotclosed',\n                            'mail'," . $templates['Ticket3'] . ", '', 1, 1, NOW())";
        $queries[] = "INSERT INTO `glpi_notifications`\n                    VALUES (NULL, 'New Ticket', 0, 'Ticket', 'new', 'mail',\n                            " . $templates['Ticket'] . ", '', 1, 1, NOW())";
        $queries[] = "INSERT INTO `glpi_notifications`\n                    VALUES (NULL, 'Update Ticket', 0, 'Ticket', 'update', 'mail',\n                            " . $templates['Ticket'] . ", '', 1, 1, NOW())";
        $queries[] = "INSERT INTO `glpi_notifications`\n                    VALUES (NULL, 'Close Ticket', 0, 'Ticket', 'closed', 'mail',\n                            " . $templates['Ticket'] . ", '', 1, 1, NOW())";
        $queries[] = "INSERT INTO `glpi_notifications`\n                    VALUES (NULL, 'Add Followup', 0, 'Ticket', 'add_followup', 'mail',\n                            " . $templates['Ticket'] . ", '', 1, 1, NOW())";
        $queries[] = "INSERT INTO `glpi_notifications`\n                    VALUES (NULL, 'Add Task', 0, 'Ticket', 'add_task', 'mail',\n                            " . $templates['Ticket'] . ", '', 1, 1, NOW())";
        $queries[] = "INSERT INTO `glpi_notifications`\n                    VALUES (NULL, 'Update Followup', 0, 'Ticket', 'update_followup', 'mail',\n                            " . $templates['Ticket'] . ", '', 1, 1, NOW())";
        $queries[] = "INSERT INTO `glpi_notifications`\n                    VALUES (NULL, 'Update Task', 0, 'Ticket', 'update_task', 'mail',\n                            " . $templates['Ticket'] . ", '', 1, 1, NOW())";
        $queries[] = "INSERT INTO `glpi_notifications`\n                    VALUES (NULL, 'Delete Followup', 0, 'Ticket', 'delete_followup', 'mail',\n                            " . $templates['Ticket'] . ", '', 1, 1, NOW())";
        $queries[] = "INSERT INTO `glpi_notifications`\n                    VALUES (NULL, 'Delete Task', 0, 'Ticket', 'delete_task', 'mail',\n                            " . $templates['Ticket'] . ", '', 1, 1, NOW())";
        $queries[] = "INSERT INTO `glpi_notifications`\n                    VALUES (NULL, 'Resolve ticket', 0, 'Ticket', 'solved', 'mail',\n                            " . $templates['Ticket'] . ", '', 1, 1, NOW())";
        $queries[] = "INSERT INTO `glpi_notifications`\n                    VALUES (NULL, 'Ticket Validation', 0, 'Ticket', 'validation', 'mail',\n                            " . $templates['TicketValidation'] . ", '', 1, 1, NOW())";
        $queries[] = "INSERT INTO `glpi_notifications`\n                    VALUES (NULL, 'New Reservation', 0, 'Reservation', 'new', 'mail',\n                            " . $templates['Reservation'] . ", '', 1, 1, NOW())";
        $queries[] = "INSERT INTO `glpi_notifications`\n                    VALUES (NULL, 'Update Reservation', 0, 'Reservation', 'update', 'mail',\n                            " . $templates['Reservation'] . ", '', 1, 1, NOW())";
        $queries[] = "INSERT INTO `glpi_notifications`\n                    VALUES (NULL, 'Delete Reservation', 0, 'Reservation', 'delete', 'mail',\n                            " . $templates['Reservation'] . ", '', 1, 1, NOW())";
        $queries[] = "INSERT INTO `glpi_notifications`\n                    VALUES (NULL, 'Alert Reservation', 0, 'Reservation', 'alert', 'mail',\n                            " . $templates['Reservation2'] . ", '', 1, 1, NOW())";
        $queries[] = "INSERT INTO `glpi_notifications`\n                    VALUES (NULL, 'Contract Notice', 0, 'Contract', 'notice', 'mail',\n                            " . $templates['Contract'] . ", '', 1, 1, NOW())";
        $queries[] = "INSERT INTO `glpi_notifications`\n                    VALUES (NULL, 'Contract End', 0, 'Contract', 'end', 'mail',\n                            " . $templates['Contract'] . ", '', 1, 1, NOW())";
        $queries[] = "INSERT INTO `glpi_notifications`\n                    VALUES (NULL, 'MySQL Synchronization', 0, 'DBConnection', 'desynchronization',\n                            'mail'," . $templates['DBConnection'] . ", '', 1, 1, NOW())";
        $queries[] = "INSERT INTO `glpi_notifications`\n                    VALUES (NULL, 'Cartridges', 0, 'Cartridge', 'alert', 'mail',\n                            " . $templates['Cartridge'] . ", '', 1, 1, NOW())";
        $queries[] = "INSERT INTO `glpi_notifications`\n                    VALUES (NULL, 'Consumables', 0, 'Consumable', 'alert', 'mail',\n                            " . $templates['Consumable'] . ", '', 1, 1, NOW())";
        $queries[] = "INSERT INTO `glpi_notifications`\n                    VALUES (NULL, 'Infocoms', 0, 'Infocom', 'alert', 'mail',\n                            " . $templates['Infocom'] . ", '', 1, 1, NOW())";
        $queries[] = "INSERT INTO `glpi_notifications`\n                    VALUES (NULL, 'Software Licenses', 0, 'SoftwareLicense', 'alert', 'mail',\n                            " . $templates['SoftwareLicense'] . ", '', 1, 1, NOW())";
        foreach ($queries as $query) {
            $DB->queryOrDie($query, "0.78 insert notification");
        }
        $ADDTODISPLAYPREF['Notification'] = array(5, 6, 2, 4, 80, 86);
        unset($queries);
    }
    if (!TableExists('glpi_notificationtargets') && TableExists('glpi_mailingsettings')) {
        $query = "RENAME TABLE `glpi_mailingsettings` TO `glpi_notificationtargets`;";
        $DB->queryOrDie($query, "0.78 rename table glpi_mailingsettings in glpi_notificationtargets");
        $query = "ALTER TABLE `glpi_notificationtargets`\n                ADD `notifications_id` INT( 11 ) NOT NULL DEFAULT '0',\n                ADD INDEX `notifications_id` (`notifications_id`)";
        $DB->queryOrDie($query, "0.78 add field notifications_id to glpi_notificationtargets");
        $query = "ALTER TABLE `glpi_notificationtargets`\n                CHANGE `type` `oldtype` VARCHAR(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci\n                                        NULL DEFAULT NULL";
        $DB->queryOrDie($query, "0.78 change field type in oldtype");
        $query = "ALTER TABLE `glpi_notificationtargets`\n                CHANGE `mailingtype` `type` INT( 11 ) NOT NULL DEFAULT '0'";
        $DB->queryOrDie($query, "0.78 change field mailingtype in type");
        $fields = array('new' => array('itemtype' => 'Ticket', 'newaction' => 'new'), 'update' => array('itemtype' => 'Ticket', 'newaction' => 'update'), 'finish' => array('itemtype' => 'Ticket', 'newaction' => 'closed'), 'resa' => array('itemtype' => 'Reservation', 'newaction' => 'new'), 'followup' => array('itemtype' => 'Ticket', 'newaction' => 'add_followup'), 'alertconsumable' => array('itemtype' => 'Consumable', 'newaction' => 'alert'), 'alertcartridge' => array('itemtype' => 'Cartridge', 'newaction' => 'alert'), 'alertlicense' => array('itemtype' => 'SoftwareLicense', 'newaction' => 'alert'), 'alertinfocom' => array('itemtype' => 'Infocom', 'newaction' => 'alert'), 'alertcontract' => array('itemtype' => 'Contract', 'newaction' => 'end'));
        $query = "SELECT `oldtype`\n                FROM `glpi_notificationtargets`\n                GROUP BY `oldtype`";
        foreach ($DB->request($query) as $data) {
            $infos = $fields[$data['oldtype']];
            $query_type = "SELECT `id`\n                        FROM `glpi_notifications`\n                        WHERE `itemtype`='" . $infos['itemtype'] . "'\n                              AND `event`='" . $infos['newaction'] . "'";
            $result = $DB->queryOrDie($query_type, "0.78 get notificationtargets_id");
            if ($DB->numrows($result)) {
                $id = $DB->result($result, 0, 'id');
                $query_update = "UPDATE `glpi_notificationtargets`\n                             SET `notifications_id` = '{$id}'\n                             WHERE `oldtype` = '" . $data['oldtype'] . "'";
                $DB->queryOrDie($query_update, "0.78 set notificationtargets_id");
            }
        }
        $query = "ALTER TABLE `glpi_notificationtargets`\n               DROP INDEX `unicity` ";
        $DB->queryOrDie($query, "0.78 drop index unicity from glpi_notificationtargets");
        $query = "ALTER TABLE `glpi_notificationtargets`\n                DROP `oldtype`";
        $DB->queryOrDie($query, "0.78 drop field oldtype in glpi_notificationtargets");
        //Add administrator as target for MySQL Synchronization notification
        $query_type = "SELECT `id`\n                     FROM `glpi_notifications`\n                     WHERE `itemtype` = 'DBConnection'";
        $result = $DB->queryOrDie($query_type, "0.78 get notificationtargets_id");
        if ($DB->numrows($result)) {
            $id = $DB->result($result, 0, 'id');
            $query = "INSERT INTO `glpi_notificationtargets`\n                          (`id`, `notifications_id`, `type`, `items_id`)\n                   VALUES (NULL, " . $id . ", 1, 1)";
            $DB->queryOrDie($query, "0.78 add target for dbsynchronization");
        }
        //Add validator as target for Ticket Validation
        $query_type = "SELECT `id`\n                     FROM `glpi_notifications`\n                     WHERE `itemtype` = 'Ticket'\n                           AND `event` = 'validation'";
        $result = $DB->queryOrDie($query_type, "0.78 get notificationtargets_id");
        if ($DB->numrows($result)) {
            $id = $DB->result($result, 0, 'id');
            $query = "INSERT INTO `glpi_notificationtargets`\n                          (`id`, `notifications_id`, `type`, `items_id`)\n                     VALUES (NULL, " . $id . ", 1, 14);";
            $DB->queryOrDie($query, "0.78 add target for Ticket Validation");
        }
        //Manage Reservation update & delete
        $query_type = "SELECT `id`\n                     FROM `glpi_notifications`\n                     WHERE `itemtype` = 'Reservation'\n                           AND `event` IN ('update', 'delete')";
        foreach ($DB->request($query_type) as $data_resa) {
            $query_targets = "SELECT `glpi_notificationtargets` . *\n                          FROM `glpi_notifications` ,\n                               `glpi_notificationtargets`\n                          WHERE `glpi_notifications`.`itemtype` = 'Reservation'\n                               AND `glpi_notifications`.`event` = 'new'\n                               AND `glpi_notificationtargets`.notifications_id\n                                       = `glpi_notifications`.id";
            foreach ($DB->request($query_targets) as $data_targets) {
                $query_insert = "INSERT INTO `glpi_notificationtargets`\n                                    (`id`, `notifications_id`, `type`, `items_id`)\n                             VALUES (NULL, " . $data_resa['id'] . ", " . $data_targets['type'] . ",\n                                     " . $data_targets['items_id'] . ");";
                $DB->queryOrDie($query_insert, "0.78 add target for reservations");
            }
        }
        //Manage contract notice
        $query_type = "SELECT `id`\n                     FROM `glpi_notifications`\n                     WHERE `itemtype` = 'Contract'\n                           AND `event` = 'notice'";
        foreach ($DB->request($query_type) as $data_contract) {
            $query_targets = "SELECT `glpi_notificationtargets`.*\n                          FROM `glpi_notifications` , `glpi_notificationtargets`\n                          WHERE `glpi_notifications`.`itemtype` = 'Contract'\n                               AND `glpi_notifications`.`event` = 'end'\n                               AND `glpi_notificationtargets`.notifications_id\n                                       = `glpi_notifications`.id";
            foreach ($DB->request($query_targets) as $data_targets) {
                $query_insert = "INSERT INTO `glpi_notificationtargets`\n                                    (`id`, `notifications_id`, `type`, `items_id`)\n                             VALUES (NULL, " . $data_contract['id'] . ", " . $data_targets['type'] . ",\n                                     " . $data_targets['items_id'] . ")";
                $DB->queryOrDie($query_insert, "0.78 add target for contract");
            }
        }
        //Manage ticket tasks & followups
        $query_type = "SELECT `id`\n                     FROM `glpi_notifications`\n                     WHERE `itemtype`='Ticket'\n                           AND `event` IN ('add_task', 'update_task', 'update_followup',\n                                           'delete_task', 'delete_followup')";
        foreach ($DB->request($query_type) as $data_ticket) {
            $query_targets = "SELECT `glpi_notificationtargets`.*\n                          FROM `glpi_notifications` ,\n                               `glpi_notificationtargets`\n                          WHERE `glpi_notifications`.`itemtype` = 'Ticket'\n                               AND `glpi_notifications`.`event` = 'add_followup'\n                               AND `glpi_notificationtargets`.notifications_id\n                                       = `glpi_notifications`.id";
            foreach ($DB->request($query_targets) as $data_targets) {
                $query_insert = "INSERT INTO `glpi_notificationtargets`\n                                    (`id`, `notifications_id`, `type`, `items_id`)\n                             VALUES (NULL, " . $data_ticket['id'] . ",  " . $data_targets['type'] . ",\n                                     " . $data_targets['items_id'] . ");";
                $DB->queryOrDie($query_insert, "0.78 add target for tickets");
            }
        }
        //Manage ticket solved
        $query_type = "SELECT `id`\n                     FROM `glpi_notifications`\n                     WHERE `itemtype` = 'Ticket'\n                           AND `event` = 'solved'";
        foreach ($DB->request($query_type) as $data_ticket) {
            $query_targets = "SELECT `glpi_notificationtargets`.*\n                          FROM `glpi_notifications` ,\n                               `glpi_notificationtargets`\n                          WHERE `glpi_notifications`.`itemtype` = 'Ticket'\n                               AND `glpi_notifications`.`event` = 'closed'\n                               AND `glpi_notificationtargets`.notifications_id\n                                       = `glpi_notifications`.id";
            foreach ($DB->request($query_targets) as $data_targets) {
                $query_insert = "INSERT INTO `glpi_notificationtargets`\n                                    (`id`, `notifications_id`, `type`, `items_id`)\n                             VALUES (NULL, " . $data_ticket['id'] . ", " . $data_targets['type'] . ",\n                                     " . $data_targets['items_id'] . ")";
                $DB->queryOrDie($query_insert, "0.78 add target for tickets action solved");
            }
        }
    }
    if (!FieldExists('glpi_profiles', 'notification', false)) {
        $query = "ALTER TABLE `glpi_profiles`\n                ADD `notification` CHAR( 1 ) NULL";
        $DB->queryOrDie($query, "0.78 add notification in glpi_profiles");
        $query = "UPDATE `glpi_profiles`\n                SET `notification` = 'w'\n                WHERE `config` ='w'";
        $DB->queryOrDie($query, "0.78 add notification write right user which have config right");
    }
    if (!FieldExists('glpi_entitydatas', 'mailing_signature', false)) {
        $query = "ALTER TABLE `glpi_entitydatas` ADD `mailing_signature` TEXT DEFAULT NULL ,\n                ADD `cartridges_alert_repeat` INT( 11 ) NOT NULL DEFAULT '-1',\n                ADD `consumables_alert_repeat` INT( 11 ) NOT NULL DEFAULT '-1',\n                ADD `use_licenses_alert` TINYINT( 1 ) NOT NULL DEFAULT '-1',\n                ADD `use_contracts_alert` TINYINT( 1 ) NOT NULL DEFAULT '-1',\n                ADD `use_infocoms_alert` TINYINT( 1 ) NOT NULL DEFAULT '-1',\n                ADD `use_reservations_alert` INT( 11 ) NOT NULL DEFAULT '-1',\n                ADD `autoclose_delay` INT( 11 ) NOT NULL DEFAULT '-1',\n                ADD `notclosed_delay` INT( 11 ) NOT NULL DEFAULT '-1'";
        $DB->queryOrDie($query, "0.78 add notifications fields in glpi_entitydatas");
    }
    if (!FieldExists('glpi_configs', 'use_reservations_alert', false)) {
        $query = "ALTER TABLE `glpi_configs`\n                ADD `use_infocoms_alert` TINYINT( 1 ) NOT NULL DEFAULT '0',\n                ADD `use_contracts_alert` TINYINT( 1 ) NOT NULL DEFAULT '0',\n                ADD `use_reservations_alert` TINYINT( 1 ) NOT NULL DEFAULT '0',\n                ADD `autoclose_delay` INT( 11 ) NOT NULL DEFAULT '0',\n                ADD `notclosed_delay` INT( 11 ) NOT NULL DEFAULT '0'";
        $DB->queryOrDie($query, "0.78 add notifications fields in glpi_configs");
    }
    if (TableExists('glpi_mailingsettings')) {
        $query = "DROP TABLE `glpi_mailingsettings`;";
        $DB->queryOrDie($query, "0.78 drop table glpi_mailingsettings");
    }
    $tables = array('glpi_infocoms' => __('Financial and administrative information'), 'glpi_reservationitems' => _n('Reservation', 'Reservations', 2), 'glpi_networkports' => _n('Network port', 'Network ports', 2));
    foreach ($tables as $table => $label) {
        // Migrate infocoms entity information
        if (!FieldExists($table, 'entities_id', false)) {
            $migration->displayMessage(sprintf(__('Change of the database layout - %s'), $label));
            $query = "ALTER TABLE `{$table}`\n                   ADD `entities_id` int(11) NOT NULL DEFAULT 0 AFTER `itemtype`,\n                   ADD `is_recursive` tinyint(1) NOT NULL DEFAULT 0 AFTER `entities_id`,\n                   ADD INDEX `entities_id` ( `entities_id` ),\n                   ADD INDEX `is_recursive` (`is_recursive`)";
            $DB->queryOrDie($query, "0.78 add entities_id and is_recursive in {$table}");
            $entities = getAllDatasFromTable('glpi_entities');
            $entities[0] = "Root";
            $query = "SELECT DISTINCT `itemtype`\n                   FROM `{$table}`";
            if ($result = $DB->query($query)) {
                if ($DB->numrows($result) > 0) {
                    while ($data = $DB->fetch_assoc($result)) {
                        $migration->displayMessage(sprintf(__('Change of the database layout - %s'), sprintf(__('%1$s - %2$s'), $label, $data['itemtype'])));
                        $itemtable = getTableForItemType($data['itemtype']);
                        // ajout d'un contrôle pour voir si la table existe ( cas migration plugin non fait)
                        if (!TableExists($itemtable)) {
                            $migration->displayWarning("*** Skip : no table {$itemtable} ***", true);
                            continue;
                        }
                        $do_recursive = false;
                        if (FieldExists($itemtable, 'is_recursive', false)) {
                            $do_recursive = true;
                        }
                        // This is duplicated in Plugin::migrateItemType() for plugin object
                        foreach ($entities as $entID => $val) {
                            if ($do_recursive) {
                                // Non recursive ones
                                $query3 = "UPDATE `{$table}`\n                                   SET `entities_id` = {$entID},\n                                       `is_recursive` = 0\n                                   WHERE `itemtype` = '" . $data['itemtype'] . "'\n                                         AND `items_id` IN (SELECT `id`\n                                                            FROM `{$itemtable}`\n                                                            WHERE `entities_id` = {$entID}\n                                                                  AND `is_recursive` = 0)";
                                $DB->queryOrDie($query3, "0.78 update entities_id and is_recursive=0 in {$table} for " . $data['itemtype']);
                                // Recursive ones
                                $query3 = "UPDATE `{$table}`\n                                   SET `entities_id` = {$entID},\n                                       `is_recursive` = 1\n                                   WHERE `itemtype` = '" . $data['itemtype'] . "'\n                                         AND `items_id` IN (SELECT `id`\n                                                            FROM `{$itemtable}`\n                                                            WHERE `entities_id` = {$entID}\n                                                                  AND `is_recursive` = 1)";
                                $DB->queryOrDie($query3, "0.78 update entities_id and is_recursive=1 in {$table} for " . $data['itemtype']);
                            } else {
                                $query3 = "UPDATE `{$table}`\n                                   SET `entities_id` = {$entID}\n                                   WHERE `itemtype` = '" . $data['itemtype'] . "'\n                                         AND `items_id` IN (SELECT `id`\n                                                            FROM `{$itemtable}`\n                                                            WHERE `entities_id` = {$entID})";
                                $DB->queryOrDie($query3, "0.78 update entities_id in {$table} for " . $data['itemtype']);
                            }
                        }
                    }
                }
            }
        }
    }
    // Migrate consumable and cartridge and computerdisks entity information
    $items = array('glpi_cartridges' => 'glpi_cartridgeitems', 'glpi_consumables' => 'glpi_consumableitems', 'glpi_computerdisks' => 'glpi_computers');
    foreach ($items as $linkitem => $sourceitem) {
        if (!FieldExists($linkitem, 'entities_id', false)) {
            $migration->displayMessage(sprintf(__('Change of the database layout - %s'), $linkitem));
            $query = "ALTER TABLE `{$linkitem}`\n                   ADD `entities_id` int(11) NOT NULL DEFAULT 0 AFTER `id`,\n                   ADD INDEX `entities_id` ( `entities_id` )";
            $DB->queryOrDie($query, "0.78 add entities_id in {$linkitem}");
            $entities = getAllDatasFromTable('glpi_entities');
            $entities[0] = "Root";
            foreach ($entities as $entID => $val) {
                $query3 = "UPDATE `{$linkitem}`\n                       SET `entities_id` = '{$entID}'\n                       WHERE " . getForeignKeyFieldForTable($sourceitem) . "\n                              IN (SELECT `id`\n                                  FROM `{$sourceitem}`\n                                  WHERE `entities_id` = '{$entID}' )";
                $DB->queryOrDie($query3, "0.78 update entities_id in {$linkitem}");
            }
        }
    }
    // Migrate softwareversions entity information
    if (!FieldExists('glpi_softwareversions', 'entities_id', false)) {
        $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'glpi_softwareversions'));
        $query = "ALTER TABLE `glpi_softwareversions`\n                ADD `entities_id` int(11) NOT NULL DEFAULT 0 AFTER `id`,\n                ADD INDEX `entities_id` ( `entities_id` ),\n                ADD `is_recursive` tinyint(1) NOT NULL DEFAULT 0 AFTER `entities_id`,\n                ADD INDEX `is_recursive` ( `is_recursive` )";
        $DB->queryOrDie($query, "0.78 add entities_id in glpi_softwareversion");
        $entities = getAllDatasFromTable('glpi_entities');
        $entities[0] = "Root";
        foreach ($entities as $entID => $val) {
            // Non recursive ones
            $query3 = "UPDATE `glpi_softwareversions`\n                    SET `entities_id` = {$entID},\n                        `is_recursive` = 0\n                    WHERE `softwares_id` IN (SELECT `id`\n                                             FROM `glpi_softwares`\n                                             WHERE `entities_id` = {$entID}\n                                                   AND `is_recursive` = 0)";
            $DB->queryOrDie($query3, "0.78 update entities_id and is_recursive=0 in glpi_softwareversions");
            // Recursive ones
            $query3 = "UPDATE `glpi_softwareversions`\n                    SET `entities_id` = {$entID},\n                        `is_recursive` = 1\n                    WHERE `softwares_id` IN (SELECT `id`\n                                             FROM `glpi_softwares`\n                                             WHERE `entities_id` = {$entID}\n                                                   AND `is_recursive` = 1)";
            $DB->queryOrDie($query3, "0.78 update entities_id and is_recursive=1 in glpi_softwareversions");
        }
    }
    $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'glpi_mailcollectors'));
    if (!FieldExists("glpi_mailcollectors", "is_active", false)) {
        $query = "ALTER TABLE `glpi_mailcollectors`\n                ADD `is_active` tinyint( 1 ) NOT NULL DEFAULT '1',\n                ADD INDEX `is_active` (`is_active`) ";
        $DB->queryOrDie($query, "0.78 add is_active in glpi_mailcollectors");
    }
    if (!FieldExists('glpi_mailcollectors', 'date_mod', false)) {
        $query = "ALTER TABLE `glpi_mailcollectors`\n                ADD `date_mod` DATETIME NULL, ADD INDEX `date_mod` (`date_mod`)";
        $DB->queryOrDie($query, "0.78 add date_mod to glpi_mailcollectors");
    }
    if (!FieldExists('glpi_mailcollectors', 'comment', false)) {
        $query = "ALTER TABLE `glpi_mailcollectors`\n                ADD `comment` text collate utf8_unicode_ci";
        $DB->queryOrDie($query, "0.78 add comment to glpi_mailcollectors");
    }
    if (!FieldExists('glpi_profiles', 'rule_mailcollector', false)) {
        $query = "ALTER TABLE `glpi_profiles`\n                ADD `rule_mailcollector` CHAR( 1 ) NULL ";
        $DB->queryOrDie($query, "0.78 add rule_mailcollector to glpi_profiles");
        $query = "UPDATE `glpi_profiles`\n                SET `rule_mailcollector` = `rule_ticket`";
        $DB->queryOrDie($query, "0.78 set default rule_mailcollector same as rule_ticket");
    }
    // Change search pref : add active / date_mod
    $ADDTODISPLAYPREF['MailCollector'] = array(2, 19);
    $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'glpi_authldaps'));
    if (!FieldExists('glpi_authldaps', 'date_mod', false)) {
        $query = "ALTER TABLE `glpi_authldaps`\n                ADD `date_mod` DATETIME NULL,\n                ADD INDEX `date_mod` (`date_mod`)";
        $DB->queryOrDie($query, "0.78 add date_mod to glpi_authldaps");
    }
    if (!FieldExists('glpi_authldaps', 'comment', false)) {
        $query = "ALTER TABLE `glpi_authldaps`\n                ADD `comment` text collate utf8_unicode_ci";
        $DB->queryOrDie($query, "0.78 add comment to glpi_authldaps");
    }
    // Change search pref : host, date_mod
    $ADDTODISPLAYPREF['AuthLDAP'] = array(3, 19);
    $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'glpi_authldaps'));
    if (!FieldExists('glpi_authmails', 'date_mod', false)) {
        $query = "ALTER TABLE `glpi_authmails`\n                ADD `date_mod` DATETIME NULL,\n                ADD INDEX `date_mod` (`date_mod`)";
        $DB->queryOrDie($query, "0.78 add date_mod to glpi_authmails");
    }
    if (!FieldExists('glpi_authmails', 'comment', false)) {
        $query = "ALTER TABLE `glpi_authmails`\n                ADD `comment` text collate utf8_unicode_ci";
        $DB->queryOrDie($query, "0.78 add comment to glpi_authmails");
    }
    // Change search pref : host, date_mod
    $ADDTODISPLAYPREF['AuthMail'] = array(3, 19);
    $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'glpi_ocsservers'));
    if (!FieldExists('glpi_ocsservers', 'date_mod', false)) {
        $query = "ALTER TABLE `glpi_ocsservers`\n                ADD `date_mod` DATETIME NULL,\n                ADD INDEX `date_mod` (`date_mod`)";
        $DB->queryOrDie($query, "0.78 add date_mod to glpi_ocsservers");
    }
    if (!FieldExists('glpi_ocsservers', 'comment', false)) {
        $query = "ALTER TABLE `glpi_ocsservers`\n                ADD `comment` text collate utf8_unicode_ci";
        $DB->queryOrDie($query, "0.78 add comment to glpi_ocsservers");
    }
    // Change search pref : date_mod / host
    $ADDTODISPLAYPREF['OcsServer'] = array(3, 19);
    $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'glpi_profiles'));
    if (!FieldExists('glpi_profiles', 'date_mod', false)) {
        $query = "ALTER TABLE `glpi_profiles`\n                ADD `date_mod` DATETIME NULL,\n                ADD INDEX `date_mod` (`date_mod`)";
        $DB->queryOrDie($query, "0.78 add date_mod to glpi_profiles");
    }
    if (!FieldExists('glpi_profiles', 'comment', false)) {
        $query = "ALTER TABLE `glpi_profiles`\n                ADD `comment` text collate utf8_unicode_ci";
        $DB->queryOrDie($query, "0.78 add comment to glpi_profiles");
    }
    // Change search pref : date_mod / host
    $ADDTODISPLAYPREF['Profile'] = array(2, 3, 19);
    $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'glpi_printers'));
    if (!FieldExists('glpi_printers', 'have_ethernet', false)) {
        $query = "ALTER TABLE `glpi_printers`\n                ADD `have_ethernet` TINYINT( 1 ) NOT NULL DEFAULT '0' AFTER `have_usb`";
        $DB->queryOrDie($query, "0.78 add have_ethernet to glpi_printers");
    }
    if (!FieldExists('glpi_printers', 'have_wifi', false)) {
        $query = "ALTER TABLE `glpi_printers`\n                ADD `have_wifi` TINYINT( 1 ) NOT NULL DEFAULT '0' AFTER `have_usb`";
        $DB->queryOrDie($query, "0.78 add have_wifi to glpi_printers");
    }
    $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'glpi_profiles'));
    if (!FieldExists('glpi_transfers', 'date_mod', false)) {
        $query = "ALTER TABLE `glpi_transfers`\n                ADD `date_mod` DATETIME NULL,\n                ADD INDEX `date_mod` (`date_mod`)";
        $DB->queryOrDie($query, "0.78 add date_mod to glpi_transfers");
    }
    if (!FieldExists('glpi_transfers', 'comment', false)) {
        $query = "ALTER TABLE `glpi_transfers`\n                ADD `comment` text collate utf8_unicode_ci";
        $DB->queryOrDie($query, "0.78 add comment to glpi_transfers");
    }
    // Change search pref : date_mod
    $ADDTODISPLAYPREF['Transfer'] = array(19);
    // Convert events
    $migration->displayMessage(sprintf(__('Data migration - %s'), 'glpi_events'));
    $convert_types = array('tracking' => 'ticket', 'networking' => 'networkequipment', 'knowbase' => 'knowbaseitem', 'typedocs' => 'documenttype', 'mailgate' => 'mailcollector');
    foreach ($convert_types as $from => $to) {
        $query2 = "UPDATE `glpi_events`\n                 SET `type` = '{$to}'\n                WHERE `type` = '{$from}'";
        $DB->queryOrDie($query2, "0.78 update events data");
    }
    $migration->displayMessage(sprintf(__('Data migration - %s'), 'ticket bookmarks'));
    $query = "SELECT *\n             FROM `glpi_bookmarks`\n             WHERE `itemtype` = 'Ticket'\n                   AND `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);
                $newoptions = array();
                foreach ($options as $key => $val) {
                    switch ($key) {
                        case "status":
                            $newoptions['field'][$num] = 12;
                            $newoptions['searchtype'][$num] = 'equals';
                            $newoptions['link'][$num] = 'AND';
                            if ($val == 'old_done' || $val == 'old_notdone') {
                                $newoptions['contains'][$num] = 'closed';
                            } else {
                                $newoptions['contains'][$num] = $val;
                            }
                            $num++;
                            break;
                        case "priority":
                            if ($val != 0) {
                                $newoptions['field'][$num] = 3;
                                $newoptions['searchtype'][$num] = 'equals';
                                $newoptions['contains'][$num] = $val;
                                $newoptions['link'][$num] = 'AND';
                                $num++;
                            }
                            break;
                        case "category":
                            if ($val > 0) {
                                $newoptions['field'][$num] = 7;
                                $newoptions['searchtype'][$num] = 'equals';
                                $newoptions['contains'][$num] = $val;
                                $newoptions['link'][$num] = 'AND';
                                $num++;
                            }
                            break;
                        case "request_type":
                            if ($val > 0) {
                                $newoptions['field'][$num] = 9;
                                $newoptions['searchtype'][$num] = 'equals';
                                $newoptions['contains'][$num] = $val;
                                $newoptions['link'][$num] = 'AND';
                                $num++;
                            }
                            break;
                        case "type":
                            if ($val > 0 && isset($data['item']) && $data['item'] > 0) {
                                $newoptions['itemtype2'][$num2] = $typetoname[$val];
                                $newoptions['field2'][$num2] = 1;
                                $newoptions['searchtype2'][$num2] = 'equals';
                                $newoptions['contains2'][$num2] = $data['item'];
                                $newoptions['link2'][$num2] = 'AND';
                                $num2++;
                            }
                            break;
                        case "author":
                            if ($val > 0) {
                                $newoptions['field'][$num] = 4;
                                $newoptions['searchtype'][$num] = 'equals';
                                $newoptions['contains'][$num] = $val;
                                $newoptions['link'][$num] = 'AND';
                                $num++;
                            }
                            break;
                        case "group":
                            if ($val > 0) {
                                $newoptions['field'][$num] = 71;
                                $newoptions['searchtype'][$num] = 'equals';
                                $newoptions['contains'][$num] = $val;
                                $newoptions['link'][$num] = 'AND';
                                $num++;
                            }
                            break;
                        case "assign":
                            if ($val > 0) {
                                $newoptions['field'][$num] = 5;
                                $newoptions['searchtype'][$num] = 'equals';
                                $newoptions['contains'][$num] = $val;
                                $newoptions['link'][$num] = 'AND';
                                $num++;
                            }
                            break;
                        case "assign_group":
                            if ($val > 0) {
                                $newoptions['field'][$num] = 8;
                                $newoptions['searchtype'][$num] = 'equals';
                                $newoptions['contains'][$num] = $val;
                                $newoptions['link'][$num] = 'AND';
                                $num++;
                            }
                            break;
                        case "assign_ent":
                            if ($val > 0) {
                                $newoptions['field'][$num] = 6;
                                $newoptions['searchtype'][$num] = 'equals';
                                $newoptions['contains'][$num] = $val;
                                $newoptions['link'][$num] = 'AND';
                                $num++;
                            }
                            break;
                        case "recipient":
                            if ($val > 0) {
                                $newoptions['field'][$num] = 22;
                                $newoptions['searchtype'][$num] = 'equals';
                                $newoptions['contains'][$num] = $val;
                                $newoptions['link'][$num] = 'AND';
                                $num++;
                            }
                            break;
                        case "date1":
                            // begin from
                            if (strlen($val) > 0 && $val != 'NULL') {
                                $newoptions['field'][$num] = 15;
                                $newoptions['searchtype'][$num] = 'contains';
                                $newoptions['contains'][$num] = '&gt;=' . $val;
                                $newoptions['link'][$num] = 'AND';
                                $num++;
                            }
                            break;
                        case "date2":
                            // begin to
                            if (strlen($val) > 0 && $val != 'NULL') {
                                $newoptions['field'][$num] = 15;
                                $newoptions['searchtype'][$num] = 'contains';
                                $newoptions['contains'][$num] = '&lt;=' . $val;
                                $newoptions['link'][$num] = 'AND';
                                $num++;
                            }
                            break;
                        case "enddate1":
                            // end from
                            if (strlen($val) > 0 && $val != 'NULL') {
                                $newoptions['field'][$num] = 16;
                                $newoptions['searchtype'][$num] = 'contains';
                                $newoptions['contains'][$num] = '&gt;=' . $val;
                                $newoptions['link'][$num] = 'AND';
                                $num++;
                            }
                            break;
                        case "enddate2":
                            // end to
                            if (strlen($val) > 0 && $val != 'NULL') {
                                $newoptions['field'][$num] = 16;
                                $newoptions['searchtype'][$num] = 'contains';
                                $newoptions['contains'][$num] = '&lt;=' . $val;
                                $newoptions['link'][$num] = 'AND';
                                $num++;
                            }
                            break;
                        case "datemod1":
                            // mod from
                            if (strlen($val) > 0 && $val != 'NULL') {
                                $newoptions['field'][$num] = 19;
                                $newoptions['searchtype'][$num] = 'contains';
                                $newoptions['contains'][$num] = '&gt;=' . $val;
                                $newoptions['link'][$num] = 'AND';
                                $num++;
                            }
                            break;
                        case "datemod2":
                            // mod to
                            if (strlen($val) > 0 && $val != 'NULL') {
                                $newoptions['field'][$num] = 19;
                                $newoptions['searchtype'][$num] = 'contains';
                                $newoptions['contains'][$num] = '&lt;=' . $val;
                                $newoptions['link'][$num] = 'AND';
                                $num++;
                            }
                            break;
                        case "tosearch":
                            if (isset($data['search'])) {
                                $search = trim($data['search']);
                                if (strlen($search) > 0) {
                                    $first = false;
                                    if (strstr($data['search'], 'name')) {
                                        $newoptions['field'][$num] = 1;
                                        $newoptions['searchtype'][$num] = 'contains';
                                        $newoptions['contains'][$num] = $val;
                                        $newoptions['link'][$num] = $first ? 'AND' : 'OR';
                                        $first = false;
                                        $num++;
                                    }
                                    if (strstr($data['search'], 'contents')) {
                                        $newoptions['field'][$num] = 21;
                                        $newoptions['searchtype'][$num] = 'contains';
                                        $newoptions['contains'][$num] = $val;
                                        $newoptions['link'][$num] = $first ? 'AND' : 'OR';
                                        $first = false;
                                        $num++;
                                    }
                                    if (strstr($data['search'], 'followup')) {
                                        $newoptions['field'][$num] = 25;
                                        $newoptions['searchtype'][$num] = 'contains';
                                        $newoptions['contains'][$num] = $val;
                                        $newoptions['link'][$num] = $first ? 'AND' : 'OR';
                                        $first = false;
                                        $num++;
                                    }
                                    if (strstr($data['search'], 'ID')) {
                                        $newoptions['field'][$num] = 2;
                                        $newoptions['searchtype'][$num] = 'contains';
                                        $newoptions['contains'][$num] = $val;
                                        $newoptions['link'][$num] = 'AND';
                                        $first = false;
                                        $num++;
                                    }
                                }
                            }
                            break;
                    }
                }
                if ($num > 0 || $num2 > 0) {
                    $newoptions['glpisearchcount'] = $num;
                    $newoptions['glpisearchcount2'] = $num2;
                    $newoptions['itemtype'] = 'Ticket';
                    $query2 = "UPDATE `glpi_bookmarks`\n                          SET `query` = '" . addslashes(Toolbox::append_params($newoptions)) . "'\n                          WHERE `id` = '" . $data['id'] . "'";
                    $DB->queryOrDie($query2, "0.78 update ticket bookmarks");
                } else {
                    $query2 = "DELETE\n                          FROM `glpi_bookmarks`\n                          WHERE `id` = '" . $data['id'] . "'";
                    $DB->queryOrDie($query2, "0.78 delete ticket bookmarks : cannot convert");
                }
                // Lost paramaters
                //only_computers=1&contains=dddd&field=moboard.designation&
            }
        }
    }
    if (!TableExists('glpi_ticketvalidations')) {
        $query = "CREATE TABLE `glpi_ticketvalidations` (\n                  `id` int(11) NOT NULL auto_increment,\n                  `entities_id` int(11) NOT NULL default '0',\n                  `users_id` int(11) NOT NULL default '0',\n                  `tickets_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` varchar(255) collate utf8_unicode_ci default 'waiting',\n                  `submission_date` datetime default NULL,\n                  `validation_date` datetime default NULL,\n                  PRIMARY KEY  (`id`),\n                  KEY `entities_id` (`entities_id`),\n                  KEY `users_id` (`users_id`),\n                  KEY `users_id_validate` (`users_id_validate`),\n                  KEY `tickets_id` (`tickets_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.78 create glpi_ticketvalidations");
        $ADDTODISPLAYPREF['TicketValidation'] = array(3, 2, 8, 4, 9, 7);
    }
    if (!FieldExists('glpi_tickets', 'global_validation', false)) {
        $query = "ALTER TABLE `glpi_tickets`\n                ADD `global_validation` varchar(255) collate utf8_unicode_ci default 'accepted',\n                ADD INDEX `global_validation` (`global_validation`)";
        $DB->queryOrDie($query, "0.78 add global_validation to glpi_tickets");
    }
    if (!FieldExists('glpi_profiles', 'validate_ticket', false)) {
        $query = "ALTER TABLE `glpi_profiles`\n                ADD `validate_ticket` char(1) collate utf8_unicode_ci default NULL";
        $DB->queryOrDie($query, "0.78 add validate_ticket to glpi_profiles");
        $query = "UPDATE `glpi_profiles`\n                SET `validate_ticket` = '1'\n                WHERE `interface` = 'central' ";
        $DB->queryOrDie($query, "0.78 add validate_ticket write right to super-admin and admin profiles");
        $query = "ALTER TABLE `glpi_profiles`\n                ADD `create_validation` char(1) collate utf8_unicode_ci default NULL";
        $DB->queryOrDie($query, "0.78 add create_validation to glpi_profiles");
        $query = "UPDATE `glpi_profiles`\n                SET `create_validation` = `own_ticket`";
        $DB->queryOrDie($query, "0.78 add create_validation right if can own ticket");
    }
    if (FieldExists('glpi_mailcollectors', 'entities_id', false)) {
        $ranking = 1;
        // No mailcollector : set a default rule
        if (countElementsInTable('glpi_mailcollectors') == 0) {
            $query = "INSERT INTO `glpi_rules`\n                      VALUES (NULL, -1, 'RuleMailCollector', {$ranking}, 'Root', '', 'OR', 1, NULL,\n                              NULL)";
            $DB->queryOrDie($query, "0.78 error inserting new default maigate rule");
            if ($newID = $DB->insert_id()) {
                $query = "INSERT INTO `glpi_rulecriterias`\n                         VALUES (NULL, {$newID}, 'subject', 6, '/.*/')";
                $DB->queryOrDie($query, "0.78 error getting new criteria for rule");
                $query = "INSERT INTO `glpi_ruleactions`\n                         VALUES (NULL, {$newID}, 'assign', 'entities_id', '0')";
                $DB->queryOrDie($query, "0.78 error getting new action for rule");
            }
        } else {
            foreach (getAllDatasFromTable('glpi_mailcollectors') as $collector) {
                $query = "INSERT INTO `glpi_rules`\n                      VALUES (NULL, -1, 'RuleMailCollector', {$ranking}, '" . $collector['name'] . "', '',\n                              'AND', 1, NULL, NULL)";
                $DB->queryOrDie($query, "0.78 error inserting new maigate rule " . $collector['name']);
                if ($newID = $DB->insert_id()) {
                    $query = "INSERT INTO `glpi_rulecriterias`\n                         VALUES (NULL, {$newID}, 'mailcollector', 0, '" . $collector['id'] . "')";
                    $DB->queryOrDie($query, "0.78 error getting new criteria for rule " . $collector['name']);
                    $query = "INSERT INTO `glpi_ruleactions`\n                         VALUES (NULL, {$newID}, 'assign', 'entities_id',\n                                 '" . $collector['entities_id'] . "')";
                    $DB->queryOrDie($query, "0.78 error getting new action for rule " . $collector['name']);
                }
                $ranking++;
            }
        }
        $query = "ALTER TABLE `glpi_mailcollectors`\n                DROP INDEX `entities_id` ";
        $DB->queryOrDie($query, "0.78 drop index entities_id from glpi_mailcollectors");
        $query = "ALTER TABLE `glpi_mailcollectors`\n                DROP `entities_id` ";
        $DB->queryOrDie($query, "0.78 drop entities_id from glpi_mailcollectors");
        $query = "DELETE\n                FROM `glpi_displaypreferences`\n                WHERE `itemtype` = 'MailCollector'\n                      AND `num` = '80'";
        $DB->queryOrDie($query, "0.78 drop entities_id from collectors display preferences");
    }
    if (!TableExists('glpi_notimportedemails')) {
        $query = "CREATE TABLE `glpi_notimportedemails` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `from` varchar(255) NOT NULL,\n                  `to` varchar(255) NOT NULL,\n                  `mailcollectors_id` int(11) NOT NULL DEFAULT '0',\n                  `date` datetime NOT NULL,\n                  `subject` text,\n                  `messageid` varchar(255) NOT NULL,\n                  `reason` int(11) NOT NULL DEFAULT '0',\n                  `users_id` int(11) NOT NULL DEFAULT '0',\n                  PRIMARY KEY (`id`),\n                  KEY `users_id` (`users_id`),\n                  KEY `mailcollectors_id` (`mailcollectors_id`)\n               ) ENGINE=MyISAM  DEFAULT CHARSET=latin1;";
        $DB->queryOrDie($query, "0.78 add table glpi_notimportedemails");
        $ADDTODISPLAYPREF['NotImportedEmail'] = array(2, 5, 4, 6, 16, 19);
    }
    if (!FieldExists("glpi_profiles", "entity_rule_ticket", false)) {
        $query = "ALTER TABLE `glpi_profiles`\n                ADD `entity_rule_ticket` CHAR( 1 ) NULL AFTER `rule_ticket`";
        $DB->queryOrDie($query, "0.78 add entity_rule_ldap in glpi_profiles");
        $query = "UPDATE `glpi_profiles`\n                SET `entity_rule_ticket` = `rule_ticket`";
        $DB->queryOrDie($query, "0.78 update default entity_rule_ticket rights");
        $query = "UPDATE `glpi_profiles`\n                SET `rule_ticket` = 'r'\n                WHERE `rule_ticket` = 'w'";
        $DB->queryOrDie($query, "0.78 update rule_ticket rights");
    }
    if (!FieldExists('glpi_authldaps', 'is_default', false)) {
        $query = "ALTER TABLE `glpi_authldaps`\n                ADD `is_default` TINYINT( 1 ) NOT NULL DEFAULT '0',\n                ADD INDEX `is_default` (`is_default`)";
        $DB->queryOrDie($query, "0.78 add is_default to glpi_authldaps");
        $query = "SELECT COUNT(*) AS cpt\n                FROM `glpi_authldaps`";
        $result = $DB->query($query);
        $number_servers = $DB->result($result, 0, 'cpt');
        if ($number_servers >= 1) {
            //If only one server defined
            if ($number_servers == 1) {
                $query = "SELECT `id`\n                       FROM `glpi_authldaps`";
                $result = $DB->query($query);
                $ldapservers_id = $DB->result($result, 0, 'id');
            } else {
                $query = "SELECT `auths_id`, COUNT(`auths_id`) AS cpt\n                      FROM `glpi_users`\n                      WHERE `authtype` = '3'\n                      GROUP BY `auths_id`\n                      ORDER BY `cpt` DESC";
                $result = $DB->query($query);
                $ldapservers_id = $DB->result($result, 0, 'auths_id');
            }
            $query = "UPDATE `glpi_authldaps`\n                   SET `is_default` = '1'\n                   WHERE `id` = '" . $ldapservers_id . "'";
            $DB->queryOrDie($query, "0.78 set default directory");
        }
    }
    if (TableExists('glpi_rulerightparameters')) {
        $query = "ALTER TABLE `glpi_rulerightparameters`\n                ADD `comment` TEXT NOT NULL ";
        $DB->queryOrDie($query, "0.78 add comment to glpi_rulerightparameters");
        $ADDTODISPLAYPREF['RuleRightParameter'] = array(11);
    }
    if (!FieldExists('glpi_rules', 'is_recursive', false)) {
        $query = "ALTER TABLE `glpi_rules`\n                ADD `is_recursive` TINYINT( 1 ) NOT NULL DEFAULT '0',\n                ADD INDEX `is_recursive` (`is_recursive`)";
        $DB->queryOrDie($query, "0.78 add is_recursive to glpi_rules");
        $query = "UPDATE `glpi_rules`\n                SET `entities_id` = '0'\n                WHERE `entities_id` = '-1'";
        $DB->queryOrDie($query, "0.78 set entities_id to 0 where value is -1 in glpi_rules");
        $query = "UPDATE `glpi_rules`\n                SET `is_recursive`='1'\n                WHERE `sub_type` = 'RuleTicket'";
        $DB->queryOrDie($query, "0.78 set is_recursive to 1 for RuleTicket in glpi_rules");
    }
    if (!FieldExists('glpi_configs', 'user_deleted_ldap', false)) {
        $query = "ALTER TABLE `glpi_configs`\n                ADD `user_deleted_ldap` TINYINT( 1 ) NOT NULL DEFAULT '0'";
        $DB->queryOrDie($query, "0.78 add user_deleted_ldap to glpi_configs");
    }
    if (!FieldExists("glpi_profiles", "group_add_followup", false)) {
        $query = "ALTER TABLE `glpi_profiles`\n                ADD `group_add_followups` CHAR(1) NULL AFTER `add_followups`";
        $DB->queryOrDie($query, "0.78 add budget in glpi_profiles");
        $query = "UPDATE `glpi_profiles`\n                SET `group_add_followups`=`global_add_followups`";
        $DB->queryOrDie($query, "0.78 update default budget rights");
    }
    if (!FieldExists("glpi_groups_users", "is_dynamic", false)) {
        $query = "ALTER TABLE `glpi_groups_users`\n               ADD `is_dynamic` TINYINT( 1 ) NOT NULL DEFAULT '0'";
        $DB->queryOrDie($query, "0.78 add is_dynamic in glpi_groups_users");
        //If group comes from an LDAP directory, then update users belonging to it
        //by setting is_dynamic to 1
        $query = "UPDATE `glpi_groups_users` SET `is_dynamic`='1'\n               WHERE groups_id IN (SELECT `id`\n                                   FROM `glpi_groups`\n                                   WHERE (`ldap_group_dn` IS NOT NULL AND `ldap_group_dn` <> '')\n                                          OR ((`ldap_field` IS NOT NULL AND `ldap_field` <> '')\n                                              AND (`ldap_value` IS NOT NULL AND `ldap_value` <> '')))";
        $DB->queryOrDie($query, "0.78 update is_dynamic in glpi_groups_users");
    }
    $migration->displayMessage(sprintf(__('Data migration - %s'), 'glpi_displaypreferences'));
    // Add search values for tickets
    $ADDTODISPLAYPREF['Ticket'] = array(12, 19, 15, 3, 4, 5, 7);
    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++ . "', '" . $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);
                }
            }
        }
    }
    // must always be at the end (only for end message)
    $migration->executeMigration();
    return $updateresult;
}
/** Generate bigdump : generate items for an entity
 *
 * @param $ID_entity entity ID
**/
function generate_entity($ID_entity) {
   global $MAX, $DB, $percent, $FIRST, $LAST, $MAX_KBITEMS_BY_CAT, $MAX_DISK,
         $DOCUMENTS, $NET_PORT, $NET_LOC;

   regenerateTreeCompleteName("glpi_entities");

   $current_year = date("Y");


   // DOMAIN
   $items = array("SP2MI", "CAMPUS"," IUT86", "PRESIDENCE", "CEAT", "D'omaine");
   $dp    = new Domain();
   $FIRST["domain"] = getMaxItem("glpi_domains")+1;

   for ($i=0 ; $i<$MAX['domain'] ; $i++) {
      if (isset($items[$i])) {
         $val = $items[$i];
      } else {
         $val = "domain $ID_entity '$i";
      }
      $dp->add(toolbox::addslashes_deep(array('name'         => $val,
                                              'entities_id'  => $ID_entity,
                                              'is_recursive' => 1,
                                              'comment'      => "comment $val")));
   }
   $LAST["domain"] = getMaxItem("glpi_domains");


   // STATUS
   $items = array("Reparation", "En stock", "En fonction", "Retour SAV", "En attente d'");
   $dp    = new State();
   $FIRST["state"] = getMaxItem("glpi_states")+1;
   for ($i=0 ; $i<$MAX['state'] ; $i++) {
      if (isset($items[$i])) {
         $val = $items[$i];
      } else {
         $val = "State $ID_entity '$i";
      }
      $state_id = $dp->add(toolbox::addslashes_deep(array('name'         => $val,
                                                          'entities_id'  => $ID_entity,
                                                          'is_recursive' => 1,
                                                          'comment'      => "comment $val")));

      // generate sub status
      for ($j=0 ; $j<$MAX['state'] ; $j++) {
         $val2 = "Sub $val $j";

         $dp->add(toolbox::addslashes_deep(array('name'         => $val2,
                                                 'entities_id'  => $ID_entity,
                                                 'is_recursive' => 1,
                                                 'states_id'    => $state_id,
                                                 'comment'      => "comment $val")));
      }

   }
   $LAST["state"]      = getMaxItem("glpi_states");


   // glpi_groups
   $FIRST["groups"] = getMaxItem("glpi_groups")+1;
   $group           = new Group();
   for ($i=0 ; $i<$MAX['groups'] ; $i++) {
      $gID = $group->add(toolbox::addslashes_deep(
                         array('entities_id'  => $ID_entity,
                               'name'         => "group d'$i",
                               'comment'      => "comment group d'$i",
                               'is_assign'    => 0)));

      // Generate sub group
      for ($j=0 ; $j<$MAX['groups'] ; $j++) {
         $group->add(toolbox::addslashes_deep(
                     array('entities_id'  => $ID_entity,
                           'name'         => "subgroup d'$j",
                           'comment'      => "comment subgroup d'$j of group $i",
                           'groups_id'    => $gID,
                           'is_assign'    => 0)));
      }
   }

   $LAST["groups"]      = getMaxItem("glpi_groups");

   $FIRST["techgroups"] = $LAST["groups"]+1;

   for ($i=0 ; $i<$MAX['groups'] ; $i++) {
         $group->add(toolbox::addslashes_deep(
                     array('entities_id'  => $ID_entity,
                           'name'         => "tech group d'$i",
                           'comment'      => "comment tech group d'$i")));
   }

   $LAST["techgroups"] = getMaxItem("glpi_groups");
   regenerateTreeCompleteName("glpi_groups");


   // glpi_users
   $FIRST["users_sadmin"] = getMaxItem("glpi_users")+1;
   $user                  = new User();
   $gu                    = new Group_User();
   for ($i=0 ; $i<$MAX['users_sadmin'] ; $i++) {
      $users_id = $user->add(toolbox::addslashes_deep(
                             array('name'               => "sadmin$i-$ID_entity",
                                   'password'           => "sadmin'$i",
                                   'password2'          => "sadmin'$i",
                                   'phone'              => "tel $i",
                                   'phone2'             => "tel2 $i",
                                   'mobile'             => "mobile $i",
                                   'realname'           => "sadmin '$i name",
                                   'firstname'          => "sadmin '$i firstname",
                                   'comment'            => "comment' $i",
                                   'usertitles_id'      => mt_rand(0,$MAX['user_title']),
                                   'usercategories_id'  => mt_rand(0,$MAX['user_type']),
                                   '_profiles_id'       => 4,
                                   '_entities_id'       => $ID_entity,
                                   '_is_recursive'      => 1
                                   )));

      $gu->add(array('users_id'     => $users_id,
                     'groups_id'    => mt_rand($FIRST['groups'], $LAST['groups'])));

      $gu->add(array('users_id'     => $users_id,
                     'groups_id'    => mt_rand($FIRST['techgroups'], $LAST['techgroups'])));
   }
   $LAST["users_sadmin"] = getMaxItem("glpi_users");
   $FIRST["users_admin"] = getMaxItem("glpi_users")+1;

   for ($i=0 ; $i<$MAX['users_admin'] ; $i++) {

      $users_id = $user->add(toolbox::addslashes_deep(
                             array('name'               => "admin$i-$ID_entity",
                                   'password'           => "admin'$i",
                                   'password2'          => "admin'$i",
                                   'phone'              => "tel $i",
                                   'phone2'             => "tel2 $i",
                                   'mobile'             => "mobile $i",
                                   'realname'           => "admin$i 'name",
                                   'firstname'          => "admin$i 'firstname",
                                   'comment'            => "comment '$i",
                                   'usertitles_id'      => mt_rand(0,$MAX['user_title']),
                                   'usercategories_id'  => mt_rand(0,$MAX['user_type']),
                                   '_profiles_id'       => 3,
                                   '_entities_id'       => $ID_entity,
                                   '_is_recursive'      => 1)));

      $gu->add(array('users_id'     => $users_id,
                     'groups_id'    => mt_rand($FIRST['groups'], $LAST['groups']),
                     'is_manager'   => 1,
                     'is_delegate'  => 1));

      $gu->add(array('users_id'     => $users_id,
                     'groups_id'    => mt_rand($FIRST['techgroups'], $LAST['techgroups']),
                     'is_manager'   => 1,
                     'is_delegate'  => 1));
   }

   $LAST["users_admin"]   = getMaxItem("glpi_users");
   $FIRST["users_normal"] = getMaxItem("glpi_users")+1;

   for ($i=0 ; $i<$MAX['users_normal'] ; $i++) {
      $users_id = $user->add(toolbox::addslashes_deep(
                             array('name'               => "normal$i-$ID_entity",
                                   'password'           => "normal'$i",
                                   'password2'          => "normal'$i",
                                   'phone'              => "tel $i",
                                   'phone2'             => "tel2 $i",
                                   'mobile'             => "mobile $i",
                                   'realname'           => "normal$i 'name",
                                   'firstname'          => "normal$i 'firstname",
                                   'comment'            => "comment '$i",
                                   'usertitles_id'      => mt_rand(0,$MAX['user_title']),
                                   'usercategories_id'  => mt_rand(0,$MAX['user_type']),
                                   '_profiles_id'       => 2,
                                   '_entities_id'       => $ID_entity,
                                   '_is_recursive'      => 1)));

      $gu->add(array('users_id'     => $users_id,
                     'groups_id'    => mt_rand($FIRST['groups'], $LAST['groups'])));

      $gu->add(array('users_id'     => $users_id,
                     'groups_id'    => mt_rand($FIRST['techgroups'], $LAST['techgroups'])));
   }

   $LAST["users_normal"]    = getMaxItem("glpi_users");
   $FIRST["users_postonly"] = getMaxItem("glpi_users")+1;

   for ($i=0 ; $i<$MAX['users_postonly'] ; $i++) {
      $users_id = $user->add(toolbox::addslashes_deep(
                             array('name'               => "postonly$i-$ID_entity",
                                   'password'           => "postonly'$i",
                                   'password2'          => "postonly'$i",
                                   'phone'              => "tel $i",
                                   'phone2'             => "tel2 $i",
                                   'mobile'             => "mobile $i",
                                   'realname'           => "postonly$i 'name",
                                   'firstname'          => "postonly$i 'firstname",
                                   'comment'            => "comment' $i",
                                   'usertitles_id'      => mt_rand(0,$MAX['user_title']),
                                   'usercategories_id'  => mt_rand(0,$MAX['user_type']),
                                   '_profiles_id'       => 1,
                                   '_entities_id'       => $ID_entity,
                                   '_is_recursive'      => 1)));

      $gu->add(array('users_id'     => $users_id,
                     'groups_id'    => mt_rand($FIRST['groups'], $LAST['groups'])));
   }

   $LAST["users_postonly"] = getMaxItem("glpi_users");


   $FIRST["kbcategories"] = getMaxItem("glpi_knowbaseitemcategories")+1;
   $kbc                   = new KnowbaseItemCategory();

   for ($i=0 ; $i<max(1,pow($MAX['kbcategories'],1/3)) ; $i++) {
      $newID = $kbc->add(toolbox::addslashes_deep(
                         array('entities_id'     => $ID_entity,
                               'is_recursive'    => 1,
                               'name'            => "entity ' categorie $i",
                               'comment'         => "comment ' categorie $i")));

      for ($j=0 ; $j<mt_rand(0,pow($MAX['kbcategories'],1/2)) ; $j++) {
         $newID2 = $kbc->add(toolbox::addslashes_deep(
                             array('entities_id'                 => $ID_entity,
                                   'is_recursive'                => 1,
                                   'name'                        => "entity s-categorie '$j",
                                   'comment'                     => "comment s-categorie '$j",
                                   'knowbaseitemcategories_id'   => $newID)));

         for ($k=0 ; $k<mt_rand(0,pow($MAX['kbcategories'],1/2)) ; $k++) {
            $newID2 = $kbc->add(toolbox::addslashes_deep(
                                array('entities_id'               => $ID_entity,
                                      'is_recursive'              => 1,
                                      'name'                      => "entity ss-categorie' $k",
                                      'comment'                   => "comment ss-categorie' $k",
                                      'knowbaseitemcategories_id' => $newID2)));
         }
      }
   }

   $query = "OPTIMIZE TABLE `glpi_knowbaseitemcategories`";
   $DB->query($query) or die("PB REQUETE ".$query);

   regenerateTreeCompleteName("glpi_knowbaseitemcategories");
   $LAST["kbcategories"] = getMaxItem("glpi_knowbaseitemcategories");


   // LOCATIONS
   $added              = 0;
   $FIRST["locations"] = getMaxItem("glpi_locations")+1;
   $loc                = new Location();
   for ($i=0 ; $i<pow($MAX['locations'],1/5)&&$added<$MAX['locations'] ; $i++) {
      $added++;
      $newID = $loc->add(toolbox::addslashes_deep(
                         array('entities_id'     => $ID_entity,
                               'is_recursive'    => 1,
                               'name'            => "location' $i",
                               'comment'         => "comment 'location $i",
                               'building'        => "building $i")));

      for ($j=0 ; $j<mt_rand(0,pow($MAX['locations'],1/4))&&$added<$MAX['locations'] ; $j++) {
         $added++;
         $newID2 = $loc->add(toolbox::addslashes_deep(
                             array('entities_id'     => $ID_entity,
                                   'is_recursive'    => 1,
                                   'name'            => "s-location '$j",
                                   'comment'         => "comment s-location '$j",
                                   'building'        => "building $i",
                                   'room'            => "stage '$j",
                                   'locations_id'    => $newID)));

         for ($k=0 ; $k<mt_rand(0,pow($MAX['locations'],1/4))&&$added<$MAX['locations'] ; $k++) {
            $added++;
            $newID3 = $loc->add(toolbox::addslashes_deep(
                                array('entities_id'     => $ID_entity,
                                      'is_recursive'    => 1,
                                      'name'            => "ss-location '$k",
                                      'comment'         => "comment ss-location' $k",
                                      'building'        => "building $i",
                                      'room'            => "part' $k",
                                      'locations_id'    => $newID2)));

            for ($l=0 ; $l<mt_rand(0,pow($MAX['locations'],1/4))&&$added<$MAX['locations'] ; $l++) {
               $added++;
               $newID4 = $loc->add(toolbox::addslashes_deep(
                                   array('entities_id'     => $ID_entity,
                                         'is_recursive'    => 1,
                                         'name'            => "sss-location' $l",
                                         'comment'         => "comment sss-location' $l",
                                         'building'        => "building $i",
                                         'room'            => "room' $l",
                                         'locations_id'    => $newID3)));

               for ($m=0 ; $m<mt_rand(0,pow($MAX['locations'],1/4))&&$added<$MAX['locations'] ; $m++) {
                  $added++;
                  $newID5 = $loc->add(toolbox::addslashes_deep(
                                      array('entities_id'     => $ID_entity,
                                            'is_recursive'    => 1,
                                            'name'            => "ssss-location' $m",
                                            'comment'         => "comment ssss-location' $m",
                                            'building'        => "building $i",
                                            'room'            => "room' $l-$m",
                                            'locations_id'    => $newID4)));
               }
            }
         }
      }
   }

   $query = "OPTIMIZE TABLE `glpi_locations`";
   $DB->query($query) or die("PB REQUETE ".$query);

   regenerateTreeCompleteName("glpi_locations");
   $LAST["locations"]=getMaxItem("glpi_locations");


   // Task categories
   $added                 = 0;
   $FIRST["taskcategory"] = getMaxItem("glpi_taskcategories")+1;
   $tc                    = new TaskCategory();
   for ($i=0 ; $i<pow($MAX['taskcategory'],1/5)&&$added<$MAX['taskcategory'] ; $i++) {
      $added++;
      $newID = $tc->add(toolbox::addslashes_deep(
                        array('entities_id'     => $ID_entity,
                              'is_recursive'    => 1,
                              'name'            => "ent$ID_entity taskcategory' $i",
                              'comment'         => "comment ent$ID_entity taskcategory' $i")));

      for ($j=0 ; $j<mt_rand(0,pow($MAX['locations'],1/4))&&$added<$MAX['locations'] ; $j++) {
         $newID2 = $tc->add(toolbox::addslashes_deep(
                            array('entities_id'        => $ID_entity,
                                  'is_recursive'       => 1,
                                  'name'               => "ent$ID_entity taskcategory' $i",
                                  'comment'            => "comment ent$ID_entity taskcategory' $i",
                                  'taskcategories_id'  => $newID)));
         $added++;
      }
   }

   $query = "OPTIMIZE TABLE `glpi_taskcategories`";
   $DB->query($query) or die("PB REQUETE ".$query);

   regenerateTreeCompleteName("glpi_taskcategories");
   $LAST["taskcategory"] = getMaxItem("glpi_taskcategories");

   $ic = new ItilCategory();
   // Specific ticket categories
   $newID = $ic->add(toolbox::addslashes_deep(
                     array('entities_id'     => $ID_entity,
                           'is_recursive'    => 1,
                           'name'            => "category for entity' $ID_entity",
                           'comment'         => "comment category for entity' $ID_entity",
                           'users_id'        => mt_rand($FIRST['users_sadmin'],$LAST['users_admin']),
                           'groups_id'       => mt_rand($FIRST['techgroups'],$LAST['techgroups']),
                           'tickettemplates_id_incident' => 1,
                           'tickettemplates_id_demand'   => 1)));

   for ($i=0 ; $i<max(1,pow($MAX['tracking_category'],1/3)) ; $i++) {
      $ic->add(toolbox::addslashes_deep(
               array('entities_id'                 => $ID_entity,
                     'is_recursive'                => 1,
                     'name'                        => "scategory for entity' $ID_entity",
                     'comment'                     => "comment scategory for entity' $ID_entity",
                     'users_id'                    => mt_rand($FIRST['users_sadmin'],
                                                              $LAST['users_admin']),
                     'groups_id'                   => mt_rand($FIRST['techgroups'],
                                                              $LAST['techgroups']),
                     'tickettemplates_id_incident' => 1,
                     'tickettemplates_id_demand'   => 1,
                     'itilcategories_id'           => $newID)));
   }

   regenerateTreeCompleteName("glpi_itilcategories");

   $FIRST["solutiontypes"] = getMaxItem("glpi_solutiontypes")+1;

   $items = array("d'après KB");
   $st    = new SolutionType();
   for ($i=0 ; $i<$MAX['solutiontypes'] ; $i++) {
      if (isset($items[$i])) {
         $val = $items[$i];
      } else {
         $val = "type de solution ' $i";
      }
      $st->add(toolbox::addslashes_deep(array('name'         => $val,
                                              'comment'      => "comment $val",
                                              'entities_id'  => $ID_entity,
                                              'is_recursive' => 1)));
   }
   $LAST["solutiontypes"] = getMaxItem("glpi_solutiontypes");


   $FIRST["solutiontemplates"] = getMaxItem("glpi_solutiontemplates")+1;
   $nb_items                   = mt_rand(0,$MAX['solutiontemplates']);
   $st                         = new SolutionTemplate();
   for ($i=0 ; $i<$nb_items ; $i++) {
      $st-> add(toolbox::addslashes_deep(
                array('entities_id'        => $ID_entity,
                      'is_recursive'       => 1,
                      'name'               => "solution' $i-$ID_entity",
                      'content'            => "content solution' $i-$ID_entity",
                      'solutiontypes_id'   => mt_rand(0,$MAX['solutiontypes']),
                      'comment'            => "comment solution' $i-$ID_entity")));
   }

   $LAST["solutiontemplates"] = getMaxItem("glpi_solutiontemplates");

   // Add Specific questions
   $k                = 0;
   $FIRST["kbitems"] = getMaxItem("glpi_knowbaseitems")+1;
   $ki               = new KnowbaseItem();
   $eki              = new Entity_KnowbaseItem();
   for ($i=$FIRST['kbcategories'] ; $i<=$LAST['kbcategories'] ; $i++) {
      $nb = mt_rand(0,$MAX_KBITEMS_BY_CAT);
      for ($j=0 ; $j<$nb ; $j++) {
         $k++;
         $newID = $ki->add(toolbox::addslashes_deep(
                           array('knowbaseitemcategories_id'   => $i,
                                 'name'      => "Entity' $ID_entity Question $k",
                                 'answer'    => "Answer' $k".Toolbox::getRandomString(50),
                                 'is_faq'    => mt_rand(0,1),
                                 'users_id'  => mt_rand($FIRST['users_sadmin'],
                                                        $LAST['users_admin']))));

         $eki->add(array('entities_id'       => $ID_entity,
                        'knowbaseitems_id'   => $newID,
                        'is_recursive'       => 0));
      }
   }


   // Add global questions
   for ($i=$FIRST['kbcategories'] ; $i<=$LAST['kbcategories'] ; $i++) {
      $nb = mt_rand(0,$MAX_KBITEMS_BY_CAT);
      for ($j=0 ; $j<$nb ; $j++) {
         $k++;
         $newID = $ki->add(toolbox::addslashes_deep(
                           array('knowbaseitemcategories_id'   => $i,
                                 'name'      => "Entity' $ID_entity Recursive Question $k",
                                 'answer'    => "Answer' $k".Toolbox::getRandomString(50),
                                 'is_faq'    => mt_rand(0,1),
                                 'users_id'  => mt_rand($FIRST['users_sadmin'],
                                                        $LAST['users_admin']))));

         $eki->add(array('entities_id'       => $ID_entity,
                        'knowbaseitems_id'   => $newID,
                        'is_recursive'       => 1));
      }
   }

   $LAST["kbitems"] = getMaxItem("glpi_knowbaseitems");


   // Ajout documents  specific
   $FIRST["document"] = getMaxItem("glpi_documents")+1;
   $doc               = new Document();
   for ($i=0 ; $i<$MAX['document'] ; $i++) {
      $link = "";
      if (mt_rand(0,100)<50) {
         $link = "http://linktodoc/doc$i";
      }

      $docID = $doc->add(toolbox::addslashes_deep(
                         array('entities_id'           => $ID_entity,
                               'is_recursive'          => 0,
                               'name'                  => "document' $i-$ID_entity",
                               'documentcategories_id' => mt_rand(1,$MAX['rubdocs']),
                               'comment'               => "commen't $i",
                               'link'                  => $link,
                               'notepad'               => "notes document' $i")));

      $DOCUMENTS[$docID] = $ID_entity."-0";
   }


   // Global ones
   for ($i=0 ; $i<$MAX['document']/2 ; $i++) {
      $link = "";
      if (mt_rand(0,100)<50) {
         $link = "http://linktodoc/doc$i";
      }

      $docID = $doc->add(toolbox::addslashes_deep(
                         array('entities_id'           => $ID_entity,
                               'is_recursive'          => 1,
                               'name'                  => "Recursive document' $i-$ID_entity",
                               'documentcategories_id' => mt_rand(1,$MAX['rubdocs']),
                               'comment'               => "comment' $i",
                               'link'                  => $link,
                               'notepad'               => "notes document' $i")));

      $DOCUMENTS[$docID] = $ID_entity."-1";
   }

   $LAST["document"] = getMaxItem("glpi_documents");


   // Ajout budgets  specific
   $FIRST["budget"] = getMaxItem("glpi_budgets")+1;
   $b               = new Budget();
   for ($i=0 ; $i<$MAX['budget'] ; $i++) {
      $date1 = strtotime(mt_rand(2000,$current_year)."-".mt_rand(1,12)."-".mt_rand(1,28));
      $date2 = $date1+MONTH_TIMESTAMP*12*mt_rand(1,4); // + entre 1 et 4 ans

      $b->add(toolbox::addslashes_deep(
              array('name'         => "budget' $i-$ID_entity",
                    'entities_id'  => $ID_entity,
                    'is_recusive'  => 0,
                    'comment'      => "comment' $i-$ID_entity",
                    'begin_date'   => date("Y-m-d",intval($date1)),
                    'end_date'     => date("Y-m-d",intval($date2)))));
   }
   $LAST["budget"] = getMaxItem("glpi_budgets");

   // GLobal ones
   for ($i=0 ; $i<$MAX['document']/2 ; $i++) {
      $date1 = strtotime(mt_rand(2000,$current_year)."-".mt_rand(1,12)."-".mt_rand(1,28));
      $date2 = $date1+MONTH_TIMESTAMP*12*mt_rand(1,4); // + entre 1 et 4 ans

      $b->add(toolbox::addslashes_deep(
              array('name'         => "Recursive budget' $i-$ID_entity",
                    'entities_id'  => $ID_entity,
                    'is_recusive'  => 1,
                    'comment'      => "comment' $i-$ID_entity",
                    'begin_date'   => date("Y-m-d",intval($date1)),
                    'end_date'     => date("Y-m-d",intval($date2)))));

   }
   $LAST["document"] = getMaxItem("glpi_documents");


   // glpi_suppliers
   $items                = array("DELL", "IBM", "ACER", "Microsoft", "Epson", "Xerox",
                                 "Hewlett Packard", "Nikon", "Targus", "LG", "Samsung", "Lexmark");
   $FIRST["enterprises"] = getMaxItem("glpi_suppliers")+1;
   $ent                  = new Supplier();

   // Global ones
   for ($i=0 ; $i<$MAX['enterprises']/2 ; $i++) {
      if (isset($items[$i])) {
         $val = "Recursive ".$items[$i];
      } else {
         $val = "Recursive enterprise_".$i."_ID_entity";
      }
      $entID = $ent->add(toolbox::addslashes_deep(
                         array('entities_id'        => $ID_entity,
                               'is_recursive'       => 1,
                               'name'               => "Recursive' $val-$ID_entity",
                               'suppliertypes_id'   => mt_rand(1,$MAX['enttype']),
                               'address'            => "address' $i",
                               'postcode'           => "postcode $i",
                               'town'               => "town' $i",
                               'state'              => "state' $i",
                               'country'            => "country $i",
                               'website'            => "http://www.$val.com/",
                               'fax'                => "fax $i",
                               'email'              => "info@ent$i.com",
                               'notepad'            => "notes enterprises' $i")));

      addDocuments('Supplier', $entID);
   }


   // Specific ones
   for ($i=0 ; $i<$MAX['enterprises'] ; $i++) {
      if (isset($items[$i])) {
         $val = $items[$i];
      } else {
         $val = "enterprise_".$i."_ID_entity";
      }

      $entID = $ent->add(toolbox::addslashes_deep(
                         array('entities_id'        => $ID_entity,
                               'is_recursive'       => 0,
                               'name'               => "'$val-$ID_entity",
                               'suppliertypes_id'   => mt_rand(1,$MAX['enttype']),
                               'address'            => "address' $i",
                               'postcode'           => "postcode $i",
                               'town'               => "town' $i",
                               'state'              => "state' $i",
                               'country'            => "country $i",
                               'website'            => "http://www.$val.com/",
                               'fax'                => "fax $i",
                               'email'              => "info@ent$i.com",
                               'notepad'            => "notes supplier' $i",
                               'comment'            => "comment supplier' $i")));

      addDocuments('Supplier', $entID);
   }
   $LAST["enterprises"] = getMaxItem("glpi_suppliers");


   // Ajout contracts
   $FIRST["contract"] = getMaxItem("glpi_contracts")+1;
   $c                 = new Contract();
   $cs                = new Contract_Supplier();
   $cc                = new ContractCost();
   // Specific
   for ($i=0 ; $i<$MAX['contract'] ; $i++) {
      $date = mt_rand(2000,$current_year)."-".mt_rand(1,12)."-".mt_rand(1,28);
      $contractID = $c->add(toolbox::addslashes_deep(
                            array('entities_id'        => $ID_entity,
                                  'is_recursive'       => 0,
                                  'name'               => "contract' $i-$ID_entity",
                                  'num'                => "num' $i",
                                  'contracttypes_id'   => mt_rand(1,$MAX['contract_type']),
                                  'begin_date'         => $date,
                                  'duration'           => mt_rand(1,36),
                                  'notice'             => mt_rand(1,3),
                                  'periodicity'        => mt_rand(1,36),
                                  'billing'            => mt_rand(1,36),
                                  'comment'            => "comment' $i",
                                  'accounting_number'  => "compta num' $i",
                                  'renewal'            => 1)));

      addDocuments('Contract', $contractID);

      // Add an enterprise
      $cs->add(array('contracts_id' => $contractID,
                     'suppliers_id' => mt_rand($FIRST["enterprises"], $LAST["enterprises"])));
      // Add a cost
      $cc->add(toolbox::addslashes_deep(
               array('contracts_id' => $contractID,
                     'cost'         => mt_rand(100,10000),
                     'name'         => "Initial 'cost",
                     'begin_date'   => $date,
                     'budgets_id'   => mt_rand($FIRST['budget'], $LAST['budget']))));
   }

   for ($i=0 ; $i<$MAX['contract']/2 ; $i++) {
      $date = mt_rand(2000,$current_year)."-".mt_rand(1,12)."-".mt_rand(1,28);

      $contractID = $c->add(toolbox::addslashes_deep(
                            array('entities_id'        => $ID_entity,
                                  'is_recursive'       => 1,
                                  'name'               => "Recursive contract' $i-$ID_entity",
                                  'num'                => "num' $i",
                                  'cost'               => mt_rand(100,10000),
                                  'contracttypes_id'   => mt_rand(1,$MAX['contract_type']),
                                  'begin_date'         => $date,
                                  'duration'           => mt_rand(1,36),
                                  'notice'             => mt_rand(1,3),
                                  'periodicity'        => mt_rand(1,36),
                                  'billing'            => mt_rand(1,36),
                                  'comment'            => "comment' $i",
                                  'accounting_number'  => "compta num' $i",
                                  'renewal'            => 1)));

      addDocuments('Contract', $contractID);

      // Add an enterprise
      $cs->add(array('contracts_id' => $contractID,
                     'suppliers_id' => mt_rand($FIRST["enterprises"], $LAST["enterprises"])));
   }
   $LAST["contract"] = getMaxItem("glpi_contracts");


   // Ajout contacts
   $prenoms = array("Jean", "John", "Louis", "Pierre", "Auguste",
                    "Albert", "Julien", "Guillaume", "Bruno",
                    "Maurice", "Francois", "Laurent", "Richard",
                    "Henri", "Clement", "d'avy");
   $noms    = array("Dupont", "Smith", "Durand", "Martin", "Dubois",
                    "Dufour", "Dupin", "Duval", "Petit", "Grange",
                    "Bernard", "Bonnet", "Richard", "Leroy",
                    "Dumont", "Fontaine", "d'orleans");


   $FIRST["contacts"] = getMaxItem("glpi_contacts")+1;
   $c                 = new Contact();
   $cs                = new Contact_Supplier();
   for ($i=0 ; $i<$MAX['contacts'] ; $i++) {
      if (isset($noms[$i])) {
         $val = $noms[$i];
      } else {
         $val = "name $i";
      }
      if (isset($prenoms[$i])) {
         $val2 = $prenoms[$i];
      } else {
         $val2 = "firstname $i";
      }

      $contactID = $c->add(toolbox::addslashes_deep(
                           array('entities_id'        => $ID_entity,
                                 'is_recursive'       => 0,
                                 'name'               => "$val-$ID_entity",
                                 'firstname'          => $val2,
                                 'contacttypes_id'    => mt_rand(1,$MAX['contact_type']),
                                 'usertitles_id'      => mt_rand(0,$MAX['user_title']),
                                 'phone'              => "phone $i",
                                 'phone2'             => "phone2 $i",
                                 'mobile'             => "mobile $i",
                                 'fax'                => "fax $i",
                                 'email'              => "email $i",
                                 'address'            => "address' $i",
                                 'postcode'           => "postcode $i",
                                 'town'               => "town' $i",
                                 'state'              => "state' $i",
                                 'country'            => "country $i",
                                 'comment'            => "Comment' $i")));

      // Link with enterprise
      $cs->add(array('contacts_id'  => $contactID,
                     'suppliers_id' => mt_rand($FIRST['enterprises'],$LAST['enterprises'])));
   }

   for ($i=0 ; $i<$MAX['contacts']/2 ; $i++) {
      if (isset($items[$i])) {
         $val = "Recursive ".$items[$i];
      } else {
         $val = "Recursive contact $i";
      }
      $contactID = $c->add(toolbox::addslashes_deep(
                           array('entities_id'        => $ID_entity,
                                 'is_recursive'       => 0,
                                 'name'               => "$val'-$ID_entity",
                                 'contacttypes_id'    => mt_rand(1,$MAX['contact_type']),
                                 'usertitles_id'      => mt_rand(0,$MAX['user_title']),
                                 'phone'              => "phone $i",
                                 'phone2'             => "phone2 $i",
                                 'mobile'             => "mobile $i",
                                 'fax'                => "fax $i",
                                 'email'              => "email $i",
                                 'address'            => "address' $i",
                                 'postcode'           => "postcode $i",
                                 'town'               => "town' $i",
                                 'state'              => "state' $i",
                                 'country'            => "country $i",
                                 'comment'            => "Comment' $i")));

      // Link with enterprise
      $cs->add(array('contacts_id'  => $contactID,
                     'suppliers_id' => mt_rand($FIRST['enterprises'],$LAST['enterprises'])));
   }
   $LAST["contacts"] = getMaxItem("glpi_contacts");


   // TYPE DE CONSOMMABLES
   $FIRST["type_of_consumables"] = getMaxItem("glpi_consumableitems")+1;
   $ci                           = new Consumableitem();

   for ($i=0 ; $i<$MAX['type_of_consumables'] ; $i++) {
      $consID = $ci->add(toolbox::addslashes_deep(
                         array('entities_id'             => $ID_entity,
                               'is_recursive'            => mt_rand(0,1),
                               'name'                    => "consumable type' $i",
                               'ref'                     => "ref d' $i",
                               'locations_id'            => mt_rand($FIRST["locations"],
                                                                    $LAST['locations']),
                               'consumableitemtypes_id'  => mt_rand(0,$MAX['consumable_type']),
                               'manufacturers_id'        => mt_rand(1,$MAX['manufacturer']),
                               'users_id_tech'           => mt_rand($FIRST['users_sadmin'],
                                                                    $LAST['users_admin']),
                               'groups_id_tech'          => mt_rand($FIRST["groups"], $LAST["groups"]),
                               'comment'                 => "comment' $i",
                               'notepad'                 => "notes consumableitem' $i",
                               'alarm_threshold'         => mt_rand(0,10))));

      addDocuments('ConsumableItem', $consID);


      // AJOUT INFOCOMS
      addInfocoms('ConsumableItem', $consID, $ID_entity);

      // Ajout consommable en stock
      $c = new Consumable();
      for ($j=0 ; $j<mt_rand(0,$MAX['consumables_stock']) ; $j++) {
         $date = mt_rand(2000,$current_year)."-".mt_rand(1,12)."-".mt_rand(1,28);

         $ID = $c->add(array('entities_id'        => $ID_entity,
                             'consumableitems_id' => $consID,
                             'date_in'            => $date));

         // AJOUT INFOCOMS
         addInfocoms('Consumable', $ID, $ID_entity);
      }


      // Ajout consommable donne
      for ($j=0 ; $j<mt_rand(0,$MAX['consumables_given']) ; $j++) {
         $date = mt_rand(2000,$current_year-1)."-".mt_rand(1,12)."-".mt_rand(1,28);

         $ID = $c->add(array('entities_id'        => $ID_entity,
                             'consumableitems_id' => $consID,
                             'date_in'            => $date,
                             'date_out'           => date("Y-m-d")));

         // AJOUT INFOCOMS
         addInfocoms('Consumable', $ID, $ID_entity);

      }

   }
   $LAST["type_of_consumables"] = getMaxItem("glpi_consumableitems");


   // TYPE DE CARTOUCHES
   $FIRST["type_of_cartridges"] = getMaxItem("glpi_cartridgeitems")+1;
   $ct                          = new CartridgeItem();

   for ($i=0 ; $i<$MAX['type_of_cartridges'] ; $i++) {
      $cartID = $ct->add(toolbox::addslashes_deep(
                         array('entities_id'       => $ID_entity,
                               'is_recursive'      => mt_rand(0,1),
                               'name'              => "cartridge ' type $i",
                               'ref'               => "ref '$i",
                               'locations_id'      => mt_rand($FIRST["locations"], $LAST['locations']),
                               'manufacturers_id'  => mt_rand(1,$MAX['manufacturer']),
                               'users_id_tech'     => mt_rand($FIRST['users_sadmin'],
                                                              $LAST['users_admin']),
                               'groups_id_tech'    => mt_rand($FIRST["groups"], $LAST["groups"]),
                               'comment'           => "comment '$i",
                               'notepad'           => "notes cartridgeitem '$i",
                               'alarm_threshold'   => mt_rand(0,10))));

      addDocuments('CartridgeItem', $cartID);


      // AJOUT INFOCOMS
      addInfocoms('CartridgeItem', $cartID, $ID_entity);

      $c    = new Cartridge();
      $cipm = new CartridgeItem_PrinterModel();
      // Ajout cartouche en stock
      for ($j=0 ; $j<mt_rand(0,$MAX['cartridges_stock']) ; $j++) {
         $date = mt_rand(2000,$current_year-1)."-".mt_rand(1,12)."-".mt_rand(1,28);

         $ID = $c->add(array('entities_id'         => $ID_entity,
                             'cartridgeitems_id'   => $cartID,
                             'date_in'             => $date));

         // AJOUT INFOCOMS
         addInfocoms('Cartridge', $ID, $ID_entity);

      }

      // Assoc printer type to cartridge type
      $cipm->add(array('cartridgeitems_id'  => $cartID,
                       'printermodels_id'   => mt_rand(1,$MAX['type_printers']),
                     ));
   }
   $LAST["type_of_cartridges"] = getMaxItem("glpi_cartridgeitems");


   // Networking
   $NET_LOC             = array();
   $FIRST["networking"] = getMaxItem("glpi_networkequipments")+1;
   $FIRST["printers"]   = getMaxItem("glpi_printers")+1;
   $ne                  = new NetworkEquipment();
   $p                   = new Printer();
   $np                  = new Netpoint();
   $c                   = new Cartridge();

   foreach ($DB->request('glpi_locations') as $data) {
      $i          = $data["id"];
      $techID     = mt_rand($FIRST['users_sadmin'],$LAST['users_admin']);
      $gtechID    = mt_rand($FIRST["techgroups"],$LAST["techgroups"]);
      $infoIP     = getNextIP();
      $domainID   = mt_rand($FIRST['domain'],$LAST['domain']);
      $networkID  = mt_rand(1,$MAX['network']);

      // insert networking

      $netwID = $ne->add(toolbox::addslashes_deep(
                         array('entities_id'                   => $ID_entity,
                               'name'                          => "networking '$i-$ID_entity",
                               'ram'                           => mt_rand(32,256),
                               'serial'                        => Toolbox::getRandomString(10),
                               'otherserial'                   => Toolbox::getRandomString(10),
                               'contact'                       => "contact '$i",
                               'contact_num'                   => "num '$i",
                               'users_id_tech'                 => $techID,
                               'groups_id_tech'                => $gtechID,
                               'comment'                       => "comment '$i",
                               'locations_id'                  => $i,
                               'domains_id'                    => $domainID,
                               'networks_id'                   => $networkID,
                               'networkequipmenttypes_id'      => mt_rand(1,$MAX['type_networking']),
                               'networkequipmentmodels_id'     => mt_rand(1,$MAX['model_networking']),
                               'networkequipmentfirmwares_id'  => mt_rand(1,$MAX['firmware']),
                               'manufacturers_id'              => mt_rand(1,$MAX['enterprises']),
                               'mac'                           => getNextMAC(),
                               'ip'                            => $infoIP["ip"],
                               'notepad'                       => "notes networking '$i",
                               'users_id'                      => mt_rand($FIRST['users_sadmin'],
                                                                          $LAST['users_admin']),
                               'groups_id'                     => mt_rand($FIRST["groups"],
                                                                          $LAST["groups"]),
                               'states_id'                     => (mt_rand(0,100)<$percent['state']
                                                                     ?mt_rand($FIRST['state'],$LAST['state']):0)
                           )));
      $NET_LOC[$data['id']] = $netwID;
      addDocuments('NetworkEquipment', $netwID);
      addContracts('NetworkEquipment', $netwID);

      // AJOUT INFOCOMS
      addInfocoms('NetworkEquipment', $netwID, $ID_entity);

      // Link with father
      addNetworkEthernetPort('NetworkEquipment', $netwID, $ID_entity, $i);

      // Ajout imprimantes reseaux : 1 par loc + connexion d un matos reseau + ajout de cartouches
      // Add trackings
      addTracking('NetworkEquipment', $netwID, $ID_entity);

      $typeID  = mt_rand(1,$MAX['type_printers']);
      $modelID = mt_rand(1,$MAX['model_printers']);
      $recur   = mt_rand(0,1);

      $printID = $p->add(toolbox::addslashes_deep(
                         array('entities_id'      => $ID_entity,
                                'is_recursive'     => $recur,
                                'name'             => "printer of loc '$i",
                                'serial'           => Toolbox::getRandomString(10),
                                'otherserial'      => Toolbox::getRandomString(10),
                                'contact'          => "contact '$i",
                                'contact_num'      => "num' $i",
                                'users_id_tech'    => $techID,
                                'groups_id_tech'   => $gtechID,
                                'have_serial'      => mt_rand(0,1),
                                'have_parallel'    => mt_rand(0,1),
                                'have_usb'         => mt_rand(0,1),
                                'have_wifi'        => mt_rand(0,1),
                                'have_ethernet'    => mt_rand(0,1),
                                'comment'          => "comment' $i",
                                'memory_size'      => mt_rand(0,128),
                                'locations_id'     => $i,
                                'domains_id'       => $domainID,
                                'networks_id'      => $networkID,
                                'printertypes_id'  => $typeID,
                                'printermodels_id' => $modelID,
                                'manufacturers_id' => mt_rand(1,$MAX['enterprises']),
                                'is_global'        => 1,
                                'notepad'          => "notes printers '$i",
                                'users_id'         => mt_rand($FIRST['users_sadmin'],
                                                              $LAST['users_admin']),
                                'groups_id'        => mt_rand($FIRST["groups"], $LAST["groups"]),
                                'states_id'        => (mt_rand(0,100)<$percent['state']
                                                         ?mt_rand($FIRST['state'],$LAST['state']):0)
                           )));

      addDocuments('Printer', $printID);
      addContracts('Printer', $printID);

      // Add trackings
      addTracking('Printer', $printID, $ID_entity);

      // AJOUT INFOCOMS
      addInfocoms('Printer', $printID, $ID_entity, $recur);

      // Add Cartouches
      // Get compatible cartridge
      $query = "SELECT `cartridgeitems_id`
                FROM `glpi_cartridgeitems_printermodels`
                WHERE `printermodels_id` = '$typeID'";
      $result2 = $DB->query($query) or die("PB REQUETE ".$query);

      if ($DB->numrows($result2)>0) {
         $ctypeID = $DB->result($result2,0,0) or die (" PB RESULT ".$query);
         $printed = 0;
         $oldnb   = mt_rand(1,$MAX['cartridges_by_printer']);
         $date1   = strtotime(mt_rand(2000,$current_year)."-".mt_rand(1,12)."-".mt_rand(1,28));
         $date2   = time();
         $inter   = abs(round(($date2-$date1)/$oldnb));

         // Add old cartridges
         for ($j=0 ; $j<$oldnb ; $j++) {
            $printed += mt_rand(0,5000);
            $c->add(array('entities_id'        => $ID_entity,
                          'cartridgeitems_id'  => $ctypeID,
                          'printers_id'        => $printID,
                          'date_in'            => date("Y-m-d",$date1),
                          'date_use'           => date("Y-m-d",$date1+$j*$inter),
                          'date_out'           => date("Y-m-d",$date1+($j+1)*$inter),
                          'pages'              => $printed));
         }

         // Add current cartridges
         $c->add(array('entities_id'        => $ID_entity,
                       'cartridgeitems_id'  => $ctypeID,
                       'printers_id'        => $printID,
                       'date_in'            => $date,
                       'date_use'           => date("Y-m-d",$date2)));
      }

      $iface = mt_rand(1,$MAX['iface']);

      // Add networking ports
      addNetworkEthernetPort('Printer', $printID, $ID_entity, $i);
   }
   unset($NET_LOC);
   $LAST["networking"] = getMaxItem("glpi_networkequipments");


   //////////// INVENTORY

   // glpi_computers
   $FIRST["computers"]   = getMaxItem("glpi_computers")+1;
   $FIRST["monitors"]    = getMaxItem("glpi_monitors")+1;
   $FIRST["phones"]      = getMaxItem("glpi_phones")+1;
   $FIRST["peripherals"] = getMaxItem("glpi_peripherals")+1;
   $c       = new Computer();
   $mon     = new Monitor();

   $cdevmb    = new Item_DeviceMotherBoard();
   $cdevproc  = new Item_DeviceProcessor();
   $cdevmem   = new Item_DeviceMemory();
   $cdevhd    = new Item_DeviceHardDrive();
   $cdevnc    = new Item_DeviceNetworkCard();
   $cdevdr    = new Item_DeviceDrive();
   $cdevcon   = new Item_DeviceControl();
   $cdevgc    = new Item_DeviceGraphicCard();
   $cdevsc    = new Item_DeviceSoundCard();
   $cdevpci   = new Item_DevicePci();
   $cdevcase  = new Item_DeviceCase();
   $cdevps    = new Item_DevicePowerSupply();

   $cdisk   = new ComputerDisk();
   $np      = new Netpoint();
   $ci      = new Computer_Item();
   $phone   = new Phone();
   $print   = new Printer();
   $periph  = new Peripheral();
   $cart    = new Cartridge();
   for ($i=0 ; $i<$MAX['computers'] ; $i++) {
      $loc       = mt_rand($FIRST["locations"],$LAST['locations']);
      $techID    = mt_rand($FIRST['users_sadmin'],$LAST['users_admin']);
      $userID    = mt_rand($FIRST['users_normal'],$LAST['users_postonly']);
      $groupID   = mt_rand($FIRST["groups"],$LAST["groups"]);
      $gtechID   = mt_rand($FIRST["techgroups"],$LAST["techgroups"]);
      $domainID  = mt_rand($FIRST['domain'],$LAST['domain']);
      $networkID = mt_rand(1,$MAX['network']);

      $compID = $c->add(toolbox::addslashes_deep(
                        array('entities_id'                    => $ID_entity,
                              'name'                           => "computer ' $i-$ID_entity",
                              'serial'                         => Toolbox::getRandomString(10),
                              'otherserial'                    => Toolbox::getRandomString(10),
                              'contact'                        => "contact' $i",
                              'contact_num'                    => "num' $i",
                              'users_id_tech'                  => $techID,
                              'groups_id_tech'                 => $gtechID,
                              'comment'                        => "comment' $i",
                              'operatingsystems_id'            => mt_rand(1,$MAX['os']),
                              'operatingsystemversions_id'     => mt_rand(1,$MAX['os_version']),
                              'operatingsystemservicepacks_id' => mt_rand(1,$MAX['os_sp']),
                              'os_license_number'              => "os sn $i",
                              'os_licenseid'                   => "os id $i",
                              'autoupdatesystems_id'           => mt_rand(1,$MAX['os_sp']),
                              'locations_id'                   => $loc,
                              'domains_id'                     => $domainID,
                              'networks_id'                    => $networkID,
                              'computertypes_id'               => mt_rand(1,$MAX['type_computers']),
                              'computermodels_id'              => mt_rand(1,$MAX['model']),
                              'manufacturers_id'               => mt_rand(1,$MAX['manufacturer']),
                              'is_global'                      => 1,
                              'notepad'                        => "notes computer '$i",
                              'users_id'                       => $userID,
                              'groups_id'                      => $groupID,
                              'states_id'                      => (mt_rand(0,100)<$percent['state']
                                                                     ?mt_rand($FIRST['state'],$LAST['state']):0),
                              'uuid'                           => Toolbox::getRandomString(30)
                           )));

      addDocuments('Computer', $compID);
      addContracts('Computer', $compID);

      $NET_PORT['Computer'][$compID] = 0;

      // Add trackings
      addTracking('Computer', $compID, $ID_entity);

      // Add reservation
      addReservation('Computer', $compID, $ID_entity);


      // AJOUT INFOCOMS
      addInfocoms('Computer', $compID, $ID_entity);

      // ADD DEVICE
      $cdevmb->addDevices(1, 'Computer', $compID, mt_rand(1,$MAX['device']),
                          array('serial' => Toolbox::getRandomString(15)));

      $max   = mt_rand(1,4);
      $devid = mt_rand(1,$MAX['device']);
      for($nb = 0; $nb<$max; $nb++) {
         $cdevproc->addDevices(1, 'Computer', $compID, $devid,
                               array('serial' => Toolbox::getRandomString(15)));
      }
      $max   = mt_rand(1,4);
      $devid = mt_rand(1,$MAX['device']);
      for($nb = 0; $nb<$max; $nb++) {
         $cdevmem->addDevices(1, 'Computer', $compID, $devid,
                              array('serial' => Toolbox::getRandomString(15)));
      }

      $max = mt_rand(1,2);
      $devid = mt_rand(1,$MAX['device']);
      for($nb = 0; $nb<$max; $nb++) {
         $cdevhd->addDevices(1, 'Computer', $compID, $devid,
                             array('serial' => Toolbox::getRandomString(15)));
      }

      $cdevnc->addDevices(1, 'Computer', $compID, mt_rand(1,$MAX['device']),
                          array('serial' => Toolbox::getRandomString(15),
                                'mac'    => getNextMAC()));

      $cdevdr->addDevices(1, 'Computer', $compID, mt_rand(1,$MAX['device']),
                          array('serial' => Toolbox::getRandomString(15)));

      $cdevcon->addDevices(1, 'Computer', $compID, mt_rand(1,$MAX['device']),
                           array('serial' => Toolbox::getRandomString(15)));

      $cdevgc->addDevices(1, 'Computer', $compID, mt_rand(1,$MAX['device']),
                          array('serial' => Toolbox::getRandomString(15)));

      $cdevsc->addDevices(1, 'Computer', $compID, mt_rand(1,$MAX['device']),
                          array('serial' => Toolbox::getRandomString(15)));

      $max = mt_rand(1,4);
      for($nb = 0; $nb<$max; $nb++) {
         $cdevpci->addDevices(1, 'Computer', $compID, mt_rand(1,$MAX['device']),
                              array('serial' => Toolbox::getRandomString(15)));
      }

      $cdevcase->addDevices(1, 'Computer', $compID, mt_rand(1,$MAX['device']),
                            array('serial'=> Toolbox::getRandomString(15)));

      $max   = mt_rand(1,2);
      $devid = mt_rand(1,$MAX['device']);
      for($nb = 0; $nb<$max; $nb++) {
         $cdevps->addDevices(1, 'Computer', $compID, $devid,
                             array('serial' => Toolbox::getRandomString(15)));
      }

      // insert disk
      $nb_disk = mt_rand(1,$MAX_DISK);
      for ($j=1 ; $j<=$nb_disk ; $j++) {
         $totalsize = mt_rand(10000,1000000);
         $freesize  = mt_rand(0,$totalsize);

         $cdisk->add(toolbox::addslashes_deep(
                      array('entities_id'     => $ID_entity,
                            'computers_id'    => $compID,
                            'name'            => "disk '$j",
                            'device'          => "/dev/disk$j",
                            'mountpoint'      => "/mnt/disk$j",
                            'filesystems_id'  => mt_rand(1,10),
                            'totalsize'       => $totalsize,
                            'freesize'        => $freesize)));
      }


      // Add networking ports
      addNetworkEthernetPort('Computer', $compID, $ID_entity, $loc);

      // Ajout d'un ecran sur l'ordi
      $monID = $mon->add(toolbox::addslashes_deep(
                         array('entities_id'       => $ID_entity,
                               'name'              => "monitor' $i-$ID_entity",
                               'serial'            => Toolbox::getRandomString(10),
                               'otherserial'       => Toolbox::getRandomString(10),
                               'contact'           => "contact' $i",
                               'contact_num'       => "num' $i",
                               'users_id_tech'     => $techID,
                               'groups_id_tech'    => $gtechID,
                               'comment'           => "comment' $i",
                               'size'              => mt_rand(14,22),
                               'have_micro'        => mt_rand(0,1),
                               'have_speaker'      => mt_rand(0,1),
                               'have_subd'         => mt_rand(0,1),
                               'have_bnc'          => mt_rand(0,1),
                               'have_dvi'          => mt_rand(0,1),
                               'have_pivot'        => mt_rand(0,1),
                               'have_hdmi'         => mt_rand(0,1),
                               'have_displayport'  => mt_rand(0,1),
                               'locations_id'      => $loc,
                               'monitortypes_id'   => mt_rand(1,$MAX['type_monitors']),
                               'monitormodels_id'  => mt_rand(1,$MAX['model_monitors']),
                               'manufacturers_id'  => mt_rand(1,$MAX['manufacturer']),
                               'notepad'           => "notes monitor' $i",
                               'users_id'          => $userID,
                               'groups_id'         => $groupID,
                               'states_id'         => (mt_rand(0,100)<$percent['state']
                                                         ?mt_rand($FIRST['state'],$LAST['state']):0)
                           )));

      addDocuments('Monitor', $monID);
      addContracts('Monitor', $monID);

      // Add trackings
      addTracking('Monitor', $monID, $ID_entity);

      // AJOUT INFOCOMS
      addInfocoms('Monitor', $monID, $ID_entity);

      $ci->add(array('itemtype'     => 'Monitor',
                     'items_id'     => $monID,
                     'computers_id' => $compID,
      ));

      // Ajout d'un telephhone avec l'ordi
      $telID = $phone->add(toolbox::addslashes_deep(
                           array('entities_id'           => $ID_entity,
                                 'name'                  => "phone' $i-$ID_entity",
                                 'serial'                => Toolbox::getRandomString(10),
                                 'otherserial'           => Toolbox::getRandomString(10),
                                 'contact'               => "contact' $i",
                                 'contact_num'           => "num' $i",
                                 'users_id_tech'         => $techID,
                                 'groups_id_tech'        => $gtechID,
                                 'comment'               => "comment' $i",
                                 'firmware'              => Toolbox::getRandomString(10),
                                 'brand'                 => "brand' $i",
                                 'phonepowersupplies_id' => mt_rand(0,$MAX['phone_power']),
                                 'number_line'           => Toolbox::getRandomString(10),
                                 'have_headset'          => mt_rand(0,1),
                                 'have_hp'               => mt_rand(0,1),
                                 'locations_id'          => $loc,
                                 'phonetypes_id'         => mt_rand(1,$MAX['type_phones']),
                                 'phonemodels_id'        => mt_rand(1,$MAX['model_phones']),
                                 'manufacturers_id'      => mt_rand(1,$MAX['manufacturer']),
                                 'notepad'               => "notes phone' $i",
                                 'users_id'              => $userID,
                                 'groups_id'             => $groupID,
                                 'states_id'             => (mt_rand(0,100)<$percent['state']
                                                               ?mt_rand($FIRST['state'],$LAST['state']):0)
                           )));

      addDocuments('Phone', $telID);
      addContracts('Phone', $telID);

      // Add trackings
      addTracking('Phone', $telID, $ID_entity);

      // AJOUT INFOCOMS
      addInfocoms('Phone', $telID, $ID_entity);

      $ci->add(array('itemtype'     => 'Phone',
                     'items_id'     => $telID,
                     'computers_id' => $compID));

      // Ajout des periphs externes en connection directe
      while (mt_rand(0,100)<$percent['peripherals']) {

         $periphID = $periph->add(toolbox::addslashes_deep(
                                  array('entities_id'       => $ID_entity,
                                        'name'              => "periph of comp' $i-$ID_entity",
                                        'serial'            => Toolbox::getRandomString(10),
                                        'otherserial'       => Toolbox::getRandomString(10),
                                        'contact'           => "contact' $i",
                                        'contact_num'       => "num' $i",
                                        'users_id_tech'     => $techID,
                                        'groups_id_tech'    => $gtechID,
                                        'comment'           => "comment' $i",
                                        'brand'             => "brand' $i",
                                        'locations_id'      => $loc,
                                        'phonetypes_id'     => mt_rand(1,$MAX['type_peripherals']),
                                        'phonemodels_id'    => mt_rand(1,$MAX['model_peripherals']),
                                        'manufacturers_id'  => mt_rand(1,$MAX['manufacturer']),
                                        'notepad'           => "notes peripheral' $i",
                                        'users_id'          => $userID,
                                        'groups_id'         => $groupID,
                                        'states_id'         => (mt_rand(0,100)<$percent['state']
                                                                  ?mt_rand($FIRST['state'],$LAST['state']):0)
                                    )));

         addDocuments('Peripheral', $periphID);
         addContracts('Peripheral', $periphID);

         // Add trackings
         addTracking('Peripheral', $periphID, $ID_entity);

         // Add connection
         $ci->add(array('itemtype'     => 'Peripheral',
                        'items_id'     => $periphID,
                        'computers_id' => $compID));
      }


      // Ajout d'une imprimante connection directe pour X% des computers + ajout de cartouches
      if (mt_rand(0,100)<=$percent['printer']) {
         // Add printer
         $typeID  = mt_rand(1,$MAX['type_printers']);
         $modelID = mt_rand(1,$MAX['model_printers']);

         $printID = $p->add(toolbox::addslashes_deep(
                            array('entities_id'       => $ID_entity,
                                  'name'              => "printer of comp' $i-$ID_entity",
                                  'serial'            => Toolbox::getRandomString(10),
                                  'otherserial'       => Toolbox::getRandomString(10),
                                  'contact'           => "contact' $i",
                                  'contact_num'       => "num' $i",
                                  'users_id_tech'     => $techID,
                                  'groups_id_tech'    => $gtechID,
                                  'have_serial'       => mt_rand(0,1),
                                  'have_parallel'     => mt_rand(0,1),
                                  'have_usb'          => mt_rand(0,1),
                                  'have_wifi'         => mt_rand(0,1),
                                  'have_ethernet'     => mt_rand(0,1),
                                  'comment'           => "comment' $i",
                                  'memory_size'       => mt_rand(0,128),
                                  'locations_id'      => $loc,
                                  'domains_id'        => $domainID,
                                  'networks_id'       => $networkID,
                                  'printertypes_id'   => $typeID,
                                  'printermodels_id'  => $modelID,
                                  'manufacturers_id'  => mt_rand(1,$MAX['manufacturer']),
                                  'notepad'           => "notes printers '$i",
                                  'users_id'          => mt_rand($FIRST['users_postonly'],
                                                                 $LAST['users_postonly']),
                                  'groups_id'         => mt_rand($FIRST["groups"], $LAST["groups"]),
                                  'states_id'         => (mt_rand(0,100)<$percent['state']
                                                            ?mt_rand($FIRST['state'],$LAST['state']):0)
                              )));

         addDocuments('Printer', $printID);
         addContracts('Printer', $printID);

         // Add trackings
         addTracking('Printer', $printID, $ID_entity);

         // Add connection
         $ci->add(array('itemtype'     => 'Printer',
                        'items_id'     => $printID,
                        'computers_id' => $compID));

         // AJOUT INFOCOMS
         addInfocoms('Printer', $printID, $ID_entity);

         // Add Cartouches
         // Get compatible cartridge
         $query = "SELECT `cartridgeitems_id`
                   FROM `glpi_cartridgeitems_printermodels`
                   WHERE `printermodels_id` = '$typeID'";
         $result = $DB->query($query) or die("PB REQUETE ".$query);

         if ($DB->numrows($result)>0) {
            $ctypeID = $DB->result($result,0,0) or die (" PB RESULT ".$query);
            $printed = 0;
            $oldnb   = mt_rand(1,$MAX['cartridges_by_printer']);
            $date1   = strtotime(mt_rand(2000,$current_year)."-".mt_rand(1,12)."-".mt_rand(1,28));
            $date2   = time();
            $inter   = round(($date2-$date1)/$oldnb);

            // Add old cartridges
            for ($j=0 ; $j<$oldnb ; $j++) {
               $printed += mt_rand(0,5000);
               $cart->add(array('entities_id'        => $ID_entity,
                                'cartridgeitems_id'  => $ctypeID,
                                'printers_id'        => $printID,
                                'date_in'            => date("Y-m-d",$date1),
                                'date_use'           => date("Y-m-d",$date1+$j*$inter),
                                'date_out'           => date("Y-m-d",$date1+($j+1)*$inter),
                                'pages'              => $printed));
            }

            // Add current cartridges
            $cart->add(array('entities_id'        => $ID_entity,
                             'cartridgeitems_id'  => $ctypeID,
                             'printers_id'        => $printID,
                             'date_in'            => date("Y-m-d",$date1),
                             'date_use'           => date("Y-m-d",$date2)));
         }
      }
   }

   $LAST["computers"] = getMaxItem("glpi_computers");
   $LAST["monitors"]  = getMaxItem("glpi_monitors");
   $LAST["phones"]    = getMaxItem("glpi_phones");


   // Add global peripherals
   $periph = new Peripheral();
   $ci     = new Computer_Item();
   for ($i=0 ; $i<$MAX['global_peripherals'] ; $i++) {
      $techID  = mt_rand($FIRST['users_sadmin'],$LAST['users_admin']);
      $gtechID = mt_rand($FIRST["techgroups"],$LAST["techgroups"]);

      $periphID = $periph->add(toolbox::addslashes_deep(
                               array('entities_id'       => $ID_entity,
                                     'name'              => "periph '$i-$ID_entity",
                                     'serial'            => Toolbox::getRandomString(10),
                                     'otherserial'       => Toolbox::getRandomString(10),
                                     'contact'           => "contact' $i",
                                     'contact_num'       => "num' $i",
                                     'users_id_tech'     => $techID,
                                     'groups_id_tech'    => $gtechID,
                                     'comment'           => "comment' $i",
                                     'brand'             => "brand' $i",
                                     'locations_id'      => $loc,
                                     'phonetypes_id'     => mt_rand(1,$MAX['type_peripherals']),
                                     'phonemodels_id'    => mt_rand(1,$MAX['model_peripherals']),
                                     'manufacturers_id'  => mt_rand(1,$MAX['manufacturer']),
                                     'is_global'         => 1,
                                     'notepad'           => "notes peripheral' $i",
                                     'users_id'          => mt_rand($FIRST['users_normal'],
                                                                    $LAST['users_normal']),
                                     'groups_id'         => mt_rand($FIRST["groups"], $LAST["groups"]),
                                     'states_id'         => (mt_rand(0,100)<$percent['state']
                                                               ?mt_rand($FIRST['state'],$LAST['state']):0)
                                 )));

      addDocuments('Peripheral', $periphID);
      addContracts('Peripheral', $periphID);

      // Add trackings
      addTracking('Peripheral', $periphID, $ID_entity);

      // Add reservation
      addReservation('Peripheral', $periphID, $ID_entity);

      // AJOUT INFOCOMS
      addInfocoms('Peripheral', $periphID, $ID_entity);

      // Add connections
      $val = mt_rand(1,$MAX['connect_for_peripherals']);
      for ($j=1 ; $j<$val ; $j++) {
         $ci->add(array('itemtype'     => 'Peripheral',
                        'items_id'     => $periphID,
                        'computers_id' => mt_rand($FIRST["computers"],$LAST['computers'])));
      }
   }

   $LAST["peripherals"] = getMaxItem("glpi_peripherals");

   $FIRST["software"]   = getMaxItem("glpi_softwares")+1;

   // Ajout logiciels + licences associees a divers PCs
   $items = array(array("Open'Office", "1.1.4", "2.0", "2.0.1"),
                  array("Microsoft Office", "95", "97", "XP", "2000", "2003", "2007"),
                  array("Acrobat Reader", "6.0", "7.0", "7.04"),
                  array("Gimp", "2.0", "2.2"),
                  array("InkScape", "0.4"));
   $soft       = new Software();
   $softvers   = new SoftwareVersion();
   $softlic    = new SoftwareLicense();
   $csv        = new Computer_SoftwareVersion();
   $csl        = new Computer_SoftwareLicense();
   for ($i=0 ; $i<$MAX['software'] ; $i++) {

      if (isset($items[$i])) {
         $name = $items[$i][0];
      } else {
         $name = "software '$i";
      }

      $loc       = mt_rand(1,$MAX['locations']);
      $techID    = mt_rand($FIRST['users_sadmin'],$LAST['users_admin']);
      $gtechID   = mt_rand($FIRST["techgroups"],$LAST["techgroups"]);
      $recursive = mt_rand(0,1);

      $softID = $soft->add(toolbox::addslashes_deep(
                           array('entities_id'           => $ID_entity,
                                 'is_recursive'          => $recursive,
                                 'name'                  => $name,
                                 'comment'               => "comment '$i",
                                 'locations_id'          => $loc,
                                 'users_id_tech'         => $techID,
                                 'groups_id_tech'        => $gtechID,
                                 'manufacturers_id'      => mt_rand(1,$MAX['manufacturer']),
                                 'notepad'               => "notes software '$i",
                                 'users_id'              => mt_rand($FIRST['users_admin'],
                                                                    $LAST['users_admin']),
                                 'groups_id'             => mt_rand($FIRST["groups"], $LAST["groups"]),
                                 'is_helpdesk_visible'   => 1,
                                 'softwarecategories_id' => mt_rand(1,$MAX['softwarecategory'])
                              )));

      addDocuments('Software', $softID);
      addContracts('Software', $softID);

      // Add trackings
      addTracking('Software', $softID, $ID_entity);

      // AJOUT INFOCOMS
      addInfocoms('Software', $softID, $ID_entity);

      // Add versions
      $FIRST["version"] = getMaxItem("glpi_softwareversions")+1;

      if (isset($items[$i])) {
         $val2 = count($items[$i]);
      } else {
         $val2 = mt_rand(1,$MAX['softwareversions']+1);
      }

      for ($j=1 ; $j<=$val2 ; $j++) {
         if (isset($items[$i])) {
            $version = $items[$i][mt_rand(1,count($items[$i])-1)];
         } else {
            $version = "$j.0";
         }
         $os = mt_rand(1,$MAX['os']);

         $versID = $softvers->add(toolbox::addslashes_deep(
                                  array('entities_id'          => $ID_entity,
                                        'is_recursive'         => $recursive,
                                        'softwares_id'         => $softID,
                                        'name'                 => $version,
                                        'comment'              => "comment '$version",
                                        'states_id'            => (mt_rand(0,100)<$percent['state']
                                                                     ?mt_rand($FIRST['state'],$LAST['state']):0),
                                        'operatingsystems_id'  => $os)));

         $val3    = min($LAST["computers"]-$FIRST['computers'], mt_rand(1,$MAX['softwareinstall']));
         $comp_id = mt_rand($FIRST["computers"], $LAST['computers']);

         for ($k=0 ; $k<$val3 ; $k++) {
            $comp_id++;
            if ($comp_id>$LAST["computers"]) {
               $comp_id = $FIRST["computers"];
            }
            $csv->add(array('computers_id'        => $comp_id,
                            'softwareversions_id' => $versID));
         }
      }
      $LAST["version"] = getMaxItem("glpi_softwareversions");


      // Add licenses
      $val2 = mt_rand(1,$MAX['softwarelicenses']);

      for ($j=0 ; $j<$val2 ; $j++) {
         $softwareversions_id_buy = mt_rand($FIRST["version"],$LAST["version"]);
         $softwareversions_id_use = mt_rand($softwareversions_id_buy,$LAST["version"]);

         $nbused = min($LAST["computers"]-$FIRST['computers'], mt_rand(1,$MAX['softwareinstall']));

         $licID = $softlic->add(toolbox::addslashes_deep(
                                array('entities_id'               => $ID_entity,
                                      'is_recursive'              => $recursive,
                                      'softwares_id'              => $softID,
                                      'number'                    => $nbused,
                                      'softwarelicensetypes_id'   => mt_rand(1,$MAX['licensetype']),
                                      'name'                      => "license '$j",
                                      'serial'                    => "serial $j",
                                      'otherserial'               => "otherserial $j",
                                      'comment'                   => "comment license '$j",
                                      'softwareversions_id_buy'   => $softwareversions_id_buy,
                                      'softwareversions_id_use'   => $softwareversions_id_use)));

         $comp_id = mt_rand($FIRST["computers"], $LAST['computers']);

         for ($k=0 ; $k<$nbused ; $k++) {
            $comp_id++;
            if ($comp_id>$LAST["computers"]) {
               $comp_id = $FIRST["computers"];
            }
            $csl->add(array('computers_id'          => $comp_id,
                            'softwarelicenses_id'   => $licID));
         }
      }
   }
   $LAST["software"] = getMaxItem("glpi_softwares");
}
Esempio n. 4
0
/**
 * Update from 0.83.1 to 0.84
 *
 * @return bool for success (will die for most error)
**/
function update0831to084()
{
    global $DB, $migration;
    $updateresult = true;
    $ADDTODISPLAYPREF = array();
    //TRANS: %s is the number of new version
    $migration->displayTitle(sprintf(__('Update to %s'), '0.84'));
    $migration->setVersion('0.84');
    // Add the internet field and copy rights from networking
    $migration->addField('glpi_profiles', 'internet', 'char', array('after' => 'networking', 'update' => '`networking`'));
    $backup_tables = false;
    $newtables = array('glpi_contractcosts', 'glpi_entities_rssfeeds', 'glpi_groups_rssfeeds', 'glpi_problems_suppliers', 'glpi_profiles_rssfeeds', 'glpi_rssfeeds_users', 'glpi_rssfeeds', 'glpi_suppliers_tickets', 'glpi_ticketcosts');
    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);
    }
    updateNetworkFramework($ADDTODISPLAYPREF);
    $migration->addField('glpi_mailcollectors', 'accepted', 'string');
    $migration->addField('glpi_mailcollectors', 'refused', 'string');
    $migration->addField('glpi_mailcollectors', 'use_kerberos', 'bool', array('value' => 0));
    $migration->addField("glpi_mailcollectors", 'errors', "integer");
    $migration->addField("glpi_mailcollectors", 'use_mail_date', "bool", array('value' => 0));
    // Password security
    $migration->addField('glpi_configs', 'use_password_security', 'bool');
    $migration->addField('glpi_configs', 'password_min_length', 'integer', array('value' => 8));
    $migration->addField('glpi_configs', 'password_need_number', 'bool', array('value' => 1));
    $migration->addField('glpi_configs', 'password_need_letter', 'bool', array('value' => 1));
    $migration->addField('glpi_configs', 'password_need_caps', 'bool', array('value' => 1));
    $migration->addField('glpi_configs', 'password_need_symbol', 'bool', array('value' => 1));
    $migration->addField('glpi_configs', 'use_check_pref', 'bool');
    // Ajax buffer time
    $migration->addField('glpi_configs', 'ajax_buffertime_load', 'integer', array('value' => 0, 'after' => 'ajax_min_textsearch_load'));
    // Clean display prefs
    $query = "UPDATE `glpi_displaypreferences`\n             SET `num` = 160\n             WHERE `itemtype` = 'Software'\n                   AND `num` = 7";
    $DB->query($query);
    // Update bookmarks from States to AllAssets
    foreach ($DB->request("glpi_bookmarks", "`itemtype` = 'States'") as $data) {
        $query = str_replace('itemtype=States', 'itemtype=AllAssets', $data['query']);
        $query = "UPDATE `glpi_bookmarks`\n                SET query = '" . addslashes($query) . "'\n                WHERE `id` = '" . $data['id'] . "'";
        $DB->query($query);
    }
    $query = "UPDATE `glpi_bookmarks`\n             SET `itemtype` = 'AllAssets', `path` = 'front/allassets.php'\n             WHERE `itemtype` = 'States'";
    $DB->query($query);
    $query = "UPDATE `glpi_displaypreferences`\n             SET `itemtype` = 'AllAssets'\n             WHERE `itemtype` = 'States'";
    $DB->query($query);
    if (TableExists('glpi_networkportmigrations')) {
        $migration->displayWarning("You should have a look at the \"migration cleaner\" tool !", true);
        $migration->displayWarning("With it, you should re-create the networks topologies and the links between the networks and the addresses", true);
    }
    $lang_to_update = array('ca_CA' => 'ca_ES', 'dk_DK' => 'da_DK', 'ee_ET' => 'et_EE', 'el_EL' => 'el_GR', 'he_HE' => 'he_IL', 'no_NB' => 'nb_NO', 'no_NN' => 'nn_NO', 'ua_UA' => 'uk_UA');
    foreach ($lang_to_update as $old => $new) {
        $query = "UPDATE `glpi_configs`\n               SET `language` = '{$new}'\n               WHERE `language` = '{$old}';";
        $DB->queryOrDie($query, "0.84 language in config {$old} to {$new}");
        $query = "UPDATE `glpi_users`\n               SET `language` = '{$new}'\n               WHERE `language` = '{$old}';";
        $DB->queryOrDie($query, "0.84 language in users {$old} to {$new}");
    }
    $migration->displayMessage(sprintf(__('Data migration - %s'), 'tickets and problems status'));
    $status = array('new' => CommonITILObject::INCOMING, 'assign' => CommonITILObject::ASSIGNED, 'plan' => CommonITILObject::PLANNED, 'waiting' => CommonITILObject::WAITING, 'solved' => CommonITILObject::SOLVED, 'closed' => CommonITILObject::CLOSED, 'accepted' => CommonITILObject::ACCEPTED, 'observe' => CommonITILObject::OBSERVED, 'evaluation' => CommonITILObject::EVALUATION, 'approbation' => CommonITILObject::APPROVAL, 'test' => CommonITILObject::TEST, 'qualification' => CommonITILObject::QUALIFICATION);
    foreach (array('glpi_tickets', 'glpi_problems') as $table) {
        // Migrate datas
        foreach ($status as $old => $new) {
            $query = "UPDATE `{$table}`\n                   SET `status` = '{$new}'\n                   WHERE `status` = '{$old}'";
            $DB->queryOrDie($query, "0.84 status in {$table} {$old} to {$new}");
        }
        $migration->changeField($table, 'status', 'status', 'integer', array('value' => CommonITILObject::INCOMING));
    }
    // 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 '%storestatus=%'\n                   OR `glpi_notificationtemplatetranslations`.`content_html` LIKE '%storestatus=%'\n                   OR `glpi_notificationtemplatetranslations`.`subject` LIKE '%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("ticket.storestatus={$old}", "ticket.storestatus={$new}", $subject);
                    $text = str_replace("ticket.storestatus={$old}", "ticket.storestatus={$new}", $text);
                    $html = str_replace("ticket.storestatus={$old}", "ticket.storestatus={$new}", $html);
                    $subject = str_replace("problem.storestatus={$old}", "problem.storestatus={$new}", $subject);
                    $text = str_replace("problem.storestatus={$old}", "problem.storestatus={$new}", $text);
                    $html = str_replace("problem.storestatus={$old}", "problem.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.84 fix tags usage for storestatus");
            }
        }
    }
    // Update Rules
    $changes = array();
    $changes['RuleTicket'] = 'status';
    $DB->query("SET SESSION group_concat_max_len = 4194304;");
    foreach ($changes as $ruletype => $field) {
        // Get rules
        $query = "SELECT GROUP_CONCAT(`id`)\n                FROM `glpi_rules`\n                WHERE `sub_type` = '" . $ruletype . "'\n                GROUP BY `sub_type`";
        if ($result = $DB->query($query)) {
            if ($DB->numrows($result) > 0) {
                // Get rule string
                $rules = $DB->result($result, 0, 0);
                // Update actions
                foreach ($status as $old => $new) {
                    $query = "UPDATE `glpi_ruleactions`\n                         SET `value` = '{$new}'\n                         WHERE `field` = '{$field}'\n                               AND `value` = '{$old}'\n                               AND `rules_id` IN ({$rules})";
                    $DB->queryOrDie($query, "0.84 update datas for rules actions");
                }
            }
        }
    }
    // Update glpi_profiles : ticket_status
    foreach ($DB->request('glpi_profiles') as $data) {
        $fields_to_decode = array('ticket_status', 'problem_status');
        foreach ($fields_to_decode as $field) {
            $tab = importArrayFromDB($data[$field]);
            if (is_array($tab)) {
                $newtab = array();
                foreach ($tab as $key => $values) {
                    foreach ($values as $key2 => $val2) {
                        $newtab[$status[$key]][$status[$key2]] = $val2;
                    }
                }
                $query = "UPDATE `glpi_profiles`\n                       SET `{$field}` = '" . addslashes(exportArrayToDB($newtab)) . "'\n                       WHERE `id` = '" . $data['id'] . "'";
                $DB->queryOrDie($query, "0.84 migrate {$field} of glpi_profiles");
            }
        }
    }
    $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'Merge entity and entitydatas'));
    if (TableExists('glpi_entitydatas')) {
        $migration->changeField('glpi_entities', 'id', 'id', 'integer');
        $migration->migrationOneTable('glpi_entities');
        // pour que la procedure soit re-entrante
        if (countElementsInTable("glpi_entities", "id=0") < 1) {
            // Create root entity
            $query = "INSERT INTO `glpi_entities`\n                          (`id`, `name`, `completename`, `entities_id`, `level`)\n                   VALUES (0,'" . addslashes(__('Root entity')) . "',\n                           '" . addslashes(__('Root entity')) . "', '-1', '1');";
            $DB->queryOrDie($query, '0.84 insert root entity into glpi_entities');
        }
        //       $newID = $DB->insert_id();
        //       $query = "UPDATE `glpi_entities`
        //                 SET `id` = '0'
        //                 WHERE `id` = '$newID'";
        //       $DB->queryOrDie($query, '0.84 be sure that id of the root entity if 0 in glpi_entities');
        $migration->addField("glpi_entities", 'address', "text");
        $migration->addField("glpi_entities", 'postcode', "string");
        $migration->addField("glpi_entities", 'town', "string");
        $migration->addField("glpi_entities", 'state', "string");
        $migration->addField("glpi_entities", 'country', "string");
        $migration->addField("glpi_entities", 'website', "string");
        $migration->addField("glpi_entities", 'phonenumber', "string");
        $migration->addField("glpi_entities", 'fax', "string");
        $migration->addField("glpi_entities", 'email', "string");
        $migration->addField("glpi_entities", 'admin_email', "string");
        $migration->addField("glpi_entities", 'admin_email_name', "string");
        $migration->addField("glpi_entities", 'admin_reply', "string");
        $migration->addField("glpi_entities", 'admin_reply_name', "string");
        $migration->addField("glpi_entities", 'notification_subject_tag', "string");
        $migration->addField("glpi_entities", 'notepad', "longtext");
        $migration->addField("glpi_entities", 'ldap_dn', "string");
        $migration->addField("glpi_entities", 'tag', "string");
        $migration->addField("glpi_entities", 'authldaps_id', "integer");
        $migration->addField("glpi_entities", 'mail_domain', "string");
        $migration->addField("glpi_entities", 'entity_ldapfilter', "text");
        $migration->addField("glpi_entities", 'mailing_signature', "text");
        $migration->addField("glpi_entities", 'cartridges_alert_repeat', "integer", array('value' => -2));
        $migration->addField("glpi_entities", 'consumables_alert_repeat', "integer", array('value' => -2));
        $migration->addField("glpi_entities", 'use_licenses_alert', "integer", array('value' => -2));
        $migration->addField("glpi_entities", 'use_contracts_alert', "integer", array('value' => -2));
        $migration->addField("glpi_entities", 'use_infocoms_alert', "integer", array('value' => -2));
        $migration->addField("glpi_entities", 'use_reservations_alert', "integer", array('value' => -2));
        $migration->addField("glpi_entities", 'autoclose_delay', "integer", array('value' => -2));
        $migration->addField("glpi_entities", 'notclosed_delay', "integer", array('value' => -2));
        $migration->addField("glpi_entities", 'calendars_id', "integer", array('value' => -2));
        $migration->addField("glpi_entities", 'auto_assign_mode', "integer", array('value' => -2));
        $migration->addField("glpi_entities", 'tickettype', "integer", array('value' => -2));
        $migration->addField("glpi_entities", 'max_closedate', "datetime");
        $migration->addField("glpi_entities", 'inquest_config', "integer", array('value' => -2));
        $migration->addField("glpi_entities", 'inquest_rate', "integer");
        $migration->addField("glpi_entities", 'inquest_delay', "integer", array('value' => -10));
        $migration->addField("glpi_entities", 'inquest_URL', "string");
        $migration->addField("glpi_entities", 'autofill_warranty_date', "string", array('value' => -2));
        $migration->addField("glpi_entities", 'autofill_use_date', "string", array('value' => -2));
        $migration->addField("glpi_entities", 'autofill_buy_date', "string", array('value' => -2));
        $migration->addField("glpi_entities", 'autofill_delivery_date', "string", array('value' => -2));
        $migration->addField("glpi_entities", 'autofill_order_date', "string", array('value' => -2));
        $migration->addField("glpi_entities", 'tickettemplates_id', "integer", array('value' => -2));
        $migration->addField("glpi_entities", 'entities_id_software', "integer", array('value' => -2));
        $migration->addField("glpi_entities", 'default_contract_alert', "integer", array('value' => -2));
        $migration->addField("glpi_entities", 'default_infocom_alert', "integer", array('value' => -2));
        $migration->addField("glpi_entities", 'default_alarm_threshold', "integer", array('value' => -2));
        $migration->migrationOneTable('glpi_entities');
        $fields = array('address', 'postcode', 'town', 'state', 'country', 'website', 'phonenumber', 'fax', 'email', 'admin_email', 'admin_email_name', 'admin_reply', 'admin_reply_name', 'notification_subject_tag', 'notepad', 'ldap_dn', 'tag', 'authldaps_id', 'mail_domain', 'entity_ldapfilter', 'mailing_signature', 'cartridges_alert_repeat', 'consumables_alert_repeat', 'use_licenses_alert', 'use_contracts_alert', 'use_infocoms_alert', 'use_reservations_alert', 'autoclose_delay', 'notclosed_delay', 'calendars_id', 'auto_assign_mode', 'tickettype', 'max_closedate', 'inquest_config', 'inquest_rate', 'inquest_delay', 'inquest_URL', 'autofill_warranty_date', 'autofill_use_date', 'autofill_buy_date', 'autofill_delivery_date', 'autofill_order_date', 'tickettemplates_id', 'entities_id_software', 'default_contract_alert', 'default_infocom_alert', 'default_alarm_threshold');
        $entity = new Entity();
        foreach ($DB->request('glpi_entitydatas') as $data) {
            if ($entity->getFromDB($data['entities_id'])) {
                $update_fields = array();
                foreach ($fields as $field) {
                    if (is_null($data[$field])) {
                        $update_fields[] = "`{$field}` = NULL";
                    } else {
                        $update_fields[] = "`{$field}` = '" . addslashes($data[$field]) . "'";
                    }
                }
                $query = "UPDATE `glpi_entities`\n                       SET " . implode(',', $update_fields) . "\n                       WHERE `id` = '" . $data['entities_id'] . "'";
                $DB->queryOrDie($query, "0.84 transfer datas from glpi_entitydatas to glpi_entities");
            } else {
                $migration->displayMessage('Entity ID ' . $data['entities_id'] . ' does not exist');
            }
        }
        $migration->dropTable('glpi_entitydatas');
    }
    regenerateTreeCompleteName("glpi_entities");
    $migration->displayMessage(sprintf(__('Data migration - %s'), 'copy entity information to computers_softwareversions'));
    if ($migration->addField("glpi_computers_softwareversions", "entities_id", "integer")) {
        $migration->migrationOneTable('glpi_computers_softwareversions');
        $query3 = "UPDATE `glpi_computers_softwareversions`\n                 LEFT JOIN `glpi_computers`\n                    ON `computers_id`=`glpi_computers`.`id`\n                 SET `glpi_computers_softwareversions`.`entities_id` = `glpi_computers`.`entities_id`";
        $DB->queryOrDie($query3, "0.84 update entities_id in glpi_computers_softwareversions");
        /// create index for search count on tab
        $migration->addKey("glpi_computers_softwareversions", array('entities_id', 'is_template', 'is_deleted'), 'computers_info');
        $migration->addKey("glpi_computers_softwareversions", 'is_template');
        $migration->addKey("glpi_computers_softwareversions", 'is_deleted');
    }
    /// create new index for search
    $migration->addKey("glpi_softwarelicenses", array('softwares_id', 'expire'), 'softwares_id_expire');
    $migration->dropKey("glpi_softwarelicenses", 'softwares_id');
    $migration->displayMessage(sprintf(__('Data migration - %s'), 'create validation_answer notification'));
    // Check if notifications already exists
    if (countElementsInTable('glpi_notifications', "`itemtype` = 'Ticket'\n                              AND `event` = 'validation_answer'") == 0) {
        // No notifications duplicate all
        $query = "SELECT *\n                FROM `glpi_notifications`\n                WHERE `itemtype` = 'Ticket'\n                      AND `event` = 'validation'";
        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                           'validation_answer', '" . $notif['mode'] . "',\n                           '" . $notif['notificationtemplates_id'] . "',\n                           '" . addslashes($notif['comment']) . "', '" . $notif['is_recursive'] . "',\n                           '" . $notif['is_active'] . "', NOW());";
            $DB->queryOrDie($query, "0.84 insert validation_answer notification");
            $newID = $DB->insert_id();
            $query2 = "SELECT *\n                    FROM `glpi_notificationtargets`\n                    WHERE `notifications_id` = '" . $notif['id'] . "'";
            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.84 insert targets for validation_answer notification");
            }
        }
    }
    $migration->displayMessage(sprintf(__('Data migration - %s'), 'create contracts notification'));
    $from_to = array('end' => 'periodicity', 'notice' => 'periodicitynotice');
    foreach ($from_to as $from => $to) {
        // Check if notifications already exists
        if (countElementsInTable('glpi_notifications', "`itemtype` = 'Contract' AND `event` = '{$to}'") == 0) {
            // No notifications duplicate all
            $query = "SELECT *\n                   FROM `glpi_notifications`\n                   WHERE `itemtype` = 'Contract'\n                         AND `event` = '{$from}'";
            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']) . " Periodicity',\n                              '" . $notif['entities_id'] . "', 'Contract', '{$to}', '" . $notif['mode'] . "',\n                              '" . $notif['notificationtemplates_id'] . "',\n                              '" . addslashes($notif['comment']) . "', '" . $notif['is_recursive'] . "',\n                              '" . $notif['is_active'] . "', NOW());";
                $DB->queryOrDie($query, "0.84 insert contract " . $to . " notification");
                $newID = $DB->insert_id();
                $query2 = "SELECT *\n                       FROM `glpi_notificationtargets`\n                       WHERE `notifications_id` = '" . $notif['id'] . "'";
                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.84 insert targets for ĉontract " . $to . " notification");
                }
            }
        }
    }
    $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'contract and ticket costs'));
    if (!TableExists('glpi_contractcosts')) {
        $query = "CREATE TABLE `glpi_contractcosts` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `contracts_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 `contracts_id` (`contracts_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.84 add table glpi_contractcosts");
        $migration->migrationOneTable('glpi_contractcosts');
        foreach ($DB->request('glpi_contracts', "`cost` > 0") as $data) {
            $begin_to_add = "NULL";
            $end_to_add = "NULL";
            if (!is_null($data['begin_date'])) {
                $begin_to_add = "'" . $data['begin_date'] . "'";
                if ($data['duration']) {
                    $end_to_add = "'" . date("Y-m-d", strtotime($data['begin_date'] . "+" . $data['duration'] . " month")) . "'";
                } else {
                    $end_to_add = "'" . $data['begin_date'] . "'";
                }
            }
            $query = "INSERT INTO `glpi_contractcosts`\n                          (`contracts_id`, `name`, `begin_date`, `end_date`,\n                           `cost`,  `entities_id`,\n                           `is_recursive`)\n                   VALUES ('" . $data['id'] . "', 'Cost', {$begin_to_add}, {$end_to_add},\n                           '" . $data['cost'] . "', '" . $data['entities_id'] . "',\n                           '" . $data['is_recursive'] . "')";
            $DB->queryOrDie($query, '0.84 move contracts costs');
        }
        $migration->dropField('glpi_contracts', 'cost');
    }
    if (!TableExists('glpi_ticketcosts')) {
        $query = "CREATE TABLE `glpi_ticketcosts` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `tickets_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                  `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 `tickets_id` (`tickets_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.84 add table glpi_ticketcosts");
        $migration->migrationOneTable('glpi_ticketcosts');
        foreach ($DB->request('glpi_tickets', "`cost_time` > 0\n                            OR `cost_fixed` > 0\n                            OR `cost_material` > 0") as $data) {
            $begin_to_add = "NULL";
            $end_to_add = "NULL";
            if (!is_null($data['date'])) {
                $begin_to_add = "'" . $data['date'] . "'";
                if (!is_null($data['solvedate'])) {
                    $end_to_add = "'" . $data['solvedate'] . "'";
                } else {
                    $end_to_add = "'" . $data['date'] . "'";
                }
            }
            $query = "INSERT INTO `glpi_ticketcosts`\n                          (`tickets_id`, `name`, `begin_date`, `end_date`,\n                           `cost_time`,`cost_fixed`,\n                           `cost_material`, `entities_id`,\n                           `actiontime`)\n                   VALUES ('" . $data['id'] . "', 'Cost', {$begin_to_add}, {$end_to_add},\n                           '" . $data['cost_time'] . "','" . $data['cost_fixed'] . "',\n                           '" . $data['cost_material'] . "', '" . $data['entities_id'] . "',\n                           '" . $data['actiontime'] . "')";
            $DB->queryOrDie($query, '0.84 move tickets costs');
        }
        $migration->dropField('glpi_tickets', 'cost_time');
        $migration->dropField('glpi_tickets', 'cost_fixed');
        $migration->dropField('glpi_tickets', 'cost_material');
    }
    $migration->addField("glpi_profiles", "ticketcost", "char", array('update' => "'w'", 'condition' => " WHERE `update_ticket` = 1"));
    // Set default to r as before
    $query = "UPDATE `glpi_profiles`\n             SET `ticketcost` = 'r'\n             WHERE `ticketcost` IS NULL";
    $DB->queryOrDie($query, "0.84 set ticketcost in glpi_profiles");
    $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'rss flows'));
    if (!TableExists('glpi_rssfeeds')) {
        $query = "CREATE TABLE `glpi_rssfeeds` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `name` varchar(255) DEFAULT NULL,\n                  `users_id` int(11) NOT NULL DEFAULT '0',\n                  `comment` text COLLATE utf8_unicode_ci,\n                  `url` text COLLATE utf8_unicode_ci,\n                  `refresh_rate` int(11) NOT NULL DEFAULT '86400',\n                  `max_items` int(11) NOT NULL DEFAULT '20',\n                  `have_error` TINYINT( 1 ) NOT NULL DEFAULT 0,\n                  `is_active` TINYINT( 1 ) NOT NULL DEFAULT 0,\n                  `date_mod` DATETIME DEFAULT NULL,\n                  PRIMARY KEY (`id`),\n                  KEY `name` (`name`),\n                  KEY `users_id` (`users_id`),\n                  KEY `date_mod` (`date_mod`),\n                  KEY `have_error` (`have_error`),\n                  KEY `is_active` (`is_active`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.84 add table glpi_rssfeeds");
        $ADDTODISPLAYPREF['RSSFeed'] = array(2, 4, 5, 19, 6, 7);
    }
    if (!TableExists('glpi_rssfeeds_users')) {
        $query = "CREATE TABLE `glpi_rssfeeds_users` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `rssfeeds_id` int(11) NOT NULL DEFAULT '0',\n                  `users_id` int(11) NOT NULL DEFAULT '0',\n                  PRIMARY KEY (`id`),\n                  KEY `rssfeeds_id` (`rssfeeds_id`),\n                  KEY `users_id` (`users_id`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.84 add table glpi_rssfeeds_users");
    }
    if (!TableExists('glpi_groups_rssfeeds')) {
        $query = "CREATE TABLE `glpi_groups_rssfeeds` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `rssfeeds_id` int(11) NOT NULL DEFAULT '0',\n                  `groups_id` int(11) NOT NULL DEFAULT '0',\n                  `entities_id` int(11) NOT NULL DEFAULT '-1',\n                  `is_recursive` TINYINT( 1 ) NOT NULL DEFAULT 0,\n                  PRIMARY KEY (`id`),\n                  KEY `rssfeeds_id` (`rssfeeds_id`),\n                  KEY `groups_id` (`groups_id`),\n                  KEY `entities_id` (`entities_id`),\n                  KEY `is_recursive` (`is_recursive`)\n\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.84 add table glpi_groups_rssfeeds");
    }
    if (!TableExists('glpi_profiles_rssfeeds')) {
        $query = "CREATE TABLE `glpi_profiles_rssfeeds` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `rssfeeds_id` int(11) NOT NULL DEFAULT '0',\n                  `profiles_id` int(11) NOT NULL DEFAULT '0',\n                  `entities_id` int(11) NOT NULL DEFAULT '-1',\n                  `is_recursive` TINYINT( 1 ) NOT NULL DEFAULT 0,\n                  PRIMARY KEY (`id`),\n                  KEY `rssfeeds_id` (`rssfeeds_id`),\n                  KEY `profiles_id` (`profiles_id`),\n                  KEY `entities_id` (`entities_id`),\n                  KEY `is_recursive` (`is_recursive`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.84 add table glpi_profiles_rssfeeds");
    }
    if (!TableExists('glpi_entities_rssfeeds')) {
        $query = "CREATE TABLE `glpi_entities_rssfeeds` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `rssfeeds_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 `rssfeeds_id` (`rssfeeds_id`),\n                  KEY `entities_id` (`entities_id`),\n                  KEY `is_recursive` (`is_recursive`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.84 add table glpi_entities_rssfeeds");
    }
    $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'planning recalls'));
    if (!TableExists('glpi_planningrecalls')) {
        $query = "CREATE TABLE `glpi_planningrecalls` (\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 NOT NULL,\n                  `users_id` int(11) NOT NULL DEFAULT '0',\n                  `before_time` int(11) NOT NULL DEFAULT '-10',\n                  `when` datetime DEFAULT NULL,\n                  PRIMARY KEY (`id`),\n                  KEY `users_id` (`users_id`),\n                  KEY `before_time` (`before_time`),\n                  KEY `when` (`when`),\n                  UNIQUE KEY `unicity` (`itemtype`,`items_id`, `users_id`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.84 add table glpi_planningrecalls");
    }
    $query = "SELECT *\n             FROM `glpi_notificationtemplates`\n             WHERE `itemtype` = 'PlanningRecall'";
    if ($result = $DB->query($query)) {
        if ($DB->numrows($result) == 0) {
            $query = "INSERT INTO `glpi_notificationtemplates`\n                          (`name`, `itemtype`, `date_mod`)\n                   VALUES ('Planning recall', 'PlanningRecall', NOW())";
            $DB->queryOrDie($query, "0.84 add planning recall notification");
            $notid = $DB->insert_id();
            $query = "INSERT INTO `glpi_notificationtemplatetranslations`\n                          (`notificationtemplates_id`, `language`, `subject`,\n                           `content_text`,\n                           `content_html`)\n                   VALUES ({$notid}, '', '##recall.action##: ##recall.item.name##',\n                           '##recall.action##: ##recall.item.name##\n\n##recall.item.content##\n\n##lang.recall.planning.begin##: ##recall.planning.begin##\n##lang.recall.planning.end##: ##recall.planning.end##\n##lang.recall.planning.state##: ##recall.planning.state##\n##lang.recall.item.private##: ##recall.item.private##',\n'&lt;p&gt;##recall.action##: &lt;a href=\"##recall.item.url##\"&gt;##recall.item.name##&lt;/a&gt;&lt;/p&gt;\n&lt;p&gt;##recall.item.content##&lt;/p&gt;\n&lt;p&gt;##lang.recall.planning.begin##: ##recall.planning.begin##&lt;br /&gt;##lang.recall.planning.end##: ##recall.planning.end##&lt;br /&gt;##lang.recall.planning.state##: ##recall.planning.state##&lt;br /&gt;##lang.recall.item.private##: ##recall.item.private##&lt;br /&gt;&lt;br /&gt;&lt;/p&gt;\n&lt;p&gt;&lt;br /&gt;&lt;br /&gt;&lt;/p&gt;')";
            $DB->queryOrDie($query, "0.84 add planning recall 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 ('Planning recall', 0, 'PlanningRecall', 'planningrecall', 'mail',\n                             {$notid}, '', 1, 1, NOW())";
            $DB->queryOrDie($query, "0.84 add planning recall 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::AUTHOR . ");";
            $DB->queryOrDie($query, "0.84 add planning recall notification target");
        }
    }
    if (!countElementsInTable('glpi_crontasks', "`itemtype`='PlanningRecall' AND `name`='planningrecall'")) {
        $query = "INSERT INTO `glpi_crontasks`\n                       (`itemtype`, `name`, `frequency`, `param`, `state`, `mode`, `allowmode`,\n                        `hourmin`, `hourmax`, `logs_lifetime`, `lastrun`, `lastcode`, `comment`)\n                VALUES ('PlanningRecall', 'planningrecall', 300, NULL, 1, 1, 3,\n                        0, 24, 30, NULL, NULL, NULL)";
        $DB->queryOrDie($query, "0.84 populate glpi_crontasks for planningrecall");
    }
    $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'various fields'));
    $migration->changeField('glpi_entities', 'default_alarm_threshold', 'default_cartridges_alarm_threshold', 'integer', array('value' => -2));
    $migration->migrationOneTable('glpi_entities');
    $migration->addField("glpi_entities", 'default_consumables_alarm_threshold', "integer", array('value' => -2, 'update' => 'default_cartridges_alarm_threshold'));
    $migration->migrationOneTable('glpi_entities');
    // move -1 to Entity::CONFIG_NEVER
    $query = 'UPDATE `glpi_entities`
             SET `default_consumables_alarm_threshold` = -10
             WHERE `default_consumables_alarm_threshold` = -1';
    $DB->query($query);
    $query = 'UPDATE `glpi_entities`
             SET `default_cartridges_alarm_threshold` = -10
             WHERE `default_cartridges_alarm_threshold` = -1';
    $DB->query($query);
    $migration->addField("glpi_entities", 'send_contracts_alert_before_delay', "integer", array('value' => -2, 'after' => 'use_contracts_alert', 'update' => '0', 'condition' => 'WHERE `id`=0'));
    $migration->addField("glpi_entities", 'send_infocoms_alert_before_delay', "integer", array('value' => -2, 'after' => 'use_infocoms_alert', 'update' => '0', 'condition' => 'WHERE `id`=0'));
    $migration->addField("glpi_entities", 'send_licenses_alert_before_delay', "integer", array('value' => -2, 'after' => 'use_licenses_alert', 'update' => '0', 'condition' => 'WHERE `id`=0'));
    $migration->addField("glpi_configs", "notification_to_myself", "bool", array('value' => 1));
    $migration->addField("glpi_configs", 'duedateok_color', "string", array('value' => '#06ff00'));
    $migration->addField("glpi_configs", 'duedatewarning_color', "string", array('value' => '#ffb800'));
    $migration->addField("glpi_configs", 'duedatecritical_color', "string", array('value' => '#ff0000'));
    $migration->addField("glpi_configs", 'duedatewarning_less', "integer", array('value' => 20));
    $migration->addField("glpi_configs", 'duedatecritical_less', "integer", array('value' => 5));
    $migration->addField("glpi_configs", 'duedatewarning_unit', "string", array('value' => '%'));
    $migration->addField("glpi_configs", 'duedatecritical_unit', "string", array('value' => '%'));
    $migration->addField("glpi_configs", "realname_ssofield", "string");
    $migration->addField("glpi_configs", "firstname_ssofield", "string");
    $migration->addField("glpi_configs", "email1_ssofield", "string");
    $migration->addField("glpi_configs", "email2_ssofield", "string");
    $migration->addField("glpi_configs", "email3_ssofield", "string");
    $migration->addField("glpi_configs", "email4_ssofield", "string");
    $migration->addField("glpi_configs", "phone_ssofield", "string");
    $migration->addField("glpi_configs", "phone2_ssofield", "string");
    $migration->addField("glpi_configs", "mobile_ssofield", "string");
    $migration->addField("glpi_configs", "comment_ssofield", "string");
    $migration->addField("glpi_configs", "title_ssofield", "string");
    $migration->addField("glpi_configs", "category_ssofield", "string");
    $migration->addField("glpi_configs", "language_ssofield", "string");
    $migration->addField("glpi_configs", "entity_ssofield", "string");
    $migration->addField("glpi_configs", "registration_number_ssofield", "string");
    $migration->addField("glpi_users", "notification_to_myself", "tinyint(1) DEFAULT NULL");
    $migration->addField("glpi_users", 'duedateok_color', "string");
    $migration->addField("glpi_users", 'duedatewarning_color', "string");
    $migration->addField("glpi_users", 'duedatecritical_color', "string");
    $migration->addField("glpi_users", 'duedatewarning_less', "int(11) DEFAULT NULL");
    $migration->addField("glpi_users", 'duedatecritical_less', "int(11) DEFAULT NULL");
    $migration->addField("glpi_users", 'duedatewarning_unit', "string");
    $migration->addField("glpi_users", 'duedatecritical_unit', "string");
    $migration->addField("glpi_users", 'display_options', "text");
    $migration->addField("glpi_reservationitems", "is_deleted", "bool");
    $migration->addKey("glpi_reservationitems", "is_deleted");
    $migration->addField("glpi_documentcategories", 'documentcategories_id', "integer");
    $migration->addField("glpi_documentcategories", 'completename', "text");
    $migration->addField("glpi_documentcategories", 'level', "integer");
    $migration->addField("glpi_documentcategories", 'ancestors_cache', "longtext");
    $migration->addField("glpi_documentcategories", 'sons_cache', "longtext");
    $migration->migrationOneTable('glpi_documentcategories');
    $migration->addKey("glpi_documentcategories", array('documentcategories_id', 'name'), 'unicity');
    regenerateTreeCompleteName("glpi_documentcategories");
    $migration->addField("glpi_contacts", 'usertitles_id', "integer");
    $migration->addKey("glpi_contacts", 'usertitles_id');
    $migration->addField("glpi_contacts", 'address', "text");
    $migration->addField("glpi_contacts", 'postcode', "string");
    $migration->addField("glpi_contacts", 'town', "string");
    $migration->addField("glpi_contacts", 'state', "string");
    $migration->addField("glpi_contacts", 'country', "string");
    $migration->addField("glpi_configs", 'x509_ou_restrict', "string", array('after' => 'x509_email_field'));
    $migration->addField("glpi_configs", 'x509_o_restrict', "string", array('after' => 'x509_email_field'));
    $migration->addField("glpi_configs", 'x509_cn_restrict', "string", array('after' => 'x509_email_field'));
    if (!TableExists('glpi_slalevelcriterias')) {
        $query = "CREATE TABLE `glpi_slalevelcriterias` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `slalevels_id` int(11) NOT NULL DEFAULT '0',\n                  `criteria` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n                  `condition` int(11) NOT NULL DEFAULT '0'\n                              COMMENT 'see define.php PATTERN_* and REGEX_* constant',\n                  `pattern` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n                  PRIMARY KEY (`id`),\n                  KEY `slalevels_id` (`slalevels_id`),\n                  KEY `condition` (`condition`)\n                ) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.84 create glpi_slalevelcriterias");
    }
    $migration->addField("glpi_slalevels", 'match', "CHAR(10) DEFAULT NULL COMMENT 'see define.php *_MATCHING constant'");
    $query = "UPDATE `glpi_slalevelactions`\n             SET `action_type` = 'append'\n             WHERE `action_type` = 'assign'\n                   AND `field` IN ('_users_id_requester',  '_groups_id_requester',\n                                   '_users_id_assign',     '_groups_id_assign',\n                                   '_suppliers_id_assign', '_users_id_observer',\n                                   '_groups_id_observer');";
    $DB->queryOrDie($query, "0.84 update data for SLA actors add");
    // Clean observer as recipient of satisfaction survey
    $query = "DELETE FROM `glpi_notificationtargets`\n             WHERE `glpi_notificationtargets`.`type` = '" . Notification::USER_TYPE . "'\n                   AND `glpi_notificationtargets`.`items_id` = '" . Notification::OBSERVER . "'\n                   AND `notifications_id` IN (SELECT `glpi_notifications`.`id`\n                                              FROM `glpi_notifications`\n                                              WHERE `glpi_notifications`.`itemtype` = 'Ticket'\n                                                    AND `glpi_notifications`.`event` = 'satisfaction')";
    $DB->queryOrDie($query, "0.84 clean targets for satisfaction notification");
    // Clean user as recipient of item not unique
    $query = "DELETE FROM `glpi_notificationtargets`\n             WHERE `glpi_notificationtargets`.`type` = '" . Notification::USER_TYPE . "'\n                   AND `glpi_notificationtargets`.`items_id` = '" . Notification::USER . "'\n                   AND `notifications_id` IN (SELECT `glpi_notifications`.`id`\n                                              FROM `glpi_notifications`\n                                              WHERE `glpi_notifications`.`itemtype` = 'FieldUnicity'\n                                                    AND `glpi_notifications`.`event` = 'refuse')";
    $DB->queryOrDie($query, "0.84 clean targets for fieldunicity notification");
    if (!TableExists('glpi_blacklists')) {
        $query = "CREATE TABLE `glpi_blacklists` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `type` int(11) NOT NULL DEFAULT '0',\n                  `name` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n                  `value` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n                  `comment` text COLLATE utf8_unicode_ci,\n                  PRIMARY KEY (`id`),\n                  KEY `type` (`type`),\n                  KEY `name` (`name`)\n                ) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.84 create glpi_blacklists");
        $ADDTODISPLAYPREF['Blacklist'] = array(12, 11);
        $toinsert = array(Blacklist::IP => array('empty IP' => '', 'localhost' => '127.0.0.1', 'zero IP' => '0.0.0.0'), Blacklist::MAC => array('empty MAC' => ''));
        foreach ($toinsert as $type => $datas) {
            if (count($datas)) {
                foreach ($datas as $name => $value) {
                    $query = "INSERT INTO `glpi_blacklists`\n                                (`type`,`name`,`value`)\n                         VALUES ('{$type}','" . addslashes($name) . "','" . addslashes($value) . "')";
                    $DB->queryOrDie($query, "0.84 insert datas to glpi_blacklists");
                }
            }
        }
    }
    $query = "SELECT `id`\n              FROM `glpi_rulerightparameters`\n              WHERE `name` = '(LDAP) MemberOf'";
    $result = $DB->query($query);
    if (!$DB->numrows($result)) {
        $query = "INSERT INTO `glpi_rulerightparameters`\n                VALUES (NULL, '(LDAP) MemberOf', 'memberof', '')";
        $DB->queryOrDie($query, "0.84 insert (LDAP) MemberOf in glpi_rulerightparameters");
    }
    if (!TableExists('glpi_ssovariables')) {
        $query = "CREATE TABLE `glpi_ssovariables` (\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 NOT NULL,\n                  PRIMARY KEY (`id`)\n                ) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.84 create glpi_ssovariables");
        $query = "INSERT INTO `glpi_ssovariables`\n                       (`id`, `name`, `comment`)\n                VALUES (1, 'HTTP_AUTH_USER', ''),\n                       (2, 'REMOTE_USER', ''),\n                       (3, 'PHP_AUTH_USER', ''),\n                       (4, 'USERNAME', ''),\n                       (5, 'REDIRECT_REMOTE_USER', ''),\n                       (6, 'HTTP_REMOTE_USER', '')";
        $DB->queryOrDie($query, "0.84 add values from  glpi_ssovariables");
    }
    if ($migration->addField('glpi_configs', 'ssovariables_id', 'integer')) {
        $migration->migrationOneTable('glpi_configs');
        //Get configuration
        $query = "SELECT `existing_auth_server_field`\n                FROM `glpi_configs`";
        $result = $DB->query($query);
        $existing_auth_server_field = $DB->result($result, 0, "existing_auth_server_field");
        if ($existing_auth_server_field) {
            //Get dropdown value for existing_auth_server_field
            $query = "SELECT `id`\n                   FROM `glpi_ssovariables`\n                   WHERE `name` = '{$existing_auth_server_field}'";
            $result = $DB->query($query);
            //Update config
            if ($DB->numrows($result) > 0) {
                $query = "UPDATE `glpi_configs`\n                      SET `ssovariables_id` = '" . $DB->result($result, 0, "id") . "'";
                $DB->queryOrDie($query, "0.84 update glpi_configs");
            }
            //Drop old field
        }
    }
    $migration->dropField('glpi_configs', 'existing_auth_server_field');
    //Remove field to specify an ldap server for SSO users : don't need it anymore
    $migration->dropField('glpi_configs', 'authldaps_id_extra');
    // Clean uneeded logs
    $cleancondition = array();
    $cleancondition['reminder_kb'] = "`itemtype` IN ('Entity', 'User', 'Profile', 'Group')\n                                       AND `itemtype_link` IN ('Reminder', 'Knowbase')";
    foreach ($cleancondition as $name => $condition) {
        $query = "DELETE\n                FROM `glpi_logs`\n                WHERE {$condition}";
        $DB->queryOrDie($query, "0.84 clean logs for {$name}");
    }
    //Remove OCS tables from GLPI's core
    $migration->renameTable('glpi_ocsadmininfoslinks', 'ocs_glpi_ocsadmininfoslinks');
    $migration->renameTable('glpi_ocslinks', 'ocs_glpi_ocslinks');
    $migration->renameTable('glpi_ocsservers', 'ocs_glpi_ocsservers');
    $migration->renameTable('glpi_registrykeys', 'ocs_glpi_registrykeys');
    // Migrate RuleOcs to RuleImportEntity
    $query = "UPDATE `glpi_rules`\n             SET `sub_type` = 'RuleImportEntity'\n             WHERE `sub_type` = 'RuleOcs'";
    $DB->queryOrDie($query, "0.84 update datas for old OCS rules");
    $migration->copyTable('glpi_rules', 'ocs_glpi_rules');
    $migration->copyTable('glpi_ruleactions', 'ocs_glpi_ruleactions');
    $migration->copyTable('glpi_rulecriterias', 'ocs_glpi_rulecriterias');
    // Delete OCS rules
    $DB->query("SET SESSION group_concat_max_len = 4194304;");
    $query = "SELECT GROUP_CONCAT(`id`)\n             FROM `glpi_rules`\n             WHERE `sub_type` = 'RuleImportEntity'\n             GROUP BY `sub_type`";
    if ($result = $DB->query($query)) {
        if ($DB->numrows($result) > 0) {
            // Get rule string
            $rules = $DB->result($result, 0, 0);
            $query = "DELETE\n                   FROM `glpi_ruleactions`\n                   WHERE `rules_id` IN ({$rules})";
            $DB->queryOrDie($query, "0.84 clean RuleImportEntity datas");
            $query = "DELETE\n                   FROM `glpi_rulecriterias`\n                   WHERE `rules_id` IN ({$rules})";
            $DB->queryOrDie($query, "0.84 clean RuleImportEntity datas");
            $query = "DELETE\n                   FROM `glpi_rules`\n                   WHERE `id` IN ({$rules})";
            $DB->queryOrDie($query, "0.84 clean RuleImportEntity datas");
        }
    }
    // copy table to keep value of fields deleted after
    $migration->copyTable('glpi_profiles', 'ocs_glpi_profiles');
    $migration->dropField('glpi_profiles', 'ocsng');
    $migration->dropField('glpi_profiles', 'sync_ocsng');
    $migration->dropField('glpi_profiles', 'view_ocsng');
    $migration->dropField('glpi_profiles', 'clean_ocsng');
    $migration->changeField('glpi_profiles', 'rule_ocs', 'rule_import', 'char');
    $migration->changeField('glpi_rulecacheprinters', 'ignore_ocs_import', 'ignore_import', 'char');
    $migration->changeField('glpi_rulecachesoftwares', 'ignore_ocs_import', 'ignore_import', 'char');
    $migration->dropField('glpi_configs', 'use_ocs_mode');
    // clean crontask
    $migration->copyTable('glpi_crontasks', 'ocs_glpi_crontasks');
    $query = "DELETE\n             FROM `glpi_crontasks`\n             WHERE `itemtype` = 'OcsServer'";
    $DB->queryOrDie($query, "0.84 delete OcsServer in crontasks");
    // clean displaypreferences
    $migration->copyTable('glpi_displaypreferences', 'ocs_glpi_displaypreferences');
    $query = "DELETE\n             FROM `glpi_displaypreferences`\n             WHERE `itemtype` = 'OcsServer'";
    $DB->queryOrDie($query, "0.84 delete OcsServer in displaypreferences");
    // Give history entries to plugin
    $query = "UPDATE `glpi_logs`\n             SET `linked_action` = `linked_action`+1000,\n                 `itemtype_link` = 'PluginOcsinventoryngOcslink'\n             WHERE `linked_action` IN (8,9,10,11)";
    $DB->queryOrDie($query, "0.84 update OCS links in history");
    $migration->displayWarning("You can delete ocs_* tables if you use OCS mode ONLY AFTER ocsinventoryng plugin installation.", true);
    $migration->displayWarning("You can delete ocs_* tables if you do not use OCS synchronisation.", true);
    $migration->addField('glpi_authldaps', 'pagesize', 'integer');
    $migration->addField('glpi_authldaps', 'ldap_maxlimit', 'integer');
    $migration->addField('glpi_authldaps', 'can_support_pagesize', 'bool');
    // Add delete ticket notification
    if (countElementsInTable("glpi_notifications", "`itemtype` = 'Ticket' AND `event` = 'delete'") == 0) {
        // Get first template for tickets :
        $notid = 0;
        $query = "SELECT MIN(id) AS id\n                FROM `glpi_notificationtemplates`\n                WHERE `itemtype` = 'Ticket'";
        if ($result = $DB->query($query)) {
            if ($DB->numrows($result) == 1) {
                $notid = $DB->result($result, 0, 0);
            }
        }
        if ($notid > 0) {
            $notifications = array('delete' => array(Notification::GLOBAL_ADMINISTRATOR));
            $notif_names = array('delete' => 'Delete Ticket');
            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, 'Ticket', '{$type}', 'mail',\n                               {$notid}, '', 1, 1, NOW())";
                $DB->queryOrDie($query, "0.83 add problem {$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.83 add problem {$type} notification target");
                }
            }
        }
    }
    // Add multiple suppliers for itil objects
    if (!TableExists('glpi_problems_suppliers')) {
        $query = "CREATE TABLE `glpi_problems_suppliers` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `problems_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` (`problems_id`,`type`,`suppliers_id`),\n                  KEY `group` (`suppliers_id`,`type`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.84 add table glpi_problems_suppliers");
        $migration->migrationOneTable('glpi_problems_suppliers');
        foreach ($DB->request('glpi_problems', "`suppliers_id_assign` > 0") as $data) {
            $query = "INSERT INTO `glpi_problems_suppliers`\n                          (`suppliers_id`, `type`, `problems_id`)\n                   VALUES ('" . $data['suppliers_id_assign'] . "', '" . CommonITILActor::ASSIGN . "',\n                           '" . $data['id'] . "')";
            $DB->query($query);
        }
        $migration->dropField('glpi_problems', 'suppliers_id_assign');
    }
    if (!TableExists('glpi_suppliers_tickets')) {
        $query = "CREATE TABLE `glpi_suppliers_tickets` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `tickets_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` (`tickets_id`,`type`,`suppliers_id`),\n                  KEY `group` (`suppliers_id`,`type`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.84 add table glpi_suppliers_tickets");
        $migration->migrationOneTable('glpi_suppliers_tickets');
        foreach ($DB->request('glpi_tickets', "`suppliers_id_assign` > 0") as $data) {
            $query = "INSERT INTO `glpi_suppliers_tickets`\n                          (`suppliers_id`, `type`, `tickets_id`)\n                   VALUES ('" . $data['suppliers_id_assign'] . "', '" . CommonITILActor::ASSIGN . "',\n                           '" . $data['id'] . "')";
            $DB->query($query);
        }
        $migration->dropField('glpi_tickets', 'suppliers_id_assign');
    }
    $migration->addField('glpi_tickets', 'locations_id', 'integer');
    $migration->addKey('glpi_tickets', 'locations_id');
    $migration->displayMessage(sprintf(__('Data migration - %s'), 'RuleTicket'));
    $changes = array();
    $changes['RuleTicket'] = array('suppliers_id_assign' => '_suppliers_id_assign');
    $changes['RuleDictionnarySoftware'] = array('_ignore_ocs_import' => '_ignore_import');
    $changes['RuleImportEntity'] = array('_ignore_ocs_import' => '_ignore_import');
    $changes['RuleDictionnaryPrinter'] = array('_ignore_ocs_import' => '_ignore_import');
    $DB->query("SET SESSION group_concat_max_len = 4194304;");
    foreach ($changes as $ruletype => $tab) {
        // Get rules
        $query = "SELECT GROUP_CONCAT(`id`)\n                FROM `glpi_rules`\n                WHERE `sub_type` = '" . $ruletype . "'\n                GROUP BY `sub_type`";
        if ($result = $DB->query($query)) {
            if ($DB->numrows($result) > 0) {
                // Get rule string
                $rules = $DB->result($result, 0, 0);
                // Update actions
                foreach ($tab as $old => $new) {
                    $query = "UPDATE `glpi_ruleactions`\n                         SET `field` = '{$new}'\n                         WHERE `field` = '{$old}'\n                               AND `rules_id` IN ({$rules})";
                    $DB->queryOrDie($query, "0.84 update datas for rules actions");
                }
                // Update criterias
                foreach ($tab as $old => $new) {
                    $query = "UPDATE `glpi_rulecriterias`\n                         SET `criteria` = '{$new}'\n                         WHERE `criteria` = '{$old}'\n                               AND `rules_id` IN ({$rules})";
                    $DB->queryOrDie($query, "0.84 update datas for rules criterias");
                }
            }
        }
    }
    // change ruleaction for manufacturer (id to name)
    $query = "SELECT  `glpi_ruleactions` .`id` AS id,\n                     `sub_type`,\n                     `glpi_manufacturers`.`name` AS newvalue\n             FROM `glpi_rules`\n             INNER JOIN `glpi_ruleactions`\n                  ON (`glpi_rules`.`id` = `glpi_ruleactions`.`rules_id`\n                      AND `field` = 'Manufacturer')\n             LEFT JOIN `glpi_manufacturers`\n                  ON `glpi_manufacturers`.`id` = `glpi_ruleactions`.`value`\n             WHERE `sub_type` = 'RuleDictionnarySoftware'";
    if ($result = $DB->query($query)) {
        if ($DB->numrows($result) > 0) {
            while ($data = $DB->fetch_assoc($result)) {
                // Update manufacturer
                $query = "UPDATE `glpi_ruleactions`\n                      SET `value` = '" . $data['newvalue'] . "'\n                      WHERE `id` = " . $data['id'];
                $DB->queryOrDie($query, "0.84 update value of manufacturer for rules actions");
            }
        }
    }
    // Move ticketrecurrent values to correct ones
    $migration->changeField('glpi_ticketrecurrents', 'periodicity', 'periodicity', 'string');
    $migration->addField('glpi_ticketrecurrents', 'calendars_id', 'integer');
    $migration->addField('glpi_ticketrecurrents', 'end_date', 'datetime');
    $migration->migrationOneTable('glpi_ticketrecurrents');
    foreach ($DB->request('glpi_ticketrecurrents', "`periodicity` >= " . MONTH_TIMESTAMP) as $data) {
        $periodicity = $data['periodicity'];
        if (is_numeric($periodicity)) {
            if ($periodicity >= 365 * DAY_TIMESTAMP) {
                $periodicity = round($periodicity / (365 * DAY_TIMESTAMP)) . 'YEAR';
            } else {
                $periodicity = round($periodicity / MONTH_TIMESTAMP) . 'MONTH';
            }
            $query = "UPDATE `glpi_ticketrecurrents`\n                   SET `periodicity` = '{$periodicity}'\n                   WHERE `id` = '" . $data['id'] . "'";
            $DB->query($query);
        }
    }
    $query = "UPDATE `glpi_notifications`\n             SET   `itemtype` = 'CartridgeItem'\n             WHERE `itemtype` = 'Cartridge'";
    $DB->queryOrDie($query, "0.83 update glpi_notifications for Cartridge");
    $query = "UPDATE `glpi_notificationtemplates`\n             SET   `itemtype` = 'CartridgeItem'\n             WHERE `itemtype` = 'Cartridge'";
    $DB->queryOrDie($query, "0.83 update glpi_notificationtemplates for Cartridge");
    $query = "UPDATE `glpi_notifications`\n             SET   `itemtype` = 'ConsumableItem'\n             WHERE `itemtype` = 'Consumable'";
    $DB->queryOrDie($query, "0.83 update glpi_notifications for Consumable");
    $query = "UPDATE `glpi_notificationtemplates`\n             SET   `itemtype` = 'ConsumableItem'\n             WHERE `itemtype` = 'Consumable'";
    $DB->queryOrDie($query, "0.83 update glpi_notificationtemplates for Consumable");
    $migration->createRule(array('sub_type' => 'RuleTicket', 'entities_id' => 0, 'is_recursive' => 1, 'is_active' => 0, 'match' => 'AND', 'name' => 'Ticket location from item'), array(array('criteria' => 'locations_id', 'condition' => Rule::PATTERN_DOES_NOT_EXISTS, 'pattern' => 1), array('criteria' => 'items_locations', 'condition' => Rule::PATTERN_EXISTS, 'pattern' => 1)), array(array('field' => 'locations_id', 'action_type' => 'fromitem', 'value' => 1)));
    $migration->createRule(array('sub_type' => 'RuleTicket', 'entities_id' => 0, 'is_recursive' => 1, 'is_active' => 0, 'match' => 'AND', 'name' => 'Ticket location from user'), array(array('criteria' => 'locations_id', 'condition' => Rule::PATTERN_DOES_NOT_EXISTS, 'pattern' => 1), array('criteria' => 'users_locations', 'condition' => Rule::PATTERN_EXISTS, 'pattern' => 1)), array(array('field' => 'locations_id', 'action_type' => 'fromuser', 'value' => 1)));
    // Change begin_date id for budget
    $query = "UPDATE `glpi_displaypreferences`\n              SET `num` = '5'\n              WHERE `itemtype` = 'Budget'\n                    AND `num` = '2'";
    $DB->query($query);
    migrateComputerDevice('DeviceProcessor', 'frequency', 'integer', array('serial' => 'string'));
    migrateComputerDevice('DeviceMemory', 'size', 'integer', array('serial' => 'string'));
    migrateComputerDevice('DeviceHardDrive', 'capacity', 'integer', array('serial' => 'string'));
    migrateComputerDevice('DeviceGraphicCard', 'memory', 'integer');
    migrateComputerDevice('DeviceNetworkCard', 'mac', 'string');
    migrateComputerDevice('DeviceSoundCard');
    migrateComputerDevice('DeviceMotherBoard');
    migrateComputerDevice('DeviceDrive');
    migrateComputerDevice('DeviceControl');
    migrateComputerDevice('DevicePci');
    migrateComputerDevice('DeviceCase');
    migrateComputerDevice('DevicePowerSupply');
    $migration->migrationOneTable('glpi_computers_softwareversions');
    //Rename fields in glpi_computers_softwareversions with inaproprious signification
    $migration->changeField('glpi_computers_softwareversions', 'is_deleted', 'is_deleted_computer', 'bool');
    $migration->changeField('glpi_computers_softwareversions', 'is_template', 'is_template_computer', 'bool');
    $migration->migrationOneTable('glpi_computers_softwareversions');
    $types = array('glpi_computers_items', 'glpi_computervirtualmachines', 'glpi_computers_softwareversions', 'glpi_computerdisks', 'glpi_networkports', 'glpi_computers_softwarelicenses', 'glpi_networknames', 'glpi_ipaddresses');
    foreach (Item_Devices::getDeviceTypes() as $id => $type) {
        $types[] = getTableForItemType($type);
    }
    //Add is_deleted for relations
    foreach ($types as $table) {
        if ($migration->addField($table, 'is_deleted', 'bool', array('value' => 0))) {
            $migration->migrationOneTable($table);
            $migration->addKey($table, 'is_deleted');
        }
    }
    ///For computers, rename is is_ocs_import to is_dynamic
    $migration->changeField('glpi_computers', 'is_ocs_import', 'is_dynamic', 'bool');
    $migration->migrationOneTable('glpi_computers');
    $migration->dropKey("glpi_computers", 'is_ocs_import');
    $migration->addKey("glpi_computers", 'is_dynamic');
    //Add field is_dynamic
    $types = array_merge($types, array('glpi_printers', 'glpi_phones', 'glpi_peripherals', 'glpi_networkequipments', 'glpi_networkports', 'glpi_monitors', 'glpi_networknames', 'glpi_ipaddresses'));
    foreach ($types as $table) {
        if ($migration->addField($table, 'is_dynamic', 'bool')) {
            $migration->migrationOneTable($table);
            $migration->addKey($table, 'is_dynamic');
        }
    }
    $ADDTODISPLAYPREF['ReservationItem'] = array(5);
    // split validation rights in both
    $migration->changeField('glpi_profiles', 'validate_ticket', 'validate_request', 'char');
    $migration->changeField('glpi_profiles', 'create_validation', 'create_request_validation', 'char');
    $migration->migrationOneTable('glpi_profiles');
    $migration->addField('glpi_profiles', 'validate_incident', 'char', array('update' => 'validate_request'));
    $migration->addField('glpi_profiles', 'create_incident_validation', 'char', array('update' => 'create_request_validation'));
    // add rights to delete all validation
    $migration->addField('glpi_profiles', 'delete_validations', 'char', array('update' => 'delete_ticket'));
    // add rights to manage public rssfeed
    $migration->addField('glpi_profiles', 'rssfeed_public', 'char', array('update' => 'reminder_public', 'after' => 'reminder_public'));
    // add ticket templates
    $migration->addField('glpi_profiles', 'tickettemplates_id', 'integer');
    // Drop not needed fields
    $migration->dropField('glpi_tickettemplatepredefinedfields', 'entities_id');
    $migration->dropField('glpi_tickettemplatepredefinedfields', 'is_recursive');
    $migration->dropField('glpi_tickettemplatemandatoryfields', 'entities_id');
    $migration->dropField('glpi_tickettemplatemandatoryfields', 'is_recursive');
    $migration->dropField('glpi_tickettemplatehiddenfields', 'entities_id');
    $migration->dropField('glpi_tickettemplatehiddenfields', 'is_recursive');
    // Clean unlinked calendar segments and holidays
    $query = "DELETE\n             FROM `glpi_calendars_holidays`\n             WHERE `glpi_calendars_holidays`.`calendars_id`\n                     NOT IN (SELECT `glpi_calendars`.`id`\n                             FROM `glpi_calendars`)";
    $DB->queryOrDie($query, "0.84 clean glpi_calendars_holidays");
    $query = "DELETE\n             FROM `glpi_calendarsegments`\n             WHERE `glpi_calendarsegments`.`calendars_id`\n                     NOT IN (SELECT `glpi_calendars`.`id`\n                             FROM `glpi_calendars`)";
    $DB->queryOrDie($query, "0.84 clean glpi_calendarsegments");
    // Add keys for serial, otherserial and uuid
    $newindexes = array('serial' => array('glpi_computers', 'glpi_items_deviceharddrives', 'glpi_items_devicememories', 'glpi_items_deviceprocessors', 'glpi_monitors', 'glpi_networkequipments', 'glpi_peripherals', 'glpi_phones', 'glpi_printers'), 'otherserial' => array('glpi_computers', 'glpi_monitors', 'glpi_networkequipments', 'glpi_peripherals', 'glpi_phones', 'glpi_printers'), 'uuid' => array('glpi_computers', 'glpi_computervirtualmachines'));
    foreach ($newindexes as $field => $tables) {
        foreach ($tables as $table) {
            $migration->addKey($table, $field);
        }
    }
    // Clean unlinked ticket_problem
    $query = "DELETE\n             FROM `glpi_problems_tickets`\n             WHERE `glpi_problems_tickets`.`tickets_id`\n                     NOT IN (SELECT `glpi_tickets`.`id`\n                             FROM `glpi_tickets`)";
    $DB->queryOrDie($query, "0.84 clean glpi_problems_tickets");
    $query = "DELETE\n             FROM `glpi_problems_tickets`\n             WHERE `glpi_problems_tickets`.`problems_id`\n                     NOT IN (SELECT `glpi_problems`.`id`\n                             FROM `glpi_problems`)";
    $DB->queryOrDie($query, "0.84 clean glpi_problems_tickets");
    // Clean unlinked softwarelicense_computer
    $query = "DELETE\n             FROM `glpi_computers_softwarelicenses`\n             WHERE `glpi_computers_softwarelicenses`.`softwarelicenses_id`\n                     NOT IN (SELECT `glpi_softwarelicenses`.`id`\n                             FROM `glpi_softwarelicenses`)";
    $DB->queryOrDie($query, "0.84 clean glpi_computers_softwarelicenses");
    $query = "DELETE\n             FROM `glpi_computers_softwarelicenses`\n             WHERE `glpi_computers_softwarelicenses`.`computers_id`\n                     NOT IN (SELECT `glpi_computers`.`id`\n                             FROM `glpi_computers`)";
    $DB->queryOrDie($query, "0.84 clean glpi_computers_softwarelicenses");
    // Clean unlinked items_problems
    $query = "DELETE\n             FROM `glpi_items_problems`\n             WHERE `glpi_items_problems`.`problems_id`\n                     NOT IN (SELECT `glpi_problems`.`id`\n                             FROM `glpi_problems`)";
    $DB->queryOrDie($query, "0.84 clean glpi_items_problems");
    $toclean = array('Computer', 'Monitor', 'NetworkEquipment', 'Peripheral', 'Phone', 'Printer', 'Software');
    foreach ($toclean as $type) {
        $query = "DELETE\n               FROM `glpi_items_problems`\n               WHERE `glpi_items_problems`.`itemtype` = '{$type}'\n                     AND `glpi_items_problems`.`items_id`\n                        NOT IN (SELECT `" . getTableForItemType($type) . "`.`id`\n                              FROM `" . getTableForItemType($type) . "`)";
        $DB->queryOrDie($query, "0.84 clean glpi_items_problems");
    }
    // ************ 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);
                }
            }
        }
    }
    // must always be at the end
    $migration->executeMigration();
    return $updateresult;
}
Esempio n. 5
0
/**
 * Update from 0.80.3 to 0.83
 *
 * @return bool for success (will die for most error)
**/
function update0803to083()
{
    global $DB, $migration;
    $updateresult = true;
    $ADDTODISPLAYPREF = array();
    //TRANS: %s is the number of new version
    $migration->displayTitle(sprintf(__('Update to %s'), '0.83'));
    $migration->setVersion('0.83');
    $backup_tables = false;
    $newtables = array('glpi_entities_knowbaseitems', 'glpi_entities_reminders', 'glpi_groups_problems', 'glpi_groups_knowbaseitems', 'glpi_groups_reminders', 'glpi_knowbaseitems_profiles', 'glpi_knowbaseitems_users', 'glpi_items_problems', 'glpi_problems', 'glpi_problemtasks', 'glpi_problems_ticket', 'glpi_problems_users', 'glpi_profiles_reminders', 'glpi_reminders_users', 'glpi_ticketrecurrents', 'glpi_tickettemplates', 'glpi_tickettemplatehiddenfields', 'glpi_tickettemplatemandatoryfields', 'glpi_tickettemplatepredefinedfields', 'glpi_useremails');
    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);
    }
    //TRANS: %s is the table or item implied
    $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'Problems'));
    // Clean ticket validations : already done in 0.80
    $query = "DELETE\n             FROM `glpi_ticketvalidations`\n             WHERE `glpi_ticketvalidations`.`tickets_id` NOT IN (SELECT `glpi_tickets`.`id`\n                                                                 FROM `glpi_tickets`)";
    $DB->queryOrDie($query, "0.83 clean glpi_ticketvalidations");
    // Problems management
    if (!TableExists('glpi_problems')) {
        $query = "CREATE TABLE `glpi_problems` (\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` varchar(255) DEFAULT NULL,\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                  `suppliers_id_assign` 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                  `causecontent` longtext DEFAULT NULL,\n                  `symptomcontent` longtext DEFAULT NULL,\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`(1)),\n                  KEY `priority` (`priority`),\n                  KEY `date_mod` (`date_mod`),\n                  KEY `suppliers_id_assign` (`suppliers_id_assign`),\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 `users_id_lastupdater` (`users_id_lastupdater`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.83 create glpi_problems");
        $ADDTODISPLAYPREF['Problem'] = array(21, 12, 19, 15, 3, 7, 18);
    }
    if (FieldExists('glpi_tickets', 'ticket_waiting_duration', false)) {
        $migration->changeField('glpi_tickets', 'ticket_waiting_duration', 'waiting_duration', 'integer');
    }
    if (!TableExists('glpi_problems_users')) {
        $query = "CREATE TABLE `glpi_problems_users` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `problems_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` (`problems_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.83 add table glpi_problems_users");
    }
    if (!TableExists('glpi_groups_problems')) {
        $query = "CREATE TABLE `glpi_groups_problems` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `problems_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` (`problems_id`,`type`,`groups_id`),\n                  KEY `group` (`groups_id`,`type`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.83 add table glpi_groups_problems");
    }
    if (!TableExists('glpi_items_problems')) {
        $query = "CREATE TABLE `glpi_items_problems` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `problems_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` (`problems_id`,`itemtype`,`items_id`),\n                  KEY `item` (`itemtype`,`items_id`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.83 add table glpi_items_problems");
    }
    if (!TableExists('glpi_problems_tickets')) {
        $query = "CREATE TABLE `glpi_problems_tickets` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `problems_id` int(11) NOT NULL DEFAULT '0',\n                  `tickets_id` int(11) NOT NULL DEFAULT '0',\n                  PRIMARY KEY (`id`),\n                  UNIQUE KEY `unicity` (`problems_id`,`tickets_id`),\n                  KEY `tickets_id` (`tickets_id`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.83 add table glpi_problems_tickets");
    }
    if (!TableExists('glpi_problemtasks')) {
        $query = "CREATE TABLE `glpi_problemtasks` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `problems_id` int(11) NOT NULL DEFAULT '0',\n                  `taskcategories_id` 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                  `state` int(11) NOT NULL DEFAULT '0',\n                  PRIMARY KEY (`id`),\n                  KEY `problems_id` (`problems_id`),\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 `state` (`state`),\n                  KEY `taskcategories_id` (taskcategories_id)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.83 add table glpi_problemtasks");
    }
    $migration->addField("glpi_profiles", "show_my_problem", "char", array('update' => "1", 'condition' => " WHERE `own_ticket` = 1"));
    $migration->addField("glpi_profiles", "show_all_problem", "char", array('update' => "1", 'condition' => " WHERE `show_all_ticket` = 1"));
    $migration->addField("glpi_profiles", "edit_all_problem", "char", array('update' => "1", 'condition' => " WHERE `update_ticket` = 1"));
    $migration->changeField("glpi_profiles", 'helpdesk_status', 'ticket_status', "text", array('comment' => "json encoded array of from/dest allowed status change"));
    $migration->addField('glpi_profiles', 'problem_status', "text", array('comment' => "json encoded array of from/dest allowed status change"));
    $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'Changes'));
    $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'TicketPlanning'));
    // Merge tickettasks and ticket planning
    if (TableExists('glpi_ticketplannings')) {
        $migration->addField("glpi_tickettasks", "begin", "datetime");
        $migration->addField("glpi_tickettasks", "end", "datetime");
        $migration->addField("glpi_tickettasks", "state", "integer", array('value' => '1'));
        $migration->addField("glpi_tickettasks", "users_id_tech", "integer");
        $migration->migrationOneTable('glpi_tickettasks');
        // migrate DATA
        $task = new TicketTask();
        foreach ($DB->request('glpi_ticketplannings') as $data) {
            if ($task->getFromDB($data['tickettasks_id'])) {
                $query = "UPDATE `glpi_tickettasks`\n                      SET `begin` = " . ($data['begin'] == 'NULL' || is_null($data['begin']) ? 'NULL' : "'" . $data['begin'] . "'") . ",\n                          `end` = " . ($data['end'] == 'NULL' || is_null($data['end']) ? 'NULL' : "'" . $data['end'] . "'") . ",\n                          `users_id_tech` = '" . $data['users_id'] . "',\n                          `state` = '" . $data['state'] . "'\n                      WHERE `id` = '" . $data['tickettasks_id'] . "'";
                $DB->queryOrDie($query, "0.83 migrate planning to glpi_tickettasks");
            }
        }
        $migration->dropTable("glpi_ticketplannings");
        $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'Notification'));
        // Migrate templates
        $from = array('task.planning.user##', 'task.planning.begin##', 'task.planning.end##', 'task.planning.status##');
        $to = array('task.user##', 'task.begin##', 'task.end##', 'task.status##');
        $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_notificationtemplates`.`itemtype` = 'Ticket'";
        if ($result = $DB->query($query)) {
            if ($DB->numrows($result)) {
                while ($data = $DB->fetch_assoc($result)) {
                    $query = "UPDATE `glpi_notificationtemplatetranslations`\n                         SET `subject` = '" . addslashes(str_replace($from, $to, $data['subject'])) . "',\n                             `content_text` = '" . addslashes(str_replace($from, $to, $data['content_text'])) . "',\n                             `content_html` = '" . addslashes(str_replace($from, $to, $data['content_html'])) . "'\n                         WHERE `id` = " . $data['id'] . "";
                    $DB->queryOrDie($query, "0.83 fix tags usage for multi users");
                }
            }
        }
    }
    $query = "SELECT *\n             FROM `glpi_notificationtemplates`\n             WHERE `name` = 'Problems'";
    if ($result = $DB->query($query)) {
        if ($DB->numrows($result) == 0) {
            $query = "INSERT INTO `glpi_notificationtemplates`\n                          (`name`, `itemtype`, `date_mod`)\n                   VALUES ('Problems', 'Problem', NOW())";
            $DB->queryOrDie($query, "0.83 add problem notification");
            $notid = $DB->insert_id();
            $query = "INSERT INTO `glpi_notificationtemplatetranslations`\n                          (`notificationtemplates_id`, `language`, `subject`,\n                           `content_text`,\n                           `content_html`)\n                   VALUES ({$notid}, '', '##problem.action## ##problem.title##',\n                          '##IFproblem.storestatus=solved##\n ##lang.problem.url## : ##problem.urlapprove##\n ##lang.problem.solvedate## : ##problem.solvedate##\n ##lang.problem.solution.type## : ##problem.solution.type##\n ##lang.problem.solution.description## : ##problem.solution.description## ##ENDIFproblem.storestatus##\n ##ELSEproblem.storestatus## ##lang.problem.url## : ##problem.url## ##ENDELSEproblem.storestatus##\n\n ##lang.problem.description##\n\n ##lang.problem.title## &#160;:##problem.title##\n ##lang.problem.authors## &#160;:##IFproblem.authors## ##problem.authors## ##ENDIFproblem.authors## ##ELSEproblem.authors##--##ENDELSEproblem.authors##\n ##lang.problem.creationdate## &#160;:##problem.creationdate##\n ##IFproblem.assigntousers## ##lang.problem.assigntousers## &#160;: ##problem.assigntousers## ##ENDIFproblem.assigntousers##\n ##lang.problem.status## &#160;: ##problem.status##\n ##IFproblem.assigntogroups## ##lang.problem.assigntogroups## &#160;: ##problem.assigntogroups## ##ENDIFproblem.assigntogroups##\n ##lang.problem.urgency## &#160;: ##problem.urgency##\n ##lang.problem.impact## &#160;: ##problem.impact##\n ##lang.problem.priority## : ##problem.priority##\n##IFproblem.category## ##lang.problem.category## &#160;:##problem.category## ##ENDIFproblem.category## ##ELSEproblem.category## ##lang.problem.nocategoryassigned## ##ENDELSEproblem.category##\n ##lang.problem.content## &#160;: ##problem.content##\n\n##IFproblem.storestatus=closed##\n ##lang.problem.solvedate## : ##problem.solvedate##\n ##lang.problem.solution.type## : ##problem.solution.type##\n ##lang.problem.solution.description## : ##problem.solution.description##\n##ENDIFproblem.storestatus##\n ##lang.problem.numberoftickets##&#160;: ##problem.numberoftickets##\n\n##FOREACHtickets##\n [##ticket.date##] ##lang.problem.title## : ##ticket.title##\n ##lang.problem.content## ##ticket.content##\n\n##ENDFOREACHtickets##\n ##lang.problem.numberoftasks##&#160;: ##problem.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;##IFproblem.storestatus=solved##&lt;/p&gt;\n&lt;div&gt;##lang.problem.url## : &lt;a href=\"##problem.urlapprove##\"&gt;##problem.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.problem.solvedate##&lt;/span&gt;&lt;/strong&gt;&lt;/span&gt; : ##problem.solvedate##&lt;br /&gt;&lt;span style=\"text-decoration: underline; color: #888888;\"&gt;&lt;strong&gt;##lang.problem.solution.type##&lt;/strong&gt;&lt;/span&gt; : ##problem.solution.type##&lt;br /&gt;&lt;span style=\"text-decoration: underline; color: #888888;\"&gt;&lt;strong&gt;##lang.problem.solution.description##&lt;/strong&gt;&lt;/span&gt; : ##problem.solution.description## ##ENDIFproblem.storestatus##&lt;/div&gt;\n&lt;div&gt;##ELSEproblem.storestatus## ##lang.problem.url## : &lt;a href=\"##problem.url##\"&gt;##problem.url##&lt;/a&gt; ##ENDELSEproblem.storestatus##&lt;/div&gt;\n&lt;p class=\"description b\"&gt;&lt;strong&gt;##lang.problem.description##&lt;/strong&gt;&lt;/p&gt;\n&lt;p&gt;&lt;span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"&gt; ##lang.problem.title##&lt;/span&gt;&#160;:##problem.title## &lt;br /&gt; &lt;span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"&gt; ##lang.problem.authors##&lt;/span&gt;&#160;:##IFproblem.authors## ##problem.authors## ##ENDIFproblem.authors##    ##ELSEproblem.authors##--##ENDELSEproblem.authors## &lt;br /&gt; &lt;span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"&gt; ##lang.problem.creationdate##&lt;/span&gt;&#160;:##problem.creationdate## &lt;br /&gt; ##IFproblem.assigntousers## &lt;span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"&gt; ##lang.problem.assigntousers##&lt;/span&gt;&#160;: ##problem.assigntousers## ##ENDIFproblem.assigntousers##&lt;br /&gt; &lt;span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"&gt;##lang.problem.status## &lt;/span&gt;&#160;: ##problem.status##&lt;br /&gt; ##IFproblem.assigntogroups## &lt;span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"&gt; ##lang.problem.assigntogroups##&lt;/span&gt;&#160;: ##problem.assigntogroups## ##ENDIFproblem.assigntogroups##&lt;br /&gt; &lt;span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"&gt; ##lang.problem.urgency##&lt;/span&gt;&#160;: ##problem.urgency##&lt;br /&gt; &lt;span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"&gt; ##lang.problem.impact##&lt;/span&gt;&#160;: ##problem.impact##&lt;br /&gt; &lt;span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"&gt; ##lang.problem.priority##&lt;/span&gt; : ##problem.priority## &lt;br /&gt;##IFproblem.category##&lt;span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"&gt;##lang.problem.category## &lt;/span&gt;&#160;:##problem.category##  ##ENDIFproblem.category## ##ELSEproblem.category##  ##lang.problem.nocategoryassigned## ##ENDELSEproblem.category##    &lt;br /&gt; &lt;span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"&gt; ##lang.problem.content##&lt;/span&gt;&#160;: ##problem.content##&lt;/p&gt;\n&lt;p&gt;##IFproblem.storestatus=closed##&lt;br /&gt;&lt;span style=\"text-decoration: underline;\"&gt;&lt;strong&gt;&lt;span style=\"color: #888888;\"&gt;##lang.problem.solvedate##&lt;/span&gt;&lt;/strong&gt;&lt;/span&gt; : ##problem.solvedate##&lt;br /&gt;&lt;span style=\"color: #888888;\"&gt;&lt;strong&gt;&lt;span style=\"text-decoration: underline;\"&gt;##lang.problem.solution.type##&lt;/span&gt;&lt;/strong&gt;&lt;/span&gt; : ##problem.solution.type##&lt;br /&gt;&lt;span style=\"text-decoration: underline; color: #888888;\"&gt;&lt;strong&gt;##lang.problem.solution.description##&lt;/strong&gt;&lt;/span&gt; : ##problem.solution.description##&lt;br /&gt;##ENDIFproblem.storestatus##&lt;/p&gt;\n&lt;div class=\"description b\"&gt;##lang.problem.numberoftickets##&#160;: ##problem.numberoftickets##&lt;/div&gt;\n&lt;p&gt;##FOREACHtickets##&lt;/p&gt;\n&lt;div&gt;&lt;strong&gt; [##ticket.date##] &lt;em&gt;##lang.problem.title## : &lt;a href=\"##ticket.url##\"&gt;##ticket.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.problem.content## &lt;/span&gt; ##ticket.content##\n&lt;p&gt;##ENDFOREACHtickets##&lt;/p&gt;\n&lt;div class=\"description b\"&gt;##lang.problem.numberoftasks##&#160;: ##problem.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.83 add problem 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 Problem', 'update' => 'Update Problem', 'solved' => 'Resolve Problem', 'add_task' => 'Add Task', 'update_task' => 'Update Task', 'delete_task' => 'Delete Task', 'closed' => 'Close Problem', 'delete' => 'Delete Problem');
            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, 'Problem', '{$type}', 'mail',\n                              {$notid}, '', 1, 1, NOW())";
                $DB->queryOrDie($query, "0.83 add problem {$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.83 add problem {$type} notification target");
                }
            }
        }
    }
    $migration->displayMessage(sprintf(__('Data migration - %s'), 'Clean Vlans'));
    // Clean `glpi_networkports_vlans` datas (`networkports_id` whithout networkports)
    $query = "DELETE\n             FROM `glpi_networkports_vlans`\n             WHERE `networkports_id` NOT IN (SELECT `id`\n                                             FROM `glpi_networkports`)";
    $DB->queryOrDie($query, "0.83 clean networkports_vlans datas");
    $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'Rename Solution objects'));
    // rename glpi_ticketsolutiontypes to glpi_solutiontypes
    $migration->renameTable('glpi_ticketsolutiontypes', 'glpi_solutiontypes');
    // rename glpi_ticketsolutiontemplates to glpi_solutiontemplates
    $migration->renameTable('glpi_ticketsolutiontemplates', 'glpi_solutiontemplates');
    $migration->changeField('glpi_tickets', 'ticketsolutiontypes_id', 'solutiontypes_id', 'integer');
    $migration->changeField('glpi_solutiontemplates', 'ticketsolutiontypes_id', 'solutiontypes_id', 'integer');
    $migration->changeField('glpi_tickets_users', 'use_notification', 'use_notification', 'bool', array('value' => '1'));
    // to have correct name of key
    $migration->dropKey('glpi_tickets', 'ticketsolutiontypes_id');
    $migration->migrationOneTable('glpi_tickets');
    $migration->addKey('glpi_tickets', 'solutiontypes_id');
    $migration->dropKey('glpi_solutiontemplates', 'ticketsolutiontypes_id');
    $migration->migrationOneTable('glpi_solutiontemplates');
    $migration->addKey('glpi_solutiontemplates', 'solutiontypes_id');
    $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'Rename Category objects'));
    $migration->renameTable('glpi_ticketcategories', 'glpi_itilcategories');
    $migration->dropKey('glpi_itilcategories', 'ticketcategories_id');
    $migration->changeField('glpi_itilcategories', 'ticketcategories_id', 'itilcategories_id', 'integer');
    $migration->migrationOneTable('glpi_itilcategories');
    $migration->addKey('glpi_itilcategories', 'itilcategories_id');
    $migration->dropKey('glpi_tickets', 'ticketcategories_id');
    $migration->changeField('glpi_tickets', 'ticketcategories_id', 'itilcategories_id', 'integer');
    $migration->migrationOneTable('glpi_tickets');
    $migration->addKey('glpi_tickets', 'itilcategories_id');
    // Update Itemtype datas in tables
    $itemtype_tables = array("glpi_bookmarks", "glpi_bookmarks_users", "glpi_displaypreferences");
    $typestochange = array('TicketSolutionTemplate' => 'SolutionTemplate', 'TicketSolutionType' => 'SolutionType', 'TicketCategory' => 'ITILCategory');
    foreach ($itemtype_tables as $table) {
        foreach ($typestochange as $key => $val) {
            $query = "UPDATE `{$table}`\n                   SET `itemtype` = '{$val}'\n                   WHERE `itemtype` = '{$key}'";
            $DB->queryOrDie($query, "0.83 update itemtype of table {$table} for {$val}");
        }
    }
    $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'Add various fields'));
    $migration->addField("glpi_states", 'states_id', "integer");
    $migration->addField("glpi_states", 'completename', "text");
    $migration->addField("glpi_states", 'level', "integer");
    $migration->addField("glpi_states", 'ancestors_cache', "longtext");
    $migration->addField("glpi_states", 'sons_cache', "longtext");
    $migration->migrationOneTable('glpi_states');
    $migration->addKey("glpi_states", array('states_id', 'name'), 'unicity');
    regenerateTreeCompleteName("glpi_states");
    $migration->addField("glpi_knowbaseitemcategories", 'ancestors_cache', "longtext");
    $migration->addField("glpi_knowbaseitemcategories", 'sons_cache', "longtext");
    $migration->changeField("glpi_authldaps", 'group_condition', 'group_condition', "text");
    $migration->dropKey("glpi_groups", 'ldap_value');
    $migration->changeField("glpi_groups", 'ldap_value', 'ldap_value', "text");
    $migration->dropKey("glpi_groups", 'ldap_group_dn');
    $migration->changeField("glpi_groups", 'ldap_group_dn', 'ldap_group_dn', "text");
    $migration->addField("glpi_groups", 'groups_id', "integer");
    $migration->addField("glpi_groups", 'completename', "text");
    $migration->addField("glpi_groups", 'level', "integer");
    $migration->addField("glpi_groups", 'ancestors_cache', "longtext");
    $migration->addField("glpi_groups", 'sons_cache', "longtext");
    $migration->migrationOneTable('glpi_groups');
    $migration->addKey("glpi_groups", 'ldap_value', '', 'INDEX', 200);
    $migration->addKey("glpi_groups", 'ldap_group_dn', '', 'INDEX', 200);
    $migration->addKey("glpi_groups", 'groups_id');
    regenerateTreeCompleteName("glpi_groups");
    $migration->addField("glpi_entitydatas", 'notification_subject_tag', "string", array('after' => 'admin_reply_name'));
    $migration->addField("glpi_vlans", 'tag', "integer");
    $ADDTODISPLAYPREF['Vlan'] = array(11);
    $migration->addField("glpi_profiles", 'create_ticket_on_login', "bool");
    $migration->addField("glpi_reminders", 'begin_view_date', "datetime");
    $migration->addField("glpi_reminders", 'end_view_date', "datetime");
    // only to change latin1 to utf-8 if not done in update 0.68.3 to 0.71
    // because there is an index fulltext based on 2 fields (perhaps both are not in same encoding)
    $migration->changeField("glpi_knowbaseitems", 'answer', 'answer', "longtext");
    $migration->changeField("glpi_knowbaseitems", 'question', 'name', "text");
    $migration->addField("glpi_configs", "ajax_min_textsearch_load", "integer", array('after' => 'use_ajax'));
    $migration->addField("glpi_configs", "use_anonymous_followups", "bool", array('after' => 'use_anonymous_helpdesk'));
    $migration->addField("glpi_configs", "show_count_on_tabs", "bool", array('value' => '1'));
    $migration->addField("glpi_users", "show_count_on_tabs", "tinyint(1) NULL DEFAULT NULL");
    $migration->addField("glpi_configs", "refresh_ticket_list", "integer");
    $migration->addField("glpi_users", "refresh_ticket_list", "int(11) NULL DEFAULT NULL");
    $migration->addField("glpi_configs", "set_default_tech", "bool", array('value' => '1'));
    $migration->addField("glpi_users", "set_default_tech", "tinyint(1) NULL DEFAULT NULL");
    $migration->addField("glpi_reservations", "group", "integer");
    $migration->addKey("glpi_reservations", array('reservationitems_id', 'group'), "resagroup");
    /// Add document types
    $types = array('csv' => array('name' => 'Comma-Separated Values', 'icon' => 'csv-dist.png'), 'svg' => array('name' => 'Scalable Vector Graphics', 'icon' => 'svg-dist.png'));
    foreach ($types as $ext => $data) {
        $query = "SELECT *\n                FROM `glpi_documenttypes`\n                WHERE `ext` = '{$ext}'";
        if ($result = $DB->query($query)) {
            if ($DB->numrows($result) == 0) {
                $query = "INSERT INTO `glpi_documenttypes`\n                             (`name`, `ext`, `icon`, `is_uploadable`, `date_mod`)\n                      VALUES ('" . $data['name'] . "', '{$ext}', '" . $data['icon'] . "', '1', NOW())";
                $DB->queryOrDie($query, "0.83 add document type {$ext}");
            }
        }
    }
    /// Update icons
    $types = array('c' => 'c-dist.png', 'h' => 'h-dist.png', 'swf' => 'swf-dist.png', 'pas' => 'pas-dist.png', 'wmv' => 'wmv-dist.png', 'zip' => 'zip-dist.png');
    foreach ($types as $ext => $icon) {
        $query = "SELECT `id`\n                FROM `glpi_documenttypes`\n                WHERE `ext` = '{$ext}'";
        if ($result = $DB->query($query)) {
            if ($DB->numrows($result) == 1) {
                $query = "UPDATE `glpi_documenttypes`\n                      SET `icon` = '{$icon}', `date_mod` = NOW()\n                      WHERE `id` = '" . $DB->result($result, 0, 0) . "'";
                $DB->queryOrDie($query, "0.83 update icon for doc type {$ext}");
            }
        }
    }
    /// add missing indexes  for fields
    $migration->addKey("glpi_authldaps", "is_active");
    $migration->addKey("glpi_authmails", "is_active");
    $migration->addKey("glpi_ocsservers", "is_active");
    $migration->changeField("glpi_users", 'token', 'password_forget_token', "char(40) NULL DEFAULT NULL");
    $migration->changeField("glpi_users", 'tokendate', 'password_forget_token_date', "datetime");
    $migration->addField("glpi_users", "personal_token", 'string');
    $migration->addField("glpi_users", "personal_token_date", "datetime");
    $migration->addField("glpi_tickets", "is_deleted", "bool");
    $migration->addKey("glpi_tickets", "is_deleted");
    $migration->addField("glpi_contracts", "template_name", 'string');
    $migration->addField("glpi_contracts", "is_template", 'bool');
    $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'Give consumable to groups'));
    if ($migration->addField("glpi_consumables", "itemtype", "VARCHAR(100) DEFAULT NULL", array("after" => "date_out", "update" => "'User'"))) {
        $migration->dropKey("glpi_consumables", 'users_id');
        $migration->changeField("glpi_consumables", 'users_id', 'items_id', 'integer');
        $migration->addKey("glpi_consumables", array('itemtype', 'items_id'), 'item');
    }
    $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'Several emails for users'));
    // Several email per users
    if (!TableExists('glpi_useremails')) {
        $query = "CREATE TABLE `glpi_useremails` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `users_id` int(11) NOT NULL DEFAULT '0',\n                  `is_default` TINYINT( 1 ) NOT NULL DEFAULT 0,\n                  `is_dynamic` TINYINT( 1 ) NOT NULL DEFAULT 0,\n                  `email` varchar( 255 ) NULL DEFAULT NULL,\n                  PRIMARY KEY (`id`),\n                  UNIQUE KEY `unicity` (`users_id`,`email`),\n                  KEY `email` (`email`),\n                  KEY `is_default` (`is_default`),\n                  KEY `is_dynamic` (`is_dynamic`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.83 add table glpi_useremails");
    }
    // Manage migration : populate is_default=1
    // and is_dynamic depending of authldap config / authtype / auths_id
    if (FieldExists("glpi_users", 'email', false)) {
        $query = "SELECT *\n                FROM `glpi_users`\n                WHERE `email` <> '' AND `email` IS NOT NULL";
        if ($result = $DB->query($query)) {
            if ($DB->numrows($result) > 0) {
                while ($data = $DB->fetch_assoc($result)) {
                    $is_dynamic = 0;
                    $ldap_servers = array();
                    // manage is_dynamic :
                    if ($data['authtype'] == Auth::MAIL) {
                        $is_dynamic = 1;
                    } else {
                        if (Auth::isAlternateAuth($data["authtype"]) && $data['auths_id'] > 0 || $data['authtype'] == Auth::LDAP) {
                            if (!isset($ldap_servers[$data['auths_id']])) {
                                $ldap_servers[$data['auths_id']] = 0;
                                $ldap = new AuthLDAP();
                                if ($ldap->getFromDB($data['auths_id'])) {
                                    if (!empty($ldap->fields['email_field'])) {
                                        $ldap_servers[$data['auths_id']] = 1;
                                    }
                                }
                            }
                            $is_dynamic = $ldap_servers[$data['auths_id']];
                        }
                    }
                    $query2 = "INSERT INTO `glpi_useremails`\n                                 (`users_id`, `is_default`, `is_dynamic`, `email`)\n                          VALUES ('" . $data['id'] . "','1','{$is_dynamic}','" . addslashes($data['email']) . "')";
                    $DB->queryOrDie($query2, "0.83 move emails to  glpi_useremails");
                }
            }
        }
        // Drop email field from glpi_users
        $migration->dropField("glpi_users", 'email');
    }
    // check unicity for users email : unset rule and display warning
    foreach ($DB->request("glpi_fieldunicities", "`itemtype` = 'User' AND `fields` LIKE '%email%'") as $data) {
        $query = "UPDATE `glpi_fieldunicities`\n                SET `is_active` = '0'\n                WHERE `id` = '" . $data['id'] . "'";
        $DB->query($query);
        echo "<div class='red'><p>A unicity check use email for users. ";
        echo "Due to new feature permit several email per users, this rule have been disabled.</p></div>";
    }
    // multiple manager in groups
    $migration->changeField("glpi_authldaps", 'email_field', 'email1_field', 'string');
    $migration->addField("glpi_authldaps", 'email2_field', 'string');
    $migration->addField("glpi_authldaps", 'email3_field', 'string');
    $migration->addField("glpi_authldaps", 'email4_field', 'string');
    $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'Multiple managers for groups'));
    /// migration : multiple group managers
    $migration->addField("glpi_groups_users", "is_manager", 'bool');
    $migration->addKey("glpi_groups_users", "is_manager");
    $migration->migrationOneTable('glpi_groups_users');
    if (FieldExists("glpi_groups", 'users_id', false)) {
        $query = "SELECT *\n                FROM `glpi_groups`\n                WHERE `users_id` > 0";
        $user = new User();
        if ($result = $DB->query($query)) {
            if ($DB->numrows($result) > 0) {
                while ($data = $DB->fetch_assoc($result)) {
                    if ($user->getFromDB($data['users_id'])) {
                        $query = "SELECT `id`\n                            FROM `glpi_groups_users`\n                            WHERE `groups_id` = '" . $data['id'] . "'\n                                 AND `users_id` = '" . $data['users_id'] . "'";
                        if ($result2 = $DB->query($query)) {
                            // add manager to groups_users setting if not present
                            if ($DB->numrows($result2) == 0) {
                                $query2 = "INSERT INTO`glpi_groups_users`\n                                          (`users_id`, `groups_id`, `is_manager`)\n                                   VALUES ('" . $data['users_id'] . "' ,'" . $data['id'] . "', '1')";
                                $DB->queryOrDie($query2, "0.83 insert manager of groups");
                            } else {
                                // Update user as manager if presnet in groups_users
                                $query2 = "UPDATE `glpi_groups_users`\n                                   SET `is_manager` = '1'\n                                   WHERE `groups_id` = '" . $data['id'] . "'\n                                         AND `users_id` = '" . $data['users_id'] . "'";
                                $DB->queryOrDie($query2, "0.83 set manager of groups");
                            }
                        }
                    }
                }
            }
        }
        // Drop field glpi_groups
        $migration->dropField("glpi_groups", 'users_id');
    }
    $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'Add entities information on document links'));
    if ($migration->addField("glpi_documents_items", "entities_id", "integer")) {
        $migration->addField("glpi_documents_items", "is_recursive", "bool");
        $migration->migrationOneTable('glpi_documents_items');
        $query_doc_i = "UPDATE `glpi_documents_items` as `doc_i`\n                      INNER JOIN `glpi_documents` as `doc`\n                        ON  `doc`.`id` = `doc_i`.`documents_id`\n                      SET `doc_i`.`entities_id` = `doc`.`entities_id`,\n                         `doc_i`.`is_recursive` = `doc`.`is_recursive`";
        $DB->queryOrDie($query_doc_i, "0.83 update entities_id and is_recursive in glpi_documents_items");
        /// create index for search count on tab
        $migration->dropKey("glpi_documents_items", "item");
        $migration->migrationOneTable('glpi_documents_items');
        $migration->addKey("glpi_documents_items", array('itemtype', 'items_id', 'entities_id', 'is_recursive'), 'item');
    }
    $migration->displayMessage(sprintf(__('Data migration - %s'), 'RuleTicket'));
    $changes['RuleTicket'] = array('ticketcategories_id' => 'itilcategories_id');
    $DB->query("SET SESSION group_concat_max_len = 4194304;");
    foreach ($changes as $ruletype => $tab) {
        // Get rules
        $query = "SELECT GROUP_CONCAT(`id`)\n                FROM `glpi_rules`\n                WHERE `sub_type` = '" . $ruletype . "'\n                GROUP BY `sub_type`";
        if ($result = $DB->query($query)) {
            if ($DB->numrows($result) > 0) {
                // Get rule string
                $rules = $DB->result($result, 0, 0);
                // Update actions
                foreach ($tab as $old => $new) {
                    $query = "UPDATE `glpi_ruleactions`\n                         SET `field` = '{$new}'\n                         WHERE `field` = '{$old}'\n                               AND `rules_id` IN ({$rules})";
                    $DB->queryOrDie($query, "0.83 update datas for rules actions");
                }
                // Update criteria
                foreach ($tab as $old => $new) {
                    $query = "UPDATE `glpi_rulecriterias`\n                         SET `criteria` = '{$new}'\n                         WHERE `criteria` = '{$old}'\n                               AND `rules_id` IN ({$rules})";
                    $DB->queryOrDie($query, "0.83 update datas for rules criteria");
                }
            }
        }
    }
    $migration->displayMessage(sprintf(__('Data migration - %s'), 'Ticket templates'));
    $default_ticket_template = 0;
    if (!TableExists('glpi_tickettemplates')) {
        $query = "CREATE TABLE `glpi_tickettemplates` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `name` varchar( 255 ) NULL DEFAULT NULL,\n                  `entities_id` int(11) NOT NULL DEFAULT '0',\n                  `is_recursive` TINYINT( 1 ) NOT NULL DEFAULT 0,\n                  `comment` TEXT DEFAULT NULL,\n                  PRIMARY KEY (`id`),\n                  KEY `name` (`name`),\n                  KEY `entities_id` (`entities_id`),\n                  KEY `is_recursive` (`is_recursive`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.83 add table glpi_tickettemplates");
        $query = "INSERT INTO `glpi_tickettemplates`\n                       (`name`, `is_recursive`)\n                VALUES ('Default', 1)";
        $DB->queryOrDie($query, "0.83 add default ticket template");
        $default_ticket_template = $DB->insert_id();
    }
    $migration->addField('glpi_itilcategories', 'tickettemplates_id_incident', "integer");
    $migration->addKey('glpi_itilcategories', 'tickettemplates_id_incident');
    $migration->addField('glpi_itilcategories', 'tickettemplates_id_demand', "integer");
    $migration->addKey('glpi_itilcategories', 'tickettemplates_id_demand');
    $migration->addField('glpi_itilcategories', 'is_incident', "integer", array('value' => 1));
    $migration->addKey('glpi_itilcategories', 'is_incident');
    $migration->addField('glpi_itilcategories', 'is_request', "integer", array('value' => 1));
    $migration->addKey('glpi_itilcategories', 'is_request');
    $migration->addField('glpi_itilcategories', 'is_problem', "integer", array('value' => 1));
    $migration->addKey('glpi_itilcategories', 'is_problem');
    if (!TableExists('glpi_tickettemplatehiddenfields')) {
        $query = "CREATE TABLE `glpi_tickettemplatehiddenfields` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `tickettemplates_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                  `num` int(11) NOT NULL DEFAULT '0',\n                  PRIMARY KEY (`id`),\n                  KEY `entities_id` (`entities_id`),\n                  KEY `is_recursive` (`is_recursive`),\n                  KEY `unicity` (`tickettemplates_id`,`num`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.83 add table glpi_tickettemplatehiddenfields");
    }
    if (!TableExists('glpi_tickettemplatepredefinedfields')) {
        $query = "CREATE TABLE `glpi_tickettemplatepredefinedfields` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `tickettemplates_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                  `num` int(11) NOT NULL DEFAULT '0',\n                  `value` TEXT DEFAULT NULL,\n                  PRIMARY KEY (`id`),\n                  KEY `entities_id` (`entities_id`),\n                  KEY `is_recursive` (`is_recursive`),\n                  KEY `unicity` (`tickettemplates_id`,`num`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.83 add table glpi_tickettemplatepredefinedfields");
    }
    if (!TableExists('glpi_tickettemplatemandatoryfields')) {
        $query = "CREATE TABLE `glpi_tickettemplatemandatoryfields` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `tickettemplates_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                  `num` int(11) NOT NULL DEFAULT '0',\n                  PRIMARY KEY (`id`),\n                  KEY `entities_id` (`entities_id`),\n                  KEY `is_recursive` (`is_recursive`),\n                  KEY `unicity` (`tickettemplates_id`,`num`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.83 add table glpi_tickettemplatemandatoryfields");
        /// Add mandatory fields to default template
        if ($default_ticket_template > 0) {
            foreach ($DB->request('glpi_configs') as $data) {
                if (isset($data['is_ticket_title_mandatory']) && $data['is_ticket_title_mandatory']) {
                    $query = "INSERT INTO `glpi_tickettemplatemandatoryfields`\n                                (`tickettemplates_id`, `num`)\n                         VALUES ('{$default_ticket_template}', 1)";
                    $DB->queryOrDie($query, "0.83 add mandatory field for default ticket template");
                }
                if (isset($data['is_ticket_content_mandatory']) && $data['is_ticket_content_mandatory']) {
                    $query = "INSERT INTO `glpi_tickettemplatemandatoryfields`\n                                (`tickettemplates_id`, `num`)\n                         VALUES ('{$default_ticket_template}', 21)";
                    $DB->queryOrDie($query, "0.83 add mandatory field for default ticket template");
                }
                if (isset($data['is_ticket_category_mandatory']) && $data['is_ticket_category_mandatory']) {
                    $query = "INSERT INTO `glpi_tickettemplatemandatoryfields`\n                                (`tickettemplates_id`, `num`)\n                         VALUES ('{$default_ticket_template}', 7)";
                    $DB->queryOrDie($query, "0.83 add mandatory field for default ticket template");
                }
            }
            // Update itil categories
            $migration->migrationOneTable('glpi_itilcategories');
            $query = "UPDATE `glpi_itilcategories`\n                   SET `tickettemplates_id_incident` = '{$default_ticket_template}',\n                       `tickettemplates_id_demand` = '{$default_ticket_template}'";
            $DB->queryOrDie($query, "0.83 update default templates used by itil categories");
        }
    }
    // Drop global mandatory config
    $migration->dropField('glpi_configs', 'is_ticket_title_mandatory');
    $migration->dropField('glpi_configs', 'is_ticket_content_mandatory');
    $migration->dropField('glpi_configs', 'is_ticket_category_mandatory');
    $migration->addField('glpi_profiles', 'tickettemplate', "char", array('update' => '`sla`'));
    $migration->addField("glpi_entitydatas", "tickettemplates_id", 'integer', array('value' => '-2'));
    $migration->displayMessage(sprintf(__('Data migration - %s'), 'Tech Groups on items'));
    // Group of technicians in charge of Helpdesk items
    $migration->addField('glpi_computers', 'groups_id_tech', "integer", array('after' => "users_id_tech"));
    $migration->addKey('glpi_computers', 'groups_id_tech');
    $migration->addField('glpi_monitors', 'groups_id_tech', "integer", array('after' => "users_id_tech"));
    $migration->addKey('glpi_monitors', 'groups_id_tech');
    $migration->addField('glpi_networkequipments', 'groups_id_tech', "integer", array('after' => "users_id_tech"));
    $migration->addKey('glpi_networkequipments', 'groups_id_tech');
    $migration->addField('glpi_peripherals', 'groups_id_tech', "integer", array('after' => "users_id_tech"));
    $migration->addKey('glpi_peripherals', 'groups_id_tech');
    $migration->addField('glpi_phones', 'groups_id_tech', "integer", array('after' => "users_id_tech"));
    $migration->addKey('glpi_phones', 'groups_id_tech');
    $migration->addField('glpi_printers', 'groups_id_tech', "integer", array('after' => "users_id_tech"));
    $migration->addKey('glpi_printers', 'groups_id_tech');
    $migration->addField('glpi_softwares', 'groups_id_tech', "integer", array('after' => "users_id_tech"));
    $migration->addKey('glpi_softwares', 'groups_id_tech');
    $migration->addField('glpi_cartridgeitems', 'groups_id_tech', "integer", array('after' => "users_id_tech"));
    $migration->addKey('glpi_cartridgeitems', 'groups_id_tech');
    $migration->addField('glpi_consumableitems', 'groups_id_tech', "integer", array('after' => "users_id_tech"));
    $migration->addKey('glpi_consumableitems', 'groups_id_tech');
    $migration->addField('glpi_printers', 'last_pages_counter', 'integer', array('after' => 'init_pages_counter'));
    $migration->addKey('glpi_printers', 'last_pages_counter');
    $migration->displayMessage(sprintf(__('Data migration - %s'), 'various cleaning DB'));
    // Clean ticket satisfactions
    $query = "DELETE\n             FROM `glpi_ticketsatisfactions`\n             WHERE `glpi_ticketsatisfactions`.`tickets_id` NOT IN (SELECT `glpi_tickets`.`id`\n                                                                   FROM `glpi_tickets`)";
    $DB->queryOrDie($query, "0.83 clean glpi_ticketsatisfactions");
    // Clean unused slalevels
    $query = "DELETE\n             FROM `glpi_slalevels_tickets`\n             WHERE (`glpi_slalevels_tickets`.`tickets_id`, `glpi_slalevels_tickets`.`slalevels_id`)\n                  NOT IN (SELECT `glpi_tickets`.`id`, `glpi_tickets`.`slalevels_id`\n                          FROM `glpi_tickets`)";
    $DB->queryOrDie($query, "0.83 clean glpi_slalevels_tickets");
    $migration->displayMessage(sprintf(__('Data migration - %s'), 'recurrent tickets'));
    if (!TableExists('glpi_ticketrecurrents')) {
        $query = "CREATE TABLE `glpi_ticketrecurrents` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `name` varchar( 255 ) NULL DEFAULT NULL,\n                  `comment` TEXT DEFAULT NULL,\n                  `entities_id` int(11) NOT NULL DEFAULT '0',\n                  `is_recursive` TINYINT( 1 ) NOT NULL DEFAULT 0,\n                  `is_active` TINYINT( 1 ) NOT NULL DEFAULT 0,\n                  `tickettemplates_id` int(11) NOT NULL DEFAULT '0',\n                  `begin_date` datetime DEFAULT NULL,\n                  `periodicity` int(11) NOT NULL DEFAULT '0',\n                  `create_before` int(11) NOT NULL DEFAULT '0',\n                  `next_creation_date` datetime DEFAULT NULL,\n                  PRIMARY KEY (`id`),\n                  KEY `entities_id` (`entities_id`),\n                  KEY `is_recursive` (`is_recursive`),\n                  KEY `is_active` (`is_active`),\n                  KEY `tickettemplates_id` (`tickettemplates_id`),\n                  KEY `next_creation_date` (`next_creation_date`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.83 add table glpi_ticketrecurrents");
        $ADDTODISPLAYPREF['TicketRecurrent'] = array(11, 12, 13, 15, 14);
    }
    if (!countElementsInTable('glpi_crontasks', "`itemtype`='TicketRecurrent' AND `name`='ticketrecurrent'")) {
        $query = "INSERT INTO `glpi_crontasks`\n                       (`itemtype`, `name`, `frequency`, `param`, `state`, `mode`, `allowmode`,\n                        `hourmin`, `hourmax`, `logs_lifetime`, `lastrun`, `lastcode`, `comment`)\n                VALUES ('TicketRecurrent', 'ticketrecurrent', 3600, NULL, 1, 1, 3,\n                        0, 24, 30, NULL, NULL, NULL)";
        $DB->queryOrDie($query, "0.83 populate glpi_crontasks for ticketrecurrent");
    }
    $migration->addField('glpi_profiles', 'ticketrecurrent', "char", array('update' => '`sla`'));
    $migration->displayMessage(sprintf(__('Data migration - %s'), 'various fields add'));
    // Ticket delegation
    $migration->addField('glpi_groups_users', 'is_userdelegate', 'bool');
    $migration->addKey('glpi_groups_users', 'is_userdelegate');
    //Software dictionary update
    $migration->addField("glpi_rulecachesoftwares", "entities_id", "string");
    $migration->addField("glpi_rulecachesoftwares", "new_entities_id", "string");
    $migration->addField("glpi_entitydatas", "entities_id_software", 'integer', array('value' => '-2'));
    // Groups perm
    $migration->addField('glpi_groups', 'is_requester', 'bool', array('value' => '1'));
    $migration->addField('glpi_groups', 'is_assign', 'bool', array('value' => '1'));
    $migration->addField('glpi_groups', 'is_notify', 'bool', array('value' => '1'));
    $migration->addField('glpi_groups', 'is_itemgroup', 'bool', array('value' => '1'));
    $migration->addField('glpi_groups', 'is_usergroup', 'bool', array('value' => '1'));
    $migration->addKey('glpi_groups', 'is_requester');
    $migration->addKey('glpi_groups', 'is_assign');
    $migration->addKey('glpi_groups', 'is_notify');
    $migration->addKey('glpi_groups', 'is_itemgroup');
    $migration->addKey('glpi_groups', 'is_usergroup');
    // Ticket solution by entity
    $migration->addfield('glpi_solutiontypes', 'entities_id', 'integer');
    $migration->addfield('glpi_solutiontypes', 'is_recursive', 'bool', array('value' => '1'));
    $migration->addKey('glpi_solutiontypes', 'entities_id');
    $migration->addKey('glpi_solutiontypes', 'is_recursive');
    // Fix solution template index
    $migration->dropKey('glpi_solutiontemplates', 'unicity');
    $migration->addKey('glpi_solutiontemplates', 'entities_id');
    // New index for count on tab
    $migration->addKey('glpi_ruleactions', array('field', 'value'), '', 'INDEX', 50);
    $migration->displayMessage(sprintf(__('Data migration - %s'), 'Create new default profiles'));
    $profiles = array('hotliner' => array('name' => 'Hotliner', 'interface' => 'central', 'user' => 'r', 'import_externalauth_users' => 'w', 'create_ticket' => '1', 'assign_ticket' => '1', 'global_add_followups' => '1', 'add_followups' => '1', 'update_ticket' => '1', 'observe_ticket' => '1', 'show_all_ticket' => '1', 'show_full_ticket' => '1', 'show_all_problem' => '1', 'show_planning' => '1', 'statistic' => '1', 'tickettemplate' => 'r', 'password_update' => '1', 'helpdesk_hardware' => '3', 'helpdesk_item_type' => addslashes('["Computer", "Monitor", "NetworkEquipment",' . '"Peripheral", "Phone", "Printer",' . '"Software"]'), 'create_validation' => '1', 'update_own_followups' => '1', 'create_ticket_on_login' => '1'), 'technician' => array('name' => 'Technician', 'interface' => 'central', 'password_update' => '1', 'computer' => 'w', 'monitor' => 'w', 'software' => 'w', 'networking' => 'w', 'printer' => 'w', 'peripheral' => 'w', 'cartridge' => 'w', 'consumable' => 'w', 'phone' => 'w', 'notes' => 'w', 'document' => 'w', 'knowbase' => 'w', 'faq' => 'w', 'reservation_helpdesk' => '1', 'reservation_central' => 'w', 'reports' => 'r', 'view_ocsng' => 'r', 'sync_ocsng' => 'w', 'user' => 'w', 'group' => 'r', 'entity' => 'r', 'transfer' => 'r', 'reminder_public' => 'w', 'create_ticket' => '1', 'add_followups' => '1', 'global_add_followups' => '1', 'global_add_tasks' => '1', 'update_ticket' => '1', 'own_ticket' => '1', 'show_all_ticket' => '1', 'show_assign_ticket' => '1', 'show_full_ticket' => '1', 'observe_ticket' => '1', 'update_followups' => '1', 'update_tasks' => '1', 'show_planning' => '1', 'statistic' => '1', 'helpdesk_hardware' => '3', 'helpdesk_item_type' => addslashes('["Computer", "Monitor", "NetworkEquipment",' . '"Peripheral", "Phone", "Printer",' . '"Software"]'), 'import_externalauth_users' => 'w', 'create_validation' => '1', 'sla' => 'r', 'update_own_followups' => '1', 'show_my_problem' => '1', 'show_all_problem' => '1', 'tickettemplate' => 'r', 'ticketrecurrent' => 'r'), 'supervisor' => array('name' => 'Supervisor', 'interface' => 'central', 'password_update' => '1', 'computer' => 'w', 'monitor' => 'w', 'software' => 'w', 'networking' => 'w', 'printer' => 'w', 'peripheral' => 'w', 'cartridge' => 'w', 'consumable' => 'w', 'phone' => 'w', 'notes' => 'w', 'document' => 'w', 'knowbase' => 'w', 'faq' => 'w', 'reservation_helpdesk' => '1', 'reservation_central' => 'w', 'reports' => 'r', 'view_ocsng' => 'r', 'sync_ocsng' => 'w', 'entity_dropdown' => 'w', 'rule_ticket' => 'r', 'entity_rule_ticket' => 'w', 'user' => 'w', 'group' => 'r', 'entity' => 'r', 'transfer' => 'r', 'logs' => 'r', 'reminder_public' => 'w', 'create_ticket' => '1', 'delete_ticket' => '1', 'add_followups' => '1', 'global_add_followups' => '1', 'global_add_tasks' => '1', 'update_ticket' => '1', 'update_priority' => '1', 'own_ticket' => '1', 'steal_ticket' => '1', 'assign_ticket' => '1', 'show_all_ticket' => '1', 'show_assign_ticket' => '1', 'show_full_ticket' => '1', 'observe_ticket' => '1', 'update_followups' => '1', 'update_tasks' => '1', 'show_planning' => '1', 'show_all_planning' => '1', 'statistic' => '1', 'helpdesk_hardware' => '3', 'helpdesk_item_type' => addslashes('["Computer", "Monitor", "NetworkEquipment",' . '"Peripheral", "Phone", "Printer",' . '"Software"]'), 'import_externalauth_users' => 'w', 'rule_mailcollector' => 'w', 'validate_ticket' => '1', 'create_validation' => '1', 'calendar' => 'w', 'sla' => 'w', 'update_own_followups' => '1', 'delete_followups' => '1', 'show_my_problem' => '1', 'show_all_problem' => '1', 'edit_all_problem' => '1', 'tickettemplate' => 'w', 'ticketrecurrent' => 'w'));
    foreach ($profiles as $profile => $data) {
        $query = "INSERT INTO `glpi_profiles`\n                         (`" . implode("`, `", array_keys($data)) . "`)\n                  VALUES ('" . implode("', '", $data) . "')";
        $DB->queryOrDie($query, "0.83 create new profile {$profile}");
    }
    $migration->displayMessage(sprintf(__('Data migration - %s'), 'Reminder visibility'));
    if (!TableExists('glpi_reminders_users')) {
        $query = "CREATE TABLE `glpi_reminders_users` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `reminders_id` int(11) NOT NULL DEFAULT '0',\n                  `users_id` int(11) NOT NULL DEFAULT '0',\n                  PRIMARY KEY (`id`),\n                  KEY `reminders_id` (`reminders_id`),\n                  KEY `users_id` (`users_id`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.83 add table glpi_reminders_users");
    }
    if (!TableExists('glpi_groups_reminders')) {
        $query = "CREATE TABLE `glpi_groups_reminders` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `reminders_id` int(11) NOT NULL DEFAULT '0',\n                  `groups_id` int(11) NOT NULL DEFAULT '0',\n                  `entities_id` int(11) NOT NULL DEFAULT '-1',\n                  `is_recursive` TINYINT( 1 ) NOT NULL DEFAULT 0,\n                  PRIMARY KEY (`id`),\n                  KEY `reminders_id` (`reminders_id`),\n                  KEY `groups_id` (`groups_id`),\n                  KEY `entities_id` (`entities_id`),\n                  KEY `is_recursive` (`is_recursive`)\n\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.83 add table glpi_groups_reminders");
    }
    if (!TableExists('glpi_profiles_reminders')) {
        $query = "CREATE TABLE `glpi_profiles_reminders` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `reminders_id` int(11) NOT NULL DEFAULT '0',\n                  `profiles_id` int(11) NOT NULL DEFAULT '0',\n                  `entities_id` int(11) NOT NULL DEFAULT '-1',\n                  `is_recursive` TINYINT( 1 ) NOT NULL DEFAULT 0,\n                  PRIMARY KEY (`id`),\n                  KEY `reminders_id` (`reminders_id`),\n                  KEY `profiles_id` (`profiles_id`),\n                  KEY `entities_id` (`entities_id`),\n                  KEY `is_recursive` (`is_recursive`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.83 add table glpi_profiles_reminders");
    }
    if (!TableExists('glpi_entities_reminders')) {
        $query = "CREATE TABLE `glpi_entities_reminders` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `reminders_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 `reminders_id` (`reminders_id`),\n                  KEY `entities_id` (`entities_id`),\n                  KEY `is_recursive` (`is_recursive`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.83 add table glpi_entities_reminders");
    }
    /// Migrate datas for is_helpdesk_visible : add all helpdesk profiles / drop field is_helpdesk_visible
    if (FieldExists("glpi_reminders", 'is_helpdesk_visible', false)) {
        $query = "SELECT `id`\n                FROM `glpi_reminders`\n                WHERE `is_helpdesk_visible` = 1";
        if ($result = $DB->query($query)) {
            if ($DB->numrows($result) > 0) {
                // Grab helpdesk profiles
                $helpdesk_profiles = array();
                foreach ($DB->request("glpi_profiles", "`interface` = 'helpdesk' AND `reminder_public` = 'r'") as $data2) {
                    $helpdesk_profiles[$data2['id']] = $data2['id'];
                }
                if (count($helpdesk_profiles)) {
                    while ($data = $DB->fetch_assoc($result)) {
                        foreach ($helpdesk_profiles as $pid) {
                            $query = "INSERT INTO `glpi_profiles_reminders`\n                                      (`reminders_id`, `profiles_id`)\n                               VALUES ('" . $data['id'] . "', '{$pid}');";
                            $DB->queryOrDie($query, "0.83 migrate data for is_helpdesk_visible drop on glpi_reminders");
                        }
                    }
                }
            }
        }
        $migration->dropField("glpi_reminders", 'is_helpdesk_visible');
    }
    // Migrate datas for entities + drop fields : is_private / entities_id / is_recursive
    if (FieldExists("glpi_reminders", 'is_private', false)) {
        $query = "SELECT *\n                FROM `glpi_reminders`\n                WHERE `is_private` = 0";
        if ($result = $DB->query($query)) {
            if ($DB->numrows($result) > 0) {
                while ($data = $DB->fetch_assoc($result)) {
                    $query = "INSERT INTO `glpi_entities_reminders`\n                                (`reminders_id`, `entities_id`, `is_recursive`)\n                         VALUES ('" . $data['id'] . "', '" . $data['entities_id'] . "',\n                                 '" . $data['is_recursive'] . "');";
                    $DB->queryOrDie($query, "0.83 migrate data for public reminders");
                }
            }
        }
        $migration->dropField("glpi_reminders", 'is_private');
        $migration->dropField("glpi_reminders", 'entities_id');
        $migration->dropField("glpi_reminders", 'is_recursive');
    }
    $ADDTODISPLAYPREF['Reminder'] = array(2, 3, 4, 5, 6, 7);
    $migration->displayMessage(sprintf(__('Data migration - %s'), 'KnowbaseItem visibility'));
    if (!TableExists('glpi_knowbaseitems_users')) {
        $query = "CREATE TABLE `glpi_knowbaseitems_users` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `knowbaseitems_id` int(11) NOT NULL DEFAULT '0',\n                  `users_id` int(11) NOT NULL DEFAULT '0',\n                  PRIMARY KEY (`id`),\n                  KEY `knowbaseitems_id` (`knowbaseitems_id`),\n                  KEY `users_id` (`users_id`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.83 add table glpi_knowbaseitems_users");
    }
    if (!TableExists('glpi_groups_knowbaseitems')) {
        $query = "CREATE TABLE `glpi_groups_knowbaseitems` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `knowbaseitems_id` int(11) NOT NULL DEFAULT '0',\n                  `groups_id` int(11) NOT NULL DEFAULT '0',\n                  `entities_id` int(11) NOT NULL DEFAULT '-1',\n                  `is_recursive` TINYINT( 1 ) NOT NULL DEFAULT 0,\n                  PRIMARY KEY (`id`),\n                  KEY `knowbaseitems_id` (`knowbaseitems_id`),\n                  KEY `groups_id` (`groups_id`),\n                  KEY `entities_id` (`entities_id`),\n                  KEY `is_recursive` (`is_recursive`)\n\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.83 add table glpi_groups_knowbaseitems");
    }
    if (!TableExists('glpi_knowbaseitems_profiles')) {
        $query = "CREATE TABLE `glpi_knowbaseitems_profiles` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `knowbaseitems_id` int(11) NOT NULL DEFAULT '0',\n                  `profiles_id` int(11) NOT NULL DEFAULT '0',\n                  `entities_id` int(11) NOT NULL DEFAULT '-1',\n                  `is_recursive` TINYINT( 1 ) NOT NULL DEFAULT 0,\n                  PRIMARY KEY (`id`),\n                  KEY `knowbaseitems_id` (`knowbaseitems_id`),\n                  KEY `profiles_id` (`profiles_id`),\n                  KEY `entities_id` (`entities_id`),\n                  KEY `is_recursive` (`is_recursive`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.83 add table glpi_knowbaseitems_profiles");
    }
    if (!TableExists('glpi_entities_knowbaseitems')) {
        $query = "CREATE TABLE `glpi_entities_knowbaseitems` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `knowbaseitems_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 `knowbaseitems_id` (`knowbaseitems_id`),\n                  KEY `entities_id` (`entities_id`),\n                  KEY `is_recursive` (`is_recursive`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.83 add table glpi_entities_knowbaseitems");
    }
    /// Migrate datas for entities_id / is_recursive
    if (FieldExists("glpi_knowbaseitems", 'entities_id', false)) {
        $query = "SELECT *\n                FROM `glpi_knowbaseitems`";
        if ($result = $DB->query($query)) {
            if ($DB->numrows($result) > 0) {
                while ($data = $DB->fetch_assoc($result)) {
                    $query = "INSERT INTO `glpi_entities_knowbaseitems`\n                                (`knowbaseitems_id`, `entities_id`, `is_recursive`)\n                         VALUES ('" . $data['id'] . "', '" . $data['entities_id'] . "',\n                                 '" . $data['is_recursive'] . "');";
                    $DB->queryOrDie($query, "0.83 migrate data for entities on glpi_entities_knowbaseitems");
                }
            }
        }
        $migration->dropField("glpi_knowbaseitems", 'entities_id');
        $migration->dropField("glpi_knowbaseitems", 'is_recursive');
    }
    // Plugins
    $migration->addField('glpi_plugins', 'license', 'string');
    $migration->migrationOneTable('glpi_entitydatas');
    $restore_root_entity_value = false;
    // create root entity if not exist with old default values
    if (countElementsInTable('glpi_entitydatas', 'entities_id=0') == 0) {
        $query = "INSERT INTO `glpi_entitydatas`\n                       (`entities_id`, `entities_id_software`,\n                        `autofill_order_date`, `autofill_delivery_date`, `autofill_buy_date`,\n                        `autofill_use_date`, `autofill_warranty_date`,\n                        `inquest_config`, `inquest_rate`, `inquest_delay`,\n                        `tickettype`, `calendars_id`, `tickettemplates_id`,\n                        `autoclose_delay`, `auto_assign_mode`,\n                        `cartridges_alert_repeat`, `consumables_alert_repeat`,\n                        `use_licenses_alert`, `use_infocoms_alert`, `notclosed_delay`,\n                        `use_contracts_alert`, `use_reservations_alert`)\n                VALUES (0, -10,\n                        0, 0, 0,\n                        0, 0,\n                        1, 0, 0,\n                        1, 0, '{$default_ticket_template}',\n                        -1, -1,\n                        -1, -1,\n                        -1, -1, -1,\n                        -1, -1)";
        // -1 to keep config value - see 1647
        $DB->queryOrDie($query, "0.83 add entities_id 0 in glpi_entitydatas");
        $restore_root_entity_value = true;
    } else {
        $query = "UPDATE `glpi_entitydatas`\n                SET `tickettemplates_id` = '{$default_ticket_template}'\n                WHERE `entities_id` = 0\n                      AND `tickettemplates_id` = -2";
        $DB->queryOrDie($query, "0.83 update tickettemplates_id for root entity in glpi_entitydatas");
        $query = "UPDATE `glpi_entitydatas`\n                SET `entities_id_software` = -10\n                WHERE `entities_id` = 0\n                      AND `entities_id_software` = -2";
        $DB->queryOrDie($query, "0.83 update entities_id_software for root entity in glpi_entitydatas");
        // For root entity already exists in entitydatas in 0.78
        $query = "UPDATE `glpi_entitydatas`\n                SET `tickettype` = 1\n                WHERE `entities_id` = 0\n                      AND `tickettype` = 0";
        $DB->queryOrDie($query, "0.83 update tickettype for root entity in glpi_entitydatas");
        $query = "UPDATE `glpi_entitydatas`\n                SET `inquest_config` = 1\n                WHERE `entities_id` = 0\n                      AND `inquest_config` = 0";
        $DB->queryOrDie($query, "0.83 update inquest_config for root entity in glpi_entitydatas ");
        $query = "UPDATE `glpi_entitydatas`\n                SET `inquest_rate` = 0\n                WHERE `entities_id` = 0\n                      AND `inquest_rate` = '-1'";
        $DB->queryOrDie($query, "0.83 update inquest_rate for root entity in glpi_entitydatas ");
        $query = "UPDATE `glpi_entitydatas`\n                SET `inquest_delay` = 0\n                WHERE `entities_id` = 0\n                      AND `inquest_delay` = '-1'";
        $DB->queryOrDie($query, "0.83 update inquest_delay for root entity in glpi_entitydatas ");
    }
    // migration to new values for inherit parent (0 => -2)
    $field0 = array('calendars_id', 'tickettype', 'inquest_config');
    foreach ($field0 as $field_0) {
        if (FieldExists("glpi_entitydatas", $field_0, false)) {
            $query = "UPDATE `glpi_entitydatas`\n                   SET `{$field_0}` = '-2'\n                   WHERE `{$field_0}` = '0'\n                         AND `entities_id` > 0";
            $DB->queryOrDie($query, "0.83 new value for inherit parent 0 in glpi_entitydatas");
        }
    }
    // new default value
    $migration->changeField("glpi_entitydatas", "calendars_id", "calendars_id", "int(11) NOT NULL DEFAULT '-2'");
    $migration->changeField("glpi_entitydatas", "tickettype", "tickettype", "int(11) NOT NULL DEFAULT '-2'");
    $migration->changeField("glpi_entitydatas", "inquest_config", "inquest_config", "int(11) NOT NULL DEFAULT '-2'");
    $migration->changeField("glpi_entitydatas", "inquest_rate", "inquest_rate", "int(11) NOT NULL DEFAULT '0'");
    $migration->changeField("glpi_entitydatas", "inquest_delay", "inquest_delay", "int(11) NOT NULL DEFAULT '-10'");
    // migration to new values for inherit parent (-1 => -2)
    $fieldparent = array('autofill_buy_date', 'autofill_delivery_date', 'autofill_warranty_date', 'autofill_order_date', 'autofill_use_date');
    foreach ($fieldparent as $field_parent) {
        if (FieldExists("glpi_entitydatas", $field_parent, false)) {
            $query = "UPDATE `glpi_entitydatas`\n                   SET `{$field_parent}` = '-2'\n                   WHERE `{$field_parent}` = '-1'";
            $DB->queryOrDie($query, "0.83 new value for inherit parent -1 in glpi_entitydatas");
        }
    }
    // new default value
    $migration->changeField("glpi_entitydatas", "autofill_buy_date", "autofill_buy_date", 'string', array('value' => '-2'));
    $migration->changeField("glpi_entitydatas", "autofill_delivery_date", "autofill_delivery_date", 'string', array('value' => '-2'));
    $migration->changeField("glpi_entitydatas", "autofill_warranty_date", "autofill_warranty_date", 'string', array('value' => '-2'));
    $migration->changeField("glpi_entitydatas", "autofill_order_date", "autofill_order_date", 'string', array('value' => '-2'));
    $migration->changeField("glpi_entitydatas", "autofill_use_date", "autofill_use_date", 'string', array('value' => '-2'));
    // migration to new values for inherit config
    $fieldconfig = array('auto_assign_mode', 'autoclose_delay', 'cartridges_alert_repeat', 'consumables_alert_repeat', 'notclosed_delay', 'use_contracts_alert', 'use_infocoms_alert', 'use_licenses_alert', 'use_reservations_alert');
    $query = "SELECT *\n             FROM `glpi_configs`";
    if ($result = $DB->query($query)) {
        if ($DB->numrows($result) > 0) {
            if ($data = $DB->fetch_assoc($result)) {
                foreach ($fieldconfig as $field_config) {
                    if (FieldExists("glpi_entitydatas", $field_config, false) && FieldExists("glpi_configs", $field_config, false)) {
                        // value of general config
                        $query = "UPDATE `glpi_entitydatas`\n                            SET `{$field_config}` = '" . $data[$field_config] . "'\n                            WHERE `{$field_config}` = -1";
                        $DB->queryOrDie($query, "0.83 migrate data from config to glpi_entitydatas");
                        $migration->changeField("glpi_entitydatas", "{$field_config}", "{$field_config}", "int(11) NOT NULL DEFAULT '-2'");
                        $migration->dropField("glpi_configs", $field_config);
                    }
                }
                if (FieldExists("glpi_entitydatas", "auto_assign_mode", false)) {
                    // new value for never
                    $query = "UPDATE `glpi_entitydatas`\n                         SET `auto_assign_mode` = -10\n                         WHERE `auto_assign_mode` = 0";
                    $DB->queryOrDie($query, "0.83 change value Never in glpi_entitydatas for auto_assign_mode");
                }
            }
        }
    }
    // value of config in each entity
    $fieldconfig = array('default_contract_alert', 'default_infocom_alert', 'default_alarm_threshold');
    $query = "SELECT *\n             FROM `glpi_configs`";
    if ($result = $DB->query($query)) {
        if ($DB->numrows($result) > 0) {
            if ($data = $DB->fetch_assoc($result)) {
                foreach ($fieldconfig as $field_config) {
                    if (FieldExists("glpi_configs", $field_config, false) && !FieldExists("glpi_entitydatas", $field_config, false)) {
                        // add config fields in entitydatas
                        $migration->addField("glpi_entitydatas", $field_config, 'integer', array('update' => $data[$field_config], 'value' => $field_config == "default_alarm_threshold" ? 10 : 0));
                        $migration->dropField("glpi_configs", $field_config);
                    }
                }
            }
        }
    }
    if ($restore_root_entity_value) {
        $query = "UPDATE `glpi_entitydatas`\n                SET `calendars_id` = 0\n                WHERE `entities_id` = 0;";
        $DB->queryOrDie($query, "0.83 restore root entity default value");
    }
    $migration->addKey('glpi_computervirtualmachines', 'computers_id');
    $migration->addKey('glpi_computervirtualmachines', 'entities_id');
    $migration->addKey('glpi_computervirtualmachines', 'name');
    $migration->addKey('glpi_computervirtualmachines', 'virtualmachinestates_id');
    $migration->addKey('glpi_computervirtualmachines', 'virtualmachinesystems_id');
    $migration->addKey('glpi_computervirtualmachines', 'vcpu');
    $migration->addKey('glpi_computervirtualmachines', 'ram');
    //   $ADDTODISPLAYPREF['KnowbaseItem'] = array(2,3,4,5,6,7);
    $renametables = array('TicketSolutionType' => 'SolutionType', 'TicketSolutionTemplate' => 'SolutionTemplate', 'TicketCategory' => 'ITILCategory');
    $itemtype_tables = array("glpi_bookmarks" => 'itemtype', "glpi_bookmarks_users" => 'itemtype', "glpi_displaypreferences" => 'itemtype', "glpi_logs" => 'itemtype', "glpi_events" => 'type');
    foreach ($itemtype_tables as $table => $field) {
        foreach ($renametables as $key => $val) {
            $query = "UPDATE `{$table}`\n                      SET `{$field}` = '" . $val . "'\n                      WHERE `{$field}` = '" . $key . "'";
            $DB->queryOrDie($query, "0.83 update itemtype of table {$table} for {$val}");
        }
    }
    // ************ Keep it at the end **************
    $migration->displayMessage(sprintf(__('Data migration - %s'), 'glpi_displaypreferences'));
    // Change is_recursive index
    $query = "UPDATE `glpi_displaypreferences`\n              SET `num` = '86'\n              WHERE `itemtype` = 'Group'\n                    AND `num` = '6'";
    $DB->query($query);
    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);
                }
            }
        }
    }
    // must always be at the end
    $migration->executeMigration();
    return $updateresult;
}