static function uninstall()
 {
     global $DB;
     CronTask::Unregister('fusioninventory');
     PluginFusioninventoryProfile::uninstallProfile();
     $pfSetup = new PluginFusioninventorySetup();
     $user = new User();
     if (class_exists('PluginFusioninventoryConfig')) {
         $fusioninventory_config = new PluginFusioninventoryConfig();
         $users_id = $fusioninventory_config->getValue('users_id');
         $user->delete(array('id' => $users_id), 1);
     }
     if (file_exists(GLPI_PLUGIN_DOC_DIR . '/fusioninventory')) {
         $pfSetup->rrmdir(GLPI_PLUGIN_DOC_DIR . '/fusioninventory');
     }
     $query = "SHOW TABLES;";
     $result = $DB->query($query);
     while ($data = $DB->fetch_array($result)) {
         if (strstr($data[0], "glpi_plugin_fusioninventory_") or strstr($data[0], "glpi_plugin_fusinvsnmp_") or strstr($data[0], "glpi_plugin_fusinvinventory_") or strstr($data[0], "glpi_dropdown_plugin_fusioninventory") or strstr($data[0], "glpi_plugin_tracker") or strstr($data[0], "glpi_dropdown_plugin_tracker")) {
             $query_delete = "DROP TABLE `" . $data[0] . "`;";
             $DB->query($query_delete) or die($DB->error());
         }
     }
     $query = "DELETE FROM `glpi_displaypreferences`\n               WHERE `itemtype` LIKE 'PluginFusioninventory%';";
     $DB->query($query) or die($DB->error());
     // Delete rules
     $Rule = new Rule();
     $Rule->deleteByCriteria(array('sub_type' => 'PluginFusioninventoryInventoryRuleImport'));
     //Remove informations related to profiles from the session (to clean menu and breadcrumb)
     PluginFusioninventoryProfile::removeRightsFromSession();
     return TRUE;
 }
 /**
  * Log when extra-debug is activated
  */
 static function logIfExtradebug($file, $message)
 {
     if (!PluginFusioninventoryConfig::isExtradebugActive()) {
         return;
     }
     Toolbox::logInFile($file, $message);
 }
 /**
  * @depends GLPIInstallTest::installDatabase
  */
 public function testInstall()
 {
     global $DB;
     $DB->connect();
     $this->assertTrue($DB->connected, "Problem connecting to the Database");
     // Delete if Table of FusionInventory or Tracker yet in DB
     $query = "SHOW FULL TABLES WHERE TABLE_TYPE LIKE 'VIEW'";
     $result = $DB->query($query);
     while ($data = $DB->fetch_array($result)) {
         if (strstr($data[0], "fusi")) {
             $DB->query("DROP VIEW " . $data[0]);
         }
     }
     $query = "SHOW TABLES";
     $result = $DB->query($query);
     while ($data = $DB->fetch_array($result)) {
         if (strstr($data[0], "tracker") or strstr($data[0], "fusi")) {
             $DB->query("DROP TABLE " . $data[0]);
         }
     }
     $output = array();
     $returncode = 0;
     exec("php -f " . FUSINV_ROOT . "/scripts/cli_install.php -- --as-user 'glpi'", $output, $returncode);
     $this->assertEquals(0, $returncode, "Error when installing plugin in CLI mode\n" . implode("\n", $output));
     $GLPIlog = new GLPIlogs();
     $GLPIlog->testSQLlogs();
     $GLPIlog->testPHPlogs();
     $FusinvDBTest = new FusinvDB();
     $FusinvDBTest->checkInstall("fusioninventory", "install new version");
     PluginFusioninventoryConfig::loadCache();
 }
 function isActive()
 {
     global $DB;
     $config = new PluginFusioninventoryConfig();
     // state number for an active device
     if (!($active_device_state = $config->getValue("active_device_state"))) {
         return false;
     }
     // compare device status and active device status
     $query = "SELECT `state`\n                FROM {$this->table}\n                WHERE `ID`='" . $this->ID . "';";
     if ($result = $DB->query($query)) {
         if ($fields = $DB->fetch_row($result)) {
             if ($fields['0'] == $active_device_state) {
                 return true;
             }
         }
     }
     return false;
 }
 /**
  * Get logs of job
  *
  * @param array $task_ids list of tasks id
  * @return array
  */
 function getJoblogs($task_ids = array())
 {
     global $DB;
     $debug_mode = $_SESSION['glpi_use_mode'] == Session::DEBUG_MODE;
     $runclass = new PluginFusioninventoryTaskjobstate();
     $run_states = $runclass->getStateNames();
     $query_where = array();
     $query_where[] = "WHERE 1";
     if (isset($_SESSION['glpiactiveentities_string'])) {
         $query_where[] = getEntitiesRestrictRequest("AND", 'task');
     }
     if (is_array($task_ids) and count($task_ids) > 0) {
         $query_where[] = "AND task.`id` IN (" . implode(",", $task_ids) . ")";
     }
     // quickly filter empty WHERE entry
     $query_where = array_filter($query_where);
     $query_fields = array(array('task.id', 'task.`id`'), array('task.name', 'task.`name`'), array('job.id', 'job.`id`'), array('job.name', 'job.`name`'), array('job.method', 'job.`method`'), array('job.targets', 'job.`targets`'));
     $fieldmap = array();
     foreach ($query_fields as $index => $key) {
         $fieldmap[$key[0]] = $index;
     }
     $query_select = array();
     foreach ($query_fields as $index => $key) {
         $query_select[] = $key[1] . " AS '" . $key[0] . "'";
     }
     $query_joins = array();
     $query_joins['task'] = implode("\n", array("INNER JOIN `glpi_plugin_fusioninventory_tasks` as task", "  ON job.`plugin_fusioninventory_tasks_id` = task.`id`", "  AND task.`is_active` = 1"));
     $data_structure = array('query' => implode("\n", array("SELECT", implode(",\n", $query_select), "FROM `glpi_plugin_fusioninventory_taskjobs` as job", implode("\n", $query_joins), implode("\n", $query_where))), 'result' => null);
     $data_structure['result'] = $DB->query($data_structure['query']);
     //Results grouped by tasks > jobs > jobstates
     $logs = array();
     //Target cache (used to speed up data formatting)
     $targets_cache = array();
     $expanded = array();
     if (isset($_SESSION['plugin_fusioninventory_tasks_expanded'])) {
         $expanded = $_SESSION['plugin_fusioninventory_tasks_expanded'];
     }
     while ($result = $data_structure['result']->fetch_row()) {
         $task_id = $result[$fieldmap['task.id']];
         if (!array_key_exists($task_id, $logs)) {
             $logs[$task_id] = array('task_name' => $result[$fieldmap['task.name']], 'task_id' => $result[$fieldmap['task.id']], 'expanded' => false, 'jobs' => array());
         }
         if (isset($expanded[$task_id])) {
             $logs[$task_id]['expanded'] = $expanded[$task_id];
         }
         $job_id = $result[$fieldmap['job.id']];
         $jobs_handle =& $logs[$task_id]['jobs'];
         if (!array_key_exists($job_id, $jobs_handle)) {
             $jobs_handle[$job_id] = array('name' => $result[$fieldmap['job.name']], 'id' => $result[$fieldmap['job.id']], 'method' => $result[$fieldmap['job.method']], 'targets' => array());
         }
         $targets = importArrayFromDB($result[$fieldmap['job.targets']]);
         $targets_handle =& $jobs_handle[$job_id]['targets'];
         $agent_state_types = array('agents_prepared', 'agents_cancelled', 'agents_running', 'agents_success', 'agents_error', 'agents_notdone');
         if ($result[$fieldmap['job.method']] == 'networkinventory') {
             $pfNetworkinventory = new PluginFusioninventoryNetworkinventory();
             foreach ($targets as $keyt => $target) {
                 $item_type = key($target);
                 $items_id = current($target);
                 if ($item_type == 'PluginFusioninventoryIPRange') {
                     unset($targets[$keyt]);
                     // In this case get devices of this iprange
                     $deviceList = $pfNetworkinventory->getDevicesOfIPRange($items_id);
                     $targets = array_merge($targets, $deviceList);
                 }
             }
         }
         foreach ($targets as $target) {
             $item_type = key($target);
             $item_id = current($target);
             $target_id = $item_type . "_" . $item_id;
             if (isset($targets_cache[$target_id])) {
                 $item = $targets_cache[$target_id];
             } else {
                 $item = new $item_type();
                 $item->getFromDB($item_id);
                 $targets_cache[$target_id] = $item;
             }
             $targets_handle[$target_id] = array('id' => $item->fields['id'], 'name' => $item->fields['name'], 'type_name' => $item->getTypeName(), 'item_link' => $item->getLinkUrl(), 'counters' => array(), 'agents' => array());
             // create agent states counter lists
             foreach ($agent_state_types as $type) {
                 $targets_handle[$target_id]['counters'][$type] = array();
             }
         }
     }
     // Query fields mapping used to easily select fields by name
     $query_fields = array(array('task.id', 'task.`id`'), array('task.name', 'task.`name`'), array('job.id', 'job.`id`'), array('job.name', 'job.`name`'), array('job.method', 'job.`method`'), array('agent.id', 'agent.`id`'), array('agent.name', 'agent.`name`'), array('run.id', 'run.`id`'), array('run.itemtype', 'run.`itemtype`'), array('run.items_id', 'run.`items_id`'), array('run.state', 'run.`state`'), array('log.last_date', 'log.`date`'), array('log.last_timestamp', 'UNIX_TIMESTAMP(log.`date`)'), array('log.last_id', 'log.`id`'), array('log.last_comment', 'log.`comment`'));
     $fieldmap = array();
     foreach ($query_fields as $index => $key) {
         $fieldmap[$key[0]] = $index;
     }
     $query_select = array();
     foreach ($query_fields as $index => $key) {
         $query_select[] = $key[1] . " AS '" . $key[0] . "'";
     }
     $query_joins = array();
     $query_joins['max_run'] = implode("\n", array("INNER JOIN (", "  SELECT", "     MAX(run.`id`) AS max_id,", "     run.`plugin_fusioninventory_agents_id`,", "     run.`plugin_fusioninventory_taskjobs_id`,", "     run.`items_id`, run.`itemtype`,", "     MAX(log.`id`) AS max_log_id", "  FROM `glpi_plugin_fusioninventory_taskjobstates` AS run", "  LEFT JOIN `glpi_plugin_fusioninventory_taskjoblogs` AS log", "  ON log.`plugin_fusioninventory_taskjobstates_id` = run.`id`", "  GROUP BY", "     run.`plugin_fusioninventory_agents_id`,", "     run.`plugin_fusioninventory_taskjobs_id`,", "     run.`items_id`, run.`itemtype`", ") max_run ON max_run.`plugin_fusioninventory_agents_id` = agent.`id`"));
     $query_joins['run'] = implode("\n", array("INNER JOIN `glpi_plugin_fusioninventory_taskjobstates` AS run", "  ON max_run.`max_id` = run.`id`"));
     $query_joins['log'] = implode("\n", array("LEFT JOIN `glpi_plugin_fusioninventory_taskjoblogs` as log", "  ON log.`id` = max_run.`max_log_id`"));
     $query_joins['job'] = implode("\n", array("INNER JOIN `glpi_plugin_fusioninventory_taskjobs` AS job", "  ON job.`id` = run.`plugin_fusioninventory_taskjobs_id`"));
     $query_joins['task'] = implode("\n", array("INNER JOIN `glpi_plugin_fusioninventory_tasks` as task", "  ON job.`plugin_fusioninventory_tasks_id` = task.`id`"));
     $queries = array();
     /*
      * Get latest jobstates for agents
      */
     $queries['1_last_runs'] = array('query' => implode(" \n", array("SELECT", implode(",\n", $query_select), "FROM `glpi_plugin_fusioninventory_agents` AS agent", implode("\n", $query_joins), implode("\n", $query_where), "GROUP BY job.`id`, agent.`id`, run.`id`")), 'result' => null);
     /*
      * Get last finished jobstates (ie. `state` >= 3)
      */
     $query_joins['max_run'] = implode("\n", array("INNER JOIN (", "  SELECT", "     MAX(run.`id`) AS max_id,", "     run.`plugin_fusioninventory_agents_id`,", "     run.`plugin_fusioninventory_taskjobs_id`,", "     run.`items_id`, run.`itemtype`,", "     MAX(log.`id`) AS max_log_id", "  FROM `glpi_plugin_fusioninventory_taskjobstates` AS run", "  LEFT JOIN `glpi_plugin_fusioninventory_taskjoblogs` AS log", "  ON log.`plugin_fusioninventory_taskjobstates_id` = run.`id`", "  WHERE run.`state` IN ( " . implode(",", array(PluginFusioninventoryTaskjobstate::FINISHED, PluginFusioninventoryTaskjobstate::IN_ERROR)) . " )", "  GROUP BY", "     run.`plugin_fusioninventory_agents_id`,", "     run.`plugin_fusioninventory_taskjobs_id`,", "     run.`items_id`, run.`itemtype`", ") max_run ON max_run.`plugin_fusioninventory_agents_id` = agent.`id`"));
     $queries['2_finished_runs'] = array('query' => implode(" \n", array("SELECT", implode(",\n", $query_select), "FROM `glpi_plugin_fusioninventory_agents` AS agent", implode("\n", $query_joins), implode("\n", $query_where), "GROUP BY job.`id`, agent.`id`, run.`id`")), 'result' => null);
     $query_chrono = array("start" => microtime(true), "end" => 0);
     ksort($queries);
     foreach ($queries as $query_name => $contents) {
         $queries[$query_name]['result'] = $DB->query($contents['query']);
         $query_chrono['end'] = microtime(true);
         // For debug only
         //if ($debug_mode) {
         //   file_put_contents("/tmp/glpi_".$query_name.".sql",$contents['query']);
         //}
     }
     $agents = array();
     $format_chrono = array("start" => microtime(true), "end" => 0);
     foreach ($queries as $query_name => $contents) {
         if (!is_null($contents['result'])) {
             while ($result = $contents['result']->fetch_row()) {
                 // We need to check if the results are consistent with the view's structure gathered
                 // by the first query
                 $task_id = $result[$fieldmap['task.id']];
                 //if (!array_key_exists($task_id, $logs)) {
                 if (!isset($logs[$task_id])) {
                     continue;
                 }
                 $job_id = $result[$fieldmap['job.id']];
                 $jobs =& $logs[$task_id]['jobs'];
                 if (!isset($jobs[$job_id])) {
                     continue;
                 }
                 $target_id = $result[$fieldmap['run.itemtype']] . '_' . $result[$fieldmap['run.items_id']];
                 $targets =& $jobs[$job_id]['targets'];
                 if (!isset($targets[$target_id])) {
                     continue;
                 }
                 $counters =& $targets[$target_id]['counters'];
                 $agent_id = $result[$fieldmap['agent.id']];
                 $agents[$agent_id] = $result[$fieldmap['agent.name']];
                 if (!isset($targets[$target_id]['agents'][$agent_id])) {
                     $targets[$target_id]['agents'][$agent_id] = array();
                 }
                 $agent_state = '';
                 // Update counters
                 switch ($result[$fieldmap['run.state']]) {
                     case PluginFusioninventoryTaskjobstate::CANCELLED:
                         // We put this agent in the cancelled counter if it does not have any other job
                         // states.
                         if (!isset($counters['agents_prepared'][$agent_id]) and !isset($counters['agents_running'][$agent_id])) {
                             $counters['agents_cancelled'][$agent_id] = 1;
                             $agent_state = 'cancelled';
                         }
                         break;
                     case PluginFusioninventoryTaskjobstate::PREPARED:
                         // We put this agent in the prepared counter if it has not yet completed any job.
                         $counters['agents_prepared'][$agent_id] = 1;
                         $agent_state = 'prepared';
                         break;
                     case PluginFusioninventoryTaskjobstate::SERVER_HAS_SENT_DATA:
                     case PluginFusioninventoryTaskjobstate::AGENT_HAS_SENT_DATA:
                         // This agent is running so it must not be in any other counter
                         foreach ($agent_state_types as $type) {
                             if (isset($counters[$type][$agent_id])) {
                                 unset($counters[$type][$agent_id]);
                             }
                         }
                         $counters['agents_running'][$agent_id] = 1;
                         $agent_state = 'running';
                         break;
                     case PluginFusioninventoryTaskjobstate::IN_ERROR:
                         if (isset($counters['agents_success'][$agent_id])) {
                             unset($counters['agents_success'][$agent_id]);
                         }
                         $counters['agents_error'][$agent_id] = 1;
                         $agent_state = 'error';
                         if (isset($counters['agents_notdone'][$agent_id])) {
                             unset($counters['agents_notdone'][$agent_id]);
                         }
                         break;
                     case PluginFusioninventoryTaskjobstate::FINISHED:
                         if (isset($counters['agents_error'][$agent_id])) {
                             unset($counters['agents_error'][$agent_id]);
                         }
                         $counters['agents_success'][$agent_id] = 1;
                         $agent_state = 'success';
                         if (isset($counters['agents_notdone'][$agent_id])) {
                             unset($counters['agents_notdone'][$agent_id]);
                         }
                         break;
                 }
                 if (!isset($counters['agents_error'][$agent_id]) and !isset($counters['agents_success'][$agent_id])) {
                     $counters['agents_notdone'][$agent_id] = 1;
                 }
                 if (isset($counters['agents_running'][$agent_id]) or isset($counters['agents_prepared'][$agent_id])) {
                     unset($counters['agents_cancelled'][$agent_id]);
                 }
                 $targets[$target_id]['agents'][$agent_id][] = array('agent_id' => $agent_id, 'numstate' => $result[$fieldmap['run.state']], 'state' => $agent_state, 'jobstate_id' => $result[$fieldmap['run.id']], 'last_log_id' => $result[$fieldmap['log.last_id']], 'last_log_date' => $result[$fieldmap['log.last_date']], 'timestamp' => $result[$fieldmap['log.last_timestamp']], 'last_log' => $result[$fieldmap['log.last_comment']]);
             }
         }
     }
     $format_chrono['end'] = microtime(true);
     if ($debug_mode) {
         function tmp_display_log($log)
         {
             return "ID:" . $log['task_id'] . "(" . $log['task_name'] . ")";
         }
         if (PluginFusioninventoryConfig::isExtradebugActive()) {
             Toolbox::logDebug(array("tasks" => implode(',', array_map('tmp_display_log', $logs)), "row count" => count($logs), "Joblogs Query" => self::FormatChrono($query_chrono), "Format logs results" => self::FormatChrono($format_chrono)));
         }
     }
     return array('tasks' => $logs, 'agents' => $agents);
 }
 /**
  * Display form for config tab in fusioninventory config form
  *
  * @param $options array
  *
  * @return bool TRUE if form is ok
  *
  **/
 static function showFormDeploy($options = array())
 {
     $pfConfig = new PluginFusioninventoryConfig();
     $pfConfig->fields['id'] = 1;
     $options['colspan'] = 1;
     $pfConfig->showFormHeader($options);
     echo "<tr class='tab_bg_1'>";
     echo "<td>" . __('Root folder for sending files from server', 'fusioninventory') . "&nbsp;:</td>";
     echo "<td>";
     echo "<input type='text' name='server_upload_path' value='" . $pfConfig->getValue('server_upload_path') . "' size='60' />";
     echo "</td>";
     echo "</tr>";
     echo "<tr>";
     echo "<td>" . __('Use this GLPI server as a mirror server', 'fusioninventory') . "&nbsp;:</td>";
     echo "<td>";
     Dropdown::showYesNo("server_as_mirror", $pfConfig->getValue('server_as_mirror'));
     echo "</td>";
     echo "</tr>";
     $options['candel'] = FALSE;
     $pfConfig->showFormButtons($options);
     return TRUE;
 }
 /**
  * Clean agent too old (so haven't contacted glpi
  * since xx days)
  *
  * @return bool cron is ok or not
  *
  **/
 static function cronCleanoldagents()
 {
     global $DB;
     $pfConfig = new PluginFusioninventoryConfig();
     $pfAgent = new PluginFusioninventoryAgent();
     $retentiontime = $pfConfig->getValue('agents_old_days');
     if ($retentiontime == 0) {
         return TRUE;
     }
     $sql = "SELECT * FROM `glpi_plugin_fusioninventory_agents`\n                WHERE `last_contact` < date_add(now(), interval -" . $retentiontime . " day)";
     $result = $DB->query($sql);
     if ($result) {
         while ($data = $DB->fetch_array($result)) {
             $pfAgent->delete($data);
         }
     }
     return TRUE;
 }
 static function getAdditionalMenuOptions()
 {
     global $CFG_GLPI;
     $elements = array('iprange' => 'PluginFusioninventoryIPRange', 'config' => 'PluginFusioninventoryConfig', 'task' => 'PluginFusioninventoryTask', 'timeslot' => 'PluginFusioninventoryTimeslot', 'unmanaged' => 'PluginFusioninventoryUnmanaged', 'inventoryruleimport' => 'PluginFusioninventoryInventoryRuleImport', 'inventoryruleentity' => 'PluginFusioninventoryInventoryRuleEntity', 'inventoryrulelocation' => 'PluginFusioninventoryInventoryRuleLocation', 'collectrule' => 'PluginFusioninventoryCollectRule', 'inventorycomputerblacklist' => 'PluginFusioninventoryInventoryComputerBlacklist', 'configsecurity' => 'PluginFusioninventoryConfigSecurity', 'credential' => 'PluginFusioninventoryCredential', 'credentialip' => 'PluginFusioninventoryCredentialIp', 'collect' => 'PluginFusioninventoryCollect', 'deploypackage' => 'PluginFusioninventoryDeployPackage', 'deploymirror' => 'PluginFusioninventoryDeployMirror', 'deploygroup' => 'PluginFusioninventoryDeployGroup', 'ignoredimportdevice' => 'PluginFusioninventoryIgnoredimportdevice', 'ruledictionnarycomputerarch' => 'PluginFusioninventoryRuleDictionnaryComputerArch');
     $options = array();
     $options['menu']['title'] = self::getTypeName();
     $options['menu']['page'] = self::getSearchURL(false);
     if (Session::haveRight('plugin_fusioninventory_configuration', READ)) {
         $options['menu']['links']['config'] = PluginFusioninventoryConfig::getFormURL(false);
     }
     foreach ($elements as $type => $itemtype) {
         $options[$type] = array('title' => $itemtype::getTypeName(), 'page' => $itemtype::getSearchURL(false));
         $options[$type]['links']['search'] = $itemtype::getSearchURL(false);
         if ($itemtype::canCreate()) {
             if ($type != 'ignoredimportdevice') {
                 $options[$type]['links']['add'] = $itemtype::getFormURL(false);
             }
         }
         if (Session::haveRight('plugin_fusioninventory_configuration', READ)) {
             $options[$type]['links']['config'] = PluginFusioninventoryConfig::getFormURL(false);
         }
     }
     // Add icon for import package
     $img = Html::image($CFG_GLPI["root_doc"] . "/plugins/fusioninventory/pics/menu_import.png", array('alt' => __('Import', 'fusioninventory')));
     $options['deploypackage']['links'][$img] = '/plugins/fusioninventory/front/deploypackage.import.php';
     // Add icon for documentation
     $img = Html::image($CFG_GLPI["root_doc"] . "/plugins/fusioninventory/pics/books.png", array('alt' => __('Import', 'fusioninventory')));
     $options['menu']['links'][$img] = '/plugins/fusioninventory/front/documentation.php';
     $options['agent'] = array('title' => PluginFusioninventoryAgent::getTypeName(), 'page' => PluginFusioninventoryAgent::getSearchURL(false), 'links' => array('search' => PluginFusioninventoryAgent::getSearchURL(false)));
     if (Session::haveRight('plugin_fusioninventory_configuration', READ)) {
         $options['agent']['links']['config'] = PluginFusioninventoryConfig::getFormURL(false);
     }
     return $options;
 }
 static function auth_dropdown($selected = "")
 {
     global $DB;
     $plugin_fusioninventory_snmp_auth = new PluginFusioninventorySnmpauth();
     $config = new PluginFusioninventoryConfig();
     if ($config->getValue("authsnmp") == "file") {
         echo $plugin_fusioninventory_snmp_auth->selectbox($selected);
     } else {
         if ($config->getValue("authsnmp") == "DB") {
             Dropdown::show("PluginFusioninventorySnmpauth", array('name' => "FK_snmp_connection", 'value' => $selected, 'comments' => false));
         }
     }
 }
 /**
  * Cron for clean taskjob
  *
  * @return nothing
  */
 static function cronCleantaskjob()
 {
     global $DB;
     $config = new PluginFusioninventoryConfig();
     $retentiontime = $config->getValue('delete_task');
     $pfTaskjobstate = new PluginFusioninventoryTaskjobstate();
     $sql = "SELECT * FROM `glpi_plugin_fusioninventory_taskjoblogs`\n         WHERE  `date` < date_add(now(), interval -" . $retentiontime . " day)\n         GROUP BY `plugin_fusioninventory_taskjobstates_id`";
     $result = $DB->query($sql);
     if ($result) {
         while ($data = $DB->fetch_array($result)) {
             $pfTaskjobstate->getFromDB($data['plugin_fusioninventory_taskjobstates_id']);
             $pfTaskjobstate->delete($pfTaskjobstate->fields, 1);
             $sql_delete = "DELETE FROM `glpi_plugin_fusioninventory_taskjoblogs`\n               WHERE `plugin_fusioninventory_taskjobstates_id` = '" . $data['plugin_fusioninventory_taskjobstates_id'] . "'";
             $DB->query($sql_delete);
         }
     }
 }
  @author    Vincent Mazzoni
  @co-author David Durieux
  @copyright Copyright (c) 2010-2015 FusionInventory team
  @license   AGPL License 3.0 or (at your option) any later version
             http://www.gnu.org/licenses/agpl-3.0-standalone.html
  @link      http://www.fusioninventory.org/
  @link      http://forge.fusioninventory.org/projects/fusioninventory-for-glpi/
  @since     2010

  ------------------------------------------------------------------------
*/
include "../../../inc/includes.php";
Session::checkRight('plugin_fusioninventory_configuration', READ);
Html::header(__('Features', 'fusioninventory'), $_SERVER["PHP_SELF"], "plugins", "pluginfusioninventorymenu", "config");
PluginFusioninventoryMenu::displayMenu("mini");
$pfConfig = new PluginFusioninventoryConfig();
if (isset($_POST['update'])) {
    $data = $_POST;
    unset($data['update']);
    unset($data['id']);
    unset($data['_glpi_csrf_token']);
    foreach ($data as $key => $value) {
        $pfConfig->updateValue($key, $value);
    }
    Html::back();
}
$a_config = current($pfConfig->find("", "", 1));
$pfConfig->getFromDB($a_config['id']);
if (isset($_GET['glpi_tab'])) {
    $_SESSION['glpi_tabs']['pluginfusioninventoryconfiguration'] = $_GET['glpi_tab'];
    Html::redirect(Toolbox::getItemTypeFormURL($pfConfig->getType()));
function plugin_fusioninventory_getAddSearchOptions($itemtype)
{
    $sopt = array();
    if ($itemtype == 'Computer' or $itemtype == 'PluginFusioninventoryComputer') {
        $sopt[5150]['table'] = 'glpi_plugin_fusioninventory_inventorycomputercomputers';
        $sopt[5150]['field'] = 'last_fusioninventory_update';
        $sopt[5150]['linkfield'] = 'id';
        $sopt[5150]['name'] = __('FusInv', 'fusioninventory') . " - " . __('Last inventory', 'fusioninventory');
        $sopt[5150]['datatype'] = 'datetime';
        $sopt[5150]['itemlink_type'] = 'PluginFusioninventoryInventoryComputerLib';
        $sopt[5150]['massiveaction'] = FALSE;
        $sopt[5151]['table'] = 'glpi_plugin_fusioninventory_inventorycomputerantiviruses';
        $sopt[5151]['field'] = 'name';
        $sopt[5151]['name'] = __('Antivirus name', 'fusioninventory');
        $sopt[5151]['datatype'] = 'string';
        $sopt[5151]['joinparams'] = array('jointype' => 'child');
        $sopt[5151]['massiveaction'] = FALSE;
        $sopt[5151]['forcegroupby'] = TRUE;
        $sopt[5151]['searchtype'] = array('contains');
        $sopt[5152]['table'] = 'glpi_plugin_fusioninventory_inventorycomputerantiviruses';
        $sopt[5152]['field'] = 'version';
        $sopt[5152]['name'] = __('Antivirus version', 'fusioninventory');
        $sopt[5152]['datatype'] = 'string';
        $sopt[5152]['joinparams'] = array('jointype' => 'child');
        $sopt[5152]['massiveaction'] = FALSE;
        $sopt[5152]['forcegroupby'] = TRUE;
        $sopt[5151]['searchtype'] = array('contains');
        $sopt[5153]['table'] = 'glpi_plugin_fusioninventory_inventorycomputerantiviruses';
        $sopt[5153]['field'] = 'is_active';
        $sopt[5153]['linkfield'] = '';
        $sopt[5153]['name'] = __('Antivirus enabled', 'fusioninventory');
        $sopt[5153]['datatype'] = 'bool';
        $sopt[5153]['joinparams'] = array('jointype' => 'child');
        $sopt[5153]['massiveaction'] = FALSE;
        $sopt[5153]['forcegroupby'] = TRUE;
        $sopt[5153]['searchtype'] = array('equals');
        $sopt[5154]['table'] = 'glpi_plugin_fusioninventory_inventorycomputerantiviruses';
        $sopt[5154]['field'] = 'uptodate';
        $sopt[5154]['linkfield'] = '';
        $sopt[5154]['name'] = __('Antivirus up to date', 'fusioninventory');
        $sopt[5154]['datatype'] = 'bool';
        $sopt[5154]['joinparams'] = array('jointype' => 'child');
        $sopt[5154]['massiveaction'] = FALSE;
        $sopt[5154]['forcegroupby'] = TRUE;
        $sopt[5154]['searchtype'] = array('equals');
        $sopt[5155]['table'] = 'glpi_plugin_fusioninventory_inventorycomputercomputers';
        $sopt[5155]['field'] = 'bios_date';
        $sopt[5155]['name'] = __('BIOS', 'fusioninventory') . "-" . __('Date');
        //         $sopt[5155]['forcegroupby'] = true;
        //         $sopt[5155]['usehaving'] = true;
        $sopt[5155]['datatype'] = 'date';
        $sopt[5155]['joinparams'] = array('jointype' => 'child');
        $sopt[5155]['massiveaction'] = FALSE;
        $sopt[5156]['table'] = 'glpi_plugin_fusioninventory_inventorycomputercomputers';
        $sopt[5156]['field'] = 'bios_version';
        $sopt[5156]['name'] = __('BIOS', 'fusioninventory') . "-" . __('Version');
        $sopt[5156]['joinparams'] = array('jointype' => 'child');
        $sopt[5156]['massiveaction'] = FALSE;
        $sopt[5157]['table'] = 'glpi_plugin_fusioninventory_inventorycomputercomputers';
        $sopt[5157]['field'] = 'operatingsystem_installationdate';
        $sopt[5157]['name'] = __('Operating system') . " - " . __('Installation') . " (" . strtolower(__('Date')) . ")";
        $sopt[5157]['joinparams'] = array('jointype' => 'child');
        $sopt[5157]['datatype'] = 'date';
        $sopt[5157]['massiveaction'] = FALSE;
        $sopt[5158]['table'] = 'glpi_plugin_fusioninventory_inventorycomputercomputers';
        $sopt[5158]['field'] = 'winowner';
        $sopt[5158]['joinparams'] = array('jointype' => 'child');
        $sopt[5158]['name'] = __('Owner', 'fusioninventory');
        $sopt[5158]['massiveaction'] = FALSE;
        $sopt[5159]['table'] = 'glpi_plugin_fusioninventory_inventorycomputercomputers';
        $sopt[5159]['field'] = 'wincompany';
        $sopt[5159]['name'] = __('Company', 'fusioninventory');
        $sopt[5159]['joinparams'] = array('jointype' => 'child');
        $sopt[5159]['massiveaction'] = FALSE;
        $sopt[5160]['table'] = 'glpi_plugin_fusioninventory_agents';
        $sopt[5160]['field'] = 'useragent';
        $sopt[5160]['name'] = __('Useragent', 'fusioninventory');
        $sopt[5160]['joinparams'] = array('jointype' => 'child');
        $sopt[5160]['massiveaction'] = FALSE;
        $sopt[5161]['table'] = 'glpi_plugin_fusioninventory_agents';
        $sopt[5161]['field'] = 'tag';
        $sopt[5161]['linkfield'] = '';
        $sopt[5161]['name'] = __('FusionInventory tag', 'fusioninventory');
        $sopt[5162]['table'] = 'glpi_plugin_fusioninventory_computerarchs';
        $sopt[5162]['field'] = 'name';
        $sopt[5162]['name'] = __('Architecture', 'fusioninventory');
        $sopt[5162]['datatype'] = 'dropdown';
        $sopt[5162]['massiveaction'] = FALSE;
        $sopt[5162]['joinparams'] = array('beforejoin' => array('table' => 'glpi_plugin_fusioninventory_inventorycomputercomputers', 'joinparams' => array('jointype' => 'child')));
        //         $sopt[5163]['table']     = 'glpi_plugin_fusioninventory_configurationmanagements';
        //         $sopt[5163]['field']     = 'conform';
        //         $sopt[5163]['name']      = __('Conformité (configuration management)', 'fusioninventory');
        //         $sopt[5163]['joinparams']  = array('jointype' => 'itemtype_item');
        //         $sopt[5163]['massiveaction'] = FALSE;
        //         $sopt[5163]['datatype']  = 'bool';
        $sopt[5163]['table'] = 'glpi_plugin_fusioninventory_inventorycomputercomputers';
        $sopt[5163]['field'] = 'oscomment';
        $sopt[5163]['name'] = __('Operating system') . '/' . __('Comments');
        $sopt[5163]['joinparams'] = array('jointype' => 'child');
        $sopt[5163]['massiveaction'] = FALSE;
        $sopt[5164]['table'] = "glpi_plugin_fusioninventory_agentmodules";
        $sopt[5164]['field'] = "DEPLOY";
        $sopt[5164]['linkfield'] = "DEPLOY";
        $sopt[5164]['name'] = __('Module', 'fusioninventory') . "-" . __('Deploy', 'fusioninventory');
        $sopt[5164]['datatype'] = 'bool';
        $sopt[5164]['massiveaction'] = FALSE;
        $sopt[5165]['table'] = "glpi_plugin_fusioninventory_agentmodules";
        $sopt[5165]['field'] = "WAKEONLAN";
        $sopt[5165]['linkfield'] = "WAKEONLAN";
        $sopt[5165]['name'] = __('Module', 'fusioninventory') . "-" . __('WakeOnLan', 'fusioninventory');
        $sopt[5165]['datatype'] = 'bool';
        $sopt[5165]['massiveaction'] = FALSE;
        $sopt[5166]['table'] = "glpi_plugin_fusioninventory_agentmodules";
        $sopt[5166]['field'] = "INVENTORY";
        $sopt[5166]['linkfield'] = "INVENTORY";
        $sopt[5166]['name'] = __('Module', 'fusioninventory') . "-" . __('Local inventory', 'fusioninventory');
        $sopt[5166]['datatype'] = 'bool';
        $sopt[5166]['massiveaction'] = FALSE;
        $sopt[5167]['table'] = "glpi_plugin_fusioninventory_agentmodules";
        $sopt[5167]['field'] = "InventoryComputerESX";
        $sopt[5167]['linkfield'] = "InventoryComputerESX";
        $sopt[5167]['name'] = __('Module', 'fusioninventory') . "-" . __('ESX/VMWare', 'fusioninventory');
        $sopt[5167]['datatype'] = 'bool';
        $sopt[5167]['massiveaction'] = FALSE;
        $sopt[5168]['table'] = "glpi_plugin_fusioninventory_agentmodules";
        $sopt[5168]['field'] = "NETWORKINVENTORY";
        $sopt[5168]['linkfield'] = "NETWORKINVENTORY";
        $sopt[5168]['name'] = __('Module', 'fusioninventory') . "-" . __('Network inventory', 'fusioninventory');
        $sopt[5168]['datatype'] = 'bool';
        $sopt[5168]['massiveaction'] = FALSE;
        $sopt[5169]['table'] = "glpi_plugin_fusioninventory_agentmodules";
        $sopt[5169]['field'] = "NETWORKDISCOVERY";
        $sopt[5169]['linkfield'] = "NETWORKDISCOVERY";
        $sopt[5169]['name'] = __('Module', 'fusioninventory') . "-" . __('Network discovery', 'fusioninventory');
        $sopt[5169]['datatype'] = 'bool';
        $sopt[5169]['massiveaction'] = FALSE;
        $sopt[5170]['table'] = "glpi_plugin_fusioninventory_agentmodules";
        $sopt[5170]['field'] = "Collect";
        $sopt[5170]['linkfield'] = "Collect";
        $sopt[5170]['name'] = __('Module', 'fusioninventory') . "-" . __('Collect', 'fusioninventory');
        $sopt[5170]['datatype'] = 'bool';
        $sopt[5170]['massiveaction'] = FALSE;
        $sopt[5171]['name'] = __('Static group', 'fusioninventory');
        $sopt[5171]['table'] = getTableForItemType('PluginFusioninventoryDeployGroup');
        $sopt[5171]['massiveaction'] = FALSE;
        $sopt[5171]['field'] = 'name';
        $sopt[5171]['forcegroupby'] = true;
        $sopt[5171]['usehaving'] = true;
        $sopt[5171]['datatype'] = 'dropdown';
        $sopt[5171]['joinparams'] = array('beforejoin' => array('table' => 'glpi_plugin_fusioninventory_deploygroups_staticdatas', 'joinparams' => array('jointype' => 'itemtype_item', 'specific_itemtype' => 'Computer')));
    }
    if ($itemtype == 'Computer') {
        // Switch
        $sopt[5192]['table'] = 'glpi_plugin_fusioninventory_networkequipments';
        $sopt[5192]['field'] = 'name';
        $sopt[5192]['linkfield'] = '';
        $sopt[5192]['name'] = __('FusInv', 'fusioninventory') . " - " . __('Switch');
        $sopt[5192]['itemlink_type'] = 'NetworkEquipment';
        // Port of switch
        $sopt[5193]['table'] = 'glpi_plugin_fusioninventory_networkports';
        $sopt[5193]['field'] = 'id';
        $sopt[5193]['linkfield'] = '';
        $sopt[5193]['name'] = __('FusInv', 'fusioninventory') . " - " . __('Switch ports');
        $sopt[5193]['forcegroupby'] = '1';
    }
    if ($itemtype == 'Entity') {
        // Agent base URL
        $sopt[6192]['table'] = 'glpi_plugin_fusioninventory_entities';
        $sopt[6192]['field'] = 'agent_base_url';
        $sopt[6192]['linkfield'] = '';
        $sopt[6192]['name'] = __('Agent base URL', 'fusioninventory');
        $sopt[6192]['joinparams'] = array('jointype' => 'child');
        $sopt[6192]['massiveaction'] = FALSE;
    }
    if ($itemtype == 'Printer') {
        // Switch
        $sopt[5192]['table'] = 'glpi_plugin_fusioninventory_networkequipments';
        $sopt[5192]['field'] = 'name';
        $sopt[5192]['linkfield'] = '';
        $sopt[5192]['name'] = __('FusInv', 'fusioninventory') . " - " . __('Switch');
        $sopt[5192]['itemlink_type'] = 'NetworkEquipment';
        // Port of switch
        $sopt[5193]['table'] = 'glpi_plugin_fusioninventory_networkports';
        $sopt[5193]['field'] = 'id';
        $sopt[5193]['linkfield'] = '';
        $sopt[5193]['name'] = __('FusInv', 'fusioninventory') . " - " . __('Hardware ports');
        $sopt[5193]['forcegroupby'] = '1';
        $pfConfig = new PluginFusioninventoryConfig();
        $plugins_id = PluginFusioninventoryModule::getModuleId('fusioninventory');
        if ($pfConfig->getValue("storagesnmpauth") == "file") {
            $sopt[5191]['table'] = 'glpi_plugin_fusioninventory_printers';
            $sopt[5191]['field'] = 'plugin_fusioninventory_configsecurities_id';
            $sopt[5191]['linkfield'] = 'id';
            $sopt[5191]['name'] = __('FusInv', 'fusioninventory') . " - " . __('SNMP authentication', 'fusioninventory');
            $sopt[5191]['massiveaction'] = FALSE;
        } else {
            $sopt[5191]['table'] = 'glpi_plugin_fusioninventory_configsecurities';
            $sopt[5191]['field'] = 'name';
            $sopt[5191]['linkfield'] = 'plugin_fusioninventory_configsecurities_id';
            $sopt[5191]['name'] = __('FusInv', 'fusioninventory') . " - " . __('SNMP authentication', 'fusioninventory');
            $sopt[5191]['datatype'] = 'itemlink';
            $sopt[5191]['itemlink_type'] = 'PluginFusioninventoryConfigSecurity';
            $sopt[5191]['massiveaction'] = FALSE;
        }
        $sopt[5194]['table'] = 'glpi_plugin_fusioninventory_printers';
        $sopt[5194]['field'] = 'last_fusioninventory_update';
        $sopt[5194]['linkfield'] = '';
        $sopt[5194]['name'] = __('FusInv', 'fusioninventory') . " - " . __('Last inventory', 'fusioninventory');
        $sopt[5194]['datatype'] = 'datetime';
        $sopt[5194]['massiveaction'] = FALSE;
        $sopt[5196]['table'] = 'glpi_plugin_fusioninventory_printers';
        $sopt[5196]['field'] = 'sysdescr';
        $sopt[5196]['linkfield'] = '';
        $sopt[5196]['name'] = __('Sysdescr', 'fusioninventory');
        $sopt[5196]['datatype'] = 'text';
    }
    if ($itemtype == 'NetworkEquipment') {
        $pfConfig = new PluginFusioninventoryConfig();
        $plugins_id = PluginFusioninventoryModule::getModuleId('fusioninventory');
        $sopt[5191]['table'] = 'glpi_plugin_fusioninventory_configsecurities';
        $sopt[5191]['field'] = 'name';
        $sopt[5191]['linkfield'] = 'plugin_fusioninventory_configsecurities_id';
        $sopt[5191]['name'] = __('FusInv', 'fusioninventory') . " - " . __('SNMP authentication', 'fusioninventory');
        $sopt[5191]['datatype'] = 'itemlink';
        $sopt[5191]['itemlink_type'] = 'PluginFusioninventoryConfigSecurity';
        $sopt[5191]['massiveaction'] = FALSE;
        $sopt[5194]['table'] = 'glpi_plugin_fusioninventory_networkequipments';
        $sopt[5194]['field'] = 'last_fusioninventory_update';
        $sopt[5194]['linkfield'] = '';
        $sopt[5194]['name'] = __('FusInv', 'fusioninventory') . " - " . __('Last inventory', 'fusioninventory');
        $sopt[5194]['datatype'] = 'datetime';
        $sopt[5194]['massiveaction'] = FALSE;
        $sopt[5195]['table'] = 'glpi_plugin_fusioninventory_networkequipments';
        $sopt[5195]['field'] = 'cpu';
        $sopt[5195]['linkfield'] = '';
        $sopt[5195]['name'] = __('FusInv', 'fusioninventory') . " - " . __('CPU usage (in %)', 'fusioninventory');
        $sopt[5195]['datatype'] = 'number';
        $sopt[5196]['table'] = 'glpi_plugin_fusioninventory_networkequipments';
        $sopt[5196]['field'] = 'sysdescr';
        $sopt[5196]['linkfield'] = '';
        $sopt[5196]['name'] = __('Sysdescr', 'fusioninventory');
        $sopt[5196]['datatype'] = 'text';
    }
    return $sopt;
}
 /**
  * Display tab
  *
  * @param CommonGLPI $item
  * @param integer $withtemplate
  *
  * @return varchar name of the tab(s) to display
  */
 function getTabNameForItem(CommonGLPI $item, $withtemplate = 0)
 {
     $ong = array();
     if ($item->fields['id'] > 0) {
         $ong[1] = __('Import');
         $pfConfig = new PluginFusioninventoryConfig();
         if ($pfConfig->isActive('remotehttpagent') && Session::haveRight('plugin_fusioninventory_remotecontrol', UPDATE)) {
             $ong[2] = __('Job', 'fusioninventory');
         }
     }
     return $ong;
 }
 /**
  * Get default value for state of devices (monitor, printer...)
  *
  * @param type $input
  * @param type $check_management
  * @param type $management_value
  *
  */
 static function addDefaultStateIfNeeded(&$input, $check_management = FALSE, $management_value = 0)
 {
     $config = new PluginFusioninventoryConfig();
     $state = $config->getValue("states_id_default");
     if ($state) {
         if (!$check_management || $check_management && !$management_value) {
             $input['states_id'] = $state;
         }
     }
     return $input;
 }
 /**
  * After rules import device
  *
  * @param integer $items_id id of the device in GLPI DB (0 = created, other = merge)
  * @param varchar $itemtype itemtype of the device
  *
  * @return type
  */
 function rulepassed($items_id, $itemtype)
 {
     PluginFusioninventoryLogger::logIfExtradebug("pluginFusioninventory-rules", "Rule passed : " . $items_id . ", " . $itemtype . "\n");
     PluginFusioninventoryLogger::logIfExtradebugAndDebugMode('fusioninventorycommunication', 'Function PluginFusinvsnmpCommunicationSNMPQuery->rulepassed().');
     $_SESSION["plugin_fusioninventory_entity"] = 0;
     PluginFusioninventoryConfig::logIfExtradebug("pluginFusioninventory-rules", "Rule passed : " . $items_id . ", " . $itemtype . "\n");
     PluginFusioninventoryCommunication::addLog('Function PluginFusioninventoryCommunicationNetworkInventory->rulepassed().');
     $a_inventory = $_SESSION['SOURCE_XMLDEVICE'];
     $errors = '';
     $class = new $itemtype();
     if ($items_id == "0") {
         $input = array();
         $input['date_mod'] = date("Y-m-d H:i:s");
         if ($class->getFromDB($a_inventory[$a_inventory['itemtype']]['id'])) {
             $input['entities_id'] = $class->fields['entities_id'];
         } else {
             $input['entities_id'] = 0;
         }
         if (!isset($_SESSION['glpiactiveentities_string'])) {
             $_SESSION['glpiactiveentities_string'] = "'" . $input['entities_id'] . "'";
         }
         $_SESSION["plugin_fusioninventory_entity"] = $input['entities_id'];
         $items_id = $class->add($input);
         if (isset($_SESSION['plugin_fusioninventory_rules_id'])) {
             $pfRulematchedlog = new PluginFusioninventoryRulematchedlog();
             $inputrulelog = array();
             $inputrulelog['date'] = date('Y-m-d H:i:s');
             $inputrulelog['rules_id'] = $_SESSION['plugin_fusioninventory_rules_id'];
             if (isset($_SESSION['plugin_fusioninventory_agents_id'])) {
                 $inputrulelog['plugin_fusioninventory_agents_id'] = $_SESSION['plugin_fusioninventory_agents_id'];
             }
             $inputrulelog['items_id'] = $items_id;
             $inputrulelog['itemtype'] = $itemtype;
             $inputrulelog['method'] = 'snmpinventory';
             $pfRulematchedlog->add($inputrulelog);
             $pfRulematchedlog->cleanOlddata($items_id, $itemtype);
             unset($_SESSION['plugin_fusioninventory_rules_id']);
         }
     }
     if ($itemtype == "PluginFusioninventoryUnmanaged") {
         $class->getFromDB($items_id);
         $input = array();
         $input['id'] = $class->fields['id'];
         if (!empty($a_inventory[$a_inventory['itemtype']]['name'])) {
             $input['name'] = $a_inventory[$a_inventory['itemtype']]['name'];
         }
         if (!empty($a_inventory[$a_inventory['itemtype']]['serial'])) {
             $input['serial'] = $a_inventory[$a_inventory['itemtype']]['serial'];
         }
         if (!empty($a_inventory['itemtype'])) {
             $input['itemtype'] = $a_inventory['itemtype'];
         }
         // TODO : add import ports
         PluginFusioninventoryToolbox::writeXML($items_id, serialize($_SESSION['SOURCE_XMLDEVICE']), 'PluginFusioninventoryUnmanaged');
         $class->update($input);
         $_SESSION['plugin_fusinvsnmp_taskjoblog']['comment'] = '[==detail==] ==updatetheitem== Update ' . PluginFusioninventoryUnmanaged::getTypeName() . ' [[PluginFusioninventoryUnmanaged::' . $items_id . ']]';
         $this->addtaskjoblog();
     } else {
         $_SESSION['plugin_fusinvsnmp_taskjoblog']['comment'] = '[==detail==] Update ' . $class->getTypeName() . ' [[' . $itemtype . '::' . $items_id . ']]';
         $this->addtaskjoblog();
         $errors .= $this->importDevice($itemtype, $items_id, $a_inventory);
     }
     return $errors;
 }
 /**
  * Update computer data
  *
  * @global type $DB
  *
  * @param php array $a_computerinventory all data from the agent
  * @param integer $computers_id id of the computer
  * @param boolean $no_history set true if not want history
  *
  * @return nothing
  */
 function updateComputer($a_computerinventory, $computers_id, $no_history, $setdynamic = 0)
 {
     global $DB, $CFG_GLPI;
     $computer = new Computer();
     $pfInventoryComputerComputer = new PluginFusioninventoryInventoryComputerComputer();
     $item_DeviceProcessor = new Item_DeviceProcessor();
     $deviceProcessor = new DeviceProcessor();
     $item_DeviceMemory = new Item_DeviceMemory();
     $deviceMemory = new DeviceMemory();
     $computerVirtualmachine = new ComputerVirtualMachine();
     $computerDisk = new ComputerDisk();
     $item_DeviceControl = new Item_DeviceControl();
     $item_DeviceHardDrive = new Item_DeviceHardDrive();
     $item_DeviceDrive = new Item_DeviceDrive();
     $item_DeviceGraphicCard = new Item_DeviceGraphicCard();
     $item_DeviceNetworkCard = new Item_DeviceNetworkCard();
     $item_DeviceSoundCard = new Item_DeviceSoundCard();
     $networkPort = new NetworkPort();
     $networkName = new NetworkName();
     $iPAddress = new IPAddress();
     $ipnetwork = new IPNetwork();
     $pfInventoryComputerAntivirus = new PluginFusioninventoryInventoryComputerAntivirus();
     $pfConfig = new PluginFusioninventoryConfig();
     $pfComputerLicenseInfo = new PluginFusioninventoryComputerLicenseInfo();
     $computer_Item = new Computer_Item();
     $monitor = new Monitor();
     $printer = new Printer();
     $peripheral = new Peripheral();
     //      $pfInventoryComputerStorage   = new PluginFusioninventoryInventoryComputerStorage();
     //      $pfInventoryComputerStorage_Storage =
     //             new PluginFusioninventoryInventoryComputerStorage_Storage();
     $computer->getFromDB($computers_id);
     $a_lockable = PluginFusioninventoryLock::getLockFields('glpi_computers', $computers_id);
     // * Computer
     $db_computer = array();
     $db_computer = $computer->fields;
     $computerName = $a_computerinventory['Computer']['name'];
     $a_ret = PluginFusioninventoryToolbox::checkLock($a_computerinventory['Computer'], $db_computer, $a_lockable);
     $a_computerinventory['Computer'] = $a_ret[0];
     $input = $a_computerinventory['Computer'];
     $input['id'] = $computers_id;
     $history = TRUE;
     if ($no_history) {
         $history = FALSE;
     }
     $input['_no_history'] = $no_history;
     PluginFusioninventoryInventoryComputerInventory::addDefaultStateIfNeeded($input);
     $computer->update($input, !$no_history);
     $this->computer = $computer;
     // * Computer fusion (ext)
     $db_computer = array();
     if ($no_history === FALSE) {
         $query = "SELECT * FROM `glpi_plugin_fusioninventory_inventorycomputercomputers`\n                WHERE `computers_id` = '{$computers_id}'\n                LIMIT 1";
         $result = $DB->query($query);
         while ($data = $DB->fetch_assoc($result)) {
             foreach ($data as $key => $value) {
                 $data[$key] = Toolbox::addslashes_deep($value);
             }
             $db_computer = $data;
         }
     }
     if (count($db_computer) == '0') {
         // Add
         $a_computerinventory['fusioninventorycomputer']['computers_id'] = $computers_id;
         $pfInventoryComputerComputer->add($a_computerinventory['fusioninventorycomputer'], array(), FALSE);
     } else {
         // Update
         if (!empty($db_computer['serialized_inventory'])) {
             $setdynamic = 0;
         }
         $idtmp = $db_computer['id'];
         unset($db_computer['id']);
         unset($db_computer['computers_id']);
         $a_ret = PluginFusioninventoryToolbox::checkLock($a_computerinventory['fusioninventorycomputer'], $db_computer);
         $a_computerinventory['fusioninventorycomputer'] = $a_ret[0];
         $db_computer = $a_ret[1];
         $input = $a_computerinventory['fusioninventorycomputer'];
         $input['id'] = $idtmp;
         $input['_no_history'] = $no_history;
         $pfInventoryComputerComputer->update($input, !$no_history);
     }
     // Put all link item dynamic (in case of update computer not yet inventoried with fusion)
     if ($setdynamic == 1) {
         $this->setDynamicLinkItems($computers_id);
     }
     // * Processors
     if ($pfConfig->getValue("component_processor") != 0) {
         $db_processors = array();
         if ($no_history === FALSE) {
             $query = "SELECT `glpi_items_deviceprocessors`.`id`, `designation`,\n                     `frequency`, `frequence`, `frequency_default`,\n                     `serial`, `manufacturers_id`, `glpi_items_deviceprocessors`.`nbcores`,\n                     `glpi_items_deviceprocessors`.`nbthreads`\n                  FROM `glpi_items_deviceprocessors`\n                  LEFT JOIN `glpi_deviceprocessors`\n                     ON `deviceprocessors_id`=`glpi_deviceprocessors`.`id`\n                  WHERE `items_id` = '{$computers_id}'\n                     AND `itemtype`='Computer'\n                     AND `is_dynamic`='1'";
             $result = $DB->query($query);
             while ($data = $DB->fetch_assoc($result)) {
                 $idtmp = $data['id'];
                 unset($data['id']);
                 $db_processors[$idtmp] = Toolbox::addslashes_deep($data);
             }
         }
         if (count($db_processors) == 0) {
             foreach ($a_computerinventory['processor'] as $a_processor) {
                 $this->addProcessor($a_processor, $computers_id, $no_history);
             }
         } else {
             // Check all fields from source: 'designation', 'serial', 'manufacturers_id',
             // 'frequence'
             foreach ($a_computerinventory['processor'] as $key => $arrays) {
                 $frequence = $arrays['frequence'];
                 unset($arrays['frequence']);
                 unset($arrays['frequency']);
                 unset($arrays['frequency_default']);
                 foreach ($db_processors as $keydb => $arraydb) {
                     $frequencedb = $arraydb['frequence'];
                     unset($arraydb['frequence']);
                     unset($arraydb['frequency']);
                     unset($arraydb['frequency_default']);
                     if ($arrays == $arraydb) {
                         $a_criteria = $deviceProcessor->getImportCriteria();
                         $criteriafrequence = $a_criteria['frequence'];
                         $compare = explode(':', $criteriafrequence);
                         if ($frequence > $frequencedb - $compare[1] && $frequence < $frequencedb + $compare[1]) {
                             unset($a_computerinventory['processor'][$key]);
                             unset($db_processors[$keydb]);
                             break;
                         }
                     }
                 }
             }
             if (count($a_computerinventory['processor']) == 0 and count($db_processors) == 0) {
                 // Nothing to do
             } else {
                 if (count($db_processors) != 0) {
                     // Delete processor in DB
                     foreach ($db_processors as $idtmp => $data) {
                         $item_DeviceProcessor->delete(array('id' => $idtmp), 1);
                     }
                 }
                 if (count($a_computerinventory['processor']) != 0) {
                     foreach ($a_computerinventory['processor'] as $a_processor) {
                         $this->addProcessor($a_processor, $computers_id, $no_history);
                     }
                 }
             }
         }
     }
     // * Memories
     if ($pfConfig->getValue("component_memory") != 0) {
         $db_memories = array();
         if ($no_history === FALSE) {
             $query = "SELECT `glpi_items_devicememories`.`id`, `designation`, `size`,\n                     `frequence`, `serial`, `devicememorytypes_id`,\n                     `glpi_items_devicememories`.`busID`\n                     FROM `glpi_items_devicememories`\n                  LEFT JOIN `glpi_devicememories` ON `devicememories_id`=`glpi_devicememories`.`id`\n                  WHERE `items_id` = '{$computers_id}'\n                     AND `itemtype`='Computer'\n                     AND `is_dynamic`='1'";
             $result = $DB->query($query);
             while ($data = $DB->fetch_assoc($result)) {
                 $idtmp = $data['id'];
                 unset($data['id']);
                 $data1 = Toolbox::addslashes_deep($data);
                 $db_memories[$idtmp] = $data1;
             }
         }
         if (count($db_memories) == 0) {
             foreach ($a_computerinventory['memory'] as $a_memory) {
                 $this->addMemory($a_memory, $computers_id, $no_history);
             }
         } else {
             // Check all fields from source: 'designation', 'serial', 'size',
             // 'devicememorytypes_id', 'frequence'
             foreach ($a_computerinventory['memory'] as $key => $arrays) {
                 $frequence = $arrays['frequence'];
                 unset($arrays['frequence']);
                 foreach ($db_memories as $keydb => $arraydb) {
                     $frequencedb = $arraydb['frequence'];
                     unset($arraydb['frequence']);
                     if ($arrays == $arraydb) {
                         $a_criteria = $deviceMemory->getImportCriteria();
                         $criteriafrequence = $a_criteria['frequence'];
                         $compare = explode(':', $criteriafrequence);
                         if ($frequence > $frequencedb - $compare[1] && $frequence < $frequencedb + $compare[1]) {
                             unset($a_computerinventory['memory'][$key]);
                             unset($db_memories[$keydb]);
                             break;
                         }
                     }
                 }
             }
             if (count($a_computerinventory['memory']) == 0 and count($db_memories) == 0) {
                 // Nothing to do
             } else {
                 if (count($db_memories) != 0) {
                     // Delete memory in DB
                     foreach ($db_memories as $idtmp => $data) {
                         $item_DeviceMemory->delete(array('id' => $idtmp), 1);
                     }
                 }
                 if (count($a_computerinventory['memory']) != 0) {
                     foreach ($a_computerinventory['memory'] as $a_memory) {
                         $this->addMemory($a_memory, $computers_id, $no_history);
                     }
                 }
             }
         }
     }
     // * Hard drive
     if ($pfConfig->getValue("component_harddrive") != 0) {
         $db_harddrives = array();
         if ($no_history === FALSE) {
             $query = "SELECT `glpi_items_deviceharddrives`.`id`, `serial`,\n                     `capacity`\n                     FROM `glpi_items_deviceharddrives`\n                  WHERE `items_id` = '{$computers_id}'\n                     AND `itemtype`='Computer'\n                     AND `is_dynamic`='1'";
             $result = $DB->query($query);
             while ($data = $DB->fetch_assoc($result)) {
                 $idtmp = $data['id'];
                 unset($data['id']);
                 $data1 = Toolbox::addslashes_deep($data);
                 $data2 = array_map('strtolower', $data1);
                 $db_harddrives[$idtmp] = $data2;
             }
         }
         if (count($db_harddrives) == 0) {
             foreach ($a_computerinventory['harddrive'] as $a_harddrive) {
                 $this->addHardDisk($a_harddrive, $computers_id, $no_history);
             }
         } else {
             foreach ($a_computerinventory['harddrive'] as $key => $arrays) {
                 $arrayslower = array_map('strtolower', $arrays);
                 foreach ($db_harddrives as $keydb => $arraydb) {
                     if ($arrayslower['serial'] == $arraydb['serial']) {
                         if ($arraydb['capacity'] == 0 and $arrayslower['capacity'] > 0) {
                             $input = array('id' => $keydb, 'capacity' => $arrayslower['capacity']);
                             $item_DeviceHardDrive->update($input);
                         }
                         unset($a_computerinventory['harddrive'][$key]);
                         unset($db_harddrives[$keydb]);
                         break;
                     }
                 }
             }
             if (count($a_computerinventory['harddrive']) == 0 and count($db_harddrives) == 0) {
                 // Nothing to do
             } else {
                 if (count($db_harddrives) != 0) {
                     // Delete hard drive in DB
                     foreach ($db_harddrives as $idtmp => $data) {
                         $item_DeviceHardDrive->delete(array('id' => $idtmp), 1);
                     }
                 }
                 if (count($a_computerinventory['harddrive']) != 0) {
                     foreach ($a_computerinventory['harddrive'] as $a_harddrive) {
                         $this->addHardDisk($a_harddrive, $computers_id, $no_history);
                     }
                 }
             }
         }
     }
     // * drive
     if ($pfConfig->getValue("component_drive") != 0) {
         $db_drives = array();
         if ($no_history === FALSE) {
             $query = "SELECT `glpi_items_devicedrives`.`id`, `serial`,\n                     `glpi_devicedrives`.`designation`\n                     FROM `glpi_items_devicedrives`\n                  LEFT JOIN `glpi_devicedrives` ON `devicedrives_id`=`glpi_devicedrives`.`id`\n                  WHERE `items_id` = '{$computers_id}'\n                     AND `itemtype`='Computer'\n                     AND `is_dynamic`='1'";
             $result = $DB->query($query);
             while ($data = $DB->fetch_assoc($result)) {
                 $idtmp = $data['id'];
                 unset($data['id']);
                 $data1 = Toolbox::addslashes_deep($data);
                 $data2 = array_map('strtolower', $data1);
                 $db_drives[$idtmp] = $data2;
             }
         }
         if (count($db_drives) == 0) {
             foreach ($a_computerinventory['drive'] as $a_drive) {
                 $this->addDrive($a_drive, $computers_id, $no_history);
             }
         } else {
             foreach ($a_computerinventory['drive'] as $key => $arrays) {
                 $arrayslower = array_map('strtolower', $arrays);
                 if ($arrayslower['serial'] == '') {
                     foreach ($db_drives as $keydb => $arraydb) {
                         if ($arrayslower['designation'] == $arraydb['designation']) {
                             unset($a_computerinventory['drive'][$key]);
                             unset($db_drives[$keydb]);
                             break;
                         }
                     }
                 } else {
                     foreach ($db_drives as $keydb => $arraydb) {
                         if ($arrayslower['serial'] == $arraydb['serial']) {
                             unset($a_computerinventory['drive'][$key]);
                             unset($db_drives[$keydb]);
                             break;
                         }
                     }
                 }
             }
             if (count($a_computerinventory['drive']) == 0 and count($db_drives) == 0) {
                 // Nothing to do
             } else {
                 if (count($db_drives) != 0) {
                     // Delete drive in DB
                     foreach ($db_drives as $idtmp => $data) {
                         $item_DeviceDrive->delete(array('id' => $idtmp), 1);
                     }
                 }
                 if (count($a_computerinventory['drive']) != 0) {
                     foreach ($a_computerinventory['drive'] as $a_drive) {
                         $this->addDrive($a_drive, $computers_id, $no_history);
                     }
                 }
             }
         }
     }
     // * Graphiccard
     if ($pfConfig->getValue("component_graphiccard") != 0) {
         $db_graphiccards = array();
         if ($no_history === FALSE) {
             $query = "SELECT `glpi_items_devicegraphiccards`.`id`, `designation`, `memory`\n                     FROM `glpi_items_devicegraphiccards`\n                  LEFT JOIN `glpi_devicegraphiccards`\n                     ON `devicegraphiccards_id`=`glpi_devicegraphiccards`.`id`\n                  WHERE `items_id` = '{$computers_id}'\n                     AND `itemtype`='Computer'\n                     AND `is_dynamic`='1'";
             $result = $DB->query($query);
             while ($data = $DB->fetch_assoc($result)) {
                 $idtmp = $data['id'];
                 unset($data['id']);
                 if (preg_match("/[^a-zA-Z0-9 \\-_\\(\\)]+/", $data['designation'])) {
                     $data['designation'] = Toolbox::addslashes_deep($data['designation']);
                 }
                 $data['designation'] = trim(strtolower($data['designation']));
                 $db_graphiccards[$idtmp] = $data;
             }
         }
         if (count($db_graphiccards) == 0) {
             foreach ($a_computerinventory['graphiccard'] as $a_graphiccard) {
                 $this->addGraphicCard($a_graphiccard, $computers_id, $no_history);
             }
         } else {
             // Check all fields from source: 'designation', 'memory'
             foreach ($a_computerinventory['graphiccard'] as $key => $arrays) {
                 $arrays['designation'] = strtolower($arrays['designation']);
                 foreach ($db_graphiccards as $keydb => $arraydb) {
                     if ($arrays == $arraydb) {
                         unset($a_computerinventory['graphiccard'][$key]);
                         unset($db_graphiccards[$keydb]);
                         break;
                     }
                 }
             }
             if (count($a_computerinventory['graphiccard']) == 0 and count($db_graphiccards) == 0) {
                 // Nothing to do
             } else {
                 if (count($db_graphiccards) != 0) {
                     // Delete graphiccard in DB
                     foreach ($db_graphiccards as $idtmp => $data) {
                         $item_DeviceGraphicCard->delete(array('id' => $idtmp), 1);
                     }
                 }
                 if (count($a_computerinventory['graphiccard']) != 0) {
                     foreach ($a_computerinventory['graphiccard'] as $a_graphiccard) {
                         $this->addGraphicCard($a_graphiccard, $computers_id, $no_history);
                     }
                 }
             }
         }
     }
     // * networkcard
     if ($pfConfig->getValue("component_networkcard") != 0) {
         $db_networkcards = array();
         if ($no_history === FALSE) {
             $query = "SELECT `glpi_items_devicenetworkcards`.`id`, `designation`, `mac`,\n                     `manufacturers_id`\n                     FROM `glpi_items_devicenetworkcards`\n                  LEFT JOIN `glpi_devicenetworkcards`\n                     ON `devicenetworkcards_id`=`glpi_devicenetworkcards`.`id`\n                  WHERE `items_id` = '{$computers_id}'\n                     AND `itemtype`='Computer'\n                     AND `is_dynamic`='1'";
             $result = $DB->query($query);
             while ($data = $DB->fetch_assoc($result)) {
                 $idtmp = $data['id'];
                 unset($data['id']);
                 if (preg_match("/[^a-zA-Z0-9 \\-_\\(\\)]+/", $data['designation'])) {
                     $data['designation'] = Toolbox::addslashes_deep($data['designation']);
                 }
                 $data['designation'] = trim(strtolower($data['designation']));
                 $db_networkcards[$idtmp] = $data;
             }
         }
         if (count($db_networkcards) == 0) {
             foreach ($a_computerinventory['networkcard'] as $a_networkcard) {
                 $this->addNetworkCard($a_networkcard, $computers_id, $no_history);
             }
         } else {
             // Check all fields from source: 'designation', 'mac'
             foreach ($a_computerinventory['networkcard'] as $key => $arrays) {
                 $arrays['designation'] = strtolower($arrays['designation']);
                 foreach ($db_networkcards as $keydb => $arraydb) {
                     if ($arrays == $arraydb) {
                         unset($a_computerinventory['networkcard'][$key]);
                         unset($db_networkcards[$keydb]);
                         break;
                     }
                 }
             }
             if (count($a_computerinventory['networkcard']) == 0 and count($db_networkcards) == 0) {
                 // Nothing to do
             } else {
                 if (count($db_networkcards) != 0) {
                     // Delete networkcard in DB
                     foreach ($db_networkcards as $idtmp => $data) {
                         $item_DeviceNetworkCard->delete(array('id' => $idtmp), 1);
                     }
                 }
                 if (count($a_computerinventory['networkcard']) != 0) {
                     foreach ($a_computerinventory['networkcard'] as $a_networkcard) {
                         $this->addNetworkCard($a_networkcard, $computers_id, $no_history);
                     }
                 }
             }
         }
     }
     // * Sound
     if ($pfConfig->getValue("component_soundcard") != 0) {
         $db_soundcards = array();
         if ($no_history === FALSE) {
             $query = "SELECT `glpi_items_devicesoundcards`.`id`, `designation`, `comment`,\n                     `manufacturers_id` FROM `glpi_items_devicesoundcards`\n                  LEFT JOIN `glpi_devicesoundcards`\n                     ON `devicesoundcards_id`=`glpi_devicesoundcards`.`id`\n                  WHERE `items_id` = '{$computers_id}'\n                     AND `itemtype`='Computer'\n                     AND `is_dynamic`='1'";
             $result = $DB->query($query);
             while ($data = $DB->fetch_assoc($result)) {
                 $idtmp = $data['id'];
                 unset($data['id']);
                 $data1 = Toolbox::addslashes_deep($data);
                 $db_soundcards[$idtmp] = $data1;
             }
         }
         if (count($db_soundcards) == 0) {
             foreach ($a_computerinventory['soundcard'] as $a_soundcard) {
                 $this->addSoundCard($a_soundcard, $computers_id, $no_history);
             }
         } else {
             // Check all fields from source: 'designation', 'memory', 'manufacturers_id'
             foreach ($a_computerinventory['soundcard'] as $key => $arrays) {
                 //               $arrayslower = array_map('strtolower', $arrays);
                 $arrayslower = $arrays;
                 foreach ($db_soundcards as $keydb => $arraydb) {
                     if ($arrayslower == $arraydb) {
                         unset($a_computerinventory['soundcard'][$key]);
                         unset($db_soundcards[$keydb]);
                         break;
                     }
                 }
             }
             if (count($a_computerinventory['soundcard']) == 0 and count($db_soundcards) == 0) {
                 // Nothing to do
             } else {
                 if (count($db_soundcards) != 0) {
                     // Delete soundcard in DB
                     foreach ($db_soundcards as $idtmp => $data) {
                         $item_DeviceSoundCard->delete(array('id' => $idtmp), 1);
                     }
                 }
                 if (count($a_computerinventory['soundcard']) != 0) {
                     foreach ($a_computerinventory['soundcard'] as $a_soundcard) {
                         $this->addSoundCard($a_soundcard, $computers_id, $no_history);
                     }
                 }
             }
         }
     }
     // * Controllers
     if ($pfConfig->getValue("component_control") != 0) {
         $db_controls = array();
         if ($no_history === FALSE) {
             $query = "SELECT `glpi_items_devicecontrols`.`id`, `interfacetypes_id`,\n                     `manufacturers_id`, `designation` FROM `glpi_items_devicecontrols`\n                  LEFT JOIN `glpi_devicecontrols` ON `devicecontrols_id`=`glpi_devicecontrols`.`id`\n                  WHERE `items_id` = '{$computers_id}'\n                     AND `itemtype`='Computer'\n                     AND `is_dynamic`='1'";
             $result = $DB->query($query);
             while ($data = $DB->fetch_assoc($result)) {
                 $idtmp = $data['id'];
                 unset($data['id']);
                 $data1 = Toolbox::addslashes_deep($data);
                 $data2 = array_map('strtolower', $data1);
                 $db_controls[$idtmp] = $data2;
             }
         }
         if (count($db_controls) == 0) {
             foreach ($a_computerinventory['controller'] as $a_control) {
                 $this->addControl($a_control, $computers_id, $no_history);
             }
         } else {
             // Check all fields from source:
             foreach ($a_computerinventory['controller'] as $key => $arrays) {
                 $arrayslower = array_map('strtolower', $arrays);
                 foreach ($db_controls as $keydb => $arraydb) {
                     if ($arrayslower == $arraydb) {
                         unset($a_computerinventory['controller'][$key]);
                         unset($db_controls[$keydb]);
                         break;
                     }
                 }
             }
             if (count($a_computerinventory['controller']) == 0 and count($db_controls) == 0) {
                 // Nothing to do
             } else {
                 if (count($db_controls) != 0) {
                     // Delete controller in DB
                     foreach ($db_controls as $idtmp => $data) {
                         $item_DeviceControl->delete(array('id' => $idtmp), 1);
                     }
                 }
                 if (count($a_computerinventory['controller']) != 0) {
                     foreach ($a_computerinventory['controller'] as $a_control) {
                         $this->addControl($a_control, $computers_id, $no_history);
                     }
                 }
             }
         }
     }
     // * Software
     if ($pfConfig->getValue("import_software") != 0) {
         $entities_id = 0;
         if (count($a_computerinventory['software']) > 0) {
             $a_softfirst = current($a_computerinventory['software']);
             if (isset($a_softfirst['entities_id'])) {
                 $entities_id = $a_softfirst['entities_id'];
             }
         }
         $db_software = array();
         if ($no_history === FALSE) {
             $query = "SELECT `glpi_computers_softwareversions`.`id` as sid,\n                          `glpi_softwares`.`name`,\n                          `glpi_softwareversions`.`name` AS version,\n                          `glpi_softwares`.`manufacturers_id`,\n                          `glpi_softwareversions`.`entities_id`,\n                          `glpi_computers_softwareversions`.`is_template_computer`,\n                          `glpi_computers_softwareversions`.`is_deleted_computer`\n                   FROM `glpi_computers_softwareversions`\n                   LEFT JOIN `glpi_softwareversions`\n                        ON (`glpi_computers_softwareversions`.`softwareversions_id`\n                              = `glpi_softwareversions`.`id`)\n                   LEFT JOIN `glpi_softwares`\n                        ON (`glpi_softwareversions`.`softwares_id` = `glpi_softwares`.`id`)\n                   WHERE `glpi_computers_softwareversions`.`computers_id` = '{$computers_id}'\n                     AND `glpi_computers_softwareversions`.`is_dynamic`='1'";
             $result = $DB->query($query);
             while ($data = $DB->fetch_assoc($result)) {
                 $idtmp = $data['sid'];
                 unset($data['sid']);
                 if (preg_match("/[^a-zA-Z0-9 \\-_\\(\\)]+/", $data['name'])) {
                     $data['name'] = Toolbox::addslashes_deep($data['name']);
                 }
                 if (preg_match("/[^a-zA-Z0-9 \\-_\\(\\)]+/", $data['version'])) {
                     $data['version'] = Toolbox::addslashes_deep($data['version']);
                 }
                 $comp_key = strtolower($data['name']) . "\$\$\$\$" . strtolower($data['version']) . "\$\$\$\$" . $data['manufacturers_id'] . "\$\$\$\$" . $data['entities_id'];
                 $db_software[$comp_key] = $idtmp;
             }
         }
         $lastSoftwareid = 0;
         $lastSoftwareVid = 0;
         /*
          * Schema
          *
          * LOCK software
          * 1/ Add all software
          * RELEASE software
          *
          * LOCK softwareversion
          * 2/ Add all software versions
          * RELEASE softwareversion
          *
          * 3/ add version to computer
          *
          */
         if (count($db_software) == 0) {
             // there are no software associated with computer
             $nb_unicity = count(FieldUnicity::getUnicityFieldsConfig("Software", $entities_id));
             $options = array();
             if ($nb_unicity == 0) {
                 $options['disable_unicity_check'] = TRUE;
             }
             $a_softwareInventory = array();
             $a_softwareVersionInventory = array();
             $lastSoftwareid = $this->loadSoftwares($entities_id, $a_computerinventory['software'], $lastSoftwareid);
             $queryDBLOCK = "INSERT INTO `glpi_plugin_fusioninventory_dblocksoftwares`\n                     SET `value`='1'";
             $CFG_GLPI["use_log_in_files"] = FALSE;
             while (!$DB->query($queryDBLOCK)) {
                 usleep(100000);
             }
             $CFG_GLPI["use_log_in_files"] = TRUE;
             $this->loadSoftwares($entities_id, $a_computerinventory['software'], $lastSoftwareid);
             foreach ($a_computerinventory['software'] as $a_software) {
                 if (!isset($this->softList[$a_software['name'] . "\$\$\$\$" . $a_software['manufacturers_id']])) {
                     $this->addSoftware($a_software, $options);
                 }
             }
             $queryDBLOCK = "DELETE FROM `glpi_plugin_fusioninventory_dblocksoftwares`\n                     WHERE `value`='1'";
             $DB->query($queryDBLOCK);
             $lastSoftwareVid = $this->loadSoftwareVersions($entities_id, $a_computerinventory['software'], $lastSoftwareVid);
             $queryDBLOCK = "INSERT INTO `glpi_plugin_fusioninventory_dblocksoftwareversions`\n                     SET `value`='1'";
             $CFG_GLPI["use_log_in_files"] = FALSE;
             while (!$DB->query($queryDBLOCK)) {
                 usleep(100000);
             }
             $CFG_GLPI["use_log_in_files"] = TRUE;
             $this->loadSoftwareVersions($entities_id, $a_computerinventory['software'], $lastSoftwareVid);
             foreach ($a_computerinventory['software'] as $a_software) {
                 $softwares_id = $this->softList[$a_software['name'] . "\$\$\$\$" . $a_software['manufacturers_id']];
                 if (!isset($this->softVersionList[strtolower($a_software['version']) . "\$\$\$\$" . $softwares_id])) {
                     $this->addSoftwareVersion($a_software, $softwares_id);
                 }
             }
             $queryDBLOCK = "DELETE FROM `glpi_plugin_fusioninventory_dblocksoftwareversions`\n                     WHERE `value`='1'";
             $DB->query($queryDBLOCK);
             $a_toinsert = array();
             foreach ($a_computerinventory['software'] as $a_software) {
                 $softwares_id = $this->softList[$a_software['name'] . "\$\$\$\$" . $a_software['manufacturers_id']];
                 $softwareversions_id = $this->softVersionList[strtolower($a_software['version']) . "\$\$\$\$" . $softwares_id];
                 $a_tmp = array('computers_id' => $computers_id, 'softwareversions_id' => $softwareversions_id, 'is_dynamic' => 1, 'entities_id' => $a_software['entities_id']);
                 $a_toinsert[] = "('" . implode("','", $a_tmp) . "')";
             }
             if (count($a_toinsert) > 0) {
                 $this->addSoftwareVersionsComputer($a_toinsert);
                 if (!$no_history) {
                     foreach ($a_computerinventory['software'] as $a_software) {
                         $softwares_id = $this->softList[$a_software['name'] . "\$\$\$\$" . $a_software['manufacturers_id']];
                         $softwareversions_id = $this->softVersionList[strtolower($a_software['version']) . "\$\$\$\$" . $softwares_id];
                         $changes[0] = '0';
                         $changes[1] = "";
                         $changes[2] = $a_software['name'] . " - " . sprintf(__('%1$s (%2$s)'), $a_software['version'], $softwareversions_id);
                         $this->addPrepareLog($computers_id, 'Computer', 'SoftwareVersion', $changes, Log::HISTORY_INSTALL_SOFTWARE);
                         $changes[0] = '0';
                         $changes[1] = "";
                         $changes[2] = sprintf(__('%1$s (%2$s)'), $computerName, $computers_id);
                         $this->addPrepareLog($softwareversions_id, 'SoftwareVersion', 'Computer', $changes, Log::HISTORY_INSTALL_SOFTWARE);
                     }
                 }
             }
         } else {
             foreach ($a_computerinventory['software'] as $key => $arrayslower) {
                 if (isset($db_software[$key])) {
                     unset($a_computerinventory['software'][$key]);
                     unset($db_software[$key]);
                 }
             }
             if (count($a_computerinventory['software']) == 0 && count($db_software) == 0) {
                 // Nothing to do
             } else {
                 if (count($db_software) > 0) {
                     // Delete softwares in DB
                     $a_delete = array();
                     foreach ($db_software as $idtmp) {
                         $this->computer_SoftwareVersion->getFromDB($idtmp);
                         $this->softwareVersion->getFromDB($this->computer_SoftwareVersion->fields['softwareversions_id']);
                         //                        $this->computer_SoftwareVersion->delete(array('id'=>$idtmp, '_no_history'=> TRUE), FALSE);
                         if (!$no_history) {
                             $changes[0] = '0';
                             $changes[1] = addslashes($this->computer_SoftwareVersion->getHistoryNameForItem1($this->softwareVersion, 'delete'));
                             $changes[2] = "";
                             $this->addPrepareLog($computers_id, 'Computer', 'SoftwareVersion', $changes, Log::HISTORY_UNINSTALL_SOFTWARE);
                             $changes[0] = '0';
                             $changes[1] = sprintf(__('%1$s (%2$s)'), $computerName, $computers_id);
                             $changes[2] = "";
                             $this->addPrepareLog($idtmp, 'SoftwareVersion', 'Computer', $changes, Log::HISTORY_UNINSTALL_SOFTWARE);
                         }
                     }
                     $query = "DELETE FROM `glpi_computers_softwareversions` " . "WHERE `id` IN ('" . implode("', '", $db_software) . "')";
                     $DB->query($query);
                 }
                 if (count($a_computerinventory['software']) > 0) {
                     $nb_unicity = count(FieldUnicity::getUnicityFieldsConfig("Software", $entities_id));
                     $options = array();
                     if ($nb_unicity == 0) {
                         $options['disable_unicity_check'] = TRUE;
                     }
                     $lastSoftwareid = $this->loadSoftwares($entities_id, $a_computerinventory['software'], $lastSoftwareid);
                     $queryDBLOCK = "INSERT INTO `glpi_plugin_fusioninventory_dblocksoftwares`\n                           SET `value`='1'";
                     $CFG_GLPI["use_log_in_files"] = FALSE;
                     while (!$DB->query($queryDBLOCK)) {
                         usleep(100000);
                     }
                     $CFG_GLPI["use_log_in_files"] = TRUE;
                     $this->loadSoftwares($entities_id, $a_computerinventory['software'], $lastSoftwareid);
                     foreach ($a_computerinventory['software'] as $a_software) {
                         if (!isset($this->softList[$a_software['name'] . "\$\$\$\$" . $a_software['manufacturers_id']])) {
                             $this->addSoftware($a_software, $options);
                         }
                     }
                     $queryDBLOCK = "DELETE FROM `glpi_plugin_fusioninventory_dblocksoftwares`\n                           WHERE `value`='1'";
                     $DB->query($queryDBLOCK);
                     $lastSoftwareVid = $this->loadSoftwareVersions($entities_id, $a_computerinventory['software'], $lastSoftwareVid);
                     $queryDBLOCK = "INSERT INTO `glpi_plugin_fusioninventory_dblocksoftwareversions`\n                           SET `value`='1'";
                     $CFG_GLPI["use_log_in_files"] = FALSE;
                     while (!$DB->query($queryDBLOCK)) {
                         usleep(100000);
                     }
                     $CFG_GLPI["use_log_in_files"] = TRUE;
                     $this->loadSoftwareVersions($entities_id, $a_computerinventory['software'], $lastSoftwareVid);
                     foreach ($a_computerinventory['software'] as $a_software) {
                         $softwares_id = $this->softList[$a_software['name'] . "\$\$\$\$" . $a_software['manufacturers_id']];
                         if (!isset($this->softVersionList[strtolower($a_software['version']) . "\$\$\$\$" . $softwares_id])) {
                             $this->addSoftwareVersion($a_software, $softwares_id);
                         }
                     }
                     $queryDBLOCK = "DELETE FROM `glpi_plugin_fusioninventory_dblocksoftwareversions`\n                           WHERE `value`='1'";
                     $DB->query($queryDBLOCK);
                     $a_toinsert = array();
                     foreach ($a_computerinventory['software'] as $a_software) {
                         $softwares_id = $this->softList[$a_software['name'] . "\$\$\$\$" . $a_software['manufacturers_id']];
                         $softwareversions_id = $this->softVersionList[strtolower($a_software['version']) . "\$\$\$\$" . $softwares_id];
                         $a_tmp = array('computers_id' => $computers_id, 'softwareversions_id' => $softwareversions_id, 'is_dynamic' => 1, 'entities_id' => $a_software['entities_id']);
                         $a_toinsert[] = "('" . implode("','", $a_tmp) . "')";
                     }
                     $this->addSoftwareVersionsComputer($a_toinsert);
                     if (!$no_history) {
                         foreach ($a_computerinventory['software'] as $a_software) {
                             $softwares_id = $this->softList[$a_software['name'] . "\$\$\$\$" . $a_software['manufacturers_id']];
                             $softwareversions_id = $this->softVersionList[strtolower($a_software['version']) . "\$\$\$\$" . $softwares_id];
                             $changes[0] = '0';
                             $changes[1] = "";
                             $changes[2] = $a_software['name'] . " - " . sprintf(__('%1$s (%2$s)'), $a_software['version'], $softwareversions_id);
                             $this->addPrepareLog($computers_id, 'Computer', 'SoftwareVersion', $changes, Log::HISTORY_INSTALL_SOFTWARE);
                             $changes[0] = '0';
                             $changes[1] = "";
                             $changes[2] = sprintf(__('%1$s (%2$s)'), $computerName, $computers_id);
                             $this->addPrepareLog($softwareversions_id, 'SoftwareVersion', 'Computer', $changes, Log::HISTORY_INSTALL_SOFTWARE);
                         }
                     }
                 }
             }
         }
     }
     // * Virtualmachines
     if ($pfConfig->getValue("import_vm") == 1) {
         $db_computervirtualmachine = array();
         if ($no_history === FALSE) {
             $query = "SELECT `id`, `name`, `uuid`, `virtualmachinesystems_id`\n                     FROM `glpi_computervirtualmachines`\n                  WHERE `computers_id` = '{$computers_id}'\n                     AND `is_dynamic`='1'";
             $result = $DB->query($query);
             while ($data = $DB->fetch_assoc($result)) {
                 $idtmp = $data['id'];
                 unset($data['id']);
                 $data1 = Toolbox::addslashes_deep($data);
                 $db_computervirtualmachine[$idtmp] = $data1;
             }
         }
         $simplecomputervirtualmachine = array();
         if (isset($a_computerinventory['virtualmachine'])) {
             foreach ($a_computerinventory['virtualmachine'] as $key => $a_computervirtualmachine) {
                 $a_field = array('name', 'uuid', 'virtualmachinesystems_id');
                 foreach ($a_field as $field) {
                     if (isset($a_computervirtualmachine[$field])) {
                         $simplecomputervirtualmachine[$key][$field] = $a_computervirtualmachine[$field];
                     }
                 }
             }
         }
         foreach ($simplecomputervirtualmachine as $key => $arrays) {
             foreach ($db_computervirtualmachine as $keydb => $arraydb) {
                 if ($arrays == $arraydb) {
                     $input = array();
                     $input['id'] = $keydb;
                     if (isset($a_computerinventory['virtualmachine'][$key]['vcpu'])) {
                         $input['vcpu'] = $a_computerinventory['virtualmachine'][$key]['vcpu'];
                     }
                     if (isset($a_computerinventory['virtualmachine'][$key]['ram'])) {
                         $input['ram'] = $a_computerinventory['virtualmachine'][$key]['ram'];
                     }
                     if (isset($a_computerinventory['virtualmachine'][$key]['virtualmachinetypes_id'])) {
                         $input['virtualmachinetypes_id'] = $a_computerinventory['virtualmachine'][$key]['virtualmachinetypes_id'];
                     }
                     if (isset($a_computerinventory['virtualmachine'][$key]['virtualmachinestates_id'])) {
                         $input['virtualmachinestates_id'] = $a_computerinventory['virtualmachine'][$key]['virtualmachinestates_id'];
                     }
                     $computerVirtualmachine->update($input, !$no_history);
                     unset($simplecomputervirtualmachine[$key]);
                     unset($a_computerinventory['virtualmachine'][$key]);
                     unset($db_computervirtualmachine[$keydb]);
                     break;
                 }
             }
         }
         if (count($a_computerinventory['virtualmachine']) == 0 && count($db_computervirtualmachine) == 0) {
             // Nothing to do
         } else {
             if (count($db_computervirtualmachine) != 0) {
                 // Delete virtualmachine in DB
                 foreach ($db_computervirtualmachine as $idtmp => $data) {
                     $computerVirtualmachine->delete(array('id' => $idtmp), 1);
                 }
             }
             if (count($a_computerinventory['virtualmachine']) != 0) {
                 foreach ($a_computerinventory['virtualmachine'] as $a_virtualmachine) {
                     $a_virtualmachine['computers_id'] = $computers_id;
                     $computerVirtualmachine->add($a_virtualmachine, array(), !$no_history);
                 }
             }
         }
     }
     if ($pfConfig->getValue("create_vm") == 1) {
         // Create VM based on information of section VIRTUALMACHINE
         $pfAgent = new PluginFusioninventoryAgent();
         // Use ComputerVirtualMachine::getUUIDRestrictRequest to get existant
         // vm in computer list
         $computervm = new Computer();
         if (isset($a_computerinventory['virtualmachine_creation']) && is_array($a_computerinventory['virtualmachine_creation'])) {
             foreach ($a_computerinventory['virtualmachine_creation'] as $a_vm) {
                 // Define location of physical computer (host)
                 $a_vm['locations_id'] = $computer->fields['locations_id'];
                 if (isset($a_vm['uuid']) && $a_vm['uuid'] != '') {
                     $query = "SELECT * FROM `glpi_computers`\n                        WHERE `uuid` " . ComputerVirtualMachine::getUUIDRestrictRequest($a_vm['uuid']) . "\n                        LIMIT 1";
                     // TODO: Add entity search
                     $result = $DB->query($query);
                     $computers_vm_id = 0;
                     while ($data = $DB->fetch_assoc($result)) {
                         $computers_vm_id = $data['id'];
                     }
                     if ($computers_vm_id == 0) {
                         // Add computer
                         $a_vm['entities_id'] = $computer->fields['entities_id'];
                         $computers_vm_id = $computervm->add($a_vm, array(), !$no_history);
                         // Manage networks
                         $this->manageNetworkPort($a_vm['networkport'], $computers_vm_id, FALSE);
                     } else {
                         if ($pfAgent->getAgentWithComputerid($computers_vm_id) === FALSE) {
                             // Update computer
                             $a_vm['id'] = $computers_vm_id;
                             $computervm->update($a_vm, !$no_history);
                             // Manage networks
                             $this->manageNetworkPort($a_vm['networkport'], $computers_vm_id, FALSE);
                         }
                     }
                 }
             }
         }
     }
     // * ComputerDisk
     if ($pfConfig->getValue("import_volume") != 0) {
         $db_computerdisk = array();
         if ($no_history === FALSE) {
             $query = "SELECT `id`, `name`, `device`, `mountpoint`\n                   FROM `glpi_computerdisks`\n                   WHERE `computers_id` = '" . $computers_id . "'\n                     AND `is_dynamic`='1'";
             $result = $DB->query($query);
             while ($data = $DB->fetch_assoc($result)) {
                 $idtmp = $data['id'];
                 unset($data['id']);
                 $data1 = Toolbox::addslashes_deep($data);
                 $data2 = array_map('strtolower', $data1);
                 $db_computerdisk[$idtmp] = $data2;
             }
         }
         $simplecomputerdisk = array();
         foreach ($a_computerinventory['computerdisk'] as $key => $a_computerdisk) {
             $a_field = array('name', 'device', 'mountpoint');
             foreach ($a_field as $field) {
                 if (isset($a_computerdisk[$field])) {
                     $simplecomputerdisk[$key][$field] = $a_computerdisk[$field];
                 }
             }
         }
         foreach ($simplecomputerdisk as $key => $arrays) {
             $arrayslower = array_map('strtolower', $arrays);
             foreach ($db_computerdisk as $keydb => $arraydb) {
                 if ($arrayslower == $arraydb) {
                     $input = array();
                     $input['id'] = $keydb;
                     if (isset($a_computerinventory['computerdisk'][$key]['filesystems_id'])) {
                         $input['filesystems_id'] = $a_computerinventory['computerdisk'][$key]['filesystems_id'];
                     }
                     $input['totalsize'] = $a_computerinventory['computerdisk'][$key]['totalsize'];
                     $input['freesize'] = $a_computerinventory['computerdisk'][$key]['freesize'];
                     $input['_no_history'] = TRUE;
                     $computerDisk->update($input, FALSE);
                     unset($simplecomputerdisk[$key]);
                     unset($a_computerinventory['computerdisk'][$key]);
                     unset($db_computerdisk[$keydb]);
                     break;
                 }
             }
         }
         if (count($a_computerinventory['computerdisk']) == 0 and count($db_computerdisk) == 0) {
             // Nothing to do
         } else {
             if (count($db_computerdisk) != 0) {
                 // Delete computerdisk in DB
                 foreach ($db_computerdisk as $idtmp => $data) {
                     $computerDisk->delete(array('id' => $idtmp), 1);
                 }
             }
             if (count($a_computerinventory['computerdisk']) != 0) {
                 foreach ($a_computerinventory['computerdisk'] as $a_computerdisk) {
                     $a_computerdisk['computers_id'] = $computers_id;
                     $a_computerdisk['is_dynamic'] = 1;
                     $a_computerdisk['_no_history'] = $no_history;
                     $computerDisk->add($a_computerdisk, array(), !$no_history);
                 }
             }
         }
     }
     // * Networkports
     if ($pfConfig->getValue("component_networkcard") != 0) {
         // Get port from unmanaged device if exist
         $this->manageNetworkPort($a_computerinventory['networkport'], $computers_id, $no_history);
     }
     // * Antivirus
     $db_antivirus = array();
     if ($no_history === FALSE) {
         $query = "SELECT `id`, `name`, `version`\n                  FROM `glpi_plugin_fusioninventory_inventorycomputerantiviruses`\n               WHERE `computers_id` = '{$computers_id}'";
         $result = $DB->query($query);
         while ($data = $DB->fetch_assoc($result)) {
             $idtmp = $data['id'];
             unset($data['id']);
             $data1 = Toolbox::addslashes_deep($data);
             $data2 = array_map('strtolower', $data1);
             $db_antivirus[$idtmp] = $data2;
         }
     }
     $simpleantivirus = array();
     foreach ($a_computerinventory['antivirus'] as $key => $a_antivirus) {
         $a_field = array('name', 'version');
         foreach ($a_field as $field) {
             if (isset($a_antivirus[$field])) {
                 $simpleantivirus[$key][$field] = $a_antivirus[$field];
             }
         }
     }
     foreach ($simpleantivirus as $key => $arrays) {
         $arrayslower = array_map('strtolower', $arrays);
         foreach ($db_antivirus as $keydb => $arraydb) {
             if ($arrayslower == $arraydb) {
                 $input = array();
                 $input = $a_computerinventory['antivirus'][$key];
                 $input['id'] = $keydb;
                 $pfInventoryComputerAntivirus->update($input, !$no_history);
                 unset($simpleantivirus[$key]);
                 unset($a_computerinventory['antivirus'][$key]);
                 unset($db_antivirus[$keydb]);
                 break;
             }
         }
     }
     if (count($a_computerinventory['antivirus']) == 0 and count($db_antivirus) == 0) {
         // Nothing to do
     } else {
         if (count($db_antivirus) != 0) {
             foreach ($db_antivirus as $idtmp => $data) {
                 $pfInventoryComputerAntivirus->delete(array('id' => $idtmp), 1);
             }
         }
         if (count($a_computerinventory['antivirus']) != 0) {
             foreach ($a_computerinventory['antivirus'] as $a_antivirus) {
                 $a_antivirus['computers_id'] = $computers_id;
                 $pfInventoryComputerAntivirus->add($a_antivirus, array(), !$no_history);
             }
         }
     }
     // * Licenseinfo
     $db_licenseinfo = array();
     if ($no_history === FALSE) {
         $query = "SELECT `id`, `name`, `fullname`, `serial`\n                  FROM `glpi_plugin_fusioninventory_computerlicenseinfos`\n               WHERE `computers_id` = '{$computers_id}'";
         $result = $DB->query($query);
         while ($data = $DB->fetch_assoc($result)) {
             $idtmp = $data['id'];
             unset($data['id']);
             $data1 = Toolbox::addslashes_deep($data);
             $data2 = array_map('strtolower', $data1);
             $db_licenseinfo[$idtmp] = $data2;
         }
     }
     foreach ($a_computerinventory['licenseinfo'] as $key => $arrays) {
         $arrayslower = array_map('strtolower', $arrays);
         foreach ($db_licenseinfo as $keydb => $arraydb) {
             if ($arrayslower == $arraydb) {
                 unset($a_computerinventory['licenseinfo'][$key]);
                 unset($db_licenseinfo[$keydb]);
                 break;
             }
         }
     }
     if (count($a_computerinventory['licenseinfo']) == 0 and count($db_licenseinfo) == 0) {
         // Nothing to do
     } else {
         if (count($db_licenseinfo) != 0) {
             foreach ($db_licenseinfo as $idtmp => $data) {
                 $pfComputerLicenseInfo->delete(array('id' => $idtmp), 1);
             }
         }
         if (count($a_computerinventory['licenseinfo']) != 0) {
             foreach ($a_computerinventory['licenseinfo'] as $a_licenseinfo) {
                 $a_licenseinfo['computers_id'] = $computers_id;
                 $pfComputerLicenseInfo->add($a_licenseinfo, array(), !$no_history);
             }
         }
     }
     // * Batteries
     /* Standby, see ticket http://forge.fusioninventory.org/issues/1907
              $db_batteries = array();
              if ($no_history === FALSE) {
                 $query = "SELECT `id`, `name`, `serial`
                       FROM `glpi_plugin_fusioninventory_inventorycomputerbatteries`
                    WHERE `computers_id` = '$computers_id'";
                 $result = $DB->query($query);
                 while ($data = $DB->fetch_assoc($result)) {
                    $idtmp = $data['id'];
                    unset($data['id']);
                    $data = Toolbox::addslashes_deep($data);
                    $data = array_map('strtolower', $data);
                    $db_batteries[$idtmp] = $data;
                 }
              }
              $simplebatteries = array();
              foreach ($a_computerinventory['batteries'] as $key=>$a_batteries) {
                 $a_field = array('name', 'serial');
                 foreach ($a_field as $field) {
                    if (isset($a_batteries[$field])) {
                       $simplebatteries[$key][$field] = $a_batteries[$field];
                    }
                 }
              }
              foreach ($simplebatteries as $key => $arrays) {
                 $arrayslower = array_map('strtolower', $arrays);
                 foreach ($db_batteries as $keydb => $arraydb) {
                    if ($arrayslower == $arraydb) {
                       $input = array();
                       $input = $a_computerinventory['batteries'][$key];
                       $input['id'] = $keydb;
                       $pfInventoryComputerBatteries->update($input);
                       unset($simplebatteries[$key]);
                       unset($a_computerinventory['batteries'][$key]);
                       unset($db_batteries[$keydb]);
                       break;
                    }
                 }
              }
              if (count($a_computerinventory['batteries']) == 0
                 AND count($db_batteries) == 0) {
                 // Nothing to do
              } else {
                 if (count($db_batteries) != 0) {
                    foreach ($db_batteries as $idtmp => $data) {
                       $pfInventoryComputerBatteries->delete(array('id'=>$idtmp), 1);
                    }
                 }
                 if (count($a_computerinventory['batteries']) != 0) {
                    foreach($a_computerinventory['batteries'] as $a_batteries) {
                       $a_batteries['computers_id'] = $computers_id;
                       $pfInventoryComputerBatteries->add($a_batteries, array(), FALSE);
                    }
                 }
              }
     */
     $entities_id = $_SESSION["plugin_fusioninventory_entity"];
     // * Monitors
     $rule = new PluginFusioninventoryInventoryRuleImportCollection();
     $a_monitors = array();
     foreach ($a_computerinventory['monitor'] as $key => $arrays) {
         $input = array();
         $input['itemtype'] = "Monitor";
         $input['name'] = $arrays['name'];
         $input['serial'] = $arrays['serial'];
         $data = $rule->processAllRules($input, array(), array('class' => $this, 'return' => TRUE));
         if (isset($data['found_equipment'])) {
             if ($data['found_equipment'][0] == 0) {
                 // add monitor
                 $arrays['entities_id'] = $entities_id;
                 $a_monitors[] = $monitor->add($arrays);
             } else {
                 $a_monitors[] = $data['found_equipment'][0];
             }
         }
     }
     $db_monitors = array();
     $query = "SELECT `glpi_monitors`.`id`,\n                       `glpi_computers_items`.`id` as link_id\n            FROM `glpi_computers_items`\n         LEFT JOIN `glpi_monitors` ON `items_id`=`glpi_monitors`.`id`\n         WHERE `itemtype`='Monitor'\n            AND `computers_id`='" . $computers_id . "'\n            AND `entities_id`='" . $entities_id . "'\n            AND `glpi_computers_items`.`is_dynamic`='1'\n            AND `glpi_monitors`.`is_global`='0'";
     $result = $DB->query($query);
     while ($data = $DB->fetch_assoc($result)) {
         $idtmp = $data['link_id'];
         unset($data['link_id']);
         $db_monitors[$idtmp] = $data['id'];
     }
     if (count($db_monitors) == 0) {
         foreach ($a_monitors as $monitors_id) {
             $input = array();
             $input['computers_id'] = $computers_id;
             $input['itemtype'] = 'Monitor';
             $input['items_id'] = $monitors_id;
             $input['is_dynamic'] = 1;
             $input['_no_history'] = $no_history;
             $computer_Item->add($input, array(), !$no_history);
         }
     } else {
         // Check all fields from source:
         foreach ($a_monitors as $key => $monitors_id) {
             foreach ($db_monitors as $keydb => $monits_id) {
                 if ($monitors_id == $monits_id) {
                     unset($a_monitors[$key]);
                     unset($db_monitors[$keydb]);
                     break;
                 }
             }
         }
         if (count($a_monitors) == 0 and count($db_monitors) == 0) {
             // Nothing to do
         } else {
             if (count($db_monitors) != 0) {
                 // Delete monitors links in DB
                 foreach ($db_monitors as $idtmp => $monits_id) {
                     $computer_Item->delete(array('id' => $idtmp), 1);
                 }
             }
             if (count($a_monitors) != 0) {
                 foreach ($a_monitors as $key => $monitors_id) {
                     $input = array();
                     $input['computers_id'] = $computers_id;
                     $input['itemtype'] = 'Monitor';
                     $input['items_id'] = $monitors_id;
                     $input['is_dynamic'] = 1;
                     $input['_no_history'] = $no_history;
                     $computer_Item->add($input, array(), !$no_history);
                 }
             }
         }
     }
     // * Printers
     $rule = new PluginFusioninventoryInventoryRuleImportCollection();
     $a_printers = array();
     foreach ($a_computerinventory['printer'] as $key => $arrays) {
         $input = array();
         $input['itemtype'] = "Printer";
         $input['name'] = $arrays['name'];
         $input['serial'] = $arrays['serial'];
         $data = $rule->processAllRules($input, array(), array('class' => $this, 'return' => TRUE));
         if (isset($data['found_equipment'])) {
             if ($data['found_equipment'][0] == 0) {
                 // add printer
                 $arrays['entities_id'] = $entities_id;
                 $a_printers[] = $printer->add($arrays);
             } else {
                 $a_printers[] = $data['found_equipment'][0];
             }
         }
     }
     $db_printers = array();
     $query = "SELECT `glpi_printers`.`id`, `glpi_computers_items`.`id` as link_id\n            FROM `glpi_computers_items`\n         LEFT JOIN `glpi_printers` ON `items_id`=`glpi_printers`.`id`\n         WHERE `itemtype`='Printer'\n            AND `computers_id`='" . $computers_id . "'\n            AND `entities_id`='" . $entities_id . "'\n            AND `glpi_computers_items`.`is_dynamic`='1'\n            AND `glpi_printers`.`is_global`='0'";
     $result = $DB->query($query);
     while ($data = $DB->fetch_assoc($result)) {
         $idtmp = $data['link_id'];
         unset($data['link_id']);
         $db_printers[$idtmp] = $data['id'];
     }
     if (count($db_printers) == 0) {
         foreach ($a_printers as $printers_id) {
             $input['entities_id'] = $entities_id;
             $input['computers_id'] = $computers_id;
             $input['itemtype'] = 'Printer';
             $input['items_id'] = $printers_id;
             $input['is_dynamic'] = 1;
             $input['_no_history'] = $no_history;
             $computer_Item->add($input, array(), !$no_history);
         }
     } else {
         // Check all fields from source:
         foreach ($a_printers as $key => $printers_id) {
             foreach ($db_printers as $keydb => $prints_id) {
                 if ($printers_id == $prints_id) {
                     unset($a_printers[$key]);
                     unset($db_printers[$keydb]);
                     break;
                 }
             }
         }
         if (count($a_printers) == 0 and count($db_printers) == 0) {
             // Nothing to do
         } else {
             if (count($db_printers) != 0) {
                 // Delete printers links in DB
                 foreach ($db_printers as $idtmp => $data) {
                     $computer_Item->delete(array('id' => $idtmp), 1);
                 }
             }
             if (count($a_printers) != 0) {
                 foreach ($a_printers as $printers_id) {
                     $input['entities_id'] = $entities_id;
                     $input['computers_id'] = $computers_id;
                     $input['itemtype'] = 'Printer';
                     $input['items_id'] = $printers_id;
                     $input['is_dynamic'] = 1;
                     $input['_no_history'] = $no_history;
                     $computer_Item->add($input, array(), !$no_history);
                 }
             }
         }
     }
     // * Peripheral
     $rule = new PluginFusioninventoryInventoryRuleImportCollection();
     $a_peripherals = array();
     foreach ($a_computerinventory['peripheral'] as $key => $arrays) {
         $input = array();
         $input['itemtype'] = "Peripheral";
         $input['name'] = $arrays['name'];
         $input['serial'] = $arrays['serial'];
         $data = $rule->processAllRules($input, array(), array('class' => $this, 'return' => TRUE));
         if (isset($data['found_equipment'])) {
             if ($data['found_equipment'][0] == 0) {
                 // add peripheral
                 $arrays['entities_id'] = $entities_id;
                 $a_peripherals[] = $peripheral->add($arrays);
             } else {
                 $a_peripherals[] = $data['found_equipment'][0];
             }
         }
     }
     $db_peripherals = array();
     $query = "SELECT `glpi_peripherals`.`id`, `glpi_computers_items`.`id` as link_id\n            FROM `glpi_computers_items`\n         LEFT JOIN `glpi_peripherals` ON `items_id`=`glpi_peripherals`.`id`\n         WHERE `itemtype`='Peripheral'\n            AND `computers_id`='" . $computers_id . "'\n            AND `entities_id`='" . $entities_id . "'\n            AND `glpi_computers_items`.`is_dynamic`='1'\n      AND `glpi_peripherals`.`is_global`='0'";
     $result = $DB->query($query);
     while ($data = $DB->fetch_assoc($result)) {
         $idtmp = $data['link_id'];
         unset($data['link_id']);
         $db_peripherals[$idtmp] = $data['id'];
     }
     if (count($db_peripherals) == 0) {
         foreach ($a_peripherals as $peripherals_id) {
             $input = array();
             $input['computers_id'] = $computers_id;
             $input['itemtype'] = 'Peripharal';
             $input['items_id'] = $peripherals_id;
             $input['is_dynamic'] = 1;
             $input['_no_history'] = $no_history;
             $computer_Item->add($input, array(), !$no_history);
         }
     } else {
         // Check all fields from source:
         foreach ($a_peripherals as $key => $peripherals_id) {
             foreach ($db_peripherals as $keydb => $periphs_id) {
                 if ($peripherals_id == $periphs_id) {
                     unset($a_peripherals[$key]);
                     unset($db_peripherals[$keydb]);
                     break;
                 }
             }
         }
         if (count($a_peripherals) == 0 and count($db_peripherals) == 0) {
             // Nothing to do
         } else {
             if (count($db_peripherals) != 0) {
                 // Delete peripherals links in DB
                 foreach ($db_peripherals as $idtmp => $data) {
                     $computer_Item->delete(array('id' => $idtmp), 1);
                 }
             }
             if (count($a_peripherals) != 0) {
                 foreach ($a_peripherals as $peripherals_id) {
                     $input = array();
                     $input['computers_id'] = $computers_id;
                     $input['itemtype'] = 'Peripharal';
                     $input['items_id'] = $peripherals_id;
                     $input['is_dynamic'] = 1;
                     $input['_no_history'] = $no_history;
                     $computer_Item->add($input, array(), !$no_history);
                 }
             }
         }
     }
     // * storage
     // Manage by uuid to correspond with GLPI data
     //         $db_storage = array();
     //         if ($no_history === FALSE) {
     //            $query = "SELECT `id`, `uuid` FROM ".
     //                "`glpi_plugin_fusioninventory_inventorycomputerstorages`
     //                WHERE `computers_id` = '$computers_id'";
     //            $result = $DB->query($query);
     //            while ($data = $DB->fetch_assoc($result)) {
     //               $idtmp = $data['id'];
     //               unset($data['id']);
     //               $data = Toolbox::addslashes_deep($data);
     //               $data = array_map('strtolower', $data);
     //               $db_storage[$idtmp] = $data;
     //            }
     //         }
     //         if (count($db_storage) == 0) {
     //            $a_links = array();
     //            $a_uuid  = array();
     //            foreach ($a_computerinventory['storage'] as $a_storage) {
     //               $a_storage['computers_id'] = $computers_id;
     //               $insert_id = $pfInventoryComputerStorage->add($a_storage);
     //               if (isset($a_storage['uuid'])) {
     //                  $a_uuid[$a_storage['uuid']] = $insert_id;
     //                  if (isset($a_storage['uuid_link'])) {
     //                     if (is_array($a_storage['uuid_link'])) {
     //                        $a_links[$insert_id] = $a_storage['uuid_link'];
     //                     } else {
     //                        $a_links[$insert_id][] = $a_storage['uuid_link'];
     //                     }
     //                  }
     //               }
     //            }
     //            foreach ($a_links as $id=>$data) {
     //               foreach ($data as $num=>$uuid) {
     //                  $a_links[$id][$num] = $a_uuid[$uuid];
     //               }
     //            }
     //            foreach ($a_links as $id=>$data) {
     //               foreach ($data as $id2) {
     //                  $input = array();
     //                  $input['plugin_fusioninventory_inventorycomputerstorages_id_1'] = $id;
     //                  $input['plugin_fusioninventory_inventorycomputerstorages_id_2'] = $id2;
     //                  $pfInventoryComputerStorage_Storage->add($input);
     //               }
     //            }
     //         } else {
     //            // Check only field *** from source:
     //
     //         }
     $this->addLog();
 }
 /**
  * @test
  */
 public function getCollectURLRootEntity()
 {
     global $DB;
     $DB->connect();
     $_SESSION['glpiactive_entity'] = 0;
     $_SESSION["plugin_fusioninventory_entity"] = 0;
     $_SESSION["glpiname"] = 'Plugin_FusionInventory';
     $entities_id = 1;
     $agents_id = 1;
     $config = new PluginFusioninventoryConfig();
     $config->loadCache();
     $pfEntity = new PluginFusioninventoryEntity();
     $pfEntity->delete(array('id' => 2));
     // Get answer
     $input = array('action' => 'getConfig', 'task' => array('COLLECT' => '1.0.0'), 'machineid' => 'toto-device');
     $response = PluginFusioninventoryCommunicationRest::communicate($input);
     $this->assertEquals('http://127.0.0.1/glpi085/plugins/fusioninventory/b/collect/', $response['schedule'][0]['remote'], 'Wrong URL');
 }
  You should have received a copy of the GNU General Public License
  along with GLPI; if not, write to the Free Software
  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
  ------------------------------------------------------------------------
*/
// Original Author of file: David DURIEUX
// Purpose of file:
// ----------------------------------------------------------------------
if (!defined('GLPI_ROOT')) {
    define('GLPI_ROOT', '../../..');
}
$NEEDED_ITEMS = array("fusioninventory", "search", "setup", "rulesengine");
include GLPI_ROOT . "/inc/includes.php";
commonHeader($LANG['plugin_fusioninventory']["title"][0], $_SERVER["PHP_SELF"], "plugins", "fusioninventory", "snmp_auth");
PluginFusioninventoryAuth::checkRight("snmp_authentification", "r");
$config = new PluginFusioninventoryConfig();
PluginFusioninventoryDisplay::mini_menu();
// Forms for FILE
if ($config->getValue("authsnmp") == "file") {
    $plugin_fusioninventory_snmp_auth = new PluginFusioninventorySnmpauth();
    if (!isset($_GET["ID"])) {
        echo $plugin_fusioninventory_snmp_auth->plugin_fusioninventory_snmp_connections();
    }
} else {
    if ($config->getValue("authsnmp") == "DB") {
        // Forms for DB
        $_GET['target'] = "snmp_auth.php";
        manageGetValuesInSearch(PLUGIN_FUSIONINVENTORY_SNMP_AUTH);
        searchForm(PLUGIN_FUSIONINVENTORY_SNMP_AUTH, $_GET);
        showList(PLUGIN_FUSIONINVENTORY_SNMP_AUTH, $_GET);
    } else {
function pluginFusioninventoryInstall($version, $migrationname = 'Migration')
{
    global $DB;
    ini_set("memory_limit", "-1");
    ini_set("max_execution_time", "0");
    $migration = new $migrationname($version);
    /*
     * Load classes
     */
    foreach (glob(GLPI_ROOT . '/plugins/fusioninventory/inc/*.php') as $file) {
        require_once $file;
    }
    $migration->displayMessage("Installation of plugin FusionInventory");
    // Get informations of plugin
    /*
     * Clean if Fusion / Tracker has been installed and uninstalled (not clean correctly)
     */
    $migration->displayMessage("Clean data from old installation of the plugin");
    $sql = "DELETE FROM `glpi_displaypreferences`\n         WHERE `itemtype`='5150'";
    $DB->query($sql);
    $sql = "DELETE FROM `glpi_displaypreferences`\n         WHERE `itemtype`='5151'";
    $DB->query($sql);
    $sql = "DELETE FROM `glpi_displaypreferences`\n         WHERE `itemtype`='5152'";
    $DB->query($sql);
    $sql = "DELETE FROM `glpi_displaypreferences`\n         WHERE `itemtype`='5153'";
    $DB->query($sql);
    $sql = "DELETE FROM `glpi_displaypreferences`\n         WHERE `itemtype`='5156'";
    $DB->query($sql);
    $sql = "DELETE FROM `glpi_displaypreferences`\n         WHERE `itemtype`='5157'";
    $DB->query($sql);
    $sql = "DELETE FROM `glpi_displaypreferences`\n         WHERE `itemtype`='5158'";
    $DB->query($sql);
    $sql = "DELETE FROM `glpi_displaypreferences`\n         WHERE `itemtype`='5159'";
    $DB->query($sql);
    $sql = "DELETE FROM `glpi_displaypreferences`\n         WHERE `itemtype`='5161'";
    $DB->query($sql);
    $sql = "DELETE FROM `glpi_displaypreferences`\n         WHERE `itemtype`='5165'";
    $DB->query($sql);
    $sql = "DELETE FROM `glpi_displaypreferences`\n         WHERE `itemtype`='5166'";
    $DB->query($sql);
    $sql = "DELETE FROM `glpi_displaypreferences`\n         WHERE `itemtype`='5167'";
    $DB->query($sql);
    $sql = "DELETE FROM `glpi_displaypreferences`\n         WHERE `itemtype`='5168'";
    $DB->query($sql);
    $sql = "DELETE FROM `glpi_displaypreferences`\n         WHERE `itemtype` LIKE 'PluginFusioninventory%'";
    $DB->query($sql);
    $sql = "DELETE FROM `glpi_displaypreferences`\n         WHERE `itemtype` LIKE 'PluginFusinvinventory%'";
    $DB->query($sql);
    $sql = "DELETE FROM `glpi_displaypreferences`\n         WHERE `itemtype` LIKE 'PluginFusinvsnmp%'";
    $DB->query($sql);
    // Purge network ports have itemtype tp 5153
    $networkPort = new NetworkPort();
    $sql = "SELECT * FROM `glpi_networkports`\n            WHERE `itemtype`='5153'";
    $result = $DB->query($sql);
    while ($data = $DB->fetch_array($result)) {
        $networkPort->delete(array('id' => $data['id']), 1);
    }
    /*
     * Remove old rules
     */
    $migration->displayMessage("Clean rules from old installation of the plugin");
    $Rule = new Rule();
    $a_rules = $Rule->find("`sub_type`='PluginFusioninventoryInventoryRuleImport'");
    foreach ($a_rules as $data) {
        $Rule->delete($data);
    }
    $a_rules = $Rule->find("`sub_type`='PluginFusinvinventoryRuleEntity'");
    foreach ($a_rules as $data) {
        $Rule->delete($data);
    }
    $a_rules = $Rule->find("`sub_type`='PluginFusinvinventoryRuleLocation'");
    foreach ($a_rules as $data) {
        $Rule->delete($data);
    }
    /*
     * Create DB structure
     */
    $migration->displayMessage("Creation tables in database");
    $DB_file = GLPI_ROOT . "/plugins/fusioninventory/install/mysql/plugin_fusioninventory-empty.sql";
    if (!$DB->runFile($DB_file)) {
        $migration->displayMessage("Error on creation tables in database");
    }
    if (!$DB->runFile(GLPI_ROOT . "/plugins/fusioninventory/install/mysql/usbid.sql")) {
        $migration->displayMessage("Error on creation table usbid in database");
    }
    if (!$DB->runFile(GLPI_ROOT . "/plugins/fusioninventory/install/mysql/pciid.sql")) {
        $migration->displayMessage("Error on creation table pciid in database");
    }
    if (!$DB->runFile(GLPI_ROOT . "/plugins/fusioninventory/install/mysql/oui.sql")) {
        $migration->displayMessage("Error on creation table oui in database");
    }
    /*
     * Creation of folders
     */
    $migration->displayMessage("Creation of folders");
    if (!is_dir(GLPI_PLUGIN_DOC_DIR . '/fusioninventory')) {
        mkdir(GLPI_PLUGIN_DOC_DIR . '/fusioninventory');
    }
    if (!is_dir(GLPI_PLUGIN_DOC_DIR . '/fusioninventory/tmp')) {
        mkdir(GLPI_PLUGIN_DOC_DIR . '/fusioninventory/tmp');
    }
    if (!is_dir(GLPI_PLUGIN_DOC_DIR . '/fusioninventory/xml')) {
        mkdir(GLPI_PLUGIN_DOC_DIR . '/fusioninventory/xml');
    }
    if (!is_dir(GLPI_PLUGIN_DOC_DIR . '/fusioninventory/xml/computer')) {
        mkdir(GLPI_PLUGIN_DOC_DIR . '/fusioninventory/xml/computer');
    }
    if (!is_dir(GLPI_PLUGIN_DOC_DIR . '/fusioninventory/xml/printer')) {
        mkdir(GLPI_PLUGIN_DOC_DIR . '/fusioninventory/xml/printer');
    }
    if (!is_dir(GLPI_PLUGIN_DOC_DIR . '/fusioninventory/xml/networkequipment')) {
        mkdir(GLPI_PLUGIN_DOC_DIR . '/fusioninventory/xml/networkequipment');
    }
    if (!is_dir(GLPI_PLUGIN_DOC_DIR . '/fusioninventory/upload')) {
        mkdir(GLPI_PLUGIN_DOC_DIR . '/fusioninventory/upload');
    }
    if (!is_dir(GLPI_PLUGIN_DOC_DIR . '/fusioninventory/walks')) {
        mkdir(GLPI_PLUGIN_DOC_DIR . '/fusioninventory/walks');
    }
    if (!is_dir(GLPI_PLUGIN_DOC_DIR . '/fusioninventory/tmpmodels')) {
        mkdir(GLPI_PLUGIN_DOC_DIR . '/fusioninventory/tmpmodels');
    }
    /*
     * Deploy folders
     */
    if (!is_dir(GLPI_PLUGIN_DOC_DIR . '/fusioninventory/files')) {
        mkdir(GLPI_PLUGIN_DOC_DIR . '/fusioninventory/files');
    }
    if (!is_dir(GLPI_PLUGIN_DOC_DIR . '/fusioninventory/files/repository')) {
        mkdir(GLPI_PLUGIN_DOC_DIR . '/fusioninventory/files/repository');
    }
    if (!is_dir(GLPI_PLUGIN_DOC_DIR . '/fusioninventory/files/manifests')) {
        mkdir(GLPI_PLUGIN_DOC_DIR . '/fusioninventory/files/manifests');
    }
    if (!is_dir(GLPI_PLUGIN_DOC_DIR . '/fusioninventory/files/import')) {
        mkdir(GLPI_PLUGIN_DOC_DIR . '/fusioninventory/files/import');
    }
    if (!is_dir(GLPI_PLUGIN_DOC_DIR . '/fusioninventory/files/export')) {
        mkdir(GLPI_PLUGIN_DOC_DIR . '/fusioninventory/files/export');
    }
    /*
     * Manage profiles
     */
    $migration->displayMessage("Initialize profiles");
    PluginFusioninventoryProfile::initProfile();
    /*
     * bug of purge network port when purge unmanaged devices, so we clean
     */
    $sql = "SELECT `glpi_networkports`.`id` as nid FROM `glpi_networkports`\n         LEFT JOIN `glpi_plugin_fusioninventory_unmanageds`\n            ON `glpi_plugin_fusioninventory_unmanageds`.`id` = `glpi_networkports`.`items_id`\n         WHERE `itemtype`='PluginFusioninventoryUnmanaged'\n            AND `glpi_plugin_fusioninventory_unmanageds`.`id` IS NULL ";
    $result = $DB->query($sql);
    while ($data = $DB->fetch_array($result)) {
        $networkPort->delete(array('id' => $data['nid']), 1);
    }
    /*
     * Add config
     */
    $migration->displayMessage("Initialize configuration");
    $pfConfig = new PluginFusioninventoryConfig();
    $pfConfig->initConfigModule();
    $configLogField = new PluginFusioninventoryConfigLogField();
    $configLogField->initConfig();
    /*
     * Register Agent TASKS
     */
    $migration->displayMessage("Initialize agent TASKS");
    $pfAgentmodule = new PluginFusioninventoryAgentmodule();
    $input = array();
    $input['modulename'] = "WAKEONLAN";
    $input['is_active'] = 0;
    $input['exceptions'] = exportArrayToDB(array());
    $pfAgentmodule->add($input);
    $input = array();
    $input['modulename'] = "INVENTORY";
    $input['is_active'] = 1;
    $input['exceptions'] = exportArrayToDB(array());
    $pfAgentmodule->add($input);
    $input = array();
    $input['modulename'] = "InventoryComputerESX";
    $input['is_active'] = 0;
    $input['exceptions'] = exportArrayToDB(array());
    $pfAgentmodule->add($input);
    $input = array();
    $input['modulename'] = "NETWORKINVENTORY";
    $input['is_active'] = 0;
    $input['exceptions'] = exportArrayToDB(array());
    $pfAgentmodule->add($input);
    $input = array();
    $input['modulename'] = "NETWORKDISCOVERY";
    $input['is_active'] = 0;
    $input['exceptions'] = exportArrayToDB(array());
    $pfAgentmodule->add($input);
    $input = array();
    $input['modulename'] = "DEPLOY";
    $input['is_active'] = 0;
    $input['exceptions'] = exportArrayToDB(array());
    $pfAgentmodule->add($input);
    $input = array();
    $input['modulename'] = "Collect";
    $input['is_active'] = 1;
    $input['exceptions'] = exportArrayToDB(array());
    $pfAgentmodule->add($input);
    /*
     * Add cron task
     */
    $migration->displayMessage("Initialize cron task");
    CronTask::Register('PluginFusioninventoryTask', 'taskscheduler', '60', array('mode' => 2, 'allowmode' => 3, 'logs_lifetime' => 30));
    Crontask::Register('PluginFusioninventoryTaskjobstate', 'cleantaskjob', 3600 * 24, array('mode' => 2, 'allowmode' => 3, 'logs_lifetime' => 30));
    Crontask::Register('PluginFusioninventoryNetworkPortLog', 'cleannetworkportlogs', 3600 * 24, array('mode' => 2, 'allowmode' => 3, 'logs_lifetime' => 30));
    CronTask::Register('PluginFusioninventoryTaskjob', 'updatedynamictasks', '60', array('mode' => 2, 'allowmode' => 3, 'logs_lifetime' => 30, 'state' => 0));
    Crontask::Register('PluginFusioninventoryAgent', 'cleanoldagents', 3600 * 24, array('mode' => 2, 'allowmode' => 3, 'logs_lifetime' => 30, 'comment' => 'Clean agents not contacted since xxx days'));
    Crontask::Register('PluginFusioninventoryAgentWakeup', 'wakeupAgents', 120, array('mode' => 2, 'allowmode' => 3, 'logs_lifetime' => 30, 'comment' => 'Wake agents ups'));
    /*
     * Create rules
     */
    $migration->displayMessage("Create rules");
    $pfSetup = new PluginFusioninventorySetup();
    $pfSetup->initRules();
    /*
     * Add notification for configuration management
     */
    /*
     *  Import OCS locks
     */
    $migration->displayMessage("Import OCS locks if exists");
    $pfLock = new PluginFusioninventoryLock();
    $pfLock->importFromOcs();
    Crontask::Register('PluginFusioninventoryTaskjobstate', 'cleantaskjob', 3600 * 24, array('mode' => 2, 'allowmode' => 3, 'logs_lifetime' => 30));
    $pfNetworkporttype = new PluginFusioninventoryNetworkporttype();
    $pfNetworkporttype->init();
    require_once GLPI_ROOT . "/plugins/fusioninventory/inc/inventorycomputerstat.class.php";
    PluginFusioninventoryInventoryComputerStat::init();
    $mode_cli = basename($_SERVER['SCRIPT_NAME']) == "cli_install.php";
}
  @since     2010

  ------------------------------------------------------------------------
*/
include "../../../inc/includes.php";
/**
 *  List of all FusionInventorys versions :
 *    1.0.0
 *    1.1.0 non exists glpi_plugin_fusioninventory_agents (MySQL)
 *    2.0.0 non exists glpi_plugin_fusioninventory_config_discovery (MySQL)
 *    2.0.1 Nothing
 *    2.0.2 config version field 2.0.2
 *    2.1.0 config version field 2.1.0
 **/
if (Session::haveRight('config', UPDATE) && Session::haveRight('profile', UPDATE)) {
    $config = new PluginFusioninventoryConfig();
    if (!TableExists("glpi_plugin_fusioninventory_agents")) {
        PluginFusioninventorySetup::update("1.1.0");
    }
    if (!TableExists("glpi_plugin_fusioninventory_config_discovery")) {
        PluginFusioninventorySetup::update("2.0.0");
    }
    if (!FieldExists("glpi_plugin_fusioninventory_configs", "version")) {
        PluginFusioninventorySetup::update("2.0.2");
    }
    if (FieldExists("glpi_plugin_fusioninventory_configs", "version")) {
        if ($config->getValue('version') == "2.0.2" || $config->getValue('version') == "2.1.0") {
            $DB->query("UPDATE `glpi_plugin_fusioninventory_configs`\n                     SET `version` = '2.1.1'\n                     WHERE `id`=1");
        }
        PluginFusioninventorySetup::update("2.0.2");
        if ($config->getValue('version') == "0") {
 /**
  *  Execute a function as Fusioninventory user
  *  @param $function callable
  *  @param $args array
  *
  *  @return the normally returned value from executed callable
  */
 function executeAsFusioninventoryUser($function, array $args = array())
 {
     $config = new PluginFusioninventoryConfig();
     $user = new User();
     // Backup _SESSION environment
     $OLD_SESSION = array();
     foreach (array('glpiID', 'glpiname', 'glpiactiveentities_string', 'glpiactiveentities', 'glpiparententities') as $session_key) {
         if (isset($_SESSION[$session_key])) {
             $OLD_SESSION[$session_key] = $_SESSION[$session_key];
         }
     }
     // Configure impersonation
     $users_id = $config->getValue('users_id');
     $user->getFromDB($users_id);
     $_SESSION['glpiID'] = $users_id;
     $_SESSION['glpiname'] = $user->getField('name');
     $_SESSION['glpiactiveentities'] = getSonsOf('glpi_entities', 0);
     $_SESSION['glpiactiveentities_string'] = "'" . implode("', '", $_SESSION['glpiactiveentities']) . "'";
     $_SESSION['glpiparententities'] = array();
     // Execute function with impersonated SESSION
     $result = call_user_func_array($function, $args);
     // Restore SESSION
     foreach ($OLD_SESSION as $key => $value) {
         $_SESSION[$key] = $value;
     }
     // Return function results
     return $result;
 }
 static function computerInventoryTransformation($array)
 {
     global $DB, $PF_ESXINVENTORY, $CFG_GLPI;
     // Initialize
     $a_inventory = array('Computer' => array(), 'fusioninventorycomputer' => array(), 'processor' => array(), 'memory' => array(), 'harddrive' => array(), 'drive' => array(), 'graphiccard' => array(), 'networkcard' => array(), 'soundcard' => array(), 'controller' => array(), 'SOFTWARES' => array(), 'virtualmachine' => array(), 'computerdisk' => array(), 'networkport' => array(), 'antivirus' => array(), 'licenseinfo' => array(), 'batteries' => array(), 'monitor' => array(), 'printer' => array(), 'peripheral' => array(), 'storage' => array());
     $thisc = new self();
     $pfConfig = new PluginFusioninventoryConfig();
     $ignorecontrollers = array();
     if (isset($array['ACCOUNTINFO'])) {
         $a_inventory['ACCOUNTINFO'] = $array['ACCOUNTINFO'];
     }
     // * HARDWARE
     $array_tmp = $thisc->addValues($array['HARDWARE'], array('NAME' => 'name', 'OSNAME' => 'operatingsystems_id', 'OSVERSION' => 'operatingsystemversions_id', 'WINPRODID' => 'os_licenseid', 'WINPRODKEY' => 'os_license_number', 'WORKGROUP' => 'domains_id', 'UUID' => 'uuid', 'LASTLOGGEDUSER' => 'users_id', 'operatingsystemservicepacks_id' => 'operatingsystemservicepacks_id', 'manufacturers_id' => 'manufacturers_id', 'computermodels_id' => 'computermodels_id', 'serial' => 'serial', 'computertypes_id' => 'computertypes_id'));
     if ($array_tmp['operatingsystemservicepacks_id'] == '' && isset($array['HARDWARE']['OSCOMMENTS']) && $array['HARDWARE']['OSCOMMENTS'] != '') {
         $array_tmp['operatingsystemservicepacks_id'] = $array['HARDWARE']['OSCOMMENTS'];
     }
     if (isset($array_tmp['users_id'])) {
         if ($array_tmp['users_id'] == '') {
             unset($array_tmp['users_id']);
         } else {
             $array_tmp['contact'] = $array_tmp['users_id'];
             $tmp_users_id = $array_tmp['users_id'];
             $split_user = explode("@", $tmp_users_id);
             $query = "SELECT `id`\n                      FROM `glpi_users`\n                      WHERE `name` = '" . $split_user[0] . "'\n                      LIMIT 1";
             $result = $DB->query($query);
             if ($DB->numrows($result) == 1) {
                 $array_tmp['users_id'] = $DB->result($result, 0, 0);
             } else {
                 $array_tmp['users_id'] = 0;
             }
         }
     }
     $array_tmp['is_dynamic'] = 1;
     $a_inventory['Computer'] = $array_tmp;
     $array_tmp = $thisc->addValues($array['HARDWARE'], array('OSINSTALLDATE' => 'operatingsystem_installationdate', 'WINOWNER' => 'winowner', 'WINCOMPANY' => 'wincompany'));
     $array_tmp['last_fusioninventory_update'] = date('Y-m-d H:i:s');
     // * Determine "Public contact address"
     if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
         // Try "X-Forwarded-For" HTTP header
         // Parse "X-Forwarded-For" header (can contain multiple IP addresses, client should be first)
         $forwarded_for_ip_tmp = explode(', ', $_SERVER['HTTP_X_FORWARDED_FOR']);
         $forwarded_for_ip_tmp = new IPAddress($forwarded_for_ip_tmp[0]);
         if ($forwarded_for_ip_tmp->is_valid()) {
             $array_tmp['remote_addr'] = $forwarded_for_ip_tmp->getTextual();
         }
     } elseif (isset($_SERVER['HTTP_X_REAL_IP'])) {
         // Then try "X-Real-IP" HTTP header
         $real_ip_tmp = new IPAddress($_SERVER['HTTP_X_REAL_IP']);
         if ($real_ip_tmp->is_valid()) {
             $array_tmp['remote_addr'] = $real_ip_tmp->getTextual();
         }
     } elseif (isset($_SERVER['REMOTE_ADDR'])) {
         // Fall back on the currently connected IP
         $array_tmp['remote_addr'] = $_SERVER['REMOTE_ADDR'];
     }
     $a_inventory['fusioninventorycomputer'] = $array_tmp;
     if (isset($array['OPERATINGSYSTEM']['INSTALL_DATE']) && !empty($array['OPERATINGSYSTEM']['INSTALL_DATE'])) {
         $a_inventory['fusioninventorycomputer']['operatingsystem_installationdate'] = $array['OPERATINGSYSTEM']['INSTALL_DATE'];
     }
     if (isset($array['HARDWARE']['DESCRIPTION'])) {
         $a_inventory['fusioninventorycomputer']['oscomment'] = $array['HARDWARE']['DESCRIPTION'];
     }
     if (empty($a_inventory['fusioninventorycomputer']['operatingsystem_installationdate'])) {
         $a_inventory['fusioninventorycomputer']['operatingsystem_installationdate'] = "NULL";
     }
     // * BIOS
     if (isset($array['BIOS'])) {
         if (isset($array['BIOS']['ASSETTAG'])) {
             $a_inventory['fusioninventorycomputer']['bios_assettag'] = $array['BIOS']['ASSETTAG'];
         }
         if (isset($array['BIOS']['SMANUFACTURER']) and !empty($array['BIOS']['SMANUFACTURER'])) {
             $a_inventory['Computer']['manufacturers_id'] = $array['BIOS']['SMANUFACTURER'];
         } else {
             if (isset($array['BIOS']['MMANUFACTURER']) and !empty($array['BIOS']['MMANUFACTURER'])) {
                 $a_inventory['Computer']['manufacturers_id'] = $array['BIOS']['MMANUFACTURER'];
             } else {
                 if (isset($array['BIOS']['BMANUFACTURER']) and !empty($array['BIOS']['BMANUFACTURER'])) {
                     $a_inventory['Computer']['manufacturers_id'] = $array['BIOS']['BMANUFACTURER'];
                 } else {
                     if (isset($array['BIOS']['MMANUFACTURER']) and !empty($array['BIOS']['MMANUFACTURER'])) {
                         $a_inventory['Computer']['manufacturers_id'] = $array['BIOS']['MMANUFACTURER'];
                     } else {
                         if (isset($array['BIOS']['BMANUFACTURER']) and !empty($array['BIOS']['BMANUFACTURER'])) {
                             $a_inventory['Computer']['manufacturers_id'] = $array['BIOS']['BMANUFACTURER'];
                         }
                     }
                 }
             }
         }
         if (isset($array['BIOS']['MMANUFACTURER']) and !empty($array['BIOS']['MMANUFACTURER'])) {
             $a_inventory['Computer']['mmanufacturer'] = $array['BIOS']['MMANUFACTURER'];
         }
         if (isset($array['BIOS']['BMANUFACTURER']) and !empty($array['BIOS']['BMANUFACTURER'])) {
             $a_inventory['Computer']['bmanufacturer'] = $array['BIOS']['BMANUFACTURER'];
         }
         if (isset($array['BIOS']['SMODEL']) and $array['BIOS']['SMODEL'] != '') {
             $a_inventory['Computer']['computermodels_id'] = $array['BIOS']['SMODEL'];
         } else {
             if (isset($array['BIOS']['MMODEL']) and $array['BIOS']['MMODEL'] != '') {
                 $a_inventory['Computer']['computermodels_id'] = $array['BIOS']['MMODEL'];
             }
         }
         if (isset($array['BIOS']['MMODEL']) and $array['BIOS']['MMODEL'] != '') {
             $a_inventory['Computer']['mmodel'] = $array['BIOS']['MMODEL'];
         }
         if (isset($array['BIOS']['SSN'])) {
             $a_inventory['Computer']['serial'] = trim($array['BIOS']['SSN']);
             // HP patch for serial begin with 'S'
             if (isset($a_inventory['Computer']['manufacturers_id']) and strstr($a_inventory['Computer']['manufacturers_id'], "ewlett") && preg_match("/^[sS]/", $a_inventory['Computer']['serial'])) {
                 $a_inventory['Computer']['serial'] = trim(preg_replace("/^[sS]/", "", $a_inventory['Computer']['serial']));
             }
         }
         if (isset($array['BIOS']['MSN'])) {
             $a_inventory['Computer']['mserial'] = trim($array['BIOS']['MSN']);
         }
     }
     // * Type of computer
     //First the HARDWARE/VMSYSTEM is not Physical : then it's a virtual machine
     if (isset($array['HARDWARE']['VMSYSTEM']) && $array['HARDWARE']['VMSYSTEM'] != '' && $array['HARDWARE']['VMSYSTEM'] != 'Physical') {
         $a_inventory['Computer']['computertypes_id'] = $array['HARDWARE']['VMSYSTEM'];
         // HACK FOR BSDJail, remove serial and UUID (because it's of host, not contener)
         if ($array['HARDWARE']['VMSYSTEM'] == 'BSDJail') {
             if (isset($a_inventory['Computer']['serial'])) {
                 $a_inventory['Computer']['serial'] = '';
             }
             $a_inventory['Computer']['uuid'] .= "-" . $a_inventory['Computer']['name'];
         }
     } else {
         //It's not a virtual machine, then check :
         //1 - HARDWARE/CHASSIS_TYPE
         //2 - BIOS/TYPE
         //3 - BIOS/MMODEL
         //4 - HARDWARE/VMSYSTEM (should not go there)
         if (isset($array['HARDWARE']['CHASSIS_TYPE']) && !empty($array['HARDWARE']['CHASSIS_TYPE'])) {
             $a_inventory['Computer']['computertypes_id'] = $array['HARDWARE']['CHASSIS_TYPE'];
         } else {
             if (isset($array['BIOS']['TYPE']) && !empty($array['BIOS']['TYPE'])) {
                 $a_inventory['Computer']['computertypes_id'] = $array['BIOS']['TYPE'];
             } else {
                 if (isset($array['BIOS']['MMODEL']) && !empty($array['BIOS']['MMODEL'])) {
                     $a_inventory['Computer']['computertypes_id'] = $array['BIOS']['MMODEL'];
                 } else {
                     if (isset($array['HARDWARE']['VMSYSTEM']) && !empty($array['HARDWARE']['VMSYSTEM'])) {
                         $a_inventory['Computer']['computertypes_id'] = $array['HARDWARE']['VMSYSTEM'];
                     }
                 }
             }
         }
     }
     //      if (isset($array['BIOS']['SKUNUMBER'])) {
     //         $a_inventory['BIOS']['PARTNUMBER'] = $array['BIOS']['SKUNUMBER'];
     //      }
     if (isset($array['BIOS']['BDATE'])) {
         $a_split = explode("/", $array['BIOS']['BDATE']);
         // 2011-06-29 13:19:48
         if (isset($a_split[0]) and isset($a_split[1]) and isset($a_split[2])) {
             $a_inventory['fusioninventorycomputer']['bios_date'] = $a_split[2] . "-" . $a_split[0] . "-" . $a_split[1];
         }
     }
     if (isset($array['BIOS']['BVERSION'])) {
         $a_inventory['fusioninventorycomputer']['bios_version'] = $array['BIOS']['BVERSION'];
     }
     if (isset($array['BIOS']['BMANUFACTURER'])) {
         $a_inventory['fusioninventorycomputer']['bios_manufacturers_id'] = $array['BIOS']['BMANUFACTURER'];
     }
     $CFG_GLPI['plugin_fusioninventory_computermanufacturer'][$a_inventory['Computer']['manufacturers_id']] = $a_inventory['Computer']['manufacturers_id'];
     // * OPERATINGSYSTEM
     if (isset($array['OPERATINGSYSTEM'])) {
         $array_tmp = $thisc->addValues($array['OPERATINGSYSTEM'], array('FULL_NAME' => 'operatingsystems_id', 'VERSION' => 'operatingsystemversions_id', 'SERVICE_PACK' => 'operatingsystemservicepacks_id', 'ARCH' => 'plugin_fusioninventory_computerarchs_id'));
         if (!isset($array['OPERATINGSYSTEM']['VERSION']) && isset($array['OPERATINGSYSTEM']['KERNEL_VERSION'])) {
             $array_tmp['operatingsystemversions_id'] = $array['OPERATINGSYSTEM']['KERNEL_VERSION'];
         }
         foreach ($array_tmp as $key => $value) {
             if (isset($a_inventory['Computer'][$key]) && $a_inventory['Computer'][$key] != '') {
                 $a_inventory['Computer'][$key] = $value;
             }
         }
         if (isset($array_tmp['plugin_fusioninventory_computerarchs_id']) && $array_tmp['plugin_fusioninventory_computerarchs_id'] != '') {
             $rulecollection = new PluginFusioninventoryRuleDictionnaryComputerArchCollection();
             $res_rule = $rulecollection->processAllRules(array("name" => $array_tmp['plugin_fusioninventory_computerarchs_id']));
             if (isset($res_rule['name'])) {
                 $a_inventory['fusioninventorycomputer']['plugin_fusioninventory_computerarchs_id'] = $res_rule['name'];
             } else {
                 $a_inventory['fusioninventorycomputer']['plugin_fusioninventory_computerarchs_id'] = $array_tmp['plugin_fusioninventory_computerarchs_id'];
             }
         }
     }
     // otherserial (on tag) if defined in config
     if ($pfConfig->getValue('otherserial') == 1) {
         if (isset($array['ACCOUNTINFO'])) {
             //In very rare case, ACCOUNTINFO section is present twice in the XML file...
             if (isset($array['ACCOUNTINFO'][0])) {
                 $tmpacc = $array['ACCOUNTINFO'][0];
                 $array['ACCOUNTINFO'] = $tmpacc;
             }
             if (isset($array['ACCOUNTINFO']['KEYNAME']) && $array['ACCOUNTINFO']['KEYNAME'] == 'TAG') {
                 if (isset($array['ACCOUNTINFO']['KEYVALUE']) && $array['ACCOUNTINFO']['KEYVALUE'] != '') {
                     $a_inventory['Computer']['otherserial'] = $array['ACCOUNTINFO']['KEYVALUE'];
                 }
             }
         }
     }
     // Hack for problems of ESX inventory with same deviceid than real computer inventory
     if (isset($a_inventory['Computer']['operatingsystems_id']) && strstr($a_inventory['Computer']['operatingsystems_id'], 'VMware ESX')) {
         $PF_ESXINVENTORY = TRUE;
     }
     // * BATTERIES
     //      $a_inventory['batteries'] = array();
     //      if (isset($array['BATTERIES'])) {
     //         foreach ($array['BATTERIES'] as $a_batteries) {
     //            $a_inventory['soundcard'][] = $thisc->addValues($a_batteries,
     //               array(
     //                  'NAME'          => 'name',
     //                  'MANUFACTURER'  => 'manufacturers_id',
     //                  'SERIAL'     => 'serial',
     //                  'DATE'       => 'date',
     //                  'CAPACITY'   => 'capacity',
     //                  'CHEMISTRY'  => 'plugin_fusioninventory_inventorycomputerchemistries_id',
     //                  'VOLTAGE'    => 'voltage'));
     //         }
     //      }
     // * SOUNDS
     $a_inventory['soundcard'] = array();
     if ($pfConfig->getValue('component_soundcard') == 1) {
         if (isset($array['SOUNDS'])) {
             foreach ($array['SOUNDS'] as $a_sounds) {
                 $a_inventory['soundcard'][] = $thisc->addValues($a_sounds, array('NAME' => 'designation', 'MANUFACTURER' => 'manufacturers_id', 'DESCRIPTION' => 'comment'));
                 $ignorecontrollers[$a_sounds['NAME']] = 1;
             }
         }
     }
     // * VIDEOS
     $a_inventory['graphiccard'] = array();
     if ($pfConfig->getValue('component_graphiccard') == 1) {
         if (isset($array['VIDEOS'])) {
             foreach ($array['VIDEOS'] as $a_videos) {
                 if (is_array($a_videos) && isset($a_videos['NAME'])) {
                     $array_tmp = $thisc->addValues($a_videos, array('NAME' => 'designation', 'MEMORY' => 'memory'));
                     $array_tmp['designation'] = trim($array_tmp['designation']);
                     $a_inventory['graphiccard'][] = $array_tmp;
                     if (isset($a_videos['NAME'])) {
                         $ignorecontrollers[$a_videos['NAME']] = 1;
                     }
                     if (isset($a_videos['CHIPSET'])) {
                         $ignorecontrollers[$a_videos['CHIPSET']] = 1;
                     }
                 }
             }
         }
     }
     // * NETWORK CARD
     $a_inventory['networkcard'] = array();
     if ($pfConfig->getValue('component_networkcard') == 1) {
         if (isset($array['NETWORKS'])) {
             foreach ($array['NETWORKS'] as $a_netcards) {
                 if (is_array($a_netcards) && isset($a_netcards['DESCRIPTION'])) {
                     // Search in controller if find NAME = CONTROLLER TYPE
                     $a_found = array();
                     if (isset($array['CONTROLLERS'])) {
                         foreach ($array['CONTROLLERS'] as $a_controllers) {
                             if (count($a_found) == 0) {
                                 if (isset($a_controllers['TYPE']) && ($a_netcards['DESCRIPTION'] == $a_controllers['TYPE'] || strtolower($a_netcards['DESCRIPTION'] . " controller") == strtolower($a_controllers['TYPE'])) && !isset($ignorecontrollers[$a_controllers['NAME']])) {
                                     $a_found = $a_controllers;
                                     if (isset($a_netcards['MACADDR'])) {
                                         $a_found['MACADDR'] = $a_netcards['MACADDR'];
                                     }
                                 }
                             }
                         }
                     }
                     if (count($a_found) > 0) {
                         $array_tmp = $thisc->addValues($a_found, array('NAME' => 'designation', 'MANUFACTURER' => 'manufacturers_id', 'MACADDR' => 'mac'));
                         if (isset($a_found['PCIID'])) {
                             $a_PCIData = PluginFusioninventoryInventoryExternalDB::getDataFromPCIID($a_found['PCIID']);
                             if (isset($a_PCIData['manufacturer'])) {
                                 $array_tmp['manufacturers_id'] = $a_PCIData['manufacturer'];
                             }
                             if (isset($a_PCIData['name'])) {
                                 $array_tmp['designation'] = $a_PCIData['name'];
                             }
                             $array_tmp['designation'] = Toolbox::addslashes_deep($array_tmp['designation']);
                         }
                         $array_tmp['mac'] = strtolower($array_tmp['mac']);
                         $a_inventory['networkcard'][] = $array_tmp;
                         if (isset($a_found['NAME'])) {
                             $ignorecontrollers[$a_found['NAME']] = 1;
                         }
                     }
                 }
             }
         }
     }
     // * NETWORKS
     $a_inventory['networkport'] = array();
     if ($pfConfig->getValue('component_networkcard') == 1) {
         if (isset($array['NETWORKS'])) {
             $a_networknames = array();
             foreach ($array['NETWORKS'] as $a_networks) {
                 $virtual_import = 1;
                 if ($pfConfig->getValue("component_networkcardvirtual") == 0) {
                     if (isset($a_networks['VIRTUALDEV']) && $a_networks['VIRTUALDEV'] == 1) {
                         $virtual_import = 0;
                     }
                 }
                 if ($virtual_import == 1) {
                     $array_tmp = $thisc->addValues($a_networks, array('DESCRIPTION' => 'name', 'MACADDR' => 'mac', 'TYPE' => 'instantiation_type', 'IPADDRESS' => 'ip', 'VIRTUALDEV' => 'virtualdev', 'IPSUBNET' => 'subnet', 'SSID' => 'ssid', 'IPGATEWAY' => 'gateway', 'IPMASK' => 'netmask', 'IPDHCP' => 'dhcpserver', 'SPEED' => 'speed'));
                     if (isset($array_tmp['name']) && $array_tmp['name'] != '' || isset($array_tmp['mac']) && $array_tmp['mac'] != '') {
                         if (!isset($array_tmp['virtualdev']) || $array_tmp['virtualdev'] != 1) {
                             $array_tmp['virtualdev'] = 0;
                         }
                         $array_tmp['logical_number'] = 1;
                         if ($array_tmp['virtualdev'] == 1) {
                             $array_tmp['logical_number'] = 0;
                         }
                         $array_tmp['mac'] = strtolower($array_tmp['mac']);
                         if (isset($a_networknames[$array_tmp['name'] . '-' . $array_tmp['mac']])) {
                             if (isset($array_tmp['ip']) && $array_tmp['ip'] != '') {
                                 if (!in_array($array_tmp['ip'], $a_networknames[$array_tmp['name'] . '-' . $array_tmp['mac']]['ipaddress'])) {
                                     $a_networknames[$array_tmp['name'] . '-' . $array_tmp['mac']]['ipaddress'][] = $array_tmp['ip'];
                                 }
                             }
                             if (isset($a_networks['IPADDRESS6']) && $a_networks['IPADDRESS6'] != '') {
                                 if (!in_array($a_networks['IPADDRESS6'], $a_networknames[$array_tmp['name'] . '-' . $array_tmp['mac']]['ipaddress'])) {
                                     $a_networknames[$array_tmp['name'] . '-' . $array_tmp['mac']]['ipaddress'][] = $a_networks['IPADDRESS6'];
                                 }
                             }
                         } else {
                             if (isset($array_tmp['ip']) && $array_tmp['ip'] != '') {
                                 $array_tmp['ipaddress'] = array($array_tmp['ip']);
                                 unset($array_tmp['ip']);
                             } else {
                                 $array_tmp['ipaddress'] = array();
                             }
                             if (isset($a_networks['IPADDRESS6']) && $a_networks['IPADDRESS6'] != '') {
                                 $array_tmp['ipaddress'][] = $a_networks['IPADDRESS6'];
                             }
                             if (isset($array_tmp["instantiation_type"]) and $array_tmp["instantiation_type"] == 'Ethernet') {
                                 $array_tmp["instantiation_type"] = 'NetworkPortEthernet';
                             } else {
                                 if (isset($array_tmp["instantiation_type"]) and ($array_tmp["instantiation_type"] == 'wifi' or $array_tmp["instantiation_type"] == 'IEEE')) {
                                     $array_tmp["instantiation_type"] = 'NetworkPortWifi';
                                 } else {
                                     if ($array_tmp['mac'] != '') {
                                         $array_tmp["instantiation_type"] = 'NetworkPortEthernet';
                                     } else {
                                         $array_tmp["instantiation_type"] = 'NetworkPortLocal';
                                     }
                                 }
                             }
                             if (isset($array_tmp['ip'])) {
                                 unset($array_tmp['ip']);
                             }
                             if (isset($array_tmp['speed']) && is_numeric($array_tmp['speed'])) {
                                 // Old agent version have speed in b/s instead Mb/s
                                 if ($array_tmp['speed'] > 100000) {
                                     $array_tmp['speed'] = $array_tmp['speed'] / 1000000;
                                 }
                             } else {
                                 $array_tmp['speed'] = 0;
                             }
                             $a_networknames[$array_tmp['name'] . '-' . $array_tmp['mac']] = $array_tmp;
                         }
                     }
                 }
             }
             $a_inventory['networkport'] = $a_networknames;
         }
     }
     // * CONTROLLERS
     $a_inventory['controller'] = array();
     if ($pfConfig->getValue('component_control') == 1) {
         if (isset($array['CONTROLLERS'])) {
             foreach ($array['CONTROLLERS'] as $a_controllers) {
                 if (isset($a_controllers["NAME"]) and !isset($ignorecontrollers[$a_controllers["NAME"]])) {
                     $array_tmp = $thisc->addValues($a_controllers, array('NAME' => 'designation', 'MANUFACTURER' => 'manufacturers_id', 'type' => 'interfacetypes_id'));
                     if (isset($a_controllers['PCIID'])) {
                         $a_PCIData = PluginFusioninventoryInventoryExternalDB::getDataFromPCIID($a_controllers['PCIID']);
                         if (isset($a_PCIData['manufacturer'])) {
                             $array_tmp['manufacturers_id'] = $a_PCIData['manufacturer'];
                         }
                         if (isset($a_PCIData['name'])) {
                             $array_tmp['designation'] = $a_PCIData['name'];
                         }
                         $array_tmp['designation'] = Toolbox::addslashes_deep($array_tmp['designation']);
                     }
                     $a_inventory['controller'][] = $array_tmp;
                 }
             }
         }
     }
     // * CPUS
     $a_inventory['processor'] = array();
     if ($pfConfig->getValue('component_processor') == 1) {
         if (isset($array['CPUS'])) {
             foreach ($array['CPUS'] as $a_cpus) {
                 if (is_array($a_cpus) && (isset($a_cpus['NAME']) || isset($a_cpus['TYPE']))) {
                     $array_tmp = $thisc->addValues($a_cpus, array('SPEED' => 'frequency', 'MANUFACTURER' => 'manufacturers_id', 'SERIAL' => 'serial', 'NAME' => 'designation', 'CORE' => 'nbcores', 'THREAD' => 'nbthreads'));
                     if ($array_tmp['designation'] == '' && isset($a_cpus['TYPE'])) {
                         $array_tmp['designation'] = $a_cpus['TYPE'];
                     }
                     $array_tmp['frequence'] = $array_tmp['frequency'];
                     $array_tmp['frequency_default'] = $array_tmp['frequency'];
                     $a_inventory['processor'][] = $array_tmp;
                 }
             }
         }
     }
     // * DRIVES
     $a_inventory['computerdisk'] = array();
     if (isset($array['DRIVES'])) {
         foreach ($array['DRIVES'] as $a_drives) {
             if ($pfConfig->getValue("component_drive") == '0' or $pfConfig->getValue("component_networkdrive") == '0' and (isset($a_drives['TYPE']) and $a_drives['TYPE'] == 'Network Drive' or isset($a_drives['FILESYSTEM']) and $a_drives['FILESYSTEM'] == 'nfs') or isset($a_drives['TYPE']) and ($a_drives['TYPE'] == "Removable Disk" or $a_drives['TYPE'] == "Compact Disc")) {
             } else {
                 if ($pfConfig->getValue('import_volume') == 1) {
                     $array_tmp = $thisc->addValues($a_drives, array('VOLUMN' => 'device', 'FILESYSTEM' => 'filesystems_id', 'TOTAL' => 'totalsize', 'FREE' => 'freesize'));
                     if (isset($a_drives['LABEL']) and !empty($a_drives['LABEL'])) {
                         $array_tmp['name'] = $a_drives['LABEL'];
                     } else {
                         if ((!isset($a_drives['VOLUMN']) or empty($a_drives['VOLUMN'])) and isset($a_drives['LETTER'])) {
                             $array_tmp['name'] = $a_drives['LETTER'];
                         } else {
                             if (isset($a_drives['TYPE'])) {
                                 $array_tmp['name'] = $a_drives['TYPE'];
                             } else {
                                 if (isset($a_drives['VOLUMN'])) {
                                     $array_tmp['name'] = $a_drives['VOLUMN'];
                                 }
                             }
                         }
                     }
                     if (isset($a_drives['MOUNTPOINT'])) {
                         $array_tmp['mountpoint'] = $a_drives['MOUNTPOINT'];
                     } else {
                         if (isset($a_drives['LETTER'])) {
                             $array_tmp['mountpoint'] = $a_drives['LETTER'];
                         } else {
                             if (isset($a_drives['TYPE'])) {
                                 $array_tmp['mountpoint'] = $a_drives['TYPE'];
                             }
                         }
                     }
                     $a_inventory['computerdisk'][] = $array_tmp;
                 }
             }
         }
     }
     // * MEMORIES
     $a_inventory['memory'] = array();
     if ($pfConfig->getValue('component_memory') == 1) {
         if (isset($array['MEMORIES'])) {
             foreach ($array['MEMORIES'] as $a_memories) {
                 if (!isset($a_memories["CAPACITY"]) or isset($a_memories["CAPACITY"]) and !preg_match("/^[0-9]+\$/i", $a_memories["CAPACITY"])) {
                     // Nothing
                 } else {
                     $array_tmp = $thisc->addValues($a_memories, array('CAPACITY' => 'size', 'SPEED' => 'frequence', 'TYPE' => 'devicememorytypes_id', 'SERIALNUMBER' => 'serial', 'NUMSLOTS' => 'busID'));
                     if ($array_tmp['size'] > 0) {
                         $array_tmp['designation'] = "";
                         if (isset($a_memories["TYPE"]) && $a_memories["TYPE"] != "Empty Slot" && $a_memories["TYPE"] != "Unknown") {
                             $array_tmp["designation"] = $a_memories["TYPE"];
                         }
                         if (isset($a_memories["DESCRIPTION"])) {
                             if (!empty($array_tmp["designation"])) {
                                 $array_tmp["designation"] .= " - ";
                             }
                             $array_tmp["designation"] .= $a_memories["DESCRIPTION"];
                         }
                         $a_inventory['memory'][] = $array_tmp;
                     }
                 }
             }
         }
     }
     // * MONITORS
     $a_inventory['monitor'] = array();
     if (isset($array['MONITORS'])) {
         $a_serialMonitor = array();
         foreach ($array['MONITORS'] as $a_monitors) {
             $array_tmp = $thisc->addValues($a_monitors, array('CAPTION' => 'name', 'MANUFACTURER' => 'manufacturers_id', 'SERIAL' => 'serial', 'DESCRIPTION' => 'comment'));
             if (!isset($array_tmp['name'])) {
                 $array_tmp['name'] = '';
             }
             if ($array_tmp['name'] == '' && isset($array_tmp['comment'])) {
                 $array_tmp['name'] = $array_tmp['comment'];
             }
             if (isset($array_tmp['comment'])) {
                 unset($array_tmp['comment']);
             }
             if (!isset($array_tmp['serial'])) {
                 $array_tmp['serial'] = '';
             }
             if (!isset($array_tmp['manufacturers_id'])) {
                 $array_tmp['manufacturers_id'] = '';
             }
             if (!isset($a_serialMonitor[$array_tmp['serial']])) {
                 $a_inventory['monitor'][] = $array_tmp;
                 $a_serialMonitor[$array_tmp['serial']] = 1;
             }
         }
     }
     // * PRINTERS
     $a_inventory['printer'] = array();
     if (isset($array['PRINTERS'])) {
         $rulecollection = new RuleDictionnaryPrinterCollection();
         foreach ($array['PRINTERS'] as $a_printers) {
             $array_tmp = $thisc->addValues($a_printers, array('NAME' => 'name', 'PORT' => 'port', 'SERIAL' => 'serial'));
             if (strstr($array_tmp['port'], "USB")) {
                 $array_tmp['have_usb'] = 1;
             } else {
                 $array_tmp['have_usb'] = 0;
             }
             unset($array_tmp['port']);
             $res_rule = $rulecollection->processAllRules(array("name" => $array_tmp['name']));
             if (isset($res_rule['_ignore_ocs_import']) && $res_rule['_ignore_ocs_import'] == "1") {
                 // Ignrore import printer
             } else {
                 if (isset($res_rule['_ignore_import']) && $res_rule['_ignore_import'] == "1") {
                     // Ignrore import printer
                 } else {
                     if (isset($res_rule['name'])) {
                         $array_tmp['name'] = $res_rule['name'];
                     }
                     if (isset($res_rule['manufacturer'])) {
                         $array_tmp['manufacturers_id'] = $res_rule['manufacturer'];
                     }
                     $a_inventory['printer'][] = $array_tmp;
                 }
             }
         }
     }
     // * PERIPHERAL
     $a_inventory['peripheral'] = array();
     $a_peripheral_name = array();
     $per = 0;
     if (isset($array['USBDEVICES'])) {
         foreach ($array['USBDEVICES'] as $a_peripherals) {
             $array_tmp = $thisc->addValues($a_peripherals, array('NAME' => 'name', 'MANUFACTURER' => 'manufacturers_id', 'SERIAL' => 'serial', 'PRODUCTNAME' => 'productname'));
             if (isset($a_peripherals['VENDORID']) and $a_peripherals['VENDORID'] != '' and isset($a_peripherals['PRODUCTID'])) {
                 $dataArray = PluginFusioninventoryInventoryExternalDB::getDataFromUSBID($a_peripherals['VENDORID'], $a_peripherals['PRODUCTID']);
                 $dataArray[0] = preg_replace('/&(?!\\w+;)/', '&amp;', $dataArray[0]);
                 if (!empty($dataArray[0]) and empty($array_tmp['manufacturers_id'])) {
                     $array_tmp['manufacturers_id'] = $dataArray[0];
                 }
                 $dataArray[1] = preg_replace('/&(?!\\w+;)/', '&amp;', $dataArray[1]);
                 if (!empty($dataArray[1]) and empty($a_peripherals['productname'])) {
                     $a_peripherals['productname'] = $dataArray[1];
                 }
             }
             if ($array_tmp['productname'] != '') {
                 $array_tmp['name'] = $array_tmp['productname'];
             }
             unset($array_tmp['productname']);
             $a_inventory['peripheral'][] = $array_tmp;
             $a_peripheral_name[$array_tmp['name']] = $per;
             $per++;
         }
     }
     if (isset($array['INPUTS'])) {
         $a_pointingtypes = array(3 => 'Mouse', 4 => 'Trackball', 5 => 'Track Point', 6 => 'Glide Point', 7 => 'Touch Pad', 8 => 'Touch Screen', 9 => 'Mouse - Optical Sensor');
         foreach ($array['INPUTS'] as $a_peripherals) {
             $array_tmp = $thisc->addValues($a_peripherals, array('NAME' => 'name', 'MANUFACTURER' => 'manufacturers_id'));
             $array_tmp['serial'] = '';
             $array_tmp['peripheraltypes_id'] = '';
             if (isset($a_peripherals['POINTINGTYPE']) && isset($a_pointingtypes[$a_peripherals['POINTINGTYPE']])) {
                 $array_tmp['peripheraltypes_id'] = $a_pointingtypes[$a_peripherals['POINTINGTYPE']];
             }
             if (isset($a_peripherals['LAYOUT'])) {
                 $array_tmp['peripheraltypes_id'] = 'keyboard';
             }
             if (isset($a_peripheral_name[$array_tmp['name']])) {
                 $a_inventory['peripheral'][$a_peripheral_name[$array_tmp['name']]]['peripheraltypes_id'] = $array_tmp['peripheraltypes_id'];
             } else {
                 $a_inventory['peripheral'][] = $array_tmp;
             }
         }
     }
     // * SLOTS
     // * SOFTWARES
     $a_inventory['SOFTWARES'] = array();
     if ($pfConfig->getValue('import_software') == 1) {
         if (isset($array['SOFTWARES'])) {
             $a_inventory['SOFTWARES'] = $array['SOFTWARES'];
         }
     }
     // * STORAGES/COMPUTERDISK
     $a_inventory['harddrive'] = array();
     if (isset($array['STORAGES'])) {
         foreach ($array['STORAGES'] as $a_storage) {
             $type_tmp = PluginFusioninventoryFormatconvert::getTypeDrive($a_storage);
             if ($type_tmp == "Drive") {
                 // it's cd-rom / dvd
                 //               if ($pfConfig->getValue(,
                 //                    "component_drive") =! 0) {
                 if ($pfConfig->getValue('component_drive') == 1) {
                     $array_tmp = $thisc->addValues($a_storage, array('SERIALNUMBER' => 'serial', 'NAME' => 'designation', 'TYPE' => 'interfacetypes_id', 'MANUFACTURER' => 'manufacturers_id'));
                     if ($array_tmp['designation'] == '') {
                         if (isset($a_storage['DESCRIPTION'])) {
                             $array_tmp['designation'] = $a_storage['DESCRIPTION'];
                         }
                     }
                     $a_inventory['drive'][] = $array_tmp;
                 }
             } else {
                 // it's harddisk
                 //               if ($pfConfig->getValue(,
                 //                    "component_harddrive") != 0) {
                 if (is_array($a_storage)) {
                     if ($pfConfig->getValue('component_harddrive') == 1) {
                         $array_tmp = $thisc->addValues($a_storage, array('DISKSIZE' => 'capacity', 'INTERFACE' => 'interfacetypes_id', 'MANUFACTURER' => 'manufacturers_id', 'MODEL' => 'designation', 'SERIALNUMBER' => 'serial'));
                         if ($array_tmp['designation'] == '') {
                             if (isset($a_storage['NAME'])) {
                                 $array_tmp['designation'] = $a_storage['NAME'];
                             } else {
                                 if (isset($a_storage['DESIGNATION'])) {
                                     $array_tmp['designation'] = $a_storage['DESIGNATION'];
                                 }
                             }
                         }
                         $a_inventory['harddrive'][] = $array_tmp;
                     }
                 }
             }
         }
     }
     // * USERS
     $cnt = 0;
     if (isset($array['USERS'])) {
         if (count($array['USERS']) > 0) {
             $user_temp = '';
             if (isset($a_inventory['Computer']['contact'])) {
                 $user_temp = $a_inventory['Computer']['contact'];
             }
             $a_inventory['Computer']['contact'] = '';
         }
         foreach ($array['USERS'] as $a_users) {
             $array_tmp = $thisc->addValues($a_users, array('LOGIN' => 'login', 'DOMAIN' => 'domain'));
             $user = '';
             if (isset($array_tmp['login'])) {
                 $user = $array_tmp['login'];
                 if (isset($array_tmp['domain']) && !empty($array_tmp['domain'])) {
                     $user .= "@" . $array_tmp['domain'];
                 }
             }
             if ($cnt == 0) {
                 if (isset($array_tmp['login'])) {
                     $query = "SELECT `id`\n                            FROM `glpi_users`\n                            WHERE `name` = '" . $array_tmp['login'] . "'\n                            LIMIT 1";
                     $result = $DB->query($query);
                     if ($DB->numrows($result) == 1) {
                         $a_inventory['Computer']['users_id'] = $DB->result($result, 0, 0);
                     }
                 }
             }
             if ($user != '') {
                 if (isset($a_inventory['Computer']['contact'])) {
                     if ($a_inventory['Computer']['contact'] == '') {
                         $a_inventory['Computer']['contact'] = $user;
                     } else {
                         $a_inventory['Computer']['contact'] .= "/" . $user;
                     }
                 } else {
                     $a_inventory['Computer']['contact'] = $user;
                 }
             }
             $cnt++;
         }
         if (empty($a_inventory['Computer']['contact'])) {
             $a_inventory['Computer']['contact'] = $user_temp;
         }
     }
     // * VIRTUALMACHINES
     $a_inventory['virtualmachine'] = array();
     if ($pfConfig->getValue('import_vm') == 1) {
         if (isset($array['VIRTUALMACHINES'])) {
             foreach ($array['VIRTUALMACHINES'] as $a_virtualmachines) {
                 $array_tmp = $thisc->addValues($a_virtualmachines, array('NAME' => 'name', 'VCPU' => 'vcpu', 'MEMORY' => 'ram', 'VMTYPE' => 'virtualmachinetypes_id', 'SUBSYSTEM' => 'virtualmachinesystems_id', 'STATUS' => 'virtualmachinestates_id', 'UUID' => 'uuid'));
                 $array_tmp['is_dynamic'] = 1;
                 // Hack for BSD jails
                 if ($array_tmp['virtualmachinetypes_id'] == 'jail') {
                     $array_tmp['uuid'] = $a_inventory['Computer']['uuid'] . "-" . $array_tmp['name'];
                 }
                 $a_inventory['virtualmachine'][] = $array_tmp;
             }
         }
     }
     if ($pfConfig->getValue('create_vm') == 1) {
         if (isset($array['VIRTUALMACHINES'])) {
             foreach ($array['VIRTUALMACHINES'] as $a_virtualmachines) {
                 if (strstr($a_virtualmachines['MEMORY'], 'MB')) {
                     $a_virtualmachines['MEMORY'] = str_replace('MB', '', $a_virtualmachines['MEMORY']);
                 } else {
                     if (strstr($a_virtualmachines['MEMORY'], 'KB')) {
                         $a_virtualmachines['MEMORY'] = str_replace('KB', '', $a_virtualmachines['MEMORY']);
                         $a_virtualmachines['MEMORY'] = $a_virtualmachines['MEMORY'] / 1000;
                     } else {
                         if (strstr($a_virtualmachines['MEMORY'], 'GB')) {
                             $a_virtualmachines['MEMORY'] = str_replace('GB', '', $a_virtualmachines['MEMORY']);
                             $a_virtualmachines['MEMORY'] = $a_virtualmachines['MEMORY'] * 1000;
                         } else {
                             if (strstr($a_virtualmachines['MEMORY'], 'B')) {
                                 $a_virtualmachines['MEMORY'] = str_replace('B', '', $a_virtualmachines['MEMORY']);
                                 $a_virtualmachines['MEMORY'] = $a_virtualmachines['MEMORY'] / 1000000;
                             }
                         }
                     }
                 }
                 $array_tmp = $thisc->addValues($a_virtualmachines, array('NAME' => 'name', 'VCPU' => 'vcpu', 'MEMORY' => 'ram', 'VMTYPE' => 'computertypes_id', 'UUID' => 'uuid', 'OPERATINGSYSTEM' => 'operatingsystems_id', 'CUSTOMFIELDS' => 'comment'));
                 $array_tmp['is_dynamic'] = 1;
                 if (isset($array_tmp['comment']) && is_array($array_tmp['comment'])) {
                     $a_com_temp = $array_tmp['comment'];
                     $array_tmp['comment'] = '';
                     foreach ($a_com_temp as $data) {
                         $array_tmp['comment'] .= $data['NAME'] . ' : ' . $data['VALUE'] . '\\n';
                     }
                 }
                 $array_tmp['networkport'] = array();
                 if (isset($a_virtualmachines['NETWORKS']) && is_array($a_virtualmachines['NETWORKS'])) {
                     foreach ($a_virtualmachines['NETWORKS'] as $data) {
                         $array_tmp_np = $thisc->addValues($data, array('DESCRIPTION' => 'name', 'MACADDR' => 'mac', 'IPADDRESS' => 'ip'));
                         $array_tmp_np['instantiation_type'] = 'NetworkPortEthernet';
                         $array_tmp_np['mac'] = strtolower($array_tmp_np['mac']);
                         if (isset($array_tmp['networkport'][$array_tmp_np['name'] . '-' . $array_tmp_np['mac']])) {
                             if (isset($array_tmp_np['ip'])) {
                                 $array_tmp['networkport'][$array_tmp_np['name'] . '-' . $array_tmp_np['mac']]['ipaddress'][] = $array_tmp_np['ip'];
                             }
                         } else {
                             if (isset($array_tmp_np['ip']) && $array_tmp_np['ip'] != '') {
                                 $array_tmp_np['ipaddress'] = array($array_tmp_np['ip']);
                                 unset($array_tmp_np['ip']);
                             } else {
                                 $array_tmp_np['ipaddress'] = array();
                             }
                             $array_tmp['networkport'][$array_tmp_np['name'] . '-' . $array_tmp_np['mac']] = $array_tmp_np;
                         }
                     }
                 }
                 $a_inventory['virtualmachine_creation'][] = $array_tmp;
             }
         }
     }
     // * ANTIVIRUS
     $a_inventory['antivirus'] = array();
     if (isset($array['ANTIVIRUS'])) {
         foreach ($array['ANTIVIRUS'] as $a_antiviruses) {
             $array_tmp = $thisc->addValues($a_antiviruses, array('NAME' => 'name', 'COMPANY' => 'manufacturers_id', 'VERSION' => 'version', 'ENABLED' => 'is_active', 'UPTODATE' => 'uptodate'));
             $a_inventory['antivirus'][] = $array_tmp;
         }
     }
     // * STORAGE/VOLUMES
     $a_inventory['storage'] = array();
     /* begin code, may works at 90%
           if (isset($array['PHYSICAL_VOLUMES'])) {
              foreach ($array['PHYSICAL_VOLUMES'] as $a_physicalvolumes) {
                 $array_tmp = $thisc->addValues($a_physicalvolumes,
                                                array(
                                                   'DEVICE'   => 'name',
                                                   'PV_UUID'  => 'uuid',
                                                   'VG_UUID'  => 'uuid_link',
                                                   'SIZE'     => 'totalsize',
                                                   'FREE'     => 'freesize'));
                 $array_tmp['plugin_fusioninventory_inventorycomputerstoragetypes_id'] =
                       'partition';
                 $a_inventory['storage'][] = $array_tmp;
              }
           }
           if (isset($array['STORAGES'])) {
              foreach ($array['STORAGES']  as $a_storage) {
                 $type_tmp = PluginFusioninventoryFormatconvert::getTypeDrive($a_storage);
                 if ($type_tmp != "Drive") {
                    if (isset($a_storage['NAME'])
                            AND $a_storage['NAME'] != '') {
                       $detectsize = 0;
                       $array_tmp = array();
     
                       foreach ($a_inventory['storage'] as $a_physicalvol) {
                          if (preg_match("/^\/dev\/".$a_storage['NAME']."/", $a_physicalvol['name'])) {
                             $array_tmp['name'] = $a_storage['NAME'];
                             if (isset($a_storage['SERIALNUMBER'])) {
                                $array_tmp['uuid'] = $a_storage['SERIALNUMBER'];
                             } else {
                                $array_tmp['uuid'] = $a_storage['NAME'];
                             }
                             $array_tmp['plugin_fusioninventory_inventorycomputerstoragetypes_id'] =
                                'hard disk';
                             if (!isset($array_tmp['uuid_link'])) {
                                $array_tmp['uuid_link'] = array();
                             }
                             $array_tmp['uuid_link'][] = $a_physicalvol['uuid'];
                             $detectsize += $a_physicalvol['totalsize'];
                          }
                       }
                       if (isset($a_storage['DISKSIZE'])
                               && $a_storage['DISKSIZE'] != '') {
                          $array_tmp['totalsize'] = $a_storage['DISKSIZE'];
                          $array_tmp['size_dynamic'] = 0;
                       } else {
                          $array_tmp['totalsize'] = $detectsize;
                          $array_tmp['size_dynamic'] = 1;
                       }
                       $a_inventory['storage'][] = $array_tmp;
                    }
                 }
              }
           }
     
           if (isset($array['VOLUME_GROUPS'])) {
              foreach ($array['VOLUME_GROUPS'] as $a_volumegroups) {
                 $array_tmp = $thisc->addValues($a_volumegroups,
                                                array(
                                                   'VG_NAME'  => 'name',
                                                   'VG_UUID'  => 'uuid',
                                                   'SIZE'     => 'totalsize',
                                                   'FREE'     => 'freesize'));
                 $array_tmp['plugin_fusioninventory_inventorycomputerstoragetypes_id'] =
                       'volume groups';
                 $a_inventory['storage'][] = $array_tmp;
              }
           }
           if (isset($array['LOGICAL_VOLUMES'])) {
              foreach ($array['LOGICAL_VOLUMES'] as $a_logicalvolumes) {
                 $array_tmp = $thisc->addValues($a_logicalvolumes,
                                                array(
                                                   'LV_NAME'  => 'name',
                                                   'LV_UUID'  => 'uuid',
                                                   'VG_UUID'  => 'uuid_link',
                                                   'SIZE'     => 'totalsize'));
                 $array_tmp['plugin_fusioninventory_inventorycomputerstoragetypes_id'] =
                       'logical volumes';
                 $a_inventory['storage'][] = $array_tmp;
              }
           }
     
           if (isset($array['DRIVES'])) {
              foreach ($array['DRIVES'] as $a_drives) {
                 if ((((isset($a_drives['TYPE'])
                            AND $a_drives['TYPE'] == 'Network Drive')
                             OR isset($a_drives['FILESYSTEM'])
                            AND $a_drives['FILESYSTEM'] == 'nfs'))
                     OR ((isset($a_drives['TYPE'])) AND
                         (($a_drives['TYPE'] == "Removable Disk")
                        OR ($a_drives['TYPE'] == "Compact Disc")))) {
     
                 } else if (isset($a_drives['VOLUMN'])
                         && strstr($a_drives['VOLUMN'], "/dev/mapper")){
                    // LVM
                    $a_split = explode("-", $a_drives['VOLUMN']);
                    $volumn = end($a_split);
                    $detectsize = 0;
                    $array_tmp = array();
                    foreach ($a_inventory['storage'] as $num=>$a_physicalvol) {
                       if ($a_physicalvol['plugin_fusioninventory_inventorycomputerstoragetypes_id']
                               == 'logical volumes') {
                          if ($volumn == $a_physicalvol['name']) {
                             $array_tmp['name'] = $a_drives['TYPE'];
                             if (isset($a_drives['SERIAL'])) {
                                $array_tmp['uuid'] = $a_drives['SERIAL'];
                             } else {
                                $array_tmp['uuid'] = $a_drives['TYPE'];
                             }
                             $array_tmp['plugin_fusioninventory_inventorycomputerstoragetypes_id'] =
                                'mount';
                             if (!isset($array_tmp['uuid_link'])) {
                                $array_tmp['uuid_link'] = array();
                             }
                             $array_tmp['uuid_link'][] = $a_physicalvol['uuid'];
                             $detectsize += $a_physicalvol['totalsize'];
                          }
                       }
                    }
                    if (isset($array_tmp['name'])) {
                       $array_tmp['totalsize'] = $a_drives['TOTAL'];
                       $a_inventory['storage'][] = $array_tmp;
                    }
     
                 } else if (isset($a_drives['VOLUMN'])
                         && strstr($a_drives['VOLUMN'], "/dev/")){
                    $detectsize = 0;
                    $array_tmp = array();
                    foreach ($a_inventory['storage'] as $num=>$a_physicalvol) {
                       $volumn = $a_drives['VOLUMN'];
                       $volumn = substr_replace($volumn , "", -1);
                       $volumn = str_replace("/dev/", "", $volumn);
                       if ($volumn == $a_physicalvol['name']) {
                          $array_tmp['name'] = $a_drives['VOLUMN'];
                          if (isset($a_drives['SERIAL'])) {
                             $array_tmp['uuid'] = $a_drives['SERIAL'];
                          } else {
                             $array_tmp['uuid'] = $a_drives['TYPE'];
                          }
                          $array_tmp['plugin_fusioninventory_inventorycomputerstoragetypes_id'] =
                             'partition';
                          if (!isset($array_tmp['uuid_link'])) {
                             $array_tmp['uuid_link'] = array();
                          }
                          $array_tmp['uuid_link'][] = $a_physicalvol['uuid'];
                          $detectsize += $a_physicalvol['totalsize'];
                          if ($a_physicalvol['size_dynamic'] == 1) {
                             $a_inventory['storage'][$num]['totalsize'] += $a_drives['TOTAL'];
                          }
                       }
                    }
                    if (isset($array_tmp['name'])) {
                       $array_tmp['totalsize'] = $a_drives['TOTAL'];
                       $a_inventory['storage'][] = $array_tmp;
     
                       $array_tmp['plugin_fusioninventory_inventorycomputerstoragetypes_id'] =
                                'mount';
                       $array_tmp['name'] = $a_drives['TYPE'];
                       $array_tmp['uuid_link'] = array();
                       $array_tmp['uuid_link'][] = $array_tmp['uuid'];
                       $array_tmp['uuid'] = $array_tmp['uuid']."-mount";
                       $a_inventory['storage'][] = $array_tmp;
                    }
                 }
              }
           }
     */
     // * LICENSEINFOS
     $a_inventory['licenseinfo'] = array();
     if (isset($array['LICENSEINFOS'])) {
         foreach ($array['LICENSEINFOS'] as $a_licenseinfo) {
             $array_tmp = $thisc->addValues($a_licenseinfo, array('NAME' => 'name', 'FULLNAME' => 'fullname', 'KEY' => 'serial'));
             $a_inventory['licenseinfo'][] = $array_tmp;
         }
     }
     return $a_inventory;
 }
 function CleanErrors()
 {
     $ptc = new PluginFusioninventoryConfig();
     $data = $this->find("`date`<DATE_SUB(NOW(), INTERVAL " . $ptc->getValue('delete_agent_process') . " HOUR)");
     foreach ($data as $process_id => $dataInfos) {
         $this->deleteFromDB($process_id, 1);
     }
 }
 static function getServerFileTree($params)
 {
     $nodes = array();
     if (isset($params['node'])) {
         //root node
         $pfConfig = new PluginFusioninventoryConfig();
         $dir = $pfConfig->getValue('server_upload_path');
         // leaf node
         if ($params['node'] != -1) {
             $dir = $params['node'];
         }
         if ($handle = opendir($dir)) {
             $folders = $files = array();
             //list files in dir selected
             //we store folders and files separately to sort them alphabeticaly separatly
             while (FALSE !== ($entry = readdir($handle))) {
                 if ($entry != "." && $entry != "..") {
                     $filepath = $dir . "/" . $entry;
                     if (is_dir($filepath)) {
                         $folders[$filepath] = $entry;
                     } else {
                         $files[$filepath] = $entry;
                     }
                 }
             }
             //sort folders and files (and maintain index association)
             asort($folders);
             asort($files);
             //add folders in json
             foreach ($folders as $filepath => $entry) {
                 $path['text'] = $entry;
                 $path['id'] = $filepath;
                 $path['draggable'] = FALSE;
                 $path['leaf'] = FALSE;
                 $path['cls'] = 'folder';
                 $nodes[] = $path;
             }
             //add files in json
             foreach ($files as $filepath => $entry) {
                 $path['text'] = $entry;
                 $path['id'] = $filepath;
                 $path['draggable'] = FALSE;
                 $path['leaf'] = TRUE;
                 $path['cls'] = 'file';
                 $nodes[] = $path;
             }
             closedir($handle);
         }
     }
     print json_encode($nodes);
 }
 /**
  * Prepare data and send them to rule engine
  *
  * @param type $p_xml simpleXML object
  */
 function sendCriteria($arrayinventory)
 {
     PluginFusioninventoryCommunication::addLog('Function PluginFusioninventoryCommunicationNetworkDiscovery->sendCriteria().');
     if (isset($arrayinventory['MAC']) && $arrayinventory['MAC'] == "00:00:00:00:00:00") {
         unset($arrayinventory['MAC']);
     }
     $_SESSION['SOURCE_XMLDEVICE'] = $arrayinventory;
     $input = array();
     // Global criterias
     if (isset($arrayinventory['SERIAL']) && !empty($arrayinventory['SERIAL'])) {
         $input['serial'] = $arrayinventory['SERIAL'];
     }
     if (isset($arrayinventory['MAC']) && !empty($arrayinventory['MAC'])) {
         $input['mac'][] = $arrayinventory['MAC'];
     }
     if (isset($arrayinventory['IP']) && !empty($arrayinventory['IP'])) {
         $input['ip'][] = $arrayinventory['IP'];
     }
     if (isset($arrayinventory['MODELSNMP']) && !empty($arrayinventory['MODELSNMP'])) {
         $input['model'] = $arrayinventory['MODELSNMP'];
     }
     if (isset($arrayinventory['SNMPHOSTNAME']) && !empty($arrayinventory['SNMPHOSTNAME'])) {
         $input['name'] = $arrayinventory['SNMPHOSTNAME'];
     } else {
         if (isset($arrayinventory['NETBIOSNAME']) && !empty($arrayinventory['NETBIOSNAME'])) {
             $input['name'] = $arrayinventory['NETBIOSNAME'];
         } else {
             if (isset($arrayinventory['DNSHOSTNAME']) && !empty($arrayinventory['DNSHOSTNAME'])) {
                 if (strpos($arrayinventory['DNSHOSTNAME'], '.') !== false) {
                     $splitname = explode('.', $arrayinventory['DNSHOSTNAME']);
                     $input['name'] = $splitname[0];
                     if (!isset($arrayinventory['WORKGROUP'])) {
                         unset($splitname[0]);
                         $arrayinventory['WORKGROUP'] = implode('.', $splitname);
                         $_SESSION['SOURCE_XMLDEVICE'] = $arrayinventory;
                     }
                 } else {
                     $input['name'] = $arrayinventory['DNSHOSTNAME'];
                 }
             }
         }
     }
     if (!isset($arrayinventory['ENTITY'])) {
         $arrayinventory['ENTITY'] = 0;
     }
     $input['entities_id'] = $arrayinventory['ENTITY'];
     if (isset($arrayinventory['TYPE'])) {
         switch ($arrayinventory['TYPE']) {
             case '1':
             case 'COMPUTER':
                 $input['itemtype'] = "Computer";
                 // Computer
                 break;
             case '2':
             case 'NETWORKING':
                 $input['itemtype'] = "NetworkEquipment";
                 break;
             case '3':
             case 'PRINTER':
                 $input['itemtype'] = "Printer";
                 break;
         }
     }
     $_SESSION['plugin_fusinvsnmp_datacriteria'] = serialize($input);
     $_SESSION['plugin_fusioninventory_classrulepassed'] = "PluginFusioninventoryCommunicationNetworkDiscovery";
     $rule = new PluginFusioninventoryInventoryRuleImportCollection();
     $data = $rule->processAllRules($input, array());
     PluginFusioninventoryConfig::logIfExtradebug("pluginFusioninventory-rules", $data);
     if (isset($data['action']) && $data['action'] == PluginFusioninventoryInventoryRuleImport::LINK_RESULT_DENIED) {
         $a_text = '';
         foreach ($input as $key => $data) {
             if (is_array($data)) {
                 $a_text[] = "[" . $key . "]:" . implode(", ", $data);
             } else {
                 $a_text[] = "[" . $key . "]:" . $data;
             }
         }
         $_SESSION['plugin_fusinvsnmp_taskjoblog']['comment'] = '==importdenied== ' . implode(", ", $a_text);
         $this->addtaskjoblog();
         $pfIgnoredimport = new PluginFusioninventoryIgnoredimportdevice();
         $inputdb = array();
         if (isset($input['name'])) {
             $inputdb['name'] = $input['name'];
         }
         $inputdb['date'] = date("Y-m-d H:i:s");
         if (isset($input['itemtype'])) {
             $inputdb['itemtype'] = $input['itemtype'];
         }
         if (isset($input['serial'])) {
             $input['serial'] = $input['serial'];
         }
         if (isset($input['ip'])) {
             $inputdb['ip'] = exportArrayToDB($input['ip']);
         }
         if (isset($input['mac'])) {
             $inputdb['mac'] = exportArrayToDB($input['mac']);
         }
         if (isset($input['uuid'])) {
             $inputdb['uuid'] = $input['uuid'];
         }
         $inputdb['rules_id'] = $_SESSION['plugin_fusioninventory_rules_id'];
         $inputdb['method'] = 'netdiscovery';
         $pfIgnoredimport->add($inputdb);
         unset($_SESSION['plugin_fusioninventory_rules_id']);
     }
     if (isset($data['_no_rule_matches']) and $data['_no_rule_matches'] == '1') {
         if (!isset($_SESSION['glpiactiveentities_string'])) {
             $_SESSION['glpiactiveentities_string'] = "'" . $input['entities_id'] . "'";
         }
         if (isset($input['itemtype']) && isset($data['action']) && $data['action'] == PluginFusioninventoryInventoryRuleImport::LINK_RESULT_CREATE) {
             $this->rulepassed(0, $input['itemtype'], $input['entities_id']);
         } else {
             if (isset($input['itemtype']) and !isset($data['action'])) {
                 $this->rulepassed(0, $input['itemtype'], $input['entities_id']);
             } else {
                 $this->rulepassed(0, "PluginFusioninventoryUnmanaged", $input['entities_id']);
             }
         }
     }
 }
// ----------------------------------------------------------------------
if (!defined('GLPI_ROOT')) {
    define('GLPI_ROOT', '../../..');
}
$NEEDED_ITEMS = array("computer", "device", "printer", "networking", "peripheral", "monitor", "software", "infocom", "phone", "tracking", "enterprise", "reservation", "setup", "group", "registry", "rulesengine", "ocsng", "admininfo", "rule.ocs", "rule.softwarecategories", "rule.dictionnary.software", "rule.dictionnary.dropdown", "entity");
include GLPI_ROOT . "/inc/includes.php";
$_SESSION["glpi_use_mode"] = 2;
$ptc = new PluginFusioninventoryCommunication();
$ptap = new PluginFusioninventoryAgentsProcesses();
$res = '';
$errors = '';
// ***** For debug only ***** //
//$GLOBALS["HTTP_RAW_POST_DATA"] = gzcompress('');
// ********** End ********** //
// Get conf tu know if SSL is only
$fusioninventory_config = new PluginFusioninventoryConfig();
$ssl = $fusioninventory_config->getValue('ssl_only');
if (isset($_SERVER["HTTPS"]) and $_SERVER["HTTPS"] == "on" and $ssl == "1" or $ssl == "0") {
    // echo "On continue";
} else {
    $ptc->setXML("<?xml version='1.0' encoding='ISO-8859-1'?>\n<REPLY>\n</REPLY>");
    $ptc->noSSL();
    exit;
}
$ocsinventory = '0';
file_put_contents(GLPI_PLUGIN_DOC_DIR . "/fusioninventory/dial.log" . rand(), gzuncompress($GLOBALS["HTTP_RAW_POST_DATA"]));
$state = $ptc->importToken(gzuncompress($GLOBALS["HTTP_RAW_POST_DATA"]));
if ($state == '2') {
    // agent created
    $ocsinventory = '1';
}
 /**
  * Get SNMP version and authentification 
  *
  * @param $ID_Device ID of the device ("all" if we want to get all snmp auth)
  * @param $xml_auth_rep folder where as stocked authxml file (if the management is by FILE)
  * @param $type type of device (NETWORKING_TYPE, PRINTER_TYPE ...)
  *
  * @return $snmp_auth : array with auth informations && version
  *
  **/
 function GetInfos($ID_Device, $xml_auth_rep, $type)
 {
     global $DB, $CFG_GLPI, $LANG;
     $config = new PluginFusioninventoryConfig();
     if ($ID_Device != "all") {
         switch ($type) {
             case NETWORKING_TYPE:
                 $query = "SELECT *\n                         FROM `glpi_plugin_fusioninventory_networking`\n                         WHERE `FK_networking`='" . $ID_Device . "';";
                 break;
             case PRINTER_TYPE:
                 $query = "SELECT *\n                         FROM `glpi_plugin_fusioninventory_printers`\n                         WHERE `FK_printers`='" . $ID_Device . "';";
                 break;
         }
         $result = $DB->query($query);
         if ($DB->numrows($result) > 0) {
             $ID_auth = $DB->result($result, 0, "FK_snmp_connection");
         } else {
             return;
         }
     } else {
         // Put Default community of devices
         $snmp_auth[0]["Name"] = "Public-v2c";
         $snmp_auth[0]["snmp_version"] = "2c";
         $snmp_auth[0]["community"] = "public";
         $snmp_auth[0]["sec_name"] = "";
         $snmp_auth[0]["auth_protocol"] = "";
         $snmp_auth[0]["auth_passphrase"] = "";
         $snmp_auth[0]["priv_protocol"] = "";
         $snmp_auth[0]["priv_passphrase"] = "";
         $snmp_auth[0]["ID"] = 0;
         $snmp_auth[1]["Name"] = "Public-v1";
         $snmp_auth[1]["snmp_version"] = "1";
         $snmp_auth[1]["community"] = "public";
         $snmp_auth[1]["sec_name"] = "";
         $snmp_auth[1]["auth_protocol"] = "";
         $snmp_auth[1]["auth_passphrase"] = "";
         $snmp_auth[1]["priv_protocol"] = "";
         $snmp_auth[1]["priv_passphrase"] = "";
         $snmp_auth[1]["ID"] = 0;
     }
     if ($config->getValue("authsnmp") == "file") {
         $xml = simplexml_load_file($xml_auth_rep . "auth.xml");
         $i = -1;
         foreach ($xml->auth[0] as $num) {
             $i++;
             $j = 0;
             $recup = 0;
             foreach ($xml->auth->conf[$i] as $item) {
                 $j++;
                 switch ($j) {
                     case 1:
                         if ($ID_Device == "all") {
                             $recup = 1;
                             $snmp_auth[$i + 2]["ID"] = $item;
                         } else {
                             if ($item == $ID_auth) {
                                 $recup = 1;
                             }
                         }
                         break;
                     case 2:
                         if ($recup == "1" and $ID_Device != "all") {
                             $snmp_auth["Name"] = $item;
                         }
                         if ($ID_Device == "all") {
                             $snmp_auth[$i + 2]["Name"] = $item;
                         }
                         break;
                     case 3:
                         if ($recup == "1" and $ID_Device != "all") {
                             $snmp_auth["snmp_version"] = Dropdown::getDropdownName("glpi_plugin_fusioninventory_snmpversions", $item);
                         }
                         if ($ID_Device == "all") {
                             $snmp_auth[$i + 2]["snmp_version"] = Dropdown::getDropdownName("glpi_plugin_fusioninventory_snmpversions", $item);
                         }
                         break;
                     case 4:
                         if ($recup == "1" and $ID_Device != "all") {
                             $snmp_auth["community"] = $item;
                         }
                         if ($ID_Device == "all") {
                             $snmp_auth[$i + 2]["community"] = $item;
                         }
                         break;
                     case 5:
                         if ($recup == "1" and $ID_Device != "all") {
                             $snmp_auth["sec_name"] = $item;
                         }
                         if ($ID_Device == "all") {
                             $snmp_auth[$i + 2]["sec_name"] = $item;
                         }
                         break;
                     case 7:
                         if ($recup == "1" and $ID_Device != "all") {
                             $snmp_auth["auth_protocol"] = Dropdown::getDropdownName("glpi_plugin_fusioninventory_snmpprotocolauths", $item);
                         }
                         if ($ID_Device == "all") {
                             $snmp_auth[$i + 2]["auth_protocol"] = Dropdown::getDropdownName("glpi_plugin_fusioninventory_snmpprotocolauths", $item);
                         }
                         break;
                     case 8:
                         if ($recup == "1" and $ID_Device != "all") {
                             $snmp_auth["auth_passphrase"] = $item;
                         }
                         if ($ID_Device == "all") {
                             $snmp_auth[$i + 2]["auth_passphrase"] = $item;
                         }
                         break;
                     case 9:
                         if ($recup == "1" and $ID_Device != "all") {
                             $snmp_auth["priv_protocol"] = Dropdown::getDropdownName("glpi_plugin_fusioninventory_snmpprotocolprivs", $item);
                         }
                         if ($ID_Device == "all") {
                             $snmp_auth[$i + 2]["priv_protocol"] = Dropdown::getDropdownName("glpi_plugin_fusioninventory_snmpprotocolprivs", $item);
                         }
                         break;
                     case 10:
                         if ($recup == "1" and $ID_Device != "all") {
                             $snmp_auth["priv_passphrase"] = $item;
                         }
                         if ($ID_Device == "all") {
                             $snmp_auth[$i + 2]["priv_passphrase"] = $item;
                         }
                         break;
                 }
             }
         }
     } else {
         if ($config->getValue("authsnmp") == "DB") {
             if ($ID_Device == "all") {
                 $query = "SELECT *\n                      FROM `glpi_plugin_fusioninventory_snmpauths`";
             } else {
                 $query = "SELECT *\n                      FROM `glpi_plugin_fusioninventory_snmpauths`\n                      WHERE `ID`='" . $ID_auth . "';";
             }
             $result = $DB->query($query);
             if ($DB->numrows($result) == "0" and $ID_Device != "all") {
                 $snmp_auth["Name"] = "";
                 $snmp_auth["snmp_version"] = "";
                 $snmp_auth["community"] = "";
                 $snmp_auth["sec_name"] = "";
                 $snmp_auth["auth_protocol"] = "";
                 $snmp_auth["auth_passphrase"] = "";
                 $snmp_auth["priv_protocol"] = "";
                 $snmp_auth["priv_passphrase"] = "";
             } else {
                 if ($ID_Device != "all") {
                     $snmp_auth["Name"] = $DB->result($result, 0, "name");
                     $snmp_auth["snmp_version"] = Dropdown::getDropdownName("glpi_plugin_fusioninventory_snmpversions", $DB->result($result, 0, "FK_snmp_version"));
                     $snmp_auth["community"] = $DB->result($result, 0, "community");
                     $snmp_auth["sec_name"] = $DB->result($result, 0, "sec_name");
                     $snmp_auth["auth_protocol"] = Dropdown::getDropdownName("glpi_plugin_fusioninventory_snmpprotocolauths", $DB->result($result, 0, "auth_protocol"));
                     $snmp_auth["auth_passphrase"] = $DB->result($result, 0, "auth_passphrase");
                     $snmp_auth["priv_protocol"] = Dropdown::getDropdownName("glpi_plugin_fusioninventory_snmpprotocolprivs", $DB->result($result, 0, "priv_protocol"));
                     $snmp_auth["priv_passphrase"] = $DB->result($result, 0, "priv_passphrase");
                 } else {
                     if ($ID_Device == "all") {
                         $i = 2;
                         while ($data = $DB->fetch_array($result)) {
                             if ($snmp_auth[0]["snmp_version"] == Dropdown::getDropdownName("glpi_plugin_fusioninventory_snmpversions", $data["FK_snmp_version"]) and $snmp_auth[0]["community"] == $data["community"]) {
                                 $snmp_auth[0]["ID"] = $data["ID"];
                             } else {
                                 if ($snmp_auth[1]["snmp_version"] == Dropdown::getDropdownName("glpi_plugin_fusioninventory_snmpversions", $data["FK_snmp_version"]) and $snmp_auth[1]["community"] == $data["community"]) {
                                     $snmp_auth[1]["ID"] = $data["ID"];
                                 } else {
                                     $snmp_auth[$i]["ID"] = $data["ID"];
                                     $snmp_auth[$i]["Name"] = $data["name"];
                                     $snmp_auth[$i]["snmp_version"] = Dropdown::getDropdownName("glpi_plugin_fusioninventory_snmpversions", $data["FK_snmp_version"]);
                                     $snmp_auth[$i]["community"] = $data["community"];
                                     $snmp_auth[$i]["sec_name"] = $data["sec_name"];
                                     $snmp_auth[$i]["auth_protocol"] = Dropdown::getDropdownName("glpi_plugin_fusioninventory_snmpprotocolauths", $data["auth_protocol"]);
                                     $snmp_auth[$i]["auth_passphrase"] = $data["auth_passphrase"];
                                     $snmp_auth[$i]["priv_protocol"] = Dropdown::getDropdownName("glpi_plugin_fusioninventory_snmpprotocolprivs", $data["priv_protocol"]);
                                     $snmp_auth[$i]["priv_passphrase"] = $data["priv_passphrase"];
                                     $i++;
                                 }
                             }
                         }
                     }
                 }
             }
         }
     }
     return $snmp_auth;
 }
function plugin_init_fusioninventory()
{
    global $PLUGIN_HOOKS, $CFG_GLPI;
    $PLUGIN_HOOKS['csrf_compliant']['fusioninventory'] = TRUE;
    $Plugin = new Plugin();
    $moduleId = 0;
    if (isset($_SESSION['glpi_use_mode'])) {
        $debug_mode = $_SESSION['glpi_use_mode'] == Session::DEBUG_MODE;
    } else {
        $debug_mode = false;
    }
    if ($Plugin->isActivated('fusioninventory')) {
        // check if plugin is active
        // Register classes into GLPI plugin factory
        Plugin::registerClass('PluginFusioninventoryAgent', array('addtabon' => array('Computer', 'Printer', 'NetworkEquipment', 'PluginFusioninventoryCredentialIp')));
        Plugin::registerClass('PluginFusioninventoryAgentmodule');
        Plugin::registerClass('PluginFusioninventoryConfig');
        Plugin::registerClass('PluginFusioninventoryTask', array('addtabon' => array('Computer', 'Printer', 'NetworkEquipment', 'PluginFusioninventoryCredentialIp')));
        Plugin::registerClass('PluginFusioninventoryTaskjob', array('addtabon' => array('PluginFusioninventoryTask')));
        Plugin::registerClass('PluginFusioninventoryTaskjobstate', array('addtabon' => array('PluginFusioninventoryTask')));
        Plugin::registerClass('PluginFusioninventoryUnmanaged');
        Plugin::registerClass('PluginFusioninventoryModule');
        Plugin::registerClass('PluginFusioninventoryProfile', array('addtabon' => array('Profile')));
        Plugin::registerClass('PluginFusioninventoryEntity', array('addtabon' => array('Entity')));
        Plugin::registerClass('PluginFusioninventorySetup');
        Plugin::registerClass('PluginFusioninventoryIPRange');
        Plugin::registerClass('PluginFusioninventoryIPRange_ConfigSecurity', array('addtabon' => 'PluginFusioninventoryIPRange'));
        Plugin::registerClass('PluginFusioninventoryCredential');
        Plugin::registerClass('PluginFusioninventoryTimeslot');
        Plugin::registerClass('PluginFusioninventoryLock', array('addtabon' => array('Computer', 'Printer', 'NetworkEquipment')));
        Plugin::registerClass('PluginFusioninventoryInventoryComputerAntivirus', array('addtabon' => array('Computer')));
        Plugin::registerClass('PluginFusioninventoryInventoryComputerComputer', array('addtabon' => array('Computer')));
        Plugin::registerClass('PluginFusioninventoryInventoryComputerInventory');
        Plugin::registerClass('PluginFusioninventoryInventoryComputerStorage', array('addtabon' => array('Computer')));
        Plugin::registerClass('PluginFusioninventoryCollect');
        Plugin::registerClass('PluginFusioninventoryCollect_Registry', array('addtabon' => array('PluginFusioninventoryCollect')));
        Plugin::registerClass('PluginFusioninventoryCollect_Registry_Content', array('addtabon' => array('PluginFusioninventoryCollect', 'Computer')));
        Plugin::registerClass('PluginFusioninventoryCollect_Wmi', array('addtabon' => array('PluginFusioninventoryCollect')));
        Plugin::registerClass('PluginFusioninventoryCollect_Wmi_Content', array('addtabon' => array('PluginFusioninventoryCollect', 'Computer')));
        Plugin::registerClass('PluginFusioninventoryCollect_File', array('addtabon' => array('PluginFusioninventoryCollect')));
        Plugin::registerClass('PluginFusioninventoryCollect_File_Content', array('addtabon' => array('PluginFusioninventoryCollect', 'Computer')));
        Plugin::registerClass('PluginFusioninventoryComputerLicenseInfo', array('addtabon' => array('Computer')));
        //Classes for rulesengine
        Plugin::registerClass('PluginFusioninventoryInventoryRuleLocation');
        Plugin::registerClass('PluginFusioninventoryInventoryRuleLocationCollection', array('rulecollections_types' => TRUE));
        Plugin::registerClass('PluginFusioninventoryInventoryRuleEntity');
        Plugin::registerClass('PluginFusioninventoryInventoryRuleEntityCollection', array('rulecollections_types' => TRUE));
        Plugin::registerClass('PluginFusioninventoryRulematchedlog', array('addtabon' => array('Computer', 'PluginFusioninventoryAgent', 'PluginFusioninventoryUnmanaged', 'Printer', 'NetworkEquipment')));
        //Classes for rulesengine
        Plugin::registerClass('PluginFusioninventoryInventoryRuleImport');
        Plugin::registerClass('PluginFusioninventoryInventoryRuleImportCollection', array('rulecollections_types' => TRUE));
        Plugin::registerClass('PluginFusioninventoryConstructDevice');
        //Computer arch dictionnary
        Plugin::registerClass('PluginFusioninventoryRuleDictionnaryComputerArch');
        Plugin::registerClass('PluginFusioninventoryRuleDictionnaryComputerArchCollection', array('rulecollections_types' => TRUE));
        array_push($CFG_GLPI["dictionnary_types"], 'PluginFusioninventoryRuleDictionnaryComputerArchCollection');
        // Networkinventory and networkdiscovery
        Plugin::registerClass('PluginFusioninventorySnmpmodel');
        Plugin::registerClass('PluginFusioninventoryNetworkEquipment', array('addtabon' => array('NetworkEquipment')));
        Plugin::registerClass('PluginFusioninventoryPrinter', array('addtabon' => array('Printer')));
        Plugin::registerClass('PluginFusioninventoryPrinterCartridge');
        Plugin::registerClass('PluginFusioninventoryConfigSecurity');
        Plugin::registerClass('PluginFusioninventoryNetworkPortLog', array('addtabon' => array('NetworkPort')));
        Plugin::registerClass('PluginFusinvsnmpAgentconfig');
        Plugin::registerClass('PluginFusioninventoryNetworkPort', array('classname' => 'glpi_networkports'));
        Plugin::registerClass('PluginFusioninventoryStateDiscovery');
        Plugin::registerClass('PluginFusioninventoryPrinterLogReport');
        Plugin::registerClass('PluginFusioninventorySnmpmodelConstructdevice_User', array('addtabon' => array('User')));
        Plugin::registerClass('PluginFusioninventoryDeployGroup');
        Plugin::registerClass('PluginFusioninventoryDeployGroup_Staticdata', array('addtabon' => array('PluginFusioninventoryDeployGroup')));
        Plugin::registerClass('PluginFusioninventoryDeployGroup_Dynamicdata', array('addtabon' => array('PluginFusioninventoryDeployGroup')));
        $CFG_GLPI['glpitablesitemtype']["PluginFusioninventoryPrinterLogReport"] = "glpi_plugin_fusioninventory_printers";
        $CFG_GLPI['glpitablesitemtype']["PluginFusioninventoryComputer"] = "glpi_computers";
        // ##### 3. get informations of the plugin #####
        $Plugin->getFromDBbyDir('fusioninventory');
        $moduleId = $Plugin->fields['id'];
        // Load config
        PluginFusioninventoryConfig::loadCache();
        // ##### 5. Set in session XMLtags of methods #####
        $_SESSION['glpi_plugin_fusioninventory']['xmltags']['WAKEONLAN'] = '';
        $_SESSION['glpi_plugin_fusioninventory']['xmltags']['INVENTORY'] = 'PluginFusioninventoryInventoryComputerInventory';
        $_SESSION['glpi_plugin_fusioninventory']['xmltags']['NETWORKDISCOVERY'] = 'PluginFusioninventoryCommunicationNetworkDiscovery';
        $_SESSION['glpi_plugin_fusioninventory']['xmltags']['NETWORKINVENTORY'] = 'PluginFusioninventoryCommunicationNetworkInventory';
        $PLUGIN_HOOKS['import_item']['fusioninventory'] = array('Computer' => array('Plugin'));
        $CFG_GLPI["specif_entities_tables"][] = 'glpi_plugin_fusioninventory_ipranges';
        $CFG_GLPI["networkport_types"][] = 'PluginFusioninventoryUnmanaged';
        /**
         * Load the relevant javascript/css files only on pages that need them.
         */
        $PLUGIN_HOOKS['add_javascript']['fusioninventory'] = array();
        $PLUGIN_HOOKS['add_css']['fusioninventory'] = array();
        if (strpos($_SERVER['SCRIPT_FILENAME'], "plugins/fusioninventory") != false) {
            $PLUGIN_HOOKS['add_css']['fusioninventory'][] = "css/views.css";
            $PLUGIN_HOOKS['add_css']['fusioninventory'][] = "css/deploy.css";
            array_push($PLUGIN_HOOKS['add_javascript']['fusioninventory'], "lib/d3-3.4.3/d3" . ($debug_mode ? "" : ".min") . ".js", "lib/nvd3/nv.d3" . ($debug_mode ? "" : ".min") . ".js", "lib/expanding/expanding" . ($debug_mode ? "" : ".min") . ".js");
        }
        if (script_endswith("timeslot.form.php")) {
            $PLUGIN_HOOKS['add_javascript']['fusioninventory'][] = "lib/timeslot" . ($debug_mode ? "" : ".min") . ".js";
        }
        if (script_endswith("deploypackage.form.php")) {
            $PLUGIN_HOOKS['add_css']['fusioninventory'][] = "lib/extjs/resources/css/ext-all.css";
            array_push($PLUGIN_HOOKS['add_javascript']['fusioninventory'], "lib/extjs/adapter/ext/ext-base" . ($debug_mode ? "-debug" : "") . ".js", "lib/extjs/ext-all" . ($debug_mode ? "-debug" : "") . ".js", "lib/REDIPS_drag/redips-drag" . ($debug_mode ? "-source" : "-min") . ".js", "lib/REDIPS_drag/drag_table_rows.js", "lib/plusbutton" . ($debug_mode ? "" : ".min") . ".js", "lib/deploy_editsubtype" . ($debug_mode ? "" : ".min") . ".js");
        }
        if (script_endswith("task.form.php") || script_endswith("taskjob.php") || script_endswith("iprange.form.php")) {
            array_push($PLUGIN_HOOKS['add_javascript']['fusioninventory'], "lib/lazy.js-0.4.0/lazy" . ($debug_mode ? "" : ".min") . ".js", "lib/mustache.js-2.0.0/mustache" . ($debug_mode ? "" : ".min") . ".js", "js/taskjobs" . ($debug_mode ? "" : ".min") . ".js");
        }
        if (script_endswith("menu.php")) {
            $PLUGIN_HOOKS['add_javascript']['fusioninventory'][] = "js/stats" . ($debug_mode ? "" : ".min") . ".js";
        }
        if (Session::haveRight('plugin_fusioninventory_configuration', READ) || Session::haveRight('profile', UPDATE)) {
            // Config page
            $PLUGIN_HOOKS['config_page']['fusioninventory'] = 'front/config.form.php' . '?itemtype=pluginfusioninventoryconfig&glpi_tab=1';
        }
        $PLUGIN_HOOKS['autoinventory_information']['fusioninventory'] = array('Computer' => array('PluginFusioninventoryInventoryComputerComputer', 'showInfo'), 'NetworkEquipment' => array('PluginFusioninventoryNetworkEquipment', 'showInfo'), 'Printer' => array('PluginFusioninventoryPrinter', 'showInfo'));
        $PLUGIN_HOOKS['use_massive_action']['fusioninventory'] = 1;
        $PLUGIN_HOOKS['item_add']['fusioninventory'] = array('NetworkPort_NetworkPort' => 'plugin_item_add_fusioninventory', 'NetworkPort' => 'plugin_item_add_fusioninventory');
        $PLUGIN_HOOKS['pre_item_update']['fusioninventory'] = array('Plugin' => 'plugin_pre_item_update_fusioninventory');
        $PLUGIN_HOOKS['item_update']['fusioninventory'] = array('Computer' => 'plugin_item_update_fusioninventory', 'NetworkEquipment' => 'plugin_item_update_fusioninventory', 'Printer' => 'plugin_item_update_fusioninventory', 'Monitor' => 'plugin_item_update_fusioninventory', 'Peripheral' => 'plugin_item_update_fusioninventory', 'Phone' => 'plugin_item_update_fusioninventory', 'NetworkPort' => 'plugin_item_update_fusioninventory', 'PluginFusioninventoryInventoryComputerAntivirus' => array('PluginFusioninventoryInventoryComputerAntivirus', 'addhistory'), 'PluginFusioninventoryLock' => array('PluginFusioninventoryLock', 'deleteLock'));
        $PLUGIN_HOOKS['pre_item_purge']['fusioninventory'] = array('Computer' => 'plugin_pre_item_purge_fusioninventory', 'NetworkPort_NetworkPort' => 'plugin_pre_item_purge_fusioninventory', 'PluginFusioninventoryLock' => array('PluginFusioninventoryLock', 'deleteLock'));
        $p = array('NetworkPort_NetworkPort' => 'plugin_item_purge_fusioninventory', 'PluginFusioninventoryTask' => array('PluginFusioninventoryTask', 'purgeTask'), 'PluginFusioninventoryTaskjob' => array('PluginFusioninventoryTaskjob', 'purgeTaskjob'), 'PluginFusioninventoryUnmanaged' => array('PluginFusioninventoryUnmanaged', 'purgeUnmanaged'), 'NetworkEquipment' => 'plugin_item_purge_fusinvsnmp', 'Printer' => 'plugin_item_purge_fusinvsnmp', 'PluginFusioninventoryUnmanaged' => 'plugin_item_purge_fusinvsnmp');
        $PLUGIN_HOOKS['item_purge']['fusioninventory'] = $p;
        $PLUGIN_HOOKS['item_transfer']['fusioninventory'] = 'plugin_item_transfer_fusioninventory';
        if (Session::haveRight('plugin_fusioninventory_unmanaged', READ)) {
            $PLUGIN_HOOKS["menu_toadd"]['fusioninventory']['assets'] = 'PluginFusioninventoryUnmanaged';
        }
        if (Session::haveRight('plugin_fusioninventory_menu', READ)) {
            $PLUGIN_HOOKS["menu_toadd"]['fusioninventory']['plugins'] = 'PluginFusioninventoryMenu';
        }
        if (isset($_SESSION["glpiname"])) {
            $report_list = array();
            if (Session::haveRight('plugin_fusioninventory_reportprinter', READ)) {
                $report_list["front/printerlogreport.php"] = __('Printed page counter', 'fusioninventory');
            }
            if (Session::haveRight('plugin_fusioninventory_reportnetworkequipment', READ)) {
                $report_list["report/switch_ports.history.php"] = __('Switchs ports history', 'fusioninventory');
                $report_list["report/ports_date_connections.php"] = __('Unused switchs ports', 'fusioninventory');
                $report_list["report/not_queried_recently.php"] = __('Number of days since last inventory', 'fusioninventory');
            }
            if (Session::haveRight('computer', READ)) {
                $report_list["report/computer_last_inventory.php"] = __('Computers not inventoried since xx days', 'fusioninventory');
            }
            $PLUGIN_HOOKS['reports']['fusioninventory'] = $report_list;
            /*
             * Deploy submenu entries
             */
            if (Session::haveRight('plugin_fusioninventory_configuration', READ)) {
                // Config page
                $PLUGIN_HOOKS['submenu_entry']['fusioninventory']['config'] = 'front/config.form.php';
            }
            $PLUGIN_HOOKS['webservices']['fusioninventory'] = 'plugin_fusioninventory_registerMethods';
            // Hack for NetworkEquipment display ports
            if (strstr($_SERVER['PHP_SELF'], '/ajax/common.tabs.php')) {
                if (isset($_GET['_target']) && strstr($_GET['_target'], '/front/networkequipment.form.php') && $_GET['_itemtype'] == 'NetworkEquipment') {
                    if ($_GET['_glpi_tab'] == 'NetworkPort$1') {
                        $_GET['_glpi_tab'] = 'PluginFusioninventoryNetworkEquipment$1';
                    } else {
                        if ($_GET['_glpi_tab'] == 'PluginFusioninventoryNetworkEquipment$1') {
                            $_GET['displaysnmpinfo'] = 1;
                        }
                    }
                }
            }
            // Load nvd3 for printerpage counter graph
            if (strstr($_SERVER['PHP_SELF'], '/front/printer.form.php') || strstr($_SERVER['PHP_SELF'], 'fusioninventory/front/menu.php')) {
                // Add graph javascript
                $PLUGIN_HOOKS['add_javascript']['fusioninventory'] = array_merge($PLUGIN_HOOKS['add_javascript']['fusioninventory'], array("lib/nvd3/lib/d3.v2.min.js", "lib/nvd3/nv.d3.min.js", "lib/nvd3/src/tooltip.js", "lib/nvd3/src/utils.js", "lib/nvd3/src/models/legend.js", "lib/nvd3/src/models/axis.js", "lib/nvd3/src/models/scatter.js", "lib/nvd3/src/models/line.js", "lib/nvd3/src/models/multiBar.js", "lib/nvd3/src/models/multiBarChart.js", "lib/nvd3/src/models/lineChart.js"));
                // Add graph css
                $PLUGIN_HOOKS['add_css']['fusioninventory'] = array_merge($PLUGIN_HOOKS['add_css']['fusioninventory'], array("lib/nvd3/src/nv.d3.css"));
            }
        }
    } else {
        // plugin not active, need $moduleId for uninstall check
        include_once GLPI_ROOT . '/plugins/fusioninventory/inc/module.class.php';
        $moduleId = PluginFusioninventoryModule::getModuleId('fusioninventory');
    }
    // Check for uninstall
    if (isset($_GET['id']) && $_GET['id'] == $moduleId && (isset($_GET['action']) && $_GET['action'] == 'uninstall') && strstr($_SERVER['HTTP_REFERER'], "front/plugin.php")) {
        if (PluginFusioninventoryModule::getAll(TRUE)) {
            Session::addMessageAfterRedirect(__('Other FusionInventory plugins (fusinv...) must be uninstalled before removing the FusionInventory plugin'));
            Html::redirect($CFG_GLPI["root_doc"] . "/front/plugin.php");
            exit;
        }
    }
    // Add unmanaged devices in list of devices with networport
    $CFG_GLPI["netport_types"][] = "PluginFusioninventoryUnmanaged";
}
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();
}
 static function cronWakeupAgents($crontask)
 {
     global $DB;
     $wakeupArray = array();
     $tasks = array();
     //Get the maximum number of agent to wakeup,
     //as allowed in the general configuration
     $config = new PluginFusioninventoryConfig();
     $maxWakeUp = $config->getValue('wakeup_agent_max');
     $counter = 0;
     $continue = true;
     //Get all active timeslots
     $timeslot = new PluginFusioninventoryTimeslot();
     $timeslots = $timeslot->getCurrentActiveTimeslots();
     if (empty($timeslots)) {
         $query_timeslot = '';
     } else {
         $query_timeslot = "OR (`plugin_fusioninventory_timeslots_id` IN (" . implode(',', $timeslots) . "))";
     }
     //Get all active task requiring an agent wakeup
     //Check all tasks without timeslot or task with a current active timeslot
     $query = "SELECT `id`, `wakeup_agent_counter`, `wakeup_agent_time`, `last_agent_wakeup` \n                 FROM `glpi_plugin_fusioninventory_tasks` \n                 WHERE `wakeup_agent_time` > 0 \n                    AND `wakeup_agent_counter` > 0\n                    AND `is_active`='1' \n                    AND ((`plugin_fusioninventory_timeslots_id`='0') \n                    {$query_timeslot})";
     foreach ($DB->request($query) as $task) {
         if (!is_null($task['wakeup_agent_time'])) {
             //Do not wake up is last wake up in inferior to the minimum wake up interval
             $interval = time() - strtotime($task['last_agent_wakeup']);
             if ($interval < $task['wakeup_agent_time'] * MINUTE_TIMESTAMP) {
                 continue;
             }
         }
         //For each task, get a number of taskjobs at the PREPARED state
         //(the maximum is defined in wakeup_agent_counter)
         $query_states = "SELECT `taskjobstates`.`plugin_fusioninventory_agents_id`, \n                                 `tasks`.`id` as `taskID`, \n                                 `tasks`.`wakeup_agent_time`,\n                                 `tasks`.`last_agent_wakeup`\n                          FROM `glpi_plugin_fusioninventory_taskjobstates` as `taskjobstates`,\n                               `glpi_plugin_fusioninventory_taskjobs` as `taskjobs`\n                          LEFT JOIN `glpi_plugin_fusioninventory_tasks` as `tasks` \n                             ON `tasks`.`id`=`taskjobs`.`plugin_fusioninventory_tasks_id`\n                          WHERE `tasks`.`id`='" . $task['id'] . "' \n                             AND `taskjobs`.`id`=`taskjobstates`.`plugin_fusioninventory_taskjobs_id` \n                             AND `taskjobstates`.`state`='" . PluginFusioninventoryTaskjobstate::PREPARED . "' \n                          ORDER BY `taskjobstates`.`id` ASC LIMIT " . $task['wakeup_agent_counter'];
         foreach ($DB->request($query_states) as $state) {
             $agents_id = $state['plugin_fusioninventory_agents_id'];
             //Check if agent is already added to the list of agents to wake up
             if (!isset($wakeupArray[$agents_id])) {
                 //This agent must be woken up
                 $wakeupArray[$agents_id] = $agents_id;
                 $counter++;
             }
             //Store task ID
             if (!in_array($state['taskID'], $tasks)) {
                 $tasks[] = $state['taskID'];
             }
             //Do not process more than the maximum number of wakeup allowed in the configuration
             if ($counter >= $maxWakeUp) {
                 if (PluginFusioninventoryConfig::isExtradebugActive()) {
                     Toolbox::logDebug(__("Maximum number of agent wakeup reached", 'fusioninventory') . ":" . $maxWakeUp);
                 }
                 $continue = false;
                 break;
             }
         }
         //We've reached the maximum number of agents to wake up !
         if (!$continue) {
             break;
         }
     }
     //Number of agents successfully woken up
     $wokeup = 0;
     $myTask = new PluginFusioninventoryTask();
     if (!empty($tasks)) {
         //Update last wake up time each task
         $query_lastrun = "UPDATE `glpi_plugin_fusioninventory_tasks` \n                           SET `last_agent_wakeup`='" . $_SESSION['glpi_currenttime'] . "' \n                           WHERE `id` IN (" . implode(",", $tasks) . ")";
         $DB->query($query_lastrun);
         $agent = new PluginFusioninventoryAgent();
         //Try to wake up agents one by one
         foreach ($wakeupArray as $ID => $value) {
             $agent->getFromDB($ID);
             if ($agent->wakeUp()) {
                 $wokeup++;
             }
         }
     }
     $crontask->addVolume($wokeup);
     return true;
 }