header("Content-Type: text/html; charset=UTF-8");
Html::header_nocache();
if (!isset($_POST["id"])) {
    exit;
}
if (!isset($_POST["sort"])) {
    $_POST["sort"] = "";
}
if (!isset($_POST["order"])) {
    $_POST["order"] = "";
}
if (!isset($_POST["withtemplate"])) {
    $_POST["withtemplate"] = "";
}
$pfTask = new PluginFusioninventoryTask();
$pfTaskjoblog = new PluginFusioninventoryTaskjoblog();
$pfTaskjob = new PluginFusioninventoryTaskjob();
$a_taskjob = $pfTaskjob->find("`plugin_fusioninventory_tasks_id`='" . $_POST["id"] . "'\n      AND `rescheduled_taskjob_id`='0' ", "id");
$i = 1;
switch ($_POST['glpi_tab']) {
    case -1:
        foreach ($a_taskjob as $taskjob_id => $datas) {
            $pfTaskjob->showForm($taskjob_id);
            $pfTaskjoblog->showHistory($taskjob_id);
            $taskjob_id_next = $taskjob_id;
            for ($j = 2; $j > 1; $j++) {
                $a_taskjobreties = $pfTaskjob->find("`rescheduled_taskjob_id`='" . $taskjob_id_next . "' ", "", 1);
                if (!empty($a_taskjobreties)) {
                    foreach ($a_taskjobreties as $taskjob_id_next => $datas2) {
                        $pfTaskjob->showForm($taskjob_id_next);
                    }
 function cancel($reason = '')
 {
     $log = new PluginFusioninventoryTaskjoblog();
     $log_input = array('plugin_fusioninventory_taskjobstates_id' => $this->fields['id'], 'items_id' => $this->fields['items_id'], 'itemtype' => $this->fields['itemtype'], 'date' => date("Y-m-d H:i:s"), 'state' => PluginFusioninventoryTaskjoblog::TASK_INFO, 'comment' => Toolbox::addslashes_deep($reason));
     $log->add($log_input);
     $this->update(array('id' => $this->fields['id'], 'state' => self::CANCELLED));
 }
 /**
  * Display high detail of each history line
  *
  * @param $datas array datas of history
  * @param $comment boolean 0/1 display comment or not
  *
  * @return array
  *               - boolean 0/1 if this log = finish
  *               - text to display
  *
  **/
 function displayHistoryDetail($datas, $comment = 1)
 {
     $text = "<td align='center'>";
     $text .= Html::convDateTime($datas['date']);
     $text .= "</td>";
     $finish = 0;
     switch ($datas['state']) {
         case self::TASK_PREPARED:
             $text .= "<td align='center'>";
             $text .= __('Prepared', 'fusioninventory');
             break;
         case self::TASK_STARTED:
             $text .= "<td align='center'>";
             $text .= __('Started', 'fusioninventory');
             break;
         case self::TASK_OK:
             $text .= "<td style='background-color: rgb(0, 255, 0);-moz-border-radius:" . " 4px;-webkit-border-radius: 4px;-o-border-radius: 4px;padding: 2px;' " . "align='center'>";
             $text .= "<strong>" . __('Ok', 'fusioninventory') . "</strong>";
             $finish++;
             break;
         case self::TASK_ERROR_OR_REPLANNED:
             $text .= "<td style='background-color: rgb(255, 120, 0);-moz-border-radius: " . "4px;-webkit-border-radius: 4px;-o-border-radius: 4px;padding: 2px;' " . "align='center'>";
             $text .= "<strong>" . __('Error / rescheduled', 'fusioninventory') . "</strong>";
             $finish++;
             break;
         case self::TASK_ERROR:
             $text .= "<td style='background-color: rgb(255, 0, 0);-moz-border-radius: " . "4px;-webkit-border-radius: 4px;-o-border-radius: 4px;padding: 2px;' " . "align='center'>";
             $text .= "<strong>" . __('Error') . "</strong>";
             $finish++;
             break;
         case self::TASK_INFO:
             $text .= "<td style='background-color: rgb(255, 200, 0);-moz-border-radius: " . "4px;-webkit-border-radius: 4px;-o-border-radius: 4px;padding: 2px;' " . "align='center'>";
             $text .= "<strong>" . __('Info', 'fusioninventory') . "</strong>";
             $finish++;
             break;
         case self::TASK_RUNNING:
             $text .= "<td style='background-color: rgb(255, 200, 0);-moz-border-radius: " . "4px;-webkit-border-radius: 4px;-o-border-radius: 4px;padding: 2px;' " . "align='center'>";
             $text .= "<strong>" . __('Running') . "</strong>";
             break;
         default:
             $text .= "<td>";
             break;
     }
     $text .= "</td>";
     if ($comment == '1') {
         $text .= "<td class='fusinv_task_comment'>";
         $datas['comment'] = PluginFusioninventoryTaskjoblog::convertComment($datas['comment']);
         $text .= $datas['comment'];
         $text .= "</td>";
     }
     return array($finish, $text);
 }
 static function quickListLogs()
 {
     $pfTaskjoblog = new PluginFusioninventoryTaskjoblog();
     $pfTaskjob = new PluginFusioninventoryTaskjob();
     if (isset($_SESSION["plugin_fusioninventory_forcerun"])) {
         foreach ($_SESSION["plugin_fusioninventory_forcerun"] as $taskjobs_id => $uniqid) {
             $pfTaskjob->getFromDB($taskjobs_id);
             echo "<table class='tab_cadrehov' style='width:950px'>";
             echo "<tr class='tab_bg_1'>";
             echo "<th>" . $pfTaskjob->getLink(1) . "</th>";
             echo "</tr>";
             echo "<tr class='tab_bg_1'>";
             echo "<td>";
             $pfTaskjoblog->showHistory($taskjobs_id, 950, array('uniqid' => $uniqid));
             echo "</td>";
             echo "</table>";
             echo "<br/>";
         }
     }
 }
 function prepareRun($taskjob_id, $definitions_filter = NULL)
 {
     global $DB;
     $task = new PluginFusioninventoryTask();
     $job = new PluginFusioninventoryTaskjob();
     $joblog = new PluginFusioninventoryTaskjoblog();
     $jobstate = new PluginFusioninventoryTaskjobstate();
     $agent = new PluginFusioninventoryAgent();
     $agentmodule = new PluginFusioninventoryAgentmodule();
     $job->getFromDB($taskjob_id);
     $task->getFromDB($job->fields['plugin_fusioninventory_tasks_id']);
     $communication = $task->fields['communication'];
     $actions = importArrayFromDB($job->fields['action']);
     $definitions = importArrayFromDB($job->fields['definition']);
     $taskvalid = 0;
     $computers = array();
     foreach ($actions as $action) {
         $itemtype = key($action);
         $items_id = current($action);
         switch ($itemtype) {
             case 'Computer':
                 if ($this->definitionFiltered("Computer", $definitions_filter)) {
                     break;
                 }
                 $computers[] = $items_id;
                 break;
             case 'Group':
                 if ($this->definitionFiltered("Group", $definitions_filter)) {
                     break;
                 }
                 $computer_object = new Computer();
                 //find computers by user associated with this group
                 $group_users = new Group_User();
                 $group = new Group();
                 $group->getFromDB($items_id);
                 $members = array();
                 $computers_a_1 = array();
                 $computers_a_2 = array();
                 //array_keys($group_users->find("groups_id = '$items_id'"));
                 $members = $group_users->getGroupUsers($items_id);
                 foreach ($members as $member) {
                     $computers = $computer_object->find("users_id = '{$member['id']}' " . " AND `is_deleted`='0' AND `is_template`='0'");
                     foreach ($computers as $computer) {
                         $computers_a_1[] = $computer['id'];
                     }
                 }
                 //find computers directly associated with this group
                 $computers = $computer_object->find("groups_id = '{$items_id}' " . " AND `is_deleted`='0' AND `is_template`='0'");
                 foreach ($computers as $computer) {
                     $computers_a_2[] = $computer['id'];
                 }
                 //merge two previous array and deduplicate entries
                 $computers = array_unique(array_merge($computers_a_1, $computers_a_2));
                 break;
             case 'PluginFusioninventoryDeployGroup':
                 $group = new PluginFusioninventoryDeployGroup();
                 $group->getFromDB($items_id);
                 switch ($group->getField('type')) {
                     case 'STATIC':
                         if ($this->definitionFiltered("PluginFusioninventoryDeployGroupStatic", $definitions_filter)) {
                             break;
                         }
                         $query = "SELECT items_id\n                     FROM glpi_plugin_fusioninventory_deploygroups_staticdatas\n                     WHERE groups_id = '{$items_id}'\n                     AND itemtype = 'Computer'";
                         $res = $DB->query($query);
                         while ($row = $DB->fetch_assoc($res)) {
                             $computers[] = $row['items_id'];
                         }
                         break;
                     case 'DYNAMIC':
                         if ($this->definitionFiltered("PluginFusioninventoryDeployGroupDynamic", $definitions_filter)) {
                             break;
                         }
                         //$definitions_filter is NULL = update by crontask !
                         if ($definitions_filter != NULL) {
                             $where = " AND `can_update_group`='1'";
                         } else {
                             $where = "";
                         }
                         $query = "SELECT fields_array\n                     FROM glpi_plugin_fusioninventory_deploygroups_dynamicdatas\n                     WHERE groups_id = '{$items_id}' {$where}\n                     LIMIT 1";
                         $res = $DB->query($query);
                         $row = $DB->fetch_assoc($res);
                         //No dynamic groups have been found : break
                         if ($DB->numrows($res) == 0) {
                             break;
                         }
                         if (isset($_GET)) {
                             $get_tmp = $_GET;
                         }
                         if (isset($_SESSION["glpisearchcount"]['Computer'])) {
                             unset($_SESSION["glpisearchcount"]['Computer']);
                         }
                         if (isset($_SESSION["glpisearchcount2"]['Computer'])) {
                             unset($_SESSION["glpisearchcount2"]['Computer']);
                         }
                         $_GET = importArrayFromDB($row['fields_array']);
                         $_GET["glpisearchcount"] = count($_GET['field']);
                         if (isset($_GET['field2'])) {
                             $_GET["glpisearchcount2"] = count($_GET['field2']);
                         }
                         $pfSearch = new PluginFusioninventorySearch();
                         Search::manageParams('Computer');
                         $glpilist_limit = $_SESSION['glpilist_limit'];
                         $_SESSION['glpilist_limit'] = 999999999;
                         $result = $pfSearch->constructSQL('Computer', $_GET);
                         $_SESSION['glpilist_limit'] = $glpilist_limit;
                         while ($data = $DB->fetch_array($result)) {
                             $computers[] = $data['id'];
                         }
                         if (count($get_tmp) > 0) {
                             $_GET = $get_tmp;
                         }
                         break;
                 }
                 break;
         }
     }
     //Remove duplicatas from array
     //We are using isset for faster processing than array_unique because we might have many
     //entries in this list.
     $tmp_computers = array();
     foreach ($computers as $computer) {
         if (!isset($tmp_computers[$computer])) {
             $tmp_computers[$computer] = 1;
         }
     }
     $computers = array_keys($tmp_computers);
     $c_input = array();
     $c_input['plugin_fusioninventory_taskjobs_id'] = $job->fields['id'];
     $c_input['state'] = 0;
     $c_input['plugin_fusioninventory_agents_id'] = 0;
     $c_input['execution_id'] = $task->fields['execution_id'];
     $package = new PluginFusioninventoryDeployPackage();
     foreach ($computers as $computer_id) {
         //Unique Id match taskjobstatuses for an agent(computer)
         foreach ($definitions as $definition) {
             $uniqid = uniqid();
             $package->getFromDB($definition['PluginFusioninventoryDeployPackage']);
             $c_input['state'] = 0;
             $c_input['itemtype'] = 'PluginFusioninventoryDeployPackage';
             $c_input['items_id'] = $package->fields['id'];
             $c_input['date'] = date("Y-m-d H:i:s");
             $c_input['uniqid'] = $uniqid;
             //get agent for this computer
             $agents_id = $agent->getAgentWithComputerid($computer_id);
             if ($agents_id === FALSE) {
                 $jobstates_id = $jobstate->add($c_input);
                 $jobstate->changeStatusFinish($jobstates_id, 0, '', 1, "No agent found for [[Computer::" . $computer_id . "]]", 0, 0);
             } else {
                 if ($agentmodule->isAgentCanDo('DEPLOY', $agents_id)) {
                     $c_input['plugin_fusioninventory_agents_id'] = $agents_id;
                     $jobstates_running = $jobstate->find(implode(" ", array("    `itemtype` = 'PluginFusioninventoryDeployPackage'", "AND `items_id` = " . $package->fields['id'], "AND `state` <> " . PluginFusioninventoryTaskjobstate::FINISHED, "AND `plugin_fusioninventory_agents_id` = " . $agents_id)));
                     if (count($jobstates_running) == 0) {
                         # Push the agent, in the stack of agent to awake
                         if ($communication == "push") {
                             $_SESSION['glpi_plugin_fusioninventory']['agents'][$agents_id] = 1;
                         }
                         $jobstates_id = $jobstate->add($c_input);
                         //Add log of taskjob
                         $c_input['plugin_fusioninventory_taskjobstates_id'] = $jobstates_id;
                         $c_input['state'] = PluginFusioninventoryTaskjoblog::TASK_PREPARED;
                         $taskvalid++;
                         $joblog->add($c_input);
                         unset($c_input['state']);
                         unset($c_input['plugin_fusioninventory_agents_id']);
                     }
                 }
             }
         }
     }
     if ($taskvalid > 0) {
         $job->fields['status'] = 1;
         $job->update($job->fields);
     } else {
         $job->reinitializeTaskjobs($job->fields['plugin_fusioninventory_tasks_id']);
     }
 }
 /**
  * Get all devices and put in taskjobstate each task for
  * each device for each agent
  *
  * @param type $taskjobs_id id of taskjob esx
  *
  * @return uniqid value
  */
 function prepareRun($taskjobs_id)
 {
     $task = new PluginFusioninventoryTask();
     $job = new PluginFusioninventoryTaskjob();
     $joblog = new PluginFusioninventoryTaskjoblog();
     $jobstate = new PluginFusioninventoryTaskjobstate();
     $uniqid = uniqid();
     $job->getFromDB($taskjobs_id);
     $task->getFromDB($job->fields['plugin_fusioninventory_tasks_id']);
     $communication = $task->fields['communication'];
     //list all agents
     $agent_actions = importArrayFromDB($job->fields['action']);
     $task_definitions = importArrayFromDB($job->fields['definition']);
     $agent_actionslist = array();
     foreach ($agent_actions as $targets) {
         foreach ($targets as $itemtype => $items_id) {
             $item = new $itemtype();
             // Detect if agent exists
             if ($item->getFromDB($items_id)) {
                 $agent_actionslist[$items_id] = 1;
             }
         }
     }
     // *** Add jobstate
     if (empty($agent_actionslist)) {
         $a_input = array();
         $a_input['plugin_fusioninventory_taskjobs_id'] = $taskjobs_id;
         $a_input['state'] = 0;
         $a_input['plugin_fusioninventory_agents_id'] = 0;
         $a_input['uniqid'] = $uniqid;
         $a_input['execution_id'] = $task->fields['execution_id'];
         foreach ($task_definitions as $task_definition) {
             foreach ($task_definition as $task_itemtype => $task_items_id) {
                 $a_input['itemtype'] = $task_itemtype;
                 $a_input['items_id'] = $task_items_id;
                 $jobstates_id = $jobstate->add($a_input);
                 //Add log of taskjob
                 $a_input['plugin_fusioninventory_taskjobstates_id'] = $jobstates_id;
                 $a_input['state'] = PluginFusioninventoryTaskjoblog::TASK_PREPARED;
                 $a_input['date'] = date("Y-m-d H:i:s");
                 $joblog->add($a_input);
                 $jobstate->changeStatusFinish($jobstates_id, 0, 'PluginFusioninventoryInventoryComputerESX', 1, "Unable to find agent to run this job");
             }
         }
         $job->update($job->fields);
     } else {
         foreach ($agent_actions as $targets) {
             foreach ($targets as $items_id) {
                 if ($communication == "push") {
                     $_SESSION['glpi_plugin_fusioninventory']['agents'][$items_id] = 1;
                 }
                 foreach ($task_definitions as $task_definition) {
                     foreach ($task_definition as $task_itemtype => $task_items_id) {
                         $a_input = array();
                         $a_input['plugin_fusioninventory_taskjobs_id'] = $taskjobs_id;
                         $a_input['state'] = 0;
                         $a_input['plugin_fusioninventory_agents_id'] = $items_id;
                         $a_input['itemtype'] = $task_itemtype;
                         $a_input['items_id'] = $task_items_id;
                         $a_input['uniqid'] = $uniqid;
                         $a_input['date'] = date("Y-m-d H:i:s");
                         $a_input['execution_id'] = $task->fields['execution_id'];
                         $jobstates_id = $jobstate->add($a_input);
                         //Add log of taskjob
                         $a_input['plugin_fusioninventory_taskjobstates_id'] = $jobstates_id;
                         $a_input['state'] = PluginFusioninventoryTaskjoblog::TASK_PREPARED;
                         $joblog->add($a_input);
                         unset($a_input['state']);
                     }
                 }
             }
         }
         $job->fields['status'] = 1;
         $job->update($job->fields);
     }
     return $uniqid;
 }
 /**
  * @test
  */
 public function PrinterDiscoveryImportDenied()
 {
     global $DB;
     $DB->connect();
     $a_inventory = array('AUTHSNMP' => '1', 'DESCRIPTION' => 'Brother NC-6400h, Firmware Ver.1.11  (06.12.20),MID 84UZ92', 'ENTITY' => '0', 'FIRMWARE' => '', 'IP' => '10.36.4.29', 'MAC' => '00:80:77:d9:51:c3', 'MANUFACTURER' => 'Brother', 'MODEL' => '', 'MODELSNMP' => 'Printer0442', 'NETBIOSNAME' => 'UH4DLPT01', 'SERIAL' => 'E8J596100A', 'SNMPHOSTNAME' => 'UH4DLPT01', 'TYPE' => 'PRINTER');
     $pfCommunicationNetworkDiscovery = new PluginFusioninventoryCommunicationNetworkDiscovery();
     $printer = new Printer();
     $_SESSION['plugin_fusinvsnmp_taskjoblog']['taskjobs_id'] = 1;
     $_SESSION['plugin_fusinvsnmp_taskjoblog']['items_id'] = '1';
     $_SESSION['plugin_fusinvsnmp_taskjoblog']['itemtype'] = 'Printer';
     $_SESSION['plugin_fusinvsnmp_taskjoblog']['state'] = 0;
     $_SESSION['plugin_fusinvsnmp_taskjoblog']['comment'] = '';
     $pfCommunicationNetworkDiscovery->sendCriteria($a_inventory);
     $a_printers = $printer->find();
     $this->assertEquals(0, count($a_printers), 'May have only one Printer');
     $pfTaskjoblog = new PluginFusioninventoryTaskjoblog();
     $a_logs = $pfTaskjoblog->find("`comment` LIKE '%importdenied%'", '`id` DESC', 1);
     $a_log = current($a_logs);
     $this->assertEquals('==importdenied== [serial]:E8J596100A, ' . '[mac]:00:80:77:d9:51:c3, [ip]:10.36.4.29, [model]:Printer0442, ' . '[name]:UH4DLPT01, [entities_id]:0, [itemtype]:Printer', $a_log['comment'], 'Import denied message');
 }
 function pre_deleteItem()
 {
     global $CFG_GLPI;
     //if task active, delete denied
     if ($this->getField('is_active') == 1) {
         Session::addMessageAfterRedirect(__('This task is active. delete denied', 'fusioninventory'));
         Html::redirect($CFG_GLPI["root_doc"] . "/plugins/fusinvdeploy/front/task.form.php?id=" . $this->getField('id'));
         return FALSE;
     }
     $task_id = $this->getField('id');
     $job = new PluginFusioninventoryTaskjob();
     $status = new PluginFusioninventoryTaskjobstate();
     $log = new PluginFusioninventoryTaskjoblog();
     // clean all sub-tables
     $a_taskjobs = $job->find("`plugin_fusioninventory_tasks_id`='{$task_id}'");
     foreach ($a_taskjobs as $a_taskjob) {
         $a_taskjobstatuss = $status->find("`plugin_fusioninventory_taskjobs_id`='" . $a_taskjob['id'] . "'");
         foreach ($a_taskjobstatuss as $a_taskjobstatus) {
             $a_taskjoblogs = $log->find("`plugin_fusioninventory_taskjobstates_id`='" . $a_taskjobstatus['id'] . "'");
             foreach ($a_taskjoblogs as $a_taskjoblog) {
                 $log->delete($a_taskjoblog, 1);
             }
             $status->delete($a_taskjobstatus, 1);
         }
         $job->delete($a_taskjob, 1);
     }
     return TRUE;
 }
 /**
  * @test
  */
 public function deleteTask()
 {
     global $DB;
     $pfTask = new PluginFusioninventoryTask();
     $pfTaskjob = new PluginFusioninventoryTaskjob();
     $pfTaskjobState = new PluginFusioninventoryTaskjobstate();
     $pfTaskjoblog = new PluginFusioninventoryTaskjoblog();
     //delete task
     $return = $pfTask->delete(array('id' => self::$tasks_id));
     $this->assertEquals(true, $return);
     //check deletion of job
     $jobs_found = $pfTaskjob->find("id = " . self::$taskjobs_id);
     $this->assertEquals(array(), $jobs_found);
     //check deletion of state
     $states_found = $pfTaskjobState->find("id = " . self::$taskjobstates_id);
     $this->assertEquals(array(), $states_found);
     //check deletion of log
     $logs_found = $pfTaskjoblog->find("id = " . self::$taskjobstates_id);
     $this->assertEquals(array(), $logs_found);
 }
function plugin_fusioninventory_searchOptionsValues($item)
{
    global $DB;
    if ($item['searchoption']['table'] == 'glpi_plugin_fusioninventory_taskjoblogs' and $item['searchoption']['field'] == 'state') {
        $pfTaskjoblog = new PluginFusioninventoryTaskjoblog();
        $elements = $pfTaskjoblog->dropdownStateValues();
        Dropdown::showFromArray($item['name'], $elements, array('value' => $item['value']));
        return TRUE;
    } else {
        if ($item['searchoption']['table'] == 'glpi_plugin_fusioninventory_taskjobstates' and $item['searchoption']['field'] == 'uniqid') {
            $elements = array();
            $query = "SELECT * FROM `" . $item['searchoption']['table'] . "`\n      GROUP BY `uniqid`\n      ORDER BY `uniqid`";
            $result = $DB->query($query);
            while ($data = $DB->fetch_array($result)) {
                $elements[$data['uniqid']] = $data['uniqid'];
            }
            Dropdown::showFromArray($item['name'], $elements, array('value' => $item['value']));
            return TRUE;
        }
    }
}
 function prepareRun($taskjobs_id)
 {
     global $DB;
     $task = new PluginFusioninventoryTask();
     $job = new PluginFusioninventoryTaskjob();
     $joblog = new PluginFusioninventoryTaskjoblog();
     $jobstate = new PluginFusioninventoryTaskjobstate();
     $agent = new PluginFusioninventoryAgent();
     $uniqid = uniqid();
     $job->getFromDB($taskjobs_id);
     $task->getFromDB($job->fields['plugin_fusioninventory_tasks_id']);
     $communication = $task->fields['communication'];
     $actions = importArrayFromDB($job->fields['action']);
     $definitions = importArrayFromDB($job->fields['definition']);
     $taskvalid = 0;
     $computers = array();
     foreach ($actions as $action) {
         $itemtype = key($action);
         $items_id = current($action);
         switch ($itemtype) {
             case 'Computer':
                 $computers[] = $items_id;
                 break;
             case 'Group':
                 $computer_object = new Computer();
                 //find computers by user associated with this group
                 $group_users = new Group_User();
                 $group = new Group();
                 $group->getFromDB($items_id);
                 $members = array();
                 $computers_a_1 = array();
                 $computers_a_2 = array();
                 //array_keys($group_users->find("groups_id = '$items_id'"));
                 $members = $group_users->getGroupUsers($items_id);
                 foreach ($members as $member) {
                     $computers = $computer_object->find("users_id = '{$member['id']}'");
                     foreach ($computers as $computer) {
                         $computers_a_1[] = $computer['id'];
                     }
                 }
                 //find computers directly associated with this group
                 $computers = $computer_object->find("groups_id = '{$items_id}'");
                 foreach ($computers as $computer) {
                     $computers_a_2[] = $computer['id'];
                 }
                 //merge two previous array and deduplicate entries
                 $computers = array_unique(array_merge($computers_a_1, $computers_a_2));
                 break;
             case 'PluginFusioninventoryDeployGroup':
                 $group = new PluginFusioninventoryDeployGroup();
                 $group->getFromDB($items_id);
                 switch ($group->getField('type')) {
                     case 'STATIC':
                         $query = "SELECT items_id\n                     FROM glpi_plugin_fusioninventory_deploygroups_staticdatas\n                     WHERE groups_id = '{$items_id}'\n                     AND itemtype = 'Computer'";
                         $res = $DB->query($query);
                         while ($row = $DB->fetch_assoc($res)) {
                             $computers[] = $row['items_id'];
                         }
                         break;
                     case 'DYNAMIC':
                         $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)) {
                             $computers[] = $data['id'];
                         }
                         if (count($get_tmp) > 0) {
                             $_GET = $get_tmp;
                         }
                         break;
                 }
                 break;
         }
     }
     $c_input = array();
     $c_input['plugin_fusioninventory_taskjobs_id'] = $taskjobs_id;
     $c_input['state'] = 0;
     $c_input['plugin_fusioninventory_agents_id'] = 0;
     $c_input['execution_id'] = $task->fields['execution_id'];
     $pfCollect = new PluginFusioninventoryCollect();
     foreach ($computers as $computer_id) {
         //get agent if for this computer
         $agents_id = $agent->getAgentWithComputerid($computer_id);
         if ($agents_id === FALSE) {
             $jobstates_id = $jobstate->add($c_input);
             $jobstate->changeStatusFinish($jobstates_id, 0, '', 1, "No agent found for [[Computer::" . $computer_id . "]]", 0, 0);
         } else {
             foreach ($definitions as $definition) {
                 $pfCollect->getFromDB($definition['PluginFusioninventoryCollect']);
                 switch ($pfCollect->fields['type']) {
                     case 'registry':
                         // get all registry
                         $pfCollect_Registry = new PluginFusioninventoryCollect_Registry();
                         $a_registries = $pfCollect_Registry->find("`plugin_fusioninventory_collects_id`='" . $pfCollect->fields['id'] . "'");
                         foreach ($a_registries as $data_r) {
                             $uniqid = uniqid();
                             $c_input['state'] = 0;
                             $c_input['itemtype'] = 'PluginFusioninventoryCollect_Registry';
                             $c_input['items_id'] = $data_r['id'];
                             $c_input['date'] = date("Y-m-d H:i:s");
                             $c_input['uniqid'] = $uniqid;
                             $c_input['plugin_fusioninventory_agents_id'] = $agents_id;
                             # Push the agent, in the stack of agent to awake
                             if ($communication == "push") {
                                 $_SESSION['glpi_plugin_fusioninventory']['agents'][$agents_id] = 1;
                             }
                             $jobstates_id = $jobstate->add($c_input);
                             //Add log of taskjob
                             $c_input['plugin_fusioninventory_taskjobstates_id'] = $jobstates_id;
                             $c_input['state'] = PluginFusioninventoryTaskjoblog::TASK_PREPARED;
                             $taskvalid++;
                             $joblog->add($c_input);
                         }
                         break;
                     case 'wmi':
                         // get all wmi
                         $pfCollect_Wmi = new PluginFusioninventoryCollect_Wmi();
                         $a_wmies = $pfCollect_Wmi->find("`plugin_fusioninventory_collects_id`='" . $pfCollect->fields['id'] . "'");
                         foreach ($a_wmies as $data_r) {
                             $uniqid = uniqid();
                             $c_input['state'] = 0;
                             $c_input['itemtype'] = 'PluginFusioninventoryCollect_Wmi';
                             $c_input['items_id'] = $data_r['id'];
                             $c_input['date'] = date("Y-m-d H:i:s");
                             $c_input['uniqid'] = $uniqid;
                             $c_input['plugin_fusioninventory_agents_id'] = $agents_id;
                             # Push the agent, in the stack of agent to awake
                             if ($communication == "push") {
                                 $_SESSION['glpi_plugin_fusioninventory']['agents'][$agents_id] = 1;
                             }
                             $jobstates_id = $jobstate->add($c_input);
                             //Add log of taskjob
                             $c_input['plugin_fusioninventory_taskjobstates_id'] = $jobstates_id;
                             $c_input['state'] = PluginFusioninventoryTaskjoblog::TASK_PREPARED;
                             $taskvalid++;
                             $joblog->add($c_input);
                         }
                         break;
                     case 'file':
                         // find files
                         $pfCollect_File = new PluginFusioninventoryCollect_File();
                         $a_files = $pfCollect_File->find("`plugin_fusioninventory_collects_id`='" . $pfCollect->fields['id'] . "'");
                         foreach ($a_files as $data_r) {
                             $uniqid = uniqid();
                             $c_input['state'] = 0;
                             $c_input['itemtype'] = 'PluginFusioninventoryCollect_File';
                             $c_input['items_id'] = $data_r['id'];
                             $c_input['date'] = date("Y-m-d H:i:s");
                             $c_input['uniqid'] = $uniqid;
                             $c_input['plugin_fusioninventory_agents_id'] = $agents_id;
                             # Push the agent, in the stack of agent to awake
                             if ($communication == "push") {
                                 $_SESSION['glpi_plugin_fusioninventory']['agents'][$agents_id] = 1;
                             }
                             $jobstates_id = $jobstate->add($c_input);
                             //Add log of taskjob
                             $c_input['plugin_fusioninventory_taskjobstates_id'] = $jobstates_id;
                             $c_input['state'] = PluginFusioninventoryTaskjoblog::TASK_PREPARED;
                             $taskvalid++;
                             $joblog->add($c_input);
                         }
                         break;
                 }
             }
         }
     }
     if ($taskvalid > 0) {
         $job->fields['status'] = 1;
         $job->update($job->fields);
     } else {
         $job->reinitializeTaskjobs($job->fields['plugin_fusioninventory_tasks_id']);
     }
 }
 function showJobLogs()
 {
     $refresh_intervals = array("off" => __('Off', 'fusioninventory'), "1" => '1 ' . _n('second', 'seconds', 1), "5" => '5 ' . _n('second', 'seconds', 5), "10" => '10 ' . _n('second', 'seconds', 10), "60" => '1 ' . _n('minute', 'minutes', 1), "120" => '2 ' . _n('minute', 'minutes', 2), "300" => '5 ' . _n('minute', 'minutes', 5), "600" => '10 ' . _n('minute', 'minutes', 10));
     echo "<div class='fusinv_panel'>";
     echo "   <div class='fusinv_form large'>";
     $refresh_randid = $this->showDropdownFromArray(__("refresh interval", "fusioninventory"), null, $refresh_intervals, array('value' => 'off', 'width' => '20%'));
     // Add a manual refresh button
     echo "      <div class='refresh_button submit'>";
     echo "      <span></span></div>";
     echo "   </div>";
     // end of fusinv_form
     echo "</div>";
     //$pfTaskjob = new PluginFusioninventoryTaskjob();
     //$taskjobs = $pfTaskjob->find(
     //   "`plugin_fusioninventory_tasks_id`='".$this->fields['id']."'",
     //   "id"
     //);
     // Template structure for tasks' blocks
     echo implode("\n", array("<script id='template_task' type='x-tmpl-mustache'>", "<div id='{{task_id}}' class='task_block {{expanded}}'>", "  <h3>" . __("Task", 'fusioninventory') . " <span class='task_name'>{{task_name}}</span></h3>", "  <div class='jobs_block'></div>", "</div>", "</script>"));
     // Template structure for jobs' blocks
     echo implode("\n", array("<script id='template_job' type='x-tmpl-mustache'>", "<div id='{{job_id}}' class='job_block'>", "  <div class='refresh_button submit'><span></span></div>", "  <h3 class='job_name'>{{job_name}}</h3>", "  <div class='targets_block'></div>", "</div>", "</script>"));
     // Template structure for targets' blocks
     echo implode("\n", array("<script id='template_target' type='x-tmpl-mustache'>", "<div id='{{target_id}}' class='target_block'>", "  <div class='target_details'>", "  <div class='target_infos'>", "     <h4 class='target_name'>", "        <a target='_blank' href={{target_link}}>", "          {{target_name}}", "        </a>", "     </h4>", "     <div class='target_stats'>", "     </div>", "  </div>", "  <div class='progressbar'></div>", "  </div>", "  <div class='show_more'></div>", "  <div class='agents_block'></div>", "  <div class='show_more'></div>", "</script>"));
     // Template structure for targets' statistics
     echo implode("\n", array("<script id='template_target_stats' type='x-tmp-mustache'>", "  <div class='{{stats_type}} stats_block'>", "  </div>", "</script>"));
     // Template for counters' blocks
     echo implode("\n", array("<script id='template_counter_block' type='x-tmpl-mustache'>", "<div class='counter_block {{counter_type}} {{#counter_empty}}empty{{/counter_empty}}'>", "<a", "  href='javascript:void(0)'", "  class='' ", "  title='" . __("Show/Hide details", "fusioninventory") . "'", "  onclick='taskjobs.toggle_details_type(this, \"{{counter_type}}\", \"{{chart_id}}\")'", ">", "<div class='fold'></div>", "<span class='counter_name'>{{counter_type_name}}</span>", "<span class='counter_value'>{{counter_value}}</span>", "</div>", "</a>", "</script>"));
     /*
      * List of counter names
      */
     echo implode("\n", array("<script type='text/javascript'>", "  taskjobs.statuses_order = {", "     last_executions : [", "        'agents_prepared',", "        'agents_running',", "        'agents_cancelled'", "     ],", "     last_finish_states : [", "        'agents_notdone',", "        'agents_success',", "        'agents_error'", "     ]", "  };", "  taskjobs.statuses_names = {", "     'agents_notdone'   : '" . __('Not done yet', 'fusioninventory') . "',", "     'agents_error'     : '" . __('In error', 'fusioninventory') . "',", "     'agents_success'   : '" . __('Successful', 'fusioninventory') . "',", "     'agents_running'   : '" . __('Running', 'fusioninventory') . "',", "     'agents_prepared'  : '" . __('Prepared', 'fusioninventory') . "',", "     'agents_cancelled' : '" . __('Cancelled', 'fusioninventory') . "',", "  };", "  taskjobs.logstatuses_names = " . json_encode(PluginFusioninventoryTaskjoblog::dropdownStateValues()) . ";", "</script>"));
     // Template for agents' blocks
     echo implode("\n", array("<script id='template_agent' type='x-tmpl-mustache'>", "<div class='agent_block' id='{{agent_id}}'>", "  <div class='status {{status.last_exec}}'></span>", "  <div class='status {{status.last_finish}}'></span>", "</div>", "</script>"));
     // Display empty block for each jobs display which will be rendered later by mustache.js
     echo implode("\n", array("<div class='tasks_block'>", "</div>"));
     if (isset($this->fields['id'])) {
         $task_id = $this->fields['id'];
     } else {
         $task_id = json_encode(array());
     }
     $pfAgent = new PluginFusioninventoryAgent();
     $Computer = new Computer();
     echo implode("\n", array("<script type='text/javascript'>", "  taskjobs.agents_url = '" . $pfAgent->getFormUrl() . "'", "  taskjobs.computers_url = '" . $Computer->getFormUrl() . "'", "  taskjobs.init_templates();", "  taskjobs.init_refresh_form(", "     '" . $this->getBaseUrlFor('fi.job.logs') . "',", "     " . $task_id . ",", "     'dropdown_" . $refresh_randid . "'", "  );", "  taskjobs.update_logs_timeout(", "     '" . $this->getBaseUrlFor('fi.job.logs') . "',", "     " . $task_id . ",", "     'dropdown_" . $refresh_randid . "'", "  );", "</script>"));
 }
 function prepareTaskjobs($methods = array())
 {
     global $DB;
     $agent = new PluginFusioninventoryAgent();
     $timeslot = new PluginFusioninventoryTimeslot();
     $now = new DateTime();
     //transform methods array into string for database query
     $methods = "'" . implode("','", $methods) . "'";
     $query = implode(" \n", array("SELECT", "     task.`id`, task.`name`,", "     job.`id`, job.`name`, job.`method`, ", "     job.`targets`, job.`actors`", "FROM `glpi_plugin_fusioninventory_taskjobs` job", "LEFT JOIN `glpi_plugin_fusioninventory_tasks` task", "  ON task.`id` = job.`plugin_fusioninventory_tasks_id`", "WHERE task.`is_active` = 1", "AND (", "        (   task.`datetime_start` IS NOT NULL AND task.`datetime_end` IS NULL", "              AND '" . $now->format("Y-m-d H:i:s") . "' >= task.`datetime_start` )", "     OR", "        (   task.`datetime_start` IS NOT NULL AND task.`datetime_end` IS NOT NULL", "              AND '" . $now->format("Y-m-d H:i:s") . "' ", "                    between task.`datetime_start` AND task.`datetime_end` )", "     OR", "        ( task.`datetime_start` IS NULL AND task.`datetime_end` IS NULL )", ")", "AND job.`method` IN (" . $methods . ")", "ORDER BY job.`id`"));
     $query_result = $DB->query($query);
     $results = array();
     if ($query_result) {
         $results = PluginFusioninventoryToolbox::fetchAssocByTable($query_result);
     }
     // Fetch a list of actors to be prepared. We may have the same actors for each job so this
     // part can speed up the process.
     //$actors = array();
     // Set basic elements of jobstates
     $run_base = array('state' => PluginFusioninventoryTaskjobstate::PREPARED);
     $log_base = array('date' => $now->format("Y-m-d H:i:s"), 'state' => PluginFusioninventoryTaskjoblog::TASK_PREPARED, 'comment' => '');
     $jobstate = new PluginFusioninventoryTaskjobstate();
     $joblog = new PluginFusioninventoryTaskjoblog();
     foreach ($results as $index => $result) {
         $actors = importArrayFromDB($result['job']['actors']);
         // Get agents linked to the actors
         $agent_ids = array();
         foreach ($this->getAgentsFromActors($actors) as $agent_id) {
             $agent_ids[$agent_id] = true;
         }
         //Continue with next job if there are no agents found from actors.
         //TODO: This may be good to report this kind of information. We just need to do a list of
         //agent's ids generated by actors like array('actors_type-id' => array( 'agent_0',...).
         //Then the following could be put in the targets foreach loop before looping through
         //agents.
         if (count($agent_ids) == 0) {
             continue;
         }
         $saved_agent_ids = $agent_ids;
         $targets = importArrayFromDB($result['job']['targets']);
         if ($result['job']['method'] == 'networkinventory') {
             $pfNetworkinventory = new PluginFusioninventoryNetworkinventory();
             foreach ($targets as $keyt => $target) {
                 $item_type = key($target);
                 $items_id = current($target);
                 if ($item_type == 'PluginFusioninventoryIPRange') {
                     unset($targets[$keyt]);
                     // In this case get devices of this iprange
                     $deviceList = $pfNetworkinventory->getDevicesOfIPRange($items_id);
                     $targets = array_merge($targets, $deviceList);
                 }
             }
         }
         $limit = 0;
         foreach ($targets as $target) {
             $agent_ids = $saved_agent_ids;
             $item_type = key($target);
             $item_id = current($target);
             $job_id = $result['job']['id'];
             $jobstates_running = $jobstate->find(implode(" \n", array("    `itemtype` = '" . $item_type . "'", "AND `items_id` = " . $item_id, "AND `plugin_fusioninventory_taskjobs_id` = " . $job_id, "AND `state` not in ('" . implode("','", array(PluginFusioninventoryTaskjobstate::FINISHED, PluginFusioninventoryTaskjobstate::IN_ERROR, PluginFusioninventoryTaskjobstate::CANCELLED)) . "')", "AND `plugin_fusioninventory_agents_id` IN (", "'" . implode("','", array_keys($agent_ids)) . "'", ")")));
             // Filter out agents that are already running the targets.
             foreach ($jobstates_running as $jobstate_running) {
                 $jobstate_agent_id = $jobstate_running['plugin_fusioninventory_agents_id'];
                 if (isset($agent_ids[$jobstate_agent_id])) {
                     $agent_ids[$jobstate_agent_id] = false;
                 }
             }
             // Cancel agents prepared but not in $agent_ids (like computer
             // not in dynamic group)
             $jobstates_tocancel = $jobstate->find(implode(" \n", array("    `itemtype` = '" . $item_type . "'", "AND `items_id` = " . $item_id, "AND `plugin_fusioninventory_taskjobs_id` = " . $job_id, "AND `state` not in ('" . implode("','", array(PluginFusioninventoryTaskjobstate::FINISHED, PluginFusioninventoryTaskjobstate::IN_ERROR, PluginFusioninventoryTaskjobstate::CANCELLED)) . "')", "AND `plugin_fusioninventory_agents_id` NOT IN (", "'" . implode("','", array_keys($agent_ids)) . "'", ")")));
             foreach ($jobstates_tocancel as $jobstate_tocancel) {
                 $jobstate->getFromDB($jobstate_tocancel['id']);
                 $jobstate->cancel(__('Device no longer defined in definition of job', 'fusioninventory'));
             }
             foreach ($agent_ids as $agent_id => $agent_not_running) {
                 if ($agent_not_running) {
                     $limit += 1;
                     if ($limit > 500) {
                         $limit = 0;
                         break;
                     }
                     $run = array_merge($run_base, array('itemtype' => $item_type, 'items_id' => $item_id, 'plugin_fusioninventory_taskjobs_id' => $job_id, 'plugin_fusioninventory_agents_id' => $agent_id, 'uniqid' => uniqid()));
                     $run_id = $jobstate->add($run);
                     if ($run_id !== false) {
                         $log = array_merge($log_base, array('plugin_fusioninventory_taskjobstates_id' => $run_id, ''));
                         $joblog->add($log);
                     }
                 }
             }
         }
     }
     return true;
 }
 /**
  * Used to add log in the task
  */
 function addtaskjoblog()
 {
     $pfTaskjoblog = new PluginFusioninventoryTaskjoblog();
     $pfTaskjoblog->addTaskjoblog($_SESSION['plugin_fusinvsnmp_taskjoblog']['taskjobs_id'], $_SESSION['plugin_fusinvsnmp_taskjoblog']['items_id'], $_SESSION['plugin_fusinvsnmp_taskjoblog']['itemtype'], $_SESSION['plugin_fusinvsnmp_taskjoblog']['state'], $_SESSION['plugin_fusinvsnmp_taskjoblog']['comment']);
 }
 /**
  *  When agent contact server, this function send datas to agent
  */
 function run($jobstate)
 {
     $pfTaskjobstate = new PluginFusioninventoryTaskjobstate();
     $pfTaskjoblog = new PluginFusioninventoryTaskjoblog();
     $NetworkPort = new NetworkPort();
     $sxml_option = $this->message->addChild('OPTION');
     $sxml_option->addChild('NAME', 'WAKEONLAN');
     $changestate = 0;
     //      foreach ($taskjobstates as $jobstate) {
     $data = $jobstate->fields;
     $a_networkPort = $NetworkPort->find("`itemtype`='Computer' AND `items_id`='" . $data['items_id'] . "' ");
     $computerip = 0;
     foreach ($a_networkPort as $datanetwork) {
         //if ($datanetwork['ip'] != "127.0.0.1") {
         if ($datanetwork['mac'] != '') {
             $computerip++;
             $sxml_param = $sxml_option->addChild('PARAM');
             $sxml_param->addAttribute('MAC', $datanetwork['mac']);
             //$sxml_param->addAttribute('IP', $datanetwork['ip']);
             if ($changestate == '0') {
                 $pfTaskjobstate->changeStatus($data['id'], 1);
                 $pfTaskjoblog->addTaskjoblog($data['id'], '0', 'Computer', '1', '');
                 $changestate = $pfTaskjobstate->fields['id'];
             } else {
                 $pfTaskjobstate->changeStatusFinish($data['id'], $data['items_id'], $data['itemtype'], 0, "Merged with " . $changestate);
             }
             // Update taskjobstate (state = 3 : finish); Because we haven't return of agent on this action
             $pfTaskjobstate->changeStatusFinish($data['id'], $data['items_id'], $data['itemtype'], 0, 'WakeOnLan have not return state', 1);
         }
         //}
     }
     if ($computerip == '0') {
         $pfTaskjobstate->changeStatusFinish($data['id'], $data['items_id'], $data['itemtype'], 1, "No IP found on the computer");
     }
     //}
     return $this->message;
 }
 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;
 }
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  GNU Affero General Public License for more details.

  You should have received a copy of the GNU Affero General Public License
  along with FusionInventory. If not, see <http://www.gnu.org/licenses/>.

  ------------------------------------------------------------------------

  @package   FusionInventory
  @author    David Durieux
  @co-author
  @copyright Copyright (c) 2010-2014 FusionInventory team
  @license   AGPL License 3.0 or (at your option) any later version
             http://www.gnu.org/licenses/agpl-3.0-standalone.html
  @link      http://www.fusioninventory.org/
  @link      http://forge.fusioninventory.org/projects/fusioninventory-for-glpi/
  @since     2010

  ------------------------------------------------------------------------
*/
if (strpos($_SERVER['PHP_SELF'], "showtaskjoblogdetail.php")) {
    include "../../../inc/includes.php";
    header("Content-Type: text/html; charset=UTF-8");
    Html::header_nocache();
}
if (!defined('GLPI_ROOT')) {
    die("Can not acces directly to this file");
}
Session::checkCentralAccess();
$pftaskjoblog = new PluginFusioninventoryTaskjoblog();
echo $pftaskjoblog->showHistoryInDetail($_POST["agents_id"], $_POST["uniqid"], "900") . "</td>";
  @since     2013

  ------------------------------------------------------------------------
*/
ob_start();
include "../../../../inc/includes.php";
ob_end_clean();
$response = array();
//Agent communication using REST protocol
if (isset($_GET['action'])) {
    switch ($_GET['action']) {
        case 'getJobs':
            if (isset($_GET['machineid'])) {
                $pfAgent = new PluginFusioninventoryAgent();
                $pfTaskjobstate = new PluginFusioninventoryTaskjobstate();
                $pfTaskjoblog = new PluginFusioninventoryTaskjoblog();
                $a_agent = $pfAgent->InfosByKey(Toolbox::addslashes_deep($_GET['machineid']));
                if (isset($a_agent['id'])) {
                    $moduleRun = $pfTaskjobstate->getTaskjobsAgent($a_agent['id']);
                    foreach ($moduleRun as $className => $array) {
                        if (class_exists($className)) {
                            if ($className == "PluginFusioninventoryCollect") {
                                $class = new PluginFusioninventoryCollect();
                                foreach ($array as $data) {
                                    $out = $class->run($data, $a_agent);
                                    if (count($out) > 0) {
                                        $response[] = $out;
                                    }
                                    $pfTaskjobstate->changeStatus($data['id'], PluginFusioninventoryTaskjobstate::SERVER_HAS_SENT_DATA);
                                    $a_input = array();
                                    $a_input['plugin_fusioninventory_taskjobstates_id'] = $data['id'];
 function run($jobstate)
 {
     $pfAgent = new PluginFusioninventoryAgent();
     $pfTaskjobstate = new PluginFusioninventoryTaskjobstate();
     $pfTaskjoblog = new PluginFusioninventoryTaskjoblog();
     $pfConfigSecurity = new PluginFusioninventoryConfigSecurity();
     $pfToolbox = new PluginFusioninventoryToolbox();
     $current = $jobstate;
     $pfAgent->getFromDB($current->fields['plugin_fusioninventory_agents_id']);
     $ip = current(PluginFusioninventoryToolbox::getIPforDevice($jobstate->fields['itemtype'], $jobstate->fields['items_id']));
     if ($ip == '') {
         $pfTaskjobstate->changeStatusFinish($jobstate->fields['id'], $jobstate->fields['items_id'], $jobstate->fields['itemtype'], 1, "Device have no ip");
     } else {
         $sxml_option = $this->message->addChild('OPTION');
         $sxml_option->addChild('NAME', 'SNMPQUERY');
         $sxml_param = $sxml_option->addChild('PARAM');
         $sxml_param->addAttribute('THREADS_QUERY', $pfAgent->fields["threads_networkinventory"]);
         $sxml_param->addAttribute('TIMEOUT', $pfAgent->fields["timeout_networkinventory"]);
         $sxml_param->addAttribute('PID', $current->fields['id']);
         $changestate = 0;
         $taskjobstatedatas = $jobstate->fields;
         $sxml_device = $sxml_option->addChild('DEVICE');
         $a_extended = array('plugin_fusioninventory_configsecurities_id' => 0);
         if ($jobstate->fields['itemtype'] == 'Printer') {
             $sxml_device->addAttribute('TYPE', 'PRINTER');
             $pfPrinter = new PluginFusioninventoryPrinter();
             $a_extended = current($pfPrinter->find("`printers_id`='" . $jobstate->fields['items_id'] . "'", '', 1));
         } else {
             if ($jobstate->fields['itemtype'] == 'NetworkEquipment') {
                 $sxml_device->addAttribute('TYPE', 'NETWORKING');
                 $pfNetworkEquipment = new PluginFusioninventoryNetworkEquipment();
                 $a_extended = current($pfNetworkEquipment->find("`networkequipments_id`='" . $jobstate->fields['items_id'] . "'", '', 1));
             }
         }
         $sxml_device->addAttribute('ID', $jobstate->fields['items_id']);
         $sxml_device->addAttribute('IP', $ip);
         $sxml_device->addAttribute('AUTHSNMP_ID', $a_extended['plugin_fusioninventory_configsecurities_id']);
         if ($changestate == '0') {
             $pfTaskjobstate->changeStatus($taskjobstatedatas['id'], 1);
             $pfTaskjoblog->addTaskjoblog($taskjobstatedatas['id'], '0', 'PluginFusioninventoryAgent', '1', $pfAgent->fields["threads_networkinventory"] . ' threads', $pfAgent->fields["timeout_networkinventory"] . ' timeout');
             $changestate = $pfTaskjobstate->fields['id'];
         } else {
             $pfTaskjobstate->changeStatusFinish($taskjobstatedatas['id'], $taskjobstatedatas['items_id'], $taskjobstatedatas['itemtype'], 0, "Merged with " . $changestate);
         }
         $snmpauthlist = $pfConfigSecurity->find();
         if (count($snmpauthlist)) {
             foreach ($snmpauthlist as $snmpauth) {
                 $pfToolbox->addAuth($sxml_option, $snmpauth['id']);
             }
         }
     }
     return $this->message;
 }
 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>";
 }