static function getList($agents_id = NULL)
 {
     global $PF_CONFIG;
     if (is_null($agents_id)) {
         return array();
     }
     $pfAgent = new PluginFusioninventoryAgent();
     $pfAgent->getFromDB($agents_id);
     $agent = $pfAgent->fields;
     $results = getAllDatasFromTable('glpi_plugin_fusioninventory_deploymirrors');
     if (!isset($agent) || !isset($agent['computers_id'])) {
         return array();
     }
     $computer = new Computer();
     $computer->getFromDB($agent['computers_id']);
     $mirrors = array();
     foreach ($results as $result) {
         if ($computer->fields['locations_id'] == $result['locations_id']) {
             $mirrors[] = $result['url'];
         }
     }
     //add default mirror (this server) if enabled in config
     $entities_id = 0;
     if (isset($agent['entities_id'])) {
         $entities_id = $agent['entities_id'];
     }
     if (isset($PF_CONFIG['server_as_mirror']) && (bool) $PF_CONFIG['server_as_mirror'] == TRUE) {
         $mirrors[] = PluginFusioninventoryAgentmodule::getUrlForModule('DEPLOY', $entities_id) . "?action=getFilePart&file=";
     }
     return $mirrors;
 }
 /**
  * Import data
  *
  * @param $p_DEVICEID XML code to import
  * @param $p_CONTENT XML code to import
  * @param $p_xml value XML code to import
  *
  * @return "" (import ok) / error string (import ko)
  *
  **/
 function import($p_DEVICEID, $a_CONTENT, $arrayinventory)
 {
     $pfTaskjobstate = new PluginFusioninventoryTaskjobstate();
     $pfAgent = new PluginFusioninventoryAgent();
     PluginFusioninventoryCommunication::addLog('Function PluginFusioninventoryCommunicationNetworkDiscovery->import().');
     $errors = '';
     $a_agent = $pfAgent->InfosByKey($p_DEVICEID);
     if (isset($a_CONTENT['PROCESSNUMBER'])) {
         $_SESSION['glpi_plugin_fusioninventory_processnumber'] = $a_CONTENT['PROCESSNUMBER'];
         if ($pfTaskjobstate->getFromDB($a_CONTENT['PROCESSNUMBER'])) {
             if ($pfTaskjobstate->fields['state'] != "3") {
                 $pfTaskjobstate->changeStatus($a_CONTENT['PROCESSNUMBER'], 2);
                 if (!isset($a_CONTENT['AGENT']['START']) and !isset($a_CONTENT['AGENT']['END'])) {
                     $nb_devices = 0;
                     if (isset($a_CONTENT['DEVICE'])) {
                         if (is_int(key($a_CONTENT['DEVICE']))) {
                             $nb_devices = count($a_CONTENT['DEVICE']);
                         } else {
                             $nb_devices = 1;
                         }
                     }
                     $_SESSION['plugin_fusinvsnmp_taskjoblog']['taskjobs_id'] = $a_CONTENT['PROCESSNUMBER'];
                     $_SESSION['plugin_fusinvsnmp_taskjoblog']['items_id'] = $a_agent['id'];
                     $_SESSION['plugin_fusinvsnmp_taskjoblog']['itemtype'] = 'PluginFusioninventoryAgent';
                     $_SESSION['plugin_fusinvsnmp_taskjoblog']['state'] = '6';
                     $_SESSION['plugin_fusinvsnmp_taskjoblog']['comment'] = $nb_devices . ' ==devicesfound==';
                     $this->addtaskjoblog();
                 }
             }
         }
     }
     if ($pfTaskjobstate->getFromDB($a_CONTENT['PROCESSNUMBER'])) {
         if ($pfTaskjobstate->fields['state'] != "3") {
             $pfImportExport = new PluginFusioninventorySnmpmodelImportExport();
             $errors .= $pfImportExport->import_netdiscovery($a_CONTENT, $p_DEVICEID);
             if (isset($a_CONTENT['AGENT']['END'])) {
                 if (isset($a_CONTENT['DICO']) and $a_CONTENT['DICO'] == "REQUEST") {
                     $pfAgent->getFromDB($pfTaskjobstate->fields["plugin_fusioninventory_agents_id"]);
                     $input = array();
                     $input['id'] = $pfAgent->fields['id'];
                     $input["senddico"] = "1";
                     $pfAgent->update($input);
                     $pfTaskjobstate->changeStatusFinish($a_CONTENT['PROCESSNUMBER'], $a_agent['id'], 'PluginFusioninventoryAgent', '1', '==diconotuptodate==');
                 } else {
                     $messages = array('Total Found' => 0, 'Created' => 0, 'Updated' => 0);
                     $messages['Updated'] = countElementsInTable('glpi_plugin_fusioninventory_taskjoblogs', "`plugin_fusioninventory_taskjobstates_id`='" . $a_CONTENT['PROCESSNUMBER'] . "' " . " AND `comment` LIKE '%==updatetheitem==%'");
                     $messages['Created'] = countElementsInTable('glpi_plugin_fusioninventory_taskjoblogs', "`plugin_fusioninventory_taskjobstates_id`='" . $a_CONTENT['PROCESSNUMBER'] . "' " . " AND `comment` LIKE '%==addtheitem==%'");
                     $messages['Total Found'] = $messages['Updated'] + $messages['Created'];
                     $message = 'Total Found:' . $messages['Total Found'] . ' Created:' . $messages['Created'] . ' Updated:' . $messages['Updated'];
                     $pfTaskjobstate->changeStatusFinish($a_CONTENT['PROCESSNUMBER'], $a_agent['id'], 'PluginFusioninventoryAgent', '0', $message);
                 }
             }
         }
     }
     return $errors;
 }
 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;
 }
                             $pfTaskjoblog->add($a_input);
                         }
                     }
                 }
             }
         }
     }
     break;
 case 'setAnswer':
     // example
     // ?action=setAnswer&InformationSource=0x00000000&BIOSVersion=VirtualBox&SystemManufacturer=innotek%20GmbH&uuid=fepjhoug56743h&SystemProductName=VirtualBox&BIOSReleaseDate=12%2F01%2F2006
     $pfTaskjobstate = new PluginFusioninventoryTaskjobstate();
     $pfAgent = new PluginFusioninventoryAgent();
     $jobstate = current($pfTaskjobstate->find("`uniqid`='" . $_GET['uuid'] . "'\n            AND `state`!='" . PluginFusioninventoryTaskjobstate::FINISHED . "'", '', 1));
     if (isset($jobstate['plugin_fusioninventory_agents_id'])) {
         $pfAgent->getFromDB($jobstate['plugin_fusioninventory_agents_id']);
         $computers_id = $pfAgent->fields['computers_id'];
         $a_values = $_GET;
         unset($a_values['action']);
         unset($a_values['uuid']);
         switch ($jobstate['itemtype']) {
             case 'PluginFusioninventoryCollect_Registry':
                 // update registry content
                 $pfCRC = new PluginFusioninventoryCollect_Registry_Content();
                 $pfCRC->updateComputer($computers_id, $a_values, $jobstate['items_id']);
                 $pfTaskjobstate->changeStatus($jobstate['id'], PluginFusioninventoryTaskjobstate::AGENT_HAS_SENT_DATA);
                 if (isset($a_values['_cpt']) && $a_values['_cpt'] == 0) {
                     // it not find the path
                     $pfTaskjobstate->changeStatusFinish($jobstate['id'], $jobstate['items_id'], $jobstate['itemtype'], 1, 'Path not found');
                 }
                 if (isset($a_values['_cpt']) && $a_values['_cpt'] == 1) {
 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;
 }
 /**
  * Display form to add exception of modules activation for each agent
  *
  * @param interger $items_id ID of the agent
  *
  * @return bool TRUE if form is ok
  *
  **/
 function showFormAgentException($items_id)
 {
     global $CFG_GLPI;
     $pfAgent = new PluginFusioninventoryAgent();
     $pfAgent->getFromDB($items_id);
     $canedit = $pfAgent->can($items_id, UPDATE);
     echo "<br/>";
     if ($canedit) {
         echo "<form name='form_ic' method='post' action='" . $CFG_GLPI['root_doc'] . "/plugins/fusioninventory/front/agentmodule.form.php'>";
     }
     echo "<table class='tab_cadre_fixe'>";
     echo "<tr>";
     echo "<th>" . __('Module', 'fusioninventory') . "</th>";
     echo "<th>Activation</th>";
     echo "<th>" . __('Module', 'fusioninventory') . "</th>";
     echo "<th>Activation</th>";
     echo "</tr>";
     $a_modules = $this->find();
     $i = 0;
     $a_methods = PluginFusioninventoryStaticmisc::getmethods();
     foreach ($a_modules as $data) {
         if ($i == 0) {
             echo "<tr class='tab_bg_1'>";
         }
         $modulename = $data["modulename"];
         foreach ($a_methods as $datamod) {
             if (strtolower($data["modulename"]) == strtolower($datamod['method']) || isset($datamod['task']) && strtolower($data["modulename"]) == strtolower($datamod['task'])) {
                 if (isset($datamod['name'])) {
                     $modulename = $datamod['name'];
                 }
                 break;
             }
         }
         // Hack for snmpquery
         if ($data["modulename"] == 'SNMPQUERY') {
             $modulename = __('Network inventory (SNMP)', 'fusioninventory');
         }
         // Hack for deploy
         if ($data["modulename"] == 'DEPLOY') {
             $modulename = __('Package deployment', 'fusioninventory');
         }
         echo "<td width='50%'>" . $modulename . " :</td>";
         echo "<td align='center'>";
         $checked = $data['is_active'];
         $a_agentList = importArrayFromDB($data['exceptions']);
         if (in_array($items_id, $a_agentList)) {
             if ($checked == 1) {
                 $checked = 0;
             } else {
                 $checked = 1;
             }
         }
         $check = "";
         if ($checked == 1) {
             $check = "checked='checked'";
         }
         echo "<input type='checkbox' name='activation-" . $data["modulename"] . "' " . "value='Activation' " . $check . " />";
         echo "</td>";
         if ($i == 1) {
             echo "</tr>";
             $i = -1;
         }
         $i++;
     }
     if ($i == 1) {
         echo "<td></td>";
         echo "<td></td>";
         echo "</tr>";
     }
     if ($canedit) {
         echo "<tr>";
         echo "<td class='tab_bg_2 center' colspan='4'>";
         echo Html::hidden('id', array('value' => $items_id));
         echo "<input type='submit' name='updateexceptions' " . "value=\"" . __('Update') . "\" class='submit'>";
         echo "</td>";
         echo "</tr>";
         echo "</table>";
         Html::closeForm();
     } else {
         echo "</table>";
     }
 }
 static function cronWakeupAgents($crontask)
 {
     global $DB;
     $wakeupArray = array();
     $tasks = array();
     //Get the maximum number of agent to wakeup,
     //as allowed in the general configuration
     $config = new PluginFusioninventoryConfig();
     $maxWakeUp = $config->getValue('wakeup_agent_max');
     $counter = 0;
     $continue = true;
     //Get all active timeslots
     $timeslot = new PluginFusioninventoryTimeslot();
     $timeslots = $timeslot->getCurrentActiveTimeslots();
     if (empty($timeslots)) {
         $query_timeslot = '';
     } else {
         $query_timeslot = "OR (`plugin_fusioninventory_timeslots_id` IN (" . implode(',', $timeslots) . "))";
     }
     //Get all active task requiring an agent wakeup
     //Check all tasks without timeslot or task with a current active timeslot
     $query = "SELECT `id`, `wakeup_agent_counter`, `wakeup_agent_time`, `last_agent_wakeup` \n                 FROM `glpi_plugin_fusioninventory_tasks` \n                 WHERE `wakeup_agent_time` > 0 \n                    AND `wakeup_agent_counter` > 0\n                    AND `is_active`='1' \n                    AND ((`plugin_fusioninventory_timeslots_id`='0') \n                    {$query_timeslot})";
     foreach ($DB->request($query) as $task) {
         if (!is_null($task['wakeup_agent_time'])) {
             //Do not wake up is last wake up in inferior to the minimum wake up interval
             $interval = time() - strtotime($task['last_agent_wakeup']);
             if ($interval < $task['wakeup_agent_time'] * MINUTE_TIMESTAMP) {
                 continue;
             }
         }
         //For each task, get a number of taskjobs at the PREPARED state
         //(the maximum is defined in wakeup_agent_counter)
         $query_states = "SELECT `taskjobstates`.`plugin_fusioninventory_agents_id`, \n                                 `tasks`.`id` as `taskID`, \n                                 `tasks`.`wakeup_agent_time`,\n                                 `tasks`.`last_agent_wakeup`\n                          FROM `glpi_plugin_fusioninventory_taskjobstates` as `taskjobstates`,\n                               `glpi_plugin_fusioninventory_taskjobs` as `taskjobs`\n                          LEFT JOIN `glpi_plugin_fusioninventory_tasks` as `tasks` \n                             ON `tasks`.`id`=`taskjobs`.`plugin_fusioninventory_tasks_id`\n                          WHERE `tasks`.`id`='" . $task['id'] . "' \n                             AND `taskjobs`.`id`=`taskjobstates`.`plugin_fusioninventory_taskjobs_id` \n                             AND `taskjobstates`.`state`='" . PluginFusioninventoryTaskjobstate::PREPARED . "' \n                          ORDER BY `taskjobstates`.`id` ASC LIMIT " . $task['wakeup_agent_counter'];
         foreach ($DB->request($query_states) as $state) {
             $agents_id = $state['plugin_fusioninventory_agents_id'];
             //Check if agent is already added to the list of agents to wake up
             if (!isset($wakeupArray[$agents_id])) {
                 //This agent must be woken up
                 $wakeupArray[$agents_id] = $agents_id;
                 $counter++;
             }
             //Store task ID
             if (!in_array($state['taskID'], $tasks)) {
                 $tasks[] = $state['taskID'];
             }
             //Do not process more than the maximum number of wakeup allowed in the configuration
             if ($counter >= $maxWakeUp) {
                 if (PluginFusioninventoryConfig::isExtradebugActive()) {
                     Toolbox::logDebug(__("Maximum number of agent wakeup reached", 'fusioninventory') . ":" . $maxWakeUp);
                 }
                 $continue = false;
                 break;
             }
         }
         //We've reached the maximum number of agents to wake up !
         if (!$continue) {
             break;
         }
     }
     //Number of agents successfully woken up
     $wokeup = 0;
     $myTask = new PluginFusioninventoryTask();
     if (!empty($tasks)) {
         //Update last wake up time each task
         $query_lastrun = "UPDATE `glpi_plugin_fusioninventory_tasks` \n                           SET `last_agent_wakeup`='" . $_SESSION['glpi_currenttime'] . "' \n                           WHERE `id` IN (" . implode(",", $tasks) . ")";
         $DB->query($query_lastrun);
         $agent = new PluginFusioninventoryAgent();
         //Try to wake up agents one by one
         foreach ($wakeupArray as $ID => $value) {
             $agent->getFromDB($ID);
             if ($agent->wakeUp()) {
                 $wokeup++;
             }
         }
     }
     $crontask->addVolume($wokeup);
     return true;
 }
 /**
  * Display detail of each history line
  *
  * @param  $agents_id integer id of the agent
  * @param $uniqid integer uniq id of each taskjobs runing
  * @param $width integer how large in pixel display array
  *
  * @return value all text to display
  *
  **/
 function showHistoryInDetail($agents_id, $uniqid, $width = "950")
 {
     global $CFG_GLPI;
     $pfTaskjobstate = new PluginFusioninventoryTaskjobstate();
     $pfAgent = new PluginFusioninventoryAgent();
     $text = "<center><table class='tab_cadrehov' style='width: " . $width . "px'>";
     $a_jobstates = $pfTaskjobstate->find('`plugin_fusioninventory_agents_id`="' . $agents_id . '" ' . 'AND `uniqid`="' . $uniqid . '"', '`id` DESC');
     $a_devices_merged = array();
     foreach ($a_jobstates as $data) {
         $displayforceend = 0;
         $a_history = $this->find('`plugin_fusioninventory_taskjobstates_id` = "' . $data['id'] . '"', 'id');
         if (strstr(exportArrayToDB($a_history), "Merged with ")) {
             $classname = $data['itemtype'];
             $Class = new $classname();
             $Class->getFromDB($data['items_id']);
             $a_devices_merged[] = $Class->getLink(1) . "&nbsp;(" . $Class->getTypeName() . ")";
         } else {
             $text .= "<tr>";
             $text .= "<th colspan='2'><img src='" . $CFG_GLPI['root_doc'] . "/pics/puce.gif' />" . __('Process number', 'fusioninventory') . "&nbsp;: " . $data['id'] . "</th>";
             $text .= "<th>";
             $text .= __('Date');
             $text .= "</th>";
             $text .= "<th>";
             $text .= __('Status');
             $text .= "</th>";
             $text .= "<th>";
             $text .= __('Comments');
             $text .= "</th>";
             $text .= "</tr>";
             $text .= "<tr class='tab_bg_1'>";
             $text .= "<th colspan='2'>";
             $text .= __('Agent', 'fusioninventory');
             $text .= "</th>";
             $a_return = $this->displayHistoryDetail(array_shift($a_history));
             $count = $a_return[0];
             $text .= $a_return[1];
             $displayforceend += $count;
             $text .= "</tr>";
             $text .= "<tr class='tab_bg_1'>";
             $text .= "<td colspan='2'>";
             $pfAgent->getFromDB($data['plugin_fusioninventory_agents_id']);
             $text .= $pfAgent->getLink(1);
             $text .= "</td>";
             $a_return = $this->displayHistoryDetail(array_shift($a_history));
             $count = $a_return[0];
             $text .= $a_return[1];
             $displayforceend += $count;
             $text .= "</tr>";
             $text .= "<tr class='tab_bg_1'>";
             $text .= "<th colspan='2'>";
             $text .= __('Definition', 'fusioninventory');
             $text .= "<sup>(" . (count($a_devices_merged) + 1) . ")</sup>";
             $text .= "</th>";
             $a_return = $this->displayHistoryDetail(array_shift($a_history));
             $count = $a_return[0];
             $text .= $a_return[1];
             $displayforceend += $count;
             $text .= "</tr>";
             $text .= "<tr class='tab_bg_1'>";
             $text .= "<td colspan='2'>";
             if (!empty($data["itemtype"])) {
                 $device = new $data["itemtype"]();
                 $device->getFromDB($data["items_id"]);
                 $text .= $device->getLink(1);
                 $text .= "&nbsp;";
                 $text .= "(" . $device->getTypeName() . ")";
             }
             $text .= "</td>";
             $a_return = $this->displayHistoryDetail(array_shift($a_history));
             $count = $a_return[0];
             $text .= $a_return[1];
             $displayforceend += $count;
             $text .= "</tr>";
             while (count($a_history) != 0) {
                 if (count($a_devices_merged) > 0) {
                     $text .= "<tr class='tab_bg_1'>";
                     $text .= "<td colspan='2'>";
                     $text .= array_pop($a_devices_merged);
                     $text .= "</td>";
                     $a_return = $this->displayHistoryDetail(array_shift($a_history));
                     $count = $a_return[0];
                     $text .= $a_return[1];
                     $displayforceend += $count;
                     $text .= "</tr>";
                 } else {
                     $text .= "<tr class='tab_bg_1'>";
                     $text .= "<td colspan='2' rowspan='" . count($a_history) . "'>";
                     $text .= "</td>";
                     $a_return = $this->displayHistoryDetail(array_shift($a_history));
                     $count = $a_return[0];
                     $text .= $a_return[1];
                     $displayforceend += $count;
                     $text .= "</tr>";
                     while (count($a_history) != 0) {
                         $text .= "<tr class='tab_bg_1'>";
                         $a_return = $this->displayHistoryDetail(array_shift($a_history));
                         $count = $a_return[0];
                         $text .= $a_return[1];
                         $displayforceend += $count;
                         $text .= "</tr>";
                     }
                 }
             }
             $display = 1;
             while (count($a_devices_merged) != 0) {
                 $text .= "<tr class='tab_bg_1'>";
                 $text .= "<td colspan='2'>";
                 $text .= array_pop($a_devices_merged);
                 $text .= "</td>";
                 if ($display == "1") {
                     $text .= "<td colspan='3' rowspan='" . (count($a_devices_merged) + 1) . "'></td>";
                     $display = 0;
                 }
                 $text .= "</tr>";
             }
             $text .= "<tr class='tab_bg_4'>";
             $text .= "<td colspan='5' height='4'>";
             $text .= "</td>";
             $text .= "</tr>";
         }
     }
     $text .= "</table></center>";
     return $text;
 }
 public function AgentEntity($computers_id = 0, $entities_id = 0, $text = '')
 {
     global $DB;
     $DB->connect();
     if ($computers_id == 0) {
         return;
     }
     $pfAgent = new PluginFusioninventoryAgent();
     $a_agents_id = $pfAgent->getAgentWithComputerid($computers_id);
     $pfAgent->getFromDB($a_agents_id);
     $this->assertEquals($entities_id, $pfAgent->fields['entities_id'], $text);
 }
Beispiel #10
0
function plugin_fields_rule_matched($params)
{
    global $DB;
    $container = new PluginFieldsContainer();
    switch ($params['sub_type']) {
        case "PluginFusioninventoryTaskpostactionRule":
            $agent = new PluginFusioninventoryAgent();
            if (isset($params['input']['plugin_fusioninventory_agents_id'])) {
                foreach ($params['output'] as $field => $value) {
                    // check if current field is in a tab container
                    $query = "SELECT c.id\n                         FROM glpi_plugin_fields_fields f\n                         LEFT JOIN glpi_plugin_fields_containers c\n                            ON c.id = f.plugin_fields_containers_id\n                         WHERE f.name = '{$field}'";
                    $res = $DB->query($query);
                    if ($DB->numrows($res) > 0) {
                        $data = $DB->fetch_assoc($res);
                        //retrieve computer
                        $agents_id = $params['input']['plugin_fusioninventory_agents_id'];
                        $agent->getFromDB($agents_id);
                        // update current field
                        $container->updateFieldsValues(array('plugin_fields_containers_id' => $data['id'], $field => $value, 'items_id' => $agent->fields['computers_id']));
                    }
                }
            }
            break;
    }
}
 function showForm($items_id, $itemtype)
 {
     $rule = new PluginFusioninventoryInventoryRuleImport();
     $pfAgent = new PluginFusioninventoryAgent();
     echo "<table class='tab_cadre_fixe' cellpadding='1'>";
     echo "<tr>";
     echo "<th colspan='4'>";
     echo __('Rule import logs', 'fusioninventory');
     echo "</th>";
     echo "</tr>";
     echo "<tr>";
     echo "<th>";
     echo __('Date');
     echo "</th>";
     echo "<th>";
     echo __('Rule name');
     echo "</th>";
     echo "<th>";
     echo __('Agent', 'fusioninventory');
     echo "</th>";
     echo "<th>";
     echo __('Module', 'fusioninventory');
     echo "</th>";
     echo "</tr>";
     $allData = $this->find("`itemtype`='" . $itemtype . "'\n                              AND `items_id`='" . $items_id . "'", "`date` DESC");
     foreach ($allData as $data) {
         echo "<tr class='tab_bg_1'>";
         echo "<td align='center'>";
         echo Html::convDateTime($data['date']);
         echo "</td>";
         echo "<td align='center'>";
         if ($rule->getFromDB($data['rules_id'])) {
             echo $rule->getLink(1);
         }
         echo "</td>";
         echo "<td align='center'>";
         if ($pfAgent->getFromDB($data['plugin_fusioninventory_agents_id'])) {
             echo $pfAgent->getLink(1);
         }
         echo "</td>";
         echo "<td>";
         $a_methods = PluginFusioninventoryStaticmisc::getmethods();
         foreach ($a_methods as $mdata) {
             if ($mdata['method'] == $data['method']) {
                 echo $mdata['name'];
             }
         }
         echo "</td>";
         echo "</tr>";
     }
     echo "</table>";
 }
function plugin_fusioninventory_giveItem($type, $id, $data, $num)
{
    global $CFG_GLPI;
    $searchopt =& Search::getOptions($type);
    $table = $searchopt[$id]["table"];
    $field = $searchopt[$id]["field"];
    switch ($table . '.' . $field) {
        case "glpi_plugin_fusioninventory_taskjobs.status":
            $pfTaskjobstate = new PluginFusioninventoryTaskjobstate();
            return $pfTaskjobstate->stateTaskjob($data['raw']['id'], '200', 'htmlvar', 'simple');
            break;
        case "glpi_plugin_fusioninventory_agents.version":
            $array = importArrayFromDB($data['raw']['ITEM_' . $num]);
            $input = "";
            foreach ($array as $name => $version) {
                $input .= "<strong>" . $name . "</strong> : " . $version . "<br/>";
            }
            $input .= "*";
            $input = str_replace("<br/>*", "", $input);
            return $input;
            break;
        case "glpi_plugin_fusioninventory_credentials.itemtype":
            if ($label = PluginFusioninventoryCredential::getLabelByItemtype($data['raw']['ITEM_' . $num])) {
                return $label;
            } else {
                return '';
            }
            break;
        case 'glpi_plugin_fusioninventory_taskjoblogs.state':
            $pfTaskjoblog = new PluginFusioninventoryTaskjoblog();
            return $pfTaskjoblog->getDivState($data['raw']['ITEM_' . $num]);
            break;
        case 'glpi_plugin_fusioninventory_taskjoblogs.comment':
            $comment = $data['raw']['ITEM_' . $num];
            return PluginFusioninventoryTaskjoblog::convertComment($comment);
            break;
        case 'glpi_plugin_fusioninventory_taskjobstates.plugin_fusioninventory_agents_id':
            $pfAgent = new PluginFusioninventoryAgent();
            $pfAgent->getFromDB($data['raw']['ITEM_' . $num]);
            if (!isset($pfAgent->fields['name'])) {
                return NOT_AVAILABLE;
            }
            $itemtype = PluginFusioninventoryTaskjoblog::getStateItemtype($data['raw']['ITEM_0']);
            if ($itemtype == 'PluginFusioninventoryDeployPackage') {
                $computer = new Computer();
                $computer->getFromDB($pfAgent->fields['computers_id']);
                return $computer->getLink(1);
            }
            return $pfAgent->getLink(1);
            break;
        case 'glpi_plugin_fusioninventory_ignoredimportdevices.ip':
        case 'glpi_plugin_fusioninventory_ignoredimportdevices.mac':
            $array = importArrayFromDB($data['raw']['ITEM_' . $num]);
            return implode("<br/>", $array);
            break;
        case 'glpi_plugin_fusioninventory_ignoredimportdevices.method':
            $a_methods = PluginFusioninventoryStaticmisc::getmethods();
            foreach ($a_methods as $mdata) {
                if ($mdata['method'] == $data['raw']['ITEM_' . $num]) {
                    return $mdata['name'];
                }
            }
            break;
    }
    if ($table == "glpi_plugin_fusioninventory_agentmodules") {
        if ($type == 'Computer') {
            $pfAgentmodule = new PluginFusioninventoryAgentmodule();
            $a_modules = $pfAgentmodule->find("`modulename`='" . $field . "'");
            $data2 = current($a_modules);
            if ($table . "." . $field == "glpi_plugin_fusioninventory_agentmodules." . $data2['modulename']) {
                if (strstr($data['raw']["ITEM_" . $num . "_0"], '"' . $data['raw']["ITEM_" . $num . "_1"] . '"')) {
                    if ($data['raw']['ITEM_' . $num] == '0') {
                        return Dropdown::getYesNo(TRUE);
                    } else {
                        return Dropdown::getYesNo(FALSE);
                    }
                }
                return Dropdown::getYesNo($data['raw']['ITEM_' . $num]);
            }
        } else {
            $pfAgentmodule = new PluginFusioninventoryAgentmodule();
            $a_modules = $pfAgentmodule->find("`modulename`='" . $field . "'");
            foreach ($a_modules as $data2) {
                if ($table . "." . $field == "glpi_plugin_fusioninventory_agentmodules." . $data2['modulename']) {
                    if (strstr($data['raw']["ITEM_" . $num . "_0"], '"' . $data['raw']['id'] . '"')) {
                        if ($data['raw']['ITEM_' . $num] == 0) {
                            return Dropdown::getYesNo('1');
                        } else {
                            return Dropdown::getYesNo('0');
                        }
                    }
                    return Dropdown::getYesNo($data['raw']['ITEM_' . $num]);
                }
            }
        }
    }
    switch ($type) {
        case 'Computer':
            if ($table . '.' . $field == 'glpi_plugin_fusioninventory_networkports.id') {
                if (strstr($data['raw']["ITEM_{$num}"], "\$")) {
                    $split = explode("\$\$\$\$", $data['raw']["ITEM_{$num}"]);
                    $ports = array();
                    foreach ($split as $portconcat) {
                        $split2 = explode("....", $portconcat);
                        if (isset($split2[1])) {
                            $ports[] = $split2[1];
                        }
                    }
                    $out = implode("<br/>", $ports);
                    return $out;
                }
            }
            break;
            // * Networking List (front/networking.php)
        // * Networking List (front/networking.php)
        case 'NetworkEquipment':
            switch ($table . '.' . $field) {
            }
            break;
        case 'Printer':
            if ($table . '.' . $field == 'glpi_plugin_fusioninventory_networkequipments.name') {
                if (strstr($data['raw']["ITEM_{$num}"], "\$")) {
                    $split = explode("\$\$\$\$", $data['raw']["ITEM_{$num}"]);
                    $out = implode("<br/>", $split);
                    return $out;
                }
            }
            break;
            // * Authentification List (plugins/fusinvsnmp/front/configsecurity.php)
        // * Authentification List (plugins/fusinvsnmp/front/configsecurity.php)
        case 'PluginFusioninventoryConfigSecurity':
            switch ($table . '.' . $field) {
                // ** Hidden auth passphrase (SNMP v3)
                case "glpi_plugin_fusioninventory_configsecurities.auth_passphrase":
                    $out = "";
                    if (empty($data['raw']["ITEM_{$num}"])) {
                    } else {
                        $out = "********";
                    }
                    return $out;
                    break;
                    // ** Hidden priv passphrase (SNMP v3)
                // ** Hidden priv passphrase (SNMP v3)
                case "glpi_plugin_fusioninventory_configsecurities.priv_passphrase":
                    $out = "";
                    if (empty($data['raw']["ITEM_{$num}"])) {
                    } else {
                        $out = "********";
                    }
                    return $out;
                    break;
            }
            break;
            // * Unknown mac addresses connectd on switch - report
            //   (plugins/fusinvsnmp/report/unknown_mac.php)
        // * Unknown mac addresses connectd on switch - report
        //   (plugins/fusinvsnmp/report/unknown_mac.php)
        case 'PluginFusioninventoryUnmanaged':
            switch ($table . '.' . $field) {
                // ** FusionInventory - switch
                case "glpi_plugin_fusioninventory_networkequipments.id":
                    $out = '';
                    $NetworkPort = new NetworkPort();
                    $list = explode("\$\$\$\$", $data['raw']["ITEM_{$num}"]);
                    foreach ($list as $numtmp => $vartmp) {
                        $NetworkPort->getDeviceData($vartmp, 'PluginFusioninventoryUnmanaged');
                        $out .= "<a href=\"" . $CFG_GLPI["root_doc"] . "/";
                        $out .= "plugins/fusioninventory/front/unmanaged.form.php?id=" . $vartmp . "\">";
                        $out .= $NetworkPort->device_name;
                        if ($CFG_GLPI["view_ID"]) {
                            $out .= " (" . $vartmp . ")";
                        }
                        $out .= "</a><br/>";
                    }
                    return "<center>" . $out . "</center>";
                    break;
                    // ** FusionInventory - switch port
                // ** FusionInventory - switch port
                case "glpi_plugin_fusioninventory_networkports.id":
                    $out = '';
                    if (!empty($data['raw']["ITEM_{$num}"])) {
                        $list = explode("\$\$\$\$", $data['raw']["ITEM_{$num}"]);
                        $np = new NetworkPort();
                        foreach ($list as $numtmp => $vartmp) {
                            $np->getFromDB($vartmp);
                            $out .= "<a href='" . $CFG_GLPI['root_doc'] . "/front/networkport.form.php?id=" . $vartmp . "'>";
                            $out .= $np->fields["name"] . "</a><br/>";
                        }
                    }
                    return "<center>" . $out . "</center>";
                    break;
                case "glpi_plugin_fusinvsnmp_unmanageds.type":
                    $out = '<center> ';
                    switch ($data['raw']["ITEM_{$num}"]) {
                        case COMPUTER_TYPE:
                            $out .= __('Computers');
                            break;
                        case NETWORKING_TYPE:
                            $out .= __('Networks');
                            break;
                        case PRINTER_TYPE:
                            $out .= __('Printers');
                            break;
                        case PERIPHERAL_TYPE:
                            $out .= __('Devices');
                            break;
                        case PHONE_TYPE:
                            $out .= __('Phones');
                            break;
                    }
                    $out .= '</center>';
                    return $out;
                    break;
            }
            break;
            // * Ports date connection - report (plugins/fusinvsnmp/report/ports_date_connections.php)
        // * Ports date connection - report (plugins/fusinvsnmp/report/ports_date_connections.php)
        case 'PluginFusioninventoryNetworkPort':
            switch ($table . '.' . $field) {
                // ** Name and link of networking device (switch)
                case "glpi_plugin_fusioninventory_networkports.id":
                    $query = "SELECT `glpi_networkequipments`.`name` AS `name`, `glpi_networkequipments`.`id` AS `id`\n                         FROM `glpi_networkequipments`\n                              LEFT JOIN `glpi_networkports`\n                                        ON `items_id` = `glpi_networkequipments`.`id`\n                              LEFT JOIN `glpi_plugin_fusioninventory_networkports`\n                                        ON `glpi_networkports`.`id`=`networkports_id`\n                         WHERE `glpi_plugin_fusioninventory_networkports`.`id`='" . $data['raw']["ITEM_{$num}"] . "'\n                         LIMIT 0, 1;";
                    $result = $DB->query($query);
                    $data2 = $DB->fetch_assoc($result);
                    $out = "<a href='" . $CFG_GLPI['root_doc'] . "/front/networking.form.php?id=" . $data2["id"] . "'>";
                    $out .= $data2["name"] . "</a>";
                    return "<center>" . $out . "</center>";
                    break;
                    // ** Name and link of port of networking device (port of switch)
                // ** Name and link of port of networking device (port of switch)
                case "glpi_plugin_fusioninventory_networkports.networkports_id":
                    $NetworkPort = new NetworkPort();
                    $NetworkPort->getFromDB($data['raw']["ITEM_{$num}"]);
                    $name = "";
                    if (isset($NetworkPort->fields["name"])) {
                        $name = $NetworkPort->fields["name"];
                    }
                    $out = "<a href='" . $CFG_GLPI['root_doc'] . "/front/networkport.form.php?id=" . $data['raw']["ITEM_{$num}"];
                    $out .= "'>" . $name . "</a>";
                    return "<center>" . $out . "</center>";
                    break;
                    // ** Location of switch
                // ** Location of switch
                case "glpi_locations.id":
                    $out = Dropdown::getDropdownName("glpi_locations", $data['raw']["ITEM_{$num}"]);
                    return "<center>" . $out . "</center>";
                    break;
            }
            break;
            // * range IP list (plugins/fusinvsnmp/front/iprange.php)
        // * range IP list (plugins/fusinvsnmp/front/iprange.php)
        case 'PluginFusioninventoryIPRange':
            switch ($table . '.' . $field) {
                // ** Display entity name
                case "glpi_entities.name":
                    if ($data['raw']["ITEM_{$num}"] == '') {
                        $out = Dropdown::getDropdownName("glpi_entities", $data['raw']["ITEM_{$num}"]);
                        return "<center>" . $out . "</center>";
                    }
                    break;
            }
            break;
        case 'PluginFusioninventoryNetworkPortLog':
            switch ($table . '.' . $field) {
                // ** Display switch and Port
                case "glpi_networkports.id":
                    $Array_device = PluginFusioninventoryNetworkPort::getUniqueObjectfieldsByportID($data['raw']["ITEM_{$num}"]);
                    $item = new $Array_device["itemtype"]();
                    $item->getFromDB($Array_device["items_id"]);
                    $out = "<div align='center'>" . $item->getLink(1);
                    $query = "SELECT *\n                         FROM `glpi_networkports`\n                         WHERE `id`='" . $data['raw']["ITEM_{$num}"] . "';";
                    $result = $DB->query($query);
                    if ($DB->numrows($result) != "0") {
                        $out .= "<br/><a href='" . $CFG_GLPI['root_doc'] . "/front/networkport.form.php?id=";
                        $out .= $data['raw']["ITEM_{$num}"] . "'>" . $DB->result($result, 0, "name") . "</a>";
                    }
                    $out .= "</td>";
                    return $out;
                    break;
                    // ** Display GLPI field of device
                // ** Display GLPI field of device
                case "glpi_plugin_fusinvsnmp_networkportlogs.field":
                    //               $out = $FUSIONINVENTORY_MAPPING[NETWORKING_TYPE][$data['raw']["ITEM_$num"]]['name'];
                    $out = '';
                    $map = new PluginFusioninventoryMapping();
                    $mapfields = $map->get('NetworkEquipment', $data['raw']["ITEM_{$num}"]);
                    if ($mapfields != FALSE) {
                        $out = _get('_LANG[\'plugin_fusinvsnmp\'][\'mapping\'][$mapfields["locale"]]');
                    }
                    return $out;
                    break;
                    // ** Display Old Value (before changement of value)
                // ** Display Old Value (before changement of value)
                case "glpi_plugin_fusinvsnmp_networkportlogs.old_value":
                    // TODO ADD LINK TO DEVICE
                    if (substr_count($data['raw']["ITEM_{$num}"], ":") == 5 && empty($data['raw']["ITEM_3"])) {
                        return "<center><b>" . $data['raw']["ITEM_{$num}"] . "</b></center>";
                    }
                    break;
                    // ** Display New Value (new value modified)
                // ** Display New Value (new value modified)
                case "glpi_plugin_fusinvsnmp_networkportlogs.new_value":
                    if (substr_count($data['raw']["ITEM_{$num}"], ":") == 5 && empty($data['raw']["ITEM_3"])) {
                        return "<center><b>" . $data['raw']["ITEM_{$num}"] . "</b></center>";
                    }
                    break;
            }
            break;
        case "PluginFusioninventoryPrinterLog":
            switch ($table . '.' . $field) {
                case 'glpi_printers.name':
                    // Search pages in printer history to limit SQL queries
                    if (isset($_SESSION['glpi_plugin_fusioninventory_history_start'])) {
                        unset($_SESSION['glpi_plugin_fusioninventory_history_start']);
                    }
                    if (isset($_SESSION['glpi_plugin_fusioninventory_history_end'])) {
                        unset($_SESSION['glpi_plugin_fusioninventory_history_end']);
                    }
                    if (isset($_SESSION['glpi_plugin_fusioninventory_date_start']) and isset($_SESSION['glpi_plugin_fusioninventory_date_end'])) {
                        $query = "SELECT * FROM `glpi_plugin_fusioninventory_printerlogs`\n                     WHERE `printers_id`='" . $data['raw']['ITEM_0_2'] . "'\n                        AND `date`>= '" . $_SESSION['glpi_plugin_fusioninventory_date_start'] . "'\n                        AND `date`<= '" . $_SESSION['glpi_plugin_fusioninventory_date_end'] . " 23:59:59'\n                     ORDER BY date asc\n                     LIMIT 1";
                        $result = $DB->query($query);
                        while ($data2 = $DB->fetch_array($result)) {
                            $_SESSION['glpi_plugin_fusioninventory_history_start'] = $data2;
                        }
                        $query = "SELECT * FROM `glpi_plugin_fusioninventory_printerlogs`\n                     WHERE `printers_id`='" . $data['raw']['ITEM_0_2'] . "'\n                        AND `date`>= '" . $_SESSION['glpi_plugin_fusioninventory_date_start'] . "'\n                        AND `date`<= '" . $_SESSION['glpi_plugin_fusioninventory_date_end'] . " 23:59:59'\n                     ORDER BY date desc\n                     LIMIT 1";
                        $result = $DB->query($query);
                        while ($data2 = $DB->fetch_array($result)) {
                            $_SESSION['glpi_plugin_fusioninventory_history_end'] = $data2;
                        }
                    }
                    return "";
                    break;
            }
            switch ($table) {
                case 'glpi_plugin_fusioninventory_printerlogs':
                    if (isset($_SESSION['glpi_plugin_fusioninventory_history_start'][$field]) and isset($_SESSION['glpi_plugin_fusioninventory_history_end'][$field])) {
                        $counter_start = $_SESSION['glpi_plugin_fusioninventory_history_start'][$field];
                        $counter_end = $_SESSION['glpi_plugin_fusioninventory_history_end'][$field];
                        if ($_SESSION['glpi_plugin_fusioninventory_date_start'] == "1970-01-01") {
                            $counter_start = 0;
                        }
                        $number = $counter_end - $counter_start;
                        if ($number == '0') {
                            return '-';
                        } else {
                            return $number;
                        }
                    } else {
                        return '-';
                    }
                    break;
            }
            break;
    }
    return "";
}
  @co-author
  @copyright Copyright (c) 2010-2014 FusionInventory team
  @license   AGPL License 3.0 or (at your option) any later version
             http://www.gnu.org/licenses/agpl-3.0-standalone.html
  @link      http://www.fusioninventory.org/
  @link      http://forge.fusioninventory.org/projects/fusioninventory-for-glpi/
  @since     2010

  ------------------------------------------------------------------------
*/
include "../../../inc/includes.php";
$agent = new PluginFusioninventoryAgent();
Session::checkRight('plugin_fusioninventory_agent', READ);
if (isset($_POST['startagent'])) {
    $agent = new PluginFusioninventoryAgent();
    $agent->getFromDB($_POST['agent_id']);
    if ($agent->wakeUp()) {
        Session::addMessageAfterRedirect(__('The agent is running', 'fusioninventory'));
    } else {
        Session::addMessageAfterRedirect(__('Impossible to communicate with agent!', 'fusioninventory'));
    }
    Html::back();
} else {
    if (isset($_POST["update"])) {
        Session::checkRight('plugin_fusioninventory_agent', UPDATE);
        if (isset($_POST['items_id'])) {
            if ($_POST['items_id'] != "0" and $_POST['items_id'] != "") {
                $_POST['itemtype'] = '1';
            }
        }
        $agent->update($_POST);
 function prepareRun($taskjobs_id)
 {
     global $DB;
     $pfTask = new PluginFusioninventoryTask();
     $pfTaskjob = new PluginFusioninventoryTaskjob();
     $pfTaskjobstate = new PluginFusioninventoryTaskjobstate();
     $pfTaskjoblog = new PluginFusioninventoryTaskjoblog();
     $pfAgent = new PluginFusioninventoryAgent();
     $uniqid = uniqid();
     $pfTaskjob->getFromDB($taskjobs_id);
     $pfTask->getFromDB($pfTaskjob->fields['plugin_fusioninventory_tasks_id']);
     $communication = $pfTask->fields['communication'];
     $a_definitions = importArrayFromDB($pfTaskjob->fields['definition']);
     $a_computers_to_wake = array();
     foreach ($a_definitions as $definition) {
         $itemtype = key($definition);
         $items_id = current($definition);
         switch ($itemtype) {
             case 'Computer':
                 $a_computers_to_wake[] = $items_id;
                 break;
             case 'PluginFusioninventoryDeployGroup':
                 $group = new PluginFusioninventoryDeployGroup();
                 $group->getFromDB($items_id);
                 switch ($group->getField('type')) {
                     case 'STATIC':
                         $query = "SELECT items_id\n                     FROM glpi_plugin_fusioninventory_deploygroups_staticdatas\n                     WHERE groups_id = '{$items_id}'\n                     AND itemtype = 'Computer'";
                         $res = $DB->query($query);
                         while ($row = $DB->fetch_assoc($res)) {
                             $a_computers_to_wake[] = $row['items_id'];
                         }
                         break;
                     case 'DYNAMIC':
                         $query = "SELECT fields_array\n                     FROM glpi_plugin_fusioninventory_deploygroups_dynamicdatas\n                     WHERE groups_id = '{$items_id}'\n                     LIMIT 1";
                         $res = $DB->query($query);
                         $row = $DB->fetch_assoc($res);
                         if (isset($_GET)) {
                             $get_tmp = $_GET;
                         }
                         if (isset($_SESSION["glpisearchcount"]['Computer'])) {
                             unset($_SESSION["glpisearchcount"]['Computer']);
                         }
                         if (isset($_SESSION["glpisearchcount2"]['Computer'])) {
                             unset($_SESSION["glpisearchcount2"]['Computer']);
                         }
                         $_GET = importArrayFromDB($row['fields_array']);
                         $_GET["glpisearchcount"] = count($_GET['field']);
                         if (isset($_GET['field2'])) {
                             $_GET["glpisearchcount2"] = count($_GET['field2']);
                         }
                         $pfSearch = new PluginFusioninventorySearch();
                         Search::manageGetValues('Computer');
                         $glpilist_limit = $_SESSION['glpilist_limit'];
                         $_SESSION['glpilist_limit'] = 999999999;
                         $result = $pfSearch->constructSQL('Computer', $_GET);
                         $_SESSION['glpilist_limit'] = $glpilist_limit;
                         while ($data = $DB->fetch_array($result)) {
                             $a_computers_to_wake[] = $data['id'];
                         }
                         if (count($get_tmp) > 0) {
                             $_GET = $get_tmp;
                         }
                         break;
                 }
         }
     }
     $a_actions = importArrayFromDB($pfTaskjob->fields['action']);
     $a_agentList = array();
     if (!strstr($pfTaskjob->fields['action'], '".1"') and !strstr($pfTaskjob->fields['action'], '".2"')) {
         foreach ($a_actions as $a_action) {
             if (!in_array('.1', $a_action) && !in_array('.2', $a_action)) {
                 $agent_id = current($a_action);
                 if ($pfAgent->getFromDB($agent_id)) {
                     if ($communication == 'pull') {
                         $a_agentList[] = $agent_id;
                     } else {
                         if ($pfTaskjob->isAgentAlive('1', $agent_id)) {
                             $a_agentList[] = $agent_id;
                         }
                     }
                 }
             }
         }
     } else {
         if (strstr($pfTaskjob->fields['action'], '".1"')) {
             $a_agentList = $this->getAgentsSubnet(count($a_computers_to_wake), $communication);
         } else {
             if (in_array('.2', $a_actions)) {
                 $subnet = '';
                 foreach ($a_computers_to_wake as $items_id) {
                     $sql = "SELECT * FROM `glpi_networkports`\n               WHERE `items_id`='" . $items_id . "'\n                  AND `itemtype`='Computer'\n                  AND `mac`!='' ";
                     $result = $DB->query($sql);
                     if ($result) {
                         while ($data = $DB->fetch_array($result)) {
                             $subnet = $data['subnet'];
                         }
                     }
                 }
                 if ($subnet != '') {
                     $a_agentList = $this->getAgentsSubnet(count($a_computers_to_wake), $communication, $subnet);
                 }
             }
         }
     }
     if (count($a_agentList) == '0') {
         $a_input = array();
         $a_input['plugin_fusioninventory_taskjobs_id'] = $taskjobs_id;
         $a_input['state'] = 1;
         $a_input['plugin_fusioninventory_agents_id'] = 0;
         $a_input['itemtype'] = 'Computer';
         $a_input['items_id'] = 0;
         $a_input['uniqid'] = $uniqid;
         $Taskjobstates_id = $pfTaskjobstate->add($a_input);
         //Add log of taskjob
         $a_input['plugin_fusioninventory_taskjobstates_id'] = $Taskjobstates_id;
         $a_input['state'] = 7;
         $a_input['date'] = date("Y-m-d H:i:s");
         $pfTaskjoblog->add($a_input);
         $pfTaskjobstate->changeStatusFinish($Taskjobstates_id, 0, 'Computer', 1, "Unable to find agent to run this job");
     } else {
         $nb_computers = ceil(count($a_computers_to_wake) / count($a_agentList));
         $a_input = array();
         $a_input['plugin_fusioninventory_taskjobs_id'] = $taskjobs_id;
         $a_input['state'] = 0;
         $a_input['itemtype'] = 'Computer';
         $a_input['uniqid'] = $uniqid;
         while (count($a_computers_to_wake) != 0) {
             $agent_id = array_pop($a_agentList);
             $a_input['plugin_fusioninventory_agents_id'] = $agent_id;
             for ($i = 0; $i < $nb_computers; $i++) {
                 //Add jobstate and put status
                 $a_input['items_id'] = array_pop($a_computers_to_wake);
                 $Taskjobstates_id = $pfTaskjobstate->add($a_input);
                 //Add log of taskjob
                 $a_input['plugin_fusioninventory_taskjobstates_id'] = $Taskjobstates_id;
                 $a_input['state'] = 7;
                 $a_input['date'] = date("Y-m-d H:i:s");
                 $pfTaskjoblog->add($a_input);
                 unset($a_input['state']);
                 if ($communication == "push") {
                     $_SESSION['glpi_plugin_fusioninventory']['agents'][$agent_id] = 1;
                 }
             }
         }
     }
     $pfTaskjob->fields['status'] = 1;
     $pfTaskjob->update($pfTaskjob->fields);
     return $uniqid;
 }
 function display($options = array())
 {
     global $DB, $CFG_GLPI;
     $pfAgent = new PluginFusioninventoryAgent();
     $pfTaskjobstate = new PluginFusioninventoryTaskjobstate();
     $pfTaskjoblog = new PluginFusioninventoryTaskjoblog();
     $pfStateInventory = new PluginFusioninventoryStateInventory();
     $pfTaskjob = new PluginFusioninventoryTaskjob();
     $start = 0;
     if (isset($_REQUEST["start"])) {
         $start = $_REQUEST["start"];
     }
     // Total Number of events
     $querycount = "SELECT count(*) AS cpt FROM `glpi_plugin_fusioninventory_taskjobstates`\n         LEFT JOIN `glpi_plugin_fusioninventory_taskjobs`\n            ON `plugin_fusioninventory_taskjobs_id` = `glpi_plugin_fusioninventory_taskjobs`.`id`\n         WHERE `method` = 'networkdiscovery'\n         GROUP BY `uniqid`\n         ORDER BY `uniqid` DESC ";
     $resultcount = $DB->query($querycount);
     $number = $DB->numrows($resultcount);
     // Display the pager
     Html::printPager($start, $number, $CFG_GLPI['root_doc'] . "/plugins/fusioninventory/front/stateinventory.php", '');
     echo "<table class='tab_cadre_fixe'>";
     echo "<tr class='tab_bg_1'>";
     echo "<th>" . __('Unique id', 'fusioninventory') . "</th>";
     echo "<th>" . __('Task job', 'fusioninventory') . "</th>";
     echo "<th>" . __('Agent', 'fusioninventory') . "</th>";
     echo "<th>" . __('Status') . "</th>";
     echo "<th>" . __('Starting date', 'fusioninventory') . "</th>";
     echo "<th>" . __('Ending date', 'fusioninventory') . "</th>";
     echo "<th>" . __('Total duration') . "</th>";
     echo "<th>" . __('Threads number', 'fusioninventory') . "</th>";
     echo "<th>" . __('Total discovery devices', 'fusioninventory') . "</th>";
     echo "<th>" . __('Devices not imported', 'fusioninventory') . "</th>";
     echo "<th>" . __('Devices linked', 'fusioninventory') . "</th>";
     echo "<th>" . __('Devices imported', 'fusioninventory') . "</th>";
     echo "</tr>";
     $sql = "SELECT `glpi_plugin_fusioninventory_taskjobstates`.*\n            FROM `glpi_plugin_fusioninventory_taskjobstates`\n         LEFT JOIN `glpi_plugin_fusioninventory_taskjobs`\n            ON `plugin_fusioninventory_taskjobs_id` = `glpi_plugin_fusioninventory_taskjobs`.`id`\n         WHERE `method` = 'networkdiscovery'\n         GROUP BY `uniqid`\n         ORDER BY `uniqid` DESC\n         LIMIT " . intval($start) . ", " . intval($_SESSION['glpilist_limit']);
     $result = $DB->query($sql);
     while ($data = $DB->fetch_array($result)) {
         echo "<tr class='tab_bg_1'>";
         echo "<td>" . $data['uniqid'] . "</td>";
         $pfTaskjob->getFromDB($data['plugin_fusioninventory_taskjobs_id']);
         echo "<td>" . $pfTaskjob->getLink() . "</td>";
         $pfAgent->getFromDB($data['plugin_fusioninventory_agents_id']);
         echo "<td>" . $pfAgent->getLink(1) . "</td>";
         $nb_found = 0;
         $nb_threads = 0;
         $start_date = "";
         $end_date = "";
         $notimporteddevices = 0;
         $updateddevices = 0;
         $createddevices = 0;
         $a_taskjobstates = $pfTaskjobstate->find("`uniqid`='" . $data['uniqid'] . "'");
         foreach ($a_taskjobstates as $datastate) {
             $a_taskjoblog = $pfTaskjoblog->find("`plugin_fusioninventory_taskjobstates_id`='" . $datastate['id'] . "'");
             foreach ($a_taskjoblog as $taskjoblog) {
                 if (strstr($taskjoblog['comment'], " ==devicesfound==")) {
                     $nb_found += str_replace(" ==devicesfound==", "", $taskjoblog['comment']);
                 } else {
                     if (strstr($taskjoblog['comment'], "==importdenied==")) {
                         $notimporteddevices++;
                     } else {
                         if (strstr($taskjoblog['comment'], "==updatetheitem==")) {
                             $updateddevices++;
                         } else {
                             if (strstr($taskjoblog['comment'], "==addtheitem==")) {
                                 $createddevices++;
                             } else {
                                 if ($taskjoblog['state'] == "1") {
                                     $nb_threads = str_replace(" threads", "", $taskjoblog['comment']);
                                     $start_date = $taskjoblog['date'];
                                 }
                             }
                         }
                     }
                 }
                 if ($taskjoblog['state'] == "2" or $taskjoblog['state'] == "3" or $taskjoblog['state'] == "4" or $taskjoblog['state'] == "5") {
                     if (!strstr($taskjoblog['comment'], 'Merged with ')) {
                         $end_date = $taskjoblog['date'];
                     }
                 }
             }
         }
         // State
         echo "<td>";
         switch ($data['state']) {
             case 0:
                 echo __('Prepared', 'fusioninventory');
                 break;
             case 1:
             case 2:
                 echo __('Started', 'fusioninventory');
                 break;
             case 3:
                 echo __('Finished tasks', 'fusioninventory');
                 break;
         }
         echo "</td>";
         echo "<td>" . Html::convDateTime($start_date) . "</td>";
         echo "<td>" . Html::convDateTime($end_date) . "</td>";
         if ($end_date == '') {
             $end_date = date("Y-m-d H:i:s");
         }
         if ($start_date == '') {
             echo "<td>-</td>";
         } else {
             $interval = '';
             if (phpversion() >= 5.3) {
                 $date1 = new DateTime($start_date);
                 $date2 = new DateTime($end_date);
                 $interval = $date1->diff($date2);
                 $display_date = '';
                 if ($interval->h > 0) {
                     $display_date .= $interval->h . "h ";
                 } else {
                     if ($interval->i > 0) {
                         $display_date .= $interval->i . "min ";
                     }
                 }
                 echo "<td>" . $display_date . $interval->s . "s</td>";
             } else {
                 $interval = $pfStateInventory->date_diff($start_date, $end_date);
             }
         }
         echo "<td>" . $nb_threads . "</td>";
         echo "<td>" . $nb_found . "</td>";
         echo "<td>" . $notimporteddevices . "</td>";
         echo "<td>" . $updateddevices . "</td>";
         echo "<td>" . $createddevices . "</td>";
         echo "</tr>";
     }
     echo "</table>";
 }