/**
  * @param $computers_id
  * @param $date
  * @param $computer_updates
  * @return array
  */
 static function addInfocomsForComputer($computers_id, $date, $computer_updates)
 {
     global $DB;
     $infocom = new Infocom();
     $use_date = substr($date, 0, 10);
     if ($infocom->getFromDBByQuery("WHERE `items_id` = {$computers_id} AND `itemtype` = 'Computer'")) {
         if (empty($infocom->fields['use_date']) || $infocom->fields['use_date'] == 'NULL') {
             //add use_date
             $infocom->update(array('id' => $infocom->fields['id'], 'use_date' => $use_date));
         }
     } else {
         //add infocom
         $infocom->add(array('items_id' => $computers_id, 'itemtype' => 'Computer', 'use_date' => $use_date));
     }
     //Add lock
     $ocslink = new PluginOcsinventoryngOcslink();
     if ($ocslink->getFromDBforComputer($computers_id)) {
         $cfg_ocs = PluginOcsinventoryngOcsServer::getConfig($ocslink->fields["plugin_ocsinventoryng_ocsservers_id"]);
         if ($cfg_ocs["use_locks"]) {
             $computer_updates[] = "use_date";
             $query = "UPDATE `glpi_plugin_ocsinventoryng_ocslinks`\n                         SET `computer_update` = '" . addslashes(exportArrayToDB($computer_updates)) . "'\n                         WHERE `computers_id` = '{$computers_id}'";
             $DB->query($query);
         }
     }
     return $computer_updates;
 }
 function prepareInputForUpdate($input)
 {
     if (isset($input['networkports_id_list']) && is_array($input['networkports_id_list'])) {
         $input['networkports_id_list'] = exportArrayToDB($input['networkports_id_list']);
     } else {
         $input['networkports_id_list'] = exportArrayToDB(array());
     }
     return parent::prepareInputForAdd($input);
 }
 /**
  * Update the calendar cache
  *
  * @param $calendars_id integer calendar ID
  **/
 function updateDurationCache($calendars_id)
 {
     if ($this->getFromDB($calendars_id)) {
         $input['id'] = $calendars_id;
         $input['cache_duration'] = exportArrayToDB($this->getDaysDurations());
         return $this->update($input);
     }
     return false;
 }
 /**
  * Add lock fields for a record.
  *
  * @param $p_itemtype Table id.
  * @param $p_items_id Line id.
  * @param $p_fieldsToLock Array of fields to lock.
  *TODO:  check rights and entity
  *
  * @return nothing
  **/
 static function addLocks($p_itemtype, $p_items_id, $p_fieldsToLock)
 {
     global $DB;
     $tableName = getTableForItemType($p_itemtype);
     $pfl = new PluginFusioninventoryLock();
     $a_exclude = $pfl->excludeFields();
     $p_fieldsToLock = array_diff($p_fieldsToLock, $a_exclude);
     $result = PluginFusioninventoryLock::getLock($tableName, $p_items_id);
     if ($DB->numrows($result)) {
         $row = $DB->fetch_assoc($result);
         $lockedFields = importArrayFromDB($row['tablefields']);
         if (count(array_diff($p_fieldsToLock, $lockedFields))) {
             // old locks --> new locks
             $p_fieldsToLock = array_merge($p_fieldsToLock, $lockedFields);
             $a_lines = $pfl->find("`tablename`='" . $tableName . "' AND `items_id`='" . $p_items_id . "'");
             $a_line = current($a_lines);
             $pfl->getFromDB($a_line['id']);
             $pfl->fields['tablefields'] = exportArrayToDB($p_fieldsToLock);
             $pfl->update($pfl->fields);
         }
     } elseif (count($p_fieldsToLock)) {
         // no locks --> new locks
         $input = array();
         $input['tablename'] = $tableName;
         $input['items_id'] = $p_items_id;
         $input['tablefields'] = exportArrayToDB($p_fieldsToLock);
         $pfl->add($input);
     }
 }
 function prepareRun($taskjobs_id)
 {
     global $DB;
     $pfTask = new PluginFusioninventoryTask();
     $pfTaskjob = new PluginFusioninventoryTaskjob();
     $pfTaskjoblog = new PluginFusioninventoryTaskjoblog();
     $pfTaskjobstate = new PluginFusioninventoryTaskjobstate();
     $pfIPRange = new PluginFusioninventoryIPRange();
     $pfAgent = new PluginFusioninventoryAgent();
     $a_specificity = array();
     $a_specificity['DEVICE'] = array();
     $uniqid = uniqid();
     $pfTaskjob->getFromDB($taskjobs_id);
     $pfTask->getFromDB($pfTaskjob->fields['plugin_fusioninventory_tasks_id']);
     $NetworkEquipment = new NetworkEquipment();
     $NetworkPort = new NetworkPort();
     /*
      * * Different possibilities  :
      * IP RANGE
      * NetworkEquipment
      * Printer
      *
      * We will count total number of devices to query
      */
     // get all snmpauth
     $a_snmpauth = getAllDatasFromTable("glpi_plugin_fusioninventory_configsecurities");
     // get items_id by type
     $a_iprange = array();
     $a_NetworkEquipment = array();
     $a_Printer = array();
     $communication = $pfTask->fields['communication'];
     $a_definition = importArrayFromDB($pfTaskjob->fields['definition']);
     foreach ($a_definition as $datas) {
         $itemtype = key($datas);
         $items_id = current($datas);
         switch ($itemtype) {
             case 'PluginFusioninventoryIPRange':
                 $a_iprange[] = $items_id;
                 break;
             case 'NetworkEquipment':
                 $query = "SELECT `glpi_networkequipments`.`id` AS `gID`,\n                         `glpi_ipaddresses`.`name` AS `gnifaddr`,\n                         `plugin_fusioninventory_configsecurities_id`,\n                  FROM `glpi_networkequipments`\n                  LEFT JOIN `glpi_plugin_fusioninventory_networkequipments`\n                       ON `networkequipments_id`=`glpi_networkequipments`.`id`\n                  LEFT JOIN `glpi_networkports`\n                       ON `glpi_networkports`.`items_id`=`glpi_networkequipments`.`id`\n                          AND `glpi_networkports`.`itemtype`='NetworkEquipment'\n                  LEFT JOIN `glpi_networknames`\n                       ON `glpi_networknames`.`items_id`=`glpi_networkports`.`id`\n                          AND `glpi_networknames`.`itemtype`='NetworkPort'\n                  LEFT JOIN `glpi_ipaddresses`\n                       ON `glpi_ipaddresses`.`items_id`=`glpi_networknames`.`id`\n                          AND `glpi_ipaddresses`.`itemtype`='NetworkName'\n                  WHERE `glpi_networkequipments`.`is_deleted`='0'\n                       AND `plugin_fusioninventory_configsecurities_id`!='0'\n                       AND `glpi_networkequipments`.`id` = '" . $items_id . "'\n                       AND `glpi_ipaddresses`.`name`!=''\n                  LIMIT 1";
                 $result = $DB->query($query);
                 while ($data = $DB->fetch_array($result)) {
                     if (isset($a_snmpauth[$data['plugin_fusioninventory_configsecurities_id']])) {
                         $input = array();
                         $input['TYPE'] = 'NETWORKING';
                         $input['ID'] = $data['gID'];
                         $input['IP'] = $data['gnifaddr'];
                         $input['AUTHSNMP_ID'] = $data['plugin_fusioninventory_configsecurities_id'];
                         $a_specificity['DEVICE']['NetworkEquipment' . $data['gID']] = $input;
                         $a_NetworkEquipment[] = $items_id;
                     }
                 }
                 break;
             case 'Printer':
                 $query = "SELECT `glpi_printers`.`id` AS `gID`,\n                         `glpi_ipaddresses`.`name` AS `gnifaddr`,\n                         `plugin_fusioninventory_configsecurities_id`,\n                  FROM `glpi_printers`\n                  LEFT JOIN `glpi_plugin_fusioninventory_printers`\n                          ON `printers_id`=`glpi_printers`.`id`\n                  LEFT JOIN `glpi_networkports`\n                       ON `glpi_networkports`.`items_id`=`glpi_printers`.`id`\n                          AND `glpi_networkports`.`itemtype`='Printer'\n                  LEFT JOIN `glpi_networknames`\n                       ON `glpi_networknames`.`items_id`=`glpi_networkports`.`id`\n                          AND `glpi_networknames`.`itemtype`='NetworkPort'\n                  LEFT JOIN `glpi_ipaddresses`\n                       ON `glpi_ipaddresses`.`items_id`=`glpi_networknames`.`id`\n                          AND `glpi_ipaddresses`.`itemtype`='NetworkName'\n                  WHERE `glpi_printers`.`is_deleted`=0\n                        AND `plugin_fusioninventory_configsecurities_id`!='0'\n                        AND `glpi_printers`.`id` = '" . $items_id . "'\n                        AND `glpi_ipaddresses`.`name`!=''\n                  LIMIT 1";
                 $result = $DB->query($query);
                 while ($data = $DB->fetch_array($result)) {
                     if (isset($a_snmpauth[$data['plugin_fusioninventory_configsecurities_id']])) {
                         $input = array();
                         $input['TYPE'] = 'PRINTER';
                         $input['ID'] = $data['gID'];
                         $input['IP'] = $data['gnifaddr'];
                         $input['AUTHSNMP_ID'] = $data['plugin_fusioninventory_configsecurities_id'];
                         $a_specificity['DEVICE']['Printer' . $data['gID']] = $input;
                         $a_Printer[] = $items_id;
                     }
                 }
                 break;
         }
     }
     // Get all devices on each iprange
     foreach ($a_iprange as $items_id) {
         $pfIPRange->getFromDB($items_id);
         // Search NetworkEquipment
         $query = "SELECT `glpi_networkequipments`.`id` AS `gID`,\n                            `glpi_ipaddresses`.`name` AS `gnifaddr`,\n                            `plugin_fusioninventory_configsecurities_id`,\n                     FROM `glpi_networkequipments`\n                     LEFT JOIN `glpi_plugin_fusioninventory_networkequipments`\n                          ON `networkequipments_id`=`glpi_networkequipments`.`id`\n                     LEFT JOIN `glpi_networkports`\n                          ON `glpi_networkports`.`items_id`=`glpi_networkequipments`.`id`\n                             AND `glpi_networkports`.`itemtype`='NetworkEquipment'\n                     LEFT JOIN `glpi_networknames`\n                          ON `glpi_networknames`.`items_id`=`glpi_networkports`.`id`\n                             AND `glpi_networknames`.`itemtype`='NetworkPort'\n                     LEFT JOIN `glpi_ipaddresses`\n                          ON `glpi_ipaddresses`.`items_id`=`glpi_networknames`.`id`\n                             AND `glpi_ipaddresses`.`itemtype`='NetworkName'\n                     WHERE `glpi_networkequipments`.`is_deleted`='0'\n                          AND `plugin_fusioninventory_configsecurities_id`!='0'";
         if ($pfIPRange->fields['entities_id'] != '-1') {
             $entities = "(" . $this->fields['entities_id'];
             foreach (getAncestorsOf("glpi_entities", $pfIPRange->fields['entities_id']) as $parent) {
                 $entities .= ",{$parent}";
             }
             $entities .= ")";
             $query .= " AND `glpi_networkequipments`.`entities_id` IN " . $entities . " ";
         }
         $query .= " AND inet_aton(`glpi_ipaddresses`.`name`)\n                         BETWEEN inet_aton('" . $pfIPRange->fields['ip_start'] . "')\n                         AND inet_aton('" . $pfIPRange->fields['ip_end'] . "') ";
         $query .= " GROUP BY `glpi_networkequipments`.`id`";
         $result = $DB->query($query);
         while ($data = $DB->fetch_array($result)) {
             if (isset($a_snmpauth[$data['plugin_fusioninventory_configsecurities_id']])) {
                 $input = array();
                 $input['TYPE'] = 'NETWORKING';
                 $input['ID'] = $data['gID'];
                 $input['IP'] = $data['gnifaddr'];
                 $input['AUTHSNMP_ID'] = $data['plugin_fusioninventory_configsecurities_id'];
                 $a_specificity['DEVICE']['NetworkEquipment' . $data['gID']] = $input;
                 $a_NetworkEquipment[] = $data['gID'];
             }
         }
         // Search Printer
         $query = "SELECT `glpi_printers`.`id` AS `gID`,\n                         `glpi_ipaddresses`.`name` AS `gnifaddr`,\n                         `plugin_fusioninventory_configsecurities_id`,\n                  FROM `glpi_printers`\n                  LEFT JOIN `glpi_plugin_fusioninventory_printers`\n                          ON `printers_id`=`glpi_printers`.`id`\n                  LEFT JOIN `glpi_networkports`\n                       ON `glpi_networkports`.`items_id`=`glpi_printers`.`id`\n                          AND `glpi_networkports`.`itemtype`='Printer'\n                  LEFT JOIN `glpi_networknames`\n                       ON `glpi_networknames`.`items_id`=`glpi_networkports`.`id`\n                          AND `glpi_networknames`.`itemtype`='NetworkPort'\n                  LEFT JOIN `glpi_ipaddresses`\n                       ON `glpi_ipaddresses`.`items_id`=`glpi_networknames`.`id`\n                          AND `glpi_ipaddresses`.`itemtype`='NetworkName'\n                  WHERE `glpi_printers`.`is_deleted`=0\n                        AND `plugin_fusioninventory_configsecurities_id`!='0'";
         if ($pfIPRange->fields['entities_id'] != '-1') {
             $entities = "(" . $this->fields['entities_id'];
             foreach (getAncestorsOf("glpi_entities", $pfIPRange->fields['entities_id']) as $parent) {
                 $entities .= ",{$parent}";
             }
             $entities .= ")";
             $query .= "AND `glpi_printers`.`entities_id` IN " . $entities . " ";
         }
         $query .= " AND inet_aton(`glpi_ipaddresses`.`name`)\n                      BETWEEN inet_aton('" . $pfIPRange->fields['ip_start'] . "')\n                      AND inet_aton('" . $pfIPRange->fields['ip_end'] . "') ";
         $query .= " GROUP BY `glpi_printers`.`id`";
         $result = $DB->query($query);
         while ($data = $DB->fetch_array($result)) {
             if (isset($a_snmpauth[$data['plugin_fusioninventory_configsecurities_id']])) {
                 $input = array();
                 $input['TYPE'] = 'PRINTER';
                 $input['ID'] = $data['gID'];
                 $input['IP'] = $data['gnifaddr'];
                 $input['AUTHSNMP_ID'] = $data['plugin_fusioninventory_configsecurities_id'];
                 $a_specificity['DEVICE']['Printer' . $data['gID']] = $input;
                 $a_Printer[] = $data['gID'];
             }
         }
     }
     $count_device = count($a_NetworkEquipment) + count($a_Printer);
     $a_actions = importArrayFromDB($pfTaskjob->fields['action']);
     // *** For dynamic agent same subnet, it's an another management ***
     if (strstr($pfTaskjob->fields['action'], '".2"')) {
         $a_subnet = array();
         $a_agentList = array();
         $a_devicesubnet = array();
         foreach ($a_NetworkEquipment as $items_id) {
             $NetworkEquipment->getFromDB($items_id);
             $a_ip = explode(".", $NetworkEquipment->fields['ip']);
             $ip_subnet = $a_ip[0] . "." . $a_ip[1] . "." . $a_ip[2] . ".";
             if (!isset($a_subnet[$ip_subnet])) {
                 $a_subnet[$ip_subnet] = 0;
             }
             $a_subnet[$ip_subnet]++;
             $a_devicesubnet[$ip_subnet]['NetworkEquipment'][$items_id] = 1;
         }
         foreach ($a_Printer as $items_id) {
             $a_ports = $NetworkPort->find("`itemtype`='Printer'\n                                          AND `items_id`='" . $items_id . "'\n                                          AND `ip`!='127.0.0.1'");
             foreach ($a_ports as $a_port) {
                 $a_ip = explode(".", $a_port['ip']);
                 $ip_subnet = $a_ip[0] . "." . $a_ip[1] . "." . $a_ip[2] . ".";
                 if (!isset($a_subnet[$ip_subnet])) {
                     $a_subnet[$ip_subnet] = 0;
                 }
                 $a_subnet[$ip_subnet]++;
                 $a_devicesubnet[$ip_subnet]['Printer'][$items_id] = 1;
             }
         }
         $a_agentsubnet = array();
         foreach ($a_subnet as $subnet => $num) {
             $a_agentList = $this->getAgentsSubnet($num, $communication, $subnet);
             if (!isset($a_agentList)) {
                 $a_agentsubnet[$subnet] = '';
             } else {
                 $a_agentsubnet[$subnet] = $a_agentList;
             }
         }
         $a_input = array();
         $a_input['plugin_fusioninventory_taskjobs_id'] = $taskjobs_id;
         $a_input['state'] = 1;
         $a_input['plugin_fusioninventory_agents_id'] = 0;
         $a_input['itemtype'] = '';
         $a_input['items_id'] = 0;
         $a_input['uniqid'] = $uniqid;
         $a_input['execution_id'] = $task->fields['execution_id'];
         $taskvalid = 0;
         foreach ($a_agentsubnet as $subnet => $a_agentList) {
             if (!isset($a_agentList) or isset($a_agentList) && is_array($a_agentList) && count($a_agentList) == '0' or isset($a_agentList) && !is_array($a_agentList) && $a_agentList == '') {
                 // No agent available for this subnet
                 for ($i = 0; $i < 2; $i++) {
                     $itemtype = 'Printer';
                     if ($i == '0') {
                         $itemtype = 'NetworkEquipment';
                     }
                     if (isset($a_devicesubnet[$subnet][$itemtype])) {
                         foreach ($a_devicesubnet[$subnet][$itemtype] as $items_id => $num) {
                             $a_input['itemtype'] = $itemtype;
                             $a_input['items_id'] = $items_id;
                             $a_input['specificity'] = exportArrayToDB($a_specificity['DEVICE'][$itemtype . $items_id]);
                             $Taskjobstates_id = $pfTaskjobstate->add($a_input);
                             //Add log of taskjob
                             $a_input['plugin_fusioninventory_taskjobstates_id'] = $Taskjobstates_id;
                             $a_input['state'] = 7;
                             $a_input['date'] = date("Y-m-d H:i:s");
                             $pfTaskjoblog->add($a_input);
                             $pfTaskjobstate->changeStatusFinish($Taskjobstates_id, 0, '', 1, "Unable to find agent to inventory " . "this " . $itemtype, 0, 0);
                             $a_input['state'] = 1;
                         }
                     }
                 }
             } else {
                 // add taskjobstate
                 $count_device_subnet = 0;
                 if (isset($a_devicesubnet[$subnet]['NetworkEquipment'])) {
                     $count_device_subnet += count($a_devicesubnet[$subnet]['NetworkEquipment']);
                 }
                 if (isset($a_devicesubnet[$subnet]['Printer'])) {
                     $count_device_subnet += count($a_devicesubnet[$subnet]['Printer']);
                 }
                 $nb_devicebyagent = ceil($count_device_subnet / count($a_agentList));
                 $nbagent = 0;
                 $agent_id = array_pop($a_agentList);
                 $a_input['state'] = 0;
                 for ($i = 0; $i < 2; $i++) {
                     $itemtype = 'Printer';
                     if ($i == '0') {
                         $itemtype = 'NetworkEquipment';
                     }
                     if (isset($a_devicesubnet[$subnet][$itemtype])) {
                         foreach ($a_devicesubnet[$subnet][$itemtype] as $items_id => $num) {
                             $a_input['itemtype'] = $itemtype;
                             $a_input['items_id'] = $items_id;
                             $a_input['specificity'] = exportArrayToDB($a_specificity['DEVICE'][$itemtype . $items_id]);
                             if ($nbagent == $nb_devicebyagent) {
                                 $agent_id = array_pop($a_agentList);
                                 $nbagent = 0;
                             }
                             $a_input['plugin_fusioninventory_agents_id'] = $agent_id;
                             $nbagent++;
                             $taskvalid++;
                             $Taskjobstates_id = $pfTaskjobstate->add($a_input);
                             //Add log of taskjob
                             $a_input['plugin_fusioninventory_taskjobstates_id'] = $Taskjobstates_id;
                             $a_input['state'] = 7;
                             $a_input['date'] = date("Y-m-d H:i:s");
                             $pfTaskjoblog->add($a_input);
                             unset($a_input['state']);
                             $a_input['plugin_fusioninventory_agents_id'] = 0;
                             $a_input['state'] = 0;
                             if ($communication == "push") {
                                 $_SESSION['glpi_plugin_fusioninventory']['agents'][$agent_id] = 1;
                             }
                         }
                     }
                 }
             }
         }
         if ($taskvalid == "0") {
             $pfTaskjob->reinitializeTaskjobs($pfTaskjob->fields['plugin_fusioninventory_tasks_id']);
         }
     } else {
         $a_agentList = array();
         // *** Only agents not dynamic ***
         if (!strstr($pfTaskjob->fields['action'], '".1"') and !strstr($pfTaskjob->fields['action'], '".2"')) {
             $agent_require_model = 0;
             foreach ($a_actions as $a_action) {
                 if (!in_array('.1', $a_action) and !in_array('.2', $a_action)) {
                     $agent_id = current($a_action);
                     if ($pfAgent->getFromDB($agent_id)) {
                         $agent_version = $pfAgent->getAgentVersion($agent_id);
                         if (strnatcmp($agent_version, '2.3.4') < 0) {
                             $agent_require_model = 1;
                         }
                         if ($communication == 'pull') {
                             $a_agentList[] = $agent_id;
                         } else {
                             if ($pfTaskjob->isAgentAlive('1', $agent_id)) {
                                 $a_agentList[] = $agent_id;
                             }
                         }
                     }
                 }
             }
         } else {
             if (strstr($pfTaskjob->fields['action'], '".1"')) {
                 $a_agentList = $this->getAgentsSubnet($count_device, $communication);
             }
         }
         /*
          * Manage agents
          */
         if (count($a_agentList) == 0) {
             $a_input = array();
             $a_input['plugin_fusioninventory_taskjobs_id'] = $taskjobs_id;
             $a_input['state'] = 1;
             $a_input['plugin_fusioninventory_agents_id'] = 0;
             $a_input['itemtype'] = '';
             $a_input['items_id'] = 0;
             $a_input['uniqid'] = $uniqid;
             $a_input['execution_id'] = $task->fields['execution_id'];
             $Taskjobstates_id = $pfTaskjobstate->add($a_input);
             //Add log of taskjob
             $a_input['plugin_fusioninventory_taskjobstates_id'] = $Taskjobstates_id;
             $a_input['state'] = 7;
             $a_input['date'] = date("Y-m-d H:i:s");
             $pfTaskjoblog->add($a_input);
             $pfTaskjobstate->changeStatusFinish($Taskjobstates_id, 0, '', 1, "Unable to find agent to run this job");
             $input_taskjob = array();
             $input_taskjob['id'] = $pfTaskjob->fields['id'];
             //$input_taskjob['status'] = 0;
             $pfTaskjob->update($input_taskjob);
         } elseif ($count_device == 0) {
             $a_input = array();
             $a_input['plugin_fusioninventory_taskjobs_id'] = $taskjobs_id;
             $a_input['state'] = 1;
             $a_input['plugin_fusioninventory_agents_id'] = 0;
             $a_input['itemtype'] = '';
             $a_input['items_id'] = 0;
             $a_input['uniqid'] = $uniqid;
             $Taskjobstates_id = $pfTaskjobstate->add($a_input);
             //Add log of taskjob
             $a_input['plugin_fusioninventory_taskjobstates_id'] = $Taskjobstates_id;
             $a_input['state'] = 7;
             $a_input['date'] = date("Y-m-d H:i:s");
             $pfTaskjoblog->add($a_input);
             $pfTaskjobstate->changeStatusFinish($Taskjobstates_id, 0, '', 0, "No suitable devices to inventory");
             $input_taskjob = array();
             $input_taskjob['id'] = $pfTaskjob->fields['id'];
             //$input_taskjob['status'] = 1;
             $pfTaskjob->update($input_taskjob);
         } else {
             foreach ($a_agentList as $agent_id) {
                 //Add jobstate and put status (waiting on server = 0)
                 $a_input = array();
                 $a_input['plugin_fusioninventory_taskjobs_id'] = $taskjobs_id;
                 $a_input['state'] = 0;
                 $a_input['plugin_fusioninventory_agents_id'] = $agent_id;
                 $a_input['uniqid'] = $uniqid;
                 $a_input['execution_id'] = $task->fields['execution_id'];
                 $alternate = 0;
                 for ($d = 0; $d < ceil($count_device / count($a_agentList)); $d++) {
                     if (count($a_NetworkEquipment) + count($a_Printer) > 0) {
                         $getdevice = "NetworkEquipment";
                         if ($alternate == "1") {
                             $getdevice = "Printer";
                             $alternate = 0;
                         } else {
                             $getdevice = "NetworkEquipment";
                             $alternate++;
                         }
                         if (count($a_NetworkEquipment) == '0') {
                             $getdevice = "Printer";
                         } else {
                             if (count($a_Printer) == '0') {
                                 $getdevice = "NetworkEquipment";
                             }
                         }
                         $a_input['itemtype'] = $getdevice;
                         switch ($getdevice) {
                             case 'NetworkEquipment':
                                 $a_input['items_id'] = array_pop($a_NetworkEquipment);
                                 $a_input['specificity'] = exportArrayToDB($a_specificity['DEVICE']['NetworkEquipment' . $a_input['items_id']]);
                                 break;
                             case 'Printer':
                                 $a_input['items_id'] = array_pop($a_Printer);
                                 $a_input['specificity'] = exportArrayToDB($a_specificity['DEVICE']['Printer' . $a_input['items_id']]);
                                 break;
                         }
                         $Taskjobstates_id = $pfTaskjobstate->add($a_input);
                         //Add log of taskjob
                         $a_input['plugin_fusioninventory_taskjobstates_id'] = $Taskjobstates_id;
                         $a_input['state'] = 7;
                         $a_input['date'] = date("Y-m-d H:i:s");
                         $pfTaskjoblog->add($a_input);
                         unset($a_input['state']);
                         if ($communication == "push") {
                             $_SESSION['glpi_plugin_fusioninventory']['agents'][$agent_id] = 1;
                         }
                     }
                 }
             }
             $input_taskjob = array();
             $input_taskjob['id'] = $pfTaskjob->fields['id'];
             $input_taskjob['status'] = 1;
             $pfTaskjob->update($input_taskjob);
         }
     }
     return $uniqid;
 }
Example #6
0
 function prepareInputForAdd($input)
 {
     if (isset($input["helpdesk_item_type"])) {
         $input["helpdesk_item_type"] = exportArrayToDB($input["helpdesk_item_type"]);
     }
     $this->profileRight = array();
     foreach (ProfileRight::getAllPossibleRights() as $right => $default) {
         if (isset($input[$right])) {
             $this->profileRight[$right] = $input[$right];
             unset($input[$right]);
         }
     }
     return $input;
 }
 function FusionUnknownKnownDevice()
 {
     global $DB;
     $query = "SELECT *\n                FROM `glpi_networking_ports`\n                WHERE `ifmac` != ''\n                      AND `ifmac` != '00:00:00:00:00:00'\n                      AND `device_type`=" . PLUGIN_FUSIONINVENTORY_MAC_UNKNOWN . "\n                GROUP BY `ifmac`\n                HAVING COUNT(*)>0;";
     if ($result = $DB->query($query)) {
         while ($data = $DB->fetch_array($result)) {
             // $data = ID of unknown device
             $query_known = "SELECT *\n                            FROM `glpi_networking_ports`\n                            WHERE `ifmac` IN ('" . $data["ifmac"] . "','" . strtoupper($data["ifmac"]) . "',\n                                              '" . strtolower($data["ifmac"]) . "')\n                                  AND `device_type`!=" . PLUGIN_FUSIONINVENTORY_MAC_UNKNOWN . "\n                            LIMIT 0,1;";
             $result_known = $DB->query($query_known);
             if ($DB->numrows($result_known) > 0) {
                 $data_known = $DB->fetch_array($result_known);
                 $query_update = "UPDATE `glpi_networking_ports`\n                                SET `on_device`='" . $data_known["on_device"] . "',\n                                    `device_type='" . $data_known["device_type"] . "',\n                                    `logical_number`='" . $data_known["logical_number"] . "',\n                                    `name`='" . $data_known["name"] . "',\n                                    `ifaddr`='" . $data_known["ifaddr"] . "',\n                                    `iface`='" . $data_known["iface"] . "',\n                                    `netpoint`='" . $data_known["netpoint"] . "',\n                                    `netmask`='" . $data_known["netmask"] . "',\n                                    `gateway`='" . $data_known["gateway"] . "',\n                                    `subnet`='" . $data_known["subnet"] . "'\n                                  WHERE `ID`='" . $data["ID"] . "';";
                 $DB->query($query_update);
                 // Delete old networking port
                 $this->deleteFromDB($data_known["ID"], 1);
                 // Delete unknown device
                 $this->deleteFromDB($data["on_device"], 1);
                 // Modify OCS link of this networking port
                 $query = "SELECT *\n                         FROM `glpi_ocs_link`\n                         WHERE `glpi_id`='" . $data_known["on_device"] . "';";
                 $result = $DB->query($query);
                 if ($DB->numrows($result) == 1) {
                     $line = $DB->fetch_assoc($result);
                     $import_ip = importArrayFromDB($line["import_ip"]);
                     $ip_port = $import_ip[$data_known["ID"]];
                     unset($import_ip[$data_known["ID"]]);
                     $import_ip[$data["ID"]] = $ip_port;
                     $query_update = "UPDATE `glpi_ocs_link`\n                                   SET `import_ip`='" . exportArrayToDB($import_ip) . "'\n                                   WHERE `glpi_id`='" . $line["ID"] . "';";
                     $DB->query($query_update);
                 }
             }
         }
     }
 }
Example #8
0
 /**
  * Update $_SESSION to set the display options.
  *
  * @since version 0.84
  *
  * @param $input         array   of data to update
  * @param $sub_itemtype  string  sub itemtype if needed (default '')
  *
  * @return nothing
  **/
 static function updateDisplayOptions($input = array(), $sub_itemtype = '')
 {
     $options = static::getAvailableDisplayOptions();
     if (count($options)) {
         if (empty($sub_itemtype)) {
             $display_options =& $_SESSION['glpi_display_options'][self::getType()];
         } else {
             $display_options =& $_SESSION['glpi_display_options'][self::getType()][$sub_itemtype];
         }
         // reset
         if (isset($input['reset'])) {
             foreach ($options as $option_group_name => $option_group) {
                 foreach ($option_group as $option_name => $attributs) {
                     $display_options[$option_name] = $attributs['default'];
                 }
             }
         } else {
             foreach ($options as $option_group_name => $option_group) {
                 foreach ($option_group as $option_name => $attributs) {
                     if (isset($input[$option_name]) && $_GET[$option_name] == 'on') {
                         $display_options[$option_name] = true;
                     } else {
                         $display_options[$option_name] = false;
                     }
                 }
             }
         }
         // Store new display options for user
         if ($uid = Session::getLoginUserID()) {
             $user = new User();
             if ($user->getFromDB($uid)) {
                 $user->update(array('id' => $uid, 'display_options' => exportArrayToDB($_SESSION['glpi_display_options'])));
             }
         }
     }
 }
Example #9
0
 /**
  * Gère la transformation des inputs multiples en quelque chose d'inserable dans la base (en l'occurence une chaine json).
  * .
  *
  * @see CommonDBTM::prepareInputForAdd()
  */
 final function prepareInputForAdd($input)
 {
     foreach (self::getConfigParams() as $param => $desc) {
         if (isset($input[$param]) && isset($desc['multiple']) && $desc['multiple']) {
             $input[$param] = exportArrayToDB($input[$param]);
         }
     }
     return $input;
 }
 function saveDatas($params)
 {
     global $DB;
     $tasks_id = $params['tasks_id'];
     $tasks = json_decode($params['tasks']);
     //remove old jobs from task
     $query = "DELETE FROM " . $this->getTable() . "\n      WHERE plugin_fusioninventory_deploytasks_id = '" . $tasks_id . "'";
     $res = $DB->query($query);
     //get plugin id
     $plug = new Plugin();
     $plug->getFromDBbyDir('fusinvdeploy');
     $plugins_id = $plug->getField('id');
     //insert new rows
     $sql_tasks = array();
     $i = 0;
     foreach ($tasks as $task) {
         $task = get_object_vars($task);
         //encode action and definition
         //$action = exportArrayToDB(array(array(
         //    $task['action_type'] => $task['action_selection'])));
         $action = exportArrayToDB($task['action']);
         $definition = exportArrayToDB(array(array('PluginFusioninventoryDeployPackage' => $task['package_id'])));
         $sql_tasks[] = "INSERT INTO " . $this->getTable() . "\n         (\n            plugin_fusioninventory_deploytasks_id, name, date_creation, entities_id,\n            plugins_id, method, definition, action,\n            retry_nb, retry_time, periodicity_type, periodicity_count\n         ) VALUES (\n            '{$tasks_id}', 'job_" . $tasks_id . "_{$i}', NOW(), '0',\n            '{$plugins_id}', '" . $task['method'] . "', '{$definition}', '{$action}',\n            '" . $task['retry_nb'] . "', '" . $task['retry_time'] . "', 'minutes', '0'\n         )";
         $i++;
     }
     foreach ($sql_tasks as $query) {
         $res = $DB->query($query);
     }
 }
Example #11
0
 static function addToOcsArray($computers_id, $toadd, $field)
 {
     global $DB;
     $query = "SELECT `{$field}`\n                FROM `glpi_plugin_ocsinventoryng_ocslinks`\n                WHERE `computers_id` = '{$computers_id}'";
     if ($result = $DB->query($query)) {
         if ($DB->numrows($result)) {
             $tab = importArrayFromDB($DB->result($result, 0, 0));
             // Stripslashes because importArray get clean array
             foreach ($toadd as $key => $val) {
                 $tab[$key] = stripslashes($val);
             }
             $query = "UPDATE `glpi_plugin_ocsinventoryng_ocslinks`\n                      SET `{$field}` = '" . addslashes(exportArrayToDB($tab)) . "'\n                      WHERE `computers_id` = '{$computers_id}'";
             $DB->query($query);
         }
     }
 }
 function deleteGaugeItems($array)
 {
     $this->getFromDB($array['id']);
     $aggregate_items = importArrayFromDB($this->fields['aggregate_items']);
     $split = explode('|', $array['delete_item']);
     if (count($split) == 5) {
         unset($aggregate_items[$split[0]][$split[1]][$split[2]][$split[3]][$split[4]]);
         if (count($aggregate_items[$split[0]][$split[1]][$split[2]][$split[3]]) == 0) {
             unset($aggregate_items[$split[0]][$split[1]][$split[2]][$split[3]]);
             if (count($aggregate_items[$split[0]][$split[1]][$split[2]]) == 0) {
                 unset($aggregate_items[$split[0]][$split[1]][$split[2]]);
                 if (count($aggregate_items[$split[0]][$split[1]]) == 0) {
                     unset($aggregate_items[$split[0]][$split[1]]);
                     if (count($aggregate_items[$split[0]]) == 0) {
                         unset($aggregate_items[$split[0]]);
                     }
                 }
             }
         }
     }
     $input = array('id' => $array['id'], 'aggregate_items' => exportArrayToDB($aggregate_items));
     $this->update($input);
 }
      $input = array();
      $pmComponentscatalog->getFromDB($_POST['plugin_monitoring_componentscalalog_id']);
      $input['id'] = $_POST['id'];
      $input['entities_id'] = $pmComponentscatalog->fields['entities_id'];
      $input['is_recursive'] = $pmComponentscatalog->fields['is_recursive'];
      $input['name'] = $_POST['name'];
      $input['itemtype'] = $_POST['itemtype'];
      $input['plugin_monitoring_componentscalalog_id'] = $_POST['plugin_monitoring_componentscalalog_id'];
      unset($_POST['entities_id']);
      unset($_POST['is_recursive']);
      unset($_POST['name']);
      unset($_POST['updaterule']);
      unset($_POST['itemtypen']);
      unset($_POST['plugin_monitoring_componentscalalog_id']);
      unset($_POST['id']);
      $input['condition'] = exportArrayToDB($_POST);
      $pmComponentscatalog_rule->update($input);
      unset($_SESSION['plugin_monitoring_rules']);
      unset($_SESSION["glpisearch"][$input['itemtype']]);
      Html::redirect($CFG_GLPI['root_doc']."/plugins/monitoring/front/componentscatalog.form.php?id=".$input['plugin_monitoring_componentscalalog_id']);

   }
} else if (isset($_GET['deleterule'])) {
   $_POST = $_GET;
   $pmComponentscatalog_rule->delete($_POST);
   Html::redirect($CFG_GLPI['root_doc']."/plugins/monitoring/front/componentscatalog.form.php?id=".$_POST['plugin_monitoring_componentscalalog_id']);
} else if (isset($_GET['contains'])
        OR isset($_GET['reset'])) {
//   if (isset($_SESSION['plugin_monitoring_rules'])) {
//      unset($_SESSION['plugin_monitoring_rules']);
//   }
Example #14
0
 /**
  * Move a bookmark in an ordered collection
  *
  * @since version 0.85
  *
  * @param $items    array      of the rules ID to move
  * @param $ref_ID   integer    of the rule position  (0 means all, so before all or after all)
  * @param $action   string     of move : after or before ( default 'after')
  *
  * @return true if all ok
  **/
 function moveBookmark($items = array(), $ref_ID, $action = 'after')
 {
     global $DB;
     if (count($items)) {
         // Clean IDS : drop ref_ID
         if (isset($items[$ref_ID])) {
             unset($items[$ref_ID]);
         }
         $user = new User();
         $personalorderfield = 'privatebookmarkorder';
         if ($user->getFromDB(Session::getLoginUserID())) {
             $personalorder = importArrayFromDB($user->fields[$personalorderfield]);
         }
         if (!is_array($personalorder)) {
             return false;
         }
         $newpersonalorder = array();
         foreach ($personalorder as $val) {
             // Found item
             if ($val == $ref_ID) {
                 // Add after so add ref ID
                 if ($action == 'after') {
                     $newpersonalorder[] = $ref_ID;
                 }
                 foreach ($items as $val2) {
                     $newpersonalorder[] = $val2;
                 }
                 if ($action == 'before') {
                     $newpersonalorder[] = $ref_ID;
                 }
             } else {
                 if (!isset($items[$val])) {
                     $newpersonalorder[] = $val;
                 }
             }
         }
         $user->update(array('id' => Session::getLoginUserID(), $personalorderfield => exportArrayToDB($newpersonalorder)));
         return true;
     }
     return false;
 }
Example #15
0
 static function savePlanningsInDB()
 {
     $user = new User();
     $user->update(array('id' => $_SESSION['glpiID'], 'plannings' => exportArrayToDB($_SESSION['glpi_plannings'])));
 }
/**
 * 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 #17
0
/**
 * Update all Network Organisation
 *
 * @param $ADDTODISPLAYPREF
**/
function updateNetworkFramework(&$ADDTODISPLAYPREF)
{
    global $DB, $migration;
    $ADDTODISPLAYPREF['FQDN'] = array(11);
    $ADDTODISPLAYPREF['WifiNetwork'] = array(10);
    $ADDTODISPLAYPREF['NetworkPortMigration'] = array();
    $ADDTODISPLAYPREF['IPNetwork'] = array(14, 10, 11, 12, 13);
    $ADDTODISPLAYPREF['NetworkName'] = array(12, 13);
    $optionIndex = 10;
    foreach (NetworkPortMigration::getMotives() as $key => $name) {
        $ADDTODISPLAYPREF['NetworkPortMigration'][] = $optionIndex++;
    }
    $migration->displayMessage(sprintf(__('Data migration - %s'), 'Network framework'));
    $originTables = array();
    foreach (array('glpi_networkports', 'glpi_networkequipments') as $table) {
        $originTables[$table] = 'origin_' . $table;
    }
    if (!TableExists('origin_glpi_networkequipments')) {
        // remove of mac field from glpi_networkequipments is done at the end of migration
        // framework process
        if (!FieldExists('glpi_networkequipments', 'mac')) {
            // Nothing to be done : migration of NetworkPort already OK !
            // But don't add display preference for NetworkPortMigration if none exists
            if (!TableExists('glpi_networkportmigrations')) {
                unset($ADDTODISPLAYPREF['NetworkPortMigration']);
            }
            $migration->displayWarning('Network Framework already migrated: nothing to be done !', false);
            return;
        }
        foreach ($originTables as $table => $originTable) {
            if (!TableExists($originTable) && TableExists($table)) {
                $migration->copyTable($table, $originTable);
                $migration->displayWarning("To be safe, we are working on {$originTable}. " . "It is a copy of {$table}", false);
            }
        }
    }
    // Remove all tables created by any previous migration
    $new_network_ports = array('glpi_fqdns', 'glpi_ipaddresses', 'glpi_ipaddresses_ipnetworks', 'glpi_ipnetworks', 'glpi_networkaliases', 'glpi_networknames', 'glpi_networkportaggregates', 'glpi_networkportdialups', 'glpi_networkportethernets', 'glpi_networkportlocals', 'glpi_networkportmigrations', 'glpi_networkportwifis', 'glpi_wifinetworks');
    foreach ($new_network_ports as $table) {
        $migration->dropTable($table);
    }
    // Create the glpi_networkportmigrations that is a copy of origin_glpi_networkports
    $query = "CREATE TABLE `glpi_networkportmigrations` LIKE `origin_glpi_networkports`";
    $DB->queryOrDie($query, "0.84 create glpi_networkportmigrations");
    // And add the error motive fields
    foreach (NetworkPortMigration::getMotives() as $key => $name) {
        $migration->addField('glpi_networkportmigrations', $key, 'bool');
    }
    $migration->migrationOneTable('glpi_networkportmigrations');
    $migration->displayMessage(sprintf(__('Data migration - %s'), 'glpi_fqdns'));
    // Adding FQDN table
    if (!TableExists('glpi_fqdns')) {
        $query = "CREATE TABLE `glpi_fqdns` (\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                  `fqdn` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n                  `comment` text COLLATE utf8_unicode_ci,\n                  PRIMARY KEY (`id`),\n                  KEY `entities_id` (`entities_id`),\n                  KEY `name` (`name`),\n                  KEY `fqdn` (`fqdn`),\n                  KEY `is_recursive` (`is_recursive`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.84 create glpi_fqdns");
        $fqdn = new FQDN();
        // Then, populate it from domains (beware that "domains" can be FQDNs and Windows workgroups)
        $query = "SELECT DISTINCT LOWER(`name`) AS name, `comment`\n                FROM `glpi_domains`";
        foreach ($DB->request($query) as $domain) {
            $domainName = $domain['name'];
            // We ensure that domains have at least 1 dote to be sure it is not a Windows workgroup
            if (strpos($domainName, '.') !== false && FQDN::checkFQDN($domainName)) {
                $migration->insertInTable($fqdn->getTable(), array('entities_id' => 0, 'name' => $domainName, 'fqdn' => $domainName, 'comment' => $domain['comment']));
            }
        }
    }
    $migration->displayMessage(sprintf(__('Data migration - %s'), 'glpi_ipaddresses'));
    // Adding IPAddress table
    if (!TableExists('glpi_ipaddresses')) {
        $query = "CREATE TABLE `glpi_ipaddresses` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `entities_id` int(11) NOT NULL DEFAULT '0',\n                  `items_id` int(11) NOT NULL DEFAULT '0',\n                  `itemtype` varchar(100) COLLATE utf8_unicode_ci NOT NULL,\n                  `version` tinyint unsigned DEFAULT '0',\n                  `name` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n                  `binary_0`  int unsigned NOT NULL DEFAULT '0',\n                  `binary_1`  int unsigned NOT NULL DEFAULT '0',\n                  `binary_2`  int unsigned NOT NULL DEFAULT '0',\n                  `binary_3`  int unsigned NOT NULL DEFAULT '0',\n                  PRIMARY KEY (`id`),\n                  KEY `entities_id` (`entities_id`),\n                  KEY `textual` (`name`),\n                  KEY `binary` (`binary_0`, `binary_1`, `binary_2`, `binary_3`),\n                  KEY `item` (`itemtype`, `items_id`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.84 create glpi_ipaddresses");
    }
    $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'glpi_wifinetworks'));
    // Adding WifiNetwork table
    if (!TableExists('glpi_wifinetworks')) {
        $query = "CREATE TABLE `glpi_wifinetworks` (\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                 `essid` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n                 `mode` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL\n                        COMMENT 'ad-hoc, access_point',\n                 `comment` text COLLATE utf8_unicode_ci,\n                 PRIMARY KEY (`id`),\n                 KEY `entities_id` (`entities_id`),\n                 KEY `essid` (`essid`),\n                 KEY `name` (`name`)\n               ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.84 create glpi_wifinetworks");
    }
    $migration->displayMessage(sprintf(__('Data migration - %s'), "glpi_ipnetworks"));
    // Adding IPNetwork table
    if (!TableExists('glpi_ipnetworks')) {
        $query = "CREATE TABLE `glpi_ipnetworks` (\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                  `ipnetworks_id` int(11) NOT NULL DEFAULT '0',\n                  `completename` text COLLATE utf8_unicode_ci,\n                  `level` int(11) NOT NULL DEFAULT '0',\n                  `ancestors_cache` longtext COLLATE utf8_unicode_ci,\n                  `sons_cache` longtext COLLATE utf8_unicode_ci,\n                  `addressable` tinyint(1) NOT NULL DEFAULT '0',\n                  `version` tinyint unsigned DEFAULT '0',\n                  `name` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n                  `address` varchar(40) COLLATE utf8_unicode_ci DEFAULT NULL,\n                  `address_0`  int unsigned NOT NULL DEFAULT '0',\n                  `address_1`  int unsigned NOT NULL DEFAULT '0',\n                  `address_2`  int unsigned NOT NULL DEFAULT '0',\n                  `address_3`  int unsigned NOT NULL DEFAULT '0',\n                  `netmask` varchar(40) COLLATE utf8_unicode_ci DEFAULT NULL,\n                  `netmask_0`  int unsigned NOT NULL DEFAULT '0',\n                  `netmask_1`  int unsigned NOT NULL DEFAULT '0',\n                  `netmask_2`  int unsigned NOT NULL DEFAULT '0',\n                  `netmask_3`  int unsigned NOT NULL DEFAULT '0',\n                  `gateway` varchar(40) COLLATE utf8_unicode_ci DEFAULT NULL,\n                  `gateway_0`  int unsigned NOT NULL DEFAULT '0',\n                  `gateway_1`  int unsigned NOT NULL DEFAULT '0',\n                  `gateway_2`  int unsigned NOT NULL DEFAULT '0',\n                  `gateway_3`  int unsigned NOT NULL DEFAULT '0',\n                  `comment` text COLLATE utf8_unicode_ci,\n                  PRIMARY KEY (`id`),\n                  KEY `network_definition` (`entities_id`,`address`,`netmask`),\n                  KEY `address` (`address_0`, `address_1`, `address_2`, `address_3`),\n                  KEY `netmask` (`netmask_0`, `netmask_1`, `netmask_2`, `netmask_3`),\n                  KEY `gateway` (`gateway_0`, `gateway_1`, `gateway_2`, `gateway_3`),\n                  KEY `name` (`name`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.84 create glpi_ipnetworks");
        // Retrieve all the networks from the current network ports and add them to the IPNetworks
        $query = "SELECT DISTINCTROW INET_NTOA(INET_ATON(`ip`)&INET_ATON(`netmask`)) AS address,\n                     `netmask`, `gateway`, `entities_id`\n                FROM `origin_glpi_networkports`\n                ORDER BY `gateway` DESC";
        $address = new IPAddress();
        $netmask = new IPNetmask();
        $gateway = new IPAddress();
        $network = new IPNetwork();
        foreach ($DB->request($query) as $entry) {
            $address = $entry['address'];
            $netmask = $entry['netmask'];
            $gateway = $entry['gateway'];
            $entities_id = $entry['entities_id'];
            if (empty($address) || $address == '0.0.0.0' || empty($netmask) || $netmask == '0.0.0.0' || $netmask == '255.255.255.255') {
                continue;
            }
            if ($gateway == '0.0.0.0') {
                $gateway = '';
            }
            $networkDefinition = "{$address}/{$netmask}";
            $networkName = $networkDefinition . (empty($gateway) ? "" : " - " . $gateway);
            $input = array('entities_id' => $entities_id, 'name' => $networkName, 'network' => $networkDefinition, 'gateway' => $gateway, 'ipnetworks_id' => 0, 'addressable' => 1, 'completename' => $networkName, 'level' => 1);
            $preparedInput = $network->prepareInput($input);
            if (is_array($preparedInput['input'])) {
                $input = $preparedInput['input'];
                if (isset($preparedInput['error'])) {
                    $query = "SELECT id, items_id, itemtype\n                         FROM origin_glpi_networkports\n                         WHERE INET_NTOA(INET_ATON(`ip`)&INET_ATON(`netmask`)) = '{$address}'\n                               AND `netmask` = '{$netmask}'\n                               AND `gateway` = '{$gateway}'\n                               AND `entities_id` = '{$entities_id}'";
                    $result = $DB->query($query);
                    foreach ($DB->request($query) as $data) {
                        addNetworkPortMigrationError($data['id'], 'invalid_gateway');
                        logNetworkPortError('network warning', $data['id'], $data['itemtype'], $data['items_id'], $preparedInput['error']);
                    }
                }
                $migration->insertInTable($network->getTable(), $input);
            } else {
                if (isset($preparedInput['error'])) {
                    $query = "SELECT id, items_id, itemtype\n                      FROM origin_glpi_networkports\n                      WHERE INET_NTOA(INET_ATON(`ip`)&INET_ATON(`netmask`)) = '" . $entry['address'] . "'\n                            AND `netmask` = '{$netmask}'\n                            AND `gateway` = '{$gateway}'\n                            AND `entities_id` = '{$entities_id}'";
                    $result = $DB->query($query);
                    foreach ($DB->request($query) as $data) {
                        addNetworkPortMigrationError($data['id'], 'invalid_network');
                        logNetworkPortError('network error', $data['id'], $data['itemtype'], $data['items_id'], $preparedInput['error']);
                    }
                }
            }
        }
    }
    $migration->displayMessage(sprintf(__('Data migration - %s'), "glpi_ipnetworks_vlans"));
    // Adding IPNetwork table
    if (!TableExists('glpi_ipnetworks_vlans')) {
        $query = "CREATE TABLE `glpi_ipnetworks_vlans` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `ipnetworks_id` int(11) NOT NULL DEFAULT '0',\n                  `vlans_id` int(11) NOT NULL DEFAULT '0',\n                  PRIMARY KEY (`id`),\n                  UNIQUE KEY `link` (`ipnetworks_id`, `vlans_id`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;";
        $DB->queryOrDie($query, "0.84 create glpi_ipnetworks_vlans");
    }
    $migration->displayMessage(sprintf(__('Data migration - %s'), "glpi_networknames"));
    // Adding NetworkName table
    if (!TableExists('glpi_networknames')) {
        $query = "CREATE TABLE `glpi_networknames` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `entities_id` int(11) NOT NULL DEFAULT '0',\n                  `items_id` int(11) NOT NULL DEFAULT '0',\n                  `itemtype` varchar(100) COLLATE utf8_unicode_ci NOT NULL,\n                  `name` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n                  `comment` text COLLATE utf8_unicode_ci,\n                  `fqdns_id` int(11) NOT NULL DEFAULT '0',\n                  `is_deleted` tinyint(1) NOT NULL DEFAULT '0',\n                  `is_dynamic` tinyint(1) NOT NULL DEFAULT '0',\n                  PRIMARY KEY (`id`),\n                  KEY `entities_id` (`entities_id`),\n                  KEY `FQDN` (`name`,`fqdns_id`),\n                  KEY `name` (`name`),\n                  KEY `item` (`itemtype`, `items_id`),\n                  KEY `fqdns_id` (`fqdns_id`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.84 create glpi_networknames");
        // Retrieve all the networks from the current network ports and add them to the IPNetworks
        $query = "SELECT `ip`, `id`, `entities_id`, `itemtype`, `items_id`\n                FROM `origin_glpi_networkports`\n                WHERE `ip` <> ''";
        foreach ($DB->request($query) as $entry) {
            if (empty($entry["ip"])) {
                continue;
            }
            createNetworkNameFromItem('NetworkPort', $entry['id'], $entry['items_id'], $entry['itemtype'], $entry['entities_id'], $entry["ip"]);
        }
    }
    $migration->displayMessage(sprintf(__('Change of the database layout - %s'), "glpi_networkaliases"));
    // Adding NetworkAlias table
    if (!TableExists('glpi_networkaliases')) {
        $query = "CREATE TABLE `glpi_networkaliases` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `entities_id` int(11) NOT NULL DEFAULT '0',\n                  `networknames_id` int(11) NOT NULL DEFAULT '0',\n                  `name` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n                  `fqdns_id` int(11) NOT NULL DEFAULT '0',\n                  `comment` text COLLATE utf8_unicode_ci,\n                  PRIMARY KEY (`id`),\n                  KEY `entities_id` (`entities_id`),\n                  KEY `name` (`name`),\n                  KEY `networknames_id` (`networknames_id`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.84 create glpi_networkaliases");
    }
    $migration->displayMessage(sprintf(__('Data migration - %s'), "glpi_ipaddresses_ipnetworks"));
    // Adding IPAddress_IPNetwork table
    if (!TableExists('glpi_ipaddresses_ipnetworks')) {
        $query = "CREATE TABLE `glpi_ipaddresses_ipnetworks` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `ipaddresses_id` int(11) NOT NULL DEFAULT '0',\n                  `ipnetworks_id` int(11) NOT NULL DEFAULT '0',\n                  PRIMARY KEY (`id`),\n                  UNIQUE KEY `unicity` (`ipaddresses_id`,`ipnetworks_id`),\n                  KEY `ipnetworks_id` (`ipnetworks_id`),\n                  KEY `ipaddresses_id` (`ipaddresses_id`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;";
        $DB->queryOrDie($query, "0.84 create glpi_ipaddresses_ipnetworks");
    }
    $migration->displayMessage(sprintf(__('Change of the database layout - %s'), "glpi_networkinterfaces"));
    // Update NetworkPorts
    $migration->addField('glpi_networkports', 'instantiation_type', 'string', array('after' => 'name', 'update' => "'NetworkPortEthernet'"));
    $migration->displayMessage(sprintf(__('Data migration - %s'), "glpi_networkports"));
    // Retrieve all the networks from the current network ports and add them to the IPNetwork
    $query = "SELECT *\n             FROM `glpi_networkinterfaces`";
    foreach ($DB->request($query) as $entry) {
        $instantiation_type = "";
        switch ($entry['name']) {
            case 'Local':
                $instantiation_type = "NetworkPortLocal";
                break;
            case 'Ethernet':
                $instantiation_type = "NetworkPortEthernet";
                break;
            case 'Wifi':
                $instantiation_type = "NetworkPortWifi";
                break;
            case 'Dialup':
                $instantiation_type = "NetworkPortDialup";
                break;
            default:
                if (preg_match('/TX/i', $entry['name']) || preg_match('/SX/i', $entry['name']) || preg_match('/Ethernet/i', $entry['name'])) {
                    $instantiation_type = "NetworkPortEthernet";
                }
                break;
        }
        /// In case of unknown Interface Type, we should have to set instantiation_type to ''
        /// Thus we should be able to convert it later to correct type (ethernet, wifi, loopback ...)
        if (!empty($instantiation_type)) {
            $query = "UPDATE `glpi_networkports`\n                   SET `instantiation_type` = '{$instantiation_type}'\n                   WHERE `id` IN (SELECT `id`\n                                  FROM `origin_glpi_networkports`\n                                  WHERE `networkinterfaces_id` = '" . $entry['id'] . "')";
            $DB->queryOrDie($query, "0.84 update instantiation_type field of glpi_networkports");
            // Clear $instantiation_type for next check inside the loop
            unset($instantiation_type);
        }
    }
    foreach (array('ip', 'gateway', 'netmask', 'netpoints_id', 'networkinterfaces_id', 'subnet') as $field) {
        $migration->dropField('glpi_networkports', $field);
    }
    foreach (array('ip', 'mac') as $field) {
        $migration->dropField('glpi_networkequipments', $field);
    }
    $migration->displayMessage(sprintf(__('Data migration - %s'), 'Index mac field and transform address mac to lower'));
    $query = "UPDATE `glpi_networkports`\n             SET `mac` = LOWER(`mac`)";
    $DB->queryOrDie($query, "0.84 transforme MAC to lower case");
    $migration->addKey('glpi_networkports', 'mac');
    $migration->displayMessage(sprintf(__('Data migration - %s'), 'Update migration of interfaces errors'));
    $query = "SELECT id\n             FROM `glpi_networkports`\n             WHERE `instantiation_type` = ''";
    foreach ($DB->request($query) as $networkPortID) {
        addNetworkPortMigrationError($networkPortID['id'], 'unknown_interface_type');
    }
    $migration->displayMessage(sprintf(__('Change of the database layout - %s'), "glpi_networkportethernets"));
    // Adding NetworkPortEthernet table
    if (!TableExists('glpi_networkportethernets')) {
        $query = "CREATE TABLE `glpi_networkportethernets` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `networkports_id` int(11) NOT NULL DEFAULT '0',\n                  `items_devicenetworkcards_id` int(11) NOT NULL DEFAULT '0',\n                  `netpoints_id` int(11) NOT NULL DEFAULT '0',\n                  `type` varchar(10) COLLATE utf8_unicode_ci DEFAULT '' COMMENT 'T, LX, SX',\n                  `speed` int(11) NOT NULL DEFAULT '10' COMMENT 'Mbit/s: 10, 100, 1000, 10000',\n                  PRIMARY KEY (`id`),\n                  UNIQUE KEY `networkports_id` (`networkports_id`),\n                  KEY `card` (`items_devicenetworkcards_id`),\n                  KEY `netpoint` (`netpoints_id`),\n                  KEY `type` (`type`),\n                  KEY `speed` (`speed`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.84 create glpi_networkportethernets");
        $port = new NetworkPortEthernet();
        updateNetworkPortInstantiation($port, array('`netpoints_id`' => 'netpoints_id'), true);
    }
    $migration->displayMessage(sprintf(__('Change of the database layout - %s'), "glpi_networkportwifis"));
    // Adding NetworkPortWifi table
    if (!TableExists('glpi_networkportwifis')) {
        $query = "CREATE TABLE `glpi_networkportwifis` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `networkports_id` int(11) NOT NULL DEFAULT '0',\n                  `items_devicenetworkcards_id` int(11) NOT NULL DEFAULT '0',\n                  `wifinetworks_id` int(11) NOT NULL DEFAULT '0',\n                  `networkportwifis_id` int(11) NOT NULL DEFAULT '0'\n                                        COMMENT 'only usefull in case of Managed node',\n                  `version` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL\n                            COMMENT 'a, a/b, a/b/g, a/b/g/n, a/b/g/n/y',\n                  `mode` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL\n                         COMMENT 'ad-hoc, managed, master, repeater, secondary, monitor, auto',\n                  PRIMARY KEY (`id`),\n                  UNIQUE KEY `networkports_id` (`networkports_id`),\n                  KEY `card` (`items_devicenetworkcards_id`),\n                  KEY `essid` (`wifinetworks_id`),\n                  KEY `version` (`version`),\n                  KEY `mode` (`mode`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.84 create glpi_networkportwifis");
        $port = new NetworkPortWifi();
        updateNetworkPortInstantiation($port, array(), true);
    }
    $migration->displayMessage(sprintf(__('Change of the database layout - %s'), "glpi_networkportlocals"));
    // Adding NetworkPortLocal table
    if (!TableExists('glpi_networkportlocals')) {
        $query = "CREATE TABLE `glpi_networkportlocals` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `networkports_id` int(11) NOT NULL DEFAULT '0',\n                  PRIMARY KEY (`id`),\n                  UNIQUE KEY `networkports_id` (`networkports_id`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.84 create glpi_networkportlocals");
        $port = new NetworkPortLocal();
        updateNetworkPortInstantiation($port, array(), false);
    }
    $migration->displayMessage(sprintf(__('Change of the database layout - %s'), "glpi_networkportdialups"));
    // Adding NetworkPortDialup table
    if (!TableExists('glpi_networkportdialups')) {
        $query = "CREATE TABLE `glpi_networkportdialups` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `networkports_id` int(11) NOT NULL DEFAULT '0',\n                  PRIMARY KEY (`id`),\n                  UNIQUE KEY `networkports_id` (`networkports_id`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.84 create glpi_networkportdialups");
        $port = new NetworkPortDialup();
        updateNetworkPortInstantiation($port, array(), true);
    }
    $migration->displayMessage(sprintf(__('Change of the database layout - %s'), "glpi_networkportaggregates"));
    // Adding NetworkPortAggregate table
    if (!TableExists('glpi_networkportaggregates')) {
        $query = "CREATE TABLE `glpi_networkportaggregates` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `networkports_id` int(11) NOT NULL DEFAULT '0',\n                  `networkports_id_list` TEXT DEFAULT NULL\n                             COMMENT 'array of associated networkports_id',\n                  PRIMARY KEY (`id`),\n                  UNIQUE KEY `networkports_id` (`networkports_id`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.84 create glpi_networkportaggregates");
        // Transform NetworkEquipment local MAC address as a networkport that aggregates all ports
        $query = "SELECT *\n                FROM `origin_glpi_networkequipments`\n                WHERE `mac` != ''\n                      OR `ip` != ''";
        $port_input = array('itemtype' => 'NetworkEquipment', 'logical_number' => '0', 'name' => 'management', 'instantiation_type' => 'NetworkPortAggregate');
        foreach ($DB->request($query) as $equipment) {
            $networkequipments_id = $equipment['id'];
            $query = "SELECT `id`, `ip`, `mac`\n                   FROM `origin_glpi_networkports`\n                   WHERE `itemtype` = 'NetworkEquipment'\n                         AND `items_id` = '{$networkequipments_id}'\n                         AND (`ip` = '" . $equipment['ip'] . "'\n                              OR `mac` = '" . $equipment['mac'] . "')";
            $both = array();
            $mac = array();
            $ip = array();
            foreach ($DB->request($query) as $ports) {
                if ($ports['ip'] == $equipment['ip']) {
                    if ($ports['mac'] == $equipment['mac']) {
                        $both[] = $ports['id'];
                    } else {
                        $ip[] = $ports['id'];
                    }
                } else {
                    $mac[] = $ports['id'];
                }
            }
            if (count($both) != 1) {
                // Only add a NetworkPort if there is 0 or more than one element !
                $port_input['items_id'] = $networkequipments_id;
                $port_input['entities_id'] = $equipment['entities_id'];
                $port_input['is_recursive'] = $equipment['is_recursive'];
                $port_input['mac'] = strtolower($equipment['mac']);
                $networkports_id = $migration->insertInTable('glpi_networkports', $port_input);
                $aggregate_input = array();
                $aggregate_input['networkports_id'] = $networkports_id;
                $aggregate_input['networkports_id_list'] = exportArrayToDB($both);
                $migration->insertInTable('glpi_networkportaggregates', $aggregate_input);
                createNetworkNameFromItem('NetworkPort', $networkports_id, $equipment['id'], 'NetworkEquipment', $equipment['entities_id'], $equipment['ip']);
                foreach ($both as $aggregated_networkports_id) {
                    $query = "DELETE\n                         FROM `glpi_networknames`\n                         WHERE `itemtype` = 'NetworkPort'\n                               AND `items_id` = '{$aggregated_networkports_id}'";
                    $DB->query($query);
                    $query = "UPDATE `glpi_networkports`\n                         SET `mac` = ''\n                         WHERE `id` = '{$aggregated_networkports_id}'";
                    $DB->query($query);
                }
            }
        }
    }
    $migration->displayMessage(sprintf(__('Change of the database layout - %s'), "glpi_networkportaliases"));
    // Adding NetworkPortAlias table
    if (!TableExists('glpi_networkportaliases')) {
        $query = "CREATE TABLE `glpi_networkportaliases` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `networkports_id` int(11) NOT NULL DEFAULT '0',\n                  `networkports_id_alias` int(11) NOT NULL DEFAULT '0',\n                  PRIMARY KEY (`id`),\n                  UNIQUE KEY `networkports_id` (`networkports_id`),\n                  KEY `networkports_id_alias` (`networkports_id_alias`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.84 create glpi_networkportaliases");
        // New element, so, we don't need to create items
    }
    $migration->addField('glpi_networkports_vlans', 'tagged', 'bool', array('value' => '0'));
    $migration->addField('glpi_vlans', 'entities_id', 'integer', array('value' => '0', 'after' => 'id'));
    $migration->addKey('glpi_vlans', 'entities_id');
    $migration->addField('glpi_vlans', 'is_recursive', 'bool', array('value' => '0', 'after' => 'entities_id', 'update' => '1'));
    $migration->addKey('glpi_vlans', 'tag');
    $migration->displayMessage(sprintf(__('Data migration - %s'), 'Update connections between IPAddress and IPNetwork'));
    // Here, we are sure that there is only IPv4 addresses. So, the SQL requests are simplified
    $query = "SELECT `id`, `address_3`, `netmask_3`\n             FROM `glpi_ipnetworks`";
    if ($network_result = $DB->query($query)) {
        unset($query);
        while ($ipnetwork_row = $DB->fetch_assoc($network_result)) {
            $ipnetworks_id = $ipnetwork_row['id'];
            $netmask = floatval($ipnetwork_row['netmask_3']);
            $address = floatval($ipnetwork_row['address_3']) & $netmask;
            $query = "SELECT `id`\n                   FROM `glpi_ipaddresses`\n                   WHERE (`glpi_ipaddresses`.`binary_3` & '{$netmask}') = {$address}\n                         AND `glpi_ipaddresses`.`version` = '4'\n                   GROUP BY `items_id`";
            if ($ipaddress_result = $DB->query($query)) {
                unset($query);
                while ($link = $DB->fetch_assoc($ipaddress_result)) {
                    $query = "INSERT INTO `glpi_ipaddresses_ipnetworks`\n                                (`ipaddresses_id`, `ipnetworks_id`)\n                         VALUES ('" . $link['id'] . "', '{$ipnetworks_id}')";
                    $DB->query($query);
                    unset($query);
                }
            }
        }
    }
    $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'Drop table glpi_networkportmigrations if empty'));
    if (countElementsInTable("glpi_networkportmigrations") == 0) {
        $migration->dropTable("glpi_networkportmigrations");
        $migration->dropTable("glpi_networkportinterfaces");
        unset($ADDTODISPLAYPREF['NetworkPortMigration']);
    }
    // We migrate glpi_networkequipments: mac field presence is used to check if framework has
    // already been migrated
    $migration->migrationOneTable('glpi_networkequipments');
    foreach ($originTables as $table) {
        $migration->dropTable($table);
    }
}
function pluginFusioninventoryInstall($version, $migrationname = 'Migration')
{
    global $DB;
    ini_set("memory_limit", "-1");
    ini_set("max_execution_time", "0");
    $migration = new $migrationname($version);
    /*
     * Load classes
     */
    foreach (glob(GLPI_ROOT . '/plugins/fusioninventory/inc/*.php') as $file) {
        require_once $file;
    }
    $migration->displayMessage("Installation of plugin FusionInventory");
    // Get informations of plugin
    /*
     * Clean if Fusion / Tracker has been installed and uninstalled (not clean correctly)
     */
    $migration->displayMessage("Clean data from old installation of the plugin");
    $sql = "DELETE FROM `glpi_displaypreferences`\n         WHERE `itemtype`='5150'";
    $DB->query($sql);
    $sql = "DELETE FROM `glpi_displaypreferences`\n         WHERE `itemtype`='5151'";
    $DB->query($sql);
    $sql = "DELETE FROM `glpi_displaypreferences`\n         WHERE `itemtype`='5152'";
    $DB->query($sql);
    $sql = "DELETE FROM `glpi_displaypreferences`\n         WHERE `itemtype`='5153'";
    $DB->query($sql);
    $sql = "DELETE FROM `glpi_displaypreferences`\n         WHERE `itemtype`='5156'";
    $DB->query($sql);
    $sql = "DELETE FROM `glpi_displaypreferences`\n         WHERE `itemtype`='5157'";
    $DB->query($sql);
    $sql = "DELETE FROM `glpi_displaypreferences`\n         WHERE `itemtype`='5158'";
    $DB->query($sql);
    $sql = "DELETE FROM `glpi_displaypreferences`\n         WHERE `itemtype`='5159'";
    $DB->query($sql);
    $sql = "DELETE FROM `glpi_displaypreferences`\n         WHERE `itemtype`='5161'";
    $DB->query($sql);
    $sql = "DELETE FROM `glpi_displaypreferences`\n         WHERE `itemtype`='5165'";
    $DB->query($sql);
    $sql = "DELETE FROM `glpi_displaypreferences`\n         WHERE `itemtype`='5166'";
    $DB->query($sql);
    $sql = "DELETE FROM `glpi_displaypreferences`\n         WHERE `itemtype`='5167'";
    $DB->query($sql);
    $sql = "DELETE FROM `glpi_displaypreferences`\n         WHERE `itemtype`='5168'";
    $DB->query($sql);
    $sql = "DELETE FROM `glpi_displaypreferences`\n         WHERE `itemtype` LIKE 'PluginFusioninventory%'";
    $DB->query($sql);
    $sql = "DELETE FROM `glpi_displaypreferences`\n         WHERE `itemtype` LIKE 'PluginFusinvinventory%'";
    $DB->query($sql);
    $sql = "DELETE FROM `glpi_displaypreferences`\n         WHERE `itemtype` LIKE 'PluginFusinvsnmp%'";
    $DB->query($sql);
    // Purge network ports have itemtype tp 5153
    $networkPort = new NetworkPort();
    $sql = "SELECT * FROM `glpi_networkports`\n            WHERE `itemtype`='5153'";
    $result = $DB->query($sql);
    while ($data = $DB->fetch_array($result)) {
        $networkPort->delete(array('id' => $data['id']), 1);
    }
    /*
     * Remove old rules
     */
    $migration->displayMessage("Clean rules from old installation of the plugin");
    $Rule = new Rule();
    $a_rules = $Rule->find("`sub_type`='PluginFusioninventoryInventoryRuleImport'");
    foreach ($a_rules as $data) {
        $Rule->delete($data);
    }
    $a_rules = $Rule->find("`sub_type`='PluginFusinvinventoryRuleEntity'");
    foreach ($a_rules as $data) {
        $Rule->delete($data);
    }
    $a_rules = $Rule->find("`sub_type`='PluginFusinvinventoryRuleLocation'");
    foreach ($a_rules as $data) {
        $Rule->delete($data);
    }
    /*
     * Create DB structure
     */
    $migration->displayMessage("Creation tables in database");
    $DB_file = GLPI_ROOT . "/plugins/fusioninventory/install/mysql/plugin_fusioninventory-empty.sql";
    if (!$DB->runFile($DB_file)) {
        $migration->displayMessage("Error on creation tables in database");
    }
    if (!$DB->runFile(GLPI_ROOT . "/plugins/fusioninventory/install/mysql/usbid.sql")) {
        $migration->displayMessage("Error on creation table usbid in database");
    }
    if (!$DB->runFile(GLPI_ROOT . "/plugins/fusioninventory/install/mysql/pciid.sql")) {
        $migration->displayMessage("Error on creation table pciid in database");
    }
    if (!$DB->runFile(GLPI_ROOT . "/plugins/fusioninventory/install/mysql/oui.sql")) {
        $migration->displayMessage("Error on creation table oui in database");
    }
    /*
     * Creation of folders
     */
    $migration->displayMessage("Creation of folders");
    if (!is_dir(GLPI_PLUGIN_DOC_DIR . '/fusioninventory')) {
        mkdir(GLPI_PLUGIN_DOC_DIR . '/fusioninventory');
    }
    if (!is_dir(GLPI_PLUGIN_DOC_DIR . '/fusioninventory/tmp')) {
        mkdir(GLPI_PLUGIN_DOC_DIR . '/fusioninventory/tmp');
    }
    if (!is_dir(GLPI_PLUGIN_DOC_DIR . '/fusioninventory/xml')) {
        mkdir(GLPI_PLUGIN_DOC_DIR . '/fusioninventory/xml');
    }
    if (!is_dir(GLPI_PLUGIN_DOC_DIR . '/fusioninventory/xml/computer')) {
        mkdir(GLPI_PLUGIN_DOC_DIR . '/fusioninventory/xml/computer');
    }
    if (!is_dir(GLPI_PLUGIN_DOC_DIR . '/fusioninventory/xml/printer')) {
        mkdir(GLPI_PLUGIN_DOC_DIR . '/fusioninventory/xml/printer');
    }
    if (!is_dir(GLPI_PLUGIN_DOC_DIR . '/fusioninventory/xml/networkequipment')) {
        mkdir(GLPI_PLUGIN_DOC_DIR . '/fusioninventory/xml/networkequipment');
    }
    if (!is_dir(GLPI_PLUGIN_DOC_DIR . '/fusioninventory/upload')) {
        mkdir(GLPI_PLUGIN_DOC_DIR . '/fusioninventory/upload');
    }
    if (!is_dir(GLPI_PLUGIN_DOC_DIR . '/fusioninventory/walks')) {
        mkdir(GLPI_PLUGIN_DOC_DIR . '/fusioninventory/walks');
    }
    if (!is_dir(GLPI_PLUGIN_DOC_DIR . '/fusioninventory/tmpmodels')) {
        mkdir(GLPI_PLUGIN_DOC_DIR . '/fusioninventory/tmpmodels');
    }
    /*
     * Deploy folders
     */
    if (!is_dir(GLPI_PLUGIN_DOC_DIR . '/fusioninventory/files')) {
        mkdir(GLPI_PLUGIN_DOC_DIR . '/fusioninventory/files');
    }
    if (!is_dir(GLPI_PLUGIN_DOC_DIR . '/fusioninventory/files/repository')) {
        mkdir(GLPI_PLUGIN_DOC_DIR . '/fusioninventory/files/repository');
    }
    if (!is_dir(GLPI_PLUGIN_DOC_DIR . '/fusioninventory/files/manifests')) {
        mkdir(GLPI_PLUGIN_DOC_DIR . '/fusioninventory/files/manifests');
    }
    if (!is_dir(GLPI_PLUGIN_DOC_DIR . '/fusioninventory/files/import')) {
        mkdir(GLPI_PLUGIN_DOC_DIR . '/fusioninventory/files/import');
    }
    if (!is_dir(GLPI_PLUGIN_DOC_DIR . '/fusioninventory/files/export')) {
        mkdir(GLPI_PLUGIN_DOC_DIR . '/fusioninventory/files/export');
    }
    /*
     * Manage profiles
     */
    $migration->displayMessage("Initialize profiles");
    PluginFusioninventoryProfile::initProfile();
    /*
     * bug of purge network port when purge unmanaged devices, so we clean
     */
    $sql = "SELECT `glpi_networkports`.`id` as nid FROM `glpi_networkports`\n         LEFT JOIN `glpi_plugin_fusioninventory_unmanageds`\n            ON `glpi_plugin_fusioninventory_unmanageds`.`id` = `glpi_networkports`.`items_id`\n         WHERE `itemtype`='PluginFusioninventoryUnmanaged'\n            AND `glpi_plugin_fusioninventory_unmanageds`.`id` IS NULL ";
    $result = $DB->query($sql);
    while ($data = $DB->fetch_array($result)) {
        $networkPort->delete(array('id' => $data['nid']), 1);
    }
    /*
     * Add config
     */
    $migration->displayMessage("Initialize configuration");
    $pfConfig = new PluginFusioninventoryConfig();
    $pfConfig->initConfigModule();
    $configLogField = new PluginFusioninventoryConfigLogField();
    $configLogField->initConfig();
    /*
     * Register Agent TASKS
     */
    $migration->displayMessage("Initialize agent TASKS");
    $pfAgentmodule = new PluginFusioninventoryAgentmodule();
    $input = array();
    $input['modulename'] = "WAKEONLAN";
    $input['is_active'] = 0;
    $input['exceptions'] = exportArrayToDB(array());
    $pfAgentmodule->add($input);
    $input = array();
    $input['modulename'] = "INVENTORY";
    $input['is_active'] = 1;
    $input['exceptions'] = exportArrayToDB(array());
    $pfAgentmodule->add($input);
    $input = array();
    $input['modulename'] = "InventoryComputerESX";
    $input['is_active'] = 0;
    $input['exceptions'] = exportArrayToDB(array());
    $pfAgentmodule->add($input);
    $input = array();
    $input['modulename'] = "NETWORKINVENTORY";
    $input['is_active'] = 0;
    $input['exceptions'] = exportArrayToDB(array());
    $pfAgentmodule->add($input);
    $input = array();
    $input['modulename'] = "NETWORKDISCOVERY";
    $input['is_active'] = 0;
    $input['exceptions'] = exportArrayToDB(array());
    $pfAgentmodule->add($input);
    $input = array();
    $input['modulename'] = "DEPLOY";
    $input['is_active'] = 0;
    $input['exceptions'] = exportArrayToDB(array());
    $pfAgentmodule->add($input);
    $input = array();
    $input['modulename'] = "Collect";
    $input['is_active'] = 1;
    $input['exceptions'] = exportArrayToDB(array());
    $pfAgentmodule->add($input);
    /*
     * Add cron task
     */
    $migration->displayMessage("Initialize cron task");
    CronTask::Register('PluginFusioninventoryTask', 'taskscheduler', '60', array('mode' => 2, 'allowmode' => 3, 'logs_lifetime' => 30));
    Crontask::Register('PluginFusioninventoryTaskjobstate', 'cleantaskjob', 3600 * 24, array('mode' => 2, 'allowmode' => 3, 'logs_lifetime' => 30));
    Crontask::Register('PluginFusioninventoryNetworkPortLog', 'cleannetworkportlogs', 3600 * 24, array('mode' => 2, 'allowmode' => 3, 'logs_lifetime' => 30));
    CronTask::Register('PluginFusioninventoryTaskjob', 'updatedynamictasks', '60', array('mode' => 2, 'allowmode' => 3, 'logs_lifetime' => 30, 'state' => 0));
    Crontask::Register('PluginFusioninventoryAgent', 'cleanoldagents', 3600 * 24, array('mode' => 2, 'allowmode' => 3, 'logs_lifetime' => 30, 'comment' => 'Clean agents not contacted since xxx days'));
    Crontask::Register('PluginFusioninventoryAgentWakeup', 'wakeupAgents', 120, array('mode' => 2, 'allowmode' => 3, 'logs_lifetime' => 30, 'comment' => 'Wake agents ups'));
    /*
     * Create rules
     */
    $migration->displayMessage("Create rules");
    $pfSetup = new PluginFusioninventorySetup();
    $pfSetup->initRules();
    /*
     * Add notification for configuration management
     */
    /*
     *  Import OCS locks
     */
    $migration->displayMessage("Import OCS locks if exists");
    $pfLock = new PluginFusioninventoryLock();
    $pfLock->importFromOcs();
    Crontask::Register('PluginFusioninventoryTaskjobstate', 'cleantaskjob', 3600 * 24, array('mode' => 2, 'allowmode' => 3, 'logs_lifetime' => 30));
    $pfNetworkporttype = new PluginFusioninventoryNetworkporttype();
    $pfNetworkporttype->init();
    require_once GLPI_ROOT . "/plugins/fusioninventory/inc/inventorycomputerstat.class.php";
    PluginFusioninventoryInventoryComputerStat::init();
    $mode_cli = basename($_SERVER['SCRIPT_NAME']) == "cli_install.php";
}
Example #19
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;
}
 static function updateSession()
 {
     global $CFG_GLPI;
     return;
     $pmSecurity = new self();
     $a_data = $pmSecurity->find("`users_id`='" . $_SESSION['glpiID'] . "' " . " AND `session_id`='" . session_id() . "'", '', 1);
     if (count($a_data) == 1) {
         $data = current($a_data);
         $data['session'] = Toolbox::addslashes_deep(exportArrayToDB($_SESSION));
         $debug_sql = 0;
         if ($CFG_GLPI["debug_sql"]) {
             $debug_sql = $CFG_GLPI["debug_sql"];
             $CFG_GLPI["debug_sql"] = 0;
         }
         $pmSecurity->update($data);
         if ($debug_sql) {
             $CFG_GLPI["debug_sql"] = $debug_sql;
         }
     }
 }
Example #21
0
/**
 * Update from 0.84 to 0.85
 *
 * @return bool for success (will die for most error)
**/
function update084to085()
{
    global $DB, $migration;
    $updateresult = true;
    $ADDTODISPLAYPREF = array();
    $DELFROMDISPLAYPREF = array();
    //TRANS: %s is the number of new version
    $migration->displayTitle(sprintf(__('Update to %s'), '0.85'));
    $migration->setVersion('0.85');
    $backup_tables = false;
    $newtables = array('glpi_blacklistedmailcontents', 'glpi_changecosts', 'glpi_changes', 'glpi_changes_groups', 'glpi_changes_items', 'glpi_changes_problems', 'glpi_changes_projects', 'glpi_changes_suppliers', 'glpi_changes_tickets', 'glpi_changes_users', 'glpi_changetasks', 'glpi_changevalidations', 'glpi_dropdowntranslations', 'glpi_knowbaseitemtranslations', 'glpi_notepads', 'glpi_problemcosts', 'glpi_projectcosts', 'glpi_projects', 'glpi_projects_changes', 'glpi_projects_items', 'glpi_projectstates', 'glpi_projecttasks', 'glpi_projecttasks_tickets', 'glpi_projecttaskteams', 'glpi_projecttasktypes', 'glpi_projectteams', 'glpi_projecttypes', 'glpi_queuedmails');
    foreach ($newtables as $new_table) {
        // rename new tables if exists ?
        if (TableExists($new_table)) {
            $migration->dropTable("backup_{$new_table}");
            $migration->displayWarning("{$new_table} table already exists. " . "A backup have been done to backup_{$new_table}.");
            $backup_tables = true;
            $query = $migration->renameTable("{$new_table}", "backup_{$new_table}");
        }
    }
    if ($backup_tables) {
        $migration->displayWarning("You can delete backup tables if you have no need of them.", true);
    }
    $migration->displayMessage(sprintf(__('Data migration - %s'), 'config table'));
    if (FieldExists('glpi_configs', 'version')) {
        if (!TableExists('origin_glpi_configs')) {
            $migration->copyTable('glpi_configs', 'origin_glpi_configs');
        }
        $query = "SELECT *\n                 FROM `glpi_configs`\n                 WHERE `id` = '1'";
        $result_of_configs = $DB->query($query);
        // Update glpi_configs
        $migration->addField('glpi_configs', 'context', 'VARCHAR(150) COLLATE utf8_unicode_ci', array('update' => "'core'"));
        $migration->addField('glpi_configs', 'name', 'VARCHAR(150) COLLATE utf8_unicode_ci', array('update' => "'version'"));
        $migration->addField('glpi_configs', 'value', 'text', array('update' => "'0.85'"));
        $migration->addKey('glpi_configs', array('context', 'name'), 'unicity', 'UNIQUE');
        $migration->migrationOneTable('glpi_configs');
        $fields = array();
        if ($DB->numrows($result_of_configs) == 1) {
            $configs = $DB->fetch_assoc($result_of_configs);
            unset($configs['id']);
            unset($configs['version']);
            // First drop fields not to have constraint on insert
            foreach ($configs as $name => $value) {
                $migration->dropField('glpi_configs', $name);
            }
            $migration->migrationOneTable('glpi_configs');
            // Then insert new values
            foreach ($configs as $name => $value) {
                $query = "INSERT INTO `glpi_configs`\n                             (`context`, `name`, `value`)\n                      VALUES ('core', '{$name}', '" . addslashes($value) . "');";
                $DB->query($query);
            }
        }
        $migration->dropField('glpi_configs', 'version');
        $migration->migrationOneTable('glpi_configs');
        $migration->dropTable('origin_glpi_configs');
    }
    $migration->displayMessage(sprintf(__('Data migration - %s'), 'profile table'));
    if (!TableExists('glpi_profilerights')) {
        if (!TableExists('origin_glpi_profiles')) {
            $migration->copyTable('glpi_profiles', 'origin_glpi_profiles');
        }
        $query = "CREATE TABLE `glpi_profilerights` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `profiles_id` int(11) NOT NULL DEFAULT '0',\n                  `name` varchar(255) DEFAULT NULL,\n                  `rights` int(11) NOT NULL DEFAULT '0',\n                  PRIMARY KEY (`id`),\n                  UNIQUE KEY `unicity` (`profiles_id`, `name`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.85 add table glpi_profilerights");
        $query = "DESCRIBE `origin_glpi_profiles`";
        $rights = array();
        foreach ($DB->request($query) as $field) {
            if ($field['Type'] == 'char(1)') {
                $rights[$field['Field']] = $field['Field'];
                $migration->dropField('glpi_profiles', $field['Field']);
            }
        }
        $query = "SELECT *\n                FROM `origin_glpi_profiles`";
        foreach ($DB->request($query) as $profile) {
            $profiles_id = $profile['id'];
            foreach ($rights as $right) {
                $new_right = 0;
                if ($profile[$right] == 'r' || $profile[$right] == '1') {
                    $new_right = READ;
                } else {
                    if ($profile[$right] == 'w') {
                        $new_right = ALLSTANDARDRIGHT;
                    }
                }
                $query = "INSERT INTO `glpi_profilerights`\n                             (`profiles_id`, `name`, `rights`)\n                      VALUES ('{$profiles_id}', '{$right}', '" . $new_right . "')";
                $DB->query($query);
            }
        }
        $migration->migrationOneTable('glpi_profiles');
        $migration->dropTable('origin_glpi_profiles');
    }
    // New system of profiles
    // delete import_externalauth_users
    foreach ($DB->request("glpi_profilerights", "`name` = 'import_externalauth_users' AND `rights` = '" . ALLSTANDARDRIGHT . "'") as $profrights) {
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = `rights` | " . User::IMPORTEXTAUTHUSERS . "\n                 WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                       AND `name` = 'user'";
        $DB->queryOrDie($query, "0.85 update user with import_externalauth_users right");
    }
    $query = "DELETE\n             FROM `glpi_profilerights`\n             WHERE `name` = 'import_externalauth_users'";
    $DB->queryOrDie($query, "0.85 delete import_externalauth_users right");
    // save value of rule_ticket to root_rule_ticket
    $query = "UPDATE `glpi_profilerights`\n              SET `name` = 'root_rule_ticket'\n              WHERE `name` = 'rule_ticket'";
    $DB->queryOrDie($query, "0.85 rename rule_ticket to root_rule_ticket");
    // rename entity_rule_ticket to rule_ticket
    $query = "UPDATE `glpi_profilerights`\n              SET `name` = 'rule_ticket'\n              WHERE `name` = 'entity_rule_ticket'";
    $DB->queryOrDie($query, "0.85 rename entity_rule_ticket to rule_ticket");
    // delete root_rule_ticket
    foreach ($DB->request("glpi_profilerights", "`name` = 'root_rule_ticket' AND `rights` = '1'") as $profrights) {
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` =  `rights` | " . RuleTicket::PARENT . "\n                 WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                       AND `name` = 'rule_ticket'";
        $DB->queryOrDie($query, "0.85 update new rule_ticket with old rule_ticket right");
    }
    $query = "DELETE\n             FROM `glpi_profilerights`\n             WHERE `name` = 'root_rule_ticket'";
    $DB->queryOrDie($query, "0.85 delete old rule_ticket right");
    // delete knowbase_admin
    foreach ($DB->request("glpi_profilerights", "`name` = 'knowbase_admin' AND `rights` = '1'") as $profrights) {
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = `rights` | " . KnowbaseItem::KNOWBASEADMIN . "\n                 WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                      AND `name` = 'knowbase'";
        $DB->queryOrDie($query, "0.85 update knowbase with knowbase_admin right");
    }
    $query = "DELETE\n             FROM `glpi_profilerights`\n             WHERE `name` = 'knowbase_admin'";
    $DB->queryOrDie($query, "0.85 delete knowbase_admin right");
    // delete faq
    foreach ($DB->request("glpi_profilerights", "`name` = 'faq' AND `rights` = '1'") as $profrights) {
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = `rights` | " . KnowbaseItem::READFAQ . "\n                 WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                       AND `name` = 'knowbase'";
        $DB->queryOrDie($query, "0.85 update knowbase with read faq right");
    }
    foreach ($DB->request("glpi_profilerights", "`name` = 'faq' AND `rights` = '" . ALLSTANDARDRIGHT . "'") as $profrights) {
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = `rights` | " . KnowbaseItem::READFAQ . " | " . KnowbaseItem::PUBLISHFAQ . "\n                 WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                       AND `name` = 'knowbase'";
        $DB->queryOrDie($query, "0.85 update knowbase with write faq right");
    }
    $query = "DELETE\n             FROM `glpi_profilerights`\n             WHERE `name` = 'faq'";
    $DB->queryOrDie($query, "0.85 delete faq right");
    // delete user_authtype
    foreach ($DB->request("glpi_profilerights", "`name` = 'user_authtype' AND `rights` = '1'") as $profrights) {
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = `rights` | " . User::READAUTHENT . "\n                 WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                       AND `name` = 'user'";
        $DB->queryOrDie($query, "0.85 update user with read user_authtype right");
    }
    foreach ($DB->request("glpi_profilerights", "`name` = 'user_authtype' AND `rights` = '" . ALLSTANDARDRIGHT . "'") as $profrights) {
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = `rights` | " . User::READAUTHENT . " | " . User::UPDATEAUTHENT . "\n                 WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                       AND `name` = 'user'";
        $DB->queryOrDie($query, "0.85 update user with write user_authtype right");
    }
    $query = "DELETE\n             FROM `glpi_profilerights`\n             WHERE `name` = 'user_authtype'";
    $DB->queryOrDie($query, "0.85 delete user_authtype right");
    // delete entity_helpdesk
    foreach ($DB->request("glpi_profilerights", "`name` = 'entity_helpdesk' AND `rights` = '1'") as $profrights) {
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = `rights` | " . Entity::READHELPDESK . "\n                 WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                       AND `name` = 'entity'";
        $DB->queryOrDie($query, "0.85 update entity with read entity_helpdesk right");
    }
    foreach ($DB->request("glpi_profilerights", "`name` = 'entity_helpdesk' AND `rights` = '" . ALLSTANDARDRIGHT . "'") as $profrights) {
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = `rights` | " . Entity::READHELPDESK . " | " . Entity::UPDATEHELPDESK . "\n                 WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                       AND `name` = 'entity'";
        $DB->queryOrDie($query, "0.85 update user with write entity_helpdesk right");
    }
    $query = "DELETE\n             FROM `glpi_profilerights`\n             WHERE `name` = 'entity_helpdesk'";
    $DB->queryOrDie($query, "0.85 delete entity_helpdesk right");
    // delete reservation_helpdesk
    foreach ($DB->request("glpi_profilerights", "`name` = 'reservation_helpdesk' AND `rights` = '1'") as $profrights) {
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = `rights` | " . ReservationItem::RESERVEANITEM . "\n                 WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                      AND `name` = 'reservation_central'";
        $DB->queryOrDie($query, "0.85 update reservation_central with reservation_helpdesk right");
    }
    $query = "DELETE\n             FROM `glpi_profilerights`\n             WHERE `name` = 'reservation_helpdesk'";
    $DB->queryOrDie($query, "0.85 delete reservation_helpdesk right");
    // rename reservation_central
    $query = "UPDATE `glpi_profilerights`\n              SET `name` = 'reservation'\n              WHERE `name` = 'reservation_central'";
    $DB->queryOrDie($query, "0.85 delete reservation_central");
    // pour que la procédure soit ré-entrante et ne pas perdre les sélections dans le profile
    if (countElementsInTable("glpi_profilerights", "`name` = 'ticket'") == 0) {
        // rename create_ticket
        $query = "UPDATE `glpi_profilerights`\n                 SET `name` = 'ticket'\n                 WHERE `name` = 'create_ticket'";
        $DB->queryOrDie($query, "0.85 rename create_ticket to ticket");
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = " . (CREATE | Ticket::READMY) . "\n                 WHERE `name` = 'ticket'\n                       AND `rights` = '1'";
        $DB->queryOrDie($query, "0.85 update ticket with create_ticket right");
    }
    // delete update_ticket
    foreach ($DB->request("glpi_profilerights", "`name` = 'update_ticket' AND `rights` = '1'") as $profrights) {
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = `rights` | " . UPDATE . "\n                 WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                      AND `name` = 'ticket'";
        $DB->queryOrDie($query, "0.85 update ticket with update_ticket right");
    }
    $query = "DELETE\n             FROM `glpi_profilerights`\n             WHERE `name` = 'update_ticket'";
    $DB->queryOrDie($query, "0.85 delete update_ticket right");
    // delete delete_ticket
    foreach ($DB->request("glpi_profilerights", "`name` = 'delete_ticket' AND `rights` = '1'") as $profrights) {
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = `rights` | " . DELETE . " | " . PURGE . "\n                 WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                      AND `name` = 'ticket'";
        $DB->queryOrDie($query, "0.85 update ticket with delete_ticket right");
    }
    $query = "DELETE\n             FROM `glpi_profilerights`\n             WHERE `name` = 'delete_ticket'";
    $DB->queryOrDie($query, "0.85 delete delete_ticket right");
    // delete show_all_ticket
    foreach ($DB->request("glpi_profilerights", "`name` = 'show_all_ticket' AND `rights` = '1'") as $profrights) {
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = `rights` | " . Ticket::READALL . "\n                 WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                      AND `name` = 'ticket'";
        $DB->queryOrDie($query, "0.85 update ticket with show_all_ticket right");
    }
    $query = "DELETE\n             FROM `glpi_profilerights`\n             WHERE `name` = 'show_all_ticket'";
    $DB->queryOrDie($query, "0.85 delete show_all_ticket right");
    // delete show_group_ticket
    foreach ($DB->request("glpi_profilerights", "`name` = 'show_group_ticket' AND `rights` = '1'") as $profrights) {
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = `rights` | " . Ticket::READGROUP . "\n                 WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                      AND `name` = 'ticket'";
        $DB->queryOrDie($query, "0.85 update ticket with show_group_ticket right");
    }
    $query = "DELETE\n             FROM `glpi_profilerights`\n             WHERE `name` = 'show_group_ticket'";
    $DB->queryOrDie($query, "0.85 delete show_group_ticket right");
    // delete show_assign_ticket
    foreach ($DB->request("glpi_profilerights", "`name` = 'show_assign_ticket' AND `rights` = '1'") as $profrights) {
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = `rights` | " . Ticket::READASSIGN . "\n                 WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                      AND `name` = 'ticket'";
        $DB->queryOrDie($query, "0.85 update ticket with show_assign_ticket right");
    }
    $query = "DELETE\n             FROM `glpi_profilerights`\n             WHERE `name` = 'show_assign_ticket'";
    $DB->queryOrDie($query, "0.85 delete show_assign_ticket right");
    // delete assign_ticket
    foreach ($DB->request("glpi_profilerights", "`name` = 'assign_ticket' AND `rights` = '1'") as $profrights) {
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = `rights` | " . Ticket::ASSIGN . "\n                 WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                      AND `name` = 'ticket'";
        $DB->queryOrDie($query, "0.85 update ticket with assign_ticket right");
    }
    $query = "DELETE\n             FROM `glpi_profilerights`\n             WHERE `name` = 'assign_ticket'";
    $DB->queryOrDie($query, "0.85 delete assign_ticket right");
    // delete steal_ticket
    foreach ($DB->request("glpi_profilerights", "`name` = 'steal_ticket' AND `rights` = '1'") as $profrights) {
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = `rights` | " . Ticket::STEAL . "\n                 WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                      AND `name` = 'ticket'";
        $DB->queryOrDie($query, "0.85 update ticket with steal_ticket right");
    }
    $query = "DELETE\n             FROM `glpi_profilerights`\n             WHERE `name` = 'steal_ticket'";
    $DB->queryOrDie($query, "0.85 delete steal_ticket right");
    // delete own_ticket
    foreach ($DB->request("glpi_profilerights", "`name` = 'own_ticket' AND `rights` = '1'") as $profrights) {
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = `rights` | " . Ticket::OWN . "\n                 WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                      AND `name` = 'ticket'";
        $DB->queryOrDie($query, "0.85 update ticket with own_ticket right");
    }
    $query = "DELETE\n             FROM `glpi_profilerights`\n             WHERE `name` = 'own_ticket'";
    $DB->queryOrDie($query, "0.85 delete own_ticket right");
    // delete update_priority
    foreach ($DB->request("glpi_profilerights", "`name` = 'update_priority' AND `rights` = '1'") as $profrights) {
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = `rights` | " . Ticket::CHANGEPRIORITY . "\n                 WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                      AND `name` = 'ticket'";
        $DB->queryOrDie($query, "0.85 update ticket with update_priority right");
    }
    $query = "DELETE\n             FROM `glpi_profilerights`\n             WHERE `name` = 'update_priority'";
    $DB->queryOrDie($query, "0.85 delete update_priority right");
    // pour que la procédure soit ré-entrante et ne pas perdre les sélections dans le profile
    if (countElementsInTable("glpi_profilerights", "`name` = 'followup'") == 0) {
        // rename create_ticket
        $query = "UPDATE `glpi_profilerights`\n                 SET `name` = 'followup'\n                 WHERE `name` = 'global_add_followups'";
        $DB->queryOrDie($query, "0.85 rename global_add_followups to followup");
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = " . TicketFollowup::ADDALLTICKET . "\n                 WHERE `name` = 'followup'\n                       AND `rights` = '1'";
        $DB->queryOrDie($query, "0.85 update followup with global_add_followups right");
    }
    // delete add_followups
    foreach ($DB->request("glpi_profilerights", "`name` = 'add_followups' AND `rights` = '1'") as $profrights) {
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = `rights` | " . TicketFollowup::ADDMYTICKET . "\n                 WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                      AND `name` = 'followup'";
        $DB->queryOrDie($query, "0.85 update followup with add_followups right");
    }
    $query = "DELETE\n             FROM `glpi_profilerights`\n             WHERE `name` = 'add_followups'";
    $DB->queryOrDie($query, "0.85 delete add_followups right");
    // delete group_add_followups
    foreach ($DB->request("glpi_profilerights", "`name` = 'group_add_followups' AND `rights` = '1'") as $profrights) {
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = `rights` | " . TicketFollowup::ADDGROUPTICKET . "\n                 WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                      AND `name` = 'followup'";
        $DB->queryOrDie($query, "0.85 update followup with group_add_followups right");
    }
    $query = "DELETE\n             FROM `glpi_profilerights`\n             WHERE `name` = 'group_add_followups'";
    $DB->queryOrDie($query, "0.85 delete group_add_followups right");
    // delete observe_ticket for followup
    foreach ($DB->request("glpi_profilerights", "`name` = 'observe_ticket' AND `rights` = '1'") as $profrights) {
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = `rights` | " . TicketFollowup::SEEPUBLIC . "\n                 WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                      AND `name` = 'followup'";
        $DB->queryOrDie($query, "0.85 update followup with observe_ticket right");
    }
    // don't delete observe_ticket because already use for task
    // delete show_full_ticket for followup
    foreach ($DB->request("glpi_profilerights", "`name` = 'show_full_ticket' AND `rights` = '1'") as $profrights) {
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = `rights` | " . TicketFollowup::SEEPUBLIC . " | " . TicketFollowup::SEEPRIVATE . "\n                 WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                      AND `name` = 'followup'";
        $DB->queryOrDie($query, "0.85 update followup with show_full_ticket right");
    }
    // don't delete show_full_ticket because already use for task
    // delete update_followups
    foreach ($DB->request("glpi_profilerights", "`name` = 'update_followups' AND `rights` = '1'") as $profrights) {
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = `rights` | " . READ . " | " . TicketFollowup::UPDATEALL . "\n                 WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                      AND `name` = 'followup'";
        $DB->queryOrDie($query, "0.85 update followup with update_followups right");
    }
    $query = "DELETE\n             FROM `glpi_profilerights`\n             WHERE `name` = 'update_followups'";
    $DB->queryOrDie($query, "0.85 delete update_followups right");
    // delete update_own_followups
    foreach ($DB->request("glpi_profilerights", "`name` = 'update_own_followups' AND `rights` = '1'") as $profrights) {
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = `rights` | " . READ . " | " . TicketFollowup::UPDATEMY . "\n                 WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                      AND `name` = 'followup'";
        $DB->queryOrDie($query, "0.85 update followup with update_own_followups right");
    }
    $query = "DELETE\n             FROM `glpi_profilerights`\n             WHERE `name` = 'update_own_followups'";
    $DB->queryOrDie($query, "0.85 delete update_own_followups right");
    // delete delete_followups
    foreach ($DB->request("glpi_profilerights", "`name` = 'delete_followups' AND `rights` = '1'") as $profrights) {
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = `rights` | " . PURGE . "\n                 WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                      AND `name` = 'followup'";
        $DB->queryOrDie($query, "0.85 update followup with delete_followups right");
    }
    $query = "DELETE\n             FROM `glpi_profilerights`\n             WHERE `name` = 'delete_followups'";
    $DB->queryOrDie($query, "0.85 delete delete_followups right");
    // pour que la procédure soit ré-entrante et ne pas perdre les sélections dans le profile
    if (countElementsInTable("glpi_profilerights", "`name` = 'task'") == 0) {
        // rename create_ticket
        $query = "UPDATE `glpi_profilerights`\n                 SET `name` = 'task'\n                 WHERE `name` = 'global_add_tasks'";
        $DB->queryOrDie($query, "0.85 rename global_add_tasks to task");
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = " . TicketTask::ADDALLTICKET . "\n                 WHERE `name` = 'task'\n                       AND `rights` = '1'";
        $DB->queryOrDie($query, "0.85 update followup with global_add_tasks right");
    }
    // delete update_tasks
    foreach ($DB->request("glpi_profilerights", "`name` = 'update_tasks' AND `rights` = '1'") as $profrights) {
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = `rights` | " . READ . " | " . TicketTask::UPDATEALL . " | " . PURGE . "\n                 WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                      AND `name` = 'task'";
        $DB->queryOrDie($query, "0.85 update task with update_tasks right");
    }
    $query = "DELETE\n             FROM `glpi_profilerights`\n             WHERE `name` = 'update_tasks'";
    $DB->queryOrDie($query, "0.85 delete update_tasks right");
    // delete observe_ticket for task
    foreach ($DB->request("glpi_profilerights", "`name` = 'observe_ticket' AND `rights` = '1'") as $profrights) {
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = `rights` | " . TicketTask::SEEPUBLIC . "\n                 WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                      AND `name` = 'task'";
        $DB->queryOrDie($query, "0.85 update task with observe_ticket right");
    }
    $query = "DELETE\n             FROM `glpi_profilerights`\n             WHERE `name` = 'observe_ticket'";
    $DB->queryOrDie($query, "0.85 delete observe_ticket right");
    // delete show_full_ticket for task
    foreach ($DB->request("glpi_profilerights", "`name` = 'show_full_ticket' AND `rights` = '1'") as $profrights) {
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = `rights` | " . TicketTask::SEEPUBLIC . " | " . TicketTask::SEEPRIVATE . "\n                 WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                      AND `name` = 'task'";
        $DB->queryOrDie($query, "0.85 update task with show_full_ticket right");
    }
    $query = "DELETE\n             FROM `glpi_profilerights`\n             WHERE `name` = 'show_full_ticket'";
    $DB->queryOrDie($query, "0.85 delete show_full_ticket right");
    // pour que la procédure soit ré-entrante et ne pas perdre les sélections dans le profile
    if (countElementsInTable("glpi_profilerights", "`name` = 'ticketvalidation'") == 0) {
        // rename delete_validations
        $query = "UPDATE `glpi_profilerights`\n                 SET `name` = 'ticketvalidation'\n                 WHERE `name` = 'delete_validations'";
        $DB->queryOrDie($query, "0.85 rename delete_validations to ticketvalidation");
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = " . DELETE . "\n                 WHERE `name` = 'ticketvalidation'\n                       AND `rights` = '1'";
        $DB->queryOrDie($query, "0.85 update ticketvalidation with delete_validations right");
    }
    // delete create_request_validation
    foreach ($DB->request("glpi_profilerights", "`name` = 'create_request_validation' AND `rights` = '1'") as $profrights) {
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = `rights` | " . TicketValidation::CREATEREQUEST . " | " . PURGE . "\n                 WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                       AND `name` = 'ticketvalidation'";
        $DB->queryOrDie($query, "0.85 update ticketvalidation with create_request_validation right");
    }
    $query = "DELETE\n             FROM `glpi_profilerights`\n             WHERE `name` = 'create_request_validation'";
    $DB->queryOrDie($query, "0.85 delete create_request_validation right");
    // delete create_incident_validation
    foreach ($DB->request("glpi_profilerights", "`name` = 'create_incident_validation' AND `rights` = '1'") as $profrights) {
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = `rights` | " . TicketValidation::CREATEINCIDENT . " | " . PURGE . "\n                 WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                       AND `name` = 'ticketvalidation'";
        $DB->queryOrDie($query, "0.85 update ticketvalidation with create_incident_validation right");
    }
    $query = "DELETE\n             FROM `glpi_profilerights`\n             WHERE `name` = 'create_incident_validation'";
    $DB->queryOrDie($query, "0.85 delete create_incident_validation right");
    // delete validate_request
    foreach ($DB->request("glpi_profilerights", "`name` = 'validate_request' AND `rights` = '1'") as $profrights) {
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = `rights` | " . TicketValidation::VALIDATEREQUEST . "\n                 WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                       AND `name` = 'ticketvalidation'";
        $DB->queryOrDie($query, "0.85 update ticketvalidation with validate_request right");
    }
    $query = "DELETE\n             FROM `glpi_profilerights`\n             WHERE `name` = 'validate_request'";
    $DB->queryOrDie($query, "0.85 delete validate_request right");
    // delete validate_incident
    foreach ($DB->request("glpi_profilerights", "`name` = 'validate_incident' AND `rights` = '1'") as $profrights) {
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = `rights` | " . TicketValidation::VALIDATEINCIDENT . "\n                 WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                       AND `name` = 'ticketvalidation'";
        $DB->queryOrDie($query, "0.85 update ticketvalidation with validate_incident right");
    }
    $query = "DELETE\n             FROM `glpi_profilerights`\n             WHERE `name` = 'validate_incident'";
    $DB->queryOrDie($query, "0.85 delete validate_incident right");
    // must be done after ticket right
    // pour que la procédure soit ré-entrante
    if (countElementsInTable("glpi_profilerights", "`name` = 'change'") == 0) {
        ProfileRight::addProfileRights(array('change'));
        ProfileRight::updateProfileRightAsOtherRight('change', Change::READMY, "`name` = 'ticket'\n                                                     AND `rights` & " . Ticket::OWN);
        ProfileRight::updateProfileRightAsOtherRight('change', Change::READALL, "`name` = 'ticket'\n                                                     AND `rights` & " . Ticket::READALL);
        ProfileRight::updateProfileRightAsOtherRight('change', CREATE . " | " . UPDATE . " | " . DELETE . " | " . PURGE, "`name` = 'ticket' AND `rights` & " . UPDATE);
    }
    if (countElementsInTable("glpi_profilerights", "`name` = 'changevalidation'") == 0) {
        ProfileRight::addProfileRights(array('changevalidation'));
        ProfileRight::updateProfileRightAsOtherRight('changevalidation', CREATE, "`name` = 'ticketvalidation'\n                                                     AND `rights` & " . TicketValidation::CREATEINCIDENT . "\n                                                     AND `rights` & " . TicketValidation::CREATEREQUEST);
        ProfileRight::updateProfileRightAsOtherRight('changevalidation', ChangeValidation::VALIDATE, "`name` = 'ticketvalidation'\n                                                     AND `rights` & " . TicketValidation::VALIDATEINCIDENT . "\n                                                     AND `rights` & " . TicketValidation::VALIDATEREQUEST);
        ProfileRight::updateProfileRightAsOtherRight('changevalidation', PURGE, "`name` = 'ticketvalidation'\n                                                     AND `rights` & " . PURGE);
    }
    // pour que la procédure soit ré-entrante et ne pas perdre les sélections dans le profile
    if (countElementsInTable("glpi_profilerights", "`name` = 'planning'") == 0) {
        // rename show_planning
        $query = "UPDATE `glpi_profilerights`\n                 SET `name` = 'planning'\n                 WHERE `name` = 'show_planning'";
        $DB->queryOrDie($query, "0.85 rename show_planning to planning");
        // READMY = 1 => do update needed
    }
    // delete show_group_planning
    foreach ($DB->request("glpi_profilerights", "`name` = 'show_group_planning' AND `rights` = '1'") as $profrights) {
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = `rights` | " . Planning::READGROUP . "\n                 WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                      AND `name` = 'planning'";
        $DB->queryOrDie($query, "0.85 update planning with show_group_planning right");
    }
    $query = "DELETE\n             FROM `glpi_profilerights`\n             WHERE `name` = 'show_group_planning'";
    $DB->queryOrDie($query, "0.85 delete show_group_planning right");
    // delete show_all_planning
    foreach ($DB->request("glpi_profilerights", "`name` = 'show_all_planning' AND `rights` = '1'") as $profrights) {
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = `rights` | " . Planning::READALL . "\n                 WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                      AND `name` = 'planning'";
        $DB->queryOrDie($query, "0.85 update planning with show_all_planning right");
    }
    $query = "DELETE\n             FROM `glpi_profilerights`\n             WHERE `name` = 'show_all_planning'";
    $DB->queryOrDie($query, "0.85 delete show_all_planning right");
    // pour que la procédure soit ré-entrante et ne pas perdre les sélections dans le profile
    if (countElementsInTable("glpi_profilerights", "`name` = 'problem'") == 0) {
        // rename show_my_problem
        $query = "UPDATE `glpi_profilerights`\n                 SET `name` = 'problem'\n                 WHERE `name` = 'show_my_problem'";
        $DB->queryOrDie($query, "0.85 rename show_my_problem to problem");
        // READMY = 1 => do update needed
    }
    // delete show_all_problem
    foreach ($DB->request("glpi_profilerights", "`name` = 'show_all_problem' AND `rights` = '1'") as $profrights) {
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = `rights` | " . Problem::READALL . "\n                 WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                      AND `name` = 'problem'";
        $DB->queryOrDie($query, "0.85 update problem with show_all_problem right");
    }
    $query = "DELETE\n             FROM `glpi_profilerights`\n             WHERE `name` = 'show_all_problem'";
    $DB->queryOrDie($query, "0.85 delete show_all_problem right");
    // delete edit_all_problem
    foreach ($DB->request("glpi_profilerights", "`name` = 'edit_all_problem' AND `rights` = '1'") as $profrights) {
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = `rights` | " . CREATE . " | " . UPDATE . " | " . PURGE . "\n                 WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                      AND `name` = 'problem'";
        $DB->queryOrDie($query, "0.85 update problem with edit_all_problem right");
    }
    $query = "DELETE\n             FROM `glpi_profilerights`\n             WHERE `name` = 'edit_all_problem'";
    $DB->queryOrDie($query, "0.85 delete edit_all_problem right");
    // delete delete_problem
    foreach ($DB->request("glpi_profilerights", "`name` = 'delete_problem' AND `rights` = '1'") as $profrights) {
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = `rights` | " . DELETE . "\n                 WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                      AND `name` = 'problem'";
        $DB->queryOrDie($query, "0.85 update problem with delete_problem");
    }
    $query = "DELETE\n             FROM `glpi_profilerights`\n             WHERE `name` = 'delete_problem'";
    $DB->queryOrDie($query, "0.85 delete problem right");
    // update search_config
    foreach ($DB->request("glpi_profilerights", "`name` = 'search_config' AND `rights` = '" . ALLSTANDARDRIGHT . "'") as $profrights) {
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = `rights` | " . DisplayPreference::PERSONAL . "\n                 WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                      AND `name` = 'search_config'";
        $DB->queryOrDie($query, "0.85 update search_config with search_config");
    }
    // delete search_config_global
    foreach ($DB->request("glpi_profilerights", "`name` = 'search_config_global' AND `rights` = '" . ALLSTANDARDRIGHT . "'") as $profrights) {
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = `rights` | " . DisplayPreference::GENERAL . "\n                 WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                      AND `name` = 'search_config'";
        $DB->queryOrDie($query, "0.85 update search_config with search_config_global");
    }
    $query = "DELETE\n             FROM `glpi_profilerights`\n             WHERE `name` = 'search_config_global'";
    $DB->queryOrDie($query, "0.85 delete search_config_global right");
    // delete check_update
    foreach ($DB->request("glpi_profilerights", "`name` = 'check_update' AND `rights` = '1'") as $profrights) {
        $query = "UPDATE `glpi_profilerights`\n                 SET `rights` = `rights` | " . Backup::CHECKUPDATE . "\n                 WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                      AND `name` = 'backup'";
        $DB->queryOrDie($query, "0.85 update backup with check_update");
    }
    $query = "DELETE\n             FROM `glpi_profilerights`\n             WHERE `name` = 'check_update'";
    $DB->queryOrDie($query, "0.85 delete check_update right");
    // entity_dropdown => right by object
    // pour que la procédure soit ré-entrante et ne pas perdre les sélections dans le profile
    if (countElementsInTable("glpi_profilerights", "`name` = 'domain'") == 0) {
        ProfileRight::addProfileRights(array('domain'));
        ProfileRight::updateProfileRightsAsOtherRights('domain', 'entity_dropdown');
    }
    if (countElementsInTable("glpi_profilerights", "`name` = 'location'") == 0) {
        ProfileRight::addProfileRights(array('location'));
        ProfileRight::updateProfileRightsAsOtherRights('location', 'entity_dropdown');
    }
    if (countElementsInTable("glpi_profilerights", "`name` = 'itilcategory'") == 0) {
        ProfileRight::addProfileRights(array('itilcategory'));
        ProfileRight::updateProfileRightsAsOtherRights('itilcategory', 'entity_dropdown');
    }
    if (countElementsInTable("glpi_profilerights", "`name` = 'knowbasecategory'") == 0) {
        ProfileRight::addProfileRights(array('knowbasecategory'));
        ProfileRight::updateProfileRightsAsOtherRights('knowbasecategory', 'entity_dropdown');
    }
    if (countElementsInTable("glpi_profilerights", "`name` = 'netpoint'") == 0) {
        ProfileRight::addProfileRights(array('netpoint'));
        ProfileRight::updateProfileRightsAsOtherRights('netpoint', 'entity_dropdown');
    }
    if (countElementsInTable("glpi_profilerights", "`name` = 'taskcategory'") == 0) {
        ProfileRight::addProfileRights(array('taskcategory'));
        ProfileRight::updateProfileRightsAsOtherRights('taskcategory', 'entity_dropdown');
    }
    if (countElementsInTable("glpi_profilerights", "`name` = 'state'") == 0) {
        ProfileRight::addProfileRights(array('state'));
        ProfileRight::updateProfileRightsAsOtherRights('state', 'entity_dropdown');
    }
    if (countElementsInTable("glpi_profilerights", "`name` = 'solutiontemplate'") == 0) {
        ProfileRight::addProfileRights(array('solutiontemplate'));
        ProfileRight::updateProfileRightsAsOtherRights('solutiontemplate', 'entity_dropdown');
    }
    $query = "DELETE\n             FROM `glpi_profilerights`\n             WHERE `name` = 'entity_dropdown'";
    $DB->queryOrDie($query, "0.85 delete entity_dropdown right");
    // delete notes
    $tables = array('budget', 'cartridge', 'change', 'computer', 'consumable', 'contact_enterprise', 'contract', 'document', 'entity', 'monitor', 'networking', 'peripheral', 'phone', 'printer', 'problem', 'software');
    foreach ($DB->request("glpi_profilerights", "`name` = 'notes' AND `rights` = '1'") as $profrights) {
        foreach ($tables as $table) {
            $query = "UPDATE `glpi_profilerights`\n                    SET `rights` = `rights` | " . READNOTE . "\n                    WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                          AND `name` = '{$table}'";
            $DB->queryOrDie($query, "0.85 update {$table} with read notes right");
        }
    }
    foreach ($DB->request("glpi_profilerights", "`name` = 'notes' AND `rights` = '" . ALLSTANDARDRIGHT . "'") as $profrights) {
        foreach ($tables as $table) {
            $query = "UPDATE `glpi_profilerights`\n                    SET `rights` = `rights` | " . READNOTE . " | " . UPDATENOTE . "\n                    WHERE `profiles_id` = '" . $profrights['profiles_id'] . "'\n                          AND `name` = '{$table}'";
            $DB->queryOrDie($query, "0.85 update {$table} with update notes right");
        }
    }
    $query = "DELETE\n             FROM `glpi_profilerights`\n             WHERE `name` = 'notes'";
    $DB->queryOrDie($query, "0.85 delete notes right");
    $DELFROMDISPLAYPREF['Profile'] = array(29, 35, 37, 43, 53, 54, 57, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 80, 81, 88, 93, 94, 95, 96, 97, 98, 99, 104, 113, 114, 116, 117, 121, 122, 123);
    $migration->displayMessage('Update for mailqueue');
    if (!TableExists('glpi_queuedmails')) {
        $query = "CREATE TABLE `glpi_queuedmails` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `itemtype` varchar(100) default NULL,\n                  `items_id` int(11) NOT NULL DEFAULT '0',\n                  `notificationtemplates_id` int(11) NOT NULL DEFAULT '0',\n                  `entities_id` int(11) NOT NULL DEFAULT '0',\n                  `is_deleted` tinyint(1) NOT NULL DEFAULT '0',\n                  `sent_try` int(11) NOT NULL DEFAULT '0',\n                  `create_time` datetime DEFAULT NULL,\n                  `send_time` datetime DEFAULT NULL,\n                  `sent_time` datetime DEFAULT NULL,\n                  `name` TEXT DEFAULT NULL,\n                  `sender` TEXT DEFAULT NULL,\n                  `sendername` TEXT DEFAULT NULL,\n                  `recipient` TEXT DEFAULT NULL,\n                  `recipientname` TEXT DEFAULT NULL,\n                  `replyto` TEXT DEFAULT NULL,\n                  `replytoname` TEXT DEFAULT NULL,\n                  `headers` TEXT DEFAULT NULL,\n                  `body_html` LONGTEXT DEFAULT NULL,\n                  `body_text` LONGTEXT DEFAULT NULL,\n                  `messageid` TEXT DEFAULT NULL,\n                  PRIMARY KEY (`id`),\n                  KEY `item` (`itemtype`,`items_id`, `notificationtemplates_id`),\n                  KEY `is_deleted` (`is_deleted`),\n                  KEY `entities_id` (`entities_id`),\n                  KEY `sent_try` (`sent_try`),\n                  KEY `create_time` (`create_time`),\n                  KEY `send_time` (`send_time`),\n                  KEY `sent_time` (`sent_time`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.85 add glpi_queuedmails");
        $ADDTODISPLAYPREF['QueueMail'] = array(16, 7, 20, 21, 22, 15);
    }
    if (!countElementsInTable('glpi_crontasks', "`itemtype`='QueuedMail' AND `name`='queuedmail'")) {
        $query = "INSERT INTO `glpi_crontasks`\n                       (`itemtype`, `name`, `frequency`, `param`, `state`, `mode`, `allowmode`,\n                        `hourmin`, `hourmax`, `logs_lifetime`, `lastrun`, `lastcode`, `comment`)\n                VALUES ('QueuedMail', 'queuedmail', 60, 50, 1, 1, 3,\n                        0, 24, 30, NULL, NULL, NULL)";
        $DB->queryOrDie($query, "0.85 populate glpi_crontasks for queuemail");
    }
    if (!countElementsInTable('glpi_crontasks', "`itemtype`='QueuedMail' AND `name`='queuedmailclean'")) {
        $query = "INSERT INTO `glpi_crontasks`\n                       (`itemtype`, `name`, `frequency`, `param`, `state`, `mode`, `allowmode`,\n                        `hourmin`, `hourmax`, `logs_lifetime`, `lastrun`, `lastcode`, `comment`)\n                VALUES ('QueuedMail', 'queuedmailclean', 86400, 30, 1, 1, 3,\n                        0, 24, 30, NULL, NULL, NULL)";
        $DB->queryOrDie($query, "0.85 populate glpi_crontasks for queuemail");
    }
    if (!countElementsInTable('glpi_crontasks', "`itemtype`='Crontask' AND `name`='temp'")) {
        $query = "INSERT INTO `glpi_crontasks`\n                       (`itemtype`, `name`, `frequency`, `param`, `state`, `mode`, `allowmode`,\n                        `hourmin`, `hourmax`, `logs_lifetime`, `lastrun`, `lastcode`, `comment`)\n                VALUES ('Crontask', 'temp', 3600, NULL, 1, 1, 3,\n                        0, 24, 30, NULL, NULL, NULL)";
        $DB->queryOrDie($query, "0.85 populate glpi_crontasks for clean temporary files");
    }
    if ($migration->addField("glpi_entities", "delay_send_emails", "integer", array('value' => -2))) {
        $migration->migrationOneTable('glpi_entities');
        // Set directly to root entity
        $query = 'UPDATE `glpi_entities`
                SET `delay_send_emails` = 0
                WHERE `id` = 0';
        $DB->queryOrDie($query, "0.85 default value for delay_send_emails for root entity");
    }
    // pour que la procédure soit ré-entrante
    if (countElementsInTable("glpi_profilerights", "`name` = 'queuedmail'") == 0) {
        ProfileRight::addProfileRights(array('queuedmail'));
        ProfileRight::updateProfileRightsAsOtherRights('queuedmail', 'notification');
    }
    $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'Change'));
    // changes management
    if (!TableExists('glpi_changes')) {
        $query = "CREATE TABLE `glpi_changes` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `name` varchar(255) DEFAULT NULL,\n                  `entities_id` int(11) NOT NULL DEFAULT '0',\n                  `is_recursive` tinyint(1) NOT NULL DEFAULT '0',\n                  `is_deleted` tinyint(1) NOT NULL DEFAULT '0',\n                  `status` int(11) NOT NULL DEFAULT '1',\n                  `content` longtext DEFAULT NULL,\n                  `date_mod` DATETIME DEFAULT NULL,\n                  `date` DATETIME DEFAULT NULL,\n                  `solvedate` DATETIME DEFAULT NULL,\n                  `closedate` DATETIME DEFAULT NULL,\n                  `due_date` DATETIME DEFAULT NULL,\n                  `users_id_recipient` int(11) NOT NULL DEFAULT '0',\n                  `users_id_lastupdater` int(11) NOT NULL DEFAULT '0',\n                  `urgency` int(11) NOT NULL DEFAULT '1',\n                  `impact` int(11) NOT NULL DEFAULT '1',\n                  `priority` int(11) NOT NULL DEFAULT '1',\n                  `itilcategories_id` int(11) NOT NULL DEFAULT '0',\n                  `impactcontent` longtext DEFAULT NULL,\n                  `controlistcontent` longtext DEFAULT NULL,\n                  `rolloutplancontent` longtext DEFAULT NULL,\n                  `backoutplancontent` longtext DEFAULT NULL,\n                  `checklistcontent` longtext DEFAULT NULL,\n                  `global_validation` varchar(255) COLLATE utf8_unicode_ci DEFAULT 'none',\n                  `validation_percent` int(11) NOT NULL DEFAULT '0',\n                  `solutiontypes_id` int(11) NOT NULL DEFAULT '0',\n                  `solution` text COLLATE utf8_unicode_ci,\n                  `actiontime` int(11) NOT NULL DEFAULT '0',\n                  `begin_waiting_date` datetime DEFAULT NULL,\n                  `waiting_duration` int(11) NOT NULL DEFAULT '0',\n                  `close_delay_stat` int(11) NOT NULL DEFAULT '0',\n                  `solve_delay_stat` int(11) NOT NULL DEFAULT '0',\n                  `notepad` LONGTEXT NULL,\n                  PRIMARY KEY (`id`),\n                  KEY `name` (`name`),\n                  KEY `entities_id` (`entities_id`),\n                  KEY `is_recursive` (`is_recursive`),\n                  KEY `is_deleted` (`is_deleted`),\n                  KEY `date` (`date`),\n                  KEY `closedate` (`closedate`),\n                  KEY `status` (`status`),\n                  KEY `priority` (`priority`),\n                  KEY `date_mod` (`date_mod`),\n                  KEY `itilcategories_id` (`itilcategories_id`),\n                  KEY `users_id_recipient` (`users_id_recipient`),\n                  KEY `solvedate` (`solvedate`),\n                  KEY `solutiontypes_id` (`solutiontypes_id`),\n                  KEY `urgency` (`urgency`),\n                  KEY `impact` (`impact`),\n                  KEY `due_date` (`due_date`),\n                  KEY `global_validation` (`global_validation`),\n                  KEY `users_id_lastupdater` (`users_id_lastupdater`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.85 create glpi_changes");
    }
    $migration->addField('glpi_itilcategories', 'is_change', 'bool', array('value' => 1));
    $migration->addKey('glpi_itilcategories', 'is_change');
    if (!TableExists('glpi_changes_users')) {
        $query = "CREATE TABLE `glpi_changes_users` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `changes_id` int(11) NOT NULL DEFAULT '0',\n                  `users_id` int(11) NOT NULL DEFAULT '0',\n                  `type` int(11) NOT NULL DEFAULT '1',\n                  `use_notification` tinyint(1) NOT NULL DEFAULT '0',\n                  `alternative_email` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n                  PRIMARY KEY (`id`),\n                  UNIQUE KEY `unicity` (`changes_id`,`type`,`users_id`,`alternative_email`),\n                  KEY `user` (`users_id`,`type`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.85 add table glpi_changes_users");
    }
    if (!TableExists('glpi_changes_groups')) {
        $query = "CREATE TABLE `glpi_changes_groups` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `changes_id` int(11) NOT NULL DEFAULT '0',\n                  `groups_id` int(11) NOT NULL DEFAULT '0',\n                  `type` int(11) NOT NULL DEFAULT '1',\n                  PRIMARY KEY (`id`),\n                  UNIQUE KEY `unicity` (`changes_id`,`type`,`groups_id`),\n                  KEY `group` (`groups_id`,`type`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.85 add table glpi_changes_groups");
    }
    if (!TableExists('glpi_changes_suppliers')) {
        $query = "CREATE TABLE `glpi_changes_suppliers` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `changes_id` int(11) NOT NULL DEFAULT '0',\n                  `suppliers_id` int(11) NOT NULL DEFAULT '0',\n                  `type` int(11) NOT NULL DEFAULT '1',\n                  PRIMARY KEY (`id`),\n                  UNIQUE KEY `unicity` (`changes_id`,`type`,`suppliers_id`),\n                  KEY `group` (`suppliers_id`,`type`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.85 add table glpi_changes_suppliers");
    }
    if (!TableExists('glpi_changes_items')) {
        $query = "CREATE TABLE `glpi_changes_items` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `changes_id` int(11) NOT NULL DEFAULT '0',\n                  `itemtype` varchar(100) default NULL,\n                  `items_id` int(11) NOT NULL DEFAULT '0',\n                  PRIMARY KEY (`id`),\n                  UNIQUE KEY `unicity` (`changes_id`,`itemtype`,`items_id`),\n                  KEY `item` (`itemtype`,`items_id`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.85 add table glpi_changes_items");
    }
    if (!TableExists('glpi_changes_tickets')) {
        $query = "CREATE TABLE `glpi_changes_tickets` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `changes_id` int(11) NOT NULL DEFAULT '0',\n                  `tickets_id` int(11) NOT NULL DEFAULT '0',\n                  PRIMARY KEY (`id`),\n                  UNIQUE KEY `unicity` (`changes_id`,`tickets_id`),\n                  KEY `tickets_id` (`tickets_id`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.85 add table glpi_changes_tickets");
    }
    if (!TableExists('glpi_changes_problems')) {
        $query = "CREATE TABLE `glpi_changes_problems` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `changes_id` int(11) NOT NULL DEFAULT '0',\n                  `problems_id` int(11) NOT NULL DEFAULT '0',\n                  PRIMARY KEY (`id`),\n                  UNIQUE KEY `unicity` (`changes_id`,`problems_id`),\n                  KEY `problems_id` (`problems_id`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.85 add table glpi_changes_problems");
    }
    if (!TableExists('glpi_changetasks')) {
        $query = "CREATE TABLE `glpi_changetasks` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `changes_id` int(11) NOT NULL DEFAULT '0',\n                  `taskcategories_id` int(11) NOT NULL DEFAULT '0',\n                  `state` int(11) NOT NULL DEFAULT '0',\n                  `date` datetime DEFAULT NULL,\n                  `begin` datetime DEFAULT NULL,\n                  `end` datetime DEFAULT NULL,\n                  `users_id` int(11) NOT NULL DEFAULT '0',\n                  `users_id_tech` int(11) NOT NULL DEFAULT '0',\n                  `content` longtext COLLATE utf8_unicode_ci,\n                  `actiontime` int(11) NOT NULL DEFAULT '0',\n                  PRIMARY KEY (`id`),\n                  KEY `changes_id` (`changes_id`),\n                  KEY `state` (`state`),\n                  KEY `users_id` (`users_id`),\n                  KEY `users_id_tech` (`users_id_tech`),\n                  KEY `date` (`date`),\n                  KEY `begin` (`begin`),\n                  KEY `end` (`end`),\n                  KEY `taskcategories_id` (taskcategories_id)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.85 add table glpi_changetasks");
    }
    if (!TableExists('glpi_changecosts')) {
        $query = "CREATE TABLE `glpi_changecosts` (\n               `id` int(11) NOT NULL AUTO_INCREMENT,\n               `changes_id` int(11) NOT NULL DEFAULT '0',\n               `name` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n               `comment` text COLLATE utf8_unicode_ci,\n               `begin_date` date DEFAULT NULL,\n               `end_date` date DEFAULT NULL,\n               `actiontime` int(11) NOT NULL DEFAULT '0',\n               `cost_time` decimal(20,4) NOT NULL DEFAULT '0.0000',\n               `cost_fixed` decimal(20,4) NOT NULL DEFAULT '0.0000',\n               `cost_material` decimal(20,4) NOT NULL DEFAULT '0.0000',\n               `budgets_id` int(11) NOT NULL DEFAULT '0',\n               `entities_id` int(11) NOT NULL DEFAULT '0',\n               `is_recursive` tinyint(1) NOT NULL DEFAULT '0',\n               PRIMARY KEY (`id`),\n               KEY `name` (`name`),\n               KEY `changes_id` (`changes_id`),\n               KEY `begin_date` (`begin_date`),\n               KEY `end_date` (`end_date`),\n               KEY `entities_id` (`entities_id`),\n               KEY `is_recursive` (`is_recursive`),\n               KEY `budgets_id` (`budgets_id`)\n               ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;";
        $DB->queryOrDie($query, "0.85 add table glpi_changecosts");
    }
    if (!TableExists('glpi_changevalidations')) {
        $query = "CREATE TABLE `glpi_changevalidations` (\n            `id` int(11) NOT NULL AUTO_INCREMENT,\n            `entities_id` int(11) NOT NULL DEFAULT '0',\n            `is_recursive` tinyint(1) NOT NULL DEFAULT '0',\n            `users_id` int(11) NOT NULL DEFAULT '0',\n            `changes_id` int(11) NOT NULL DEFAULT '0',\n            `users_id_validate` int(11) NOT NULL DEFAULT '0',\n            `comment_submission` text COLLATE utf8_unicode_ci,\n            `comment_validation` text COLLATE utf8_unicode_ci,\n            `status` int(11) NOT NULL DEFAULT '2',\n            `submission_date` datetime DEFAULT NULL,\n            `validation_date` datetime DEFAULT NULL,\n            PRIMARY KEY (`id`),\n            KEY `entities_id` (`entities_id`),\n            KEY `is_recursive` (`is_recursive`),\n            KEY `users_id` (`users_id`),\n            KEY `users_id_validate` (`users_id_validate`),\n            KEY `changes_id` (`changes_id`),\n            KEY `submission_date` (`submission_date`),\n            KEY `validation_date` (`validation_date`),\n            KEY `status` (`status`)\n            ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;";
        $DB->queryOrDie($query, "0.85 add table glpi_changevalidations");
    }
    // Change notifications
    $query = "SELECT *\n             FROM `glpi_notificationtemplates`\n             WHERE `itemtype` = 'Change'";
    if ($result = $DB->query($query)) {
        if ($DB->numrows($result) == 0) {
            $query = "INSERT INTO `glpi_notificationtemplates`\n                          (`name`, `itemtype`, `date_mod`)\n                   VALUES ('Changes', 'Change', NOW())";
            $DB->queryOrDie($query, "0.85 add change notification");
            $notid = $DB->insert_id();
            $query = "INSERT INTO `glpi_notificationtemplatetranslations`\n                          (`notificationtemplates_id`, `language`, `subject`,\n                           `content_text`,\n                           `content_html`)\n                   VALUES ({$notid}, '', '##change.action## ##change.title##',\n                          '##IFchange.storestatus=5##\n ##lang.change.url## : ##change.urlapprove##\n ##lang.change.solvedate## : ##change.solvedate##\n ##lang.change.solution.type## : ##change.solution.type##\n ##lang.change.solution.description## : ##change.solution.description## ##ENDIFchange.storestatus##\n ##ELSEchange.storestatus## ##lang.change.url## : ##change.url## ##ENDELSEchange.storestatus##\n\n ##lang.change.description##\n\n ##lang.change.title##  :##change.title##\n ##lang.change.authors##  :##IFchange.authors## ##change.authors## ##ENDIFchange.authors## ##ELSEchange.authors##--##ENDELSEchange.authors##\n ##lang.change.creationdate##  :##change.creationdate##\n ##IFchange.assigntousers## ##lang.change.assigntousers##  : ##change.assigntousers## ##ENDIFchange.assigntousers##\n ##lang.change.status##  : ##change.status##\n ##IFchange.assigntogroups## ##lang.change.assigntogroups##  : ##change.assigntogroups## ##ENDIFchange.assigntogroups##\n ##lang.change.urgency##  : ##change.urgency##\n ##lang.change.impact##  : ##change.impact##\n ##lang.change.priority## : ##change.priority##\n##IFchange.category## ##lang.change.category##  :##change.category## ##ENDIFchange.category## ##ELSEchange.category## ##lang.change.nocategoryassigned## ##ENDELSEchange.category##\n ##lang.change.content##  : ##change.content##\n\n##IFchange.storestatus=6##\n ##lang.change.solvedate## : ##change.solvedate##\n ##lang.change.solution.type## : ##change.solution.type##\n ##lang.change.solution.description## : ##change.solution.description##\n##ENDIFchange.storestatus##\n ##lang.change.numberofproblems## : ##change.numberofproblems##\n\n##FOREACHproblems##\n [##problem.date##] ##lang.change.title## : ##problem.title##\n ##lang.change.content## ##problem.content##\n\n##ENDFOREACHproblems##\n ##lang.change.numberoftasks## : ##change.numberoftasks##\n\n##FOREACHtasks##\n [##task.date##]\n ##lang.task.author## ##task.author##\n ##lang.task.description## ##task.description##\n ##lang.task.time## ##task.time##\n ##lang.task.category## ##task.category##\n\n##ENDFOREACHtasks##\n',\n                          '&lt;p&gt;##IFchange.storestatus=5##&lt;/p&gt;\n&lt;div&gt;##lang.change.url## : &lt;a href=\"##change.urlapprove##\"&gt;##change.urlapprove##&lt;/a&gt;&lt;/div&gt;\n&lt;div&gt;&lt;span style=\"color: #888888;\"&gt;&lt;strong&gt;&lt;span style=\"text-decoration: underline;\"&gt;##lang.change.solvedate##&lt;/span&gt;&lt;/strong&gt;&lt;/span&gt; : ##change.solvedate##&lt;br /&gt;&lt;span style=\"text-decoration: underline; color: #888888;\"&gt;&lt;strong&gt;##lang.change.solution.type##&lt;/strong&gt;&lt;/span&gt; : ##change.solution.type##&lt;br /&gt;&lt;span style=\"text-decoration: underline; color: #888888;\"&gt;&lt;strong&gt;##lang.change.solution.description##&lt;/strong&gt;&lt;/span&gt; : ##change.solution.description## ##ENDIFchange.storestatus##&lt;/div&gt;\n&lt;div&gt;##ELSEchange.storestatus## ##lang.change.url## : &lt;a href=\"##change.url##\"&gt;##change.url##&lt;/a&gt; ##ENDELSEchange.storestatus##&lt;/div&gt;\n&lt;p class=\"description b\"&gt;&lt;strong&gt;##lang.change.description##&lt;/strong&gt;&lt;/p&gt;\n&lt;p&gt;&lt;span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"&gt; ##lang.change.title##&lt;/span&gt;&#160;:##change.title## &lt;br /&gt; &lt;span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"&gt; ##lang.change.authors##&lt;/span&gt;&#160;:##IFchange.authors## ##change.authors## ##ENDIFchange.authors##    ##ELSEchange.authors##--##ENDELSEchange.authors## &lt;br /&gt; &lt;span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"&gt; ##lang.change.creationdate##&lt;/span&gt;&#160;:##change.creationdate## &lt;br /&gt; ##IFchange.assigntousers## &lt;span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"&gt; ##lang.change.assigntousers##&lt;/span&gt;&#160;: ##change.assigntousers## ##ENDIFchange.assigntousers##&lt;br /&gt; &lt;span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"&gt;##lang.change.status## &lt;/span&gt;&#160;: ##change.status##&lt;br /&gt; ##IFchange.assigntogroups## &lt;span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"&gt; ##lang.change.assigntogroups##&lt;/span&gt;&#160;: ##change.assigntogroups## ##ENDIFchange.assigntogroups##&lt;br /&gt; &lt;span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"&gt; ##lang.change.urgency##&lt;/span&gt;&#160;: ##change.urgency##&lt;br /&gt; &lt;span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"&gt; ##lang.change.impact##&lt;/span&gt;&#160;: ##change.impact##&lt;br /&gt; &lt;span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"&gt; ##lang.change.priority##&lt;/span&gt; : ##change.priority## &lt;br /&gt;##IFchange.category##&lt;span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"&gt;##lang.change.category## &lt;/span&gt;&#160;:##change.category##  ##ENDIFchange.category## ##ELSEchange.category##  ##lang.change.nocategoryassigned## ##ENDELSEchange.category##    &lt;br /&gt; &lt;span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"&gt; ##lang.change.content##&lt;/span&gt;&#160;: ##change.content##&lt;/p&gt;\n&lt;p&gt;##IFchange.storestatus=6##&lt;br /&gt;&lt;span style=\"text-decoration: underline;\"&gt;&lt;strong&gt;&lt;span style=\"color: #888888;\"&gt;##lang.change.solvedate##&lt;/span&gt;&lt;/strong&gt;&lt;/span&gt; : ##change.solvedate##&lt;br /&gt;&lt;span style=\"color: #888888;\"&gt;&lt;strong&gt;&lt;span style=\"text-decoration: underline;\"&gt;##lang.change.solution.type##&lt;/span&gt;&lt;/strong&gt;&lt;/span&gt; : ##change.solution.type##&lt;br /&gt;&lt;span style=\"text-decoration: underline; color: #888888;\"&gt;&lt;strong&gt;##lang.change.solution.description##&lt;/strong&gt;&lt;/span&gt; : ##change.solution.description##&lt;br /&gt;##ENDIFchange.storestatus##&lt;/p&gt;\n&lt;div class=\"description b\"&gt;##lang.change.numberofproblems##&#160;: ##change.numberofproblems##&lt;/div&gt;\n&lt;p&gt;##FOREACHproblems##&lt;/p&gt;\n&lt;div&gt;&lt;strong&gt; [##problem.date##] &lt;em&gt;##lang.change.title## : &lt;a href=\"##problem.url##\"&gt;##problem.title## &lt;/a&gt;&lt;/em&gt;&lt;/strong&gt;&lt;br /&gt; &lt;span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"&gt; &lt;/span&gt;&lt;span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"&gt;##lang.change.content## &lt;/span&gt; ##problem.content##\n&lt;p&gt;##ENDFOREACHproblems##&lt;/p&gt;\n&lt;div class=\"description b\"&gt;##lang.change.numberoftasks##&#160;: ##change.numberoftasks##&lt;/div&gt;\n&lt;p&gt;##FOREACHtasks##&lt;/p&gt;\n&lt;div class=\"description b\"&gt;&lt;strong&gt;[##task.date##] &lt;/strong&gt;&lt;br /&gt; &lt;span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"&gt; ##lang.task.author##&lt;/span&gt; ##task.author##&lt;br /&gt; &lt;span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"&gt; ##lang.task.description##&lt;/span&gt; ##task.description##&lt;br /&gt; &lt;span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"&gt; ##lang.task.time##&lt;/span&gt; ##task.time##&lt;br /&gt; &lt;span style=\"color: #8b8c8f; font-weight: bold; text-decoration: underline;\"&gt; ##lang.task.category##&lt;/span&gt; ##task.category##&lt;/div&gt;\n&lt;p&gt;##ENDFOREACHtasks##&lt;/p&gt;\n&lt;/div&gt;')";
            $DB->queryOrDie($query, "0.85 add change notification translation");
            $notifications = array('new' => array(), 'update' => array(Notification::ASSIGN_TECH, Notification::OLD_TECH_IN_CHARGE), 'solved' => array(), 'add_task' => array(), 'update_task' => array(), 'delete_task' => array(), 'closed' => array(), 'delete' => array());
            $notif_names = array('new' => 'New Change', 'update' => 'Update Change', 'solved' => 'Resolve Change', 'add_task' => 'Add Task', 'update_task' => 'Update Task', 'delete_task' => 'Delete Task', 'closed' => 'Close Change', 'delete' => 'Delete Change');
            foreach ($notifications as $key => $val) {
                $notifications[$key][] = Notification::AUTHOR;
                $notifications[$key][] = Notification::GLOBAL_ADMINISTRATOR;
                $notifications[$key][] = Notification::OBSERVER;
            }
            foreach ($notifications as $type => $targets) {
                $query = "INSERT INTO `glpi_notifications`\n                             (`name`, `entities_id`, `itemtype`, `event`, `mode`,\n                              `notificationtemplates_id`, `comment`, `is_recursive`, `is_active`,\n                              `date_mod`)\n                      VALUES ('" . $notif_names[$type] . "', 0, 'Change', '{$type}', 'mail',\n                              {$notid}, '', 1, 1, NOW())";
                $DB->queryOrDie($query, "0.85 add change {$type} notification");
                $notifid = $DB->insert_id();
                foreach ($targets as $target) {
                    $query = "INSERT INTO `glpi_notificationtargets`\n                                (`id`, `notifications_id`, `type`, `items_id`)\n                         VALUES (NULL, {$notifid}, " . Notification::USER_TYPE . ", {$target});";
                    $DB->queryOrDie($query, "0.85 add change {$type} notification target");
                }
            }
        }
    }
    $ADDTODISPLAYPREF['Change'] = array(12, 19, 15, 7, 18);
    $migration->addField('glpi_profiles', 'change_status', "text", array('comment' => "json encoded array of from/dest allowed status change"));
    // Add problem costs
    if (!TableExists('glpi_problemcosts')) {
        $query = "CREATE TABLE `glpi_problemcosts` (\n               `id` int(11) NOT NULL AUTO_INCREMENT,\n               `problems_id` int(11) NOT NULL DEFAULT '0',\n               `name` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n               `comment` text COLLATE utf8_unicode_ci,\n               `begin_date` date DEFAULT NULL,\n               `end_date` date DEFAULT NULL,\n               `actiontime` int(11) NOT NULL DEFAULT '0',\n               `cost_time` decimal(20,4) NOT NULL DEFAULT '0.0000',\n               `cost_fixed` decimal(20,4) NOT NULL DEFAULT '0.0000',\n               `cost_material` decimal(20,4) NOT NULL DEFAULT '0.0000',\n               `budgets_id` int(11) NOT NULL DEFAULT '0',\n               `entities_id` int(11) NOT NULL DEFAULT '0',\n               PRIMARY KEY (`id`),\n               KEY `name` (`name`),\n               KEY `problems_id` (`problems_id`),\n               KEY `begin_date` (`begin_date`),\n               KEY `end_date` (`end_date`),\n               KEY `entities_id` (`entities_id`),\n               KEY `budgets_id` (`budgets_id`)\n               ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;";
        $DB->queryOrDie($query, "0.85 add table glpi_problemcosts");
    }
    $migration->displayMessage(sprintf(__('Data migration - %s'), 'drop rules cache'));
    $migration->dropTable('glpi_rulecachecomputermodels');
    $migration->dropTable('glpi_rulecachecomputertypes');
    $migration->dropTable('glpi_rulecachemanufacturers');
    $migration->dropTable('glpi_rulecachemonitormodels');
    $migration->dropTable('glpi_rulecachemonitortypes');
    $migration->dropTable('glpi_rulecachenetworkequipmentmodels');
    $migration->dropTable('glpi_rulecachenetworkequipmenttypes');
    $migration->dropTable('glpi_rulecacheoperatingsystems');
    $migration->dropTable('glpi_rulecacheoperatingsystemservicepacks');
    $migration->dropTable('glpi_rulecacheoperatingsystemversions');
    $migration->dropTable('glpi_rulecacheperipheralmodels');
    $migration->dropTable('glpi_rulecacheperipheraltypes');
    $migration->dropTable('glpi_rulecachephonemodels');
    $migration->dropTable('glpi_rulecachephonetypes');
    $migration->dropTable('glpi_rulecacheprintermodels');
    $migration->dropTable('glpi_rulecacheprinters');
    $migration->dropTable('glpi_rulecacheprintertypes');
    $migration->dropTable('glpi_rulecachesoftwares');
    $migration->displayMessage(sprintf(__('Data migration - %s'), 'glpi_rules'));
    $migration->addField("glpi_rules", 'uuid', "string");
    $migration->addField("glpi_slalevels", 'uuid', "string");
    $migration->migrationOneTable('glpi_rules');
    $migration->migrationOneTable('glpi_slalevels');
    // Dropdown translations
    $migration->displayMessage(sprintf(__('Data migration - %s'), 'glpi_knowbaseitemtranslations'));
    Config::setConfigurationValues('core', array('translate_kb' => 0));
    if (!TableExists("glpi_knowbaseitemtranslations")) {
        $query = "CREATE TABLE IF NOT EXISTS `glpi_knowbaseitemtranslations` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `knowbaseitems_id` int(11) NOT NULL DEFAULT '0',\n                  `language` varchar(5) COLLATE utf8_unicode_ci DEFAULT NULL,\n                  `name` text COLLATE utf8_unicode_ci,\n                  `answer` longtext COLLATE utf8_unicode_ci,\n                  PRIMARY KEY (`id`),\n                  KEY `item` (`knowbaseitems_id`, `language`),\n                  FULLTEXT KEY `fulltext` (`name`,`answer`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;";
        $DB->queryOrDie($query, "0.85 add table glpi_knowbaseitemtranslations");
    }
    // kb translations
    $migration->displayMessage(sprintf(__('Data migration - %s'), 'glpi_dropdowntranslations'));
    Config::setConfigurationValues('core', array('translate_dropdowns' => 0));
    if (!TableExists("glpi_dropdowntranslations")) {
        $query = "CREATE TABLE IF NOT EXISTS `glpi_dropdowntranslations` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `items_id` int(11) NOT NULL DEFAULT '0',\n                  `itemtype` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,\n                  `language` varchar(5) COLLATE utf8_unicode_ci DEFAULT NULL,\n                  `field` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,\n                  `value` text COLLATE utf8_unicode_ci,\n                  PRIMARY KEY (`id`),\n                  UNIQUE KEY `unicity` (`itemtype`,`items_id`,`language`,`field`),\n                  KEY `typeid` (`itemtype`,`items_id`),\n                  KEY `language` (`language`),\n                  KEY `field` (`field`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;";
        $DB->queryOrDie($query, "0.85 add table glpi_dropdowntranslations");
    }
    //generate uuid for the basic rules of glpi
    // we use a complete sql where for cover all migration case (0.78 -> 0.85)
    $rules = array(array('sub_type' => 'RuleImportEntity', 'name' => 'Root', 'match' => 'AND', 'description' => ''), array('sub_type' => 'RuleRight', 'name' => 'Root', 'match' => 'AND', 'description' => ''), array('sub_type' => 'RuleMailCollector', 'name' => 'Root', 'match' => 'AND', 'description' => ''), array('sub_type' => 'RuleMailCollector', 'name' => 'Auto-Reply X-Auto-Response-Suppress', 'match' => 'AND', 'description' => 'Exclude Auto-Reply emails using X-Auto-Response-Suppress header'), array('sub_type' => 'RuleMailCollector', 'name' => 'Auto-Reply Auto-Submitted', 'match' => 'AND', 'description' => 'Exclude Auto-Reply emails using Auto-Submitted header'), array('sub_type' => 'RuleTicket', 'name' => 'Ticket location from item', 'match' => 'AND', 'description' => ''), array('sub_type' => 'RuleTicket', 'name' => 'Ticket location from user', 'match' => 'AND', 'description' => ''));
    $i = 0;
    foreach ($rules as $rule) {
        $query = "UPDATE `glpi_rules`\n                 SET `uuid` = 'STATIC-UUID-{$i}'\n                 WHERE `entities_id` = 0\n                       AND `is_recursive` = 0\n                       AND `sub_type` = '" . $rule['sub_type'] . "'\n                       AND `name` = '" . $rule['name'] . "'\n                       AND `description` = '" . $rule['description'] . "'\n                       AND `match` = '" . $rule['match'] . "'\n                 ORDER BY id ASC\n                 LIMIT 1";
        $DB->queryOrDie($query, "0.85 add uuid to basic rules (STATIC-UUID-{$i})");
        $i++;
    }
    //generate uuid for the rules of user
    foreach ($DB->request('glpi_rules', array('uuid' => NULL)) as $data) {
        $uuid = Rule::getUuid();
        $query = "UPDATE `glpi_rules`\n                SET `uuid` = '{$uuid}'\n                WHERE `id` = '" . $data['id'] . "'";
        $DB->queryOrDie($query, "0.85 add uuid to existing rules");
    }
    foreach ($DB->request('glpi_slalevels', array('uuid' => NULL)) as $data) {
        $uuid = Rule::getUuid();
        $query = "UPDATE `glpi_slalevels`\n                SET `uuid` = '{$uuid}'\n                WHERE `id` = '" . $data['id'] . "'";
        $DB->queryOrDie($query, "0.85 add uuid to existing slalevels");
    }
    $migration->addField('glpi_users', 'is_deleted_ldap', 'bool');
    $migration->addKey('glpi_users', 'is_deleted_ldap');
    Config::deleteConfigurationValues('core', array('use_ajax'));
    Config::deleteConfigurationValues('core', array('ajax_min_textsearch_load'));
    Config::deleteConfigurationValues('core', array('ajax_buffertime_load'));
    Config::deleteConfigurationValues('core', array('is_categorized_soft_expanded'));
    Config::deleteConfigurationValues('core', array('is_not_categorized_soft_expanded'));
    $migration->dropField("glpi_users", 'is_categorized_soft_expanded');
    $migration->dropField("glpi_users", 'is_not_categorized_soft_expanded');
    // Config::setConfigurationValues('core', array('use_unicodefont' => 0));
    // $migration->addField("glpi_users", 'use_unicodefont', "int(11) DEFAULT NULL");
    Config::deleteConfigurationValues('core', array('use_unicodefont'));
    $migration->dropField("glpi_users", 'use_unicodefont');
    Config::setConfigurationValues('core', array('pdffont' => 'helvetica'));
    $migration->addField("glpi_users", 'pdffont', "string");
    $migration->addField("glpi_users", 'picture', "string");
    $migration->addField("glpi_authldaps", 'picture_field', 'string');
    $migration->addField('glpi_links', 'open_window', 'bool', array('value' => 1));
    $migration->displayMessage(sprintf(__('Data migration - %s'), 'glpi_states'));
    foreach (array('is_visible_computer', 'is_visible_monitor', 'is_visible_networkequipment', 'is_visible_peripheral', 'is_visible_phone', 'is_visible_printer', 'is_visible_softwareversion') as $field) {
        $migration->addField('glpi_states', $field, 'bool', array('value' => '1'));
        $migration->addKey('glpi_states', $field);
    }
    // glpi_domains by entity
    $migration->addField('glpi_domains', 'entities_id', 'integer', array('after' => 'name'));
    $migration->addField('glpi_domains', 'is_recursive', 'bool', array('update' => '1', 'after' => 'entities_id'));
    // glpi_states by entity
    $migration->addField('glpi_states', 'entities_id', 'integer', array('after' => 'name'));
    $migration->addField('glpi_states', 'is_recursive', 'bool', array('update' => '1', 'after' => 'entities_id'));
    // add validity date for a user
    $migration->addField('glpi_users', 'begin_date', 'datetime');
    $migration->addField('glpi_users', 'end_date', 'datetime');
    // add validity date for a knowbaseitem
    $migration->addField('glpi_knowbaseitems', 'begin_date', 'datetime');
    $migration->addField('glpi_knowbaseitems', 'end_date', 'datetime');
    // Add validation percent for tickets
    $migration->addField('glpi_tickets', 'validation_percent', 'integer', array('value' => 0));
    // Add missing key
    $migration->addKey('glpi_tickettasks', 'state');
    $migration->addKey('glpi_tickettasks', 'users_id_tech');
    $migration->addKey('glpi_tickettasks', 'begin');
    $migration->addKey('glpi_tickettasks', 'end');
    // Create notification for reply to satisfaction survey based on satisfaction notif
    // Check if notifications already exists
    if (countElementsInTable('glpi_notifications', "`itemtype` = 'Ticket'\n                              AND `event` = 'replysatisfaction'") == 0) {
        // No notifications duplicate all
        $query = "SELECT *\n                FROM `glpi_notifications`\n                WHERE `itemtype` = 'Ticket'\n                      AND `event` = 'satisfaction'";
        foreach ($DB->request($query) as $notif) {
            $query = "INSERT INTO `glpi_notifications`\n                          (`name`, `entities_id`, `itemtype`, `event`, `mode`,\n                          `notificationtemplates_id`, `comment`, `is_recursive`, `is_active`,\n                          `date_mod`)\n                   VALUES ('" . addslashes($notif['name']) . " Answer',\n                           '" . $notif['entities_id'] . "', 'Ticket',\n                           'replysatisfaction', '" . $notif['mode'] . "',\n                           '" . $notif['notificationtemplates_id'] . "',\n                           '" . addslashes($notif['comment']) . "', '" . $notif['is_recursive'] . "',\n                           '" . $notif['is_active'] . "', NOW());";
            $DB->queryOrDie($query, "0.85 insert replysatisfaction notification");
            $newID = $DB->insert_id();
            $query2 = "SELECT *\n                    FROM `glpi_notificationtargets`\n                    WHERE `notifications_id` = '" . $notif['id'] . "'";
            // Add same recipent of satisfaction
            foreach ($DB->request($query2) as $target) {
                $query = "INSERT INTO `glpi_notificationtargets`\n                             (`notifications_id`, `type`, `items_id`)\n                      VALUES ({$newID}, '" . $target['type'] . "', '" . $target['items_id'] . "')";
                $DB->queryOrDie($query, "0.85 insert targets for replysatisfaction notification");
            }
            // Add Tech in charge
            $query = "INSERT INTO `glpi_notificationtargets`\n                             (`notifications_id`, `type`, `items_id`)\n                      VALUES ({$newID}, '" . Notification::USER_TYPE . "', '" . Notification::ASSIGN_TECH . "')";
            $DB->queryOrDie($query, "0.85 insert tech in charge target for replysatisfaction notification");
        }
    }
    $migration->displayMessage(sprintf(__('Data migration - %s'), 'glpi_slas'));
    // * Convert SLA resolution time to new system (ticket #4346)
    if (!FieldExists("glpi_slas", "definition_time")) {
        $migration->addField("glpi_slas", 'definition_time', "string");
        $migration->addField("glpi_slas", 'end_of_working_day', "bool");
        $migration->migrationOneTable('glpi_slas');
        // Minutes
        $query = "SELECT *\n                FROM `glpi_slas`\n                WHERE `resolution_time` <= '3000'";
        if ($result = $DB->query($query)) {
            if ($DB->numrows($result) > 0) {
                $a_ids = array();
                while ($data = $DB->fetch_assoc($result)) {
                    $a_ids[] = $data['id'];
                }
                $DB->query("UPDATE `glpi_slas`\n                        SET `definition_time` = 'minute',\n                            `resolution_time` = `resolution_time`/60\n                        WHERE `id` IN (" . implode(",", $a_ids) . ")");
            }
        }
        // Hours
        $query = "SELECT *\n                FROM `glpi_slas`\n                WHERE `resolution_time` > '3000'\n                      AND `resolution_time` <= '82800'";
        if ($result = $DB->query($query)) {
            if ($DB->numrows($result) > 0) {
                $a_ids = array();
                while ($data = $DB->fetch_assoc($result)) {
                    $a_ids[] = $data['id'];
                }
                $DB->query("UPDATE `glpi_slas`\n                        SET `definition_time` = 'hour',\n                            `resolution_time` = `resolution_time`/3600\n                        WHERE `id` IN (" . implode(",", $a_ids) . ")");
            }
        }
        // Days
        $query = "SELECT *\n                FROM `glpi_slas`\n                WHERE `resolution_time` > '82800'";
        if ($result = $DB->query($query)) {
            if ($DB->numrows($result) > 0) {
                $a_ids = array();
                while ($data = $DB->fetch_assoc($result)) {
                    $a_ids[] = $data['id'];
                }
                $DB->query("UPDATE `glpi_slas`\n                        SET `definition_time` = 'day',\n                            `resolution_time` = `resolution_time`/86400\n                        WHERE `id` IN (" . implode(",", $a_ids) . ")");
            }
        }
    }
    Config::setConfigurationValues('core', array('keep_devices_when_purging_item' => 0));
    $migration->addField("glpi_users", "keep_devices_when_purging_item", "int(11) DEFAULT NULL");
    Config::setConfigurationValues('core', array('maintenance_mode' => 0));
    Config::setConfigurationValues('core', array('maintenance_text' => ''));
    $query = "SELECT *\n             FROM `glpi_notificationtemplates`\n             WHERE `itemtype` = 'MailCollector'";
    if ($result = $DB->query($query)) {
        if ($DB->numrows($result) == 0) {
            $query = "INSERT INTO `glpi_notificationtemplates`\n                          (`name`, `itemtype`, `date_mod`)\n                   VALUES ('Receiver errors', 'MailCollector', NOW())";
            $DB->queryOrDie($query, "0.85 add mail collector notification");
            $notid = $DB->insert_id();
            $query = "INSERT INTO `glpi_notificationtemplatetranslations`\n                          (`notificationtemplates_id`, `language`, `subject`,\n                           `content_text`,\n                           `content_html`)\n                   VALUES ({$notid}, '', '##mailcollector.action##',\n                           '##FOREACHmailcollectors##\n##lang.mailcollector.name## : ##mailcollector.name##\n##lang.mailcollector.errors## : ##mailcollector.errors##\n##mailcollector.url##\n##ENDFOREACHmailcollectors##',\n'&lt;p&gt;##FOREACHmailcollectors##&lt;br /&gt;##lang.mailcollector.name## : ##mailcollector.name##&lt;br /&gt; ##lang.mailcollector.errors## : ##mailcollector.errors##&lt;br /&gt;&lt;a href=\"##mailcollector.url##\"&gt;##mailcollector.url##&lt;/a&gt;&lt;br /&gt; ##ENDFOREACHmailcollectors##&lt;/p&gt;\n&lt;p&gt;&lt;/p&gt;')";
            $DB->queryOrDie($query, "0.85 add mail collector notification translation");
            $query = "INSERT INTO `glpi_notifications`\n                          (`name`, `entities_id`, `itemtype`, `event`, `mode`,\n                           `notificationtemplates_id`, `comment`, `is_recursive`, `is_active`,\n                           `date_mod`)\n                   VALUES ('Receiver errors', 0, 'MailCollector', 'error', 'mail',\n                             {$notid}, '', 1, 1, NOW())";
            $DB->queryOrDie($query, "0.85 add mail collector notification");
            $notifid = $DB->insert_id();
            $query = "INSERT INTO `glpi_notificationtargets`\n                          (`id`, `notifications_id`, `type`, `items_id`)\n                   VALUES (NULL, {$notifid}, " . Notification::USER_TYPE . ", " . Notification::GLOBAL_ADMINISTRATOR . ");";
            $DB->queryOrDie($query, "0.85 add mail collector notification target");
        }
    }
    if (!countElementsInTable('glpi_crontasks', "`itemtype`='MailCollector' AND `name`='mailgateerror'")) {
        $query = "INSERT INTO `glpi_crontasks`\n                       (`itemtype`, `name`, `frequency`, `param`, `state`, `mode`, `allowmode`,\n                        `hourmin`, `hourmax`, `logs_lifetime`, `lastrun`, `lastcode`, `comment`)\n                VALUES ('MailCollector', 'mailgateerror', " . DAY_TIMESTAMP . ", NULL, 1, 1, 3,\n                        0, 24, 30, NULL, NULL, NULL)";
        $DB->queryOrDie($query, "0.85 populate glpi_crontasks for mailgateerror");
    }
    if (!countElementsInTable('glpi_crontasks', "`itemtype`='Crontask' AND `name`='circularlogs'")) {
        $query = "INSERT INTO `glpi_crontasks`\n                       (`itemtype`, `name`, `frequency`, `param`, `state`, `mode`, `allowmode`,\n                        `hourmin`, `hourmax`, `logs_lifetime`, `lastrun`, `lastcode`, `comment`)\n                VALUES ('Crontask', 'circularlogs', " . DAY_TIMESTAMP . ", 4, " . CronTask::STATE_DISABLE . ", 1, 3,\n                        0, 24, 30, NULL, NULL, NULL)";
        $DB->queryOrDie($query, "0.85 populate glpi_crontasks for circularlogs");
    }
    $migration->displayMessage(sprintf(__('Data migration - %s'), 'glpi_documents'));
    $migration->addField('glpi_documents', 'is_blacklisted', 'bool');
    if (!TableExists("glpi_blacklistedmailcontents")) {
        $query = "CREATE TABLE IF NOT EXISTS `glpi_blacklistedmailcontents` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `name` varchar(255) DEFAULT NULL,\n                  `content` text COLLATE utf8_unicode_ci,\n                  `comment` text COLLATE utf8_unicode_ci,\n                  PRIMARY KEY (`id`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;";
        $DB->queryOrDie($query, "0.85 add table glpi_blacklistedmailcontents");
    }
    $migration->addField('glpi_documents', 'tag', 'string');
    $migration->addField('glpi_queuedmails', 'documents', 'text');
    $migration->addKey('glpi_documents', 'tag');
    Config::setConfigurationValues('core', array('use_rich_text' => 0));
    Config::setConfigurationValues('core', array('attach_ticket_documents_to_mail' => 0));
    $migration->migrationOneTable('glpi_documents');
    $query = "UPDATE `glpi_documents`\n             SET `tag` = `id`";
    $DB->queryOrDie($query, "0.85 set tag to all documents");
    // increase password length
    $migration->changeField('glpi_users', 'password', 'password', 'string');
    $migration->displayMessage(sprintf(__('Data migration - %s'), 'glpi_softwarecategories'));
    // Hierarchical software category
    $migration->addField('glpi_softwarecategories', 'softwarecategories_id', 'integer');
    $migration->addField("glpi_softwarecategories", 'completename', "text");
    $migration->addField("glpi_softwarecategories", 'level', "integer");
    $migration->addField("glpi_softwarecategories", 'ancestors_cache', "longtext");
    $migration->addField("glpi_softwarecategories", 'sons_cache', "longtext");
    $migration->migrationOneTable('glpi_softwarecategories');
    $migration->addKey('glpi_softwarecategories', 'softwarecategories_id');
    regenerateTreeCompleteName("glpi_softwarecategories");
    $migration->displayMessage(sprintf(__('Change of the database layout - %s'), 'various'));
    // glpi_cartridgeitems  glpi_consumableitems by entity
    $migration->addField('glpi_consumableitems', 'is_recursive', 'bool', array('update' => '1', 'after' => 'entities_id'));
    $migration->addField('glpi_cartridgeitems', 'is_recursive', 'bool', array('update' => '1', 'after' => 'entities_id'));
    // Fix events
    $query = "UPDATE `glpi_events`\n             SET `type` = 'consumableitems'\n             WHERE `type` = 'consumables'";
    $DB->queryOrDie($query, "0.85 fix events for consumables");
    $query = "UPDATE `glpi_events`\n             SET `type` = 'cartridgeitems'\n             WHERE `type` = 'cartridges';";
    $DB->queryOrDie($query, "0.85 fix events for cartridges");
    // Bookmark order :
    $migration->addField('glpi_users', 'privatebookmarkorder', 'longtext');
    // Pref to comme back ticket created
    if ($migration->addField('glpi_users', 'backcreated', 'TINYINT(1) DEFAULT NULL')) {
        $query = "INSERT INTO `glpi_configs`\n                       (`context`, `name`, `value`)\n                VALUES ('core', 'backcreated', 0)";
        $DB->queryOrDie($query, "update glpi_configs with backcreated");
    }
    $migration->displayMessage(sprintf(__('Data migration - %s'), 'glpi_projects'));
    if (!TableExists("glpi_projects")) {
        $query = "CREATE TABLE IF NOT EXISTS `glpi_projects` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `name` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n                  `code` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n                  `priority` int(11) NOT NULL DEFAULT '1',\n                  `entities_id` int(11) NOT NULL DEFAULT '0',\n                  `is_recursive` tinyint(1) NOT NULL DEFAULT '0',\n                  `projects_id` int(11) NOT NULL DEFAULT '0',\n                  `projectstates_id` int(11) NOT NULL DEFAULT '0',\n                  `projecttypes_id` int(11) NOT NULL DEFAULT '0',\n                  `date` datetime DEFAULT NULL,\n                  `date_mod` datetime DEFAULT NULL,\n                  `users_id` int(11) NOT NULL DEFAULT '0',\n                  `groups_id` int(11) NOT NULL DEFAULT '0',\n                  `plan_start_date` datetime DEFAULT NULL,\n                  `plan_end_date` datetime DEFAULT NULL,\n                  `real_start_date` datetime DEFAULT NULL,\n                  `real_end_date` datetime DEFAULT NULL,\n                  `percent_done` int(11) NOT NULL DEFAULT '0',\n                  `show_on_global_gantt` tinyint(1) NOT NULL DEFAULT '0',\n                  `content` longtext DEFAULT NULL,\n                  `comment` longtext DEFAULT NULL,\n                  `notepad` longtext DEFAULT NULL,\n                  PRIMARY KEY (`id`),\n                  KEY `name` (`name`),\n                  KEY `code` (`code`),\n                  KEY `entities_id` (`entities_id`),\n                  KEY `is_recursive` (`is_recursive`),\n                  KEY `projects_id` (`projects_id`),\n                  KEY `projectstates_id` (`projectstates_id`),\n                  KEY `projecttypes_id` (`projecttypes_id`),\n                  KEY `priority` (`priority`),\n                  KEY `date` (`date`),\n                  KEY `date_mod` (`date_mod`),\n                  KEY `users_id` (`users_id`),\n                  KEY `groups_id` (`groups_id`),\n                  KEY `plan_start_date` (`plan_start_date`),\n                  KEY `plan_end_date` (`plan_end_date`),\n                  KEY `real_start_date` (`real_start_date`),\n                  KEY `real_end_date` (`real_end_date`),\n                  KEY `percent_done` (`percent_done`),\n                  KEY `show_on_global_gantt` (`show_on_global_gantt`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;";
        $DB->queryOrDie($query, "0.85 add table glpi_projects");
        $ADDTODISPLAYPREF['Project'] = array(3, 4, 12, 5, 15, 21);
    }
    $migration->addField("glpi_projects", 'is_deleted', "bool");
    if (countElementsInTable("glpi_profilerights", "`name` = 'project'") == 0) {
        ProfileRight::addProfileRights(array('project'));
        ProfileRight::updateProfileRightAsOtherRight('project', Project::READMY, "`name` = 'change'\n                                                     AND `rights` & " . Change::READMY);
        ProfileRight::updateProfileRightAsOtherRight('project', Project::READALL, "`name` = 'change'\n                                                     AND `rights` & " . Change::READALL);
        ProfileRight::updateProfileRightAsOtherRight('project', CREATE . " | " . UPDATE . " | " . DELETE . " | " . PURGE . " | " . READNOTE . " | " . UPDATENOTE, "`name` = 'change'\n                                                      AND `rights` & (" . CREATE . " | " . UPDATE . " | " . DELETE . " | " . PURGE . ')');
    }
    if (countElementsInTable("glpi_profilerights", "`name` = 'projecttask'") == 0) {
        ProfileRight::addProfileRights(array('projecttask'));
        ProfileRight::updateProfileRightAsOtherRight('projecttask', ProjectTask::READMY, "`name` = 'change'\n                                                     AND `rights` & " . Change::READMY);
        ProfileRight::updateProfileRightAsOtherRight('projecttask', ProjectTask::UPDATEMY, "`name` = 'change'\n                                                     AND `rights` & " . Change::READMY);
    }
    if (!TableExists('glpi_projectcosts')) {
        $query = "CREATE TABLE `glpi_projectcosts` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `projects_id` int(11) NOT NULL DEFAULT '0',\n                  `name` varchar(255) DEFAULT NULL,\n                  `comment` text COLLATE utf8_unicode_ci,\n                  `begin_date` date DEFAULT NULL,\n                  `end_date` date DEFAULT NULL,\n                  `cost` decimal(20,4) NOT NULL DEFAULT '0.0000',\n                  `budgets_id` int(11) NOT NULL DEFAULT '0',\n                  `entities_id` int(11) NOT NULL DEFAULT '0',\n                  `is_recursive` tinyint(1) NOT NULL DEFAULT '0',\n                  PRIMARY KEY (`id`),\n                  KEY `name` (`name`),\n                  KEY `projects_id` (`projects_id`),\n                  KEY `begin_date` (`begin_date`),\n                  KEY `end_date` (`end_date`),\n                  KEY `entities_id` (`entities_id`),\n                  KEY `is_recursive` (`is_recursive`),\n                  KEY `budgets_id` (`budgets_id`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.85 add table glpi_projectcosts");
    }
    if (!TableExists('glpi_projectstates')) {
        $query = "CREATE TABLE `glpi_projectstates` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `name` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n                  `comment` text COLLATE utf8_unicode_ci,\n                  `color` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n                  `is_finished` tinyint(1) NOT NULL DEFAULT '0',\n                  PRIMARY KEY (`id`),\n                  KEY `name` (`name`),\n                  KEY `is_finished` (`is_finished`)\n                ) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.85 create glpi_projectstates");
        $ADDTODISPLAYPREF['ProjectState'] = array(12, 11);
        $states = array('new' => array('name' => _x('ticket', 'New'), 'color' => '#06ff00', 'is_finished' => 0), 'do' => array('name' => __('Processing'), 'color' => '#ffb800', 'is_finished' => 0), 'end' => array('name' => __('Closed'), 'color' => '#ff0000', 'is_finished' => 1));
        foreach ($states as $key => $val) {
            $query = "INSERT INTO `glpi_projectstates`\n                          (`name`,`color`,`is_finished`)\n                   VALUES ('" . addslashes($val['name']) . "','" . addslashes($val['color']) . "',\n                           '" . addslashes($val['is_finished']) . "')";
            $DB->queryOrDie($query, "0.85 insert default project state {$key}");
        }
    }
    if (!TableExists('glpi_projecttypes')) {
        $query = "CREATE TABLE `glpi_projecttypes` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `name` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n                  `comment` text COLLATE utf8_unicode_ci,\n                  PRIMARY KEY (`id`),\n                  KEY `name` (`name`)\n                ) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.85 create glpi_projecttypes");
    }
    $migration->addField("glpi_groups", 'is_manager', "bool", array('update' => "`is_assign`", 'value' => 1));
    $migration->addKey('glpi_groups', 'is_manager');
    if (!TableExists('glpi_changes_projects')) {
        $query = "CREATE TABLE `glpi_changes_projects` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `changes_id` int(11) NOT NULL DEFAULT '0',\n                  `projects_id` int(11) NOT NULL DEFAULT '0',\n                  PRIMARY KEY (`id`),\n                  UNIQUE KEY `unicity` (`changes_id`,`projects_id`),\n                  KEY `projects_id` (`projects_id`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.85 add table glpi_changes_projects");
    }
    if (!TableExists('glpi_projectteams')) {
        $query = "CREATE TABLE `glpi_projectteams` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `projects_id` int(11) NOT NULL DEFAULT '0',\n                  `itemtype` varchar(100) default NULL,\n                  `items_id` int(11) NOT NULL DEFAULT '0',\n                  PRIMARY KEY (`id`),\n                  UNIQUE KEY `unicity` (`projects_id`,`itemtype`,`items_id`),\n                  KEY `item` (`itemtype`,`items_id`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.85 add table glpi_projectteams");
    }
    if (!TableExists('glpi_items_projects')) {
        $query = "CREATE TABLE `glpi_items_projects` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `projects_id` int(11) NOT NULL DEFAULT '0',\n                  `itemtype` varchar(100) default NULL,\n                  `items_id` int(11) NOT NULL DEFAULT '0',\n                  PRIMARY KEY (`id`),\n                  UNIQUE KEY `unicity` (`projects_id`,`itemtype`,`items_id`),\n                  KEY `item` (`itemtype`,`items_id`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.85 add table glpi_items_projects");
    }
    if (!TableExists("glpi_projecttasks")) {
        $query = "CREATE TABLE IF NOT EXISTS `glpi_projecttasks` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `name` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n                  `content` longtext DEFAULT NULL,\n                  `comment` longtext DEFAULT NULL,\n                  `entities_id` int(11) NOT NULL DEFAULT '0',\n                  `is_recursive` tinyint(1) NOT NULL DEFAULT '0',\n                  `projects_id` int(11) NOT NULL DEFAULT '0',\n                  `projecttasks_id` int(11) NOT NULL DEFAULT '0',\n                  `date` datetime DEFAULT NULL,\n                  `date_mod` datetime DEFAULT NULL,\n                  `plan_start_date` datetime DEFAULT NULL,\n                  `plan_end_date` datetime DEFAULT NULL,\n                  `real_start_date` datetime DEFAULT NULL,\n                  `real_end_date` datetime DEFAULT NULL,\n                  `planned_duration` int(11) NOT NULL DEFAULT '0',\n                  `effective_duration` int(11) NOT NULL DEFAULT '0',\n                  `projectstates_id` int(11) NOT NULL DEFAULT '0',\n                  `projecttasktypes_id` int(11) NOT NULL DEFAULT '0',\n                  `users_id` int(11) NOT NULL DEFAULT '0',\n                  `percent_done` int(11) NOT NULL DEFAULT '0',\n                  `notepad` longtext DEFAULT NULL,\n                  PRIMARY KEY (`id`),\n                  KEY `name` (`name`),\n                  KEY `entities_id` (`entities_id`),\n                  KEY `is_recursive` (`is_recursive`),\n                  KEY `projects_id` (`projects_id`),\n                  KEY `projecttasks_id` (`projecttasks_id`),\n                  KEY `date` (`date`),\n                  KEY `date_mod` (`date_mod`),\n                  KEY `users_id` (`users_id`),\n                  KEY `plan_start_date` (`plan_start_date`),\n                  KEY `plan_end_date` (`plan_end_date`),\n                  KEY `real_start_date` (`real_start_date`),\n                  KEY `real_end_date` (`real_end_date`),\n                  KEY `percent_done` (`percent_done`),\n                  KEY `projectstates_id` (`projectstates_id`),\n                  KEY `projecttasktypes_id` (`projecttasktypes_id`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;";
        $DB->queryOrDie($query, "0.85 add table glpi_projecttasks");
        $ADDTODISPLAYPREF['ProjectTask'] = array(2, 12, 14, 5, 7, 8, 13);
    }
    if (!TableExists('glpi_projecttasktypes')) {
        $query = "CREATE TABLE `glpi_projecttasktypes` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `name` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n                  `comment` text COLLATE utf8_unicode_ci,\n                  PRIMARY KEY (`id`),\n                  KEY `name` (`name`)\n                ) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.85 create glpi_projecttasktypes");
    }
    if (!TableExists('glpi_projecttaskteams')) {
        $query = "CREATE TABLE `glpi_projecttaskteams` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `projecttasks_id` int(11) NOT NULL DEFAULT '0',\n                  `itemtype` varchar(100) default NULL,\n                  `items_id` int(11) NOT NULL DEFAULT '0',\n                  PRIMARY KEY (`id`),\n                  UNIQUE KEY `unicity` (`projecttasks_id`,`itemtype`,`items_id`),\n                  KEY `item` (`itemtype`,`items_id`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.85 add table glpi_projecttaskteams");
    }
    if (!TableExists('glpi_projecttasks_tickets')) {
        $query = "CREATE TABLE `glpi_projecttasks_tickets` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `tickets_id` int(11) NOT NULL DEFAULT '0',\n                  `projecttasks_id` int(11) NOT NULL DEFAULT '0',\n                  PRIMARY KEY (`id`),\n                  UNIQUE KEY `unicity` (`tickets_id`,`projecttasks_id`),\n                  KEY `projects_id` (`projecttasks_id`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.85 add table glpi_projecttasks_tickets");
    }
    // Project notifications
    $query = "SELECT *\n             FROM `glpi_notificationtemplates`\n             WHERE `itemtype` = 'Project'";
    if ($result = $DB->query($query)) {
        if ($DB->numrows($result) == 0) {
            $query = "INSERT INTO `glpi_notificationtemplates`\n                          (`name`, `itemtype`, `date_mod`)\n                   VALUES ('Projects', 'Project', NOW())";
            $DB->queryOrDie($query, "0.85 add project notification");
            $notid = $DB->insert_id();
            $query = "INSERT INTO `glpi_notificationtemplatetranslations`\n                          (`notificationtemplates_id`, `language`, `subject`,\n                           `content_text`,\n                           `content_html`)\n                   VALUES ({$notid}, '', '##project.action## ##project.name## ##project.code##',\n                          '##lang.project.url## : ##project.url##\n\n##lang.project.description##\n\n##lang.project.name## : ##project.name##\n##lang.project.code## : ##project.code##\n##lang.project.manager## : ##project.manager##\n##lang.project.managergroup## : ##project.managergroup##\n##lang.project.creationdate## : ##project.creationdate##\n##lang.project.priority## : ##project.priority##\n##lang.project.state## : ##project.state##\n##lang.project.type## : ##project.type##\n##lang.project.description## : ##project.description##\n\n##lang.project.numberoftasks## : ##project.numberoftasks##\n\n\n\n##FOREACHtasks##\n\n[##task.creationdate##]\n##lang.task.name## : ##task.name##\n##lang.task.state## : ##task.state##\n##lang.task.type## : ##task.type##\n##lang.task.percent## : ##task.percent##\n##lang.task.description## : ##task.description##\n\n##ENDFOREACHtasks##',\n                          '&lt;p&gt;##lang.project.url## : &lt;a href=\"##project.url##\"&gt;##project.url##&lt;/a&gt;&lt;/p&gt;\n&lt;p&gt;&lt;strong&gt;##lang.project.description##&lt;/strong&gt;&lt;/p&gt;\n&lt;p&gt;##lang.project.name## : ##project.name##&lt;br /&gt;##lang.project.code## : ##project.code##&lt;br /&gt; ##lang.project.manager## : ##project.manager##&lt;br /&gt;##lang.project.managergroup## : ##project.managergroup##&lt;br /&gt; ##lang.project.creationdate## : ##project.creationdate##&lt;br /&gt;##lang.project.priority## : ##project.priority## &lt;br /&gt;##lang.project.state## : ##project.state##&lt;br /&gt;##lang.project.type## : ##project.type##&lt;br /&gt;##lang.project.description## : ##project.description##&lt;/p&gt;\n&lt;p&gt;##lang.project.numberoftasks## : ##project.numberoftasks##&lt;/p&gt;\n&lt;div&gt;\n&lt;p&gt;##FOREACHtasks##&lt;/p&gt;\n&lt;div&gt;&lt;strong&gt;[##task.creationdate##] &lt;/strong&gt;&lt;br /&gt; ##lang.task.name## : ##task.name##&lt;br /&gt;##lang.task.state## : ##task.state##&lt;br /&gt;##lang.task.type## : ##task.type##&lt;br /&gt;##lang.task.percent## : ##task.percent##&lt;br /&gt;##lang.task.description## : ##task.description##&lt;/div&gt;\n&lt;p&gt;##ENDFOREACHtasks##&lt;/p&gt;\n&lt;/div&gt;')";
            $DB->queryOrDie($query, "0.85 add project notification translation");
            $notifications = array('new' => array(), 'update' => array(), 'delete' => array());
            $notif_names = array('new' => 'New Project', 'update' => 'Update Project', 'delete' => 'Delete Project');
            foreach ($notifications as $key => $val) {
                $notifications[$key][] = Notification::MANAGER_USER;
                $notifications[$key][] = Notification::GLOBAL_ADMINISTRATOR;
                $notifications[$key][] = Notification::MANAGER_GROUP;
            }
            foreach ($notifications as $type => $targets) {
                $query = "INSERT INTO `glpi_notifications`\n                             (`name`, `entities_id`, `itemtype`, `event`, `mode`,\n                              `notificationtemplates_id`, `comment`, `is_recursive`, `is_active`,\n                              `date_mod`)\n                      VALUES ('" . $notif_names[$type] . "', 0, 'Project', '{$type}', 'mail',\n                              {$notid}, '', 1, 1, NOW())";
                $DB->queryOrDie($query, "0.85 add project {$type} notification");
                $notifid = $DB->insert_id();
                foreach ($targets as $target) {
                    $query = "INSERT INTO `glpi_notificationtargets`\n                                (`id`, `notifications_id`, `type`, `items_id`)\n                         VALUES (NULL, {$notifid}, " . Notification::USER_TYPE . ", {$target});";
                    $DB->queryOrDie($query, "0.85 add project {$type} notification target");
                }
            }
        }
    }
    // Project Task notifications
    $query = "SELECT *\n             FROM `glpi_notificationtemplates`\n             WHERE `itemtype` = 'ProjectTask'";
    if ($result = $DB->query($query)) {
        if ($DB->numrows($result) == 0) {
            $query = "INSERT INTO `glpi_notificationtemplates`\n                          (`name`, `itemtype`, `date_mod`)\n                   VALUES ('Project Tasks', 'ProjectTask', NOW())";
            $DB->queryOrDie($query, "0.85 add project task notification");
            $notid = $DB->insert_id();
            $query = "INSERT INTO `glpi_notificationtemplatetranslations`\n                          (`notificationtemplates_id`, `language`, `subject`,\n                           `content_text`,\n                           `content_html`)\n                   VALUES ({$notid}, '', '##projecttask.action## ##projecttask.name##',\n                          '##lang.projecttask.url## : ##projecttask.url##\n\n##lang.projecttask.description##\n\n##lang.projecttask.name## : ##projecttask.name##\n##lang.projecttask.project## : ##projecttask.name##\n##lang.projecttask.creationdate## : ##projecttask.creationdate##\n##lang.projecttask.state## : ##projecttask.state##\n##lang.projecttask.type## : ##projecttask.type##\n##lang.projecttask.description## : ##projecttask.description##\n\n##lang.projecttask.numberoftasks## : ##projecttask.numberoftasks##\n\n\n\n##FOREACHtasks##\n\n[##task.creationdate##]\n##lang.task.name## : ##task.name##\n##lang.task.state## : ##task.state##\n##lang.task.type## : ##task.type##\n##lang.task.percent## : ##task.percent##\n##lang.task.description## : ##task.description##\n\n##ENDFOREACHtasks##',\n                          '&lt;p&gt;##lang.projecttask.url## : &lt;a href=\"##projecttask.url##\"&gt;##projecttask.url##&lt;/a&gt;&lt;/p&gt;\n&lt;p&gt;&lt;strong&gt;##lang.projecttask.description##&lt;/strong&gt;&lt;/p&gt;\n&lt;p&gt;##lang.projecttask.name## : ##projecttask.name##&lt;br /&gt;##lang.projecttask.project## : &lt;a href=\"##projecttask.projecturl##\"&gt;##projecttask.name##&lt;/a&gt;&lt;br /&gt;##lang.projecttask.creationdate## : ##projecttask.creationdate##&lt;br /&gt;##lang.projecttask.state## : ##projecttask.state##&lt;br /&gt;##lang.projecttask.type## : ##projecttask.type##&lt;br /&gt;##lang.projecttask.description## : ##projecttask.description##&lt;/p&gt\n&lt;p&gt;##lang.projecttask.numberoftasks## : ##projecttask.numberoftasks##&lt;/p&gt;\n&lt;div&gt;\n&lt;p&gt;##FOREACHtasks##&lt;/p&gt;\n&lt;div&gt;&lt;strong&gt;[##task.creationdate##] &lt;/strong&gt;&lt;br /&gt;##lang.task.name## : ##task.name##&lt;br /&gt;##lang.task.state## : ##task.state##&lt;br /&gt;##lang.task.type## : ##task.type##&lt;br /&gt;##lang.task.percent## : ##task.percent##&lt;br /&gt;##lang.task.description## : ##task.description##&lt;/div&gt;\n&lt;p&gt;##ENDFOREACHtasks##&lt;/p&gt;\n&lt;/div&gt;')";
            $DB->queryOrDie($query, "0.85 add project task notification translation");
            $notifications = array('new' => array(), 'update' => array(), 'delete' => array());
            $notif_names = array('new' => 'New Project Task', 'update' => 'Update Project Task', 'delete' => 'Delete Project Task');
            foreach ($notifications as $key => $val) {
                $notifications[$key][] = Notification::TEAM_USER;
                $notifications[$key][] = Notification::GLOBAL_ADMINISTRATOR;
                $notifications[$key][] = Notification::TEAM_GROUP;
            }
            foreach ($notifications as $type => $targets) {
                $query = "INSERT INTO `glpi_notifications`\n                             (`name`, `entities_id`, `itemtype`, `event`, `mode`,\n                              `notificationtemplates_id`, `comment`, `is_recursive`, `is_active`,\n                              `date_mod`)\n                      VALUES ('" . $notif_names[$type] . "', 0, 'ProjectTask', '{$type}', 'mail',\n                              {$notid}, '', 1, 1, NOW())";
                $DB->queryOrDie($query, "0.85 add project task  {$type} notification");
                $notifid = $DB->insert_id();
                foreach ($targets as $target) {
                    $query = "INSERT INTO `glpi_notificationtargets`\n                                (`id`, `notifications_id`, `type`, `items_id`)\n                         VALUES (NULL, {$notifid}, " . Notification::USER_TYPE . ", {$target});";
                    $DB->queryOrDie($query, "0.85 add project task {$type} notification target");
                }
            }
        }
    }
    $migration->displayMessage(sprintf(__('Data migration - %s'), 'notepad'));
    // Create new notepad table
    if (!TableExists('glpi_notepads')) {
        $query = "CREATE TABLE `glpi_notepads` (\n                  `id` int(11) NOT NULL AUTO_INCREMENT,\n                  `itemtype` varchar(100) default NULL,\n                  `items_id` int(11) NOT NULL DEFAULT '0',\n                  `date` datetime DEFAULT NULL,\n                  `date_mod` datetime DEFAULT NULL,\n                  `users_id` int(11) NOT NULL DEFAULT '0',\n                  `users_id_lastupdater` int(11) NOT NULL DEFAULT '0',\n                  `content` LONGTEXT DEFAULT NULL,\n                  PRIMARY KEY (`id`),\n                  KEY `item` (`itemtype`,`items_id`),\n                  KEY `date_mod` (`date_mod`),\n                  KEY `date` (`date`),\n                  KEY `users_id_lastupdater` (`users_id_lastupdater`),\n                  KEY `users_id` (`users_id`)\n                ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.85 add table glpi_notepads");
        $notepad_tables = array('glpi_budgets', 'glpi_cartridgeitems', 'glpi_changes', 'glpi_computers', 'glpi_consumableitems', 'glpi_contacts', 'glpi_contracts', 'glpi_documents', 'glpi_entities', 'glpi_monitors', 'glpi_networkequipments', 'glpi_peripherals', 'glpi_phones', 'glpi_printers', 'glpi_problems', 'glpi_projects', 'glpi_projecttasks', 'glpi_softwares', 'glpi_suppliers');
        foreach ($notepad_tables as $t) {
            // Migrate data
            if (FieldExists($t, 'notepad')) {
                $query = "SELECT id, notepad\n                      FROM `{$t}`\n                      WHERE notepad IS NOT NULL\n                            AND notepad <>'';";
                foreach ($DB->request($query) as $data) {
                    $iq = "INSERT INTO `glpi_notepads`\n                             (`itemtype`, `items_id`, `content`, `date`, `date_mod`)\n                      VALUES ('" . getItemTypeForTable($t) . "', '" . $data['id'] . "',\n                              '" . addslashes($data['notepad']) . "', NOW(), NOW())";
                    $DB->queryOrDie($iq, "0.85 migrate notepad data");
                }
                $migration->dropField($t, 'notepad');
            }
        }
    }
    $migration->addField('glpi_deviceprocessors', 'nbcores_default', 'int');
    $migration->addField('glpi_deviceprocessors', 'nbthreads_default', 'int');
    $migration->addField('glpi_items_deviceprocessors', 'nbcores', 'int');
    $migration->addField('glpi_items_deviceprocessors', 'nbthreads', 'int');
    $migration->addKey('glpi_items_deviceprocessors', 'nbcores');
    $migration->addKey('glpi_items_deviceprocessors', 'nbthreads');
    $migration->displayMessage(sprintf(__('Data migration - %s'), 'ticketvalidations status'));
    $status = array('none' => CommonITILValidation::NONE, 'waiting' => CommonITILValidation::WAITING, 'accepted' => CommonITILValidation::ACCEPTED, 'rejected' => CommonITILValidation::REFUSED);
    // Migrate datas
    foreach ($status as $old => $new) {
        $query = "UPDATE `glpi_ticketvalidations`\n                SET `status` = '{$new}'\n                WHERE `status` = '{$old}'";
        $DB->queryOrDie($query, "0.85 status in glpi_ticketvalidations {$old} to {$new}");
    }
    $migration->changeField('glpi_ticketvalidations', 'status', 'status', 'integer', array('value' => CommonITILValidation::WAITING));
    $migration->displayMessage(sprintf(__('Data migration - %s'), 'tickets and changes global_validation'));
    $tables = array('glpi_tickets', 'glpi_changes');
    foreach ($tables as $table) {
        foreach ($status as $old => $new) {
            $query = "UPDATE `" . $table . "`\n                   SET `global_validation` = '{$new}'\n                   WHERE `global_validation` = '{$old}'";
            $DB->queryOrDie($query, "0.85 global_validation in {$table} {$old} to {$new}");
        }
        $migration->changeField($table, 'global_validation', 'global_validation', 'integer', array('value' => CommonITILValidation::NONE));
    }
    $migration->displayMessage(sprintf(__('Data migration - %s'), 'tickettemplatepredefinedfields value'));
    foreach ($status as $old => $new) {
        $query = "UPDATE `glpi_tickettemplatepredefinedfields`\n                SET `value` = '{$new}'\n                WHERE `num` = '52'\n                      AND `value` = '{$old}'";
        $DB->queryOrDie($query, "0.85 value in glpi_tickettemplatepredefinedfields {$old} to {$new}");
    }
    // Migrate templates
    $query = "SELECT `glpi_notificationtemplatetranslations`.*\n             FROM `glpi_notificationtemplatetranslations`\n             INNER JOIN `glpi_notificationtemplates`\n                  ON (`glpi_notificationtemplates`.`id`\n                        = `glpi_notificationtemplatetranslations`.`notificationtemplates_id`)\n             WHERE `glpi_notificationtemplatetranslations`.`content_text` LIKE '%validation.storestatus=%'\n                   OR `glpi_notificationtemplatetranslations`.`content_html` LIKE '%validation.storestatus=%'\n                   OR `glpi_notificationtemplatetranslations`.`subject` LIKE '%validation.storestatus=%'";
    if ($result = $DB->query($query)) {
        if ($DB->numrows($result)) {
            while ($data = $DB->fetch_assoc($result)) {
                $subject = $data['subject'];
                $text = $data['content_text'];
                $html = $data['content_html'];
                foreach ($status as $old => $new) {
                    $subject = str_replace("validation.storestatus={$old}", "validation.storestatus={$new}", $subject);
                    $text = str_replace("validation.storestatus={$old}", "validation.storestatus={$new}", $text);
                    $html = str_replace("validation.storestatus={$old}", "validation.storestatus={$new}", $html);
                }
                $query = "UPDATE `glpi_notificationtemplatetranslations`\n                      SET `subject` = '" . addslashes($subject) . "',\n                         `content_text` = '" . addslashes($text) . "',\n                         `content_html` = '" . addslashes($html) . "'\n                      WHERE `id` = " . $data['id'] . "";
                $DB->queryOrDie($query, "0.85 fix tags usage for storestatus");
            }
        }
    }
    // Upgrade ticket bookmarks
    $query = "SELECT *\n             FROM `glpi_bookmarks`";
    if ($result = $DB->query($query)) {
        if ($DB->numrows($result) > 0) {
            while ($data = $DB->fetch_assoc($result)) {
                $num = 0;
                $num2 = 0;
                $options = array();
                parse_str($data["query"], $options);
                if (isset($options['field'])) {
                    // update ticket statuses
                    if (($data['itemtype'] = 'Ticket') && $data['type'] == Bookmark::SEARCH) {
                        foreach ($options['field'] as $key => $val) {
                            if (($val == 55 || $val == 52) && isset($options['contains'][$key])) {
                                if (isset($status[$options['contains'][$key]])) {
                                    $options['contains'][$key] = $status[$options['contains'][$key]];
                                }
                            }
                        }
                    }
                }
                $query2 = "UPDATE `glpi_bookmarks`\n                       SET `query` = '" . addslashes(Toolbox::append_params($options)) . "'\n                       WHERE `id` = '" . $data['id'] . "'";
                $DB->queryOrDie($query2, "0.85 update bookmarks");
            }
        }
    }
    //////////////////////////////////////////////////
    // Device update
    $migration->displayMessage(sprintf(__('Data migration - %s'), 'Devices'));
    foreach (array_merge(CommonDevice::getDeviceTypes(), Item_Devices::getDeviceTypes()) as $itemtype) {
        $table = $itemtype::getTable();
        if (!FieldExists($table, 'entities_id')) {
            $migration->addField($table, 'entities_id', 'integer');
            $migration->addKey($table, array('entities_id'), 'entities_id');
        }
        if (!FieldExists($table, 'is_recursive')) {
            $migration->addField($table, 'is_recursive', 'bool', array('update' => '1', 'after' => 'entities_id'));
            $migration->addKey($table, array('is_recursive'), 'is_recursive');
        }
    }
    // Adding the Registered ID class that contains PCI IDs and USB IDs for vendors
    // as well devices
    if (!TableExists('glpi_registeredids')) {
        $query = "CREATE TABLE `glpi_registeredids` (\n                 `id` int(11) NOT NULL AUTO_INCREMENT,\n                 `name` varchar(255) DEFAULT NULL,\n                 `items_id` int(11) NOT NULL DEFAULT '0',\n                 `itemtype` varchar(100) COLLATE utf8_unicode_ci NOT NULL,\n                 `device_type` varchar(100) COLLATE utf8_unicode_ci NOT NULL COMMENT 'USB, PCI ...',\n                 PRIMARY KEY (`id`),\n                 KEY `name` (`name`),\n                 KEY `item` (`items_id`, `itemtype`),\n                 KEY `device_type` (`device_type`)\n               ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, "0.85 add table glpi_registeredids");
    }
    // Complete the item_devices
    foreach (array('glpi_items_devicecases', 'glpi_items_devicecontrols', 'glpi_items_devicedrives', 'glpi_items_devicegraphiccards', 'glpi_items_devicemotherboards', 'glpi_items_devicenetworkcards', 'glpi_items_devicepcis', 'glpi_items_devicepowersupplies', 'glpi_items_devicesoundcards') as $table) {
        if (!FieldExists($table, 'serial')) {
            $migration->addField($table, 'serial', 'string');
            $migration->addKey($table, 'serial');
        }
    }
    foreach (array('glpi_items_devicecontrols', 'glpi_items_devicedrives', 'glpi_items_devicegraphiccards', 'glpi_items_deviceharddrives', 'glpi_items_devicememories', 'glpi_items_devicenetworkcards', 'glpi_items_devicepcis', 'glpi_items_deviceprocessors', 'glpi_items_devicesoundcards') as $table) {
        if (!FieldExists($table, 'busID')) {
            $migration->addField($table, 'busID', 'string');
            $migration->addKey($table, 'busID');
        }
    }
    // Add key
    foreach (array('glpi_items_devicecases', 'glpi_items_devicecontrols', 'glpi_items_devicedrives', 'glpi_items_devicegraphiccards', 'glpi_items_deviceharddrives', 'glpi_items_devicememories', 'glpi_items_devicemotherboards', 'glpi_items_devicenetworkcards', 'glpi_items_devicepcis', 'glpi_items_devicepowersupplies', 'glpi_items_deviceprocessors', 'glpi_items_devicesoundcards') as $table) {
        $migration->dropKey($table, 'item');
        $migration->migrationOneTable($table);
        $migration->addKey($table, array('itemtype', 'items_id'), 'item');
    }
    if (!FieldExists('glpi_devicegraphiccards', 'chipset')) {
        $migration->addField('glpi_devicegraphiccards', 'chipset', 'string');
        $migration->addKey('glpi_devicegraphiccards', 'chipset');
    }
    $migration->addField("glpi_suppliers_tickets", "use_notification", "bool");
    $migration->addField("glpi_suppliers_tickets", "alternative_email", "string");
    $migration->addField("glpi_problems_suppliers", "use_notification", "bool");
    $migration->addField("glpi_problems_suppliers", "alternative_email", "string");
    $migration->addField("glpi_changes_suppliers", "use_notification", "bool");
    $migration->addField("glpi_changes_suppliers", "alternative_email", "string");
    // Add field for locations
    $migration->addField("glpi_locations", "latitude", "string");
    $migration->addField("glpi_locations", "longitude", "string");
    $migration->addField("glpi_locations", "altitude", "string");
    // Add fixed columns as variables :
    $ADDTODISPLAYPREF['CartridgeItem'] = array(9);
    $ADDTODISPLAYPREF['ConsumableItem'] = array(9);
    $ADDTODISPLAYPREF['ReservationItem'] = array(9);
    $migration->displayMessage(sprintf(__('Data migration - %s'), 'License validity'));
    // for licence validity
    if ($migration->addField("glpi_softwarelicenses", "is_valid", "bool", array("value" => 1))) {
        $migration->migrationOneTable("glpi_softwarelicenses");
        // Force all entities
        if (!isset($_SESSION['glpishowallentities'])) {
            $_SESSION['glpishowallentities'] = 0;
        }
        $savesession = $_SESSION['glpishowallentities'];
        $_SESSION['glpishowallentities'] = 1;
        $queryl = "SELECT `id`, `number`\n                 FROM `glpi_softwarelicenses`";
        foreach ($DB->request($queryl) as $datal) {
            if ($datal['number'] >= 0 && $datal['number'] < Computer_SoftwareLicense::countForLicense($datal['id'], -1)) {
                $queryl2 = "UPDATE `glpi_softwarelicenses`\n                        SET `is_valid` = 0\n                        WHERE `id` = '" . $datal['id'] . "'";
                $DB->queryOrDie($queryl2, "0.85 update softwarelicense");
            }
        }
        $_SESSION['glpishowallentities'] = $savesession;
    }
    if ($migration->addField("glpi_softwares", "is_valid", "bool", array("value" => 1))) {
        $migration->migrationOneTable("glpi_softwares");
        $querys = "SELECT `glpi_softwares`.`id`\n                 FROM `glpi_softwares`\n                 LEFT JOIN `glpi_softwarelicenses`\n                     ON (`glpi_softwarelicenses`.`softwares_id` = `glpi_softwares`.`id`)\n                 WHERE `glpi_softwarelicenses`.`is_valid` = 0";
        foreach ($DB->request($querys) as $datas) {
            $querys2 = "UPDATE `glpi_softwares`\n                     SET `is_valid` = 0\n                     WHERE `id` = '" . $datas['id'] . "'";
            $DB->queryOrDie($querys2, "0.85 update software");
        }
    }
    // Add condition to rules
    $migration->addField('glpi_rules', 'condition', 'integer');
    $migration->addKey('glpi_rules', 'condition');
    $migration->migrationOneTable('glpi_rules');
    // Update condition for RuleTicket : only on add
    $query = "UPDATE `glpi_rules`\n             SET `condition` = 1\n             WHERE `sub_type` = 'RuleTicket'";
    $DB->queryOrDie($query, "0.85 update condition for RuleTicket");
    // Update ticket_status for helpdeks profiles
    $newcycle = array(1 => array(2 => 0, 3 => 0, 4 => 0, 5 => 0, 6 => 0), 2 => array(1 => 0, 3 => 0, 4 => 0, 5 => 0, 6 => 0), 3 => array(1 => 0, 2 => 0, 4 => 0, 5 => 0, 6 => 0), 4 => array(1 => 0, 2 => 0, 3 => 0, 5 => 0, 6 => 0), 5 => array(1 => 0, 2 => 0, 3 => 0, 4 => 0), 6 => array(1 => 0, 2 => 0, 3 => 0, 4 => 0, 5 => 0));
    $query = "UPDATE `glpi_profiles`\n             SET `ticket_status` = '" . exportArrayToDB($newcycle) . "'\n             WHERE `interface` = 'helpdesk'";
    $DB->queryOrDie($query, "0.85 update default life cycle for helpdesk");
    //Add comment field to a virtualmachine
    $migration->addField('glpi_computervirtualmachines', 'comment', 'text');
    $migration->displayMessage(sprintf(__('Data migration - %s'), 'IP improvment'));
    // Ip search improve
    $migration->addField('glpi_ipaddresses', 'mainitems_id', 'integer');
    $migration->addField('glpi_ipaddresses', 'mainitemtype', 'string', array('after' => 'mainitems_id'));
    $migration->migrationOneTable('glpi_ipaddresses');
    $migration->addKey('glpi_ipaddresses', array('mainitemtype', 'mainitems_id', 'is_deleted'), 'mainitem');
    $query_doc_i = "UPDATE `glpi_ipaddresses` as `ip`\n                   INNER JOIN `glpi_networknames` as `netname`\n                     ON  (`ip`.`items_id` = `netname`.`id`\n                            AND `ip`.`itemtype` = 'NetworkName')\n                   INNER JOIN `glpi_networkports` as `netport`\n                     ON  (`netname`.`items_id` = `netport`.`id`\n                            AND `netname`.`itemtype` = 'NetworkPort')\n                   SET `ip`.`mainitemtype` = `netport`.`itemtype`,\n                       `ip`.`mainitems_id` = `netport`.`items_id`";
    $DB->queryOrDie($query_doc_i, "0.85 update mainitems fields of ipaddresses");
    // Upgrade ticket bookmarks
    $query = "SELECT *\n             FROM `glpi_bookmarks`\n             WHERE `type` = '" . Bookmark::SEARCH . "'";
    if ($result = $DB->query($query)) {
        if ($DB->numrows($result) > 0) {
            while ($data = $DB->fetch_assoc($result)) {
                $num = 0;
                $num2 = 0;
                $options = array();
                parse_str($data["query"], $options);
                // Copy itemtype if not set
                if (!isset($options['itemtype'])) {
                    $options['itemtype'] = $data['itemtype'];
                }
                // Move criteria
                if (isset($options['field']) && is_array($options['field'])) {
                    $newkey = 0;
                    foreach ($options['field'] as $key => $val) {
                        $options['criteria'][$newkey]['field'] = $val;
                        //  other field
                        if (isset($options['link'][$key])) {
                            $options['criteria'][$newkey]['link'] = $options['link'][$key];
                        }
                        if (isset($options['searchtype'][$key])) {
                            $options['criteria'][$newkey]['searchtype'] = $options['searchtype'][$key];
                        } else {
                            $options['criteria'][$newkey]['searchtype'] = 'contains';
                        }
                        if (isset($options['contains'][$key])) {
                            $options['criteria'][$newkey]['value'] = $options['contains'][$key];
                        } else {
                            $options['criteria'][$newkey]['value'] = '';
                        }
                        $newkey++;
                    }
                    unset($options['field']);
                    unset($options['contains']);
                    unset($options['searchtype']);
                    unset($options['link']);
                }
                if (isset($options['glpisearchcount'])) {
                    unset($options['glpisearchcount']);
                }
                if (isset($options['field2']) && is_array($options['field2'])) {
                    $newkey = 0;
                    foreach ($options['field2'] as $key => $val) {
                        $options['metacriteria'][$newkey]['field'] = $val;
                        //  other field
                        if (isset($options['itemtype2'][$key])) {
                            $options['metacriteria'][$newkey]['itemtype'] = $options['itemtype2'][$key];
                        }
                        if (isset($options['link2'][$newkey])) {
                            $options['metacriteria'][$newkey]['link'] = $options['link2'][$key];
                        }
                        if (isset($options['searchtype2'][$key])) {
                            $options['metacriteria'][$newkey]['searchtype'] = $options['searchtype2'][$key];
                        } else {
                            $options['metacriteria'][$newkey]['searchtype'] = 'contains';
                        }
                        if (isset($options['contains2'][$key])) {
                            $options['metacriteria'][$newkey]['value'] = $options['contains2'][$key];
                        } else {
                            $options['metacriteria'][$newkey]['value'] = '';
                        }
                        $newkey++;
                    }
                    unset($options['field2']);
                    unset($options['contains2']);
                    unset($options['searchtype2']);
                    unset($options['link2']);
                    unset($options['itemtype2']);
                }
                if (isset($options['glpisearchcount2'])) {
                    unset($options['glpisearchcount2']);
                }
                $query2 = "UPDATE `glpi_bookmarks`\n                       SET `query` = '" . addslashes(Toolbox::append_params($options)) . "'\n                       WHERE `id` = '" . $data['id'] . "'";
                $DB->queryOrDie($query2, "0.85 update bookmarks for reorg search");
            }
        }
    }
    // ************ Keep it at the end **************
    //TRANS: %s is the table or item to migrate
    $migration->displayMessage(sprintf(__('Data migration - %s'), 'glpi_displaypreferences'));
    // Clean display prefs
    // Notepad
    $query = "UPDATE `glpi_displaypreferences`\n             SET `num` = 90\n             WHERE `itemtype` = 'Entity'\n                   AND `num` = 28";
    $DB->query($query);
    $query = "UPDATE `glpi_displaypreferences`\n             SET `num` = 200\n             WHERE `num` = 90";
    $DB->query($query);
    $migration->updateDisplayPrefs($ADDTODISPLAYPREF, $DELFROMDISPLAYPREF);
    // must always be at the end
    $migration->executeMigration();
    return $updateresult;
}
 /**
  * Prepare data and send them to rule engine
  *
  * @param type $p_xml simpleXML object
  */
 function sendCriteria($arrayinventory)
 {
     PluginFusioninventoryCommunication::addLog('Function PluginFusioninventoryCommunicationNetworkDiscovery->sendCriteria().');
     if (isset($arrayinventory['MAC']) && $arrayinventory['MAC'] == "00:00:00:00:00:00") {
         unset($arrayinventory['MAC']);
     }
     $_SESSION['SOURCE_XMLDEVICE'] = $arrayinventory;
     $input = array();
     // Global criterias
     if (isset($arrayinventory['SERIAL']) && !empty($arrayinventory['SERIAL'])) {
         $input['serial'] = $arrayinventory['SERIAL'];
     }
     if (isset($arrayinventory['MAC']) && !empty($arrayinventory['MAC'])) {
         $input['mac'][] = $arrayinventory['MAC'];
     }
     if (isset($arrayinventory['IP']) && !empty($arrayinventory['IP'])) {
         $input['ip'][] = $arrayinventory['IP'];
     }
     if (isset($arrayinventory['MODELSNMP']) && !empty($arrayinventory['MODELSNMP'])) {
         $input['model'] = $arrayinventory['MODELSNMP'];
     }
     if (isset($arrayinventory['SNMPHOSTNAME']) && !empty($arrayinventory['SNMPHOSTNAME'])) {
         $input['name'] = $arrayinventory['SNMPHOSTNAME'];
     } else {
         if (isset($arrayinventory['NETBIOSNAME']) && !empty($arrayinventory['NETBIOSNAME'])) {
             $input['name'] = $arrayinventory['NETBIOSNAME'];
         } else {
             if (isset($arrayinventory['DNSHOSTNAME']) && !empty($arrayinventory['DNSHOSTNAME'])) {
                 if (strpos($arrayinventory['DNSHOSTNAME'], '.') !== false) {
                     $splitname = explode('.', $arrayinventory['DNSHOSTNAME']);
                     $input['name'] = $splitname[0];
                     if (!isset($arrayinventory['WORKGROUP'])) {
                         unset($splitname[0]);
                         $arrayinventory['WORKGROUP'] = implode('.', $splitname);
                         $_SESSION['SOURCE_XMLDEVICE'] = $arrayinventory;
                     }
                 } else {
                     $input['name'] = $arrayinventory['DNSHOSTNAME'];
                 }
             }
         }
     }
     if (!isset($arrayinventory['ENTITY'])) {
         $arrayinventory['ENTITY'] = 0;
     }
     $input['entities_id'] = $arrayinventory['ENTITY'];
     if (isset($arrayinventory['TYPE'])) {
         switch ($arrayinventory['TYPE']) {
             case '1':
             case 'COMPUTER':
                 $input['itemtype'] = "Computer";
                 // Computer
                 break;
             case '2':
             case 'NETWORKING':
                 $input['itemtype'] = "NetworkEquipment";
                 break;
             case '3':
             case 'PRINTER':
                 $input['itemtype'] = "Printer";
                 break;
         }
     }
     $_SESSION['plugin_fusinvsnmp_datacriteria'] = serialize($input);
     $_SESSION['plugin_fusioninventory_classrulepassed'] = "PluginFusioninventoryCommunicationNetworkDiscovery";
     $rule = new PluginFusioninventoryInventoryRuleImportCollection();
     $data = $rule->processAllRules($input, array());
     PluginFusioninventoryConfig::logIfExtradebug("pluginFusioninventory-rules", $data);
     if (isset($data['action']) && $data['action'] == PluginFusioninventoryInventoryRuleImport::LINK_RESULT_DENIED) {
         $a_text = '';
         foreach ($input as $key => $data) {
             if (is_array($data)) {
                 $a_text[] = "[" . $key . "]:" . implode(", ", $data);
             } else {
                 $a_text[] = "[" . $key . "]:" . $data;
             }
         }
         $_SESSION['plugin_fusinvsnmp_taskjoblog']['comment'] = '==importdenied== ' . implode(", ", $a_text);
         $this->addtaskjoblog();
         $pfIgnoredimport = new PluginFusioninventoryIgnoredimportdevice();
         $inputdb = array();
         if (isset($input['name'])) {
             $inputdb['name'] = $input['name'];
         }
         $inputdb['date'] = date("Y-m-d H:i:s");
         if (isset($input['itemtype'])) {
             $inputdb['itemtype'] = $input['itemtype'];
         }
         if (isset($input['serial'])) {
             $input['serial'] = $input['serial'];
         }
         if (isset($input['ip'])) {
             $inputdb['ip'] = exportArrayToDB($input['ip']);
         }
         if (isset($input['mac'])) {
             $inputdb['mac'] = exportArrayToDB($input['mac']);
         }
         if (isset($input['uuid'])) {
             $inputdb['uuid'] = $input['uuid'];
         }
         $inputdb['rules_id'] = $_SESSION['plugin_fusioninventory_rules_id'];
         $inputdb['method'] = 'netdiscovery';
         $pfIgnoredimport->add($inputdb);
         unset($_SESSION['plugin_fusioninventory_rules_id']);
     }
     if (isset($data['_no_rule_matches']) and $data['_no_rule_matches'] == '1') {
         if (!isset($_SESSION['glpiactiveentities_string'])) {
             $_SESSION['glpiactiveentities_string'] = "'" . $input['entities_id'] . "'";
         }
         if (isset($input['itemtype']) && isset($data['action']) && $data['action'] == PluginFusioninventoryInventoryRuleImport::LINK_RESULT_CREATE) {
             $this->rulepassed(0, $input['itemtype'], $input['entities_id']);
         } else {
             if (isset($input['itemtype']) and !isset($data['action'])) {
                 $this->rulepassed(0, $input['itemtype'], $input['entities_id']);
             } else {
                 $this->rulepassed(0, "PluginFusioninventoryUnmanaged", $input['entities_id']);
             }
         }
     }
 }
                                    }
                                }
                            }
                        }
                    }
                }
                $data['exceptions'] = exportArrayToDB($a_agentList);
                $agentmodule->update($data);
            }
            Html::back();
        } else {
            if (isset($_POST["update"])) {
                $agentmodule->getFromDB($_POST['id']);
                $input = array();
                if (isset($_POST['activation'])) {
                    $input['is_active'] = 1;
                } else {
                    $input['is_active'] = 0;
                }
                if ($agentmodule->fields['is_active'] != $input['is_active']) {
                    $a_agentList = array();
                    $input['exceptions'] = exportArrayToDB($a_agentList);
                }
                $input['id'] = $_POST['id'];
                $agentmodule->update($input);
                Html::back();
            }
        }
    }
}
Html::footer();
Example #24
0
    glpi_header($_SERVER['HTTP_REFERER']);
} else {
    if (isset($_POST['timezones_add'])) {
        $input = array();
        $pmConfig->getFromDB($_POST['id']);
        $input['id'] = $_POST['id'];
        $a_timezones = importArrayFromDB($pmConfig->fields['timezones']);
        foreach ($_POST['timezones_to_add'] as $timezone) {
            $a_timezones[] = $timezone;
        }
        $input['timezones'] = exportArrayToDB($a_timezones);
        $pmConfig->update($input);
        glpi_header($_SERVER['HTTP_REFERER']);
    } else {
        if (isset($_POST['timezones_delete'])) {
            $input = array();
            $pmConfig->getFromDB($_POST['id']);
            $input['id'] = $_POST['id'];
            $a_timezones = importArrayFromDB($pmConfig->fields['timezones']);
            foreach ($_POST['timezones_to_delete'] as $timezone) {
                $key = array_search($timezone, $a_timezones);
                unset($a_timezones[$key]);
            }
            $input['timezones'] = exportArrayToDB($a_timezones);
            $pmConfig->update($input);
            glpi_header($_SERVER['HTTP_REFERER']);
        }
    }
}
$pmConfig->showForm(0);
commonFooter();
 function convertPostdata($data)
 {
     // Convert arguments descriptions
     $a_arguments = array();
     foreach ($data as $name => $value) {
         if (strstr($name, "argument_")) {
             $name = str_replace("argument_", "", $name);
             $a_arguments[$name] = $value;
         }
     }
     $data['arguments'] = exportArrayToDB($a_arguments);
     $where = "`command_name`='" . $data['command_name'] . "'";
     if (isset($data['id'])) {
         $where .= " AND `id` != '" . $data['id'] . "'";
     }
     $num_com = countElementsInTable("glpi_plugin_monitoring_commands", $where);
     if ($num_com > 0) {
         $data['command_name'] = $data['command_name'] . mt_rand();
     }
     return $data;
 }
 /**
  * Display detail of each history line
  *
  * @param  $agents_id integer id of the agent
  * @param $uniqid integer uniq id of each taskjobs runing
  * @param $width integer how large in pixel display array
  *
  * @return value all text to display
  *
  **/
 function showHistoryInDetail($agents_id, $uniqid, $width = "950")
 {
     global $CFG_GLPI;
     $pfTaskjobstate = new PluginFusioninventoryTaskjobstate();
     $pfAgent = new PluginFusioninventoryAgent();
     $text = "<center><table class='tab_cadrehov' style='width: " . $width . "px'>";
     $a_jobstates = $pfTaskjobstate->find('`plugin_fusioninventory_agents_id`="' . $agents_id . '" ' . 'AND `uniqid`="' . $uniqid . '"', '`id` DESC');
     $a_devices_merged = array();
     foreach ($a_jobstates as $data) {
         $displayforceend = 0;
         $a_history = $this->find('`plugin_fusioninventory_taskjobstates_id` = "' . $data['id'] . '"', 'id');
         if (strstr(exportArrayToDB($a_history), "Merged with ")) {
             $classname = $data['itemtype'];
             $Class = new $classname();
             $Class->getFromDB($data['items_id']);
             $a_devices_merged[] = $Class->getLink(1) . "&nbsp;(" . $Class->getTypeName() . ")";
         } else {
             $text .= "<tr>";
             $text .= "<th colspan='2'><img src='" . $CFG_GLPI['root_doc'] . "/pics/puce.gif' />" . __('Process number', 'fusioninventory') . "&nbsp;: " . $data['id'] . "</th>";
             $text .= "<th>";
             $text .= __('Date');
             $text .= "</th>";
             $text .= "<th>";
             $text .= __('Status');
             $text .= "</th>";
             $text .= "<th>";
             $text .= __('Comments');
             $text .= "</th>";
             $text .= "</tr>";
             $text .= "<tr class='tab_bg_1'>";
             $text .= "<th colspan='2'>";
             $text .= __('Agent', 'fusioninventory');
             $text .= "</th>";
             $a_return = $this->displayHistoryDetail(array_shift($a_history));
             $count = $a_return[0];
             $text .= $a_return[1];
             $displayforceend += $count;
             $text .= "</tr>";
             $text .= "<tr class='tab_bg_1'>";
             $text .= "<td colspan='2'>";
             $pfAgent->getFromDB($data['plugin_fusioninventory_agents_id']);
             $text .= $pfAgent->getLink(1);
             $text .= "</td>";
             $a_return = $this->displayHistoryDetail(array_shift($a_history));
             $count = $a_return[0];
             $text .= $a_return[1];
             $displayforceend += $count;
             $text .= "</tr>";
             $text .= "<tr class='tab_bg_1'>";
             $text .= "<th colspan='2'>";
             $text .= __('Definition', 'fusioninventory');
             $text .= "<sup>(" . (count($a_devices_merged) + 1) . ")</sup>";
             $text .= "</th>";
             $a_return = $this->displayHistoryDetail(array_shift($a_history));
             $count = $a_return[0];
             $text .= $a_return[1];
             $displayforceend += $count;
             $text .= "</tr>";
             $text .= "<tr class='tab_bg_1'>";
             $text .= "<td colspan='2'>";
             if (!empty($data["itemtype"])) {
                 $device = new $data["itemtype"]();
                 $device->getFromDB($data["items_id"]);
                 $text .= $device->getLink(1);
                 $text .= "&nbsp;";
                 $text .= "(" . $device->getTypeName() . ")";
             }
             $text .= "</td>";
             $a_return = $this->displayHistoryDetail(array_shift($a_history));
             $count = $a_return[0];
             $text .= $a_return[1];
             $displayforceend += $count;
             $text .= "</tr>";
             while (count($a_history) != 0) {
                 if (count($a_devices_merged) > 0) {
                     $text .= "<tr class='tab_bg_1'>";
                     $text .= "<td colspan='2'>";
                     $text .= array_pop($a_devices_merged);
                     $text .= "</td>";
                     $a_return = $this->displayHistoryDetail(array_shift($a_history));
                     $count = $a_return[0];
                     $text .= $a_return[1];
                     $displayforceend += $count;
                     $text .= "</tr>";
                 } else {
                     $text .= "<tr class='tab_bg_1'>";
                     $text .= "<td colspan='2' rowspan='" . count($a_history) . "'>";
                     $text .= "</td>";
                     $a_return = $this->displayHistoryDetail(array_shift($a_history));
                     $count = $a_return[0];
                     $text .= $a_return[1];
                     $displayforceend += $count;
                     $text .= "</tr>";
                     while (count($a_history) != 0) {
                         $text .= "<tr class='tab_bg_1'>";
                         $a_return = $this->displayHistoryDetail(array_shift($a_history));
                         $count = $a_return[0];
                         $text .= $a_return[1];
                         $displayforceend += $count;
                         $text .= "</tr>";
                     }
                 }
             }
             $display = 1;
             while (count($a_devices_merged) != 0) {
                 $text .= "<tr class='tab_bg_1'>";
                 $text .= "<td colspan='2'>";
                 $text .= array_pop($a_devices_merged);
                 $text .= "</td>";
                 if ($display == "1") {
                     $text .= "<td colspan='3' rowspan='" . (count($a_devices_merged) + 1) . "'></td>";
                     $display = 0;
                 }
                 $text .= "</tr>";
             }
             $text .= "<tr class='tab_bg_4'>";
             $text .= "<td colspan='5' height='4'>";
             $text .= "</td>";
             $text .= "</tr>";
         }
     }
     $text .= "</table></center>";
     return $text;
 }
 /**
  * Add lock fields for a record.
  *
  *@param $p_itemtype Table id.
  *@param $p_items_id Line id.
  *@param $p_fieldsToLock Array of fields to lock.
  *TODO:  check rights and entity
  *
  *@return nothing
  **/
 static function addLocks($p_itemtype, $p_items_id, $p_fieldsToLock)
 {
     global $DB;
     if (TableExists('glpi_plugin_fusioninventory_lockable')) {
         $result = PluginFusioninventoryLock::getLock($p_itemtype, $p_items_id);
         if ($DB->numrows($result)) {
             $row = mysql_fetch_assoc($result);
             $lockedFields = importArrayFromDB($row['fields']);
             if (count(array_diff($p_fieldsToLock, $lockedFields))) {
                 // old locks --> new locks
                 $p_fieldsToLock = array_merge($p_fieldsToLock, $lockedFields);
                 $update = "UPDATE `glpi_plugin_fusioninventory_lock`\n                          SET `fields`='" . exportArrayToDB($p_fieldsToLock) . "'\n                          WHERE `itemtype`='" . $p_itemtype . "'\n                                AND `items_id`='" . $p_items_id . "';";
                 $DB->query($update);
             }
         } elseif (count($p_fieldsToLock)) {
             // no locks --> new locks
             $insert = "INSERT INTO `glpi_plugin_fusioninventory_lock` (`itemtype`, `items_id`, `fields`)\n                       VALUES ('" . $p_itemtype . "', '" . $p_items_id . "' ,\n                               '" . exportArrayToDB($p_fieldsToLock) . "');";
             $DB->query($insert);
         }
     }
 }
 function convertPostdata($data)
 {
     // Convert arguments descriptions
     $a_arguments = array();
     foreach ($data as $name => $value) {
         if (strstr($name, "argument_")) {
             $name = str_replace("argument_", "", $name);
             $a_arguments[$name] = $value;
         }
     }
     $data['arguments'] = exportArrayToDB($a_arguments);
     return $data;
 }
Example #29
0
function pluginFusioninventoryUpdate($current_version, $migrationname = 'Migration')
{
    global $DB;
    ini_set("max_execution_time", "0");
    ini_set("memory_limit", "-1");
    foreach (glob(GLPI_ROOT . '/plugins/fusioninventory/inc/*.php') as $file) {
        require_once $file;
    }
    $migration = new $migrationname($current_version);
    $prepare_task = array();
    $prepare_rangeip = array();
    $prepare_Config = array();
    $a_plugin = plugin_version_fusioninventory();
    $plugins_id = PluginFusioninventoryModule::getModuleId($a_plugin['shortname']);
    $migration->displayMessage("Migration Classname : " . $migrationname);
    $migration->displayMessage("Update of plugin FusionInventory");
    /*
     * Check if folders are correctly created
     */
    if (!is_dir(GLPI_PLUGIN_DOC_DIR . '/fusioninventory')) {
        mkdir(GLPI_PLUGIN_DOC_DIR . '/fusioninventory');
    }
    if (!is_dir(GLPI_PLUGIN_DOC_DIR . '/fusioninventory/tmp')) {
        mkdir(GLPI_PLUGIN_DOC_DIR . '/fusioninventory/tmp');
    }
    if (!is_dir(GLPI_PLUGIN_DOC_DIR . '/fusioninventory/xml')) {
        mkdir(GLPI_PLUGIN_DOC_DIR . '/fusioninventory/xml');
    }
    if (!is_dir(GLPI_PLUGIN_DOC_DIR . '/fusioninventory/xml/computer')) {
        mkdir(GLPI_PLUGIN_DOC_DIR . '/fusioninventory/xml/computer');
    }
    if (!is_dir(GLPI_PLUGIN_DOC_DIR . '/fusioninventory/xml/printer')) {
        mkdir(GLPI_PLUGIN_DOC_DIR . '/fusioninventory/xml/printer');
    }
    if (!is_dir(GLPI_PLUGIN_DOC_DIR . '/fusioninventory/xml/networkequipment')) {
        mkdir(GLPI_PLUGIN_DOC_DIR . '/fusioninventory/xml/networkequipment');
    }
    if (!is_dir(GLPI_PLUGIN_DOC_DIR . '/fusioninventory/walks')) {
        mkdir(GLPI_PLUGIN_DOC_DIR . '/fusioninventory/walks');
    }
    if (!is_dir(GLPI_PLUGIN_DOC_DIR . '/fusioninventory/tmpmodels')) {
        mkdir(GLPI_PLUGIN_DOC_DIR . '/fusioninventory/tmpmodels');
    }
    /*
     * Deploy folders
     */
    if (is_dir(GLPI_PLUGIN_DOC_DIR . '/fusinvdeploy/files')) {
        rename(GLPI_PLUGIN_DOC_DIR . '/fusinvdeploy/files', GLPI_PLUGIN_DOC_DIR . '/fusioninventory/files');
    }
    if (!is_dir(GLPI_PLUGIN_DOC_DIR . '/fusioninventory/files')) {
        mkdir(GLPI_PLUGIN_DOC_DIR . '/fusioninventory/files');
    }
    if (is_dir(GLPI_PLUGIN_DOC_DIR . '/fusinvdeploy/repository')) {
        rename(GLPI_PLUGIN_DOC_DIR . '/fusinvdeploy/repository', GLPI_PLUGIN_DOC_DIR . '/fusioninventory/repository');
    }
    if (!is_dir(GLPI_PLUGIN_DOC_DIR . '/fusioninventory/files/repository')) {
        mkdir(GLPI_PLUGIN_DOC_DIR . '/fusioninventory/files/repository');
    }
    if (!is_dir(GLPI_PLUGIN_DOC_DIR . '/fusioninventory/files/manifests')) {
        mkdir(GLPI_PLUGIN_DOC_DIR . '/fusioninventory/files/manifests');
    }
    if (!is_dir(GLPI_PLUGIN_DOC_DIR . '/fusioninventory/files/import')) {
        mkdir(GLPI_PLUGIN_DOC_DIR . '/fusioninventory/files/import');
    }
    if (!is_dir(GLPI_PLUGIN_DOC_DIR . '/fusioninventory/files/export')) {
        mkdir(GLPI_PLUGIN_DOC_DIR . '/fusioninventory/files/export');
    }
    if (is_dir(GLPI_PLUGIN_DOC_DIR . '/fusinvdeploy/upload')) {
        rename(GLPI_PLUGIN_DOC_DIR . '/fusinvdeploy/upload', GLPI_PLUGIN_DOC_DIR . '/fusioninventory/upload');
    }
    if (!is_dir(GLPI_PLUGIN_DOC_DIR . '/fusioninventory/upload')) {
        mkdir(GLPI_PLUGIN_DOC_DIR . '/fusioninventory/upload');
    }
    /*
     * Rename fileparts without .gz extension (cf #1999)
     */
    if (is_dir(GLPI_PLUGIN_DOC_DIR . '/fusioninventory/files')) {
        $gzfiles = pluginFusioninventoryFindFiles(GLPI_PLUGIN_DOC_DIR . '/fusioninventory/files', '/\\.gz$/');
        foreach ($gzfiles as $file) {
            $fileWithoutExt = pathinfo($file, PATHINFO_DIRNAME) . '/' . pathinfo($file, PATHINFO_FILENAME);
            rename($file, $fileWithoutExt);
        }
    }
    unset($gzfiles);
    /*
     *  Rename tables from old version of FuionInventory (2.2.1 for example)
     */
    $migration->renameTable("glpi_plugin_fusioninventory_rangeip", "glpi_plugin_fusioninventory_ipranges");
    $migration->renameTable("glpi_plugin_fusioninventory_lock", "glpi_plugin_fusioninventory_locks");
    $migration->renameTable("glpi_plugin_fusioninventory_unknown_device", "glpi_plugin_fusioninventory_unknowndevices");
    $migration->renameTable("glpi_plugin_fusioninventory_config", "glpi_plugin_fusioninventory_configs");
    $migration->renameTable("glpi_plugin_fusioninventory_networking_ports", "glpi_plugin_fusinvsnmp_networkports");
    $migration->renameTable("glpi_plugin_fusioninventory_construct_device", "glpi_plugin_fusinvsnmp_constructdevices");
    $migration->renameTable("glpi_plugin_fusioninventory_construct_mibs", "glpi_plugin_fusioninventory_snmpmodelconstructdevice_miboids");
    $migration->renameTable("glpi_plugin_fusioninventory_networking", "glpi_plugin_fusioninventory_networkequipments");
    $migration->renameTable("glpi_plugin_fusioninventory_networking_ifaddr", "glpi_plugin_fusinvsnmp_networkequipmentips");
    $migration->renameTable("glpi_plugin_fusioninventory_printers", "glpi_plugin_fusinvsnmp_printers");
    $migration->renameTable("glpi_plugin_fusioninventory_printers_cartridges", "glpi_plugin_fusinvsnmp_printercartridges");
    $migration->renameTable("glpi_plugin_fusioninventory_printers_history", "glpi_plugin_fusinvsnmp_printerlogs");
    $migration->renameTable("glpi_plugin_fusioninventory_model_infos", "glpi_plugin_fusioninventory_snmpmodels");
    $migration->renameTable("glpi_plugin_fusioninventory_mib_networking", "glpi_plugin_fusinvsnmp_modelmibs");
    $migration->renameTable("glpi_plugin_fusioninventory_snmp_connection", "glpi_plugin_fusinvsnmp_configsecurities");
    $migration->renameTable("glpi_plugin_fusioninventory_snmp_history", "glpi_plugin_fusinvsnmp_networkportlogs");
    $migration->renameTable("glpi_plugin_fusioninventory_snmp_history_connections", "glpi_plugin_fusinvsnmp_networkportconnectionlogs");
    $a_droptable = array('glpi_plugin_fusioninventory_agents_inventory_state', 'glpi_plugin_fusioninventory_config_modules', 'glpi_plugin_fusioninventory_connection_stats', 'glpi_plugin_fusioninventory_discovery', 'glpi_plugin_fusioninventory_errors', 'glpi_plugin_fusioninventory_lockable', 'glpi_plugin_fusioninventory_connection_history', 'glpi_plugin_fusioninventory_walks', 'glpi_plugin_fusioninventory_config_snmp_history', 'glpi_plugin_fusioninventory_config_snmp_networking', 'glpi_plugin_fusioninventory_task', 'glpi_plugin_fusinvinventory_pcidevices', 'glpi_plugin_fusinvinventory_pcivendors', 'glpi_plugin_fusinvinventory_usbdevices', 'glpi_plugin_fusinvinventory_usbvendors', 'glpi_plugin_fusinvsnmp_constructdevicewalks', 'glpi_plugin_fusioninventory_snmpmodelmiblabels', 'glpi_plugin_fusioninventory_snmpmodelmibobjects', 'glpi_plugin_fusioninventory_snmpmodelmiboids', 'glpi_plugin_fusioninventory_snmpmodelconstructdevices', 'glpi_plugin_fusioninventory_snmpmodelconstructdevicewalks' . 'glpi_plugin_fusioninventory_snmpmodelconstructdevices_users', 'glpi_plugin_fusioninventory_snmpmodelconstructdevice_miboids', 'glpi_plugin_fusioninventory_snmpmodelmibs', 'glpi_plugin_fusioninventory_snmpmodels', 'glpi_plugin_fusioninventory_snmpmodeldevices', 'glpi_plugin_fusinvsnmp_constructdevice_miboids', 'glpi_plugin_fusinvsnmp_constructdevices', 'glpi_plugin_fusinvsnmp_constructdevices_users', 'glpi_plugin_fusinvsnmp_miblabels', 'glpi_plugin_fusinvsnmp_mibobjects', 'glpi_plugin_fusinvsnmp_miboids', 'glpi_plugin_fusinvsnmp_modeldevices', 'glpi_plugin_fusinvsnmp_modelmibs', 'glpi_plugin_fusinvsnmp_models', 'glpi_plugin_fusioninventory_construct_walks');
    foreach ($a_droptable as $newTable) {
        $migration->dropTable($newTable);
    }
    /*
       $a_table = array();
    
       //table name
       $a_table['name'] = '';
       $a_table['oldname'] = array(
       );
    
       // fields : fields that are new, have changed type or just stay the same
       //    array(
       //        <fieldname> = array(
       //            'type' => <type>, 'value' => <value>)
       //    );
       $a_table['fields'] = array(
    
       );
    
       // oldfields = fields that need to be removed
       //    array( 'field0', 'field1', ...);
       $a_table['oldfields'] = array(
       );
    
       // renamefields = fields that need to be renamed
       //    array('oldname' = 'newname', ...)
       $a_table['renamefields'] = array(
       );
    
       // keys : new, changed or not
       //    array( 'field' => <fields>, 'name' => <keyname> , 'type' => <keytype>)
       // <fields> : fieldnames needed by the key
       //            ex : array('field0' , 'field1' ...)
       //            ex : 'fieldname'
       // <keyname> : the name of the key (if blank, the fieldname is used)
       // <type> : the type of key (ex: INDEX, ...)
       $a_table['keys'] = array(
       );
    
       // oldkeys : keys that need to be removed
       //    array( 'key0', 'key1', ... )
       $a_table['oldkeys'] = array(
       );
    */
    //Push task functionnality
    $migration->addField('glpi_plugin_fusioninventory_tasks', 'last_agent_wakeup', 'datetime');
    $migration->addField('glpi_plugin_fusioninventory_tasks', 'wakeup_agent_counter', "int(11) NOT NULL DEFAULT '0'");
    $migration->addField('glpi_plugin_fusioninventory_tasks', 'wakeup_agent_time', "int(11) NOT NULL DEFAULT '0'");
    $migration->addKey('glpi_plugin_fusioninventory_tasks', 'wakeup_agent_counter');
    $migration->migrationOneTable('glpi_plugin_fusioninventory_tasks');
    /*
     *  Table glpi_plugin_fusioninventory_agents
     */
    $newTable = "glpi_plugin_fusioninventory_agents";
    $prepare_agentConfig = array();
    if (TableExists("glpi_plugin_tracker_agents") and FieldExists("glpi_plugin_tracker_agents", "ifaddr_start")) {
        $query = "SELECT * FROM `glpi_plugin_tracker_agents`";
        $result = $DB->query($query);
        while ($data = $DB->fetch_array($result)) {
            $prepare_rangeip[] = array("ip_start" => $data['ifaddr_start'], "ip_end" => $data['ifaddr_end'], "name" => $data['name']);
            $prepare_agentConfig[] = array("name" => $data["name"], "lock" => $data['lock'], "threads_networkinventory" => $data['nb_process_query'], "threads_networkdiscovery" => $data['nb_process_discovery']);
        }
    } else {
        if (TableExists("glpi_plugin_tracker_agents") and FieldExists("glpi_plugin_tracker_agents", "core_discovery")) {
            $query = "SELECT * FROM `glpi_plugin_tracker_agents`";
            $result = $DB->query($query);
            while ($data = $DB->fetch_array($result)) {
                $prepare_agentConfig[] = array("name" => $data["name"], "lock" => $data['lock'], "threads_networkinventory" => $data['threads_query'], "threads_networkdiscovery" => $data['threads_discovery']);
            }
        } else {
            if (TableExists("glpi_plugin_fusioninventory_agents")) {
                if (FieldExists($newTable, "module_snmpquery")) {
                    $query = "SELECT * FROM `glpi_plugin_fusioninventory_agents`";
                    $result = $DB->query($query);
                    while ($data = $DB->fetch_array($result)) {
                        $prepare_agentConfig[] = array("id" => $data["ID"], "threads_networkinventory" => $data['threads_query'], "threads_networkdiscovery" => $data['threads_discovery'], "NETORKINVENTORY" => $data['module_snmpquery'], "NETWORKDISCOVERY" => $data['module_netdiscovery'], "INVENTORY" => $data['module_inventory'], "WAKEONLAN" => $data['module_wakeonlan']);
                    }
                }
            }
        }
    }
    $a_table = array();
    $a_table['name'] = 'glpi_plugin_fusioninventory_agents';
    $a_table['oldname'] = array('glpi_plugin_tracker_agents');
    $a_table['fields'] = array();
    $a_table['fields']['id'] = array('type' => 'autoincrement', 'value' => '');
    $a_table['fields']['entities_id'] = array('type' => 'integer', 'value' => NULL);
    $a_table['fields']['is_recursive'] = array('type' => 'bool', 'value' => '1');
    $a_table['fields']['name'] = array('type' => 'string', 'value' => NULL);
    $a_table['fields']['last_contact'] = array('type' => 'datetime', 'value' => NULL);
    $a_table['fields']['version'] = array('type' => 'string', 'value' => NULL);
    $a_table['fields']['lock'] = array('type' => 'bool', 'value' => NULL);
    $a_table['fields']['device_id'] = array('type' => 'string', 'value' => NULL);
    $a_table['fields']['computers_id'] = array('type' => 'integer', 'value' => NULL);
    $a_table['fields']['token'] = array('type' => 'string', 'value' => NULL);
    $a_table['fields']['useragent'] = array('type' => 'string', 'value' => NULL);
    $a_table['fields']['tag'] = array('type' => 'string', 'value' => NULL);
    $a_table['fields']['threads_networkdiscovery'] = array('type' => "int(4) NOT NULL DEFAULT '1' COMMENT 'array(xmltag=>value)'", 'value' => NULL);
    $a_table['fields']['threads_networkinventory'] = array('type' => "int(4) NOT NULL DEFAULT '1' COMMENT 'array(xmltag=>value)'", 'value' => NULL);
    $a_table['fields']['senddico'] = array('type' => 'bool', 'value' => NULL);
    $a_table['fields']['timeout_networkdiscovery'] = array('type' => "int(4) NOT NULL DEFAULT '0' COMMENT 'Network Discovery task timeout'", 'value' => NULL);
    $a_table['fields']['timeout_networkinventory'] = array('type' => "int(4) NOT NULL DEFAULT '0' COMMENT 'Network Inventory task timeout'", 'value' => NULL);
    $a_table['fields']['agent_port'] = array('type' => 'varchar(6)', 'value' => NULL);
    $a_table['oldfields'] = array('module_snmpquery', 'module_netdiscovery', 'module_inventory', 'module_wakeonlan', 'core_discovery', 'threads_discovery', 'core_query', 'threads_query', 'tracker_agent_version', 'logs', 'fragment', 'itemtype', 'device_type');
    $a_table['renamefields'] = array();
    $a_table['renamefields']['ID'] = 'id';
    $a_table['renamefields']['last_agent_update'] = 'last_contact';
    $a_table['renamefields']['fusioninventory_agent_version'] = 'version';
    $a_table['renamefields']['key'] = 'device_id';
    $a_table['renamefields']['on_device'] = 'computers_id';
    $a_table['renamefields']['items_id'] = 'computers_id';
    $a_table['keys'] = array();
    $a_table['keys'][] = array('field' => 'name', 'name' => '', 'type' => 'INDEX');
    $a_table['keys'][] = array('field' => 'device_id', 'name' => '', 'type' => 'INDEX');
    $a_table['keys'][] = array('field' => 'computers_id', 'name' => '', 'type' => 'INDEX');
    $a_table['oldkeys'] = array('key');
    migrateTablesFusionInventory($migration, $a_table);
    /*
     * Table glpi_plugin_fusioninventory_agentmodules
     */
    $a_table = array();
    $a_table['name'] = 'glpi_plugin_fusioninventory_agentmodules';
    $a_table['oldname'] = array();
    $a_table['fields'] = array();
    $a_table['fields']['id'] = array('type' => 'autoincrement', 'value' => '');
    $a_table['fields']['modulename'] = array('type' => 'string', 'value' => NULL);
    $a_table['fields']['is_active'] = array('type' => 'bool', 'value' => NULL);
    $a_table['fields']['exceptions'] = array('type' => 'text', 'value' => NULL);
    $a_table['oldfields'] = array();
    $a_table['oldfields'][] = 'plugins_id';
    $a_table['oldfields'][] = 'entities_id';
    $a_table['oldfields'][] = 'url';
    $a_table['renamefields'] = array();
    $a_table['keys'] = array();
    $a_table['keys'][] = array('field' => 'modulename', 'name' => '', 'type' => 'UNIQUE');
    $a_table['oldkeys'] = array('unicity', 'entities_id');
    migrateTablesFusionInventory($migration, $a_table);
    /*
     * Add Deploy module
     */
    $query = "SELECT `id` FROM `glpi_plugin_fusioninventory_agentmodules`\n      WHERE `modulename`='DEPLOY'";
    $result = $DB->query($query);
    if (!$DB->numrows($result)) {
        $query_ins = "INSERT INTO `glpi_plugin_fusioninventory_agentmodules`\n            (`modulename`, `is_active`, `exceptions`)\n         VALUES ('DEPLOY', '0', '" . exportArrayToDB(array()) . "')";
        $DB->query($query_ins);
    }
    /*
     * Add WakeOnLan module appear in version 2.3.0
     */
    $query = "SELECT `id` FROM `glpi_plugin_fusioninventory_agentmodules`\n      WHERE `modulename`='WAKEONLAN'";
    $result = $DB->query($query);
    if (!$DB->numrows($result)) {
        $query_ins = "INSERT INTO `glpi_plugin_fusioninventory_agentmodules`\n            (`modulename`, `is_active`, `exceptions`)\n         VALUES ('WAKEONLAN', '0', '" . exportArrayToDB(array()) . "')";
        $DB->query($query_ins);
    }
    /*
     * Add SNMPQUERY module if not present
     */
    $query = "UPDATE `glpi_plugin_fusioninventory_agentmodules`\n      SET `modulename`='NETWORKINVENTORY'\n      WHERE `modulename`='SNMPQUERY'";
    $DB->query($query);
    $query = "SELECT `id` FROM `glpi_plugin_fusioninventory_agentmodules`\n      WHERE `modulename`='NETWORKINVENTORY'";
    $result = $DB->query($query);
    if (!$DB->numrows($result)) {
        $agentmodule = new PluginFusioninventoryAgentmodule();
        $input = array();
        $input['modulename'] = "NETWORKINVENTORY";
        $input['is_active'] = 0;
        $input['exceptions'] = exportArrayToDB(array());
        $agentmodule->add($input);
    }
    /*
     * Add NETDISCOVERY module if not present
     */
    $query = "UPDATE `glpi_plugin_fusioninventory_agentmodules`\n      SET `modulename`='NETWORKDISCOVERY'\n      WHERE `modulename`='NETDISCOVERY'";
    $DB->query($query);
    $query = "SELECT `id` FROM `glpi_plugin_fusioninventory_agentmodules`\n      WHERE `modulename`='NETWORKDISCOVERY'";
    $result = $DB->query($query);
    if (!$DB->numrows($result)) {
        $agentmodule = new PluginFusioninventoryAgentmodule();
        $input = array();
        $input['modulename'] = "NETWORKDISCOVERY";
        $input['is_active'] = 0;
        $input['exceptions'] = exportArrayToDB(array());
        $agentmodule->add($input);
    }
    /*
     * Add INVENTORY module if not present
     */
    $query = "SELECT `id` FROM `glpi_plugin_fusioninventory_agentmodules`\n      WHERE `modulename`='INVENTORY'";
    $result = $DB->query($query);
    if (!$DB->numrows($result)) {
        $agentmodule = new PluginFusioninventoryAgentmodule();
        $input = array();
        $input['modulename'] = "INVENTORY";
        $input['is_active'] = 1;
        $input['exceptions'] = exportArrayToDB(array());
        $agentmodule->add($input);
    }
    /*
     * Table glpi_plugin_fusioninventory_configs
     */
    $newTable = "glpi_plugin_fusioninventory_configs";
    if (TableExists('glpi_plugin_tracker_config')) {
        if (FieldExists('glpi_plugin_tracker_config', 'ssl_only')) {
            $query = "SELECT * FROM `glpi_plugin_tracker_config`\n               LIMIT 1";
            $result = $DB->query($query);
            if ($DB->numrows($result) > 0) {
                $data = $DB->fetch_assoc($result);
                $prepare_Config['ssl_only'] = $data['ssl_only'];
            }
        }
        //         $query = "SELECT *  FROM `glpi_plugin_tracker_config`
        //            WHERE `type`='version'
        //            LIMIT 1, 10";
        //         $result=$DB->query($query);
        //         while ($data=$DB->fetch_array($result)) {
        //            $DB->query("DELETE FROM `glpi_plugin_tracker_config`
        //               WHERE `ID`='".$data['ID']."'");
        //         }
    }
    if (TableExists('glpi_plugin_fusioninventory_configs')) {
        $id = 'id';
        if (FieldExists('glpi_plugin_fusioninventory_configs', 'ID')) {
            $id = 'ID';
        }
        $query = "SELECT *  FROM `glpi_plugin_fusioninventory_configs`\n            WHERE `type`='version'\n            LIMIT 1, 10";
        $result = $DB->query($query);
        while ($data = $DB->fetch_array($result)) {
            $DB->query("DELETE FROM `glpi_plugin_fusioninventory_configs`\n               WHERE `" . $id . "`='" . $data[$id] . "'");
        }
    }
    $a_table = array();
    $a_table['name'] = 'glpi_plugin_fusioninventory_configs';
    $a_table['oldname'] = array('glpi_plugin_tracker_config');
    $a_table['fields'] = array();
    $a_table['fields']['id'] = array('type' => 'autoincrement', 'value' => '');
    $a_table['fields']['type'] = array('type' => 'string', 'value' => NULL);
    $a_table['fields']['value'] = array('type' => 'string', 'value' => NULL);
    $a_table['oldfields'] = array();
    $a_table['oldfields'][] = 'version';
    $a_table['oldfields'][] = 'URL_agent_conf';
    $a_table['oldfields'][] = 'ssl_only';
    $a_table['oldfields'][] = 'authsnmp';
    $a_table['oldfields'][] = 'inventory_frequence';
    $a_table['oldfields'][] = 'criteria1_ip';
    $a_table['oldfields'][] = 'criteria1_name';
    $a_table['oldfields'][] = 'criteria1_serial';
    $a_table['oldfields'][] = 'criteria1_macaddr';
    $a_table['oldfields'][] = 'criteria2_ip';
    $a_table['oldfields'][] = 'criteria2_name';
    $a_table['oldfields'][] = 'criteria2_serial';
    $a_table['oldfields'][] = 'criteria2_macaddr';
    $a_table['oldfields'][] = 'delete_agent_process';
    $a_table['oldfields'][] = 'activation_history';
    $a_table['oldfields'][] = 'activation_connection';
    $a_table['oldfields'][] = 'activation_snmp_computer';
    $a_table['oldfields'][] = 'activation_snmp_networking';
    $a_table['oldfields'][] = 'activation_snmp_peripheral';
    $a_table['oldfields'][] = 'activation_snmp_phone';
    $a_table['oldfields'][] = 'activation_snmp_printer';
    $a_table['oldfields'][] = 'plugins_id';
    $a_table['oldfields'][] = 'module';
    $a_table['renamefields'] = array();
    $a_table['renamefields']['ID'] = 'id';
    $a_table['keys'] = array();
    $a_table['keys'][] = array('field' => array("type"), 'name' => 'unicity', 'type' => 'UNIQUE');
    $a_table['oldkeys'] = array();
    migrateTablesFusionInventory($migration, $a_table);
    /*
     * Table glpi_plugin_fusioninventory_entities
     */
    $a_table = array();
    $a_table['name'] = 'glpi_plugin_fusioninventory_entities';
    $a_table['oldname'] = array();
    $a_table['fields'] = array();
    $a_table['fields']['id'] = array('type' => 'autoincrement', 'value' => '');
    $a_table['fields']['entities_id'] = array('type' => 'integer', 'value' => NULL);
    $a_table['fields']['transfers_id_auto'] = array('type' => 'integer', 'value' => NULL);
    $a_table['fields']['agent_base_url'] = array('type' => 'string', 'value' => '');
    $a_table['oldfields'] = array();
    $a_table['renamefields'] = array();
    $a_table['keys'] = array();
    $a_table['keys'][] = array('field' => array('entities_id', 'transfers_id_auto'), 'name' => 'entities_id', 'type' => 'INDEX');
    $a_table['oldkeys'] = array();
    migrateTablesFusionInventory($migration, $a_table);
    if (countElementsInTable($a_table['name']) == 0) {
        $a_configs = getAllDatasFromTable('glpi_plugin_fusioninventory_configs', "`type`='transfers_id_auto'");
        $transfers_id_auto = 0;
        if (count($a_configs) > 0) {
            $a_config = current($a_configs);
            $transfers_id_auto = $a_config['value'];
        }
        $a_configs = getAllDatasFromTable('glpi_plugin_fusioninventory_configs', "`type`='agent_base_url'");
        $agent_base_url = '';
        if (count($a_configs) > 0) {
            $a_config = current($a_configs);
            $agent_base_url = $a_config['value'];
        }
        $DB->query("INSERT INTO `glpi_plugin_fusioninventory_entities`\n               (`entities_id`, `transfers_id_auto`, `agent_base_url`)\n            VALUES ('0', '" . $transfers_id_auto . "', '" . $agent_base_url . "');");
    } else {
        if (countElementsInTable($a_table['name']) > 0) {
            $a_configs = getAllDatasFromTable('glpi_plugin_fusioninventory_configs', "`type`='agent_base_url'");
            $agent_base_url = '';
            if (count($a_configs) > 0) {
                $a_config = current($a_configs);
                $agent_base_url = $a_config['value'];
                $DB->query("UPDATE `glpi_plugin_fusioninventory_entities`\n                  SET `agent_base_url` = '" . $agent_base_url . "'\n                  ;");
            }
        }
    }
    /*
     * Table glpi_plugin_fusioninventory_credentials
     */
    $a_table = array();
    $a_table['name'] = 'glpi_plugin_fusioninventory_credentials';
    $a_table['oldname'] = array();
    $a_table['fields'] = array();
    $a_table['fields']['id'] = array('type' => 'autoincrement', 'value' => '');
    $a_table['fields']['entities_id'] = array('type' => 'integer', 'value' => NULL);
    $a_table['fields']['is_recursive'] = array('type' => 'bool', 'value' => NULL);
    $a_table['fields']['name'] = array('type' => 'string', 'value' => "");
    $a_table['fields']['username'] = array('type' => 'string', 'value' => "");
    $a_table['fields']['password'] = array('type' => 'string', 'value' => "");
    $a_table['fields']['comment'] = array('type' => 'text', 'value' => NULL);
    $a_table['fields']['date_mod'] = array('type' => 'datetime', 'value' => NULL);
    $a_table['fields']['itemtype'] = array('type' => 'string', 'value' => "");
    $a_table['oldfields'] = array();
    $a_table['renamefields'] = array();
    $a_table['keys'] = array();
    $a_table['oldkeys'] = array();
    migrateTablesFusionInventory($migration, $a_table);
    // Fix itemtype changed in 0.84
    $DB->query("UPDATE `glpi_plugin_fusioninventory_credentials`\n         SET `itemtype`='PluginFusioninventoryInventoryComputerESX'\n         WHERE `itemtype`='PluginFusinvinventoryVmwareESX'");
    /*
     * Table glpi_plugin_fusioninventory_credentialips
     */
    $a_table = array();
    $a_table['name'] = 'glpi_plugin_fusioninventory_credentialips';
    $a_table['oldname'] = array();
    $a_table['fields'] = array();
    $a_table['fields']['id'] = array('type' => 'autoincrement', 'value' => '');
    $a_table['fields']['entities_id'] = array('type' => 'integer', 'value' => NULL);
    $a_table['fields']['plugin_fusioninventory_credentials_id'] = array('type' => 'integer', 'value' => NULL);
    $a_table['fields']['name'] = array('type' => 'string', 'value' => "");
    $a_table['fields']['comment'] = array('type' => 'text', 'value' => NULL);
    $a_table['fields']['ip'] = array('type' => 'string', 'value' => "");
    $a_table['fields']['date_mod'] = array('type' => 'datetime', 'value' => NULL);
    $a_table['oldfields'] = array();
    $a_table['renamefields'] = array();
    $a_table['keys'] = array();
    $a_table['oldkeys'] = array();
    migrateTablesFusionInventory($migration, $a_table);
    /*
     * Table glpi_plugin_fusioninventory_ipranges
     */
    $newTable = "glpi_plugin_fusioninventory_ipranges";
    if (TableExists("glpi_plugin_tracker_rangeip")) {
        // Get all data to create task
        $query = "SELECT * FROM `glpi_plugin_tracker_rangeip`";
        $result = $DB->query($query);
        while ($data = $DB->fetch_array($result)) {
            if ($data['discover'] == '1') {
                $prepare_task[] = array("agents_id" => $data['FK_tracker_agents'], "ipranges_id" => $data['ID'], "netdiscovery" => "1");
            }
            if ($data['query'] == '1') {
                $prepare_task[] = array("agents_id" => $data['FK_tracker_agents'], "ipranges_id" => $data['ID'], "snmpquery" => "1");
            }
        }
    }
    if (TableExists("glpi_plugin_fusioninventory_rangeip") and FieldExists("glpi_plugin_fusioninventory_rangeip", "FK_fusioninventory_agents_discover")) {
        // Get all data to create task
        $query = "SELECT * FROM `glpi_plugin_fusioninventory_rangeip`";
        $result = $DB->query($query);
        while ($data = $DB->fetch_array($result)) {
            if ($data['discover'] == '1') {
                $prepare_task[] = array("agents_id" => $data['FK_fusioninventory_agents_discover'], "ipranges_id" => $data['ID'], "netdiscovery" => "1");
            }
            if ($data['query'] == '1') {
                $prepare_task[] = array("agents_id" => $data['FK_fusioninventory_agents_query'], "ipranges_id" => $data['ID'], "snmpquery" => "1");
            }
        }
    }
    $a_table = array();
    $a_table['name'] = 'glpi_plugin_fusioninventory_ipranges';
    $a_table['oldname'] = array('glpi_plugin_tracker_rangeip', 'glpi_plugin_fusinvsnmp_ipranges');
    $a_table['fields'] = array('id' => array('type' => 'autoincrement', 'value' => ''), 'name' => array('type' => 'string', 'value' => NULL), 'entities_id' => array('type' => 'integer', 'value' => NULL), 'ip_start' => array('type' => 'string', 'value' => NULL), 'ip_end' => array('type' => 'string', 'value' => NULL));
    $a_table['oldfields'] = array('FK_tracker_agents', 'discover', 'query', 'FK_fusioninventory_agents_discover', 'FK_fusioninventory_agents_query', 'construct_device_id', 'log', 'comment');
    $a_table['renamefields'] = array('ID' => 'id', 'ifaddr_start' => 'ip_start', 'ifaddr_end' => 'ip_end', 'FK_entities' => 'entities_id');
    $a_table['keys'] = array(array('field' => 'entities_id', 'name' => '', 'type' => 'INDEX'));
    $a_table['oldkeys'] = array('FK_tracker_agents', 'FK_tracker_agents_2');
    migrateTablesFusionInventory($migration, $a_table);
    /*
     * Table glpi_plugin_fusioninventory_locks
     */
    $a_table = array();
    $a_table['name'] = 'glpi_plugin_fusioninventory_locks';
    $a_table['oldname'] = array();
    $a_table['fields'] = array();
    $a_table['fields']['id'] = array('type' => 'autoincrement', 'value' => '');
    $a_table['fields']['tablename'] = array('type' => "varchar(64) COLLATE utf8_unicode_ci NOT NULL DEFAULT ''", 'value' => NULL);
    $a_table['fields']['items_id'] = array('type' => 'integer', 'value' => NULL);
    $a_table['fields']['tablefields'] = array('type' => 'text', 'value' => NULL);
    $a_table['oldfields'] = array('itemtype');
    $a_table['renamefields'] = array();
    $a_table['renamefields']['fields'] = 'tablefields';
    $a_table['keys'] = array();
    $a_table['keys'][] = array('field' => 'tablename', 'name' => '', 'type' => 'INDEX');
    $a_table['keys'][] = array('field' => 'items_id', 'name' => '', 'type' => 'INDEX');
    $a_table['oldkeys'] = array();
    migrateTablesFusionInventory($migration, $a_table);
    /*
     * Table glpi_plugin_fusioninventory_ipranges_configsecurities
     */
    $a_table = array();
    $a_table['name'] = 'glpi_plugin_fusioninventory_ipranges_configsecurities';
    $a_table['oldname'] = array();
    $a_table['fields'] = array();
    $a_table['fields']['id'] = array('type' => 'autoincrement', 'value' => '');
    $a_table['fields']['plugin_fusioninventory_ipranges_id'] = array('type' => 'integer', 'value' => NULL);
    $a_table['fields']['plugin_fusioninventory_configsecurities_id'] = array('type' => 'integer', 'value' => NULL);
    $a_table['fields']['rank'] = array('type' => 'integer', 'value' => '1');
    $a_table['oldfields'] = array();
    $a_table['renamefields'] = array();
    $a_table['keys'] = array();
    $a_table['oldkeys'] = array();
    migrateTablesFusionInventory($migration, $a_table);
    /*
     * Table glpi_plugin_fusioninventory_mappings
     */
    $a_table = array();
    $a_table['name'] = 'glpi_plugin_fusioninventory_mappings';
    $a_table['oldname'] = array();
    $a_table['fields'] = array();
    $a_table['fields']['id'] = array('type' => 'autoincrement', 'value' => '');
    $a_table['fields']['itemtype'] = array('type' => "varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL", 'value' => NULL);
    $a_table['fields']['name'] = array('type' => 'string', 'value' => NULL);
    $a_table['fields']['table'] = array('type' => 'string', 'value' => NULL);
    $a_table['fields']['tablefield'] = array('type' => 'string', 'value' => NULL);
    $a_table['fields']['locale'] = array('type' => "int(4) NOT NULL DEFAULT '0'", 'value' => NULL);
    $a_table['fields']['shortlocale'] = array('type' => 'int(4) DEFAULT NULL', 'value' => NULL);
    $a_table['oldfields'] = array();
    $a_table['renamefields'] = array();
    $a_table['keys'] = array();
    $a_table['keys'][] = array('field' => 'name', 'name' => '', 'type' => 'INDEX');
    $a_table['keys'][] = array('field' => 'itemtype', 'name' => '', 'type' => 'INDEX');
    $a_table['keys'][] = array('field' => 'table', 'name' => '', 'type' => 'INDEX');
    $a_table['keys'][] = array('field' => 'tablefield', 'name' => '', 'type' => 'INDEX');
    $a_table['oldkeys'] = array();
    migrateTablesFusionInventory($migration, $a_table);
    pluginFusioninventoryUpdatemapping();
    if (TableExists('glpi_plugin_fusioninventory_profiles')) {
        /*
         * Table glpi_plugin_fusioninventory_profiles
         */
        $a_table = array();
        $a_table['name'] = 'glpi_plugin_fusioninventory_profiles';
        $a_table['oldname'] = array();
        $a_table['fields'] = array();
        $a_table['fields']['id'] = array('type' => 'autoincrement', 'value' => '');
        $a_table['fields']['type'] = array('type' => 'string', 'value' => '');
        $a_table['fields']['right'] = array('type' => 'char', 'value' => NULL);
        $a_table['fields']['plugins_id'] = array('type' => 'integer', 'value' => NULL);
        $a_table['fields']['profiles_id'] = array('type' => 'integer', 'value' => NULL);
        $a_table['oldfields'] = array('name', 'interface', 'is_default', 'snmp_networking', 'snmp_printers', 'snmp_models', 'snmp_authentification', 'rangeip', 'agents', 'remotecontrol', 'agentsprocesses', 'unknowndevices', 'reports', 'deviceinventory', 'netdiscovery', 'snmp_query', 'wol', 'configuration');
        $a_table['renamefields'] = array();
        $a_table['renamefields']['ID'] = 'id';
        $a_table['keys'] = array();
        $a_table['oldkeys'] = array();
        migrateTablesFusionInventory($migration, $a_table);
        // Remove multiple lines can have problem with unicity
        $query = "SELECT * , count(`id`) AS cnt\n               FROM `glpi_plugin_fusioninventory_profiles`\n               GROUP BY `type`,`plugins_id`,`profiles_id`\n               HAVING cnt >1\n               ORDER BY cnt";
        $result = $DB->query($query);
        while ($data = $DB->fetch_array($result)) {
            $queryd = "DELETE FROM `glpi_plugin_fusioninventory_profiles`\n                  WHERE `type`='" . $data['type'] . "'\n                     AND `plugins_id`='" . $data['plugins_id'] . "'\n                     AND `profiles_id`='" . $data['profiles_id'] . "'\n                  ORDER BY `id` DESC\n                  LIMIT " . ($data['cnt'] - 1) . " ";
            $DB->query($queryd);
        }
        $a_table = array();
        $a_table['name'] = 'glpi_plugin_fusioninventory_profiles';
        $a_table['oldname'] = array();
        $a_table['fields'] = array();
        $a_table['oldfields'] = array();
        $a_table['renamefields'] = array();
        $a_table['keys'] = array();
        $a_table['keys'][] = array('field' => array("type", "plugins_id", "profiles_id"), 'name' => 'unicity', 'type' => 'UNIQUE');
        $a_table['oldkeys'] = array();
        migrateTablesFusionInventory($migration, $a_table);
    }
    /*
     * Update tasks related database tables
     */
    pluginFusioninventoryUpdateTasks($migration, $plugins_id);
    /*
     * Table glpi_plugin_fusioninventory_timeslots
     */
    $a_table = array();
    $a_table['name'] = 'glpi_plugin_fusioninventory_timeslots';
    $a_table['oldname'] = array();
    $a_table['fields'] = array();
    $a_table['fields']['id'] = array('type' => 'autoincrement', 'value' => '');
    $a_table['fields']['entities_id'] = array('type' => 'integer', 'value' => NULL);
    $a_table['fields']['is_recursive'] = array('type' => 'bool', 'value' => '0');
    $a_table['fields']['name'] = array('type' => 'string', 'value' => NULL);
    $a_table['fields']['comment'] = array('type' => 'text', 'value' => NULL);
    $a_table['fields']['date_mod'] = array('type' => 'datetime', 'value' => NULL);
    $a_table['oldfields'] = array();
    $a_table['renamefields'] = array();
    $a_table['keys'] = array();
    $a_table['oldkeys'] = array();
    migrateTablesFusionInventory($migration, $a_table);
    /*
     * Table glpi_plugin_fusioninventory_timeslotentries
     */
    $a_table = array();
    $a_table['name'] = 'glpi_plugin_fusioninventory_timeslotentries';
    $a_table['oldname'] = array();
    $a_table['fields'] = array();
    $a_table['fields']['id'] = array('type' => 'autoincrement', 'value' => '');
    $a_table['fields']['plugin_fusioninventory_timeslots_id'] = array('type' => 'integer', 'value' => NULL);
    $a_table['fields']['entities_id'] = array('type' => 'integer', 'value' => NULL);
    $a_table['fields']['is_recursive'] = array('type' => 'bool', 'value' => '0');
    $a_table['fields']['day'] = array('type' => 'bool', 'value' => 1);
    $a_table['fields']['begin'] = array('type' => 'int(11) DEFAULT NULL', 'value' => NULL);
    $a_table['fields']['end'] = array('type' => 'int(11) DEFAULT NULL', 'value' => NULL);
    $a_table['oldfields'] = array();
    $a_table['renamefields'] = array();
    $a_table['keys'] = array();
    $a_table['oldkeys'] = array();
    migrateTablesFusionInventory($migration, $a_table);
    /*
     * Table glpi_plugin_fusioninventory_unmanageds
     */
    $a_table = array();
    $a_table['name'] = 'glpi_plugin_fusioninventory_unmanageds';
    $a_table['oldname'] = array('glpi_plugin_fusioninventory_unknowndevices', 'glpi_plugin_tracker_unknown_device');
    $a_table['fields'] = array();
    $a_table['fields']['id'] = array('type' => 'autoincrement', 'value' => '');
    $a_table['fields']['name'] = array('type' => 'string', 'value' => NULL);
    $a_table['fields']['date_mod'] = array('type' => 'datetime', 'value' => NULL);
    $a_table['fields']['entities_id'] = array('type' => 'integer', 'value' => NULL);
    $a_table['fields']['locations_id'] = array('type' => 'integer', 'value' => NULL);
    $a_table['fields']['is_deleted'] = array('type' => 'bool', 'value' => NULL);
    $a_table['fields']['users_id'] = array('type' => 'integer', 'value' => NULL);
    $a_table['fields']['serial'] = array('type' => 'string', 'value' => NULL);
    $a_table['fields']['otherserial'] = array('type' => 'string', 'value' => NULL);
    $a_table['fields']['contact'] = array('type' => 'string', 'value' => NULL);
    $a_table['fields']['domain'] = array('type' => 'integer', 'value' => NULL);
    $a_table['fields']['comment'] = array('type' => 'text', 'value' => NULL);
    $a_table['fields']['item_type'] = array('type' => 'string', 'value' => NULL);
    $a_table['fields']['accepted'] = array('type' => 'bool', 'value' => NULL);
    $a_table['fields']['plugin_fusioninventory_agents_id'] = array('type' => 'integer', 'value' => NULL);
    $a_table['fields']['ip'] = array('type' => 'string', 'value' => NULL);
    $a_table['fields']['hub'] = array('type' => 'bool', 'value' => NULL);
    $a_table['fields']['states_id'] = array('type' => 'integer', 'value' => NULL);
    $a_table['fields']['sysdescr'] = array('type' => 'text', 'value' => NULL);
    $a_table['fields']['plugin_fusioninventory_configsecurities_id'] = array('type' => 'integer', 'value' => NULL);
    $a_table['fields']['is_dynamic'] = array('type' => 'bool', 'value' => NULL);
    $a_table['fields']['serialized_inventory'] = array('type' => 'longblob', 'value' => NULL);
    $a_table['oldfields'] = array('dnsname', 'snmp', 'FK_model_infos', 'FK_snmp_connection', 'FK_agent', 'mac', 'ifmac', 'plugin_fusinvsnmp_models_id', 'plugin_fusioninventory_snmpmodels_id', 'is_template');
    $a_table['renamefields'] = array('ID' => 'id', 'comments' => 'comment', 'type' => 'item_type', 'ifaddr' => 'ip', 'FK_entities' => 'entities_id', 'location' => 'locations_id', 'deleted' => 'is_deleted', 'plugin_fusinvsnmp_configsecurities_id' => 'plugin_fusioninventory_configsecurities_id');
    $a_table['keys'] = array(array('field' => 'entities_id', 'name' => '', 'type' => 'INDEX'), array('field' => 'plugin_fusioninventory_agents_id', 'name' => '', 'type' => 'INDEX'), array('field' => 'is_deleted', 'name' => '', 'type' => 'INDEX'), array('field' => 'date_mod', 'name' => '', 'type' => 'INDEX'));
    $a_table['oldkeys'] = array();
    migrateTablesFusionInventory($migration, $a_table);
    if (TableExists('glpi_plugin_fusinvsnmp_unknowndevices')) {
        $query = "SELECT * FROM `glpi_plugin_fusinvsnmp_unknowndevices`";
        $result = $DB->query($query);
        while ($data = $DB->fetch_array($result)) {
            $DB->query("UPDATE `glpi_plugin_fusioninventory_unmanageds`\n               SET `sysdescr`='" . $data['sysdescr'] . "',\n                   `plugin_fusioninventory_configsecurities_id`='" . $data['plugin_fusinvsnmp_configsecurities_id'] . "'\n               WHERE `id`='" . $data['plugin_fusioninventory_unknowndevices_id'] . "'");
        }
        $migration->dropTable('glpi_plugin_fusinvsnmp_unknowndevices');
    }
    /*
     * Table glpi_plugin_fusioninventory_ignoredimportdevices
     */
    $a_table = array();
    $a_table['name'] = 'glpi_plugin_fusioninventory_ignoredimportdevices';
    $a_table['oldname'] = array();
    $a_table['fields'] = array();
    $a_table['fields']['id'] = array('type' => 'autoincrement', 'value' => '');
    $a_table['fields']['name'] = array('type' => 'string', 'value' => NULL);
    $a_table['fields']['date'] = array('type' => 'datetime', 'value' => NULL);
    $a_table['fields']['itemtype'] = array('type' => "varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL", 'value' => NULL);
    $a_table['fields']['entities_id'] = array('type' => 'integer', 'value' => NULL);
    $a_table['fields']['ip'] = array('type' => 'string', 'value' => NULL);
    $a_table['fields']['mac'] = array('type' => 'string', 'value' => NULL);
    $a_table['fields']['rules_id'] = array('type' => 'integer', 'value' => NULL);
    $a_table['fields']['method'] = array('type' => 'string', 'value' => NULL);
    $a_table['fields']['serial'] = array('type' => 'string', 'value' => NULL);
    $a_table['fields']['uuid'] = array('type' => 'string', 'value' => NULL);
    $a_table['oldfields'] = array();
    $a_table['renamefields'] = array();
    $a_table['keys'] = array();
    $a_table['oldkeys'] = array();
    migrateTablesFusionInventory($migration, $a_table);
    /*
     * Table glpi_plugin_fusioninventory_inventorycomputercriterias
     */
    $a_table = array();
    $a_table['name'] = 'glpi_plugin_fusioninventory_inventorycomputercriterias';
    $a_table['oldname'] = array('glpi_plugin_fusinvinventory_criterias');
    $a_table['fields'] = array();
    $a_table['fields']['id'] = array('type' => 'autoincrement', 'value' => '');
    $a_table['fields']['name'] = array('type' => 'string', 'value' => NULL);
    $a_table['fields']['comment'] = array('type' => 'text', 'value' => NULL);
    $a_table['oldfields'] = array();
    $a_table['renamefields'] = array();
    $a_table['keys'] = array();
    $a_table['keys'][] = array('field' => 'name', 'name' => '', 'type' => 'INDEX');
    $a_table['oldkeys'] = array();
    migrateTablesFusionInventory($migration, $a_table);
    /*
     * Table glpi_plugin_fusioninventory_rulematchedlogs
     */
    $newTable = "glpi_plugin_fusioninventory_rulematchedlogs";
    if (!TableExists($newTable)) {
        $query = "CREATE TABLE `" . $newTable . "` (\n                     `id` int(11) NOT NULL AUTO_INCREMENT,\n                      PRIMARY KEY (`id`)\n                  ) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1";
        $DB->query($query);
    }
    $migration->changeField($newTable, "id", "id", "int(11) NOT NULL AUTO_INCREMENT");
    $migration->migrationOneTable($newTable);
    $migration->addField($newTable, "date", "datetime DEFAULT NULL");
    $migration->addField($newTable, "items_id", "int(11) NOT NULL DEFAULT '0'");
    $migration->addField($newTable, "itemtype", "varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL");
    $migration->addField($newTable, "rules_id", "int(11) NOT NULL DEFAULT '0'");
    $migration->addField($newTable, "plugin_fusioninventory_agents_id", "int(11) NOT NULL DEFAULT '0'");
    $migration->addField($newTable, "method", "varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL");
    $migration->migrationOneTable($newTable);
    $DB->list_fields($newTable, FALSE);
    /*
     * Table glpi_plugin_fusioninventory_inventorycomputerblacklists
     */
    $a_table = array();
    $a_table['name'] = 'glpi_plugin_fusioninventory_inventorycomputerblacklists';
    $a_table['oldname'] = array('glpi_plugin_fusinvinventory_blacklists');
    $a_table['fields'] = array();
    $a_table['fields']['id'] = array('type' => 'autoincrement', 'value' => '');
    $a_table['fields']['plugin_fusioninventory_criterium_id'] = array('type' => 'integer', 'value' => NULL);
    $a_table['fields']['value'] = array('type' => 'string', 'value' => NULL);
    $a_table['oldfields'] = array();
    $a_table['renamefields'] = array();
    $a_table['keys'] = array();
    $a_table['keys'][] = array('field' => 'plugin_fusioninventory_criterium_id', 'name' => '', 'type' => 'KEY');
    $a_table['oldkeys'] = array();
    migrateTablesFusionInventory($migration, $a_table);
    $DB->list_fields($newTable, FALSE);
    pluginFusioninventorychangeDisplayPreference("5153", "PluginFusioninventoryUnknownDevice");
    pluginFusioninventorychangeDisplayPreference("5158", "PluginFusioninventoryAgent");
    /*
     *  Udpate criteria for blacklist
     */
    $a_criteria = array();
    $a_criteria['Serial number'] = 'ssn';
    $a_criteria['uuid'] = 'uuid';
    $a_criteria['Mac address'] = 'macAddress';
    $a_criteria['Windows product key'] = 'winProdKey';
    $a_criteria['Model'] = 'smodel';
    $a_criteria['storage serial'] = 'storagesSerial';
    $a_criteria['drives serial'] = 'drivesSerial';
    $a_criteria['Asset Tag'] = 'assetTag';
    $a_criteria['Computer name'] = 'name';
    $a_criteria['Manufacturer'] = 'manufacturer';
    foreach ($a_criteria as $name => $comment) {
        $query = "SELECT * FROM `glpi_plugin_fusioninventory_inventorycomputercriterias`\n            WHERE `name`='" . $name . "'";
        $result = $DB->query($query);
        if ($DB->numrows($result) == '0') {
            $query_ins = "INSERT INTO `glpi_plugin_fusioninventory_inventorycomputercriterias`\n               (`name`, `comment`)\n               VALUES ('" . $name . "', '" . $comment . "')";
            $DB->query($query_ins);
        }
    }
    $a_criteria = array();
    $query = "SELECT * FROM `glpi_plugin_fusioninventory_inventorycomputercriterias`";
    $result = $DB->query($query);
    while ($data = $DB->fetch_array($result)) {
        $a_criteria[$data['comment']] = $data['id'];
    }
    /*
     * Update blacklist
     */
    $newTable = "glpi_plugin_fusioninventory_inventorycomputerblacklists";
    // * ssn
    $a_input = array('N/A', '(null string)', 'INVALID', 'SYS-1234567890', 'SYS-9876543210', 'SN-12345', 'SN-1234567890', '1111111111', '1111111', '1', '0123456789', '12345', '123456', '1234567', '12345678', '123456789', '1234567890', '123456789000', '12345678901234567', '0000000000', '000000000', '00000000', '0000000', '0000000', 'NNNNNNN', 'xxxxxxxxxxx', 'EVAL', 'IATPASS', 'none', 'To Be Filled By O.E.M.', 'Tulip Computers', 'Serial Number xxxxxx', 'SN-123456fvgv3i0b8o5n6n7k', 'Unknow', 'System Serial Number', 'MB-1234567890', '0', 'empty', 'Not Specified');
    foreach ($a_input as $value) {
        $query = "SELECT * FROM `" . $newTable . "`\n               WHERE `plugin_fusioninventory_criterium_id`='" . $a_criteria['ssn'] . "'\n                AND `value`='" . $value . "'";
        $result = $DB->query($query);
        if ($DB->numrows($result) == '0') {
            $query = "INSERT INTO `" . $newTable . "`\n                     (`plugin_fusioninventory_criterium_id`, `value`)\n                  VALUES ( '" . $a_criteria['ssn'] . "', '" . $value . "')";
            $DB->query($query);
        }
    }
    // * uuid
    $a_input = array('FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF', '03000200-0400-0500-0006-000700080009', '6AB5B300-538D-1014-9FB5-B0684D007B53', '01010101-0101-0101-0101-010101010101');
    foreach ($a_input as $value) {
        $query = "SELECT * FROM `" . $newTable . "`\n               WHERE `plugin_fusioninventory_criterium_id`='" . $a_criteria['uuid'] . "'\n                AND `value`='" . $value . "'";
        $result = $DB->query($query);
        if ($DB->numrows($result) == '0') {
            $query = "INSERT INTO `" . $newTable . "`\n                     (`plugin_fusioninventory_criterium_id`, `value`)\n                  VALUES ( '" . $a_criteria['uuid'] . "', '" . $value . "')";
            $DB->query($query);
        }
    }
    // * macAddress
    $a_input = array('20:41:53:59:4e:ff', '02:00:4e:43:50:49', 'e2:e6:16:20:0a:35', 'd2:0a:2d:a0:04:be', '00:a0:c6:00:00:00', 'd2:6b:25:2f:2c:e7', '33:50:6f:45:30:30', '0a:00:27:00:00:00', '00:50:56:C0:00:01', '00:50:56:C0:00:08', '02:80:37:EC:02:00', '50:50:54:50:30:30', '24:b6:20:52:41:53');
    foreach ($a_input as $value) {
        $query = "SELECT * FROM `" . $newTable . "`\n               WHERE `plugin_fusioninventory_criterium_id`='" . $a_criteria['macAddress'] . "'\n                AND `value`='" . $value . "'";
        $result = $DB->query($query);
        if ($DB->numrows($result) == '0') {
            $query = "INSERT INTO `" . $newTable . "`\n                     (`plugin_fusioninventory_criterium_id`, `value`)\n                  VALUES ( '" . $a_criteria['macAddress'] . "', '" . $value . "')";
            $DB->query($query);
        }
    }
    // * smodel
    $a_input = array('Unknow', 'To Be Filled By O.E.M.', '*', 'System Product Name', 'Product Name', 'System Name');
    foreach ($a_input as $value) {
        $query = "SELECT * FROM `" . $newTable . "`\n               WHERE `plugin_fusioninventory_criterium_id`='" . $a_criteria['smodel'] . "'\n                AND `value`='" . $value . "'";
        $result = $DB->query($query);
        if ($DB->numrows($result) == '0') {
            $query = "INSERT INTO `" . $newTable . "`\n                     (`plugin_fusioninventory_criterium_id`, `value`)\n                  VALUES ( '" . $a_criteria['smodel'] . "', '" . $value . "')";
            $DB->query($query);
        }
    }
    // * manufacturer
    $a_input = array('System manufacturer');
    foreach ($a_input as $value) {
        $query = "SELECT * FROM `" . $newTable . "`\n               WHERE `plugin_fusioninventory_criterium_id`='" . $a_criteria['manufacturer'] . "'\n                AND `value`='" . $value . "'";
        $result = $DB->query($query);
        if ($DB->numrows($result) == '0') {
            $query = "INSERT INTO `" . $newTable . "`\n                     (`plugin_fusioninventory_criterium_id`, `value`)\n                  VALUES ( '" . $a_criteria['manufacturer'] . "', '" . $value . "')";
            $DB->query($query);
        }
    }
    // * ip
    $query = "SELECT * FROM `glpi_plugin_fusioninventory_inventorycomputercriterias`\n            WHERE `name`='IP'";
    $result = $DB->query($query);
    if ($DB->numrows($result) == 0) {
        $DB->query("INSERT INTO `glpi_plugin_fusioninventory_inventorycomputercriterias`\n               (`id`, `name`, `comment`) VALUES\n               (11, 'IP', 'IP')");
    }
    $a_criteria = array();
    $query = "SELECT * FROM `glpi_plugin_fusioninventory_inventorycomputercriterias`";
    $result = $DB->query($query);
    while ($data = $DB->fetch_array($result)) {
        $a_criteria[$data['comment']] = $data['id'];
    }
    $a_input = array('0.0.0.0');
    foreach ($a_input as $value) {
        $query = "SELECT * FROM `" . $newTable . "`\n               WHERE `plugin_fusioninventory_criterium_id`='" . $a_criteria['IP'] . "'\n                AND `value`='" . $value . "'";
        $result = $DB->query($query);
        if ($DB->numrows($result) == '0') {
            $query = "INSERT INTO `" . $newTable . "`\n                     (`plugin_fusioninventory_criterium_id`, `value`)\n                  VALUES ( '" . $a_criteria['IP'] . "', '" . $value . "')";
            $DB->query($query);
        }
    }
    /*
     * Table glpi_plugin_fusioninventory_inventorycomputerantiviruses
     */
    $newTable = "glpi_plugin_fusioninventory_inventorycomputerantiviruses";
    $migration->renameTable("glpi_plugin_fusinvinventory_antivirus", $newTable);
    if (!TableExists($newTable)) {
        $DB->query("CREATE TABLE `" . $newTable . "` (\n                        `id` int(11) NOT NULL AUTO_INCREMENT,\n                        PRIMARY KEY (`id`)\n                   ) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1");
    }
    $migration->addField($newTable, "id", "int(11) NOT NULL AUTO_INCREMENT");
    $migration->addField($newTable, "computers_id", "int(11) NOT NULL DEFAULT '0'");
    $migration->addField($newTable, "name", "varchar(255) DEFAULT NULL");
    $migration->addField($newTable, "manufacturers_id", "int(11) NOT NULL DEFAULT '0'");
    $migration->addField($newTable, "version", "varchar(255) DEFAULT NULL");
    $migration->addField($newTable, "is_active", "tinyint(1) NOT NULL DEFAULT '0'");
    $migration->addField($newTable, "uptodate", "tinyint(1) NOT NULL DEFAULT '0'");
    $migration->addKey($newTable, "name");
    $migration->addKey($newTable, "version");
    $migration->addKey($newTable, "is_active");
    $migration->addKey($newTable, "uptodate");
    $migration->addKey($newTable, "computers_id");
    $migration->migrationOneTable($newTable);
    $DB->list_fields($newTable, FALSE);
    /*
     * Table glpi_plugin_fusioninventory_inventorycomputerbatteries
     */
    $newTable = "glpi_plugin_fusioninventory_inventorycomputerbatteries";
    if (!TableExists($newTable)) {
        $query = "CREATE TABLE `" . $newTable . "` (\n                     `id` int(11) NOT NULL AUTO_INCREMENT,\n                      PRIMARY KEY (`id`)\n                  ) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1";
        $DB->query($query);
    }
    $migration->changeField($newTable, "id", "id", "int(11) NOT NULL AUTO_INCREMENT");
    $migration->changeField($newTable, "computers_id", "computers_id", "int(11) NOT NULL DEFAULT '0'");
    $migration->changeField($newTable, "name", "name", "varchar(255) DEFAULT NULL");
    $migration->changeField($newTable, "manufacturers_id", "manufacturers_id", "int(11) NOT NULL DEFAULT '0'");
    $migration->changeField($newTable, "serial", "serial", "varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL");
    $migration->changeField($newTable, "capacity", "capacity", "int(11) NOT NULL DEFAULT '0'");
    $migration->changeField($newTable, "date", "date", "datetime DEFAULT NULL");
    $migration->changeField($newTable, "plugin_fusioninventory_inventorycomputerchemistries_id", "plugin_fusioninventory_inventorycomputerchemistries_id", "int(11) NOT NULL DEFAULT '0'");
    $migration->changeField($newTable, "voltage", "voltage", "int(11) NOT NULL DEFAULT '0'");
    $migration->migrationOneTable($newTable);
    $migration->addField($newTable, "id", "int(11) NOT NULL AUTO_INCREMENT");
    $migration->addField($newTable, "computers_id", "int(11) NOT NULL DEFAULT '0'");
    $migration->addField($newTable, "name", "varchar(255) DEFAULT NULL");
    $migration->addField($newTable, "manufacturers_id", "int(11) NOT NULL DEFAULT '0'");
    $migration->addField($newTable, "serial", "varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL");
    $migration->addField($newTable, "capacity", "int(11) NOT NULL DEFAULT '0'");
    $migration->addField($newTable, "date", "datetime DEFAULT NULL");
    $migration->addField($newTable, "plugin_fusioninventory_inventorycomputerchemistries_id", "int(11) NOT NULL DEFAULT '0'");
    $migration->addField($newTable, "voltage", "int(11) NOT NULL DEFAULT '0'");
    $migration->migrationOneTable($newTable);
    $migration->addKey($newTable, "computers_id");
    $migration->migrationOneTable($newTable);
    $DB->list_fields($newTable, FALSE);
    /*
     * Table glpi_plugin_fusioninventory_inventorycomputerchemistries
     */
    $newTable = "glpi_plugin_fusioninventory_inventorycomputerchemistries";
    if (!TableExists($newTable)) {
        $query = "CREATE TABLE `" . $newTable . "` (\n                     `id` int(11) NOT NULL AUTO_INCREMENT,\n                      PRIMARY KEY (`id`)\n                  ) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1";
        $DB->query($query);
    }
    $migration->changeField($newTable, "id", "id", "int(11) NOT NULL AUTO_INCREMENT");
    $migration->changeField($newTable, "name", "name", "varchar(255) DEFAULT NULL");
    $migration->migrationOneTable($newTable);
    $migration->addField($newTable, "id", "int(11) NOT NULL AUTO_INCREMENT");
    $migration->addField($newTable, "name", "varchar(255) DEFAULT NULL");
    $migration->migrationOneTable($newTable);
    $migration->addKey($newTable, "name");
    $migration->migrationOneTable($newTable);
    $DB->list_fields($newTable, FALSE);
    /*
     * Table glpi_plugin_fusioninventory_inventorycomputercomputers
     */
    if (TableExists("glpi_plugin_fusinvinventory_computers") and FieldExists("glpi_plugin_fusinvinventory_computers", "uuid")) {
        $Computer = new Computer();
        $sql = "SELECT * FROM `glpi_plugin_fusinvinventory_computers`";
        $result = $DB->query($sql);
        while ($data = $DB->fetch_array($result)) {
            if ($Computer->getFromDB($data['items_id'])) {
                $input = array();
                $input['id'] = $data['items_id'];
                $input['uuid'] = $data['uuid'];
                $Computer->update($input);
            }
        }
        $sql = "DROP TABLE `glpi_plugin_fusinvinventory_computers`";
        $DB->query($sql);
    }
    if (TableExists("glpi_plugin_fusinvinventory_tmp_agents")) {
        $sql = "DROP TABLE `glpi_plugin_fusinvinventory_tmp_agents`";
        $DB->query($sql);
    }
    $a_table = array();
    $a_table['name'] = 'glpi_plugin_fusioninventory_inventorycomputercomputers';
    $a_table['oldname'] = array('glpi_plugin_fusinvinventory_computers');
    $a_table['fields'] = array();
    $a_table['fields']['id'] = array('type' => 'autoincrement', 'value' => '');
    $a_table['fields']['computers_id'] = array('type' => 'integer', 'value' => NULL);
    $a_table['fields']['bios_date'] = array('type' => 'datetime', 'value' => NULL);
    $a_table['fields']['bios_version'] = array('type' => 'string', 'value' => NULL);
    $a_table['fields']['bios_assettag'] = array('type' => 'string', 'value' => NULL);
    $a_table['fields']['bios_manufacturers_id'] = array('type' => 'integer', 'value' => NULL);
    $a_table['fields']['operatingsystem_installationdate'] = array('type' => 'datetime', 'value' => NULL);
    $a_table['fields']['winowner'] = array('type' => 'string', 'value' => NULL);
    $a_table['fields']['wincompany'] = array('type' => 'string', 'value' => NULL);
    $a_table['fields']['last_fusioninventory_update'] = array('type' => 'datetime', 'value' => NULL);
    $a_table['fields']['remote_addr'] = array('type' => 'string', 'value' => NULL);
    $a_table['fields']['plugin_fusioninventory_computerarchs_id'] = array('type' => 'integer', 'value' => NULL);
    $a_table['fields']['serialized_inventory'] = array('type' => 'longblob', 'value' => "");
    $a_table['fields']['is_entitylocked'] = array('type' => 'bool', 'value' => "0");
    $a_table['fields']['oscomment'] = array('type' => 'text', 'value' => NULL);
    $a_table['oldfields'] = array();
    $a_table['renamefields'] = array();
    $a_table['keys'] = array();
    $a_table['keys'][] = array('field' => 'computers_id', 'name' => '', 'type' => 'INDEX');
    $a_table['keys'][] = array('field' => 'last_fusioninventory_update', 'name' => '', 'type' => 'INDEX');
    $a_table['oldkeys'] = array();
    migrateTablesFusionInventory($migration, $a_table);
    // Migrate libserialization
    require_once GLPI_ROOT . "/plugins/fusioninventory/inc/inventorycomputercomputer.class.php";
    $pfInventoryComputerComputer = new PluginFusioninventoryInventoryComputerComputer();
    if (TableExists('glpi_plugin_fusinvinventory_libserialization')) {
        $query = "SELECT * FROM `glpi_plugin_fusinvinventory_libserialization`";
        $result = $DB->query($query);
        while ($data = $DB->fetch_array($result)) {
            $a_pfcomputer = array();
            $a_pfcomputer = current($pfInventoryComputerComputer->find("`computers_id`='" . $data['computers_id'] . "'", "", 1));
            if (empty($a_pfcomputer)) {
                // Add
                if (countElementsInTable("glpi_computers", "`id`='" . $data['computers_id'] . "'") > 0) {
                    $input = array();
                    $input['computers_id'] = $data['computers_id'];
                    $input['last_fusioninventory_update'] = $data['last_fusioninventory_update'];
                    $pfInventoryComputerComputer->add($input);
                }
            } else {
                // Update
                $a_pfcomputer['last_fusioninventory_update'] = $data['last_fusioninventory_update'];
                $pfInventoryComputerComputer->update($a_pfcomputer);
            }
        }
    }
    $migration->dropTable('glpi_plugin_fusinvinventory_libserialization');
    /*
     * Table glpi_plugin_fusioninventory_inventorycomputerstats
     */
    if (!TableExists("glpi_plugin_fusioninventory_inventorycomputerstats")) {
        $a_table = array();
        $a_table['name'] = 'glpi_plugin_fusioninventory_inventorycomputerstats';
        $a_table['oldname'] = array();
        $a_table['fields'] = array();
        $a_table['fields']['id'] = array('type' => "smallint(3) NOT NULL AUTO_INCREMENT", 'value' => '');
        $a_table['fields']['day'] = array('type' => "smallint(3) NOT NULL DEFAULT '0'", 'value' => '');
        $a_table['fields']['hour'] = array('type' => "tinyint(2) NOT NULL DEFAULT '0'", 'value' => '');
        $a_table['fields']['counter'] = array('type' => 'integer', 'value' => NULL);
        $a_table['oldfields'] = array();
        $a_table['renamefields'] = array();
        $a_table['keys'] = array();
        $a_table['oldkeys'] = array();
        migrateTablesFusionInventory($migration, $a_table);
        require_once GLPI_ROOT . "/plugins/fusioninventory/inc/inventorycomputerstat.class.php";
        PluginFusioninventoryInventoryComputerStat::init();
    }
    /*
     * Table glpi_plugin_fusioninventory_inventorycomputerstorages
     */
    $newTable = "glpi_plugin_fusioninventory_inventorycomputerstorages";
    if (!TableExists($newTable)) {
        $query = "CREATE TABLE `" . $newTable . "` (\n                     `id` int(11) NOT NULL AUTO_INCREMENT,\n                      PRIMARY KEY (`id`)\n                  ) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1";
        $DB->query($query);
    }
    $migration->changeField($newTable, "id", "id", "int(11) NOT NULL AUTO_INCREMENT");
    $migration->changeField($newTable, "name", "name", "varchar(255) DEFAULT NULL");
    $migration->changeField($newTable, "uuid", "uuid", "varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL");
    $migration->changeField($newTable, "totalsize", "totalsize", "int(11) NOT NULL DEFAULT '0'");
    $migration->changeField($newTable, "freesize", "freesize", "int(11) NOT NULL DEFAULT '0'");
    $migration->changeField($newTable, "plugin_fusioninventory_inventorycomputerstoragetypes_id", "plugin_fusioninventory_inventorycomputerstoragetypes_id", "int(11) NOT NULL DEFAULT '0'");
    $migration->changeField($newTable, "computers_id", "computers_id", "int(11) NOT NULL DEFAULT '0'");
    $migration->migrationOneTable($newTable);
    $migration->addField($newTable, "id", "int(11) NOT NULL AUTO_INCREMENT");
    $migration->addField($newTable, "name", "varchar(255) DEFAULT NULL");
    $migration->addField($newTable, "uuid", "varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL");
    $migration->addField($newTable, "totalsize", "int(11) NOT NULL DEFAULT '0'");
    $migration->addField($newTable, "freesize", "int(11) NOT NULL DEFAULT '0'");
    $migration->addField($newTable, "plugin_fusioninventory_inventorycomputerstoragetypes_id", "int(11) NOT NULL DEFAULT '0'");
    $migration->addField($newTable, "computers_id", "int(11) NOT NULL DEFAULT '0'");
    $migration->migrationOneTable($newTable);
    $migration->addKey($newTable, "uuid");
    $migration->addKey($newTable, "computers_id");
    $migration->migrationOneTable($newTable);
    $DB->list_fields($newTable, FALSE);
    /*
     * Table glpi_plugin_fusioninventory_inventorycomputerstoragetypes
     */
    $newTable = "glpi_plugin_fusioninventory_inventorycomputerstoragetypes";
    if (!TableExists($newTable)) {
        $query = "CREATE TABLE `" . $newTable . "` (\n                     `id` int(11) NOT NULL AUTO_INCREMENT,\n                      PRIMARY KEY (`id`)\n                  ) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1";
        $DB->query($query);
    }
    $migration->changeField($newTable, "id", "id", "int(11) NOT NULL AUTO_INCREMENT");
    $migration->changeField($newTable, "name", "name", "varchar(255) DEFAULT NULL");
    $migration->changeField($newTable, "level", "level", "tinyint(2) NOT NULL DEFAULT '0'");
    $migration->migrationOneTable($newTable);
    $migration->addField($newTable, "id", "int(11) NOT NULL AUTO_INCREMENT");
    $migration->addField($newTable, "name", "varchar(255) DEFAULT NULL");
    $migration->addField($newTable, "level", "tinyint(2) NOT NULL DEFAULT '0'");
    $migration->migrationOneTable($newTable);
    $migration->addKey($newTable, "level");
    $migration->migrationOneTable($newTable);
    $DB->list_fields($newTable, FALSE);
    /*
     * Table glpi_plugin_fusioninventory_inventorycomputerstorages_storages
     */
    $newTable = "glpi_plugin_fusioninventory_inventorycomputerstorages_storages";
    if (!TableExists($newTable)) {
        $query = "CREATE TABLE `" . $newTable . "` (\n                     `id` int(11) NOT NULL AUTO_INCREMENT,\n                      PRIMARY KEY (`id`)\n                  ) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1";
        $DB->query($query);
    }
    $migration->changeField($newTable, "id", "id", "int(11) NOT NULL AUTO_INCREMENT");
    $migration->changeField($newTable, "plugin_fusioninventory_inventorycomputerstorages_id_1", "plugin_fusioninventory_inventorycomputerstorages_id_1", "int(11) NOT NULL DEFAULT '0'");
    $migration->changeField($newTable, "plugin_fusioninventory_inventorycomputerstorages_id_2", "plugin_fusioninventory_inventorycomputerstorages_id_2", "int(11) NOT NULL DEFAULT '0'");
    $migration->migrationOneTable($newTable);
    $migration->addField($newTable, "id", "int(11) NOT NULL AUTO_INCREMENT");
    $migration->addField($newTable, "plugin_fusioninventory_inventorycomputerstorages_id_1", "int(11) NOT NULL DEFAULT '0'");
    $migration->addField($newTable, "plugin_fusioninventory_inventorycomputerstorages_id_2", "int(11) NOT NULL DEFAULT '0'");
    $migration->migrationOneTable($newTable);
    $migration->addKey($newTable, "plugin_fusioninventory_inventorycomputerstorages_id_1");
    $migration->addKey($newTable, "plugin_fusioninventory_inventorycomputerstorages_id_2");
    $migration->migrationOneTable($newTable);
    $DB->list_fields($newTable, FALSE);
    /*
     * glpi_plugin_fusioninventory_configlogfields
     */
    $newTable = "glpi_plugin_fusioninventory_configlogfields";
    $migration->renameTable("glpi_plugin_fusioninventory_config_snmp_history", $newTable);
    $migration->renameTable("glpi_plugin_fusinvsnmp_configlogfields", $newTable);
    if (TableExists($newTable)) {
        if (FieldExists($newTable, "field")) {
            $query = "SELECT * FROM `" . $newTable . "`";
            $result = $DB->query($query);
            while ($data = $DB->fetch_array($result)) {
                $pfMapping = new PluginFusioninventoryMapping();
                $mapping = 0;
                if ($mapping = $pfMapping->get("NetworkEquipment", $data['field'])) {
                    $queryu = "UPDATE `" . $newTable . "`\n                     SET `field`='" . $mapping['id'] . "'\n                     WHERE `field`='" . $data['field'] . "'";
                    $DB->query($queryu);
                }
            }
        }
    }
    if (!TableExists($newTable)) {
        $query = "CREATE TABLE `" . $newTable . "` (\n                     `id` int(8) NOT NULL AUTO_INCREMENT,\n                      PRIMARY KEY (`id`)\n                  ) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1";
        $DB->query($query);
    }
    $migration->changeField($newTable, "ID", "id", "int(11) NOT NULL AUTO_INCREMENT");
    $migration->changeField($newTable, "id", "id", "int(8) NOT NULL AUTO_INCREMENT");
    $migration->changeField($newTable, "plugin_fusioninventory_mappings_id", "plugin_fusioninventory_mappings_id", "int(11) NOT NULL DEFAULT '0'");
    $migration->changeField($newTable, "days", "days", "int(255) NOT NULL DEFAULT '-1'");
    $migration->migrationOneTable($newTable);
    $migration->changeField($newTable, "ID", "id", "int(8) NOT NULL AUTO_INCREMENT");
    $migration->changeField($newTable, "field", "plugin_fusioninventory_mappings_id", "int(11) NOT NULL DEFAULT '0'");
    $migration->migrationOneTable($newTable);
    $migration->addField($newTable, "id", "int(8) NOT NULL AUTO_INCREMENT");
    $migration->addField($newTable, "plugin_fusioninventory_mappings_id", "int(11) NOT NULL DEFAULT '0'");
    $migration->addField($newTable, "days", "int(255) NOT NULL DEFAULT '-1'");
    $migration->addKey($newTable, "plugin_fusioninventory_mappings_id");
    $migration->migrationOneTable($newTable);
    $DB->list_fields($newTable, FALSE);
    $configLogField = new PluginFusioninventoryConfigLogField();
    $configLogField->initConfig();
    /*
     * Table glpi_plugin_fusioninventory_networkportconnectionlogs
     */
    $newTable = "glpi_plugin_fusioninventory_networkportconnectionlogs";
    $migration->renameTable("glpi_plugin_fusinvsnmp_networkportconnectionlogs", $newTable);
    if (!TableExists($newTable)) {
        $DB->query('CREATE TABLE `' . $newTable . '` (
                        `id` int(11) NOT NULL AUTO_INCREMENT,
                        PRIMARY KEY (`id`)
                   ) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1');
    }
    $migration->changeField($newTable, "ID", "id", "int(11) NOT NULL AUTO_INCREMENT");
    $migration->changeField($newTable, "id", "id", "int(11) NOT NULL AUTO_INCREMENT");
    $migration->changeField($newTable, "date", "date_mod", "datetime NOT NULL DEFAULT '0000-00-00 00:00:00'");
    $migration->changeField($newTable, "date_mod", "date_mod", "datetime NOT NULL DEFAULT '0000-00-00 00:00:00'");
    $migration->changeField($newTable, "creation", "creation", "tinyint(1) NOT NULL DEFAULT '0'");
    $migration->changeField($newTable, "FK_port_source", "networkports_id_source", "int(11) NOT NULL DEFAULT '0'");
    $migration->changeField($newTable, "networkports_id_source", "networkports_id_source", "int(11) NOT NULL DEFAULT '0'");
    $migration->changeField($newTable, "FK_port_destination", "networkports_id_destination", "int(11) NOT NULL DEFAULT '0'");
    $migration->changeField($newTable, "networkports_id_destination", "networkports_id_destination", "int(11) NOT NULL DEFAULT '0'");
    $migration->changeField($newTable, "plugin_fusioninventory_agentprocesses_id", "plugin_fusioninventory_agentprocesses_id", "int(11) NOT NULL DEFAULT '0'");
    $migration->dropField($newTable, "process_number");
    $migration->migrationOneTable($newTable);
    $migration->addField($newTable, "id", "int(11) NOT NULL AUTO_INCREMENT");
    $migration->addField($newTable, "date_mod", "datetime NOT NULL DEFAULT '0000-00-00 00:00:00'");
    $migration->addField($newTable, "creation", "tinyint(1) NOT NULL DEFAULT '0'");
    $migration->addField($newTable, "networkports_id_source", "int(11) NOT NULL DEFAULT '0'");
    $migration->addField($newTable, "networkports_id_destination", "int(11) NOT NULL DEFAULT '0'");
    $migration->addField($newTable, "plugin_fusioninventory_agentprocesses_id", "int(11) NOT NULL DEFAULT '0'");
    $migration->addKey($newTable, array("networkports_id_source", "networkports_id_destination", "plugin_fusioninventory_agentprocesses_id"), "networkports_id_source");
    $migration->addKey($newTable, "date_mod");
    $migration->migrationOneTable($newTable);
    $DB->list_fields($newTable, FALSE);
    /*
     * Table glpi_plugin_fusioninventory_networkporttypes
     */
    $newTable = "glpi_plugin_fusioninventory_networkporttypes";
    $migration->renameTable("glpi_plugin_fusinvsnmp_networkporttypes", $newTable);
    if (!TableExists($newTable)) {
        $query = "CREATE TABLE `" . $newTable . "` (\n                     `id` int(11) NOT NULL AUTO_INCREMENT,\n                      PRIMARY KEY (`id`)\n                  ) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1";
        $DB->query($query);
    }
    $migration->changeField($newTable, "id", "id", "int(11) NOT NULL AUTO_INCREMENT");
    $migration->changeField($newTable, "name", "name", "varchar(255) DEFAULT NULL");
    $migration->changeField($newTable, "number", "number", "int(4) NOT NULL DEFAULT '0'");
    $migration->changeField($newTable, "othername", "othername", "varchar(255) DEFAULT NULL");
    $migration->changeField($newTable, "import", "import", "tinyint(1) NOT NULL DEFAULT '0'");
    $migration->migrationOneTable($newTable);
    $migration->addField($newTable, "name", "varchar(255) DEFAULT NULL");
    $migration->addField($newTable, "number", "int(4) NOT NULL DEFAULT '0'");
    $migration->addField($newTable, "othername", "varchar(255) DEFAULT NULL");
    $migration->addField($newTable, "import", "tinyint(1) NOT NULL DEFAULT '0'");
    $migration->migrationOneTable($newTable);
    $DB->list_fields($newTable, FALSE);
    /*
     * Table glpi_plugin_fusioninventory_printers
     */
    $newTable = "glpi_plugin_fusioninventory_printers";
    $migration->renameTable("glpi_plugin_fusinvsnmp_printers", $newTable);
    $migration->renameTable("glpi_plugin_tracker_printers", $newTable);
    if (!TableExists($newTable)) {
        $DB->query('CREATE TABLE `' . $newTable . '` (
                        `id` int(11) NOT NULL AUTO_INCREMENT,
                        PRIMARY KEY (`id`)
                   ) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1');
    }
    $migration->changeField($newTable, "id", "id", "int(11) NOT NULL AUTO_INCREMENT");
    $migration->changeField($newTable, "printers_id", "printers_id", "int(11) NOT NULL DEFAULT '0'");
    $migration->changeField($newTable, "sysdescr", "sysdescr", "text COLLATE utf8_unicode_ci DEFAULT NULL");
    $migration->changeField($newTable, "plugin_fusinvsnmp_configsecurities_id", "plugin_fusioninventory_configsecurities_id", "int(11) NOT NULL DEFAULT '0'");
    $migration->changeField($newTable, "plugin_fusioninventory_configsecurities_id", "plugin_fusioninventory_configsecurities_id", "int(11) NOT NULL DEFAULT '0'");
    $migration->changeField($newTable, "frequence_days", "frequence_days", "int(5) NOT NULL DEFAULT '1'");
    $migration->changeField($newTable, "last_fusioninventory_update", "last_fusioninventory_update", "datetime DEFAULT NULL");
    $migration->migrationOneTable($newTable);
    $migration->changeField($newTable, "ID", "id", "int(11) NOT NULL AUTO_INCREMENT");
    $migration->changeField($newTable, "FK_printers", "printers_id", "int(11) NOT NULL DEFAULT '0'");
    $migration->changeField($newTable, "FK_snmp_connection", "plugin_fusioninventory_configsecurities_id", "int(11) NOT NULL DEFAULT '0'");
    $migration->changeField($newTable, "last_tracker_update", "last_fusioninventory_update", "datetime DEFAULT NULL");
    $migration->dropKey($newTable, "FK_printers");
    $migration->dropKey($newTable, "FK_snmp_connection");
    $migration->dropKey($newTable, "plugin_fusioninventory_snmpmodels_id");
    $migration->migrationOneTable($newTable);
    $migration->dropField($newTable, "plugin_fusinvsnmp_models_id");
    $migration->dropField($newTable, "plugin_fusioninventory_snmpmodels_id");
    $migration->dropField($newTable, "FK_model_infos");
    $migration->addField($newTable, "id", "int(11) NOT NULL AUTO_INCREMENT");
    $migration->addField($newTable, "printers_id", "int(11) NOT NULL DEFAULT '0'");
    $migration->addField($newTable, "sysdescr", "text COLLATE utf8_unicode_ci DEFAULT NULL");
    $migration->addField($newTable, "plugin_fusioninventory_configsecurities_id", "int(11) NOT NULL DEFAULT '0'");
    $migration->addField($newTable, "frequence_days", "int(5) NOT NULL DEFAULT '1'");
    $migration->addField($newTable, "last_fusioninventory_update", "datetime DEFAULT NULL");
    $migration->addField($newTable, "serialized_inventory", "longblob");
    $migration->addKey($newTable, "plugin_fusioninventory_configsecurities_id");
    $migration->addKey($newTable, "printers_id");
    $migration->migrationOneTable($newTable);
    $DB->list_fields($newTable, FALSE);
    /*
     * Table glpi_plugin_fusioninventory_printerlogs
     */
    $newTable = "glpi_plugin_fusioninventory_printerlogs";
    $migration->renameTable("glpi_plugin_fusinvsnmp_printerlogs", $newTable);
    $migration->renameTable("glpi_plugin_tracker_printers_history", $newTable);
    if (!TableExists($newTable)) {
        $DB->query('CREATE TABLE `' . $newTable . '` (
                        `id` int(11) NOT NULL AUTO_INCREMENT,
                        PRIMARY KEY (`id`)
                   ) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1');
    }
    $migration->changeField($newTable, "id", "id", "int(11) NOT NULL AUTO_INCREMENT");
    $migration->changeField($newTable, "printers_id", "printers_id", "int(11) NOT NULL DEFAULT '0'");
    $migration->changeField($newTable, "date", "date", "datetime NOT NULL DEFAULT '0000-00-00 00:00:00'");
    $migration->changeField($newTable, "pages_total", "pages_total", "int(11) NOT NULL DEFAULT '0'");
    $migration->changeField($newTable, "pages_n_b", "pages_n_b", "int(11) NOT NULL DEFAULT '0'");
    $migration->changeField($newTable, "pages_color", "pages_color", "int(11) NOT NULL DEFAULT '0'");
    $migration->changeField($newTable, "pages_recto_verso", "pages_recto_verso", "int(11) NOT NULL DEFAULT '0'");
    $migration->changeField($newTable, "scanned", "scanned", "int(11) NOT NULL DEFAULT '0'");
    $migration->changeField($newTable, "pages_total_print", "pages_total_print", "int(11) NOT NULL DEFAULT '0'");
    $migration->changeField($newTable, "pages_n_b_print", "pages_n_b_print", "int(11) NOT NULL DEFAULT '0'");
    $migration->changeField($newTable, "pages_color_print", "pages_color_print", "int(11) NOT NULL DEFAULT '0'");
    $migration->changeField($newTable, "pages_total_copy", "pages_total_copy", "int(11) NOT NULL DEFAULT '0'");
    $migration->changeField($newTable, "pages_n_b_copy", "pages_n_b_copy", "int(11) NOT NULL DEFAULT '0'");
    $migration->changeField($newTable, "pages_color_copy", "pages_color_copy", "int(11) NOT NULL DEFAULT '0'");
    $migration->changeField($newTable, "pages_total_fax", "pages_total_fax", "int(11) NOT NULL DEFAULT '0'");
    $migration->migrationOneTable($newTable);
    $migration->changeField($newTable, "ID", "id", "int(11) NOT NULL AUTO_INCREMENT");
    $migration->changeField($newTable, "FK_printers", "printers_id", "int(11) NOT NULL DEFAULT '0'");
    $migration->migrationOneTable($newTable);
    $migration->addField($newTable, "id", "int(11) NOT NULL AUTO_INCREMENT");
    $migration->addField($newTable, "printers_id", "int(11) NOT NULL DEFAULT '0'");
    $migration->addField($newTable, "date", "datetime NOT NULL DEFAULT '0000-00-00 00:00:00'");
    $migration->addField($newTable, "pages_total", "int(11) NOT NULL DEFAULT '0'");
    $migration->addField($newTable, "pages_n_b", "int(11) NOT NULL DEFAULT '0'");
    $migration->addField($newTable, "pages_color", "int(11) NOT NULL DEFAULT '0'");
    $migration->addField($newTable, "pages_recto_verso", "int(11) NOT NULL DEFAULT '0'");
    $migration->addField($newTable, "scanned", "int(11) NOT NULL DEFAULT '0'");
    $migration->addField($newTable, "pages_total_print", "int(11) NOT NULL DEFAULT '0'");
    $migration->addField($newTable, "pages_n_b_print", "int(11) NOT NULL DEFAULT '0'");
    $migration->addField($newTable, "pages_color_print", "int(11) NOT NULL DEFAULT '0'");
    $migration->addField($newTable, "pages_total_copy", "int(11) NOT NULL DEFAULT '0'");
    $migration->addField($newTable, "pages_n_b_copy", "int(11) NOT NULL DEFAULT '0'");
    $migration->addField($newTable, "pages_color_copy", "int(11) NOT NULL DEFAULT '0'");
    $migration->addField($newTable, "pages_total_fax", "int(11) NOT NULL DEFAULT '0'");
    $migration->addKey($newTable, array("printers_id", "date"), "printers_id");
    $migration->migrationOneTable($newTable);
    $DB->list_fields($newTable, FALSE);
    /*
     *  glpi_plugin_fusioninventory_printercartridges
     */
    $newTable = "glpi_plugin_fusioninventory_printercartridges";
    $migration->renameTable("glpi_plugin_fusinvsnmp_printercartridges", $newTable);
    $migration->renameTable("glpi_plugin_tracker_printers_cartridges", $newTable);
    if (!TableExists($newTable)) {
        $DB->query('CREATE TABLE `' . $newTable . '` (
                        `id` bigint(100) NOT NULL AUTO_INCREMENT,
                        PRIMARY KEY (`id`)
                   ) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1');
    }
    $migration->changeField($newTable, "id", "id", "bigint(100) NOT NULL AUTO_INCREMENT");
    $migration->changeField($newTable, "printers_id", "printers_id", "int(11) NOT NULL DEFAULT '0'");
    $migration->changeField($newTable, "plugin_fusioninventory_mappings_id", "plugin_fusioninventory_mappings_id", "int(11) NOT NULL DEFAULT '0'");
    $migration->changeField($newTable, "cartridges_id", "cartridges_id", "int(11) NOT NULL DEFAULT '0'");
    $migration->changeField($newTable, "state", "state", "int(3) NOT NULL DEFAULT '100'");
    $migration->migrationOneTable($newTable);
    $migration->changeField($newTable, "ID", "id", "bigint(100) NOT NULL AUTO_INCREMENT");
    $migration->changeField($newTable, "FK_printers", "printers_id", "int(11) NOT NULL DEFAULT '0'");
    $migration->changeField($newTable, "FK_cartridges", "cartridges_id", "int(11) NOT NULL DEFAULT '0'");
    $migration->addField($newTable, "plugin_fusioninventory_mappings_id", "int(11) NOT NULL DEFAULT '0'");
    $migration->migrationOneTable($newTable);
    // Update with mapping
    if (FieldExists($newTable, "object_name")) {
        $query = "SELECT * FROM `" . $newTable . "`\n               GROUP BY `object_name`";
        $result = $DB->query($query);
        while ($data = $DB->fetch_array($result)) {
            $pfMapping = new PluginFusioninventoryMapping();
            $mapping = 0;
            if ($mapping = $pfMapping->get("Printer", $data['object_name'])) {
                $DB->query("UPDATE `" . $newTable . "`\n                     SET `plugin_fusioninventory_mappings_id`='" . $mapping['id'] . "'\n                        WHERE `object_name`='" . $data['object_name'] . "'");
            }
        }
    }
    $migration->dropField($newTable, "object_name");
    $migration->migrationOneTable($newTable);
    $migration->addField($newTable, "id", "bigint(100) NOT NULL AUTO_INCREMENT");
    $migration->addField($newTable, "printers_id", "int(11) NOT NULL DEFAULT '0'");
    $migration->addField($newTable, "plugin_fusioninventory_mappings_id", "int(11) NOT NULL DEFAULT '0'");
    $migration->addField($newTable, "cartridges_id", "int(11) NOT NULL DEFAULT '0'");
    $migration->addField($newTable, "state", "int(3) NOT NULL DEFAULT '100'");
    $migration->addKey($newTable, "printers_id");
    $migration->addKey($newTable, "plugin_fusioninventory_mappings_id");
    $migration->addKey($newTable, "cartridges_id");
    $migration->migrationOneTable($newTable);
    $DB->list_fields($newTable, FALSE);
    /*
     * glpi_plugin_fusioninventory_networkports
     */
    $newTable = "glpi_plugin_fusioninventory_networkports";
    $migration->renameTable("glpi_plugin_fusinvsnmp_networkports", $newTable);
    $migration->renameTable("glpi_plugin_tracker_networking_ports", $newTable);
    if (!TableExists($newTable)) {
        $DB->query('CREATE TABLE `' . $newTable . '` (
                        `id` int(11) NOT NULL AUTO_INCREMENT,
                        PRIMARY KEY (`id`)
                   ) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1');
    }
    $migration->changeField($newTable, "id", "id", "int(11) NOT NULL AUTO_INCREMENT");
    $migration->changeField($newTable, "networkports_id", "networkports_id", "int(11) NOT NULL DEFAULT '0'");
    $migration->changeField($newTable, "ifmtu", "ifmtu", "int(8) NOT NULL DEFAULT '0'");
    $migration->changeField($newTable, "ifspeed", "ifspeed", "bigint(50) NOT NULL DEFAULT '0'");
    $migration->changeField($newTable, "ifinternalstatus", "ifinternalstatus", "varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL");
    $migration->changeField($newTable, "ifconnectionstatus", "ifconnectionstatus", "int(8) NOT NULL DEFAULT '0'");
    $migration->changeField($newTable, "iflastchange", "iflastchange", "varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL");
    $migration->changeField($newTable, "ifinoctets", "ifinoctets", "bigint(50) NOT NULL DEFAULT '0'");
    $migration->changeField($newTable, "ifinerrors", "ifinerrors", "bigint(50) NOT NULL DEFAULT '0'");
    $migration->changeField($newTable, "ifoutoctets", "ifoutoctets", "bigint(50) NOT NULL DEFAULT '0'");
    $migration->changeField($newTable, "ifouterrors", "ifouterrors", "bigint(50) NOT NULL DEFAULT '0'");
    $migration->changeField($newTable, "ifstatus", "ifstatus", "varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL");
    $migration->changeField($newTable, "mac", "mac", "varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL");
    $migration->changeField($newTable, "ifdescr", "ifdescr", "varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL");
    $migration->changeField($newTable, "portduplex", "portduplex", "varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL");
    $migration->changeField($newTable, "trunk", "trunk", "tinyint(1) NOT NULL DEFAULT '0'");
    $migration->changeField($newTable, "lastup", "lastup", "datetime NOT NULL DEFAULT '0000-00-00 00:00:00'");
    $migration->migrationOneTable($newTable);
    $migration->changeField($newTable, "ID", "id", "int(11) NOT NULL AUTO_INCREMENT");
    $migration->changeField($newTable, "FK_networking_ports", "networkports_id", "int(11) NOT NULL DEFAULT '0'");
    $migration->changeField($newTable, "ifmac", "mac", "varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL");
    $migration->dropKey($newTable, "FK_networking_ports");
    $migration->migrationOneTable($newTable);
    $migration->addField($newTable, "id", "int(11) NOT NULL AUTO_INCREMENT");
    $migration->addField($newTable, "networkports_id", "int(11) NOT NULL DEFAULT '0'");
    $migration->addField($newTable, "ifmtu", "int(8) NOT NULL DEFAULT '0'");
    $migration->addField($newTable, "ifspeed", "bigint(50) NOT NULL DEFAULT '0'");
    $migration->addField($newTable, "ifinternalstatus", "varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL");
    $migration->addField($newTable, "ifconnectionstatus", "int(8) NOT NULL DEFAULT '0'");
    $migration->addField($newTable, "iflastchange", "varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL");
    $migration->addField($newTable, "ifinoctets", "bigint(50) NOT NULL DEFAULT '0'");
    $migration->addField($newTable, "ifinerrors", "bigint(50) NOT NULL DEFAULT '0'");
    $migration->addField($newTable, "ifoutoctets", "bigint(50) NOT NULL DEFAULT '0'");
    $migration->addField($newTable, "ifouterrors", "bigint(50) NOT NULL DEFAULT '0'");
    $migration->addField($newTable, "ifstatus", "varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL");
    $migration->addField($newTable, "mac", "varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL");
    $migration->addField($newTable, "ifdescr", "varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL");
    $migration->addField($newTable, "ifalias", "varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL");
    $migration->addField($newTable, "portduplex", "varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL");
    $migration->addField($newTable, "trunk", "tinyint(1) NOT NULL DEFAULT '0'");
    $migration->addField($newTable, "lastup", "datetime NOT NULL DEFAULT '0000-00-00 00:00:00'");
    $migration->addKey($newTable, "networkports_id");
    $migration->migrationOneTable($newTable);
    $DB->list_fields($newTable, FALSE);
    /*
     * Table glpi_plugin_fusioninventory_networkequipments
     */
    $newTable = "glpi_plugin_fusioninventory_networkequipments";
    $migration->renameTable("glpi_plugin_fusinvsnmp_networkequipments", $newTable);
    $migration->renameTable("glpi_plugin_tracker_networking", $newTable);
    if (!TableExists($newTable)) {
        $DB->query('CREATE TABLE `' . $newTable . '` (
                        `id` int(11) NOT NULL AUTO_INCREMENT,
                        PRIMARY KEY (`id`)
                   ) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1');
    }
    $migration->changeField($newTable, "id", "id", "int(11) NOT NULL AUTO_INCREMENT");
    $migration->changeField($newTable, "networkequipments_id", "networkequipments_id", "int(11) NOT NULL DEFAULT '0'");
    $migration->changeField($newTable, "sysdescr", "sysdescr", "text COLLATE utf8_unicode_ci DEFAULT NULL");
    $migration->changeField($newTable, "plugin_fusioninventory_configsecurities_id", "plugin_fusioninventory_configsecurities_id", "int(11) NOT NULL DEFAULT '0'");
    $migration->changeField($newTable, "uptime", "uptime", "varchar(255) COLLATE utf8_unicode_ci NOT NULL DEFAULT '0'");
    $migration->changeField($newTable, "cpu", "cpu", "int(3) NOT NULL DEFAULT '0' COMMENT '%'");
    $migration->changeField($newTable, "memory", "memory", "int(11) NOT NULL DEFAULT '0'");
    $migration->changeField($newTable, "last_fusioninventory_update", "last_fusioninventory_update", "datetime DEFAULT NULL");
    $migration->changeField($newTable, "last_PID_update", "last_PID_update", "int(11) NOT NULL DEFAULT '0'");
    $migration->migrationOneTable($newTable);
    $migration->changeField($newTable, "ID", "id", "int(11) NOT NULL AUTO_INCREMENT");
    $migration->changeField($newTable, "FK_networking", "networkequipments_id", "int(11) NOT NULL DEFAULT '0'");
    $migration->changeField($newTable, "FK_snmp_connection", "plugin_fusioninventory_configsecurities_id", "int(11) NOT NULL DEFAULT '0'");
    $migration->changeField($newTable, "last_tracker_update", "last_fusioninventory_update", "datetime DEFAULT NULL");
    $migration->changeField($newTable, "plugin_fusinvsnmp_configsecurities_id", "plugin_fusioninventory_configsecurities_id", "int(11) NOT NULL DEFAULT '0'");
    $migration->dropKey($newTable, "FK_networking");
    $migration->dropKey($newTable, "FK_model_infos");
    $migration->dropKey($newTable, "plugin_fusioninventory_snmpmodels_id");
    $migration->migrationOneTable($newTable);
    $migration->dropField($newTable, "plugin_fusioninventory_snmpmodels_id");
    $migration->dropField($newTable, "plugin_fusinvsnmp_models_id");
    $migration->dropField($newTable, "FK_model_infos");
    $migration->addField($newTable, "id", "int(11) NOT NULL AUTO_INCREMENT");
    $migration->addField($newTable, "networkequipments_id", "int(11) NOT NULL DEFAULT '0'");
    $migration->addField($newTable, "sysdescr", "text COLLATE utf8_unicode_ci DEFAULT NULL");
    $migration->addField($newTable, "plugin_fusioninventory_configsecurities_id", "int(11) NOT NULL DEFAULT '0'");
    $migration->addField($newTable, "uptime", "varchar(255) COLLATE utf8_unicode_ci NOT NULL DEFAULT '0'");
    $migration->addField($newTable, "cpu", "int(3) NOT NULL DEFAULT '0' COMMENT '%'");
    $migration->addField($newTable, "memory", "int(11) NOT NULL DEFAULT '0'");
    $migration->addField($newTable, "last_fusioninventory_update", "datetime DEFAULT NULL");
    $migration->addField($newTable, "last_PID_update", "int(11) NOT NULL DEFAULT '0'");
    $migration->addField($newTable, "serialized_inventory", "longblob");
    $migration->addKey($newTable, "networkequipments_id");
    $migration->migrationOneTable($newTable);
    $DB->list_fields($newTable, FALSE);
    /*
     * glpi_plugin_fusioninventory_networkequipmentips
     * Removed in 0.84, but required here for update, we drop in edn of this function
     */
    if (TableExists("glpi_plugin_fusioninventory_networkequipmentips") || TableExists("glpi_plugin_fusinvsnmp_networkequipmentips") || TableExists("glpi_plugin_tracker_networking_ifaddr")) {
        $newTable = "glpi_plugin_fusioninventory_networkequipmentips";
        $migration->renameTable("glpi_plugin_fusinvsnmp_networkequipmentips", $newTable);
        $migration->renameTable("glpi_plugin_tracker_networking_ifaddr", $newTable);
        if (!TableExists($newTable)) {
            $DB->query('CREATE TABLE `' . $newTable . '` (
                        `id` int(11) NOT NULL AUTO_INCREMENT,
                        PRIMARY KEY (`id`)
                   ) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1');
        }
        $migration->changeField($newTable, "id", "id", "int(11) NOT NULL AUTO_INCREMENT");
        $migration->changeField($newTable, "networkequipments_id", "networkequipments_id", "int(11) NOT NULL DEFAULT '0'");
        $migration->changeField($newTable, "ip", "ip", "varchar(255) DEFAULT NULL");
        $migration->migrationOneTable($newTable);
        $migration->changeField($newTable, "ID", "id", "int(11) NOT NULL AUTO_INCREMENT");
        $migration->changeField($newTable, "FK_networking", "networkequipments_id", "int(11) NOT NULL DEFAULT '0'");
        $migration->changeField($newTable, "ifaddr", "ip", "varchar(255) DEFAULT NULL");
        $migration->dropKey($newTable, "ifaddr");
        $migration->migrationOneTable($newTable);
        $migration->addField($newTable, "id", "int(11) NOT NULL AUTO_INCREMENT");
        $migration->addField($newTable, "networkequipments_id", "int(11) NOT NULL DEFAULT '0'");
        $migration->addField($newTable, "ip", "varchar(255) DEFAULT NULL");
        $migration->addKey($newTable, "ip");
        $migration->addKey($newTable, "networkequipments_id");
        $migration->migrationOneTable($newTable);
        $DB->list_fields($newTable, FALSE);
    }
    /*
     * Table glpi_plugin_fusioninventory_networkportlogs
     */
    $newTable = "glpi_plugin_fusioninventory_networkportlogs";
    if (TableExists("glpi_plugin_tracker_snmp_history")) {
        // **** Update history
        update213to220_ConvertField($migration);
        // **** Migration network history connections
        $query = "SELECT count(ID) FROM `glpi_plugin_tracker_snmp_history`\n                              WHERE `Field`='0'";
        $result = $DB->query($query);
        $datas = $DB->fetch_assoc($result);
        $nb = $datas['count(ID)'];
        //echo "Move Connections history to another table...";
        for ($i = 0; $i < $nb; $i = $i + 500) {
            $migration->displayMessage("{$i} / {$nb}");
            $sql_connection = "SELECT * FROM `glpi_plugin_tracker_snmp_history`\n                                 WHERE `Field`='0'\n                                 ORDER BY `FK_process` DESC, `date_mod` DESC\n                                 LIMIT 500";
            $result_connection = $DB->query($sql_connection);
            while ($thread_connection = $DB->fetch_array($result_connection)) {
                $input = array();
                $input['process_number'] = $thread_connection['FK_process'];
                $input['date'] = $thread_connection['date_mod'];
                if ($thread_connection["old_device_ID"] != "0" or $thread_connection["new_device_ID"] != "0") {
                    if ($thread_connection["old_device_ID"] != "0") {
                        // disconnection
                        $input['creation'] = '0';
                    } else {
                        if ($thread_connection["new_device_ID"] != "0") {
                            // connection
                            $input['creation'] = '1';
                        }
                    }
                    $input['FK_port_source'] = $thread_connection["FK_ports"];
                    $dataPort = array();
                    if ($thread_connection["old_device_ID"] != "0") {
                        $queryPort = "SELECT *\n                                      FROM `glpi_networkports`\n                                      WHERE `mac`='" . $thread_connection['old_value'] . "'\n                                      LIMIT 1";
                        $resultPort = $DB->query($queryPort);
                        $dataPort = $DB->fetch_assoc($resultPort);
                    } else {
                        if ($thread_connection["new_device_ID"] != "0") {
                            $queryPort = "SELECT *\n                                      FROM `glpi_networkports`\n                                      WHERE `mac`='" . $thread_connection['new_value'] . "'\n                                      LIMIT 1";
                            $resultPort = $DB->query($queryPort);
                            $dataPort = $DB->fetch_assoc($resultPort);
                        }
                    }
                    if (isset($dataPort['id'])) {
                        $input['FK_port_destination'] = $dataPort['id'];
                    } else {
                        $input['FK_port_destination'] = 0;
                    }
                    $query_ins = "INSERT INTO `glpi_plugin_fusinvsnmp_networkportconnectionlogs`\n                        (`date_mod`, `creation`, `networkports_id_source`,\n                         `networkports_id_destination`)\n                        VALUES ('" . $input['date'] . "',\n                                '" . $input['creation'] . "',\n                                '" . $input['FK_port_source'] . "',\n                                '" . $input['FK_port_destination'] . "')";
                    $DB->query($query_ins);
                }
            }
        }
        $query_del = "DELETE FROM `glpi_plugin_tracker_snmp_history`\n               WHERE `Field`='0'\n               AND (`old_device_ID`!='0' OR `new_device_ID`!='0')";
        $DB->query($query_del);
        $migration->displayMessage("{$nb} / {$nb}");
    }
    $migration->renameTable("glpi_plugin_fusinvsnmp_networkportlogs", $newTable);
    $migration->renameTable("glpi_plugin_tracker_snmp_history", $newTable);
    if (!TableExists($newTable)) {
        $query = "CREATE TABLE `" . $newTable . "` (\n                     `id` int(11) NOT NULL AUTO_INCREMENT,\n                      PRIMARY KEY (`id`)\n                  ) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1";
        $DB->query($query);
    }
    $migration->changeField($newTable, "id", "id", "int(11) NOT NULL AUTO_INCREMENT");
    $migration->changeField($newTable, "networkports_id", "networkports_id", "int(11) NOT NULL DEFAULT '0'");
    $migration->changeField($newTable, "plugin_fusioninventory_mappings_id", "plugin_fusioninventory_mappings_id", "int(11) NOT NULL DEFAULT '0'");
    $migration->changeField($newTable, "date_mod", "date_mod", "datetime DEFAULT NULL");
    $migration->changeField($newTable, "value_old", "value_old", "varchar(255) DEFAULT NULL");
    $migration->changeField($newTable, "value_new", "value_new", "varchar(255) DEFAULT NULL");
    $migration->changeField($newTable, "plugin_fusioninventory_agentprocesses_id", "plugin_fusioninventory_agentprocesses_id", "int(11) NOT NULL DEFAULT '0'");
    $migration->migrationOneTable($newTable);
    $migration->changeField($newTable, "ID", "id", "int(11) NOT NULL AUTO_INCREMENT");
    $migration->changeField($newTable, "FK_ports", "networkports_id", "int(11) NOT NULL DEFAULT '0'");
    $migration->addField($newTable, "plugin_fusioninventory_mappings_id", "int(11) NOT NULL DEFAULT '0'");
    $migration->migrationOneTable($newTable);
    // Update with mapping
    if (FieldExists($newTable, "Field")) {
        //            $pfNetworkPortLog = new PluginFusioninventoryNetworkPortLog();
        $pfMapping = new PluginFusioninventoryMapping();
        $query = "SELECT * FROM `" . $newTable . "`\n               GROUP BY `Field`";
        $result = $DB->query($query);
        while ($data = $DB->fetch_array($result)) {
            $mapping = 0;
            if ($mapping = $pfMapping->get("NetworkEquipment", $data['Field'])) {
                $DB->query("UPDATE `" . $newTable . "`\n                     SET `plugin_fusioninventory_mappings_id`='" . $mapping['id'] . "'\n                     WHERE `Field`='" . $data['Field'] . "'\n                        AND `plugin_fusioninventory_mappings_id`!='" . $mapping['id'] . "'");
            }
        }
    }
    $migration->dropField($newTable, "Field");
    $migration->changeField($newTable, "old_value", "value_old", "varchar(255) DEFAULT NULL");
    $migration->dropField($newTable, "old_device_type");
    $migration->dropField($newTable, "old_device_ID");
    $migration->changeField($newTable, "new_value", "value_new", "varchar(255) DEFAULT NULL");
    $migration->dropField($newTable, "new_device_type");
    $migration->dropField($newTable, "new_device_ID");
    $migration->dropField($newTable, "FK_process");
    $migration->dropKey($newTable, "FK_process");
    $migration->dropKey($newTable, "FK_ports");
    $migration->migrationOneTable($newTable);
    $migration->addField($newTable, "id", "int(11) NOT NULL AUTO_INCREMENT");
    $migration->addField($newTable, "networkports_id", "int(11) NOT NULL DEFAULT '0'");
    $migration->addField($newTable, "plugin_fusioninventory_mappings_id", "int(11) NOT NULL DEFAULT '0'");
    $migration->addField($newTable, "date_mod", "datetime DEFAULT NULL");
    $migration->addField($newTable, "value_old", "varchar(255) DEFAULT NULL");
    $migration->addField($newTable, "value_new", "varchar(255) DEFAULT NULL");
    $migration->addField($newTable, "plugin_fusioninventory_agentprocesses_id", "int(11) NOT NULL DEFAULT '0'");
    $migration->addKey($newTable, array("networkports_id", "date_mod"), "networkports_id");
    $migration->addKey($newTable, "plugin_fusioninventory_mappings_id");
    $migration->addKey($newTable, "plugin_fusioninventory_agentprocesses_id");
    $migration->addKey($newTable, "date_mod");
    $migration->migrationOneTable($newTable);
    $DB->list_fields($newTable, FALSE);
    /*
     * Table glpi_plugin_fusioninventory_configsecurities
     */
    // TODO get info to create SNMP authentification with old values of Tracker plugin
    $newTable = "glpi_plugin_fusioninventory_configsecurities";
    $migration->renameTable("glpi_plugin_fusinvsnmp_configsecurities", $newTable);
    $migration->renameTable("glpi_plugin_tracker_snmp_connection", $newTable);
    if (!TableExists($newTable)) {
        $DB->query('CREATE TABLE `' . $newTable . '` (
                        `id` int(11) NOT NULL AUTO_INCREMENT,
                        PRIMARY KEY (`id`)
                   ) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1');
    }
    $migration->changeField($newTable, "id", "id", "int(11) NOT NULL AUTO_INCREMENT");
    $migration->changeField($newTable, "name", "name", "varchar(64) COLLATE utf8_unicode_ci DEFAULT NULL");
    $migration->changeField($newTable, "snmpversion", "snmpversion", "varchar(8) COLLATE utf8_unicode_ci NOT NULL DEFAULT '1'");
    $migration->changeField($newTable, "community", "community", "varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL");
    $migration->changeField($newTable, "username", "username", "varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL");
    $migration->changeField($newTable, "authentication", "authentication", "varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL");
    $migration->changeField($newTable, "auth_passphrase", "auth_passphrase", "varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL");
    $migration->changeField($newTable, "encryption", "encryption", "varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL");
    $migration->changeField($newTable, "priv_passphrase", "priv_passphrase", "varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL");
    $migration->changeField($newTable, "is_deleted", "is_deleted", "tinyint(1) NOT NULL DEFAULT '0'");
    $migration->migrationOneTable($newTable);
    $migration->changeField($newTable, "ID", "id", "int(11) NOT NULL AUTO_INCREMENT");
    $migration->changeField($newTable, "FK_snmp_version", "snmpversion", "varchar(8) COLLATE utf8_unicode_ci NOT NULL DEFAULT '1'");
    $migration->changeField($newTable, "sec_name", "username", "varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL");
    $migration->dropField($newTable, "sec_level");
    $migration->dropField($newTable, "auth_protocol");
    $migration->dropField($newTable, "priv_protocol");
    $migration->dropField($newTable, "deleted");
    $migration->migrationOneTable($newTable);
    $migration->addField($newTable, "id", "int(11) NOT NULL AUTO_INCREMENT");
    $migration->addField($newTable, "name", "varchar(64) COLLATE utf8_unicode_ci DEFAULT NULL");
    $migration->addField($newTable, "snmpversion", "varchar(8) COLLATE utf8_unicode_ci NOT NULL DEFAULT '1'");
    $migration->addField($newTable, "community", "varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL");
    $migration->addField($newTable, "username", "varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL");
    $migration->addField($newTable, "authentication", "varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL");
    $migration->addField($newTable, "auth_passphrase", "varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL");
    $migration->addField($newTable, "encryption", "varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL");
    $migration->addField($newTable, "priv_passphrase", "varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL");
    $migration->addField($newTable, "is_deleted", "tinyint(1) NOT NULL DEFAULT '0'");
    $migration->addKey($newTable, "snmpversion");
    $migration->addKey($newTable, "is_deleted");
    $migration->migrationOneTable($newTable);
    $DB->list_fields($newTable, FALSE);
    /*
     *  glpi_plugin_fusioninventory_statediscoveries
     */
    $newTable = "glpi_plugin_fusioninventory_statediscoveries";
    $migration->renameTable("glpi_plugin_fusinvsnmp_statediscoveries", $newTable);
    if (!TableExists($newTable)) {
        $DB->query("CREATE TABLE `" . $newTable . "` (\n                        `id` int(11) NOT NULL AUTO_INCREMENT,\n                        PRIMARY KEY (`id`)\n                   ) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1");
    }
    $migration->changeField($newTable, "id", "id", "int(11) NOT NULL AUTO_INCREMENT");
    $migration->changeField($newTable, "plugin_fusioninventory_taskjob_id", "plugin_fusioninventory_taskjob_id", "int(11) NOT NULL DEFAULT '0'");
    $migration->changeField($newTable, "plugin_fusioninventory_agents_id", "plugin_fusioninventory_agents_id", "int(11) NOT NULL DEFAULT '0'");
    $migration->changeField($newTable, "start_time", "start_time", "datetime NOT NULL DEFAULT '0000-00-00 00:00:00'");
    $migration->changeField($newTable, "end_time", "end_time", "datetime NOT NULL DEFAULT '0000-00-00 00:00:00'");
    $migration->changeField($newTable, "date_mod", "date_mod", "datetime DEFAULT NULL");
    $migration->changeField($newTable, "threads", "threads", "int(11) NOT NULL DEFAULT '0'");
    $migration->changeField($newTable, "nb_ip", "nb_ip", "int(11) NOT NULL DEFAULT '0'");
    $migration->changeField($newTable, "nb_found", "nb_found", "int(11) NOT NULL DEFAULT '0'");
    $migration->changeField($newTable, "nb_error", "nb_error", "int(11) NOT NULL DEFAULT '0'");
    $migration->changeField($newTable, "nb_exists", "nb_exists", "int(11) NOT NULL DEFAULT '0'");
    $migration->changeField($newTable, "nb_import", "nb_import", "int(11) NOT NULL DEFAULT '0'");
    $migration->migrationOneTable($newTable);
    $migration->addField($newTable, "id", "int(11) NOT NULL AUTO_INCREMENT");
    $migration->addField($newTable, "plugin_fusioninventory_taskjob_id", "int(11) NOT NULL DEFAULT '0'");
    $migration->addField($newTable, "plugin_fusioninventory_agents_id", "int(11) NOT NULL DEFAULT '0'");
    $migration->addField($newTable, "start_time", "datetime NOT NULL DEFAULT '0000-00-00 00:00:00'");
    $migration->addField($newTable, "end_time", "datetime NOT NULL DEFAULT '0000-00-00 00:00:00'");
    $migration->addField($newTable, "date_mod", "datetime DEFAULT NULL");
    $migration->addField($newTable, "threads", "int(11) NOT NULL DEFAULT '0'");
    $migration->addField($newTable, "nb_ip", "int(11) NOT NULL DEFAULT '0'");
    $migration->addField($newTable, "nb_found", "int(11) NOT NULL DEFAULT '0'");
    $migration->addField($newTable, "nb_error", "int(11) NOT NULL DEFAULT '0'");
    $migration->addField($newTable, "nb_exists", "int(11) NOT NULL DEFAULT '0'");
    $migration->addField($newTable, "nb_import", "int(11) NOT NULL DEFAULT '0'");
    $migration->migrationOneTable($newTable);
    $DB->list_fields($newTable, FALSE);
    /*
     * Table glpi_plugin_fusioninventory_computerlicenseinfos
     */
    if (TableExists("glpi_plugin_fusinvinventory_licenseinfos")) {
        $DB->query("UPDATE `glpi_plugin_fusinvinventory_licenseinfos`" . " SET `softwarelicenses_id`='0'" . " WHERE `softwarelicenses_id` IS NULL");
    }
    $a_table = array();
    $a_table['name'] = 'glpi_plugin_fusioninventory_computerlicenseinfos';
    $a_table['oldname'] = array('glpi_plugin_fusinvinventory_licenseinfos');
    $a_table['fields'] = array();
    $a_table['fields']['id'] = array('type' => 'autoincrement', 'value' => '');
    $a_table['fields']['computers_id'] = array('type' => 'integer', 'value' => NULL);
    $a_table['fields']['softwarelicenses_id'] = array('type' => 'integer', 'value' => NULL);
    $a_table['fields']['name'] = array('type' => 'string', 'value' => NULL);
    $a_table['fields']['fullname'] = array('type' => 'string', 'value' => NULL);
    $a_table['fields']['serial'] = array('type' => 'string', 'value' => NULL);
    $a_table['fields']['is_trial'] = array('type' => 'bool', 'value' => NULL);
    $a_table['fields']['is_update'] = array('type' => 'bool', 'value' => NULL);
    $a_table['fields']['is_oem'] = array('type' => 'bool', 'value' => NULL);
    $a_table['fields']['activation_date'] = array('type' => 'datetime', 'value' => NULL);
    $a_table['oldfields'] = array();
    $a_table['renamefields'] = array();
    $a_table['keys'] = array();
    $a_table['keys'][] = array('field' => 'name', 'name' => '', 'type' => 'INDEX');
    $a_table['keys'][] = array('field' => 'fullname', 'name' => '', 'type' => 'INDEX');
    $a_table['oldkeys'] = array();
    migrateTablesFusionInventory($migration, $a_table);
    /*
     * Table glpi_plugin_fusioninventory_computerarchs
     */
    $a_table = array();
    $a_table['name'] = 'glpi_plugin_fusioninventory_computerarchs';
    $a_table['oldname'] = array();
    $a_table['fields'] = array();
    $a_table['fields']['id'] = array('type' => 'autoincrement', 'value' => '');
    $a_table['fields']['name'] = array('type' => 'string', 'value' => NULL);
    $a_table['fields']['comment'] = array('type' => 'text', 'value' => NULL);
    $a_table['oldfields'] = array();
    $a_table['renamefields'] = array();
    $a_table['keys'] = array();
    $a_table['keys'][] = array('field' => 'name', 'name' => '', 'type' => 'INDEX');
    $a_table['oldkeys'] = array();
    migrateTablesFusionInventory($migration, $a_table);
    /*
     * Deploy Update Begin
     */
    /*
     * glpi_plugin_fusioninventory_deployfiles
     */
    $a_table = array();
    $a_table['name'] = 'glpi_plugin_fusioninventory_deployfiles';
    $a_table['oldname'] = array();
    $a_table['fields'] = array('id' => array('type' => 'autoincrement', 'value' => NULL), 'name' => array('type' => 'varchar(255) NOT NULL', 'value' => NULL), 'mimetype' => array('type' => 'varchar(255) NOT NULL', 'value' => NULL), 'filesize' => array('type' => 'bigint(20) NOT NULL', 'value' => NULL), 'comment' => array('type' => 'text DEFAULT NULL', 'value' => NULL), 'sha512' => array('type' => 'char(128) NOT NULL', 'value' => NULL), 'shortsha512' => array('type' => 'char(6) NOT NULL', 'value' => NULL), 'entities_id' => array('type' => 'int(11) NOT NULL', 'value' => NULL), 'is_recursive' => array('type' => 'tinyint(1) NOT NULL DEFAULT 0', 'value' => 0), 'date_mod' => array('type' => 'datetime DEFAULT NULL', 'value' => NULL));
    $a_table['oldfields'] = array();
    $a_table['renamefields'] = array();
    $a_table['keys'] = array(array('field' => 'id', 'name' => '', 'type' => 'KEY'), array('field' => 'shortsha512', 'name' => '', 'type' => 'KEY'), array('field' => 'entities_id', 'name' => '', 'type' => 'KEY'), array('field' => 'date_mod', 'name' => '', 'type' => 'KEY'));
    $a_table['oldkeys'] = array();
    migrateTablesFusionInventory($migration, $a_table);
    /*
     * glpi_plugin_fusioninventory_deployorders
     */
    $a_table = array();
    //table name
    $a_table['name'] = 'glpi_plugin_fusioninventory_deployorders';
    $a_table['oldname'] = array('glpi_plugin_fusinvdeploy_orders');
    $a_table['fields'] = array('id' => array('type' => 'autoincrement', 'value' => NULL), 'type' => array('type' => 'int(11) NOT NULL', 'value' => NULL), 'create_date' => array('type' => ' datetime NOT NULL', 'value' => NULL), 'plugin_fusioninventory_deploypackages_id' => array('type' => 'int(11) NOT NULL', 'value' => NULL), 'json' => array('type' => 'longtext DEFAULT NULL', 'value' => NULL));
    $a_table['oldfields'] = array();
    $a_table['renamefields'] = array('plugin_fusinvdeploy_packages_id' => 'plugin_fusioninventory_deploypackages_id');
    $a_table['keys'] = array(array('field' => 'type', 'name' => '', 'type' => 'KEY'), array('field' => 'create_date', 'name' => '', 'type' => 'KEY'), array('field' => 'plugin_fusioninventory_deploypackages_id', 'name' => '', 'type' => 'KEY'));
    $a_table['oldkeys'] = array('plugin_fusinvdeploy_packages_id');
    migrateTablesFusionInventory($migration, $a_table);
    /*
     * glpi_plugin_fusioninventory_deploypackages
     */
    $a_table = array();
    //table name
    $a_table['name'] = 'glpi_plugin_fusioninventory_deploypackages';
    $a_table['oldname'] = array('glpi_plugin_fusinvdeploy_packages');
    $a_table['fields'] = array('id' => array('type' => 'autoincrement', 'value' => NULL), 'name' => array('type' => 'varchar(255) COLLATE utf8_unicode_ci NOT NULL', 'value' => NULL), 'comment' => array('type' => "text", 'value' => NULL), 'entities_id' => array('type' => 'int(11) NOT NULL', 'value' => NULL), 'is_recursive' => array('type' => 'tinyint(1) NOT NULL DEFAULT 0', 'value' => NULL), 'date_mod' => array('type' => 'datetime DEFAULT NULL', 'value' => NULL), 'uuid' => array('type' => 'string', 'value' => NULL));
    $a_table['oldfields'] = array();
    $a_table['renamefields'] = array();
    $a_table['keys'] = array(array('field' => 'entities_id', 'name' => '', 'type' => 'KEY'), array('field' => 'date_mod', 'name' => '', 'type' => 'KEY'));
    $a_table['oldkeys'] = array();
    migrateTablesFusionInventory($migration, $a_table);
    /*
     * glpi_plugin_fusioninventory_deploymirrors
     */
    $a_table = array();
    //table name
    $a_table['name'] = 'glpi_plugin_fusioninventory_deploymirrors';
    $a_table['oldname'] = array('glpi_plugin_fusinvdeploy_mirrors');
    $a_table['fields'] = array('id' => array('type' => 'autoincrement', 'value' => NULL), 'entities_id' => array('type' => 'int(11) NOT NULL', 'value' => NULL), 'is_recursive' => array('type' => 'tinyint(1) NOT NULL DEFAULT 0', 'value' => NULL), 'name' => array('type' => 'varchar(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL', 'value' => NULL), 'url' => array('type' => "varchar(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci" . " NOT NULL DEFAULT ''", 'value' => NULL), 'locations_id' => array('type' => 'int(11) NOT NULL', 'value' => 0), 'comment' => array('type' => "text", 'value' => NULL), 'date_mod' => array('type' => 'datetime DEFAULT NULL', 'value' => NULL));
    $a_table['oldfields'] = array();
    $a_table['renamefields'] = array();
    $a_table['keys'] = array(array('field' => 'entities_id', 'name' => '', 'type' => 'KEY'), array('field' => 'date_mod', 'name' => '', 'type' => 'KEY'));
    $a_table['oldkeys'] = array();
    migrateTablesFusionInventory($migration, $a_table);
    /*
     * glpi_plugin_fusioninventory_deploygroups
     */
    $a_table = array();
    //table name
    $a_table['name'] = 'glpi_plugin_fusioninventory_deploygroups';
    $a_table['oldname'] = array('glpi_plugin_fusinvdeploy_groups');
    $a_table['fields'] = array('id' => array('type' => 'autoincrement', 'value' => NULL), 'name' => array('type' => 'varchar(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL', 'value' => NULL), 'comment' => array('type' => "text", 'value' => NULL), 'type' => array('type' => 'varchar(255) COLLATE utf8_unicode_ci NOT NULL', 'value' => NULL));
    $a_table['oldfields'] = array();
    $a_table['renamefields'] = array();
    $a_table['keys'] = array();
    $a_table['oldkeys'] = array();
    migrateTablesFusionInventory($migration, $a_table);
    /*
     * glpi_plugin_fusioninventory_deploygroups_staticdatas
     */
    $a_table = array();
    //table name
    $a_table['name'] = 'glpi_plugin_fusioninventory_deploygroups_staticdatas';
    $a_table['oldname'] = array('glpi_plugin_fusinvdeploy_groups_staticdatas');
    $a_table['fields'] = array('id' => array('type' => 'autoincrement', 'value' => NULL), 'groups_id' => array('type' => 'integer', 'value' => NULL), 'itemtype' => array('type' => 'varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL', 'value' => NULL), 'items_id' => array('type' => 'integer', 'value' => NULL));
    $a_table['oldfields'] = array();
    $a_table['renamefields'] = array();
    $a_table['keys'] = array(array('field' => 'groups_id', 'name' => '', 'type' => 'KEY'), array('field' => 'items_id', 'name' => '', 'type' => 'KEY'));
    $a_table['oldkeys'] = array();
    migrateTablesFusionInventory($migration, $a_table);
    /*
     * glpi_plugin_fusioninventory_deploygroups_dynamicdatas
     */
    $a_table = array();
    //table name
    $a_table['name'] = 'glpi_plugin_fusioninventory_deploygroups_dynamicdatas';
    $a_table['oldname'] = array('glpi_plugin_fusinvdeploy_groups_dynamicdatas');
    $a_table['fields'] = array('id' => array('type' => 'autoincrement', 'value' => NULL), 'groups_id' => array('type' => 'integer', 'value' => NULL), 'fields_array' => array('type' => 'text', 'value' => NULL));
    $a_table['oldfields'] = array();
    $a_table['renamefields'] = array();
    $a_table['keys'] = array(array('field' => 'groups_id', 'name' => '', 'type' => 'KEY'));
    $a_table['oldkeys'] = array();
    migrateTablesFusionInventory($migration, $a_table);
    /*
     * import old datas as json in order table before migrate this table
     */
    migrateTablesFromFusinvDeploy($migration);
    /*
     * Deploy Update End
     */
    /*
     * Table glpi_plugin_fusioninventory_collects
     */
    $a_table = array();
    $a_table['name'] = 'glpi_plugin_fusioninventory_collects';
    $a_table['oldname'] = array();
    $a_table['fields'] = array();
    $a_table['fields']['id'] = array('type' => "autoincrement", 'value' => '');
    $a_table['fields']['name'] = array('type' => 'string', 'value' => NULL);
    $a_table['fields']['entities_id'] = array('type' => 'integer', 'value' => NULL);
    $a_table['fields']['is_recursive'] = array('type' => 'bool', 'value' => NULL);
    $a_table['fields']['type'] = array('type' => 'string', 'value' => NULL);
    $a_table['fields']['is_active'] = array('type' => 'bool', 'value' => NULL);
    $a_table['fields']['comment'] = array('type' => 'text', 'value' => NULL);
    $a_table['oldfields'] = array();
    $a_table['renamefields'] = array();
    $a_table['keys'] = array();
    $a_table['oldkeys'] = array();
    migrateTablesFusionInventory($migration, $a_table);
    /*
     * Table glpi_plugin_fusioninventory_collects_registries
     */
    $a_table = array();
    $a_table['name'] = 'glpi_plugin_fusioninventory_collects_registries';
    $a_table['oldname'] = array();
    $a_table['fields'] = array();
    $a_table['fields']['id'] = array('type' => "autoincrement", 'value' => '');
    $a_table['fields']['name'] = array('type' => 'string', 'value' => NULL);
    $a_table['fields']['plugin_fusioninventory_collects_id'] = array('type' => 'integer', 'value' => NULL);
    $a_table['fields']['hive'] = array('type' => 'string', 'value' => NULL);
    $a_table['fields']['path'] = array('type' => 'text', 'value' => NULL);
    $a_table['fields']['key'] = array('type' => 'string', 'value' => NULL);
    $a_table['oldfields'] = array();
    $a_table['renamefields'] = array();
    $a_table['keys'] = array();
    $a_table['oldkeys'] = array();
    migrateTablesFusionInventory($migration, $a_table);
    /*
     * Table glpi_plugin_fusioninventory_collects_registries_contents
     */
    $a_table = array();
    $a_table['name'] = 'glpi_plugin_fusioninventory_collects_registries_contents';
    $a_table['oldname'] = array();
    $a_table['fields'] = array();
    $a_table['fields']['id'] = array('type' => "autoincrement", 'value' => '');
    $a_table['fields']['computers_id'] = array('type' => 'integer', 'value' => NULL);
    $a_table['fields']['plugin_fusioninventory_collects_registries_id'] = array('type' => 'integer', 'value' => NULL);
    $a_table['fields']['key'] = array('type' => 'string', 'value' => NULL);
    $a_table['fields']['value'] = array('type' => 'string', 'value' => NULL);
    $a_table['oldfields'] = array();
    $a_table['renamefields'] = array();
    $a_table['keys'] = array();
    $a_table['keys'][] = array('field' => 'computers_id', 'name' => '', 'type' => 'INDEX');
    $a_table['oldkeys'] = array();
    migrateTablesFusionInventory($migration, $a_table);
    /*
     * Table glpi_plugin_fusioninventory_collects_wmis
     */
    $a_table = array();
    $a_table['name'] = 'glpi_plugin_fusioninventory_collects_wmis';
    $a_table['oldname'] = array();
    $a_table['fields'] = array();
    $a_table['fields']['id'] = array('type' => "autoincrement", 'value' => '');
    $a_table['fields']['name'] = array('type' => 'string', 'value' => NULL);
    $a_table['fields']['plugin_fusioninventory_collects_id'] = array('type' => 'integer', 'value' => NULL);
    $a_table['fields']['moniker'] = array('type' => 'string', 'value' => NULL);
    $a_table['fields']['class'] = array('type' => 'string', 'value' => NULL);
    $a_table['fields']['properties'] = array('type' => 'string', 'value' => NULL);
    $a_table['oldfields'] = array();
    $a_table['renamefields'] = array();
    $a_table['keys'] = array();
    $a_table['oldkeys'] = array();
    migrateTablesFusionInventory($migration, $a_table);
    /*
     * Table glpi_plugin_fusioninventory_collects_wmis_contents
     */
    $a_table = array();
    $a_table['name'] = 'glpi_plugin_fusioninventory_collects_wmis_contents';
    $a_table['oldname'] = array();
    $a_table['fields'] = array();
    $a_table['fields']['id'] = array('type' => "autoincrement", 'value' => '');
    $a_table['fields']['computers_id'] = array('type' => 'integer', 'value' => NULL);
    $a_table['fields']['plugin_fusioninventory_collects_wmis_id'] = array('type' => 'integer', 'value' => NULL);
    $a_table['fields']['property'] = array('type' => 'string', 'value' => NULL);
    $a_table['fields']['value'] = array('type' => 'string', 'value' => NULL);
    $a_table['oldfields'] = array();
    $a_table['renamefields'] = array();
    $a_table['keys'] = array();
    $a_table['oldkeys'] = array();
    migrateTablesFusionInventory($migration, $a_table);
    /*
     * Table glpi_plugin_fusioninventory_collects_files
     */
    $a_table = array();
    $a_table['name'] = 'glpi_plugin_fusioninventory_collects_files';
    $a_table['oldname'] = array();
    $a_table['fields'] = array();
    $a_table['fields']['id'] = array('type' => "autoincrement", 'value' => '');
    $a_table['fields']['name'] = array('type' => 'string', 'value' => NULL);
    $a_table['fields']['plugin_fusioninventory_collects_id'] = array('type' => 'integer', 'value' => NULL);
    $a_table['fields']['dir'] = array('type' => 'string', 'value' => NULL);
    $a_table['fields']['limit'] = array('type' => "int(4) NOT NULL DEFAULT '50'", 'value' => NULL);
    $a_table['fields']['is_recursive'] = array('type' => 'bool', 'value' => NULL);
    $a_table['fields']['filter_regex'] = array('type' => 'string', 'value' => NULL);
    $a_table['fields']['filter_sizeequals'] = array('type' => 'integer', 'value' => NULL);
    $a_table['fields']['filter_sizegreater'] = array('type' => 'integer', 'value' => NULL);
    $a_table['fields']['filter_sizelower'] = array('type' => 'integer', 'value' => NULL);
    $a_table['fields']['filter_checksumsha512'] = array('type' => 'string', 'value' => NULL);
    $a_table['fields']['filter_checksumsha2'] = array('type' => 'string', 'value' => NULL);
    $a_table['fields']['filter_name'] = array('type' => 'string', 'value' => NULL);
    $a_table['fields']['filter_iname'] = array('type' => 'string', 'value' => NULL);
    $a_table['fields']['filter_is_file'] = array('type' => 'bool', 'value' => '1');
    $a_table['fields']['filter_is_dir'] = array('type' => 'bool', 'value' => '0');
    $a_table['oldfields'] = array();
    $a_table['renamefields'] = array();
    $a_table['keys'] = array();
    $a_table['oldkeys'] = array();
    migrateTablesFusionInventory($migration, $a_table);
    /*
     * Table glpi_plugin_fusioninventory_collects_files_contents
     */
    $a_table = array();
    $a_table['name'] = 'glpi_plugin_fusioninventory_collects_files_contents';
    $a_table['oldname'] = array();
    $a_table['fields'] = array();
    $a_table['fields']['id'] = array('type' => "autoincrement", 'value' => '');
    $a_table['fields']['computers_id'] = array('type' => 'integer', 'value' => NULL);
    $a_table['fields']['plugin_fusioninventory_collects_files_id'] = array('type' => 'integer', 'value' => NULL);
    $a_table['fields']['pathfile'] = array('type' => 'text', 'value' => NULL);
    $a_table['fields']['size'] = array('type' => 'integer', 'value' => NULL);
    $a_table['oldfields'] = array();
    $a_table['renamefields'] = array();
    $a_table['keys'] = array();
    $a_table['oldkeys'] = array();
    migrateTablesFusionInventory($migration, $a_table);
    /*
     * Table glpi_plugin_fusioninventory_dblockinventorynames
     */
    $a_table = array();
    $a_table['name'] = 'glpi_plugin_fusioninventory_dblockinventorynames';
    $a_table['oldname'] = array();
    $a_table['fields'] = array();
    $a_table['fields']['value'] = array('type' => "varchar(100) NOT NULL DEFAULT ''", 'value' => NULL);
    $a_table['fields']['date'] = array('type' => 'timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP', 'value' => NULL);
    $a_table['oldfields'] = array();
    $a_table['renamefields'] = array();
    $a_table['keys'] = array();
    $a_table['keys'][] = array('field' => 'value', 'name' => '', 'type' => 'UNIQUE');
    $a_table['oldkeys'] = array();
    migrateTablesFusionInventory($migration, $a_table);
    /*
     * Table glpi_plugin_fusioninventory_dblockinventories
     */
    $a_table = array();
    $a_table['name'] = 'glpi_plugin_fusioninventory_dblockinventories';
    $a_table['oldname'] = array();
    $a_table['fields'] = array();
    $a_table['fields']['value'] = array('type' => 'integer', 'value' => NULL);
    $a_table['fields']['date'] = array('type' => 'timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP', 'value' => NULL);
    $a_table['oldfields'] = array();
    $a_table['renamefields'] = array();
    $a_table['keys'] = array();
    $a_table['keys'][] = array('field' => 'value', 'name' => '', 'type' => 'UNIQUE');
    $a_table['oldkeys'] = array();
    migrateTablesFusionInventory($migration, $a_table);
    /*
     * Table glpi_plugin_fusioninventory_dblocksoftwares
     */
    $a_table = array();
    $a_table['name'] = 'glpi_plugin_fusioninventory_dblocksoftwares';
    $a_table['oldname'] = array();
    $a_table['fields'] = array();
    $a_table['fields']['value'] = array('type' => 'bool', 'value' => NULL);
    $a_table['fields']['date'] = array('type' => 'timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP', 'value' => NULL);
    $a_table['oldfields'] = array();
    $a_table['renamefields'] = array();
    $a_table['keys'] = array();
    $a_table['keys'][] = array('field' => 'value', 'name' => '', 'type' => 'UNIQUE');
    $a_table['oldkeys'] = array();
    migrateTablesFusionInventory($migration, $a_table);
    /*
     * Table glpi_plugin_fusioninventory_dblocksoftwareversions
     */
    $a_table = array();
    $a_table['name'] = 'glpi_plugin_fusioninventory_dblocksoftwareversions';
    $a_table['oldname'] = array();
    $a_table['fields'] = array();
    $a_table['fields']['value'] = array('type' => 'bool', 'value' => NULL);
    $a_table['fields']['date'] = array('type' => 'timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP', 'value' => NULL);
    $a_table['oldfields'] = array();
    $a_table['renamefields'] = array();
    $a_table['keys'] = array();
    $a_table['keys'][] = array('field' => 'value', 'name' => '', 'type' => 'UNIQUE');
    $a_table['oldkeys'] = array();
    migrateTablesFusionInventory($migration, $a_table);
    /*
     * Add ESX module appear in version 2.4.0(0.80+1.0)
     */
    $DB->query("UPDATE `glpi_plugin_fusioninventory_agentmodules`\n         SET `modulename`='InventoryComputerESX'\n         WHERE `modulename`='ESX'");
    $agentmodule = new PluginFusioninventoryAgentmodule();
    $query = "SELECT `id` FROM `glpi_plugin_fusioninventory_agentmodules`\n         WHERE `modulename`='InventoryComputerESX'\n         LIMIT 1";
    $result = $DB->query($query);
    if ($DB->numrows($result) == '0') {
        $input = array();
        $input['modulename'] = "InventoryComputerESX";
        $input['is_active'] = 0;
        $input['exceptions'] = exportArrayToDB(array());
        $url = '';
        if (isset($_SERVER['HTTP_REFERER'])) {
            $url = $_SERVER['HTTP_REFERER'];
        }
        $agentmodule->add($input);
    }
    /*
     * Add Collect module appear in version 0.84+2.0
     */
    $agentmodule = new PluginFusioninventoryAgentmodule();
    $query = "SELECT `id` FROM `glpi_plugin_fusioninventory_agentmodules`\n         WHERE `modulename`='Collect'\n         LIMIT 1";
    $result = $DB->query($query);
    if ($DB->numrows($result) == '0') {
        $input = array();
        $input['modulename'] = "Collect";
        $input['is_active'] = 1;
        $input['exceptions'] = exportArrayToDB(array());
        $agentmodule->add($input);
    }
    /*
     * Update pci and usb ids and oui
     */
    foreach (array('usbid.sql', 'pciid.sql', 'oui.sql') as $sql) {
        $DB_file = GLPI_ROOT . "/plugins/fusioninventory/install/mysql/{$sql}";
        $DBf_handle = fopen($DB_file, "rt");
        $sql_query = fread($DBf_handle, filesize($DB_file));
        fclose($DBf_handle);
        foreach (explode(";\n", "{$sql_query}") as $sql_line) {
            if (Toolbox::get_magic_quotes_runtime()) {
                $sql_line = Toolbox::stripslashes_deep($sql_line);
            }
            if (!empty($sql_line)) {
                $DB->query($sql_line);
            }
        }
    }
    /*
     * Migrate data of table glpi_plugin_fusinvsnmp_agentconfigs into
     * glpi_plugin_fusioninventory_agents
     */
    if (TableExists("glpi_plugin_fusinvsnmp_agentconfigs")) {
        $query = "SELECT * FROM `glpi_plugin_fusinvsnmp_agentconfigs`";
        $result = $DB->query($query);
        while ($data = $DB->fetch_array($result)) {
            $queryu = "UPDATE `glpi_plugin_fusioninventory_agents`\n            SET `threads_networkdiscovery`='" . $data['threads_netdiscovery'] . "',\n                `threads_networkinventory`='" . $data['threads_snmpquery'] . "',\n                `senddico`='" . $data['senddico'] . "'\n            WHERE `id`='" . $data['plugin_fusioninventory_agents_id'] . "'";
            $DB->query($queryu);
        }
    }
    // Update profiles
    if (TableExists("glpi_plugin_tracker_profiles")) {
        $profile = new Profile();
        $pfProfile = new PluginFusioninventoryProfile();
        $query = "SELECT * FROM `glpi_plugin_tracker_profiles`";
        $result = $DB->query($query);
        while ($data = $DB->fetch_array($result)) {
            $profiledata = current($profile->find("`name`='" . $data['name'] . "'", "", 1));
            if (!empty($profiledata)) {
                $newprofile = array();
                $newprofile['snmp_networking'] = "networkequipment";
                $newprofile['snmp_printers'] = "printer";
                $newprofile['snmp_models'] = "model";
                $newprofile['snmp_authentification'] = "configsecurity";
                $newprofile['general_config'] = "configuration";
                $newprofile['snmp_report'] = "reportprinter";
                foreach ($newprofile as $old => $new) {
                    if (isset($profiledata[$old])) {
                        //                  $pfProfile->addProfile($new,
                        //                                         $profiledata[$old],
                        //                                         $profiledata['id']);
                    }
                }
                if (isset($profiledata["snmp_report"])) {
                    //               $pfProfile->addProfile("reportnetworkequipment",
                    //                                      $profiledata["snmp_report"],
                    //                                      $profiledata['id']);
                }
            }
        }
        $DB->query("DROP TABLE `glpi_plugin_tracker_profiles`");
    }
    update213to220_ConvertField($migration);
    /*
     * Move networkequipment IPs to net system
     */
    if (TableExists("glpi_plugin_fusioninventory_networkequipmentips")) {
        $networkPort = new NetworkPort();
        $networkName = new NetworkName();
        $ipAddress = new IPAddress();
        $networkEquipment = new NetworkEquipment();
        $query = "SELECT * FROM `glpi_plugin_fusioninventory_networkequipments`";
        $result = $DB->query($query);
        while ($data = $DB->fetch_array($result)) {
            if ($networkEquipment->getFromDB($data['networkequipments_id'])) {
                $oldtableip = array();
                $queryIP = "SELECT * FROM `glpi_plugin_fusioninventory_networkequipmentips`\n               WHERE `networkequipments_id`='" . $data['networkequipments_id'] . "'";
                $resultIP = $DB->query($queryIP);
                while ($dataIP = $DB->fetch_array($resultIP)) {
                    $oldtableip[$dataIP['ip']] = $dataIP['ip'];
                }
                // Get actual IP defined
                $networknames_id = 0;
                $a_ports = $networkPort->find("`itemtype`='NetworkEquipment'\n                  AND `items_id`='" . $data['networkequipments_id'] . "'\n                  AND `instantiation_type`='NetworkPortAggregate'\n                  AND `name`='management'", "", 1);
                foreach ($a_ports as $a_port) {
                    $a_networknames = $networkName->find("`itemtype`='NetworkPort'\n                  AND `items_id`='" . $a_port['id'] . "'");
                    foreach ($a_networknames as $a_networkname) {
                        $networknames_id = $a_networkname['id'];
                        $a_ipaddresses = $ipAddress->find("`itemtype`='NetworkName'\n                     AND `items_id`='" . $a_networkname['id'] . "'");
                        foreach ($a_ipaddresses as $a_ipaddress) {
                            if (isset($oldtableip[$a_ipaddress['name']])) {
                                unset($oldtableip[$a_ipaddress['name']]);
                            } else {
                                $ipAddress->delete($a_ipaddress, 1);
                            }
                        }
                    }
                }
                // Update
                foreach ($oldtableip as $ip) {
                    $input = array();
                    $input['itemtype'] = "NetworkName";
                    $input['items_id'] = $networknames_id;
                    $input['name'] = $ip;
                    $input['is_dynamic'] = 1;
                    $ipAddress->add($input);
                }
            }
        }
    }
    /*
     * Table Delete old table not used
     */
    $a_drop = array();
    $a_drop[] = 'glpi_plugin_tracker_computers';
    $a_drop[] = 'glpi_plugin_tracker_connection_history';
    $a_drop[] = 'glpi_plugin_tracker_agents_processes';
    $a_drop[] = 'glpi_plugin_tracker_config_snmp_history';
    $a_drop[] = 'glpi_plugin_tracker_config_snmp_networking';
    $a_drop[] = 'glpi_plugin_tracker_config_snmp_printer';
    $a_drop[] = 'glpi_plugin_tracker_config_snmp_script';
    $a_drop[] = 'glpi_plugin_tracker_connection_stats';
    $a_drop[] = 'glpi_plugin_tracker_discovery';
    $a_drop[] = 'glpi_plugin_tracker_errors';
    $a_drop[] = 'glpi_plugin_tracker_model_infos';
    $a_drop[] = 'glpi_plugin_tracker_processes';
    $a_drop[] = 'glpi_plugin_tracker_processes_values';
    $a_drop[] = 'glpi_plugin_fusioninventory_agents_errors';
    $a_drop[] = 'glpi_plugin_fusioninventory_agents_processes';
    $a_drop[] = 'glpi_plugin_fusioninventory_computers';
    $a_drop[] = 'glpi_dropdown_plugin_tracker_snmp_auth_auth_protocol';
    $a_drop[] = 'glpi_dropdown_plugin_tracker_snmp_auth_priv_protocol';
    $a_drop[] = 'glpi_dropdown_plugin_tracker_snmp_auth_sec_level';
    $a_drop[] = 'glpi_dropdown_plugin_tracker_snmp_version';
    $a_drop[] = 'glpi_plugin_fusioninventory_config_snmp_networking';
    $a_drop[] = 'glpi_plugin_fusioninventory_config_snmp_history';
    $a_drop[] = 'glpi_plugin_fusinvsnmp_agentconfigs';
    $a_drop[] = 'glpi_plugin_tracker_computers';
    $a_drop[] = 'glpi_plugin_tracker_config';
    $a_drop[] = 'glpi_plugin_tracker_config_discovery';
    $a_drop[] = 'glpi_dropdown_plugin_fusioninventory_mib_label';
    $a_drop[] = 'glpi_dropdown_plugin_fusioninventory_mib_object';
    $a_drop[] = 'glpi_dropdown_plugin_fusioninventory_mib_oid';
    $a_drop[] = 'glpi_dropdown_plugin_fusioninventory_snmp_auth_auth_protocol';
    $a_drop[] = 'glpi_dropdown_plugin_fusioninventory_snmp_auth_priv_protocol';
    $a_drop[] = 'glpi_dropdown_plugin_fusioninventory_snmp_version';
    $a_drop[] = 'glpi_plugin_fusinvsnmp_temp_profiles';
    $a_drop[] = 'glpi_plugin_fusinvsnmp_tmp_agents';
    $a_drop[] = 'glpi_plugin_fusinvsnmp_tmp_configs';
    $a_drop[] = 'glpi_plugin_fusinvsnmp_tmp_tasks';
    $a_drop[] = 'glpi_plugin_tracker_tmp_connections';
    $a_drop[] = 'glpi_plugin_tracker_tmp_netports';
    $a_drop[] = 'glpi_plugin_tracker_walks';
    $a_drop[] = 'glpi_plugin_fusioninventory_networkequipmentips';
    foreach ($a_drop as $droptable) {
        if (TableExists($droptable)) {
            $DB->query("DROP TABLE `" . $droptable . "`");
        }
    }
    $migration->executeMigration();
    /*
     * Add WakeOnLan module appear in version 2.3.0
     */
    $query = "SELECT `id` FROM `glpi_plugin_fusioninventory_agentmodules`\n      WHERE `modulename`='WAKEONLAN'";
    $result = $DB->query($query);
    if (!$DB->numrows($result)) {
        $agentmodule = new PluginFusioninventoryAgentmodule();
        $input = array();
        $input['plugins_id'] = $plugins_id;
        $input['modulename'] = "WAKEONLAN";
        $input['is_active'] = 0;
        $input['exceptions'] = exportArrayToDB(array());
        $agentmodule->add($input);
    }
    /*
     * Add storage type if not present
     */
    $a_storage = array();
    $a_storage['partition'] = 5;
    $a_storage['volume groups'] = 10;
    $a_storage['logical volumes'] = 20;
    $a_storage['hard disk'] = 1;
    $a_storage['mount'] = 25;
    foreach ($a_storage as $name => $level) {
        $query = "SELECT `id` FROM `glpi_plugin_fusioninventory_inventorycomputerstoragetypes`\n         WHERE `name`='" . $name . "'";
        $result = $DB->query($query);
        if (!$DB->numrows($result)) {
            $DB->query("INSERT INTO `glpi_plugin_fusioninventory_inventorycomputerstoragetypes`\n            (`name`, `level`) VALUES\n            ('" . $name . "', '" . $level . "')");
        }
    }
    /*
     * Clean for port orphelin
     */
    //networkports with item_type = 0
    $NetworkPort = new NetworkPort();
    $NetworkPort_Vlan = new NetworkPort_Vlan();
    $NetworkPort_NetworkPort = new NetworkPort_NetworkPort();
    $a_networkports = $NetworkPort->find("`itemtype`=''");
    foreach ($a_networkports as $data) {
        if ($NetworkPort_NetworkPort->getFromDBForNetworkPort($data['id'])) {
            $NetworkPort_NetworkPort->delete($NetworkPort_NetworkPort->fields);
        }
        $a_vlans = $NetworkPort_Vlan->find("`networkports_id`='" . $data['id'] . "'");
        foreach ($a_vlans as $a_vlan) {
            $NetworkPort_Vlan->delete($a_vlan);
        }
        $NetworkPort->delete($data, 1);
    }
    /*
     *  Clean old ports deleted but have some informations in SNMP tables
     */
    //echo "Clean ports purged\n";
    $query_select = "SELECT `glpi_plugin_fusioninventory_networkports`.`id`\n                    FROM `glpi_plugin_fusioninventory_networkports`\n                          LEFT JOIN `glpi_networkports`\n                                    ON `glpi_networkports`.`id` = `networkports_id`\n                          LEFT JOIN `glpi_networkequipments`\n                              ON `glpi_networkequipments`.`id` = `glpi_networkports`.`items_id`\n                    WHERE `glpi_networkequipments`.`id` IS NULL";
    $result = $DB->query($query_select);
    while ($data = $DB->fetch_array($result)) {
        $query_del = "DELETE FROM `glpi_plugin_fusioninventory_networkports`\n         WHERE `id`='" . $data["id"] . "'";
        $DB->query($query_del);
    }
    /*
     * Clean for switch more informations again in DB when switch is purged
     */
    //echo "Clean for switch more informations again in DB when switch is purged\n";
    $query_select = "SELECT `glpi_plugin_fusioninventory_networkequipments`.`id`\n                    FROM `glpi_plugin_fusioninventory_networkequipments`\n                    LEFT JOIN `glpi_networkequipments`\n                        ON `glpi_networkequipments`.`id` = `networkequipments_id`\n                    WHERE `glpi_networkequipments`.`id` IS NULL";
    $result = $DB->query($query_select);
    while ($data = $DB->fetch_array($result)) {
        $query_del = "DELETE FROM `glpi_plugin_fusioninventory_networkequipments`\n         WHERE `id`='" . $data["id"] . "'";
        $DB->query($query_del);
    }
    /*
     * Clean for printer more informations again in DB when printer is purged
     */
    //echo "Clean for printer more informations again in DB when printer is purged\n";
    $query_select = "SELECT `glpi_plugin_fusioninventory_printers`.`id`\n                    FROM `glpi_plugin_fusioninventory_printers`\n                          LEFT JOIN `glpi_printers` ON `glpi_printers`.`id` = `printers_id`\n                    WHERE `glpi_printers`.`id` IS NULL";
    $result = $DB->query($query_select);
    while ($data = $DB->fetch_array($result)) {
        $query_del = "DELETE FROM `glpi_plugin_fusioninventory_printers`\n         WHERE `id`='" . $data["id"] . "'";
        $DB->query($query_del);
    }
    /*
     *  Clean printer cartridge not deleted with the printer associated
     */
    //echo "Clean printer cartridge not deleted with the printer associated\n";
    $query_select = "SELECT `glpi_plugin_fusioninventory_printercartridges`.`id`\n                    FROM `glpi_plugin_fusioninventory_printercartridges`\n                          LEFT JOIN `glpi_printers` ON `glpi_printers`.`id` = `printers_id`\n                    WHERE `glpi_printers`.`id` IS NULL";
    $result = $DB->query($query_select);
    while ($data = $DB->fetch_array($result)) {
        $query_del = "DELETE FROM `glpi_plugin_fusioninventory_printercartridges`\n         WHERE `id`='" . $data["id"] . "'";
        $DB->query($query_del);
    }
    /*
     *  Clean printer history not deleted with printer associated
     */
    //echo "Clean printer history not deleted with printer associated\n";
    $query_select = "SELECT `glpi_plugin_fusioninventory_printerlogs`.`id`\n                    FROM `glpi_plugin_fusioninventory_printerlogs`\n                          LEFT JOIN `glpi_printers` ON `glpi_printers`.`id` = `printers_id`\n                    WHERE `glpi_printers`.`id` IS NULL";
    $result = $DB->query($query_select);
    while ($data = $DB->fetch_array($result)) {
        $query_del = "DELETE FROM `glpi_plugin_fusioninventory_printerlogs`\n         WHERE `id`='" . $data["id"] . "'";
        $DB->query($query_del);
    }
    /*
     * Fix problem with mapping with many entries with same mapping
     */
    $a_mapping = array();
    $a_mappingdouble = array();
    $query = "SELECT * FROM `glpi_plugin_fusioninventory_mappings`\n      ORDER BY `id`";
    $result = $DB->query($query);
    while ($data = $DB->fetch_array($result)) {
        if (!isset($a_mapping[$data['itemtype'] . "." . $data['name']])) {
            $a_mapping[$data['itemtype'] . "." . $data['name']] = $data['id'];
        } else {
            $a_mappingdouble[$data['id']] = $data['itemtype'] . "." . $data['name'];
        }
    }
    foreach ($a_mappingdouble as $mapping_id => $mappingkey) {
        $query = "UPDATE `glpi_plugin_fusioninventory_printercartridges`\n         SET plugin_fusioninventory_mappings_id='" . $a_mapping[$mappingkey] . "'\n         WHERE plugin_fusioninventory_mappings_id='" . $mapping_id . "'";
        $DB->query($query);
        $query = "UPDATE `glpi_plugin_fusioninventory_networkportlogs`\n         SET plugin_fusioninventory_mappings_id='" . $a_mapping[$mappingkey] . "'\n         WHERE plugin_fusioninventory_mappings_id='" . $mapping_id . "'";
        $DB->query($query);
        $query = "UPDATE `glpi_plugin_fusioninventory_configlogfields`\n         SET plugin_fusioninventory_mappings_id='" . $a_mapping[$mappingkey] . "'\n         WHERE plugin_fusioninventory_mappings_id='" . $mapping_id . "'";
        $DB->query($query);
        $query = "DELETE FROM `glpi_plugin_fusioninventory_mappings`\n         WHERE `id` = '" . $mapping_id . "'";
        $DB->query($query);
    }
    /*
     * Update networports to convert itemtype 5153 to PluginFusioninventoryUnknownDevice
     */
    $sql = "UPDATE `glpi_networkports`\n      SET `itemtype`='PluginFusioninventoryUnknownDevice'\n      WHERE `itemtype`='5153'";
    $DB->query($sql);
    $sql = "UPDATE `glpi_networkports`\n      SET `itemtype`='PluginFusioninventoryTask'\n      WHERE `itemtype`='5166'";
    $DB->query($sql);
    /*
     * Clean display preferences not used
     */
    $sql = "DELETE FROM `glpi_displaypreferences`\n      WHERE `itemtype`='5150' ";
    $DB->query($sql);
    $sql = "DELETE FROM `glpi_displaypreferences`\n      WHERE `itemtype`='5160' ";
    $DB->query($sql);
    $sql = "DELETE FROM `glpi_displaypreferences`\n      WHERE `itemtype`='5161' ";
    $DB->query($sql);
    $sql = "DELETE FROM `glpi_displaypreferences`\n      WHERE `itemtype`='5163' ";
    $DB->query($sql);
    $sql = "DELETE FROM `glpi_displaypreferences`\n      WHERE `itemtype`='5165' ";
    $DB->query($sql);
    $sql = "DELETE FROM `glpi_displaypreferences`\n      WHERE `itemtype`='5190' ";
    $DB->query($sql);
    /*
     * Update display preferences
     */
    changeDisplayPreference("5153", "PluginFusioninventoryUnknownDevice");
    changeDisplayPreference("5158", "PluginFusioninventoryAgent");
    changeDisplayPreference("PluginFusinvinventoryBlacklist", "PluginFusioninventoryInventoryComputerBlacklist");
    changeDisplayPreference("5151", "PluginFusinvsnmpModel");
    changeDisplayPreference("PluginFusinvsnmpModel", "PluginFusioninventorySnmpmodel");
    changeDisplayPreference("5152", "PluginFusinvsnmpConfigSecurity");
    changeDisplayPreference("5156", "PluginFusinvsnmpPrinterCartridge");
    changeDisplayPreference("5157", "PluginFusinvsnmpNetworkEquipment");
    changeDisplayPreference("PluginFusinvsnmpNetworkEquipment", "PluginFusioninventoryNetworkEquipment");
    changeDisplayPreference("5159", "PluginFusinvsnmpIPRange");
    changeDisplayPreference("5162", "PluginFusinvsnmpNetworkPortLog");
    changeDisplayPreference("5167", "PluginFusioninventorySnmpmodelConstructDevice");
    changeDisplayPreference("PluginFusinvsnmpConstructDevice", "PluginFusioninventorySnmpmodelConstructDevice");
    changeDisplayPreference("5168", "PluginFusinvsnmpPrinterLog");
    changeDisplayPreference("PluginFusinvsnmpPrinterLogReport", "PluginFusioninventoryPrinterLogReport");
    changeDisplayPreference("PluginFusioninventoryUnknownDevice", "PluginFusioninventoryUnmanaged");
    /*
     * Delete IP and MAC of PluginFusioninventoryUnknownDevice in displaypreference
     */
    $queryd = "DELETE FROM `glpi_displaypreferences`\n         WHERE `itemtype`='PluginFusioninventoryUnknownDevice'\n            AND (`num`='11' OR `num`='12' OR `num`='16')";
    $DB->query($queryd);
    /*
     * Clean in displaypreference
     */
    $queryd = "DELETE FROM `glpi_displaypreferences`\n         WHERE `itemtype`='PluginFusioninventorysnmpModel'";
    $DB->query($queryd);
    /*
     * Modify displaypreference for PluginFusioninventoryPrinterLog
     */
    $pfPrinterLogReport = new PluginFusioninventoryPrinterLog();
    $a_searchoptions = $pfPrinterLogReport->getSearchOptions();
    $query = "SELECT * FROM `glpi_displaypreferences`\n      WHERE `itemtype` = 'PluginFusioninventoryPrinterLogReport'\n         AND `users_id`='0'";
    $result = $DB->query($query);
    if ($DB->numrows($result) == '0') {
        $query = "INSERT INTO `glpi_displaypreferences` (`id`, `itemtype`, `num`, `rank`,\n                        `users_id`)\n                     VALUES (NULL, 'PluginFusioninventoryPrinterLogReport', '2', '1', '0'),\n             (NULL, 'PluginFusioninventoryPrinterLogReport', '18', '2', '0'),\n             (NULL, 'PluginFusioninventoryPrinterLogReport', '20', '3', '0'),\n             (NULL, 'PluginFusioninventoryPrinterLogReport', '5', '4', '0'),\n             (NULL, 'PluginFusioninventoryPrinterLogReport', '6', '5', '0')";
        $DB->query($query);
    } else {
        while ($data = $DB->fetch_array($result)) {
            if (!isset($a_searchoptions[$data['num']])) {
                $queryd = "DELETE FROM `glpi_displaypreferences`\n                  WHERE `id`='" . $data['id'] . "'";
                $DB->query($queryd);
            }
        }
    }
    /*
     * Modify displaypreference for PluginFusinvsnmpNetworkEquipment
     */
    $a_check = array();
    $a_check["2"] = 1;
    $a_check["3"] = 2;
    $a_check["4"] = 3;
    $a_check["5"] = 4;
    $a_check["6"] = 5;
    $a_check["7"] = 6;
    $a_check["8"] = 7;
    $a_check["9"] = 8;
    $a_check["10"] = 9;
    $a_check["11"] = 10;
    $a_check["14"] = 11;
    $a_check["12"] = 12;
    $a_check["13"] = 13;
    foreach ($a_check as $num => $rank) {
        $query = "SELECT * FROM `glpi_displaypreferences`\n         WHERE `itemtype` = 'PluginFusioninventoryNetworkEquipment'\n         AND `num`='" . $num . "'\n            AND `users_id`='0'";
        $result = $DB->query($query);
        if ($DB->numrows($result) == '0') {
            $query = "INSERT INTO `glpi_displaypreferences` (`id`, `itemtype`, `num`, `rank`,\n                           `users_id`)\n                        VALUES (NULL, 'PluginFusioninventoryNetworkEquipment', '" . $num . "',\n                           '" . $rank . "', '0')";
            $DB->query($query);
        }
    }
    $query = "SELECT * FROM `glpi_displaypreferences`\n      WHERE `itemtype` = 'PluginFusioninventoryNetworkEquipment'\n         AND `users_id`='0'";
    $result = $DB->query($query);
    while ($data = $DB->fetch_array($result)) {
        if (!isset($a_check[$data['num']])) {
            $queryd = "DELETE FROM `glpi_displaypreferences`\n               WHERE `id`='" . $data['id'] . "'";
            $DB->query($queryd);
        }
    }
    // If no PluginFusioninventoryTaskjoblog in preferences, add them
    $query = "SELECT * FROM `glpi_displaypreferences`\n      WHERE `itemtype` = 'PluginFusioninventoryTaskjoblog'\n         AND `users_id`='0'";
    $result = $DB->query($query);
    if ($DB->numrows($result) == 0) {
        $DB->query("INSERT INTO `glpi_displaypreferences`\n            (`id`, `itemtype`, `num`, `rank`, `users_id`)\n         VALUES (NULL,'PluginFusioninventoryTaskjoblog', '2', '1', '0'),\n                (NULL,'PluginFusioninventoryTaskjoblog', '3', '2', '0'),\n                (NULL,'PluginFusioninventoryTaskjoblog', '4', '3', '0'),\n                (NULL,'PluginFusioninventoryTaskjoblog', '5', '4', '0'),\n                (NULL,'PluginFusioninventoryTaskjoblog', '6', '5', '0'),\n                (NULL,'PluginFusioninventoryTaskjoblog', '7', '6', '0'),\n                (NULL,'PluginFusioninventoryTaskjoblog', '8', '7', '0')");
    }
    // If no PluginFusioninventoryNetworkPort in preferences, add them
    $query = "SELECT * FROM `glpi_displaypreferences`\n      WHERE `itemtype` = 'PluginFusioninventoryNetworkPort'\n         AND `users_id`='0'";
    $result = $DB->query($query);
    if ($DB->numrows($result) == 0) {
        $DB->query("INSERT INTO `glpi_displaypreferences`\n            (`id`, `itemtype`, `num`, `rank`, `users_id`)\n         VALUES (NULL,'PluginFusioninventoryNetworkPort', '3', '1', '0'),\n                (NULL,'PluginFusioninventoryNetworkPort', '5', '2', '0'),\n                (NULL,'PluginFusioninventoryNetworkPort', '6', '3', '0'),\n                (NULL,'PluginFusioninventoryNetworkPort', '7', '4', '0'),\n                (NULL,'PluginFusioninventoryNetworkPort', '8', '5', '0'),\n                (NULL,'PluginFusioninventoryNetworkPort', '9', '6', '0'),\n                (NULL,'PluginFusioninventoryNetworkPort', '10', '7', '0'),\n                (NULL,'PluginFusioninventoryNetworkPort', '11', '8', '0'),\n                (NULL,'PluginFusioninventoryNetworkPort', '12', '9', '0'),\n                (NULL,'PluginFusioninventoryNetworkPort', '13', '10', '0'),\n                (NULL,'PluginFusioninventoryNetworkPort', '14', '11', '0')");
    }
    /*
     * Convert taskjob definition from PluginFusinvsnmpIPRange to PluginFusioninventoryIPRange
     * onvert taskjob definition from PluginFusinvdeployPackage to PluginFusioninventoryDeployPackage
     */
    $query = "SELECT * FROM `glpi_plugin_fusioninventory_taskjobs`";
    $result = $DB->query($query);
    while ($data = $DB->fetch_array($result)) {
        $a_defs = importArrayFromDB($data['targets']);
        foreach ($a_defs as $num => $a_def) {
            if (key($a_def) == 'PluginFusinvsnmpIPRange') {
                $a_defs[$num] = array('PluginFusioninventoryIPRange' => current($a_def));
            } else {
                if (key($a_def) == 'PluginFusinvdeployPackage') {
                    $a_defs[$num] = array('PluginFusioninventoryDeployPackage' => current($a_def));
                }
            }
        }
        $queryu = "UPDATE `glpi_plugin_fusioninventory_taskjobs`\n         SET `targets`='" . exportArrayToDB($a_defs) . "'\n         WHERE `id`='" . $data['id'] . "'";
        $DB->query($queryu);
    }
    /*
     * Convert taskjoblogs itemtype from PluginFusinvdeployPackage to
     * PluginFusioninventoryDeployPackage
     */
    $query = "UPDATE `glpi_plugin_fusioninventory_taskjoblogs` " . "SET `itemtype`='PluginFusioninventoryDeployPackage'" . "WHERE `itemtype`='PluginFusinvdeployPackage'";
    $result = $DB->query($query);
    /*
     * Convert taskjobstates itemtype from PluginFusinvdeployPackage to
     * PluginFusioninventoryDeployPackage
     */
    $query = "UPDATE `glpi_plugin_fusioninventory_taskjobstates` " . "SET `itemtype`='PluginFusioninventoryDeployPackage'" . "WHERE `itemtype` = 'PluginFusinvdeployPackage'";
    $result = $DB->query($query);
    /*
     * Convert taskjob action from PluginFusinvdeployGroup to PluginFusioninventoryDeployGroup
     */
    $query = "SELECT * FROM `glpi_plugin_fusioninventory_taskjobs`";
    $result = $DB->query($query);
    while ($data = $DB->fetch_array($result)) {
        $a_defs = importArrayFromDB($data['actors']);
        foreach ($a_defs as $num => $a_def) {
            if (key($a_def) == 'PluginFusinvdeployGroup') {
                $a_defs[$num] = array('PluginFusioninventoryDeployGroup' => current($a_def));
            }
        }
        $queryu = "UPDATE `glpi_plugin_fusioninventory_taskjobs`\n         SET `actors`='" . exportArrayToDB($a_defs) . "'\n         WHERE `id`='" . $data['id'] . "'";
        $DB->query($queryu);
    }
    /*
     * Convert itemtype from glpi_plugin_fusioninventory_unknowndevices to
     * PluginFusioninventoryUnmanaged
     */
    $tables = array('glpi_networkports', 'glpi_logs', 'glpi_plugin_fusioninventory_ignoredimportdevices');
    foreach ($tables as $table) {
        $query = "UPDATE `" . $table . "` " . "SET `itemtype`='PluginFusioninventoryUnmanaged'" . "WHERE `itemtype` = 'PluginFusioninventoryUnknowndevice'";
        $DB->query($query);
    }
    $query = "UPDATE `glpi_ipaddresses` " . "SET `mainitemtype`='PluginFusioninventoryUnmanaged'" . "WHERE `mainitemtype` = 'PluginFusioninventoryUnknowndevice'";
    $DB->query($query);
    /*
     * Update rules
     */
    $query = "UPDATE glpi_rules SET `sub_type`='PluginFusioninventoryInventoryRuleImport'\n      WHERE `sub_type`='PluginFusioninventoryRuleImportEquipment'";
    $DB->query($query);
    $query = "SELECT * FROM `glpi_rules`\n               WHERE `sub_type`='PluginFusioninventoryInventoryRuleImport'";
    $result = $DB->query($query);
    while ($data = $DB->fetch_array($result)) {
        $querya = "UPDATE glpi_ruleactions SET `value`='1'\n         WHERE `rules_id`='" . $data['id'] . "'\n            AND `value`='0'\n            AND `field`='_fusion'";
        $DB->query($querya);
    }
    $query = "UPDATE glpi_rules SET `sub_type`='PluginFusioninventoryInventoryRuleEntity'\n      WHERE `sub_type`='PluginFusinvinventoryRuleEntity'";
    $DB->query($query);
    /*
     *  Add default rules
     */
    if (TableExists("glpi_plugin_tracker_config_discovery")) {
        $migration->displayMessage("Create rules");
        $pfSetup = new PluginFusioninventorySetup();
        $pfSetup->initRules();
    }
    // If no rules, add them
    if (countElementsInTable('glpi_rules', "`sub_type`='PluginFusioninventoryInventoryRuleImport'") == 0) {
        $migration->displayMessage("Create rules");
        $pfSetup = new PluginFusioninventorySetup();
        $pfSetup->initRules();
    }
    // Add peripheral rules (in first in rule list) when use it since 0.85
    $query = "DELETE FROM `glpi_plugin_fusioninventory_configs`" . " WHERE `type`='import_peripheral' ";
    $DB->query($query);
    $query = "UPDATE `glpi_rules` " . " SET `ranking` = `ranking`+3" . " WHERE `sub_type`='PluginFusioninventoryInventoryRuleImport' ";
    $ranking = 0;
    // Create rule for : Peripheral + serial
    $rulecollection = new PluginFusioninventoryInventoryRuleImportCollection();
    $input = array();
    $input['is_active'] = 1;
    $input['name'] = 'Peripheral serial';
    $input['match'] = 'AND';
    $input['sub_type'] = 'PluginFusioninventoryInventoryRuleImport';
    $input['ranking'] = $ranking;
    $rule_id = $rulecollection->add($input);
    // Add criteria
    $rule = $rulecollection->getRuleClass();
    $rulecriteria = new RuleCriteria(get_class($rule));
    $input = array();
    $input['rules_id'] = $rule_id;
    $input['criteria'] = "serial";
    $input['pattern'] = 1;
    $input['condition'] = 10;
    $rulecriteria->add($input);
    $input = array();
    $input['rules_id'] = $rule_id;
    $input['criteria'] = "serial";
    $input['pattern'] = 1;
    $input['condition'] = 8;
    $rulecriteria->add($input);
    $input = array();
    $input['rules_id'] = $rule_id;
    $input['criteria'] = "itemtype";
    $input['pattern'] = 'Peripheral';
    $input['condition'] = 0;
    $rulecriteria->add($input);
    // Add action
    $ruleaction = new RuleAction(get_class($rule));
    $input = array();
    $input['rules_id'] = $rule_id;
    $input['action_type'] = 'assign';
    $input['field'] = '_fusion';
    $input['value'] = '1';
    $ruleaction->add($input);
    $ranking++;
    // Create rule for : Peripheral import
    $rulecollection = new PluginFusioninventoryInventoryRuleImportCollection();
    $input = array();
    $input['is_active'] = 1;
    $input['name'] = 'Peripheral import';
    $input['match'] = 'AND';
    $input['sub_type'] = 'PluginFusioninventoryInventoryRuleImport';
    $input['ranking'] = $ranking;
    $rule_id = $rulecollection->add($input);
    // Add criteria
    $rule = $rulecollection->getRuleClass();
    $rulecriteria = new RuleCriteria(get_class($rule));
    $input = array();
    $input['rules_id'] = $rule_id;
    $input['criteria'] = "itemtype";
    $input['pattern'] = 'Peripheral';
    $input['condition'] = 0;
    $rulecriteria->add($input);
    $input = array();
    $input['rules_id'] = $rule_id;
    $input['criteria'] = "serial";
    $input['pattern'] = 1;
    $input['condition'] = 8;
    $rulecriteria->add($input);
    // Add action
    $ruleaction = new RuleAction(get_class($rule));
    $input = array();
    $input['rules_id'] = $rule_id;
    $input['action_type'] = 'assign';
    $input['field'] = '_fusion';
    $input['value'] = '1';
    $ruleaction->add($input);
    $ranking++;
    // Create rule for : Peripheral ignore import
    $rulecollection = new PluginFusioninventoryInventoryRuleImportCollection();
    $input = array();
    $input['is_active'] = 1;
    $input['name'] = 'Peripheral ignore import';
    $input['match'] = 'AND';
    $input['sub_type'] = 'PluginFusioninventoryInventoryRuleImport';
    $input['ranking'] = $ranking;
    $rule_id = $rulecollection->add($input);
    // Add criteria
    $rule = $rulecollection->getRuleClass();
    $rulecriteria = new RuleCriteria(get_class($rule));
    $input = array();
    $input['rules_id'] = $rule_id;
    $input['criteria'] = "itemtype";
    $input['pattern'] = 'Peripheral';
    $input['condition'] = 0;
    $rulecriteria->add($input);
    // Add action
    $ruleaction = new RuleAction(get_class($rule));
    $input = array();
    $input['rules_id'] = $rule_id;
    $input['action_type'] = 'assign';
    $input['field'] = '_ignore_import';
    $input['value'] = '1';
    $ruleaction->add($input);
    // Add monitor rules (in first in rule list) when use it since 0.85
    $query = "DELETE FROM `glpi_plugin_fusioninventory_configs`" . " WHERE `type`='import_monitor' ";
    $DB->query($query);
    $query = "UPDATE `glpi_rules` " . " SET `ranking` = `ranking`+3" . " WHERE `sub_type`='PluginFusioninventoryInventoryRuleImport' ";
    $ranking = 0;
    // Create rule for : Monitor + serial
    $rulecollection = new PluginFusioninventoryInventoryRuleImportCollection();
    $input = array();
    $input['is_active'] = 1;
    $input['name'] = 'Monitor serial';
    $input['match'] = 'AND';
    $input['sub_type'] = 'PluginFusioninventoryInventoryRuleImport';
    $input['ranking'] = $ranking;
    $rule_id = $rulecollection->add($input);
    // Add criteria
    $rule = $rulecollection->getRuleClass();
    $rulecriteria = new RuleCriteria(get_class($rule));
    $input = array();
    $input['rules_id'] = $rule_id;
    $input['criteria'] = "serial";
    $input['pattern'] = 1;
    $input['condition'] = 10;
    $rulecriteria->add($input);
    $input = array();
    $input['rules_id'] = $rule_id;
    $input['criteria'] = "serial";
    $input['pattern'] = 1;
    $input['condition'] = 8;
    $rulecriteria->add($input);
    $input = array();
    $input['rules_id'] = $rule_id;
    $input['criteria'] = "itemtype";
    $input['pattern'] = 'Monitor';
    $input['condition'] = 0;
    $rulecriteria->add($input);
    // Add action
    $ruleaction = new RuleAction(get_class($rule));
    $input = array();
    $input['rules_id'] = $rule_id;
    $input['action_type'] = 'assign';
    $input['field'] = '_fusion';
    $input['value'] = '1';
    $ruleaction->add($input);
    $ranking++;
    // Create rule for : Monitor import
    $rulecollection = new PluginFusioninventoryInventoryRuleImportCollection();
    $input = array();
    $input['is_active'] = 1;
    $input['name'] = 'Monitor import';
    $input['match'] = 'AND';
    $input['sub_type'] = 'PluginFusioninventoryInventoryRuleImport';
    $input['ranking'] = $ranking;
    $rule_id = $rulecollection->add($input);
    // Add criteria
    $rule = $rulecollection->getRuleClass();
    $rulecriteria = new RuleCriteria(get_class($rule));
    $input = array();
    $input['rules_id'] = $rule_id;
    $input['criteria'] = "itemtype";
    $input['pattern'] = 'Monitor';
    $input['condition'] = 0;
    $rulecriteria->add($input);
    $input = array();
    $input['rules_id'] = $rule_id;
    $input['criteria'] = "serial";
    $input['pattern'] = 1;
    $input['condition'] = 8;
    $rulecriteria->add($input);
    // Add action
    $ruleaction = new RuleAction(get_class($rule));
    $input = array();
    $input['rules_id'] = $rule_id;
    $input['action_type'] = 'assign';
    $input['field'] = '_fusion';
    $input['value'] = '1';
    $ruleaction->add($input);
    $ranking++;
    // Create rule for : Monitor ignore import
    $rulecollection = new PluginFusioninventoryInventoryRuleImportCollection();
    $input = array();
    $input['is_active'] = 1;
    $input['name'] = 'Monitor ignore import';
    $input['match'] = 'AND';
    $input['sub_type'] = 'PluginFusioninventoryInventoryRuleImport';
    $input['ranking'] = $ranking;
    $rule_id = $rulecollection->add($input);
    // Add criteria
    $rule = $rulecollection->getRuleClass();
    $rulecriteria = new RuleCriteria(get_class($rule));
    $input = array();
    $input['rules_id'] = $rule_id;
    $input['criteria'] = "itemtype";
    $input['pattern'] = 'Monitor';
    $input['condition'] = 0;
    $rulecriteria->add($input);
    // Add action
    $ruleaction = new RuleAction(get_class($rule));
    $input = array();
    $input['rules_id'] = $rule_id;
    $input['action_type'] = 'assign';
    $input['field'] = '_ignore_import';
    $input['value'] = '1';
    $ruleaction->add($input);
    // Add printer rules (in first in rule list) when use it since 0.85
    $query = "DELETE FROM `glpi_plugin_fusioninventory_configs`" . " WHERE `type`='import_printer' ";
    /*
     *  Manage configuration of plugin
     */
    $config = new PluginFusioninventoryConfig();
    $pfSetup = new PluginFusioninventorySetup();
    $users_id = $pfSetup->createFusionInventoryUser();
    $a_input = array();
    $a_input['ssl_only'] = 0;
    $a_input['delete_task'] = 20;
    $a_input['inventory_frequence'] = 24;
    $a_input['agent_port'] = 62354;
    $a_input['extradebug'] = 0;
    $a_input['users_id'] = $users_id;
    $a_input['agents_old_days'] = 0;
    $config->addValues($a_input, FALSE);
    //      $DB->query("DELETE FROM `glpi_plugin_fusioninventory_configs`
    //        WHERE `plugins_id`='0'");
    //      $query = "SELECT * FROM `glpi_plugin_fusioninventory_configs`
    //           WHERE `type`='version'
    //           LIMIT 1, 10";
    //      $result = $DB->query($query);
    //      while ($data=$DB->fetch_array($result)) {
    //         $config->delete($data);
    //      }
    $a_input = array();
    $a_input['version'] = PLUGIN_FUSIONINVENTORY_VERSION;
    $config->addValues($a_input, TRUE);
    $a_input = array();
    $a_input['ssl_only'] = 0;
    if (isset($prepare_Config['ssl_only'])) {
        $a_input['ssl_only'] = $prepare_Config['ssl_only'];
    }
    $a_input['delete_task'] = 20;
    $a_input['inventory_frequence'] = 24;
    $a_input['agent_port'] = 62354;
    $a_input['extradebug'] = 0;
    $a_input['users_id'] = 0;
    //Deploy configuration options
    $a_input['server_upload_path'] = Toolbox::addslashes_deep(implode(DIRECTORY_SEPARATOR, array(GLPI_PLUGIN_DOC_DIR, 'fusioninventory', 'upload')));
    $a_input['alert_winpath'] = 1;
    $a_input['server_as_mirror'] = 1;
    $config->addValues($a_input, FALSE);
    $pfSetup = new PluginFusioninventorySetup();
    $users_id = $pfSetup->createFusionInventoryUser();
    $query = "UPDATE `glpi_plugin_fusioninventory_configs`\n                         SET `value`='" . $users_id . "'\n                  WHERE `type`='users_id'";
    $DB->query($query);
    // Update fusinvinventory _config values to this plugin
    $input = array();
    $input['import_software'] = 1;
    $input['import_volume'] = 1;
    $input['import_antivirus'] = 1;
    $input['import_registry'] = 1;
    $input['import_process'] = 1;
    $input['import_vm'] = 1;
    $input['component_processor'] = 1;
    $input['component_memory'] = 1;
    $input['component_harddrive'] = 1;
    $input['component_networkcard'] = 1;
    $input['component_graphiccard'] = 1;
    $input['component_soundcard'] = 1;
    $input['component_drive'] = 1;
    $input['component_networkdrive'] = 1;
    $input['component_control'] = 1;
    $input['states_id_default'] = 0;
    $input['location'] = 0;
    $input['group'] = 0;
    $input['component_networkcardvirtual'] = 1;
    $config->addValues($input, FALSE);
    // Add new config values if not added
    $input = $config->initConfigModule(TRUE);
    foreach ($input as $name => $value) {
        $a_conf = $config->find("`type`='" . $name . "'");
        if (count($a_conf) == 0) {
            $config->add(array('type' => $name, 'value' => $value));
        }
    }
    $migration->displayMessage("Clean printers");
    /*
     * Remove / at the end of printers (bugs in older versions of agents.
     */
    $printer = new Printer();
    $query = "SELECT * FROM `glpi_printers`\n         WHERE `serial` LIKE '%/' ";
    $result = $DB->query($query);
    while ($data = $DB->fetch_array($result)) {
        $cleanSerial = preg_replace('/\\/$/', '', $data['serial']);
        $querynb = "SELECT * FROM `glpi_printers`\n            WHERE `serial`='" . $cleanSerial . "'\n            LIMIT 1";
        $resultnb = $DB->query($querynb);
        if ($DB->numrows($resultnb) == '0') {
            $input = array();
            $input['id'] = $data['id'];
            $input["serial"] = $cleanSerial;
            $printer->update($input);
        }
    }
    /*
     * Update blacklist
     */
    $input = array();
    $input['03000200-0400-0500-0006-000700080009'] = '2';
    $input['6AB5B300-538D-1014-9FB5-B0684D007B53'] = '2';
    $input['01010101-0101-0101-0101-010101010101'] = '2';
    $input['20:41:53:59:4e:ff'] = '3';
    $input['02:00:4e:43:50:49'] = '3';
    $input['e2:e6:16:20:0a:35'] = '3';
    $input['d2:0a:2d:a0:04:be'] = '3';
    $input['00:a0:c6:00:00:00'] = '3';
    $input['d2:6b:25:2f:2c:e7'] = '3';
    $input['33:50:6f:45:30:30'] = '3';
    $input['0a:00:27:00:00:00'] = '3';
    $input['00:50:56:C0:00:01'] = '3';
    $input['00:50:56:C0:00:02'] = '3';
    $input['00:50:56:C0:00:03'] = '3';
    $input['00:50:56:C0:00:04'] = '3';
    $input['00:50:56:C0:00:08'] = '3';
    $input['FE:FF:FF:FF:FF:FF'] = '3';
    $input['00:00:00:00:00:00'] = '3';
    $input['00:0b:ca:fe:00:00'] = '3';
    $input['02:80:37:EC:02:00'] = '3';
    $input['MB-1234567890'] = '1';
    $input['Not Specified'] = '1';
    $input['OEM_Serial'] = '1';
    $input['SystemSerialNumb'] = '1';
    $input['Not'] = '2';
    foreach ($input as $value => $type) {
        $query = "SELECT * FROM `glpi_plugin_fusioninventory_inventorycomputerblacklists`\n         WHERE `plugin_fusioninventory_criterium_id`='" . $type . "'\n          AND `value`='" . $value . "'";
        $result = $DB->query($query);
        if ($DB->numrows($result) == '0') {
            $query = "INSERT INTO `glpi_plugin_fusioninventory_inventorycomputerblacklists`\n            (`plugin_fusioninventory_criterium_id`, `value`) VALUES\n            ( '" . $type . "', '" . $value . "')";
            $DB->query($query);
        }
    }
    $migration->displayMessage("Add Crontasks");
    /*
     * Add Crontask if not exist
     */
    $crontask = new CronTask();
    if ($crontask->getFromDBbyName('PluginFusioninventoryTaskjob', 'taskscheduler')) {
        $crontask->fields['itemtype'] = 'PluginFusioninventoryTask';
        $crontask->updateInDB(array('itemtype'));
    }
    if (!$crontask->getFromDBbyName('PluginFusioninventoryTask', 'taskscheduler')) {
        CronTask::Register('PluginFusioninventoryTask', 'taskscheduler', '60', array('mode' => 2, 'allowmode' => 3, 'logs_lifetime' => 30));
    }
    if ($crontask->getFromDBbyName('PluginFusioninventoryTaskjobstate', 'cleantaskjob') and $crontask->getFromDBbyName('PluginFusioninventoryTaskjobstatus', 'cleantaskjob')) {
        $crontask->getFromDBbyName('PluginFusioninventoryTaskjobstatus', 'cleantaskjob');
        $crontask->delete($crontask->fields);
    }
    if ($crontask->getFromDBbyName('PluginFusioninventoryTaskjobstatus', 'cleantaskjob')) {
        $query = "UPDATE `glpi_crontasks` SET `itemtype`='PluginFusioninventoryTaskjobstate'\n         WHERE `itemtype`='PluginFusioninventoryTaskjobstatus'";
        $DB->query($query);
    }
    if (!$crontask->getFromDBbyName('PluginFusioninventoryTaskjobstate', 'cleantaskjob')) {
        Crontask::Register('PluginFusioninventoryTaskjobstate', 'cleantaskjob', 3600 * 24, array('mode' => 2, 'allowmode' => 3, 'logs_lifetime' => 30));
    }
    if ($crontask->getFromDBbyName('PluginFusinvsnmpNetworkPortLog', 'cleannetworkportlogs')) {
        $crontask->delete($crontask->fields);
    }
    if (!$crontask->getFromDBbyName('PluginFusioninventoryNetworkPortLog', 'cleannetworkportlogs')) {
        Crontask::Register('PluginFusioninventoryNetworkPortLog', 'cleannetworkportlogs', 3600 * 24, array('mode' => 2, 'allowmode' => 3, 'logs_lifetime' => 30));
    }
    if ($crontask->getFromDBbyName('PluginFusioninventoryConfigurationManagement', 'checkdevices')) {
        $crontask->delete($crontask->fields);
    }
    if (!$crontask->getFromDBbyName('PluginFusioninventoryAgent', 'cleanoldagents')) {
        Crontask::Register('PluginFusioninventoryAgent', 'cleanoldagents', 86400, array('mode' => 2, 'allowmode' => 3, 'logs_lifetime' => 30, 'hourmin' => 22, 'hourmax' => 6, 'comment' => 'Clean agents not contacted since xxx days'));
    }
    /*
     * Update task's agents list from dynamic group periodically in order to automatically target new
     * computer.
     */
    if (!$crontask->getFromDBbyName('PluginFusioninventoryTaskjob', 'updatedynamictasks')) {
        CronTask::Register('PluginFusioninventoryTaskjob', 'updatedynamictasks', '60', array('mode' => 2, 'allowmode' => 3, 'logs_lifetime' => 30, 'state' => 0));
    }
    if (!$crontask->getFromDBbyName('PluginFusioninventoryAgentWakeup', 'wakeupAgents')) {
        Crontask::Register('PluginFusioninventoryAgentWakeup', 'wakeupAgents', 120, array('mode' => 2, 'allowmode' => 3, 'logs_lifetime' => 30, 'comment' => 'Wake agents ups'));
    }
    /**
     * Add field to manage which group can be refreshed by updatedynamictasks crontask
     */
    if (!FieldExists('glpi_plugin_fusioninventory_deploygroups_dynamicdatas', 'can_update_group')) {
        $migration->addField('glpi_plugin_fusioninventory_deploygroups_dynamicdatas', 'can_update_group', 'bool');
        $migration->addKey('glpi_plugin_fusioninventory_deploygroups_dynamicdatas', 'can_update_group');
        $migration->migrationOneTable('glpi_plugin_fusioninventory_deploygroups_dynamicdatas');
    }
    //   $pfIgnoredimportdevice = new PluginFusioninventoryIgnoredimportdevice();
    //   $pfIgnoredimportdevice->install();
    //Change static & dynamic structure to fit the GLPI framework
    $migration->changeField('glpi_plugin_fusioninventory_deploygroups_dynamicdatas', 'groups_id', 'plugin_fusioninventory_deploygroups_id', 'integer');
    $migration->migrationOneTable('glpi_plugin_fusioninventory_deploygroups_dynamicdatas');
    $migration->changeField('glpi_plugin_fusioninventory_deploygroups_staticdatas', 'groups_id', 'plugin_fusioninventory_deploygroups_id', 'integer');
    $migration->migrationOneTable('glpi_plugin_fusioninventory_deploygroups_staticdatas');
    // Delete data in glpi_logs(agent problem => ticket http://forge.fusioninventory.org/issues/1546)
    // ** Token
    $query = "DELETE FROM `glpi_logs`\n      WHERE `itemtype`='PluginFusioninventoryAgent'\n         AND `id_search_option`='9'";
    $DB->query($query);
    // ** Last contact
    $query = "DELETE FROM `glpi_logs`\n      WHERE `itemtype`='PluginFusioninventoryAgent'\n         AND `id_search_option`='4'";
    $DB->query($query);
    // ** Version
    $query = "DELETE FROM `glpi_logs`\n      WHERE `itemtype`='PluginFusioninventoryAgent'\n         AND `id_search_option`='8'\n         AND `old_value`=`new_value`";
    $DB->query($query);
    /*
     * Manage devices with is_dynamic
     */
    $query = "SELECT * FROM `glpi_plugin_fusioninventory_networkequipments`";
    $result = $DB->query($query);
    while ($data = $DB->fetch_array($result)) {
        $DB->query("UPDATE `glpi_networkequipments` SET `is_dynamic`='1'\n                        WHERE `id`='" . $data['networkequipments_id'] . "'");
    }
    $query = "SELECT * FROM `glpi_plugin_fusioninventory_inventorycomputercomputers`";
    $result = $DB->query($query);
    while ($data = $DB->fetch_array($result)) {
        $DB->query("UPDATE `glpi_computers` SET `is_dynamic`='1'\n                        WHERE `id`='" . $data['computers_id'] . "'");
    }
    $query = "SELECT * FROM `glpi_plugin_fusioninventory_printers`";
    $result = $DB->query($query);
    while ($data = $DB->fetch_array($result)) {
        $DB->query("UPDATE `glpi_printers` SET `is_dynamic`='1'\n                        WHERE `id`='" . $data['printers_id'] . "'");
    }
    // Update networkports types
    $pfNetworkporttype = new PluginFusioninventoryNetworkporttype();
    $pfNetworkporttype->init();
    if (TableExists('glpi_plugin_fusioninventory_profiles')) {
        //Migrate rights to the new system introduction in GLPI 0.85
        PluginFusioninventoryProfile::migrateProfiles();
        //Drop old table
        $migration->dropTable('glpi_plugin_fusioninventory_profiles');
    }
    //Create first access to the current profile is needed
    if (isset($_SESSION['glpiactiveprofile'])) {
        PluginFusioninventoryProfile::createFirstAccess($_SESSION['glpiactiveprofile']['id']);
    }
    // Define lastup field of fusion networkports
    $query = "SELECT * FROM `glpi_plugin_fusioninventory_mappings`\n      WHERE `name`='ifstatus'\n      LIMIT 1";
    $result = $DB->query($query);
    while ($data = $DB->fetch_array($result)) {
        $query_np = "SELECT * FROM `glpi_plugin_fusioninventory_networkports`";
        $result_np = $DB->query($query_np);
        while ($data_np = $DB->fetch_array($result_np)) {
            $query_nplog = "SELECT * FROM `glpi_plugin_fusioninventory_networkportlogs`\n            WHERE `networkports_id`='" . $data_np['networkports_id'] . "'\n               AND `plugin_fusioninventory_mappings_id`='" . $data['id'] . "'\n            ORDER BY `date_mod` DESC\n            LIMIT 1";
            $result_nplog = $DB->query($query_nplog);
            while ($data_nplog = $DB->fetch_array($result_nplog)) {
                $DB->query("UPDATE `glpi_plugin_fusioninventory_networkports`\n               SET `lastup`='" . $data_nplog['date_mod'] . "'\n               WHERE `id`='" . $data_np['id'] . "'");
            }
        }
    }
    //Migrate search params for dynamic groups
    doDynamicDataSearchParamsMigration();
}
 /**
  * Prepare input datas for updating the item
  *
  * @see CommonDBTM::prepareInputForUpdate()
  *
  * @param $input array of datas used to update the item
  *
  * @return the modified $input array
  **/
 function prepareInputForUpdate($input)
 {
     global $CFG_GLPI;
     // Update only an item
     if (isset($input['context'])) {
         return $input;
     }
     // Process configuration for plugins
     if (!empty($input['config_context'])) {
         $config_context = $input['config_context'];
         unset($input['id']);
         unset($input['_glpi_csrf_token']);
         unset($input['update']);
         unset($input['config_context']);
         if (!empty($input['config_class']) && class_exists($input['config_class']) && method_exists($input['config_class'], 'configUpdate')) {
             $config_method = $input['config_class'] . '::configUpdate';
             unset($input['config_class']);
             $input = call_user_func($config_method, $input);
         }
         $this->setConfigurationValues($config_context, $input);
         return false;
     }
     if (isset($input['allow_search_view']) && !$input['allow_search_view']) {
         // Global search need "view"
         $input['allow_search_global'] = 0;
     }
     if (isset($input["smtp_passwd"])) {
         if (empty($input["smtp_passwd"])) {
             unset($input["smtp_passwd"]);
         } else {
             $input["smtp_passwd"] = Toolbox::encrypt(stripslashes($input["smtp_passwd"]), GLPIKEY);
         }
     }
     if (isset($input["_blank_smtp_passwd"]) && $input["_blank_smtp_passwd"]) {
         $input['smtp_passwd'] = '';
     }
     if (isset($input["proxy_passwd"])) {
         if (empty($input["proxy_passwd"])) {
             unset($input["proxy_passwd"]);
         } else {
             $input["proxy_passwd"] = Toolbox::encrypt(stripslashes($input["proxy_passwd"]), GLPIKEY);
         }
     }
     if (isset($input["_blank_proxy_passwd"]) && $input["_blank_proxy_passwd"]) {
         $input['proxy_passwd'] = '';
     }
     // Manage DB Slave process
     if (isset($input['_dbslave_status'])) {
         $already_active = DBConnection::isDBSlaveActive();
         if ($input['_dbslave_status']) {
             DBConnection::changeCronTaskStatus(true);
             if (!$already_active) {
                 // Activate Slave from the "system" tab
                 DBConnection::createDBSlaveConfig();
             } else {
                 if (isset($input["_dbreplicate_dbhost"])) {
                     // Change parameter from the "replicate" tab
                     DBConnection::saveDBSlaveConf($input["_dbreplicate_dbhost"], $input["_dbreplicate_dbuser"], $input["_dbreplicate_dbpassword"], $input["_dbreplicate_dbdefault"]);
                 }
             }
         }
         if (!$input['_dbslave_status'] && $already_active) {
             DBConnection::deleteDBSlaveConfig();
             DBConnection::changeCronTaskStatus(false);
         }
     }
     // Matrix for Impact / Urgence / Priority
     if (isset($input['_matrix'])) {
         $tab = array();
         for ($urgency = 1; $urgency <= 5; $urgency++) {
             for ($impact = 1; $impact <= 5; $impact++) {
                 $priority = $input["_matrix_{$urgency}_{$impact}"];
                 $tab[$urgency][$impact] = $priority;
             }
         }
         $input['priority_matrix'] = exportArrayToDB($tab);
         $input['urgency_mask'] = 0;
         $input['impact_mask'] = 0;
         for ($i = 1; $i <= 5; $i++) {
             if ($input["_urgency_{$i}"]) {
                 $input['urgency_mask'] += 1 << $i;
             }
             if ($input["_impact_{$i}"]) {
                 $input['impact_mask'] += 1 << $i;
             }
         }
     }
     // Beware : with new management system, we must update each value
     unset($input['id']);
     unset($input['_glpi_csrf_token']);
     unset($input['update']);
     // Add skipMaintenance if maintenance mode update
     if (isset($input['maintenance_mode']) && $input['maintenance_mode']) {
         $_SESSION['glpiskipMaintenance'] = 1;
         $url = $CFG_GLPI['root_doc'] . "/index.php?skipMaintenance=1";
         Session::addMessageAfterRedirect(sprintf(__('Maintenance mode activated. Backdoor using: %s'), "<a href='{$url}'>{$url}</a>"), false, WARNING);
     }
     $this->setConfigurationValues('core', $input);
     return false;
 }