function executeActions($output, $params)
 {
     PluginFusioninventoryToolbox::logIfExtradebug("pluginFusioninventory-entityrules", "execute action\n");
     if (count($this->actions)) {
         foreach ($this->actions as $action) {
             switch ($action->fields["action_type"]) {
                 case "assign":
                     PluginFusioninventoryToolbox::logIfExtradebug("pluginFusioninventory-entityrules", "value " . $action->fields["value"] . "\n");
                     $output[$action->fields["field"]] = $action->fields["value"];
                     break;
                 case "regex_result":
                     //Assign entity using the regex's result
                     if ($action->fields["field"] == "_affect_entity_by_tag") {
                         PluginFusioninventoryToolbox::logIfExtradebug("pluginFusioninventory-entityrules", "value " . $action->fields["value"] . "\n");
                         //Get the TAG from the regex's results
                         $res = RuleAction::getRegexResultById($action->fields["value"], $this->regex_results[0]);
                         if (!is_null($res)) {
                             //Get the entity associated with the TAG
                             $target_entity = Entity::getEntityIDByTag($res);
                             if ($target_entity != '') {
                                 $output["entities_id"] = $target_entity;
                             } else {
                                 $output['pass_rule'] = True;
                             }
                         }
                     }
                     break;
             }
         }
     }
     return $output;
 }
 function executeActions($output, $params)
 {
     PluginFusioninventoryToolbox::logIfExtradebug("pluginFusioninventory-locationrules", "execute action\n");
     if (count($this->actions)) {
         foreach ($this->actions as $action) {
             switch ($action->fields["action_type"]) {
                 case "assign":
                     PluginFusioninventoryToolbox::logIfExtradebug("pluginFusioninventory-locationrules", "value " . $action->fields["value"] . "\n");
                     $output[$action->fields["field"]] = $action->fields["value"];
                     break;
                 case "regex_result":
                     $res = '';
                     if (isset($this->regex_results[0])) {
                         $res .= RuleAction::getRegexResultById($action->fields["value"], $this->regex_results[0]);
                     } else {
                         $res .= $action->fields["value"];
                     }
                     if ($res != '') {
                         $entities_id = 0;
                         if (isset($_SESSION["plugin_fusioninventory_entity"]) && $_SESSION["plugin_fusioninventory_entity"] > 0) {
                             $entities_id = $_SESSION["plugin_fusioninventory_entity"];
                         }
                         $res = Dropdown::importExternal(getItemTypeForTable(getTableNameForForeignKeyField($action->fields['field'])), $res, $entities_id);
                     }
                     $output[$action->fields["field"]] = $res;
                     break;
             }
         }
     }
     return $output;
 }
 public function formatlog($messages, $loglevel)
 {
     $msg = array();
     foreach ($messages as $message) {
         if (is_array($message) || is_object($message)) {
             //$msg[] = print_r($message, true);
             $msg[] = PluginFusioninventoryToolbox::formatJson(json_encode($message));
         } else {
             if (is_null($message)) {
                 $msg[] = ' NULL';
             } else {
                 if (is_bool($message)) {
                     $msg[] = $message ? 'true' : 'false';
                 } else {
                     $msg[] = $message;
                 }
             }
         }
     }
     return $loglevel['name'] . ': ' . implode("\n", $msg);
 }
 /**
  * @see CommonDBTM::post_updateItem()
  **/
 function post_updateItem($history = 1)
 {
     global $DB, $CFG_GLPI;
     if (isset($this->oldvalues['is_active']) && $this->oldvalues['is_active'] == 1) {
         // If disable task, must end all taskjobstates prepared
         $pfTaskjobstate = new PluginFusioninventoryTaskjobstate();
         $query = implode(" \n", array("SELECT", "     task.`id`, task.`name`, task.`is_active`,", "     task.`datetime_start`, task.`datetime_end`,", "     task.`plugin_fusioninventory_timeslots_id` as timeslot_id,", "     job.`id`, job.`name`, job.`method`, job.`actors`,", "     run.`itemtype`, run.`items_id`, run.`state`,", "     run.`id`, run.`plugin_fusioninventory_agents_id`", "FROM `glpi_plugin_fusioninventory_taskjobstates` run", "LEFT JOIN `glpi_plugin_fusioninventory_taskjobs` job", "  ON job.`id` = run.`plugin_fusioninventory_taskjobs_id`", "LEFT JOIN `glpi_plugin_fusioninventory_tasks` task", "  ON task.`id` = job.`plugin_fusioninventory_tasks_id`", "WHERE", "  run.`state` IN ('" . implode("','", array(PluginFusioninventoryTaskjobstate::PREPARED)) . "')", "  AND task.`id` = " . $this->fields['id'], "ORDER BY job.`id`"));
         $query_result = $DB->query($query);
         $results = array();
         if ($query_result) {
             $results = PluginFusioninventoryToolbox::fetchAssocByTable($query_result);
         }
         foreach ($results as $data) {
             $pfTaskjobstate->getFromDB($data['run']['id']);
             $pfTaskjobstate->cancel(__('Task has been disabled', 'fusioninventory'));
         }
     }
     parent::post_updateItem($history);
 }
 /**
  * TODO: rename this method in showTimeslots() since it's not only used to delete but also to
  * show the list of Timeslot Entries. -- Kevin 'kiniou' Roy
  */
 function formDeleteEntry($timeslots_id)
 {
     $dbentries = getAllDatasFromTable('glpi_plugin_fusioninventory_timeslotentries', "`plugin_fusioninventory_timeslots_id`='" . $timeslots_id . "'", '', '`day`, `begin` ASC');
     $options = array();
     $this->initForm(key($dbentries), $options);
     $this->showFormHeader($options);
     foreach ($dbentries as $dbentry) {
         echo "<tr class='tab_bg_3'>";
         echo "<td>";
         $daysofweek = Toolbox::getDaysOfWeekArray();
         $daysofweek[7] = $daysofweek[0];
         unset($daysofweek[0]);
         echo $daysofweek[$dbentry['day']];
         echo "</td>";
         echo "<td>";
         echo PluginFusioninventoryToolbox::getHourMinute($dbentry['begin']);
         echo " - ";
         echo PluginFusioninventoryToolbox::getHourMinute($dbentry['end']);
         echo "</td>";
         echo "<td colspan='2'>";
         echo "<input type='submit' class='submit' name='purge-" . $dbentry['id'] . "' value='delete' />";
         echo "</td>";
         echo "</tr>";
     }
     $this->showFormButtons(array('canedit' => false));
 }
 /**
  * Manage communication with old protocol (XML over POST)
  *
  **/
 function handleOCSCommunication($rawdata, $xml = '', $output = 'ext')
 {
     // ***** For debug only ***** //
     //$rawdata = gzcompress('');
     // ********** End ********** //
     $config = new PluginFusioninventoryConfig();
     $user = new User();
     //      ob_start();
     if (!isset($_SESSION['glpiID'])) {
         $users_id = $config->getValue('users_id');
         $_SESSION['glpiID'] = $users_id;
         $user->getFromDB($users_id);
         Session::changeActiveEntities();
         $_SESSION["glpiname"] = $user->getField('name');
         $_SESSION['glpiactiveprofile'] = array();
         $_SESSION['glpiactiveprofile']['interface'] = 'central';
         $_SESSION['glpiactiveprofile']['internet'] = 'w';
         $_SESSION['glpiactiveprofile']['computer'] = 'w';
         $_SESSION['glpiactiveprofile']['monitor'] = 'w';
         $_SESSION['glpiactiveprofile']['printer'] = 'w';
         $_SESSION['glpiactiveprofile']['peripheral'] = 'w';
         $_SESSION['glpiactiveprofile']['networking'] = 'w';
         $_SESSION["glpi_plugin_fusioninventory_profile"]['unmanaged'] = 'w';
     }
     $communication = new PluginFusioninventoryCommunication();
     $pfToolbox = new PluginFusioninventoryToolbox();
     // identify message compression algorithm
     $agent = new PluginFusioninventoryAgent();
     $agent->disableDebug();
     $compressmode = '';
     if (!empty($xml)) {
         $compressmode = 'none';
     } else {
         if ($_SERVER['CONTENT_TYPE'] == "application/x-compress-zlib") {
             $xml = gzuncompress($rawdata);
             $compressmode = "zlib";
         } else {
             if ($_SERVER['CONTENT_TYPE'] == "application/x-compress-gzip") {
                 $xml = $pfToolbox->gzdecode($rawdata);
                 $compressmode = "gzip";
             } else {
                 if ($_SERVER['CONTENT_TYPE'] == "application/xml") {
                     $xml = $rawdata;
                     $compressmode = 'none';
                 } else {
                     # try each algorithm successively
                     if ($xml = gzuncompress($rawdata)) {
                         $compressmode = "zlib";
                     } else {
                         if ($xml = $pfToolbox->gzdecode($rawdata)) {
                             $compressmode = "gzip";
                         } else {
                             if ($xml = gzinflate(substr($rawdata, 2))) {
                                 // accept deflate for OCS agent 2.0 compatibility,
                                 // but use zlib for answer
                                 if (strstr($xml, "<QUERY>PROLOG</QUERY>") and !strstr($xml, "<TOKEN>")) {
                                     $compressmode = "zlib";
                                 } else {
                                     $compressmode = "deflate";
                                 }
                             } else {
                                 $xml = $rawdata;
                                 $compressmode = 'none';
                             }
                         }
                     }
                 }
             }
         }
     }
     $agent->restoreDebug();
     // check if we are in ssl only mode
     $ssl = $config->getValue('ssl_only');
     if ($ssl == "1" and (!isset($_SERVER["HTTPS"]) or $_SERVER["HTTPS"] != "on")) {
         if ($output == 'glpi') {
             Session::addMessageAfterRedirect('SSL REQUIRED BY SERVER', false, ERROR);
         } else {
             $communication->setMessage("<?xml version='1.0' encoding='UTF-8'?>\n<REPLY>\n   <ERROR>SSL REQUIRED BY SERVER</ERROR>\n</REPLY>");
             $communication->sendMessage($compressmode);
         }
         return;
     }
     PluginFusioninventoryConfig::logIfExtradebug('pluginFusioninventory-dial' . uniqid(), $xml);
     // Check XML integrity
     $pxml = '';
     if ($pxml = @simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)) {
     } else {
         if ($pxml = @simplexml_load_string(utf8_encode($xml), 'SimpleXMLElement', LIBXML_NOCDATA)) {
             $xml = utf8_encode($xml);
         } else {
             $xml = preg_replace('/<FOLDER>.*?<\\/SOURCE>/', '', $xml);
             $pxml = @simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
             if (!$pxml) {
                 if ($output == 'glpi') {
                     Session::addMessageAfterRedirect('XML not well formed!', false, ERROR);
                 } else {
                     $communication->setMessage("<?xml version='1.0' encoding='UTF-8'?>\n<REPLY>\n   <ERROR>XML not well formed!</ERROR>\n</REPLY>");
                     $communication->sendMessage($compressmode);
                 }
                 return;
             }
         }
     }
     $_SESSION['plugin_fusioninventory_compressmode'] = $compressmode;
     // Convert XML into PHP array
     $arrayinventory = PluginFusioninventoryFormatconvert::XMLtoArray($pxml);
     unset($pxml);
     $deviceid = '';
     if (isset($arrayinventory['DEVICEID'])) {
         $deviceid = $arrayinventory['DEVICEID'];
     }
     $agent = new PluginFusioninventoryAgent();
     $agents_id = $agent->importToken($arrayinventory);
     $_SESSION['plugin_fusioninventory_agents_id'] = $agents_id;
     if (!$communication->import($arrayinventory)) {
         if ($deviceid != '') {
             $communication->setMessage("<?xml version='1.0' encoding='UTF-8'?>\n<REPLY>\n</REPLY>");
             $a_agent = $agent->InfosByKey($deviceid);
             // Get taskjob in waiting
             $communication->getTaskAgent($a_agent['id']);
             // ******** Send XML
             $communication->addInventory($a_agent['id']);
             $communication->addProlog();
             $communication->sendMessage($compressmode);
         }
     } else {
         if ($output == 'glpi') {
             Session::addMessageAfterRedirect('XML has been imported succesfully!');
         } else {
             $communication->setMessage("<?xml version='1.0' encoding='UTF-8'?>\n<REPLY>\n</REPLY>");
             $communication->sendMessage($compressmode);
         }
     }
 }
 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;
 }
 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;
 }
 static function display_json_debug(PluginFusioninventoryDeployOrder $order)
 {
     global $CFG_GLPI;
     if ($_SESSION['glpi_use_mode'] == Session::DEBUG_MODE) {
         $pfDeployPackage = new PluginFusioninventoryDeployPackage();
         $pfDeployPackage->getFromDB($order->fields['plugin_fusioninventory_deploypackages_id']);
         // === debug ===
         echo "<span class='red'><b>DEBUG</b></span>";
         echo "<form action='" . $CFG_GLPI["root_doc"] . "/plugins/fusioninventory/front/deploypackage.form.php' method='POST'>";
         echo "<textarea cols='132' rows='25' style='border:0' name='json'>";
         echo PluginFusioninventoryToolbox::formatJson($order->fields['json']);
         echo "</textarea>";
         if ($pfDeployPackage->can($pfDeployPackage->getID(), UPDATE)) {
             echo "<input type='hidden' name='orders_id' value='{$order->fields['id']}' />";
             echo "<input type='submit' name='update_json' value=\"" . _sx('button', 'Save') . "\" class='submit'>";
         }
         Html::closeForm();
         // === debug ===
     }
 }
 /**
  * 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();
 }
 function displaySerializedInventory($items_id)
 {
     global $CFG_GLPI;
     $a_computerextend = current($this->find("`computers_id`='" . $items_id . "'", "", 1));
     $this->getFromDB($a_computerextend['id']);
     $folder = substr($items_id, 0, -1);
     if (empty($folder)) {
         $folder = '0';
     }
     if (empty($this->fields['serialized_inventory']) && !file_exists(GLPI_PLUGIN_DOC_DIR . "/fusioninventory/xml/computer/" . $folder . "/" . $items_id)) {
         return;
     }
     $data = array();
     if (!empty($this->fields['serialized_inventory'])) {
         $data = unserialize(gzuncompress($this->fields['serialized_inventory']));
     }
     echo "<br/>";
     echo "<table class='tab_cadre_fixe'>";
     echo "<tr class='tab_bg_1'>";
     echo "<th colspan='2'>";
     echo __('Last inventory', 'fusioninventory');
     echo " (" . Html::convDateTime($this->fields['last_fusioninventory_update']) . ")";
     echo "</th>";
     echo "</tr>";
     echo "<tr class='tab_bg_1'>";
     echo "<th>";
     echo __('Download', 'fusioninventory');
     echo "</th>";
     echo "<td>";
     if (!empty($this->fields['serialized_inventory'])) {
         echo "<a href='" . $CFG_GLPI['root_doc'] . "/plugins/fusioninventory/front/send_inventory.php" . "?itemtype=PluginFusioninventoryInventoryComputerComputer" . "&function=sendSerializedInventory&items_id=" . $a_computerextend['id'] . "&filename=Computer-" . $items_id . ".json'" . "target='_blank'>" . __('PHP Array', 'fusioninventory') . "</a> ";
     }
     if (file_exists(GLPI_PLUGIN_DOC_DIR . "/fusioninventory/xml/computer/" . $folder . "/" . $items_id)) {
         if (!empty($this->fields['serialized_inventory'])) {
             echo "/ ";
         }
         echo "<a href='" . $CFG_GLPI['root_doc'] . "/plugins/fusioninventory/front/send_inventory.php" . "?itemtype=PluginFusioninventoryInventoryComputerComputer" . "&function=sendXML&items_id=computer/" . $folder . "/" . $items_id . "&filename=Computer-" . $items_id . ".xml'" . "target='_blank'>XML</a>";
     }
     echo "</td>";
     echo "</tr>";
     PluginFusioninventoryToolbox::displaySerializedValues($data);
     echo "</table>";
 }
 /**
  * Get all IP of an agent or a computer
  *
  * @param $items_id integer ID of the item
  * @param $type 'Agent' by default to get IP of agent or of a computer if set other text
  *
  * @return Every IP addresses registered for this agent or false
  *
  **/
 function getIPs()
 {
     $ip_addresses = array();
     $computers_id = 0;
     if (isset($this->fields['computers_id'])) {
         if ($this->fields['computers_id'] > 0) {
         }
     } else {
         trigger_error('Agent must be initialized');
     }
     $ip_addresses = PluginFusioninventoryToolbox::getIPforDevice('Computer', $this->fields['computers_id']);
     return $ip_addresses;
 }
 function prepareInputDataForProcess($input, $params)
 {
     PluginFusioninventoryToolbox::logIfExtradebug("pluginFusioninventory-locationrules", "execute action\n" . print_r($input, TRUE) . "\n" . print_r($params, TRUE));
     return $input;
 }
 static function exportDictionnaryFile($enableright = TRUE)
 {
     global $DB;
     if (!strstr($_SERVER['PHP_SELF'], "front/plugin.php") && !strstr($_SERVER['PHP_SELF'], "front/plugin.form.php") && basename($_SERVER['PHP_SELF']) != "cli_install.php") {
         if ($enableright) {
             Session::checkRight('plugin_fusioninventory_model', READ);
         }
     }
     $xmlstr = "<?xml version='1.0' encoding='UTF-8'?>" . "<SNMPDISCOVERY>" . "</SNMPDISCOVERY>";
     $xml = new SimpleXMLElement($xmlstr);
     $query = "SELECT * FROM `glpi_plugin_fusioninventory_snmpmodeldevices`\n                LEFT JOIN `glpi_plugin_fusioninventory_snmpmodels`\n                   ON `plugin_fusioninventory_snmpmodels_id`=" . "`glpi_plugin_fusioninventory_snmpmodels`.`id`\n                ORDER BY `sysdescr`";
     $result = $DB->query($query);
     while ($data = $DB->fetch_array($result)) {
         $device = $xml->addChild('DEVICE');
         $device->addChild('SYSDESCR', $data['sysdescr']);
         //            $device->addChild('MANUFACTURER', $data['manufacturers_id']);
         switch ($data['itemtype']) {
             case 'Computer':
                 $device->addChild('TYPE', '1');
                 break;
             case 'NetworkEquipment':
                 $device->addChild('TYPE', '2');
                 break;
             case 'Printer':
                 $device->addChild('TYPE', '3');
                 break;
         }
         $device->addChild('MODELSNMP', $data['discovery_key']);
         $query_serial = "SELECT * FROM `glpi_plugin_fusioninventory_snmpmodelmibs`\n                  LEFT JOIN `glpi_plugin_fusioninventory_mappings`\n                     ON `glpi_plugin_fusioninventory_snmpmodelmibs`." . "`plugin_fusioninventory_mappings_id`=\n                        `glpi_plugin_fusioninventory_mappings`.`id`\n               WHERE `plugin_fusioninventory_snmpmodels_id`='" . $data['plugin_fusioninventory_snmpmodels_id'] . "'\n                  AND `name`='serial'\n               LIMIT 1";
         $result_serial = $DB->query($query_serial);
         if ($DB->numrows($result_serial) > 0) {
             $line = $DB->fetch_assoc($result_serial);
             $device->addChild('SERIAL', Dropdown::getDropdownName('glpi_plugin_fusioninventory_snmpmodelmiboids', $line['plugin_fusioninventory_snmpmodelmiboids_id']));
         }
         $query_serial = "SELECT * FROM `glpi_plugin_fusioninventory_snmpmodelmibs`\n                  LEFT JOIN `glpi_plugin_fusioninventory_mappings`\n                     ON `glpi_plugin_fusioninventory_snmpmodelmibs`." . "`plugin_fusioninventory_mappings_id`=\n                        `glpi_plugin_fusioninventory_mappings`.`id`\n               WHERE `plugin_fusioninventory_snmpmodels_id`='" . $data['plugin_fusioninventory_snmpmodels_id'] . "'\n                  AND ((`name`='macaddr' AND `itemtype`='NetworkEquipment')\n                        OR ( `name`='ifPhysAddress' AND `itemtype`='Printer')\n                        OR ( `name`='ifPhysAddress' AND `itemtype`='Computer'))\n               LIMIT 1";
         $result_serial = $DB->query($query_serial);
         if ($DB->numrows($result_serial) > 0) {
             $line = $DB->fetch_assoc($result_serial);
             if ($line['name'] == "macaddr") {
                 $device->addChild('MAC', Dropdown::getDropdownName('glpi_plugin_fusioninventory_snmpmodelmiboids', $line['plugin_fusioninventory_snmpmodelmiboids_id']));
             } else {
                 $device->addChild('MACDYN', Dropdown::getDropdownName('glpi_plugin_fusioninventory_snmpmodelmiboids', $line['plugin_fusioninventory_snmpmodelmiboids_id']));
             }
         }
     }
     $xmlprint = PluginFusioninventoryToolbox::formatXML($xml);
     $xmlprint = str_replace("<SYSDESCR>", "<SYSDESCR><![CDATA[", $xmlprint);
     $xmlprint = str_replace("</SYSDESCR>", "]]></SYSDESCR>", $xmlprint);
     file_put_contents(GLPI_PLUGIN_DOC_DIR . "/fusioninventory/discovery.xml", $xmlprint);
 }
 /**
  * @test
  */
 public function formatJson()
 {
     $this->assertEquals($this->formatJson_expected, PluginFusioninventoryToolbox::formatJson(json_encode($this->formatJson_input)));
 }
 /**
  * Get URL for module (for REST)
  *
  * @param $module value name of module
  *
  * @return nothing
  *
  **/
 static function getUrlForModule($modulename, $entities_id = -1)
 {
     // Get current entity URL if it exists ...
     $pfEntity = new PluginFusioninventoryEntity();
     $baseUrl = $pfEntity->getValue('agent_base_url', $entities_id);
     if (!empty($baseUrl)) {
         PluginFusioninventoryToolbox::logIfExtradebug("pluginFusioninventory-agent-url", "Entity " . $entities_id . ", agent base URL: " . $baseUrl);
         if ($baseUrl != 'N/A') {
             return $baseUrl . '/plugins/fusioninventory/b/' . strtolower($modulename) . '/';
         }
     }
     // ... else use global plugin configuration parameter.
     $config = new PluginFusioninventoryConfig();
     if (strlen($pfEntity->getValue('agent_base_url', $entities_id)) < 10) {
         PluginFusioninventoryCommunicationRest::sendError();
         exit;
         // die ("agent_base_url is unset!\n");
     }
     PluginFusioninventoryToolbox::logIfExtradebug("pluginFusioninventory-agent-url", "Global configuration URL: " . $pfEntity->getValue('agent_base_url', $entities_id));
     # Construct the path to the JSON back from the agent_base_url.
     # agent_base_url is the initial URL used by the agent
     return $pfEntity->getValue('agent_base_url', $entities_id) . '/plugins/fusioninventory/b/' . strtolower($modulename) . '/';
 }
 /**
  * Dropdown for display hours
  *
  * @return type
  */
 static function showHours($name, $options = array())
 {
     $p['value'] = '';
     $p['display'] = true;
     $p['width'] = '80%';
     $p['step'] = 5;
     $p['begin'] = 0;
     $p['end'] = 24 * 3600;
     if (is_array($options) && count($options)) {
         foreach ($options as $key => $val) {
             $p[$key] = $val;
         }
     }
     if ($p['step'] <= 0) {
         $p['step'] = 5;
     }
     $values = array();
     $p['step'] = $p['step'] * 60;
     // to have in seconds
     for ($s = $p['begin']; $s < $p['end']; $s += $p['step']) {
         $values[$s] = PluginFusioninventoryToolbox::getHourMinute($s);
     }
     return Dropdown::showFromArray($name, $values, $p);
 }
 /**
  * After rules import device
  *
  * @param integer $items_id id of the device in GLPI DB (0 = created, other = merge)
  * @param varchar $itemtype itemtype of the device
  *
  * @return type
  */
 function rulepassed($items_id, $itemtype)
 {
     PluginFusioninventoryLogger::logIfExtradebug("pluginFusioninventory-rules", "Rule passed : " . $items_id . ", " . $itemtype . "\n");
     PluginFusioninventoryLogger::logIfExtradebugAndDebugMode('fusioninventorycommunication', 'Function PluginFusinvsnmpCommunicationSNMPQuery->rulepassed().');
     $_SESSION["plugin_fusioninventory_entity"] = 0;
     PluginFusioninventoryConfig::logIfExtradebug("pluginFusioninventory-rules", "Rule passed : " . $items_id . ", " . $itemtype . "\n");
     PluginFusioninventoryCommunication::addLog('Function PluginFusioninventoryCommunicationNetworkInventory->rulepassed().');
     $a_inventory = $_SESSION['SOURCE_XMLDEVICE'];
     $errors = '';
     $class = new $itemtype();
     if ($items_id == "0") {
         $input = array();
         $input['date_mod'] = date("Y-m-d H:i:s");
         if ($class->getFromDB($a_inventory[$a_inventory['itemtype']]['id'])) {
             $input['entities_id'] = $class->fields['entities_id'];
         } else {
             $input['entities_id'] = 0;
         }
         if (!isset($_SESSION['glpiactiveentities_string'])) {
             $_SESSION['glpiactiveentities_string'] = "'" . $input['entities_id'] . "'";
         }
         $_SESSION["plugin_fusioninventory_entity"] = $input['entities_id'];
         $items_id = $class->add($input);
         if (isset($_SESSION['plugin_fusioninventory_rules_id'])) {
             $pfRulematchedlog = new PluginFusioninventoryRulematchedlog();
             $inputrulelog = array();
             $inputrulelog['date'] = date('Y-m-d H:i:s');
             $inputrulelog['rules_id'] = $_SESSION['plugin_fusioninventory_rules_id'];
             if (isset($_SESSION['plugin_fusioninventory_agents_id'])) {
                 $inputrulelog['plugin_fusioninventory_agents_id'] = $_SESSION['plugin_fusioninventory_agents_id'];
             }
             $inputrulelog['items_id'] = $items_id;
             $inputrulelog['itemtype'] = $itemtype;
             $inputrulelog['method'] = 'snmpinventory';
             $pfRulematchedlog->add($inputrulelog);
             $pfRulematchedlog->cleanOlddata($items_id, $itemtype);
             unset($_SESSION['plugin_fusioninventory_rules_id']);
         }
     }
     if ($itemtype == "PluginFusioninventoryUnmanaged") {
         $class->getFromDB($items_id);
         $input = array();
         $input['id'] = $class->fields['id'];
         if (!empty($a_inventory[$a_inventory['itemtype']]['name'])) {
             $input['name'] = $a_inventory[$a_inventory['itemtype']]['name'];
         }
         if (!empty($a_inventory[$a_inventory['itemtype']]['serial'])) {
             $input['serial'] = $a_inventory[$a_inventory['itemtype']]['serial'];
         }
         if (!empty($a_inventory['itemtype'])) {
             $input['itemtype'] = $a_inventory['itemtype'];
         }
         // TODO : add import ports
         PluginFusioninventoryToolbox::writeXML($items_id, serialize($_SESSION['SOURCE_XMLDEVICE']), 'PluginFusioninventoryUnmanaged');
         $class->update($input);
         $_SESSION['plugin_fusinvsnmp_taskjoblog']['comment'] = '[==detail==] ==updatetheitem== Update ' . PluginFusioninventoryUnmanaged::getTypeName() . ' [[PluginFusioninventoryUnmanaged::' . $items_id . ']]';
         $this->addtaskjoblog();
     } else {
         $_SESSION['plugin_fusinvsnmp_taskjoblog']['comment'] = '[==detail==] Update ' . $class->getTypeName() . ' [[' . $itemtype . '::' . $items_id . ']]';
         $this->addtaskjoblog();
         $errors .= $this->importDevice($itemtype, $items_id, $a_inventory);
     }
     return $errors;
 }
 /**
  * Function to update Printer
  *
  * @param array $a_inventory data fron agent inventory
  * @param id $items_id id of the printer
  *
  * @return nothing
  */
 function updatePrinter($a_inventory, $items_id)
 {
     global $DB;
     $printer = new Printer();
     $pfPrinter = new PluginFusioninventoryPrinter();
     $printer->getFromDB($items_id);
     if (!isset($_SESSION['glpiactiveentities_string'])) {
         $_SESSION['glpiactiveentities_string'] = $printer->fields['entities_id'];
     }
     if (!isset($_SESSION['glpiactiveentities'])) {
         $_SESSION['glpiactiveentities'] = array($printer->fields['entities_id']);
     }
     if (!isset($_SESSION['glpiactive_entity'])) {
         $_SESSION['glpiactive_entity'] = $printer->fields['entities_id'];
     }
     // * Printer
     $db_printer = $printer->fields;
     $a_lockable = PluginFusioninventoryLock::getLockFields('glpi_printers', $items_id);
     $a_ret = PluginFusioninventoryToolbox::checkLock($a_inventory['Printer'], $db_printer, $a_lockable);
     $a_inventory['Printer'] = $a_ret[0];
     $input = $a_inventory['Printer'];
     $input['id'] = $items_id;
     $printer->update($input);
     // * Printer fusion (ext)
     $db_printer = array();
     $query = "SELECT *\n            FROM `" . getTableForItemType("PluginFusioninventoryPrinter") . "`\n            WHERE `printers_id` = '{$items_id}'";
     $result = $DB->query($query);
     while ($data = $DB->fetch_assoc($result)) {
         foreach ($data as $key => $value) {
             $db_printer[$key] = Toolbox::addslashes_deep($value);
         }
     }
     if (count($db_printer) == '0') {
         // Add
         $a_inventory['PluginFusioninventoryPrinter']['printers_id'] = $items_id;
         $pfPrinter->add($a_inventory['PluginFusioninventoryPrinter']);
     } else {
         // Update
         $idtmp = $db_printer['id'];
         unset($db_printer['id']);
         unset($db_printer['printers_id']);
         unset($db_printer['plugin_fusioninventory_configsecurities_id']);
         $a_ret = PluginFusioninventoryToolbox::checkLock($a_inventory['PluginFusioninventoryPrinter'], $db_printer);
         $a_inventory['PluginFusioninventoryPrinter'] = $a_ret[0];
         $input = $a_inventory['PluginFusioninventoryPrinter'];
         $input['id'] = $idtmp;
         $pfPrinter->update($input);
     }
     // * Ports
     $this->importPorts($a_inventory, $items_id);
     // Page counters
     $this->importPageCounters($a_inventory['pagecounters'], $items_id);
     // Cartridges
     $this->importCartridges($a_inventory['cartridge'], $items_id);
 }
 /**
  * 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);
         }
     }
 }
 function displaySerializedInventory($items_id)
 {
     global $CFG_GLPI;
     $a_printerextend = current($this->find("`printers_id`='" . $items_id . "'", "", 1));
     $this->getFromDB($a_printerextend['id']);
     if (empty($this->fields['serialized_inventory'])) {
         return;
     }
     $data = unserialize(gzuncompress($this->fields['serialized_inventory']));
     echo "<br/>";
     echo "<table class='tab_cadre_fixe'>";
     echo "<tr class='tab_bg_1'>";
     echo "<th colspan='2'>";
     echo __('Last inventory', 'fusioninventory');
     echo " (" . Html::convDateTime($this->fields['last_fusioninventory_update']) . ")";
     echo "</th>";
     echo "</tr>";
     echo "<tr class='tab_bg_1'>";
     echo "<th>";
     echo __('Download', 'fusioninventory');
     echo "</th>";
     echo "<td>";
     echo "<a href='" . $CFG_GLPI['root_doc'] . "/plugins/fusioninventory/front/send_inventory.php" . "?itemtype=PluginFusioninventoryPrinter" . "&function=sendSerializedInventory&items_id=" . $a_printerextend['id'] . "&filename=Printer-" . $items_id . ".json'" . "target='_blank'>PHP Array</a> / <a href=''>XML</a>";
     echo "</td>";
     echo "</tr>";
     PluginFusioninventoryToolbox::displaySerializedValues($data);
     echo "</table>";
 }
 /**
  * Execute the actions as defined in the rule
  *
  * @param $output the fields to manipulate
  * @param $params parameters
  *
  * @return the $output array modified
  **/
 function executeActions($output, $params)
 {
     if (isset($params['class'])) {
         $class = $params['class'];
     } else {
         if (isset($_SESSION['plugin_fusioninventory_classrulepassed'])) {
             $classname = $_SESSION['plugin_fusioninventory_classrulepassed'];
             $class = new $classname();
         }
     }
     $pfRulematchedlog = new PluginFusioninventoryRulematchedlog();
     $inputrulelog = array();
     $inputrulelog['date'] = date('Y-m-d H:i:s');
     $inputrulelog['rules_id'] = $this->fields['id'];
     if (!isset($params['return'])) {
         if (isset($_SESSION['plugin_fusioninventory_classrulepassed'])) {
             $inputrulelog['method'] = $class->getMethod();
         }
         if (isset($_SESSION['plugin_fusioninventory_agents_id'])) {
             $inputrulelog['plugin_fusioninventory_agents_id'] = $_SESSION['plugin_fusioninventory_agents_id'];
         }
     }
     PluginFusioninventoryToolbox::logIfExtradebug("pluginFusioninventory-rules", "execute action\n");
     if (count($this->actions)) {
         foreach ($this->actions as $action) {
             if ($action->fields['field'] == '_fusion') {
                 PluginFusioninventoryToolbox::logIfExtradebug("pluginFusioninventory-rules", "value" . $action->fields["value"] . "\n");
                 if ($action->fields["value"] == self::RULE_ACTION_LINK) {
                     if (isset($this->criterias_results['found_equipment'])) {
                         foreach ($this->criterias_results['found_equipment'] as $itemtype => $datas) {
                             $items_id = current($datas);
                             $output['found_equipment'] = array($items_id, $itemtype);
                             if (isset($_SESSION['plugin_fusioninventory_classrulepassed'])) {
                                 if (!isset($params['return'])) {
                                     $inputrulelog['items_id'] = $items_id;
                                     $inputrulelog['itemtype'] = $itemtype;
                                     $pfRulematchedlog->add($inputrulelog);
                                     $pfRulematchedlog->cleanOlddata($items_id, $itemtype);
                                     $class->rulepassed($items_id, $itemtype);
                                 }
                                 return $output;
                             } else {
                                 $_SESSION['plugin_fusioninventory_rules_id'] = $this->fields['id'];
                                 $output['action'] = self::LINK_RESULT_LINK;
                                 return $output;
                             }
                         }
                     } else {
                         // Import into new equipment
                         $itemtype_found = 0;
                         if (count($this->criterias)) {
                             foreach ($this->criterias as $criteria) {
                                 if ($criteria->fields['criteria'] == 'itemtype') {
                                     $itemtype = $criteria->fields['pattern'];
                                     if (isset($_SESSION['plugin_fusioninventory_classrulepassed'])) {
                                         if (!isset($params['return'])) {
                                             $_SESSION['plugin_fusioninventory_rules_id'] = $this->fields['id'];
                                             $class->rulepassed("0", $itemtype);
                                         }
                                         $output['found_equipment'] = array(0, $itemtype);
                                         return $output;
                                     } else {
                                         $_SESSION['plugin_fusioninventory_rules_id'] = $this->fields['id'];
                                         $output['action'] = self::LINK_RESULT_CREATE;
                                         return $output;
                                     }
                                     $itemtype_found = 1;
                                 }
                             }
                         }
                         if ($itemtype_found == "0") {
                             if (isset($_SESSION['plugin_fusioninventory_classrulepassed'])) {
                                 if (!isset($params['return'])) {
                                     $_SESSION['plugin_fusioninventory_rules_id'] = $this->fields['id'];
                                     $class->rulepassed("0", "PluginFusioninventoryUnmanaged");
                                 }
                                 $output['found_equipment'] = array(0, "PluginFusioninventoryUnmanaged");
                                 return $output;
                             } else {
                                 $_SESSION['plugin_fusioninventory_rules_id'] = $this->fields['id'];
                                 $output['action'] = self::LINK_RESULT_CREATE;
                                 return $output;
                             }
                         }
                     }
                 } else {
                     if ($action->fields["value"] == self::RULE_ACTION_DENIED) {
                         $_SESSION['plugin_fusioninventory_rules_id'] = $this->fields['id'];
                         $output['action'] = self::LINK_RESULT_DENIED;
                         return $output;
                     }
                 }
             } else {
                 if ($action->fields['field'] == '_ignore_import') {
                     PluginFusioninventoryToolbox::logIfExtradebug("pluginFusioninventory-rules", "value" . $action->fields["value"] . "\n");
                     $_SESSION['plugin_fusioninventory_rules_id'] = $this->fields['id'];
                     $output['action'] = self::LINK_RESULT_DENIED;
                     return $output;
                 } else {
                     // no import
                     $itemtype_found = 0;
                     if (count($this->criterias)) {
                         foreach ($this->criterias as $criteria) {
                             if ($criteria->fields['criteria'] == 'itemtype') {
                                 $itemtype = $criteria->fields['pattern'];
                                 if (isset($_SESSION['plugin_fusioninventory_classrulepassed'])) {
                                     if (!isset($params['return'])) {
                                         $_SESSION['plugin_fusioninventory_rules_id'] = $this->fields['id'];
                                         $class->rulepassed("0", $itemtype);
                                     }
                                     $output['found_equipment'] = array(0, $itemtype);
                                     return $output;
                                 } else {
                                     $_SESSION['plugin_fusioninventory_rules_id'] = $this->fields['id'];
                                     $output['action'] = self::LINK_RESULT_CREATE;
                                     return $output;
                                 }
                                 $itemtype_found = 1;
                             }
                         }
                     }
                     if ($itemtype_found == "0") {
                         if (isset($_SESSION['plugin_fusioninventory_classrulepassed'])) {
                             if (!isset($params['return'])) {
                                 $_SESSION['plugin_fusioninventory_rules_id'] = $this->fields['id'];
                                 $class->rulepassed("0", "PluginFusioninventoryUnmanaged");
                             }
                             $output['found_equipment'] = array(0, 'PluginFusioninventoryUnmanaged');
                             return $output;
                         } else {
                             $_SESSION['plugin_fusioninventory_rules_id'] = $this->fields['id'];
                             $output['action'] = self::LINK_RESULT_CREATE;
                             return $output;
                         }
                     }
                 }
             }
         }
     }
     return $output;
 }
 /**
  * Import discovered device (add / update data in GLPI DB)
  *
  * @param object $item
  */
 function importDevice($item)
 {
     PluginFusioninventoryLogger::logIfExtradebugAndDebugMode('fusioninventorycommunication', 'Function PluginFusinvsnmpCommunicationNetDiscovery->importDevice().');
     $arrayinventory = $_SESSION['SOURCE_XMLDEVICE'];
     $input = array();
     $input['id'] = $item->getID();
     $a_lockable = PluginFusioninventoryLock::getLockFields(getTableForItemType($item->getType()), $item->getID());
     if (!in_array('name', $a_lockable)) {
         if (isset($arrayinventory['SNMPHOSTNAME']) && !empty($arrayinventory['SNMPHOSTNAME'])) {
             $input['name'] = $arrayinventory['SNMPHOSTNAME'];
         } else {
             if (isset($arrayinventory['NETBIOSNAME']) && !empty($arrayinventory['NETBIOSNAME'])) {
                 $input['name'] = $arrayinventory['NETBIOSNAME'];
             } else {
                 if (isset($arrayinventory['DNSHOSTNAME']) && !empty($arrayinventory['DNSHOSTNAME'])) {
                     $input['name'] = $arrayinventory['DNSHOSTNAME'];
                 }
             }
         }
     }
     if (!in_array('serial', $a_lockable)) {
         if (isset($arrayinventory['SERIAL'])) {
             if (trim($arrayinventory['SERIAL']) != '') {
                 $input['serial'] = trim($arrayinventory['SERIAL']);
             }
         }
     }
     if (isset($input['name']) && $input['name'] == '') {
         unset($input['name']);
     }
     if (isset($input['serial']) && $input['serial'] == '') {
         unset($input['serial']);
     }
     if (isset($arrayinventory['ENTITY']) and !empty($arrayinventory['ENTITY'])) {
         $input['entities_id'] = $arrayinventory['ENTITY'];
         if (!isset($_SESSION['glpiactiveentities_string'])) {
             $_SESSION['glpiactiveentities_string'] = "'" . $arrayinventory['ENTITY'] . "'";
         }
     }
     if (!isset($_SESSION['glpiactiveentities_string'])) {
         $_SESSION['glpiactiveentities_string'] = "'" . $item->fields['entities_id'] . "'";
     }
     switch ($item->getType()) {
         case 'Computer':
             // don't update this computer, if it is already handled by
             // its own agent
             if (Dropdown::getDropdownName("glpi_autoupdatesystems", $item->fields['autoupdatesystems_id']) == 'FusionInventory') {
                 return;
             }
             if (isset($arrayinventory['WORKGROUP'])) {
                 $domain = new Domain();
                 if (!in_array('domains_id', $a_lockable)) {
                     $input['domains_id'] = $domain->import(array('name' => $arrayinventory['WORKGROUP']));
                 }
             }
             $item->update($input);
             $this->_updateNetworkInfo($arrayinventory, 'Computer', $item->getID(), 'NetworkPortEthernet', 1);
             break;
         case 'PluginFusioninventoryUnmanaged':
             // Write XML file
             if (isset($_SESSION['SOURCE_XMLDEVICE'])) {
                 PluginFusioninventoryToolbox::writeXML($input['id'], serialize($_SESSION['SOURCE_XMLDEVICE']), 'PluginFusioninventoryUnmanaged');
             }
             if (!in_array('contact', $a_lockable) && isset($arrayinventory['USERSESSION'])) {
                 $input['contact'] = $arrayinventory['USERSESSION'];
             }
             if (!in_array('domain', $a_lockable)) {
                 if (isset($arrayinventory['WORKGROUP']) && !empty($arrayinventory['WORKGROUP'])) {
                     $input['domain'] = Dropdown::importExternal("Domain", $arrayinventory['WORKGROUP'], $arrayinventory['ENTITY']);
                 }
             }
             if (!empty($arrayinventory['TYPE'])) {
                 switch ($arrayinventory['TYPE']) {
                     case '1':
                     case 'COMPUTER':
                         $input['item_type'] = 'Computer';
                         break;
                     case '2':
                     case 'NETWORKING':
                         $input['item_type'] = 'NetworkEquipment';
                         break;
                     case '3':
                     case 'PRINTER':
                         $input['item_type'] = 'Printer';
                         break;
                 }
             }
             $input['plugin_fusioninventory_agents_id'] = $_SESSION['glpi_plugin_fusioninventory_agentid'];
             $this->_updateSNMPInfo($arrayinventory, $input, $item);
             $this->_updateNetworkInfo($arrayinventory, 'PluginFusioninventoryUnmanaged', $item->getID(), 'NetworkPortEthernet', 1);
             break;
         case 'NetworkEquipment':
             // Write XML file
             if (isset($_SESSION['SOURCE_XMLDEVICE'])) {
                 PluginFusioninventoryToolbox::writeXML($input['id'], serialize($_SESSION['SOURCE_XMLDEVICE']), 'NetworkEquipment');
             }
             $item->update($input);
             $this->_updateNetworkInfo($arrayinventory, 'NetworkEquipment', $item->getID(), 'NetworkPortAggregate', 0);
             $pfNetworkEquipment = new PluginFusioninventoryNetworkEquipment();
             $input = $this->_initSpecificInfo('networkequipments_id', $item->getID(), $pfNetworkEquipment);
             $this->_updateSNMPInfo($arrayinventory, $input, $pfNetworkEquipment);
             break;
         case 'Printer':
             // Write XML file
             if (isset($_SESSION['SOURCE_XMLDEVICE'])) {
                 PluginFusioninventoryToolbox::writeXML($input['id'], serialize($_SESSION['SOURCE_XMLDEVICE']), 'Printer');
             }
             $input['have_ethernet'] = '1';
             $item->update($input);
             $this->_updateNetworkInfo($arrayinventory, 'Printer', $item->getID(), 'NetworkPortEthernet', 1);
             $pfPrinter = new PluginFusioninventoryPrinter();
             $input = $this->_initSpecificInfo('printers_id', $item->getID(), $pfPrinter);
             $this->_updateSNMPInfo($arrayinventory, $input, $pfPrinter);
             break;
     }
 }
 /**
  * Function to update NetworkEquipment
  *
  * @param array $a_inventory data fron agent inventory
  * @param id $items_id id of the networkequipment
  *
  * @return nothing
  */
 function updateNetworkEquipment($a_inventory, $items_id)
 {
     global $DB;
     $networkEquipment = new NetworkEquipment();
     $pfNetworkEquipment = new PluginFusioninventoryNetworkEquipment();
     $networkEquipment->getFromDB($items_id);
     if (!isset($_SESSION['glpiactiveentities_string'])) {
         $_SESSION['glpiactiveentities_string'] = $networkEquipment->fields['entities_id'];
     }
     if (!isset($_SESSION['glpiactiveentities'])) {
         $_SESSION['glpiactiveentities'] = array($networkEquipment->fields['entities_id']);
     }
     if (!isset($_SESSION['glpiactive_entity'])) {
         $_SESSION['glpiactive_entity'] = $networkEquipment->fields['entities_id'];
     }
     // * NetworkEquipment
     $db_networkequipment = $networkEquipment->fields;
     $a_lockable = PluginFusioninventoryLock::getLockFields('glpi_networkequipments', $items_id);
     $a_ret = PluginFusioninventoryToolbox::checkLock($a_inventory['NetworkEquipment'], $db_networkequipment, $a_lockable);
     $a_inventory['NetworkEquipment'] = $a_ret[0];
     $mac = $a_inventory['NetworkEquipment']['mac'];
     unset($a_inventory['NetworkEquipment']['mac']);
     $input = $a_inventory['NetworkEquipment'];
     $input['id'] = $items_id;
     $networkEquipment->update($input);
     $this->internalPorts($a_inventory['internalport'], $items_id, $mac, 'Internal');
     // * NetworkEquipment fusion (ext)
     $db_networkequipment = array();
     $query = "SELECT *\n            FROM `" . getTableForItemType("PluginFusioninventoryNetworkEquipment") . "`\n            WHERE `networkequipments_id` = '{$items_id}'";
     $result = $DB->query($query);
     while ($data = $DB->fetch_assoc($result)) {
         foreach ($data as $key => $value) {
             $db_networkequipment[$key] = Toolbox::addslashes_deep($value);
         }
     }
     if (count($db_networkequipment) == '0') {
         // Add
         $a_inventory['PluginFusioninventoryNetworkEquipment']['networkequipments_id'] = $items_id;
         $pfNetworkEquipment->add($a_inventory['PluginFusioninventoryNetworkEquipment']);
     } else {
         // Update
         $idtmp = $db_networkequipment['id'];
         unset($db_networkequipment['id']);
         unset($db_networkequipment['networkequipments_id']);
         unset($db_networkequipment['plugin_fusioninventory_configsecurities_id']);
         $a_ret = PluginFusioninventoryToolbox::checkLock($a_inventory['PluginFusioninventoryNetworkEquipment'], $db_networkequipment);
         $a_inventory['PluginFusioninventoryNetworkEquipment'] = $a_ret[0];
         $input = $a_inventory['PluginFusioninventoryNetworkEquipment'];
         $input['id'] = $idtmp;
         $pfNetworkEquipment->update($input);
     }
     // * Ports
     $this->importPorts($a_inventory, $items_id);
 }