addslashes_deep() static public méthode

Add slash for variable & array
static public addslashes_deep ( $value ) : addslashes
$value array or string: value to add slashes (array or string)
Résultat addslashes value
 public function testLog()
 {
     global $DB;
     $DB->connect();
     $pfFormatconvert = new PluginFusioninventoryFormatconvert();
     $computer = new Computer();
     $pfiComputerLib = new PluginFusioninventoryInventoryComputerLib();
     $date = date('Y-m-d H:i:s');
     $_SESSION["plugin_fusioninventory_entity"] = 0;
     $_SESSION['glpiactiveentities_string'] = 0;
     $_SESSION['glpishowallentities'] = 1;
     $_SESSION["glpiname"] = 'Plugin_FusionInventory';
     $this->a_inventory = array('fusioninventorycomputer' => array('winowner' => 'test', 'wincompany' => 'siprossii', 'operatingsystem_installationdate' => '2012-10-16 08:12:56', 'last_fusioninventory_update' => $date), 'soundcard' => array(), 'graphiccard' => array(), 'controller' => array(), 'processor' => array(), 'computerdisk' => array(), 'memory' => array(), 'monitor' => array(), 'printer' => array(), 'peripheral' => array(), 'networkport' => array(), 'SOFTWARES' => array(), 'harddrive' => array(), 'virtualmachine' => array(), 'antivirus' => array(), 'storage' => array(), 'licenseinfo' => array(), 'networkcard' => array(), 'drive' => array(), 'batteries' => array(), 'itemtype' => 'Computer');
     $this->a_inventory['Computer'] = array('name' => 'pc', 'users_id' => 0, 'operatingsystems_id' => 'freebsd', 'operatingsystemversions_id' => '9.1-RELEASE', 'uuid' => '68405E00-E5BE-11DF-801C-B05981201220', 'domains_id' => 'mydomain.local', 'os_licenseid' => '', 'os_license_number' => '', 'operatingsystemservicepacks_id' => 'GENERIC ()root@farrell.cse.buffalo.edu', 'manufacturers_id' => '', 'computermodels_id' => '', 'serial' => 'XB63J7D', 'computertypes_id' => 'Notebook', 'is_dynamic' => 1, 'contact' => 'ddurieux');
     $this->a_inventory['processor'] = array(array('nbcores' => 2, 'manufacturers_id' => 'Intel Corporation', 'designation' => 'Core i3', 'frequence' => 2400, 'nbthreads' => 2, 'serial' => '', 'frequency' => 2400, 'frequency_default' => 2400), array('nbcores' => 2, 'manufacturers_id' => 'Intel Corporation', 'designation' => 'Core i3', 'frequence' => 2400, 'nbthreads' => 2, 'serial' => '', 'frequency' => 2400, 'frequency_default' => 2400), array('nbcores' => 2, 'manufacturers_id' => 'Intel Corporation', 'designation' => 'Core i3', 'frequence' => 2400, 'nbthreads' => 2, 'serial' => '', 'frequency' => 2400, 'frequency_default' => 2400), array('nbcores' => 2, 'manufacturers_id' => 'Intel Corporation', 'designation' => 'Core i3', 'frequence' => 2400, 'nbthreads' => 2, 'serial' => '', 'frequency' => 2400, 'frequency_default' => 2400));
     $this->a_inventory['memory'] = array(array('size' => 2048, 'serial' => '98F6FF18', 'frequence' => '1067 MHz', 'devicememorytypes_id' => 'DDR3', 'designation' => 'DDR3 - SODIMM (None)', 'busID' => 1), array('size' => 2048, 'serial' => '95F1833E', 'frequence' => '1067 MHz', 'devicememorytypes_id' => 'DDR3', 'designation' => 'DDR3 - SODIMM (None)', 'busID' => 2));
     $this->a_inventory['monitor'] = array(array('name' => '', 'serial' => '', 'manufacturers_id' => ''));
     $this->a_inventory['networkport'] = array('em0-00:23:18:cf:0d:93' => array('name' => 'em0', 'netmask' => '255.255.255.0', 'subnet' => '192.168.30.0', 'mac' => '00:23:18:cf:0d:93', 'instantiation_type' => 'NetworkPortEthernet', 'virtualdev' => 0, 'ssid' => '', 'gateway' => '', 'dhcpserver' => '', 'logical_number' => 0, 'ipaddress' => array('192.168.30.198')), 'lo0-' => array('name' => 'lo0', 'virtualdev' => 1, 'mac' => '', 'instantiation_type' => 'NetworkPortLocal', 'subnet' => '', 'ssid' => '', 'gateway' => '', 'netmask' => '', 'dhcpserver' => '', 'logical_number' => 1, 'ipaddress' => array('::1', 'fe80::1', '127.0.0.1')));
     $this->a_inventory['software'] = array('gentiumbasic$$$$110$$$$1$$$$0' => array('name' => 'GentiumBasic', 'version' => 110, 'manufacturers_id' => 1, 'entities_id' => 0, 'is_template_computer' => 0, 'is_deleted_computer' => 0, 'is_dynamic' => 1), 'imagemagick$$$$6.8.0.7_1$$$$2$$$$0' => array('name' => 'ImageMagick', 'version' => '6.8.0.7_1', 'manufacturers_id' => 2, 'entities_id' => 0, 'is_template_computer' => 0, 'is_deleted_computer' => 0, 'is_dynamic' => 1), 'orbit2$$$$2.14.19$$$$3$$$$0' => array('name' => 'ORBit2', 'version' => '2.14.19', 'manufacturers_id' => 3, 'entities_id' => 0, 'is_template_computer' => 0, 'is_deleted_computer' => 0, 'is_dynamic' => 1));
     $this->a_inventory = $pfFormatconvert->replaceids($this->a_inventory);
     $serialized = gzcompress(serialize($this->a_inventory));
     $this->a_inventory['fusioninventorycomputer']['serialized_inventory'] = Toolbox::addslashes_deep($serialized);
     $computer->add(array('serial' => 'XB63J7D', 'entities_id' => 0));
     // truncate glpi_logs
     $DB->query('TRUNCATE TABLE `glpi_logs`;');
     $this->assertEquals(0, countElementsInTable('glpi_logs'), "Log must be empty (truncate)");
     $_SESSION['glpiactive_entity'] = 0;
     $pfiComputerLib->updateComputer($this->a_inventory, 1, TRUE);
     $a_logs = getAllDatasFromTable('glpi_logs');
     foreach ($a_logs as $id => $data) {
         unset($data['date_mod']);
         $a_logs[$id] = $data;
     }
     $a_reference = array(1 => array('id' => 1, 'itemtype' => 'Software', 'items_id' => 1, 'itemtype_link' => '', 'linked_action' => 20, 'user_name' => 'Plugin_FusionInventory', 'id_search_option' => 0, 'old_value' => '', 'new_value' => ''), 2 => array('id' => 2, 'itemtype' => 'Software', 'items_id' => 2, 'itemtype_link' => '', 'linked_action' => 20, 'user_name' => 'Plugin_FusionInventory', 'id_search_option' => 0, 'old_value' => '', 'new_value' => ''), 3 => array('id' => 3, 'itemtype' => 'Software', 'items_id' => 3, 'itemtype_link' => '', 'linked_action' => 20, 'user_name' => 'Plugin_FusionInventory', 'id_search_option' => 0, 'old_value' => '', 'new_value' => ''), 4 => array('id' => 4, 'itemtype' => 'SoftwareVersion', 'items_id' => 1, 'itemtype_link' => '', 'linked_action' => 20, 'user_name' => 'Plugin_FusionInventory', 'id_search_option' => 0, 'old_value' => '', 'new_value' => ''), 5 => array('id' => 5, 'itemtype' => 'SoftwareVersion', 'items_id' => 2, 'itemtype_link' => '', 'linked_action' => 20, 'user_name' => 'Plugin_FusionInventory', 'id_search_option' => 0, 'old_value' => '', 'new_value' => ''), 6 => array('id' => 6, 'itemtype' => 'SoftwareVersion', 'items_id' => 3, 'itemtype_link' => '', 'linked_action' => 20, 'user_name' => 'Plugin_FusionInventory', 'id_search_option' => 0, 'old_value' => '', 'new_value' => ''));
     $this->assertEquals($a_reference, $a_logs, "Log must be 6 " . print_r($a_logs, true));
     $DB->query('TRUNCATE `glpi_logs`');
     // Update a second time and must not have any new lines in glpi_logs
     $pfiComputerLib->updateComputer($this->a_inventory, 1, FALSE);
     $a_logs = getAllDatasFromTable('glpi_logs');
     $a_reference = array();
     $this->assertEquals($a_reference, $a_logs, "Log may be empty at second update " . print_r($a_logs, true));
     // * Modify: contact
     // * remove a processor
     // * Remove a software
     $this->a_inventory['Computer']['contact'] = 'root';
     unset($this->a_inventory['processor'][3]);
     unset($this->a_inventory['software']['orbit2$$$$2.14.19$$$$3$$$$0']);
     $DB->query('TRUNCATE `glpi_logs`');
     $pfiComputerLib->updateComputer($this->a_inventory, 1, FALSE);
     $a_logs = getAllDatasFromTable('glpi_logs');
     foreach ($a_logs as $id => $data) {
         unset($data['date_mod']);
         $a_logs[$id] = $data;
     }
     $a_reference = array(1 => array('id' => '1', 'itemtype' => 'Computer', 'items_id' => '1', 'itemtype_link' => '', 'linked_action' => '0', 'user_name' => '', 'id_search_option' => '7', 'old_value' => 'ddurieux', 'new_value' => 'root'), 2 => array('id' => '2', 'itemtype' => 'Computer', 'items_id' => '1', 'itemtype_link' => 'DeviceProcessor', 'linked_action' => '3', 'user_name' => '', 'id_search_option' => '0', 'old_value' => 'Core i3 (1)', 'new_value' => ''), 3 => array('id' => '3', 'itemtype' => 'Computer', 'items_id' => '1', 'itemtype_link' => 'SoftwareVersion', 'linked_action' => '5', 'user_name' => 'Plugin_FusionInventory', 'id_search_option' => '0', 'old_value' => 'ORBit2 - 2.14.19 (3)', 'new_value' => ''), 4 => array('id' => '4', 'itemtype' => 'SoftwareVersion', 'items_id' => '3', 'itemtype_link' => 'Computer', 'linked_action' => '5', 'user_name' => 'Plugin_FusionInventory', 'id_search_option' => '0', 'old_value' => 'pc (1)', 'new_value' => ''));
     $this->assertEquals($a_reference, $a_logs, "May have 5 logs (update contact, remove processor\n         and remove a software)");
 }
 /**
  * Function to update Printer
  *
  * @param array $a_inventory data fron agent inventory
  * @param id $items_id id of the printer
  *
  * @return nothing
  */
 function updatePrinter($a_inventory, $items_id)
 {
     global $DB;
     $printer = new Printer();
     $pfPrinter = new PluginFusioninventoryPrinter();
     $printer->getFromDB($items_id);
     if (!isset($_SESSION['glpiactiveentities_string'])) {
         $_SESSION['glpiactiveentities_string'] = $printer->fields['entities_id'];
     }
     if (!isset($_SESSION['glpiactiveentities'])) {
         $_SESSION['glpiactiveentities'] = array($printer->fields['entities_id']);
     }
     if (!isset($_SESSION['glpiactive_entity'])) {
         $_SESSION['glpiactive_entity'] = $printer->fields['entities_id'];
     }
     // * Printer
     $db_printer = $printer->fields;
     $a_lockable = PluginFusioninventoryLock::getLockFields('glpi_printers', $items_id);
     $a_ret = PluginFusioninventoryToolbox::checkLock($a_inventory['Printer'], $db_printer, $a_lockable);
     $a_inventory['Printer'] = $a_ret[0];
     $input = $a_inventory['Printer'];
     $input['id'] = $items_id;
     $printer->update($input);
     // * Printer fusion (ext)
     $db_printer = array();
     $query = "SELECT *\n            FROM `" . getTableForItemType("PluginFusioninventoryPrinter") . "`\n            WHERE `printers_id` = '{$items_id}'";
     $result = $DB->query($query);
     while ($data = $DB->fetch_assoc($result)) {
         foreach ($data as $key => $value) {
             $db_printer[$key] = Toolbox::addslashes_deep($value);
         }
     }
     if (count($db_printer) == '0') {
         // Add
         $a_inventory['PluginFusioninventoryPrinter']['printers_id'] = $items_id;
         $pfPrinter->add($a_inventory['PluginFusioninventoryPrinter']);
     } else {
         // Update
         $idtmp = $db_printer['id'];
         unset($db_printer['id']);
         unset($db_printer['printers_id']);
         unset($db_printer['plugin_fusioninventory_configsecurities_id']);
         $a_ret = PluginFusioninventoryToolbox::checkLock($a_inventory['PluginFusioninventoryPrinter'], $db_printer);
         $a_inventory['PluginFusioninventoryPrinter'] = $a_ret[0];
         $input = $a_inventory['PluginFusioninventoryPrinter'];
         $input['id'] = $idtmp;
         $pfPrinter->update($input);
     }
     // * Ports
     $this->importPorts($a_inventory, $items_id);
     // Page counters
     $this->importPageCounters($a_inventory['pagecounters'], $items_id);
     // Cartridges
     $this->importCartridges($a_inventory['cartridge'], $items_id);
 }
 static function postClone(NotificationTemplate $clone, $oldid)
 {
     global $DB;
     $trad = new NotificationTemplateTranslation();
     $fkey = getForeignKeyFieldForTable($clone->getTable());
     $crit = array($fkey => $oldid);
     foreach ($DB->request($trad->getTable(), $crit) as $data) {
         unset($data['id']);
         $data[$fkey] = $clone->getID();
         $trad->add(Toolbox::addslashes_deep($data));
     }
 }
 static function install(Migration $migration)
 {
     global $DB;
     $table = getTableForItemType(__CLASS__);
     if (!TableExists($table)) {
         $migration->displayMessage("Installing {$table}");
         $query = "CREATE TABLE IF NOT EXISTS `glpi_plugin_order_billstates` (\n                 `id` int(11) NOT NULL AUTO_INCREMENT,\n                 `name` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,\n                 `comment` text COLLATE utf8_unicode_ci,\n                 PRIMARY KEY (`id`),\n                 KEY `name` (`name`)\n               ) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;";
         $DB->query($query) or die($DB->error());
     }
     if (countElementsInTable($table) < 2) {
         $state = new self();
         foreach (array(self::PAID => __("Paid", "order"), self::NOTPAID => __("Not paid", "order")) as $id => $label) {
             $state->add(array('id' => $id, 'name' => Toolbox::addslashes_deep($label)));
         }
     }
 }
 static function install(Migration $migration)
 {
     global $DB;
     $table = getTableForItemType(__CLASS__);
     //1.2.0
     $DB->query("DROP TABLE IF EXISTS `glpi_dropdown_plugin_order_status`;");
     if (!TableExists($table)) {
         $migration->displayMessage("Installing {$table}");
         $query = "CREATE TABLE IF NOT EXISTS `glpi_plugin_order_orderstates` (\n                  `id` int(11) NOT NULL auto_increment,\n                  `name` varchar(255) collate utf8_unicode_ci default NULL,\n                  `comment` text collate utf8_unicode_ci,\n                  PRIMARY KEY  (`id`),\n                  KEY `name` (`name`)\n               ) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;";
         $DB->query($query) or die($DB->error());
     }
     $state = new self();
     foreach (array(1 => __("Draft", "order"), 2 => __("Waiting for approval", "order"), 3 => __("Validated", "order"), 4 => __("Being delivered", "order"), 5 => __("Delivered", "order"), 6 => __("Canceled", "order"), 7 => __("Paid", "order")) as $id => $label) {
         if (!countElementsInTable($table, "`id`='{$id}'")) {
             $state->add(array('id' => $id, 'name' => Toolbox::addslashes_deep($label)));
         }
     }
 }
Exemple #6
0
 static function postClone(Rule $clone, $oldid)
 {
     global $DB;
     $fkey = getForeignKeyFieldForTable($clone->getTable());
     $crit = array($fkey => $oldid);
     $criteria = new RuleCriteria();
     foreach ($DB->request($criteria->getTable(), $crit) as $data) {
         unset($data['id']);
         $data[$fkey] = $clone->getID();
         $criteria->add(Toolbox::addslashes_deep($data));
     }
     $action = new RuleAction();
     foreach ($DB->request($action->getTable(), $crit) as $data) {
         unset($data['id']);
         $data[$fkey] = $clone->getID();
         $action->add(Toolbox::addslashes_deep($data));
     }
 }
 static function cloneItem($itemtype, $oldid, $newid)
 {
     global $DB;
     foreach (self::getDeviceTypes() as $link_type) {
         $query = "SELECT *\n                   FROM `" . $link_type::getTable() . "`\n                   WHERE `itemtype` = '{$itemtype}'\n                         AND `items_id` = '{$oldid}'";
         $result_iterator = $DB->request($query);
         if ($result_iterator->numrows() > 0) {
             $link = new $link_type();
             foreach ($result_iterator as $data) {
                 unset($data['id']);
                 $data['items_id'] = $newid;
                 $data['_itemtype'] = $itemtype;
                 $data['_no_history'] = true;
                 $data = Toolbox::addslashes_deep($data);
                 $link->add($data);
             }
         }
     }
 }
 static function transfer($ID, $entity)
 {
     global $DB;
     if ($ID > 0) {
         // Not already transfer
         // Search init item
         foreach ($DB->request('glpi_plugin_racks_racktypes', array('id' => $ID)) as $data) {
             $data = Toolbox::addslashes_deep($data);
             $input['name'] = $data['name'];
             $input['entities_id'] = $entity;
             $temp = new self();
             $newID = $temp->getID($input);
             if ($newID < 0) {
                 $newID = $temp->import($input);
             }
             return $newID;
         }
     }
     return 0;
 }
 /**
  * During resource or employment transfer
  *
  * @static
  * @param $ID
  * @param $entity
  * @return ID|int|the
  */
 static function transfer($ID, $entity)
 {
     global $DB;
     if ($ID > 0) {
         // Not already transfer
         // Search init item
         $query = "SELECT *\n                   FROM `glpi_plugin_resources_professions`\n                   WHERE `id` = '{$ID}'";
         if ($result = $DB->query($query)) {
             if ($DB->numrows($result)) {
                 $data = $DB->fetch_assoc($result);
                 $data = Toolbox::addslashes_deep($data);
                 $input['name'] = $data['name'];
                 $input['entities_id'] = $entity;
                 $temp = new self();
                 $newID = $temp->getID($input);
                 if ($newID < 0) {
                     $newID = $temp->import($input);
                 }
                 //transfer of the linked line
                 $line = PluginResourcesProfessionLine::transfer($temp->fields["plugin_resources_professionlines_id"], $entity);
                 if ($line > 0) {
                     $values["id"] = $newID;
                     $values["plugin_resources_professionlines_id"] = $line;
                     $temp->update($values);
                 }
                 //transfer of the linked category
                 $category = PluginResourcesProfessionCategory::transfer($temp->fields["plugin_resources_professioncategories_id"], $entity);
                 if ($category > 0) {
                     $values["id"] = $newID;
                     $values["plugin_resources_professioncategories_id"] = $category;
                     $temp->update($values);
                 }
                 return $newID;
             }
         }
     }
     return 0;
 }
 static function transfer($ID, $entity)
 {
     global $DB;
     if ($ID > 0) {
         // Not already transfer
         // Search init item
         $query = "SELECT *\n                   FROM `glpi_plugin_webapplications_webapplicationtypes`\n                   WHERE `id` = '{$ID}'";
         if ($result = $DB->query($query)) {
             if ($DB->numrows($result)) {
                 $data = $DB->fetch_assoc($result);
                 $data = Toolbox::addslashes_deep($data);
                 $input['name'] = $data['name'];
                 $input['entities_id'] = $entity;
                 $temp = new self();
                 $newID = $temp->getID($input);
                 if ($newID < 0) {
                     $newID = $temp->import($input);
                 }
                 return $newID;
             }
         }
     }
     return 0;
 }
 static function transfer($ID, $entity)
 {
     global $DB;
     $simcardVoltage = new self();
     if ($ID > 0) {
         // Not already transfer
         // Search init item
         $query = "SELECT *\n                   FROM `" . $simcardVoltage->getTable() . "`\n                   WHERE `id` = '{$ID}'";
         if ($result = $DB->query($query)) {
             if ($DB->numrows($result)) {
                 $data = $DB->fetch_assoc($result);
                 $data = Toolbox::addslashes_deep($data);
                 $input['name'] = $data['name'];
                 $input['entities_id'] = $entity;
                 $newID = $simcardVoltage->getID($input);
                 if ($newID < 0) {
                     $newID = $simcardVoltage->import($input);
                 }
                 return $newID;
             }
         }
     }
     return 0;
 }
Exemple #12
0
 /**
  * Get confirmation on button or link before action
  *
  * @since version 0.85
  *
  * @param $string             string   to display or array of string for using multilines
  * @param $additionalactions  string   additional actions to do on success confirmation
  *                                     (default '')
  *
  * @return confirmation script
  **/
 static function getConfirmationOnActionScript($string, $additionalactions = '')
 {
     if (!is_array($string)) {
         $string = array($string);
     }
     $string = Toolbox::addslashes_deep($string);
     $additionalactions = trim($additionalactions);
     $out = "";
     $multiple = false;
     $close_string = '';
     // Manage multiple confirmation
     foreach ($string as $tab) {
         if (is_array($tab)) {
             $multiple = true;
             $out .= "if (window.confirm('";
             $out .= implode('\\n', $tab);
             $out .= "')){ ";
             $close_string .= "return true;} else { return false;}";
         }
     }
     // manage simple confirmation
     if (!$multiple) {
         $out .= "if (window.confirm('";
         $out .= implode('\\n', $string);
         $out .= "')){ ";
         $close_string .= "return true;} else { return false;}";
     }
     $out .= $additionalactions . (substr($additionalactions, -1) != ';' ? ';' : '') . $close_string;
     return $out;
 }
 function prepareInputForAdd($input)
 {
     global $CFG_GLPI;
     // Set default status to avoid notice
     if (!isset($input["status"])) {
         $input["status"] = self::INCOMING;
     }
     if (!isset($input["urgency"]) || !($CFG_GLPI['urgency_mask'] & 1 << $input["urgency"])) {
         $input["urgency"] = 3;
     }
     if (!isset($input["impact"]) || !($CFG_GLPI['impact_mask'] & 1 << $input["impact"])) {
         $input["impact"] = 3;
     }
     if (!isset($input["priority"])) {
         $input["priority"] = $this->computePriority($input["urgency"], $input["impact"]);
     }
     // set last updater if interactive user
     if (!Session::isCron() && ($last_updater = Session::getLoginUserID(true))) {
         $input['users_id_lastupdater'] = $last_updater;
     }
     // No Auto set Import for external source
     if (!isset($input['_auto_import'])) {
         if (!isset($input["_users_id_requester"])) {
             if ($uid = Session::getLoginUserID()) {
                 $input["_users_id_requester"] = $uid;
             }
         }
     }
     // No Auto set Import for external source
     if (($uid = Session::getLoginUserID()) && !isset($input['_auto_import'])) {
         $input["users_id_recipient"] = $uid;
     } else {
         if (isset($input["_users_id_requester"]) && $input["_users_id_requester"]) {
             $input["users_id_recipient"] = $input["_users_id_requester"];
         }
     }
     // No name set name
     $input["name"] = ltrim($input["name"]);
     $input['content'] = ltrim($input['content']);
     if (empty($input["name"])) {
         $input['name'] = Html::clean(Html::entity_decode_deep($input['content']));
         $input["name"] = preg_replace('/\\r\\n/', ' ', $input['name']);
         $input["name"] = preg_replace('/\\n/', ' ', $input['name']);
         // For mailcollector
         $input["name"] = preg_replace('/\\\\r\\\\n/', ' ', $input['name']);
         $input["name"] = preg_replace('/\\\\n/', ' ', $input['name']);
         $input['name'] = Toolbox::stripslashes_deep($input['name']);
         $input["name"] = Toolbox::substr($input['name'], 0, 70);
         $input['name'] = Toolbox::addslashes_deep($input['name']);
     }
     // Set default dropdown
     $dropdown_fields = array('entities_id', 'itilcategories_id');
     foreach ($dropdown_fields as $field) {
         if (!isset($input[$field])) {
             $input[$field] = 0;
         }
     }
     $input = $this->computeDefaultValuesForAdd($input);
     return $input;
 }
 /** function buildTicket - Builds,and returns, the major structure of the ticket to be entered.
  *
  * @param $i                  mail ID
  * @param $options   array    of possible options
  *
  * @return ticket fields array
  */
 function buildTicket($i, $options = array())
 {
     global $CFG_GLPI;
     $play_rules = isset($options['play_rules']) && $options['play_rules'];
     $head = $this->getHeaders($i);
     // Get Header Info Return Array Of Headers
     // **Key Are (subject,to,toOth,toNameOth,from,fromName)
     $tkt = array();
     $tkt['_blacklisted'] = false;
     // For RuleTickets
     $tkt['_mailgate'] = $options['mailgates_id'];
     // Use mail date if it's defined
     if ($this->fields['use_mail_date']) {
         $tkt['date'] = $head['date'];
     }
     // Detect if it is a mail reply
     $glpi_message_match = "/GLPI-([0-9]+)\\.[0-9]+\\.[0-9]+@\\w*/";
     // Check if email not send by GLPI : if yes -> blacklist
     if (!isset($head['message_id']) || preg_match($glpi_message_match, $head['message_id'], $match)) {
         $tkt['_blacklisted'] = true;
         return $tkt;
     }
     // manage blacklist
     $blacklisted_emails = Blacklist::getEmails();
     // Add name of the mailcollector as blacklisted
     $blacklisted_emails[] = $this->fields['name'];
     if (Toolbox::inArrayCaseCompare($head['from'], $blacklisted_emails)) {
         $tkt['_blacklisted'] = true;
         return $tkt;
     }
     // max size = 0 : no import attachments
     if ($this->fields['filesize_max'] > 0) {
         if (is_writable(GLPI_TMP_DIR)) {
             $tkt['_filename'] = $this->getAttached($i, GLPI_TMP_DIR . "/", $this->fields['filesize_max']);
             $tkt['_tag'] = $this->tags;
         } else {
             //TRANS: %s is a directory
             Toolbox::logInFile('mailgate', sprintf(__('%s is not writable'), GLPI_TMP_DIR . "/"));
         }
     }
     //  Who is the user ?
     $tkt['_users_id_requester'] = User::getOrImportByEmail($head['from']);
     $tkt["_users_id_requester_notif"]['use_notification'] = 1;
     // Set alternative email if user not found / used if anonymous mail creation is enable
     if (!$tkt['_users_id_requester']) {
         $tkt["_users_id_requester_notif"]['alternative_email'] = $head['from'];
     }
     // Add to and cc as additional observer if user found
     if (count($head['ccs'])) {
         foreach ($head['ccs'] as $cc) {
             if ($cc != $head['from'] && !Toolbox::inArrayCaseCompare($cc, $blacklisted_emails) && ($tmp = User::getOrImportByEmail($cc)) > 0) {
                 $tkt['_additional_observers'][] = array('users_id' => $tmp, 'use_notification' => 1);
             }
         }
     }
     if (count($head['tos'])) {
         foreach ($head['tos'] as $to) {
             if ($to != $head['from'] && !Toolbox::inArrayCaseCompare($to, $blacklisted_emails) && ($tmp = User::getOrImportByEmail($to)) > 0) {
                 $tkt['_additional_observers'][] = array('users_id' => $tmp, 'use_notification' => 1);
             }
         }
     }
     // Auto_import
     $tkt['_auto_import'] = 1;
     // For followup : do not check users_id = login user
     $tkt['_do_not_check_users_id'] = 1;
     $body = $this->getBody($i);
     // Do it before using charset variable
     $head['subject'] = $this->decodeMimeString($head['subject']);
     $tkt['_head'] = $head;
     if (!empty($this->charset) && !$this->body_converted) {
         $body = Toolbox::encodeInUtf8($body, $this->charset);
         $this->body_converted = true;
     }
     if (!Toolbox::seems_utf8($body)) {
         $tkt['content'] = Toolbox::encodeInUtf8($body);
     } else {
         $tkt['content'] = $body;
     }
     // See In-Reply-To field
     if (isset($head['in_reply_to'])) {
         if (preg_match($glpi_message_match, $head['in_reply_to'], $match)) {
             $tkt['tickets_id'] = intval($match[1]);
         }
     }
     // See in References
     if (!isset($tkt['tickets_id']) && isset($head['references'])) {
         if (preg_match($glpi_message_match, $head['references'], $match)) {
             $tkt['tickets_id'] = intval($match[1]);
         }
     }
     // See in title
     if (!isset($tkt['tickets_id']) && preg_match('/\\[.+#(\\d+)\\]/', $head['subject'], $match)) {
         $tkt['tickets_id'] = intval($match[1]);
     }
     $is_html = false;
     //If files are present and content is html
     if (isset($this->files) && count($this->files) && $tkt['content'] != strip_tags($tkt['content']) && !isset($tkt['tickets_id'])) {
         $is_html = true;
         $tkt['content'] = Ticket::convertContentForTicket($tkt['content'], array_merge($this->files, $this->altfiles), $this->tags);
     }
     $tkt['content'] = $this->cleanMailContent($tkt['content']);
     if ($is_html && !isset($tkt['tickets_id'])) {
         $tkt['content'] = nl2br($tkt['content']);
     }
     $tkt['_supplier_email'] = false;
     // Found ticket link
     if (isset($tkt['tickets_id'])) {
         // it's a reply to a previous ticket
         $job = new Ticket();
         $tu = new Ticket_User();
         $st = new Supplier_Ticket();
         // Check if ticket  exists and users_id exists in GLPI
         /// TODO check if users_id have right to add a followup to the ticket
         if ($job->getFromDB($tkt['tickets_id']) && $job->fields['status'] != CommonITILObject::CLOSED && ($CFG_GLPI['use_anonymous_followups'] || $tkt['_users_id_requester'] > 0 || $tu->isAlternateEmailForITILObject($tkt['tickets_id'], $head['from']) || ($tkt['_supplier_email'] = $st->isSupplierEmail($tkt['tickets_id'], $head['from'])))) {
             if ($tkt['_supplier_email']) {
                 $tkt['content'] = sprintf(__('From %s'), $head['from']) . "\n\n" . $tkt['content'];
             }
             $content = explode("\n", $tkt['content']);
             $tkt['content'] = "";
             $to_keep = array();
             // Move requester to author of followup :
             $tkt['users_id'] = $tkt['_users_id_requester'];
             $begin_strip = -1;
             $end_strip = -1;
             $begin_match = "/" . NotificationTargetTicket::HEADERTAG . ".*" . NotificationTargetTicket::HEADERTAG . "/";
             $end_match = "/" . NotificationTargetTicket::FOOTERTAG . ".*" . NotificationTargetTicket::FOOTERTAG . "/";
             foreach ($content as $ID => $val) {
                 // Get first tag for begin
                 if ($begin_strip < 0) {
                     if (preg_match($begin_match, $val)) {
                         $begin_strip = $ID;
                     }
                 }
                 // Get last tag for end
                 if ($begin_strip >= 0) {
                     if (preg_match($end_match, $val)) {
                         $end_strip = $ID;
                         continue;
                     }
                 }
             }
             if ($begin_strip >= 0) {
                 // Clean first and last lines
                 $content[$begin_strip] = preg_replace($begin_match, '', $content[$begin_strip]);
             }
             if ($end_strip >= 0) {
                 // Clean first and last lines
                 $content[$end_strip] = preg_replace($end_match, '', $content[$end_strip]);
             }
             if ($begin_strip >= 0) {
                 $length = count($content);
                 // Use end strip if set
                 if ($end_strip >= 0 && $end_strip < $length) {
                     $length = $end_strip;
                 }
                 for ($i = $begin_strip + 1; $i < $length; $i++) {
                     unset($content[$i]);
                 }
             }
             $to_keep = array();
             // Aditional clean for thunderbird
             foreach ($content as $ID => $val) {
                 if (!isset($val[0]) || $val[0] != '>') {
                     $to_keep[$ID] = $ID;
                 }
             }
             $tkt['content'] = "";
             foreach ($to_keep as $ID) {
                 $tkt['content'] .= $content[$ID] . "\n";
             }
             // Do not play rules for followups : WRONG : play rules only for refuse options
             //$play_rules = false;
         } else {
             // => to handle link in Ticket->post_addItem()
             $tkt['_linkedto'] = $tkt['tickets_id'];
             unset($tkt['tickets_id']);
         }
     }
     // Add message from getAttached
     if ($this->addtobody) {
         $tkt['content'] .= $this->addtobody;
     }
     $tkt['name'] = $this->textCleaner($head['subject']);
     if (!isset($tkt['tickets_id'])) {
         // Which entity ?
         //$tkt['entities_id']=$this->fields['entities_id'];
         //$tkt['Subject']= $head['subject'];   // not use for the moment
         // Medium
         $tkt['urgency'] = "3";
         // No hardware associated
         $tkt['itemtype'] = "";
         // Mail request type
     } else {
         // Reopen if needed
         $tkt['add_reopen'] = 1;
     }
     $tkt['requesttypes_id'] = RequestType::getDefault('mail');
     if ($play_rules) {
         $rule_options['ticket'] = $tkt;
         $rule_options['headers'] = $head;
         $rule_options['mailcollector'] = $options['mailgates_id'];
         $rule_options['_users_id_requester'] = $tkt['_users_id_requester'];
         $rulecollection = new RuleMailCollectorCollection();
         $output = $rulecollection->processAllRules(array(), array(), $rule_options);
         // New ticket : compute all
         if (!isset($tkt['tickets_id'])) {
             foreach ($output as $key => $value) {
                 $tkt[$key] = $value;
             }
         } else {
             // Followup only copy refuse data
             $tobecopied = array('_refuse_email_no_response', '_refuse_email_with_response');
             foreach ($tobecopied as $val) {
                 if (isset($output[$val])) {
                     $tkt[$val] = $output[$val];
                 }
             }
         }
     }
     $tkt = Toolbox::addslashes_deep($tkt);
     return $tkt;
 }
Exemple #15
0
 /**
  * Construct SQL request depending of search parameters
  *
  * add to data array a field sql containing an array of requests :
  *      search : request to get items limited to wanted ones
  *      count : to count all items based on search criterias
  *                    may be an array a request : need to add counts
  *                    maybe empty : use search one to count
  *
  * @since version 0.85
  *
  * @param $data    array of search datas prepared to generate SQL
  *
  * @return nothing
  **/
 static function constructSQL(array &$data)
 {
     global $CFG_GLPI;
     if (!isset($data['itemtype'])) {
         return false;
     }
     $data['sql']['count'] = array();
     $data['sql']['search'] = '';
     $searchopt =& self::getOptions($data['itemtype']);
     $blacklist_tables = array();
     if (isset($CFG_GLPI['union_search_type'][$data['itemtype']])) {
         $itemtable = $CFG_GLPI['union_search_type'][$data['itemtype']];
         $blacklist_tables[] = getTableForItemType($data['itemtype']);
     } else {
         $itemtable = getTableForItemType($data['itemtype']);
     }
     // hack for AllAssets
     if (isset($CFG_GLPI['union_search_type'][$data['itemtype']])) {
         $entity_restrict = true;
     } else {
         $entity_restrict = $data['item']->isEntityAssign();
     }
     // Construct the request
     //// 1 - SELECT
     // request currentuser for SQL supervision, not displayed
     $SELECT = "SELECT '" . Toolbox::addslashes_deep($_SESSION['glpiname']) . "' AS currentuser,\n                        " . self::addDefaultSelect($data['itemtype']);
     // Add select for all toview item
     foreach ($data['toview'] as $key => $val) {
         $SELECT .= self::addSelect($data['itemtype'], $val, $key, 0);
     }
     //// 2 - FROM AND LEFT JOIN
     // Set reference table
     $FROM = " FROM `{$itemtable}`";
     // Init already linked tables array in order not to link a table several times
     $already_link_tables = array();
     // Put reference table
     array_push($already_link_tables, $itemtable);
     // Add default join
     $COMMONLEFTJOIN = self::addDefaultJoin($data['itemtype'], $itemtable, $already_link_tables);
     $FROM .= $COMMONLEFTJOIN;
     // Add all table for toview items
     foreach ($data['tocompute'] as $key => $val) {
         if (!in_array($searchopt[$val]["table"], $blacklist_tables)) {
             $FROM .= self::addLeftJoin($data['itemtype'], $itemtable, $already_link_tables, $searchopt[$val]["table"], $searchopt[$val]["linkfield"], 0, 0, $searchopt[$val]["joinparams"], $searchopt[$val]["field"]);
         }
     }
     // Search all case :
     if ($data['search']['all_search']) {
         foreach ($searchopt as $key => $val) {
             // Do not search on Group Name
             if (is_array($val)) {
                 if (!in_array($searchopt[$key]["table"], $blacklist_tables)) {
                     $FROM .= self::addLeftJoin($data['itemtype'], $itemtable, $already_link_tables, $searchopt[$key]["table"], $searchopt[$key]["linkfield"], 0, 0, $searchopt[$key]["joinparams"], $searchopt[$key]["field"]);
                 }
             }
         }
     }
     //// 3 - WHERE
     // default string
     $COMMONWHERE = self::addDefaultWhere($data['itemtype']);
     $first = empty($COMMONWHERE);
     // Add deleted if item have it
     if ($data['item'] && $data['item']->maybeDeleted()) {
         $LINK = " AND ";
         if ($first) {
             $LINK = " ";
             $first = false;
         }
         $COMMONWHERE .= $LINK . "`{$itemtable}`.`is_deleted` = '" . $data['search']['is_deleted'] . "' ";
     }
     // Remove template items
     if ($data['item'] && $data['item']->maybeTemplate()) {
         $LINK = " AND ";
         if ($first) {
             $LINK = " ";
             $first = false;
         }
         $COMMONWHERE .= $LINK . "`{$itemtable}`.`is_template` = '0' ";
     }
     // Add Restrict to current entities
     if ($entity_restrict) {
         $LINK = " AND ";
         if ($first) {
             $LINK = " ";
             $first = false;
         }
         if ($data['itemtype'] == 'Entity') {
             $COMMONWHERE .= getEntitiesRestrictRequest($LINK, $itemtable, 'id', '', true);
         } else {
             if (isset($CFG_GLPI["union_search_type"][$data['itemtype']])) {
                 // Will be replace below in Union/Recursivity Hack
                 $COMMONWHERE .= $LINK . " ENTITYRESTRICT ";
             } else {
                 $COMMONWHERE .= getEntitiesRestrictRequest($LINK, $itemtable, '', '', $data['item']->maybeRecursive());
             }
         }
     }
     $WHERE = "";
     $HAVING = "";
     // Add search conditions
     // If there is search items
     if (count($data['search']['criteria'])) {
         foreach ($data['search']['criteria'] as $key => $criteria) {
             // if real search (strlen >0) and not all and view search
             if (isset($criteria['value']) && strlen($criteria['value']) > 0) {
                 // common search
                 if ($criteria['field'] != "all" && $criteria['field'] != "view") {
                     $LINK = " ";
                     $NOT = 0;
                     $tmplink = "";
                     if (isset($criteria['link'])) {
                         if (strstr($criteria['link'], "NOT")) {
                             $tmplink = " " . str_replace(" NOT", "", $criteria['link']);
                             $NOT = 1;
                         } else {
                             $tmplink = " " . $criteria['link'];
                         }
                     } else {
                         $tmplink = " AND ";
                     }
                     if (isset($searchopt[$criteria['field']]["usehaving"])) {
                         // Manage Link if not first item
                         if (!empty($HAVING)) {
                             $LINK = $tmplink;
                         }
                         // Find key
                         $item_num = array_search($criteria['field'], $data['tocompute']);
                         $HAVING .= self::addHaving($LINK, $NOT, $data['itemtype'], $criteria['field'], $criteria['searchtype'], $criteria['value'], 0, $item_num);
                     } else {
                         // Manage Link if not first item
                         if (!empty($WHERE)) {
                             $LINK = $tmplink;
                         }
                         $WHERE .= self::addWhere($LINK, $NOT, $data['itemtype'], $criteria['field'], $criteria['searchtype'], $criteria['value']);
                     }
                     // view and all search
                 } else {
                     $LINK = " OR ";
                     $NOT = 0;
                     $globallink = " AND ";
                     if (isset($criteria['link'])) {
                         switch ($criteria['link']) {
                             case "AND":
                                 $LINK = " OR ";
                                 $globallink = " AND ";
                                 break;
                             case "AND NOT":
                                 $LINK = " AND ";
                                 $NOT = 1;
                                 $globallink = " AND ";
                                 break;
                             case "OR":
                                 $LINK = " OR ";
                                 $globallink = " OR ";
                                 break;
                             case "OR NOT":
                                 $LINK = " AND ";
                                 $NOT = 1;
                                 $globallink = " OR ";
                                 break;
                         }
                     } else {
                         $tmplink = " AND ";
                     }
                     // Manage Link if not first item
                     if (!empty($WHERE)) {
                         $WHERE .= $globallink;
                     }
                     $WHERE .= " ( ";
                     $first2 = true;
                     $items = array();
                     if ($criteria['field'] == "all") {
                         $items = $searchopt;
                     } else {
                         // toview case : populate toview
                         foreach ($data['toview'] as $key2 => $val2) {
                             $items[$val2] = $searchopt[$val2];
                         }
                     }
                     foreach ($items as $key2 => $val2) {
                         if (isset($val2['nosearch']) && $val2['nosearch']) {
                             continue;
                         }
                         if (is_array($val2)) {
                             // Add Where clause if not to be done in HAVING CLAUSE
                             if (!isset($val2["usehaving"])) {
                                 $tmplink = $LINK;
                                 if ($first2) {
                                     $tmplink = " ";
                                     $first2 = false;
                                 }
                                 $WHERE .= self::addWhere($tmplink, $NOT, $data['itemtype'], $key2, $criteria['searchtype'], $criteria['value']);
                             }
                         }
                     }
                     $WHERE .= " ) ";
                 }
             }
         }
     }
     //// 4 - ORDER
     $ORDER = " ORDER BY `id` ";
     foreach ($data['tocompute'] as $key => $val) {
         if ($data['search']['sort'] == $val) {
             $ORDER = self::addOrderBy($data['itemtype'], $data['search']['sort'], $data['search']['order'], $key);
         }
     }
     //// 5 - META SEARCH
     // Preprocessing
     if (count($data['search']['metacriteria'])) {
         // Already link meta table in order not to linked a table several times
         $already_link_tables2 = array();
         $metanum = count($data['toview']) - 1;
         foreach ($data['search']['metacriteria'] as $key => $metacriteria) {
             if (isset($metacriteria['itemtype']) && !empty($metacriteria['itemtype']) && isset($metacriteria['value']) && strlen($metacriteria['value']) > 0) {
                 $metaopt =& self::getOptions($metacriteria['itemtype']);
                 $sopt = $metaopt[$metacriteria['field']];
                 $metanum++;
                 // a - SELECT
                 $SELECT .= self::addSelect($metacriteria['itemtype'], $metacriteria['field'], $metanum, 1, $metacriteria['itemtype']);
                 // b - ADD LEFT JOIN
                 // Link reference tables
                 if (!in_array(getTableForItemType($metacriteria['itemtype']), $already_link_tables2)) {
                     $FROM .= self::addMetaLeftJoin($data['itemtype'], $metacriteria['itemtype'], $already_link_tables2, $metacriteria['value'] == "NULL" || strstr($metacriteria['link'], "NOT"));
                 }
                 // Link items tables
                 if (!in_array($sopt["table"] . "_" . $metacriteria['itemtype'], $already_link_tables2)) {
                     $FROM .= self::addLeftJoin($metacriteria['itemtype'], getTableForItemType($metacriteria['itemtype']), $already_link_tables2, $sopt["table"], $sopt["linkfield"], 1, $metacriteria['itemtype'], $sopt["joinparams"], $sopt["field"]);
                 }
                 // Where
                 $LINK = "";
                 // For AND NOT statement need to take into account all the group by items
                 if (strstr($metacriteria['link'], "AND NOT") || isset($sopt["usehaving"])) {
                     $NOT = 0;
                     if (strstr($metacriteria['link'], "NOT")) {
                         $tmplink = " " . str_replace(" NOT", "", $metacriteria['link']);
                         $NOT = 1;
                     } else {
                         $tmplink = " " . $metacriteria['link'];
                     }
                     if (!empty($HAVING)) {
                         $LINK = $tmplink;
                     }
                     $HAVING .= self::addHaving($LINK, $NOT, $metacriteria['itemtype'], $metacriteria['field'], $metacriteria['searchtype'], $metacriteria['value'], 1, $metanum);
                 } else {
                     // Meta Where Search
                     $LINK = " ";
                     $NOT = 0;
                     // Manage Link if not first item
                     if (isset($metacriteria['link']) && strstr($metacriteria['link'], "NOT")) {
                         $tmplink = " " . str_replace(" NOT", "", $metacriteria['link']);
                         $NOT = 1;
                     } else {
                         if (isset($metacriteria['link'])) {
                             $tmplink = " " . $metacriteria['link'];
                         } else {
                             $tmplink = " AND ";
                         }
                     }
                     if (!empty($WHERE)) {
                         $LINK = $tmplink;
                     }
                     $WHERE .= self::addWhere($LINK, $NOT, $metacriteria['itemtype'], $metacriteria['field'], $metacriteria['searchtype'], $metacriteria['value'], 1);
                 }
             }
         }
     }
     //// 6 - Add item ID
     // Add ID to the select
     if (!empty($itemtable)) {
         $SELECT .= "`{$itemtable}`.`id` AS id ";
     }
     //// 7 - Manage GROUP BY
     $GROUPBY = "";
     // Meta Search / Search All / Count tickets
     if (count($data['search']['metacriteria']) || !empty($HAVING) || $data['search']['all_search']) {
         $GROUPBY = " GROUP BY `{$itemtable}`.`id`";
     }
     if (empty($GROUPBY)) {
         foreach ($data['toview'] as $key2 => $val2) {
             if (!empty($GROUPBY)) {
                 break;
             }
             if (isset($searchopt[$val2]["forcegroupby"])) {
                 $GROUPBY = " GROUP BY `{$itemtable}`.`id`";
             }
         }
     }
     $LIMIT = "";
     $numrows = 0;
     //No search : count number of items using a simple count(ID) request and LIMIT search
     if ($data['search']['no_search']) {
         $LIMIT = " LIMIT " . $data['search']['start'] . ", " . $data['search']['list_limit'];
         // Force group by for all the type -> need to count only on table ID
         if (!isset($searchopt[1]['forcegroupby'])) {
             $count = "count(*)";
         } else {
             $count = "count(DISTINCT `{$itemtable}`.`id`)";
         }
         // request currentuser for SQL supervision, not displayed
         $query_num = "SELECT {$count},\n                              '" . Toolbox::addslashes_deep($_SESSION['glpiname']) . "' AS currentuser\n                       FROM `{$itemtable}`" . $COMMONLEFTJOIN;
         $first = true;
         if (!empty($COMMONWHERE)) {
             $LINK = " AND ";
             if ($first) {
                 $LINK = " WHERE ";
                 $first = false;
             }
             $query_num .= $LINK . $COMMONWHERE;
         }
         // Union Search :
         if (isset($CFG_GLPI["union_search_type"][$data['itemtype']])) {
             $tmpquery = $query_num;
             $numrows = 0;
             foreach ($CFG_GLPI[$CFG_GLPI["union_search_type"][$data['itemtype']]] as $ctype) {
                 $ctable = getTableForItemType($ctype);
                 if (($citem = getItemForItemtype($ctype)) && $citem->canView()) {
                     // State case
                     if ($data['itemtype'] == 'AllAssets') {
                         $query_num = str_replace($CFG_GLPI["union_search_type"][$data['itemtype']], $ctable, $tmpquery);
                         $query_num = str_replace($data['itemtype'], $ctype, $query_num);
                         $query_num .= " AND `{$ctable}`.`id` IS NOT NULL ";
                         // Add deleted if item have it
                         if ($citem && $citem->maybeDeleted()) {
                             $query_num .= " AND `{$ctable}`.`is_deleted` = '0' ";
                         }
                         // Remove template items
                         if ($citem && $citem->maybeTemplate()) {
                             $query_num .= " AND `{$ctable}`.`is_template` = '0' ";
                         }
                     } else {
                         // Ref table case
                         $reftable = getTableForItemType($data['itemtype']);
                         if ($data['item'] && $data['item']->maybeDeleted()) {
                             $tmpquery = str_replace("`" . $CFG_GLPI["union_search_type"][$data['itemtype']] . "`.\n                                                   `is_deleted`", "`{$reftable}`.`is_deleted`", $tmpquery);
                         }
                         $replace = "FROM `{$reftable}`\n                                  INNER JOIN `{$ctable}`\n                                       ON (`{$reftable}`.`items_id` =`{$ctable}`.`id`\n                                           AND `{$reftable}`.`itemtype` = '{$ctype}')";
                         $query_num = str_replace("FROM `" . $CFG_GLPI["union_search_type"][$data['itemtype']] . "`", $replace, $tmpquery);
                         $query_num = str_replace($CFG_GLPI["union_search_type"][$data['itemtype']], $ctable, $query_num);
                     }
                     $query_num = str_replace("ENTITYRESTRICT", getEntitiesRestrictRequest('', $ctable, '', '', $citem->maybeRecursive()), $query_num);
                     $data['sql']['count'][] = $query_num;
                 }
             }
         } else {
             $data['sql']['count'][] = $query_num;
         }
     }
     // If export_all reset LIMIT condition
     if ($data['search']['export_all']) {
         $LIMIT = "";
     }
     if (!empty($WHERE) || !empty($COMMONWHERE)) {
         if (!empty($COMMONWHERE)) {
             $WHERE = ' WHERE ' . $COMMONWHERE . (!empty($WHERE) ? ' AND ( ' . $WHERE . ' )' : '');
         } else {
             $WHERE = ' WHERE ' . $WHERE . ' ';
         }
         $first = false;
     }
     if (!empty($HAVING)) {
         $HAVING = ' HAVING ' . $HAVING;
     }
     // Create QUERY
     if (isset($CFG_GLPI["union_search_type"][$data['itemtype']])) {
         $first = true;
         $QUERY = "";
         foreach ($CFG_GLPI[$CFG_GLPI["union_search_type"][$data['itemtype']]] as $ctype) {
             $ctable = getTableForItemType($ctype);
             if (($citem = getItemForItemtype($ctype)) && $citem->canView()) {
                 if ($first) {
                     $first = false;
                 } else {
                     $QUERY .= " UNION ";
                 }
                 $tmpquery = "";
                 // AllAssets case
                 if ($data['itemtype'] == 'AllAssets') {
                     $tmpquery = $SELECT . ", '{$ctype}' AS TYPE " . $FROM . $WHERE;
                     $tmpquery .= " AND `{$ctable}`.`id` IS NOT NULL ";
                     // Add deleted if item have it
                     if ($citem && $citem->maybeDeleted()) {
                         $tmpquery .= " AND `{$ctable}`.`is_deleted` = '0' ";
                     }
                     // Remove template items
                     if ($citem && $citem->maybeTemplate()) {
                         $tmpquery .= " AND `{$ctable}`.`is_template` = '0' ";
                     }
                     $tmpquery .= $GROUPBY . $HAVING;
                     $tmpquery = str_replace($CFG_GLPI["union_search_type"][$data['itemtype']], $ctable, $tmpquery);
                     $tmpquery = str_replace($data['itemtype'], $ctype, $tmpquery);
                 } else {
                     // Ref table case
                     $reftable = getTableForItemType($data['itemtype']);
                     $tmpquery = $SELECT . ", '{$ctype}' AS TYPE,\n                                      `{$reftable}`.`id` AS refID, " . "\n                                      `{$ctable}`.`entities_id` AS ENTITY " . $FROM . $WHERE;
                     if ($data['item']->maybeDeleted()) {
                         $tmpquery = str_replace("`" . $CFG_GLPI["union_search_type"][$data['itemtype']] . "`.\n                                                `is_deleted`", "`{$reftable}`.`is_deleted`", $tmpquery);
                     }
                     $replace = "FROM `{$reftable}`" . "\n                              INNER JOIN `{$ctable}`" . "\n                                 ON (`{$reftable}`.`items_id`=`{$ctable}`.`id`" . "\n                                     AND `{$reftable}`.`itemtype` = '{$ctype}')";
                     $tmpquery = str_replace("FROM `" . $CFG_GLPI["union_search_type"][$data['itemtype']] . "`", $replace, $tmpquery);
                     $tmpquery = str_replace($CFG_GLPI["union_search_type"][$data['itemtype']], $ctable, $tmpquery);
                 }
                 $tmpquery = str_replace("ENTITYRESTRICT", getEntitiesRestrictRequest('', $ctable, '', '', $citem->maybeRecursive()), $tmpquery);
                 // SOFTWARE HACK
                 if ($ctype == 'Software') {
                     $tmpquery = str_replace("`glpi_softwares`.`serial`", "''", $tmpquery);
                     $tmpquery = str_replace("`glpi_softwares`.`otherserial`", "''", $tmpquery);
                 }
                 $QUERY .= $tmpquery;
             }
         }
         if (empty($QUERY)) {
             echo self::showError($data['display_type']);
             return;
         }
         $QUERY .= str_replace($CFG_GLPI["union_search_type"][$data['itemtype']] . ".", "", $ORDER) . $LIMIT;
     } else {
         $QUERY = $SELECT . $FROM . $WHERE . $GROUPBY . $HAVING . $ORDER . $LIMIT;
     }
     $data['sql']['search'] = $QUERY;
 }
Exemple #16
0
 /**
  * Duplicate infocoms from an item template to its clone
  *
  * @param $itemtype     itemtype of the item
  * @param $oldid        ID of the item to clone
  * @param $newid        ID of the item cloned
  * @param $newitemtype  itemtype of the new item (= $itemtype if empty) (default '')
  **/
 static function cloneItem($itemtype, $oldid, $newid, $newitemtype = '')
 {
     global $DB;
     $ic = new self();
     if ($ic->getFromDBforDevice($itemtype, $oldid)) {
         $input = $ic->fields;
         $input = Toolbox::addslashes_deep($input);
         $input['items_id'] = $newid;
         if (!empty($newitemtype)) {
             $input['itemtype'] = $newitemtype;
         }
         unset($input["id"]);
         if (isset($input["immo_number"])) {
             $input["immo_number"] = autoName($input["immo_number"], "immo_number", 1, 'Infocom', $input['entities_id']);
         }
         $date_fields = array('buy_date', 'delivery_date', 'inventory_date', 'order_date', 'use_date', 'warranty_date');
         foreach ($date_fields as $f) {
             if (empty($input[$f])) {
                 unset($input[$f]);
             }
         }
         $ic2 = new self();
         $ic2->add($input);
     }
 }
             $nb = count($data);
             $data = Toolbox::clean_cross_side_scripting_deep(Toolbox::addslashes_deep($data));
             $hardware[$data["ID"]] = $data["DEVICEID"];
             echo "{$i}/{$nb}\r";
         }
     }
     echo "  {$nb} computers in OCS\n";
 }
 echo "+ Search links with no computer in OCS\n";
 $query = "SELECT `id`, `ocsid`, `ocs_deviceid`\n                FROM `glpi_plugin_ocsinventoryng_ocslinks`\n                WHERE `plugin_ocsinventoryng_ocsservers_id` = '{$ocsservers_id}'";
 $result = $DB->query($query);
 $nb = $DB->numrows($result);
 if ($nb > 0) {
     for ($i = 1; $data = $DB->fetch_array($result); $i++) {
         $nbchk++;
         $data = Toolbox::clean_cross_side_scripting_deep(Toolbox::addslashes_deep($data));
         if (isset($hardware[$data["ocsid"]])) {
             echo "{$i}/{$nb}\r";
         } else {
             printf("%12d : %s\n", $data['id'], $data['ocs_deviceid']);
             if (isset($_GET['clean'])) {
                 $query_del = "DELETE\n                                FROM `glpi_plugin_ocsinventoryng_ocslinks`\n                                WHERE `id` = '" . $data["id"] . "'";
                 if ($DB->query($query_del)) {
                     $nbdel++;
                 }
             } else {
                 $nbtodo++;
             }
         }
     }
     echo "  {$nb} links checked\n";
 function _initSpecificInfo($key_field, $id, $class)
 {
     $instances = $class->find("`{$key_field}`='{$id}'");
     $input = array();
     if (count($instances) > 0) {
         $input = Toolbox::addslashes_deep(current($instances));
     } else {
         $input[$key_field] = $id;
         $id = $class->add($input);
         $class->getFromDB($id);
         $input = $class->fields;
     }
     return $input;
 }
Exemple #19
0
 /**
  * Check plugins states and detect new plugins
  **/
 function checkStates()
 {
     //// Get all plugins
     // Get all from DBs
     $pluglist = $this->find("", "name, directory");
     $db_plugins = array();
     if (count($pluglist)) {
         foreach ($pluglist as $plug) {
             $db_plugins[$plug['directory']] = $plug['id'];
         }
     }
     // Parse plugin dir
     $file_plugins = array();
     $error_plugins = array();
     $dirplug = GLPI_ROOT . "/plugins";
     $dh = opendir($dirplug);
     while (false !== ($filename = readdir($dh))) {
         if ($filename != ".svn" && $filename != "." && $filename != ".." && is_dir($dirplug . "/" . $filename)) {
             // Find version
             if (file_exists($dirplug . "/" . $filename . "/setup.php")) {
                 self::loadLang($filename);
                 include_once $dirplug . "/" . $filename . "/setup.php";
                 $info = self::getInfo($filename);
                 if (count($info)) {
                     $file_plugins[$filename] = Toolbox::addslashes_deep($info);
                 }
             }
         }
     }
     // check plugin state
     foreach ($db_plugins as $plug => $ID) {
         $install_ok = true;
         // Check file
         if (!isset($file_plugins[$plug])) {
             $this->update(array('id' => $ID, 'state' => self::TOBECLEANED));
             $install_ok = false;
         } else {
             // Check version
             if ($file_plugins[$plug]['version'] != $pluglist[$ID]['version']) {
                 $input = $file_plugins[$plug];
                 $input['id'] = $ID;
                 if ($pluglist[$ID]['version']) {
                     $input['state'] = self::NOTUPDATED;
                 }
                 $this->update($input);
                 $install_ok = false;
             }
         }
         // Check install is ok for activated plugins
         if ($install_ok && $pluglist[$ID]['state'] == self::ACTIVATED) {
             $usage_ok = true;
             $function = "plugin_" . $plug . "_check_prerequisites";
             if (function_exists($function)) {
                 if (!$function()) {
                     $usage_ok = false;
                 }
             }
             $function = "plugin_" . $plug . "_check_config";
             if (function_exists($function)) {
                 if (!$function()) {
                     $usage_ok = false;
                 }
             } else {
                 $usage_ok = false;
             }
             if (!$usage_ok) {
                 $input = $file_plugins[$plug];
                 $this->unactivate($ID);
             }
         }
         // Delete plugin for file list
         if (isset($file_plugins[$plug])) {
             unset($file_plugins[$plug]);
         }
     }
     if (count($file_plugins)) {
         foreach ($file_plugins as $plug => $data) {
             if (isset($data['oldname'])) {
                 $checking = $pluglist;
                 foreach ($checking as $check) {
                     if (isset($check['directory']) && $check['directory'] == $data['oldname']) {
                         $data['state'] = self::NOTUPDATED;
                         $this->delete(array('id' => $check['id']));
                     }
                 }
             } else {
                 $data['state'] = self::NOTINSTALLED;
             }
             $data['directory'] = $plug;
             $this->add($data);
         }
     }
 }
  ------------------------------------------------------------------------
*/
ob_start();
include "../../../../inc/includes.php";
ob_end_clean();
$response = array();
//Agent communication using REST protocol
if (isset($_GET['action'])) {
    switch ($_GET['action']) {
        case 'getJobs':
            if (isset($_GET['machineid'])) {
                $pfAgent = new PluginFusioninventoryAgent();
                $pfTaskjobstate = new PluginFusioninventoryTaskjobstate();
                $pfTaskjoblog = new PluginFusioninventoryTaskjoblog();
                $a_agent = $pfAgent->InfosByKey(Toolbox::addslashes_deep($_GET['machineid']));
                if (isset($a_agent['id'])) {
                    $moduleRun = $pfTaskjobstate->getTaskjobsAgent($a_agent['id']);
                    foreach ($moduleRun as $className => $array) {
                        if (class_exists($className)) {
                            if ($className == "PluginFusioninventoryCollect") {
                                $class = new PluginFusioninventoryCollect();
                                foreach ($array as $data) {
                                    $out = $class->run($data, $a_agent);
                                    if (count($out) > 0) {
                                        $response[] = $out;
                                    }
                                    $pfTaskjobstate->changeStatus($data['id'], PluginFusioninventoryTaskjobstate::SERVER_HAS_SENT_DATA);
                                    $a_input = array();
                                    $a_input['plugin_fusioninventory_taskjobstates_id'] = $data['id'];
                                    $a_input['items_id'] = $a_agent['id'];
Exemple #21
0
 public static function install(Migration $migration)
 {
     global $DB;
     $table = getTableForItemType(__CLASS__);
     //Installation
     if (!TableExists($table) && !TableExists("glpi_plugin_order")) {
         $migration->displayMessage("Installing {$table}");
         $query = "CREATE TABLE IF NOT EXISTS `glpi_plugin_order_orders` (\n               `id` int(11) NOT NULL auto_increment,\n               `entities_id` int(11) NOT NULL default '0',\n               `is_template` tinyint(1) NOT NULL default '0',\n               `template_name` varchar(255) collate utf8_unicode_ci default NULL,\n               `is_recursive` tinyint(1) NOT NULL default '0',\n               `name` varchar(255) collate utf8_unicode_ci default NULL,\n               `num_order` varchar(255) collate utf8_unicode_ci default NULL,\n               `budgets_id` int(11) NOT NULL default '0' COMMENT 'RELATION to glpi_budgets (id)',\n               `plugin_order_ordertaxes_id` int(11) NOT NULL default '0' COMMENT 'RELATION to glpi_plugin_order_ordertaxes (id)',\n               `plugin_order_orderpayments_id` int (11)  NOT NULL default '0' COMMENT 'RELATION to glpi_plugin_order_orderpayments (id)',\n               `order_date` date default NULL,\n               `duedate` date default NULL,\n               `deliverydate` date default NULL,\n               `is_late` tinyint(1) NOT NULL default '0',\n               `suppliers_id` int(11) NOT NULL default '0' COMMENT 'RELATION to glpi_suppliers (id)',\n               `contacts_id` int(11) NOT NULL default '0' COMMENT 'RELATION to glpi_contacts (id)',\n               `locations_id` int(11) NOT NULL default '0' COMMENT 'RELATION to glpi_locations (id)',\n               `plugin_order_orderstates_id` int(11) NOT NULL default 1,\n               `plugin_order_billstates_id` int(11) NOT NULL default 1,\n               `port_price` float NOT NULL default 0,\n               `comment` text collate utf8_unicode_ci,\n               `notepad` longtext collate utf8_unicode_ci,\n               `is_deleted` tinyint(1) NOT NULL default '0',\n               `users_id` int(11) NOT NULL default '0',\n               `groups_id` int(11) NOT NULL default '0',\n               `users_id_delivery` int(11) NOT NULL default '0',\n               `groups_id_delivery` int(11) NOT NULL default '0',\n               `plugin_order_ordertypes_id` int (11) NOT NULL default '0' COMMENT 'RELATION to glpi_plugin_order_ordertypes (id)',\n               `date_mod` datetime default NULL,\n               `is_helpdesk_visible` tinyint(1) NOT NULL default '1',\n               PRIMARY KEY  (`id`),\n               KEY `name` (`name`),\n               KEY `entities_id` (`entities_id`),\n               KEY `plugin_order_ordertaxes_id` (`plugin_order_ordertaxes_id`),\n               KEY `plugin_order_orderpayments_id` (`plugin_order_orderpayments_id`),\n               KEY `states_id` (`plugin_order_orderstates_id`),\n               KEY `suppliers_id` (`suppliers_id`),\n               KEY `contacts_id` (`contacts_id`),\n               KEY `locations_id` (`locations_id`),\n               KEY `is_late` (`locations_id`),\n               KEY `is_template` (`is_template`),\n               KEY `is_deleted` (`is_deleted`),\n               KEY date_mod (date_mod)\n            ) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;";
         $DB->query($query) or die($DB->error());
         Crontask::Register(__CLASS__, 'computeLateOrders', HOUR_TIMESTAMP, array('param' => 24, 'mode' => CronTask::MODE_EXTERNAL));
     } else {
         //Upgrade
         $migration->displayMessage("Upgrading {$table}");
         if (TableExists('glpi_plugin_order')) {
             //Update to 1.1.0
             $migration->addField('glpi_plugin_order', "port_price", "FLOAT NOT NULL default '0'");
             $migration->addField('glpi_plugin_order', "taxes", "FLOAT NOT NULL default '0'");
             if (FieldExists("glpi_plugin_order", "numordersupplier")) {
                 foreach ($DB->request("glpi_plugin_order") as $data) {
                     $query = "INSERT INTO  `glpi_plugin_order_suppliers`\n                             (`ID`, `FK_order`, `numorder`, `numbill`) VALUES\n                            (NULL, '" . $data["ID"] . "', '" . $data["numordersupplier"] . "', '" . $data["numbill"] . "') ";
                     $DB->query($query) or die($DB->error());
                 }
             }
             $migration->dropField('glpi_plugin_order', 'numordersupplier');
             $migration->dropField('glpi_plugin_order', 'numbill');
             $migration->migrationOneTable('glpi_plugin_order');
         }
         //1.2.0
         $domigration_itemtypes = false;
         if ($migration->renameTable("glpi_plugin_order", $table)) {
             $domigration_itemtypes = true;
         }
         $migration->changeField($table, "ID", "id", "int(11) NOT NULL AUTO_INCREMENT");
         $migration->changeField($table, "FK_entities", "entities_id", "int(11) NOT NULL default 0");
         $migration->changeField($table, "recursive", "is_recursive", "tinyint(1) NOT NULL default 0");
         $migration->changeField($table, "name", "name", "varchar(255) collate utf8_unicode_ci default NULL");
         $migration->changeField($table, "budget", "budgets_id", "int(11) NOT NULL default '0' COMMENT 'RELATION to glpi_budgets (id)'");
         $migration->changeField($table, "numorder", "num_order", "varchar(255) collate utf8_unicode_ci default NULL");
         $migration->changeField($table, "taxes", "plugin_order_ordertaxes_id", "int(11) NOT NULL default '0' COMMENT 'RELATION to glpi_plugin_order_ordertaxes (id)'");
         $migration->changeField($table, "payment", "plugin_order_orderpayments_id", "int (11)  NOT NULL default '0' COMMENT 'RELATION to glpi_plugin_order_orderpayments (id)'");
         $migration->changeField($table, "date", "order_date", "date default NULL");
         $migration->changeField($table, "FK_enterprise", "suppliers_id", "int(11) NOT NULL default '0' COMMENT 'RELATION to glpi_suppliers (id)'");
         $migration->changeField($table, "FK_contact", "contacts_id", "int(11) NOT NULL default '0' COMMENT 'RELATION to glpi_contacts (id)'");
         $migration->changeField($table, "location", "locations_id", "int(11) NOT NULL default '0' COMMENT 'RELATION to glpi_locations (id)'");
         $migration->changeField($table, "status", "states_id", "int(11) NOT NULL default '0'");
         $migration->changeField($table, "comment", "comment", "text collate utf8_unicode_ci");
         $migration->changeField($table, "notes", "notepad", "longtext collate utf8_unicode_ci");
         $migration->changeField($table, "deleted", "is_deleted", "tinyint(1) NOT NULL default '0'");
         $migration->addKey($table, "name");
         $migration->addKey($table, "entities_id");
         $migration->addKey($table, "plugin_order_ordertaxes_id");
         $migration->addKey($table, "plugin_order_orderpayments_id");
         $migration->addKey($table, "states_id");
         $migration->addKey($table, "suppliers_id");
         $migration->addKey($table, "contacts_id");
         $migration->addKey($table, "locations_id");
         $migration->addKey($table, "is_deleted");
         $migration->migrationOneTable($table);
         //Only migrate itemtypes when it's only necessary, otherwise it breaks upgrade procedure !
         if ($domigration_itemtypes) {
             Plugin::migrateItemType(array(3150 => 'PluginOrderOrder'), array("glpi_bookmarks", "glpi_bookmarks_users", "glpi_displaypreferences", "glpi_documents_items", "glpi_infocoms", "glpi_logs", "glpi_tickets"), array());
         }
         if (TableExists("glpi_plugin_order_budgets")) {
             //Manage budgets (here because class has been remove since 1.4.0)
             $migration->changeField("glpi_plugin_order_budgets", "ID", "id", " int(11) NOT NULL auto_increment");
             $migration->changeField("glpi_plugin_order_budgets", "FK_entities", "entities_id", "int(11) NOT NULL default '0'");
             $migration->changeField("glpi_plugin_order_budgets", "FK_budget", "budgets_id", "int(11) NOT NULL default '0'");
             $migration->changeField("glpi_plugin_order_budgets", "comments", "comment", "text collate utf8_unicode_ci");
             $migration->changeField("glpi_plugin_order_budgets", "deleted", "is_deleted", "tinyint(1) NOT NULL default '0'");
             $migration->changeField("glpi_plugin_order_budgets", "startdate", "start_date", "date default NULL");
             $migration->changeField("glpi_plugin_order_budgets", "enddate", "end_date", "date default NULL");
             $migration->changeField("glpi_plugin_order_budgets", "value", "value", "float NOT NULL DEFAULT '0'");
             $migration->addKey("glpi_plugin_order_budgets", "entities_id");
             $migration->addKey("glpi_plugin_order_budgets", "is_deleted");
             $migration->migrationOneTable("glpi_plugin_order_budgets");
             Plugin::migrateItemType(array(3153 => 'PluginOrderBudget'), array("glpi_bookmarks", "glpi_bookmarks_users", "glpi_displaypreferences", "glpi_documents_items", "glpi_infocoms", "glpi_logs", "glpi_tickets"), array());
             //Manage budgets migration before dropping the table
             $budget = new Budget();
             $matchings = array('budgets_id' => 'id', 'name' => 'name', 'start_date' => 'begin_date', 'end_date' => 'end_date', 'value' => 'value', 'comment' => 'comment', 'entities_id' => 'entities_id', 'is_deleted' => 'is_deleted');
             foreach (getAllDatasFromTable("glpi_plugin_order_budgets") as $data) {
                 $tmp = array();
                 $id = false;
                 foreach ($matchings as $old => $new) {
                     if (!is_null($data[$old])) {
                         $tmp[$new] = $data[$old];
                     }
                 }
                 $tmp['comment'] = Toolbox::addslashes_deep($tmp['comment']);
                 //Budget already exists in the core: update it
                 if ($budget->getFromDB($data['budgets_id'])) {
                     $budget->update($tmp);
                     $id = $tmp['id'];
                 } else {
                     //Budget doesn't exists in the core: create it
                     unset($tmp['id']);
                     $id = $budget->add($tmp);
                 }
             }
             $DB->query("DROP TABLE `glpi_plugin_order_budgets`");
             foreach (array('glpi_displaypreferences', 'glpi_documents_items', 'glpi_bookmarks', 'glpi_logs') as $t) {
                 $DB->query("DELETE FROM `{$t}` WHERE `itemtype` = 'PluginOrderBudget'");
             }
         }
         //1.3.0
         $migration->addField($table, "plugin_order_ordertypes_id", "int (11) NOT NULL default '0' COMMENT 'RELATION to glpi_plugin_order_ordertypes (id)'");
         $migration->migrationOneTable($table);
         //1.4.0
         if ($migration->changeField("glpi_plugin_order_orders", "states_id", "plugin_order_orderstates_id", "int(11) NOT NULL default 1")) {
             $migration->migrationOneTable($table);
             $query = "UPDATE `glpi_plugin_order_orders` SET `plugin_order_orderstates_id`=`plugin_order_orderstates_id`+1";
             $DB->query($query) or die($DB->error());
         }
         $migration->addField($table, "duedate", "DATETIME NULL");
         $migration->migrationOneTable($table);
         //1.5.0
         if (TableExists("glpi_dropdown_plugin_order_status")) {
             $DB->query("DROP TABLE `glpi_dropdown_plugin_order_status`") or die($DB->error());
         }
         if (TableExists("glpi_plugin_order_mailing")) {
             $DB->query("DROP TABLE IF EXISTS `glpi_plugin_order_mailing`;") or die($DB->error());
         }
         $migration->addField($table, 'plugin_order_billstates_id', "int(11) NOT NULL default 0");
         //1.5.2
         $migration->addField($table, 'deliverydate', "DATETIME NULL");
         $migration->addField($table, "is_late", "TINYINT(1) NOT NULL DEFAULT '0'");
         $migration->addKey($table, "is_late");
         if (!countElementsInTable('glpi_crontasks', "`name`='computeLateOrders'")) {
             Crontask::Register(__CLASS__, 'computeLateOrders', HOUR_TIMESTAMP, array('param' => 24, 'mode' => CronTask::MODE_EXTERNAL));
         }
         $migration->migrationOneTable($table);
         if ($migration->addField($table, "is_template", "tinyint(1) NOT NULL DEFAULT 0")) {
             $migration->addField($table, "template_name", "VARCHAR(255) collate utf8_unicode_ci default NULL");
             $migration->migrationOneTable($table);
         }
         $migration->addField($table, "users_id", "INT(11) NOT NULL DEFAULT '0'");
         $migration->addField($table, "groups_id", "INT(11) NOT NULL DEFAULT '0'");
         $migration->addField($table, "users_id_delivery", "INT(11) NOT NULL DEFAULT '0'");
         $migration->addField($table, "groups_id_delivery", "INT(11) NOT NULL DEFAULT '0'");
         //1.7.0
         $migration->addField($table, "date_mod", "datetime");
         $migration->addKey($table, "date_mod");
         //1.7.2
         $migration->addField($table, "is_helpdesk_visible", "bool", array('value' => 1));
         $migration->migrationOneTable($table);
         //Displayprefs
         $prefs = array(1 => 1, 2 => 2, 4 => 4, 5 => 5, 6 => 6, 7 => 7, 10 => 10);
         foreach ($prefs as $num => $rank) {
             if (!countElementsInTable("glpi_displaypreferences", "`itemtype`='PluginOrderOrder' AND `num`='{$num}'\n                                           AND `users_id`='0'")) {
                 $DB->query("INSERT INTO glpi_displaypreferences\n                           VALUES (NULL,'PluginOrderOrder','{$num}','{$rank}','0');");
             }
         }
         //Remove unused notifications
         $notification = new Notification();
         $notification->deleteByCriteria("`itemtype`='PluginOrderOrder_Item'");
     }
 }
 /**
  * @since version 0.90
  *
  * @see CommonDBTM::processMassiveActionsForOneItemtype()
  **/
 static function processMassiveActionsForOneItemtype(MassiveAction $ma, CommonDBTM $item, array $ids)
 {
     switch ($ma->getAction()) {
         case 'merge':
             foreach ($ids as $key) {
                 if ($item->can($key, UPDATE)) {
                     if ($item->getEntityID() == $_SESSION['glpiactive_entity']) {
                         if ($item->update(array('id' => $key, 'is_recursive' => 1))) {
                             $ma->itemDone($item->getType(), $key, MassiveAction::ACTION_OK);
                         } else {
                             $ma->itemDone($item->getType(), $key, MassiveAction::ACTION_KO);
                             $ma->addMessage($item->getErrorMessage(ERROR_ON_ACTION));
                         }
                     } else {
                         $input2 = $item->fields;
                         // Change entity
                         $input2['entities_id'] = $_SESSION['glpiactive_entity'];
                         $input2['is_recursive'] = 1;
                         $input2 = Toolbox::addslashes_deep($input2);
                         if (!$item->import($input2)) {
                             $ma->itemDone($item->getType(), $key, MassiveAction::ACTION_KO);
                             $ma->addMessage($item->getErrorMessage(ERROR_ON_ACTION));
                         } else {
                             $ma->itemDone($item->getType(), $key, MassiveAction::ACTION_OK);
                         }
                     }
                 } else {
                     $ma->itemDone($item->getType(), $key, MassiveAction::ACTION_NORIGHT);
                     $ma->addMessage($item->getErrorMessage(ERROR_RIGHT));
                 }
             }
             return;
     }
     parent::processMassiveActionsForOneItemtype($ma, $item, $ids);
 }
 /**
  * Duplicate all costs from a contract template to its clone
  *
  * @since version 0.84
  *
  * @param $oldid
  * @param $newid
  **/
 static function cloneContract($oldid, $newid)
 {
     global $DB;
     $query = "SELECT *\n                 FROM `glpi_contractcosts`\n                 WHERE `contracts_id` = '{$oldid}'";
     foreach ($DB->request($query) as $data) {
         $cd = new self();
         unset($data['id']);
         $data['contracts_id'] = $newid;
         $data = Toolbox::addslashes_deep($data);
         $cd->add($data);
     }
 }
Exemple #24
0
 /**
  * Manage use authentication and initialize the session
  *
  * @param $login_name      string
  * @param $login_password  string
  * @param $noauto          boolean (false by default)
  *
  * @return boolean (success)
  */
 function Login($login_name, $login_password, $noauto = false)
 {
     global $DB, $CFG_GLPI;
     $this->getAuthMethods();
     $this->user_present = 1;
     $this->auth_succeded = false;
     //In case the user was deleted in the LDAP directory
     $user_deleted_ldap = false;
     // Trim login_name : avoid LDAP search errors
     $login_name = trim($login_name);
     if (!$noauto && ($authtype = self::checkAlternateAuthSystems())) {
         if ($this->getAlternateAuthSystemsUserLogin($authtype) && !empty($this->user->fields['name'])) {
             // Used for log when login process failed
             $login_name = $this->user->fields['name'];
             $this->auth_succeded = true;
             $this->extauth = 1;
             $this->user_present = $this->user->getFromDBbyName(addslashes($login_name));
             $this->user->fields['authtype'] = $authtype;
             $user_dn = false;
             $ldapservers = '';
             //if LDAP enabled too, get user's infos from LDAP
             if (Toolbox::canUseLdap()) {
                 $ldapservers = array();
                 //User has already authenticate, at least once : it's ldap server if filled
                 if (isset($this->user->fields["auths_id"]) && $this->user->fields["auths_id"] > 0) {
                     $authldap = new AuthLdap();
                     //If ldap server is enabled
                     if ($authldap->getFromDB($this->user->fields["auths_id"]) && $authldap->fields['is_active']) {
                         $ldapservers[] = $authldap->fields;
                     }
                     //User has never beeen authenticated : try all active ldap server to find the right one
                 } else {
                     foreach (getAllDatasFromTable('glpi_authldaps', "`is_active`='1'") as $ldap_config) {
                         $ldapservers[] = $ldap_config;
                     }
                 }
                 foreach ($ldapservers as $ldap_method) {
                     $ds = AuthLdap::connectToServer($ldap_method["host"], $ldap_method["port"], $ldap_method["rootdn"], Toolbox::decrypt($ldap_method["rootdn_passwd"], GLPIKEY), $ldap_method["use_tls"], $ldap_method["deref_option"]);
                     if ($ds) {
                         $params['method'] = AuthLdap::IDENTIFIER_LOGIN;
                         $params['fields'][AuthLdap::IDENTIFIER_LOGIN] = $ldap_method["login_field"];
                         $user_dn = AuthLdap::searchUserDn($ds, array('basedn' => $ldap_method["basedn"], 'login_field' => $ldap_method['login_field'], 'search_parameters' => $params, 'user_params' => array('method' => AuthLDAP::IDENTIFIER_LOGIN, 'value' => $login_name), 'condition' => $ldap_method["condition"]));
                         if ($user_dn) {
                             $this->user->fields['auths_id'] = $ldap_method['id'];
                             $this->user->getFromLDAP($ds, $ldap_method, $user_dn['dn'], $login_name, !$this->user_present);
                             break;
                         }
                     }
                 }
             }
             if (count($ldapservers) == 0 && $authtype == self::EXTERNAL) {
                 // Case of using external auth and no LDAP servers, so get data from external auth
                 $this->user->getFromSSO();
             } else {
                 //If user is set as present in GLPI but no LDAP DN found : it means that the user
                 //is not present in an ldap directory anymore
                 if (!$user_dn && $this->user_present) {
                     $user_deleted_ldap = true;
                     $this->user_deleted_ldap = true;
                 }
             }
             // Reset to secure it
             $this->user->fields['name'] = $login_name;
             $this->user->fields["last_login"] = $_SESSION["glpi_currenttime"];
         } else {
             $this->addToError(__('Empty login or password'));
         }
     }
     // If not already auth
     if (!$this->auth_succeded) {
         if (empty($login_name) || strstr($login_name, "") || empty($login_password) || strstr($login_password, "")) {
             $this->addToError(__('Empty login or password'));
         } else {
             // exists=0 -> user doesn't yet exist
             // exists=1 -> user is present in DB with password
             // exists=2 -> user is present in DB but without password
             $exists = $this->userExists(array('name' => addslashes($login_name)));
             // Pas en premier car sinon on ne fait pas le blankpassword
             // First try to connect via le DATABASE
             if ($exists == 1) {
                 // Without UTF8 decoding
                 if (!$this->auth_succeded) {
                     $this->auth_succeded = $this->connection_db(addslashes($login_name), $login_password);
                     if ($this->auth_succeded) {
                         $this->extauth = 0;
                         $this->user_present = $this->user->getFromDBbyName(addslashes($login_name));
                         $this->user->fields["authtype"] = self::DB_GLPI;
                         $this->user->fields["password"] = $login_password;
                     }
                 }
             } else {
                 if ($exists == 2) {
                     //The user is not authenticated on the GLPI DB, but we need to get information about him
                     //to find out his authentication method
                     $this->user->getFromDBbyName(addslashes($login_name));
                     //If the user has already been logged, the method_auth and auths_id are already set
                     //so we test this connection first
                     switch ($this->user->fields["authtype"]) {
                         case self::CAS:
                         case self::EXTERNAL:
                         case self::LDAP:
                             if (Toolbox::canUseLdap()) {
                                 AuthLdap::tryLdapAuth($this, $login_name, $login_password, $this->user->fields["auths_id"], $this->user->fields["user_dn"]);
                                 if (!$this->auth_succeded && $this->user_deleted_ldap) {
                                     $user_deleted_ldap = true;
                                 }
                             }
                             break;
                         case self::MAIL:
                             if (Toolbox::canUseImapPop()) {
                                 AuthMail::tryMailAuth($this, $login_name, $login_password, $this->user->fields["auths_id"]);
                             }
                             break;
                         case self::NOT_YET_AUTHENTIFIED:
                             break;
                     }
                 } else {
                     if (!$exists) {
                         //test all ldap servers only is user is not present in glpi's DB
                         if (!$this->auth_succeded && Toolbox::canUseLdap()) {
                             AuthLdap::tryLdapAuth($this, $login_name, $login_password, 0, false, false);
                         }
                         //test all imap/pop servers
                         if (!$this->auth_succeded && Toolbox::canUseImapPop()) {
                             AuthMail::tryMailAuth($this, $login_name, $login_password, 0, false);
                         }
                     }
                 }
             }
             // Fin des tests de connexion
         }
     }
     if ($user_deleted_ldap) {
         User::manageDeletedUserInLdap($this->user->fields["id"]);
     }
     // Ok, we have gathered sufficient data, if the first return false the user
     // is not present on the DB, so we add him.
     // if not, we update him.
     if ($this->auth_succeded) {
         //Set user an not deleted from LDAP
         $this->user->fields['is_deleted_ldap'] = 0;
         // Prepare data
         $this->user->fields["last_login"] = $_SESSION["glpi_currenttime"];
         if ($this->extauth) {
             $this->user->fields["_extauth"] = 1;
         }
         if ($DB->isSlave()) {
             if (!$this->user_present) {
                 // Can't add in slave mode
                 $this->addToError(__('User not authorized to connect in GLPI'));
                 $this->auth_succeded = false;
             }
         } else {
             if ($this->user_present) {
                 // First stripslashes to avoid double slashes
                 $input = Toolbox::stripslashes_deep($this->user->fields);
                 // Then ensure addslashes
                 $input = Toolbox::addslashes_deep($input);
                 // update user and Blank PWD to clean old database for the external auth
                 $this->user->update($input);
                 if ($this->extauth) {
                     $this->user->blankPassword();
                 }
             } else {
                 if ($CFG_GLPI["is_users_auto_add"]) {
                     // Auto add user
                     // First stripslashes to avoid double slashes
                     $input = Toolbox::stripslashes_deep($this->user->fields);
                     // Then ensure addslashes
                     $input = Toolbox::addslashes_deep($input);
                     unset($this->user->fields);
                     $this->user->add($input);
                 } else {
                     // Auto add not enable so auth failed
                     $this->addToError(__('User not authorized to connect in GLPI'));
                     $this->auth_succeded = false;
                 }
             }
         }
     }
     // Log Event (if possible)
     if (!$DB->isSlave()) {
         // GET THE IP OF THE CLIENT
         $ip = getenv("HTTP_X_FORWARDED_FOR") ? getenv("HTTP_X_FORWARDED_FOR") : getenv("REMOTE_ADDR");
         if ($this->auth_succeded) {
             if (GLPI_DEMO_MODE) {
                 // not translation in GLPI_DEMO_MODE
                 Event::log(-1, "system", 3, "login", $login_name . " log in from " . $ip);
             } else {
                 //TRANS: %1$s is the login of the user and %2$s its IP address
                 Event::log(-1, "system", 3, "login", sprintf(__('%1$s log in from IP %2$s'), $login_name, $ip));
             }
         } else {
             if (GLPI_DEMO_MODE) {
                 Event::log(-1, "system", 1, "login", "login", "Connection failed for " . $login_name . " ({$ip})");
             } else {
                 //TRANS: %1$s is the login of the user and %2$s its IP address
                 Event::log(-1, "system", 1, "login", sprintf(__('Failed login for %1$s from IP %2$s'), $login_name, $ip));
             }
         }
     }
     Session::init($this);
     if ($noauto) {
         $_SESSION["noAUTO"] = 1;
     }
     return $this->auth_succeded;
 }
Exemple #25
0
function update0681to07()
{
    global $DB, $CFG_GLPI;
    $DB->query("SET NAMES 'latin1'");
    // Improve user table :
    if (!isIndex("glpi_users", "firstname")) {
        $query = "ALTER TABLE `glpi_users`\n                ADD INDEX (`firstname`)";
        $DB->queryOrDie($query, "0.7 alter users add index on firstname");
    }
    if (!isIndex("glpi_users", "realname")) {
        $query = "ALTER TABLE `glpi_users`\n                ADD INDEX (`realname`)";
        $DB->queryOrDie($query, "0.7 alter users add index on realname");
    }
    // Decimal problem
    if (FieldExists("glpi_infocoms", "value", false)) {
        $query = "ALTER TABLE `glpi_infocoms`\n                CHANGE `value` `value` DECIMAL( 20, 4 ) NOT NULL DEFAULT '0'";
        $DB->queryOrDie($query, "0.7 alter value in glpi_infocoms");
    }
    if (FieldExists("glpi_infocoms", "warranty_value", false)) {
        $query = "ALTER TABLE `glpi_infocoms`\n                CHANGE warranty_value warranty_value DECIMAL( 20, 4 ) NOT NULL DEFAULT '0'";
        $DB->queryOrDie($query, "0.7 alter warranty_value in glpi_infocoms");
    }
    if (FieldExists("glpi_tracking", "cost_time", false)) {
        $query = "ALTER TABLE `glpi_tracking`\n                CHANGE cost_time cost_time DECIMAL( 20, 4 ) NOT NULL DEFAULT '0'";
        $DB->queryOrDie($query, "0.7 alter cost_time in glpi_tracking");
    }
    if (FieldExists("glpi_tracking", "cost_fixed", false)) {
        $query = "ALTER TABLE `glpi_tracking`\n                CHANGE cost_fixed cost_fixed DECIMAL( 20, 4 ) NOT NULL DEFAULT '0'";
        $DB->queryOrDie($query, "0.7 alter cost_fixed in glpi_tracking");
    }
    if (FieldExists("glpi_tracking", "cost_material", false)) {
        $query = "ALTER TABLE `glpi_tracking`\n                CHANGE cost_material cost_material DECIMAL( 20, 4 ) NOT NULL DEFAULT '0'";
        $DB->queryOrDie($query, "0.7 alter cost_material in glpi_tracking");
    }
    if (!FieldExists("glpi_config", "decimal_number", false)) {
        $query = "ALTER TABLE `glpi_config`\n                ADD `decimal_number` INT DEFAULT '2'";
        $DB->queryOrDie($query, "0.7 add decimal_number in glpi_config");
    }
    $CFG_GLPI["decimal_number"] = 2;
    if (!FieldExists("glpi_config", "cas_logout", false)) {
        $query = "ALTER TABLE `glpi_config`\n                ADD `cas_logout` VARCHAR( 255 ) NULL AFTER `cas_uri`";
        $DB->queryOrDie($query, "0.7 add cas_logout in glpi_config");
    }
    if (!isIndex("glpi_computer_device", "specificity")) {
        $query = "ALTER TABLE `glpi_computer_device`\n                ADD INDEX (`specificity`)";
        $DB->queryOrDie($query, "0.7 add index specificity in glpi_computer_device");
    }
    if (!FieldExists("glpi_docs", "comments", false)) {
        $query = "ALTER TABLE `glpi_docs`\n                CHANGE `comment` `comments` TEXT DEFAULT NULL ";
        $DB->queryOrDie($query, "0.7 alter docs.comment to be comments");
    }
    // Update polish langage file
    $query = "UPDATE `glpi_users`\n             SET `language` = 'pl_PL'\n             WHERE `language` = 'po_PO'";
    $DB->queryOrDie($query, "0.7 update polish lang file");
    // Add show_group_hardware
    if (!FieldExists("glpi_profiles", "show_group_hardware", false)) {
        $query = "ALTER TABLE `glpi_profiles`\n                ADD `show_group_hardware` CHAR(1) NULL DEFAULT '0'";
        $DB->queryOrDie($query, "0.7 alter glpi_profiles add show_group_hardware");
        $query = "UPDATE `glpi_profiles`\n                SET `show_group_hardware` = `show_group_ticket`";
        $DB->queryOrDie($query, "0.7 alter glpi_profiles add show_group_hardware");
    }
    // Clean doc association
    if (FieldExists("glpi_doc_device", "is_template", false)) {
        $query = "ALTER TABLE `glpi_doc_device`\n                DROP `is_template`";
        $DB->queryOrDie($query, "0.7 delete is_template from glpi_doc_device");
    }
    // Clean contract association
    if (FieldExists("glpi_contract_device", "is_template", false)) {
        $query = "ALTER TABLE `glpi_contract_device`\n                DROP `is_template`";
        $DB->queryOrDie($query, "0.7 delete is_template from glpi_contract_device");
    }
    //// ENTITY MANAGEMENT
    if (!TableExists("glpi_entities")) {
        $query = "CREATE TABLE `glpi_entities` (\n                  `ID` int(11) NOT NULL auto_increment,\n                  `name` varchar(255) NOT NULL,\n                  `parentID` int(11) NOT NULL default '0',\n                  `completename` text NOT NULL,\n                  `comments` text,\n                  `level` int(11) default NULL,\n                  PRIMARY KEY (`ID`),\n                  UNIQUE KEY `name` (`name`,`parentID`),\n                  KEY `parentID` (`parentID`)\n                ) ENGINE=MyISAM";
        $DB->queryOrDie($query, "0.7 create glpi_entities");
    }
    if (!TableExists("glpi_entities_data")) {
        $query = "CREATE TABLE `glpi_entities_data` (\n                  `ID` int(11) NOT NULL auto_increment,\n                  `FK_entities` int(11) NOT NULL default '0',\n                  `address` text,\n                  `postcode` varchar(255) default NULL,\n                  `town` varchar(255) default NULL,\n                  `state` varchar(255) default NULL,\n                  `country` varchar(255) default NULL,\n                  `website` varchar(200) default NULL,\n                  `phonenumber` varchar(200) default NULL,\n                  `fax` varchar(255) default NULL,\n                  `email` varchar(255) default NULL,\n                  `notes` longtext,\n                  PRIMARY KEY (`ID`),\n                  UNIQUE KEY `FK_entities` (`FK_entities`)\n                ) ENGINE=MyISAM";
        $DB->queryOrDie($query, "0.7 create glpi_entities_data");
    }
    // Add default profile to all users without any profile
    $query = "SELECT `ID`\n             FROM `glpi_profiles`\n             WHERE `is_default` = '1'";
    if ($result = $DB->query($query)) {
        if ($DB->numrows($result) > 0) {
            $IDprof = $DB->result($result, 0, 0);
            $query = "SELECT `glpi_users`.`ID`\n                   FROM `glpi_users`\n                   LEFT JOIN `glpi_users_profiles`\n                        ON (`glpi_users_profiles`.`FK_users` = `glpi_users`.`ID`)\n                   WHERE `glpi_users_profiles`.`ID` IS NULL";
            if ($result = $DB->query($query)) {
                if ($DB->numrows($result) > 0) {
                    while ($data = $DB->fetch_assoc($result)) {
                        $query = "INSERT INTO `glpi_users_profiles`\n                                   (`FK_users`, `FK_profiles`)\n                            VALUES ('" . $data['ID'] . "', '{$IDprof}') ";
                        $DB->query($query);
                    }
                }
            }
        }
    }
    if (!FieldExists("glpi_users_profiles", "FK_entities", false)) {
        // Clean Datas
        $query = "DELETE\n                FROM `glpi_users_profiles`\n                WHERE `FK_users` = '0'";
        $DB->queryOrDie($query, "0.7 clean datas of glpi_users_profiles");
        $query = " ALTER TABLE `glpi_users_profiles`\n                 ADD `FK_entities` INT NOT NULL DEFAULT '0',\n                 ADD `recursive` SMALLINT NOT NULL DEFAULT '1',\n                 ADD `dynamic` SMALLINT NOT NULL DEFAULT '0' ";
        $DB->queryOrDie($query, "0.7 alter glpi_users_profiles");
    }
    // Correct for clean active field for beta users
    if (FieldExists("glpi_users_profiles", "active", false)) {
        $query = "ALTER TABLE `glpi_users_profiles`\n                DROP `active` ";
        $DB->queryOrDie($query, "0.7 clean active field for beta of glpi_users_profiles");
    }
    if (!FieldExists("glpi_users", "active", false)) {
        $query = "ALTER TABLE `glpi_users`\n                ADD `active` INT(2) NOT NULL DEFAULT '1' ";
        $DB->queryOrDie($query, "0.7 add active field for beta of glpi_users");
        if (!isIndex("glpi_users", "active")) {
            $query = "ALTER TABLE `glpi_users`\n                   ADD INDEX (`active`)";
            $DB->queryOrDie($query, "0.7 add index active in glpi_users");
        }
    }
    // Add entity tags to tables
    $tables = array("glpi_cartridges_type", "glpi_computers", "glpi_consumables_type", "glpi_contacts", "glpi_contracts", "glpi_docs", "glpi_dropdown_locations", "glpi_dropdown_netpoint", "glpi_enterprises", "glpi_groups", "glpi_monitors", "glpi_networking", "glpi_peripherals", "glpi_phones", "glpi_printers", "glpi_reminder", "glpi_software", "glpi_tracking");
    // "glpi_kbitems","glpi_dropdown_kbcategories", -> easier to manage
    // "glpi_followups" -> always link to tracking ?
    // "glpi_licenses" -> always link to software ?
    // "glpi_infocoms" -> always link to item ? PB on reports stats ?
    // "glpi_links" -> global items easier to manage
    // "glpi_reservation_item", "glpi_state_item" -> always link to item ? but info maybe needed
    foreach ($tables as $tbl) {
        if (!FieldExists($tbl, "FK_entities", false)) {
            $query = "ALTER TABLE `{$tbl}`\n                   ADD `FK_entities` INT NOT NULL DEFAULT '0' AFTER `ID`";
            $DB->queryOrDie($query, "0.7 add FK_entities in {$tbl}");
        }
        if (!isIndex($tbl, "FK_entities")) {
            $query = "ALTER TABLE `{$tbl}`\n                   ADD INDEX (`FK_entities`)";
            $DB->queryOrDie($query, "0.7 add index FK_entities in {$tbl}");
        }
    }
    // Regenerate Indexes :
    $tables = array("glpi_dropdown_locations");
    foreach ($tables as $tbl) {
        if (isIndex($tbl, "name")) {
            $query = "ALTER TABLE `{$tbl}`\n                   DROP INDEX `name`";
            $DB->queryOrDie($query, "0.7 drop index name in {$tbl}");
        }
        if (isIndex($tbl, "parentID_2")) {
            $query = "ALTER TABLE `{$tbl}`\n                   DROP INDEX `parentID_2`";
            $DB->queryOrDie($query, "0.7 drop index name in {$tbl}");
        }
        $query = "ALTER TABLE `{$tbl}`\n                ADD UNIQUE(`name`,`parentID`,`FK_entities`)";
        $DB->queryOrDie($query, "0.7 add index name in {$tbl}");
    }
    if (isIndex("glpi_users_profiles", "FK_users_profiles")) {
        $query = "ALTER TABLE `glpi_users_profiles`\n                DROP INDEX `FK_users_profiles`";
        $DB->queryOrDie($query, "0.7 drop index FK_users_profiles in glpi_users_profiles");
    }
    if (!isIndex("glpi_users_profiles", "FK_entities")) {
        $query = "ALTER TABLE `glpi_users_profiles`\n                ADD INDEX (`FK_entities`)";
        $DB->queryOrDie($query, "0.7 add index FK_entities in glpi_users_profiles");
    }
    if (!isIndex("glpi_users_profiles", "recursive")) {
        $query = "ALTER TABLE `glpi_users_profiles`\n                ADD INDEX (`recursive`)";
        $DB->queryOrDie($query, "0.7 add index recursive in glpi_users_profiles");
    }
    //// MULTIAUTH MANAGEMENT
    if (!TableExists("glpi_auth_ldap")) {
        $query = "CREATE TABLE `glpi_auth_ldap` (\n                  `ID` int(11) NOT NULL auto_increment,\n                  `name` varchar(255) NOT NULL,\n                  `ldap_host` varchar(255) default NULL,\n                  `ldap_basedn` varchar(255) default NULL,\n                  `ldap_rootdn` varchar(255) default NULL,\n                  `ldap_pass` varchar(255) default NULL,\n                  `ldap_port` varchar(255) NOT NULL default '389',\n                  `ldap_condition` varchar(255) default NULL,\n                  `ldap_login` varchar(255) NOT NULL default 'uid',\n                  `ldap_use_tls` varchar(255) NOT NULL default '0',\n                  `ldap_field_group` varchar(255) default NULL,\n                  `ldap_group_condition` varchar(255) default NULL,\n                  `ldap_search_for_groups` int NOT NULL default '0',\n                  `ldap_field_group_member` varchar(255) default NULL,\n                  `ldap_field_email` varchar(255) default NULL,\n                  `ldap_field_realname` varchar(255) default NULL,\n                  `ldap_field_firstname` varchar(255) default NULL,\n                  `ldap_field_phone` varchar(255) default NULL,\n                  `ldap_field_phone2` varchar(255) default NULL,\n                  `ldap_field_mobile` varchar(255) default NULL,\n                  `ldap_field_comments` TEXT default NULL,\n                  PRIMARY KEY  (`ID`)\n                ) ENGINE=MyISAM";
        $DB->queryOrDie($query, "0.7 create glpi_auth_ldap");
        $query = "SELECT *\n                FROM `glpi_config`\n                WHERE `ID` = '1'";
        $result = $DB->query($query);
        $config = $DB->fetch_array($result);
        if (!empty($config["ldap_host"])) {
            //Transfer ldap information into the new table
            $query = "INSERT INTO `glpi_auth_ldap`\n                   VALUES (NULL, '" . $config["ldap_host"] . "', '" . $config["ldap_host"] . "',\n                           '" . $config["ldap_basedn"] . "', '" . $config["ldap_rootdn"] . "',\n                           '" . $config["ldap_pass"] . "', " . $config["ldap_port"] . ",\n                           '" . $config["ldap_condition"] . "', '" . $config["ldap_login"] . "',\n                           '" . $config["ldap_use_tls"] . "', '" . $config["ldap_field_group"] . "',\n                           '" . $config["ldap_condition"] . "', " . $config["ldap_search_for_groups"] . ",\n                           '" . $config["ldap_field_group_member"] . "', '" . $config["ldap_field_email"] . "',\n                           '" . $config["ldap_field_realname"] . "', '" . $config["ldap_field_firstname"] . "',\n                           '" . $config["ldap_field_phone"] . "', '" . $config["ldap_field_phone2"] . "',\n                           '" . $config["ldap_field_mobile"] . "', NULL)";
            $DB->queryOrDie($query, "0.7 transfert of ldap parameters into glpi_auth_ldap");
        }
        $query = "ALTER TABLE `glpi_config`\n                DROP `ldap_field_email`,\n                DROP `ldap_port`,\n                DROP `ldap_host`,\n                DROP `ldap_basedn`,\n                DROP `ldap_rootdn`,\n                DROP `ldap_pass`,\n                DROP `ldap_field_location`,\n                DROP `ldap_field_realname`,\n                DROP `ldap_field_firstname`,\n                DROP `ldap_field_phone`,\n                DROP `ldap_field_phone2`,\n                DROP `ldap_field_mobile`,\n                DROP `ldap_condition`,\n                DROP `ldap_login`,\n                DROP `ldap_use_tls`,\n                DROP `ldap_field_group`,\n                DROP `ldap_group_condition`,\n                DROP `ldap_search_for_groups`,\n                DROP `ldap_field_group_member`";
        $DB->queryOrDie($query, "0.7 drop ldap fields from glpi_config");
    }
    if (!FieldExists("glpi_users", "id_auth", false)) {
        $query = "ALTER TABLE `glpi_users`\n                ADD `id_auth` INT NOT NULL DEFAULT '-1',\n                ADD `auth_method` INT NOT NULL DEFAULT '-1',\n                ADD `last_login` DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00',\n                ADD `date_mod` DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00'";
        $DB->queryOrDie($query, "0.7 add auth_method & id_method in glpi_users");
    }
    if (!TableExists("glpi_auth_mail")) {
        $query = "CREATE TABLE `glpi_auth_mail` (\n                  `ID` int(11) NOT NULL auto_increment,\n                  `name` varchar(255) NOT NULL,\n                  `imap_auth_server` varchar(200) default NULL,\n                  `imap_host` varchar(200) default NULL,\n                  PRIMARY KEY (`ID`)\n                ) ENGINE=MyISAM";
        $DB->queryOrDie($query, "0.7 create glpi_auth_mail");
        $query = "select * from glpi_config WHERE ID=1";
        $result = $DB->query($query);
        $config = $DB->fetch_array($result);
        if (!empty($config["imap_host"])) {
            //Transfer ldap information into the new table
            $query = "INSERT INTO `glpi_auth_mail`\n                   VALUES (NULL, '" . $config["imap_host"] . "', '" . $config["imap_auth_server"] . "',\n                           '" . $config["imap_host"] . "')";
            $DB->queryOrDie($query, "0.7 transfert of mail parameters into glpi_auth_mail");
        }
        $query = "ALTER TABLE `glpi_config`\n                DROP `imap_auth_server`,\n                DROP `imap_host`";
        $DB->queryOrDie($query, "0.7 drop mail fields from glpi_config");
    }
    // Clean state_item -> add a field from tables
    if (TableExists("glpi_state_item")) {
        $state_type = array(SOFTWARE_TYPE => 'glpi_software', COMPUTER_TYPE => 'glpi_computers', PRINTER_TYPE => 'glpi_printers', MONITOR_TYPE => 'glpi_monitors', PERIPHERAL_TYPE => 'glpi_peripherals', NETWORKING_TYPE => 'glpi_networking', PHONE_TYPE => 'glpi_phones');
        foreach ($state_type as $type => $table) {
            if (!FieldExists($table, "state", false)) {
                $query = "ALTER TABLE `{$table}`\n                      ADD `state` INT NOT NULL DEFAULT '0'";
                $DB->queryOrDie($query, "0.7 add state field to {$table}");
                $query2 = "SELECT *\n                       FROM `glpi_state_item`\n                       WHERE `device_type` = '{$type}'";
                $result = $DB->query($query2);
                if ($DB->numrows($result)) {
                    while ($data = $DB->fetch_array($result)) {
                        $query3 = "UPDATE `{$table}`\n                             SET `state` = '" . $data["state"] . "'\n                             WHERE `ID` = '" . $data["id_device"] . "'";
                        $DB->queryOrDie($query3, "0.7 update state field value to {$table}");
                    }
                }
            }
        }
        $query = "DROP TABLE `glpi_state_item` ";
        $DB->queryOrDie($query, "0.7 drop table state_item");
        $query = "INSERT INTO `glpi_display`\n                       (`type`, `num`, `rank`, `FK_users`)\n                VALUES (22, 31, 1, 0)";
        $DB->queryOrDie($query, "0.7 add default search for states");
        // Add for reservation
        $query = "INSERT INTO `glpi_display`\n                       (`type`, `num`, `rank`, `FK_users`)\n                VALUES ( 29, 4, 1, 0)";
        $DB->queryOrDie($query, "0.7 add defaul search for reservation");
        $query = "INSERT INTO `glpi_display`\n                       (`type`, `num`, `rank`, `FK_users`)\n                VALUES ( 29, 3, 2, 0)";
        $DB->queryOrDie($query, "0.7 add defaul search for reservation");
    }
    // Add ticket_tco for hardwares
    $tco_tbl = array(SOFTWARE_TYPE => 'glpi_software', COMPUTER_TYPE => 'glpi_computers', PRINTER_TYPE => 'glpi_printers', MONITOR_TYPE => 'glpi_monitors', PERIPHERAL_TYPE => 'glpi_peripherals', NETWORKING_TYPE => 'glpi_networking', PHONE_TYPE => 'glpi_phones');
    foreach ($tco_tbl as $type => $table) {
        if (!FieldExists($table, "ticket_tco", false)) {
            $query = "ALTER TABLE `{$table}`\n                   ADD `ticket_tco` DECIMAL( 20, 4 ) DEFAULT '0.0000'";
            $DB->queryOrDie($query, "0.7 alter {$table} add ticket_tco");
            // Update values
            $query = "SELECT DISTINCT `device_type`, `computer`\n                   FROM `glpi_tracking`\n                   WHERE `device_type` = '{$type}'\n                         AND (`cost_time` > 0\n                              OR `cost_fixed` > 0\n                              OR `cost_material` > 0)";
            $result = $DB->queryOrDie($query, "0.7 update ticket_tco");
            if ($DB->numrows($result)) {
                while ($data = $DB->fetch_array($result)) {
                    $query2 = "UPDATE `{$table}`\n                          SET `ticket_tco` = '" . computeTicketTco($type, $data["computer"]) . "'\n                          WHERE `ID` = '" . $data["computer"] . "'";
                    $DB->queryOrDie($query2, "0.7 update ticket_tco");
                }
            }
        }
    }
    if (!FieldExists("glpi_software", "helpdesk_visible", false)) {
        $query = "ALTER TABLE `glpi_software`\n                ADD `helpdesk_visible` INT NOT NULL default '1'";
        $DB->queryOrDie($query, "0.7 add helpdesk_visible in glpi_software");
    }
    if (!TableExists("glpi_dropdown_manufacturer")) {
        $query = "CREATE TABLE `glpi_dropdown_manufacturer` (\n                  `ID` int(11) NOT NULL auto_increment,\n                  `name` varchar(255) NOT NULL,\n                  `comments` text,\n                  PRIMARY KEY (`ID`),\n                  KEY `name` (`name`)\n                ) ENGINE=MyISAM";
        $DB->queryOrDie($query, "0.7 add dropdown_manufacturer table");
    }
    if (countElementsInTable("glpi_dropdown_manufacturer") == 0) {
        // Fill table
        $query = "SELECT *\n                FROM `glpi_enterprises`\n                ORDER BY `ID`";
        if ($result = $DB->query($query)) {
            if ($DB->numrows($result)) {
                while ($data = $DB->fetch_assoc($result)) {
                    $data = Toolbox::addslashes_deep($data);
                    $comments = "";
                    if (!empty($data['address'])) {
                        if (!empty($comments)) {
                            $comments .= "\n";
                        }
                        $comments .= sprintf(__('%1$s: %2$s'), __('Address'), $data['address']);
                    }
                    if (!empty($data['postcode']) || !empty($data['town'])) {
                        if (!empty($comments)) {
                            $comments = sprintf(__('%1$s %2$s', $comments, __('Address'))) . "\n";
                        }
                        //TRANS: %1$s is postcode, %2$s is town
                        $comments .= sprintf(__('%1$s %2$s'), $data['postcode'], $data['town']);
                    }
                    if (!empty($data['state']) || !empty($data['country'])) {
                        if (!empty($comments)) {
                            $comments = sprintf(__('%1$s %2$s', $comments, __('Address'))) . "\n";
                        }
                        //TRANS: %1$s is country, %2$s is state
                        $comments .= sprintf(__('%1$s %2$s'), $data['country'], $data['state']);
                    }
                    if (!empty($data['website'])) {
                        if (!empty($comments)) {
                            $comments .= "\n";
                        }
                        $comments .= sprintf(__('%1$s: %2$s'), __('Website'), $data['website']);
                    }
                    if (!empty($data['phonenumber'])) {
                        if (!empty($comments)) {
                            $comments .= "\n";
                        }
                        $comments .= sprintf(__('%1$s: %2$s'), __('Phone'), $data['phonenumber']);
                    }
                    if (!empty($data['fax'])) {
                        if (!empty($comments)) {
                            $comments .= "\n";
                        }
                        $comments .= sprintf(__('%1$s: %2$s'), __('Fax'), $data['fax']);
                    }
                    if (!empty($data['email'])) {
                        if (!empty($comments)) {
                            $comments .= "\n";
                        }
                        $comments .= sprintf(__('%1$s: %2$s'), __('Email'), $data['email']);
                    }
                    if (!empty($data['comments'])) {
                        if (!empty($comments)) {
                            $comments .= "\n";
                        }
                        $comments .= $data['comments'];
                    }
                    if (!empty($data['notes'])) {
                        if (!empty($comments)) {
                            $comments .= "\n";
                        }
                        $comments .= $data['notes'];
                    }
                    $query2 = "INSERT INTO `glpi_dropdown_manufacturer`\n                                 (ID, name, comments)\n                          VALUES ('" . $data['ID'] . "', '" . $data['name'] . "', '" . $comments . "')";
                    $DB->queryOrDie($query2, "0.7 add manufacturer item");
                }
            }
        }
    }
    if (isIndex("glpi_ocs_link", "ocs_id_2")) {
        $query = "ALTER TABLE `glpi_ocs_link`\n                DROP INDEX `ocs_id_2` ";
        $DB->queryOrDie($query, "0.7 alter ocs_link clean index ocs_id");
    }
    if (isIndex("glpi_ocs_link", "ocs_id")) {
        $query = "ALTER TABLE `glpi_ocs_link`\n                DROP INDEX `ocs_id` ";
        $DB->queryOrDie($query, "0.7 alter ocs_link clean index ocs_id");
    }
    if (!FieldExists("glpi_ocs_link", "ocs_server_id", false)) {
        $query = "ALTER TABLE `glpi_ocs_link`\n                ADD `ocs_server_id` int(11) NOT NULL";
        $DB->queryOrDie($query, "0.7 add ocs_server_id in glpi_ocs_link");
        $query = "UPDATE `glpi_ocs_link`\n                SET `ocs_server_id` = '1'";
        $DB->queryOrDie($query, "0.7 update ocs_server_id=1 in glpi_ocs_link");
    }
    if (!isIndex("glpi_ocs_link", "ocs_server_id")) {
        // Clean duplicates
        $query = "SELECT COUNT(*) AS CPT, `ocs_id`\n                FROM `glpi_ocs_link`\n                GROUP BY `ocs_id`\n                HAVING CPT > 1";
        if ($result = $DB->query($query)) {
            if ($DB->numrows($result) > 0) {
                while ($data = $DB->fetch_array($result)) {
                    // Skip first
                    $query = "SELECT `ID`\n                         FROM `glpi_ocs_link`\n                         WHERE `ocs_id` = '" . $data['ocs_id'] . "'\n                         ORDER BY `last_update` DESC\n                         LIMIT 1,99999";
                    if ($result2 = $DB->query($query)) {
                        if ($DB->numrows($result2)) {
                            while ($data2 = $DB->fetch_array($result2)) {
                                $query = "DELETE\n                                  FROM `glpi_ocs_link`\n                                  WHERE `ID` ='" . $data2['ID'] . "'";
                                $DB->queryOrDie($query, "0.7 clean to update ocs_server_id=1 in glpi_ocs_link");
                            }
                        }
                    }
                }
            }
        }
        $query = "ALTER TABLE `glpi_ocs_link`\n                ADD UNIQUE `ocs_server_id` (`ocs_server_id`, `ocs_id`)";
        $DB->queryOrDie($query, "0.7 alter ocs_link add index ocs_server_id");
    }
    if (!isIndex("glpi_ocs_link", "`ocs_deviceid`")) {
        $query = "ALTER TABLE `glpi_ocs_link`\n                ADD INDEX (`ocs_deviceid`)";
        $DB->queryOrDie($query, "0.7 alter ocs_link add index ocs_deviceid");
    }
    if (!FieldExists("glpi_ocs_config", "tplname", false)) {
        $query = "ALTER TABLE `glpi_ocs_config`\n                ADD `name` varchar(200) default NULL AFTER `ID`,\n                ADD `is_template` enum('0','1') NOT NULL default '0',\n                ADD `tplname` varchar(200) default NULL,\n                ADD `date_mod` datetime default NULL";
        $DB->queryOrDie($query, "0.7 add name, is_template, tplname, date_mod in glpi_ocs_link");
        $query = "UPDATE `glpi_ocs_config`\n                SET `name` = `ocs_db_host`";
        $DB->queryOrDie($query, "0.7 add name in glpi_ocs_config");
    }
    if (!FieldExists("glpi_ocs_config", "import_registry", false)) {
        $query = "ALTER TABLE `glpi_ocs_config`\n                ADD `import_registry` INT NOT NULL default '0' AFTER `import_device_modems`";
        $DB->queryOrDie($query, "0.7 add import_registry in glpi_ocs_config");
    }
    if (FieldExists("glpi_ocs_config", "import_tag_field", false)) {
        $query = "ALTER TABLE `glpi_ocs_config`\n                DROP `import_tag_field`";
        $DB->queryOrDie($query, "0.7 drop import_tag_field in glpi_ocs_config");
    }
    if (!FieldExists("glpi_ocs_config", "import_software_licensetype", false)) {
        $query = "ALTER TABLE `glpi_ocs_config`\n                ADD `import_software_licensetype` VARCHAR(255) DEFAULT 'global'\n                     AFTER `import_software`";
        $DB->queryOrDie($query, "0.7 add import_software_licensetype in glpi_ocs_config");
    }
    if (!FieldExists("glpi_ocs_config", "import_software_buy", false)) {
        $query = "ALTER TABLE `glpi_ocs_config`\n                ADD `import_software_buy` INT NOT NULL DEFAULT '1' AFTER `import_software`";
        $DB->queryOrDie($query, "0.7 add import_software_buy in glpi_ocs_config");
    }
    if (!TableExists("glpi_registry")) {
        $query = "CREATE TABLE `glpi_registry` (\n                  `ID` int(10) NOT NULL auto_increment,\n                  `computer_id` int(10) NOT NULL DEFAULT '0',\n                  `registry_hive` varchar(45) NOT NULL,\n                  `registry_path` varchar(255) NOT NULL,\n                  `registry_value` varchar(255) NOT NULL,\n                  PRIMARY KEY (`ID`),\n                  KEY `computer_id` (`computer_id`)\n                ) ENGINE=MyISAM AUTO_INCREMENT=0 DEFAULT CHARSET=utf8";
        $DB->queryOrDie($query, "0.7 add glpi_registry table");
    }
    if (!FieldExists("glpi_ocs_link", "import_ip", false)) {
        $query = "ALTER TABLE `glpi_ocs_link`\n                ADD COLUMN `import_ip` LONGTEXT";
        $DB->queryOrDie($query, "0.7 add import_ip in glpi_ocs_link");
    }
    //// Enum clean
    // Enum 0-1
    $enum01 = array();
    $template_tables = array("glpi_computers", "glpi_networking", "glpi_printers", "glpi_monitors", "glpi_peripherals", "glpi_software", "glpi_phones", "glpi_ocs_config");
    foreach ($template_tables as $table) {
        if (!isset($enum01[$table])) {
            $enum01[$table] = array();
        }
        $enum01[$table][] = "is_template";
    }
    $enum01["glpi_config"][] = "auto_assign";
    $enum01["glpi_config"][] = "public_faq";
    $enum01["glpi_config"][] = "url_in_mail";
    $enum01["glpi_profiles"][] = "is_default";
    $enum01["glpi_monitors"][] = "is_global";
    $enum01["glpi_peripherals"][] = "is_global";
    $enum01["glpi_phones"][] = "is_global";
    $enum01["glpi_printers"][] = "is_global";
    $enum01["glpi_reminder"][] = "rv";
    $enum01["glpi_contract_device"][] = "is_template";
    $enum01["glpi_doc_device"][] = "is_template";
    foreach ($enum01 as $table => $fields) {
        foreach ($fields as $key => $field) {
            if (FieldExists($table, $field, false)) {
                $query = "ALTER TABLE `{$table}`\n                      ADD `tmp_convert_enum` SMALLINT NOT NULL DEFAULT '0' AFTER `{$field}` ";
                $DB->queryOrDie($query, "0.7 alter {$table} add new field tmp_convert_enum");
                $query = "UPDATE `{$table}`\n                      SET `tmp_convert_enum` = '1'\n                      WHERE `{$field}` = '1'";
                $DB->queryOrDie($query, "0.7 update {$table} to set correct values to alod enum01 {$field}");
                $query = "UPDATE `{$table}`\n                      SET `tmp_convert_enum` = '0'\n                      WHERE `{$field}` = '0'";
                $DB->queryOrDie($query, "0.7 update {$table} to set correct values to alod enum01 {$field}");
                $query = "ALTER TABLE `{$table}`\n                      DROP `{$field}` ";
                $DB->queryOrDie($query, "0.7 alter {$table} drop tmp enum field");
                $query = "ALTER TABLE `{$table}`\n                      CHANGE `tmp_convert_enum` `{$field}` SMALLINT NOT NULL DEFAULT '0'";
                $DB->queryOrDie($query, "0.7 alter {$table} move enum {$field} to tmp field");
                if ($table != "glpi_config" && $table != "glpi_profiles") {
                    $query = "ALTER TABLE `{$table}`\n                         ADD KEY (`{$field}`)";
                    $DB->queryOrDie($query, "0.7 alter {$table} add deleted key");
                }
            }
        }
    }
    $enumYN["N"]["glpi_contracts"][] = "monday";
    // N
    $enumYN["N"]["glpi_contracts"][] = "saturday";
    // N
    $enumYN["Y"]["glpi_device_drive"][] = "is_writer";
    // Y
    $enumYN["N"]["glpi_device_control"][] = "raid";
    // Y -> N
    $enumYN["Y"]["glpi_device_power"][] = "atx";
    // Y
    $enumYN["N"]["glpi_licenses"][] = "oem";
    // N
    $enumYN["Y"]["glpi_licenses"][] = "buy";
    // Y
    $enumYN["N"]["glpi_software"][] = "is_update";
    // N
    $enumYN["Y"]["glpi_type_docs"][] = "upload";
    // Y
    $deleted_tables = array("glpi_computers", "glpi_networking", "glpi_printers", "glpi_monitors", "glpi_peripherals", "glpi_software", "glpi_cartridges_type", "glpi_contracts", "glpi_contacts", "glpi_enterprises", "glpi_docs", "glpi_phones", "glpi_consumables_type");
    foreach ($deleted_tables as $table) {
        if (!isset($enum01[$table])) {
            $enum01[$table] = array();
        }
        $enumYN["N"][$table][] = "deleted";
    }
    foreach ($enumYN as $default => $tmptbl) {
        foreach ($tmptbl as $table => $fields) {
            foreach ($fields as $key => $field) {
                if (FieldExists($table, $field, false)) {
                    $newdef = 0;
                    if ($default == "Y") {
                        $newdef = 1;
                    }
                    $query = "ALTER TABLE `{$table}`\n                         ADD `tmp_convert_enum` SMALLINT NOT NULL DEFAULT '{$newdef}' AFTER `{$field}` ";
                    $DB->queryOrDie($query, "0.7 alter {$table} add new field tmp_convert_enum");
                    $query = "UPDATE `{$table}`\n                         SET `tmp_convert_enum` = '1'\n                         WHERE `{$field}` = 'Y'";
                    $DB->queryOrDie($query, "0.7 update {$table} to set correct values to alod enum01 {$field}");
                    $query = "UPDATE `{$table}`\n                         SET `tmp_convert_enum` = '0'\n                         WHERE `{$field}` = 'N'";
                    $DB->queryOrDie($query, "0.7 update {$table} to set correct values to alod enum01 {$field}");
                    $query = "ALTER TABLE `{$table}`\n                         DROP `{$field}` ";
                    $DB->queryOrDie($query, "0.7 alter {$table} drop tmp enum field");
                    $query = "ALTER TABLE `{$table}`\n                         CHANGE `tmp_convert_enum` `{$field}` SMALLINT NOT NULL DEFAULT '{$newdef}'";
                    $DB->queryOrDie($query, "0.7 alter {$table} move enum {$field} to tmp field");
                    if ($field == "deleted" || $table == "glpi_licenses" || $table == "glpi_software" || $table == "glpi_type_docs") {
                        $query = "ALTER TABLE `{$table}`\n                            ADD KEY (`{$field}`)";
                        $DB->queryOrDie($query, "0.7 alter {$table} add deleted key");
                    }
                }
            }
        }
    }
    if (FieldExists("glpi_tracking", "is_group", false)) {
        $query = "ALTER TABLE `glpi_tracking`\n                DROP `is_group`";
        $DB->queryOrDie($query, "0.7 drop is_group from tracking");
    }
    $enumYesNo["glpi_kbitems"][] = "faq";
    $enumYesNo["glpi_tracking"][] = "emailupdates";
    $enumYesNo["glpi_users"][] = "tracking_order";
    foreach ($enumYesNo as $table => $fields) {
        foreach ($fields as $key => $field) {
            if (FieldExists($table, $field, false)) {
                $query = "ALTER TABLE `{$table}`\n                      ADD `tmp_convert_enum` SMALLINT NOT NULL DEFAULT '0' AFTER `{$field}` ";
                $DB->queryOrDie($query, "0.7 alter {$table} add new field tmp_convert_enum");
                $query = "UPDATE `{$table}`\n                      SET `tmp_convert_enum` = '1'\n                      WHERE `{$field}` = 'yes'";
                $DB->queryOrDie($query, "0.7 update {$table} to set correct values to alod enum01 {$field}");
                $query = "UPDATE `{$table}`\n                      SET `tmp_convert_enum` = '0'\n                      WHERE `{$field}` = 'no'";
                $DB->queryOrDie($query, "0.7 update {$table} to set correct values to alod enum01 {$field}");
                $query = "ALTER TABLE `{$table}`\n                      DROP `{$field}` ";
                $DB->queryOrDie($query, "0.7 alter {$table} drop tmp enum field");
                $query = "ALTER TABLE `{$table}`\n                      CHANGE `tmp_convert_enum` `{$field}` SMALLINT NOT NULL DEFAULT '0'";
                $DB->queryOrDie($query, "0.7 alter {$table} move enum {$field} to tmp field");
                if ($table == "glpi_kbitems") {
                    $query = "ALTER TABLE `{$table}`\n                         ADD KEY (`{$field}`)";
                    $DB->queryOrDie($query, "0.7 alter {$table} add deleted key");
                }
            }
        }
    }
    // Reste enum : glpi_tracking.status et glpi_device_gfxcard.interface
    if (FieldExists("glpi_tracking", "status", false)) {
        $query = "ALTER TABLE `glpi_tracking`\n                CHANGE `status` `status` VARCHAR( 255 ) DEFAULT 'new'";
        $DB->queryOrDie($query, "0.7 alter status from tracking");
    }
    if (FieldExists("glpi_device_gfxcard", "interface", false)) {
        $query = "ALTER TABLE `glpi_device_gfxcard`\n                CHANGE `interface` `interface` VARCHAR( 255 ) NULL DEFAULT 'PCI-X'";
        $DB->queryOrDie($query, "0.7 alter interface from glpi_device_gfxcard");
    }
    if (!TableExists("glpi_rules_actions")) {
        $query = "CREATE TABLE `glpi_rules_actions` (\n                  `ID` int(11) NOT NULL auto_increment,\n                  `FK_rules` int(11) NOT NULL DEFAULT '0',\n                  `action_type` varchar(255) NOT NULL,\n                  `field` varchar(255) NOT NULL,\n                  `value` varchar(255) NOT NULL,\n                  PRIMARY KEY (`ID`),\n                  KEY `FK_rules` (`FK_rules`)\n                ) ENGINE=MyISAM  DEFAULT CHARSET=utf8";
        $DB->queryOrDie($query, "0.7 add table glpi_rules_descriptions");
    }
    if (!TableExists("glpi_rules_criterias")) {
        $query = "CREATE TABLE `glpi_rules_criterias` (\n                  `ID` int(11) NOT NULL auto_increment,\n                  `FK_rules` int(11) NOT NULL DEFAULT '0',\n                  `criteria` varchar(255) NOT NULL,\n                  `condition` smallint(4) NOT NULL DEFAULT '0',\n                  `pattern` varchar(255) NOT NULL,\n                  PRIMARY KEY (`ID`),\n                  KEY `FK_rules` (`FK_rules`)\n                ) ENGINE=MyISAM  DEFAULT CHARSET=utf8";
        $DB->queryOrDie($query, "0.7 add table glpi_rules_criterias");
    }
    if (!TableExists("glpi_rules_descriptions")) {
        $query = "CREATE TABLE `glpi_rules_descriptions` (\n                  `ID` int(11) NOT NULL auto_increment,\n                  `FK_entities` int(11) NOT NULL default '-1',\n                  `rule_type` smallint(4) NOT NULL DEFAULT '0',\n                  `ranking` int(11) NOT NULL DEFAULT '0',\n                  `name` varchar(255) NOT NULL,\n                  `description` text NOT NULL,\n                  `match` varchar(255) NOT NULL,\n                  PRIMARY KEY (`ID`)\n                ) ENGINE=MyISAM  DEFAULT CHARSET=utf8";
        $DB->queryOrDie($query, "0.7 add table glpi_rules_actions");
    }
    if (!FieldExists("glpi_config", "use_cache", false)) {
        $query = "ALTER TABLE `glpi_config`\n                ADD `use_cache` SMALLINT NOT NULL DEFAULT '1' AFTER `debug`";
        $DB->queryOrDie($query, "0.7 alter config add use_cache");
    }
    if (TableExists("glpi_rules_descriptions")) {
        //If no rule exists, then create a default one
        $query = "SELECT `ID`\n                FROM `glpi_rules_descriptions`";
        $result = $DB->query($query);
        if ($DB->numrows($result) == 0) {
            //Insert rule to affect machines in the Root entity
            $query = "INSERT INTO `glpi_rules_descriptions`\n                          (`FK_entities`, `rule_type`, `ranking`, `name`, `description`, `match`)\n                   VALUES (-1, 0, 0, 'Root', '', 'AND')";
            $DB->queryOrDie($query, "0.7 add default ocs affectation rule");
            $query = "SELECT `ID`\n                   FROM `glpi_rules_descriptions`\n                   WHERE `name` = 'Root'\n                         AND `rule_type` = '0'";
            $result = $DB->query($query);
            //Get the defaut rule's ID
            $datas = $DB->fetch_array($result);
            $query = "INSERT INTO `glpi_rules_criterias`\n                          (`FK_rules`, `criteria`, `condition`, `pattern`)\n                   VALUES (" . $datas["ID"] . ", 'TAG', 0, '*')";
            $DB->queryOrDie($query, "0.7 add default ocs criterias");
            $query = "INSERT INTO `glpi_rules_actions`\n                          (`FK_rules`, `action_type`, `field`, `value`)\n                   VALUES (" . $datas["ID"] . ", 'assign', 'FK_entities', '0')";
            $DB->queryOrDie($query, "0.7 add default ocs actions");
            //Insert rule to affect users from LDAP to the root entity
            $query = "INSERT INTO `glpi_rules_descriptions`\n                          (`FK_entities`, `rule_type`, `ranking`, `name`, `description`, `match`)\n                   VALUES (-1, 1, 1, 'Root', '', 'OR')";
            $DB->queryOrDie($query, "0.7 add default right affectation rule");
            $query = "SELECT `ID`\n                   FROM `glpi_rules_descriptions`\n                   WHERE `name` = 'Root'\n                         AND `rule_type` = '1'";
            $result = $DB->query($query);
            //Get the defaut rule's ID
            $datas = $DB->fetch_array($result);
            //Criterias
            $query = "INSERT INTO `glpi_rules_criterias`\n                          (`FK_rules`, `criteria`, `condition`, `pattern`)\n                   VALUES (" . $datas["ID"] . ", 'uid', 0, '*')";
            $DB->queryOrDie($query, "0.7 add default right criterias");
            $query = "INSERT INTO `glpi_rules_criterias`\n                          (`FK_rules`, `criteria`, `condition`, `pattern`)\n                   VALUES (" . $datas["ID"] . ", 'samaccountname', 0, '*')";
            $DB->queryOrDie($query, "0.7 add default right criterias");
            $query = "INSERT INTO `glpi_rules_criterias`\n                          (`FK_rules`, `criteria`, `condition`, `pattern`)\n                   VALUES (" . $datas["ID"] . ", 'MAIL_EMAIL', 0, '*')";
            $DB->queryOrDie($query, "0.7 add default right criterias");
            //Action
            $query = "INSERT INTO `glpi_rules_actions`\n                          (`FK_rules`, `action_type`, `field`, `value`)\n                   VALUES (" . $datas["ID"] . ", 'assign', 'FK_entities', '0')";
            $DB->queryOrDie($query, "0.7 add default right actions");
        }
    }
    if (!TableExists("glpi_ocs_admin_link")) {
        $query = "CREATE TABLE `glpi_ocs_admin_link` (\n                  `ID` int(10) unsigned NOT NULL auto_increment,\n                  `glpi_column` varchar(255) NULL,\n                  `ocs_column` varchar(255) NULL,\n                  `ocs_server_id` int(11) NOT NULL,\n                  PRIMARY KEY (`ID`)\n                ) ENGINE=MyISAM AUTO_INCREMENT=0 DEFAULT CHARSET=utf8";
        $DB->queryOrDie($query, "0.7 add table glpi_ocs_admin_link");
    }
    // Add title to tracking
    if (!FieldExists("glpi_tracking", "name", false)) {
        $query = "ALTER TABLE `glpi_tracking`\n                ADD `name` varchar(255) NULL AFTER `FK_entities`";
        $DB->queryOrDie($query, "0.7 alter tracking add name");
        $query = "UPDATE `glpi_tracking`\n                SET `name` = SUBSTRING(REPLACE(contents,'\n',' '),1,50)";
        $DB->queryOrDie($query, "0.7 update title of glpi_tracking");
    }
    if (FieldExists("glpi_reminder", "title", false)) {
        $query = "ALTER TABLE `glpi_reminder`\n                CHANGE `title` `title` VARCHAR( 255 ) NULL DEFAULT NULL ";
        $DB->queryOrDie($query, "0.7 alter title in glpi_reminder");
    }
    if (!TableExists("glpi_rules_ldap_parameters")) {
        $query = "CREATE TABLE `glpi_rules_ldap_parameters` (\n                  `ID` int(11) NOT NULL auto_increment,\n                  `name` varchar(255) NOT NULL,\n                  `value` varchar(255) NOT NULL,\n                  `rule_type` smallint(6) NOT NULL default '1',\n                  PRIMARY KEY (`ID`)\n                ) ENGINE=MyISAM  DEFAULT CHARSET=utf8";
        $DB->queryOrDie($query, "0.7 add table glpi_rules_ldap_parameters");
        $query = "INSERT INTO `glpi_rules_ldap_parameters`\n                       (`ID`, `name`, `value`, `rule_type`)\n                VALUES (1, '(LDAP)Organization', 'o', 1),\n                       (2, '(LDAP)Common Name', 'cn', 1),\n                       (3, '(LDAP)Department Number', 'departmentnumber', 1),\n                       (4, '(LDAP)Email', 'mail', 1),\n                       (5, 'Object Class', 'objectclass', 1),\n                       (6, '(LDAP)User ID', 'uid', 1),\n                       (7, '(LDAP)Telephone Number', 'phone', 1),\n                       (8, '(LDAP)Employee Number', 'employeenumber', 1),\n                       (9, '(LDAP)Manager', 'manager', 1),\n                       (10, '(LDAP)DistinguishedName', 'dn', 1),\n                       (11, '(AD)DistinguishedName', 'distinguishedname', 1),\n                       (12, '(AD)User ID', 'samaccountname', 1)";
        $DB->queryOrDie($query, "0.7 add standard values to glpi_rules_ldap_parameters");
    }
    if (!FieldExists("glpi_config", "helpdeskhelp_url", false)) {
        $query = "ALTER TABLE `glpi_config`\n                ADD `helpdeskhelp_url` VARCHAR( 255 ) NULL DEFAULT NULL ";
        $DB->queryOrDie($query, "0.7 add helpdeskhelp_url in glpi_config");
    }
    if (!FieldExists("glpi_config", "centralhelp_url", false)) {
        $query = "ALTER TABLE `glpi_config`\n                ADD `centralhelp_url` VARCHAR( 255 ) NULL DEFAULT NULL ";
        $DB->queryOrDie($query, "0.7 add centralhelp_url in glpi_config");
    }
    if (!FieldExists("glpi_config", "default_rubdoc_tracking", false)) {
        $query = "ALTER TABLE `glpi_config`\n                ADD `default_rubdoc_tracking` int(11) default '0' ";
        $DB->queryOrDie($query, "0.7 add default_rubdoc_tracking in glpi_config");
    }
    if (!FieldExists("glpi_users", "deleted", false)) {
        $query = "ALTER TABLE `glpi_users`\n                ADD `deleted` SMALLINT NOT NULL DEFAULT 0 ";
        $DB->queryOrDie($query, "0.7 add deleted in glpi_users");
        $query = "ALTER TABLE `glpi_users`\n                ADD KEY (`deleted`)";
        $DB->queryOrDie($query, "0.7 add key deleted in glpi_users");
    }
    if (!FieldExists("glpi_reservation_item", "active", false)) {
        $query = "ALTER TABLE `glpi_reservation_item`\n                ADD `active` smallint(6) NOT NULL default '1' ";
        $DB->queryOrDie($query, "0.7 add active in glpi_reservation_item");
    }
    if (!FieldExists("glpi_tracking_planning", "state", false)) {
        $query = "ALTER TABLE `glpi_tracking_planning`\n                ADD `state` smallint(6) NOT NULL default '1' ";
        $DB->queryOrDie($query, "0.7 add state in glpi_tracking_planning");
        $query = "UPDATE `glpi_tracking_planning`\n                SET `state` = '2'\n                WHERE `end` < NOW()";
        $DB->queryOrDie($query, "0.7 update values of state in glpi_tracking_planning");
    }
    if (!FieldExists("glpi_reminder", "state", false)) {
        $query = "ALTER TABLE `glpi_reminder`\n                ADD `state` smallint(6) NOT NULL default '0' ";
        $DB->queryOrDie($query, "0.7 add state in glpi_reminder");
    }
    if (!FieldExists("glpi_tracking", "recipient", false)) {
        $query = "ALTER TABLE `glpi_tracking`\n                ADD `recipient` INT NOT NULL DEFAULT '0' AFTER `author` ";
        $DB->queryOrDie($query, "0.7 add recipient in glpi_tracking");
        $query = "UPDATE `glpi_tracking`\n                SET `recipient` = `author`";
        $DB->queryOrDie($query, "0.7 update recipient in glpi_tracking");
    }
    if (!isIndex("glpi_tracking", "recipient")) {
        $query = "ALTER TABLE `glpi_tracking`\n                ADD INDEX (`recipient`) ";
        $DB->queryOrDie($query, "0.7 add recipient index in glpi_tracking");
    }
    if (!FieldExists("glpi_ocs_config", "deconnection_behavior", false)) {
        $query = "ALTER TABLE `glpi_ocs_config`\n                ADD COLUMN `deconnection_behavior` VARCHAR(45)";
        $DB->queryOrDie($query, "0.7 add state in glpi_reminder");
    }
    // Rights
    if (!FieldExists("glpi_profiles", "search_config_global", false)) {
        $query = "ALTER TABLE `glpi_profiles`\n                ADD COLUMN `search_config_global` char(1) default NULL AFTER `search_config`";
        $DB->queryOrDie($query, "0.7 add search_config_global in glpi_profiles");
        $query = "UPDATE `glpi_profiles`\n                SET `search_config_global` = `search_config`";
        $DB->queryOrDie($query, "0.7 update search_config_global values in glpi_profiles");
        $query = "UPDATE `glpi_profiles`\n                SET `search_config` = 'w'\n                WHERE `interface` = 'central'";
        $DB->queryOrDie($query, "0.7 update search_confi values in glpi_profiles");
    }
    if (!FieldExists("glpi_profiles", "entity", false)) {
        $query = "ALTER TABLE `glpi_profiles`\n                ADD COLUMN `entity` char(1) default NULL AFTER `group`";
        $DB->queryOrDie($query, "0.7 add entity in glpi_profiles");
        $query = "UPDATE `glpi_profiles`\n                SET `entity` = `config`";
        $DB->queryOrDie($query, "0.7 update entity values in glpi_profiles");
    }
    if (!FieldExists("glpi_profiles", "entity_dropdown", false)) {
        $query = "ALTER TABLE `glpi_profiles`\n                ADD COLUMN `entity_dropdown` char(1) default NULL AFTER `dropdown`";
        $DB->queryOrDie($query, "0.7 add entity_dropdown in glpi_profiles");
        $query = "UPDATE `glpi_profiles`\n                SET `entity_dropdown` = `dropdown`";
        $DB->queryOrDie($query, "0.7 update entity_dropdown values in glpi_profiles");
    }
    if (!FieldExists("glpi_profiles", "sync_ocsng", false)) {
        $query = "ALTER TABLE `glpi_profiles`\n                ADD COLUMN `sync_ocsng` char(1) default NULL AFTER `ocsng`";
        $DB->queryOrDie($query, "0.7 add sync_ocsng in glpi_profiles");
        $query = "UPDATE `glpi_profiles`\n                SET `sync_ocsng` = `ocsng`";
        $DB->queryOrDie($query, "0.7 update sync_ocsng values in glpi_profiles");
    }
    if (!FieldExists("glpi_profiles", "view_ocsng", false)) {
        $query = "ALTER TABLE `glpi_profiles`\n                ADD COLUMN `view_ocsng` char(1) default NULL AFTER `ocsng`";
        $DB->queryOrDie($query, "0.7 add view_ocsng in glpi_profiles");
        $query = "UPDATE `glpi_profiles`\n                SET `view_ocsng` = 'r'\n                WHERE `interface` = 'central'";
        $DB->queryOrDie($query, "0.7 update view_ocsng values in glpi_profiles");
    }
    if (!FieldExists("glpi_profiles", "rule_ldap", false)) {
        $query = "ALTER TABLE `glpi_profiles`\n                ADD COLUMN `rule_ldap` char(1) default NULL AFTER `config`";
        $DB->queryOrDie($query, "0.7 add rule_ldap in glpi_profiles");
        $query = "UPDATE `glpi_profiles`\n                SET `rule_ldap` = `config`";
        $DB->queryOrDie($query, "0.7 update rule_ldap values in glpi_profiles");
    }
    if (!FieldExists("glpi_profiles", "rule_ocs", false)) {
        $query = "ALTER TABLE `glpi_profiles`\n                ADD COLUMN `rule_ocs` char(1) default NULL AFTER `config`";
        $DB->queryOrDie($query, "0.7 add rule_ocs in glpi_profiles");
        $query = "UPDATE `glpi_profiles`\n                SET `rule_ocs` = `config`";
        $DB->queryOrDie($query, "0.7 update rule_ocs values in glpi_profiles");
    }
    if (!FieldExists("glpi_profiles", "rule_tracking", false)) {
        $query = "ALTER TABLE `glpi_profiles`\n                ADD COLUMN `rule_tracking` char(1) default NULL AFTER `config`";
        $DB->queryOrDie($query, "0.7 add rule_tracking in glpi_profiles");
        $query = "UPDATE `glpi_profiles`\n                SET `rule_tracking` = `config`";
        $DB->queryOrDie($query, "0.7 update rule_tracking values in glpi_profiles");
    }
    if (!FieldExists("glpi_profiles", "update_followups", false)) {
        $query = "ALTER TABLE `glpi_profiles`\n                ADD COLUMN `update_followups` char(1) default NULL AFTER `observe_ticket`";
        $DB->queryOrDie($query, "0.7 add update_followups in glpi_profiles");
        $query = "UPDATE `glpi_profiles`\n                SET `update_followups` = `show_full_ticket`";
        $DB->queryOrDie($query, "0.7 update update_followups values in glpi_profiles");
    }
    //Software version's modifications
    //First add the version field to the licenses table
    if (!FieldExists("glpi_licenses", "version", false)) {
        $query = "ALTER TABLE `glpi_licenses`\n                ADD COLUMN `version` varchar(255) default NULL AFTER `sID`";
        $DB->queryOrDie($query, "0.7 add version in glpi_licenses");
        $sql = "SELECT `ID`, `version`\n              FROM `glpi_software`";
        $result = $DB->query($sql);
        if ($DB->numrows($result) > 0) {
            while ($soft = $DB->fetch_array($result)) {
                $sql = "UPDATE `glpi_licenses`\n                    SET `version` = '" . $soft["version"] . "'\n                    WHERE `sID` = " . $soft["ID"];
                $DB->query($sql);
            }
        }
    }
    if (FieldExists("glpi_software", "version", false)) {
        $query = "ALTER TABLE `glpi_software`\n                DROP `version`";
        $DB->queryOrDie($query, "0.7 delete version in glpi_software");
    }
    // CLean multiple free / global licenses
    $query = "SELECT count(*)AS CPT, `glpi_licenses`.*\n             FROM `glpi_licenses`\n             WHERE `serial` = 'global'\n                   OR `serial` = 'free'\n             GROUP BY `sID`, `serial`, `expire`, `buy`\n             HAVING CPT > 1";
    $result = $DB->queryOrDie($query, "0.7 check multiple free global licenses");
    if ($DB->numrows($result)) {
        while ($data = $DB->fetch_array($result)) {
            // Get licenses AND installations
            if ($data['expire'] == "") {
                $expire_search = " AND `glpi_licenses`.`expire` IS NULL";
            } else {
                $expire_search = " AND `glpi_licenses`.`expireÈ = '" . $data['expire'] . "'";
            }
            $query = "SELECT `glpi_licenses`.`ID`\n                   FROM `glpi_licenses`\n                   WHERE `serial` ='" . $data['serial'] . "'\n                         AND `sID` ='" . $data['sID'] . "'\n                         {$expire_search}\n                         AND `buy` ='" . $data['buy'] . "'";
            $result2 = $DB->query($query);
            if ($DB->numrows($result2)) {
                $licIDs = array();
                while ($data2 = $DB->fetch_array($result2)) {
                    $licIDs[] = $data2['ID'];
                }
                if (count($licIDs) > 1) {
                    $refID = array_pop($licIDs);
                    $query = "UPDATE `glpi_inst_software`\n                         SET `license` = '{$refID}'\n                         WHERE `license` IN (";
                    $first = true;
                    foreach ($licIDs as $id) {
                        if ($first) {
                            $first = false;
                        } else {
                            $query .= ", ";
                        }
                        $query .= "'{$id}'";
                        $query_del = "DELETE\n                                FROM `glpi_licenses`\n                                WHERE `ID` = '{$id}'";
                        $DB->query($query_del);
                    }
                    $query .= ")";
                    $DB->query($query);
                }
            }
        }
    }
    // Clean multiple reservation item
    $query = "SELECT count(*) AS CPT, `glpi_reservation_item`.*\n             FROM `glpi_reservation_item`\n             GROUP BY `device_type`, `id_device`\n             HAVING CPT > 1";
    $result = $DB->queryOrDie($query, "0.7 check multiple free global licenses");
    if ($DB->numrows($result)) {
        while ($data = $DB->fetch_array($result)) {
            $refID = $data['ID'];
            // Get duplicates
            $query2 = "SELECT *\n                    FROM `glpi_reservation_item`\n                    WHERE `device_type` = '" . $data['device_type'] . "'\n                         AND `id_device` = '" . $data['id_device'] . "'\n                         AND `ID` <> '{$refID}'";
            $result2 = $DB->query($query2);
            if ($DB->numrows($result2)) {
                while ($data2 = $DB->fetch_array($result2)) {
                    // Update réservations
                    $query = "UPDATE `glpi_reservation_resa`\n                         SET `id_item` = '{$refID}'\n                         WHERE `id_item` = '" . $data2['ID'] . "'";
                    $DB->query($query);
                    // Delete Reservation Item
                    $query = "DELETE\n                         FROM `glpi_reservation_item`\n                         WHERE `ID` = '" . $data2['ID'] . "'";
                    $DB->query($query);
                }
            }
        }
    }
    if (!FieldExists("glpi_networking_ports", "netmask", false)) {
        $query = "ALTER TABLE `glpi_networking_ports`\n                ADD COLUMN `netmask` VARCHAR( 255 ) NULL DEFAULT NULL";
        $DB->queryOrDie($query, "0.7 add netmask in glpi_networking_ports");
    }
    if (!FieldExists("glpi_networking_ports", "gateway", false)) {
        $query = "ALTER TABLE `glpi_networking_ports`\n                ADD COLUMN `gateway` VARCHAR( 255 ) NULL DEFAULT NULL";
        $DB->queryOrDie($query, "0.7 add gateway in glpi_networking_ports");
    }
    if (!FieldExists("glpi_networking_ports", "subnet", false)) {
        $query = "ALTER TABLE `glpi_networking_ports`\n                ADD COLUMN subnet VARCHAR( 255 ) NULL DEFAULT NULL";
        $DB->queryOrDie($query, "0.7 add subnet in glpi_networking_ports");
    }
    if (FieldExists("glpi_networking_ports", "name", false)) {
        $query = "ALTER TABLE `glpi_networking_ports`\n                CHANGE `name` `name` VARCHAR( 255 ) NULL DEFAULT NULL,\n                CHANGE `ifaddr` `ifaddr` VARCHAR( 255 ) NULL DEFAULT NULL,\n                CHANGE `ifmac` `ifmac` VARCHAR( 255 ) NULL DEFAULT NULL ";
        $DB->queryOrDie($query, "0.7 alter networking_ports fields");
    }
    // mailgate
    if (!TableExists("glpi_mailgate")) {
        $query = "CREATE TABLE `glpi_mailgate` (\n                  `ID` int(11) NOT NULL auto_increment,\n                  `name` varchar(255) collate utf8_unicode_ci default NULL,\n                  `FK_entities` int(11) NOT NULL default '0',\n                  `host` varchar(255) collate utf8_unicode_ci NOT NULL,\n                  `login` varchar(255) collate utf8_unicode_ci NOT NULL,\n                  `password` varchar(255) collate utf8_unicode_ci NOT NULL,\n                  PRIMARY KEY (`ID`)\n                ) ENGINE=MyISAM";
        $DB->queryOrDie($query, "0.7 add glpi_mailgate");
        $query = "INSERT INTO `glpi_display`\n                       (`type`, `num`, `rank`, `FK_users`)\n                VALUES (35, 80, 1, 0)";
        $DB->queryOrDie($query, "0.7 add glpi_mailgate display values");
    }
    if (!FieldExists("glpi_computers", "os_license_number", false)) {
        $query = "ALTER TABLE `glpi_computers`\n                ADD COLUMN `os_license_number` VARCHAR( 255 ) NULL DEFAULT NULL AFTER os_sp";
        $DB->queryOrDie($query, "0.7 alter glpi_computers field " . __('Serial of the operating system'));
    }
    if (!FieldExists("glpi_computers", "os_license_id", false)) {
        $query = "ALTER TABLE `glpi_computers`\n                ADD COLUMN `os_license_id` VARCHAR( 255 ) NULL DEFAULT NULL AFTER os_license_number";
        $DB->queryOrDie($query, "0.7 alter glpi_computers field " . __('Product ID of the operating system'));
    }
    if (!FieldExists("glpi_ocs_config", "import_os_serial", false)) {
        $query = "ALTER TABLE `glpi_ocs_config`\n                ADD `import_os_serial` INT( 2 ) NULL AFTER `import_registry`";
        $DB->queryOrDie($query, "0.7 alter glpi_computers field import_ocs_serial");
    }
    if (!FieldExists("glpi_auth_ldap", "use_dn", false)) {
        $query = "ALTER TABLE `glpi_auth_ldap`\n                ADD `use_dn` INT( 1 ) NOT NULL DEFAULT '1'";
        $DB->queryOrDie($query, "0.7 alter glpi_computers field use_dn " . $DB->error());
    }
    if (!FieldExists("glpi_config", "monitors_management_restrict", false)) {
        $query = "ALTER TABLE `glpi_config`\n                ADD `monitors_management_restrict` INT( 1 ) NOT NULL DEFAULT '2'";
        $DB->queryOrDie($query, "0.7 alter glpi_computers field monitors_management_restrict " . $DB->error());
    }
    if (!FieldExists("glpi_config", "phones_management_restrict", false)) {
        $query = "ALTER TABLE `glpi_config`\n                ADD `phones_management_restrict` INT( 1 ) NOT NULL DEFAULT '2'";
        $DB->queryOrDie($query, "0.7 alter glpi_computers field phones_management_restrict " . $DB->error());
    }
    if (!FieldExists("glpi_config", "peripherals_management_restrict", false)) {
        $query = "ALTER TABLE `glpi_config`\n                ADD `peripherals_management_restrict` INT( 1 ) NOT NULL DEFAULT '2'";
        $DB->queryOrDie($query, "0.7 alter glpi_computers field peripherals_management_restrict " . $DB->error());
    }
    if (!FieldExists("glpi_config", "printers_management_restrict", false)) {
        $query = "ALTER TABLE `glpi_config`\n                ADD `printers_management_restrict` INT( 1 ) NOT NULL DEFAULT '2'";
        $DB->queryOrDie($query, "0.7 alter glpi_computers field printers_management_restrict " . $DB->error());
    }
    if (!FieldExists("glpi_config", "licenses_management_restrict", false)) {
        $query = "ALTER TABLE `glpi_config`\n                ADD `licenses_management_restrict` INT( 1 ) NOT NULL DEFAULT '2'";
        $DB->queryOrDie($query, "0.7 alter glpi_computers field licenses_management_restrict " . $DB->error());
    }
    if (!FieldExists("glpi_config", "license_deglobalisation", false)) {
        $query = "ALTER TABLE `glpi_config`\n                ADD `license_deglobalisation` INT( 1 ) NOT NULL DEFAULT '1'";
        $DB->queryOrDie($query, "0.7 alter glpi_computers field license_deglobalisation " . $DB->error());
    }
    if (!FieldExists("glpi_registry", "registry_ocs_name", false)) {
        $query = "ALTER TABLE `glpi_registry`\n                ADD COLUMN `registry_ocs_name` char(255) NOT NULL default ''";
        $DB->queryOrDie($query, "0.7 add registry_ocs_name in glpi_registry");
    }
    if (!FieldExists("glpi_config", "use_errorlog", false)) {
        $query = "ALTER TABLE `glpi_config`\n                ADD COLUMN `use_errorlog` INT( 1 ) NOT NULL default 0";
        $DB->queryOrDie($query, "0.7 add use_errorlog in glpi_config");
    }
    if (!FieldExists("glpi_config", "glpi_timezone", false)) {
        $query = "ALTER TABLE `glpi_config`\n                ADD COLUMN `glpi_timezone` VARCHAR( 4 ) NOT NULL default 0";
        $DB->queryOrDie($query, "0.7 add glpi_timezone in glpi_config");
    }
    if (!FieldExists("glpi_auth_ldap", "timezone", false)) {
        $query = "ALTER TABLE `glpi_auth_ldap`\n                ADD COLUMN `timezone` VARCHAR( 4 ) NOT NULL default 0";
        $DB->queryOrDie($query, "0.7 add timezone in glpi_auth_ldap");
    }
    if (!FieldExists("glpi_ocs_config", "glpi_link_enabled", false)) {
        $query = "ALTER TABLE `glpi_ocs_config`\n                ADD COLUMN `glpi_link_enabled` int(1) NOT NULL,\n                ADD COLUMN `link_ip` int(1) NOT NULL,\n                ADD COLUMN `link_name` int(1) NOT NULL,\n                ADD COLUMN `link_mac_address` int(1) NOT NULL,\n                ADD COLUMN `link_serial` int(1) NOT NULL,\n                ADD COLUMN `link_if_status` int(11) NOT NULL default '0'";
        $DB->queryOrDie($query, "0.7 add glpi_link fields in glpi_ocs_config");
    }
    $intnull = array("glpi_alerts" => array("device_type", "FK_device", "type"), "glpi_cartridges_type" => array("tech_num"), "glpi_computers" => array("FK_users", "FK_groups"), "glpi_consumables_type" => array("tech_num"), "glpi_contacts" => array("type"), "glpi_device_case" => array("type"), "glpi_device_control" => array("interface"), "glpi_device_drive" => array("interface"), "glpi_dropdown_kbcategories" => array("level"), "glpi_dropdown_locations" => array("level"), "glpi_dropdown_tracking_category" => array("level"), "glpi_entities" => array("level"), "glpi_infocoms" => array("FK_enterprise", "budget"), "glpi_monitors" => array("type", "model", "FK_users", "FK_groups"), "glpi_networking" => array("type", "model", "firmware", "FK_users", "FK_groups"), "glpi_networking_ports" => array("iface", "netpoint"), "glpi_ocs_link" => array("ocs_server_id"), "glpi_peripherals" => array("model", "FK_users", "FK_groups"), "glpi_phones" => array("model", "FK_users", "FK_groups"), "glpi_printers" => array("type", "model", "FK_users", "FK_groups"), "glpi_software" => array("location", "platform", "FK_users", "FK_groups"), "glpi_tracking" => array("computer"), "glpi_users_groups" => array("FK_users", "FK_groups"));
    foreach ($intnull as $table => $fields) {
        foreach ($fields as $field) {
            if (FieldExists($table, $field, false)) {
                $query = "UPDATE `{$table}`\n                      SET `{$field}` = '0'\n                      WHERE `{$field}` IS NULL";
                $DB->queryOrDie($query, "0.7 update datas in {$table} for NULL values " . $DB->error());
                $query = "ALTER TABLE `{$table}`\n                      CHANGE `{$field}` `{$field}` INT NOT NULL DEFAULT '0'";
                $DB->queryOrDie($query, "0.7 alter {$field} in {$table} " . $DB->error());
            } else {
                // Error field does not exists : correct it
                $query = "ALTER TABLE `{$table}`\n                      ADD COLUMN `{$field}` INT NOT NULL DEFAULT '0'";
                $DB->queryOrDie($query, "0.7 add {$field} in {$table} " . $DB->error());
            }
        }
    }
    // Clean history
    $query = "DELETE\n             FROM `glpi_history`\n             WHERE `linked_action` = 0\n                   AND `device_internal_type` = 0\n                   AND `old_value` = `new_value`\n                   AND `old_value` IS NOT NULL\n                   AND `old_value` != ''";
    $DB->queryOrDie($query, "0.7 clean glpi_history " . $DB->error());
    $query = "DELETE\n             FROM `glpi_display`\n             WHERE `type` = " . USER_TYPE . "\n                   AND (`num` = 4)";
    $DB->queryOrDie($query, "0.7 clean glpi_display for glpi_users " . $DB->error());
    // Add fields to block auto updates on linked items
    if (!FieldExists("glpi_config", "autoupdate_link_contact", false)) {
        $query = "ALTER TABLE `glpi_config`\n                ADD COLUMN `autoupdate_link_contact` smallint(6) NOT NULL default '1'";
        $DB->queryOrDie($query, "0.7 add autoupdate_link_contact in glpi_config");
    }
    if (!FieldExists("glpi_config", "autoupdate_link_user", false)) {
        $query = "ALTER TABLE `glpi_config`\n                ADD COLUMN `autoupdate_link_user` smallint(6) NOT NULL default '1'";
        $DB->queryOrDie($query, "0.7 add autoupdate_link_user in glpi_config");
    }
    if (!FieldExists("glpi_config", "autoupdate_link_group", false)) {
        $query = "ALTER TABLE `glpi_config`\n                ADD COLUMN `autoupdate_link_group` smallint(6) NOT NULL default '1'";
        $DB->queryOrDie($query, "0.7 add autoupdate_link_group in glpi_config");
    }
    if (!FieldExists("glpi_config", "autoupdate_link_location", false)) {
        $query = "ALTER TABLE `glpi_config`\n                ADD COLUMN `autoupdate_link_location` smallint(6) NOT NULL default '1'";
        $DB->queryOrDie($query, "0.7 add autoupdate_link_location in glpi_config");
    }
    // Flat dropdowntree
    if (!FieldExists("glpi_config", "flat_dropdowntree", false)) {
        $query = "ALTER TABLE `glpi_config`\n                ADD COLUMN `flat_dropdowntree` smallint(6) NOT NULL default '0'";
        $DB->queryOrDie($query, "0.7 add flat_dropdowntree in glpi_config");
    }
    if (FieldExists("glpi_config", "mailing_signature", false)) {
        $query = "ALTER TABLE `glpi_config`\n                CHANGE `mailing_signature` `mailing_signature` TEXT NULL ";
        $DB->queryOrDie($query, "0.7 alter mailing signature in glpi_config");
    }
    //Software categories
    if (!TableExists("glpi_dropdown_software_category")) {
        $query = "CREATE TABLE `glpi_dropdown_software_category` (\n                  `ID` int(11) NOT NULL auto_increment,\n                  `name` varchar(255) default NULL,\n                  `comments` text,\n                  PRIMARY KEY (`ID`)\n                ) ENGINE=MyISAM ";
        $DB->queryOrDie($query, "0.7 add table glpi_dropdown_software_category");
    }
    if (!FieldExists("glpi_profiles", "rule_softwarecategories", false)) {
        $query = "ALTER TABLE `glpi_profiles`\n                ADD COLUMN `rule_softwarecategories` char(1) default NULL AFTER `rule_ldap`";
        $DB->queryOrDie($query, "0.7 add rule_softwarecategories in glpi_profiles");
        $query = "UPDATE `glpi_profiles`\n                SET `rule_softwarecategories` = `config`";
        $DB->queryOrDie($query, "0.7 update rule_softwarecategories values in glpi_profiles");
    }
    if (!FieldExists("glpi_software", "category", false)) {
        $query = "ALTER TABLE `glpi_software`\n                ADD `category` INT( 11 ) NOT NULL DEFAULT '0'";
        $DB->queryOrDie($query, "0.7 alter category in glpi_software");
    }
    if (!FieldExists("glpi_ocs_config", "import_monitor_comments", false)) {
        $query = "ALTER TABLE `glpi_ocs_config`\n                ADD `import_monitor_comments` INT( 2 ) NOT NULL DEFAULT '0' AFTER `import_ip`";
        $DB->queryOrDie($query, "0.7 alter import_monitor_comments in glpi_ocs_config");
    }
    if (!FieldExists("glpi_ocs_config", "import_software_comments", false)) {
        $query = "ALTER TABLE `glpi_ocs_config`\n                ADD `import_software_comments` INT NOT NULL DEFAULT '0'\n                     AFTER `import_monitor_comments`";
        $DB->queryOrDie($query, "0.7 alter import_software_comments in glpi_ocs_config");
    }
    if (FieldExists("glpi_device_gfxcard", "ram", false)) {
        //Update gfxcard memory management
        $query = "UPDATE `glpi_device_gfxcard`\n                SET `specif_default` = `ram`";
        $DB->queryOrDie($query, "0.7 glpi_device_gfxcard");
        $query = "ALTER TABLE `glpi_device_gfxcard`\n              DROP `ram`";
        $DB->queryOrDie($query, "0.7 delete 'ram' field from glpi_device_gfxcard");
    }
    if (FieldExists("glpi_config", "list_limit", false)) {
        //Update gfxcard memory management
        $query = "ALTER TABLE `glpi_config`\n                CHANGE `list_limit` `list_limit` INT NULL DEFAULT '20'";
        $DB->queryOrDie($query, "0.7 alter list_limit in config");
    }
    if (!FieldExists("glpi_config", "list_limit_max", false)) {
        //Update gfxcard memory management
        $query = "ALTER TABLE `glpi_config`\n                ADD `list_limit_max` INT NOT NULL DEFAULT '50' AFTER `list_limit` ";
        $DB->queryOrDie($query, "0.7 add list_limit_max in config");
    }
    if (!FieldExists("glpi_users", "list_limit", false)) {
        //Update gfxcard memory management
        $query = "ALTER TABLE `glpi_users`\n                ADD `list_limit` INT NOT NULL DEFAULT '20' AFTER `language`";
        $DB->queryOrDie($query, "0.7 add list_limit_max in users");
    }
    if (!FieldExists("glpi_config", "autoname_entity", false)) {
        $query = "ALTER TABLE `glpi_config`\n                ADD `autoname_entity` smallint(6) NOT NULL default '1' ";
        $DB->queryOrDie($query, "0.7 add autoname_entity in glpi_config");
    }
    if (!FieldExists("glpi_profiles", "rule_tracking", false)) {
        $query = "ALTER TABLE `glpi_profiles`\n                ADD COLUMN `rule_tracking` char(1) default NULL AFTER `config`";
        $DB->queryOrDie($query, "0.7 add rule_tracking in glpi_profiles");
        $query = "UPDATE `glpi_profiles`\n                SET `rule_tracking` = `config`";
        $DB->queryOrDie($query, "0.7 update rule_tracking values in glpi_profiles");
    }
    if (FieldExists("glpi_profiles", "show_ticket", false)) {
        $query = "ALTER TABLE `glpi_profiles`\n                CHANGE `show_ticket` `show_all_ticket` CHAR( 1 ) DEFAULT NULL ";
        $DB->queryOrDie($query, "0.7 rename show_ticket to show_all_ticket in glpi_profiles");
    }
    if (!FieldExists("glpi_profiles", "show_assign_ticket", false)) {
        $query = "ALTER TABLE `glpi_profiles`\n                ADD COLUMN `show_assign_ticket` char(1) default NULL AFTER `show_all_ticket`";
        $DB->queryOrDie($query, "0.7 add show_assign_ticket in glpi_profiles");
        $query = "UPDATE `glpi_profiles`\n                SET `show_assign_ticket` = `show_all_ticket`";
        $DB->queryOrDie($query, "0.7 update show_assign_ticket values in glpi_profiles");
    }
    if (!FieldExists("glpi_tracking", "assign_group", false)) {
        $query = "ALTER TABLE `glpi_tracking`\n                ADD `assign_group` INT NOT NULL DEFAULT '0' AFTER `assign_ent`";
        $DB->queryOrDie($query, "0.7 add assign_group in tracking");
        $query = "ALTER TABLE `glpi_tracking`\n                ADD INDEX (`assign_group`)";
        $DB->queryOrDie($query, "0.7 add index on assign_group in tracking");
    }
    if (!FieldExists("glpi_config", "expand_soft_categorized", false)) {
        $query = "ALTER TABLE `glpi_config`\n                ADD `expand_soft_categorized` int(1) NOT NULL DEFAULT '1'";
        $DB->queryOrDie($query, "0.7 add expand_soft_categorized in glpi_config");
    }
    if (!FieldExists("glpi_config", "expand_soft_not_categorized", false)) {
        $query = "ALTER TABLE `glpi_config`\n                ADD `expand_soft_not_categorized` int(1) NOT NULL DEFAULT '1'";
        $DB->queryOrDie($query, "0.7 add expand_soft_not_categorized in glpi_config");
    }
    $LINK_ID_TABLE = array(1 => "glpi_computers", 2 => "glpi_networking", 3 => "glpi_printers", 4 => "glpi_monitors", 5 => "glpi_peripherals", 6 => "glpi_software", 7 => "glpi_contacts", 8 => "glpi_enterprises", 9 => "glpi_infocoms", 10 => "glpi_contracts", 11 => "glpi_cartridges_type", 12 => "glpi_type_docs", 13 => "glpi_docs", 14 => "glpi_kbitems", 15 => "glpi_users", 16 => "glpi_tracking", 17 => "glpi_consumables_type", 18 => "glpi_consumables", 19 => "glpi_cartridges", 20 => "glpi_softwarelicenses", 21 => "glpi_links", 23 => "glpi_phones", 25 => "glpi_reminder", 27 => "glpi_groups", 28 => "glpi_entities", 29 => "glpi_reservation_item", 32 => "glpi_ocs_config", 33 => "glpi_registry", 34 => "glpi_profiles", 35 => "glpi_mailgate", 36 => "glpi_rules_descriptions", 37 => "glpi_transfers", 39 => "glpi_softwareversions", 41 => "glpi_computerdisks", 42 => "glpi_networking_ports", 43 => "glpi_followups");
    // Clean history
    $query = "SELECT DISTINCT `device_type`\n             FROM `glpi_history`";
    if ($result = $DB->query($query)) {
        if ($DB->numrows($result) > 0) {
            while ($data = $DB->fetch_array($result)) {
                $query2 = "DELETE\n                       FROM `glpi_history`\n                       WHERE `glpi_history`.`device_type` = '" . $data['device_type'] . "'\n                             AND `glpi_history`.`FK_glpi_device`\n                                  NOT IN (SELECT `ID`\n                                          FROM `" . $LINK_ID_TABLE[$data['device_type']] . "`)";
                $DB->query($query2);
            }
        }
    }
    if (!TableExists("glpi_transfers")) {
        $query = "CREATE TABLE `glpi_transfers` (\n                  `ID` int(11) NOT NULL auto_increment,\n                  `name` varchar(255) NOT NULL,\n                  `keep_tickets` tinyint(4) NOT NULL default '0',\n                  `keep_networklinks` tinyint(4) NOT NULL default '0',\n                  `keep_reservations` tinyint(4) NOT NULL default '0',\n                  `keep_history` tinyint(4) NOT NULL default '0',\n                  `keep_devices` tinyint(4) NOT NULL default '0',\n                  `keep_infocoms` tinyint(4) NOT NULL default '0',\n                  `keep_dc_monitor` tinyint(4) NOT NULL default '0',\n                  `clean_dc_monitor` tinyint(4) NOT NULL default '0',\n                  `keep_dc_phone` tinyint(4) NOT NULL default '0',\n                  `clean_dc_phone` tinyint(4) NOT NULL default '0',\n                  `keep_dc_peripheral` tinyint(4) NOT NULL default '0',\n                  `clean_dc_peripheral` tinyint(4) NOT NULL default '0',\n                  `keep_dc_printer` tinyint(4) NOT NULL default '0',\n                  `clean_dc_printer` tinyint(4) NOT NULL default '0',\n                  `keep_enterprises` tinyint(4) NOT NULL default '0',\n                  `clean_enterprises` tinyint(4) NOT NULL default '0',\n                  `keep_contacts` tinyint(4) NOT NULL default '0',\n                  `clean_contacts` tinyint(4) NOT NULL default '0',\n                  `keep_contracts` tinyint(4) NOT NULL default '0',\n                  `clean_contracts` tinyint(4) NOT NULL default '0',\n                  `keep_softwares` tinyint(4) NOT NULL default '0',\n                  `clean_softwares` tinyint(4) NOT NULL default '0',\n                  `keep_documents` tinyint(4) NOT NULL default '0',\n                  `clean_documents` tinyint(4) NOT NULL default '0',\n                  `keep_cartridges_type` tinyint(4) NOT NULL default '0',\n                  `clean_cartridges_type` tinyint(4) NOT NULL default '0',\n                  `keep_cartridges` tinyint(4) NOT NULL default '0',\n                  `keep_consumables` tinyint(4) NOT NULL default '0',\n                  PRIMARY KEY (`ID`)\n                ) ENGINE=MyISAM";
        $DB->queryOrDie($query, "0.7 add glpi_transfers");
        $query = "INSERT INTO `glpi_transfers`\n                VALUES ('1', 'complete', '2', '2', '1', '1', '1', '1', '1', '1', '1', '1', '1',\n                        '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1',\n                        '1', '1')";
        $DB->queryOrDie($query, "0.7 insert transfer default values");
    }
    if (!FieldExists("glpi_profiles", "transfer", false)) {
        $query = "ALTER TABLE `glpi_profiles`\n                ADD COLUMN `transfer` char(1) default NULL AFTER `entity`";
        $DB->queryOrDie($query, "0.7 add transfer in glpi_profiles");
        $query = "UPDATE `glpi_profiles`\n                SET `transfer` = `entity`";
        $DB->queryOrDie($query, "0.7 update transfer values in glpi_profiles");
    }
    // Need for update from SVN version
    if (!FieldExists("glpi_users", "location", false)) {
        $query = "ALTER TABLE `glpi_users`\n                ADD `location` int(11) NOT NULL DEFAULT 0";
        $DB->queryOrDie($query, "0.7 add location in users if not present for compatibility");
    }
    if (!FieldExists("glpi_ocs_config", "ocs_url", false)) {
        $query = "ALTER TABLE `glpi_ocs_config`\n                ADD `ocs_url` VARCHAR( 255 ) NOT NULL";
        $DB->queryOrDie($query, "0.7 add ocs_url in glpi_ocs_config if not present for compatibility");
    }
    if (!FieldExists("glpi_ocs_link", "ocs_agent_version", false)) {
        $query = "ALTER TABLE `glpi_ocs_link`\n                ADD `ocs_agent_version` VARCHAR( 255 ) default NULL";
        $DB->queryOrDie($query, "0.7 add ocs_agent_version in glpi_ocs_link if not present for compatibility");
    }
    if (!isIndex("glpi_history", "date_mod")) {
        $query = "ALTER TABLE `glpi_history`\n                ADD INDEX (`date_mod`)";
        $DB->queryOrDie($query, "0.7 alter history add index on date_mod");
    }
}
Exemple #26
0
 /**
  * Summary of jsAlertCallback
  * Is a replacement for Javascript native alert function
  * Beware that native alert is synchronous by nature (will block
  * browser waiting an answer from user, but that this is emulating the alert behaviour
  * by using a callback function when user presses 'Ok' button.
  *
  * @since version 9.1
  *
  * @param $msg          string   message to be shown
  * @param $title        string   title for dialog box
  * @param $okCallback   string   function that will be called when 'Ok' is pressed
  *                               (default null)
  **/
 static function jsAlertCallback($msg, $title, $okCallback = null)
 {
     return "\n         // Dialog and its properties.\n         \$('<div></div>').dialog({\n            open: function(event, ui) { \$('.ui-dialog-titlebar-close').hide(); },\n            close: function(event, ui) { \$(this).remove(); },\n            resizable: false,\n            modal: true,\n            title: '" . Toolbox::addslashes_deep($title) . "',\n            buttons: {\n               'Ok': function () {\n                     \$(this).dialog('close');\n                     " . ($okCallback !== null ? '(' . $okCallback . ')()' : '') . "\n                  }\n            }\n         }).text('" . Toolbox::addslashes_deep($msg) . "');\n         ";
 }
Exemple #27
0
 /**
  * Function that try to load from LDAP the user membership
  * by searching in the attribute of the Groups
  *
  * @param $ldap_connection    ldap connection descriptor
  * @param $ldap_method        LDAP method
  * @param $userdn             Basedn of the user
  * @param $login              User login
  *
  * @return nothing : false if not applicable
  **/
 private function getFromLDAPGroupDiscret($ldap_connection, $ldap_method, $userdn, $login)
 {
     global $DB;
     // No group_member_field : unable to get group
     if (empty($ldap_method["group_member_field"])) {
         return false;
     }
     if ($ldap_method["use_dn"]) {
         $user_tmp = $userdn;
     } else {
         //Don't add $ldap_method["login_field"]."=", because sometimes it may not work (for example with posixGroup)
         $user_tmp = $login;
     }
     $v = $this->ldap_get_user_groups($ldap_connection, $ldap_method["basedn"], $user_tmp, $ldap_method["group_condition"], $ldap_method["group_member_field"], $ldap_method["use_dn"], $ldap_method["login_field"]);
     foreach ($v as $result) {
         if (isset($result[$ldap_method["group_member_field"]]) && is_array($result[$ldap_method["group_member_field"]]) && count($result[$ldap_method["group_member_field"]]) > 0) {
             $query = "SELECT `id`\n                      FROM `glpi_groups`\n                      WHERE `ldap_group_dn`\n                        IN ('" . implode("', '", Toolbox::addslashes_deep($result[$ldap_method["group_member_field"]])) . "')";
             foreach ($DB->request($query) as $group) {
                 $this->fields["_groups"][] = $group['id'];
             }
         }
     }
     return true;
 }
 function updateComputer($computers_id, $wmi_data, $collects_wmis_id)
 {
     global $DB;
     $db_wmis = array();
     $query = "SELECT `id`, `property`, `value`\n            FROM `glpi_plugin_fusioninventory_collects_wmis_contents`\n         WHERE `computers_id` = '" . $computers_id . "'\n              AND `plugin_fusioninventory_collects_wmis_id`=\n               '" . $collects_wmis_id . "'";
     $result = $DB->query($query);
     while ($data = $DB->fetch_assoc($result)) {
         $idtmp = $data['id'];
         unset($data['id']);
         $data1 = Toolbox::addslashes_deep($data);
         $db_wmis[$idtmp] = $data1;
     }
     unset($wmi_data['_cpt']);
     foreach ($wmi_data as $key => $value) {
         foreach ($db_wmis as $keydb => $arraydb) {
             if ($arraydb['property'] == $key) {
                 $input = array();
                 $input['property'] = $arraydb['property'];
                 $input['id'] = $keydb;
                 $input['value'] = $value;
                 $this->update($input);
                 unset($wmi_data[$key]);
                 unset($db_wmis[$keydb]);
                 break;
             }
         }
     }
     if (count($wmi_data) == 0 and count($db_wmis) == 0) {
         // Nothing to do
     } else {
         if (count($db_wmis) != 0) {
             foreach ($db_wmis as $idtmp => $data) {
                 $this->delete(array('id' => $idtmp), 1);
             }
         }
         if (count($wmi_data) != 0) {
             foreach ($wmi_data as $key => $value) {
                 $input = array('computers_id' => $computers_id, 'plugin_fusioninventory_collects_wmis_id' => $collects_wmis_id, 'property' => $key, 'value' => $value);
                 $this->add($input);
             }
         }
     }
 }
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();
}
 /**
  * @since version 0.84 new parameter $limitexceeded
  *
  * @param $ldap_connection
  * @param $config_ldap
  * @param $filter
  * @param $search_in_groups         (true by default)
  * @param $groups             array
  * @param $limitexceeded
  **/
 static function getGroupsFromLDAP($ldap_connection, $config_ldap, $filter, $search_in_groups = true, $groups = array(), &$limitexceeded)
 {
     global $DB;
     //First look for groups in group objects
     $extra_attribute = $search_in_groups ? "cn" : $config_ldap->fields["group_field"];
     $attrs = array("dn", $extra_attribute);
     if ($filter == '') {
         if ($search_in_groups) {
             $filter = !empty($config_ldap->fields['group_condition']) ? $config_ldap->fields['group_condition'] : "(objectclass=*)";
         } else {
             $filter = !empty($config_ldap->fields['condition']) ? $config_ldap->fields['condition'] : "(objectclass=*)";
         }
     }
     $cookie = '';
     $count = 0;
     do {
         if (self::isLdapPageSizeAvailable($config_ldap)) {
             ldap_control_paged_result($ldap_connection, $config_ldap->fields['pagesize'], true, $cookie);
         }
         $filter = Toolbox::unclean_cross_side_scripting_deep($filter);
         $sr = @ldap_search($ldap_connection, $config_ldap->fields['basedn'], $filter, $attrs);
         if ($sr) {
             if (in_array(ldap_errno($ldap_connection), array(4, 11))) {
                 // openldap return 4 for Size limit exceeded
                 $limitexceeded = true;
             }
             $infos = self::get_entries_clean($ldap_connection, $sr);
             if (in_array(ldap_errno($ldap_connection), array(4, 11))) {
                 // openldap return 4 for Size limit exceeded
                 $limitexceeded = true;
             }
             $count += $infos['count'];
             //If page results are enabled and the number of results is greater than the maximum allowed
             //warn user that limit is exceeded and stop search
             if (self::isLdapPageSizeAvailable($config_ldap) && $config_ldap->fields['ldap_maxlimit'] && $count > $config_ldap->fields['ldap_maxlimit']) {
                 $limitexceeded = true;
                 break;
             }
             for ($ligne = 0; $ligne < $infos["count"]; $ligne++) {
                 if ($search_in_groups) {
                     // No cn : not a real object
                     if (isset($infos[$ligne]["cn"][0])) {
                         $cn = $infos[$ligne]["cn"][0];
                         $groups[$infos[$ligne]["dn"]] = array("cn" => $infos[$ligne]["cn"][0], "search_type" => "groups");
                     }
                 } else {
                     if (isset($infos[$ligne][$extra_attribute])) {
                         if ($config_ldap->fields["group_field"] == 'dn' || in_array('ou', $groups)) {
                             $dn = $infos[$ligne][$extra_attribute];
                             $ou = array();
                             for ($tmp = $dn; count($tmptab = explode(',', $tmp, 2)) == 2; $tmp = $tmptab[1]) {
                                 $ou[] = $tmptab[1];
                             }
                             /// Search in DB for group with ldap_group_dn
                             if ($config_ldap->fields["group_field"] == 'dn' && count($ou) > 0) {
                                 $query = "SELECT `ldap_value`\n                                     FROM `glpi_groups`\n                                     WHERE `ldap_group_dn`\n                                             IN ('" . implode("', '", Toolbox::addslashes_deep($ou)) . "')";
                                 foreach ($DB->request($query) as $group) {
                                     $groups[$group['ldap_value']] = array("cn" => $group['ldap_value'], "search_type" => "users");
                                 }
                             }
                         } else {
                             for ($ligne_extra = 0; $ligne_extra < $infos[$ligne][$extra_attribute]["count"]; $ligne_extra++) {
                                 $groups[$infos[$ligne][$extra_attribute][$ligne_extra]] = array("cn" => self::getGroupCNByDn($ldap_connection, $infos[$ligne][$extra_attribute][$ligne_extra]), "search_type" => "users");
                             }
                         }
                     }
                 }
             }
         }
         if (self::isLdapPageSizeAvailable($config_ldap)) {
             ldap_control_paged_result_response($ldap_connection, $sr, $cookie);
         }
     } while ($cookie !== null && $cookie != '');
     return $groups;
 }