Example #1
0
function update0712to0713()
{
    global $DB, $CFG_GLPI;
    if (!FieldExists("glpi_rule_cache_software", "ignore_ocs_import", false)) {
        $query = "ALTER TABLE `glpi_rule_cache_software`\n                ADD `ignore_ocs_import` VARCHAR( 255 ) NULL ";
        $DB->queryOrDie($query, "0.71.3 add ignore_ocs_import field in dictionnary cache");
    }
    // Update to longtext for fields which may be very long
    if (FieldExists("glpi_kbitems", "answer", false)) {
        if (isIndex("glpi_kbitems", "fulltext")) {
            // to avoid pb in altering column answer
            $query = "ALTER TABLE `glpi_kbitems`\n                   DROP INDEX `fulltext`";
            $DB->queryOrDie($query, "0.71.3 alter kbitem drop index Fulltext");
        }
        // field question : only to change latin1 to utf-8 if not done in update 0.68.3 to 0.71
        // before creating index fulltext based on 2 fields (perhaps both are not in same encoding)
        $query = "ALTER TABLE `glpi_kbitems`\n                CHANGE `question` `question` TEXT,\n                CHANGE `answer` `answer` LONGTEXT NULL DEFAULT NULL ";
        $DB->queryOrDie($query, "0.71.3 alter kbitem answer field to longtext");
        $query = "ALTER TABLE `glpi_kbitems`\n                ADD FULLTEXT `fulltext` (`question`,`answer`)";
        $DB->queryOrDie($query, "0.71.3 alter kbitem re-add index Fulltext");
    }
    if (FieldExists("glpi_tracking", "contents", false)) {
        $query = "ALTER TABLE `glpi_tracking`\n                CHANGE `contents` `contents` LONGTEXT NULL DEFAULT NULL ";
        $DB->queryOrDie($query, "0.71.3 alter tracking contents field to longtext");
    }
}
function update072to0721()
{
    global $DB, $CFG_GLPI, $LANG;
    echo "<h3>" . $LANG['install'][4] . " -&gt; 0.72.1</h3>";
    displayMigrationMessage("0721");
    // Start
    if (!isIndex("glpi_groups", "ldap_group_dn")) {
        $query = "ALTER TABLE `glpi_groups` ADD INDEX `ldap_group_dn` ( `ldap_group_dn` );";
        $DB->query($query) or die("0.72.1 add index on ldap_group_dn in glpi_groups" . $LANG['update'][140] . $DB->error());
    }
    if (!isIndex("glpi_groups", "ldap_value")) {
        $query = "ALTER TABLE `glpi_groups` ADD INDEX `ldap_value`  ( `ldap_value` );";
        $DB->query($query) or die("0.72.1 add index on ldap_value in glpi_groups" . $LANG['update'][140] . $DB->error());
    }
    if (!isIndex('glpi_tracking', 'date_mod')) {
        $query = " ALTER TABLE `glpi_tracking` ADD INDEX `date_mod` (`date_mod`)  ";
        $DB->query($query) or die("0.72.1 add date_mod index in glpi_tracking " . $LANG['update'][90] . $DB->error());
    }
    // Display "Work ended." message - Keep this as the last action.
    displayMigrationMessage("0721");
    // End
}
Example #3
0
function update072to0721()
{
    global $DB, $CFG_GLPI;
    //TRANS: %s is the number of new version
    echo "<h3>" . sprintf(__('Update to %s'), '0.72.1') . "</h3>";
    displayMigrationMessage("0721");
    // Start
    if (!isIndex("glpi_groups", "ldap_group_dn")) {
        $query = "ALTER TABLE `glpi_groups` ADD INDEX `ldap_group_dn` ( `ldap_group_dn` );";
        $DB->query($query, "0.72.1 add index on ldap_group_dn in glpi_groups");
    }
    if (!isIndex("glpi_groups", "ldap_value")) {
        $query = "ALTER TABLE `glpi_groups` ADD INDEX `ldap_value`  ( `ldap_value` );";
        $DB->query($query, "0.72.1 add index on ldap_value in glpi_groups");
    }
    if (!isIndex('glpi_tracking', 'date_mod')) {
        $query = " ALTER TABLE `glpi_tracking` ADD INDEX `date_mod` (`date_mod`)  ";
        $DB->query($query, "0.72.1 add date_mod index in glpi_tracking");
    }
    // Display "Work ended." message - Keep this as the last action.
    displayMigrationMessage("0721");
    // End
}
function update0712to0713()
{
    global $DB, $CFG_GLPI, $LANG;
    if (!FieldExists("glpi_rule_cache_software", "ignore_ocs_import")) {
        $query = "ALTER TABLE `glpi_rule_cache_software` ADD `ignore_ocs_import` VARCHAR( 255 ) NULL ;";
        $DB->query($query) or die("0.71.3 add ignore_ocs_import field in dictionnary cache " . $LANG['update'][90] . $DB->error());
    }
    // Update to longtext for fields which may be very long
    if (FieldExists("glpi_kbitems", "answer")) {
        if (isIndex("glpi_kbitems", "fulltext")) {
            // to avoid pb in altering column answer
            $query = "ALTER TABLE `glpi_kbitems` DROP INDEX `fulltext`";
            $DB->query($query) or die("0.71.3 alter kbitem drop index Fulltext " . $LANG['update'][90] . $DB->error());
        }
        $query = "ALTER TABLE `glpi_kbitems` CHANGE `answer` `answer` LONGTEXT NULL DEFAULT NULL  ";
        $DB->query($query) or die("0.71.3 alter kbitem answer field to longtext " . $LANG['update'][90] . $DB->error());
        $query = "ALTER TABLE `glpi_kbitems` ADD FULLTEXT `fulltext` (`question`,`answer`)";
        $DB->query($query) or die("0.71.3 alter kbitem re-add index Fulltext " . $LANG['update'][90] . $DB->error());
    }
    if (FieldExists("glpi_tracking", "contents")) {
        $query = "ALTER TABLE `glpi_tracking` CHANGE `contents` `contents` LONGTEXT NULL DEFAULT NULL  ";
        $DB->query($query) or die("0.71.3 alter tracking contents field to longtext " . $LANG['update'][90] . $DB->error());
    }
}
Example #5
0
                            </div>
                        <?php 
    }
    ?>
                        <div class="filter-block ">
                            <a class="show-hide-filters" href="javascript:void(0);">Показать/скрыть фильтры</a>
                            <?php 
    filterCatalog();
    ?>
                        </div>
                    </div>
                <?php 
}
?>
                <?php 
if (!isIndex()) {
    ?>
                    <div class="main-block">
                        <?php 
    if (isCatalog() && !isSearch()) {
        ?>
                            <!--Вывод аякс поиска-->
                            <?php 
        layout('search');
        ?>
                            <!--/Вывод аякс поиска-->
                        <?php 
    }
    ?>
                        <?php 
    layout('content');
function update042to05()
{
    global $DB;
    echo "<p class='center'>Version 0.5 </p>";
    // Augmentation taille itemtype
    $query = "ALTER TABLE `glpi_event_log`\n             CHANGE `itemtype` `itemtype` VARCHAR(20) NOT NULL";
    $DB->queryOrDie($query, "4204");
    // Correction des itemtype tronque
    $query = "UPDATE `glpi_event_log`\n             SET `itemtype` = 'reservation'\n             WHERE `itemtype` = 'reservatio'";
    $DB->queryOrDie($query, "4204");
    /*******************************GLPI 0.5***********************************************/
    //pass all templates to computers
    if (!FieldExists("glpi_computers", "is_template", false)) {
        $query = "ALTER TABLE `glpi_computers`\n                ADD `is_template` ENUM('0','1') DEFAULT '0' NOT NULL ";
        $DB->queryOrDie($query, "0.5 alter computers add is_template");
        $query = "ALTER TABLE `glpi_computers`\n                ADD `tplname` VARCHAR(200) DEFAULT NULL ";
        $DB->queryOrDie($query, "0.5 alter computers add tplname");
        $query = "SELECT *\n                FROM `glpi_templates`";
        $result = $DB->query($query);
        while ($line = $DB->fetch_array($result)) {
            $line = Toolbox::addslashes_deep($line);
            $query2 = "INSERT INTO `glpi_computers`\n                        (`name`, `osver`, `processor_speed`, `serial`, `otherserial`, `ram`,\n                         `hdspace`, `contact`, `contact_num`, `comments`, `achat_date`,\n                         `date_fin_garantie`, `maintenance`, `os`, `hdtype`, `sndcard`, `moboard`,\n                         `gfxcard`, `network`, `ramtype`, `location`, `processor`, `type`,\n                         `is_template`, `tplname`)";
            if (empty($line["location"])) {
                $line["location"] = 0;
            }
            $query2 .= " VALUES ('" . $line["name"] . "', '" . $line["osver"] . "',\n                              '" . $line["processor_speed"] . "', '" . $line["serial"] . "',\n                              '" . $line["otherserial"] . "', '" . $line["ram"] . "',\n                              '" . $line["hdspace"] . "', '" . $line["contact"] . "',\n                              '" . $line["contact_num"] . "', '" . $line["comments"] . "',\n                              '" . $line["achat_date"] . "', '" . $line["date_fin_garantie"] . "',\n                              '" . $line["maintenance"] . "', '" . $line["os"] . "', '" . $line["hdtype"] . "',\n                              '" . $line["sndcard"] . "', '" . $line["moboard"] . "', '" . $line["gfxcard"] . "',\n                              '" . $line["network"] . "', '" . $line["ramtype"] . "',\n                              '" . $line["location"] . "', '" . $line["processor"] . "', '" . $line["type"] . "',\n                              '1', '" . $line["templname"] . "')";
            $DB->queryOrDie($query2, "0.5-convert template 2 computers");
        }
        $DB->free_result($result);
        $query = "DROP TABLE `glpi_templates`";
        $DB->queryOrDie($query, "0.5 drop table templates");
        $query = "SELECT `ID`\n                FROM `glpi_computers`\n                WHERE `tplname` = 'Blank Template'";
        $result = $DB->query($query);
        if ($DB->numrows($result) == 0) {
            $query = "INSERT INTO `glpi_computers`\n                          (`is_template`, `tplname`, `name`, `comment`, `contact`, `contact_num`,\n                           `serial`, `otherserial`)\n                   VALUES ('1', 'Blank Template', '', '', '', '', '', '')";
            $DB->queryOrDie($query, "0.5 add blank template");
        }
        $DB->free_result($result);
    }
    //New internal peripherals ( devices ) config
    if (!TableExists("glpi_computer_device")) {
        $query = "CREATE TABLE `glpi_computer_device` (\n                  `ID` int(11) NOT NULL auto_increment,\n                  `specificity` varchar(250) NOT NULL default '',\n                  `device_type` tinyint(4) NOT NULL default '0',\n                  `FK_device` int(11) NOT NULL default '0',\n                  `FK_computers` int(11) NOT NULL default '0',\n                  PRIMARY KEY  (`ID`),\n                  KEY (`device_type`),\n                  KEY (`device_type`,`FK_device`),\n                  KEY (`FK_computers`)\n               ) TYPE=MyISAM;";
        $DB->queryOrDie($query, "0.5 CREATE TABLE `glpi_computer_device`");
    }
    if (!TableExists("glpi_device_gfxcard")) {
        $query = "CREATE TABLE `glpi_device_gfxcard` (\n                  `ID` int(11) NOT NULL auto_increment,\n                  `designation` varchar(120) NOT NULL default '',\n                  `ram` varchar(10) NOT NULL default '',\n                  `interface` enum('AGP','PCI','PCI-X','Other') NOT NULL default 'AGP',\n                  `comment` text NOT NULL,\n                  `FK_glpi_enterprise` int(11) NOT NULL default '0',\n                  `specif_default` VARCHAR(250) NOT NULL,\n                  PRIMARY KEY  (`ID`),\n                  KEY (`FK_glpi_enterprise`)\n                ) TYPE=MyISAM;";
        $DB->queryOrDie($query, "0.5 create table `glpi_device_gfxcard`");
        compDpd2Device(GFX_DEVICE, "gfxcard", "gfxcard", "gfxcard");
    }
    if (!TableExists("glpi_device_hdd")) {
        $query = "CREATE TABLE `glpi_device_hdd` (\n                  `ID` int(11) NOT NULL auto_increment,\n                  `designation` varchar(100) NOT NULL default '',\n                  `rpm` varchar(20) NOT NULL default '',\n                  `interface` enum('IDE','SATA','SCSI') NOT NULL default 'IDE',\n                  `cache` varchar(20) NOT NULL default '',\n                  `comment` text NOT NULL,\n                  `FK_glpi_enterprise` int(11) NOT NULL default '0',\n                  `specif_default` VARCHAR(250) NOT NULL,\n                  PRIMARY KEY  (`ID`),\n                  KEY (`FK_glpi_enterprise`)\n                ) TYPE=MyISAM";
        $DB->queryOrDie($query, "0.5 CREATE TABLE `glpi_device_hdtype`");
        compDpd2Device(HDD_DEVICE, "hdd", "hdtype", "hdtype", "hdspace");
    }
    if (!TableExists("glpi_device_iface")) {
        $query = "CREATE TABLE `glpi_device_iface` (\n                  `ID` int(11) NOT NULL auto_increment,\n                  `designation` varchar(120) NOT NULL default '',\n                  `bandwidth` varchar(20) NOT NULL default '',\n                  `comment` text NOT NULL,\n                  `FK_glpi_enterprise` int(11) NOT NULL default '0',\n                  `specif_default` VARCHAR(250) NOT NULL,\n                  PRIMARY KEY  (`ID`),\n                  KEY (`FK_glpi_enterprise`)\n                ) TYPE=MyISAM";
        $DB->queryOrDie($query, "0.5- CREATE TABLE `glpi_device_iface`");
        compDpd2Device(NETWORK_DEVICE, "iface", "network", "network");
    }
    if (!TableExists("glpi_device_moboard")) {
        $query = "CREATE TABLE `glpi_device_moboard` (\n                  `ID` int(11) NOT NULL auto_increment,\n                  `designation` varchar(100) NOT NULL default '',\n                  `chipset` varchar(120) NOT NULL default '',\n                  `comment` text NOT NULL,\n                  `FK_glpi_enterprise` int(11) NOT NULL default '0',\n                  `specif_default` VARCHAR(250) NOT NULL,\n                  PRIMARY KEY  (`ID`),\n                  KEY (`FK_glpi_enterprise`)\n                ) TYPE=MyISAM";
        $DB->queryOrDie($query, "0.5 CREATE TABLE `glpi_device_moboard`");
        compDpd2Device(MOBOARD_DEVICE, "moboard", "moboard", "moboard");
    }
    if (!TableExists("glpi_device_processor")) {
        $query = "CREATE TABLE `glpi_device_processor` (\n                  `ID` int(11) NOT NULL auto_increment,\n                  `designation` varchar(120) NOT NULL default '',\n                  `frequence` int(11) NOT NULL default '0',\n                  `comment` text NOT NULL,\n                  `FK_glpi_enterprise` int(11) NOT NULL default '0',\n                  `specif_default` VARCHAR(250) NOT NULL,\n                  PRIMARY KEY  (`ID`),\n                  KEY (`FK_glpi_enterprise`)\n                ) TYPE=MyISAM";
        $DB->queryOrDie($query, "0.5 CREATE TABLE `glpi_device_processor`");
        compDpd2Device(PROCESSOR_DEVICE, "processor", "processor", "processor", "processor_speed");
    }
    if (!TableExists("glpi_device_ram")) {
        $query = "CREATE TABLE `glpi_device_ram` (\n                  `ID` int(11) NOT NULL auto_increment,\n                  `designation` varchar(100) NOT NULL default '',\n                  `type` enum('EDO','DDR','SDRAM','SDRAM-2') NOT NULL default 'EDO',\n                  `frequence` varchar(8) NOT NULL default '',\n                  `comment` text NOT NULL,\n                  `FK_glpi_enterprise` int(11) NOT NULL default '0',\n                  `specif_default` VARCHAR(250) NOT NULL,\n                  PRIMARY KEY  (`ID`),\n                  KEY (`FK_glpi_enterprise`)\n                ) TYPE=MyISAM";
        $DB->queryOrDie($query, "0.5 CREATE TABLE `glpi_device_ram`");
        compDpd2Device(RAM_DEVICE, "ram", "ram", "ramtype", "ram");
    }
    if (!TableExists("glpi_device_sndcard")) {
        $query = "CREATE TABLE `glpi_device_sndcard` (\n                  `ID` int(11) NOT NULL auto_increment,\n                  `designation` varchar(120) NOT NULL default '',\n                  `type` varchar(100) NOT NULL default '',\n                  `comment` text NOT NULL,\n                  `FK_glpi_enterprise` int(11) NOT NULL default '0',\n                  `specif_default` VARCHAR(250) NOT NULL,\n                  PRIMARY KEY  (`ID`),\n                  KEY (`FK_glpi_enterprise`)\n                ) TYPE=MyISAM";
        $DB->queryOrDie($query, "0.5 CREATE TABLE `glpi_device_sndcard");
        compDpd2Device(SND_DEVICE, "sndcard", "sndcard", "sndcard");
    }
    if (!TableExists("glpi_device_power")) {
        $query = "CREATE TABLE glpi_device_power (\n                  `ID` int(11) NOT NULL auto_increment,\n                  `designation` VARCHAR(255) NOT NULL default '',\n                  `power` VARCHAR(20) NOT NULL default '',\n                  `atx` enum('Y','N') NOT NULL default 'Y',\n                  `comment` text NOT NULL,\n                  `FK_glpi_enterprise` int(11) NOT NULL default '0',\n                  `specif_default` VARCHAR(250) NOT NULL,\n                  PRIMARY KEY (`ID`),\n                  KEY FK_glpi_enterprise (`FK_glpi_enterprise`)\n                ) TYPE=MyISAM";
        $DB->queryOrDie($query);
    }
    if (!TableExists("glpi_device_case")) {
        $query = "CREATE TABLE glpi_device_case(\n                  `ID` int(11) NOT NULL AUTO_INCREMENT ,\n                  `designation` VARCHAR(255) NOT NULL default '',\n                  `format` enum('Grand', 'Moyen', 'Micro') NOT NULL default 'Moyen',\n                  `comment` text NOT NULL ,\n                  `FK_glpi_enterprise` int(11) NOT NULL default '0',\n                  `specif_default` VARCHAR(250) NOT NULL,\n                  PRIMARY KEY (`ID`) ,\n                  KEY FK_glpi_enterprise(`FK_glpi_enterprise`)\n                ) TYPE = MyISAM";
        $DB->queryOrDie($query);
    }
    if (!TableExists("glpi_device_drive")) {
        $query = "CREATE TABLE `glpi_device_drive` (\n                  `ID` INT NOT NULL AUTO_INCREMENT ,\n                  `designation` VARCHAR(255) NOT NULL ,\n                  `is_writer` ENUM('Y', 'N') DEFAULT 'Y' NOT NULL ,\n                  `speed` VARCHAR(30) NOT NULL ,\n                  `interface` ENUM('IDE', 'SATA', 'SCSI') NOT NULL ,\n                  `comment` TEXT NOT NULL ,\n                  `FK_glpi_enterprise` INT NOT NULL ,\n                  `specif_default` VARCHAR(250) NOT NULL,\n                  KEY FK_glpi_enterprise(`FK_glpi_enterprise`),\n                  PRIMARY KEY (`ID`)\n                ) TYPE=MyISAM";
        $DB->queryOrDie($query);
    }
    if (!TableExists("glpi_device_pci")) {
        $query = "CREATE TABLE glpi_device_pci (\n                  `ID` int(11) NOT NULL auto_increment,\n                  `designation` VARCHAR(255) NOT NULL default '',\n                  `comment` text NOT NULL,\n                  `FK_glpi_enterprise` int(11) NOT NULL default '0',\n                  `specif_default` VARCHAR(250) NOT NULL,\n                  PRIMARY KEY (`ID`),\n                  KEY FK_glpi_enterprise (`FK_glpi_enterprise`)\n                ) TYPE=MyISAM";
        $DB->queryOrDie($query);
    }
    if (!TableExists("glpi_device_control")) {
        $query = "CREATE TABLE glpi_device_control (\n                  `ID` int(11) NOT NULL auto_increment,\n                  `designation` VARCHAR(255) NOT NULL default '',\n                  `interface` enum('IDE','SATA','SCSI','USB') NOT NULL default 'IDE',\n                  `raid` enum('Y','N') NOT NULL default 'Y',\n                  `comment` text NOT NULL,\n                  `FK_glpi_enterprise` int(11) NOT NULL default '0',\n                  `specif_default` VARCHAR(250) NOT NULL,\n                  PRIMARY KEY (`ID`),\n                  KEY FK_glpi_enterprise (`FK_glpi_enterprise`)\n                ) TYPE=MyISAM";
        $DB->queryOrDie($query);
    }
    // END new internal devices.
    if (!TableExists("glpi_enterprises")) {
        $query = "CREATE TABLE `glpi_enterprises` (\n                  `ID` int(11) NOT NULL auto_increment,\n                  `name` varchar(50) NOT NULL default '',\n                  `type` int(11) NOT NULL default '0',\n                  `address` text NOT NULL,\n                  `website` varchar(100) NOT NULL default '',\n                  `phonenumber` varchar(20) NOT NULL default '',\n                  `comments` text NOT NULL,\n                  `deleted` enum('Y','N') NOT NULL default 'N',\n                  PRIMARY KEY  (`ID`),\n                  KEY `deleted` (`deleted`),\n                  KEY `type` (`type`)\n                ) TYPE=MyISAM";
        $DB->queryOrDie($query, "0.5 CREATE TABLE `glpi_enterprise");
    }
    /// Base connaissance
    if (!TableExists("glpi_dropdown_kbcategories")) {
        $query = "CREATE TABLE `glpi_dropdown_kbcategories` (\n                  `ID` int(11) NOT NULL auto_increment,\n                  `parentID` int(11) NOT NULL default '0',\n                  `name` varchar(255) NOT NULL,\n                  PRIMARY KEY  (`ID`),\n                  KEY (`parentID`),\n                  UNIQUE KEY (`parentID`, `name`)\n                ) TYPE=MyISAM";
        $DB->queryOrDie($query, "0.5 CREATE TABLE `glpi_dropdown_kbcategories");
        $query = "CREATE TABLE `glpi_kbitems` (\n                  `ID` int(11) NOT NULL auto_increment,\n                  `categoryID` int(11) NOT NULL default '0',\n                  `question` text NOT NULL,\n                  `answer` text NOT NULL,\n                  `faq` enum('yes','no') NOT NULL default 'no',\n                  PRIMARY KEY  (`ID`),\n                  KEY (`categoryID`)\n                ) TYPE=MyISAM";
        $DB->queryOrDie($query, "0.5 CREATE TABLE `glpi_kbitems");
    }
    // Comment reservation
    if (!FieldExists("glpi_reservation_resa", "comment", false)) {
        $query = "ALTER TABLE `glpi_reservation_resa`\n                ADD `comment` VARCHAR(255) NOT NULL ";
        $DB->queryOrDie($query, "0.5 alter reservation add comment");
    }
    // Tracking categorie
    if (!TableExists("glpi_dropdown_tracking_category")) {
        $query = "CREATE TABLE `glpi_dropdown_tracking_category` (\n                  `ID` int(11) NOT NULL auto_increment,\n                  `name` varchar(255) default NULL,\n                  PRIMARY KEY  (`ID`)\n                ) TYPE=MyISAM";
        $DB->queryOrDie($query, "0.5 CREATE TABLE `glpi_dropdown_tracking_category");
    }
    if (!FieldExists("glpi_tracking", "category", false)) {
        $query = "ALTER TABLE `glpi_tracking`\n               ADD `category` INT(11) ";
        $DB->queryOrDie($query, "0.5 alter tracking add categorie");
    }
    // Nouvelle gestion des software et licenses
    if (!FieldExists("glpi_licenses", "oem", false)) {
        $query = "ALTER TABLE `glpi_licenses`\n                ADD `oem` ENUM('N', 'Y') DEFAULT 'N' NOT NULL ,\n                ADD `oem_computer` INT(11) NOT NULL,\n                ADD `buy` ENUM('Y', 'N') DEFAULT 'Y' NOT NULL";
        $DB->queryOrDie($query, "0.5 alter licenses add oem + buy");
        $query = "ALTER TABLE `glpi_software`\n                ADD `is_update` ENUM('N', 'Y') DEFAULT 'N' NOT NULL ,\n                ADD `update_software` INT(11) NOT NULL DEFAULT '-1'";
        $DB->queryOrDie($query, "0.5 alter software add update");
    }
    // Couleur pour les priorites
    if (!FieldExists("glpi_config", "priority_1", false)) {
        $query = "ALTER TABLE `glpi_config`\n                ADD `priority_1` VARCHAR(200) DEFAULT '#fff2f2' NOT NULL,\n                ADD `priority_2` VARCHAR(200) DEFAULT '#ffe0e0' NOT NULL,\n                ADD `priority_3` VARCHAR(200) DEFAULT '#ffcece' NOT NULL,\n                ADD `priority_4` VARCHAR(200) DEFAULT '#ffbfbf' NOT NULL,\n                ADD `priority_5` VARCHAR(200) DEFAULT '#ffadad' NOT NULL ";
        $DB->queryOrDie($query, "0.5 alter config add priority_X");
    }
    // Gestion des cartouches
    if (!TableExists("glpi_cartridges")) {
        $query = "CREATE TABLE `glpi_cartridges` (\n                  `ID` int(11) NOT NULL auto_increment,\n                  `FK_glpi_cartridges_type` int(11) NOT NULL default '0',\n                  `FK_glpi_printers` int(11) NOT NULL default '0',\n                  `date_in` date default NULL,\n                  `date_use` date default NULL,\n                  `date_out` date default NULL,\n                  `pages` int(11)  NOT NULL default '0',\n                  PRIMARY KEY  (`ID`),\n                  KEY (`FK_glpi_cartridges_type`),\n                  KEY (`FK_glpi_printers`)\n                ) TYPE=MyISAM";
        $DB->queryOrDie($query, "0.5 CREATE TABLE glpi_cartridges");
        $query = "CREATE TABLE `glpi_cartridges_type` (\n                  `ID` int(11) NOT NULL auto_increment,\n                  `name` varchar(255) NOT NULL default '',\n                  `ref` varchar(255) NOT NULL default '',\n                  `location` int(11) NOT NULL default '0',\n                  `type` tinyint(4) NOT NULL default '0',\n                  `FK_glpi_enterprise` int(11) NOT NULL default '0',\n                  `tech_num` int(11) default '0',\n                  `deleted` enum('Y','N') NOT NULL default 'N',\n                  `comments` text NOT NULL,\n                  PRIMARY KEY  (`ID`),\n                  KEY (`FK_glpi_enterprise`),\n                  KEY (`tech_num`),\n                  KEY (`deleted`)\n                ) TYPE=MyISAM";
        $DB->queryOrDie($query, "0.5 CREATE TABLE glpi_cartridges_type");
        $query = "CREATE TABLE `glpi_cartridges_assoc` (\n                  `ID` int(11) NOT NULL auto_increment,\n                  `FK_glpi_cartridges_type` int(11) NOT NULL default '0',\n                  `FK_glpi_type_printer` int(11) NOT NULL default '0',\n                  PRIMARY KEY  (`ID`),\n                  UNIQUE KEY `FK_glpi_type_printer` (`FK_glpi_type_printer`,`FK_glpi_cartridges_type`),\n                  KEY (`FK_glpi_cartridges_type`),\n                  KEY (`FK_glpi_type_printer`)\n                ) TYPE=MyISAM";
        $DB->queryOrDie($query, "0.5 CREATE TABLE glpi_cartridges_assoc");
    }
    //// DEBUT INSERTION PARTIE GESTION
    if (!TableExists("glpi_contracts")) {
        $query = "CREATE TABLE `glpi_contacts` (\n                  `ID` int(11) NOT NULL auto_increment,\n                  `name` varchar(255) NOT NULL default '',\n                  `phone` varchar(30) NOT NULL default '',\n                  `phone2` varchar(30) NOT NULL default '',\n                  `fax` varchar(30) NOT NULL default '',\n                  `email` varchar(255) NOT NULL default '',\n                  `type` tinyint(4) NOT NULL default '1',\n                  `comments` text NOT NULL,\n                  `deleted` enum('Y','N') NOT NULL default 'N',\n                  PRIMARY KEY  (`ID`)\n                ) TYPE=MyISAM";
        $DB->queryOrDie($query, "0.5 CREATE TABLE glpi_contact");
        $query = "CREATE TABLE `glpi_dropdown_enttype` (\n                  `ID` INT NOT NULL AUTO_INCREMENT ,\n                  `name` VARCHAR(255) NOT NULL ,\n                  PRIMARY KEY (`ID`)\n                )";
        $DB->queryOrDie($query, "23");
        $query = "CREATE TABLE `glpi_contact_enterprise` (\n                  `ID` int(11) NOT NULL auto_increment,\n                  `FK_enterprise` int(11) NOT NULL default '0',\n                  `FK_contact` int(11) NOT NULL default '0',\n                  PRIMARY KEY  (`ID`),\n                  UNIQUE KEY `FK_enterprise` (`FK_enterprise`,`FK_contact`),\n                  KEY (`FK_enterprise`),\n                  KEY (`FK_contact`)\n                ) TYPE=MyISAM";
        $DB->queryOrDie($query, "0.5 CREATE TABLE glpi_contact_enterprise");
        $query = "CREATE TABLE `glpi_contracts` (\n                  `ID` int(11) NOT NULL auto_increment,\n                  `name` varchar(255) NOT NULL default '',\n                  `num` varchar(255) NOT NULL default '',\n                  `cost` float NOT NULL default '0',\n                  `contract_type` int(11) NOT NULL default '0',\n                  `begin_date` date default NULL,\n                  `duration` tinyint(4) NOT NULL default '0',\n                  `notice` tinyint(4) NOT NULL default '0',\n                  `periodicity` tinyint(4) NOT NULL default '0',\n                  `facturation` tinyint(4) NOT NULL default '0',\n                  `bill_type` int(11) NOT NULL default '0',\n                  `comments` text NOT NULL,\n                  `compta_num` varchar(255) NOT NULL default '',\n                  `deleted` enum('Y','N') NOT NULL default 'N',\n                  `week_begin_hour` time NOT NULL default '00:00:00',\n                  `week_end_hour` time NOT NULL default '00:00:00',\n                  `saturday_begin_hour` time NOT NULL default '00:00:00',\n                  `saturday_end_hour` time NOT NULL default '00:00:00',\n                  `saturday` enum('Y','N') NOT NULL default 'N',\n                  `monday_begin_hour` time NOT NULL default '00:00:00',\n                  `monday_end_hour` time NOT NULL default '00:00:00',\n                  `monday` enum('Y','N') NOT NULL default 'N',\n                  PRIMARY KEY  (`ID`),\n                  KEY `contract_type` (`contract_type`),\n                  KEY `begin_date` (`begin_date`),\n                  KEY `bill_type` (`bill_type`)\n                ) TYPE=MyISAM";
        $DB->queryOrDie($query, "0.5 CREATE TABLE glpi_contract");
        $query = "CREATE TABLE `glpi_contract_device` (\n                  `ID` int(11) NOT NULL auto_increment,\n                  `FK_contract` int(11) NOT NULL default '0',\n                  `FK_device` int(11) NOT NULL default '0',\n                  `device_type` tinyint(4) NOT NULL default '0',\n                  PRIMARY KEY  (`ID`),\n                  UNIQUE KEY `FK_contract` (`FK_contract`,`FK_device`,`device_type`),\n                  KEY (`FK_contract`),\n                  KEY (`FK_device`,`device_type`)\n                ) TYPE=MyISAM";
        $DB->queryOrDie($query, "0.5 CREATE TABLE glpi_contract_device");
        $query = "CREATE TABLE `glpi_contract_enterprise` (\n                  `ID` int(11) NOT NULL auto_increment,\n                  `FK_enterprise` int(11) NOT NULL default '0',\n                  `FK_contract` int(11) NOT NULL default '0',\n                  PRIMARY KEY  (`ID`),\n                  UNIQUE KEY `FK_enterprise` (`FK_enterprise`,`FK_contract`),\n                  KEY (`FK_enterprise`),\n                  KEY (`FK_contract`)\n                ) TYPE=MyISAM";
        $DB->queryOrDie($query, "0.5 CREATE TABLE glpi_contrat_enterprise");
        $query = "CREATE TABLE `glpi_infocoms` (\n                  `ID` int(11) NOT NULL auto_increment,\n                  `FK_device` int(11) NOT NULL default '0',\n                  `device_type` tinyint(4) NOT NULL default '0',\n                  `buy_date` date NOT NULL default '0000-00-00',\n                  `use_date` date NOT NULL default '0000-00-00',\n                  `warranty_duration` tinyint(4) NOT NULL default '0',\n                  `warranty_info` varchar(255) NOT NULL default '',\n                  `FK_enterprise` int(11) default NULL,\n                  `num_commande` varchar(50) NOT NULL default '',\n                  `bon_livraison` varchar(50) NOT NULL default '',\n                  `num_immo` varchar(50) NOT NULL default '',\n                  `value` float NOT NULL default '0',\n                  `warranty_value` float default NULL,\n                  `amort_time` tinyint(4) NOT NULL default '0',\n                  `amort_type` varchar(20) NOT NULL default '',\n                  `amort_coeff` float NOT NULL default '0',\n                  `comments` text NOT NULL,\n                  PRIMARY KEY  (`ID`),\n                  UNIQUE KEY `FK_device` (`FK_device`,`device_type`),\n                  KEY `FK_enterprise` (`FK_enterprise`),\n                  KEY `buy_date` (`buy_date`)\n                ) TYPE=MyISAM";
        $DB->queryOrDie($query, "0.5 CREATE TABLE glpi_infocom");
        ///// Move warranty infos from item to infocoms.
        // Update Warranty Infos
        updateWarrantyInfos("glpi_computers", COMPUTER_TYPE);
        updateWarrantyInfos("glpi_printers", PRINTER_TYPE);
        updateWarrantyInfos("glpi_networking", NETWORKING_TYPE);
        updateWarrantyInfos("glpi_monitors", MONITOR_TYPE);
        updateWarrantyInfos("glpi_peripherals", PERIPHERAL_TYPE);
        // Update Maintenance Infos
        if (isMaintenanceUsed()) {
            $query = "INSERT INTO `glpi_contracts`\n                   VALUES (1, 'Maintenance', '', '0', 5, '2005-01-01', 120, 0, 0, 0, 0, '', '', 'N',\n                           '00:00:00', '00:00:00', '00:00:00', '00:00:00', 'N', '00:00:00',\n                           '00:00:00', 'N')";
            $result = $DB->queryOrDie($query, "0.5 insert_init for update maintenance");
            if ($result) {
                $query = "SELECT `ID`\n                      FROM `glpi_contracts`";
                $result = $DB->queryOrDie($query, "0.5 select_init for update maintenance");
                if ($result) {
                    $data = $DB->fetch_array($result);
                    $IDcontract = $data["ID"];
                    updateMaintenanceInfos("glpi_computers", COMPUTER_TYPE, $IDcontract);
                    updateMaintenanceInfos("glpi_printers", PRINTER_TYPE, $IDcontract);
                    updateMaintenanceInfos("glpi_networking", NETWORKING_TYPE, $IDcontract);
                    updateMaintenanceInfos("glpi_monitors", MONITOR_TYPE, $IDcontract);
                    updateMaintenanceInfos("glpi_peripherals", PERIPHERAL_TYPE, $IDcontract);
                }
            }
        } else {
            dropMaintenanceField();
        }
    }
    //// FIN INSERTION PARTIE GESTION
    // Merge de l'OS et de la version
    if (FieldExists("glpi_computers", "osver", false)) {
        // Recuperation des couples existants
        $query = "SELECT DISTINCT `glpi_computers`.`os` AS ID ,\n                                `glpi_computers`.`osver` AS VERS,\n                                `glpi_dropdown_os`.`name` AS NAME\n                FROM `glpi_computers`\n                LEFT JOIN `glpi_dropdown_os` ON `glpi_dropdown_os`.`ID` = `glpi_computers`.`os`\n                ORDER BY `glpi_computers`.`os`, `glpi_computers`.`osver`";
        $result = $DB->queryOrDie($query, "0.5 select for update OS");
        $valeur = array();
        $curros = -1;
        $currvers = "-------------------------";
        while ($data = $DB->fetch_array($result)) {
            // Nouvel OS -> update de l'element de dropdown
            if ($data["ID"] != $curros) {
                $curros = $data["ID"];
                if (!empty($data["VERS"])) {
                    $query_update = "UPDATE `glpi_dropdown_os`\n                                SET `name` = '" . $data["NAME"] . " - " . $data["VERS"] . "'\n                                WHERE `ID` = '" . $data["ID"] . "'";
                    $DB->queryOrDie($query_update, "0.5 update for update OS");
                }
            } else {
                // OS deja mis a jour -> creation d'un nouvel OS et mise a jour des elements
                $newname = $data["NAME"] . " - " . $data["VERS"];
                $query_insert = "INSERT INTO `glpi_dropdown_os`\n                                    (`name`)\n                             VALUES ('{$newname}')";
                $DB->queryOrDie($query_insert, "0.5 insert for update OS");
                $query_select = "SELECT `ID`\n                             FROM `glpi_dropdown_os`\n                             WHERE `name` = '{$newname}'";
                $res = $DB->queryOrDie($query_select, "0.5 select for update OS");
                if ($DB->numrows($res) == 1) {
                    $query_update = "UPDATE `glpi_computers`\n                                SET `os` . ='" . $DB->result($res, 0, "ID") . "'\n                                WHERE `os` = '" . $data["ID"] . "'\n                                      AND `osver` = '" . $data["VERS"] . "'";
                    $DB->queryOrDie($query_update, "0.5 update2 for update OS");
                }
            }
        }
        $DB->free_result($result);
        $query_alter = "ALTER TABLE `glpi_computers`\n                      DROP `osver` ";
        $DB->queryOrDie($query_alter, "0.5 alter for update OS");
    }
    // Ajout Fabriquant computer
    if (!FieldExists("glpi_computers", "FK_glpi_enterprise", false)) {
        $query = "ALTER TABLE `glpi_computers`\n                ADD `FK_glpi_enterprise` INT(11) DEFAULT '0' NOT NULL ";
        $DB->queryOrDie($query, "0.5 add field manufacturer");
        $query = "ALTER TABLE `glpi_computers`\n                ADD INDEX (`FK_glpi_enterprise`)";
        $DB->queryOrDie($query, "0.5 alter field manufacturer");
    }
    // Ajout Fabriquant printer
    if (!FieldExists("glpi_printers", "FK_glpi_enterprise", false)) {
        $query = "ALTER TABLE `glpi_printers`\n                ADD `FK_glpi_enterprise` INT(11) DEFAULT '0' NOT NULL ";
        $DB->queryOrDie($query, "0.5 add field manufacturer");
        $query = "ALTER TABLE `glpi_printers`\n                ADD INDEX (`FK_glpi_enterprise`)";
        $DB->queryOrDie($query, "0.5 alter field manufacturer");
    }
    // Ajout Fabriquant networking
    if (!FieldExists("glpi_networking", "FK_glpi_enterprise", false)) {
        $query = "ALTER TABLE `glpi_networking`\n                ADD `FK_glpi_enterprise` INT(11) DEFAULT '0' NOT NULL ";
        $DB->queryOrDie($query, "0.5 add field manufacturer");
        $query = "ALTER TABLE `glpi_networking`\n                ADD INDEX (`FK_glpi_enterprise`)";
        $DB->queryOrDie($query, "0.5 alter field manufacturer");
    }
    // Ajout Fabriquant monitor
    if (!FieldExists("glpi_monitors", "FK_glpi_enterprise", false)) {
        $query = "ALTER TABLE `glpi_monitors`\n                ADD `FK_glpi_enterprise` INT(11) DEFAULT '0' NOT NULL ";
        $DB->queryOrDie($query, "0.5 add field manufacturer");
        $query = "ALTER TABLE `glpi_monitors`\n                ADD INDEX (`FK_glpi_enterprise`)";
        $DB->queryOrDie($query, "0.5 alter field manufacturer");
    }
    // Ajout Fabriquant software
    if (!FieldExists("glpi_software", "FK_glpi_enterprise", false)) {
        $query = "ALTER TABLE `glpi_software`\n                ADD `FK_glpi_enterprise` INT(11) DEFAULT '0' NOT NULL ";
        $DB->queryOrDie($query, "0.5 add field manufacturer");
        $query = "ALTER TABLE `glpi_software`\n                ADD INDEX (`FK_glpi_enterprise`)";
        $DB->queryOrDie($query, "0.5 alter field manufacturer");
    }
    // Ajout Fabriquant peripheral
    if (!FieldExists("glpi_peripherals", "FK_glpi_enterprise", false)) {
        $query = "ALTER TABLE `glpi_peripherals`\n                ADD `FK_glpi_enterprise` INT(11) DEFAULT '0' NOT NULL ";
        $DB->queryOrDie($query, "0.5 add field manufacturer");
        $query = "ALTER TABLE `glpi_peripherals`\n                ADD INDEX (`FK_glpi_enterprise`)";
        $DB->queryOrDie($query, "0.5 alter field manufacturer");
    }
    // Ajout deleted peripheral
    if (!FieldExists("glpi_peripherals", "deleted", false)) {
        $query = "ALTER TABLE `glpi_peripherals`\n                ADD `deleted` ENUM('Y', 'N') DEFAULT 'N' NOT NULL ";
        $DB->queryOrDie($query, "0.5 add field deleted");
        $query = "ALTER TABLE `glpi_peripherals`\n                ADD INDEX (`deleted`)";
        $DB->queryOrDie($query, "0.5 alter field deleted");
    }
    // Ajout deleted software
    if (!FieldExists("glpi_software", "deleted", false)) {
        $query = "ALTER TABLE `glpi_software`\n                ADD `deleted` ENUM('Y', 'N') DEFAULT 'N' NOT NULL ";
        $DB->queryOrDie($query, "0.5 add field deleted");
        $query = "ALTER TABLE `glpi_software`\n                ADD INDEX (`deleted`)";
        $DB->queryOrDie($query, "0.5 alter field deleted");
    }
    // Ajout deleted monitor
    if (!FieldExists("glpi_monitors", "deleted", false)) {
        $query = "ALTER TABLE `glpi_monitors`\n                ADD `deleted` ENUM('Y', 'N') DEFAULT 'N' NOT NULL ";
        $DB->queryOrDie($query, "0.5 add field deleted");
        $query = "ALTER TABLE `glpi_monitors`\n                ADD INDEX (`deleted`)";
        $DB->queryOrDie($query, "0.5 alter field deleted");
    }
    // Ajout deleted networking
    if (!FieldExists("glpi_networking", "deleted", false)) {
        $query = "ALTER TABLE `glpi_networking`\n                ADD `deleted` ENUM('Y', 'N') DEFAULT 'N' NOT NULL ";
        $DB->queryOrDie($query, "0.5 add field deleted");
        $query = "ALTER TABLE `glpi_networking`\n                ADD INDEX (`deleted`)";
        $DB->queryOrDie($query, "0.5 alter field deleted");
    }
    // Ajout deleted printer
    if (!FieldExists("glpi_printers", "deleted", false)) {
        $query = "ALTER TABLE `glpi_printers`\n                ADD `deleted` ENUM('Y', 'N') DEFAULT 'N' NOT NULL ";
        $DB->queryOrDie($query, "0.5 add field deleted");
        $query = "ALTER TABLE `glpi_printers`\n                ADD INDEX (`deleted`)";
        $DB->queryOrDie($query, "0.5 alter field deleted");
    }
    // Ajout deleted computer
    if (!FieldExists("glpi_computers", "deleted", false)) {
        $query = "ALTER TABLE `glpi_computers`\n                ADD `deleted` ENUM('Y', 'N') DEFAULT 'N' NOT NULL ";
        $DB->queryOrDie($query, "0.5 add field deleted");
        $query = "ALTER TABLE `glpi_computers`\n                ADD INDEX (`deleted`)";
        $DB->queryOrDie($query, "0.5 alter field deleted");
    }
    // Ajout template peripheral
    if (!FieldExists("glpi_peripherals", "is_template", false)) {
        $query = "ALTER TABLE `glpi_peripherals`\n                ADD `is_template` ENUM('0', '1') DEFAULT '0' NOT NULL ,\n                ADD `tplname` VARCHAR(255) ";
        $DB->queryOrDie($query, "0.5 add field deleted");
        $query = "INSERT INTO `glpi_peripherals`\n                       (`is_template`, `tplname`, `name`, `contact`, `contact_num`, `comments`,\n                        `serial`, `otherserial`, `brand`)\n                VALUES ('1', 'Blank Template', '', '', '', '', '', '', '')";
        $DB->queryOrDie($query, "0.5 add blank template");
        $query = "ALTER TABLE `glpi_peripherals`\n                ADD INDEX (`is_template`)";
        $DB->queryOrDie($query, "0.5 alter field is_template");
    }
    // Ajout template software
    if (!FieldExists("glpi_software", "is_template", false)) {
        $query = "ALTER TABLE `glpi_software`\n                ADD `is_template` ENUM('0', '1') DEFAULT '0' NOT NULL ,\n                ADD `tplname` VARCHAR(255) ";
        $DB->queryOrDie($query, "0.5 add field deleted");
        $query = "INSERT INTO `glpi_software`\n                       (`is_template`, `tplname`, `name`, `comments`, `version`)\n                VALUES ('1', 'Blank Template', '', '', '')";
        $DB->queryOrDie($query, "0.5 add blank template");
        $query = "ALTER TABLE `glpi_software`\n                ADD INDEX (`is_template`)";
        $DB->queryOrDie($query, "0.5 alter field is_template");
    }
    // Ajout template monitor
    if (!FieldExists("glpi_monitors", "is_template", false)) {
        $query = "ALTER TABLE `glpi_monitors`\n                ADD `is_template` ENUM('0', '1') DEFAULT '0' NOT NULL ,\n                ADD `tplname` VARCHAR(255) ";
        $DB->queryOrDie($query, "0.5 add field deleted");
        $query = "INSERT INTO `glpi_monitors`\n                       (`is_template`, `tplname`, `name`, `contact`, `contact_num`, `comments`,\n                        `serial`, `otherserial`)\n                VALUES ('1', 'Blank Template', '', '', '', '', '', '')";
        $DB->queryOrDie($query, "0.5 add blank template");
        $query = "ALTER TABLE `glpi_monitors`\n                ADD INDEX (`is_template`)";
        $DB->queryOrDie($query, "0.5 alter field is_template");
    }
    if (!isIndex("glpi_computers", "is_template")) {
        $query = "ALTER TABLE `glpi_computers`\n                ADD INDEX (`is_template`) ";
        $DB->queryOrDie($query, "5");
    }
    // Ajout template networking
    if (!FieldExists("glpi_networking", "is_template", false)) {
        $query = "ALTER TABLE `glpi_networking`\n                ADD `is_template` ENUM('0', '1') DEFAULT '0' NOT NULL ,\n                ADD `tplname` VARCHAR(255) ";
        $DB->queryOrDie($query, "0.5 add field deleted");
        $query = "INSERT INTO `glpi_networking`\n                       (`is_template`, `tplname`, `name`, `contact`, `contact_num`, `comments`,\n                        `ram`, `otherserial`, `serial`)\n                VALUES ('1', 'Blank Template', '', '', '', '', '', '', '')";
        $DB->queryOrDie($query, "0.5 add blank template");
        $query = "ALTER TABLE `glpi_networking`\n                ADD INDEX (`is_template`)";
        $DB->queryOrDie($query, "0.5 alter field is_template");
    }
    // Ajout template printer
    if (!FieldExists("glpi_printers", "is_template", false)) {
        $query = "ALTER TABLE `glpi_printers`\n                ADD `is_template` ENUM('0', '1') DEFAULT '0' NOT NULL ,\n                ADD `tplname` VARCHAR(255) ";
        $DB->queryOrDie($query, "0.5 add field deleted");
        $query = "INSERT INTO `glpi_printers`\n                       (`is_template`, `tplname`, `name`, `contact`, `contact_num`, `comments`,\n                        `serial`, `otherserial`, `ramSize`)\n                VALUES ('1', 'Blank Template', '', '', '', '', '', '', '')";
        $DB->queryOrDie($query, "0.5 add blank template");
        $query = "ALTER TABLE `glpi_printers`\n                ADD INDEX (`is_template`)";
        $DB->queryOrDie($query, "0.5 alter field is_template");
    }
    // Ajout date_mod
    if (!FieldExists("glpi_printers", "date_mod", false)) {
        $query = "ALTER TABLE `glpi_printers`\n                ADD `date_mod` DATETIME DEFAULT NULL";
        $DB->queryOrDie($query);
        $query = "ALTER TABLE `glpi_printers`\n                ADD INDEX (`date_mod`)";
        $DB->queryOrDie($query, "0.5 alter field date_mod");
    }
    if (!isIndex("glpi_computers", "date_mod")) {
        $query = "ALTER TABLE `glpi_computers`\n                ADD INDEX (`date_mod`) ";
        $DB->queryOrDie($query, "5");
    }
    // Ajout date_mod
    if (!FieldExists("glpi_monitors", "date_mod", false)) {
        $query = "ALTER TABLE `glpi_monitors`\n                ADD `date_mod` DATETIME DEFAULT NULL";
        $DB->queryOrDie($query);
        $query = "ALTER TABLE `glpi_monitors`\n                ADD INDEX (`date_mod`)";
        $DB->queryOrDie($query, "0.5 alter field date_mod");
    }
    // Ajout date_mod
    if (!FieldExists("glpi_software", "date_mod", false)) {
        $query = "ALTER TABLE `glpi_software`\n                ADD `date_mod` DATETIME DEFAULT NULL";
        $DB->queryOrDie($query);
        $query = "ALTER TABLE `glpi_software`\n                ADD INDEX (`date_mod`)";
        $DB->queryOrDie($query, "0.5 alter field date_mod");
    }
    // Ajout date_mod
    if (!FieldExists("glpi_networking", "date_mod", false)) {
        $query = "ALTER TABLE `glpi_networking`\n                ADD `date_mod` DATETIME DEFAULT NULL";
        $DB->queryOrDie($query);
        $query = "ALTER TABLE `glpi_networking`\n                ADD INDEX (`date_mod`)";
        $DB->queryOrDie($query, "0.5 alter field date_mod");
    }
    // Ajout tech_num
    if (!FieldExists("glpi_computers", "tech_num", false)) {
        $query = "ALTER TABLE `glpi_computers`\n                ADD `tech_num` int(11) NOT NULL default '0' AFTER `contact_num`";
        $DB->queryOrDie($query);
        $query = "ALTER TABLE `glpi_computers`\n                ADD INDEX (`tech_num`)";
        $DB->queryOrDie($query, "0.5 alter field tech_num");
    }
    // Ajout tech_num
    if (!FieldExists("glpi_networking", "tech_num", false)) {
        $query = "ALTER TABLE `glpi_networking`\n                ADD `tech_num` int(11) NOT NULL default '0' AFTER `contact_num`";
        $DB->queryOrDie($query);
        $query = "ALTER TABLE `glpi_networking`\n                ADD INDEX (`tech_num`)";
        $DB->queryOrDie($query, "0.5 alter field tech_num");
    }
    // Ajout tech_num
    if (!FieldExists("glpi_printers", "tech_num", false)) {
        $query = "ALTER TABLE `glpi_printers`\n                ADD `tech_num` int(11) NOT NULL default '0' AFTER `contact_num`";
        $DB->queryOrDie($query);
        $query = "ALTER TABLE `glpi_printers`\n                ADD INDEX (`tech_num`)";
        $DB->queryOrDie($query, "0.5 alter field tech_num");
    }
    // Ajout tech_num
    if (!FieldExists("glpi_monitors", "tech_num", false)) {
        $query = "ALTER TABLE `glpi_monitors`\n                ADD `tech_num` int(11) NOT NULL default '0' AFTER `contact_num`";
        $DB->queryOrDie($query);
        $query = "ALTER TABLE `glpi_monitors`\n                ADD INDEX (`tech_num`)";
        $DB->queryOrDie($query, "0.5 alter field tech_num");
    }
    // Ajout tech_num
    if (!FieldExists("glpi_software", "tech_num", false)) {
        $query = "ALTER TABLE `glpi_software`\n                ADD `tech_num` int(11) NOT NULL default '0' AFTER `location`";
        $DB->queryOrDie($query);
        $query = "ALTER TABLE `glpi_software`\n                ADD INDEX (`tech_num`)";
        $DB->queryOrDie($query, "0.5 alter field tech_num");
    }
    // Ajout tech_num
    if (!FieldExists("glpi_peripherals", "tech_num", false)) {
        $query = "ALTER TABLE `glpi_peripherals`\n                ADD `tech_num` int(11) NOT NULL default '0' AFTER `contact_num`";
        $DB->queryOrDie($query);
        $query = "ALTER TABLE `glpi_peripherals`\n                ADD INDEX (`tech_num`)";
        $DB->queryOrDie($query, "0.5 alter field tech_num");
    }
    // Ajout tech_num
    if (!FieldExists("glpi_software", "tech_num", false)) {
        $query = "ALTER TABLE `glpi_software`\n                ADD `tech_num` int(11) NOT NULL default '0'";
        $DB->queryOrDie($query);
        $query = "ALTER TABLE `glpi_software` ADD INDEX (`tech_num`)";
        $DB->queryOrDie($query, "0.5 alter field tech_num");
    }
    // Ajout tech_num
    if (!TableExists("glpi_type_docs")) {
        $query = "CREATE TABLE glpi_type_docs (\n                  `ID` int(11) NOT NULL auto_increment,\n                  `name` varchar(255) NOT NULL default '',\n                  `ext` varchar(10) NOT NULL default '',\n                  `icon` varchar(255) NOT NULL default '',\n                  `mime` varchar(100) NOT NULL default '',\n                  `upload` enum('Y','N') NOT NULL default 'Y',\n                  `date_mod` datetime default NULL,\n                  PRIMARY KEY  (`ID`),\n                  UNIQUE KEY `extension` (`ext`),\n                  KEY (`upload`)\n                ) TYPE=MyISAM";
        $DB->queryOrDie($query, "Error creating table typedoc");
        $query = "INSERT INTO `glpi_type_docs`\n                       (`ID`, `name`, `ext`, `icon`, `mime`, `upload`, `date_mod`)\n                VALUES (1, 'JPEG', 'jpg', 'jpg-dist.png', '', 'Y', '2004-12-13 19:47:21'),\n                       (2, 'PNG', 'png', 'png-dist.png', '', 'Y', '2004-12-13 19:47:21'),\n                       (3, 'GIF', 'gif', 'gif-dist.png', '', 'Y', '2004-12-13 19:47:21'),\n                       (4, 'BMP', 'bmp', 'bmp-dist.png', '', 'Y', '2004-12-13 19:47:21'),\n                       (5, 'Photoshop', 'psd', 'psd-dist.png', '', 'Y', '2004-12-13 19:47:21'),\n                       (6, 'TIFF', 'tif', 'tif-dist.png', '', 'Y', '2004-12-13 19:47:21'),\n                       (7, 'AIFF', 'aiff', 'aiff-dist.png', '', 'Y', '2004-12-13 19:47:21'),\n                       (8, 'Windows Media', 'asf', 'asf-dist.png', '', 'Y', '2004-12-13 19:47:21'),\n                       (9, 'Windows Media', 'avi', 'avi-dist.png', '', 'Y', '2004-12-13 19:47:21'),\n                       (44, 'C source', 'c', '', '', 'Y', '2004-12-13 19:47:22'),\n                       (27, 'RealAudio', 'rm', 'rm-dist.png', '', 'Y', '2004-12-13 19:47:21'),\n                       (16, 'Midi', 'mid', 'mid-dist.png', '', 'Y', '2004-12-13 19:47:21'),\n                       (17, 'QuickTime', 'mov', 'mov-dist.png', '', 'Y', '2004-12-13 19:47:21'),\n                       (18, 'MP3', 'mp3', 'mp3-dist.png', '', 'Y', '2004-12-13 19:47:21'),\n                       (19, 'MPEG', 'mpg', 'mpg-dist.png', '', 'Y', '2004-12-13 19:47:21'),\n                       (20, 'Ogg Vorbis', 'ogg', 'ogg-dist.png', '', 'Y', '2004-12-13 19:47:21'),\n                       (24, 'QuickTime', 'qt', 'qt-dist.png', '', 'Y', '2004-12-13 19:47:21'),\n                       (10, 'BZip', 'bz2', 'bz2-dist.png', '', 'Y', '2004-12-13 19:47:21'),\n                       (25, 'RealAudio', 'ra', 'ra-dist.png', '', 'Y', '2004-12-13 19:47:21'),\n                       (26, 'RealAudio', 'ram', 'ram-dist.png', '', 'Y', '2004-12-13 19:47:21'),\n                       (11, 'Word', 'doc', 'doc-dist.png', '', 'Y', '2004-12-13 19:47:21'),\n                       (12, 'DjVu', 'djvu', '', '', 'Y', '2004-12-13 19:47:21'),\n                       (42, 'MNG', 'mng', '', '', 'Y', '2004-12-13 19:47:22'),\n                       (13, 'PostScript', 'eps', 'ps-dist.png', '', 'Y', '2004-12-13 19:47:21'),\n                       (14, 'GZ', 'gz', 'gz-dist.png', '', 'Y', '2004-12-13 19:47:21'),\n                       (37, 'WAV', 'wav', 'wav-dist.png', '', 'Y', '2004-12-13 19:47:22'),\n                       (15, 'HTML', 'html', 'html-dist.png', '', 'Y', '2004-12-13 19:47:21'),\n                       (34, 'Flash', 'swf', '', '', 'Y', '2004-12-13 19:47:22'),\n                       (21, 'PDF', 'pdf', 'pdf-dist.png', '', 'Y', '2004-12-13 19:47:21'),\n                       (22, 'PowerPoint', 'ppt', 'ppt-dist.png', '', 'Y', '2004-12-13 19:47:21'),\n                       (23, 'PostScript', 'ps', 'ps-dist.png', '', 'Y', '2004-12-13 19:47:21'),\n                       (40, 'Windows Media', 'wmv', '', '', 'Y', '2004-12-13 19:47:22'),\n                       (28, 'RTF', 'rtf', 'rtf-dist.png', '', 'Y', '2004-12-13 19:47:21'),\n                       (29, 'StarOffice', 'sdd', 'sdd-dist.png', '', 'Y', '2004-12-13 19:47:22'),\n                       (30, 'StarOffice', 'sdw', 'sdw-dist.png', '', 'Y', '2004-12-13 19:47:22'),\n                       (31, 'Stuffit', 'sit', 'sit-dist.png', '', 'Y', '2004-12-13 19:47:22'),\n                       (43, 'Adobe Illustrator', 'ai', 'ai-dist.png', '', 'Y', '2004-12-13 19:47:22'),\n                       (32, 'OpenOffice Impress', 'sxi', 'sxi-dist.png', '', 'Y', '2004-12-13 19:47:22'),\n                       (33, 'OpenOffice', 'sxw', 'sxw-dist.png', '', 'Y', '2004-12-13 19:47:22'),\n                       (46, 'DVI', 'dvi', 'dvi-dist.png', '', 'Y', '2004-12-13 19:47:22'),\n                       (35, 'TGZ', 'tgz', 'tgz-dist.png', '', 'Y', '2004-12-13 19:47:22'),\n                       (36, 'texte', 'txt', 'txt-dist.png', '', 'Y', '2004-12-13 19:47:22'),\n                       (49, 'RedHat/Mandrake/SuSE', 'rpm', 'rpm-dist.png', '', 'Y', '2004-12-13 19:47:22'),\n                       (38, 'Excel', 'xls', 'xls-dist.png', '', 'Y', '2004-12-13 19:47:22'),\n                       (39, 'XML', 'xml', 'xml-dist.png', '', 'Y', '2004-12-13 19:47:22'),\n                       (41, 'Zip', 'zip', 'zip-dist.png', '', 'Y', '2004-12-13 19:47:22'),\n                       (45, 'Debian', 'deb', 'deb-dist.png', '', 'Y', '2004-12-13 19:47:22'),\n                       (47, 'C header', 'h', '', '', 'Y', '2004-12-13 19:47:22'),\n                       (48, 'Pascal', 'pas', '', '', 'Y', '2004-12-13 19:47:22'),\n                       (50, 'OpenOffice Calc', 'sxc', 'sxc-dist.png', '', 'Y', '2004-12-13 19:47:22'),\n                       (51, 'LaTeX', 'tex', 'tex-dist.png', '', 'Y', '2004-12-13 19:47:22'),\n                       (52, 'GIMP multi-layer', 'xcf', 'xcf-dist.png', '', 'Y', '2004-12-13 19:47:22'),\n                       (53, 'JPEG', 'jpeg', 'jpg-dist.png', '', 'Y', '2005-03-07 22:23:17')";
        $DB->queryOrDie($query, "Error inserting elements in table typedoc");
    }
    if (!TableExists("glpi_docs")) {
        $query = "CREATE TABLE `glpi_docs` (\n                  `ID` int(11) NOT NULL auto_increment,\n                  `name` varchar(255) NOT NULL default '',\n                  `filename` varchar(255) NOT NULL default '',\n                  `rubrique` int(11) NOT NULL default '0',\n                  `mime` varchar(30) NOT NULL default '',\n                  `date_mod` datetime NOT NULL default '0000-00-00 00:00:00',\n                  `comment` text NOT NULL,\n                  `deleted` enum('Y','N') NOT NULL default 'N',\n                  PRIMARY KEY  (`ID`),\n                  KEY `rubrique` (`rubrique`),\n                  KEY `deleted` (`deleted`),\n                  KEY `date_mod` (`date_mod`)\n                ) TYPE=MyISAM";
        $DB->queryOrDie($query, "Error creating table docs");
    }
    if (!TableExists("glpi_doc_device")) {
        $query = "CREATE TABLE `glpi_doc_device` (\n                  `ID` int(11) NOT NULL auto_increment,\n                  `FK_doc` int(11) NOT NULL default '0',\n                  `FK_device` int(11) NOT NULL default '0',\n                  `device_type` tinyint(4) NOT NULL default '0',\n                  PRIMARY KEY  (`ID`),\n                  UNIQUE KEY `FK_doc` (`FK_doc`,`FK_device`,`device_type`),\n                  KEY FK_`doc_2` (`FK_doc`),\n                  KEY FK_`device` (`FK_device`,`device_type`)\n                ) TYPE=MyISAM";
        $DB->queryOrDie($query, "Error creating table docs");
    }
    if (!TableExists("glpi_dropdown_rubdocs")) {
        $query = "CREATE TABLE `glpi_dropdown_rubdocs` (\n                  `ID` int(11) NOT NULL auto_increment,\n                  `name` varchar(255) default NULL,\n                  PRIMARY KEY  (`ID`)\n                ) TYPE=MyISAM";
        $DB->queryOrDie($query, "Error creating table docs");
    }
    if (!isIndex("glpi_contacts", "deleted")) {
        $query = "ALTER TABLE `glpi_contacts`\n                ADD INDEX `deleted` (`deleted`) ";
        $DB->queryOrDie($query, "0.5 alter field deleted");
    }
    if (!isIndex("glpi_contacts", "type")) {
        $query = "ALTER TABLE `glpi_contacts`\n                ADD INDEX `type` (`type`) ";
        $DB->queryOrDie($query, "0.5 alter field type");
    }
    if (!isIndex("glpi_event_log", "itemtype")) {
        $query = "ALTER TABLE `glpi_event_log`\n                ADD INDEX (`itemtype`) ";
        $DB->queryOrDie($query, "0.5 alter field itemtype");
    }
    if (!isIndex("glpi_followups", "date")) {
        $query = "ALTER TABLE `glpi_followups`\n                ADD INDEX (`date`) ";
        $DB->queryOrDie($query, "0.5 alter field date");
    }
    if (!isIndex("glpi_tracking", "category")) {
        $query = "ALTER TABLE `glpi_tracking`\n                ADD INDEX (`category`) ";
        $DB->queryOrDie($query, "0.5 alter field category");
    }
    if (!FieldExists("glpi_config", "date_fiscale", false)) {
        $query = "ALTER TABLE `glpi_config`\n                ADD `date_fiscale` date NOT NULL default '2005-12-31'";
        $DB->queryOrDie($query, "0.5 add field date_fiscale");
    }
    if (!FieldExists("glpi_networking", "ifmac", false)) {
        $query = "ALTER TABLE `glpi_networking`\n                ADD `ifmac` char(30) NOT NULL default ''";
        $DB->queryOrDie($query, "0.5 add field ifmac");
    }
    if (!FieldExists("glpi_networking", "ifaddr", false)) {
        $query = "ALTER TABLE `glpi_networking`\n                ADD `ifaddr` char(30) NOT NULL default ''";
        $DB->queryOrDie($query, "0.5 add field ifaddr");
    }
    if (!TableExists("glpi_repair_item")) {
        $query = "CREATE TABLE `glpi_repair_item` (\n                  `ID` int(11) NOT NULL auto_increment,\n                  `device_type` tinyint(4) NOT NULL default '0',\n                  `id_device` int(11) NOT NULL default '0',\n                  PRIMARY KEY  (`ID`),\n                  KEY `device_type` (`device_type`),\n                  KEY `device_type_2` (`device_type`,`id_device`)\n                ) TYPE=MyISAM";
        $DB->queryOrDie($query, "0.5 create glpirepair_item table");
    }
    if (TableExists("glpi_prefs") && !FieldExists("glpi_prefs", "username", false)) {
        if (isIndex("glpi_prefs", "user")) {
            $query = " ALTER TABLE `glpi_prefs`\n                    DROP INDEX `user`";
            $DB->queryOrDie($query, "0.5 drop key user");
        }
        $query = " ALTER TABLE `glpi_prefs`\n                 CHANGE `user` `username` VARCHAR(80) NOT NULL";
        $DB->queryOrDie($query, "0.5 change user to username");
        $query = "ALTER TABLE `glpi_prefs`\n                ADD UNIQUE (`username`) ";
        $DB->queryOrDie($query, "0.5 alter field username");
    }
    //Mise a jour 0.5 verification des prefs pour chaque user.
    if (TableExists("glpi_prefs")) {
        $query = "SELECT `ID`, `name`\n                  FROM `glpi_users`";
        $query2 = "SELECT `ID`, `username`\n                 FROM `glpi_prefs`";
        $result = $DB->query($query);
        $result2 = $DB->query($query2);
        if ($DB->numrows($result) != $DB->numrows($result2)) {
            $users = array();
            $i = 0;
            while ($line = $DB->fetch_array($result2)) {
                $prefs[$i] = $line["username"];
                $i++;
            }
            while ($line = $DB->fetch_array($result)) {
                if (!in_array($line["name"], $prefs)) {
                    $query_insert = "INSERT INTO `glpi_prefs`\n                                       (`username` , `tracking_order` , `language`)\n                                VALUES ('" . $line["name"] . "', 'no', 'english')";
                    $DB->queryOrDie($query_insert, "glpi maj prefs");
                }
            }
        }
        $DB->free_result($result);
        $DB->free_result($result2);
    }
}
Example #7
0
function update0713to072()
{
    global $DB, $CFG_GLPI;
    //TRANS: %s is the number of new version
    echo "<h3>" . sprintf(__('Update to %s'), '0.72') . "</h3>";
    displayMigrationMessage("072");
    // Start
    if (!FieldExists("glpi_networking", "recursive", false)) {
        $query = "ALTER TABLE `glpi_networking`\n                ADD `recursive` TINYINT( 1 ) NOT NULL DEFAULT '0' AFTER `FK_entities`";
        $DB->queryOrDie($query, "0.72 add recursive in glpi_networking");
    }
    if (!FieldExists("glpi_printers", "recursive", false)) {
        $query = "ALTER TABLE `glpi_printers`\n                ADD `recursive` TINYINT( 1 ) NOT NULL DEFAULT '0' AFTER `FK_entities`";
        $DB->queryOrDie($query, "0.72 add recursive in glpi_printers");
    }
    if (!FieldExists("glpi_links", "FK_entities", false)) {
        $query = "ALTER TABLE `glpi_links`\n                ADD `FK_entities` INT( 11 ) NOT NULL DEFAULT '0' AFTER `ID`";
        $DB->queryOrDie($query, "0.72 add FK_entities in glpi_links");
    }
    if (!FieldExists("glpi_links", "recursive", false)) {
        $query = "ALTER TABLE `glpi_links`\n                ADD `recursive` INT( 1 ) NOT NULL DEFAULT '1' AFTER `FK_entities`";
        $DB->queryOrDie($query, "0.72 add recursive in glpi_links");
    }
    // Clean datetime fields
    $date_fields = array('glpi_docs.date_mod', 'glpi_event_log.date', 'glpi_monitors.date_mod', 'glpi_networking.date_mod', 'glpi_ocs_link.last_update', 'glpi_peripherals.date_mod', 'glpi_phones.date_mod', 'glpi_printers.date_mod', 'glpi_reservation_resa.begin', 'glpi_reservation_resa.end', 'glpi_tracking.closedate', 'glpi_tracking_planning.begin', 'glpi_tracking_planning.end', 'glpi_users.last_login', 'glpi_users.date_mod');
    foreach ($date_fields as $tablefield) {
        displayMigrationMessage("072", "Date format (1) ({$tablefield})");
        list($table, $field) = explode('.', $tablefield);
        if (FieldExists($table, $field, false)) {
            $query = "ALTER TABLE `{$table}`\n                   CHANGE `{$field}` `{$field}` DATETIME NULL";
            $DB->queryOrDie($query, "0.72 alter {$field} in {$table}");
        }
    }
    $date_fields[] = "glpi_computers.date_mod";
    $date_fields[] = "glpi_followups.date";
    $date_fields[] = "glpi_history.date_mod";
    $date_fields[] = "glpi_kbitems.date";
    $date_fields[] = "glpi_kbitems.date_mod";
    $date_fields[] = "glpi_ocs_config.date_mod";
    $date_fields[] = "glpi_ocs_link.last_ocs_update";
    $date_fields[] = "glpi_reminder.date";
    $date_fields[] = "glpi_reminder.begin";
    $date_fields[] = "glpi_reminder.end";
    $date_fields[] = "glpi_reminder.date_mod";
    $date_fields[] = "glpi_software.date_mod";
    $date_fields[] = "glpi_tracking.date";
    $date_fields[] = "glpi_tracking.date_mod";
    $date_fields[] = "glpi_type_docs.date_mod";
    foreach ($date_fields as $tablefield) {
        displayMigrationMessage("072", "Date format (2) ({$tablefield})");
        list($table, $field) = explode('.', $tablefield);
        if (FieldExists($table, $field, false)) {
            $query = "UPDATE `{$table}`\n                   SET `{$field}` = NULL\n                   WHERE `{$field}` = '0000-00-00 00:00:00'";
            $DB->queryOrDie($query, "0.72 update data of {$field} in {$table}");
        }
    }
    // Clean date fields
    $date_fields = array('glpi_infocoms.buy_date', 'glpi_infocoms.use_date');
    foreach ($date_fields as $tablefield) {
        list($table, $field) = explode('.', $tablefield);
        if (FieldExists($table, $field, false)) {
            $query = "ALTER TABLE `{$table}`\n                   CHANGE `{$field}` `{$field}` DATE NULL";
            $DB->queryOrDie($query, "0.72 alter {$field} in {$table}");
        }
    }
    $date_fields[] = "glpi_cartridges.date_in";
    $date_fields[] = "glpi_cartridges.date_use";
    $date_fields[] = "glpi_cartridges.date_out";
    $date_fields[] = "glpi_consumables.date_in";
    $date_fields[] = "glpi_consumables.date_out";
    $date_fields[] = "glpi_contracts.begin_date";
    $date_fields[] = "glpi_licenses.expire";
    foreach ($date_fields as $tablefield) {
        list($table, $field) = explode('.', $tablefield);
        if (FieldExists($table, $field, false)) {
            $query = "UPDATE `{$table}`\n                   SET `{$field}` = NULL\n                   WHERE `{$field}` = '0000-00-00'";
            $DB->queryOrDie($query, "0.72 update data of {$field} in {$table}");
        }
    }
    // Software Updates
    displayMigrationMessage("072", _n('Software', 'Software', 2));
    // Make software recursive
    if (!FieldExists("glpi_software", "recursive", false)) {
        $query = "ALTER TABLE `glpi_software`\n                ADD `recursive` TINYINT( 1 ) NOT NULL DEFAULT '0' AFTER `FK_entities`";
        $DB->queryOrDie($query, "0.72 add recursive in glpi_software");
    }
    if (!FieldExists("glpi_inst_software", "vID", false)) {
        $query = "ALTER TABLE `glpi_inst_software`\n                CHANGE `license` `vID` INT( 11 ) NOT NULL DEFAULT '0'";
        $DB->queryOrDie($query, "0.72 alter inst_software rename license to vID");
    }
    if (TableExists("glpi_softwarelicenses")) {
        if (TableExists("glpi_softwarelicenses_backup")) {
            $query = "DROP TABLE `glpi_softwarelicenses_backup`";
            $DB->queryOrDie($query, "0.72 drop backup table glpi_softwarelicenses_backup");
        }
        $query = "RENAME TABLE `glpi_softwarelicenses`\n                TO `glpi_softwarelicenses_backup`";
        $DB->queryOrDie($query, "0.72 backup table glpi_softwareversions");
        echo "<span class='b'><p>glpi_softwarelicenses table already exists.\n            A backup have been done to glpi_softwarelicenses_backup.</p>\n            <p>You can delete it if you have no need of it.</p></span>";
    }
    // Create licenses
    if (!TableExists("glpi_softwarelicenses")) {
        $query = "CREATE TABLE `glpi_softwarelicenses` (\n                  `ID` int(11) NOT NULL auto_increment,\n                  `sID` int(11) NOT NULL default '0',\n                  `FK_entities` int(11) NOT NULL default '0',\n                  `recursive` tinyint(1) NOT NULL DEFAULT '0',\n                  `number` int(11) NOT NULL default '0',\n                  `type` int(11) NOT NULL default '0',\n                  `name` varchar(255) NULL default NULL,\n                  `serial` varchar(255) NULL default NULL,\n                  `otherserial` varchar(255) NULL default NULL,\n                  `buy_version` int(11) NOT NULL default '0',\n                  `use_version` int(11) NOT NULL default '0',\n                  `expire` date default NULL,\n                  `FK_computers` int(11) NOT NULL default '0',\n                  `comments` text,\n                  PRIMARY KEY (`ID`),\n                  KEY `name` (`name`),\n                  KEY `type` (`type`),\n                  KEY `sID` (`sID`),\n                  KEY `FK_entities` (`FK_entities`),\n                  KEY `buy_version` (`buy_version`),\n                  KEY `use_version` (`use_version`),\n                  KEY `FK_computers` (`FK_computers`),\n                  KEY `serial` (`serial`),\n                  KEY `otherserial` (`otherserial`),\n                  KEY `expire` (`expire`)\n                ) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.72 create glpi_softwarelicenses");
    }
    if (TableExists("glpi_softwareversions")) {
        if (TableExists("glpi_softwareversions_backup")) {
            $query = "DROP TABLE `glpi_softwareversions_backup`";
            $DB->queryOrDie($query, "0.72 drop backup table glpi_softwareversions_backup");
        }
        $query = "RENAME TABLE `glpi_softwareversions`\n               TO `glpi_softwareversions_backup`";
        $DB->queryOrDie($query, "0.72 backup table glpi_softwareversions");
        echo "<p><span class='b'>glpi_softwareversions table already exists.\n            A backup have been done to glpi_softwareversions_backup.</p><p>\n            You can delete it if you have no need of it.</p></span>";
    }
    if (!TableExists("glpi_softwareversions")) {
        $query = "CREATE TABLE `glpi_softwareversions` (\n                  `ID` int(11) NOT NULL auto_increment,\n                  `sID` int(11) NOT NULL default '0',\n                  `state` int(11) NOT NULL default '0',\n                  `name` varchar(255) NULL default NULL,\n                  `comments` text,\n                  PRIMARY KEY (`ID`),\n                  KEY `sID` (`sID`),\n                  KEY `name` (`name`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.72 create glpi_softwareversions");
    }
    if (TableExists("glpi_licenses")) {
        // Update Infocoms to device_type 9999
        $query = "UPDATE `glpi_infocoms`\n                SET `device_type` = '9999'\n                WHERE `device_type` = '" . SOFTWARELICENSE_TYPE . "'";
        $DB->queryOrDie($query, "0.72 prepare infocoms for update softwares");
        // Foreach software
        $query_softs = "SELECT *\n                      FROM `glpi_software`\n                      ORDER BY `FK_entities`";
        if ($result_softs = $DB->query($query_softs)) {
            $nbsoft = $DB->numrows($result_softs);
            $step = round($nbsoft / 100);
            if (!$step) {
                $step = 1;
            }
            if ($step > 500) {
                $step = 500;
            }
            for ($numsoft = 0; $soft = $DB->fetch_assoc($result_softs); $numsoft++) {
                // To avoid navigator timeout on by DB
                if (!($numsoft % $step)) {
                    displayMigrationMessage("072 ", "Licenses : {$numsoft} / {$nbsoft}");
                }
                // oldstate present if migration run more than once
                if (isset($soft["oldstate"])) {
                    $soft["state"] = $soft["oldstate"];
                }
                // Foreach lics
                $query_versions = "SELECT `glpi_licenses`.*,\n                                      `glpi_infocoms`.`ID` AS infocomID\n                               FROM `glpi_licenses`\n                               LEFT JOIN `glpi_infocoms`\n                                  ON (`glpi_infocoms`.`device_type` = '9999'\n                                      AND `glpi_infocoms`.`FK_device` = `glpi_licenses`.`ID`)\n                               WHERE `sID` = '" . $soft['ID'] . "'\n                               ORDER BY `ID`";
                if ($result_vers = $DB->query($query_versions)) {
                    if ($DB->numrows($result_vers) > 0) {
                        while ($vers = $DB->fetch_assoc($result_vers)) {
                            $install_count = 0;
                            $vers_ID = $vers['ID'];
                            // init : count installations
                            $query_count = "SELECT COUNT(*)\n                                     FROM `glpi_inst_software`\n                                     WHERE `vID` = '" . $vers['ID'] . "'";
                            if ($result_count = $DB->query($query_count)) {
                                $install_count = $DB->result($result_count, 0, 0);
                                $DB->free_result($result_count);
                            }
                            // 1 - Is version already exists ?
                            $query_search_version = "SELECT *\n                                              FROM `glpi_softwareversions`\n                                              WHERE `sID` = '" . $soft['ID'] . "'\n                                                    AND `name` = '" . $vers['version'] . "'";
                            if ($result_searchvers = $DB->query($query_search_version)) {
                                // Version already exists : update inst_software
                                if ($DB->numrows($result_searchvers) == 1) {
                                    $found_vers = $DB->fetch_assoc($result_searchvers);
                                    $vers_ID = $found_vers['ID'];
                                    $query = "UPDATE `glpi_inst_software`\n                                     SET `vID` = '" . $found_vers['ID'] . "'\n                                     WHERE `vID` = '" . $vers['ID'] . "'";
                                    $DB->query($query);
                                } else {
                                    // Re Create new entry
                                    $query = "INSERT INTO `glpi_softwareversions`\n                                            SELECT `ID`, `sID`, '" . $soft["state"] . "', `version`,''\n                                            FROM `glpi_licenses`\n                                            WHERE `ID` = '" . $vers_ID . "'";
                                    $DB->query($query);
                                    // Transfert History for this version
                                    $findstr = " (v. " . $vers['version'] . ")";
                                    // Log event format in 0.71
                                    $findlen = Toolbox::strlen($findstr);
                                    $DB->query("UPDATE `glpi_history`\n                                      SET `FK_glpi_device` = '" . $vers_ID . "',\n                                          `device_type` = '" . SOFTWAREVERSION_TYPE . "'\n                                      WHERE `FK_glpi_device` = '" . $soft['ID'] . "'\n                                            AND `device_type` = '" . SOFTWARE_TYPE . "'\n                                            AND ((`linked_action` = '" . Log::HISTORY_INSTALL_SOFTWARE . "'\n                                                   AND RIGHT(new_value, {$findlen}) = '{$findstr}')\n                                                 OR (`linked_action` = '" . Log::HISTORY_UNINSTALL_SOFTWARE . "'\n                                                      AND RIGHT(old_value, {$findlen}) = '{$findstr}'))");
                                }
                                $DB->free_result($result_searchvers);
                            }
                            // 2 - Create glpi_licenses
                            if ($vers['buy'] || !empty($vers['serial']) && !in_array($vers['serial'], array('free', 'global')) || !empty($vers['comments']) || !empty($vers['expire']) || $vers['oem_computer'] > 0 || !empty($vers['infocomID'])) {
                                // with and infocoms
                                $found_lic = -1;
                                // No infocoms try to find already exists license
                                if (empty($vers['infocomID'])) {
                                    $query_search_lic = "SELECT `ID`\n                                                FROM `glpi_softwarelicenses`\n                                                WHERE `buy_version` = '{$vers_ID}'\n                                                      AND `serial` = '" . $vers['serial'] . "'\n                                                      AND `FK_computers` = '" . $vers['oem_computer'] . "'\n                                                      AND `comments` = '" . $vers['comments'] . "'";
                                    if (empty($vers['expire'])) {
                                        $query .= " AND `expire` IS NULL";
                                    } else {
                                        $query .= " AND `expire` = '" . $vers['expire'] . "'";
                                    }
                                    if ($result_searchlic = $DB->query($query_search_lic)) {
                                        if ($DB->numrows($result_searchlic) > 0) {
                                            $found_lic = $DB->result($result_searchlic, 0, 0);
                                            $DB->free_result($result_searchlic);
                                        }
                                    }
                                }
                                if ($install_count == 0) {
                                    $install_count = 1;
                                    // license exists so count 1
                                }
                                // Found license : merge with found one
                                if ($found_lic > 0) {
                                    $query = "UPDATE `glpi_softwarelicenses`\n                                     SET `number` = `number`+1\n                                     WHERE `ID` = '{$found_lic}'";
                                    $DB->query($query);
                                } else {
                                    // Create new license
                                    if (empty($vers['expire'])) {
                                        $vers['expire'] = 'NULL';
                                    } else {
                                        $vers['expire'] = "'" . $vers['expire'] . "'";
                                    }
                                    $query = "INSERT INTO `glpi_softwarelicenses`\n                                            (`sID` ,`FK_entities`,\n                                             `number` ,`type` ,`name` ,\n                                             `serial` ,`buy_version`,\n                                             `use_version`, `expire`,\n                                             `FK_computers` ,\n                                             `comments`)\n                                     VALUES ('" . $soft['ID'] . "', '" . $soft["FK_entities"] . "',\n                                             {$install_count}, 0, '" . $vers['serial'] . "',\n                                             '" . addslashes($vers['serial']) . "' , '{$vers_ID}',\n                                             '{$vers_ID}', " . $vers['expire'] . ",\n                                             '" . $vers['oem_computer'] . "',\n                                             '" . addslashes($vers['comments']) . "')";
                                    if ($DB->query($query)) {
                                        $lic_ID = $DB->insert_id();
                                        // Update infocoms link
                                        if (!empty($vers['infocomID'])) {
                                            $query = "UPDATE `glpi_infocoms`\n                                           SET `device_type` = '" . SOFTWARELICENSE_TYPE . "',\n                                               `FK_device` = '{$lic_ID}'\n                                           WHERE `device_type` = '9999'\n                                                 AND `FK_device` = '" . $vers['ID'] . "'";
                                            $DB->query($query);
                                        }
                                    }
                                }
                                // Create licence
                            }
                            // Buy licence
                        }
                        // Each license
                    }
                    // while
                    $DB->free_result($result_vers);
                }
                // Clean History for this software (old versions no more installed)
                $DB->query("DELETE\n                        FROM `glpi_history`\n                        WHERE `FK_glpi_device` = '" . $soft['ID'] . "'\n                              AND `device_type` = '" . SOFTWARE_TYPE . "'\n                              AND (`linked_action` = '" . Log::HISTORY_INSTALL_SOFTWARE . "'\n                                   OR `linked_action` = '" . Log::HISTORY_UNINSTALL_SOFTWARE . "')");
            }
            // For
        }
        // Each Software
        $query = "DROP TABLE `glpi_licenses`";
        $DB->queryOrDie($query, "0.72 drop table glpi_licenses");
        // Drop alerts on licenses : 2 = Alert::END
        $query = "DELETE\n                FROM `glpi_alerts`\n                WHERE `glpi_alerts`.`device_type` = '" . SOFTWARELICENSE_TYPE . "'\n                      AND `glpi_alerts`.`type` = '2'";
        $DB->queryOrDie($query, "0.72 clean alerts for licenses infocoms");
    }
    // TableExists("glpi_licenses")
    // Change software search pref
    $query = "SELECT DISTINCT `FK_users`\n             FROM `glpi_display`\n             WHERE `type` = '" . SOFTWARE_TYPE . "'";
    if ($result = $DB->query($query)) {
        if ($DB->numrows($result) > 0) {
            while ($data = $DB->fetch_assoc($result)) {
                $query = "SELECT max(`rank`)\n                      FROM `glpi_display`\n                      WHERE `FK_users` = '" . $data['FK_users'] . "'\n                            AND `type` = '" . SOFTWARE_TYPE . "'";
                $result = $DB->query($query);
                $rank = $DB->result($result, 0, 0);
                $rank++;
                $query = "SELECT *\n                      FROM `glpi_display`\n                      WHERE `FK_users` = '" . $data['FK_users'] . "'\n                            AND `num` = '72'\n                            AND `type` = '" . SOFTWARE_TYPE . "'";
                if ($result2 = $DB->query($query)) {
                    if ($DB->numrows($result2) == 0) {
                        $query = "INSERT INTO `glpi_display`\n                                   (`type` ,`num` ,`rank` ,\n                                    `FK_users`)\n                            VALUES ('" . SOFTWARE_TYPE . "', '72', '" . $rank++ . "',\n                                    '" . $data['FK_users'] . "')";
                        $DB->query($query);
                    }
                }
                $query = "SELECT *\n                      FROM `glpi_display`\n                      WHERE `FK_users` = '" . $data['FK_users'] . "'\n                            AND `num` = '163'\n                            AND `type` = '" . SOFTWARE_TYPE . "'";
                if ($result2 = $DB->query($query)) {
                    if ($DB->numrows($result2) == 0) {
                        $query = "INSERT INTO `glpi_display`\n                                   (`type` ,`num` ,`rank` ,\n                                    `FK_users`)\n                            VALUES ('" . SOFTWARE_TYPE . "', '163', '" . $rank++ . "',\n                                    '" . $data['FK_users'] . "');";
                        $DB->query($query);
                    }
                }
            }
        }
    }
    displayMigrationMessage("072", _n('Software', 'Software', 2));
    // If migration run more than once
    if (!FieldExists("glpi_softwareversions", "state", false)) {
        $query = "ALTER TABLE `glpi_softwareversions`\n                ADD `state` INT NOT NULL DEFAULT '0' AFTER `sID`";
        $DB->queryOrDie($query, "0.72 add state to softwareversion table");
    }
    // To allow migration to be run more than once
    if (FieldExists("glpi_software", "state", false)) {
        $query = "ALTER TABLE `glpi_software`\n                CHANGE `state` `oldstate` INT( 11 ) NOT NULL DEFAULT '0'";
        $DB->queryOrDie($query, "0.72 change state to to oldtsate in softwareversion table");
    }
    if (!TableExists("glpi_dropdown_licensetypes")) {
        $query = "CREATE TABLE `glpi_dropdown_licensetypes` (\n                  `ID` int(11) NOT NULL auto_increment,\n                  `name` varchar(255) NULL default NULL,\n                  `comments` text,\n                  PRIMARY KEY (`ID`),\n                  KEY `name` (`name`)\n                ) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.72 create glpi_dropdown_licensetypes table");
        $input["tablename"] = "glpi_dropdown_licensetypes";
        $input["value"] = "OEM";
        $input['type'] = "first";
        $input["comment"] = "";
        $input["entities_id"] = -1;
        $query = "INSERT INTO `glpi_dropdown_licensetypes`\n                       (`name`)\n                VALUES ('OEM')";
        if ($result = $DB->query($query)) {
            $oemtype = $DB->insert_id();
            $query = "UPDATE `glpi_softwarelicenses`\n                      SET `type` = '{$oemtype}'\n                      WHERE `FK_computers` > '0'";
            $DB->queryOrDie($query, "0.72 affect OEM as licensetype");
        }
    }
    displayMigrationMessage("072", _n('User', 'Users', 2));
    if (!FieldExists("glpi_groups", "recursive", false)) {
        $query = "ALTER TABLE `glpi_groups`\n                ADD `recursive` TINYINT( 1 ) NOT NULL DEFAULT '0' AFTER `FK_entities`";
        $DB->queryOrDie($query, "0.72 add recursive in glpi_groups");
    }
    if (!FieldExists("glpi_auth_ldap", "ldap_field_title", false)) {
        $query = "ALTER TABLE `glpi_auth_ldap`\n                ADD `ldap_field_title` VARCHAR( 255 ) DEFAULT NULL ";
        $DB->queryOrDie($query, "0.72 add ldap_field_title in glpi_auth_ldap");
    }
    //Add user title retrieval from LDAP
    if (!TableExists("glpi_dropdown_user_titles")) {
        $query = "CREATE TABLE `glpi_dropdown_user_titles` (\n                  `ID` int( 11 ) NOT NULL AUTO_INCREMENT ,\n                  `name` varchar( 255 ) NULL default NULL ,\n                  `comments` text ,\n                  PRIMARY KEY ( `ID` ) ,\n                  KEY `name` (`name`)\n                ) ENGINE = MYISAM DEFAULT CHARSET = utf8 COLLATE = utf8_unicode_ci";
        $DB->queryOrDie($query, "0.72 create glpi_dropdown_user_titles table");
    }
    if (!FieldExists("glpi_users", "title", false)) {
        $query = "ALTER TABLE `glpi_users`\n                ADD `title` INT( 11 ) NOT NULL DEFAULT '0'";
        $DB->queryOrDie($query, "0.72 add title in glpi_users");
    }
    if (!isIndex("glpi_users", "title")) {
        $query = " ALTER TABLE `glpi_users`\n                ADD INDEX `title` (`title`)";
        $DB->queryOrDie($query, "0.72 add index on title in glpi_users");
    }
    if (!FieldExists("glpi_auth_ldap", "ldap_field_type", false)) {
        $query = "ALTER TABLE `glpi_auth_ldap`\n                ADD `ldap_field_type` VARCHAR( 255 ) DEFAULT NULL";
        $DB->queryOrDie($query, "0.72 add ldap_field_title in glpi_auth_ldap");
    }
    //Add user type retrieval from LDAP
    if (!TableExists("glpi_dropdown_user_types")) {
        $query = "CREATE TABLE `glpi_dropdown_user_types` (\n                  `ID` int( 11 ) NOT NULL AUTO_INCREMENT,\n                  `name` varchar( 255 ) NULL default NULL,\n                  `comments` text,\n                  PRIMARY KEY (`ID`),\n                  KEY `name` (`name`)\n                ) ENGINE = MYISAM DEFAULT CHARSET = utf8 COLLATE = utf8_unicode_ci";
        $DB->queryOrDie($query, "0.72 create glpi_dropdown_user_types table");
    }
    if (!FieldExists("glpi_users", "type", false)) {
        $query = "ALTER TABLE `glpi_users`\n                ADD `type` INT( 11 ) NOT NULL DEFAULT '0'";
        $DB->queryOrDie($query, "0.72 add type in glpi_users");
    }
    if (!isIndex("glpi_users", "type")) {
        $query = " ALTER TABLE `glpi_users`\n                 ADD INDEX `type` (`type`)";
        $DB->queryOrDie($query, "0.72 add index on type in glpi_users");
    }
    if (!isIndex("glpi_users", "active")) {
        $query = " ALTER TABLE `glpi_users`\n                 ADD INDEX `active` (`active`)";
        $DB->queryOrDie($query, "0.72 add index on active in glpi_users");
    }
    if (!FieldExists("glpi_auth_ldap", "ldap_field_language", false)) {
        $query = "ALTER TABLE `glpi_auth_ldap`\n                ADD `ldap_field_language` VARCHAR( 255 ) NULL DEFAULT NULL ";
        $DB->queryOrDie($query, "0.72 add ldap_field_language in glpi_auth_ldap");
    }
    if (!FieldExists("glpi_ocs_config", "tag_exclude", false)) {
        $query = "ALTER TABLE `glpi_ocs_config`\n                ADD `tag_exclude` VARCHAR( 255 ) NULL AFTER `tag_limit`";
        $DB->queryOrDie($query, "0.72 add tag_exclude in glpi_ocs_config");
    }
    if (!FieldExists("glpi_config", "cache_max_size", false)) {
        $query = "ALTER TABLE `glpi_config`\n                ADD `cache_max_size` INT( 11 ) NOT NULL DEFAULT '20' AFTER `use_cache`";
        $DB->queryOrDie($query, "0.72 add cache_max_size in glpi_config");
    }
    displayMigrationMessage("072", _n('Volume', 'Volumes', 2));
    if (!TableExists("glpi_dropdown_filesystems")) {
        $query = "CREATE TABLE `glpi_dropdown_filesystems` (\n                  `ID` int(11) NOT NULL auto_increment,\n                  `name` varchar(255) NULL default NULL,\n                  `comments` text ,\n                  PRIMARY KEY (`ID`),\n                  KEY `name` (`name`)\n                ) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.72 create glpi_dropdown_filesystems table");
        $fstype = array('ext', 'ext2', 'ext3', 'ext4', 'FAT', 'FAT32', 'VFAT', 'HFS', 'HPFS', 'HTFS', 'JFS', 'JFS2', 'NFS', 'NTFS', 'ReiserFS', 'SMBFS', 'UDF', 'UFS', 'XFS', 'ZFS');
        foreach ($fstype as $fs) {
            $query = "INSERT INTO `glpi_dropdown_filesystems`\n                         (`name`)\n                   VALUES ('{$fs}')";
            $DB->queryOrDie($query, "0.72 add filesystems type");
        }
    }
    if (!TableExists("glpi_computerdisks")) {
        $query = "CREATE TABLE `glpi_computerdisks` (\n                  `ID` int(11) NOT NULL auto_increment,\n                  `FK_computers` int(11) NOT NULL default 0,\n                  `name` varchar(255)  NULL default NULL,\n                  `device` varchar(255) NULL default NULL,\n                  `mountpoint` varchar(255) NULL default NULL,\n                  `FK_filesystems` int(11) NOT NULL default 0,\n                  `totalsize` int(11) NOT NULL default 0,\n                  `freesize` int(11) NOT NULL default 0,\n                  PRIMARY KEY  (`ID`),\n                  KEY `name` (`name`),\n                  KEY `FK_filesystems` (`FK_filesystems`),\n                  KEY `FK_computers` (`FK_computers`),\n                  KEY `device` (`device`),\n                  KEY `mountpoint` (`mountpoint`),\n                  KEY `totalsize` (`totalsize`),\n                  KEY `freesize` (`freesize`)\n                ) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.72 create glpi_computerfilesystems table");
    }
    if (!FieldExists("glpi_ocs_config", "import_disk", false)) {
        $query = "ALTER TABLE `glpi_ocs_config`\n                ADD `import_disk` INT( 2 ) NOT NULL DEFAULT '0' AFTER `import_ip`";
        $DB->queryOrDie($query, "0.72 add import_disk in glpi_ocs_config");
    }
    if (!FieldExists("glpi_ocs_link", "import_disk", false)) {
        $query = "ALTER TABLE `glpi_ocs_link`\n                ADD `import_disk` LONGTEXT NULL AFTER `import_device`";
        $DB->queryOrDie($query, "0.72 add import_device in glpi_ocs_link");
    }
    // Clean software ocs
    if (FieldExists("glpi_ocs_config", "import_software_buy", false)) {
        $query = " ALTER TABLE `glpi_ocs_config`\n                 DROP `import_software_buy`";
        $DB->queryOrDie($query, "0.72 drop import_software_buy in glpi_ocs_config");
    }
    if (FieldExists("glpi_ocs_config", "import_software_licensetype", false)) {
        $query = " ALTER TABLE `glpi_ocs_config`\n                 DROP `import_software_licensetype`";
        $DB->queryOrDie($query, "0.72 drop import_software_licensetype in glpi_ocs_config");
    }
    //// Clean interface use for GFX card
    // Insert default values
    update_importDropdown("glpi_dropdown_interface", "AGP");
    update_importDropdown("glpi_dropdown_interface", "PCI");
    update_importDropdown("glpi_dropdown_interface", "PCIe");
    update_importDropdown("glpi_dropdown_interface", "PCI-X");
    if (!FieldExists("glpi_device_gfxcard", "FK_interface", false)) {
        $query = "ALTER TABLE `glpi_device_gfxcard`\n                ADD `FK_interface` INT NOT NULL DEFAULT '0' AFTER `interface` ";
        $DB->queryOrDie($query, "0.72 alter glpi_device_gfxcard add new field interface");
        // Get all data from interface_old / Insert in glpi_dropdown_interface if needed
        $query = "SELECT DISTINCT `interface` AS OLDNAME\n                FROM `glpi_device_gfxcard`";
        if ($result = $DB->query($query)) {
            if ($DB->numrows($result) > 0) {
                while ($data = $DB->fetch_assoc($result)) {
                    $data = Toolbox::addslashes_deep($data);
                    // Update datas
                    if ($newID = update_importDropdown("glpi_dropdown_interface", $data['OLDNAME'])) {
                        $query2 = "UPDATE `glpi_device_gfxcard`\n                             SET `FK_interface` = '{$newID}'\n                             WHERE `interface` = '" . $data['OLDNAME'] . "'";
                        $DB->queryOrDie($query2, "0.72 update glpi_device_gfxcard set new interface value");
                    }
                }
            }
        }
        $query = "ALTER TABLE `glpi_device_gfxcard`\n                DROP `interface` ";
        $DB->queryOrDie($query, "0.72 alter {$table} drop tmp enum field");
    }
    if (!FieldExists("glpi_config", "existing_auth_server_field_clean_domain", false)) {
        $query = "ALTER TABLE `glpi_config`\n                ADD `existing_auth_server_field_clean_domain` SMALLINT NOT NULL DEFAULT '0'\n                                                              AFTER `existing_auth_server_field`";
        $DB->queryOrDie($query, "0.72 alter config add existing_auth_server_field_clean_domain");
    }
    if (FieldExists("glpi_profiles", "contract_infocom", false)) {
        $query = "ALTER TABLE `glpi_profiles`\n                CHANGE `contract_infocom` `contract` CHAR( 1 ) NULL DEFAULT NULL ";
        $DB->queryOrDie($query, "0.72 alter profiles rename contract_infocom to contract");
        $query = "ALTER TABLE `glpi_profiles`\n                ADD `infocom` CHAR( 1 ) NULL DEFAULT NULL AFTER `contract`";
        $DB->queryOrDie($query, "0.72 alter profiles create infocom");
        $query = "UPDATE `glpi_profiles`\n                SET `infocom` = `contract`";
        $DB->queryOrDie($query, "0.72 update data for infocom in profiles");
    }
    // Debug mode in user pref to allow debug in production environment
    if (FieldExists("glpi_config", "debug", false)) {
        $query = "ALTER TABLE `glpi_config`\n                DROP `debug`";
        $DB->queryOrDie($query, "0.72 drop debug mode in config");
    }
    if (!FieldExists("glpi_users", "use_mode", false)) {
        $query = "ALTER TABLE `glpi_users`\n                ADD `use_mode` SMALLINT NOT NULL DEFAULT '0' AFTER `language`";
        $DB->queryOrDie($query, "0.72 create use_mode in glpi_users");
    }
    // Default bookmark as default view
    if (!TableExists("glpi_display_default")) {
        $query = "CREATE TABLE IF NOT EXISTS `glpi_display_default` (\n                  `ID` int(11) NOT NULL auto_increment,\n                  `FK_users` int(11) NOT NULL,\n                  `device_type` int(11) NOT NULL,\n                  `FK_bookmark` int(11) NOT NULL,\n                  PRIMARY KEY (`ID`),\n                  UNIQUE KEY `FK_users` (`FK_users`,`device_type`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.72 create table glpi_display_default");
    }
    // Correct cost contract data type
    if (FieldExists("glpi_contracts", "cost", false)) {
        $query = " ALTER TABLE `glpi_contracts`\n               CHANGE `cost` `cost` DECIMAL( 20, 4 ) NOT NULL DEFAULT '0.0000'";
        $DB->queryOrDie($query, "0.72 alter contract cost data type");
    }
    // Plugins table
    if (!TableExists("glpi_plugins")) {
        $query = "CREATE TABLE IF NOT EXISTS `glpi_plugins` (\n                  `ID` int(11) NOT NULL auto_increment,\n                  `directory` varchar(255) NOT NULL,\n                  `name` varchar(255)  NOT NULL,\n                  `version` varchar(255)  NOT NULL,\n                  `state` tinyint(4) NOT NULL default '0',\n                  `author` varchar(255) NULL default NULL,\n                  `homepage` varchar(255) NULL default NULL,\n                  PRIMARY KEY (`ID`),\n                  UNIQUE KEY `name` (`directory`)\n                ) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.72 create table glpi_plugins");
    }
    //// CORRECT glpi_config field type
    if (FieldExists("glpi_config", "num_of_events", false)) {
        $query = "ALTER TABLE `glpi_config`\n                CHANGE `num_of_events` `num_of_events` INT( 11 ) NOT NULL DEFAULT '10'";
        $DB->queryOrDie($query, "0.72 alter config num_of_events");
    }
    if (FieldExists("glpi_config", "jobs_at_login", false)) {
        $query = "ALTER TABLE `glpi_config`\n                CHANGE `jobs_at_login` `jobs_at_login` SMALLINT( 6 ) NOT NULL DEFAULT '0'";
        $DB->queryOrDie($query, "0.72 alter config jobs_at_login");
    }
    if (FieldExists("glpi_config", "cut", false)) {
        $query = "UPDATE `glpi_config`\n                SET `cut` = ROUND(`cut`/50)*50";
        $DB->queryOrDie($query, "0.72 update config cut value to prepare update");
        $query = "ALTER TABLE `glpi_config`\n                CHANGE `cut` `cut` INT( 11 ) NOT NULL DEFAULT '255'";
        $DB->queryOrDie($query, "0.72 alter config cut");
    }
    if (FieldExists("glpi_config", "list_limit", false)) {
        $query = "ALTER TABLE `glpi_config`\n                CHANGE `list_limit` `list_limit` INT( 11 ) NOT NULL DEFAULT '20'";
        $DB->queryOrDie($query, "0.72 alter config list_limit");
    }
    if (FieldExists("glpi_config", "expire_events", false)) {
        $query = "ALTER TABLE `glpi_config`\n                CHANGE `expire_events` `expire_events` INT( 11 ) NOT NULL DEFAULT '30'";
        $DB->queryOrDie($query, "0.72 alter config expire_events");
    }
    if (FieldExists("glpi_config", "event_loglevel", false)) {
        $query = "ALTER TABLE `glpi_config`\n                CHANGE `event_loglevel` `event_loglevel` SMALLINT( 6 ) NOT NULL DEFAULT '5'";
        $DB->queryOrDie($query, "0.72 alter config event_loglevel");
    }
    if (FieldExists("glpi_config", "permit_helpdesk", false)) {
        $query = "UPDATE `glpi_config`\n                SET `permit_helpdesk` = '0'\n                WHERE `permit_helpdesk` = ''";
        $DB->queryOrDie($query, "0.72 update config permit_helpdesk value to prepare update");
        $query = "ALTER TABLE `glpi_config`\n                CHANGE `permit_helpdesk` `permit_helpdesk` SMALLINT NOT NULL DEFAULT '0'";
        $DB->queryOrDie($query, "0.72 alter config permit_helpdesk");
    }
    if (!FieldExists("glpi_config", "language", false)) {
        $query = "ALTER TABLE `glpi_config`\n                CHANGE `default_language` `language` VARCHAR( 255 ) NULL DEFAULT 'en_GB'";
        $DB->queryOrDie($query, "0.72 alter config default_language");
    }
    if (!FieldExists("glpi_config", "tracking_order", false)) {
        $query = "ALTER TABLE `glpi_config`\n                ADD `tracking_order` SMALLINT NOT NULL default '0'";
        $DB->queryOrDie($query, "0.72 alter config add tracking_order");
    }
    if (!FieldExists("glpi_users", "dateformat", false)) {
        $query = "ALTER TABLE `glpi_users`\n                ADD `dateformat` SMALLINT NULL DEFAULT NULL";
        $DB->queryOrDie($query, "0.72 add dateformat in users");
    }
    if (FieldExists("glpi_users", "list_limit", false)) {
        $query = "ALTER TABLE `glpi_users`\n                CHANGE `list_limit` `list_limit` INT( 11 ) NULL DEFAULT NULL";
        $DB->queryOrDie($query, "0.72 alter list_limit in users");
    }
    if (FieldExists("glpi_users", "tracking_order", false)) {
        $query = "ALTER TABLE `glpi_users`\n                CHANGE `tracking_order` `tracking_order` SMALLINT( 6 ) NULL DEFAULT NULL";
        $DB->queryOrDie($query, "0.72 alter tracking_order in users");
    }
    if (!FieldExists("glpi_users", "numberformat", false)) {
        $query = "ALTER TABLE `glpi_users`\n                ADD `numberformat` SMALLINT NULL DEFAULT NULL";
        $DB->queryOrDie($query, "0.72 add numberformat in users");
    }
    if (!FieldExists("glpi_users", "view_ID", false)) {
        $query = "ALTER TABLE `glpi_users`\n                ADD `view_ID` SMALLINT NULL DEFAULT NULL";
        $DB->queryOrDie($query, "0.72 add view_ID in users");
    }
    if (!FieldExists("glpi_users", "dropdown_limit", false)) {
        $query = "ALTER TABLE `glpi_users`\n                ADD `dropdown_limit` INT NULL DEFAULT NULL";
        $DB->queryOrDie($query, "0.72 add dropdown_limit in users");
    }
    if (!FieldExists("glpi_users", "flat_dropdowntree", false)) {
        $query = "ALTER TABLE `glpi_users`\n                ADD `flat_dropdowntree` SMALLINT NULL DEFAULT NULL";
        $DB->queryOrDie($query, "0.72 add flat_dropdowntree in users");
    }
    if (!FieldExists("glpi_users", "num_of_events", false)) {
        $query = "ALTER TABLE `glpi_users`\n                ADD `num_of_events` INT NULL DEFAULT NULL";
        $DB->queryOrDie($query, "0.72 add num_of_events in users");
    }
    if (!FieldExists("glpi_users", "nextprev_item", false)) {
        $query = "ALTER TABLE `glpi_users`\n                ADD `nextprev_item` VARCHAR( 255 ) NULL DEFAULT NULL";
        $DB->queryOrDie($query, "0.72 add nextprev_item in users");
    }
    if (!FieldExists("glpi_users", "jobs_at_login", false)) {
        $query = "ALTER TABLE `glpi_users`\n                ADD `jobs_at_login` SMALLINT NULL DEFAULT NULL";
        $DB->queryOrDie($query, "0.72 add jobs_at_login in users");
    }
    if (!FieldExists("glpi_users", "priority_1", false)) {
        $query = "ALTER TABLE `glpi_users`\n                ADD `priority_1` VARCHAR( 255 ) NULL DEFAULT NULL,\n                ADD `priority_2` VARCHAR( 255 ) NULL DEFAULT NULL,\n                ADD `priority_3` VARCHAR( 255 ) NULL DEFAULT NULL,\n                ADD `priority_4` VARCHAR( 255 ) NULL DEFAULT NULL,\n                ADD `priority_5` VARCHAR( 255 ) NULL DEFAULT NULL";
        $DB->queryOrDie($query, "0.72 add priority_X in users");
    }
    if (!FieldExists("glpi_users", "expand_soft_categorized", false)) {
        $query = "ALTER TABLE `glpi_users`\n                ADD `expand_soft_categorized` INT( 1 ) NULL DEFAULT NULL";
        $DB->queryOrDie($query, "0.72 add expand_soft_categorized in users");
    }
    if (!FieldExists("glpi_users", "expand_soft_not_categorized", false)) {
        $query = "ALTER TABLE `glpi_users`\n                ADD `expand_soft_not_categorized` INT( 1 ) NULL DEFAULT NULL";
        $DB->queryOrDie($query, "0.72 add expand_soft_not_categorized in users");
    }
    if (!FieldExists("glpi_users", "followup_private", false)) {
        $query = "ALTER TABLE `glpi_users`\n                ADD `followup_private` SMALLINT NULL DEFAULT NULL";
        $DB->queryOrDie($query, "0.72 add followup_private in users");
    }
    if (!FieldExists("glpi_config", "followup_private", false)) {
        $query = "ALTER TABLE `glpi_config`\n                ADD `followup_private` SMALLINT NOT NULL DEFAULT '0'";
        $DB->queryOrDie($query, "0.72 add followup_private in config");
    }
    // INDEX key order change
    if (isIndex("glpi_contract_device", "FK_contract")) {
        $query = "ALTER TABLE `glpi_contract_device`\n                DROP INDEX `FK_contract`";
        $DB->queryOrDie($query, "0.72 drop index FK_contract on glpi_contract_device");
    }
    if (!isIndex("glpi_contract_device", "FK_contract_device")) {
        $query = "ALTER TABLE `glpi_contract_device`\n                ADD UNIQUE INDEX `FK_contract_device` (`FK_contract` , `device_type`, `FK_device` )";
        $DB->queryOrDie($query, "0.72 add index FK_contract_device in glpi_contract_device");
    }
    if (isIndex("glpi_doc_device", "FK_doc")) {
        $query = "ALTER TABLE `glpi_doc_device`\n                DROP INDEX `FK_doc`";
        $DB->queryOrDie($query, "0.72 drop index FK_doc on glpi_doc_device");
    }
    if (!isIndex("glpi_doc_device", "FK_doc_device")) {
        $query = "ALTER TABLE `glpi_doc_device`\n                ADD UNIQUE INDEX `FK_doc_device` (`FK_doc` , `device_type`, `FK_device` )";
        $DB->queryOrDie($query, "0.72 add index FK_doc_device in glpi_doc_device");
    }
    //(AD) DistinguishedName criteria is wrong. DN in AD is not distinguishedName but DN.
    $query = "SELECT `ID`\n             FROM `glpi_rules_ldap_parameters`\n             WHERE `value` = 'distinguishedname'";
    $result = $DB->query($query);
    //If (AD) DistinguishedName criteria is still present
    if ($DB->numrows($result) == 1) {
        $query = "SELECT COUNT(`ID`) AS cpt\n                FROM `glpi_rules_criterias`\n                WHERE `criteria` = 'distinguishedname'";
        $result = $DB->query($query);
        if ($DB->result($result, 0, "cpt") > 0) {
            echo "<div class='center spaced'>";
            echo "<span class='red'>LDAP Criteria (AD)Distinguishedname must be removed.<br>" . "As it is used in one or more LDAP rules, you need to remove it manually</span>";
            echo "</div><br>";
        } else {
            //Delete If (AD) DistinguishedName criteria
            $query = "DELETE\n                   FROM `glpi_rules_ldap_parameters`\n                   WHERE `value` = 'distinguishedname'";
            $result = $DB->query($query);
        }
    }
    //// Clean DB
    if (isIndex("glpi_alerts", "item") && isIndex("glpi_alerts", "alert")) {
        $query = "ALTER TABLE `glpi_alerts`\n                DROP INDEX `item`";
        $DB->queryOrDie($query, "0.72 drop item index on glpi_alerts");
    }
    if (isIndex("glpi_alerts", "device_type") && isIndex("glpi_alerts", "alert")) {
        $query = "ALTER TABLE `glpi_alerts`\n                DROP INDEX `device_type`";
        $DB->queryOrDie($query, "0.72 drop device_type index on glpi_alerts");
    }
    if (isIndex("glpi_cartridges_assoc", "FK_glpi_type_printer_2") && isIndex("glpi_cartridges_assoc", "FK_glpi_type_printer")) {
        $query = "ALTER TABLE `glpi_cartridges_assoc`\n                DROP INDEX `FK_glpi_type_printer_2`";
        $DB->queryOrDie($query, "0.72 drop FK_glpi_type_printer_2 index on glpi_cartridges_assoc");
    }
    if (isIndex("glpi_computer_device", "device_type") && isIndex("glpi_computer_device", "device_type_2")) {
        $query = "ALTER TABLE `glpi_computer_device`\n                DROP INDEX `device_type`";
        $DB->queryOrDie($query, "0.72 drop device_type index on glpi_computer_device");
        $query = "ALTER TABLE `glpi_computer_device`\n                DROP INDEX `device_type_2`,\n                ADD INDEX `device_type` (`device_type` , `FK_device`) ";
        $DB->queryOrDie($query, "0.72 rename device_type_2 index on glpi_computer_device");
    }
    if (isIndex("glpi_connect_wire", "end1") && isIndex("glpi_connect_wire", "end1_1")) {
        $query = "ALTER TABLE `glpi_connect_wire`\n                DROP INDEX `end1`";
        $DB->queryOrDie($query, "0.72 drop end1 index on glpi_connect_wire");
        $query = "ALTER TABLE `glpi_connect_wire`\n                DROP INDEX `end1_1`,\n                ADD UNIQUE `connect` (`end1` , `end2` , `type`)";
        $DB->queryOrDie($query, "0.72 rename end1_1 index on glpi_connect_wire");
    }
    if (isIndex("glpi_contract_enterprise", "FK_enterprise") && isIndex("glpi_contract_enterprise", "FK_enterprise_2")) {
        $query = "ALTER TABLE `glpi_contract_enterprise`\n                DROP INDEX `FK_enterprise_2`";
        $DB->queryOrDie($query, "0.72 drop FK_enterprise_2 index on glpi_contract_enterprise");
    }
    if (isIndex("glpi_contact_enterprise", "FK_enterprise") && isIndex("glpi_contact_enterprise", "FK_enterprise_2")) {
        $query = "ALTER TABLE `glpi_contact_enterprise`\n                DROP INDEX `FK_enterprise_2`";
        $DB->queryOrDie($query, "0.72 drop FK_enterprise_2 index on glpi_contact_enterprise");
    }
    if (isIndex("glpi_contract_device", "FK_contract_2") && isIndex("glpi_contract_device", "FK_contract_device")) {
        $query = "ALTER TABLE `glpi_contract_device`\n                DROP INDEX `FK_contract_2`";
        $DB->queryOrDie($query, "0.72 drop FK_contract_2 index on glpi_contract_device");
    }
    if (isIndex("glpi_display", "type") && isIndex("glpi_display", "type_2")) {
        $query = "ALTER TABLE `glpi_display`\n                DROP INDEX `type`";
        $DB->queryOrDie($query, "0.72 drop type index on glpi_display");
        $query = "ALTER TABLE `glpi_display`\n                DROP INDEX `type_2`,\n                ADD UNIQUE `display` (`type` , `num` , `FK_users`)";
        $DB->queryOrDie($query, "0.72 rename type_2 index on glpi_display");
    }
    if (isIndex("glpi_doc_device", "FK_doc_2") && isIndex("glpi_doc_device", "FK_doc_device")) {
        $query = "ALTER TABLE `glpi_doc_device`\n                DROP INDEX `FK_doc_2`";
        $DB->queryOrDie($query, "0.72 drop FK_doc_2 index on glpi_doc_device");
    }
    if (isIndex("glpi_links_device", "device_type") && isIndex("glpi_links_device", "device_type_2")) {
        $query = "ALTER TABLE `glpi_links_device`\n                DROP INDEX `device_type`";
        $DB->queryOrDie($query, "0.72 drop device_type index on glpi_links_device");
        $query = "ALTER TABLE `glpi_links_device`\n                DROP INDEX `device_type_2`,\n                ADD UNIQUE `link` (`device_type` , `FK_links`)";
        $DB->queryOrDie($query, "0.72 rename device_type_2 index on glpi_links_device");
    }
    if (isIndex("glpi_mailing", "item_type") && isIndex("glpi_mailing", "items")) {
        $query = "ALTER TABLE `glpi_mailing`\n                DROP INDEX `item_type`";
        $DB->queryOrDie($query, "0.72 drop item_type index on glpi_mailing");
    }
    if (isIndex("glpi_mailing", "type") && isIndex("glpi_mailing", "mailings")) {
        $query = "ALTER TABLE `glpi_mailing`\n                DROP INDEX `type`";
        $DB->queryOrDie($query, "0.72 drop type index on glpi_mailing");
    }
    if (isIndex("glpi_networking_ports", "on_device_2") && isIndex("glpi_networking_ports", "on_device")) {
        $query = "ALTER TABLE `glpi_networking_ports`\n                DROP INDEX `on_device_2`";
        $DB->queryOrDie($query, "0.72 drop on_device_2 index on glpi_networking_ports");
    }
    if (isIndex("glpi_networking_vlan", "FK_port") && isIndex("glpi_networking_vlan", "FK_port_2")) {
        $query = "ALTER TABLE `glpi_networking_vlan`\n                DROP INDEX `FK_port`";
        $DB->queryOrDie($query, "0.72 drop FK_port index on glpi_networking_vlan");
        $query = "ALTER TABLE `glpi_networking_vlan`\n                DROP INDEX `FK_port_2`,\n                ADD UNIQUE `portvlan` (`FK_port`, `FK_vlan`)";
        $DB->queryOrDie($query, "0.72 rename FK_port_2 index on glpi_networking_vlan");
    }
    if (isIndex("glpi_networking_wire", "end1") && isIndex("glpi_networking_wire", "end1_1")) {
        $query = "ALTER TABLE `glpi_networking_wire`\n                DROP INDEX `end1`";
        $DB->queryOrDie($query, "0.72 drop end1 index on glpi_networking_wire");
        $query = "ALTER TABLE `glpi_networking_wire`\n                DROP INDEX `end1_1`,\n                ADD UNIQUE `netwire` (`end1`, `end2`)";
        $DB->queryOrDie($query, "0.72 rename end1_1 index on glpi_networking_wire");
    }
    if (isIndex("glpi_reservation_item", "device_type") && isIndex("glpi_reservation_item", "device_type_2")) {
        $query = "ALTER TABLE `glpi_reservation_item`\n                DROP INDEX `device_type`";
        $DB->queryOrDie($query, "0.72 drop device_type index on glpi_reservation_item");
        $query = "ALTER TABLE `glpi_reservation_item`\n                DROP INDEX `device_type_2`,\n                ADD INDEX `reservationitem` (`device_type`, `id_device`)";
        $DB->queryOrDie($query, "0.72 rename device_type_2 index on glpi_reservation_item");
    }
    if (isIndex("glpi_users_groups", "FK_users") && isIndex("glpi_users_groups", "FK_users_2")) {
        $query = "ALTER TABLE `glpi_users_groups`\n                DROP INDEX `FK_users_2`";
        $DB->queryOrDie($query, "0.72 drop FK_users_2 index on glpi_users_groups");
        $query = "ALTER TABLE `glpi_users_groups`\n                DROP INDEX `FK_users`,\n                ADD UNIQUE `usergroup` (`FK_users`, `FK_groups`)";
        $DB->queryOrDie($query, "0.72 rename FK_users index on glpi_users_groups");
    }
    if (!FieldExists("glpi_config", "software_helpdesk_visible", false)) {
        $query = " ALTER TABLE `glpi_config`\n                 ADD `software_helpdesk_visible` INT(1) NOT NULL DEFAULT '1'";
        $DB->queryOrDie($query, "0.72 add software_helpdesk_visible in config");
    }
    if (!FieldExists("glpi_entities_data", "ldap_dn", false)) {
        $query = "ALTER TABLE `glpi_entities_data`\n                ADD `ldap_dn` VARCHAR( 255 ) NULL";
        $DB->queryOrDie($query, "0.72 add ldap_dn in config");
    }
    if (!FieldExists("glpi_entities_data", "tag", false)) {
        $query = "ALTER TABLE `glpi_entities_data`\n                ADD `tag` VARCHAR( 255 ) NULL";
        $DB->queryOrDie($query, "0.72 add tag in config");
    }
    if (FieldExists("glpi_rules_ldap_parameters", "rule_type", false)) {
        $query = "ALTER TABLE `glpi_rules_ldap_parameters`\n                CHANGE `rule_type` `sub_type` SMALLINT( 6 ) NOT NULL DEFAULT '1'";
        $DB->queryOrDie($query, "0.72 rename rule_type to sub_type in glpi_rules_ldap_parameters");
    }
    if (FieldExists("glpi_rules_descriptions", "rule_type", false)) {
        $query = "ALTER TABLE `glpi_rules_descriptions`\n                CHANGE `rule_type` `sub_type` SMALLINT( 4 ) NOT NULL DEFAULT '0'";
        $DB->queryOrDie($query, "0.72 rename rule_type to sub_type in glpi_rules_descriptions");
    }
    //Add title criteria
    $result = $DB->query("SELECT COUNT(*) AS cpt\n                          FROM `glpi_rules_ldap_parameters`\n                          WHERE `value` = 'title'\n                          AND `sub_type` = '1'");
    if (!$DB->result($result, 0, "cpt")) {
        $DB->query("INSERT INTO `glpi_rules_ldap_parameters`\n                         (`ID` ,`name` ,`value` ,`sub_type`)\n                  VALUES (NULL , '(LDAP) Title', 'title', '1')");
    }
    // Duplicate index with PRIMARY
    if (isIndex("glpi_monitors", "ID")) {
        $query = "ALTER TABLE `glpi_monitors`\n                DROP INDEX `ID`";
        $DB->queryOrDie($query, "0.72 drop ID index on glpi_monitors");
    }
    if (FieldExists("glpi_ocs_config", "is_template", false)) {
        $query = "DELETE\n                FROM `glpi_ocs_config`\n                WHERE `is_template` = '1'";
        $DB->queryOrDie($query, "0.72 delete templates in glpi_ocs_config");
        $query = "ALTER TABLE `glpi_ocs_config`\n                DROP `is_template`";
        $DB->queryOrDie($query, "0.72 drop is_template in glpi_ocs_config");
    }
    if (FieldExists("glpi_ocs_config", "tplname", false)) {
        $query = "ALTER TABLE `glpi_ocs_config`\n                DROP `tplname`";
        $DB->queryOrDie($query, "0.72 drop tplname in glpi_ocs_config");
    }
    if (FieldExists("glpi_ocs_config", "date_mod", false)) {
        $query = "ALTER TABLE `glpi_ocs_config`\n                DROP `date_mod`";
        $DB->queryOrDie($query, "0.72 drop date_mod in glpi_ocs_config");
    }
    if (FieldExists("glpi_ocs_config", "glpi_link_enabled", false)) {
        $query = "ALTER TABLE `glpi_ocs_config`\n                CHANGE `glpi_link_enabled` `glpi_link_enabled` INT(1) NOT NULL DEFAULT '0' ";
        $DB->queryOrDie($query, "0.72 alter glpi_link_enabled in glpi_ocs_config");
    }
    if (FieldExists("glpi_ocs_config", "link_ip", false)) {
        $query = "ALTER TABLE `glpi_ocs_config`\n                CHANGE `link_ip` `link_ip` INT( 1 ) NOT NULL DEFAULT '0' ";
        $DB->queryOrDie($query, "0.72 alter link_ip in glpi_ocs_config");
    }
    if (FieldExists("glpi_ocs_config", "link_name", false)) {
        $query = "ALTER TABLE `glpi_ocs_config`\n                CHANGE `link_name` `link_name` INT (1) NOT NULL DEFAULT '0' ";
        $DB->queryOrDie($query, "0.72 alter link_name in glpi_ocs_config");
    }
    if (FieldExists("glpi_ocs_config", "link_mac_address", false)) {
        $query = "ALTER TABLE `glpi_ocs_config`\n                CHANGE `link_mac_address` `link_mac_address` INT( 1 ) NOT NULL DEFAULT '0' ";
        $DB->queryOrDie($query, "0.72 alter link_mac_address in glpi_ocs_config");
    }
    if (FieldExists("glpi_ocs_config", "link_serial", false)) {
        $query = "ALTER TABLE `glpi_ocs_config`\n                CHANGE `link_serial` `link_serial` INT( 1 ) NOT NULL DEFAULT '0' ";
        $DB->queryOrDie($query, "0.72 alter link_serial in glpi_ocs_config");
    }
    if (!FieldExists("glpi_config", "name_display_order", false)) {
        $query = "ALTER TABLE `glpi_config`\n                ADD `name_display_order` TINYINT NOT NULL DEFAULT '0'";
        $DB->queryOrDie($query, "0.72 add name_display_order in glpi_config");
    }
    // Display "Work ended." message - Keep this as the last action.
    displayMigrationMessage("072");
    // End
}
Example #8
0
function update101to110()
{
    global $DB, $CFG_GLPI;
    echo "<strong>Update 1.0.1 to 1.1.0</strong><br/>";
    // ** Update glpi_plugin_projet_projets
    if (TableExists("glpi_plugin_projet")) {
        $query = "RENAME TABLE `glpi_plugin_projet` TO `glpi_plugin_projet_projets` ";
        $DB->query($query);
    }
    if (FieldExists("glpi_plugin_projet_projets", "ID")) {
        $query = "ALTER TABLE `glpi_plugin_projet_projets` \n                  CHANGE `ID` `id` INT( 11 ) NOT NULL AUTO_INCREMENT";
        $DB->query($query);
    }
    if (FieldExists("glpi_plugin_projet_projets", "FK_entities")) {
        $query = "ALTER TABLE `glpi_plugin_projet_projets` \n                  CHANGE `FK_entities` `entities_id` INT( 11 ) NOT NULL DEFAULT '0'";
        $DB->query($query);
    }
    if (FieldExists("glpi_plugin_projet_projets", "recursive")) {
        $query = "ALTER TABLE `glpi_plugin_projet_projets` \n                  CHANGE `recursive` `is_recursive` tinyint(1) NOT NULL default '0'";
        $DB->query($query);
    }
    if (FieldExists("glpi_plugin_projet_projets", "FK_users")) {
        $query = "ALTER TABLE `glpi_plugin_projet_projets` \n                  CHANGE `FK_users` `users_id` int(11) NOT NULL default '0'";
        $DB->query($query);
    }
    if (FieldExists("glpi_plugin_projet_projets", "FK_groups")) {
        $query = "ALTER TABLE `glpi_plugin_projet_projets` \n                  CHANGE `FK_groups` `groups_id` int(11) NOT NULL default '0'";
        $DB->query($query);
    }
    if (FieldExists("glpi_plugin_projet_projets", "status")) {
        $query = "ALTER TABLE `glpi_plugin_projet_projets` \n                  CHANGE `status` `plugin_projet_projetstates_id` INT( 4 ) NOT NULL default '0'";
        $DB->query($query);
    }
    if (FieldExists("glpi_plugin_projet_projets", "parentID")) {
        $query = "ALTER TABLE `glpi_plugin_projet_projets` \n                  CHANGE `parentID` `plugin_projet_projets_id` int(11) NOT NULL default '0'";
        $DB->query($query);
    }
    if (FieldExists("glpi_plugin_projet_projets", "comments")) {
        $query = "ALTER TABLE `glpi_plugin_projet_projets` \n                  CHANGE `comments` `comment` TEXT CHARACTER \n                     SET utf8 COLLATE utf8_unicode_ci NULL DEFAULT NULL";
        $DB->query($query);
    }
    if (FieldExists("glpi_plugin_projet_projets", "tplname")) {
        $query = "ALTER TABLE `glpi_plugin_projet_projets` \n                  CHANGE `tplname` `template_name` varchar(255) collate utf8_unicode_ci NOT NULL default ''";
        $DB->query($query);
    }
    if (FieldExists("glpi_plugin_projet_projets", "deleted")) {
        $query = "ALTER TABLE `glpi_plugin_projet_projets` \n                  CHANGE `deleted` `is_deleted` smallint(6) NOT NULL default '0'";
        $DB->query($query);
    }
    // ** Update glpi_plugin_projet_projetitems
    if (TableExists("glpi_plugin_projet_items")) {
        $query = "RENAME TABLE `glpi_plugin_projet_items` TO `glpi_plugin_projet_projetitems` ";
        $DB->query($query);
    }
    if (FieldExists("glpi_plugin_projet_projetitems", "ID")) {
        $query = "ALTER TABLE `glpi_plugin_projet_projetitems` \n                  CHANGE `ID` `id` INT( 11 ) NOT NULL AUTO_INCREMENT";
        $DB->query($query);
    }
    if (FieldExists("glpi_plugin_projet_projetitems", "FK_projet")) {
        $query = "ALTER TABLE `glpi_plugin_projet_projetitems` \n                  CHANGE `FK_projet` `plugin_projet_projets_id` int(11) NOT NULL default '0'";
        $DB->query($query);
    }
    if (FieldExists("glpi_plugin_projet_projetitems", "FK_device")) {
        $query = "ALTER TABLE `glpi_plugin_projet_projetitems` \n                  CHANGE `FK_device` `items_id` int(11) NOT NULL default '0'";
        $DB->query($query);
    }
    if (FieldExists("glpi_plugin_projet_projetitems", "device_type")) {
        $query = "ALTER TABLE `glpi_plugin_projet_projetitems` \n                  CHANGE `device_type` `itemtype` varchar(100) NOT NULL default '0'";
        $DB->query($query);
    }
    if (isIndex("glpi_plugin_projet_projetitems", "FK_device")) {
        $query = "ALTER TABLE `glpi_plugin_projet_projetitems` \n                  DROP INDEX `FK_device` ,\n                  ADD INDEX `items_id` (`items_id`,`plugin_projet_projets_id`) ";
        $DB->query($query);
    }
    if (isIndex("glpi_plugin_projet_projetitems", "FK_projet")) {
        $query = "ALTER TABLE `glpi_plugin_projet_projetitems` \n                  DROP INDEX `FK_projet` ,\n                  ADD INDEX `plugin_projet_projets_id` (`plugin_projet_projets_id`) ";
        $DB->query($query);
    }
    if (isIndex("glpi_plugin_projet_projetitems", "FK_device_2")) {
        $query = "ALTER TABLE `glpi_plugin_projet_projetitems` \n                  DROP INDEX `FK_device_2` ,\n                  ADD INDEX `items_id_2` (`items_id`) ";
        $DB->query($query);
    }
    if (isIndex("glpi_plugin_projet_projetitems", "device_type")) {
        $query = "ALTER TABLE `glpi_plugin_projet_projetitems` \n                  DROP INDEX `device_type` ,\n                  ADD INDEX itemtype (`itemtype`) ";
        $DB->query($query);
    }
    // ** Update glpi_plugin_projet_tasks
    if (FieldExists("glpi_plugin_projet_tasks", "ID")) {
        $query = "ALTER TABLE `glpi_plugin_projet_tasks` \n                  CHANGE `ID` `id` INT( 11 ) NOT NULL AUTO_INCREMENT";
        $DB->query($query);
    }
    if (FieldExists("glpi_plugin_projet_tasks", "FK_projet")) {
        $query = "ALTER TABLE `glpi_plugin_projet_tasks` \n                  CHANGE `FK_projet` `plugin_projet_projets_id` int(4) NOT NULL default '0'";
        $DB->query($query);
    }
    if (FieldExists("glpi_plugin_projet_tasks", "FK_users")) {
        $query = "ALTER TABLE `glpi_plugin_projet_tasks` \n                  CHANGE `FK_users` `users_id` int(11) NOT NULL default '0'";
        $DB->query($query);
    }
    if (FieldExists("glpi_plugin_projet_tasks", "FK_groups")) {
        $query = "ALTER TABLE `glpi_plugin_projet_tasks` \n                  CHANGE `FK_groups` `groups_id` int(11) NOT NULL default '0'";
        $DB->query($query);
    }
    if (FieldExists("glpi_plugin_projet_tasks", "FK_enterprise")) {
        $query = "ALTER TABLE `glpi_plugin_projet_tasks` \n                  CHANGE `FK_enterprise` `suppliers_id` int(11) NOT NULL default '0'";
        $DB->query($query);
    }
    if (FieldExists("glpi_plugin_projet_tasks", "type_task")) {
        $query = "ALTER TABLE `glpi_plugin_projet_tasks` \n                  CHANGE `type_task` `plugin_projet_tasktypes_id` int(4) NOT NULL default '0'";
        $DB->query($query);
    }
    if (FieldExists("glpi_plugin_projet_tasks", "status")) {
        $query = "ALTER TABLE `glpi_plugin_projet_tasks` \n                  CHANGE `status` `plugin_projet_taskstates_id` int(4) NOT NULL default '0'";
        $DB->query($query);
    }
    if (FieldExists("glpi_plugin_projet_tasks", "parentID")) {
        $query = "ALTER TABLE `glpi_plugin_projet_tasks` \n                  CHANGE `parentID` `plugin_projet_tasks_id` int(11) NOT NULL default '0'";
        $DB->query($query);
    }
    if (FieldExists("glpi_plugin_projet_tasks", "location")) {
        $query = "ALTER TABLE `glpi_plugin_projet_tasks` \n                  CHANGE `location` `locations_id` INT( 11 ) NOT NULL";
        $DB->query($query);
    }
    if (FieldExists("glpi_plugin_projet_tasks", "tplname")) {
        $query = "ALTER TABLE `glpi_plugin_projet_tasks` \n                  CHANGE `tplname` `template_name` varchar(255) collate utf8_unicode_ci NOT NULL default ''";
        $DB->query($query);
    }
    if (FieldExists("glpi_plugin_projet_tasks", "deleted")) {
        $query = "ALTER TABLE `glpi_plugin_projet_tasks` \n                  CHANGE `deleted` `is_deleted` smallint(6) NOT NULL default '0'";
        $DB->query($query);
    }
    // ** Update glpi_plugin_projet_taskitems
    if (TableExists("glpi_plugin_projet_tasks_items")) {
        $query = "RENAME TABLE `glpi_plugin_projet_tasks_items` TO `glpi_plugin_projet_taskitems` ";
        $DB->query($query);
    }
    if (FieldExists("glpi_plugin_projet_taskitems", "ID")) {
        $query = "ALTER TABLE `glpi_plugin_projet_taskitems` \n                  CHANGE `ID` `id` INT( 11 ) NOT NULL AUTO_INCREMENT";
        $DB->query($query);
    }
    if (FieldExists("glpi_plugin_projet_taskitems", "FK_task")) {
        $query = "ALTER TABLE `glpi_plugin_projet_taskitems` \n                  CHANGE `FK_task` `plugin_projet_tasks_id` int(11) NOT NULL default '0'";
        $DB->query($query);
    }
    if (FieldExists("glpi_plugin_projet_taskitems", "FK_device")) {
        $query = "ALTER TABLE `glpi_plugin_projet_taskitems` \n                  CHANGE `FK_device` `items_id` int(11) NOT NULL default '0'";
        $DB->query($query);
    }
    if (FieldExists("glpi_plugin_projet_taskitems", "device_type")) {
        $query = "ALTER TABLE `glpi_plugin_projet_taskitems` \n                  CHANGE `device_type` `itemtype` int(11) NOT NULL default '0'";
        $DB->query($query);
    }
    if (isIndex("glpi_plugin_projet_taskitems", "FK_device")) {
        $query = "ALTER TABLE `glpi_plugin_projet_taskitems` \n                  DROP INDEX `FK_device` ,\n                  ADD INDEX `items_id` (`items_id`,`plugin_projet_tasks_id`) ";
        $DB->query($query);
    }
    if (isIndex("glpi_plugin_projet_taskitems", "FK_task")) {
        $query = "ALTER TABLE `glpi_plugin_projet_taskitems` \n                  DROP INDEX `FK_task` ,\n                  ADD INDEX `plugin_projet_tasks_id` (`plugin_projet_tasks_id`)";
        $DB->query($query);
    }
    if (isIndex("glpi_plugin_projet_taskitems", "FK_device_2")) {
        $query = "ALTER TABLE `glpi_plugin_projet_taskitems` \n                  DROP INDEX `FK_device_2` ,\n                  ADD INDEX `items_id_2` (`items_id`) ";
        $DB->query($query);
    }
    if (isIndex("glpi_plugin_projet_taskitems", "device_type")) {
        $query = "ALTER TABLE `glpi_plugin_projet_taskitems` \n                  DROP INDEX `device_type` ,\n                  ADD INDEX `itemtype` (`itemtype`) ";
        $DB->query($query);
    }
    // ** Update glpi_plugin_projet_projetstates
    if (TableExists("glpi_dropdown_plugin_projet_status")) {
        $query = "RENAME TABLE `glpi_dropdown_plugin_projet_status` TO `glpi_plugin_projet_projetstates` ";
        $DB->query($query);
    }
    if (FieldExists("glpi_plugin_projet_projetstates", "ID")) {
        $query = "ALTER TABLE `glpi_plugin_projet_projetstates` \n                  CHANGE `ID` `id` INT( 11 ) NOT NULL AUTO_INCREMENT";
        $DB->query($query);
    }
    if (FieldExists("glpi_plugin_projet_projetstates", "comments")) {
        $query = "ALTER TABLE `glpi_plugin_projet_projetstates` \n                  CHANGE `comments` `comment` TEXT CHARACTER \n                     SET utf8 COLLATE utf8_unicode_ci NULL DEFAULT NULL";
        $DB->query($query);
    }
    // ** Update glpi_plugin_projet_tasktypes
    if (TableExists("glpi_dropdown_plugin_projet_tasks_type")) {
        $query = "RENAME TABLE `glpi_dropdown_plugin_projet_tasks_type` TO `glpi_plugin_projet_tasktypes` ";
        $DB->query($query);
    }
    if (FieldExists("glpi_plugin_projet_tasktypes", "ID")) {
        $query = "ALTER TABLE `glpi_plugin_projet_tasktypes` \n                  CHANGE `ID` `id` INT( 11 ) NOT NULL AUTO_INCREMENT";
        $DB->query($query);
    }
    if (FieldExists("glpi_plugin_projet_tasktypes", "FK_entities")) {
        $query = "ALTER TABLE `glpi_plugin_projet_tasktypes` \n                  CHANGE `FK_entities` `entities_id` int(11) NOT NULL default '0'";
        $DB->query($query);
    }
    if (FieldExists("glpi_plugin_projet_tasktypes", "comments")) {
        $query = "ALTER TABLE `glpi_plugin_projet_tasktypes` \n                  CHANGE `comments` `comment` TEXT CHARACTER \n                     SET utf8 COLLATE utf8_unicode_ci NULL DEFAULT NULL";
        $DB->query($query);
    }
    // ** Update glpi_plugin_projet_taskstates
    if (TableExists("glpi_dropdown_plugin_projet_task_status")) {
        $query = "RENAME TABLE `glpi_dropdown_plugin_projet_task_status` TO `glpi_plugin_projet_taskstates` ";
        $DB->query($query);
    }
    if (FieldExists("glpi_plugin_projet_taskstates", "ID")) {
        $query = "ALTER TABLE `glpi_plugin_projet_taskstates` \n                  CHANGE `ID` `id` INT( 11 ) NOT NULL AUTO_INCREMENT";
        $DB->query($query);
    }
    if (FieldExists("glpi_plugin_projet_taskstates", "comments")) {
        $query = "ALTER TABLE `glpi_plugin_projet_taskstates` \n                  CHANGE `comments` `comment` TEXT CHARACTER \n                     SET utf8 COLLATE utf8_unicode_ci NULL DEFAULT NULL";
        $DB->query($query);
    }
    // ** Update glpi_plugin_projet_mailings
    if (TableExists("glpi_plugin_projet_mailing")) {
        $query = "RENAME TABLE `glpi_plugin_projet_mailing` TO `glpi_plugin_projet_mailings` ";
        $DB->query($query);
    }
    if (FieldExists("glpi_plugin_projet_mailings", "ID")) {
        $query = "ALTER TABLE `glpi_plugin_projet_mailings` \n                  CHANGE `ID` `id` INT( 11 ) NOT NULL AUTO_INCREMENT";
        $DB->query($query);
    }
    if (FieldExists("glpi_plugin_projet_mailings", "FK_item")) {
        $query = "ALTER TABLE `glpi_plugin_projet_mailings` \n                  CHANGE `FK_item` `plugin_projet_items_id` int(11) NOT NULL default '0'";
        $DB->query($query);
    }
    if (FieldExists("glpi_plugin_projet_mailings", "item_type")) {
        $query = "ALTER TABLE `glpi_plugin_projet_mailings` \n                  CHANGE `item_type` `itemtype` int(11) NOT NULL default '0'";
        $DB->query($query);
    }
    if (isIndex("glpi_plugin_projet_mailings", "FK_item")) {
        $query = "ALTER TABLE `glpi_plugin_projet_mailings` \n                  DROP INDEX `FK_item` ,\n                  ADD INDEX `plugin_projet_items_id` (`plugin_projet_items_id`) ";
        $DB->query($query);
    }
    if (isIndex("glpi_plugin_projet_mailings", "item_type")) {
        $query = "ALTER TABLE `glpi_plugin_projet_mailings` \n                  DROP INDEX `item_type` ,\n                  ADD INDEX `itemtype` (`itemtype`) ";
        $DB->query($query);
    }
    // ** Update glpi_plugin_projet_profiles
    if (FieldExists("glpi_plugin_projet_profiles", "ID")) {
        $query = "ALTER TABLE `glpi_plugin_projet_profiles` \n                  CHANGE `ID` `id` INT( 11 ) NOT NULL AUTO_INCREMENT";
        $DB->query($query);
    }
    // Update itemtype in display preferences
    $query = "UPDATE `glpi_displaypreferences` \n               SET `itemtype` = 'PluginProjetProjet' WHERE `itemtype` = '2300'";
    $DB->query($query);
    $query = "UPDATE `glpi_displaypreferences` \n               SET `itemtype` = 'PluginProjetTask' WHERE `itemtype` = '2301'";
    $DB->query($query);
    // Update itemtype in tickets
    $query = "UPDATE `glpi_tickets` \n               SET `itemtype` = 'PluginProjetProjet' WHERE `itemtype` = '2300'";
    $DB->query($query);
    $query = "UPDATE `glpi_tickets` \n               SET `itemtype` = 'PluginProjetTask' WHERE `itemtype` = '2301'";
    $DB->query($query);
    // Update itemtype in bookmarks
    $query = "UPDATE `glpi_bookmarks` \n               SET `itemtype` = 'PluginProjetProjet' WHERE `itemtype` = '2300'";
    $DB->query($query);
    $query = "UPDATE `glpi_bookmarks` \n               SET `itemtype` = 'PluginProjetTask' WHERE `itemtype` = '2301'";
    $DB->query($query);
    $query = "UPDATE `glpi_bookmarks_users` \n               SET `itemtype` = 'PluginProjetProjet' WHERE `itemtype` = '2300'";
    $DB->query($query);
    $query = "UPDATE `glpi_bookmarks_users` \n               SET `itemtype` = 'PluginProjetTask' WHERE `itemtype` = '2301'";
    $DB->query($query);
    // Update itemtype for contracts
    $query = "UPDATE `glpi_contracts_items` \n               SET `itemtype` = 'PluginProjetProjet' WHERE `itemtype` = '2300'";
    $DB->query($query);
    $query = "UPDATE `glpi_contracts_items` \n               SET `itemtype` = 'PluginProjetTask' WHERE `itemtype` = '2301'";
    $DB->query($query);
    // Update itemtype for documents
    $query = "UPDATE `glpi_documents_items` \n               SET `itemtype` = 'PluginProjetProjet' WHERE `itemtype` = '2300'";
    $DB->query($query);
    $query = "UPDATE `glpi_documents_items` \n               SET `itemtype` = 'PluginProjetTask' WHERE `itemtype` = '2301'";
    $DB->query($query);
    // Update itemtype for logs
    $query = "UPDATE `glpi_logs` \n               SET `itemtype` = 'PluginProjetProjet' WHERE `itemtype` = '2300'";
    $DB->query($query);
    $query = "UPDATE `glpi_logs` \n               SET `itemtype` = 'PluginProjetTask' WHERE `itemtype` = '2301'";
    $DB->query($query);
    // Update itemtype
    // 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");
    foreach ($typetoname as $key => $val) {
        $query = "UPDATE `glpi_plugin_projet_projetitems` \n                  SET `itemtype` = '{$val}' WHERE `itemtype` = '{$key}'";
        $DB->query($query);
        $query = "UPDATE `glpi_plugin_projet_taskitems` \n                  SET `itemtype` = '{$val}' WHERE `itemtype` = '{$key}'";
        $DB->query($query);
        $query = "UPDATE `glpi_plugin_projet_mailings` \n                  SET `itemtype` = '{$val}' WHERE `itemtype` = '{$key}'";
        $DB->query($query);
    }
}
Example #9
0
function update0681to07()
{
    global $DB, $CFG_GLPI;
    $DB->query("SET NAMES 'latin1'");
    // Improve user table :
    if (!isIndex("glpi_users", "firstname")) {
        $query = "ALTER TABLE `glpi_users`\n                ADD INDEX (`firstname`)";
        $DB->queryOrDie($query, "0.7 alter users add index on firstname");
    }
    if (!isIndex("glpi_users", "realname")) {
        $query = "ALTER TABLE `glpi_users`\n                ADD INDEX (`realname`)";
        $DB->queryOrDie($query, "0.7 alter users add index on realname");
    }
    // Decimal problem
    if (FieldExists("glpi_infocoms", "value", false)) {
        $query = "ALTER TABLE `glpi_infocoms`\n                CHANGE `value` `value` DECIMAL( 20, 4 ) NOT NULL DEFAULT '0'";
        $DB->queryOrDie($query, "0.7 alter value in glpi_infocoms");
    }
    if (FieldExists("glpi_infocoms", "warranty_value", false)) {
        $query = "ALTER TABLE `glpi_infocoms`\n                CHANGE warranty_value warranty_value DECIMAL( 20, 4 ) NOT NULL DEFAULT '0'";
        $DB->queryOrDie($query, "0.7 alter warranty_value in glpi_infocoms");
    }
    if (FieldExists("glpi_tracking", "cost_time", false)) {
        $query = "ALTER TABLE `glpi_tracking`\n                CHANGE cost_time cost_time DECIMAL( 20, 4 ) NOT NULL DEFAULT '0'";
        $DB->queryOrDie($query, "0.7 alter cost_time in glpi_tracking");
    }
    if (FieldExists("glpi_tracking", "cost_fixed", false)) {
        $query = "ALTER TABLE `glpi_tracking`\n                CHANGE cost_fixed cost_fixed DECIMAL( 20, 4 ) NOT NULL DEFAULT '0'";
        $DB->queryOrDie($query, "0.7 alter cost_fixed in glpi_tracking");
    }
    if (FieldExists("glpi_tracking", "cost_material", false)) {
        $query = "ALTER TABLE `glpi_tracking`\n                CHANGE cost_material cost_material DECIMAL( 20, 4 ) NOT NULL DEFAULT '0'";
        $DB->queryOrDie($query, "0.7 alter cost_material in glpi_tracking");
    }
    if (!FieldExists("glpi_config", "decimal_number", false)) {
        $query = "ALTER TABLE `glpi_config`\n                ADD `decimal_number` INT DEFAULT '2'";
        $DB->queryOrDie($query, "0.7 add decimal_number in glpi_config");
    }
    $CFG_GLPI["decimal_number"] = 2;
    if (!FieldExists("glpi_config", "cas_logout", false)) {
        $query = "ALTER TABLE `glpi_config`\n                ADD `cas_logout` VARCHAR( 255 ) NULL AFTER `cas_uri`";
        $DB->queryOrDie($query, "0.7 add cas_logout in glpi_config");
    }
    if (!isIndex("glpi_computer_device", "specificity")) {
        $query = "ALTER TABLE `glpi_computer_device`\n                ADD INDEX (`specificity`)";
        $DB->queryOrDie($query, "0.7 add index specificity in glpi_computer_device");
    }
    if (!FieldExists("glpi_docs", "comments", false)) {
        $query = "ALTER TABLE `glpi_docs`\n                CHANGE `comment` `comments` TEXT DEFAULT NULL ";
        $DB->queryOrDie($query, "0.7 alter docs.comment to be comments");
    }
    // Update polish langage file
    $query = "UPDATE `glpi_users`\n             SET `language` = 'pl_PL'\n             WHERE `language` = 'po_PO'";
    $DB->queryOrDie($query, "0.7 update polish lang file");
    // Add show_group_hardware
    if (!FieldExists("glpi_profiles", "show_group_hardware", false)) {
        $query = "ALTER TABLE `glpi_profiles`\n                ADD `show_group_hardware` CHAR(1) NULL DEFAULT '0'";
        $DB->queryOrDie($query, "0.7 alter glpi_profiles add show_group_hardware");
        $query = "UPDATE `glpi_profiles`\n                SET `show_group_hardware` = `show_group_ticket`";
        $DB->queryOrDie($query, "0.7 alter glpi_profiles add show_group_hardware");
    }
    // Clean doc association
    if (FieldExists("glpi_doc_device", "is_template", false)) {
        $query = "ALTER TABLE `glpi_doc_device`\n                DROP `is_template`";
        $DB->queryOrDie($query, "0.7 delete is_template from glpi_doc_device");
    }
    // Clean contract association
    if (FieldExists("glpi_contract_device", "is_template", false)) {
        $query = "ALTER TABLE `glpi_contract_device`\n                DROP `is_template`";
        $DB->queryOrDie($query, "0.7 delete is_template from glpi_contract_device");
    }
    //// ENTITY MANAGEMENT
    if (!TableExists("glpi_entities")) {
        $query = "CREATE TABLE `glpi_entities` (\n                  `ID` int(11) NOT NULL auto_increment,\n                  `name` varchar(255) NOT NULL,\n                  `parentID` int(11) NOT NULL default '0',\n                  `completename` text NOT NULL,\n                  `comments` text,\n                  `level` int(11) default NULL,\n                  PRIMARY KEY (`ID`),\n                  UNIQUE KEY `name` (`name`,`parentID`),\n                  KEY `parentID` (`parentID`)\n                ) ENGINE=MyISAM";
        $DB->queryOrDie($query, "0.7 create glpi_entities");
    }
    if (!TableExists("glpi_entities_data")) {
        $query = "CREATE TABLE `glpi_entities_data` (\n                  `ID` int(11) NOT NULL auto_increment,\n                  `FK_entities` int(11) NOT NULL default '0',\n                  `address` text,\n                  `postcode` varchar(255) default NULL,\n                  `town` varchar(255) default NULL,\n                  `state` varchar(255) default NULL,\n                  `country` varchar(255) default NULL,\n                  `website` varchar(200) default NULL,\n                  `phonenumber` varchar(200) default NULL,\n                  `fax` varchar(255) default NULL,\n                  `email` varchar(255) default NULL,\n                  `notes` longtext,\n                  PRIMARY KEY (`ID`),\n                  UNIQUE KEY `FK_entities` (`FK_entities`)\n                ) ENGINE=MyISAM";
        $DB->queryOrDie($query, "0.7 create glpi_entities_data");
    }
    // Add default profile to all users without any profile
    $query = "SELECT `ID`\n             FROM `glpi_profiles`\n             WHERE `is_default` = '1'";
    if ($result = $DB->query($query)) {
        if ($DB->numrows($result) > 0) {
            $IDprof = $DB->result($result, 0, 0);
            $query = "SELECT `glpi_users`.`ID`\n                   FROM `glpi_users`\n                   LEFT JOIN `glpi_users_profiles`\n                        ON (`glpi_users_profiles`.`FK_users` = `glpi_users`.`ID`)\n                   WHERE `glpi_users_profiles`.`ID` IS NULL";
            if ($result = $DB->query($query)) {
                if ($DB->numrows($result) > 0) {
                    while ($data = $DB->fetch_assoc($result)) {
                        $query = "INSERT INTO `glpi_users_profiles`\n                                   (`FK_users`, `FK_profiles`)\n                            VALUES ('" . $data['ID'] . "', '{$IDprof}') ";
                        $DB->query($query);
                    }
                }
            }
        }
    }
    if (!FieldExists("glpi_users_profiles", "FK_entities", false)) {
        // Clean Datas
        $query = "DELETE\n                FROM `glpi_users_profiles`\n                WHERE `FK_users` = '0'";
        $DB->queryOrDie($query, "0.7 clean datas of glpi_users_profiles");
        $query = " ALTER TABLE `glpi_users_profiles`\n                 ADD `FK_entities` INT NOT NULL DEFAULT '0',\n                 ADD `recursive` SMALLINT NOT NULL DEFAULT '1',\n                 ADD `dynamic` SMALLINT NOT NULL DEFAULT '0' ";
        $DB->queryOrDie($query, "0.7 alter glpi_users_profiles");
    }
    // Correct for clean active field for beta users
    if (FieldExists("glpi_users_profiles", "active", false)) {
        $query = "ALTER TABLE `glpi_users_profiles`\n                DROP `active` ";
        $DB->queryOrDie($query, "0.7 clean active field for beta of glpi_users_profiles");
    }
    if (!FieldExists("glpi_users", "active", false)) {
        $query = "ALTER TABLE `glpi_users`\n                ADD `active` INT(2) NOT NULL DEFAULT '1' ";
        $DB->queryOrDie($query, "0.7 add active field for beta of glpi_users");
        if (!isIndex("glpi_users", "active")) {
            $query = "ALTER TABLE `glpi_users`\n                   ADD INDEX (`active`)";
            $DB->queryOrDie($query, "0.7 add index active in glpi_users");
        }
    }
    // Add entity tags to tables
    $tables = array("glpi_cartridges_type", "glpi_computers", "glpi_consumables_type", "glpi_contacts", "glpi_contracts", "glpi_docs", "glpi_dropdown_locations", "glpi_dropdown_netpoint", "glpi_enterprises", "glpi_groups", "glpi_monitors", "glpi_networking", "glpi_peripherals", "glpi_phones", "glpi_printers", "glpi_reminder", "glpi_software", "glpi_tracking");
    // "glpi_kbitems","glpi_dropdown_kbcategories", -> easier to manage
    // "glpi_followups" -> always link to tracking ?
    // "glpi_licenses" -> always link to software ?
    // "glpi_infocoms" -> always link to item ? PB on reports stats ?
    // "glpi_links" -> global items easier to manage
    // "glpi_reservation_item", "glpi_state_item" -> always link to item ? but info maybe needed
    foreach ($tables as $tbl) {
        if (!FieldExists($tbl, "FK_entities", false)) {
            $query = "ALTER TABLE `{$tbl}`\n                   ADD `FK_entities` INT NOT NULL DEFAULT '0' AFTER `ID`";
            $DB->queryOrDie($query, "0.7 add FK_entities in {$tbl}");
        }
        if (!isIndex($tbl, "FK_entities")) {
            $query = "ALTER TABLE `{$tbl}`\n                   ADD INDEX (`FK_entities`)";
            $DB->queryOrDie($query, "0.7 add index FK_entities in {$tbl}");
        }
    }
    // Regenerate Indexes :
    $tables = array("glpi_dropdown_locations");
    foreach ($tables as $tbl) {
        if (isIndex($tbl, "name")) {
            $query = "ALTER TABLE `{$tbl}`\n                   DROP INDEX `name`";
            $DB->queryOrDie($query, "0.7 drop index name in {$tbl}");
        }
        if (isIndex($tbl, "parentID_2")) {
            $query = "ALTER TABLE `{$tbl}`\n                   DROP INDEX `parentID_2`";
            $DB->queryOrDie($query, "0.7 drop index name in {$tbl}");
        }
        $query = "ALTER TABLE `{$tbl}`\n                ADD UNIQUE(`name`,`parentID`,`FK_entities`)";
        $DB->queryOrDie($query, "0.7 add index name in {$tbl}");
    }
    if (isIndex("glpi_users_profiles", "FK_users_profiles")) {
        $query = "ALTER TABLE `glpi_users_profiles`\n                DROP INDEX `FK_users_profiles`";
        $DB->queryOrDie($query, "0.7 drop index FK_users_profiles in glpi_users_profiles");
    }
    if (!isIndex("glpi_users_profiles", "FK_entities")) {
        $query = "ALTER TABLE `glpi_users_profiles`\n                ADD INDEX (`FK_entities`)";
        $DB->queryOrDie($query, "0.7 add index FK_entities in glpi_users_profiles");
    }
    if (!isIndex("glpi_users_profiles", "recursive")) {
        $query = "ALTER TABLE `glpi_users_profiles`\n                ADD INDEX (`recursive`)";
        $DB->queryOrDie($query, "0.7 add index recursive in glpi_users_profiles");
    }
    //// MULTIAUTH MANAGEMENT
    if (!TableExists("glpi_auth_ldap")) {
        $query = "CREATE TABLE `glpi_auth_ldap` (\n                  `ID` int(11) NOT NULL auto_increment,\n                  `name` varchar(255) NOT NULL,\n                  `ldap_host` varchar(255) default NULL,\n                  `ldap_basedn` varchar(255) default NULL,\n                  `ldap_rootdn` varchar(255) default NULL,\n                  `ldap_pass` varchar(255) default NULL,\n                  `ldap_port` varchar(255) NOT NULL default '389',\n                  `ldap_condition` varchar(255) default NULL,\n                  `ldap_login` varchar(255) NOT NULL default 'uid',\n                  `ldap_use_tls` varchar(255) NOT NULL default '0',\n                  `ldap_field_group` varchar(255) default NULL,\n                  `ldap_group_condition` varchar(255) default NULL,\n                  `ldap_search_for_groups` int NOT NULL default '0',\n                  `ldap_field_group_member` varchar(255) default NULL,\n                  `ldap_field_email` varchar(255) default NULL,\n                  `ldap_field_realname` varchar(255) default NULL,\n                  `ldap_field_firstname` varchar(255) default NULL,\n                  `ldap_field_phone` varchar(255) default NULL,\n                  `ldap_field_phone2` varchar(255) default NULL,\n                  `ldap_field_mobile` varchar(255) default NULL,\n                  `ldap_field_comments` TEXT default NULL,\n                  PRIMARY KEY  (`ID`)\n                ) ENGINE=MyISAM";
        $DB->queryOrDie($query, "0.7 create glpi_auth_ldap");
        $query = "SELECT *\n                FROM `glpi_config`\n                WHERE `ID` = '1'";
        $result = $DB->query($query);
        $config = $DB->fetch_array($result);
        if (!empty($config["ldap_host"])) {
            //Transfer ldap information into the new table
            $query = "INSERT INTO `glpi_auth_ldap`\n                   VALUES (NULL, '" . $config["ldap_host"] . "', '" . $config["ldap_host"] . "',\n                           '" . $config["ldap_basedn"] . "', '" . $config["ldap_rootdn"] . "',\n                           '" . $config["ldap_pass"] . "', " . $config["ldap_port"] . ",\n                           '" . $config["ldap_condition"] . "', '" . $config["ldap_login"] . "',\n                           '" . $config["ldap_use_tls"] . "', '" . $config["ldap_field_group"] . "',\n                           '" . $config["ldap_condition"] . "', " . $config["ldap_search_for_groups"] . ",\n                           '" . $config["ldap_field_group_member"] . "', '" . $config["ldap_field_email"] . "',\n                           '" . $config["ldap_field_realname"] . "', '" . $config["ldap_field_firstname"] . "',\n                           '" . $config["ldap_field_phone"] . "', '" . $config["ldap_field_phone2"] . "',\n                           '" . $config["ldap_field_mobile"] . "', NULL)";
            $DB->queryOrDie($query, "0.7 transfert of ldap parameters into glpi_auth_ldap");
        }
        $query = "ALTER TABLE `glpi_config`\n                DROP `ldap_field_email`,\n                DROP `ldap_port`,\n                DROP `ldap_host`,\n                DROP `ldap_basedn`,\n                DROP `ldap_rootdn`,\n                DROP `ldap_pass`,\n                DROP `ldap_field_location`,\n                DROP `ldap_field_realname`,\n                DROP `ldap_field_firstname`,\n                DROP `ldap_field_phone`,\n                DROP `ldap_field_phone2`,\n                DROP `ldap_field_mobile`,\n                DROP `ldap_condition`,\n                DROP `ldap_login`,\n                DROP `ldap_use_tls`,\n                DROP `ldap_field_group`,\n                DROP `ldap_group_condition`,\n                DROP `ldap_search_for_groups`,\n                DROP `ldap_field_group_member`";
        $DB->queryOrDie($query, "0.7 drop ldap fields from glpi_config");
    }
    if (!FieldExists("glpi_users", "id_auth", false)) {
        $query = "ALTER TABLE `glpi_users`\n                ADD `id_auth` INT NOT NULL DEFAULT '-1',\n                ADD `auth_method` INT NOT NULL DEFAULT '-1',\n                ADD `last_login` DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00',\n                ADD `date_mod` DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00'";
        $DB->queryOrDie($query, "0.7 add auth_method & id_method in glpi_users");
    }
    if (!TableExists("glpi_auth_mail")) {
        $query = "CREATE TABLE `glpi_auth_mail` (\n                  `ID` int(11) NOT NULL auto_increment,\n                  `name` varchar(255) NOT NULL,\n                  `imap_auth_server` varchar(200) default NULL,\n                  `imap_host` varchar(200) default NULL,\n                  PRIMARY KEY (`ID`)\n                ) ENGINE=MyISAM";
        $DB->queryOrDie($query, "0.7 create glpi_auth_mail");
        $query = "select * from glpi_config WHERE ID=1";
        $result = $DB->query($query);
        $config = $DB->fetch_array($result);
        if (!empty($config["imap_host"])) {
            //Transfer ldap information into the new table
            $query = "INSERT INTO `glpi_auth_mail`\n                   VALUES (NULL, '" . $config["imap_host"] . "', '" . $config["imap_auth_server"] . "',\n                           '" . $config["imap_host"] . "')";
            $DB->queryOrDie($query, "0.7 transfert of mail parameters into glpi_auth_mail");
        }
        $query = "ALTER TABLE `glpi_config`\n                DROP `imap_auth_server`,\n                DROP `imap_host`";
        $DB->queryOrDie($query, "0.7 drop mail fields from glpi_config");
    }
    // Clean state_item -> add a field from tables
    if (TableExists("glpi_state_item")) {
        $state_type = array(SOFTWARE_TYPE => 'glpi_software', COMPUTER_TYPE => 'glpi_computers', PRINTER_TYPE => 'glpi_printers', MONITOR_TYPE => 'glpi_monitors', PERIPHERAL_TYPE => 'glpi_peripherals', NETWORKING_TYPE => 'glpi_networking', PHONE_TYPE => 'glpi_phones');
        foreach ($state_type as $type => $table) {
            if (!FieldExists($table, "state", false)) {
                $query = "ALTER TABLE `{$table}`\n                      ADD `state` INT NOT NULL DEFAULT '0'";
                $DB->queryOrDie($query, "0.7 add state field to {$table}");
                $query2 = "SELECT *\n                       FROM `glpi_state_item`\n                       WHERE `device_type` = '{$type}'";
                $result = $DB->query($query2);
                if ($DB->numrows($result)) {
                    while ($data = $DB->fetch_array($result)) {
                        $query3 = "UPDATE `{$table}`\n                             SET `state` = '" . $data["state"] . "'\n                             WHERE `ID` = '" . $data["id_device"] . "'";
                        $DB->queryOrDie($query3, "0.7 update state field value to {$table}");
                    }
                }
            }
        }
        $query = "DROP TABLE `glpi_state_item` ";
        $DB->queryOrDie($query, "0.7 drop table state_item");
        $query = "INSERT INTO `glpi_display`\n                       (`type`, `num`, `rank`, `FK_users`)\n                VALUES (22, 31, 1, 0)";
        $DB->queryOrDie($query, "0.7 add default search for states");
        // Add for reservation
        $query = "INSERT INTO `glpi_display`\n                       (`type`, `num`, `rank`, `FK_users`)\n                VALUES ( 29, 4, 1, 0)";
        $DB->queryOrDie($query, "0.7 add defaul search for reservation");
        $query = "INSERT INTO `glpi_display`\n                       (`type`, `num`, `rank`, `FK_users`)\n                VALUES ( 29, 3, 2, 0)";
        $DB->queryOrDie($query, "0.7 add defaul search for reservation");
    }
    // Add ticket_tco for hardwares
    $tco_tbl = array(SOFTWARE_TYPE => 'glpi_software', COMPUTER_TYPE => 'glpi_computers', PRINTER_TYPE => 'glpi_printers', MONITOR_TYPE => 'glpi_monitors', PERIPHERAL_TYPE => 'glpi_peripherals', NETWORKING_TYPE => 'glpi_networking', PHONE_TYPE => 'glpi_phones');
    foreach ($tco_tbl as $type => $table) {
        if (!FieldExists($table, "ticket_tco", false)) {
            $query = "ALTER TABLE `{$table}`\n                   ADD `ticket_tco` DECIMAL( 20, 4 ) DEFAULT '0.0000'";
            $DB->queryOrDie($query, "0.7 alter {$table} add ticket_tco");
            // Update values
            $query = "SELECT DISTINCT `device_type`, `computer`\n                   FROM `glpi_tracking`\n                   WHERE `device_type` = '{$type}'\n                         AND (`cost_time` > 0\n                              OR `cost_fixed` > 0\n                              OR `cost_material` > 0)";
            $result = $DB->queryOrDie($query, "0.7 update ticket_tco");
            if ($DB->numrows($result)) {
                while ($data = $DB->fetch_array($result)) {
                    $query2 = "UPDATE `{$table}`\n                          SET `ticket_tco` = '" . computeTicketTco($type, $data["computer"]) . "'\n                          WHERE `ID` = '" . $data["computer"] . "'";
                    $DB->queryOrDie($query2, "0.7 update ticket_tco");
                }
            }
        }
    }
    if (!FieldExists("glpi_software", "helpdesk_visible", false)) {
        $query = "ALTER TABLE `glpi_software`\n                ADD `helpdesk_visible` INT NOT NULL default '1'";
        $DB->queryOrDie($query, "0.7 add helpdesk_visible in glpi_software");
    }
    if (!TableExists("glpi_dropdown_manufacturer")) {
        $query = "CREATE TABLE `glpi_dropdown_manufacturer` (\n                  `ID` int(11) NOT NULL auto_increment,\n                  `name` varchar(255) NOT NULL,\n                  `comments` text,\n                  PRIMARY KEY (`ID`),\n                  KEY `name` (`name`)\n                ) ENGINE=MyISAM";
        $DB->queryOrDie($query, "0.7 add dropdown_manufacturer table");
    }
    if (countElementsInTable("glpi_dropdown_manufacturer") == 0) {
        // Fill table
        $query = "SELECT *\n                FROM `glpi_enterprises`\n                ORDER BY `ID`";
        if ($result = $DB->query($query)) {
            if ($DB->numrows($result)) {
                while ($data = $DB->fetch_assoc($result)) {
                    $data = Toolbox::addslashes_deep($data);
                    $comments = "";
                    if (!empty($data['address'])) {
                        if (!empty($comments)) {
                            $comments .= "\n";
                        }
                        $comments .= sprintf(__('%1$s: %2$s'), __('Address'), $data['address']);
                    }
                    if (!empty($data['postcode']) || !empty($data['town'])) {
                        if (!empty($comments)) {
                            $comments = sprintf(__('%1$s %2$s', $comments, __('Address'))) . "\n";
                        }
                        //TRANS: %1$s is postcode, %2$s is town
                        $comments .= sprintf(__('%1$s %2$s'), $data['postcode'], $data['town']);
                    }
                    if (!empty($data['state']) || !empty($data['country'])) {
                        if (!empty($comments)) {
                            $comments = sprintf(__('%1$s %2$s', $comments, __('Address'))) . "\n";
                        }
                        //TRANS: %1$s is country, %2$s is state
                        $comments .= sprintf(__('%1$s %2$s'), $data['country'], $data['state']);
                    }
                    if (!empty($data['website'])) {
                        if (!empty($comments)) {
                            $comments .= "\n";
                        }
                        $comments .= sprintf(__('%1$s: %2$s'), __('Website'), $data['website']);
                    }
                    if (!empty($data['phonenumber'])) {
                        if (!empty($comments)) {
                            $comments .= "\n";
                        }
                        $comments .= sprintf(__('%1$s: %2$s'), __('Phone'), $data['phonenumber']);
                    }
                    if (!empty($data['fax'])) {
                        if (!empty($comments)) {
                            $comments .= "\n";
                        }
                        $comments .= sprintf(__('%1$s: %2$s'), __('Fax'), $data['fax']);
                    }
                    if (!empty($data['email'])) {
                        if (!empty($comments)) {
                            $comments .= "\n";
                        }
                        $comments .= sprintf(__('%1$s: %2$s'), __('Email'), $data['email']);
                    }
                    if (!empty($data['comments'])) {
                        if (!empty($comments)) {
                            $comments .= "\n";
                        }
                        $comments .= $data['comments'];
                    }
                    if (!empty($data['notes'])) {
                        if (!empty($comments)) {
                            $comments .= "\n";
                        }
                        $comments .= $data['notes'];
                    }
                    $query2 = "INSERT INTO `glpi_dropdown_manufacturer`\n                                 (ID, name, comments)\n                          VALUES ('" . $data['ID'] . "', '" . $data['name'] . "', '" . $comments . "')";
                    $DB->queryOrDie($query2, "0.7 add manufacturer item");
                }
            }
        }
    }
    if (isIndex("glpi_ocs_link", "ocs_id_2")) {
        $query = "ALTER TABLE `glpi_ocs_link`\n                DROP INDEX `ocs_id_2` ";
        $DB->queryOrDie($query, "0.7 alter ocs_link clean index ocs_id");
    }
    if (isIndex("glpi_ocs_link", "ocs_id")) {
        $query = "ALTER TABLE `glpi_ocs_link`\n                DROP INDEX `ocs_id` ";
        $DB->queryOrDie($query, "0.7 alter ocs_link clean index ocs_id");
    }
    if (!FieldExists("glpi_ocs_link", "ocs_server_id", false)) {
        $query = "ALTER TABLE `glpi_ocs_link`\n                ADD `ocs_server_id` int(11) NOT NULL";
        $DB->queryOrDie($query, "0.7 add ocs_server_id in glpi_ocs_link");
        $query = "UPDATE `glpi_ocs_link`\n                SET `ocs_server_id` = '1'";
        $DB->queryOrDie($query, "0.7 update ocs_server_id=1 in glpi_ocs_link");
    }
    if (!isIndex("glpi_ocs_link", "ocs_server_id")) {
        // Clean duplicates
        $query = "SELECT COUNT(*) AS CPT, `ocs_id`\n                FROM `glpi_ocs_link`\n                GROUP BY `ocs_id`\n                HAVING CPT > 1";
        if ($result = $DB->query($query)) {
            if ($DB->numrows($result) > 0) {
                while ($data = $DB->fetch_array($result)) {
                    // Skip first
                    $query = "SELECT `ID`\n                         FROM `glpi_ocs_link`\n                         WHERE `ocs_id` = '" . $data['ocs_id'] . "'\n                         ORDER BY `last_update` DESC\n                         LIMIT 1,99999";
                    if ($result2 = $DB->query($query)) {
                        if ($DB->numrows($result2)) {
                            while ($data2 = $DB->fetch_array($result2)) {
                                $query = "DELETE\n                                  FROM `glpi_ocs_link`\n                                  WHERE `ID` ='" . $data2['ID'] . "'";
                                $DB->queryOrDie($query, "0.7 clean to update ocs_server_id=1 in glpi_ocs_link");
                            }
                        }
                    }
                }
            }
        }
        $query = "ALTER TABLE `glpi_ocs_link`\n                ADD UNIQUE `ocs_server_id` (`ocs_server_id`, `ocs_id`)";
        $DB->queryOrDie($query, "0.7 alter ocs_link add index ocs_server_id");
    }
    if (!isIndex("glpi_ocs_link", "`ocs_deviceid`")) {
        $query = "ALTER TABLE `glpi_ocs_link`\n                ADD INDEX (`ocs_deviceid`)";
        $DB->queryOrDie($query, "0.7 alter ocs_link add index ocs_deviceid");
    }
    if (!FieldExists("glpi_ocs_config", "tplname", false)) {
        $query = "ALTER TABLE `glpi_ocs_config`\n                ADD `name` varchar(200) default NULL AFTER `ID`,\n                ADD `is_template` enum('0','1') NOT NULL default '0',\n                ADD `tplname` varchar(200) default NULL,\n                ADD `date_mod` datetime default NULL";
        $DB->queryOrDie($query, "0.7 add name, is_template, tplname, date_mod in glpi_ocs_link");
        $query = "UPDATE `glpi_ocs_config`\n                SET `name` = `ocs_db_host`";
        $DB->queryOrDie($query, "0.7 add name in glpi_ocs_config");
    }
    if (!FieldExists("glpi_ocs_config", "import_registry", false)) {
        $query = "ALTER TABLE `glpi_ocs_config`\n                ADD `import_registry` INT NOT NULL default '0' AFTER `import_device_modems`";
        $DB->queryOrDie($query, "0.7 add import_registry in glpi_ocs_config");
    }
    if (FieldExists("glpi_ocs_config", "import_tag_field", false)) {
        $query = "ALTER TABLE `glpi_ocs_config`\n                DROP `import_tag_field`";
        $DB->queryOrDie($query, "0.7 drop import_tag_field in glpi_ocs_config");
    }
    if (!FieldExists("glpi_ocs_config", "import_software_licensetype", false)) {
        $query = "ALTER TABLE `glpi_ocs_config`\n                ADD `import_software_licensetype` VARCHAR(255) DEFAULT 'global'\n                     AFTER `import_software`";
        $DB->queryOrDie($query, "0.7 add import_software_licensetype in glpi_ocs_config");
    }
    if (!FieldExists("glpi_ocs_config", "import_software_buy", false)) {
        $query = "ALTER TABLE `glpi_ocs_config`\n                ADD `import_software_buy` INT NOT NULL DEFAULT '1' AFTER `import_software`";
        $DB->queryOrDie($query, "0.7 add import_software_buy in glpi_ocs_config");
    }
    if (!TableExists("glpi_registry")) {
        $query = "CREATE TABLE `glpi_registry` (\n                  `ID` int(10) NOT NULL auto_increment,\n                  `computer_id` int(10) NOT NULL DEFAULT '0',\n                  `registry_hive` varchar(45) NOT NULL,\n                  `registry_path` varchar(255) NOT NULL,\n                  `registry_value` varchar(255) NOT NULL,\n                  PRIMARY KEY (`ID`),\n                  KEY `computer_id` (`computer_id`)\n                ) ENGINE=MyISAM AUTO_INCREMENT=0 DEFAULT CHARSET=utf8";
        $DB->queryOrDie($query, "0.7 add glpi_registry table");
    }
    if (!FieldExists("glpi_ocs_link", "import_ip", false)) {
        $query = "ALTER TABLE `glpi_ocs_link`\n                ADD COLUMN `import_ip` LONGTEXT";
        $DB->queryOrDie($query, "0.7 add import_ip in glpi_ocs_link");
    }
    //// Enum clean
    // Enum 0-1
    $enum01 = array();
    $template_tables = array("glpi_computers", "glpi_networking", "glpi_printers", "glpi_monitors", "glpi_peripherals", "glpi_software", "glpi_phones", "glpi_ocs_config");
    foreach ($template_tables as $table) {
        if (!isset($enum01[$table])) {
            $enum01[$table] = array();
        }
        $enum01[$table][] = "is_template";
    }
    $enum01["glpi_config"][] = "auto_assign";
    $enum01["glpi_config"][] = "public_faq";
    $enum01["glpi_config"][] = "url_in_mail";
    $enum01["glpi_profiles"][] = "is_default";
    $enum01["glpi_monitors"][] = "is_global";
    $enum01["glpi_peripherals"][] = "is_global";
    $enum01["glpi_phones"][] = "is_global";
    $enum01["glpi_printers"][] = "is_global";
    $enum01["glpi_reminder"][] = "rv";
    $enum01["glpi_contract_device"][] = "is_template";
    $enum01["glpi_doc_device"][] = "is_template";
    foreach ($enum01 as $table => $fields) {
        foreach ($fields as $key => $field) {
            if (FieldExists($table, $field, false)) {
                $query = "ALTER TABLE `{$table}`\n                      ADD `tmp_convert_enum` SMALLINT NOT NULL DEFAULT '0' AFTER `{$field}` ";
                $DB->queryOrDie($query, "0.7 alter {$table} add new field tmp_convert_enum");
                $query = "UPDATE `{$table}`\n                      SET `tmp_convert_enum` = '1'\n                      WHERE `{$field}` = '1'";
                $DB->queryOrDie($query, "0.7 update {$table} to set correct values to alod enum01 {$field}");
                $query = "UPDATE `{$table}`\n                      SET `tmp_convert_enum` = '0'\n                      WHERE `{$field}` = '0'";
                $DB->queryOrDie($query, "0.7 update {$table} to set correct values to alod enum01 {$field}");
                $query = "ALTER TABLE `{$table}`\n                      DROP `{$field}` ";
                $DB->queryOrDie($query, "0.7 alter {$table} drop tmp enum field");
                $query = "ALTER TABLE `{$table}`\n                      CHANGE `tmp_convert_enum` `{$field}` SMALLINT NOT NULL DEFAULT '0'";
                $DB->queryOrDie($query, "0.7 alter {$table} move enum {$field} to tmp field");
                if ($table != "glpi_config" && $table != "glpi_profiles") {
                    $query = "ALTER TABLE `{$table}`\n                         ADD KEY (`{$field}`)";
                    $DB->queryOrDie($query, "0.7 alter {$table} add deleted key");
                }
            }
        }
    }
    $enumYN["N"]["glpi_contracts"][] = "monday";
    // N
    $enumYN["N"]["glpi_contracts"][] = "saturday";
    // N
    $enumYN["Y"]["glpi_device_drive"][] = "is_writer";
    // Y
    $enumYN["N"]["glpi_device_control"][] = "raid";
    // Y -> N
    $enumYN["Y"]["glpi_device_power"][] = "atx";
    // Y
    $enumYN["N"]["glpi_licenses"][] = "oem";
    // N
    $enumYN["Y"]["glpi_licenses"][] = "buy";
    // Y
    $enumYN["N"]["glpi_software"][] = "is_update";
    // N
    $enumYN["Y"]["glpi_type_docs"][] = "upload";
    // Y
    $deleted_tables = array("glpi_computers", "glpi_networking", "glpi_printers", "glpi_monitors", "glpi_peripherals", "glpi_software", "glpi_cartridges_type", "glpi_contracts", "glpi_contacts", "glpi_enterprises", "glpi_docs", "glpi_phones", "glpi_consumables_type");
    foreach ($deleted_tables as $table) {
        if (!isset($enum01[$table])) {
            $enum01[$table] = array();
        }
        $enumYN["N"][$table][] = "deleted";
    }
    foreach ($enumYN as $default => $tmptbl) {
        foreach ($tmptbl as $table => $fields) {
            foreach ($fields as $key => $field) {
                if (FieldExists($table, $field, false)) {
                    $newdef = 0;
                    if ($default == "Y") {
                        $newdef = 1;
                    }
                    $query = "ALTER TABLE `{$table}`\n                         ADD `tmp_convert_enum` SMALLINT NOT NULL DEFAULT '{$newdef}' AFTER `{$field}` ";
                    $DB->queryOrDie($query, "0.7 alter {$table} add new field tmp_convert_enum");
                    $query = "UPDATE `{$table}`\n                         SET `tmp_convert_enum` = '1'\n                         WHERE `{$field}` = 'Y'";
                    $DB->queryOrDie($query, "0.7 update {$table} to set correct values to alod enum01 {$field}");
                    $query = "UPDATE `{$table}`\n                         SET `tmp_convert_enum` = '0'\n                         WHERE `{$field}` = 'N'";
                    $DB->queryOrDie($query, "0.7 update {$table} to set correct values to alod enum01 {$field}");
                    $query = "ALTER TABLE `{$table}`\n                         DROP `{$field}` ";
                    $DB->queryOrDie($query, "0.7 alter {$table} drop tmp enum field");
                    $query = "ALTER TABLE `{$table}`\n                         CHANGE `tmp_convert_enum` `{$field}` SMALLINT NOT NULL DEFAULT '{$newdef}'";
                    $DB->queryOrDie($query, "0.7 alter {$table} move enum {$field} to tmp field");
                    if ($field == "deleted" || $table == "glpi_licenses" || $table == "glpi_software" || $table == "glpi_type_docs") {
                        $query = "ALTER TABLE `{$table}`\n                            ADD KEY (`{$field}`)";
                        $DB->queryOrDie($query, "0.7 alter {$table} add deleted key");
                    }
                }
            }
        }
    }
    if (FieldExists("glpi_tracking", "is_group", false)) {
        $query = "ALTER TABLE `glpi_tracking`\n                DROP `is_group`";
        $DB->queryOrDie($query, "0.7 drop is_group from tracking");
    }
    $enumYesNo["glpi_kbitems"][] = "faq";
    $enumYesNo["glpi_tracking"][] = "emailupdates";
    $enumYesNo["glpi_users"][] = "tracking_order";
    foreach ($enumYesNo as $table => $fields) {
        foreach ($fields as $key => $field) {
            if (FieldExists($table, $field, false)) {
                $query = "ALTER TABLE `{$table}`\n                      ADD `tmp_convert_enum` SMALLINT NOT NULL DEFAULT '0' AFTER `{$field}` ";
                $DB->queryOrDie($query, "0.7 alter {$table} add new field tmp_convert_enum");
                $query = "UPDATE `{$table}`\n                      SET `tmp_convert_enum` = '1'\n                      WHERE `{$field}` = 'yes'";
                $DB->queryOrDie($query, "0.7 update {$table} to set correct values to alod enum01 {$field}");
                $query = "UPDATE `{$table}`\n                      SET `tmp_convert_enum` = '0'\n                      WHERE `{$field}` = 'no'";
                $DB->queryOrDie($query, "0.7 update {$table} to set correct values to alod enum01 {$field}");
                $query = "ALTER TABLE `{$table}`\n                      DROP `{$field}` ";
                $DB->queryOrDie($query, "0.7 alter {$table} drop tmp enum field");
                $query = "ALTER TABLE `{$table}`\n                      CHANGE `tmp_convert_enum` `{$field}` SMALLINT NOT NULL DEFAULT '0'";
                $DB->queryOrDie($query, "0.7 alter {$table} move enum {$field} to tmp field");
                if ($table == "glpi_kbitems") {
                    $query = "ALTER TABLE `{$table}`\n                         ADD KEY (`{$field}`)";
                    $DB->queryOrDie($query, "0.7 alter {$table} add deleted key");
                }
            }
        }
    }
    // Reste enum : glpi_tracking.status et glpi_device_gfxcard.interface
    if (FieldExists("glpi_tracking", "status", false)) {
        $query = "ALTER TABLE `glpi_tracking`\n                CHANGE `status` `status` VARCHAR( 255 ) DEFAULT 'new'";
        $DB->queryOrDie($query, "0.7 alter status from tracking");
    }
    if (FieldExists("glpi_device_gfxcard", "interface", false)) {
        $query = "ALTER TABLE `glpi_device_gfxcard`\n                CHANGE `interface` `interface` VARCHAR( 255 ) NULL DEFAULT 'PCI-X'";
        $DB->queryOrDie($query, "0.7 alter interface from glpi_device_gfxcard");
    }
    if (!TableExists("glpi_rules_actions")) {
        $query = "CREATE TABLE `glpi_rules_actions` (\n                  `ID` int(11) NOT NULL auto_increment,\n                  `FK_rules` int(11) NOT NULL DEFAULT '0',\n                  `action_type` varchar(255) NOT NULL,\n                  `field` varchar(255) NOT NULL,\n                  `value` varchar(255) NOT NULL,\n                  PRIMARY KEY (`ID`),\n                  KEY `FK_rules` (`FK_rules`)\n                ) ENGINE=MyISAM  DEFAULT CHARSET=utf8";
        $DB->queryOrDie($query, "0.7 add table glpi_rules_descriptions");
    }
    if (!TableExists("glpi_rules_criterias")) {
        $query = "CREATE TABLE `glpi_rules_criterias` (\n                  `ID` int(11) NOT NULL auto_increment,\n                  `FK_rules` int(11) NOT NULL DEFAULT '0',\n                  `criteria` varchar(255) NOT NULL,\n                  `condition` smallint(4) NOT NULL DEFAULT '0',\n                  `pattern` varchar(255) NOT NULL,\n                  PRIMARY KEY (`ID`),\n                  KEY `FK_rules` (`FK_rules`)\n                ) ENGINE=MyISAM  DEFAULT CHARSET=utf8";
        $DB->queryOrDie($query, "0.7 add table glpi_rules_criterias");
    }
    if (!TableExists("glpi_rules_descriptions")) {
        $query = "CREATE TABLE `glpi_rules_descriptions` (\n                  `ID` int(11) NOT NULL auto_increment,\n                  `FK_entities` int(11) NOT NULL default '-1',\n                  `rule_type` smallint(4) NOT NULL DEFAULT '0',\n                  `ranking` int(11) NOT NULL DEFAULT '0',\n                  `name` varchar(255) NOT NULL,\n                  `description` text NOT NULL,\n                  `match` varchar(255) NOT NULL,\n                  PRIMARY KEY (`ID`)\n                ) ENGINE=MyISAM  DEFAULT CHARSET=utf8";
        $DB->queryOrDie($query, "0.7 add table glpi_rules_actions");
    }
    if (!FieldExists("glpi_config", "use_cache", false)) {
        $query = "ALTER TABLE `glpi_config`\n                ADD `use_cache` SMALLINT NOT NULL DEFAULT '1' AFTER `debug`";
        $DB->queryOrDie($query, "0.7 alter config add use_cache");
    }
    if (TableExists("glpi_rules_descriptions")) {
        //If no rule exists, then create a default one
        $query = "SELECT `ID`\n                FROM `glpi_rules_descriptions`";
        $result = $DB->query($query);
        if ($DB->numrows($result) == 0) {
            //Insert rule to affect machines in the Root entity
            $query = "INSERT INTO `glpi_rules_descriptions`\n                          (`FK_entities`, `rule_type`, `ranking`, `name`, `description`, `match`)\n                   VALUES (-1, 0, 0, 'Root', '', 'AND')";
            $DB->queryOrDie($query, "0.7 add default ocs affectation rule");
            $query = "SELECT `ID`\n                   FROM `glpi_rules_descriptions`\n                   WHERE `name` = 'Root'\n                         AND `rule_type` = '0'";
            $result = $DB->query($query);
            //Get the defaut rule's ID
            $datas = $DB->fetch_array($result);
            $query = "INSERT INTO `glpi_rules_criterias`\n                          (`FK_rules`, `criteria`, `condition`, `pattern`)\n                   VALUES (" . $datas["ID"] . ", 'TAG', 0, '*')";
            $DB->queryOrDie($query, "0.7 add default ocs criterias");
            $query = "INSERT INTO `glpi_rules_actions`\n                          (`FK_rules`, `action_type`, `field`, `value`)\n                   VALUES (" . $datas["ID"] . ", 'assign', 'FK_entities', '0')";
            $DB->queryOrDie($query, "0.7 add default ocs actions");
            //Insert rule to affect users from LDAP to the root entity
            $query = "INSERT INTO `glpi_rules_descriptions`\n                          (`FK_entities`, `rule_type`, `ranking`, `name`, `description`, `match`)\n                   VALUES (-1, 1, 1, 'Root', '', 'OR')";
            $DB->queryOrDie($query, "0.7 add default right affectation rule");
            $query = "SELECT `ID`\n                   FROM `glpi_rules_descriptions`\n                   WHERE `name` = 'Root'\n                         AND `rule_type` = '1'";
            $result = $DB->query($query);
            //Get the defaut rule's ID
            $datas = $DB->fetch_array($result);
            //Criterias
            $query = "INSERT INTO `glpi_rules_criterias`\n                          (`FK_rules`, `criteria`, `condition`, `pattern`)\n                   VALUES (" . $datas["ID"] . ", 'uid', 0, '*')";
            $DB->queryOrDie($query, "0.7 add default right criterias");
            $query = "INSERT INTO `glpi_rules_criterias`\n                          (`FK_rules`, `criteria`, `condition`, `pattern`)\n                   VALUES (" . $datas["ID"] . ", 'samaccountname', 0, '*')";
            $DB->queryOrDie($query, "0.7 add default right criterias");
            $query = "INSERT INTO `glpi_rules_criterias`\n                          (`FK_rules`, `criteria`, `condition`, `pattern`)\n                   VALUES (" . $datas["ID"] . ", 'MAIL_EMAIL', 0, '*')";
            $DB->queryOrDie($query, "0.7 add default right criterias");
            //Action
            $query = "INSERT INTO `glpi_rules_actions`\n                          (`FK_rules`, `action_type`, `field`, `value`)\n                   VALUES (" . $datas["ID"] . ", 'assign', 'FK_entities', '0')";
            $DB->queryOrDie($query, "0.7 add default right actions");
        }
    }
    if (!TableExists("glpi_ocs_admin_link")) {
        $query = "CREATE TABLE `glpi_ocs_admin_link` (\n                  `ID` int(10) unsigned NOT NULL auto_increment,\n                  `glpi_column` varchar(255) NULL,\n                  `ocs_column` varchar(255) NULL,\n                  `ocs_server_id` int(11) NOT NULL,\n                  PRIMARY KEY (`ID`)\n                ) ENGINE=MyISAM AUTO_INCREMENT=0 DEFAULT CHARSET=utf8";
        $DB->queryOrDie($query, "0.7 add table glpi_ocs_admin_link");
    }
    // Add title to tracking
    if (!FieldExists("glpi_tracking", "name", false)) {
        $query = "ALTER TABLE `glpi_tracking`\n                ADD `name` varchar(255) NULL AFTER `FK_entities`";
        $DB->queryOrDie($query, "0.7 alter tracking add name");
        $query = "UPDATE `glpi_tracking`\n                SET `name` = SUBSTRING(REPLACE(contents,'\n',' '),1,50)";
        $DB->queryOrDie($query, "0.7 update title of glpi_tracking");
    }
    if (FieldExists("glpi_reminder", "title", false)) {
        $query = "ALTER TABLE `glpi_reminder`\n                CHANGE `title` `title` VARCHAR( 255 ) NULL DEFAULT NULL ";
        $DB->queryOrDie($query, "0.7 alter title in glpi_reminder");
    }
    if (!TableExists("glpi_rules_ldap_parameters")) {
        $query = "CREATE TABLE `glpi_rules_ldap_parameters` (\n                  `ID` int(11) NOT NULL auto_increment,\n                  `name` varchar(255) NOT NULL,\n                  `value` varchar(255) NOT NULL,\n                  `rule_type` smallint(6) NOT NULL default '1',\n                  PRIMARY KEY (`ID`)\n                ) ENGINE=MyISAM  DEFAULT CHARSET=utf8";
        $DB->queryOrDie($query, "0.7 add table glpi_rules_ldap_parameters");
        $query = "INSERT INTO `glpi_rules_ldap_parameters`\n                       (`ID`, `name`, `value`, `rule_type`)\n                VALUES (1, '(LDAP)Organization', 'o', 1),\n                       (2, '(LDAP)Common Name', 'cn', 1),\n                       (3, '(LDAP)Department Number', 'departmentnumber', 1),\n                       (4, '(LDAP)Email', 'mail', 1),\n                       (5, 'Object Class', 'objectclass', 1),\n                       (6, '(LDAP)User ID', 'uid', 1),\n                       (7, '(LDAP)Telephone Number', 'phone', 1),\n                       (8, '(LDAP)Employee Number', 'employeenumber', 1),\n                       (9, '(LDAP)Manager', 'manager', 1),\n                       (10, '(LDAP)DistinguishedName', 'dn', 1),\n                       (11, '(AD)DistinguishedName', 'distinguishedname', 1),\n                       (12, '(AD)User ID', 'samaccountname', 1)";
        $DB->queryOrDie($query, "0.7 add standard values to glpi_rules_ldap_parameters");
    }
    if (!FieldExists("glpi_config", "helpdeskhelp_url", false)) {
        $query = "ALTER TABLE `glpi_config`\n                ADD `helpdeskhelp_url` VARCHAR( 255 ) NULL DEFAULT NULL ";
        $DB->queryOrDie($query, "0.7 add helpdeskhelp_url in glpi_config");
    }
    if (!FieldExists("glpi_config", "centralhelp_url", false)) {
        $query = "ALTER TABLE `glpi_config`\n                ADD `centralhelp_url` VARCHAR( 255 ) NULL DEFAULT NULL ";
        $DB->queryOrDie($query, "0.7 add centralhelp_url in glpi_config");
    }
    if (!FieldExists("glpi_config", "default_rubdoc_tracking", false)) {
        $query = "ALTER TABLE `glpi_config`\n                ADD `default_rubdoc_tracking` int(11) default '0' ";
        $DB->queryOrDie($query, "0.7 add default_rubdoc_tracking in glpi_config");
    }
    if (!FieldExists("glpi_users", "deleted", false)) {
        $query = "ALTER TABLE `glpi_users`\n                ADD `deleted` SMALLINT NOT NULL DEFAULT 0 ";
        $DB->queryOrDie($query, "0.7 add deleted in glpi_users");
        $query = "ALTER TABLE `glpi_users`\n                ADD KEY (`deleted`)";
        $DB->queryOrDie($query, "0.7 add key deleted in glpi_users");
    }
    if (!FieldExists("glpi_reservation_item", "active", false)) {
        $query = "ALTER TABLE `glpi_reservation_item`\n                ADD `active` smallint(6) NOT NULL default '1' ";
        $DB->queryOrDie($query, "0.7 add active in glpi_reservation_item");
    }
    if (!FieldExists("glpi_tracking_planning", "state", false)) {
        $query = "ALTER TABLE `glpi_tracking_planning`\n                ADD `state` smallint(6) NOT NULL default '1' ";
        $DB->queryOrDie($query, "0.7 add state in glpi_tracking_planning");
        $query = "UPDATE `glpi_tracking_planning`\n                SET `state` = '2'\n                WHERE `end` < NOW()";
        $DB->queryOrDie($query, "0.7 update values of state in glpi_tracking_planning");
    }
    if (!FieldExists("glpi_reminder", "state", false)) {
        $query = "ALTER TABLE `glpi_reminder`\n                ADD `state` smallint(6) NOT NULL default '0' ";
        $DB->queryOrDie($query, "0.7 add state in glpi_reminder");
    }
    if (!FieldExists("glpi_tracking", "recipient", false)) {
        $query = "ALTER TABLE `glpi_tracking`\n                ADD `recipient` INT NOT NULL DEFAULT '0' AFTER `author` ";
        $DB->queryOrDie($query, "0.7 add recipient in glpi_tracking");
        $query = "UPDATE `glpi_tracking`\n                SET `recipient` = `author`";
        $DB->queryOrDie($query, "0.7 update recipient in glpi_tracking");
    }
    if (!isIndex("glpi_tracking", "recipient")) {
        $query = "ALTER TABLE `glpi_tracking`\n                ADD INDEX (`recipient`) ";
        $DB->queryOrDie($query, "0.7 add recipient index in glpi_tracking");
    }
    if (!FieldExists("glpi_ocs_config", "deconnection_behavior", false)) {
        $query = "ALTER TABLE `glpi_ocs_config`\n                ADD COLUMN `deconnection_behavior` VARCHAR(45)";
        $DB->queryOrDie($query, "0.7 add state in glpi_reminder");
    }
    // Rights
    if (!FieldExists("glpi_profiles", "search_config_global", false)) {
        $query = "ALTER TABLE `glpi_profiles`\n                ADD COLUMN `search_config_global` char(1) default NULL AFTER `search_config`";
        $DB->queryOrDie($query, "0.7 add search_config_global in glpi_profiles");
        $query = "UPDATE `glpi_profiles`\n                SET `search_config_global` = `search_config`";
        $DB->queryOrDie($query, "0.7 update search_config_global values in glpi_profiles");
        $query = "UPDATE `glpi_profiles`\n                SET `search_config` = 'w'\n                WHERE `interface` = 'central'";
        $DB->queryOrDie($query, "0.7 update search_confi values in glpi_profiles");
    }
    if (!FieldExists("glpi_profiles", "entity", false)) {
        $query = "ALTER TABLE `glpi_profiles`\n                ADD COLUMN `entity` char(1) default NULL AFTER `group`";
        $DB->queryOrDie($query, "0.7 add entity in glpi_profiles");
        $query = "UPDATE `glpi_profiles`\n                SET `entity` = `config`";
        $DB->queryOrDie($query, "0.7 update entity values in glpi_profiles");
    }
    if (!FieldExists("glpi_profiles", "entity_dropdown", false)) {
        $query = "ALTER TABLE `glpi_profiles`\n                ADD COLUMN `entity_dropdown` char(1) default NULL AFTER `dropdown`";
        $DB->queryOrDie($query, "0.7 add entity_dropdown in glpi_profiles");
        $query = "UPDATE `glpi_profiles`\n                SET `entity_dropdown` = `dropdown`";
        $DB->queryOrDie($query, "0.7 update entity_dropdown values in glpi_profiles");
    }
    if (!FieldExists("glpi_profiles", "sync_ocsng", false)) {
        $query = "ALTER TABLE `glpi_profiles`\n                ADD COLUMN `sync_ocsng` char(1) default NULL AFTER `ocsng`";
        $DB->queryOrDie($query, "0.7 add sync_ocsng in glpi_profiles");
        $query = "UPDATE `glpi_profiles`\n                SET `sync_ocsng` = `ocsng`";
        $DB->queryOrDie($query, "0.7 update sync_ocsng values in glpi_profiles");
    }
    if (!FieldExists("glpi_profiles", "view_ocsng", false)) {
        $query = "ALTER TABLE `glpi_profiles`\n                ADD COLUMN `view_ocsng` char(1) default NULL AFTER `ocsng`";
        $DB->queryOrDie($query, "0.7 add view_ocsng in glpi_profiles");
        $query = "UPDATE `glpi_profiles`\n                SET `view_ocsng` = 'r'\n                WHERE `interface` = 'central'";
        $DB->queryOrDie($query, "0.7 update view_ocsng values in glpi_profiles");
    }
    if (!FieldExists("glpi_profiles", "rule_ldap", false)) {
        $query = "ALTER TABLE `glpi_profiles`\n                ADD COLUMN `rule_ldap` char(1) default NULL AFTER `config`";
        $DB->queryOrDie($query, "0.7 add rule_ldap in glpi_profiles");
        $query = "UPDATE `glpi_profiles`\n                SET `rule_ldap` = `config`";
        $DB->queryOrDie($query, "0.7 update rule_ldap values in glpi_profiles");
    }
    if (!FieldExists("glpi_profiles", "rule_ocs", false)) {
        $query = "ALTER TABLE `glpi_profiles`\n                ADD COLUMN `rule_ocs` char(1) default NULL AFTER `config`";
        $DB->queryOrDie($query, "0.7 add rule_ocs in glpi_profiles");
        $query = "UPDATE `glpi_profiles`\n                SET `rule_ocs` = `config`";
        $DB->queryOrDie($query, "0.7 update rule_ocs values in glpi_profiles");
    }
    if (!FieldExists("glpi_profiles", "rule_tracking", false)) {
        $query = "ALTER TABLE `glpi_profiles`\n                ADD COLUMN `rule_tracking` char(1) default NULL AFTER `config`";
        $DB->queryOrDie($query, "0.7 add rule_tracking in glpi_profiles");
        $query = "UPDATE `glpi_profiles`\n                SET `rule_tracking` = `config`";
        $DB->queryOrDie($query, "0.7 update rule_tracking values in glpi_profiles");
    }
    if (!FieldExists("glpi_profiles", "update_followups", false)) {
        $query = "ALTER TABLE `glpi_profiles`\n                ADD COLUMN `update_followups` char(1) default NULL AFTER `observe_ticket`";
        $DB->queryOrDie($query, "0.7 add update_followups in glpi_profiles");
        $query = "UPDATE `glpi_profiles`\n                SET `update_followups` = `show_full_ticket`";
        $DB->queryOrDie($query, "0.7 update update_followups values in glpi_profiles");
    }
    //Software version's modifications
    //First add the version field to the licenses table
    if (!FieldExists("glpi_licenses", "version", false)) {
        $query = "ALTER TABLE `glpi_licenses`\n                ADD COLUMN `version` varchar(255) default NULL AFTER `sID`";
        $DB->queryOrDie($query, "0.7 add version in glpi_licenses");
        $sql = "SELECT `ID`, `version`\n              FROM `glpi_software`";
        $result = $DB->query($sql);
        if ($DB->numrows($result) > 0) {
            while ($soft = $DB->fetch_array($result)) {
                $sql = "UPDATE `glpi_licenses`\n                    SET `version` = '" . $soft["version"] . "'\n                    WHERE `sID` = " . $soft["ID"];
                $DB->query($sql);
            }
        }
    }
    if (FieldExists("glpi_software", "version", false)) {
        $query = "ALTER TABLE `glpi_software`\n                DROP `version`";
        $DB->queryOrDie($query, "0.7 delete version in glpi_software");
    }
    // CLean multiple free / global licenses
    $query = "SELECT count(*)AS CPT, `glpi_licenses`.*\n             FROM `glpi_licenses`\n             WHERE `serial` = 'global'\n                   OR `serial` = 'free'\n             GROUP BY `sID`, `serial`, `expire`, `buy`\n             HAVING CPT > 1";
    $result = $DB->queryOrDie($query, "0.7 check multiple free global licenses");
    if ($DB->numrows($result)) {
        while ($data = $DB->fetch_array($result)) {
            // Get licenses AND installations
            if ($data['expire'] == "") {
                $expire_search = " AND `glpi_licenses`.`expire` IS NULL";
            } else {
                $expire_search = " AND `glpi_licenses`.`expireÈ = '" . $data['expire'] . "'";
            }
            $query = "SELECT `glpi_licenses`.`ID`\n                   FROM `glpi_licenses`\n                   WHERE `serial` ='" . $data['serial'] . "'\n                         AND `sID` ='" . $data['sID'] . "'\n                         {$expire_search}\n                         AND `buy` ='" . $data['buy'] . "'";
            $result2 = $DB->query($query);
            if ($DB->numrows($result2)) {
                $licIDs = array();
                while ($data2 = $DB->fetch_array($result2)) {
                    $licIDs[] = $data2['ID'];
                }
                if (count($licIDs) > 1) {
                    $refID = array_pop($licIDs);
                    $query = "UPDATE `glpi_inst_software`\n                         SET `license` = '{$refID}'\n                         WHERE `license` IN (";
                    $first = true;
                    foreach ($licIDs as $id) {
                        if ($first) {
                            $first = false;
                        } else {
                            $query .= ", ";
                        }
                        $query .= "'{$id}'";
                        $query_del = "DELETE\n                                FROM `glpi_licenses`\n                                WHERE `ID` = '{$id}'";
                        $DB->query($query_del);
                    }
                    $query .= ")";
                    $DB->query($query);
                }
            }
        }
    }
    // Clean multiple reservation item
    $query = "SELECT count(*) AS CPT, `glpi_reservation_item`.*\n             FROM `glpi_reservation_item`\n             GROUP BY `device_type`, `id_device`\n             HAVING CPT > 1";
    $result = $DB->queryOrDie($query, "0.7 check multiple free global licenses");
    if ($DB->numrows($result)) {
        while ($data = $DB->fetch_array($result)) {
            $refID = $data['ID'];
            // Get duplicates
            $query2 = "SELECT *\n                    FROM `glpi_reservation_item`\n                    WHERE `device_type` = '" . $data['device_type'] . "'\n                         AND `id_device` = '" . $data['id_device'] . "'\n                         AND `ID` <> '{$refID}'";
            $result2 = $DB->query($query2);
            if ($DB->numrows($result2)) {
                while ($data2 = $DB->fetch_array($result2)) {
                    // Update réservations
                    $query = "UPDATE `glpi_reservation_resa`\n                         SET `id_item` = '{$refID}'\n                         WHERE `id_item` = '" . $data2['ID'] . "'";
                    $DB->query($query);
                    // Delete Reservation Item
                    $query = "DELETE\n                         FROM `glpi_reservation_item`\n                         WHERE `ID` = '" . $data2['ID'] . "'";
                    $DB->query($query);
                }
            }
        }
    }
    if (!FieldExists("glpi_networking_ports", "netmask", false)) {
        $query = "ALTER TABLE `glpi_networking_ports`\n                ADD COLUMN `netmask` VARCHAR( 255 ) NULL DEFAULT NULL";
        $DB->queryOrDie($query, "0.7 add netmask in glpi_networking_ports");
    }
    if (!FieldExists("glpi_networking_ports", "gateway", false)) {
        $query = "ALTER TABLE `glpi_networking_ports`\n                ADD COLUMN `gateway` VARCHAR( 255 ) NULL DEFAULT NULL";
        $DB->queryOrDie($query, "0.7 add gateway in glpi_networking_ports");
    }
    if (!FieldExists("glpi_networking_ports", "subnet", false)) {
        $query = "ALTER TABLE `glpi_networking_ports`\n                ADD COLUMN subnet VARCHAR( 255 ) NULL DEFAULT NULL";
        $DB->queryOrDie($query, "0.7 add subnet in glpi_networking_ports");
    }
    if (FieldExists("glpi_networking_ports", "name", false)) {
        $query = "ALTER TABLE `glpi_networking_ports`\n                CHANGE `name` `name` VARCHAR( 255 ) NULL DEFAULT NULL,\n                CHANGE `ifaddr` `ifaddr` VARCHAR( 255 ) NULL DEFAULT NULL,\n                CHANGE `ifmac` `ifmac` VARCHAR( 255 ) NULL DEFAULT NULL ";
        $DB->queryOrDie($query, "0.7 alter networking_ports fields");
    }
    // mailgate
    if (!TableExists("glpi_mailgate")) {
        $query = "CREATE TABLE `glpi_mailgate` (\n                  `ID` int(11) NOT NULL auto_increment,\n                  `name` varchar(255) collate utf8_unicode_ci default NULL,\n                  `FK_entities` int(11) NOT NULL default '0',\n                  `host` varchar(255) collate utf8_unicode_ci NOT NULL,\n                  `login` varchar(255) collate utf8_unicode_ci NOT NULL,\n                  `password` varchar(255) collate utf8_unicode_ci NOT NULL,\n                  PRIMARY KEY (`ID`)\n                ) ENGINE=MyISAM";
        $DB->queryOrDie($query, "0.7 add glpi_mailgate");
        $query = "INSERT INTO `glpi_display`\n                       (`type`, `num`, `rank`, `FK_users`)\n                VALUES (35, 80, 1, 0)";
        $DB->queryOrDie($query, "0.7 add glpi_mailgate display values");
    }
    if (!FieldExists("glpi_computers", "os_license_number", false)) {
        $query = "ALTER TABLE `glpi_computers`\n                ADD COLUMN `os_license_number` VARCHAR( 255 ) NULL DEFAULT NULL AFTER os_sp";
        $DB->queryOrDie($query, "0.7 alter glpi_computers field " . __('Serial of the operating system'));
    }
    if (!FieldExists("glpi_computers", "os_license_id", false)) {
        $query = "ALTER TABLE `glpi_computers`\n                ADD COLUMN `os_license_id` VARCHAR( 255 ) NULL DEFAULT NULL AFTER os_license_number";
        $DB->queryOrDie($query, "0.7 alter glpi_computers field " . __('Product ID of the operating system'));
    }
    if (!FieldExists("glpi_ocs_config", "import_os_serial", false)) {
        $query = "ALTER TABLE `glpi_ocs_config`\n                ADD `import_os_serial` INT( 2 ) NULL AFTER `import_registry`";
        $DB->queryOrDie($query, "0.7 alter glpi_computers field import_ocs_serial");
    }
    if (!FieldExists("glpi_auth_ldap", "use_dn", false)) {
        $query = "ALTER TABLE `glpi_auth_ldap`\n                ADD `use_dn` INT( 1 ) NOT NULL DEFAULT '1'";
        $DB->queryOrDie($query, "0.7 alter glpi_computers field use_dn " . $DB->error());
    }
    if (!FieldExists("glpi_config", "monitors_management_restrict", false)) {
        $query = "ALTER TABLE `glpi_config`\n                ADD `monitors_management_restrict` INT( 1 ) NOT NULL DEFAULT '2'";
        $DB->queryOrDie($query, "0.7 alter glpi_computers field monitors_management_restrict " . $DB->error());
    }
    if (!FieldExists("glpi_config", "phones_management_restrict", false)) {
        $query = "ALTER TABLE `glpi_config`\n                ADD `phones_management_restrict` INT( 1 ) NOT NULL DEFAULT '2'";
        $DB->queryOrDie($query, "0.7 alter glpi_computers field phones_management_restrict " . $DB->error());
    }
    if (!FieldExists("glpi_config", "peripherals_management_restrict", false)) {
        $query = "ALTER TABLE `glpi_config`\n                ADD `peripherals_management_restrict` INT( 1 ) NOT NULL DEFAULT '2'";
        $DB->queryOrDie($query, "0.7 alter glpi_computers field peripherals_management_restrict " . $DB->error());
    }
    if (!FieldExists("glpi_config", "printers_management_restrict", false)) {
        $query = "ALTER TABLE `glpi_config`\n                ADD `printers_management_restrict` INT( 1 ) NOT NULL DEFAULT '2'";
        $DB->queryOrDie($query, "0.7 alter glpi_computers field printers_management_restrict " . $DB->error());
    }
    if (!FieldExists("glpi_config", "licenses_management_restrict", false)) {
        $query = "ALTER TABLE `glpi_config`\n                ADD `licenses_management_restrict` INT( 1 ) NOT NULL DEFAULT '2'";
        $DB->queryOrDie($query, "0.7 alter glpi_computers field licenses_management_restrict " . $DB->error());
    }
    if (!FieldExists("glpi_config", "license_deglobalisation", false)) {
        $query = "ALTER TABLE `glpi_config`\n                ADD `license_deglobalisation` INT( 1 ) NOT NULL DEFAULT '1'";
        $DB->queryOrDie($query, "0.7 alter glpi_computers field license_deglobalisation " . $DB->error());
    }
    if (!FieldExists("glpi_registry", "registry_ocs_name", false)) {
        $query = "ALTER TABLE `glpi_registry`\n                ADD COLUMN `registry_ocs_name` char(255) NOT NULL default ''";
        $DB->queryOrDie($query, "0.7 add registry_ocs_name in glpi_registry");
    }
    if (!FieldExists("glpi_config", "use_errorlog", false)) {
        $query = "ALTER TABLE `glpi_config`\n                ADD COLUMN `use_errorlog` INT( 1 ) NOT NULL default 0";
        $DB->queryOrDie($query, "0.7 add use_errorlog in glpi_config");
    }
    if (!FieldExists("glpi_config", "glpi_timezone", false)) {
        $query = "ALTER TABLE `glpi_config`\n                ADD COLUMN `glpi_timezone` VARCHAR( 4 ) NOT NULL default 0";
        $DB->queryOrDie($query, "0.7 add glpi_timezone in glpi_config");
    }
    if (!FieldExists("glpi_auth_ldap", "timezone", false)) {
        $query = "ALTER TABLE `glpi_auth_ldap`\n                ADD COLUMN `timezone` VARCHAR( 4 ) NOT NULL default 0";
        $DB->queryOrDie($query, "0.7 add timezone in glpi_auth_ldap");
    }
    if (!FieldExists("glpi_ocs_config", "glpi_link_enabled", false)) {
        $query = "ALTER TABLE `glpi_ocs_config`\n                ADD COLUMN `glpi_link_enabled` int(1) NOT NULL,\n                ADD COLUMN `link_ip` int(1) NOT NULL,\n                ADD COLUMN `link_name` int(1) NOT NULL,\n                ADD COLUMN `link_mac_address` int(1) NOT NULL,\n                ADD COLUMN `link_serial` int(1) NOT NULL,\n                ADD COLUMN `link_if_status` int(11) NOT NULL default '0'";
        $DB->queryOrDie($query, "0.7 add glpi_link fields in glpi_ocs_config");
    }
    $intnull = array("glpi_alerts" => array("device_type", "FK_device", "type"), "glpi_cartridges_type" => array("tech_num"), "glpi_computers" => array("FK_users", "FK_groups"), "glpi_consumables_type" => array("tech_num"), "glpi_contacts" => array("type"), "glpi_device_case" => array("type"), "glpi_device_control" => array("interface"), "glpi_device_drive" => array("interface"), "glpi_dropdown_kbcategories" => array("level"), "glpi_dropdown_locations" => array("level"), "glpi_dropdown_tracking_category" => array("level"), "glpi_entities" => array("level"), "glpi_infocoms" => array("FK_enterprise", "budget"), "glpi_monitors" => array("type", "model", "FK_users", "FK_groups"), "glpi_networking" => array("type", "model", "firmware", "FK_users", "FK_groups"), "glpi_networking_ports" => array("iface", "netpoint"), "glpi_ocs_link" => array("ocs_server_id"), "glpi_peripherals" => array("model", "FK_users", "FK_groups"), "glpi_phones" => array("model", "FK_users", "FK_groups"), "glpi_printers" => array("type", "model", "FK_users", "FK_groups"), "glpi_software" => array("location", "platform", "FK_users", "FK_groups"), "glpi_tracking" => array("computer"), "glpi_users_groups" => array("FK_users", "FK_groups"));
    foreach ($intnull as $table => $fields) {
        foreach ($fields as $field) {
            if (FieldExists($table, $field, false)) {
                $query = "UPDATE `{$table}`\n                      SET `{$field}` = '0'\n                      WHERE `{$field}` IS NULL";
                $DB->queryOrDie($query, "0.7 update datas in {$table} for NULL values " . $DB->error());
                $query = "ALTER TABLE `{$table}`\n                      CHANGE `{$field}` `{$field}` INT NOT NULL DEFAULT '0'";
                $DB->queryOrDie($query, "0.7 alter {$field} in {$table} " . $DB->error());
            } else {
                // Error field does not exists : correct it
                $query = "ALTER TABLE `{$table}`\n                      ADD COLUMN `{$field}` INT NOT NULL DEFAULT '0'";
                $DB->queryOrDie($query, "0.7 add {$field} in {$table} " . $DB->error());
            }
        }
    }
    // Clean history
    $query = "DELETE\n             FROM `glpi_history`\n             WHERE `linked_action` = 0\n                   AND `device_internal_type` = 0\n                   AND `old_value` = `new_value`\n                   AND `old_value` IS NOT NULL\n                   AND `old_value` != ''";
    $DB->queryOrDie($query, "0.7 clean glpi_history " . $DB->error());
    $query = "DELETE\n             FROM `glpi_display`\n             WHERE `type` = " . USER_TYPE . "\n                   AND (`num` = 4)";
    $DB->queryOrDie($query, "0.7 clean glpi_display for glpi_users " . $DB->error());
    // Add fields to block auto updates on linked items
    if (!FieldExists("glpi_config", "autoupdate_link_contact", false)) {
        $query = "ALTER TABLE `glpi_config`\n                ADD COLUMN `autoupdate_link_contact` smallint(6) NOT NULL default '1'";
        $DB->queryOrDie($query, "0.7 add autoupdate_link_contact in glpi_config");
    }
    if (!FieldExists("glpi_config", "autoupdate_link_user", false)) {
        $query = "ALTER TABLE `glpi_config`\n                ADD COLUMN `autoupdate_link_user` smallint(6) NOT NULL default '1'";
        $DB->queryOrDie($query, "0.7 add autoupdate_link_user in glpi_config");
    }
    if (!FieldExists("glpi_config", "autoupdate_link_group", false)) {
        $query = "ALTER TABLE `glpi_config`\n                ADD COLUMN `autoupdate_link_group` smallint(6) NOT NULL default '1'";
        $DB->queryOrDie($query, "0.7 add autoupdate_link_group in glpi_config");
    }
    if (!FieldExists("glpi_config", "autoupdate_link_location", false)) {
        $query = "ALTER TABLE `glpi_config`\n                ADD COLUMN `autoupdate_link_location` smallint(6) NOT NULL default '1'";
        $DB->queryOrDie($query, "0.7 add autoupdate_link_location in glpi_config");
    }
    // Flat dropdowntree
    if (!FieldExists("glpi_config", "flat_dropdowntree", false)) {
        $query = "ALTER TABLE `glpi_config`\n                ADD COLUMN `flat_dropdowntree` smallint(6) NOT NULL default '0'";
        $DB->queryOrDie($query, "0.7 add flat_dropdowntree in glpi_config");
    }
    if (FieldExists("glpi_config", "mailing_signature", false)) {
        $query = "ALTER TABLE `glpi_config`\n                CHANGE `mailing_signature` `mailing_signature` TEXT NULL ";
        $DB->queryOrDie($query, "0.7 alter mailing signature in glpi_config");
    }
    //Software categories
    if (!TableExists("glpi_dropdown_software_category")) {
        $query = "CREATE TABLE `glpi_dropdown_software_category` (\n                  `ID` int(11) NOT NULL auto_increment,\n                  `name` varchar(255) default NULL,\n                  `comments` text,\n                  PRIMARY KEY (`ID`)\n                ) ENGINE=MyISAM ";
        $DB->queryOrDie($query, "0.7 add table glpi_dropdown_software_category");
    }
    if (!FieldExists("glpi_profiles", "rule_softwarecategories", false)) {
        $query = "ALTER TABLE `glpi_profiles`\n                ADD COLUMN `rule_softwarecategories` char(1) default NULL AFTER `rule_ldap`";
        $DB->queryOrDie($query, "0.7 add rule_softwarecategories in glpi_profiles");
        $query = "UPDATE `glpi_profiles`\n                SET `rule_softwarecategories` = `config`";
        $DB->queryOrDie($query, "0.7 update rule_softwarecategories values in glpi_profiles");
    }
    if (!FieldExists("glpi_software", "category", false)) {
        $query = "ALTER TABLE `glpi_software`\n                ADD `category` INT( 11 ) NOT NULL DEFAULT '0'";
        $DB->queryOrDie($query, "0.7 alter category in glpi_software");
    }
    if (!FieldExists("glpi_ocs_config", "import_monitor_comments", false)) {
        $query = "ALTER TABLE `glpi_ocs_config`\n                ADD `import_monitor_comments` INT( 2 ) NOT NULL DEFAULT '0' AFTER `import_ip`";
        $DB->queryOrDie($query, "0.7 alter import_monitor_comments in glpi_ocs_config");
    }
    if (!FieldExists("glpi_ocs_config", "import_software_comments", false)) {
        $query = "ALTER TABLE `glpi_ocs_config`\n                ADD `import_software_comments` INT NOT NULL DEFAULT '0'\n                     AFTER `import_monitor_comments`";
        $DB->queryOrDie($query, "0.7 alter import_software_comments in glpi_ocs_config");
    }
    if (FieldExists("glpi_device_gfxcard", "ram", false)) {
        //Update gfxcard memory management
        $query = "UPDATE `glpi_device_gfxcard`\n                SET `specif_default` = `ram`";
        $DB->queryOrDie($query, "0.7 glpi_device_gfxcard");
        $query = "ALTER TABLE `glpi_device_gfxcard`\n              DROP `ram`";
        $DB->queryOrDie($query, "0.7 delete 'ram' field from glpi_device_gfxcard");
    }
    if (FieldExists("glpi_config", "list_limit", false)) {
        //Update gfxcard memory management
        $query = "ALTER TABLE `glpi_config`\n                CHANGE `list_limit` `list_limit` INT NULL DEFAULT '20'";
        $DB->queryOrDie($query, "0.7 alter list_limit in config");
    }
    if (!FieldExists("glpi_config", "list_limit_max", false)) {
        //Update gfxcard memory management
        $query = "ALTER TABLE `glpi_config`\n                ADD `list_limit_max` INT NOT NULL DEFAULT '50' AFTER `list_limit` ";
        $DB->queryOrDie($query, "0.7 add list_limit_max in config");
    }
    if (!FieldExists("glpi_users", "list_limit", false)) {
        //Update gfxcard memory management
        $query = "ALTER TABLE `glpi_users`\n                ADD `list_limit` INT NOT NULL DEFAULT '20' AFTER `language`";
        $DB->queryOrDie($query, "0.7 add list_limit_max in users");
    }
    if (!FieldExists("glpi_config", "autoname_entity", false)) {
        $query = "ALTER TABLE `glpi_config`\n                ADD `autoname_entity` smallint(6) NOT NULL default '1' ";
        $DB->queryOrDie($query, "0.7 add autoname_entity in glpi_config");
    }
    if (!FieldExists("glpi_profiles", "rule_tracking", false)) {
        $query = "ALTER TABLE `glpi_profiles`\n                ADD COLUMN `rule_tracking` char(1) default NULL AFTER `config`";
        $DB->queryOrDie($query, "0.7 add rule_tracking in glpi_profiles");
        $query = "UPDATE `glpi_profiles`\n                SET `rule_tracking` = `config`";
        $DB->queryOrDie($query, "0.7 update rule_tracking values in glpi_profiles");
    }
    if (FieldExists("glpi_profiles", "show_ticket", false)) {
        $query = "ALTER TABLE `glpi_profiles`\n                CHANGE `show_ticket` `show_all_ticket` CHAR( 1 ) DEFAULT NULL ";
        $DB->queryOrDie($query, "0.7 rename show_ticket to show_all_ticket in glpi_profiles");
    }
    if (!FieldExists("glpi_profiles", "show_assign_ticket", false)) {
        $query = "ALTER TABLE `glpi_profiles`\n                ADD COLUMN `show_assign_ticket` char(1) default NULL AFTER `show_all_ticket`";
        $DB->queryOrDie($query, "0.7 add show_assign_ticket in glpi_profiles");
        $query = "UPDATE `glpi_profiles`\n                SET `show_assign_ticket` = `show_all_ticket`";
        $DB->queryOrDie($query, "0.7 update show_assign_ticket values in glpi_profiles");
    }
    if (!FieldExists("glpi_tracking", "assign_group", false)) {
        $query = "ALTER TABLE `glpi_tracking`\n                ADD `assign_group` INT NOT NULL DEFAULT '0' AFTER `assign_ent`";
        $DB->queryOrDie($query, "0.7 add assign_group in tracking");
        $query = "ALTER TABLE `glpi_tracking`\n                ADD INDEX (`assign_group`)";
        $DB->queryOrDie($query, "0.7 add index on assign_group in tracking");
    }
    if (!FieldExists("glpi_config", "expand_soft_categorized", false)) {
        $query = "ALTER TABLE `glpi_config`\n                ADD `expand_soft_categorized` int(1) NOT NULL DEFAULT '1'";
        $DB->queryOrDie($query, "0.7 add expand_soft_categorized in glpi_config");
    }
    if (!FieldExists("glpi_config", "expand_soft_not_categorized", false)) {
        $query = "ALTER TABLE `glpi_config`\n                ADD `expand_soft_not_categorized` int(1) NOT NULL DEFAULT '1'";
        $DB->queryOrDie($query, "0.7 add expand_soft_not_categorized in glpi_config");
    }
    $LINK_ID_TABLE = array(1 => "glpi_computers", 2 => "glpi_networking", 3 => "glpi_printers", 4 => "glpi_monitors", 5 => "glpi_peripherals", 6 => "glpi_software", 7 => "glpi_contacts", 8 => "glpi_enterprises", 9 => "glpi_infocoms", 10 => "glpi_contracts", 11 => "glpi_cartridges_type", 12 => "glpi_type_docs", 13 => "glpi_docs", 14 => "glpi_kbitems", 15 => "glpi_users", 16 => "glpi_tracking", 17 => "glpi_consumables_type", 18 => "glpi_consumables", 19 => "glpi_cartridges", 20 => "glpi_softwarelicenses", 21 => "glpi_links", 23 => "glpi_phones", 25 => "glpi_reminder", 27 => "glpi_groups", 28 => "glpi_entities", 29 => "glpi_reservation_item", 32 => "glpi_ocs_config", 33 => "glpi_registry", 34 => "glpi_profiles", 35 => "glpi_mailgate", 36 => "glpi_rules_descriptions", 37 => "glpi_transfers", 39 => "glpi_softwareversions", 41 => "glpi_computerdisks", 42 => "glpi_networking_ports", 43 => "glpi_followups");
    // Clean history
    $query = "SELECT DISTINCT `device_type`\n             FROM `glpi_history`";
    if ($result = $DB->query($query)) {
        if ($DB->numrows($result) > 0) {
            while ($data = $DB->fetch_array($result)) {
                $query2 = "DELETE\n                       FROM `glpi_history`\n                       WHERE `glpi_history`.`device_type` = '" . $data['device_type'] . "'\n                             AND `glpi_history`.`FK_glpi_device`\n                                  NOT IN (SELECT `ID`\n                                          FROM `" . $LINK_ID_TABLE[$data['device_type']] . "`)";
                $DB->query($query2);
            }
        }
    }
    if (!TableExists("glpi_transfers")) {
        $query = "CREATE TABLE `glpi_transfers` (\n                  `ID` int(11) NOT NULL auto_increment,\n                  `name` varchar(255) NOT NULL,\n                  `keep_tickets` tinyint(4) NOT NULL default '0',\n                  `keep_networklinks` tinyint(4) NOT NULL default '0',\n                  `keep_reservations` tinyint(4) NOT NULL default '0',\n                  `keep_history` tinyint(4) NOT NULL default '0',\n                  `keep_devices` tinyint(4) NOT NULL default '0',\n                  `keep_infocoms` tinyint(4) NOT NULL default '0',\n                  `keep_dc_monitor` tinyint(4) NOT NULL default '0',\n                  `clean_dc_monitor` tinyint(4) NOT NULL default '0',\n                  `keep_dc_phone` tinyint(4) NOT NULL default '0',\n                  `clean_dc_phone` tinyint(4) NOT NULL default '0',\n                  `keep_dc_peripheral` tinyint(4) NOT NULL default '0',\n                  `clean_dc_peripheral` tinyint(4) NOT NULL default '0',\n                  `keep_dc_printer` tinyint(4) NOT NULL default '0',\n                  `clean_dc_printer` tinyint(4) NOT NULL default '0',\n                  `keep_enterprises` tinyint(4) NOT NULL default '0',\n                  `clean_enterprises` tinyint(4) NOT NULL default '0',\n                  `keep_contacts` tinyint(4) NOT NULL default '0',\n                  `clean_contacts` tinyint(4) NOT NULL default '0',\n                  `keep_contracts` tinyint(4) NOT NULL default '0',\n                  `clean_contracts` tinyint(4) NOT NULL default '0',\n                  `keep_softwares` tinyint(4) NOT NULL default '0',\n                  `clean_softwares` tinyint(4) NOT NULL default '0',\n                  `keep_documents` tinyint(4) NOT NULL default '0',\n                  `clean_documents` tinyint(4) NOT NULL default '0',\n                  `keep_cartridges_type` tinyint(4) NOT NULL default '0',\n                  `clean_cartridges_type` tinyint(4) NOT NULL default '0',\n                  `keep_cartridges` tinyint(4) NOT NULL default '0',\n                  `keep_consumables` tinyint(4) NOT NULL default '0',\n                  PRIMARY KEY (`ID`)\n                ) ENGINE=MyISAM";
        $DB->queryOrDie($query, "0.7 add glpi_transfers");
        $query = "INSERT INTO `glpi_transfers`\n                VALUES ('1', 'complete', '2', '2', '1', '1', '1', '1', '1', '1', '1', '1', '1',\n                        '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1',\n                        '1', '1')";
        $DB->queryOrDie($query, "0.7 insert transfer default values");
    }
    if (!FieldExists("glpi_profiles", "transfer", false)) {
        $query = "ALTER TABLE `glpi_profiles`\n                ADD COLUMN `transfer` char(1) default NULL AFTER `entity`";
        $DB->queryOrDie($query, "0.7 add transfer in glpi_profiles");
        $query = "UPDATE `glpi_profiles`\n                SET `transfer` = `entity`";
        $DB->queryOrDie($query, "0.7 update transfer values in glpi_profiles");
    }
    // Need for update from SVN version
    if (!FieldExists("glpi_users", "location", false)) {
        $query = "ALTER TABLE `glpi_users`\n                ADD `location` int(11) NOT NULL DEFAULT 0";
        $DB->queryOrDie($query, "0.7 add location in users if not present for compatibility");
    }
    if (!FieldExists("glpi_ocs_config", "ocs_url", false)) {
        $query = "ALTER TABLE `glpi_ocs_config`\n                ADD `ocs_url` VARCHAR( 255 ) NOT NULL";
        $DB->queryOrDie($query, "0.7 add ocs_url in glpi_ocs_config if not present for compatibility");
    }
    if (!FieldExists("glpi_ocs_link", "ocs_agent_version", false)) {
        $query = "ALTER TABLE `glpi_ocs_link`\n                ADD `ocs_agent_version` VARCHAR( 255 ) default NULL";
        $DB->queryOrDie($query, "0.7 add ocs_agent_version in glpi_ocs_link if not present for compatibility");
    }
    if (!isIndex("glpi_history", "date_mod")) {
        $query = "ALTER TABLE `glpi_history`\n                ADD INDEX (`date_mod`)";
        $DB->queryOrDie($query, "0.7 alter history add index on date_mod");
    }
}
Example #10
0
function update068to0681()
{
    global $DB, $CFG_GLPI;
    if (TableExists("glpi_repair_item")) {
        $query = "DROP TABLE `glpi_repair_item`";
        $DB->queryOrDie($query, "0.68.1 drop glpi_repair_item");
    }
    $tables = array("computers", "monitors", "networking", "peripherals", "phones", "printers");
    foreach ($tables as $tbl) {
        if (isIndex("glpi_" . $tbl, "type")) {
            $query = "ALTER TABLE `glpi_{$tbl}`\n                   DROP INDEX `type`";
            $DB->queryOrDie($query, "0.68.1 drop index type glpi_{$tbl}");
        }
        if (isIndex("glpi_" . $tbl, "type_2")) {
            $query = "ALTER TABLE `glpi_{$tbl}`\n                   DROP INDEX `type_2`";
            $DB->queryOrDie($query, "0.68.1 drop index type_2 glpi_{$tbl}");
        }
        if (isIndex("glpi_" . $tbl, "model")) {
            $query = "ALTER TABLE `glpi_{$tbl}`\n                   DROP INDEX `model`";
            $DB->queryOrDie($query, "0.68.1 drop index model glpi_{$tbl}");
        }
        if (!isIndex("glpi_" . $tbl, "type")) {
            $query = "ALTER TABLE `glpi_{$tbl}`\n                   ADD INDEX (`type`)";
            $DB->queryOrDie($query, "0.68.1 add index type glpi_{$tbl}");
        }
        if (!isIndex("glpi_" . $tbl, "model")) {
            $query = "ALTER TABLE `glpi_{$tbl}`\n                   ADD INDEX (`model`)";
            $DB->queryOrDie($query, "0.68.1 add index model glpi_{$tbl}");
        }
        if (!isIndex("glpi_" . $tbl, "FK_groups")) {
            $query = "ALTER TABLE `glpi_{$tbl}`\n                   ADD INDEX (`FK_groups`)";
            $DB->queryOrDie($query, "0.68.1 add index on glpi_{$tbl}.FK_groups");
        }
        if (!isIndex("glpi_" . $tbl, "FK_users")) {
            $query = "ALTER TABLE `glpi_{$tbl}`\n                   ADD INDEX ( `FK_users` )";
            $DB->queryOrDie($query, "0.68.1 add index on glpi_{$tbl}.FK_users");
        }
    }
    if (!isIndex("glpi_software", "FK_groups")) {
        $query = "ALTER TABLE `glpi_software`\n                ADD INDEX (`FK_groups`)";
        $DB->queryOrDie($query, "0.68.1 add index on glpi_software.FK_groups");
    }
    if (!isIndex("glpi_software", "FK_users")) {
        $query = "ALTER TABLE `glpi_software`\n                ADD INDEX ( `FK_users` )";
        $DB->queryOrDie($query, "0.68.1 add index on glpi_software.FK_users");
    }
    if (!isIndex("glpi_cartridges_type", "location")) {
        $query = "ALTER TABLE `glpi_cartridges_type`\n                ADD INDEX (`location`)";
        $DB->queryOrDie($query, "0.68.1 add index on glpi_cartridges_type.location");
    }
    if (FieldExists("glpi_cartridges_type", "type", false)) {
        $query = "ALTER TABLE `glpi_cartridges_type`\n                CHANGE `type` `type` INT NOT NULL DEFAULT '0'";
        $DB->queryOrDie($query, "0.68.1 alter glpi_cartridges_type.type");
    }
    if (!isIndex("glpi_cartridges_type", "type")) {
        $query = "ALTER TABLE `glpi_cartridges_type`\n               ADD INDEX (`type`)";
        $DB->queryOrDie($query, "0.68.1 add index on glpi_cartridges_type.type");
    }
    if (!isIndex("glpi_cartridges_type", "alarm")) {
        $query = "ALTER TABLE `glpi_cartridges_type`\n                ADD INDEX (`alarm`)";
        $DB->queryOrDie($query, "0.68.1 add index on glpi_cartridges_type.alarm");
    }
    if (!isIndex("glpi_computers", "os_sp")) {
        $query = "ALTER TABLE `glpi_computers`\n                ADD INDEX (`os_sp`)";
        $DB->queryOrDie($query, "0.68.1 add index on glpi_computers.os_sp");
    }
    if (!isIndex("glpi_computers", "os_version")) {
        $query = "ALTER TABLE `glpi_computers`\n                ADD INDEX (`os_version`)";
        $DB->queryOrDie($query, "0.68.1 add index on glpi_computers.os_version");
    }
    if (!isIndex("glpi_computers", "network")) {
        $query = "ALTER TABLE `glpi_computers`\n                ADD INDEX (`network`)";
        $DB->queryOrDie($query, "0.68.1 add index on glpi_computers.network");
    }
    if (!isIndex("glpi_computers", "domain")) {
        $query = "ALTER TABLE `glpi_computers`\n                ADD INDEX (`domain`)";
        $DB->queryOrDie($query, "0.68.1 add index on glpi_computers.domain");
    }
    if (!isIndex("glpi_computers", "auto_update")) {
        $query = "ALTER TABLE `glpi_computers`\n                ADD INDEX (`auto_update`)";
        $DB->queryOrDie($query, "0.68.1 add index on glpi_computers.auto_update");
    }
    if (!isIndex("glpi_computers", "ocs_import")) {
        $query = "ALTER TABLE `glpi_computers`\n                ADD INDEX (`ocs_import`)";
        $DB->queryOrDie($query, "0.68.1 add index on glpi_computers.ocs_import");
    }
    if (!isIndex("glpi_consumables", "id_user")) {
        $query = "ALTER TABLE `glpi_consumables`\n                ADD INDEX (`id_user`)";
        $DB->queryOrDie($query, "0.68.1 add index on glpi_consumables.id_user");
    }
    if (!isIndex("glpi_consumables_type", "location")) {
        $query = "ALTER TABLE `glpi_consumables_type`\n                ADD INDEX (`location`)";
        $DB->queryOrDie($query, "0.68.1 add index on glpi_consumables_type.location");
    }
    if (!isIndex("glpi_consumables_type", "type")) {
        $query = "ALTER TABLE `glpi_consumables_type`\n                ADD INDEX (`type`)";
        $DB->queryOrDie($query, "0.68.1 add index on glpi_consumables_type.type");
    }
    if (!isIndex("glpi_consumables_type", "alarm")) {
        $query = "ALTER TABLE `glpi_consumables_type`\n                ADD INDEX (`alarm`)";
        $DB->queryOrDie($query, "0.68.1 add index on glpi_consumables_type.alarm");
    }
    if (FieldExists("glpi_contacts", "type", false)) {
        $query = "ALTER TABLE `glpi_contacts`\n                CHANGE `type` `type` INT( 11 ) NULL ";
        $DB->queryOrDie($query, "0.68.1 alter glpi_contacts.type");
    }
    if (!isIndex("glpi_contract_device", "device_type")) {
        $query = "ALTER TABLE `glpi_contract_device`\n                ADD INDEX (`device_type`)";
        $DB->queryOrDie($query, "0.68.1 add index on glpi_contract_device.device_type");
    }
    if (!isIndex("glpi_contract_device", "is_template")) {
        $query = "ALTER TABLE `glpi_contract_device`\n                ADD INDEX (`is_template`)";
        $DB->queryOrDie($query, "0.68.1 add index on glpi_contract_device.is_template");
    }
    if (!isIndex("glpi_device_hdd", "interface")) {
        $query = "ALTER TABLE `glpi_device_hdd`\n                ADD INDEX (`interface`)";
        $DB->queryOrDie($query, "0.68.1 add index on glpi_device_hdd.interface");
    }
    if (!isIndex("glpi_device_ram", "type")) {
        $query = "ALTER TABLE `glpi_device_ram`\n                ADD INDEX (`type`)";
        $DB->queryOrDie($query, "0.68.1 add index on glpi_device_ram.type");
    }
    if (!isIndex("glpi_display", "FK_users")) {
        $query = "ALTER TABLE `glpi_display`\n                ADD INDEX (`FK_users`)";
        $DB->queryOrDie($query, "0.68.1 add index on glpi_display.FK_users");
    }
    if (!isIndex("glpi_docs", "FK_users")) {
        $query = "ALTER TABLE `glpi_docs`\n                ADD INDEX (`FK_users`)";
        $DB->queryOrDie($query, "0.68.1 add index on glpi_docs.FK_users");
    }
    if (!isIndex("glpi_docs", "FK_tracking")) {
        $query = "ALTER TABLE `glpi_docs`\n                ADD INDEX (`FK_tracking`)";
        $DB->queryOrDie($query, "0.68.1 add index on glpi_docs.FK_tracking");
    }
    if (!isIndex("glpi_doc_device", "device_type")) {
        $query = "ALTER TABLE `glpi_doc_device`\n                ADD INDEX (`device_type`)";
        $DB->queryOrDie($query, "0.68.1 add index on glpi_doc_device.device_type");
    }
    if (!isIndex("glpi_dropdown_tracking_category", "parentID")) {
        $query = "ALTER TABLE `glpi_dropdown_tracking_category`\n                ADD INDEX (`parentID`)";
        $DB->queryOrDie($query, "0.68.1 add index on glpi_dropdown_tracking_category.parentID");
    }
    if (!isIndex("glpi_history", "device_type")) {
        $query = "ALTER TABLE `glpi_history`\n                ADD INDEX (`device_type`)";
        $DB->queryOrDie($query, "0.68.1 add index on glpi_history.device_type");
    }
    if (!isIndex("glpi_history", "device_internal_type")) {
        $query = "ALTER TABLE `glpi_history`\n                ADD INDEX (`device_internal_type`)";
        $DB->queryOrDie($query, "0.68.1 add index on glpi_history.device_internal_type");
    }
    if (!isIndex("glpi_infocoms", "budget")) {
        $query = "ALTER TABLE `glpi_infocoms`\n                ADD INDEX (`budget`)";
        $DB->queryOrDie($query, "0.68.1 add index on glpi_infocoms.budget");
    }
    if (!isIndex("glpi_infocoms", "alert")) {
        $query = "ALTER TABLE `glpi_infocoms`\n                ADD INDEX (`alert`)";
        $DB->queryOrDie($query, "0.68.1 add index on glpi_infocoms.alert");
    }
    if (!isIndex("glpi_kbitems", "author")) {
        $query = "ALTER TABLE `glpi_kbitems`\n                ADD INDEX (`author`)";
        $DB->queryOrDie($query, "0.68.1 add index on glpi_kbitems.author");
    }
    if (!isIndex("glpi_kbitems", "faq")) {
        $query = "ALTER TABLE `glpi_kbitems`\n                ADD INDEX (`faq`)";
        $DB->queryOrDie($query, "0.68.1 add index on glpi_kbitems.faq");
    }
    if (!isIndex("glpi_licenses", "oem_computer")) {
        $query = "ALTER TABLE `glpi_licenses`\n                ADD INDEX (`oem_computer`)";
        $DB->queryOrDie($query, "0.68.1 add index on glpi_licenses.oem_computer");
    }
    if (!isIndex("glpi_licenses", "oem")) {
        $query = "ALTER TABLE `glpi_licenses`\n                ADD INDEX (`oem`)";
        $DB->queryOrDie($query, "0.68.1 add index on glpi_licenses.oem");
    }
    if (!isIndex("glpi_licenses", "buy")) {
        $query = "ALTER TABLE `glpi_licenses`\n                ADD INDEX (`buy`)";
        $DB->queryOrDie($query, "0.68.1 add index on glpi_licenses.buy");
    }
    if (!isIndex("glpi_licenses", "serial")) {
        $query = "ALTER TABLE `glpi_licenses`\n                ADD INDEX (`serial`)";
        $DB->queryOrDie($query, "0.68.1 add index on glpi_licenses.serial");
    }
    if (!isIndex("glpi_licenses", "expire")) {
        $query = "ALTER TABLE `glpi_licenses`\n                ADD INDEX (`expire`)";
        $DB->queryOrDie($query, "0.68.1 add index on glpi_licenses.expire");
    }
    if (!isIndex("glpi_networking", "network")) {
        $query = "ALTER TABLE `glpi_networking`\n                ADD INDEX (`network`)";
        $DB->queryOrDie($query, "0.68.1 add index on glpi_networking.network");
    }
    if (!isIndex("glpi_networking", "domain")) {
        $query = "ALTER TABLE `glpi_networking`\n                ADD INDEX (`domain`)";
        $DB->queryOrDie($query, "0.68.1 add index on glpi_networking.domain");
    }
    if (!isIndex("glpi_networking_ports", "iface")) {
        $query = "ALTER TABLE `glpi_networking_ports`\n                ADD INDEX (`iface`)";
        $DB->queryOrDie($query, "0.68.1 add index on glpi_networking_ports.iface");
    }
    if (FieldExists("glpi_phones", "power", false)) {
        $query = "ALTER TABLE `glpi_phones`\n                CHANGE `power` `power` INT NOT NULL DEFAULT '0'";
        $DB->queryOrDie($query, "0.68.1 alter glpi_phones.power");
    }
    if (!isIndex("glpi_phones", "power")) {
        $query = "ALTER TABLE `glpi_phones`\n                ADD INDEX (`power`)";
        $DB->queryOrDie($query, "0.68.1 add index on glpi_phones.power");
    }
    if (!isIndex("glpi_reminder", "begin")) {
        $query = "ALTER TABLE `glpi_reminder`\n                ADD INDEX (`begin`)";
        $DB->queryOrDie($query, "0.68.1 add index on glpi_reminder.begin");
    }
    if (!isIndex("glpi_reminder", "end")) {
        $query = "ALTER TABLE `glpi_reminder`\n                ADD INDEX (`end`)";
        $DB->queryOrDie($query, "0.68.1 add index on glpi_reminder.end");
    }
    if (!isIndex("glpi_software", "update_software")) {
        $query = "ALTER TABLE `glpi_software`\n                ADD INDEX (`update_software`)";
        $DB->queryOrDie($query, "0.68.1 add index on glpi_software.update_software");
    }
    if (!isIndex("glpi_state_item", "state")) {
        $query = "ALTER TABLE `glpi_state_item`\n                ADD INDEX (`state`)";
        $DB->queryOrDie($query, "0.68.1 add index on glpi_state_item.state");
    }
    if (!isIndex("glpi_tracking", "FK_group")) {
        $query = "ALTER TABLE `glpi_tracking`\n                ADD INDEX (`FK_group`)";
        $DB->queryOrDie($query, "0.68.1 add index on glpi_tracking.FK_group");
    }
    if (!isIndex("glpi_tracking", "assign_ent")) {
        $query = "ALTER TABLE `glpi_tracking`\n                ADD INDEX (`assign_ent`)";
        $DB->queryOrDie($query, "0.68.1 add index on glpi_tracking.assign_ent");
    }
    if (!isIndex("glpi_tracking", "device_type")) {
        $query = "ALTER TABLE `glpi_tracking`\n                ADD INDEX (`device_type`)";
        $DB->queryOrDie($query, "0.68.1 add index on glpi_tracking.device_type");
    }
    if (!isIndex("glpi_tracking", "priority")) {
        $query = "ALTER TABLE `glpi_tracking`\n                ADD INDEX (`priority`)";
        $DB->queryOrDie($query, "0.68.1 add index on glpi_tracking.priority");
    }
    if (!isIndex("glpi_tracking", "request_type")) {
        $query = "ALTER TABLE `glpi_tracking`\n                ADD INDEX (`request_type`)";
        $DB->queryOrDie($query, "0.68.1 add index on glpi_tracking.request_type");
    }
    if (!isIndex("glpi_users", "location")) {
        $query = "ALTER TABLE `glpi_users`\n                ADD INDEX (`location`)";
        $DB->queryOrDie($query, "0.68.1 add index on glpi_users.location");
    }
    if (!isIndex("glpi_printers", "network")) {
        $query = "ALTER TABLE `glpi_printers`\n                ADD INDEX (`network`)";
        $DB->queryOrDie($query, "0.68.1 add index on glpi_printers.network");
    }
    if (!isIndex("glpi_printers", "domain")) {
        $query = "ALTER TABLE `glpi_printers`\n                ADD INDEX (`domain`)";
        $DB->queryOrDie($query, "0.68.1 add index on glpi_printers.domain");
    }
    if (FieldExists("glpi_device_case", "format", false)) {
        $query = "ALTER TABLE `glpi_device_case`\n                CHANGE `format` `format` ENUM('Grand', 'Moyen', 'Micro', 'Slim', '')\n                                         NULL DEFAULT 'Moyen'";
        $DB->queryOrDie($query, "0.68.1 alter glpi_device_case.format");
    }
    if (FieldExists("glpi_device_gfxcard", "interface", false)) {
        $query = "ALTER TABLE `glpi_device_gfxcard`\n                CHANGE `interface` `interface` ENUM('AGP', 'PCI', 'PCI-X', 'Other', '')\n                                               NULL DEFAULT 'AGP'";
        $DB->queryOrDie($query, "0.68.1 alter glpi_device_gfxcard.interface");
    }
    // Add default values in GLPI_DROPDOWN_HDD_TYPE
    // Rename glpi_dropdown HDD_TYPE -> INTERFACE
    if (!TableExists("glpi_dropdown_interface")) {
        $query = "ALTER TABLE `glpi_dropdown_hdd_type`\n                RENAME `glpi_dropdown_interface` ";
        $DB->queryOrDie($query, "0.68.1 alter dropdown_hdd_type -> dropdown_interface");
        $values = array("SATA", "IDE", "SCSI", "USB");
        $interfaces = array();
        foreach ($values as $val) {
            $query = "SELECT *\n                   FROM `glpi_dropdown_interface`\n                   WHERE `name` LIKE '{$val}'";
            $result = $DB->query($query);
            if ($DB->numrows($result) == 1) {
                $row = $DB->fetch_array($result);
                $interfaces[$val] = $row["ID"];
            } else {
                $query = "INSERT INTO `glpi_dropdown_interface`\n                             (`name`)\n                      VALUES ('{$val}');";
                $DB->query($query);
                $interfaces[$val] = $DB->insert_id();
            }
        }
        // ALTER TABLES
        $query = "ALTER TABLE `glpi_device_control`\n                CHANGE `interface` `interface2` ENUM('IDE', 'SATA', 'SCSI', 'USB') NOT NULL\n                                                DEFAULT 'IDE'";
        $DB->queryOrDie($query, "0.68.1 alter device_control");
        $query = "ALTER TABLE `glpi_device_drive`\n                CHANGE `interface` `interface2` ENUM('IDE', 'SATA', 'SCSI') NOT NULL DEFAULT 'IDE'";
        $DB->queryOrDie($query, "0.68.1 alter device_drive");
        $query = "ALTER TABLE `glpi_device_control`\n                ADD `interface` INT NULL ";
        $DB->queryOrDie($query, "0.68.1 alter device_control");
        $query = "ALTER TABLE `glpi_device_drive`\n                ADD `interface` INT NULL ";
        $DB->queryOrDie($query, "0.68.1 alter device_drive");
        foreach ($interfaces as $name => $ID) {
            $query = "UPDATE `glpi_device_drive`\n                   SET `interface` = '{$ID}'\n                   WHERE `interface2` = '{$name}'";
            $DB->queryOrDie($query, "0.68.1 update data device_drive");
            $query = "UPDATE `glpi_device_control`\n                   SET `interface` = '{$ID}'\n                   WHERE `interface2` = '{$name}'";
            $DB->queryOrDie($query, "0.68.1 update data device_control");
        }
        // DROP TABLES
        $query = "ALTER TABLE `glpi_device_control`\n                DROP `interface2`";
        $DB->queryOrDie($query, "0.68.1 drop interface2 device_drive");
        $query = "ALTER TABLE `glpi_device_drive`\n                DROP `interface2`";
        $DB->queryOrDie($query, "0.68.1 drop interface2 device_drive");
        // ADD INDEX
        $query = "ALTER TABLE `glpi_device_drive`\n                ADD INDEX (`interface`)";
        $DB->queryOrDie($query, "0.68.1 add index on glpi_device_drive.interface");
        $query = "ALTER TABLE `glpi_device_control`\n                ADD INDEX (`interface`)";
        $DB->queryOrDie($query, "0.68.1 add index on glpi_device_drive.interface");
    }
    if (FieldExists("glpi_profiles", "update", false)) {
        $query = "ALTER TABLE `glpi_profiles`\n                CHANGE `update` `check_update` CHAR( 1 ) NULL DEFAULT NULL";
        $DB->queryOrDie($query, "0.68.1 alter glpi_profiles.update");
    }
    if (FieldExists("glpi_config", "last_update_check", false)) {
        $query = "ALTER TABLE `glpi_config`\n                DROP `last_update_check`";
        $DB->queryOrDie($query, "0.68.1 drop glpi_config.last_update_check");
    }
    if (!FieldExists("glpi_config", "keep_tracking_on_delete", false)) {
        $query = "ALTER TABLE `glpi_config`\n                ADD `keep_tracking_on_delete` INT DEFAULT '1'";
        $DB->queryOrDie($query, "0.68.1 drop glpi_config.keep_tracking_on_delete");
    }
    if (!FieldExists("glpi_config", "show_admin_doc", false)) {
        $query = "ALTER TABLE `glpi_config`\n                ADD `show_admin_doc` INT DEFAULT '0' ";
        $DB->queryOrDie($query, "0.68.1 drop glpi_config.show_admin_doc");
    }
    if (!FieldExists("glpi_config", "time_step", false)) {
        $query = "ALTER TABLE `glpi_config`\n                ADD `time_step` INT DEFAULT '5' ";
        $DB->queryOrDie($query, "0.68.1 drop glpi_config.time_step");
    }
    $query = "UPDATE `glpi_config`\n             SET `time_step` = '5',\n                 `show_admin_doc` = '0',\n                 `keep_tracking_on_delete` = '0'";
    $DB->queryOrDie($query, "0.68.1 update glpi_config data");
    if (!FieldExists("glpi_ocs_config", "cron_sync_number", false)) {
        $query = "ALTER TABLE `glpi_ocs_config`\n                ADD `cron_sync_number` INT DEFAULT '1' ";
        $DB->queryOrDie($query, "0.68.1 drop glpi_ocs_config.cron_sync_number");
    }
    if (!FieldExists("glpi_profiles", "show_group_ticket", false)) {
        $query = "ALTER TABLE `glpi_profiles`\n                ADD `show_group_ticket` char(1) DEFAULT '0' ";
        $DB->queryOrDie($query, "0.68.1 drop glpi_profiles.show_group_ticket");
    }
    if (!FieldExists("glpi_config", "ldap_group_condition", false)) {
        $query = "ALTER TABLE `glpi_config`\n                ADD `ldap_group_condition` VARCHAR( 255 ) NULL ,\n                ADD `ldap_search_for_groups` TINYINT NOT NULL DEFAULT '0',\n                ADD `ldap_field_group_member` VARCHAR( 255 ) NULL ";
        $DB->queryOrDie($query, "0.68.1 add glpi_config.ldap_*_groups");
    }
    if (!FieldExists("glpi_groups", "ldap_group_dn", false)) {
        $query = "ALTER TABLE `glpi_groups`\n                ADD `ldap_group_dn` VARCHAR( 255 ) NULL ";
        $DB->queryOrDie($query, "0.68.1 add glpi_groups.ldap_group_dn");
    }
    if (!FieldExists("glpi_ocs_link", "ocs_deviceid", false)) {
        $query = "ALTER TABLE `glpi_ocs_link`\n                CHANGE `ocs_id` `ocs_deviceid` VARCHAR( 255 ) NOT NULL ";
        $DB->queryOrDie($query, "0.68.1 add glpi_ocs_link.ocs_deviceid");
    }
    if (!FieldExists("glpi_ocs_link", "ocs_id", false)) {
        $query = "ALTER TABLE `glpi_ocs_link`\n                ADD `ocs_id` INT NOT NULL DEFAULT '0' AFTER `glpi_id` ";
        $DB->queryOrDie($query, "0.68.1 add glpi_ocs_link.ocs_id");
    }
    if (!FieldExists("glpi_ocs_link", "last_ocs_update", false)) {
        $query = "ALTER TABLE `glpi_ocs_link`\n                ADD `last_ocs_update` DATETIME NULL AFTER `last_update` ";
        $DB->queryOrDie($query, "0.68.1 add glpi_ocs_link.last_ocs_update");
    }
    if (countElementsInTable("glpi_ocs_link")) {
        $CFG_GLPI["ocs_mode"] = 1;
        $DBocs = new DBocs(1);
        // Get datas to update
        $query = "SELECT *\n                FROM `glpi_ocs_link`";
        $result_glpi = $DB->query($query);
        while ($data_glpi = $DB->fetch_array($result_glpi)) {
            // Get ocs information
            $query_ocs = "SELECT *\n                       FROM `hardware`\n                       WHERE `DEVICEID` = '" . $data_glpi["ocs_deviceid"] . "'\n                       LIMIT 1";
            $result_ocs = $DBocs->queryOrDie($query_ocs, "0.68.1 get ocs infos");
            if ($result_ocs && $DBocs->numrows($result_ocs)) {
                $data_ocs = $DBocs->fetch_array($result_ocs);
                $query_update = "UPDATE `glpi_ocs_link`\n                             SET `ocs_id` = '" . $data_ocs["ID"] . "',\n                                 `last_ocs_update` = '" . $data_ocs["LASTDATE"] . "'\n                             WHERE `ID` = '" . $data_glpi["ID"] . "'";
                $DB->queryOrDie($query_update, "0.68.1 update ocs infos");
            }
        }
    }
    if (!TableExists("glpi_dropdown_case_type")) {
        $query = "CREATE TABLE `glpi_dropdown_case_type` (\n                  `ID` int(11) NOT NULL auto_increment,\n                  `name` varchar(255) NOT NULL,\n                  `comments` text,\n                  PRIMARY KEY (`ID`),\n                  KEY `name` (`name`)\n                ) ENGINE=MyISAM;";
        $DB->queryOrDie($query, "0.68.1 add table dropdown_case_type");
        // ajout du champs type
        $query = "ALTER TABLE `glpi_device_case`\n                ADD   `type` INT(11) default NULL AFTER `designation` ";
        $DB->queryOrDie($query, "0.68.1 add glpi_device_case.type");
        // Ajout des entrees dans la table dropdown_case_type
        $query = "INSERT INTO `glpi_dropdown_case_type`\n                       (`ID` , `name` , `comments`)\n                VALUES ('1' , 'Grand', NULL)";
        $DB->queryOrDie($query, "0.68.1 glpi_device_case");
        $query = "INSERT INTO `glpi_dropdown_case_type`\n                       (`ID` , `name` , `comments`)\n                VALUES ('2' , 'Moyen', NULL)";
        $DB->queryOrDie($query, "0.68.1 glpi_device_case");
        $query = "INSERT INTO `glpi_dropdown_case_type`\n                       (`ID` , `name` , `comments`)\n                VALUES ('3' , 'Micro', NULL)";
        $DB->queryOrDie($query, "0.68.1 glpi_device_case");
        // Mapping format enum / type
        $query = "UPDATE `glpi_device_case`\n                SET `type` = '1'\n                WHERE `format` = 'Grand'";
        $DB->queryOrDie($query, "0.68.1 glpi_device_case");
        $query = "UPDATE `glpi_device_case`\n                SET `type` = '2'\n                WHERE `format` = 'Moyen'";
        $DB->queryOrDie($query, "0.68.1 glpi_device_case");
        $query = "UPDATE `glpi_device_case`\n                SET `type` = '3'\n                 WHERE `format` = 'Micro'";
        $DB->queryOrDie($query, "0.68.1 glpi_device_case");
        // Supression du champ format
        $query = "ALTER TABLE `glpi_device_case`\n                DROP `format`";
        $DB->queryOrDie($query, "0.68.1 drop format from glpi_device_case");
    }
    // Clean state datas
    if (TableExists("glpi_state_item")) {
        $query = "SELECT COUNT(*) AS CPT, `device_type`, `id_device`\n                FROM `glpi_state_item`\n                GROUP BY `device_type`, `id_device`\n                HAVING CPT > 1";
        $result = $DB->query($query);
        if ($DB->numrows($result)) {
            while ($data = $DB->fetch_array($result)) {
                $query2 = "DELETE\n                       FROM `glpi_state_item`\n                       WHERE `device_type` = '" . $data["device_type"] . "'\n                             AND `id_device` = '" . $data["id_device"] . "'\n                       LIMIT " . ($data["CPT"] - 1) . "";
                $DB->queryOrDie($query2, "0.68.1 clean glpi_state_item");
            }
        }
        if (isIndex("glpi_state_item", "device_type")) {
            $query = "ALTER TABLE `glpi_state_item`\n                   DROP INDEX `device_type` ";
            $DB->queryOrDie($query, "0.68.1 drop index glpi_state_item");
        }
        if (isIndex("glpi_state_item", "device_type2")) {
            $query = "ALTER TABLE `glpi_state_item`\n                   DROP INDEX `device_type2` ";
            $DB->queryOrDie($query, "0.68.1 drop index glpi_state_item");
        }
        $query = "ALTER TABLE `glpi_state_item`\n                ADD INDEX (`device_type`) ";
        $DB->queryOrDie($query, "0.68.1 add index glpi_state_item");
        $query = "ALTER TABLE `glpi_state_item`\n                ADD UNIQUE (`device_type`, `id_device`) ";
        $DB->queryOrDie($query, "0.68.1 add unique glpi_state_item");
    }
}
Example #11
0
 /**
  * @covers ::isIndex
  **/
 public function testIsIndex()
 {
     $this->assertFalse(isIndex('glpi_configs', 'fakeField'));
     $this->assertFalse(isIndex('fakeTable', 'id'));
     $this->assertFalse(isIndex('glpi_configs', 'name'));
     $this->assertTrue(isIndex('glpi_users', 'locations_id'));
     $this->assertTrue(isIndex('glpi_users', 'unicity'));
 }
/**
 * Update from 0.78.2 to 0.80
 *
 * @return bool for success (will die for most error)
**/
function update0782to080()
{
    global $DB, $migration;
    $updateresult = true;
    $ADDTODISPLAYPREF = array();
    //TRANS: %s is the number of new version
    $migration->displayTitle(sprintf(__('Update to %s'), '0.80'));
    $migration->setVersion('0.80');
    $backup_tables = false;
    $newtables = array('glpi_calendars', 'glpi_calendars_holidays', 'glpi_calendarsegments', 'glpi_computervirtualmachines', 'glpi_computers_softwarelicenses', 'glpi_fieldblacklists', 'glpi_fieldunicities', 'glpi_groups_tickets', 'glpi_holidays', 'glpi_rulecacheprinters', 'glpi_slas', 'glpi_slalevels', 'glpi_slalevels_tickets', 'glpi_slalevelactions', 'glpi_tickets_tickets', 'glpi_tickets_users', 'glpi_ticketsatisfactions', 'glpi_ticketsolutiontemplates', 'glpi_virtualmachinestates', 'glpi_virtualmachinesystems', 'glpi_virtualmachinetypes');
    foreach ($newtables as $new_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.80 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 = $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(__('Change of the database layout - %s'), 'Calendar'));
    // Updating schema
    $default_calendar_id = 0;
    if (!TableExists('glpi_calendars')) {
        $query = "CREATE TABLE `glpi_calendars` (\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                  `comment` TEXT DEFAULT NULL ,\n                  `date_mod` DATETIME DEFAULT NULL ,\n                  `cache_duration` TEXT DEFAULT NULL ,\n                  PRIMARY KEY  (`id`),\n                  KEY `name` (`name`),\n                  KEY `entities_id` (`entities_id`),\n                  KEY `is_recursive` (`is_recursive`),\n                  KEY `date_mod` (`date_mod`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.80 create glpi_calendars");
        $ADDTODISPLAYPREF['Calendar'] = array(19);
        // Create default calendar : use existing config planning_begin _end
        $query = "INSERT INTO `glpi_calendars`\n                       (`name`, `entities_id`, `is_recursive`, `comment`)\n                VALUES ('Default', 0, 1, 'Default calendar');";
        $DB->queryOrDie($query, "0.80 add default glpi_calendars");
        $default_calendar_id = $DB->insert_id();
    }
    if (!TableExists('glpi_calendarsegments')) {
        $query = "CREATE TABLE `glpi_calendarsegments` (\n                  `id` int(11) NOT NULL auto_increment,\n                  `calendars_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                  `day` tinyint(1) NOT NULL default '1' COMMENT 'numer of the day based on date(w)',\n                  `begin` time DEFAULT NULL,\n                  `end` time DEFAULT NULL,\n                  PRIMARY KEY  (`id`),\n                  KEY `calendars_id` (`calendars_id`),\n                  KEY `day` (`day`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.80 create glpi_calendarsegments");
        // add defautl days : from monday to friday
        if ($default_calendar_id > 0) {
            $query = "SELECT `planning_begin`, `planning_end`\n                   FROM `glpi_configs`\n                   WHERE `id` = '1'";
            if ($result = $DB->query($query)) {
                $begin = $DB->result($result, 0, 'planning_begin');
                $end = $DB->result($result, 0, 'planning_end');
                if ($begin < $end) {
                    for ($i = 1; $i < 6; $i++) {
                        $query = "INSERT INTO `glpi_calendarsegments`\n                                   (`calendars_id`, `day`, `begin`, `end`)\n                            VALUES ({$default_calendar_id}, {$i}, '{$begin}', '{$end}')";
                        $DB->queryOrDie($query, "0.80 add default glpi_calendarsegments");
                    }
                }
            }
            // Update calendar
            $calendar = new Calendar();
            if ($calendar->getFromDB($default_calendar_id)) {
                $query = "UPDATE `glpi_calendars`\n                      SET `cache_duration` = '" . exportArrayToDB($calendar->getDaysDurations()) . "'\n                      WHERE `id` = '{$default_calendar_id}'";
                $DB->queryOrDie($query, "0.80 update default calendar cache");
            }
        }
    }
    // Holidays : wrong management : may be a group of several days : will be easy to managed holidays
    if (!TableExists('glpi_holidays')) {
        $query = "CREATE TABLE `glpi_holidays` (\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                  `comment` TEXT DEFAULT NULL ,\n                  `begin_date` date default NULL,\n                  `end_date` date default NULL,\n                  `is_perpetual` tinyint(1) NOT NULL default '0',\n                  PRIMARY KEY  (`id`),\n                  KEY `name` (`name`),\n                  KEY `begin_date` (`begin_date`),\n                  KEY `end_date` (`end_date`),\n                  KEY `is_perpetual` (`is_perpetual`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.80 create glpi_holidays");
        $ADDTODISPLAYPREF['Holiday'] = array(11, 12, 13);
    }
    if (!TableExists('glpi_calendars_holidays')) {
        $query = "CREATE TABLE `glpi_calendars_holidays` (\n                  `id` int(11) NOT NULL auto_increment,\n                  `calendars_id` int(11) NOT NULL default '0',\n                  `holidays_id` int(11) NOT NULL default '0',\n                  PRIMARY KEY  (`id`),\n                  UNIQUE KEY `unicity` (`calendars_id`,`holidays_id`),\n                  KEY `holidays_id` (`holidays_id`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.80 create glpi_calendars_holidays");
    }
    $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'SLA'));
    // Updating schema
    if (!TableExists('glpi_slas')) {
        $query = "CREATE TABLE `glpi_slas` (\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                  `comment` TEXT DEFAULT NULL ,\n                  `resolution_time` int(11) NOT NULL,\n                  `calendars_id` int(11) NOT NULL default '0',\n                  `date_mod` datetime default NULL,\n                  PRIMARY KEY  (`id`),\n                  KEY `name` (`name`),\n                  KEY `calendars_id` (`calendars_id`),\n                  KEY `entities_id` (`entities_id`),\n                  KEY `is_recursive` (`is_recursive`),\n                  KEY `date_mod` (`date_mod`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.80 create glpi_slas");
        $ADDTODISPLAYPREF['SLA'] = array(4);
        // Get first Ticket template
        $query = "SELECT `id`\n                FROM `glpi_notificationtemplates`\n                WHERE `itemtype` LIKE 'Ticket%'\n                ORDER BY `id` ASC";
        if ($result = $DB->query($query)) {
            if ($DB->numrows($result) > 0) {
                $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 ('Ticket Recall', 0, 'Ticket', 'recall', 'mail',\n                              " . $DB->result($result, 0, 0) . ", '', 1, 1,\n                              NOW());";
                $DB->queryOrDie($query, "0.80 insert notification");
            }
        }
    }
    if (!TableExists('glpi_slalevels')) {
        $query = "CREATE TABLE `glpi_slalevels` (\n                  `id` int(11) NOT NULL auto_increment,\n                  `name` varchar(255) collate utf8_unicode_ci default NULL,\n                  `slas_id` int(11) NOT NULL default '0',\n                  `execution_time` int(11) NOT NULL,\n                  `is_active` tinyint(1) NOT NULL default '1',\n                  PRIMARY KEY  (`id`),\n                  KEY `name` (`name`),\n                  KEY `is_active` (`is_active`),\n                  KEY `slas_id` (`slas_id`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.80 create glpi_slalevels");
    }
    if (!TableExists('glpi_slalevelactions')) {
        $query = "CREATE TABLE `glpi_slalevelactions` (\n                  `id` int(11) NOT NULL auto_increment,\n                  `slalevels_id` int(11) NOT NULL default '0',\n                  `action_type` varchar(255) collate utf8_unicode_ci default NULL,\n                  `field` varchar(255) collate utf8_unicode_ci default NULL,\n                  `value` varchar(255) collate utf8_unicode_ci default NULL,\n                  PRIMARY KEY  (`id`),\n                  KEY `slalevels_id` (`slalevels_id`)\n                ) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci ;";
        $DB->queryOrDie($query, "0.80 create glpi_slalevelactions");
    }
    $migration->addField("glpi_profiles", "calendar", "CHAR( 1 ) NULL", array('update' => "`entity_dropdown`"));
    $migration->addField("glpi_profiles", "sla", "CHAR( 1 ) NULL", array('update' => "`entity_rule_ticket`"));
    $migration->addField("glpi_tickets", "slas_id", "INT( 11 ) NOT NULL DEFAULT 0");
    $migration->addKey("glpi_tickets", "slas_id");
    $migration->addField("glpi_tickets", "slalevels_id", "INT( 11 ) NOT NULL DEFAULT 0");
    $migration->addKey("glpi_tickets", "slalevels_id");
    if ($migration->addField("glpi_tickets", "due_date", "datetime default NULL")) {
        $ADDTODISPLAYPREF['Ticket'] = array(18);
    }
    $migration->addKey("glpi_tickets", "due_date");
    $migration->addField("glpi_tickets", "begin_waiting_date", "datetime default NULL");
    $migration->addField("glpi_tickets", "sla_waiting_duration", "INT( 11 ) NOT NULL DEFAULT 0");
    if (!TableExists('glpi_slalevels_tickets')) {
        $query = "CREATE TABLE `glpi_slalevels_tickets` (\n                  `id` int(11) NOT NULL auto_increment,\n                  `tickets_id` int(11) NOT NULL default '0',\n                  `slalevels_id` int(11) NOT NULL default '0',\n                  `date` datetime default NULL,\n                  PRIMARY KEY  (`id`),\n                  KEY `tickets_id` (`tickets_id`),\n                  KEY `slalevels_id` (`slalevels_id`)\n                ) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci ;";
        $DB->queryOrDie($query, "0.80 create glpi_slalevels_tickets");
    }
    if (!countElementsInTable('glpi_crontasks', "`itemtype`='SlaLevel_Ticket' AND `name`='slaticket'")) {
        $query = "INSERT INTO `glpi_crontasks`\n                       (`itemtype`, `name`, `frequency`, `param`, `state`, `mode`, `allowmode`,\n                        `hourmin`, `hourmax`, `logs_lifetime`, `lastrun`, `lastcode`, `comment`)\n                VALUES ('SlaLevel_Ticket', 'slaticket', 300, NULL, 1, 1, 3,\n                        0, 24, 30, NULL, NULL, NULL)";
        $DB->queryOrDie($query, "0.80 populate glpi_crontasks for slaticket");
    }
    $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'PasswordForget'));
    // Updating schema
    $migration->addField("glpi_users", "token", "char( 40 ) NULL DEFAULT ''");
    $migration->addField("glpi_users", "tokendate", "datetime NULL DEFAULT NULL");
    $query = "SELECT *\n             FROM `glpi_notificationtemplates`\n             WHERE `name` = 'Password Forget'";
    if ($result = $DB->query($query)) {
        if ($DB->numrows($result) == 0) {
            $query = "INSERT INTO `glpi_notificationtemplates`\n                          (`name`, `itemtype`, `date_mod`)\n                   VALUES ('Password Forget', 'User', NOW())";
            $DB->queryOrDie($query, "0.80 add password forget notification");
            $notid = $DB->insert_id();
            $query = "INSERT INTO `glpi_notificationtemplatetranslations`\n                          (`notificationtemplates_id`, `language`, `subject`,\n                           `content_text`,\n                           `content_html`)\n                   VALUES ({$notid}, '', '##user.action##',\n                          '##user.realname## ##user.firstname##\n\n##lang.passwordforget.information##\n\n##lang.passwordforget.link## ##user.passwordforgeturl##',\n                          '&lt;p&gt;&lt;strong&gt;##user.realname## ##user.firstname##&lt;/strong&gt;&lt;/p&gt;\n&lt;p&gt;##lang.passwordforget.information##&lt;/p&gt;\n&lt;p&gt;##lang.passwordforget.link## &lt;a title=\"##user.passwordforgeturl##\" href=\"##user.passwordforgeturl##\"&gt;##user.passwordforgeturl##&lt;/a&gt;&lt;/p&gt;')";
            $DB->queryOrDie($query, "0.80 add password forget 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 ('Password Forget', 0, 'User', 'passwordforget', 'mail',\n                        {$notid}, '', 1, 1,\n                        NOW())";
            $DB->queryOrDie($query, "0.80 add password forget notification");
            $notifid = $DB->insert_id();
            $query = "INSERT INTO `glpi_notificationtargets`\n                       (`id`, `notifications_id`, `type`, `items_id`)\n                VALUES (NULL, {$notifid}, 1, 19);";
            $DB->queryOrDie($query, "0.80 add password forget notification target");
        }
    }
    $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'Ticket'));
    // Updating schema
    $migration->addField("glpi_tickets", "ticket_waiting_duration", "INT( 11 ) NOT NULL DEFAULT 0");
    $migration->addField("glpi_entitydatas", "calendars_id", "INT( 11 ) NOT NULL DEFAULT 0");
    $migration->addField("glpi_tickets", "close_delay_stat", "INT( 11 ) NOT NULL DEFAULT 0", array('update' => "(UNIX_TIMESTAMP(`glpi_tickets`.`closedate`)\n                                               - UNIX_TIMESTAMP(`glpi_tickets`.`date`))", 'condition' => " WHERE `glpi_tickets`.`status` = 'closed'\n                                                     AND `glpi_tickets`.`date` IS NOT NULL\n                                                     AND `glpi_tickets`.`closedate` IS NOT NULL\n                                                     AND `glpi_tickets`.`closedate` > `glpi_tickets`.`date`"));
    $migration->addField("glpi_tickets", "solve_delay_stat", "INT( 11 ) NOT NULL DEFAULT 0", array('update' => "(UNIX_TIMESTAMP(`glpi_tickets`.`solvedate`)\n                                               - UNIX_TIMESTAMP(`glpi_tickets`.`date`))", 'condition' => " WHERE (`glpi_tickets`.`status` = 'closed'\n                                                      OR `glpi_tickets`.`status` = 'solved')\n                                                    AND `glpi_tickets`.`date` IS NOT NULL\n                                                    AND `glpi_tickets`.`solvedate` IS NOT NULL\n                                                    AND `glpi_tickets`.`solvedate` > `glpi_tickets`.`date`"));
    if ($migration->addField("glpi_tickets", "takeintoaccount_delay_stat", "INT( 11 ) NOT NULL DEFAULT 0")) {
        $migration->migrationOneTable('glpi_tickets');
        // Manage stat computation for existing tickets
        // Solved tickets
        $query = "SELECT `glpi_tickets`.`id` AS ID,\n                       MIN(UNIX_TIMESTAMP(`glpi_tickets`.`solvedate`)\n                            - UNIX_TIMESTAMP(`glpi_tickets`.`date`)) AS OPEN,\n                       MIN(UNIX_TIMESTAMP(`glpi_ticketfollowups`.`date`)\n                            - UNIX_TIMESTAMP(`glpi_tickets`.`date`)) AS FIRST,\n                       MIN(UNIX_TIMESTAMP(`glpi_tickettasks`.`date`)\n                            - UNIX_TIMESTAMP(`glpi_tickets`.`date`)) AS FIRST2\n               FROM `glpi_tickets`\n               LEFT JOIN `glpi_ticketfollowups`\n                     ON (`glpi_ticketfollowups`.`tickets_id` = `glpi_tickets`.`id`)\n               LEFT JOIN `glpi_tickettasks`\n                     ON (`glpi_tickettasks`.`tickets_id` = `glpi_tickets`.`id`)\n               WHERE (`glpi_tickets`.`status` = 'closed'\n                      OR `glpi_tickets`.`status` = 'solved')\n                     AND `glpi_tickets`.`solvedate` IS NOT NULL\n               GROUP BY `glpi_tickets`.`id`";
        if ($result = $DB->query($query)) {
            if ($DB->numrows($result) > 0) {
                while ($data = $DB->fetch_assoc($result)) {
                    $firstactiontime = min($data['OPEN'], $data['FIRST'], $data['FIRST2']);
                    $firstactiontime = max(0, $firstactiontime);
                    $query2 = "UPDATE `glpi_tickets`\n                          SET `takeintoaccount_delay_stat` = '{$firstactiontime}'\n                          WHERE `id` = '" . $data['ID'] . "'";
                    $DB->queryOrDie($query2, "0.80 update takeintoaccount_delay_stat values for #" . $data['ID']);
                }
            }
        }
        // Not solved tickets
        $query = "SELECT `glpi_tickets`.`id` AS ID,\n                       MIN(UNIX_TIMESTAMP(`glpi_ticketfollowups`.`date`)\n                            - UNIX_TIMESTAMP(`glpi_tickets`.`date`)) AS FIRST,\n                       MIN(UNIX_TIMESTAMP(`glpi_tickettasks`.`date`)\n                            - UNIX_TIMESTAMP(`glpi_tickets`.`date`)) AS FIRST2\n                FROM `glpi_tickets`\n                LEFT JOIN `glpi_ticketfollowups`\n                     ON (`glpi_ticketfollowups`.`tickets_id` = `glpi_tickets`.`id`)\n                LEFT JOIN `glpi_tickettasks`\n                     ON (`glpi_tickettasks`.`tickets_id` = `glpi_tickets`.`id`)\n                WHERE (`glpi_tickets`.`status` <> 'closed'\n                       AND `glpi_tickets`.`status` <> 'solved')\n                      OR `glpi_tickets`.`solvedate` IS NULL\n                GROUP BY `glpi_tickets`.`id`";
        if ($result = $DB->query($query)) {
            if ($DB->numrows($result) > 0) {
                while ($data = $DB->fetch_assoc($result)) {
                    $firstactiontime = min($data['FIRST'], $data['FIRST2']);
                    $firstactiontime = max(0, $firstactiontime);
                    $query2 = "UPDATE `glpi_tickets`\n                          SET `takeintoaccount_delay_stat` = '{$firstactiontime}'\n                          WHERE `id` = '" . $data['ID'] . "'";
                    $DB->queryOrDie($query2, "0.80 update takeintoaccount_delay_stat values for #" . $data['ID']);
                }
            }
        }
    }
    // Put realtime in seconds
    $migration->addField("glpi_tickets", "actiontime", "INT( 11 ) NOT NULL DEFAULT 0", array('update' => "ROUND(realtime * 3600)"));
    $migration->dropField("glpi_tickets", "realtime");
    $migration->addField("glpi_tickettasks", "actiontime", "INT( 11 ) NOT NULL DEFAULT 0", array('update' => "ROUND(realtime * 3600)"));
    $migration->dropField("glpi_tickettasks", "realtime");
    $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'Software'));
    // Updating schema
    if ($migration->addField("glpi_softwareversions", "operatingsystems_id", "INT( 11 ) NOT NULL DEFAULT '0'")) {
        $migration->addKey("glpi_softwareversions", "operatingsystems_id");
        $migration->migrationOneTable('glpi_softwareversions');
        $query = "UPDATE `glpi_softwareversions`,\n                        (SELECT `id`, `operatingsystems_id`\n                         FROM `glpi_softwares`) AS SOFT\n                SET `glpi_softwareversions`.`operatingsystems_id` = `SOFT`.`operatingsystems_id`\n                WHERE `glpi_softwareversions`.`softwares_id` = `SOFT`.`id` ";
        $DB->queryOrDie($query, "0.80 transfer operatingsystems_id from glpi_softwares to glpi_softwareversions");
        $migration->dropField("glpi_softwares", "operatingsystems_id");
    }
    if (!isIndex("glpi_computers_softwareversions", "unicity")) {
        // clean datas
        $query = "SELECT `computers_id`,\n                       `softwareversions_id`,\n                       COUNT(*) AS CPT\n               FROM `glpi_computers_softwareversions`\n               GROUP BY `computers_id`, `softwareversions_id`\n               HAVING CPT > 1";
        if ($result = $DB->query($query)) {
            if ($DB->numrows($result)) {
                while ($data = $DB->fetch_assoc($result)) {
                    $query2 = "SELECT `id`\n                          FROM `glpi_computers_softwareversions`\n                          WHERE `computers_id` = '" . $data['computers_id'] . "'\n                                AND `softwareversions_id` = '" . $data['softwareversions_id'] . "'\n                          LIMIT 1";
                    if ($result2 = $DB->query($query2)) {
                        if ($DB->numrows($result2)) {
                            $keep_id = $DB->result($result2, 0, 0);
                            $query3 = "DELETE\n                                FROM `glpi_computers_softwareversions`\n                                WHERE `computers_id` = '" . $data['computers_id'] . "'\n                                      AND `softwareversions_id` = '" . $data['softwareversions_id'] . "'\n                                      AND `id` <> {$keep_id}";
                            $DB->queryOrDie($query3, "0.80 clean glpi_computers_softwareversions");
                        }
                    }
                }
            }
        }
        $migration->addKey("glpi_computers_softwareversions", array('computers_id', 'softwareversions_id'), 'unicity', "UNIQUE");
    }
    $migration->dropKey("glpi_computers_softwareversions", "computers_id");
    // For real count : copy template and deleted information
    $migration->addField("glpi_computers_softwareversions", "is_deleted", "tinyint(1) NOT NULL DEFAULT 0");
    // Gain de temps pour les beta-testeurs
    if ($migration->addField("glpi_computers_softwareversions", "is_template", "tinyint(1) NOT NULL DEFAULT 0")) {
        $migration->migrationOneTable('glpi_computers_softwareversions');
        // Update datas
        $query = "SELECT DISTINCT `computers_id`\n                FROM `glpi_computers_softwareversions`";
        if ($result = $DB->query($query)) {
            if ($DB->numrows($result)) {
                while ($data = $DB->fetch_assoc($result)) {
                    $comp = new Computer();
                    if ($comp->getFromDB($data['computers_id'])) {
                        $query = "UPDATE `glpi_computers_softwareversions`\n                            SET `is_template` = '" . $comp->getField('is_template') . "',\n                                `is_deleted` = '" . $comp->getField('is_deleted') . "'\n                            WHERE `computers_id` = '" . $data['computers_id'] . "';";
                        $DB->query($query);
                    }
                }
            }
        }
    }
    if (!TableExists("glpi_computers_softwarelicenses")) {
        $query = "CREATE TABLE `glpi_computers_softwarelicenses` (\n                  `id` int(11) NOT NULL auto_increment,\n                  `computers_id` int(11) NOT NULL default '0',\n                  `softwarelicenses_id` int(11) NOT NULL default '0',\n                  PRIMARY KEY  (`id`),\n                  KEY `computers_id` (`computers_id`),\n                  KEY `softwarelicenses_id` (`softwarelicenses_id`),\n                  UNIQUE `unicity` ( `computers_id` , `softwarelicenses_id` )\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.80 create glpi_computers_softwarelicenses");
    }
    if (FieldExists("glpi_softwarelicenses", "computers_id", false)) {
        $query = "SELECT *\n                FROM `glpi_softwarelicenses`\n                WHERE `computers_id` > 0\n                      AND `computers_id` IS NOT NULL";
        if ($result = $DB->query($query)) {
            if ($DB->numrows($result)) {
                while ($data = $DB->fetch_assoc($result)) {
                    $query = "INSERT INTO `glpi_computers_softwarelicenses`\n                                (`computers_id`, `softwarelicenses_id`)\n                         VALUES ('" . $data['computers_id'] . "','" . $data['id'] . "')";
                    $DB->queryOrDie($query, "0.80 migrate data to computers_softwarelicenses table");
                }
            }
        }
        $migration->dropField("glpi_softwarelicenses", "computers_id");
    }
    $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'Common'));
    // Updating schema
    $migration->addField("glpi_softwarelicenses", "date_mod", "DATETIME NULL");
    $migration->addKey("glpi_softwarelicenses", "date_mod");
    $migration->renameTable("glpi_cartridges_printermodels", "glpi_cartridgeitems_printermodels");
    $migration->addField("glpi_monitors", "have_hdmi", "tinyint(1) NOT NULL DEFAULT 0 AFTER `have_pivot`");
    $migration->addField("glpi_monitors", "have_displayport", "tinyint(1) NOT NULL DEFAULT 0 AFTER `have_hdmi`");
    $migration->dropField("glpi_configs", "dbreplicate_email");
    $migration->addField("glpi_configs", "auto_create_infocoms", "tinyint(1) NOT NULL DEFAULT 0");
    $migration->addField("glpi_configs", "csv_delimiter", "CHAR( 1 ) NOT NULL AFTER `number_format`", array('update' => "';'"));
    $migration->addField("glpi_users", "csv_delimiter", "CHAR( 1 ) NULL AFTER `number_format`");
    $migration->addField("glpi_users", "names_format", "INT( 11 ) NULL DEFAULT NULL AFTER `number_format`");
    // drop car fait sur mauvais champ
    $migration->dropKey("glpi_budgets", "end_date");
    $migration->migrationOneTable("glpi_budgets");
    $migration->addKey("glpi_budgets", "end_date");
    $migration->addField("glpi_authldaps", "is_active", "TINYINT( 1 ) NOT NULL DEFAULT '0'", array('update' => "'1'"));
    $ADDTODISPLAYPREF['AuthLdap'] = array(30);
    $migration->addField("glpi_authmails", "is_active", "TINYINT( 1 ) NOT NULL DEFAULT '0'", array('update' => "'1'"));
    $ADDTODISPLAYPREF['AuthMail'] = array(6);
    $migration->addField("glpi_ocsservers", "is_active", "TINYINT( 1 ) NOT NULL DEFAULT '0'", array('update' => "'1'"));
    $ADDTODISPLAYPREF['OcsServer'] = array(6);
    $migration->changeField("glpi_configs", "use_auto_assign_to_tech", "auto_assign_mode", "INT( 11 ) NOT NULL DEFAULT '1'");
    $migration->addField("glpi_entitydatas", "auto_assign_mode", "INT( 11 ) NOT NULL DEFAULT '-1'");
    $migration->changeField("glpi_entitydatas", "ldapservers_id", "authldaps_id", "INT( 11 ) NOT NULL DEFAULT '0'");
    $migration->addField("glpi_users", "user_dn", "TEXT DEFAULT NULL");
    $migration->addField("glpi_tickets", "users_id_lastupdater", "INT( 11 ) NOT NULL DEFAULT 0 AFTER `date_mod`");
    $migration->addKey("glpi_tickets", "users_id_lastupdater");
    $migration->addField("glpi_tickets", "type", "INT( 11 ) NOT NULL DEFAULT 1 AFTER `ticketcategories_id`");
    $migration->addKey("glpi_tickets", "type");
    $migration->addField("glpi_entitydatas", "tickettype", "INT( 11 ) NOT NULL DEFAULT 0");
    // Link between tickets
    if (!TableExists('glpi_tickets_tickets')) {
        $query = "CREATE TABLE `glpi_tickets_tickets` (\n                  `id` int(11) NOT NULL auto_increment,\n                  `tickets_id_1` int(11) NOT NULL default '0',\n                  `tickets_id_2` int(11) NOT NULL default '0',\n                  `link` int(11) NOT NULL default '1',\n                  PRIMARY KEY  (`id`),\n                  KEY `unicity` (`tickets_id_1`,`tickets_id_2`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.80 create glpi_tickets_tickets");
    }
    //inquest
    if (!TableExists('glpi_ticketsatisfactions')) {
        $query = "CREATE TABLE `glpi_ticketsatisfactions` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `tickets_id` int(11) NOT NULL DEFAULT '0',\n                  `type` int(11) NOT NULL DEFAULT '1',\n                  `date_begin` DATETIME NULL ,\n                  `date_answered` DATETIME NULL ,\n                  `satisfaction` INT(11) NULL ,\n                  `comment` text COLLATE utf8_unicode_ci,\n                  PRIMARY KEY (`id`),\n                  UNIQUE KEY `tickets_id` (`tickets_id`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.80 create glpi_ticketsatisfactions");
    }
    // config inquest by entity
    $migration->addField("glpi_entitydatas", "max_closedate", "DATETIME NULL");
    if (!countElementsInTable('glpi_crontasks', "`itemtype`='Ticket' AND `name`='createinquest'")) {
        $query = "INSERT INTO `glpi_crontasks`\n                       (`itemtype`, `name`, `frequency`, `param`, `state`, `mode`, `allowmode`,\n                        `hourmin`, `hourmax`, `logs_lifetime`, `lastrun`, `lastcode`, `comment`)\n                VALUES ('Ticket', 'createinquest', 86400, NULL, 1, 1, 3,\n                        0, 24, 30, NULL, NULL, NULL)";
        $DB->queryOrDie($query, "0.80 populate glpi_crontasks for ticketsatisfaction");
    }
    $migration->addField("glpi_entitydatas", "inquest_config", "INT(11) NOT NULL DEFAULT '0'");
    $migration->addField("glpi_entitydatas", "inquest_rate", "INT(11) NOT NULL DEFAULT '-1'");
    $migration->addField("glpi_entitydatas", "inquest_delay", "INT(11) NOT NULL DEFAULT '-1'");
    $migration->addField("glpi_entitydatas", "inquest_URL", "VARCHAR( 255 ) NULL");
    $migration->addField("glpi_networkports", "comment", "TEXT COLLATE utf8_unicode_ci");
    $migration->addField("glpi_profiles", "rule_dictionnary_printer", "CHAR( 1 ) NULL", array('update' => "`rule_dictionnary_software`"));
    $query = "SELECT *\n             FROM `glpi_notificationtemplates`\n             WHERE `name` = 'Ticket Satisfaction'";
    if ($result = $DB->query($query)) {
        if ($DB->numrows($result) == 0) {
            $query = "INSERT INTO `glpi_notificationtemplates`\n                          (`name`, `itemtype`, `date_mod`)\n                   VALUES ('Ticket Satisfaction', 'Ticket', NOW())";
            $DB->queryOrDie($query, "0.80 add ticket satisfaction notification");
            $notid = $DB->insert_id();
            $query = "INSERT INTO `glpi_notificationtemplatetranslations`\n                          (`notificationtemplates_id`, `language`, `subject`,\n                           `content_text`, `content_html`)\n                   VALUES ({$notid}, '', '##ticket.action## ##ticket.title##',\n                          '##lang.ticket.title## : ##ticket.title##\n\n##lang.ticket.closedate## : ##ticket.closedate##\n\n##lang.satisfaction.text## ##ticket.urlsatisfaction##',\n\n                          '&lt;p&gt;##lang.ticket.title## : ##ticket.title##&lt;/p&gt;\n&lt;p&gt;##lang.ticket.closedate## : ##ticket.closedate##&lt;/p&gt;\n&lt;p&gt;##lang.satisfaction.text## &lt;a href=\"##ticket.urlsatisfaction##\"&gt;##ticket.urlsatisfaction##&lt;/a&gt;&lt;/p&gt;')";
            $DB->queryOrDie($query, "0.80 add ticket satisfaction 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 ('Ticket Satisfaction', 0, 'Ticket', 'satisfaction', 'mail',\n                           {$notid}, '', 1, 1,\n                           NOW())";
            $DB->queryOrDie($query, "0.80 add ticket satisfaction notification");
            $notifid = $DB->insert_id();
            //          $query = "INSERT INTO `glpi_notificationtargets`
            //                           (`id`, `notifications_id`, `type`, `items_id`)
            //                    VALUES (NULL, $notifid, 1, 3)";
            //          $DB->queryOrDie($query, "0.80 add ticket satisfaction notification target");
        }
    }
    //New infocom dates
    $migration->addField("glpi_infocoms", "order_date", "DATE NULL");
    $migration->addField("glpi_infocoms", "delivery_date", "DATE NULL");
    $migration->addField("glpi_infocoms", "inventory_date", "DATE NULL");
    $migration->addField("glpi_infocoms", "warranty_date", "DATE NULL", array('update' => "`buy_date`"));
    if (!TableExists('glpi_rulecacheprinters')) {
        $query = "CREATE TABLE `glpi_rulecacheprinters` (\n                    `id` int(11) NOT NULL AUTO_INCREMENT,\n                    `old_value` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n                    `manufacturer` varchar(255) COLLATE utf8_unicode_ci NOT NULL,\n                    `rules_id` int(11) NOT NULL DEFAULT '0',\n                    `new_value` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n                    `new_manufacturer` varchar(255) COLLATE utf8_unicode_ci NOT NULL,\n                    `ignore_ocs_import` char(1) COLLATE utf8_unicode_ci DEFAULT NULL,\n                    `is_global` char(1) COLLATE utf8_unicode_ci DEFAULT NULL,\n                    PRIMARY KEY (`id`),\n                    KEY `old_value` (`old_value`),\n                    KEY `rules_id` (`rules_id`)\n                  ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.80 add table glpi_rulecacheprinters");
    }
    $migration->addField("glpi_configs", "use_slave_for_search", "tinyint( 1 ) NOT NULL DEFAULT '0'");
    $migration->addField("glpi_configs", "admin_email_name", "varchar( 255 ) collate utf8_unicode_ci default NULL AFTER `admin_email`");
    $migration->addField("glpi_configs", "admin_reply_name", "varchar( 255 ) collate utf8_unicode_ci default NULL AFTER `admin_reply`");
    $migration->addField("glpi_entitydatas", "admin_email_name", "varchar( 255 ) collate utf8_unicode_ci default NULL AFTER `admin_email`");
    $migration->addField("glpi_entitydatas", "admin_reply_name", "varchar( 255 ) collate utf8_unicode_ci default NULL AFTER `admin_reply`");
    $migration->addField("glpi_notificationtemplates", "css", "text COLLATE utf8_unicode_ci");
    $migration->addField("glpi_configs", "url_maxlength", "int(11) NOT NULL DEFAULT '30' AFTER `list_limit_max`");
    $migration->displayMessage(sprintf(__('Data migration - %s'), 'Multi user group for tickets'));
    if (!TableExists('glpi_groups_tickets')) {
        $query = "CREATE TABLE `glpi_groups_tickets` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `tickets_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                  KEY `unicity` (`tickets_id`,`type`,`groups_id`),\n                  KEY `group` (`groups_id`,`type`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.80 add table glpi_groups_tickets");
        $query = "SELECT `id`, `groups_id`, `groups_id_assign`\n                FROM `glpi_tickets`";
        if ($result = $DB->query($query)) {
            if ($DB->numrows($result)) {
                while ($data = $DB->fetch_assoc($result)) {
                    if ($data['groups_id'] > 0) {
                        $query = "INSERT INTO `glpi_groups_tickets`\n                                   (`tickets_id`, `groups_id`,\n                                    `type`)\n                            VALUES ('" . $data['id'] . "', '" . $data['groups_id'] . "',\n                                    '" . CommonITILActor::REQUESTER . "')";
                        $DB->queryOrDie($query, "0.80 migrate data to glpi_groups_tickets table");
                    }
                    if ($data['groups_id_assign'] > 0) {
                        $query = "INSERT INTO `glpi_groups_tickets`\n                                  (`tickets_id`, `groups_id`,\n                                   `type`)\n                           VALUES ('" . $data['id'] . "', '" . $data['groups_id_assign'] . "',\n                                   '" . CommonITILActor::ASSIGN . "')";
                        $DB->queryOrDie($query, "0.80 migrate data to glpi_groups_tickets table");
                    }
                }
            }
        }
        $migration->dropField('glpi_tickets', 'groups_id');
        $migration->dropField('glpi_tickets', 'groups_id_assign');
        // Migrate templates
        $from = array('ticket.group##', 'ticket.assigntogroup##', 'ticket.assigntouser##', 'ticket.author.name##', 'ticket.author##');
        $to = array('ticket.groups##', 'ticket.assigntogroups##', 'ticket.assigntousers##', 'ticket.authors##', 'author.id##');
        $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.80 fix tags usage for multi users");
                }
            }
        }
    }
    if (!TableExists('glpi_tickets_users')) {
        $query = "CREATE TABLE `glpi_tickets_users` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `tickets_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                  KEY `tickets_id` (`tickets_id`),\n                  KEY `user` (`users_id`,`type`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.80 add table glpi_tickets_users");
        $query = "SELECT `glpi_tickets`.`id`,\n                       `glpi_tickets`.`users_id_assign`,\n                       `glpi_tickets`.`users_id`,\n                       `glpi_tickets`.`use_email_notification`,\n                       `glpi_tickets`.`user_email`,\n                       `glpi_users`.`email` AS EMAIL\n                FROM `glpi_tickets`\n                LEFT JOIN `glpi_users` ON (`glpi_users`.`id` = `glpi_tickets`.`users_id`)";
        if ($result = $DB->query($query)) {
            if ($DB->numrows($result)) {
                while ($data = $DB->fetch_assoc($result)) {
                    if ($data['users_id_assign'] > 0) {
                        $query = "INSERT INTO `glpi_tickets_users`\n                                   (`tickets_id`, `users_id`,\n                                    `type`, `use_notification`)\n                            VALUES ('" . $data['id'] . "', '" . $data['users_id_assign'] . "',\n                                    '" . CommonITILActor::ASSIGN . "', '1')";
                        $DB->queryOrDie($query, "0.80 migrate data to glpi_tickets_users table");
                    }
                    if ($data['users_id'] > 0 || $data['use_email_notification'] && !empty($data['user_email'])) {
                        $user_id = 0;
                        if ($data['users_id'] > 0) {
                            $user_id = $data['users_id'];
                        }
                        $user_email = '';
                        if (strcasecmp($data['user_email'], $data['EMAIL']) != 0) {
                            $user_email = addslashes($data['user_email']);
                        }
                        $query = "INSERT INTO `glpi_tickets_users`\n                                   (`tickets_id`, `users_id`,`type`,\n                                    `use_notification`, `alternative_email`)\n                            VALUES ('" . $data['id'] . "', '{$user_id}', '" . CommonITILActor::REQUESTER . "',\n                                    '" . $data['use_email_notification'] . "', '{$user_email}')";
                        $DB->queryOrDie($query, "0.80 migrate data to glpi_tickets_users table");
                    }
                }
            }
        }
        $migration->dropField('glpi_tickets', 'users_id');
        $migration->dropField('glpi_tickets', 'users_id_assign');
        $migration->dropField('glpi_tickets', 'use_email_notification');
        $migration->dropField('glpi_tickets', 'user_email');
        // ADD observer when requester is set : 3>21 / 13>20 / 12 >22
        $fromto = array(3 => 21, 13 => 20, 12 => 22);
        // GROUP_SUPERVISOR
        foreach ($fromto as $from => $to) {
            $query = "SELECT *\n                   FROM `glpi_notificationtargets`\n                   INNER JOIN `glpi_notifications`\n                     ON (`glpi_notifications`.`id` = `glpi_notificationtargets`.`notifications_id`)\n                   WHERE `glpi_notifications`.`itemtype` = 'Ticket'\n                         AND `glpi_notificationtargets`.`type` = '1'\n                         AND `glpi_notificationtargets`.`items_id` = '{$from}'";
            if ($result = $DB->query($query)) {
                if ($DB->numrows($result)) {
                    while ($data = $DB->fetch_assoc($result)) {
                        $query = "INSERT INTO `glpi_notificationtargets`\n                                   (`items_id` ,`type` ,`notifications_id`)\n                            VALUES ('{$to}', '1', '" . $data['notifications_id'] . "')";
                        $DB->queryOrDie($query, "0.80 insert default notif for observer");
                    }
                }
            }
        }
    }
    $migration->displayMessage(sprintf(__('Data migration - %s'), 'passwords encryption'));
    if ($migration->addField('glpi_configs', 'proxy_passwd', 'varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL')) {
        $migration->migrationOneTable('glpi_configs');
        $query = "SELECT `proxy_password`\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 (!empty($value)) {
                    $query = "UPDATE `glpi_configs`\n                         SET `proxy_passwd` = '" . addslashes(Toolbox::encrypt($value, GLPIKEY)) . "'\n                         WHERE `id` = '1' ";
                    $DB->queryOrDie($query, "0.80 update proxy_passwd in glpi_configs");
                }
            }
        }
        $migration->dropField('glpi_configs', 'proxy_password');
    }
    if ($migration->addField('glpi_configs', 'smtp_passwd', 'varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL')) {
        $migration->migrationOneTable('glpi_configs');
        $query = "SELECT `smtp_password`\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 (!empty($value)) {
                    $query = "UPDATE `glpi_configs`\n                         SET `smtp_passwd` = '" . addslashes(Toolbox::encrypt($value, GLPIKEY)) . "'\n                         WHERE `id` = '1' ";
                    $DB->queryOrDie($query, "0.80 update smtp_passwd in glpi_configs");
                }
            }
        }
        $migration->dropField('glpi_configs', 'smtp_password');
    }
    if ($migration->addField('glpi_authldaps', 'rootdn_passwd', 'varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL')) {
        $migration->migrationOneTable('glpi_authldaps');
        $query = "SELECT *\n                FROM `glpi_authldaps`\n                WHERE `rootdn_password` IS NOT NULL\n                      AND `rootdn_password` <> ''";
        if ($result = $DB->query($query)) {
            if ($DB->numrows($result)) {
                while ($data = $DB->fetch_assoc($result)) {
                    if (!empty($data['rootdn_password'])) {
                        $query = "UPDATE `glpi_authldaps`\n                            SET `rootdn_passwd` = '" . addslashes(Toolbox::encrypt($data['rootdn_password'], GLPIKEY)) . "'\n                            WHERE `id` = '" . $data['id'] . "' ";
                        $DB->queryOrDie($query, "0.80 update rootdn_passwd in glpi_authldaps");
                    }
                }
            }
        }
        $migration->dropField('glpi_authldaps', 'rootdn_password');
    }
    //Add date config management fields
    $migration->addField("glpi_entitydatas", "autofill_warranty_date", "varchar(255) COLLATE utf8_unicode_ci DEFAULT '-1'", array('update' => "'0'", 'condition' => " WHERE `entities_id` = '0'"));
    $migration->addField("glpi_entitydatas", "autofill_use_date", "varchar(255) COLLATE utf8_unicode_ci DEFAULT '-1'", array('update' => "'0'", 'condition' => " WHERE `entities_id` = '0'"));
    $migration->addField("glpi_entitydatas", "autofill_buy_date", "varchar(255) COLLATE utf8_unicode_ci DEFAULT '-1'", array('update' => "'0'", 'condition' => " WHERE `entities_id` = '0'"));
    $migration->addField("glpi_entitydatas", "autofill_delivery_date", "varchar(255) COLLATE utf8_unicode_ci DEFAULT '-1'", array('update' => "'0'", 'condition' => " WHERE `entities_id` = '0'"));
    $migration->addField("glpi_entitydatas", "autofill_order_date", "varchar(255) COLLATE utf8_unicode_ci DEFAULT '-1'", array('update' => "'0'", 'condition' => " WHERE `entities_id` = '0'"));
    if (!TableExists('glpi_fieldunicities')) {
        $query = "CREATE TABLE `glpi_fieldunicities` (\n                  `id` INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY ,\n                  `name` VARCHAR( 255 ) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',\n                  `is_recursive` TINYINT( 1 ) NOT NULL DEFAULT '0',\n                  `itemtype` VARCHAR( 255 ) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',\n                  `entities_id` INT( 11 ) NOT NULL DEFAULT  '-1',\n                  `fields` VARCHAR( 255 ) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',\n                  `is_active` TINYINT( 1 ) NOT NULL DEFAULT '0',\n                  `action_refuse` TINYINT( 1 ) NOT NULL DEFAULT '0',\n                  `action_notify` TINYINT( 1 ) NOT NULL DEFAULT '0',\n                  `comment` text COLLATE utf8_unicode_ci\n                ) ENGINE=MYISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci\n                  COMMENT = 'Stores field unicity criterias'";
        $DB->queryOrDie($query, "0.80 add table glpi_fieldunicities");
        $ADDTODISPLAYPREF['FieldUnicity'] = array(1, 80, 4, 3, 86, 30);
    }
    $query = "SELECT *\n             FROM `glpi_notificationtemplates`\n             WHERE `name` = 'Item not unique'";
    if ($result = $DB->query($query)) {
        if ($DB->numrows($result) == 0) {
            $query = "INSERT INTO `glpi_notificationtemplates`\n                          (`name`, `itemtype`, `date_mod`)\n                   VALUES ('Item not unique', 'FieldUnicity', NOW())";
            $DB->queryOrDie($query, "0.80 add item not unique notification");
            $notid = $DB->insert_id();
            $query = "INSERT INTO `glpi_notificationtemplatetranslations` " . "VALUES(NULL, {$notid}, '', '##lang.unicity.action##', " . "'##lang.unicity.entity## : ##unicity.entity## \r\n\n" . "##lang.unicity.itemtype## : ##unicity.itemtype## \r\n\n" . "##lang.unicity.message## : ##unicity.message## \r\n\n" . "##lang.unicity.action_user## : ##unicity.action_user## \r\n\n" . "##lang.unicity.action_type## : ##unicity.action_type## \r\n\n" . "##lang.unicity.date## : ##unicity.date##'," . "'&lt;p&gt;##lang.unicity.entity## : ##unicity.entity##&lt;/p&gt;\r\n&lt;p&gt;" . "##lang.unicity.itemtype## : ##unicity.itemtype##&lt;/p&gt;\r\n&lt;p&gt;" . "##lang.unicity.message## : ##unicity.message##&lt;/p&gt;\r\n&lt;p&gt;" . "##lang.unicity.action_user## : ##unicity.action_user##&lt;/p&gt;\r\n&lt;p&gt;" . "##lang.unicity.action_type## : ##unicity.action_type##&lt;/p&gt;\r\n&lt;p&gt;" . "##lang.unicity.date## : ##unicity.date##&lt;/p&gt;');";
            $DB->queryOrDie($query, "0.80 add item not unique 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 ('Item not unique', 0, 'FieldUnicity', 'refuse', 'mail',\n                        {$notid}, '', 1, 1,\n                        NOW())";
            $DB->queryOrDie($query, "0.80 add computer not unique notification");
            $notifid = $DB->insert_id();
            //       $query = "INSERT INTO `glpi_notificationtargets`
            //                        (`notifications_id`, `type`, `items_id`)
            //                 VALUES ($notifid, 1, 19);";
            //       $DB->queryOrDie($query, "0.80 add computer not unique notification target");
        }
    }
    if (!TableExists("glpi_fieldblacklists")) {
        $query = "CREATE TABLE `glpi_fieldblacklists` (\n                  `id` INT (11) NOT NULL AUTO_INCREMENT,\n                  `name` VARCHAR (255) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',\n                  `field` VARCHAR (255) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',\n                  `value` VARCHAR (255) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',\n                  `itemtype` VARCHAR (255) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',\n                  `entities_id` INT (11) NOT NULL DEFAULT '0',\n                  `is_recursive` TINYINT (1) NOT NULL DEFAULT '0',\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.80 add table glpi_fieldblacklists");
    }
    if ($migration->addField('glpi_mailcollectors', 'passwd', 'varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL')) {
        $migration->migrationOneTable('glpi_mailcollectors');
        $query = "SELECT *\n                FROM `glpi_mailcollectors`\n                WHERE `password` IS NOT NULL\n                      AND `password` <> ''";
        if ($result = $DB->query($query)) {
            if ($DB->numrows($result)) {
                while ($data = $DB->fetch_assoc($result)) {
                    if (!empty($data['password'])) {
                        $query = "UPDATE `glpi_mailcollectors`\n                            SET `passwd` = '" . addslashes(Toolbox::encrypt($data['password'], GLPIKEY)) . "'\n                            WHERE `id`= '" . $data['id'] . "' ";
                        $DB->queryOrDie($query, "0.80 update passwd in glpi_mailcollectors");
                    }
                }
            }
        }
        $migration->dropField('glpi_mailcollectors', 'password');
    }
    $migration->displayMessage(sprintf(__('Data migration - %s'), 'rule ticket migration'));
    $changes['RuleTicket'] = array('users_id' => '_users_id_requester', 'groups_id' => '_groups_id_requester', 'users_id_assign' => '_users_id_assign', 'groups_id_assign' => '_groups_id_assign');
    // For Rule::RULE_TRACKING_AUTO_ACTION
    $changes['RuleMailCollector'] = array('username' => '_users_id_requester');
    $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.80 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.80 update datas for rules criterias");
                }
            }
        }
    }
    // Add watcher crontask
    if (!countElementsInTable('glpi_crontasks', "`itemtype`='Crontask' AND `name`='watcher'")) {
        $query = "INSERT INTO `glpi_crontasks`\n                       (`itemtype`, `name`, `frequency`, `param`, `state`, `mode`, `allowmode`,\n                        `hourmin`, `hourmax`, `logs_lifetime`, `lastrun`, `lastcode`, `comment`)\n                VALUES ('Crontask', 'watcher', 86400, NULL, 1, 1, 3,\n                         0, 24, 30, NULL, NULL, NULL);";
        $DB->queryOrDie($query, "0.80 populate glpi_crontasks for watcher");
    }
    $query = "SELECT *\n             FROM `glpi_notificationtemplates`\n             WHERE `name` = 'Crontask'";
    if ($result = $DB->query($query)) {
        if ($DB->numrows($result) == 0) {
            $query = "INSERT INTO `glpi_notificationtemplates`\n                          (`name`, `itemtype`, `date_mod`)\n                   VALUES ('Crontask', 'Crontask', NOW())";
            $DB->queryOrDie($query, "0.80 add crontask watcher notification");
            $notid = $DB->insert_id();
            $query = "INSERT INTO `glpi_notificationtemplatetranslations`\n                   VALUES (NULL, {$notid}, '', '##crontask.action##',\n                           '##lang.crontask.warning## \r\n\n##FOREACHcrontasks## \n ##crontask.name## : ##crontask.description##\n \n##ENDFOREACHcrontasks##', '&lt;p&gt;##lang.crontask.warning##&lt;/p&gt;\r\n&lt;p&gt;##FOREACHcrontasks## &lt;br /&gt;&lt;a href=\"##crontask.url##\"&gt;##crontask.name##&lt;/a&gt; : ##crontask.description##&lt;br /&gt; &lt;br /&gt;##ENDFOREACHcrontasks##&lt;/p&gt;')";
            $DB->queryOrDie($query, "0.80 add crontask notification translation");
            $query = "INSERT INTO `glpi_notifications`\n                VALUES (NULL, 'Crontask Watcher', 0, 'Crontask', 'alert', 'mail', {$notid}, '', 1, 1,\n                        NOW())";
            $DB->queryOrDie($query, "0.80 add crontask notification");
            $notifid = $DB->insert_id();
            $query = "INSERT INTO `glpi_notificationtargets`\n                       (`id`, `notifications_id`, `type`, `items_id`)\n                VALUES (NULL, {$notifid}, 1, 1)";
            $DB->queryOrDie($query, "0.80 add crontask notification target to global admin");
        }
    }
    /* OCS-NG new clean links features */
    if ($migration->addField('glpi_ocslinks', 'entities_id', 'int(11) NOT NULL DEFAULT \'0\'')) {
        $migration->migrationOneTable("glpi_ocslinks");
        $query = "SELECT `glpi_ocslinks`.`computers_id`, `glpi_computers`.`entities_id`\n                FROM `glpi_ocslinks`\n                INNER JOIN `glpi_computers`\n                  ON (`glpi_computers`.`id` = `glpi_ocslinks`.`computers_id`)";
        if ($result = $DB->query($query)) {
            if ($DB->numrows($result)) {
                while ($data = $DB->fetch_assoc($result)) {
                    $query = "UPDATE `glpi_ocslinks`\n                         SET `entities_id` = '" . $data['entities_id'] . "'\n                         WHERE `computers_id` = '" . $data['computers_id'] . "'";
                    $DB->queryOrDie($query, "0.80 copy entities_id from computers to ocslinks ");
                }
            }
        }
    }
    $migration->addField("glpi_profiles", "clean_ocsng", "char(1) COLLATE utf8_unicode_ci DEFAULT NULL", array('update' => "`sync_ocsng`"));
    /* END - OCS-NG new clean links features */
    $migration->addField("glpi_transfers", "keep_disk", "int( 11 ) NOT NULL DEFAULT 0", array('update' => "'1'"));
    if ($migration->addField("glpi_reminders", "is_helpdesk_visible", "tinyint( 1 ) NOT NULL DEFAULT 0")) {
        $query = "UPDATE `glpi_profiles`\n                SET `reminder_public` = 'r'\n                WHERE `interface` = 'helpdesk';";
        $DB->queryOrDie($query, "0.80 default set of reminder view for helpdesk users");
    }
    if (!TableExists('glpi_ticketsolutiontemplates')) {
        $query = "CREATE TABLE `glpi_ticketsolutiontemplates` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `entities_id` int(11) NOT NULL DEFAULT '0',\n                  `is_recursive` tinyint(1) NOT NULL DEFAULT '0',\n                  `name` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n                  `content` text COLLATE utf8_unicode_ci,\n                  `ticketsolutiontypes_id` int(11) NOT NULL DEFAULT '0',\n                  `comment` text COLLATE utf8_unicode_ci,\n                  PRIMARY KEY (`id`),\n                  UNIQUE KEY `unicity` (`entities_id`,`name`),\n                  KEY `name` (`name`),\n                  KEY `is_recursive` (`is_recursive`)\n                  ) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.80 create glpi_ticketsolutiontemplates");
    }
    // Fix templates tags
    $updates = array('Ticket' => array('from' => array('##lang.validation.validationstatus##'), 'to' => array('##lang.validation.status## : ##validation.status##')));
    foreach ($updates as $itemtype => $changes) {
        $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` = '{$itemtype}'";
        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($changes['from'], $changes['to'], $data['subject'])) . "',\n                              `content_text` = '" . addslashes(str_replace($changes['from'], $changes['to'], $data['content_text'])) . "',\n                              `content_html` = '" . addslashes(str_replace($changes['from'], $changes['to'], $data['content_html'])) . "'\n                           WHERE `id` = '" . $data['id'] . "'";
                    $DB->queryOrDie($query, "0.80 fix template tag usage for {$itemtype}");
                }
            }
        }
    }
    $migration->addField('glpi_profiles', 'update_own_followups', 'char(1) COLLATE utf8_unicode_ci DEFAULT NULL', array('update' => '1', 'condition' => " WHERE `update_followups` = 1"));
    $migration->addField('glpi_profiles', 'delete_followups', 'char(1) COLLATE utf8_unicode_ci DEFAULT NULL', array('update' => '`update_followups`'));
    $migration->addField('glpi_ocsservers', 'deleted_behavior', "VARCHAR( 255 ) NOT NULL DEFAULT '1'");
    //User registration number
    $migration->addField('glpi_users', 'registration_number', 'VARCHAR( 255 ) COLLATE utf8_unicode_ci DEFAULT NULL');
    $migration->addField('glpi_authldaps', 'registration_number_field', 'VARCHAR( 255 ) COLLATE utf8_unicode_ci DEFAULT NULL');
    $migration->addField("glpi_users", "date_sync", "datetime default NULL AFTER `date_mod`", array('update' => "`date_mod`", 'condition' => " WHERE `auths_id` > 0"));
    //Migrate OCS computers link from static config to rules engine
    if (FieldExists('glpi_ocsservers', 'is_glpi_link_enabled', false)) {
        $ocs_servers = getAllDatasFromTable('glpi_ocsservers');
        $ranking = 1;
        foreach ($ocs_servers as $ocs_server) {
            if ($ocs_server['is_glpi_link_enabled']) {
                $query = "INSERT INTO `glpi_rules`\n                             (`entities_id`, `sub_type`, `ranking`, `name`,\n                              `description`, `match`, `is_active`, `date_mod`, `is_recursive`)\n                      VALUES ('0', 'RuleImportComputer', '{$ranking}', '" . $ocs_server['name'] . "',\n                              '', 'AND', 1, NOW(), 1)";
                $DB->queryOrDie($query, "0.80 add new rule RuleImportComputer");
                $rule_id = $DB->insert_id();
                $query = "INSERT INTO `glpi_rulecriterias`\n                             (`rules_id`, `criteria`, `condition`, `pattern`)\n                      VALUES ('{$rule_id}', 'ocsservers_id', '0', '" . $ocs_server['id'] . "')";
                $DB->queryOrDie($query, "0.80 add new criteria RuleImportComputer");
                if ($ocs_server['states_id_linkif']) {
                    $query = "INSERT INTO `glpi_rulecriterias`\n                                (`rules_id`, `criteria`, `condition`,\n                                 `pattern`)\n                         VALUES ('{$rule_id}', 'states_id', '0',\n                                 '" . $ocs_server['states_id_linkif'] . "')";
                    $DB->queryOrDie($query, "0.80 add new criteria RuleImportComputer");
                }
                $simple_criteria = array('use_ip_to_link' => 'IPADDRESS', 'use_mac_to_link' => 'MACADDRESS', 'use_serial_to_link' => 'serial');
                foreach ($simple_criteria as $field => $value) {
                    $tmpcriteria = array();
                    if ($ocs_server[$field]) {
                        $query = "INSERT INTO `glpi_rulecriterias`\n                                   (`rules_id`, `criteria`, `condition`, `pattern`)\n                            VALUES ('{$rule_id}', '{$value}', '10', '1')";
                        $DB->queryOrDie($query, "0.80 add new criteria RuleImportComputer");
                    }
                }
                $tmpcriteria = array();
                $query = "INSERT INTO `glpi_rulecriterias`\n                             (`rules_id`, `criteria`, `condition`, `pattern`)";
                switch ($ocs_server['use_name_to_link']) {
                    case 1:
                        $query .= "VALUES ('{$rule_id}', 'name', '10', '1')";
                        $DB->query($query);
                        break;
                    case 2:
                        $query .= "VALUES ('{$rule_id}', 'name', '30', '1')";
                        $DB->query($query);
                        break;
                }
                $query = "INSERT INTO `glpi_ruleactions`\n                             (`rules_id`, `action_type`, `field`, `value`)\n                      VALUES ('{$rule_id}', 'assign', '_fusion', '0')";
                $DB->queryOrDie($query, "0.80 add new action RuleImportComputer");
                $ranking++;
            }
        }
        $todrop = array('is_glpi_link_enabled', 'states_id_linkif', 'use_ip_to_link', 'use_mac_to_link', 'use_name_to_link', 'use_serial_to_link');
        foreach ($todrop as $field) {
            $migration->dropField('glpi_ocsservers', $field);
        }
    }
    /* New automatic transfert feature */
    $migration->addField('glpi_configs', 'transfers_id_auto', 'int(11) NOT NULL DEFAULT 0');
    $migration->addField('glpi_ocslinks', 'tag', 'varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL');
    /* END - New automatic transfert feature */
    $migration->addField('glpi_profiles', 'entity_helpdesk', 'char(1) COLLATE utf8_unicode_ci DEFAULT NULL', array('update' => '`notification`'));
    $migration->addField('glpi_computers', 'uuid', 'varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL');
    $migration->addField('glpi_ocsservers', 'import_vms', 'TINYINT(1) NOT NULL DEFAULT 0');
    $migration->addField('glpi_ocsservers', 'import_general_uuid', 'TINYINT(1) NOT NULL DEFAULT 0');
    $migration->addField('glpi_ocslinks', 'import_vm', 'LONGTEXT COLLATE utf8_unicode_ci DEFAULT NULL');
    if (!TableExists('glpi_virtualmachinetypes')) {
        $query = "CREATE TABLE `glpi_virtualmachinetypes` (\n                  `id` INT(11) NOT NULL AUTO_INCREMENT,\n                  `name` VARCHAR(255) NOT NULL DEFAULT '',\n                  `comment` TEXT NOT NULL,\n                  PRIMARY KEY (`id`)\n                  ) ENGINE = MYISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.80 add new table glpi_virtualmachinetypes");
    }
    if (!TableExists('glpi_virtualmachinesystems')) {
        $query = "CREATE TABLE `glpi_virtualmachinesystems` (\n                  `id` INT(11) NOT NULL AUTO_INCREMENT,\n                  `name` VARCHAR(255) NOT NULL DEFAULT '',\n                  `comment` TEXT NOT NULL,\n                  PRIMARY KEY (`id`)\n                  ) ENGINE = MYISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.80 add new table glpi_virtualmachinesystems");
    }
    if (!TableExists('glpi_virtualmachinestates')) {
        $query = "CREATE TABLE `glpi_virtualmachinestates` (\n                  `id` INT(11) NOT NULL AUTO_INCREMENT,\n                  `name` VARCHAR(255) NOT NULL DEFAULT '',\n                  `comment` TEXT NOT NULL,\n                  PRIMARY KEY (`id`)\n                  ) ENGINE = MYISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.80 add new table glpi_virtualmachinestates");
    }
    if (!TableExists('glpi_computervirtualmachines')) {
        $query = "CREATE TABLE `glpi_computervirtualmachines` (\n                  `id` INT NOT NULL AUTO_INCREMENT,\n                  `entities_id` INT(11) NOT NULL DEFAULT '0',\n                  `computers_id` INT(11) NOT NULL DEFAULT '0',\n                  `name` VARCHAR(255) NOT NULL DEFAULT '',\n                  `virtualmachinestates_id` INT(11) NOT NULL DEFAULT '0',\n                  `virtualmachinesystems_id` INT(11) NOT NULL DEFAULT '0',\n                  `virtualmachinetypes_id` INT(11) NOT NULL DEFAULT '0',\n                  `uuid` VARCHAR(255) NOT NULL DEFAULT '',\n                  `vcpu` INT(11) NOT NULL DEFAULT '0',\n                  `ram` VARCHAR(255) NOT NULL DEFAULT '',\n                  PRIMARY KEY (`id`)\n                  ) ENGINE = MYISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.80 add new table glpi_computervirtualmachines");
    }
    // Clean ticket validations
    $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.80 clean glpi_ticketvalidations");
    // Keep it at the end
    $migration->displayMessage(sprintf(__('Data migration - %s'), 'glpi_displaypreferences'));
    foreach ($ADDTODISPLAYPREF as $type => $tab) {
        $query = "SELECT DISTINCT users_id\n                FROM `glpi_displaypreferences`\n                WHERE `itemtype` = '{$type}'";
        if ($result = $DB->query($query)) {
            if ($DB->numrows($result) > 0) {
                while ($data = $DB->fetch_assoc($result)) {
                    $query = "SELECT MAX(`rank`)\n                         FROM `glpi_displaypreferences`\n                         WHERE `users_id` = '" . $data['users_id'] . "'\n                               AND `itemtype` = '{$type}'";
                    $result = $DB->query($query);
                    $rank = $DB->result($result, 0, 0);
                    $rank++;
                    foreach ($tab as $newval) {
                        $query = "SELECT *\n                            FROM `glpi_displaypreferences`\n                            WHERE `users_id` = '" . $data['users_id'] . "'\n                                  AND `num` = '{$newval}'\n                                  AND `itemtype` = '{$type}'";
                        if ($result2 = $DB->query($query)) {
                            if ($DB->numrows($result2) == 0) {
                                $query = "INSERT INTO `glpi_displaypreferences`\n                                        (`itemtype` ,`num` ,`rank` ,`users_id`)\n                                 VALUES ('{$type}', '{$newval}', '" . $rank++ . "',\n                                         '" . $data['users_id'] . "')";
                                $DB->query($query);
                            }
                        }
                    }
                }
            } else {
                // Add for default user
                $rank = 1;
                foreach ($tab as $newval) {
                    $query = "INSERT INTO `glpi_displaypreferences`\n                               (`itemtype` ,`num` ,`rank` ,`users_id`)\n                        VALUES ('{$type}', '{$newval}', '" . $rank++ . "', '0')";
                    $DB->query($query);
                }
            }
        }
    }
    // Change value of autoclose ticket
    $query = "UPDATE `glpi_configs`\n             SET `autoclose_delay` = '-1'\n             WHERE `id` = '1'\n                   AND `autoclose_delay` = '0'";
    $DB->queryOrDie($query, "0.80 change autoclose ticket in glpi_configs");
    $query = "UPDATE `glpi_entitydatas`\n             SET `autoclose_delay` = '-2'\n             WHERE `autoclose_delay` = '-1'";
    $DB->queryOrDie($query, "0.80 change autoclose ticket in glpi_entitydatas for inherit");
    $query = "UPDATE `glpi_entitydatas`\n             SET `autoclose_delay` = '-1'\n             WHERE `autoclose_delay` = '0'";
    $DB->queryOrDie($query, "0.80 change autoclose ticket in glpi_entitydatas for inactive");
    // must always be at the end
    $migration->executeMigration();
    return $updateresult;
}
Example #13
0
function update07to071()
{
    global $DB, $CFG_GLPI, $LANG;
    if (!FieldExists("glpi_profiles", "rule_dictionnary_software")) {
        $query = "ALTER TABLE `glpi_profiles` ADD `rule_dictionnary_software` VARCHAR( 1 ) NULL DEFAULT NULL;";
        $DB->query($query) or die("0.71 add rule_dictionnary_software in glpi_profiles if not present for compatibility " . $LANG['update'][90] . $DB->error());
        $query = "UPDATE glpi_profiles SET rule_dictionnary_software=rule_softwarecategories";
        $DB->query($query) or die("0.71 update value of rule_dictionnary_software right " . $LANG['update'][90] . $DB->error());
    }
    if (!FieldExists("glpi_profiles", "rule_dictionnary_dropdown")) {
        $query = "ALTER TABLE `glpi_profiles` ADD `rule_dictionnary_dropdown` VARCHAR( 1 ) NULL DEFAULT NULL;";
        $DB->query($query) or die("0.71 add rule_dictionnary_dropdown in glpi_profiles " . $LANG['update'][90] . $DB->error());
        $query = "UPDATE glpi_profiles SET rule_dictionnary_dropdown=rule_dictionnary_software";
        $DB->query($query) or die("0.71 update value of rule_dictionnary_dropdown" . $LANG['update'][90] . $DB->error());
    }
    $cache_tables = array("glpi_rule_cache_manufacturer", "glpi_rule_cache_model_computer", "glpi_rule_cache_model_monitor", "glpi_rule_cache_model_printer", "glpi_rule_cache_model_peripheral", "glpi_rule_cache_model_phone", "glpi_rule_cache_model_networking", "glpi_rule_cache_type_computer", "glpi_rule_cache_type_monitor", "glpi_rule_cache_type_printer", "glpi_rule_cache_type_peripheral", "glpi_rule_cache_type_phone", "glpi_rule_cache_type_networking", "glpi_rule_cache_software", "glpi_rule_cache_os", "glpi_rule_cache_os_sp", "glpi_rule_cache_os_version");
    foreach ($cache_tables as $cache_table) {
        if (!TableExists($cache_table)) {
            $query = "CREATE TABLE `" . $cache_table . "` (\n\t\t\t`ID` INT( 11 ) NOT NULL auto_increment ,\n\t\t\t`old_value` VARCHAR( 255 ) NULL default NULL ,\n\t\t\t`rule_id` INT( 11 ) NOT NULL DEFAULT '0',\n\t\t\t`new_value` VARCHAR( 255 ) NULL default NULL ,\n\t\t\tPRIMARY KEY ( `ID` ),\n\t\t\tKEY `rule_id` (`rule_id`),\n\t\t\tKEY `old_value` (`old_value`)\n\t\t\t) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;";
            $DB->query($query) or die("0.71 add table " . $cache_table . " " . $LANG['update'][90] . $DB->error());
        }
    }
    //Add the field version espacially for the software's cache
    if (!FieldExists("glpi_rule_cache_software", "version")) {
        $query = "ALTER TABLE `glpi_rule_cache_software` ADD `version` VARCHAR( 255 ) DEFAULT NULL ;";
        $DB->query($query) or die("0.71 add version in glpi_rule_cache_software if not present " . $LANG['update'][90] . $DB->error());
    }
    if (!FieldExists("glpi_rule_cache_software", "manufacturer")) {
        $query = "ALTER TABLE `glpi_rule_cache_software` ADD `manufacturer` VARCHAR( 255 ) NOT NULL AFTER `old_value` ;";
        $DB->query($query) or die("0.71 add manufacturer in glpi_rule_cache_software if not present " . $LANG['update'][90] . $DB->error());
    }
    if (!FieldExists("glpi_rule_cache_software", "new_manufacturer")) {
        $query = "ALTER TABLE `glpi_rule_cache_software` ADD `new_manufacturer` VARCHAR( 255 ) NOT NULL AFTER `version` ;";
        $DB->query($query) or die("0.71 add new_manufacturer in glpi_rule_cache_software if not present " . $LANG['update'][90] . $DB->error());
    }
    $model_cache_tables = array("glpi_rule_cache_model_computer", "glpi_rule_cache_model_monitor", "glpi_rule_cache_model_printer", "glpi_rule_cache_model_peripheral", "glpi_rule_cache_model_phone", "glpi_rule_cache_model_networking");
    foreach ($model_cache_tables as $model_cache_table) {
        if (!FieldExists($model_cache_table, "manufacturer")) {
            $query = "ALTER TABLE `" . $model_cache_table . "` ADD `manufacturer` VARCHAR( 255 ) DEFAULT NULL ;";
            $DB->query($query) or die("0.71 add manufacturer in " . $model_cache_table . " if not present " . $LANG['update'][90] . $DB->error());
        }
    }
    if (!FieldExists("glpi_rules_descriptions", "active")) {
        $query = "ALTER TABLE `glpi_rules_descriptions` ADD `active` INT( 1 ) NOT NULL DEFAULT '1';";
        $DB->query($query) or die("0.71 add active in glpi_rules_descriptions if not present " . $LANG['update'][90] . $DB->error());
    }
    if (!TableExists("glpi_auth_ldap_replicate")) {
        $query = "CREATE TABLE IF NOT EXISTS `glpi_auth_ldap_replicate` (\n\t  `ID` int(11) NOT NULL auto_increment,\n\t  `server_id` int(11) NOT NULL default '0',\n\t  `ldap_host` varchar(255) NULL default NULL,\n\t  `ldap_port` int(11) NOT NULL default '389',\n\t  `name` varchar(255) NULL default NULL,\n\t  PRIMARY KEY  (`ID`)\n\t) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;";
        $DB->query($query) or die("0.71 add table glpi_auth_ldap_replicate " . $LANG['update'][90] . $DB->error());
    }
    if (!FieldExists("glpi_config", "dbreplicate_notify_desynchronization")) {
        $query = "ALTER TABLE `glpi_config` ADD `dbreplicate_notify_desynchronization` SMALLINT NOT NULL DEFAULT '0',\n\t\t\t\tADD `dbreplicate_email` VARCHAR( 255 ) NULL ,\n\t\t\t\tADD `dbreplicate_maxdelay` INT NOT NULL DEFAULT '3600';";
        $DB->query($query) or die("0.71 alter config add config for dbreplicate notif " . $LANG['update'][90] . $DB->error());
    }
    if (FieldExists("glpi_reminder", "author")) {
        $query = "ALTER TABLE `glpi_reminder` CHANGE `author` `FK_users` INT( 11 ) NOT NULL DEFAULT '0';";
        $DB->query($query) or die("0.71 rename author in glpi_reminder" . $LANG['update'][90] . $DB->error());
        if (isIndex("glpi_reminder", "author")) {
            $query = "ALTER TABLE `glpi_reminder` DROP INDEX `author`";
            $DB->query($query) or die("0.7 drop index author on glpi_reminder " . $LANG['update'][90] . $DB->error());
        }
        $query = " ALTER TABLE `glpi_reminder` ADD INDEX `FK_users` ( `FK_users` ) ";
        $DB->query($query) or die("0.71 ad index FK_users in glpi_reminder" . $LANG['update'][90] . $DB->error());
    }
    if (!FieldExists("glpi_reminder", "recursive")) {
        $query = "ALTER TABLE `glpi_reminder` ADD `recursive` TINYINT( 1 ) NOT NULL DEFAULT '0' AFTER `type`;";
        $DB->query($query) or die("0.71 add recursive in glpi_reminder" . $LANG['update'][90] . $DB->error());
        $query = "ALTER TABLE `glpi_reminder` ADD INDEX `recursive` ( `recursive` ); ";
        $DB->query($query) or die("0.71 add recursive index in glpi_reminder" . $LANG['update'][90] . $DB->error());
    }
    if (!FieldExists("glpi_reminder", "private")) {
        $query = "ALTER TABLE `glpi_reminder` ADD `private` TINYINT( 1 ) NOT NULL DEFAULT '1' AFTER `type`;";
        $DB->query($query) or die("0.71 add private in glpi_reminder" . $LANG['update'][90] . $DB->error());
        $query = "UPDATE `glpi_reminder` SET private = '0' WHERE type='public' ";
        $DB->query($query) or die("0.71 update private field in glpi_reminder" . $LANG['update'][90] . $DB->error());
        $query = "ALTER TABLE `glpi_reminder` ADD INDEX `private` ( `private` ); ";
        $DB->query($query) or die("0.71 add private index in glpi_reminder" . $LANG['update'][90] . $DB->error());
        // Drop type
        $query = "ALTER TABLE `glpi_reminder` DROP `type`;";
        $DB->query($query) or die("0.71 drop type in glpi_reminder" . $LANG['update'][90] . $DB->error());
    }
    if (FieldExists("glpi_reminder", "title")) {
        $query = "ALTER TABLE `glpi_reminder` CHANGE `title` `name` VARCHAR( 255 ) NULL DEFAULT NULL  ";
        $DB->query($query) or die("0.71 alter title to namein glpi_reminder" . $LANG['update'][90] . $DB->error());
    }
    if (!isIndex("glpi_ocs_link", "last_ocs_update")) {
        $query = "ALTER TABLE `glpi_ocs_link` ADD INDEX `last_ocs_update` ( `ocs_server_id` , `last_ocs_update` )";
        $DB->query($query) or die("0.7 alter ocs_link add index on last_ocs_update " . $LANG['update'][90] . $DB->error());
    }
    if (!FieldExists("glpi_contacts", "recursive")) {
        $query = "ALTER TABLE `glpi_contacts` ADD `recursive` TINYINT( 1 ) NOT NULL DEFAULT '0' AFTER `FK_entities`;";
        $DB->query($query) or die("0.71 add recursive in glpi_contacts" . $LANG['update'][90] . $DB->error());
    }
    if (!FieldExists("glpi_contracts", "recursive")) {
        $query = "ALTER TABLE `glpi_contracts` ADD `recursive` TINYINT( 1 ) NOT NULL DEFAULT '0' AFTER `FK_entities`;";
        $DB->query($query) or die("0.71 add recursive in glpi_contracts" . $LANG['update'][90] . $DB->error());
    }
    if (!FieldExists("glpi_enterprises", "recursive")) {
        $query = "ALTER TABLE `glpi_enterprises` ADD `recursive` TINYINT( 1 ) NOT NULL DEFAULT '0' AFTER `FK_entities`;";
        $DB->query($query) or die("0.71 add recursive in glpi_enterprises" . $LANG['update'][90] . $DB->error());
    }
    if (!FieldExists("glpi_docs", "recursive")) {
        $query = "ALTER TABLE `glpi_docs` ADD `recursive` TINYINT( 1 ) NOT NULL DEFAULT '0' AFTER `FK_entities`;";
        $DB->query($query) or die("0.71 add recursive in glpi_docs" . $LANG['update'][90] . $DB->error());
    }
    if (!FieldExists("glpi_monitors", "flags_pivot")) {
        $query = "ALTER TABLE `glpi_monitors` ADD `flags_pivot` SMALLINT( 6 ) NOT NULL DEFAULT 0 AFTER `flags_dvi`;";
        $DB->query($query) or die("0.71 add flags_pivot in glpi_monitors" . $LANG['update'][90] . $DB->error());
    }
    if (!FieldExists("glpi_kbitems", "FK_entities")) {
        $query = "ALTER TABLE `glpi_kbitems` ADD `FK_entities` INT(11) NOT NULL DEFAULT 0 AFTER `ID`;";
        $DB->query($query) or die("0.71 add FK_entities in glpi_kbitems" . $LANG['update'][90] . $DB->error());
    }
    if (!FieldExists("glpi_kbitems", "recursive")) {
        // Default 1 for migration. All articles become "global" (root + recursive)
        $query = "ALTER TABLE `glpi_kbitems` ADD `recursive` TINYINT(1) NOT NULL DEFAULT 1 AFTER `FK_entities`;";
        $DB->query($query) or die("0.71 add recursive in glpi_kbitems" . $LANG['update'][90] . $DB->error());
    }
    if (!isIndex("glpi_kbitems", "FK_entities")) {
        $query = "ALTER TABLE `glpi_kbitems` ADD INDEX `FK_entities` (`FK_entities`)";
        $DB->query($query) or die("0.7 alter ocs_link add index on last_ocs_update " . $LANG['update'][90] . $DB->error());
    }
    if (!FieldExists("glpi_config", "category_on_software_delete")) {
        $query = "ALTER TABLE `glpi_config` ADD `category_on_software_delete` INT( 11 ) NOT NULL DEFAULT '0';";
        $DB->query($query) or die("0.71 add category_on_software_delete in glpi_config" . $LANG['update'][90] . $DB->error());
        //Create a software category for softwares to be deleted by the dictionnary
        $result = $DB->query("SELECT ID FROM glpi_dropdown_software_category WHERE name='" . $LANG['rulesengine'][94] . "'");
        if (!$DB->numrows($result)) {
            $DB->query("INSERT INTO glpi_dropdown_software_category SET name='" . $LANG['rulesengine'][94] . "'");
            $result = $DB->query("SELECT ID FROM glpi_dropdown_software_category WHERE name='" . $LANG['rulesengine'][94] . "'");
        }
        $cat_id = $DB->result($result, 0, "ID");
        $DB->query("UPDATE glpi_config SET category_on_software_delete=" . $cat_id);
    }
    $query = "DELETE FROM glpi_display WHERE num='121'";
    $DB->query($query) or die("0.71 clean glpi_display for end_warranty infocoms " . $DB->error());
    // Delete helpdesk injector user
    $query = "DELETE FROM glpi_users WHERE ID='1'";
    $DB->query($query) or die("0.71 delete helpdesk injector user " . $DB->error());
    // Delete helpdesk injector user
    $query = "DELETE FROM glpi_users_profiles WHERE FK_users='1'";
    $DB->query($query) or die("0.71 delete helpdesk injector user profile " . $DB->error());
    // change default device type for tracking
    if (FieldExists("glpi_tracking", "device_type")) {
        $query = " ALTER TABLE `glpi_tracking` CHANGE `device_type` `device_type` INT( 11 ) NOT NULL DEFAULT '0' ";
        $DB->query($query) or die("0.71 alter device_type from glpi_tracking " . $DB->error());
    }
    // Change ldap condition field bigger
    if (FieldExists("glpi_auth_ldap", "ldap_condition")) {
        $query = "ALTER TABLE `glpi_auth_ldap` CHANGE `ldap_condition` `ldap_condition` TEXT NULL DEFAULT NULL   ";
        $DB->query($query) or die("0.71 alter change ldap_condition field to be bigger " . $DB->error());
    }
    // Add date_mod to glpi_tracking
    if (!FieldExists("glpi_tracking", "date_mod")) {
        $query = "ALTER TABLE `glpi_tracking` ADD `date_mod` DATETIME NULL DEFAULT NULL AFTER `closedate` ;";
        $DB->query($query) or die("0.71 alter glpi_tracking add date_mod" . $DB->error());
        $query = "UPDATE `glpi_tracking` SET `date_mod` = date;";
        $DB->query($query) or die("0.71 alter glpi_tracking update date_mod value to creation date" . $DB->error());
    }
    // Add number format
    if (!FieldExists("glpi_config", "numberformat")) {
        $query = "ALTER TABLE `glpi_config` ADD `numberformat` SMALLINT NOT NULL DEFAULT '0' AFTER `dateformat` ;";
        $DB->query($query) or die("0.71 alter config add numberformat" . $DB->error());
    }
    // Add group supervisor
    if (!FieldExists("glpi_groups", "FK_users")) {
        $query = "ALTER TABLE `glpi_groups` ADD `FK_users` INT NOT NULL DEFAULT '0' AFTER `comments` ;";
        $DB->query($query) or die("0.71 alter groups add FK_users supervisor" . $DB->error());
    }
    // Add group supervisor
    if (!FieldExists("glpi_entities_data", "admin_email")) {
        $query = "ALTER TABLE `glpi_entities_data` ADD `admin_email` VARCHAR( 255 ) NULL AFTER `email` ;";
        $DB->query($query) or die("0.71 alter entities_data add admin_email " . $DB->error());
    }
    // Add cas ldap server link
    if (!FieldExists("glpi_config", "extra_ldap_server")) {
        $query = "ALTER TABLE `glpi_config` ADD `extra_ldap_server` INT NOT NULL DEFAULT '1' AFTER `cas_logout` ;";
        $DB->query($query) or die("0.71 alter config add extra_ldap_server" . $DB->error());
    }
    // Add x509 email field definition
    if (!FieldExists("glpi_config", "x509_email_field")) {
        $query = "ALTER TABLE `glpi_config` ADD `x509_email_field` VARCHAR( 255 ) NULL;";
        $DB->query($query) or die("0.71 alter config add x509_email_field" . $DB->error());
    }
    // Add x509 email field definition
    if (!FieldExists("glpi_config", "existing_auth_server_field")) {
        $query = "ALTER TABLE `glpi_config` ADD `existing_auth_server_field` VARCHAR( 255 ) NULL  AFTER `extra_ldap_server`;";
        $DB->query($query) or die("0.71 alter config add existing_auth_server_field" . $DB->error());
    }
    // update cas auth field from 0 -> 5
    $query = "UPDATE `glpi_users` SET `auth_method`=5 WHERE `auth_method`=0;";
    $DB->query($query) or die("0.71 update auth method for CAS " . $DB->error());
    if (!TableExists("glpi_bookmark")) {
        $query = "CREATE TABLE IF NOT EXISTS `glpi_bookmark` (\n\t\t\t`ID` int(11) NOT NULL auto_increment,\n\t\t\t`name` varchar(255) default NULL,\n\t\t\t`type` int(11) NOT NULL default '0',\n\t\t\t`device_type` int(11) NOT NULL default '0',\n\t\t\t`FK_users` int(11) NOT NULL default '0',\n\t\t\t`private` smallint(6) NOT NULL default '1',\n\t\t\t`FK_entities` int(11) NOT NULL default '-1',\n\t\t\t`recursive` smallint(6) NOT NULL default '0',\n\t\t\t`path` varchar(255) default NULL,\n\t\t\t`query` text,\n\t\t\tPRIMARY KEY  (`ID`),\n\t\t\tKEY `FK_users` (`FK_users`),\n\t\t\tKEY `private` (`private`),\n\t\t\tKEY `device_type` (`device_type`),\n\t\t\tKEY `recursive` (`recursive`),\n\t\t\tKEY `FK_entities` (`FK_entities`),\n\t\t\tKEY `type` (`type`)\n\t\t\t) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;";
        $DB->query($query) or die("0.71 add table glpi_bookmark " . $DB->error());
    }
    if (!FieldExists("glpi_profiles", "show_group_planning")) {
        $query = "ALTER TABLE `glpi_profiles` ADD `show_group_planning` CHAR( 1 ) NULL AFTER `show_planning` ;";
        $DB->query($query) or die("0.71 add show_group_planning in glpi_profiles " . $LANG['update'][90] . $DB->error());
        $query = "UPDATE glpi_profiles SET show_group_planning=show_all_planning";
        $DB->query($query) or die("0.71 update value of show_group_planning right " . $LANG['update'][90] . $DB->error());
    }
    if (!FieldExists("glpi_users", "FK_profiles")) {
        $query = "ALTER TABLE `glpi_users` ADD `FK_profiles` INT NOT NULL DEFAULT '0';";
        $DB->query($query) or die("0.71 add default profile to user " . $LANG['update'][90] . $DB->error());
    }
    if (!FieldExists("glpi_users", "FK_entities")) {
        $query = "ALTER TABLE `glpi_users` ADD `FK_entities` INT NOT NULL DEFAULT '0';";
        $DB->query($query) or die("0.71 add default entity to user " . $LANG['update'][90] . $DB->error());
    }
    if (!FieldExists("glpi_auth_ldap", "ldap_opt_deref")) {
        $query = "ALTER TABLE `glpi_auth_ldap` ADD `ldap_opt_deref` INT (1) NOT NULL DEFAULT '0';";
        $DB->query($query) or die("0.71 add ldap_opt_deref to glpi_auth_ldap " . $LANG['update'][90] . $DB->error());
    }
    //ticket opening restrictions
    if (!FieldExists("glpi_config", "ticket_title_mandatory")) {
        $query = "ALTER TABLE `glpi_config` ADD `ticket_title_mandatory` INT (1) NOT NULL DEFAULT '0';";
        $DB->query($query) or die("0.71 add ticket_title_mandatory to glpi_config " . $LANG['update'][90] . $DB->error());
    }
    if (!FieldExists("glpi_config", "ticket_content_mandatory")) {
        $query = "ALTER TABLE `glpi_config` ADD `ticket_content_mandatory` INT (1) NOT NULL DEFAULT '1';";
        $DB->query($query) or die("0.71 add ticket_content_mandatory to glpi_config " . $LANG['update'][90] . $DB->error());
    }
    if (!FieldExists("glpi_config", "ticket_category_mandatory")) {
        $query = "ALTER TABLE `glpi_config` ADD `ticket_category_mandatory` INT (1) NOT NULL DEFAULT '0';";
        $DB->query($query) or die("0.71 add ticket_category_mandatory to glpi_config " . $LANG['update'][90] . $DB->error());
    }
    // Add alerts on licenses
    if (!FieldExists("glpi_config", "licenses_alert")) {
        $query = "ALTER TABLE `glpi_config` ADD `licenses_alert` SMALLINT NOT NULL DEFAULT '0' AFTER `infocom_alerts` ;";
        $DB->query($query) or die("0.71 add licenses_alert to glpi_config " . $LANG['update'][90] . $DB->error());
    }
    if (!FieldExists("glpi_config", "autoclean_link_contact")) {
        $query = "ALTER TABLE `glpi_config` ADD `autoclean_link_contact` smallint(6) NOT NULL DEFAULT '0' AFTER `autoupdate_link_location` ," . "ADD `autoclean_link_user` smallint(6) NOT NULL DEFAULT '0' AFTER `autoclean_link_contact` ," . "ADD `autoclean_link_group` smallint(6) NOT NULL DEFAULT '0' AFTER `autoclean_link_user` ," . "ADD `autoclean_link_location` smallint(6) NOT NULL DEFAULT '0' AFTER `autoclean_link_group` ;";
        $DB->query($query) or die("0.71 add autoclean_link_* to glpi_config " . $LANG['update'][90] . $DB->error());
    }
    if (!FieldExists("glpi_config", "autoupdate_link_state")) {
        $query = "ALTER TABLE `glpi_config` ADD `autoupdate_link_state` smallint(6) NOT NULL DEFAULT '0' AFTER `autoupdate_link_location` ," . "ADD `autoclean_link_state` smallint(6) NOT NULL DEFAULT '0' AFTER `autoclean_link_location`;";
        $DB->query($query) or die("0.71 add autoclean_link_state to glpi_config " . $LANG['update'][90] . $DB->error());
        $query = "UPDATE glpi_ocs_config SET deconnection_behavior = '' WHERE deconnection_behavior != 'trash' AND deconnection_behavior != 'delete';";
        $DB->query($query);
    }
    if (!FieldExists("glpi_profiles", "bookmark_public")) {
        $query = "ALTER TABLE `glpi_profiles` ADD `bookmark_public` CHAR( 1 ) AFTER `reminder_public` ;";
        $DB->query($query) or die("0.71 add bookmark_public to glpi_profiles " . $LANG['update'][90] . $DB->error());
        $query = "UPDATE `glpi_profiles` SET `bookmark_public` = `reminder_public` ;";
        $DB->query($query) or die("0.71 init bookmark_public value in glpi_profiles " . $LANG['update'][90] . $DB->error());
    }
    if (!FieldExists("glpi_config", "admin_reply")) {
        $query = "ALTER TABLE `glpi_config` ADD `admin_reply` VARCHAR( 255 ) NULL AFTER `admin_email` ;";
        $DB->query($query) or die("0.71 add admin_reply to glpi_config " . $LANG['update'][90] . $DB->error());
    }
    if (!FieldExists("glpi_config", "mailgate_filesize_max")) {
        $query = "ALTER TABLE `glpi_config` ADD `mailgate_filesize_max` int(11) NOT NULL DEFAULT " . 2 * 1024 * 1024 . " AFTER `ticket_category_mandatory` ;";
        $DB->query($query) or die("0.71 add mailgate_filesize_max to glpi_config " . $LANG['update'][90] . $DB->error());
    }
    if (!FieldExists("glpi_entities_data", "admin_reply")) {
        $query = "ALTER TABLE `glpi_entities_data` ADD `admin_reply` VARCHAR( 255 ) NULL AFTER `admin_email` ;";
        $DB->query($query) or die("0.71 add admin_reply to glpi_entities_data " . $LANG['update'][90] . $DB->error());
    }
    if (!isIndex("glpi_kbitems", "fulltext")) {
        $query = "ALTER TABLE `glpi_kbitems` ADD FULLTEXT `fulltext` (`question`,`answer`);";
        $DB->query($query) or die("0.71 add fulltext index  glpi_kbitems " . $LANG['update'][90] . $DB->error());
    }
    if (!FieldExists("glpi_profiles", "user_auth_method")) {
        $query = "ALTER TABLE `glpi_profiles` ADD `user_auth_method` CHAR( 1 ) NULL DEFAULT NULL AFTER `user`;";
        $DB->query($query) or die("0.71 add user_auth_method to glpi_profiles " . $LANG['update'][90] . $DB->error());
        $query = "UPDATE `glpi_profiles` SET `user_auth_method` = `user`;";
        $DB->query($query) or die("0.71 init user_auth_method value in glpi_profiles " . $LANG['update'][90] . $DB->error());
    }
    if (isIndex("glpi_printers", "id")) {
        $query = "ALTER TABLE `glpi_printers` DROP INDEX `id`;";
        $DB->query($query) or die("0.71 drop id index in glpi_printers " . $LANG['update'][90] . $DB->error());
    }
    if (isIndex("glpi_users", "name_2")) {
        $query = "ALTER TABLE `glpi_users` DROP INDEX `name_2`;";
        $DB->query($query) or die("0.71 drop name_2 index in glpi_users " . $LANG['update'][90] . $DB->error());
    }
    if (!FieldExists("glpi_rules_descriptions", "comments")) {
        $query = "ALTER TABLE `glpi_rules_descriptions` ADD `comments` TEXT NULL DEFAULT NULL;";
        $DB->query($query) or die("0.71 add comments to glpi_rules_descriptions " . $LANG['update'][90] . $DB->error());
    }
}
Example #14
0
function plugin_escalade_install()
{
    global $DB;
    //get version
    $plugin = new Plugin();
    $found = $plugin->find("name = 'escalade'");
    $plugin_escalade = array_shift($found);
    //init migration
    $migration = new Migration($plugin_escalade['version']);
    // == Tables creation (initial installation) ==
    if (!TableExists('glpi_plugin_escalade_histories')) {
        $query = "CREATE TABLE `glpi_plugin_escalade_histories` (\n         `id`              INT(11) NOT NULL AUTO_INCREMENT,\n         `tickets_id`      INT(11) NOT NULL,\n         `groups_id`       INT(11) NOT NULL,\n         `date_mod`        DATETIME NOT NULL,\n         PRIMARY KEY (`id`),\n         KEY `tickets_id` (`tickets_id`),\n         KEY `groups_id` (`groups_id`)\n      ) ENGINE = MYISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;";
        $DB->query($query);
    }
    if (!TableExists('glpi_plugin_escalade_configs')) {
        $query = "CREATE TABLE `glpi_plugin_escalade_configs` (\n         `id`                                      INT(11) NOT NULL AUTO_INCREMENT,\n         `remove_group`                            INT(11) NOT NULL,\n         `remove_delete_group_btn`                 INT(11) NOT NULL,\n         `remove_delete_user_btn`                  INT(11) NOT NULL,\n         `show_history`                            INT(11) NOT NULL,\n         `task_history`                            INT(11) NOT NULL,\n         `remove_tech`                             INT(11) NOT NULL,\n         `solve_return_group`                      INT(11) NOT NULL,\n         `reassign_group_from_cat`                 INT(11) NOT NULL,\n         `reassign_tech_from_cat`                  INT(11) NOT NULL,\n         `cloneandlink_ticket`                     INT(11) NOT NULL,\n         `close_linkedtickets`                     INT(11) NOT NULL,\n         `use_assign_user_group`                   INT(11) NOT NULL,\n         `use_assign_user_group_creation`          INT(11) NOT NULL,\n         `use_assign_user_group_modification`      INT(11) NOT NULL,\n         `assign_me_ticket`                        INT(11) NOT NULL,\n         `use_filter_assign_group`                 INT(11) NOT NULL,\n         `ticket_last_status`                      INT(11) NOT NULL,\n         PRIMARY KEY (`id`)\n      ) ENGINE = MYISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;";
        $DB->query($query);
        $query = "INSERT INTO glpi_plugin_escalade_configs \n      VALUES (NULL, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 0, '" . Ticket::WAITING . "')";
        $DB->query($query);
    }
    // == Update to 1.2 ==
    if (!FieldExists('glpi_plugin_escalade_configs', 'cloneandlink_ticket')) {
        $migration->addField('glpi_plugin_escalade_configs', 'cloneandlink_ticket', 'INT(11) NOT NULL', array('after' => 'reassign_tech_from_cat'));
        $migration->migrationOneTable('glpi_plugin_escalade_configs');
    }
    if (!FieldExists('glpi_plugin_escalade_configs', 'close_linkedtickets')) {
        $migration->addField('glpi_plugin_escalade_configs', 'close_linkedtickets', 'INT(11) NOT NULL', array('after' => 'cloneandlink_ticket'));
        $migration->migrationOneTable('glpi_plugin_escalade_configs');
    }
    if (!FieldExists('glpi_plugin_escalade_configs', 'use_assign_user_group')) {
        $migration->addField('glpi_plugin_escalade_configs', 'use_assign_user_group', 'INT(11) NOT NULL', array('after' => 'close_linkedtickets'));
        $migration->migrationOneTable('glpi_plugin_escalade_configs');
    }
    if (!FieldExists('glpi_plugin_escalade_configs', 'use_assign_user_group_creation')) {
        $migration->addField('glpi_plugin_escalade_configs', 'use_assign_user_group_creation', 'INT(11) NOT NULL', array('after' => 'use_assign_user_group'));
        $migration->migrationOneTable('glpi_plugin_escalade_configs');
    }
    if (!FieldExists('glpi_plugin_escalade_configs', 'use_assign_user_group_modification')) {
        $migration->addField('glpi_plugin_escalade_configs', 'use_assign_user_group_modification', 'INT(11) NOT NULL', array('after' => 'use_assign_user_group_creation'));
        $migration->migrationOneTable('glpi_plugin_escalade_configs');
    }
    if (!FieldExists('glpi_plugin_escalade_configs', 'remove_delete_group_btn')) {
        $migration->addField('glpi_plugin_escalade_configs', 'remove_delete_group_btn', 'INT(11) NOT NULL', array('after' => 'remove_group'));
        $migration->migrationOneTable('glpi_plugin_escalade_configs');
    }
    if (!FieldExists('glpi_plugin_escalade_configs', 'assign_me_ticket')) {
        $migration->addField('glpi_plugin_escalade_configs', 'assign_me_ticket', 'INT(11) NOT NULL', array('after' => 'use_assign_user_group_modification'));
        $migration->migrationOneTable('glpi_plugin_escalade_configs');
    }
    if (!isIndex("glpi_plugin_escalade_histories", 'tickets_id') || !isIndex("glpi_plugin_escalade_histories", 'groups_id')) {
        $migration->addKey("glpi_plugin_escalade_histories", 'tickets_id', 'tickets_id');
        $migration->addKey("glpi_plugin_escalade_histories", 'groups_id', 'groups_id');
        $migration->migrationOneTable('glpi_plugin_escalade_histories');
    }
    // == Update to 1.3 ==
    if (!FieldExists('glpi_plugin_escalade_configs', 'remove_delete_user_btn')) {
        $migration->addField('glpi_plugin_escalade_configs', 'remove_delete_user_btn', 'INT(11) NOT NULL DEFAULT 1', array('after' => 'remove_delete_group_btn'));
        $migration->migrationOneTable('glpi_plugin_escalade_configs');
    }
    if (!FieldExists('glpi_plugin_escalade_configs', 'use_filter_assign_group')) {
        $migration->addField('glpi_plugin_escalade_configs', 'use_filter_assign_group', 'INT(11) NOT NULL', array('after' => 'use_assign_user_group_modification'));
        $migration->migrationOneTable('glpi_plugin_escalade_configs');
    }
    if (!TableExists('glpi_plugin_escalade_groups_groups')) {
        $query = "CREATE TABLE `glpi_plugin_escalade_groups_groups` (\n         `id`                                      INT(11) NOT NULL AUTO_INCREMENT,\n         `groups_id_source` int(11) NOT NULL DEFAULT '0',\n         `groups_id_destination` int(11) NOT NULL DEFAULT '0',\n         PRIMARY KEY (`id`)\n      ) ENGINE = MYISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;";
        $DB->query($query);
    }
    // Update for 0.84 status
    if (TableExists('glpi_plugin_escalade_configs')) {
        foreach ($DB->request("glpi_plugin_escalade_configs") as $data) {
            switch ($data['ticket_last_status']) {
                case 'solved':
                    $status = Ticket::SOLVED;
                    break;
                case 'waiting':
                    $status = Ticket::WAITING;
                    break;
                case 'closed':
                    $status = Ticket::CLOSED;
                    break;
                case 'assign':
                    $status = Ticket::ASSIGNED;
                    break;
                case 'new':
                    $status = Ticket::INCOMING;
                    break;
                case 'plan':
                    $status = Ticket::PLANNED;
                    break;
                default:
                    $status = -1;
                    break;
            }
            $query = "UPDATE `glpi_plugin_escalade_configs`\n                   SET `ticket_last_status` = '" . $status . "'\n                   WHERE `id` = '" . $data['id'] . "'";
            $DB->query($query);
        }
        $query = "ALTER TABLE `glpi_plugin_escalade_configs` MODIFY `ticket_last_status` INT(11);";
        $DB->query($query);
    }
    return true;
}
Example #15
0
                    'ROOT_MENU_TYPE' => 'top',
                    'CHILD_MENU_TYPE' => 'sub',
                    'USE_EXT' => 'Y',
                    'MAX_LEVEL' => 1,
                    'MENU_CACHE_TYPE' => 'A',
                    'MENU_CACHE_TIME' => COMPONENTS_CACHE_TTL,
                )
            ); ?>

            <div class="clear"></div>
        </div>
    </div>
    <div class="logo"
        <? if (isIndex()) { ?>
            style="padding-bottom: 30px;"
        <?}?>
        >
        <div class="domino-logo">
            <a href="/index.php"><span class="domino-span"><img src="/web/images/logo.png" alt="Мебельный Центр Домино"></a>

     <? $APPLICATION->IncludeComponent('sitedevelopment:contacts', 'top')?>
        </div>
    </div>
    <div class="header_bottom">
        <div class="wrap">
            <? if (isIndex()) { ?>
                <? $APPLICATION->IncludeComponent('sitedevelopment:slider') ?>
            <? } ?>
        </div>
    </div>
</div>
Example #16
0
function plugin_appliances_install()
{
    global $DB;
    if (TableExists("glpi_plugin_applicatifs_profiles")) {
        if (FieldExists("glpi_plugin_applicatifs_profiles", "create_applicatifs")) {
            // version <1.3
            $DB->runFile(GLPI_ROOT . "/plugins/appliances/sql/update-1.3.sql");
        }
    }
    if (TableExists("glpi_plugin_applicatifs")) {
        if (!FieldExists("glpi_plugin_applicatifs", "recursive")) {
            // version 1.3
            $DB->runFile(GLPI_ROOT . "/plugins/appliances/sql/update-1.4.sql");
        }
        if (!FieldExists("glpi_plugin_applicatifs", "FK_groups")) {
            // version 1.4
            $DB->runFile(GLPI_ROOT . "/plugins/appliances/sql/update-1.5.0.sql");
        }
        if (!FieldExists("glpi_plugin_applicatifs", "helpdesk_visible")) {
            // version 1.5.0
            $DB->runFile(GLPI_ROOT . "/plugins/appliances/sql/update-1.5.1.sql");
        }
        if (FieldExists("glpi_plugin_applicatifs", "state")) {
            // empty 1.5.0 not in update 1.5.0
            $DB->query("ALTER TABLE `glpi_plugin_applicatifs` DROP `state`");
        }
        if (isIndex("glpi_plugin_applicatifs_optvalues_machines", "optvalue_ID")) {
            // in empty 1.5.0 not in update 1.5.0
            $DB->query("ALTER TABLE `glpi_plugin_applicatifs_optvalues_machines`\n                     DROP KEY `optvalue_ID`");
        }
        $DB->runFile(GLPI_ROOT . "/plugins/appliances/sql/update-1.6.0.sql");
        Plugin::migrateItemType(array(1200 => 'PluginAppliancesAppliance'), array("glpi_bookmarks", "glpi_bookmarks_users", "glpi_displaypreferences", "glpi_documents_items", "glpi_infocoms", "glpi_logs", "glpi_tickets"), array("glpi_plugin_appliances_appliances_items", "glpi_plugin_appliances_optvalues_items"));
        Plugin::migrateItemType(array(4450 => "PluginRacksRack"), array("glpi_plugin_appliances_appliances_items"));
    }
    if (!TableExists("glpi_plugin_appliances_appliances")) {
        // not installed
        $DB->runFile(GLPI_ROOT . '/plugins/appliances/sql/empty-1.8.0.sql');
    } else {
        $migration = new Migration(180);
        include_once GLPI_ROOT . "/plugins/appliances/inc/appliance.class.php";
        PluginAppliancesAppliance::updateSchema($migration);
        $migration->executeMigration();
    }
    // required cause autoload don't work for unactive plugin'
    include_once GLPI_ROOT . "/plugins/appliances/inc/profile.class.php";
    PluginAppliancesProfile::createAdminAccess($_SESSION['glpiactiveprofile']['id']);
    return true;
}
Example #17
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;
}
Example #18
0
function update031to04()
{
    global $DB, $LANG;
    //0.4 Prefixage des tables :
    echo "<p class='center'>Version 0.4 </p>";
    if (!TableExists("glpi_computers")) {
        $query = "ALTER TABLE `computers` RENAME `glpi_computers`";
        $DB->query($query) or die($LANG['update'][90] . $DB->error());
        $query = "ALTER TABLE `connect_wire` RENAME `glpi_connect_wire`";
        $DB->query($query) or die($LANG['update'][90] . $DB->error());
        $query = "ALTER TABLE `dropdown_gfxcard` RENAME `glpi_dropdown_gfxcard`";
        $DB->query($query) or die($LANG['update'][90] . $DB->error());
        $query = "ALTER TABLE `dropdown_hdtype` RENAME `glpi_dropdown_hdtype`";
        $DB->query($query) or die($LANG['update'][90] . $DB->error());
        $query = "ALTER TABLE `dropdown_iface` RENAME `glpi_dropdown_iface`";
        $DB->query($query) or die($LANG['update'][90] . $DB->error());
        $query = "ALTER TABLE `dropdown_locations` RENAME `glpi_dropdown_locations`";
        $DB->query($query) or die($LANG['update'][90] . $DB->error());
        $query = "ALTER TABLE `dropdown_moboard` RENAME `glpi_dropdown_moboard`";
        $DB->query($query) or die($LANG['update'][90] . $DB->error());
        $query = "ALTER TABLE `dropdown_network` RENAME `glpi_dropdown_network`";
        $DB->query($query) or die($LANG['update'][90] . $DB->error());
        $query = "ALTER TABLE `dropdown_os` RENAME `glpi_dropdown_os`";
        $DB->query($query) or die($LANG['update'][90] . $DB->error());
        $query = "ALTER TABLE `dropdown_processor` RENAME `glpi_dropdown_processor`";
        $DB->query($query) or die($LANG['update'][90] . $DB->error());
        $query = "ALTER TABLE `dropdown_ram` RENAME `glpi_dropdown_ram`";
        $DB->query($query) or die($LANG['update'][90] . $DB->error());
        $query = "ALTER TABLE `dropdown_sndcard` RENAME `glpi_dropdown_sndcard`";
        $DB->query($query) or die($LANG['update'][90] . $DB->error());
        $query = "ALTER TABLE `event_log` RENAME `glpi_event_log`";
        $DB->query($query) or die($LANG['update'][90] . $DB->error());
        $query = "ALTER TABLE `followups` RENAME `glpi_followups`";
        $DB->query($query) or die($LANG['update'][90] . $DB->error());
        $query = "ALTER TABLE `inst_software` RENAME `glpi_inst_software`";
        $DB->query($query) or die($LANG['update'][90] . $DB->error());
        $query = "ALTER TABLE `licenses` RENAME `glpi_licenses`";
        $DB->query($query) or die($LANG['update'][90] . $DB->error());
        $query = "ALTER TABLE `monitors` RENAME `glpi_monitors`";
        $DB->query($query) or die($LANG['update'][90] . $DB->error());
        $query = "ALTER TABLE `networking` RENAME `glpi_networking`";
        $DB->query($query) or die($LANG['update'][90] . $DB->error());
        $query = "ALTER TABLE `networking_ports` RENAME `glpi_networking_ports`";
        $DB->query($query) or die($LANG['update'][90] . $DB->error());
        $query = "ALTER TABLE `networking_wire` RENAME `glpi_networking_wire`";
        $DB->query($query) or die($LANG['update'][90] . $DB->error());
        if (TableExists("prefs") && !TableExists("glpi_prefs")) {
            $query = "ALTER TABLE `prefs` RENAME `glpi_prefs`";
            $DB->query($query) or die($LANG['update'][90] . $DB->error());
        }
        $query = "ALTER TABLE `printers` RENAME `glpi_printers`";
        $DB->query($query) or die($LANG['update'][90] . $DB->error());
        $query = "ALTER TABLE `software` RENAME `glpi_software`";
        $DB->query($query) or die($LANG['update'][90] . $DB->error());
        $query = "ALTER TABLE `templates` RENAME `glpi_templates`";
        $DB->query($query) or die($LANG['update'][90] . $DB->error());
        $query = "ALTER TABLE `tracking` RENAME `glpi_tracking`";
        $DB->query($query) or die($LANG['update'][90] . $DB->error());
        $query = "ALTER TABLE `type_computers` RENAME `glpi_type_computers`";
        $DB->query($query) or die($LANG['update'][90] . $DB->error());
        $query = "ALTER TABLE `type_monitors` RENAME `glpi_type_monitors`";
        $DB->query($query) or die($LANG['update'][90] . $DB->error());
        $query = "ALTER TABLE `type_networking` RENAME `glpi_type_networking`";
        $DB->query($query) or die($LANG['update'][90] . $DB->error());
        $query = "ALTER TABLE `type_printers` RENAME `glpi_type_printers`";
        $DB->query($query) or die($LANG['update'][90] . $DB->error());
        $query = "ALTER TABLE `users` RENAME `glpi_users`";
        $DB->query($query) or die($LANG['update'][90] . $DB->error());
    }
    //Ajout d'un champs ID dans la table users
    if (!FieldExists("glpi_users", "ID")) {
        $query = "ALTER TABLE `glpi_users`\n                DROP PRIMARY KEY";
        $DB->query($query) or die($LANG['update'][90] . $DB->error());
        $query = "ALTER TABLE `glpi_users`\n                ADD UNIQUE (`name`)";
        $DB->query($query) or die($LANG['update'][90] . $DB->error());
        $query = "ALTER TABLE `glpi_users`\n                ADD INDEX (`name`)";
        $DB->query($query) or die($LANG['update'][90] . $DB->error());
        $query = " ALTER TABLE `glpi_users`\n                 ADD `ID` INT NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST";
        $DB->query($query) or die($LANG['update'][90] . $DB->error());
    }
    //Mise a jour des ID pour les tables dropdown et type
    //cles primaires sur les tables dropdown et type, et mise a jour des champs lies
    if (!FieldExists("glpi_dropdown_os", "ID")) {
        changeVarcharToID("glpi_computers", "glpi_dropdown_os", "os");
        changeVarcharToID("glpi_computers", "glpi_dropdown_hdtype", "hdtype");
        changeVarcharToID("glpi_computers", "glpi_dropdown_sndcard", "sndcard");
        changeVarcharToID("glpi_computers", "glpi_dropdown_moboard", "moboard");
        changeVarcharToID("glpi_computers", "glpi_dropdown_gfxcard", "gfxcard");
        changeVarcharToID("glpi_computers", "glpi_dropdown_network", "network");
        changeVarcharToID("glpi_computers", "glpi_dropdown_ram", "ramtype");
        changeVarcharToID("glpi_computers", "glpi_dropdown_locations", "location");
        changeVarcharToID("glpi_computers", "glpi_dropdown_processor", "processor");
        changeVarcharToID("glpi_computers", "glpi_type_computers", "type");
        changeVarcharToID("glpi_monitors", "glpi_dropdown_locations", "location");
        changeVarcharToID("glpi_monitors", "glpi_type_monitors", "type");
        changeVarcharToID("glpi_networking", "glpi_dropdown_locations", "location");
        changeVarcharToID("glpi_networking", "glpi_type_networking", "type");
        changeVarcharToID("glpi_networking_ports", "glpi_dropdown_iface", "iface");
        changeVarcharToID("glpi_printers", "glpi_dropdown_locations", "location");
        changeVarcharToID("glpi_printers", "glpi_type_printers", "type");
        changeVarcharToID("glpi_software", "glpi_dropdown_locations", "location");
        changeVarcharToID("glpi_software", "glpi_dropdown_os", "platform");
        changeVarcharToID("glpi_templates", "glpi_dropdown_os", "os");
        changeVarcharToID("glpi_templates", "glpi_dropdown_hdtype", "hdtype");
        changeVarcharToID("glpi_templates", "glpi_dropdown_sndcard", "sndcard");
        changeVarcharToID("glpi_templates", "glpi_dropdown_moboard", "moboard");
        changeVarcharToID("glpi_templates", "glpi_dropdown_gfxcard", "gfxcard");
        changeVarcharToID("glpi_templates", "glpi_dropdown_network", "network");
        changeVarcharToID("glpi_templates", "glpi_dropdown_ram", "ramtype");
        changeVarcharToID("glpi_templates", "glpi_dropdown_locations", "location");
        changeVarcharToID("glpi_templates", "glpi_dropdown_processor", "processor");
        changeVarcharToID("glpi_templates", "glpi_type_computers", "type");
        changeVarcharToID("glpi_users", "glpi_dropdown_locations", "location");
    }
    if (!TableExists("glpi_type_peripherals")) {
        $query = "CREATE TABLE `glpi_type_peripherals` (\n                  `ID` int(11) NOT NULL auto_increment,\n                  `name` varchar(255),\n                  PRIMARY KEY  (`ID`)\n                ) TYPE=MyISAM";
        $DB->query($query) or die("0A " . $LANG['update'][90] . $DB->error());
    }
    if (!TableExists("glpi_peripherals")) {
        $query = "CREATE TABLE `glpi_peripherals` (\n                  `ID` int(11) NOT NULL auto_increment,\n                  `name` varchar(255) NOT NULL default '',\n                  `date_mod` datetime NOT NULL default '0000-00-00 00:00:00',\n                  `contact` varchar(255) NOT NULL default '',\n                  `contact_num` varchar(255) NOT NULL default '',\n                  `comments` text NOT NULL,\n                  `serial` varchar(255) NOT NULL default '',\n                  `otherserial` varchar(255) NOT NULL default '',\n                  `date_fin_garantie` date default NULL,\n                  `achat_date` date NOT NULL default '0000-00-00',\n                  `maintenance` int(2) default '0',\n                  `location` int(11) NOT NULL default '0',\n                  `type` int(11) NOT NULL default '0',\n                  `brand` varchar(255) NOT NULL default '',\n                  PRIMARY KEY  (`ID`)\n                ) TYPE=MyISAM";
        $DB->query($query) or die("0 " . $LANG['update'][90] . $DB->error());
    }
    if (TableExists("glpi_prefs") && !FieldExists("glpi_prefs", "ID")) {
        $query = "ALTER TABLE `glpi_prefs`\n                DROP PRIMARY KEY";
        $DB->query($query) or die("1 " . $LANG['update'][90] . $DB->error());
        $query = "ALTER TABLE `glpi_prefs`\n                ADD `ID` INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY";
        $DB->query($query) or die("3 " . $LANG['update'][90] . $DB->error());
    }
    if (!FieldExists("glpi_config", "ID")) {
        $query = "ALTER TABLE `glpi_config`\n                CHANGE `config_id` `ID` INT(11) NOT NULL AUTO_INCREMENT";
        $DB->query($query) or die("4 " . $LANG['update'][90] . $DB->error());
    }
    if (!isIndex("glpi_computers", "location")) {
        $query = "ALTER TABLE `glpi_computers`\n                ADD INDEX (`location`)";
        $DB->query($query) or die("5 " . $LANG['update'][90] . $DB->error());
    }
    if (!isIndex("glpi_computers", "os")) {
        $query = "ALTER TABLE `glpi_computers`\n                ADD INDEX (`os`)";
        $DB->query($query) or die("6 " . $LANG['update'][90] . $DB->error());
    }
    if (!isIndex("glpi_computers", "type")) {
        $query = "ALTER TABLE `glpi_computers`\n                ADD INDEX (`type`)";
        $DB->query($query) or die("7 " . $LANG['update'][90] . $DB->error());
    }
    if (!isIndex("glpi_followups", "tracking")) {
        $query = "ALTER TABLE `glpi_followups`\n                ADD INDEX (`tracking`)";
        $DB->query($query) or die("12 " . $LANG['update'][90] . $DB->error());
    }
    if (!isIndex("glpi_networking", "location")) {
        $query = "ALTER TABLE `glpi_networking`\n                ADD INDEX (`location`)";
        $DB->query($query) or die("13 " . $LANG['update'][90] . $DB->error());
    }
    if (!isIndex("glpi_networking_ports", "on_device")) {
        $query = "ALTER TABLE `glpi_networking_ports`\n                ADD INDEX (`on_device` , `device_type`)";
        $DB->query($query) or die("14 " . $LANG['update'][90] . $DB->error());
    }
    if (!isIndex("glpi_peripherals", "type")) {
        $query = "ALTER TABLE `glpi_peripherals`\n                ADD INDEX (`type`)";
        $DB->query($query) or die("14 " . $LANG['update'][90] . $DB->error());
    }
    if (!isIndex("glpi_peripherals", "location")) {
        $query = "ALTER TABLE `glpi_peripherals`\n                ADD INDEX (`location`)";
        $DB->query($query) or die("15 " . $LANG['update'][90] . $DB->error());
    }
    if (!isIndex("glpi_printers", "location")) {
        $query = "ALTER TABLE `glpi_printers`\n                ADD INDEX (`location`)";
        $DB->query($query) or die("16 " . $LANG['update'][90] . $DB->error());
    }
    if (!isIndex("glpi_tracking", "computer")) {
        $query = "ALTER TABLE `glpi_tracking`\n                ADD INDEX (`computer`)";
        $DB->query($query) or die("17 " . $LANG['update'][90] . $DB->error());
    }
    if (!isIndex("glpi_tracking", "author")) {
        $query = "ALTER TABLE `glpi_tracking`\n                ADD INDEX (`author`)";
        $DB->query($query) or die("18 " . $LANG['update'][90] . $DB->error());
    }
    if (!isIndex("glpi_tracking", "assign")) {
        $query = "ALTER TABLE `glpi_tracking`\n                ADD INDEX (`assign`)";
        $DB->query($query) or die("19 " . $LANG['update'][90] . $DB->error());
    }
    if (!isIndex("glpi_tracking", "date")) {
        $query = "ALTER TABLE `glpi_tracking`\n                ADD INDEX (`date`)";
        $DB->query($query) or die("20 " . $LANG['update'][90] . $DB->error());
    }
    if (!isIndex("glpi_tracking", "closedate")) {
        $query = "ALTER TABLE `glpi_tracking`\n                ADD INDEX (`closedate`)";
        $DB->query($query) or die("21 " . $LANG['update'][90] . $DB->error());
    }
    if (!isIndex("glpi_tracking", "status")) {
        $query = "ALTER TABLE `glpi_tracking`\n                ADD INDEX (`status`)";
        $DB->query($query) or die("22 " . $LANG['update'][90] . $DB->error());
    }
    if (!TableExists("glpi_dropdown_firmware")) {
        $query = "CREATE TABLE `glpi_dropdown_firmware` (\n                  `ID` INT NOT NULL AUTO_INCREMENT,\n                  `name` VARCHAR(255) NOT NULL,\n                  PRIMARY KEY (`ID`))";
        $DB->query($query) or die("23 " . $LANG['update'][90] . $DB->error());
    }
    if (!FieldExists("glpi_networking", "firmware")) {
        $query = "ALTER TABLE `glpi_networking`\n                ADD `firmware` INT(11)";
        $DB->query($query) or die("24 " . $LANG['update'][90] . $DB->error());
    }
    if (!FieldExists("glpi_tracking", "realtime")) {
        $query = "ALTER TABLE `glpi_tracking`\n                ADD `realtime` FLOAT NOT NULL";
        $DB->query($query) or die("25 " . $LANG['update'][90] . $DB->error());
    }
    if (!FieldExists("glpi_printers", "flags_usb")) {
        $query = "ALTER TABLE `glpi_printers`\n                ADD `flags_usb` TINYINT DEFAULT '0' NOT NULL AFTER `flags_par`";
        $DB->query($query) or die("26 " . $LANG['update'][90] . $DB->error());
    }
    if (!FieldExists("glpi_licenses", "expire")) {
        $query = "ALTER TABLE `glpi_licenses`\n                ADD `expire` date default NULL";
        $DB->query($query) or die("27 " . $LANG['update'][90] . $DB->error());
    }
    if (!isIndex("glpi_licenses", "sID")) {
        $query = "ALTER TABLE `glpi_licenses`\n                ADD INDEX (`sID`) ";
        $DB->query($query) or die("32 " . $LANG['update'][90] . $DB->error());
    }
    if (!isIndex("glpi_followups", "author")) {
        $query = "ALTER TABLE `glpi_followups`\n                ADD INDEX (`author`) ";
        $DB->query($query) or die("33 " . $LANG['update'][90] . $DB->error());
    }
    if (!isIndex("glpi_monitors", "type")) {
        $query = "ALTER TABLE `glpi_monitors`\n                ADD INDEX (`type`) ";
        $DB->query($query) or die("34 " . $LANG['update'][90] . $DB->error());
    }
    if (!isIndex("glpi_monitors", "location")) {
        $query = "ALTER TABLE `glpi_monitors`\n                ADD INDEX (`location`) ";
        $DB->query($query) or die("35 " . $LANG['update'][90] . $DB->error());
    }
    if (!isIndex("glpi_monitors", "type")) {
        $query = "ALTER TABLE `glpi_monitors`\n                ADD INDEX (`type`)";
        $DB->query($query) or die("37 " . $LANG['update'][90] . $DB->error());
    }
    if (!isIndex("glpi_networking", "type")) {
        $query = "ALTER TABLE `glpi_networking`\n                ADD INDEX (`type`)";
        $DB->query($query) or die("38 " . $LANG['update'][90] . $DB->error());
    }
    if (!isIndex("glpi_networking", "firmware")) {
        $query = "ALTER TABLE `glpi_networking`\n                ADD INDEX (`firmware`)";
        $DB->query($query) or die("39 " . $LANG['update'][90] . $DB->error());
    }
    if (!isIndex("glpi_printers", "type")) {
        $query = "ALTER TABLE `glpi_printers`\n                ADD INDEX (`type`)";
        $DB->query($query) or die("42 " . $LANG['update'][90] . $DB->error());
    }
    if (!isIndex("glpi_software", "platform")) {
        $query = "ALTER TABLE `glpi_software`\n                ADD INDEX (`platform`)";
        $DB->query($query) or die("44 " . $LANG['update'][90] . $DB->error());
    }
    if (!isIndex("glpi_software", "location")) {
        $query = "ALTER TABLE `glpi_software`\n                ADD INDEX (`location`) ";
        $DB->query($query) or die("45 " . $LANG['update'][90] . $DB->error());
    }
    if (!TableExists("glpi_dropdown_netpoint")) {
        $query = " CREATE TABLE `glpi_dropdown_netpoint` (\n                     `ID` INT NOT NULL AUTO_INCREMENT ,\n                     `location` INT NOT NULL ,\n                     `name` VARCHAR(255) NOT NULL ,\n                     PRIMARY KEY (`ID`))";
        $DB->query($query) or die("46 " . $LANG['update'][90] . $DB->error());
    }
    if (!isIndex("glpi_dropdown_netpoint", "location")) {
        $query = "ALTER TABLE `glpi_dropdown_netpoint`\n                ADD INDEX (`location`) ";
        $DB->query($query) or die("47 " . $LANG['update'][90] . $DB->error());
    }
    if (!FieldExists("glpi_networking_ports", "netpoint")) {
        $query = "ALTER TABLE `glpi_networking_ports`\n                ADD `netpoint` INT default NULL";
        $DB->query($query) or die("27 " . $LANG['update'][90] . $DB->error());
    }
    if (!isIndex("glpi_networking_ports", "netpoint")) {
        $query = "ALTER TABLE `glpi_networking_ports`\n                ADD INDEX (`netpoint`) ";
        $DB->query($query) or die("47 " . $LANG['update'][90] . $DB->error());
    }
    if (!isIndex("glpi_networking_wire", "end1")) {
        $query = "ALTER TABLE `glpi_networking_wire`\n                ADD INDEX (`end1`) ";
        $DB->query($query) or die("40 " . $LANG['update'][90] . $DB->error());
        // Clean Table
        $query = "SELECT *\n                FROM `glpi_networking_wire`\n                ORDER BY `end1`, `end2`";
        $result = $DB->query($query);
        $curend1 = -1;
        $curend2 = -1;
        while ($line = $DB->fetch_array($result)) {
            if ($curend1 == $line['end1'] && $curend2 == $line['end2']) {
                $q2 = "DELETE\n                   FROM `glpi_networking_wire`\n                   WHERE `ID` = '" . $line['ID'] . "' LIMIT 1";
                $DB->query($q2);
            } else {
                $curend1 = $line['end1'];
                $curend2 = $line['end2'];
            }
        }
        $DB->free_result($result);
        $query = "ALTER TABLE `glpi_networking_wire`\n                ADD UNIQUE end1_1 (`end1`,`end2`)";
        $DB->query($query) or die("477 " . $LANG['update'][90] . $DB->error());
    }
    if (!isIndex("glpi_networking_wire", "end2")) {
        $query = "ALTER TABLE `glpi_networking_wire`\n                ADD INDEX (`end2`) ";
        $DB->query($query) or die("41 " . $LANG['update'][90] . $DB->error());
    }
    if (!isIndex("glpi_connect_wire", "end1")) {
        $query = "ALTER TABLE `glpi_connect_wire`\n                ADD INDEX (`end1`) ";
        $DB->query($query) or die("40 " . $LANG['update'][90] . $DB->error());
        // Clean Table
        $query = "SELECT *\n                FROM  `glpi_connect_wire`\n                ORDER BY `type`, `end1`, `end2`";
        $result = $DB->query($query);
        $curend1 = -1;
        $curend2 = -1;
        $curtype = -1;
        while ($line = $DB->fetch_array($result)) {
            if ($curend1 == $line['end1'] && $curend2 == $line['end2'] && $curtype == $line['type']) {
                $q2 = "DELETE\n                   FROM `glpi_connect_wire`\n                   WHERE `ID`='" . $line['ID'] . "'\n                   LIMIT 1";
                $DB->query($q2);
            } else {
                $curend1 = $line['end1'];
                $curend2 = $line['end2'];
                $curtype = $line['type'];
            }
        }
        $DB->free_result($result);
        $query = "ALTER TABLE `glpi_connect_wire`\n                ADD UNIQUE end1_1 (`end1`,`end2`,`type`) ";
        $DB->query($query) or die("478 " . $LANG['update'][90] . $DB->error());
    }
    if (!isIndex("glpi_connect_wire", "end2")) {
        $query = "ALTER TABLE `glpi_connect_wire`\n                ADD INDEX (`end2`) ";
        $DB->query($query) or die("40 " . $LANG['update'][90] . $DB->error());
    }
    if (!isIndex("glpi_connect_wire", "type")) {
        $query = "ALTER TABLE `glpi_connect_wire`\n                ADD INDEX (`type`)";
        $DB->query($query) or die("40 " . $LANG['update'][90] . $DB->error());
    }
    if (!FieldExists("glpi_config", "ldap_condition")) {
        $query = "ALTER TABLE `glpi_config`\n                ADD `ldap_condition` VARCHAR(255) NOT NULL DEFAULT ''";
        $DB->query($query) or die("48 " . $LANG['update'][90] . $DB->error());
    }
    $query = "ALTER TABLE `glpi_users`\n             CHANGE `type` `type` ENUM('normal', 'admin', 'post-only', 'super-admin') DEFAULT 'normal' NOT NULL";
    $DB->query($query) or die("49 " . $LANG['update'][90] . $DB->error());
    $ret["adminchange"] = false;
    //All "admin" users have to be set as "super-admin"
    if (!superAdminExists()) {
        $query = "UPDATE `glpi_users`\n                SET `type` = 'super-admin'\n                WHERE `type` = 'admin'";
        $DB->query($query) or die("49 " . $LANG['update'][90] . $DB->error());
        if ($DB->affected_rows() != 0) {
            $ret["adminchange"] = true;
        }
    }
    if (!FieldExists("glpi_users", "password_md5")) {
        $query = "ALTER TABLE `glpi_users`\n                ADD `password_md5` VARCHAR(80) NOT NULL AFTER `password`";
        $DB->query($query) or die("glpi_users.Password_md5" . $LANG['update'][90] . $DB->error());
    }
    if (!FieldExists("glpi_config", "permit_helpdesk")) {
        $query = "ALTER TABLE `glpi_config`\n                ADD `permit_helpdesk` VARCHAR(200) NOT NULL";
        $DB->query($query) or die("glpi_config_permit_helpdesk " . $LANG['update'][90] . $DB->error());
    }
}
Example #19
0
 /**
  * Drop index for migration
  *
  * @param $table     string
  * @param $indexname string
  **/
 function dropKey($table, $indexname)
 {
     if (isIndex($table, $indexname)) {
         $this->change[$table][] = "DROP INDEX `{$indexname}`";
     }
 }
Example #20
0
function plugin_archires_install()
{
    global $DB;
    include_once GLPI_ROOT . "/plugins/archires/inc/profile.class.php";
    $update = false;
    if (!TableExists("glpi_plugin_archires_config") && !TableExists("glpi_plugin_archires_views")) {
        $DB->runFile(GLPI_ROOT . "/plugins/archires/sql/empty-2.1.0.sql");
    } else {
        $update = true;
        // update to 1.3
        if (TableExists("glpi_plugin_archires_display") && !FieldExists("glpi_plugin_archires_display", "display_ports")) {
            $migration = new Migration(13);
            $migration->addField("glpi_plugin_archires_display", "display_ports", "ENUM('1', '0') NOT NULL DEFAULT '0'");
            $migration->executeMigration();
        }
        // update to 1.4
        if (TableExists("glpi_plugin_archires_display") && !TableExists("glpi_plugin_archires_profiles")) {
            plugin_archires_updateTo14();
        }
        // update to 1.5
        if (TableExists("glpi_plugin_archires_display") && !TableExists("glpi_plugin_archires_image_device")) {
            plugin_archires_updateTo15();
        }
        // update to 1.7.0
        if (TableExists("glpi_plugin_archires_profiles") && FieldExists("glpi_plugin_archires_profiles", "interface")) {
            plugin_archires_updateTo170();
        }
        // update to 1.7.2
        if (TableExists("glpi_plugin_archires_config") && FieldExists("glpi_plugin_archires_config", "system")) {
            $migration = new Migration(172);
            $migration->dropField("glpi_plugin_archires_config", "system");
            $migration->executeMigration();
        }
        // update to 1.8.0
        if (!TableExists("glpi_plugin_archires_views")) {
            plugin_archires_updateTo180();
        }
        // update to 2.1.0
        if (TableExists("glpi_plugin_archires_appliancequeries") && !FieldExists("glpi_plugin_archires_appliancequeries", "plugin_appliances_appliances_id")) {
            plugin_archires_updateTo210();
        }
    }
    if ($update) {
        $table = "glpi_plugin_archires_statecolors";
        $index = "state";
        if (isIndex($table, $index)) {
            $query = "ALTER TABLE `{$table}` DROP INDEX `{$index}`;";
            $result = $DB->query($query);
        }
        $query_ = "SELECT *\n                  FROM `glpi_plugin_archires_profiles` ";
        $result_ = $DB->query($query_);
        if ($DB->numrows($result_) > 0) {
            while ($data = $DB->fetch_array($result_)) {
                $query = "UPDATE `glpi_plugin_archires_profiles`\n                      SET `profiles_id` = '" . $data["id"] . "'\n                      WHERE `id` = '" . $data["id"] . "';";
                $result = $DB->query($query);
            }
        }
        if (FieldExists("glpi_plugin_archires_profiles", "name")) {
            $query = "ALTER TABLE `glpi_plugin_archires_profiles`\n                    DROP `name`";
        }
        $result = $DB->query($query);
        Plugin::migrateItemType(array(3000 => 'PluginArchiresLocationQuery', 3001 => 'PluginArchiresNetworkEquipmentQuery', 3002 => 'PluginArchiresApplianceQuery', 3003 => 'PluginArchiresView'), array("glpi_bookmarks", "glpi_bookmarks_users", "glpi_displaypreferences", "glpi_documents_items", "glpi_infocoms", "glpi_logs", "glpi_tickets"), array("glpi_plugin_archires_querytypes", "glpi_plugin_archires_imageitems"));
    }
    $rep_files_archires = realpath(GLPI_PLUGIN_DOC_DIR) . "/archires";
    if (!is_dir($rep_files_archires) && !mkdir($rep_files_archires)) {
        die(sprintf(__('Failed to create the directory %s. Verify that you have the correct permission'), $rep_files_archires));
    }
    PluginArchiresProfile::createFirstAccess($_SESSION['glpiactiveprofile']['id']);
    return true;
}
Example #21
0
function update06to065()
{
    global $DB, $LANG;
    echo "<p class='center'>Version 0.65 </p>";
    if (!isIndex("glpi_networking_ports", "on_device_2")) {
        $query = "ALTER TABLE `glpi_networking_ports` ADD INDEX (`on_device`) ";
        $DB->query($query) or die("0.65 " . $LANG['update'][90] . $DB->error());
    }
    if (!isIndex("glpi_networking_ports", "device_type")) {
        $query = "ALTER TABLE `glpi_networking_ports` ADD INDEX (`device_type`) ";
        $DB->query($query) or die("0.65 " . $LANG['update'][90] . $DB->error());
    }
    if (!isIndex("glpi_computer_device", "FK_device")) {
        $query = "ALTER TABLE `glpi_computer_device` ADD INDEX (`FK_device`) ";
        $DB->query($query) or die("0.65 " . $LANG['update'][90] . $DB->error());
    }
    // Field for public FAQ
    if (!FieldExists("glpi_config", "public_faq")) {
        $query = "ALTER TABLE `glpi_config` ADD `public_faq` ENUM( '0', '1' ) NOT NULL AFTER `auto_assign` ;";
        $DB->query($query) or die("0.65 add public_faq in config" . $LANG['update'][90] . $DB->error());
    }
    // Optimize amort_type field
    if (FieldExists("glpi_infocoms", "amort_type")) {
        $query2 = "UPDATE `glpi_infocoms` SET `amort_type`='0' WHERE `amort_type` = '';";
        $DB->query($query2) or die("0.65 update amort_type='' in tracking" . $LANG['update'][90] . $DB->error());
        $query = "ALTER TABLE `glpi_infocoms` CHANGE `amort_type` `amort_type` tinyint(4) NOT NULL DEFAULT '0'";
        $DB->query($query) or die("0.65 alter amort_type in infocoms" . $LANG['update'][90] . $DB->error());
    }
    if (!TableExists("glpi_display")) {
        $query = "CREATE TABLE glpi_display (\n\t\t\tID int(11) NOT NULL auto_increment,\n\t\t\t   type smallint(6) NOT NULL default '0',\n\t\t\t   num smallint(6) NOT NULL default '0',\n\t\t\t   rank smallint(6) NOT NULL default '0',\n\t\t\t   PRIMARY KEY  (ID),\n\t\t\t   UNIQUE KEY `type_2` (`type`,`num`),\n\t\t\t   KEY type (type),\n\t\t\t   KEY rank (rank),\n\t\t\t   KEY num (num)\n\t\t\t\t   ) TYPE=MyISAM;";
        $DB->query($query) or die("0.65 add glpi_display table" . $LANG['update'][90] . $DB->error());
        // TEMPORARY : ADD ITEMS TO DISPLAY TABLE : TO DEL OR TO
        $query = "INSERT INTO `glpi_display` VALUES (32, 1, 4, 4),\n\t\t\t(34, 1, 6, 6),\n\t\t\t(33, 1, 5, 5),\n\t\t\t(31, 1, 8, 3),\n\t\t\t(30, 1, 23, 2),\n\t\t\t(86, 12, 3, 1),\n\t\t\t(49, 4, 31, 1),\n\t\t\t(50, 4, 23, 2),\n\t\t\t(51, 4, 3, 3),\n\t\t\t(52, 4, 4, 4),\n\t\t\t(44, 3, 31, 1),\n\t\t\t(38, 2, 31, 1),\n\t\t\t(39, 2, 23, 2),\n\t\t\t(45, 3, 23, 2),\n\t\t\t(46, 3, 3, 3),\n\t\t\t(63, 6, 4, 3),\n\t\t\t(62, 6, 5, 2),\n\t\t\t(61, 6, 23, 1),\n\t\t\t(83, 11, 4, 2),\n\t\t\t(82, 11, 3, 1),\n\t\t\t(57, 5, 3, 3),\n\t\t\t(56, 5, 23, 2),\n\t\t\t(55, 5, 31, 1),\n\t\t\t(29, 1, 31, 1),\n\t\t\t(35, 1, 3, 7),\n\t\t\t(36, 1, 19, 8),\n\t\t\t(37, 1, 17, 9),\n\t\t\t(40, 2, 3, 3),\n\t\t\t(41, 2, 4, 4),\n\t\t\t(42, 2, 11, 6),\n\t\t\t(43, 2, 9, 7),\n\t\t\t(47, 3, 4, 4),\n\t\t\t(48, 3, 9, 6),\n\t\t\t(53, 4, 9, 6),\n\t\t\t(54, 4, 7, 7),\n\t\t\t(58, 5, 4, 4),\n\t\t\t(59, 5, 9, 6),\n\t\t\t(60, 5, 7, 7),\n\t\t\t(64, 7, 3, 1),\n\t\t\t(65, 7, 4, 2),\n\t\t\t(66, 7, 5, 3),\n\t\t\t(67, 7, 6, 4),\n\t\t\t(68, 7, 9, 5),\n\t\t\t(69, 8, 9, 1),\n\t\t\t(70, 8, 3, 2),\n\t\t\t(71, 8, 4, 3),\n\t\t\t(72, 8, 5, 4),\n\t\t\t(73, 8, 10, 5),\n\t\t\t(74, 8, 6, 6),\n\t\t\t(75, 10, 4, 1),\n\t\t\t(76, 10, 3, 2),\n\t\t\t(77, 10, 5, 3),\n\t\t\t(78, 10, 6, 4),\n\t\t\t(79, 10, 7, 5),\n\t\t\t(80, 10, 11, 6),\n\t\t\t(84, 11, 5, 3),\n\t\t\t(85, 11, 6, 4),\n\t\t\t(88, 12, 6, 2),\n\t\t\t(89, 12, 4, 3),\n\t\t\t(90, 12, 5, 4),\n\t\t\t(91, 13, 3, 1),\n\t\t\t(92, 13, 4, 2),\n\t\t\t(93, 13, 7, 3),\n\t\t\t(94, 13, 5, 4),\n\t\t\t(95, 13, 6, 5),\n\t\t\t(96, 15, 3, 1),\n\t\t\t(97, 15, 4, 2),\n\t\t\t(98, 15, 5, 3),\n\t\t\t(99, 15, 6, 4),\n\t\t\t(100, 15, 7, 5),\n\t\t\t(101, 17, 3, 1),\n\t\t\t(102, 17, 4, 2),\n\t\t\t(103, 17, 5, 3),\n\t\t\t(104, 17, 6, 4),\n\t\t\t(105, 2, 40, 5),\n\t\t\t(106, 3, 40, 5),\n\t\t\t(107, 4, 40, 5),\n\t\t\t(108, 5, 40, 5),\n\t\t\t(109, 15, 8, 6),\n\t\t\t(110, 23, 31, 1),\n\t\t\t(111, 23, 23, 2),\n\t\t\t(112, 23, 3, 3),\n\t\t\t(113, 23, 4, 4),\n\t\t\t(114, 23, 40, 5),\n\t\t\t(115, 23, 9, 6),\n\t\t\t(116, 23, 7, 7);";
        $DB->query($query);
    }
    if (!FieldExists("glpi_config", "ldap_login")) {
        $query = "ALTER TABLE `glpi_config` ADD `ldap_login` VARCHAR( 200 ) NOT NULL DEFAULT 'uid' AFTER `ldap_condition`;";
        $DB->query($query) or die("0.65 add url in config" . $LANG['update'][90] . $DB->error());
    }
    if (!FieldExists("glpi_config", "url_base")) {
        $query = "ALTER TABLE `glpi_config` ADD `url_base` VARCHAR( 255 ) NOT NULL ;";
        $DB->query($query) or die("0.65 add url in config" . $LANG['update'][90] . $DB->error());
        $query = "ALTER TABLE `glpi_config` ADD `url_in_mail` ENUM( '0', '1' ) NOT NULL ;";
        $DB->query($query) or die("0.65 add url_in_mail in config" . $LANG['update'][90] . $DB->error());
        $query = "UPDATE glpi_config SET url_base='" . str_replace("/install.php", "", $_SERVER['HTTP_REFERER']) . "' WHERE ID='1'";
        $DB->query($query) or die(" url " . $LANG['update'][90] . $DB->error());
    }
    if (!FieldExists("glpi_config", "text_login")) {
        $query = "ALTER TABLE `glpi_config` ADD `text_login` TEXT NOT NULL ;";
        $DB->query($query) or die("0.65 add text_login in config" . $LANG['update'][90] . $DB->error());
    }
    if (!FieldExists("glpi_config", "auto_update_check")) {
        $query = "ALTER TABLE `glpi_config` ADD `auto_update_check` SMALLINT DEFAULT '0' NOT NULL ,\n\t\t\tADD `last_update_check` DATE DEFAULT '" . date("Y-m-d") . "' NOT NULL, ADD `founded_new_version` VARCHAR( 10 ) NOT NULL ;";
        $DB->query($query) or die("0.65 add auto_login_check in config" . $LANG['update'][90] . $DB->error());
    }
    //// Tracking
    if (FieldExists("glpi_tracking", "status")) {
        $already_done = false;
        if ($result = $DB->query("show fields from glpi_tracking")) {
            while ($data = $DB->fetch_array($result)) {
                if ($data["Field"] == "status" && strstr($data["Type"], "done")) {
                    $already_done = true;
                }
            }
        }
        if (!$already_done) {
            $query = "ALTER TABLE `glpi_tracking` CHANGE `status` `status` ENUM( 'new', 'old', 'old_done', 'assign', 'plan', 'old_notdone', 'waiting' ) DEFAULT 'new' NOT NULL ;";
            $DB->query($query) or die("0.65 alter status in tracking" . $LANG['update'][90] . $DB->error());
            $query2 = " UPDATE `glpi_tracking` SET status='old_done' WHERE status <> 'new';";
            $DB->query($query2) or die("0.65 update status=old in tracking" . $LANG['update'][90] . $DB->error());
            $query3 = " UPDATE `glpi_tracking` SET status='assign' WHERE status='new' AND assign <> '0';";
            $DB->query($query3) or die("0.65 update status=assign in tracking" . $LANG['update'][90] . $DB->error());
            $query4 = "ALTER TABLE `glpi_tracking` CHANGE `status` `status` ENUM( 'new', 'old_done', 'assign', 'plan', 'old_notdone', 'waiting' ) DEFAULT 'new' NOT NULL ;";
            $DB->query($query4) or die("0.65 alter status in tracking" . $LANG['update'][90] . $DB->error());
        }
    }
    if (!isIndex("glpi_tracking_planning", "id_assign")) {
        $query = "ALTER TABLE `glpi_tracking_planning` ADD INDEX ( `id_assign` ) ;";
        $DB->query($query) or die("0.65 add index for id_assign in tracking_planning" . $LANG['update'][90] . $DB->error());
    }
    if (FieldExists("glpi_tracking", "emailupdates")) {
        $query2 = " UPDATE `glpi_tracking` SET `emailupdates`='no' WHERE `emailupdates`='';";
        $DB->query($query2) or die("0.65 update emailupdate='' in tracking" . $LANG['update'][90] . $DB->error());
        $query = "ALTER TABLE `glpi_tracking` CHANGE `emailupdates` `emailupdates` ENUM( 'yes', 'no' ) DEFAULT 'no' NOT NULL;";
        $DB->query($query) or die("0.65 alter emailupdates in tracking" . $LANG['update'][90] . $DB->error());
    }
    if (!FieldExists("glpi_followups", "private")) {
        $query = "ALTER TABLE `glpi_followups` ADD `private` INT( 1 ) DEFAULT '0' NOT NULL;";
        $DB->query($query) or die("0.65 add private in followups" . $LANG['update'][90] . $DB->error());
    }
    if (!FieldExists("glpi_followups", "realtime")) {
        $query = "ALTER TABLE `glpi_followups` ADD `realtime` FLOAT DEFAULT '0' NOT NULL ;";
        $DB->query($query) or die("0.65 add realtime in followups" . $LANG['update'][90] . $DB->error());
    }
    if (!FieldExists("glpi_config", "mailing_attrib_attrib")) {
        $query = "ALTER TABLE `glpi_config` ADD `mailing_attrib_attrib` tinyint(4) NOT NULL DEFAULT '1' AFTER `mailing_finish_user` ;";
        $DB->query($query) or die("0.65 add mailing_attrib_attrib in config" . $LANG['update'][90] . $DB->error());
    }
    if (!FieldExists("glpi_tracking_planning", "id_followup")) {
        $query = "ALTER TABLE `glpi_tracking_planning` ADD `id_followup` INT DEFAULT '0' NOT NULL AFTER `id_tracking` ;";
        $DB->query($query) or die("0.65 add id_followup in tracking_planning" . $LANG['update'][90] . $DB->error());
        $query = " ALTER TABLE `glpi_tracking_planning` ADD INDEX ( `id_followup` );";
        $DB->query($query) or die("0.65 add index for id_followup in tracking_planning" . $LANG['update'][90] . $DB->error());
        //// Move Planned item to followup
        // Get super-admin ID
        $suid = 0;
        $query0 = "SELECT ID from glpi_users WHERE type='super-admin'";
        $result0 = $DB->query($query0);
        if ($DB->numrows($result0) > 0) {
            $suid = $DB->result($result0, 0, 0);
        }
        $DB->free_result($result0);
        $query = "SELECT * FROM glpi_tracking_planning order by id_tracking";
        $result = $DB->query($query);
        $used_followups = array();
        if ($DB->numrows($result) > 0) {
            while ($data = $DB->fetch_array($result)) {
                $found = -1;
                // Is a followup existing ?
                $query2 = "SELECT * FROM glpi_followups WHERE tracking='" . $data["id_tracking"] . "'";
                $result2 = $DB->query($query2);
                if ($DB->numrows($result2) > 0) {
                    while ($found < 0 && ($data2 = $DB->fetch_array($result2))) {
                        if (!in_array($data2['ID'], $used_followups)) {
                            $found = $data2['ID'];
                        }
                    }
                }
                $DB->free_result($result2);
                // Followup not founded
                if ($found < 0) {
                    $query3 = "INSERT INTO glpi_followups (tracking,date,author,contents) VALUES ('" . $data["id_tracking"] . "','" . date("Y-m-d") . "','{$suid}','Automatic Added followup for compatibility problem in update')";
                    $DB->query($query3);
                    $found = $DB->insert_id();
                }
                array_push($used_followups, $found);
                $query4 = "UPDATE glpi_tracking_planning SET id_followup='{$found}' WHERE ID ='" . $data['ID'] . "';";
                $DB->query($query4);
            }
        }
        unset($used_followups);
        $DB->free_result($result);
        $query = " ALTER TABLE `glpi_tracking_planning` DROP `id_tracking` ;";
        $DB->query($query) or die("0.65 add index for id_followup in tracking_planning" . $LANG['update'][90] . $DB->error());
    }
    if (!FieldExists("glpi_config", "use_ajax")) {
        $query = "ALTER TABLE `glpi_config` ADD `dropdown_max` INT DEFAULT '100' NOT NULL ,\n\t\t\tADD `ajax_wildcard` CHAR( 1 ) DEFAULT '*' NOT NULL ,\n\t\t\tADD `use_ajax` SMALLINT DEFAULT '0' NOT NULL ,\n\t\t\tADD `ajax_limit_count` INT DEFAULT '50' NOT NULL ; ";
        $DB->query($query) or die("0.65 add ajax fields in config" . $LANG['update'][90] . $DB->error());
    }
    if (!FieldExists("glpi_config", "ajax_autocompletion")) {
        $query = "ALTER TABLE `glpi_config` ADD `ajax_autocompletion` SMALLINT DEFAULT '1' NOT NULL ;";
        $DB->query($query) or die("0.65 add ajax_autocompletion field in config" . $LANG['update'][90] . $DB->error());
    }
    if (!FieldExists("glpi_config", "auto_add_users")) {
        $query = "ALTER TABLE `glpi_config` ADD `auto_add_users` SMALLINT DEFAULT '1' NOT NULL ;";
        $DB->query($query) or die("0.65 add auto_add_users field in config" . $LANG['update'][90] . $DB->error());
    }
    if (!FieldExists("glpi_config", "dateformat")) {
        $query = "ALTER TABLE `glpi_config` ADD `dateformat` SMALLINT DEFAULT '0' NOT NULL ;";
        $DB->query($query) or die("0.65 add dateformat field in config" . $LANG['update'][90] . $DB->error());
    }
    if (FieldExists("glpi_software", "version")) {
        $query = " ALTER TABLE `glpi_software` CHANGE `version` `version` VARCHAR( 200 ) NOT NULL;";
        $DB->query($query) or die("0.65 alter version field in software" . $LANG['update'][90] . $DB->error());
    }
    if (!FieldExists("glpi_config", "nextprev_item")) {
        $query = "ALTER TABLE `glpi_config` ADD `nextprev_item` VARCHAR( 200 ) DEFAULT 'name' NOT NULL ;";
        $DB->query($query) or die("0.65 add nextprev_item field in config" . $LANG['update'][90] . $DB->error());
    }
    if (!FieldExists("glpi_config", "view_ID")) {
        $query = "ALTER TABLE `glpi_config` ADD `view_ID` SMALLINT DEFAULT '0' NOT NULL ;";
        $DB->query($query) or die("0.65 add nextprev_item field in config" . $LANG['update'][90] . $DB->error());
    }
    if (FieldExists("glpi_infocoms", "comments")) {
        $query = " ALTER TABLE `glpi_infocoms` CHANGE `comments` `comments` TEXT";
        $DB->query($query) or die("0.65 alter comments in glpi_infocoms" . $LANG['update'][90] . $DB->error());
    }
    $new_model = array("monitors", "networking", "peripherals", "printers");
    foreach ($new_model as $model) {
        if (!TableExists("glpi_dropdown_model_{$model}")) {
            // model=type pour faciliter la gestion en post mise �jour : ya plus qu'a deleter les elements non voulu
            // cela conviendra a tout le monde en fonction de l'utilisation du champ type
            $query = "CREATE TABLE `glpi_dropdown_model_{$model}` (\n\t\t\t\t`ID` int(11) NOT NULL auto_increment,\n\t\t\t\t`name` varchar(255) NOT NULL default '',\n\t\t\t\tPRIMARY KEY  (`ID`)\n\t\t\t\t\t) TYPE=MyISAM;";
            $DB->query($query) or die("0.6 add table glpi_dropdown_model_{$model} " . $LANG['update'][90] . $DB->error());
            // copie type dans model
            $query = "SELECT * FROM glpi_type_{$model}";
            $result = $DB->query($query);
            if ($DB->numrows($result) > 0) {
                while ($data = $DB->fetch_array($result)) {
                    $query = "INSERT INTO `glpi_dropdown_model_{$model}` (`ID`,`name`) VALUES ('" . $data['ID'] . "','" . addslashes($data['name']) . "');";
                    $DB->query($query) or die("0.6 insert value in glpi_dropdown_model_{$model} " . $LANG['update'][90] . $DB->error());
                }
            }
            $DB->free_result($result);
        }
        if (!FieldExists("glpi_{$model}", "model")) {
            $query = "ALTER TABLE `glpi_{$model}` ADD `model` INT(11) DEFAULT NULL AFTER `type` ;";
            $DB->query($query) or die("0.6 add model in {$model}" . $LANG['update'][90] . $DB->error());
            $query = "UPDATE `glpi_{$model}` SET `model` = `type` ";
            $DB->query($query) or die("0.6 add model in {$model}" . $LANG['update'][90] . $DB->error());
        }
    }
    // Update pour les cartouches compatibles : type -> model
    if (FieldExists("glpi_cartridges_assoc", "FK_glpi_type_printer")) {
        $query = " ALTER TABLE `glpi_cartridges_assoc` CHANGE `FK_glpi_type_printer` `FK_glpi_dropdown_model_printers` INT( 11 ) DEFAULT '0' NOT NULL ";
        $DB->query($query) or die("0.65 alter FK_glpi_type_printer field in cartridges_assoc " . $LANG['update'][90] . $DB->error());
    }
    if (!FieldExists("glpi_links", "data")) {
        $query = " ALTER TABLE `glpi_links` ADD `data` TEXT NOT NULL ;";
        $DB->query($query) or die("0.65 create data in links " . $LANG['update'][90] . $DB->error());
    }
    if (!TableExists("glpi_dropdown_auto_update")) {
        $query = "CREATE TABLE `glpi_dropdown_auto_update` (\n\t\t\t`ID` int(11) NOT NULL auto_increment,\n\t\t\t`name` varchar(255) NOT NULL default '',\n\t\t\tPRIMARY KEY  (`ID`)\n\t\t\t\t) TYPE=MyISAM;";
        $DB->query($query) or die("0.65 add table glpi_dropdown_auto_update " . $LANG['update'][90] . $DB->error());
    }
    if (!FieldExists("glpi_computers", "auto_update")) {
        $query = "ALTER TABLE `glpi_computers` ADD `auto_update` INT DEFAULT '0' NOT NULL AFTER `os` ;";
        $DB->query($query) or die("0.65 alter computers add auto_update " . $LANG['update'][90] . $DB->error());
    }
    // Update specificity of computer_device
    $query = "SELECT glpi_computer_device.ID as ID,glpi_device_processor.specif_default as SPECIF FROM glpi_computer_device LEFT JOIN glpi_device_processor ON (glpi_computer_device.FK_device=glpi_device_processor.ID AND glpi_computer_device.device_type='" . PROCESSOR_DEVICE . "') WHERE glpi_computer_device.specificity =''";
    $result = $DB->query($query);
    if ($DB->numrows($result) > 0) {
        while ($data = $DB->fetch_assoc($result)) {
            $query2 = "UPDATE glpi_computer_device SET specificity='" . $data["SPECIF"] . "' WHERE ID = '" . $data["ID"] . "'";
            $DB->query($query2);
        }
    }
    $query = "SELECT glpi_computer_device.ID as ID,glpi_device_processor.specif_default as SPECIF FROM glpi_computer_device LEFT JOIN glpi_device_processor ON (glpi_computer_device.FK_device=glpi_device_processor.ID AND glpi_computer_device.device_type='" . PROCESSOR_DEVICE . "') WHERE glpi_computer_device.specificity =''";
    $result = $DB->query($query);
    if ($DB->numrows($result) > 0) {
        while ($data = $DB->fetch_assoc($result)) {
            $query2 = "UPDATE glpi_computer_device SET specificity='" . $data["SPECIF"] . "' WHERE ID = '" . $data["ID"] . "'";
            $DB->query($query2);
        }
    }
    $query = "SELECT glpi_computer_device.ID as ID,glpi_device_ram.specif_default as SPECIF FROM glpi_computer_device LEFT JOIN glpi_device_ram ON (glpi_computer_device.FK_device=glpi_device_ram.ID AND glpi_computer_device.device_type='" . RAM_DEVICE . "') WHERE glpi_computer_device.specificity =''";
    $result = $DB->query($query);
    if ($DB->numrows($result) > 0) {
        while ($data = $DB->fetch_assoc($result)) {
            $query2 = "UPDATE glpi_computer_device SET specificity='" . $data["SPECIF"] . "' WHERE ID = '" . $data["ID"] . "'";
            $DB->query($query2);
        }
    }
    $query = "SELECT glpi_computer_device.ID as ID,glpi_device_hdd.specif_default as SPECIF FROM glpi_computer_device LEFT JOIN glpi_device_hdd ON (glpi_computer_device.FK_device=glpi_device_hdd.ID AND glpi_computer_device.device_type='" . HDD_DEVICE . "') WHERE glpi_computer_device.specificity =''";
    $result = $DB->query($query);
    if ($DB->numrows($result) > 0) {
        while ($data = $DB->fetch_assoc($result)) {
            $query2 = "UPDATE glpi_computer_device SET specificity='" . $data["SPECIF"] . "' WHERE ID = '" . $data["ID"] . "'";
            $DB->query($query2);
        }
    }
    $query = "SELECT glpi_computer_device.ID as ID,glpi_device_iface.specif_default as SPECIF FROM glpi_computer_device LEFT JOIN glpi_device_iface ON (glpi_computer_device.FK_device=glpi_device_iface.ID AND glpi_computer_device.device_type='" . NETWORK_DEVICE . "') WHERE glpi_computer_device.specificity =''";
    $result = $DB->query($query);
    if ($DB->numrows($result) > 0) {
        while ($data = $DB->fetch_assoc($result)) {
            $query2 = "UPDATE glpi_computer_device SET specificity='" . $data["SPECIF"] . "' WHERE ID = '" . $data["ID"] . "'";
            $DB->query($query2);
        }
    }
    // add field notes in tables
    $new_notes = array("computers", "software", "monitors", "networking", "peripherals", "printers", "cartridges_type", "consumables_type", "contacts", "enterprises", "contracts", "docs");
    foreach ($new_notes as $notes) {
        if (!FieldExists("glpi_{$notes}", "notes")) {
            $query = "ALTER TABLE `glpi_{$notes}` ADD   `notes` LONGTEXT NULL ;";
            $DB->query($query) or die("0.65 add notes field in table" . $LANG['update'][90] . $DB->error());
        }
    }
    if (!FieldExists("glpi_users", "active")) {
        $query = "ALTER TABLE `glpi_users` ADD `active` INT( 2 ) DEFAULT '1' NOT NULL ";
        $DB->query($query) or die("0.65 add active in users " . $LANG['update'][90] . $DB->error());
    }
    if (TableExists("glpi_type_docs")) {
        $query = "SELECT * from glpi_type_docs WHERE ext='odt' OR ext='ods' OR ext='odp' OR ext='otp' OR ext='ott' OR ext='ots' OR ext='odf' OR ext='odg' OR ext='otg' OR ext='odb' OR ext='oth' OR ext='odm' OR ext='odc' OR ext='odi'";
        $result = $DB->query($query);
        if ($DB->numrows($result) == 0) {
            $query2 = "INSERT INTO `glpi_type_docs` ( `name` , `ext` , `icon` , `mime` , `upload` , `date_mod` ) VALUES ('Oasis Open Office Writer', 'odt', 'odt-dist.png', '', 'Y', '2006-01-21 17:41:13'),\n\t\t\t\t( 'Oasis Open Office Calc', 'ods', 'ods-dist.png', '', 'Y', '2006-01-21 17:41:31'),\n\t\t\t\t('Oasis Open Office Impress', 'odp', 'odp-dist.png', '', 'Y', '2006-01-21 17:42:54'),\n\t\t\t\t('Oasis Open Office Impress Template', 'otp', 'odp-dist.png', '', 'Y', '2006-01-21 17:43:58'),\n\t\t\t\t('Oasis Open Office Writer Template', 'ott', 'odt-dist.png', '', 'Y', '2006-01-21 17:44:41'),\n\t\t\t\t('Oasis Open Office Calc Template', 'ots', 'ods-dist.png', '', 'Y', '2006-01-21 17:45:30'),\n\t\t\t\t('Oasis Open Office Math', 'odf', 'odf-dist.png', '', 'Y', '2006-01-21 17:48:05'),\n\t\t\t\t('Oasis Open Office Draw', 'odg', 'odg-dist.png', '', 'Y', '2006-01-21 17:48:31'),\n\t\t\t\t('Oasis Open Office Draw Template', 'otg', 'odg-dist.png', '', 'Y', '2006-01-21 17:49:46'),\n\t\t\t\t('Oasis Open Office Base', 'odb', 'odb-dist.png', '', 'Y', '2006-01-21 18:03:34'),\n\t\t\t\t('Oasis Open Office HTML', 'oth', 'oth-dist.png', '', 'Y', '2006-01-21 18:05:27'),\n\t\t\t\t('Oasis Open Office Writer Master', 'odm', 'odm-dist.png', '', 'Y', '2006-01-21 18:06:34'),\n\t\t\t\t('Oasis Open Office Chart', 'odc', NULL, '', 'Y', '2006-01-21 18:07:48'),\n\t\t\t\t('Oasis Open Office Image', 'odi', NULL, '', 'Y', '2006-01-21 18:08:18');";
            $DB->query($query2) or die("0.65 add new type docs " . $LANG['update'][90] . $DB->error());
        }
    }
    ///// BEGIN  MySQL Compatibility
    if (FieldExists("glpi_infocoms", "warranty_value")) {
        $query2 = " UPDATE `glpi_infocoms` SET `warranty_value`='0' WHERE `warranty_value` IS NULL;";
        $DB->query($query2) or die("0.65 update warranty_value='' in tracking" . $LANG['update'][90] . $DB->error());
        $query = "ALTER TABLE `glpi_infocoms` CHANGE `warranty_info` `warranty_info` VARCHAR( 255 ) NULL DEFAULT NULL,\n\t\t\tCHANGE `warranty_value` `warranty_value` FLOAT NOT NULL DEFAULT '0',\n\t\t\tCHANGE `num_commande` `num_commande` VARCHAR( 200 ) NULL DEFAULT NULL,\n\t\t\tCHANGE `bon_livraison` `bon_livraison` VARCHAR( 200 ) NULL DEFAULT NULL,\n\t\t\tCHANGE `facture` `facture` VARCHAR( 200 ) NULL DEFAULT NULL,\n\t\t\tCHANGE `num_immo` `num_immo` VARCHAR( 200 ) NULL DEFAULT NULL;";
        $DB->query($query) or die("0.65 alter various fields in infocoms " . $LANG['update'][90] . $DB->error());
    }
    if (FieldExists("glpi_reservation_item", "comments")) {
        $query = "ALTER TABLE `glpi_reservation_item` CHANGE `comments` `comments` TEXT NULL ";
        $DB->query($query) or die("0.65 alter comments in glpi_reservation_item " . $LANG['update'][90] . $DB->error());
    }
    if (FieldExists("glpi_cartridges_type", "comments")) {
        $query = "ALTER TABLE `glpi_cartridges_type` CHANGE `name` `name` VARCHAR( 255 ) NULL DEFAULT NULL,\n\t\t\tCHANGE `ref` `ref` VARCHAR( 255 ) NULL DEFAULT NULL ,\n\t\t\tCHANGE `comments` `comments` TEXT NULL DEFAULT NULL ";
        $DB->query($query) or die("0.65 alter various fields in cartridges_type " . $LANG['update'][90] . $DB->error());
    }
    if (FieldExists("glpi_computer_device", "specificity")) {
        $query = "ALTER TABLE `glpi_computer_device` CHANGE `specificity` `specificity` VARCHAR( 250 ) NULL ";
        $DB->query($query) or die("0.65 alter specificity in glpi_computer_device " . $LANG['update'][90] . $DB->error());
    }
    $inv_table = array("computers", "monitors", "networking", "peripherals", "printers");
    foreach ($inv_table as $table) {
        if (FieldExists("glpi_{$table}", "comments")) {
            $query = "UPDATE glpi_{$table} SET location='0' WHERE location IS NULL;";
            $DB->query($query) or die("0.65 prepare data fro alter various fields in {$table} " . $LANG['update'][90] . $DB->error());
            $query = "ALTER TABLE `glpi_{$table}` CHANGE `name` `name` VARCHAR( 200 ) NULL ,\n\t\t\t\tCHANGE `serial` `serial` VARCHAR( 200 ) NULL ,\n\t\t\t\tCHANGE `otherserial` `otherserial` VARCHAR( 200 ) NULL ,\n\t\t\t\tCHANGE `contact` `contact` VARCHAR( 200 ) NULL ,\n\t\t\t\tCHANGE `contact_num` `contact_num` VARCHAR( 200 ) NULL ,\n\t\t\t\tCHANGE `location` `location` INT( 11 ) NOT NULL DEFAULT '0',\n\t\t\t\tCHANGE `comments` `comments` TEXT NULL ";
            $DB->query($query) or die("0.65 alter various fields in {$table} " . $LANG['update'][90] . $DB->error());
        }
    }
    if (FieldExists("glpi_computers", "os")) {
        $query = "UPDATE glpi_computers SET model='0' WHERE model IS NULL;";
        $DB->query($query) or die("0.65 prepare model for alter computers " . $LANG['update'][90] . $DB->error());
        $query = "UPDATE glpi_computers SET type='0' WHERE type IS NULL;";
        $DB->query($query) or die("0.65 prepare type for alter computers " . $LANG['update'][90] . $DB->error());
        $query = "ALTER TABLE `glpi_computers` CHANGE `os` `os` INT( 11 ) NOT NULL DEFAULT '0',\n\t\t\tCHANGE `model` `model` INT( 11 ) NOT NULL DEFAULT '0',\n\t\t\tCHANGE `type` `type` INT( 11 ) NOT NULL DEFAULT '0'";
        $DB->query($query) or die("0.65 alter various fields in computers " . $LANG['update'][90] . $DB->error());
    }
    if (FieldExists("glpi_networking", "ram")) {
        $query = "ALTER TABLE `glpi_networking` CHANGE `ram` `ram` VARCHAR( 200 ) NULL ,\n\t\t\tCHANGE `ifmac` `ifmac` VARCHAR( 200 ) NULL ,\n\t\t\tCHANGE `ifaddr` `ifaddr` VARCHAR( 200 ) NULL";
        $DB->query($query) or die("0.65 alter 2 various fields in networking " . $LANG['update'][90] . $DB->error());
    }
    if (FieldExists("glpi_peripherals", "brand")) {
        $query = "ALTER TABLE `glpi_peripherals` CHANGE `brand` `brand` VARCHAR( 200 ) NULL ";
        $DB->query($query) or die("0.65 alter 2 various fields in peripherals " . $LANG['update'][90] . $DB->error());
    }
    if (FieldExists("glpi_printers", "ramSize")) {
        $query = "ALTER TABLE `glpi_printers` CHANGE `ramSize` `ramSize` VARCHAR( 200 ) NULL ";
        $DB->query($query) or die("0.65 alter 2 various fields in printers " . $LANG['update'][90] . $DB->error());
    }
    if (FieldExists("glpi_consumables_type", "comments")) {
        $query = "ALTER TABLE `glpi_consumables_type` CHANGE `name` `name` VARCHAR( 255 ) NULL ,\n\t\t\tCHANGE `ref` `ref` VARCHAR( 255 ) NULL ,\n\t\t\tCHANGE `comments` `comments` TEXT NULL  ";
        $DB->query($query) or die("0.65 alter various fields in consumables_type " . $LANG['update'][90] . $DB->error());
    }
    if (FieldExists("glpi_contacts", "comments")) {
        $query = "ALTER TABLE `glpi_contacts` CHANGE `name` `name` VARCHAR( 255 ) NULL ,\n\t\t\tCHANGE `phone` `phone` VARCHAR( 200 ) NULL ,\n\t\t\tCHANGE `phone2` `phone2` VARCHAR( 200 ) NULL ,\n\t\t\tCHANGE `fax` `fax` VARCHAR( 200 ) NULL ,\n\t\t\tCHANGE `email` `email` VARCHAR( 255 ) NULL ,\n\t\t\tCHANGE `comments` `comments` TEXT NULL  ";
        $DB->query($query) or die("0.65 alter various fields in contacts " . $LANG['update'][90] . $DB->error());
    }
    if (FieldExists("glpi_contracts", "comments")) {
        $query = "ALTER TABLE `glpi_contracts` CHANGE `name` `name` VARCHAR( 255 ) NULL ,\n\t\t\tCHANGE `num` `num` VARCHAR( 255 ) NULL ,\n\t\t\tCHANGE `comments` `comments` TEXT NULL ,\n\t\t\tCHANGE `compta_num` `compta_num` VARCHAR( 255 ) NULL ";
        $DB->query($query) or die("0.65 alter various fields in contracts " . $LANG['update'][90] . $DB->error());
    }
    $device = array("case", "control", "drive", "gfxcard", "hdd", "iface", "moboard", "pci", "power", "processor", "ram", "sndcard");
    foreach ($device as $dev) {
        if (FieldExists("glpi_device_{$dev}", "comment")) {
            $query = "ALTER TABLE `glpi_device_{$dev}` CHANGE `designation` `designation` VARCHAR( 255 ) NULL ,\n\t\t\t\tCHANGE `comment` `comment` TEXT NULL ,\n\t\t\t\tCHANGE `specif_default` `specif_default` VARCHAR( 250 ) NULL ";
            $DB->query($query) or die("0.65 alter various fields in device_{$dev} " . $LANG['update'][90] . $DB->error());
        }
        if (!isIndex("glpi_device_{$dev}", "designation")) {
            $query = "ALTER TABLE `glpi_device_{$dev}` ADD INDEX ( `designation` ); ";
            $DB->query($query) or die("0.65 alter various fields in device_{$dev} " . $LANG['update'][90] . $DB->error());
        }
    }
    if (FieldExists("glpi_docs", "comment")) {
        $query = "ALTER TABLE `glpi_docs` CHANGE `name` `name` VARCHAR( 255 ) NULL ,\n\t\t\tCHANGE `filename` `filename` VARCHAR( 255 ) NULL ,\n\t\t\tCHANGE `mime` `mime` VARCHAR( 30 ) NULL ,\n\t\t\tCHANGE `comment` `comment` TEXT NULL ,\n\t\t\tCHANGE `link` `link` VARCHAR( 255 ) NULL  ";
        $DB->query($query) or die("0.65 alter various fields in docs " . $LANG['update'][90] . $DB->error());
    }
    if (FieldExists("glpi_enterprises", "comments")) {
        $query = "ALTER TABLE `glpi_enterprises` CHANGE `name` `name` VARCHAR( 200 ) NULL ,\n\t\t\tCHANGE `address` `address` TEXT NULL ,\n\t\t\tCHANGE `website` `website` VARCHAR( 200 ) NULL ,\n\t\t\tCHANGE `phonenumber` `phonenumber` VARCHAR( 200 ) NULL ,\n\t\t\tCHANGE `comments` `comments` TEXT NULL ,\n\t\t\tCHANGE `fax` `fax` VARCHAR( 255 ) NULL ,\n\t\t\tCHANGE `email` `email` VARCHAR( 255 ) NULL  ";
        $DB->query($query) or die("0.65 alter various fields in enterprises " . $LANG['update'][90] . $DB->error());
    }
    if (FieldExists("glpi_event_log", "message")) {
        $query = "ALTER TABLE `glpi_event_log` CHANGE `itemtype` `itemtype` VARCHAR( 200 ) NULL ,\n\t\t\tCHANGE `service` `service` VARCHAR( 200 ) NULL ,\n\t\t\tCHANGE `message` `message` TEXT NULL   ";
        $DB->query($query) or die("0.65 alter various fields in event_log " . $LANG['update'][90] . $DB->error());
    }
    if (FieldExists("glpi_kbitems", "question")) {
        $query = "ALTER TABLE `glpi_kbitems` CHANGE `question` `question` TEXT NULL ,\n\t\t\tCHANGE `answer` `answer` TEXT NULL ";
        $DB->query($query) or die("0.65 alter various fields in kbitems " . $LANG['update'][90] . $DB->error());
    }
    if (FieldExists("glpi_licenses", "serial")) {
        $query = "ALTER TABLE `glpi_licenses` CHANGE `serial` `serial` VARCHAR( 255 ) NULL";
        $DB->query($query) or die("0.65 alter serial in licenses " . $LANG['update'][90] . $DB->error());
    }
    if (FieldExists("glpi_links", "data")) {
        $query = "ALTER TABLE `glpi_links` CHANGE `name` `name` VARCHAR( 255 ) NULL ,\n\t\t\tCHANGE `data` `data` TEXT NULL";
        $DB->query($query) or die("0.65 alter various fields in links " . $LANG['update'][90] . $DB->error());
    }
    if (FieldExists("glpi_networking_ports", "ifmac")) {
        $query = "ALTER TABLE `glpi_networking_ports` CHANGE `name` `name` CHAR( 200 ) NULL ,\n\t\t\tCHANGE `ifaddr` `ifaddr` CHAR( 200 ) NULL ,\n\t\t\tCHANGE `ifmac` `ifmac` CHAR( 200 ) NULL";
        $DB->query($query) or die("0.65 alter various fields in networking_ports " . $LANG['update'][90] . $DB->error());
    }
    if (FieldExists("glpi_reservation_resa", "comment")) {
        $query = "ALTER TABLE `glpi_reservation_resa` CHANGE `comment` `comment` TEXT NULL";
        $DB->query($query) or die("0.65 alter comment in reservation_resa " . $LANG['update'][90] . $DB->error());
    }
    if (FieldExists("glpi_software", "version")) {
        $query = "ALTER TABLE `glpi_software` CHANGE `name` `name` VARCHAR( 200 ) NULL ,\n\t\t\tCHANGE `version` `version` VARCHAR( 200 ) NULL ";
        $DB->query($query) or die("0.65 alter various fields in software " . $LANG['update'][90] . $DB->error());
    }
    if (FieldExists("glpi_type_docs", "name")) {
        $query = "ALTER TABLE `glpi_type_docs` CHANGE `name` `name` VARCHAR( 255 ) NULL ,\n\t\t\tCHANGE `ext` `ext` VARCHAR( 10 ) NULL ,\n\t\t\tCHANGE `icon` `icon` VARCHAR( 255 ) NULL ,\n\t\t\tCHANGE `mime` `mime` VARCHAR( 100 ) NULL ";
        $DB->query($query) or die("0.65 alter various fields in type_docs " . $LANG['update'][90] . $DB->error());
    }
    if (FieldExists("glpi_users", "language")) {
        $query = "ALTER TABLE `glpi_users` CHANGE `name` `name` VARCHAR( 80 ) NULL ,\n\t\t\tCHANGE `password` `password` VARCHAR( 80 ) NULL ,\n\t\t\tCHANGE `password_md5` `password_md5` VARCHAR( 80 ) NULL ,\n\t\t\tCHANGE `email` `email` VARCHAR( 200 ) NULL ,\n\t\t\tCHANGE `realname` `realname` VARCHAR( 255 ) NULL ,\n\t\t\tCHANGE `language` `language` VARCHAR( 255 ) NULL  ";
        $DB->query($query) or die("0.65 alter various fields in users " . $LANG['update'][90] . $DB->error());
    }
    if (FieldExists("glpi_config", "cut")) {
        $query = "ALTER TABLE `glpi_config` CHANGE `num_of_events` `num_of_events` VARCHAR( 200 ) NULL ,\n\t\t\tCHANGE `jobs_at_login` `jobs_at_login` VARCHAR( 200 ) NULL ,\n\t\t\tCHANGE `sendexpire` `sendexpire` VARCHAR( 200 ) NULL ,\n\t\t\tCHANGE `cut` `cut` VARCHAR( 200 ) NULL ,\n\t\t\tCHANGE `expire_events` `expire_events` VARCHAR( 200 ) NULL ,\n\t\t\tCHANGE `list_limit` `list_limit` VARCHAR( 200 ) NULL ,\n\t\t\tCHANGE `version` `version` VARCHAR( 200 ) NULL ,\n\t\t\tCHANGE `logotxt` `logotxt` VARCHAR( 200 ) NULL ,\n\t\t\tCHANGE `root_doc` `root_doc` VARCHAR( 200 ) NULL ,\n\t\t\tCHANGE `event_loglevel` `event_loglevel` VARCHAR( 200 ) NULL ,\n\t\t\tCHANGE `mailing` `mailing` VARCHAR( 200 ) NULL ,\n\t\t\tCHANGE `imap_auth_server` `imap_auth_server` VARCHAR( 200 ) NULL ,\n\t\t\tCHANGE `imap_host` `imap_host` VARCHAR( 200 ) NULL ,\n\t\t\tCHANGE `ldap_host` `ldap_host` VARCHAR( 200 ) NULL ,\n\t\t\tCHANGE `ldap_basedn` `ldap_basedn` VARCHAR( 200 ) NULL ,\n\t\t\tCHANGE `ldap_rootdn` `ldap_rootdn` VARCHAR( 200 ) NULL ,\n\t\t\tCHANGE `ldap_pass` `ldap_pass` VARCHAR( 200 ) NULL ,\n\t\t\tCHANGE `admin_email` `admin_email` VARCHAR( 200 ) NULL ,\n\t\t\tCHANGE `mailing_signature` `mailing_signature` VARCHAR( 200 ) NOT NULL DEFAULT '--' ,\n\t\t\tCHANGE `mailing_new_admin` `mailing_new_admin` tinyint(4) NOT NULL DEFAULT '1' ,\n\t\t\tCHANGE `mailing_followup_admin` `mailing_followup_admin` tinyint(4) NOT NULL DEFAULT '1' ,\n\t\t\tCHANGE `mailing_finish_admin` `mailing_finish_admin` tinyint(4) NOT NULL DEFAULT '1' ,\n\t\t\tCHANGE `mailing_new_all_admin` `mailing_new_all_admin` tinyint(4) NOT NULL DEFAULT '0' ,\n\t\t\tCHANGE `mailing_followup_all_admin` `mailing_followup_all_admin` tinyint(4) NOT NULL DEFAULT '0' ,\n\t\t\tCHANGE `mailing_finish_all_admin` `mailing_finish_all_admin` tinyint(4) NOT NULL DEFAULT '0' ,\n\t\t\tCHANGE `mailing_new_all_normal` `mailing_new_all_normal` tinyint(4) NOT NULL DEFAULT '0' ,\n\t\t\tCHANGE `mailing_followup_all_normal` `mailing_followup_all_normal` tinyint(4) NOT NULL DEFAULT '0' ,\n\t\t\tCHANGE `mailing_finish_all_normal` `mailing_finish_all_normal` tinyint(4) NOT NULL DEFAULT '0' ,\n\t\t\tCHANGE `mailing_new_attrib` `mailing_new_attrib` tinyint(4) NOT NULL DEFAULT '1' ,\n\t\t\tCHANGE `mailing_followup_attrib` `mailing_followup_attrib` tinyint(4) NOT NULL DEFAULT '1' ,\n\t\t\tCHANGE `mailing_finish_attrib` `mailing_finish_attrib` tinyint(4) NOT NULL DEFAULT '1' ,\n\t\t\tCHANGE `mailing_new_user` `mailing_new_user` tinyint(4) NOT NULL DEFAULT '1' ,\n\t\t\tCHANGE `mailing_followup_user` `mailing_followup_user` tinyint(4) NOT NULL DEFAULT '1' ,\n\t\t\tCHANGE `mailing_finish_user` `mailing_finish_user` tinyint(4) NOT NULL DEFAULT '1' ,\n\t\t\tCHANGE `mailing_resa_all_admin` `mailing_resa_all_admin` tinyint(4) NOT NULL DEFAULT '0' ,\n\t\t\tCHANGE `mailing_resa_user` `mailing_resa_user` tinyint(4) NOT NULL DEFAULT '1' ,\n\t\t\tCHANGE `mailing_resa_admin` `mailing_resa_admin` tinyint(4) NOT NULL DEFAULT '1' ,\n\t\t\tCHANGE `ldap_field_name` `ldap_field_name` VARCHAR( 200 ) NULL ,\n\t\t\tCHANGE `ldap_field_email` `ldap_field_email` VARCHAR( 200 ) NULL ,\n\t\t\tCHANGE `ldap_field_location` `ldap_field_location` VARCHAR( 200 ) NULL ,\n\t\t\tCHANGE `ldap_field_realname` `ldap_field_realname` VARCHAR( 200 ) NULL ,\n\t\t\tCHANGE `ldap_field_phone` `ldap_field_phone` VARCHAR( 200 ) NULL ,\n\t\t\tCHANGE `ldap_condition` `ldap_condition` VARCHAR( 255 ) NULL ,\n\t\t\tCHANGE `permit_helpdesk` `permit_helpdesk` VARCHAR( 200 ) NULL ,\n\t\t\tCHANGE `cas_host` `cas_host` VARCHAR( 255 ) NULL ,\n\t\t\tCHANGE `cas_port` `cas_port` VARCHAR( 255 ) NULL ,\n\t\t\tCHANGE `cas_uri` `cas_uri` VARCHAR( 255 ) NULL ,\n\t\t\tCHANGE `url_base` `url_base` VARCHAR( 255 ) NULL ,\n\t\t\tCHANGE `text_login` `text_login` TEXT NULL ,\n\t\t\tCHANGE `founded_new_version` `founded_new_version` VARCHAR( 10 ) NULL ";
        $DB->query($query) or die("0.65 alter various fields in config " . $LANG['update'][90] . $DB->error());
    }
    ///// END  MySQL Compatibility
    if (!FieldExists("glpi_config", "dropdown_limit")) {
        $query = "ALTER TABLE `glpi_config` ADD `dropdown_limit` INT( 11 ) DEFAULT '50' NOT NULL ";
        $DB->query($query) or die("0.65 add dropdown_limit in config " . $LANG['update'][90] . $DB->error());
    }
    if (FieldExists("glpi_consumables_type", "type")) {
        $query = "ALTER TABLE `glpi_consumables_type` CHANGE `type` `type` INT( 11 ) NOT NULL DEFAULT '0',\n\t\t\tCHANGE `alarm` `alarm` INT( 11 ) NOT NULL DEFAULT '10'";
        $DB->query($query) or die("0.65 alter type and alarm in consumables_type " . $LANG['update'][90] . $DB->error());
    }
    if (!FieldExists("glpi_config", "post_only_followup")) {
        $query = "ALTER TABLE `glpi_config` ADD `post_only_followup` tinyint( 4 ) DEFAULT '1' NOT NULL ";
        $DB->query($query) or die("0.65 add dropdown_limit in config " . $LANG['update'][90] . $DB->error());
    }
    if (!FieldExists("glpi_monitors", "flags_dvi")) {
        $query = "ALTER TABLE `glpi_monitors` ADD `flags_dvi` tinyint( 4 ) DEFAULT '0' NOT NULL AFTER `flags_bnc`";
        $DB->query($query) or die("0.65 add dropdown_limit in config " . $LANG['update'][90] . $DB->error());
    }
    if (!TableExists("glpi_history")) {
        $query = "CREATE TABLE `glpi_history` (\n\t\t\t`ID` int(11) NOT NULL auto_increment,\n\t\t\t`FK_glpi_device` int(11) NOT NULL default '0',\n\t\t\t`device_type` tinyint(4) NOT NULL default '0',\n\t\t\t`device_internal_type` int(11) default '0',\n\t\t\t`device_internal_action` tinyint(4) default '0',\n\t\t\t`user_name` varchar(200) default NULL,\n\t\t\t`date_mod` datetime default NULL,\n\t\t\t`id_search_option` int(11) NOT NULL default '0',\n\t\t\t`old_value` varchar(255) default NULL,\n\t\t\t`new_value` varchar(255) default NULL,\n\t\t\tPRIMARY KEY  (`ID`),\n\t\t\tKEY `FK_glpi_device` (`FK_glpi_device`)\n\t\t\t\t) TYPE=MyISAM;";
        $DB->query($query) or die("0.65 add glpi_history table" . $LANG['update'][90] . $DB->error());
    }
    if (FieldExists("glpi_tracking", "assign_type")) {
        $query = "ALTER TABLE `glpi_tracking` ADD `assign_ent` INT NOT NULL DEFAULT '0' AFTER `assign` ";
        $DB->query($query) or die("0.65 add assign_ent in tracking " . $LANG['update'][90] . $DB->error());
        $query = "UPDATE `glpi_tracking` SET assign_ent=assign WHERE assign_type='" . ENTERPRISE_TYPE . "'";
        $DB->query($query) or die("0.65 update assign_ent in tracking " . $LANG['update'][90] . $DB->error());
        $query = "UPDATE `glpi_tracking` SET assign=0 WHERE assign_type='" . ENTERPRISE_TYPE . "'";
        $DB->query($query) or die("0.65 update assign_ent in tracking " . $LANG['update'][90] . $DB->error());
        $query = "ALTER TABLE `glpi_tracking` DROP `assign_type`";
        $DB->query($query) or die("0.65 drop assign_type in tracking " . $LANG['update'][90] . $DB->error());
    }
    if (!FieldExists("glpi_config", "mailing_update_admin")) {
        $query = "ALTER TABLE `glpi_config` ADD `mailing_update_admin` tinyint(4) NOT NULL DEFAULT '1' AFTER `mailing_new_admin` ;";
        $DB->query($query) or die("0.65 add mailing_update_admin in config" . $LANG['update'][90] . $DB->error());
    }
    if (!FieldExists("glpi_config", "mailing_update_all_admin")) {
        $query = "ALTER TABLE `glpi_config` ADD `mailing_update_all_admin` tinyint(4) NOT NULL DEFAULT '0' AFTER `mailing_new_all_admin` ;";
        $DB->query($query) or die("0.65 add mailing_update_all_admin in config" . $LANG['update'][90] . $DB->error());
    }
    if (!FieldExists("glpi_config", "mailing_update_all_normal")) {
        $query = "ALTER TABLE `glpi_config` ADD `mailing_update_all_normal` tinyint(4) NOT NULL DEFAULT '0' AFTER `mailing_new_all_normal` ;";
        $DB->query($query) or die("0.65 add mailing_update_all_normal in config" . $LANG['update'][90] . $DB->error());
    }
    if (!FieldExists("glpi_config", "mailing_update_attrib")) {
        $query = "ALTER TABLE `glpi_config` ADD `mailing_update_attrib` tinyint(4) NOT NULL DEFAULT '1' AFTER `mailing_new_attrib` ;";
        $DB->query($query) or die("0.65 add mailing_update_attrib in config" . $LANG['update'][90] . $DB->error());
    }
    if (!FieldExists("glpi_config", "mailing_update_user")) {
        $query = "ALTER TABLE `glpi_config` ADD `mailing_update_user` tinyint(4) NOT NULL DEFAULT '1' AFTER `mailing_new_user` ;";
        $DB->query($query) or die("0.65 add mailing_update_user in config" . $LANG['update'][90] . $DB->error());
    }
    if (!FieldExists("glpi_config", "ldap_use_tls")) {
        $query = "ALTER TABLE `glpi_config` ADD `ldap_use_tls` VARCHAR( 200 ) NOT NULL DEFAULT '0' AFTER `ldap_login` ";
        $DB->query($query) or die("0.65 add ldap_use_tls in config" . $LANG['update'][90] . $DB->error());
    }
    if (FieldExists("glpi_config", "cut")) {
        // juste pour affichage identique sur toutes les versions.
        $query = "UPDATE `glpi_config` SET `cut` = '255' WHERE `ID` =1";
        $DB->query($query) or die("0.65 update Cut in config" . $LANG['update'][90] . $DB->error());
    }
    if (!FieldExists("glpi_licenses", "comments")) {
        $query = "ALTER TABLE `glpi_licenses` ADD `comments` TEXT NULL ";
        $DB->query($query) or die("0.65 add comments in licenses" . $LANG['update'][90] . $DB->error());
    }
    ///////////// MODE OCS
    // Delete plugin table
    if (TableExists("glpi_ocs_link") && !FieldExists("glpi_ocs_link", "import_device")) {
        $query = "DROP TABLE `glpi_ocs_link`";
        $DB->query($query) or die("0.65 MODE OCS drop plugin ocs_link " . $LANG['update'][90] . $DB->error());
    }
    if (TableExists("glpi_ocs_config") && !FieldExists("glpi_ocs_config", "checksum")) {
        $query = "DROP TABLE `glpi_ocs_config`";
        $DB->query($query) or die("0.65 MODE OCS drop plugin ocs_config " . $LANG['update'][90] . $DB->error());
    }
    if (!TableExists("glpi_ocs_link")) {
        $query = "CREATE TABLE `glpi_ocs_link` (\n\t\t\t`ID` int(11) NOT NULL auto_increment,\n\t\t\t`glpi_id` int(11) NOT NULL default '0',\n\t\t\t`ocs_id` varchar(255) NOT NULL default '',\n\t\t\t`auto_update` int(2) NOT NULL default '1',\n\t\t\t`last_update` datetime NOT NULL default '0000-00-00 00:00:00',\n\t\t\t`computer_update` LONGTEXT NULL,\n\t\t\t`import_device` LONGTEXT NULL,\n\t\t\t`import_software` LONGTEXT NULL,\n\t\t\t`import_monitor` LONGTEXT NULL,\n\t\t\t`import_peripheral` LONGTEXT NULL,\n\t\t\t`import_printers` LONGTEXT NULL,\n\t\t\tPRIMARY KEY  (`ID`),\n\t\t\tUNIQUE KEY `ocs_id_2` (`ocs_id`),\n\t\t\tKEY `ocs_id` (`ocs_id`),\n\t\t\tKEY `glpi_id` (`glpi_id`),\n\t\t\tKEY `auto_update` (`auto_update`),\n\t\t\tKEY `last_update` (`last_update`)\n\t\t\t\t) TYPE=MyISAM";
        $DB->query($query) or die("0.65 MODE OCS creation ocs_link " . $LANG['update'][90] . $DB->error());
    }
    if (!TableExists("glpi_ocs_config")) {
        $query = "CREATE TABLE `glpi_ocs_config` (\n\t\t\t`ID` int(11) NOT NULL auto_increment,\n\t\t\t`ocs_db_user` varchar(255) NOT NULL default '',\n\t\t\t`ocs_db_passwd` varchar(255) NOT NULL default '',\n\t\t\t`ocs_db_host` varchar(255) NOT NULL default '',\n\t\t\t`ocs_db_name` varchar(255) NOT NULL default '',\n\t\t\t`checksum` int(11) NOT NULL default '0',\n\t\t\t`import_periph` int(2) NOT NULL default '0',\n\t\t\t`import_monitor` int(2) NOT NULL default '0',\n\t\t\t`import_software` int(2) NOT NULL default '0',\n\t\t\t`import_printer` int(2) NOT NULL default '0',\n\t\t\t`import_general_os` int(2) NOT NULL default '0',\n\t\t\t`import_general_serial` int(2) NOT NULL default '0',\n\t\t\t`import_general_model` int(2) NOT NULL default '0',\n\t\t\t`import_general_enterprise` int(2) NOT NULL default '0',\n\t\t\t`import_general_type` int(2) NOT NULL default '0',\n\t\t\t`import_general_domain` int(2) NOT NULL default '0',\n\t\t\t`import_general_contact` int(2) NOT NULL default '0',\n\t\t\t`import_general_comments` int(2) NOT NULL default '0',\n\t\t\t`import_device_processor` int(2) NOT NULL default '0',\n\t\t\t`import_device_memory` int(2) NOT NULL default '0',\n\t\t\t`import_device_hdd` int(2) NOT NULL default '0',\n\t\t\t`import_device_iface` int(2) NOT NULL default '0',\n\t\t\t`import_device_gfxcard` int(2) NOT NULL default '0',\n\t\t\t`import_device_sound` int(2) NOT NULL default '0',\n\t\t\t`import_device_drives` int(2) NOT NULL default '0',\n\t\t\t`import_device_ports` int(2) NOT NULL default '0',\n\t\t\t`import_device_modems` int(2) NOT NULL default '0',\n\t\t\t`import_ip` int(2) NOT NULL default '0',\n\t\t\t`default_state` int(11) NOT NULL default '0',\n\t\t\t`tag_limit` varchar(255) NOT NULL default '',\n\t\t\tPRIMARY KEY  (`ID`)\n\t\t\t\t) TYPE=MyISAM";
        $DB->query($query) or die("0.65 MODE OCS creation ocs_config " . $LANG['update'][90] . $DB->error());
        $query = "INSERT INTO `glpi_ocs_config` VALUES (1, 'ocs', 'ocs', 'localhost', 'ocsweb', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '');";
        $DB->query($query) or die("0.65 MODE OCS add default config " . $LANG['update'][90] . $DB->error());
    }
    if (!FieldExists("glpi_computers", "ocs_import")) {
        $query = "ALTER TABLE `glpi_computers` ADD `ocs_import` TINYINT NOT NULL DEFAULT '0'";
        $DB->query($query) or die("0.65 MODE OCS add default config " . $LANG['update'][90] . $DB->error());
    }
    if (!FieldExists("glpi_config", "ocs_mode")) {
        $query = "ALTER TABLE `glpi_config` ADD `ocs_mode` TINYINT NOT NULL DEFAULT '0' ";
        $DB->query($query) or die("0.65 MODE OCS add ocs_mode in config " . $LANG['update'][90] . $DB->error());
    }
    ///////////// FIN MODE OCS
    if (!TableExists("glpi_dropdown_budget")) {
        $query = "CREATE TABLE `glpi_dropdown_budget` (\n\t\t\t`ID` int(11) NOT NULL auto_increment,\n\t\t\t`name` varchar(255) NOT NULL DEFAULT '',\n\t\t\tPRIMARY KEY  (`ID`)\n\t\t\t\t) TYPE=MyISAM;";
        $DB->query($query) or die("0.65 add dropdown_budget " . $LANG['update'][90] . $DB->error());
    }
    if (!FieldExists("glpi_infocoms", "budget")) {
        $query = "ALTER TABLE `glpi_infocoms` ADD `budget` INT NULL DEFAULT '0';";
        $DB->query($query) or die("0.65 add budget in infocoms " . $LANG['update'][90] . $DB->error());
    }
    if (!FieldExists("glpi_tracking", "cost_time")) {
        $query = "ALTER TABLE `glpi_tracking` ADD `cost_time` FLOAT NOT NULL DEFAULT '0',\n\t\t\tADD `cost_fixed` FLOAT NOT NULL DEFAULT '0',\n\t\t\tADD `cost_material` FLOAT NOT NULL DEFAULT '0'";
        $DB->query($query) or die("0.65 add cost fields in tracking " . $LANG['update'][90] . $DB->error());
    }
    // Global Printers
    if (!FieldExists("glpi_printers", "is_global")) {
        $query = "ALTER TABLE `glpi_printers` ADD `is_global` ENUM('0', '1') DEFAULT '0' NOT NULL AFTER `FK_glpi_enterprise` ;";
        $DB->query($query) or die("0.6 add is_global in printers " . $LANG['update'][90] . $DB->error());
    }
    if (!FieldExists("glpi_config", "debug")) {
        $query = "ALTER TABLE `glpi_config` ADD `debug` int(2) NOT NULL default '0' ";
        $DB->query($query) or die("0.65 add debug in config " . $LANG['update'][90] . $DB->error());
    }
    if (!TableExists("glpi_dropdown_os_version")) {
        $query = "CREATE TABLE `glpi_dropdown_os_version` (\n\t\t\t`ID` int(11) NOT NULL auto_increment,\n\t\t\t`name` varchar(255) NOT NULL default '',\n\t\t\tPRIMARY KEY  (`ID`)\n\t\t\t\t) TYPE=MyISAM;";
        $DB->query($query) or die("0.65 add dropdown_os_version " . $LANG['update'][90] . $DB->error());
    }
    if (!TableExists("glpi_dropdown_os_sp")) {
        $query = "CREATE TABLE `glpi_dropdown_os_sp` (\n\t\t\t`ID` int(11) NOT NULL auto_increment,\n\t\t\t`name` varchar(255) NOT NULL default '',\n\t\t\tPRIMARY KEY  (`ID`)\n\t\t\t\t) TYPE=MyISAM;";
        $DB->query($query) or die("0.65 add dropdown_os_sp " . $LANG['update'][90] . $DB->error());
    }
    if (!FieldExists("glpi_computers", "os_version")) {
        $query = "ALTER TABLE `glpi_computers` ADD `os_version` INT NOT NULL DEFAULT '0' AFTER `os` ,\n\t\t\tADD `os_sp` INT NOT NULL DEFAULT '0' AFTER `os_version` ";
        $DB->query($query) or die("0.65 add os_version os_sp in computers " . $LANG['update'][90] . $DB->error());
    }
    // ADD INDEX
    $tbl = array("cartridges_type", "computers", "consumables_type", "contacts", "contracts", "docs", "enterprises", "monitors", "networking", "peripherals", "printers", "software", "users");
    foreach ($tbl as $t) {
        if (!isIndex("glpi_{$t}", "name")) {
            $query = "ALTER TABLE `glpi_{$t}` ADD INDEX ( `name` ) ";
            $DB->query($query) or die("0.65 add index in name field {$t} " . $LANG['update'][90] . $DB->error());
        }
    }
    $result = $DB->list_tables();
    while ($line = $DB->fetch_array($result)) {
        if (strstr($line[0], "glpi_dropdown") || strstr($line[0], "glpi_type")) {
            if (!isIndex($line[0], "name")) {
                $query = "ALTER TABLE `" . $line[0] . "` ADD INDEX ( `name` ) ";
                $DB->query($query) or die("0.65 add index in name field " . $line[0] . " " . $LANG['update'][90] . $DB->error());
            }
        }
    }
    if (!isIndex("glpi_reservation_item", "device_type_2")) {
        $query = "ALTER TABLE `glpi_reservation_item` ADD INDEX  `device_type_2` ( `device_type`,`id_device` ) ";
        $DB->query($query) or die("0.65 add index in reservation_item " . $line[0] . " " . $LANG['update'][90] . $DB->error());
    }
    if (!TableExists("glpi_dropdown_model_phones")) {
        $query = "CREATE TABLE `glpi_dropdown_model_phones` (\n\t\t\t`ID` int(11) NOT NULL auto_increment,\n\t\t\t`name` varchar(255) NOT NULL default '',\n\t\t\tPRIMARY KEY  (`ID`),\n\t\t\tKEY `name` (`name`)\n\t\t\t\t) TYPE=MyISAM;";
        $DB->query($query) or die("0.65 add dropdown_model_phones " . $LANG['update'][90] . $DB->error());
    }
    if (!TableExists("glpi_type_phones")) {
        $query = "CREATE TABLE `glpi_type_phones` (\n\t\t\t`ID` int(11) NOT NULL auto_increment,\n\t\t\t`name` varchar(255) NOT NULL default '',\n\t\t\tPRIMARY KEY  (`ID`),\n\t\t\tKEY `name` (`name`)\n\t\t\t\t) TYPE=MyISAM;";
        $DB->query($query) or die("0.65 add type_phones " . $LANG['update'][90] . $DB->error());
    }
    if (!TableExists("glpi_dropdown_phone_power")) {
        $query = "CREATE TABLE `glpi_dropdown_phone_power` (\n\t\t\t`ID` int(11) NOT NULL auto_increment,\n\t\t\t`name` varchar(255) NOT NULL default '',\n\t\t\tPRIMARY KEY  (`ID`),\n\t\t\tKEY `name` (`name`)\n\t\t\t\t) TYPE=MyISAM;";
        $DB->query($query) or die("0.65 add dropdown_phone_power " . $LANG['update'][90] . $DB->error());
    }
    if (!TableExists("glpi_phones")) {
        $query = "CREATE TABLE `glpi_phones` (\n\t\t\t`ID` int(11) NOT NULL auto_increment,\n\t\t\t`name` varchar(255) default NULL,\n\t\t\t`date_mod` datetime NOT NULL default '0000-00-00 00:00:00',\n\t\t\t`contact` varchar(255) default NULL,\n\t\t\t`contact_num` varchar(255) default NULL,\n\t\t\t`tech_num` int(11) NOT NULL default '0',\n\t\t\t`comments` text,\n\t\t\t`serial` varchar(255) default NULL,\n\t\t\t`otherserial` varchar(255) default NULL,\n\t\t\t`firmware` varchar(255) default NULL,\n\t\t\t`location` int(11) NOT NULL default '0',\n\t\t\t`type` int(11) NOT NULL default '0',\n\t\t\t`model` int(11) default NULL,\n\t\t\t`brand` varchar(255) default NULL,\n\t\t\t`power` tinyint(4) NOT NULL default '0',\n\t\t\t`number_line` varchar(255) NOT NULL default '',\n\t\t\t`flags_casque` tinyint(4) NOT NULL default '0',\n\t\t\t`flags_hp` tinyint(4) NOT NULL default '0',\n\t\t\t`FK_glpi_enterprise` int(11) NOT NULL default '0',\n\t\t\t`is_global` enum('0','1') NOT NULL default '0',\n\t\t\t`deleted` enum('Y','N') NOT NULL default 'N',\n\t\t\t`is_template` enum('0','1') NOT NULL default '0',\n\t\t\t`tplname` varchar(255) default NULL,\n\t\t\t`notes` longtext,\n\t\t\tPRIMARY KEY  (`ID`),\n\t\t\tKEY `type` (`type`),\n\t\t\tKEY `name` (`name`),\n\t\t\tKEY `location` (`location`),\n\t\t\tKEY `FK_glpi_enterprise` (`FK_glpi_enterprise`),\n\t\t\tKEY `deleted` (`deleted`),\n\t\t\tKEY `is_template` (`is_template`),\n\t\t\tKEY `tech_num` (`tech_num`)\n\t\t\t\t) TYPE=MyISAM;";
        $DB->query($query) or die("0.65 add phones " . $LANG['update'][90] . $DB->error());
        $query = "INSERT INTO `glpi_phones` VALUES (1, NULL, '0000-00-00 00:00:00', NULL, NULL, 0, NULL, NULL, NULL, NULL, 0, 0, NULL, NULL, 0, '', 0, 0, 0, '0', 'N', '1', 'Blank Template', NULL);";
        $DB->query($query) or die("0.65 blank template in phones " . $LANG['update'][90] . $DB->error());
    }
    if (!TableExists("glpi_reminder")) {
        $query = "CREATE TABLE `glpi_reminder` (\n\t\t\t`ID` int(11) NOT NULL auto_increment,\n\t\t\t`date` datetime default NULL,\n\t\t\t`author` int(11) NOT NULL default '0',\n\t\t\t`title` text,\n\t\t\t`text` text,\n\t\t\t`type` varchar(50) NOT NULL default 'private',\n\t\t\t`begin` datetime default NULL,\n\t\t\t`end` datetime default NULL,\n\t\t\t`rv` enum('0','1') NOT NULL default '0',\n\t\t\t`date_mod` datetime default NULL,\n\t\t\tPRIMARY KEY  (`ID`),\n\t\t\tKEY `date` (`date`),\n\t\t\tKEY `author` (`author`),\n\t\t\tKEY `rv` (`rv`),\n\t\t\tKEY `type` (`type`)\n\t\t\t\t) TYPE=MyISAM ;";
        $DB->query($query) or die("0.65 add reminder " . $LANG['update'][90] . $DB->error());
    }
    $result = $DB->list_tables();
    while ($line = $DB->fetch_array($result)) {
        if (strstr($line[0], "glpi_dropdown") || strstr($line[0], "glpi_type")) {
            if ($line[0] != "glpi_type_docs") {
                if (!FieldExists($line[0], "comments")) {
                    $query = "ALTER TABLE `" . $line[0] . "` ADD `comments` TEXT NULL ";
                    $DB->query($query) or die("0.65 add comments field in " . $line[0] . " " . $LANG['update'][90] . $DB->error());
                }
            }
        }
    }
    if (!FieldExists("glpi_consumables", "id_user")) {
        $query = "ALTER TABLE `glpi_consumables` ADD `id_user` INT NOT NULL DEFAULT '0';";
        $DB->query($query) or die("0.65 add id_user field in consumables " . $LANG['update'][90] . $DB->error());
    }
}
/**
 * Update from 0.78.1 to 0.78.2
 *
 * @return bool for success (will die for most error)
 */
function update0781to0782($output = 'HTML')
{
    global $DB, $migration;
    $updateresult = true;
    //TRANS: %s is the number of new version
    $migration->displayTitle(sprintf(__('Update to %s'), '0.78.2'));
    $migration->setVersion('0.78.2');
    $migration->displayMessage(__('Data migration'));
    // Updating schema
    /// Add document types
    $types = array('docx' => array('name' => 'Word XML', 'icon' => 'doc-dist.png'), 'xlsx' => array('name' => 'Excel XML', 'icon' => 'xls-dist.png'), 'pptx' => array('name' => 'PowerPoint XML', 'icon' => 'ppt-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.78.2 add document type {$ext}");
            }
        }
    }
    // Drop nl_be langage
    $query = "UPDATE `glpi_configs`\n             SET `language` = 'nl_NL'\n             WHERE `language` = 'nl_BE';";
    $DB->queryOrDie($query, "0.78.2 drop nl_be langage");
    $query = "UPDATE `glpi_users`\n             SET `language` = 'nl_NL'\n             WHERE `language` = 'nl_BE';";
    $DB->queryOrDie($query, "0.78.2 drop nl_be langage");
    // CLean sl_SL
    $query = "UPDATE `glpi_configs`\n             SET `language` = 'sl_SI'\n             WHERE `language` = 'sl_SL';";
    $DB->queryOrDie($query, "0.78.2 clean sl_SL langage");
    $query = "UPDATE `glpi_users`\n             SET `language` = 'sl_SI'\n             WHERE `language` = 'sl_SL';";
    $DB->queryOrDie($query, "0.78.2 clean sl_SL langage");
    if (isIndex('glpi_computers_items', 'unicity')) {
        $query = "ALTER TABLE `glpi_computers_items` DROP INDEX `unicity`";
        $DB->queryOrDie($query, "0.78.2 drop unicity index for glpi_computers_items");
        $query = "ALTER TABLE `glpi_computers_items` ADD INDEX `item` ( `itemtype` , `items_id` ) ";
        $DB->queryOrDie($query, "0.78.2 add index for glpi_computers_items");
    }
    // For Rule::RULE_TRACKING_AUTO_ACTION
    $changes['RuleMailCollector'] = array('X-Priority' => 'x-priority');
    $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.2 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.2 update datas for rules criterias");
                }
            }
        }
    }
    // Reorder ranking : start with 1
    $query = "SELECT DISTINCT `sub_type`\n             FROM `glpi_rules`\n             WHERE ranking = '0'";
    if ($result = $DB->query($query)) {
        if ($DB->numrows($result) > 0) {
            while ($data = $DB->fetch_assoc($result)) {
                $query = "UPDATE `glpi_rules`\n                      SET `ranking` = ranking +1\n                      WHERE `sub_type` = '" . $data['sub_type'] . "';";
                $DB->queryOrDie($query, "0.78.2 reorder rule ranking for " . $data['sub_type']);
            }
        }
    }
    // Check existing rule
    if (countElementsInTable('glpi_rulecriterias', "`criteria` IN ('auto-submitted','x-auto-response-suppress')") == 0) {
        /// Reorder ranking
        $query = "UPDATE `glpi_rules`\n                SET `ranking` = ranking +2\n                WHERE `sub_type` = 'RuleMailCollector';";
        $DB->queryOrDie($query, "0.78.2 reorder rule ranking for RuleMailCollector");
        /// Insert new rule
        $query = "INSERT INTO `glpi_rules`\n                       (`entities_id`, `sub_type`, `ranking`, `name`,\n                        `description`, `match`, `is_active`, `date_mod`, `is_recursive`)\n                VALUES ('0', 'RuleMailCollector', '1', 'Auto-Reply X-Auto-Response-Suppress',\n                        'Exclude Auto-Reply emails using X-Auto-Response-Suppress header', 'AND',\n                        0, NOW(), 1)";
        $DB->queryOrDie($query, "0.78.2 add new rule RuleMailCollector");
        $rule_id = $DB->insert_id();
        /// Insert criteria and action
        $query = "INSERT INTO `glpi_rulecriterias`\n                       (`rules_id`, `criteria`, `condition`, `pattern`)\n                VALUES ('{$rule_id}', 'x-auto-response-suppress', '6', '/\\\\S+/')";
        $DB->queryOrDie($query, "0.78.2 add new criteria RuleMailCollector");
        $query = "INSERT INTO `glpi_ruleactions`\n                       (`rules_id`, `action_type`, `field`, `value`)\n                VALUES ('{$rule_id}', 'assign', '_refuse_email_no_response', '1')";
        $DB->queryOrDie($query, "0.78.2 add new action RuleMailCollector");
        /// Insert new rule
        $query = "INSERT INTO `glpi_rules`\n                       (`entities_id`, `sub_type`, `ranking`, `name`,\n                        `description`, `match`, `is_active`, `date_mod`, `is_recursive`)\n                VALUES ('0', 'RuleMailCollector', '2', 'Auto-Reply Auto-Submitted',\n                        'Exclude Auto-Reply emails using Auto-Submitted header', 'AND', 0, NOW(), 1)";
        $DB->queryOrDie($query, "0.78.2 add new rule RuleMailCollector");
        $rule_id = $DB->insert_id();
        /// Insert criteria and action
        $query = "INSERT INTO `glpi_rulecriterias`\n                       (`rules_id`, `criteria`, `condition`, `pattern`)\n                VALUES ('{$rule_id}', 'auto-submitted', '6', '/\\\\S+/')";
        $DB->queryOrDie($query, "0.78.2 add new criteria RuleMailCollector");
        $query = "INSERT INTO `glpi_rulecriterias`\n                       (`rules_id`, `criteria`, `condition`, `pattern`)\n                VALUES ('{$rule_id}', 'auto-submitted', '1', 'no')";
        $DB->queryOrDie($query, "0.78.2 add new criteria RuleMailCollector");
        $query = "INSERT INTO `glpi_ruleactions`\n                       (`rules_id`, `action_type`, `field`, `value`)\n                VALUES ('{$rule_id}', 'assign', '_refuse_email_no_response', '1')";
        $DB->queryOrDie($query, "0.78.2 add new action RuleMailCollector");
    }
    if (!FieldExists('glpi_ocsservers', 'ocs_db_utf8', false)) {
        $query = "ALTER TABLE `glpi_ocsservers`\n                ADD `ocs_db_utf8` tinyint(1) NOT NULL default '0' AFTER `ocs_db_name`";
        $DB->queryOrDie($query, "0.78.2 add ocs_db_utf8 in glpi_ocsservers");
    }
    // must always be at the end (only for end message)
    $migration->executeMigration();
    return $updateresult;
}