/**
  * 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;
 }
 /**
  * @test
  */
 public function getDevicesToInventory()
 {
     global $DB;
     // Verify prepare a network discovery task
     $DB->connect();
     $pfNetworkinventory = new PluginFusioninventoryNetworkinventory();
     $jobstate = new PluginFusioninventoryTaskjobstate();
     $jobstate->getFromDB(1);
     $data = $pfNetworkinventory->run($jobstate);
     $this->mark_incomplete("This test doesn't assert anything! Also, there are too much notices thrown ... needs" . "investigations.");
 }
 /**
  * Cron for clean taskjob
  *
  * @return nothing
  */
 static function cronCleantaskjob()
 {
     global $DB;
     $config = new PluginFusioninventoryConfig();
     $retentiontime = $config->getValue('delete_task');
     $pfTaskjobstate = new PluginFusioninventoryTaskjobstate();
     $sql = "SELECT * FROM `glpi_plugin_fusioninventory_taskjoblogs`\n         WHERE  `date` < date_add(now(), interval -" . $retentiontime . " day)\n         GROUP BY `plugin_fusioninventory_taskjobstates_id`";
     $result = $DB->query($sql);
     if ($result) {
         while ($data = $DB->fetch_array($result)) {
             $pfTaskjobstate->getFromDB($data['plugin_fusioninventory_taskjobstates_id']);
             $pfTaskjobstate->delete($pfTaskjobstate->fields, 1);
             $sql_delete = "DELETE FROM `glpi_plugin_fusioninventory_taskjoblogs`\n               WHERE `plugin_fusioninventory_taskjobstates_id` = '" . $data['plugin_fusioninventory_taskjobstates_id'] . "'";
             $DB->query($sql_delete);
         }
     }
 }
 /**
  * @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);
 }
 /**
  * Display each history line
  *
  * @param $taskjobstates_id integer id of the taskjobstate
  *
  * @return nothing
  *
  **/
 function showHistoryLines($taskjobstates_id, $displayprocess = 1, $displaytaskjob = 0, $nb_td = '5')
 {
     global $CFG_GLPI;
     $pfTaskjobstate = new PluginFusioninventoryTaskjobstate();
     $pfAgent = new PluginFusioninventoryAgent();
     $pfTaskjobstate->getFromDB($taskjobstates_id);
     $displayforceend = 0;
     $a_history = $this->find('`plugin_fusioninventory_taskjobstates_id` = "' . $pfTaskjobstate->fields['id'] . '"', 'id DESC', '1');
     echo "<tr class='tab_bg_1'>";
     echo "<td width='40' id='plusmoins" . $pfTaskjobstate->fields["id"] . "'><img src='" . $CFG_GLPI['root_doc'] . "/plugins/fusioninventory/pics/expand.png' " . "onClick='document.getElementById(\"viewfollowup" . $pfTaskjobstate->fields["id"] . "\").show();close_array(" . $pfTaskjobstate->fields["id"] . ");' /></td>";
     echo "<td>";
     echo $pfTaskjobstate->fields['uniqid'];
     echo "</td>";
     if ($displayprocess == '1') {
         echo "<td>";
         echo $pfTaskjobstate->fields['id'];
         echo "</td>";
     }
     if ($displaytaskjob == '1') {
         $pfTaskjob = new PluginFusioninventoryTaskjob();
         $pfTask = new PluginFusioninventoryTask();
         $pfTaskjob->getFromDB($pfTaskjobstate->fields['plugin_fusioninventory_taskjobs_id']);
         $pfTask->getFromDB($pfTaskjob->fields['plugin_fusioninventory_tasks_id']);
         echo "<td>";
         echo $pfTaskjob->getLink(1) . " (" . $pfTask->getLink() . ")";
         echo "</td>";
     }
     echo "<td>";
     $pfAgent->getFromDB($pfTaskjobstate->fields['plugin_fusioninventory_agents_id']);
     echo $pfAgent->getLink(1);
     Ajax::UpdateItemOnEvent('plusmoins' . $pfTaskjobstate->fields["id"], 'viewfollowup' . $pfTaskjobstate->fields["id"], $CFG_GLPI['root_doc'] . "/plugins/fusioninventory/ajax/showtaskjoblogdetail.php", array('agents_id' => $pfTaskjobstate->fields['plugin_fusioninventory_agents_id'], 'uniqid' => $pfTaskjobstate->fields['uniqid']), array("click"));
     echo "</td>";
     $a_return = $this->displayHistoryDetail(array_pop($a_history), 0);
     $count = $a_return[0];
     $displayforceend += $count;
     echo $a_return[1];
     if ($displayforceend == "0") {
         echo "<td align='center'>";
         echo "<form name='form' method='post' action='" . $CFG_GLPI['root_doc'] . "/plugins/fusioninventory/front/taskjob.form.php'>";
         echo "<input type='hidden' name='taskjobstates_id' value='" . $pfTaskjobstate->fields['id'] . "' />";
         echo "<input type='hidden' name='taskjobs_id' value='" . $pfTaskjobstate->fields['plugin_fusioninventory_taskjobs_id'] . "' />";
         echo '<input name="forceend" value="' . __('Force the end', 'fusioninventory') . '"
          class="submit" type="submit">';
         Html::closeForm();
         echo "</td>";
     }
     echo "</tr>";
     echo "<tr>";
     echo "<td colspan='" . $nb_td . "' style='display: none;' id='viewfollowup" . $pfTaskjobstate->fields["id"] . "' class='tab_bg_4'>";
     echo "</td>";
     echo "</tr>";
 }
 /**
  * Update agent status for a task
  *
  * @param params parameters from the GET HTTP request
  *
  * @return nothing
  */
 static function updateLog($params = array())
 {
     global $DB;
     $p = array();
     $p['machineid'] = '';
     //DeviceId
     $p['uuid'] = '';
     //Task uuid
     $p['msg'] = 'ok';
     //status of the task
     $p['code'] = '';
     //current step of processing
     foreach ($params as $key => $value) {
         $p[$key] = $value;
     }
     //Get the agent ID by its deviceid
     $agent = PluginFusioninventoryAgent::getByDeviceID($p['machineid']);
     //No need to continue since the requested agent doesn't exists in database
     if ($agent === FALSE) {
         self::sendError();
         return;
     }
     //Get task job status : identifier is the uuid given by the agent
     $taskjobstates = $DB->request(getTableForItemType('PluginFusioninventoryTaskjobstate'), "`uniqid`='" . $p['uuid'] . "'");
     $taskjobstate = new PluginFusioninventoryTaskjobstate();
     foreach ($taskjobstates as $jobstate) {
         $taskjobstate->getFromDB($jobstate['id']);
         //Get taskjoblog associated
         $taskjoblog = new PluginFusioninventoryTaskjobLog();
         $taskjoblog->getFromDBByQuery("WHERE `plugin_fusioninventory_taskjobstates_id`=" . $jobstate['id']);
         switch ($p['code']) {
             case 'running':
                 $taskjoblog->addTaskjoblog($taskjobstate->fields['id'], $taskjobstate->fields['items_id'], $taskjobstate->fields['itemtype'], PluginFusioninventoryTaskjoblog::TASK_RUNNING, $p['msg']);
                 break;
             case 'ok':
                 $taskjobstate->changeStatusFinish($taskjobstate->fields['id'], $taskjobstate->fields['items_id'], $taskjobstate->fields['itemtype'], 0, $p['msg']);
                 break;
             case 'ko':
                 $taskjobstate->changeStatusFinish($taskjobstate->fields['id'], $taskjobstate->fields['items_id'], $taskjobstate->fields['itemtype'], 1, $p['msg']);
                 break;
         }
     }
     self::sendOk();
 }
 function storeTempFilesFound($taskjobstates_id, $a_values)
 {
     $pfTaskjobstate = new PluginFusioninventoryTaskjobstate();
     $pfTaskjobstate->getFromDB($taskjobstates_id);
     $a_specificity = array();
     if ($pfTaskjobstate->fields['specificity'] != '') {
         $a_specificity = importArrayFromDB($pfTaskjobstate->fields['specificity']);
     }
     unset($a_values['_cpt']);
     $a_specificity[] = $a_values;
     $input = array();
     $input['id'] = $pfTaskjobstate->fields['id'];
     $input['specificity'] = exportArrayToDB($a_specificity);
     $pfTaskjobstate->update($input);
 }
 /**
  * Force end task
  */
 function forceEnd()
 {
     $pfTaskjobstate = new PluginFusioninventoryTaskjobstate();
     $a_taskjobstates = $pfTaskjobstate->find("`plugin_fusioninventory_taskjobs_id`='" . $this->fields["id"] . "'");
     //TODO: in order to avoid too many atomic operations on DB, convert the
     //following into a massive prepared operation (ie. ids in one massive action)
     foreach ($a_taskjobstates as $a_taskjobstate) {
         $pfTaskjobstate->getFromDB($a_taskjobstate['id']);
         if ($a_taskjobstate['state'] != PluginFusioninventoryTaskjobstate::FINISHED) {
             $pfTaskjobstate->changeStatusFinish($a_taskjobstate['id'], 0, '', 1, "Action cancelled by user", 0, 0);
         }
     }
     $this->reinitializeTaskjobs($this->fields['plugin_fusioninventory_tasks_id']);
 }