static function getList($agents_id = NULL)
 {
     global $PF_CONFIG;
     if (is_null($agents_id)) {
         return array();
     }
     $pfAgent = new PluginFusioninventoryAgent();
     $pfAgent->getFromDB($agents_id);
     $agent = $pfAgent->fields;
     $results = getAllDatasFromTable('glpi_plugin_fusioninventory_deploymirrors');
     if (!isset($agent) || !isset($agent['computers_id'])) {
         return array();
     }
     $computer = new Computer();
     $computer->getFromDB($agent['computers_id']);
     $mirrors = array();
     foreach ($results as $result) {
         if ($computer->fields['locations_id'] == $result['locations_id']) {
             $mirrors[] = $result['url'];
         }
     }
     //add default mirror (this server) if enabled in config
     $entities_id = 0;
     if (isset($agent['entities_id'])) {
         $entities_id = $agent['entities_id'];
     }
     if (isset($PF_CONFIG['server_as_mirror']) && (bool) $PF_CONFIG['server_as_mirror'] == TRUE) {
         $mirrors[] = PluginFusioninventoryAgentmodule::getUrlForModule('DEPLOY', $entities_id) . "?action=getFilePart&file=";
     }
     return $mirrors;
 }
 /**
  * Import data
  *
  * @param $p_DEVICEID XML code to import
  * @param $p_CONTENT XML code to import
  * @param $p_xml value XML code to import
  *
  * @return "" (import ok) / error string (import ko)
  *
  **/
 function import($p_DEVICEID, $a_CONTENT, $arrayinventory)
 {
     $pfTaskjobstate = new PluginFusioninventoryTaskjobstate();
     $pfAgent = new PluginFusioninventoryAgent();
     PluginFusioninventoryCommunication::addLog('Function PluginFusioninventoryCommunicationNetworkDiscovery->import().');
     $errors = '';
     $a_agent = $pfAgent->InfosByKey($p_DEVICEID);
     if (isset($a_CONTENT['PROCESSNUMBER'])) {
         $_SESSION['glpi_plugin_fusioninventory_processnumber'] = $a_CONTENT['PROCESSNUMBER'];
         if ($pfTaskjobstate->getFromDB($a_CONTENT['PROCESSNUMBER'])) {
             if ($pfTaskjobstate->fields['state'] != "3") {
                 $pfTaskjobstate->changeStatus($a_CONTENT['PROCESSNUMBER'], 2);
                 if (!isset($a_CONTENT['AGENT']['START']) and !isset($a_CONTENT['AGENT']['END'])) {
                     $nb_devices = 0;
                     if (isset($a_CONTENT['DEVICE'])) {
                         if (is_int(key($a_CONTENT['DEVICE']))) {
                             $nb_devices = count($a_CONTENT['DEVICE']);
                         } else {
                             $nb_devices = 1;
                         }
                     }
                     $_SESSION['plugin_fusinvsnmp_taskjoblog']['taskjobs_id'] = $a_CONTENT['PROCESSNUMBER'];
                     $_SESSION['plugin_fusinvsnmp_taskjoblog']['items_id'] = $a_agent['id'];
                     $_SESSION['plugin_fusinvsnmp_taskjoblog']['itemtype'] = 'PluginFusioninventoryAgent';
                     $_SESSION['plugin_fusinvsnmp_taskjoblog']['state'] = '6';
                     $_SESSION['plugin_fusinvsnmp_taskjoblog']['comment'] = $nb_devices . ' ==devicesfound==';
                     $this->addtaskjoblog();
                 }
             }
         }
     }
     if ($pfTaskjobstate->getFromDB($a_CONTENT['PROCESSNUMBER'])) {
         if ($pfTaskjobstate->fields['state'] != "3") {
             $pfImportExport = new PluginFusioninventorySnmpmodelImportExport();
             $errors .= $pfImportExport->import_netdiscovery($a_CONTENT, $p_DEVICEID);
             if (isset($a_CONTENT['AGENT']['END'])) {
                 if (isset($a_CONTENT['DICO']) and $a_CONTENT['DICO'] == "REQUEST") {
                     $pfAgent->getFromDB($pfTaskjobstate->fields["plugin_fusioninventory_agents_id"]);
                     $input = array();
                     $input['id'] = $pfAgent->fields['id'];
                     $input["senddico"] = "1";
                     $pfAgent->update($input);
                     $pfTaskjobstate->changeStatusFinish($a_CONTENT['PROCESSNUMBER'], $a_agent['id'], 'PluginFusioninventoryAgent', '1', '==diconotuptodate==');
                 } else {
                     $messages = array('Total Found' => 0, 'Created' => 0, 'Updated' => 0);
                     $messages['Updated'] = countElementsInTable('glpi_plugin_fusioninventory_taskjoblogs', "`plugin_fusioninventory_taskjobstates_id`='" . $a_CONTENT['PROCESSNUMBER'] . "' " . " AND `comment` LIKE '%==updatetheitem==%'");
                     $messages['Created'] = countElementsInTable('glpi_plugin_fusioninventory_taskjoblogs', "`plugin_fusioninventory_taskjobstates_id`='" . $a_CONTENT['PROCESSNUMBER'] . "' " . " AND `comment` LIKE '%==addtheitem==%'");
                     $messages['Total Found'] = $messages['Updated'] + $messages['Created'];
                     $message = 'Total Found:' . $messages['Total Found'] . ' Created:' . $messages['Created'] . ' Updated:' . $messages['Updated'];
                     $pfTaskjobstate->changeStatusFinish($a_CONTENT['PROCESSNUMBER'], $a_agent['id'], 'PluginFusioninventoryAgent', '0', $message);
                 }
             }
         }
     }
     return $errors;
 }
 /**
  * @test
  */
 public function prepareDB()
 {
     global $DB;
     $DB->connect();
     $computer = new Computer();
     $pfAgent = new PluginFusioninventoryAgent();
     $pfTask = new PluginFusioninventoryTask();
     $pfTaskjob = new PluginFusioninventoryTaskjob();
     $pfIPRange = new PluginFusioninventoryIPRange();
     // Create computers + agents
     $input = array('entities_id' => 0, 'name' => 'computer1');
     $computers_id = $computer->add($input);
     $input = array('entities_id' => 0, 'name' => 'computer1', 'version' => '{"INVENTORY":"v2.3.11"}', 'device_id' => 'computer1', 'useragent' => 'FusionInventory-Agent_v2.3.11', 'computers_id' => $computers_id);
     $pfAgent->add($input);
     $input = array('entities_id' => 0, 'name' => 'computer2');
     $computers_id = $computer->add($input);
     $input = array('entities_id' => 0, 'name' => 'computer2', 'version' => '{"INVENTORY":"v2.3.11"}', 'device_id' => 'computer2', 'useragent' => 'FusionInventory-Agent_v2.3.11', 'computers_id' => $computers_id);
     $pfAgent->add($input);
     $input = array('entities_id' => 0, 'name' => 'computer3');
     $computers_id = $computer->add($input);
     $input = array('entities_id' => 0, 'name' => 'computer3', 'version' => '{"INVENTORY":"v2.3.11"}', 'device_id' => 'computer3', 'useragent' => 'FusionInventory-Agent_v2.3.11', 'computers_id' => $computers_id);
     $pfAgent->add($input);
     // Add IPRange
     $input = array('entities_id' => 0, 'name' => 'Office', 'ip_start' => '10.0.0.1', 'ip_end' => '10.0.0.254');
     $ipranges_id = $pfIPRange->add($input);
     $input = array('entities_id' => 0, 'name' => 'Office2', 'ip_start' => '10.0.2.1', 'ip_end' => '10.0.2.254');
     $ipranges_id2 = $pfIPRange->add($input);
     // Allow all agents to do network discovery
     $query = "UPDATE `glpi_plugin_fusioninventory_agentmodules` " . " SET `is_active`='1' " . " WHERE `modulename`='NETWORKDISCOVERY'";
     $DB->query($query);
     // create task
     $input = array('entities_id' => 0, 'name' => 'network discovery', 'is_active' => 1);
     $tasks_id = $pfTask->add($input);
     // create taskjob
     $input = array('plugin_fusioninventory_tasks_id' => $tasks_id, 'entities_id' => 0, 'name' => 'discovery', 'method' => 'networkdiscovery', 'targets' => '[{"PluginFusioninventoryIPRange":"' . $ipranges_id . '"}]', 'actors' => '[{"PluginFusioninventoryAgent":"2"}]');
     $pfTaskjob->add($input);
     // create task
     $input = array('entities_id' => 0, 'name' => 'network discovery2', 'is_active' => 1);
     $tasks2_id = $pfTask->add($input);
     // create taskjob
     $input = array('plugin_fusioninventory_tasks_id' => $tasks2_id, 'entities_id' => 0, 'name' => 'discovery', 'method' => 'networkdiscovery', 'targets' => '[{"PluginFusioninventoryIPRange":"' . $ipranges_id2 . '"}]', 'actors' => '[{"PluginFusioninventoryAgent":"3"}]');
     $pfTaskjob->add($input);
 }
 /**
  * @test
  * @dataProvider dataprovider
  */
 public function AddComputer($data)
 {
     $_SESSION['glpiactive_entity'] = 0;
     $_SESSION['glpiactiveentities_string'] = 0;
     $_SESSION['glpishowallentities'] = 1;
     $_SESSION['glpiname'] = 'glpi';
     $pfiComputerInv = new PluginFusioninventoryInventoryComputerInventory();
     $inventory = array();
     $inventory['CONTENT'] = $data['inventory']['CONTENT'];
     // ** Add agent
     $pfAgent = new PluginFusioninventoryAgent();
     $agent_name = $data['inventory']['AGENT']['name'];
     $computer_name = $data['inventory']['CONTENT']['HARDWARE']['NAME'];
     $agents_id = $pfAgent->add($data['inventory']['AGENT']);
     $_SESSION['plugin_fusioninventory_agents_id'] = $agents_id;
     // ** Add
     $pfiComputerInv->import($data['inventory']['AGENT']['device_id'], "", $inventory);
     // creation
     $this->CountSoftwares($data);
     $this->CountVersions($data);
 }
 /**
  * @test
  */
 public function PeripheralUniqueSerialimport()
 {
     global $DB;
     $DB->connect();
     self::restore_database();
     $_SESSION['glpiactive_entity'] = 0;
     $_SESSION["plugin_fusioninventory_entity"] = 0;
     $_SESSION["glpiname"] = 'Plugin_FusionInventory';
     $pfConfig = new PluginFusioninventoryConfig();
     $pfiComputerLib = new PluginFusioninventoryInventoryComputerLib();
     $computer = new Computer();
     $GLPIlog = new GLPIlogs();
     $pxml = @simplexml_load_string($this->a_computer1_XML, 'SimpleXMLElement', LIBXML_NOCDATA);
     $arrayinventory = PluginFusioninventoryFormatconvert::XMLtoArray($pxml);
     $agent = new PluginFusioninventoryAgent();
     $agents_id = $agent->importToken($arrayinventory);
     $_SESSION['plugin_fusioninventory_agents_id'] = $agents_id;
     $pfInventoryComputerInventory = new PluginFusioninventoryInventoryComputerInventory();
     $pfInventoryComputerInventory->import('deviceid', $arrayinventory['CONTENT'], $arrayinventory);
     $computer->getFromDB(1);
     $this->assertEquals('ggheb7ne7', $computer->fields['serial'], 'Computer not updated correctly');
     $a_ref = array(1 => array('name' => 'Périphérique USB composite', 'id' => '1', 'serial' => '10075973', 'peripheraltypes_id' => '0', 'peripheralmodels_id' => '0', 'manufacturers_id' => '2', 'is_global' => '0', 'is_deleted' => '0', 'is_template' => '0', 'is_dynamic' => '0'), 2 => array('name' => 'H5321 gw Mobile Broadband Device', 'id' => '2', 'serial' => '187A047919938CM0', 'peripheraltypes_id' => '0', 'peripheralmodels_id' => '0', 'manufacturers_id' => '7', 'is_global' => '0', 'is_deleted' => '0', 'is_template' => '0', 'is_dynamic' => '0'), 3 => array('name' => 'Périphérique d’entrée USB', 'id' => '3', 'serial' => 'STM32_EMOTION2', 'peripheraltypes_id' => '0', 'peripheralmodels_id' => '0', 'manufacturers_id' => '8', 'is_global' => '0', 'is_deleted' => '0', 'is_template' => '0', 'is_dynamic' => '0'));
     $a_db_peripherals = getAllDatasFromTable('glpi_peripherals');
     foreach ($a_db_peripherals as $id => $data) {
         $data_temp = array('name' => $data['name'], 'id' => $data['id'], 'serial' => $data['serial'], 'peripheraltypes_id' => $data['peripheraltypes_id'], 'peripheralmodels_id' => $data['peripheralmodels_id'], 'manufacturers_id' => $data['manufacturers_id'], 'is_global' => $data['is_global'], 'is_deleted' => $data['is_deleted'], 'is_template' => $data['is_template'], 'is_dynamic' => $data['is_dynamic']);
         $a_db_peripherals[$id] = $data_temp;
     }
     $this->assertEquals($a_ref, $a_db_peripherals, 'List of peripherals');
     // Update computer and may not have new values in glpi_logs
     $query = "SELECT * FROM `glpi_logs`\n         ORDER BY `id` DESC LIMIT 1";
     $result = $DB->query($query);
     $data = $DB->fetch_assoc($result);
     $last_id = $data['id'];
     $pfInventoryComputerInventory->import('deviceid', $arrayinventory['CONTENT'], $arrayinventory);
     $data = getAllDatasFromTable('glpi_logs', "`id`>'" . $last_id . "'");
     $this->assertEquals(array(), $data, 'On update peripherals, may not have new lines in glpi_logs');
 }
 /**
  * @test
  */
 public function prepareDB()
 {
     global $DB;
     $DB->connect();
     $_SESSION['glpiactive_entity'] = 0;
     $_SESSION["plugin_fusioninventory_entity"] = 0;
     $_SESSION["glpiname"] = 'Plugin_FusionInventory';
     $query = "INSERT INTO `glpi_entities` " . " (`id`, `name`, `entities_id`, `level`) " . " VALUES ('1', 'ent1', '0', '2')";
     $DB->query($query);
     $entities_id = 1;
     $pfAgent = new PluginFusioninventoryAgent();
     $input = array('name' => 'toto', 'entities_id' => $entities_id, 'device_id' => 'toto-device');
     $agents_id = $pfAgent->add($input);
     $config = new PluginFusioninventoryConfig();
     $config->loadCache();
     $pfEntity = new PluginFusioninventoryEntity();
     $input = array('id' => 1, 'entities_id' => 0, 'agent_base_url' => 'http://127.0.0.1/glpi085');
     $pfEntity->update($input);
     $input = array('entities_id' => $entities_id, 'agent_base_url' => 'http://10.0.2.2/glpi085');
     $pfEntity->add($input);
     // active all modules
     $query = "UPDATE `glpi_plugin_fusioninventory_agentmodules`" . " SET `is_active`='1'";
     $DB->query($query);
 }
 function showJobLogs()
 {
     $refresh_intervals = array("off" => __('Off', 'fusioninventory'), "1" => '1 ' . _n('second', 'seconds', 1), "5" => '5 ' . _n('second', 'seconds', 5), "10" => '10 ' . _n('second', 'seconds', 10), "60" => '1 ' . _n('minute', 'minutes', 1), "120" => '2 ' . _n('minute', 'minutes', 2), "300" => '5 ' . _n('minute', 'minutes', 5), "600" => '10 ' . _n('minute', 'minutes', 10));
     echo "<div class='fusinv_panel'>";
     echo "   <div class='fusinv_form large'>";
     $refresh_randid = $this->showDropdownFromArray(__("refresh interval", "fusioninventory"), null, $refresh_intervals, array('value' => 'off', 'width' => '20%'));
     // Add a manual refresh button
     echo "      <div class='refresh_button submit'>";
     echo "      <span></span></div>";
     echo "   </div>";
     // end of fusinv_form
     echo "</div>";
     //$pfTaskjob = new PluginFusioninventoryTaskjob();
     //$taskjobs = $pfTaskjob->find(
     //   "`plugin_fusioninventory_tasks_id`='".$this->fields['id']."'",
     //   "id"
     //);
     // Template structure for tasks' blocks
     echo implode("\n", array("<script id='template_task' type='x-tmpl-mustache'>", "<div id='{{task_id}}' class='task_block {{expanded}}'>", "  <h3>" . __("Task", 'fusioninventory') . " <span class='task_name'>{{task_name}}</span></h3>", "  <div class='jobs_block'></div>", "</div>", "</script>"));
     // Template structure for jobs' blocks
     echo implode("\n", array("<script id='template_job' type='x-tmpl-mustache'>", "<div id='{{job_id}}' class='job_block'>", "  <div class='refresh_button submit'><span></span></div>", "  <h3 class='job_name'>{{job_name}}</h3>", "  <div class='targets_block'></div>", "</div>", "</script>"));
     // Template structure for targets' blocks
     echo implode("\n", array("<script id='template_target' type='x-tmpl-mustache'>", "<div id='{{target_id}}' class='target_block'>", "  <div class='target_details'>", "  <div class='target_infos'>", "     <h4 class='target_name'>", "        <a target='_blank' href={{target_link}}>", "          {{target_name}}", "        </a>", "     </h4>", "     <div class='target_stats'>", "     </div>", "  </div>", "  <div class='progressbar'></div>", "  </div>", "  <div class='show_more'></div>", "  <div class='agents_block'></div>", "  <div class='show_more'></div>", "</script>"));
     // Template structure for targets' statistics
     echo implode("\n", array("<script id='template_target_stats' type='x-tmp-mustache'>", "  <div class='{{stats_type}} stats_block'>", "  </div>", "</script>"));
     // Template for counters' blocks
     echo implode("\n", array("<script id='template_counter_block' type='x-tmpl-mustache'>", "<div class='counter_block {{counter_type}} {{#counter_empty}}empty{{/counter_empty}}'>", "<a", "  href='javascript:void(0)'", "  class='' ", "  title='" . __("Show/Hide details", "fusioninventory") . "'", "  onclick='taskjobs.toggle_details_type(this, \"{{counter_type}}\", \"{{chart_id}}\")'", ">", "<div class='fold'></div>", "<span class='counter_name'>{{counter_type_name}}</span>", "<span class='counter_value'>{{counter_value}}</span>", "</div>", "</a>", "</script>"));
     /*
      * List of counter names
      */
     echo implode("\n", array("<script type='text/javascript'>", "  taskjobs.statuses_order = {", "     last_executions : [", "        'agents_prepared',", "        'agents_running',", "        'agents_cancelled'", "     ],", "     last_finish_states : [", "        'agents_notdone',", "        'agents_success',", "        'agents_error'", "     ]", "  };", "  taskjobs.statuses_names = {", "     'agents_notdone'   : '" . __('Not done yet', 'fusioninventory') . "',", "     'agents_error'     : '" . __('In error', 'fusioninventory') . "',", "     'agents_success'   : '" . __('Successful', 'fusioninventory') . "',", "     'agents_running'   : '" . __('Running', 'fusioninventory') . "',", "     'agents_prepared'  : '" . __('Prepared', 'fusioninventory') . "',", "     'agents_cancelled' : '" . __('Cancelled', 'fusioninventory') . "',", "  };", "  taskjobs.logstatuses_names = " . json_encode(PluginFusioninventoryTaskjoblog::dropdownStateValues()) . ";", "</script>"));
     // Template for agents' blocks
     echo implode("\n", array("<script id='template_agent' type='x-tmpl-mustache'>", "<div class='agent_block' id='{{agent_id}}'>", "  <div class='status {{status.last_exec}}'></span>", "  <div class='status {{status.last_finish}}'></span>", "</div>", "</script>"));
     // Display empty block for each jobs display which will be rendered later by mustache.js
     echo implode("\n", array("<div class='tasks_block'>", "</div>"));
     if (isset($this->fields['id'])) {
         $task_id = $this->fields['id'];
     } else {
         $task_id = json_encode(array());
     }
     $pfAgent = new PluginFusioninventoryAgent();
     $Computer = new Computer();
     echo implode("\n", array("<script type='text/javascript'>", "  taskjobs.agents_url = '" . $pfAgent->getFormUrl() . "'", "  taskjobs.computers_url = '" . $Computer->getFormUrl() . "'", "  taskjobs.init_templates();", "  taskjobs.init_refresh_form(", "     '" . $this->getBaseUrlFor('fi.job.logs') . "',", "     " . $task_id . ",", "     'dropdown_" . $refresh_randid . "'", "  );", "  taskjobs.update_logs_timeout(", "     '" . $this->getBaseUrlFor('fi.job.logs') . "',", "     " . $task_id . ",", "     'dropdown_" . $refresh_randid . "'", "  );", "</script>"));
 }
 /**
  * Get agents can do a "module name"
  *
  * @param $module_name value Name of the module
  *
  * @return array of agents
  *
  **/
 function getAgentsCanDo($module_name)
 {
     $pfAgent = new PluginFusioninventoryAgent();
     if ($module_name == 'SNMPINVENTORY') {
         $module_name = 'SNMPQUERY';
     }
     $agentModule = $this->getActivationExceptions($module_name);
     $where = "";
     if ($agentModule['is_active'] == 0) {
         $a_agentList = importArrayFromDB($agentModule['exceptions']);
         if (count($a_agentList) > 0) {
             $where = " `id` IN (";
             $i = 0;
             $sep = '';
             foreach ($a_agentList as $agent_id) {
                 if ($i > 0) {
                     $sep = ', ';
                 }
                 $where .= $sep . $agent_id;
                 $i++;
             }
             $where .= ") ";
             if (isset($_SESSION['glpiactiveentities_string'])) {
                 $where .= getEntitiesRestrictRequest("AND", $pfAgent->getTable());
             }
         } else {
             return array();
         }
     } else {
         $a_agentList = importArrayFromDB($agentModule['exceptions']);
         if (count($a_agentList) > 0) {
             $where = " `id` NOT IN (";
             $i = 0;
             $sep = '';
             foreach ($a_agentList as $agent_id) {
                 if ($i > 0) {
                     $sep = ', ';
                 }
                 $where .= $sep . $agent_id;
                 $i++;
             }
             $where .= ") ";
             if (isset($_SESSION['glpiactiveentities_string'])) {
                 $where .= getEntitiesRestrictRequest("AND", $pfAgent->getTable());
             }
         }
     }
     $a_agents = $pfAgent->find($where);
     return $a_agents;
 }
 /**
  * @test
  */
 public function PrinterToInventoryWithoutIP()
 {
     self::restore_database();
     $printer = new Printer();
     $networkport = new NetworkPort();
     $networkName = new NetworkName();
     $pfPrinter = new PluginFusioninventoryPrinter();
     $pfTask = new PluginFusioninventoryTask();
     $pfTaskjob = new PluginFusioninventoryTaskjob();
     $computer = new Computer();
     $pfAgent = new PluginFusioninventoryAgent();
     $communication = new PluginFusioninventoryCommunication();
     // Create computers + agents
     $input = array('entities_id' => 0, 'name' => 'computer1');
     $computers_id = $computer->add($input);
     $input = array('entities_id' => 0, 'name' => 'computer1', 'version' => '{"INVENTORY":"v2.3.11"}', 'device_id' => 'computer1', 'useragent' => 'FusionInventory-Agent_v2.3.11', 'computers_id' => $computers_id);
     $pfAgent->add($input);
     // Create printer
     $input = array('name' => 'printer 001', 'entities_id' => 0);
     $printers_id = $printer->add($input);
     // Add port
     $networkports_id = $networkport->add(array('itemtype' => 'Printer', 'instantiation_type' => 'NetworkPortEthernet', 'items_id' => $printers_id, 'entities_id' => 0));
     $networknames_id = $networkName->add(array('entities_id' => 0, 'itemtype' => 'NetworkPort', 'items_id' => $networkports_id));
     $input = array('printers_id' => 1, 'plugin_fusioninventory_configsecurities_id' => 2);
     $pfPrinter->add($input);
     // Add task
     // create task
     $input = array('entities_id' => 0, 'name' => 'network inventory', 'is_active' => 1);
     $tasks_id = $pfTask->add($input);
     // create taskjob
     $input = array('plugin_fusioninventory_tasks_id' => $tasks_id, 'entities_id' => 0, 'name' => 'inventory', 'method' => 'networkinventory', 'targets' => '[{"Printer":"' . $printers_id . '"}]', 'actors' => '[{"PluginFusioninventoryAgent":"1"}]');
     $pfTaskjob->add($input);
     PluginFusioninventoryTask::cronTaskscheduler();
     $data = $pfTask->getJoblogs(array(1));
     // Task is prepared
     // Agent will get data
     $communication->getTaskAgent(1);
     $message = $communication->getMessage();
     $json = json_encode($message);
     $array = json_decode($json, TRUE);
     $ref = array();
     $this->assertEquals($ref, $array, 'XML of SNMP inventory task');
 }
  @link      http://www.fusioninventory.org/
  @link      http://forge.fusioninventory.org/projects/fusioninventory-for-glpi/
  @since     2010

  ------------------------------------------------------------------------
*/
ob_start();
include "../../../../inc/includes.php";
ob_end_clean();
$response = FALSE;
//Agent communication using REST protocol
if (isset($_GET['action'])) {
    switch ($_GET['action']) {
        case 'getJobs':
            if (isset($_GET['machineid'])) {
                $pfAgent = new PluginFusioninventoryAgent();
                $pfAgentModule = new PluginFusioninventoryAgentModule();
                $pfTask = new PluginFusioninventoryTask();
                $pfTaskjob = new PluginFusioninventoryTaskjob();
                $pfTaskjobstate = new PluginFusioninventoryTaskjobstate();
                $agent = $pfAgent->InfosByKey(Toolbox::addslashes_deep($_GET['machineid']));
                if (isset($agent['id'])) {
                    $taskjobstates = $pfTask->getTaskjobstatesForAgent($agent['id'], array('deployinstall', 'deployuninstall'));
                    if (!$pfAgentModule->isAgentCanDo("DEPLOY", $agent['id'])) {
                        foreach ($taskjobstates as $taskjobstate) {
                            $taskjobstate->cancel(__("Deploy module has been disabled for this agent", 'fusioninventory'));
                        }
                        $response = "{}";
                    } else {
                        //sort taskjobs by key id
                        /**
 function run($jobstate)
 {
     $pfAgent = new PluginFusioninventoryAgent();
     $pfTaskjobstate = new PluginFusioninventoryTaskjobstate();
     $pfTaskjoblog = new PluginFusioninventoryTaskjoblog();
     $pfConfigSecurity = new PluginFusioninventoryConfigSecurity();
     $pfToolbox = new PluginFusioninventoryToolbox();
     $current = $jobstate;
     $pfAgent->getFromDB($current->fields['plugin_fusioninventory_agents_id']);
     $ip = current(PluginFusioninventoryToolbox::getIPforDevice($jobstate->fields['itemtype'], $jobstate->fields['items_id']));
     if ($ip == '') {
         $pfTaskjobstate->changeStatusFinish($jobstate->fields['id'], $jobstate->fields['items_id'], $jobstate->fields['itemtype'], 1, "Device have no ip");
     } else {
         $sxml_option = $this->message->addChild('OPTION');
         $sxml_option->addChild('NAME', 'SNMPQUERY');
         $sxml_param = $sxml_option->addChild('PARAM');
         $sxml_param->addAttribute('THREADS_QUERY', $pfAgent->fields["threads_networkinventory"]);
         $sxml_param->addAttribute('TIMEOUT', $pfAgent->fields["timeout_networkinventory"]);
         $sxml_param->addAttribute('PID', $current->fields['id']);
         $changestate = 0;
         $taskjobstatedatas = $jobstate->fields;
         $sxml_device = $sxml_option->addChild('DEVICE');
         $a_extended = array('plugin_fusioninventory_configsecurities_id' => 0);
         if ($jobstate->fields['itemtype'] == 'Printer') {
             $sxml_device->addAttribute('TYPE', 'PRINTER');
             $pfPrinter = new PluginFusioninventoryPrinter();
             $a_extended = current($pfPrinter->find("`printers_id`='" . $jobstate->fields['items_id'] . "'", '', 1));
         } else {
             if ($jobstate->fields['itemtype'] == 'NetworkEquipment') {
                 $sxml_device->addAttribute('TYPE', 'NETWORKING');
                 $pfNetworkEquipment = new PluginFusioninventoryNetworkEquipment();
                 $a_extended = current($pfNetworkEquipment->find("`networkequipments_id`='" . $jobstate->fields['items_id'] . "'", '', 1));
             }
         }
         $sxml_device->addAttribute('ID', $jobstate->fields['items_id']);
         $sxml_device->addAttribute('IP', $ip);
         $sxml_device->addAttribute('AUTHSNMP_ID', $a_extended['plugin_fusioninventory_configsecurities_id']);
         if ($changestate == '0') {
             $pfTaskjobstate->changeStatus($taskjobstatedatas['id'], 1);
             $pfTaskjoblog->addTaskjoblog($taskjobstatedatas['id'], '0', 'PluginFusioninventoryAgent', '1', $pfAgent->fields["threads_networkinventory"] . ' threads', $pfAgent->fields["timeout_networkinventory"] . ' timeout');
             $changestate = $pfTaskjobstate->fields['id'];
         } else {
             $pfTaskjobstate->changeStatusFinish($taskjobstatedatas['id'], $taskjobstatedatas['items_id'], $taskjobstatedatas['itemtype'], 0, "Merged with " . $changestate);
         }
         $snmpauthlist = $pfConfigSecurity->find();
         if (count($snmpauthlist)) {
             foreach ($snmpauthlist as $snmpauth) {
                 $pfToolbox->addAuth($sxml_option, $snmpauth['id']);
             }
         }
     }
     return $this->message;
 }
 /**
  * @test
  */
 public function AddComputerStep3()
 {
     global $DB;
     $this->mark_incomplete();
     return;
     // TODO: recode this test
     $DB->connect();
     $DB->query("UPDATE `glpi_entities`\n         SET `entities_id_software` = '-2'\n         WHERE `id`='1'");
     $_SESSION['glpiactive_entity'] = 0;
     $_SESSION['glpiactiveentities_string'] = 0;
     $_SESSION['glpishowallentities'] = 1;
     $_SESSION['glpiname'] = 'glpi';
     $pfiComputerInv = new PluginFusioninventoryInventoryComputerInventory();
     $computer = new Computer();
     $software = new Software();
     $input = array('id' => 1, 'is_recursive' => 0);
     $software->update($input);
     $computer->add(array('name' => 'pc2', 'entities_id' => 1));
     $a_inventory = array();
     $a_inventory['CONTENT']['HARDWARE'] = array('NAME' => 'pc2');
     $a_inventory['CONTENT']['SOFTWARES'][] = array('COMMENTS' => "Non-interactive tool to get files from FTP, GOPHER, HTTP(S)", 'NAME' => "curl", 'VERSION' => "7.24.0_1");
     // ** Add agent
     $pfAgent = new PluginFusioninventoryAgent();
     $a_agents_id = $pfAgent->add(array('name' => 'pc-2013-02-13', 'device_id' => 'pc-2013-02-13'));
     $_SESSION['plugin_fusioninventory_agents_id'] = $a_agents_id;
     // ** Add
     $pfiComputerInv->import("pc2-2013-02-13", "", $a_inventory);
     // creation
     $computer->getFromDB(2);
     $this->assertEquals(1, $computer->fields['entities_id'], 'Add computer');
     $nbSoftwares = countElementsInTable("glpi_softwares");
     $softs = getAllDatasFromTable("glpi_softwares");
     $this->assertEquals(2, $nbSoftwares, 'Nb softwares ' . print_r($softs, true));
     $software->getFromDB(2);
     $this->assertEquals(1, $software->fields['entities_id'], "May be on entity 1");
     // Software not in same entity as computer, may be recursive
     $this->assertEquals(0, $software->fields['is_recursive'], 'Software may have recursive = 0');
 }
 function prepareRun($taskjob_id, $definitions_filter = NULL)
 {
     global $DB;
     $task = new PluginFusioninventoryTask();
     $job = new PluginFusioninventoryTaskjob();
     $joblog = new PluginFusioninventoryTaskjoblog();
     $jobstate = new PluginFusioninventoryTaskjobstate();
     $agent = new PluginFusioninventoryAgent();
     $agentmodule = new PluginFusioninventoryAgentmodule();
     $job->getFromDB($taskjob_id);
     $task->getFromDB($job->fields['plugin_fusioninventory_tasks_id']);
     $communication = $task->fields['communication'];
     $actions = importArrayFromDB($job->fields['action']);
     $definitions = importArrayFromDB($job->fields['definition']);
     $taskvalid = 0;
     $computers = array();
     foreach ($actions as $action) {
         $itemtype = key($action);
         $items_id = current($action);
         switch ($itemtype) {
             case 'Computer':
                 if ($this->definitionFiltered("Computer", $definitions_filter)) {
                     break;
                 }
                 $computers[] = $items_id;
                 break;
             case 'Group':
                 if ($this->definitionFiltered("Group", $definitions_filter)) {
                     break;
                 }
                 $computer_object = new Computer();
                 //find computers by user associated with this group
                 $group_users = new Group_User();
                 $group = new Group();
                 $group->getFromDB($items_id);
                 $members = array();
                 $computers_a_1 = array();
                 $computers_a_2 = array();
                 //array_keys($group_users->find("groups_id = '$items_id'"));
                 $members = $group_users->getGroupUsers($items_id);
                 foreach ($members as $member) {
                     $computers = $computer_object->find("users_id = '{$member['id']}' " . " AND `is_deleted`='0' AND `is_template`='0'");
                     foreach ($computers as $computer) {
                         $computers_a_1[] = $computer['id'];
                     }
                 }
                 //find computers directly associated with this group
                 $computers = $computer_object->find("groups_id = '{$items_id}' " . " AND `is_deleted`='0' AND `is_template`='0'");
                 foreach ($computers as $computer) {
                     $computers_a_2[] = $computer['id'];
                 }
                 //merge two previous array and deduplicate entries
                 $computers = array_unique(array_merge($computers_a_1, $computers_a_2));
                 break;
             case 'PluginFusioninventoryDeployGroup':
                 $group = new PluginFusioninventoryDeployGroup();
                 $group->getFromDB($items_id);
                 switch ($group->getField('type')) {
                     case 'STATIC':
                         if ($this->definitionFiltered("PluginFusioninventoryDeployGroupStatic", $definitions_filter)) {
                             break;
                         }
                         $query = "SELECT items_id\n                     FROM glpi_plugin_fusioninventory_deploygroups_staticdatas\n                     WHERE groups_id = '{$items_id}'\n                     AND itemtype = 'Computer'";
                         $res = $DB->query($query);
                         while ($row = $DB->fetch_assoc($res)) {
                             $computers[] = $row['items_id'];
                         }
                         break;
                     case 'DYNAMIC':
                         if ($this->definitionFiltered("PluginFusioninventoryDeployGroupDynamic", $definitions_filter)) {
                             break;
                         }
                         //$definitions_filter is NULL = update by crontask !
                         if ($definitions_filter != NULL) {
                             $where = " AND `can_update_group`='1'";
                         } else {
                             $where = "";
                         }
                         $query = "SELECT fields_array\n                     FROM glpi_plugin_fusioninventory_deploygroups_dynamicdatas\n                     WHERE groups_id = '{$items_id}' {$where}\n                     LIMIT 1";
                         $res = $DB->query($query);
                         $row = $DB->fetch_assoc($res);
                         //No dynamic groups have been found : break
                         if ($DB->numrows($res) == 0) {
                             break;
                         }
                         if (isset($_GET)) {
                             $get_tmp = $_GET;
                         }
                         if (isset($_SESSION["glpisearchcount"]['Computer'])) {
                             unset($_SESSION["glpisearchcount"]['Computer']);
                         }
                         if (isset($_SESSION["glpisearchcount2"]['Computer'])) {
                             unset($_SESSION["glpisearchcount2"]['Computer']);
                         }
                         $_GET = importArrayFromDB($row['fields_array']);
                         $_GET["glpisearchcount"] = count($_GET['field']);
                         if (isset($_GET['field2'])) {
                             $_GET["glpisearchcount2"] = count($_GET['field2']);
                         }
                         $pfSearch = new PluginFusioninventorySearch();
                         Search::manageParams('Computer');
                         $glpilist_limit = $_SESSION['glpilist_limit'];
                         $_SESSION['glpilist_limit'] = 999999999;
                         $result = $pfSearch->constructSQL('Computer', $_GET);
                         $_SESSION['glpilist_limit'] = $glpilist_limit;
                         while ($data = $DB->fetch_array($result)) {
                             $computers[] = $data['id'];
                         }
                         if (count($get_tmp) > 0) {
                             $_GET = $get_tmp;
                         }
                         break;
                 }
                 break;
         }
     }
     //Remove duplicatas from array
     //We are using isset for faster processing than array_unique because we might have many
     //entries in this list.
     $tmp_computers = array();
     foreach ($computers as $computer) {
         if (!isset($tmp_computers[$computer])) {
             $tmp_computers[$computer] = 1;
         }
     }
     $computers = array_keys($tmp_computers);
     $c_input = array();
     $c_input['plugin_fusioninventory_taskjobs_id'] = $job->fields['id'];
     $c_input['state'] = 0;
     $c_input['plugin_fusioninventory_agents_id'] = 0;
     $c_input['execution_id'] = $task->fields['execution_id'];
     $package = new PluginFusioninventoryDeployPackage();
     foreach ($computers as $computer_id) {
         //Unique Id match taskjobstatuses for an agent(computer)
         foreach ($definitions as $definition) {
             $uniqid = uniqid();
             $package->getFromDB($definition['PluginFusioninventoryDeployPackage']);
             $c_input['state'] = 0;
             $c_input['itemtype'] = 'PluginFusioninventoryDeployPackage';
             $c_input['items_id'] = $package->fields['id'];
             $c_input['date'] = date("Y-m-d H:i:s");
             $c_input['uniqid'] = $uniqid;
             //get agent for this computer
             $agents_id = $agent->getAgentWithComputerid($computer_id);
             if ($agents_id === FALSE) {
                 $jobstates_id = $jobstate->add($c_input);
                 $jobstate->changeStatusFinish($jobstates_id, 0, '', 1, "No agent found for [[Computer::" . $computer_id . "]]", 0, 0);
             } else {
                 if ($agentmodule->isAgentCanDo('DEPLOY', $agents_id)) {
                     $c_input['plugin_fusioninventory_agents_id'] = $agents_id;
                     $jobstates_running = $jobstate->find(implode(" ", array("    `itemtype` = 'PluginFusioninventoryDeployPackage'", "AND `items_id` = " . $package->fields['id'], "AND `state` <> " . PluginFusioninventoryTaskjobstate::FINISHED, "AND `plugin_fusioninventory_agents_id` = " . $agents_id)));
                     if (count($jobstates_running) == 0) {
                         # Push the agent, in the stack of agent to awake
                         if ($communication == "push") {
                             $_SESSION['glpi_plugin_fusioninventory']['agents'][$agents_id] = 1;
                         }
                         $jobstates_id = $jobstate->add($c_input);
                         //Add log of taskjob
                         $c_input['plugin_fusioninventory_taskjobstates_id'] = $jobstates_id;
                         $c_input['state'] = PluginFusioninventoryTaskjoblog::TASK_PREPARED;
                         $taskvalid++;
                         $joblog->add($c_input);
                         unset($c_input['state']);
                         unset($c_input['plugin_fusioninventory_agents_id']);
                     }
                 }
             }
         }
     }
     if ($taskvalid > 0) {
         $job->fields['status'] = 1;
         $job->update($job->fields);
     } else {
         $job->reinitializeTaskjobs($job->fields['plugin_fusioninventory_tasks_id']);
     }
 }
 function run($jobstate)
 {
     $pfAgent = new PluginFusioninventoryAgent();
     $pfTaskjobstate = new PluginFusioninventoryTaskjobstate();
     $pfTaskjob = new PluginFusioninventoryTaskjob();
     $pfTaskjoblog = new PluginFusioninventoryTaskjoblog();
     $pfIPRange = new PluginFusioninventoryIPRange();
     $pfConfigSecurity = new PluginFusioninventoryConfigSecurity();
     $pfToolbox = new PluginFusioninventoryToolbox();
     $pfAgent->getFromDB($jobstate->fields['plugin_fusioninventory_agents_id']);
     $sxml_option = $this->message->addChild('OPTION');
     $sxml_option->addChild('NAME', 'NETDISCOVERY');
     $a_versions = importArrayFromDB($pfAgent->fields["version"]);
     // * Disabled by David Durieux, I think it's not required now * //
     //      if (((isset($a_versions["NETWORKDISCOVERY"])) AND ($a_versions["NETWORKDISCOVERY"] >= 1.3))
     //              OR !isset($a_versions["NETWORKDISCOVERY"])) {
     //         if (!file_exists(GLPI_PLUGIN_DOC_DIR."/fusioninventory/discovery.xml")) {
     //            PluginFusioninventorySnmpmodelImportExport::exportDictionnaryFile(FALSE);
     //         }
     //         $sxml_option->addChild('DICOHASH',
     //                                md5_file(GLPI_PLUGIN_DOC_DIR."/fusioninventory/discovery.xml"));
     //      }
     //      if (($pfAgent->fields["senddico"] == "1")) {
     //
     //         if (((isset($a_versions["NETWORKDISCOVERY"]))
     //                 AND ($a_versions["NETWORKDISCOVERY"] >= 1.3))) {
     //
     //            $sxml_option->addChild('DICO',
     //                                   file_get_contents(
     //                                           GLPI_PLUGIN_DOC_DIR."/fusioninventory/discovery.xml"));
     //         }
     //         $input = array();
     //         $input['id'] = $pfAgent->fields['id'];
     //         $input["senddico"] = "0";
     //         $pfAgent->update($input);
     //      }
     $sxml_param = $sxml_option->addChild('PARAM');
     $sxml_param->addAttribute('THREADS_DISCOVERY', $pfAgent->fields["threads_networkdiscovery"]);
     $sxml_param->addAttribute('TIMEOUT', $pfAgent->fields["timeout_networkdiscovery"]);
     $sxml_param->addAttribute('PID', $jobstate->fields['id']);
     $changestate = 0;
     //foreach ($a_Taskjobstates as $taskjobstate) {
     $taskjobstatedatas = $jobstate->fields;
     $sxml_rangeip = $sxml_option->addChild('RANGEIP');
     $pfTaskjob->getFromDB($taskjobstatedatas['plugin_fusioninventory_taskjobs_id']);
     $pfTaskjobstate->getFromDB($taskjobstatedatas['id']);
     $pfIPRange->getFromDB($taskjobstatedatas['items_id']);
     $sxml_rangeip->addAttribute('ID', $pfIPRange->fields['id']);
     if (!is_null($pfTaskjobstate->fields['specificity'])) {
         $a_split = explode("-", $pfTaskjobstate->fields['specificity']);
         $first_ip = $pfIPRange->getIp2long($pfIPRange->fields["ip_start"]);
         $last_ip = long2ip($first_ip + $a_split[1]);
         $first_ip = long2ip($first_ip + $a_split[0]);
         if ($first_ip != '0.0.0.0' && $last_ip != '0.0.0.0') {
             $sxml_rangeip->addAttribute('IPSTART', $first_ip);
             $sxml_rangeip->addAttribute('IPEND', $last_ip);
         }
     } else {
         $sxml_rangeip->addAttribute('IPSTART', $pfIPRange->fields["ip_start"]);
         $sxml_rangeip->addAttribute('IPEND', $pfIPRange->fields["ip_end"]);
     }
     $sxml_rangeip->addAttribute('ENTITY', $pfIPRange->fields["entities_id"]);
     if ($changestate == '0') {
         $pfTaskjobstate->changeStatus($pfTaskjobstate->fields['id'], 1);
         $pfTaskjoblog->addTaskjoblog($pfTaskjobstate->fields['id'], '0', 'PluginFusioninventoryAgent', '1', $pfAgent->fields["threads_networkdiscovery"] . ' threads', $pfAgent->fields["timeout_networkdiscovery"] . ' timeout');
         $changestate = $pfTaskjobstate->fields['id'];
     } else {
         $pfTaskjobstate->changeStatusFinish($pfTaskjobstate->fields['id'], $taskjobstatedatas['items_id'], $taskjobstatedatas['itemtype'], 0, "Merged with " . $changestate);
     }
     //}
     $pfIPRange_ConfigSecurity = new PluginFusioninventoryIPRange_ConfigSecurity();
     $a_auths = $pfIPRange_ConfigSecurity->find("`plugin_fusioninventory_ipranges_id`='" . $pfIPRange->fields['id'] . "'", "rank");
     foreach ($a_auths as $dataAuth) {
         $pfToolbox->addAuth($sxml_option, $dataAuth['plugin_fusioninventory_configsecurities_id']);
     }
     return $this->message;
 }
 /**
  * Import the content (where have all devices)
  *@param $p_content CONTENT code to import
  *
  *@return errors string to be alimented if import ko / '' if ok
  **/
 function importContent($arrayinventory)
 {
     PluginFusioninventoryCommunication::addLog('Function PluginFusioninventoryCommunicationNetworkInventory->importContent().');
     $pfAgent = new PluginFusioninventoryAgent();
     $errors = '';
     $nbDevices = 0;
     foreach ($arrayinventory as $childname => $child) {
         PluginFusioninventoryCommunication::addLog($childname);
         switch ($childname) {
             case 'DEVICE':
                 $a_devices = array();
                 if (is_int(key($child))) {
                     $a_devices = $child;
                 } else {
                     $a_devices[] = $child;
                 }
                 $xml_num = 0;
                 foreach ($a_devices as $dchild) {
                     $_SESSION['plugin_fusioninventory_xmlnum'] = $xml_num;
                     $a_inventory = array();
                     if (isset($dchild['INFO'])) {
                         if ($dchild['INFO']['TYPE'] == "NETWORKING") {
                             $a_inventory = PluginFusioninventoryFormatconvert::networkequipmentInventoryTransformation($dchild);
                         } else {
                             if ($dchild['INFO']['TYPE'] == "PRINTER") {
                                 $a_inventory = PluginFusioninventoryFormatconvert::printerInventoryTransformation($dchild);
                             }
                         }
                     }
                     if (isset($dchild['ERROR'])) {
                         $itemtype = "";
                         if ($dchild['ERROR']['TYPE'] == "NETWORKING") {
                             $itemtype = "NetworkEquipment";
                         } else {
                             if ($dchild['ERROR']['TYPE'] == "PRINTER") {
                                 $itemtype = "Printer";
                             }
                         }
                         $_SESSION['plugin_fusinvsnmp_taskjoblog']['comment'] = '[==detail==] ' . $dchild['ERROR']['MESSAGE'] . ' [[' . $itemtype . '::' . $dchild['ERROR']['ID'] . ']]';
                         $this->addtaskjoblog();
                     } else {
                         if ($a_inventory['PluginFusioninventory' . $a_inventory['itemtype']]['sysdescr'] == '' && $a_inventory[$a_inventory['itemtype']]['name'] == '' && $a_inventory[$a_inventory['itemtype']]['serial'] == '') {
                             $_SESSION['plugin_fusinvsnmp_taskjoblog']['comment'] = '[==detail==] No informations [[' . $a_inventory['itemtype'] . '::' . $dchild['INFO']['ID'] . ']]';
                             $this->addtaskjoblog();
                         } else {
                             if (count($a_inventory) > 0) {
                                 $errors .= $this->sendCriteria($a_inventory);
                                 $nbDevices++;
                             }
                         }
                     }
                     $xml_num++;
                 }
                 break;
             case 'AGENT':
                 if (isset($this->arrayinventory['CONTENT']['AGENT']['AGENTVERSION'])) {
                     $agent = $pfAgent->InfosByKey($this->arrayinventory['DEVICEID']);
                     $agent['fusioninventory_agent_version'] = $this->arrayinventory['CONTENT']['AGENT']['AGENTVERSION'];
                     $agent['last_agent_update'] = date("Y-m-d H:i:s");
                     $pfAgent->update($agent);
                 }
                 break;
             case 'PROCESSNUMBER':
                 break;
             case 'MODULEVERSION':
                 break;
             default:
                 $_SESSION['plugin_fusinvsnmp_taskjoblog']['comment'] = '[==detail==] ' . __('Unattended element in', 'fusioninventory') . ' CONTENT : ' . $childname;
                 $this->addtaskjoblog();
         }
     }
     return $errors;
 }
 /**
  * If rule have found computer or rule give to create computer
  *
  * @param $items_id integer id of the computer found (or 0 if must be created)
  * @param $itemtype value Computer type here
  *
  * @return nothing
  *
  **/
 function rulepassed($items_id, $itemtype)
 {
     global $DB, $PLUGIN_FUSIONINVENTORY_XML, $PF_ESXINVENTORY, $CFG_GLPI;
     PluginFusioninventoryToolbox::logIfExtradebug("pluginFusioninventory-rules", "Rule passed : " . $items_id . ", " . $itemtype . "\n");
     $pfFormatconvert = new PluginFusioninventoryFormatconvert();
     $a_computerinventory = $pfFormatconvert->replaceids($this->arrayinventory);
     $entities_id = $_SESSION["plugin_fusioninventory_entity"];
     if ($itemtype == 'Computer') {
         $pfInventoryComputerLib = new PluginFusioninventoryInventoryComputerLib();
         $pfAgent = new PluginFusioninventoryAgent();
         $computer = new Computer();
         if ($items_id == '0') {
             if ($entities_id == -1) {
                 $entities_id = 0;
                 $_SESSION["plugin_fusioninventory_entity"] = 0;
             }
             $_SESSION['glpiactiveentities'] = array($entities_id);
             $_SESSION['glpiactiveentities_string'] = $entities_id;
             $_SESSION['glpiactive_entity'] = $entities_id;
         } else {
             $computer->getFromDB($items_id);
             $a_computerinventory['Computer']['states_id'] = $computer->fields['states_id'];
             $input = array();
             PluginFusioninventoryInventoryComputerInventory::addDefaultStateIfNeeded($input);
             if (isset($input['states_id'])) {
                 $a_computerinventory['Computer']['states_id'] = $input['states_id'];
             }
             if ($entities_id == -1) {
                 $entities_id = $computer->fields['entities_id'];
                 $_SESSION["plugin_fusioninventory_entity"] = $computer->fields['entities_id'];
             }
             $_SESSION['glpiactiveentities'] = array($entities_id);
             $_SESSION['glpiactiveentities_string'] = $entities_id;
             $_SESSION['glpiactive_entity'] = $entities_id;
             if ($computer->fields['entities_id'] != $entities_id) {
                 $pfEntity = new PluginFusioninventoryEntity();
                 $pfInventoryComputerComputer = new PluginFusioninventoryInventoryComputerComputer();
                 $moveentity = FALSE;
                 if ($pfEntity->getValue('transfers_id_auto', $computer->fields['entities_id']) > 0) {
                     if (!$pfInventoryComputerComputer->getLock($items_id)) {
                         $moveentity = TRUE;
                     }
                 }
                 if ($moveentity) {
                     $pfEntity = new PluginFusioninventoryEntity();
                     $transfer = new Transfer();
                     $transfer->getFromDB($pfEntity->getValue('transfers_id_auto', $entities_id));
                     $item_to_transfer = array("Computer" => array($items_id => $items_id));
                     $transfer->moveItems($item_to_transfer, $entities_id, $transfer->fields);
                 } else {
                     $_SESSION["plugin_fusioninventory_entity"] = $computer->fields['entities_id'];
                     $_SESSION['glpiactiveentities'] = array($computer->fields['entities_id']);
                     $_SESSION['glpiactiveentities_string'] = $computer->fields['entities_id'];
                     $_SESSION['glpiactive_entity'] = $computer->fields['entities_id'];
                     $entities_id = $computer->fields['entities_id'];
                 }
             }
         }
         $a_computerinventory = $pfFormatconvert->extraCollectInfo($a_computerinventory, $items_id);
         $a_computerinventory = $pfFormatconvert->computerSoftwareTransformation($a_computerinventory, $entities_id);
         $no_history = FALSE;
         // * New
         $setdynamic = 1;
         if ($items_id == '0') {
             $input = array();
             $input['entities_id'] = $entities_id;
             PluginFusioninventoryInventoryComputerInventory::addDefaultStateIfNeeded($input);
             if (isset($input['states_id'])) {
                 $a_computerinventory['Computer']['states_id'] = $input['states_id'];
             } else {
                 $a_computerinventory['Computer']['states_id'] = 0;
             }
             $items_id = $computer->add($input);
             $no_history = TRUE;
             $setdynamic = 0;
         }
         if (isset($_SESSION['plugin_fusioninventory_locations_id'])) {
             $a_computerinventory['Computer']['locations_id'] = $_SESSION['plugin_fusioninventory_locations_id'];
             unset($_SESSION['plugin_fusioninventory_locations_id']);
         }
         $serialized = gzcompress(serialize($a_computerinventory));
         $a_computerinventory['fusioninventorycomputer']['serialized_inventory'] = Toolbox::addslashes_deep($serialized);
         if (!$PF_ESXINVENTORY) {
             $pfAgent->setAgentWithComputerid($items_id, $this->device_id, $entities_id);
         }
         $pfConfig = new PluginFusioninventoryConfig();
         $query = "INSERT INTO `glpi_plugin_fusioninventory_dblockinventories`\n            SET `value`='" . $items_id . "'";
         $CFG_GLPI["use_log_in_files"] = FALSE;
         if (!$DB->query($query)) {
             $communication = new PluginFusioninventoryCommunication();
             $communication->setMessage("<?xml version='1.0' encoding='UTF-8'?>\n         <REPLY>\n         <ERROR>ERROR: SAME COMPUTER IS CURRENTLY UPDATED</ERROR>\n         </REPLY>");
             $communication->sendMessage($_SESSION['plugin_fusioninventory_compressmode']);
             exit;
         }
         $CFG_GLPI["use_log_in_files"] = TRUE;
         // * For benchs
         //$start = microtime(TRUE);
         PluginFusioninventoryInventoryComputerStat::increment();
         $pfInventoryComputerLib->updateComputer($a_computerinventory, $items_id, $no_history, $setdynamic);
         $query = "DELETE FROM `glpi_plugin_fusioninventory_dblockinventories`\n               WHERE `value`='" . $items_id . "'";
         $DB->query($query);
         $plugin = new Plugin();
         if ($plugin->isActivated('monitoring')) {
             Plugin::doOneHook("monitoring", "ReplayRulesForItem", array('Computer', $items_id));
         }
         // * For benchs
         //Toolbox::logInFile("exetime", (microtime(TRUE) - $start)." (".$items_id.")\n".
         //  memory_get_usage()."\n".
         //  memory_get_usage(TRUE)."\n".
         //  memory_get_peak_usage()."\n".
         //  memory_get_peak_usage()."\n");
         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'] = 'inventory';
             $pfRulematchedlog->add($inputrulelog, array(), FALSE);
             $pfRulematchedlog->cleanOlddata($items_id, $itemtype);
             unset($_SESSION['plugin_fusioninventory_rules_id']);
         }
         // Write XML file
         if (!empty($PLUGIN_FUSIONINVENTORY_XML)) {
             PluginFusioninventoryToolbox::writeXML($items_id, $PLUGIN_FUSIONINVENTORY_XML->asXML(), 'computer');
         }
     } else {
         if ($itemtype == 'PluginFusioninventoryUnmanaged') {
             $a_computerinventory = $pfFormatconvert->computerSoftwareTransformation($a_computerinventory, $entities_id);
             $class = new $itemtype();
             if ($items_id == "0") {
                 if ($entities_id == -1) {
                     $entities_id = 0;
                     $_SESSION["plugin_fusioninventory_entity"] = 0;
                 }
                 $input = array();
                 $input['date_mod'] = date("Y-m-d H:i:s");
                 $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'] = 'inventory';
                     $pfRulematchedlog->add($inputrulelog);
                     $pfRulematchedlog->cleanOlddata($items_id, $itemtype);
                     unset($_SESSION['plugin_fusioninventory_rules_id']);
                 }
             }
             $class->getFromDB($items_id);
             $_SESSION["plugin_fusioninventory_entity"] = $class->fields['entities_id'];
             $input = array();
             $input['id'] = $class->fields['id'];
             // Write XML file
             if (!empty($PLUGIN_FUSIONINVENTORY_XML)) {
                 PluginFusioninventoryToolbox::writeXML($items_id, $PLUGIN_FUSIONINVENTORY_XML->asXML(), 'PluginFusioninventoryUnmanaged');
             }
             if (isset($a_computerinventory['Computer']['name'])) {
                 $input['name'] = $a_computerinventory['Computer']['name'];
             }
             $input['item_type'] = "Computer";
             if (isset($a_computerinventory['Computer']['domains_id'])) {
                 $input['domain'] = $a_computerinventory['Computer']['domains_id'];
             }
             if (isset($a_computerinventory['Computer']['serial'])) {
                 $input['serial'] = $a_computerinventory['Computer']['serial'];
             }
             $class->update($input);
         }
     }
 }
 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;
 }
 /**
  * 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();
 }
Example #19
0
function plugin_fields_rule_matched($params)
{
    global $DB;
    $container = new PluginFieldsContainer();
    switch ($params['sub_type']) {
        case "PluginFusioninventoryTaskpostactionRule":
            $agent = new PluginFusioninventoryAgent();
            if (isset($params['input']['plugin_fusioninventory_agents_id'])) {
                foreach ($params['output'] as $field => $value) {
                    // check if current field is in a tab container
                    $query = "SELECT c.id\n                         FROM glpi_plugin_fields_fields f\n                         LEFT JOIN glpi_plugin_fields_containers c\n                            ON c.id = f.plugin_fields_containers_id\n                         WHERE f.name = '{$field}'";
                    $res = $DB->query($query);
                    if ($DB->numrows($res) > 0) {
                        $data = $DB->fetch_assoc($res);
                        //retrieve computer
                        $agents_id = $params['input']['plugin_fusioninventory_agents_id'];
                        $agent->getFromDB($agents_id);
                        // update current field
                        $container->updateFieldsValues(array('plugin_fields_containers_id' => $data['id'], $field => $value, 'items_id' => $agent->fields['computers_id']));
                    }
                }
            }
            break;
    }
}
 function showForm($items_id, $itemtype)
 {
     $rule = new PluginFusioninventoryInventoryRuleImport();
     $pfAgent = new PluginFusioninventoryAgent();
     echo "<table class='tab_cadre_fixe' cellpadding='1'>";
     echo "<tr>";
     echo "<th colspan='4'>";
     echo __('Rule import logs', 'fusioninventory');
     echo "</th>";
     echo "</tr>";
     echo "<tr>";
     echo "<th>";
     echo __('Date');
     echo "</th>";
     echo "<th>";
     echo __('Rule name');
     echo "</th>";
     echo "<th>";
     echo __('Agent', 'fusioninventory');
     echo "</th>";
     echo "<th>";
     echo __('Module', 'fusioninventory');
     echo "</th>";
     echo "</tr>";
     $allData = $this->find("`itemtype`='" . $itemtype . "'\n                              AND `items_id`='" . $items_id . "'", "`date` DESC");
     foreach ($allData as $data) {
         echo "<tr class='tab_bg_1'>";
         echo "<td align='center'>";
         echo Html::convDateTime($data['date']);
         echo "</td>";
         echo "<td align='center'>";
         if ($rule->getFromDB($data['rules_id'])) {
             echo $rule->getLink(1);
         }
         echo "</td>";
         echo "<td align='center'>";
         if ($pfAgent->getFromDB($data['plugin_fusioninventory_agents_id'])) {
             echo $pfAgent->getLink(1);
         }
         echo "</td>";
         echo "<td>";
         $a_methods = PluginFusioninventoryStaticmisc::getmethods();
         foreach ($a_methods as $mdata) {
             if ($mdata['method'] == $data['method']) {
                 echo $mdata['name'];
             }
         }
         echo "</td>";
         echo "</tr>";
     }
     echo "</table>";
 }
 /**
  * Display detail of each history line
  *
  * @param  $agents_id integer id of the agent
  * @param $uniqid integer uniq id of each taskjobs runing
  * @param $width integer how large in pixel display array
  *
  * @return value all text to display
  *
  **/
 function showHistoryInDetail($agents_id, $uniqid, $width = "950")
 {
     global $CFG_GLPI;
     $pfTaskjobstate = new PluginFusioninventoryTaskjobstate();
     $pfAgent = new PluginFusioninventoryAgent();
     $text = "<center><table class='tab_cadrehov' style='width: " . $width . "px'>";
     $a_jobstates = $pfTaskjobstate->find('`plugin_fusioninventory_agents_id`="' . $agents_id . '" ' . 'AND `uniqid`="' . $uniqid . '"', '`id` DESC');
     $a_devices_merged = array();
     foreach ($a_jobstates as $data) {
         $displayforceend = 0;
         $a_history = $this->find('`plugin_fusioninventory_taskjobstates_id` = "' . $data['id'] . '"', 'id');
         if (strstr(exportArrayToDB($a_history), "Merged with ")) {
             $classname = $data['itemtype'];
             $Class = new $classname();
             $Class->getFromDB($data['items_id']);
             $a_devices_merged[] = $Class->getLink(1) . "&nbsp;(" . $Class->getTypeName() . ")";
         } else {
             $text .= "<tr>";
             $text .= "<th colspan='2'><img src='" . $CFG_GLPI['root_doc'] . "/pics/puce.gif' />" . __('Process number', 'fusioninventory') . "&nbsp;: " . $data['id'] . "</th>";
             $text .= "<th>";
             $text .= __('Date');
             $text .= "</th>";
             $text .= "<th>";
             $text .= __('Status');
             $text .= "</th>";
             $text .= "<th>";
             $text .= __('Comments');
             $text .= "</th>";
             $text .= "</tr>";
             $text .= "<tr class='tab_bg_1'>";
             $text .= "<th colspan='2'>";
             $text .= __('Agent', 'fusioninventory');
             $text .= "</th>";
             $a_return = $this->displayHistoryDetail(array_shift($a_history));
             $count = $a_return[0];
             $text .= $a_return[1];
             $displayforceend += $count;
             $text .= "</tr>";
             $text .= "<tr class='tab_bg_1'>";
             $text .= "<td colspan='2'>";
             $pfAgent->getFromDB($data['plugin_fusioninventory_agents_id']);
             $text .= $pfAgent->getLink(1);
             $text .= "</td>";
             $a_return = $this->displayHistoryDetail(array_shift($a_history));
             $count = $a_return[0];
             $text .= $a_return[1];
             $displayforceend += $count;
             $text .= "</tr>";
             $text .= "<tr class='tab_bg_1'>";
             $text .= "<th colspan='2'>";
             $text .= __('Definition', 'fusioninventory');
             $text .= "<sup>(" . (count($a_devices_merged) + 1) . ")</sup>";
             $text .= "</th>";
             $a_return = $this->displayHistoryDetail(array_shift($a_history));
             $count = $a_return[0];
             $text .= $a_return[1];
             $displayforceend += $count;
             $text .= "</tr>";
             $text .= "<tr class='tab_bg_1'>";
             $text .= "<td colspan='2'>";
             if (!empty($data["itemtype"])) {
                 $device = new $data["itemtype"]();
                 $device->getFromDB($data["items_id"]);
                 $text .= $device->getLink(1);
                 $text .= "&nbsp;";
                 $text .= "(" . $device->getTypeName() . ")";
             }
             $text .= "</td>";
             $a_return = $this->displayHistoryDetail(array_shift($a_history));
             $count = $a_return[0];
             $text .= $a_return[1];
             $displayforceend += $count;
             $text .= "</tr>";
             while (count($a_history) != 0) {
                 if (count($a_devices_merged) > 0) {
                     $text .= "<tr class='tab_bg_1'>";
                     $text .= "<td colspan='2'>";
                     $text .= array_pop($a_devices_merged);
                     $text .= "</td>";
                     $a_return = $this->displayHistoryDetail(array_shift($a_history));
                     $count = $a_return[0];
                     $text .= $a_return[1];
                     $displayforceend += $count;
                     $text .= "</tr>";
                 } else {
                     $text .= "<tr class='tab_bg_1'>";
                     $text .= "<td colspan='2' rowspan='" . count($a_history) . "'>";
                     $text .= "</td>";
                     $a_return = $this->displayHistoryDetail(array_shift($a_history));
                     $count = $a_return[0];
                     $text .= $a_return[1];
                     $displayforceend += $count;
                     $text .= "</tr>";
                     while (count($a_history) != 0) {
                         $text .= "<tr class='tab_bg_1'>";
                         $a_return = $this->displayHistoryDetail(array_shift($a_history));
                         $count = $a_return[0];
                         $text .= $a_return[1];
                         $displayforceend += $count;
                         $text .= "</tr>";
                     }
                 }
             }
             $display = 1;
             while (count($a_devices_merged) != 0) {
                 $text .= "<tr class='tab_bg_1'>";
                 $text .= "<td colspan='2'>";
                 $text .= array_pop($a_devices_merged);
                 $text .= "</td>";
                 if ($display == "1") {
                     $text .= "<td colspan='3' rowspan='" . (count($a_devices_merged) + 1) . "'></td>";
                     $display = 0;
                 }
                 $text .= "</tr>";
             }
             $text .= "<tr class='tab_bg_4'>";
             $text .= "<td colspan='5' height='4'>";
             $text .= "</td>";
             $text .= "</tr>";
         }
     }
     $text .= "</table></center>";
     return $text;
 }
Example #22
0
 /**
  * Function to uninstall an object
  *
  * @param $computers_id the computer's ID in GLPI
  *
  * @return nothing
  **/
 static function deleteFusionInventoryLink($itemtype, $items_id)
 {
     if (function_exists('plugin_pre_item_purge_fusioninventory')) {
         $item = new $itemtype();
         $item->getFromDB($items_id);
         $agent = new PluginFusioninventoryAgent();
         $agents = $agent->getAgentsFromComputers(array($items_id));
         // clean item associated to agents
         plugin_pre_item_purge_fusioninventory($item);
         if ($itemtype == 'Computer') {
             // remove agent(s)
             foreach ($agents as $current_agent) {
                 $agent->deleteByCriteria(array('id' => $current_agent['id']), true);
             }
             // remove licences
             $pfComputerLicenseInfo = new PluginFusioninventoryComputerLicenseInfo();
             $pfComputerLicenseInfo->deleteByCriteria(array('computers_id' => $items_id));
             // remove batteries
             $pfInventoryComputerBatteries = new PluginFusioninventoryInventoryComputerBatteries();
             $pfInventoryComputerBatteries->deleteByCriteria(array('computers_id' => $items_id));
             // Delete links between two computerstorages
             $pfInventoryComputerStorageStorageStorage = new PluginFusioninventoryInventoryComputerStorage_Storage();
             $tab_ids = $pfInventoryComputerStorageStorageStorage->getOpposites($items_id);
             if (!empty($tab_ids)) {
                 //because getOpposites can return 0
                 foreach ($tab_ids as $inventorycomputerstorages_id) {
                     $storage->deleteByCriteria(array('plugin_fusioninventory_inventorycomputerstorages_id_1' => $inventorycomputerstorages_id));
                     $storage->deleteByCriteria(array('plugin_fusioninventory_inventorycomputerstorages_id_2' => $inventorycomputerstorages_id));
                 }
             }
             // ** Delete computerstorages **
             $pfInventoryComputerStorage = new PluginFusioninventoryInventoryComputerStorage();
             $pfInventoryComputerStorage->deleteByCriteria(array('computers_id' => $items_id));
         }
     }
 }
function plugin_item_transfer_fusioninventory($parm)
{
    switch ($parm['type']) {
        case 'Computer':
            $pfAgent = new PluginFusioninventoryAgent();
            if ($agent_id = $pfAgent->getAgentWithComputerid($parm['id'])) {
                $input = array();
                $input['id'] = $agent_id;
                $computer = new Computer();
                $computer->getFromDB($parm['newID']);
                $input['entities_id'] = $computer->fields['entities_id'];
                $pfAgent->update($input);
            }
            break;
    }
    return FALSE;
}
                             $a_input['date'] = date("Y-m-d H:i:s");
                             $a_input['comment'] = '';
                             $a_input['state'] = PluginFusioninventoryTaskjoblog::TASK_STARTED;
                             $pfTaskjoblog->add($a_input);
                         }
                     }
                 }
             }
         }
     }
     break;
 case 'setAnswer':
     // example
     // ?action=setAnswer&InformationSource=0x00000000&BIOSVersion=VirtualBox&SystemManufacturer=innotek%20GmbH&uuid=fepjhoug56743h&SystemProductName=VirtualBox&BIOSReleaseDate=12%2F01%2F2006
     $pfTaskjobstate = new PluginFusioninventoryTaskjobstate();
     $pfAgent = new PluginFusioninventoryAgent();
     $jobstate = current($pfTaskjobstate->find("`uniqid`='" . $_GET['uuid'] . "'\n            AND `state`!='" . PluginFusioninventoryTaskjobstate::FINISHED . "'", '', 1));
     if (isset($jobstate['plugin_fusioninventory_agents_id'])) {
         $pfAgent->getFromDB($jobstate['plugin_fusioninventory_agents_id']);
         $computers_id = $pfAgent->fields['computers_id'];
         $a_values = $_GET;
         unset($a_values['action']);
         unset($a_values['uuid']);
         switch ($jobstate['itemtype']) {
             case 'PluginFusioninventoryCollect_Registry':
                 // update registry content
                 $pfCRC = new PluginFusioninventoryCollect_Registry_Content();
                 $pfCRC->updateComputer($computers_id, $a_values, $jobstate['items_id']);
                 $pfTaskjobstate->changeStatus($jobstate['id'], PluginFusioninventoryTaskjobstate::AGENT_HAS_SENT_DATA);
                 if (isset($a_values['_cpt']) && $a_values['_cpt'] == 0) {
                     // it not find the path
 /**
  * Get Computers from Actors defined in taskjobs
  * TODO: this method should be rewritten to call directly a getAgents() method in the
  * corresponding itemtype classes.
  */
 public function getAgentsFromActors($actors = array())
 {
     $agents = array();
     $computers = array();
     $computer = new Computer();
     $agent = new PluginFusioninventoryAgent();
     $pfToolbox = new PluginFusioninventoryToolbox();
     foreach ($actors as $actor) {
         $itemtype = key($actor);
         $itemid = $actor[$itemtype];
         $item = getItemForItemtype($itemtype);
         $dbresult = $item->getFromDB($itemid);
         // If this item doesn't exists, we continue to the next actor item.
         // TODO: remove this faulty actor from the list of job actor.
         if ($dbresult === false) {
             continue;
         }
         switch ($itemtype) {
             case 'Computer':
                 $computers[$itemid] = 1;
                 break;
             case 'PluginFusioninventoryDeployGroup':
                 $group_targets = $pfToolbox->executeAsFusioninventoryUser('PluginFusioninventoryDeployGroup::getTargetsForGroup', array($itemid));
                 foreach ($group_targets as $computerid) {
                     $computers[$computerid] = 1;
                 }
                 break;
             case 'Group':
                 //find computers by user associated with this group
                 $group_users = new Group_User();
                 $members = array();
                 //array_keys($group_users->find("groups_id = '$items_id'"));
                 $members = $group_users->getGroupUsers($itemid);
                 foreach ($members as $member) {
                     $computers_from_user = $computer->find("users_id = '{$member['id']}'");
                     foreach ($computers_from_user as $computer_entry) {
                         $computers[$computer_entry['id']] = 1;
                     }
                 }
                 //find computers directly associated with this group
                 $computer_from_group = $computer->find("groups_id = '{$itemid}'");
                 foreach ($computer_from_group as $computer_entry) {
                     $computers[$computer_entry['id']] = 1;
                 }
                 break;
                 /**
                  * TODO: The following should be replaced with Dynamic groups
                  */
             /**
              * TODO: The following should be replaced with Dynamic groups
              */
             case 'PluginFusioninventoryAgent':
                 switch ($itemid) {
                     case "dynamic":
                         break;
                     case "dynamic-same-subnet":
                         break;
                     default:
                         $agents[$itemid] = 1;
                         break;
                 }
                 break;
         }
     }
     //Get agents from the computer's ids list
     foreach ($agent->getAgentsFromComputers(array_keys($computers)) as $agent_entry) {
         $agents[$agent_entry['id']] = 1;
     }
     // Return the list of agent's ids.
     // (We used hash keys to avoid duplicates in the list)
     return array_keys($agents);
 }
 public function AgentEntity($computers_id = 0, $entities_id = 0, $text = '')
 {
     global $DB;
     $DB->connect();
     if ($computers_id == 0) {
         return;
     }
     $pfAgent = new PluginFusioninventoryAgent();
     $a_agents_id = $pfAgent->getAgentWithComputerid($computers_id);
     $pfAgent->getFromDB($a_agents_id);
     $this->assertEquals($entities_id, $pfAgent->fields['entities_id'], $text);
 }
 /**
  * Display informations about computer (bios...)
  *
  * @param type $computers_id
  */
 static function showInfo($item)
 {
     global $CFG_GLPI;
     // Manage locks pictures
     PluginFusioninventoryLock::showLockIcon('Computer');
     $pfInventoryComputerComputer = new PluginFusioninventoryInventoryComputerComputer();
     $a_computerextend = current($pfInventoryComputerComputer->find("`computers_id`='" . $item->getID() . "'", "", 1));
     if (empty($a_computerextend)) {
         return;
     }
     echo '<table class="tab_glpi" width="100%">';
     echo '<tr>';
     echo '<th colspan="2">' . __('FusionInventory', 'fusioninventory') . '</th>';
     echo '</tr>';
     echo '<tr class="tab_bg_1">';
     echo '<td>';
     echo __('Last inventory', 'fusioninventory');
     echo '</td>';
     echo '<td>';
     echo Html::convDateTime($a_computerextend['last_fusioninventory_update']);
     echo '</td>';
     echo '</tr>';
     if ($a_computerextend['remote_addr'] != '') {
         echo '<tr class="tab_bg_1">';
         echo '<td>' . __('Public contact address', 'fusioninventory') . '</td>';
         echo '<td>' . $a_computerextend['remote_addr'] . '</td>';
         echo '</tr>';
     }
     $pfAgent = new PluginFusioninventoryAgent();
     $pfAgent->showInfoForComputer($item->getID());
     if ($a_computerextend['bios_date'] != '') {
         echo '<tr class="tab_bg_1">';
         echo '<td>' . __('BIOS date', 'fusioninventory') . '</td>';
         echo '<td>' . Html::convDate($a_computerextend['bios_date']) . '</td>';
         echo '</tr>';
     }
     if ($a_computerextend['bios_version'] != '') {
         echo '<tr class="tab_bg_1">';
         echo '<td>' . __('BIOS version', 'fusioninventory') . '</td>';
         echo '<td>' . $a_computerextend['bios_version'] . '</td>';
         echo '</tr>';
     }
     if ($a_computerextend['bios_manufacturers_id'] > 0) {
         echo '<tr class="tab_bg_1">';
         echo '<td>' . __('Manufacturer') . '&nbsp;:</td>';
         echo '<td>';
         echo Dropdown::getDropdownName("glpi_manufacturers", $a_computerextend['bios_manufacturers_id']);
         echo '</td>';
         echo '</tr>';
     }
     if ($a_computerextend['plugin_fusioninventory_computerarchs_id'] != '') {
         echo '<tr class="tab_bg_1">';
         echo "<td>" . __('Architecture', 'fusioninventory') . "</td>";
         echo '<td>';
         echo Dropdown::getDropdownName('glpi_plugin_fusioninventory_computerarchs', $a_computerextend['plugin_fusioninventory_computerarchs_id']);
         echo '</td>';
         echo '</tr>';
     }
     if ($a_computerextend['operatingsystem_installationdate'] != '') {
         echo '<tr class="tab_bg_1">';
         echo "<td>" . __('Operating system') . " - " . __('Installation') . " (" . strtolower(__('Date')) . ")</td>";
         echo '<td>' . Html::convDate($a_computerextend['operatingsystem_installationdate']) . '</td>';
         echo '</tr>';
     }
     if ($a_computerextend['winowner'] != '') {
         echo '<tr class="tab_bg_1">';
         echo '<td>' . __('Owner', 'fusioninventory') . '</td>';
         echo '<td>' . $a_computerextend['winowner'] . '</td>';
         echo '</tr>';
     }
     if ($a_computerextend['wincompany'] != '') {
         echo '<tr class="tab_bg_1">';
         echo '<td>' . __('Company', 'fusioninventory') . '</td>';
         echo '<td>' . $a_computerextend['wincompany'] . '</td>';
         echo '</tr>';
     }
     if ($a_computerextend['oscomment'] != '') {
         echo '<tr class="tab_bg_1">';
         echo "<td>" . __('Comments') . "</td>";
         echo '<td>' . $a_computerextend['oscomment'] . '</td>';
         echo '</tr>';
     }
     // Display automatic entity transfer
     if (Session::isMultiEntitiesMode()) {
         echo '<tr class="tab_bg_1">';
         echo '<td>' . __('Automatic entity transfer', 'fusioninventory') . '</td>';
         echo '<td>';
         $pfEntity = new PluginFusioninventoryEntity();
         if ($pfEntity->getValue('transfers_id_auto', $item->fields['entities_id']) == 0) {
             echo __('No, locked (by entity configuration)', 'fusioninventory');
         } else {
             if ($a_computerextend['is_entitylocked'] == 1) {
                 echo __('No, locked manually', 'fusioninventory');
                 echo " [ <a href='" . $CFG_GLPI['root_doc'] . "/plugins/fusioninventory/front/computerentitylock.form.php?id=" . $a_computerextend['id'] . "&lock=0'>" . __('Unlock it', 'fusioninventory') . "</a> ]";
             } else {
                 echo __('Yes');
                 echo " [ <a href='" . $CFG_GLPI['root_doc'] . "/plugins/fusioninventory/front/computerentitylock.form.php?id=" . $a_computerextend['id'] . "&lock=1'>" . __('Lock it', 'fusioninventory') . "</a> ]";
             }
         }
         echo '</td>';
         echo '</tr>';
     }
     echo '</table>';
 }
 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;
 }
  @author    David Durieux
  @co-author
  @copyright Copyright (c) 2010-2014 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";
$agent = new PluginFusioninventoryAgent();
Session::checkRight('plugin_fusioninventory_agent', READ);
if (isset($_POST['startagent'])) {
    $agent = new PluginFusioninventoryAgent();
    $agent->getFromDB($_POST['agent_id']);
    if ($agent->wakeUp()) {
        Session::addMessageAfterRedirect(__('The agent is running', 'fusioninventory'));
    } else {
        Session::addMessageAfterRedirect(__('Impossible to communicate with agent!', 'fusioninventory'));
    }
    Html::back();
} else {
    if (isset($_POST["update"])) {
        Session::checkRight('plugin_fusioninventory_agent', UPDATE);
        if (isset($_POST['items_id'])) {
            if ($_POST['items_id'] != "0" and $_POST['items_id'] != "") {
                $_POST['itemtype'] = '1';
            }
        }
 function display($options = array())
 {
     global $DB, $CFG_GLPI;
     $pfAgent = new PluginFusioninventoryAgent();
     $pfTaskjobstate = new PluginFusioninventoryTaskjobstate();
     $pfTaskjoblog = new PluginFusioninventoryTaskjoblog();
     $pfStateInventory = new PluginFusioninventoryStateInventory();
     $pfTaskjob = new PluginFusioninventoryTaskjob();
     $start = 0;
     if (isset($_REQUEST["start"])) {
         $start = $_REQUEST["start"];
     }
     // Total Number of events
     $querycount = "SELECT count(*) AS cpt FROM `glpi_plugin_fusioninventory_taskjobstates`\n         LEFT JOIN `glpi_plugin_fusioninventory_taskjobs`\n            ON `plugin_fusioninventory_taskjobs_id` = `glpi_plugin_fusioninventory_taskjobs`.`id`\n         WHERE `method` = 'networkdiscovery'\n         GROUP BY `uniqid`\n         ORDER BY `uniqid` DESC ";
     $resultcount = $DB->query($querycount);
     $number = $DB->numrows($resultcount);
     // Display the pager
     Html::printPager($start, $number, $CFG_GLPI['root_doc'] . "/plugins/fusioninventory/front/stateinventory.php", '');
     echo "<table class='tab_cadre_fixe'>";
     echo "<tr class='tab_bg_1'>";
     echo "<th>" . __('Unique id', 'fusioninventory') . "</th>";
     echo "<th>" . __('Task job', 'fusioninventory') . "</th>";
     echo "<th>" . __('Agent', 'fusioninventory') . "</th>";
     echo "<th>" . __('Status') . "</th>";
     echo "<th>" . __('Starting date', 'fusioninventory') . "</th>";
     echo "<th>" . __('Ending date', 'fusioninventory') . "</th>";
     echo "<th>" . __('Total duration') . "</th>";
     echo "<th>" . __('Threads number', 'fusioninventory') . "</th>";
     echo "<th>" . __('Total discovery devices', 'fusioninventory') . "</th>";
     echo "<th>" . __('Devices not imported', 'fusioninventory') . "</th>";
     echo "<th>" . __('Devices linked', 'fusioninventory') . "</th>";
     echo "<th>" . __('Devices imported', 'fusioninventory') . "</th>";
     echo "</tr>";
     $sql = "SELECT `glpi_plugin_fusioninventory_taskjobstates`.*\n            FROM `glpi_plugin_fusioninventory_taskjobstates`\n         LEFT JOIN `glpi_plugin_fusioninventory_taskjobs`\n            ON `plugin_fusioninventory_taskjobs_id` = `glpi_plugin_fusioninventory_taskjobs`.`id`\n         WHERE `method` = 'networkdiscovery'\n         GROUP BY `uniqid`\n         ORDER BY `uniqid` DESC\n         LIMIT " . intval($start) . ", " . intval($_SESSION['glpilist_limit']);
     $result = $DB->query($sql);
     while ($data = $DB->fetch_array($result)) {
         echo "<tr class='tab_bg_1'>";
         echo "<td>" . $data['uniqid'] . "</td>";
         $pfTaskjob->getFromDB($data['plugin_fusioninventory_taskjobs_id']);
         echo "<td>" . $pfTaskjob->getLink() . "</td>";
         $pfAgent->getFromDB($data['plugin_fusioninventory_agents_id']);
         echo "<td>" . $pfAgent->getLink(1) . "</td>";
         $nb_found = 0;
         $nb_threads = 0;
         $start_date = "";
         $end_date = "";
         $notimporteddevices = 0;
         $updateddevices = 0;
         $createddevices = 0;
         $a_taskjobstates = $pfTaskjobstate->find("`uniqid`='" . $data['uniqid'] . "'");
         foreach ($a_taskjobstates as $datastate) {
             $a_taskjoblog = $pfTaskjoblog->find("`plugin_fusioninventory_taskjobstates_id`='" . $datastate['id'] . "'");
             foreach ($a_taskjoblog as $taskjoblog) {
                 if (strstr($taskjoblog['comment'], " ==devicesfound==")) {
                     $nb_found += str_replace(" ==devicesfound==", "", $taskjoblog['comment']);
                 } else {
                     if (strstr($taskjoblog['comment'], "==importdenied==")) {
                         $notimporteddevices++;
                     } else {
                         if (strstr($taskjoblog['comment'], "==updatetheitem==")) {
                             $updateddevices++;
                         } else {
                             if (strstr($taskjoblog['comment'], "==addtheitem==")) {
                                 $createddevices++;
                             } else {
                                 if ($taskjoblog['state'] == "1") {
                                     $nb_threads = str_replace(" threads", "", $taskjoblog['comment']);
                                     $start_date = $taskjoblog['date'];
                                 }
                             }
                         }
                     }
                 }
                 if ($taskjoblog['state'] == "2" or $taskjoblog['state'] == "3" or $taskjoblog['state'] == "4" or $taskjoblog['state'] == "5") {
                     if (!strstr($taskjoblog['comment'], 'Merged with ')) {
                         $end_date = $taskjoblog['date'];
                     }
                 }
             }
         }
         // State
         echo "<td>";
         switch ($data['state']) {
             case 0:
                 echo __('Prepared', 'fusioninventory');
                 break;
             case 1:
             case 2:
                 echo __('Started', 'fusioninventory');
                 break;
             case 3:
                 echo __('Finished tasks', 'fusioninventory');
                 break;
         }
         echo "</td>";
         echo "<td>" . Html::convDateTime($start_date) . "</td>";
         echo "<td>" . Html::convDateTime($end_date) . "</td>";
         if ($end_date == '') {
             $end_date = date("Y-m-d H:i:s");
         }
         if ($start_date == '') {
             echo "<td>-</td>";
         } else {
             $interval = '';
             if (phpversion() >= 5.3) {
                 $date1 = new DateTime($start_date);
                 $date2 = new DateTime($end_date);
                 $interval = $date1->diff($date2);
                 $display_date = '';
                 if ($interval->h > 0) {
                     $display_date .= $interval->h . "h ";
                 } else {
                     if ($interval->i > 0) {
                         $display_date .= $interval->i . "min ";
                     }
                 }
                 echo "<td>" . $display_date . $interval->s . "s</td>";
             } else {
                 $interval = $pfStateInventory->date_diff($start_date, $end_date);
             }
         }
         echo "<td>" . $nb_threads . "</td>";
         echo "<td>" . $nb_found . "</td>";
         echo "<td>" . $notimporteddevices . "</td>";
         echo "<td>" . $updateddevices . "</td>";
         echo "<td>" . $createddevices . "</td>";
         echo "</tr>";
     }
     echo "</table>";
 }