/**
  * @test
  */
 public function prepareDB()
 {
     global $DB;
     $DB->connect();
     $computer = new Computer();
     $pfAgent = new PluginFusioninventoryAgent();
     $pfTask = new PluginFusioninventoryTask();
     $pfTaskjob = new PluginFusioninventoryTaskjob();
     $pfIPRange = new PluginFusioninventoryIPRange();
     // Create computers + agents
     $input = array('entities_id' => 0, 'name' => 'computer1');
     $computers_id = $computer->add($input);
     $input = array('entities_id' => 0, 'name' => 'computer1', 'version' => '{"INVENTORY":"v2.3.11"}', 'device_id' => 'computer1', 'useragent' => 'FusionInventory-Agent_v2.3.11', 'computers_id' => $computers_id);
     $pfAgent->add($input);
     $input = array('entities_id' => 0, 'name' => 'computer2');
     $computers_id = $computer->add($input);
     $input = array('entities_id' => 0, 'name' => 'computer2', 'version' => '{"INVENTORY":"v2.3.11"}', 'device_id' => 'computer2', 'useragent' => 'FusionInventory-Agent_v2.3.11', 'computers_id' => $computers_id);
     $pfAgent->add($input);
     $input = array('entities_id' => 0, 'name' => 'computer3');
     $computers_id = $computer->add($input);
     $input = array('entities_id' => 0, 'name' => 'computer3', 'version' => '{"INVENTORY":"v2.3.11"}', 'device_id' => 'computer3', 'useragent' => 'FusionInventory-Agent_v2.3.11', 'computers_id' => $computers_id);
     $pfAgent->add($input);
     // Add IPRange
     $input = array('entities_id' => 0, 'name' => 'Office', 'ip_start' => '10.0.0.1', 'ip_end' => '10.0.0.254');
     $ipranges_id = $pfIPRange->add($input);
     $input = array('entities_id' => 0, 'name' => 'Office2', 'ip_start' => '10.0.2.1', 'ip_end' => '10.0.2.254');
     $ipranges_id2 = $pfIPRange->add($input);
     // Allow all agents to do network discovery
     $query = "UPDATE `glpi_plugin_fusioninventory_agentmodules` " . " SET `is_active`='1' " . " WHERE `modulename`='NETWORKDISCOVERY'";
     $DB->query($query);
     // create task
     $input = array('entities_id' => 0, 'name' => 'network discovery', 'is_active' => 1);
     $tasks_id = $pfTask->add($input);
     // create taskjob
     $input = array('plugin_fusioninventory_tasks_id' => $tasks_id, 'entities_id' => 0, 'name' => 'discovery', 'method' => 'networkdiscovery', 'targets' => '[{"PluginFusioninventoryIPRange":"' . $ipranges_id . '"}]', 'actors' => '[{"PluginFusioninventoryAgent":"2"}]');
     $pfTaskjob->add($input);
     // create task
     $input = array('entities_id' => 0, 'name' => 'network discovery2', 'is_active' => 1);
     $tasks2_id = $pfTask->add($input);
     // create taskjob
     $input = array('plugin_fusioninventory_tasks_id' => $tasks2_id, 'entities_id' => 0, 'name' => 'discovery', 'method' => 'networkdiscovery', 'targets' => '[{"PluginFusioninventoryIPRange":"' . $ipranges_id2 . '"}]', 'actors' => '[{"PluginFusioninventoryAgent":"3"}]');
     $pfTaskjob->add($input);
 }
 /**
  * @test
  */
 public function prepareDB()
 {
     global $DB;
     $DB->connect();
     $computer = new Computer();
     $pfAgent = new PluginFusioninventoryAgent();
     $pfDeployPackage = new PluginFusioninventoryDeployPackage();
     $pfDeployGroup = new PluginFusioninventoryDeployGroup();
     $pfTask = new PluginFusioninventoryTask();
     $pfTaskjob = new PluginFusioninventoryTaskjob();
     $pfDeployGroup_Dynamicdata = new PluginFusioninventoryDeployGroup_Dynamicdata();
     // Create package
     $input = array('entities_id' => 0, 'name' => 'package');
     $packages_id = $pfDeployPackage->add($input);
     // Create fusioninventory dynamic group
     $input = array('name' => 'all computers have name computer', 'type' => 'DYNAMIC');
     $groups_id = $pfDeployGroup->add($input);
     $input = array('plugin_fusioninventory_deploygroups_id' => $groups_id, 'fields_array' => 'a:2:{s:8:"criteria";a:1:{i:0;a:3:{s:5:"field";s:1:"1";s:10:"searchtype";s:8:"contains";s:5:"value";s:8:"computer";}}s:12:"metacriteria";s:0:"";}');
     $pfDeployGroup_Dynamicdata->add($input);
     // create task
     $input = array('entities_id' => 0, 'name' => 'deploy', 'is_active' => 1);
     $tasks_id = $pfTask->add($input);
     // create takjob
     $input = array('plugin_fusioninventory_tasks_id' => $tasks_id, 'entities_id' => 0, 'name' => 'deploy', 'method' => 'deployinstall', 'targets' => '[{"PluginFusioninventoryDeployPackage":"' . $packages_id . '"}]', 'actors' => '[{"PluginFusioninventoryDeployGroup":"' . $tasks_id . '"}]');
     $pfTaskjob->add($input);
     // Create computers + agents
     $input = array('entities_id' => 0, 'name' => 'computer1');
     $computers_id = $computer->add($input);
     $input = array('entities_id' => 0, 'name' => 'portdavid', 'version' => '{"INVENTORY":"v2.3.11"}', 'device_id' => 'portdavid', 'useragent' => 'FusionInventory-Agent_v2.3.11', 'computers_id' => $computers_id);
     $pfAgent->add($input);
     $input = array('entities_id' => 0, 'name' => 'computer2');
     $computers_id = $computer->add($input);
     $input = array('entities_id' => 0, 'name' => 'computer2', 'version' => '{"INVENTORY":"v2.3.11"}', 'device_id' => 'computer2', 'useragent' => 'FusionInventory-Agent_v2.3.11', 'computers_id' => $computers_id);
     $pfAgent->add($input);
     $input = array('entities_id' => 0, 'name' => 'computer3');
     $computers_id = $computer->add($input);
     $input = array('entities_id' => 0, 'name' => 'computer3', 'version' => '{"INVENTORY":"v2.3.11"}', 'device_id' => 'computer3', 'useragent' => 'FusionInventory-Agent_v2.3.11', 'computers_id' => $computers_id);
     $pfAgent->add($input);
 }
 /**
  * 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;
 }
 function prepareRun($taskjob_id, $definitions_filter = NULL)
 {
     global $DB;
     $task = new PluginFusioninventoryTask();
     $job = new PluginFusioninventoryTaskjob();
     $joblog = new PluginFusioninventoryTaskjoblog();
     $jobstate = new PluginFusioninventoryTaskjobstate();
     $agent = new PluginFusioninventoryAgent();
     $agentmodule = new PluginFusioninventoryAgentmodule();
     $job->getFromDB($taskjob_id);
     $task->getFromDB($job->fields['plugin_fusioninventory_tasks_id']);
     $communication = $task->fields['communication'];
     $actions = importArrayFromDB($job->fields['action']);
     $definitions = importArrayFromDB($job->fields['definition']);
     $taskvalid = 0;
     $computers = array();
     foreach ($actions as $action) {
         $itemtype = key($action);
         $items_id = current($action);
         switch ($itemtype) {
             case 'Computer':
                 if ($this->definitionFiltered("Computer", $definitions_filter)) {
                     break;
                 }
                 $computers[] = $items_id;
                 break;
             case 'Group':
                 if ($this->definitionFiltered("Group", $definitions_filter)) {
                     break;
                 }
                 $computer_object = new Computer();
                 //find computers by user associated with this group
                 $group_users = new Group_User();
                 $group = new Group();
                 $group->getFromDB($items_id);
                 $members = array();
                 $computers_a_1 = array();
                 $computers_a_2 = array();
                 //array_keys($group_users->find("groups_id = '$items_id'"));
                 $members = $group_users->getGroupUsers($items_id);
                 foreach ($members as $member) {
                     $computers = $computer_object->find("users_id = '{$member['id']}' " . " AND `is_deleted`='0' AND `is_template`='0'");
                     foreach ($computers as $computer) {
                         $computers_a_1[] = $computer['id'];
                     }
                 }
                 //find computers directly associated with this group
                 $computers = $computer_object->find("groups_id = '{$items_id}' " . " AND `is_deleted`='0' AND `is_template`='0'");
                 foreach ($computers as $computer) {
                     $computers_a_2[] = $computer['id'];
                 }
                 //merge two previous array and deduplicate entries
                 $computers = array_unique(array_merge($computers_a_1, $computers_a_2));
                 break;
             case 'PluginFusioninventoryDeployGroup':
                 $group = new PluginFusioninventoryDeployGroup();
                 $group->getFromDB($items_id);
                 switch ($group->getField('type')) {
                     case 'STATIC':
                         if ($this->definitionFiltered("PluginFusioninventoryDeployGroupStatic", $definitions_filter)) {
                             break;
                         }
                         $query = "SELECT items_id\n                     FROM glpi_plugin_fusioninventory_deploygroups_staticdatas\n                     WHERE groups_id = '{$items_id}'\n                     AND itemtype = 'Computer'";
                         $res = $DB->query($query);
                         while ($row = $DB->fetch_assoc($res)) {
                             $computers[] = $row['items_id'];
                         }
                         break;
                     case 'DYNAMIC':
                         if ($this->definitionFiltered("PluginFusioninventoryDeployGroupDynamic", $definitions_filter)) {
                             break;
                         }
                         //$definitions_filter is NULL = update by crontask !
                         if ($definitions_filter != NULL) {
                             $where = " AND `can_update_group`='1'";
                         } else {
                             $where = "";
                         }
                         $query = "SELECT fields_array\n                     FROM glpi_plugin_fusioninventory_deploygroups_dynamicdatas\n                     WHERE groups_id = '{$items_id}' {$where}\n                     LIMIT 1";
                         $res = $DB->query($query);
                         $row = $DB->fetch_assoc($res);
                         //No dynamic groups have been found : break
                         if ($DB->numrows($res) == 0) {
                             break;
                         }
                         if (isset($_GET)) {
                             $get_tmp = $_GET;
                         }
                         if (isset($_SESSION["glpisearchcount"]['Computer'])) {
                             unset($_SESSION["glpisearchcount"]['Computer']);
                         }
                         if (isset($_SESSION["glpisearchcount2"]['Computer'])) {
                             unset($_SESSION["glpisearchcount2"]['Computer']);
                         }
                         $_GET = importArrayFromDB($row['fields_array']);
                         $_GET["glpisearchcount"] = count($_GET['field']);
                         if (isset($_GET['field2'])) {
                             $_GET["glpisearchcount2"] = count($_GET['field2']);
                         }
                         $pfSearch = new PluginFusioninventorySearch();
                         Search::manageParams('Computer');
                         $glpilist_limit = $_SESSION['glpilist_limit'];
                         $_SESSION['glpilist_limit'] = 999999999;
                         $result = $pfSearch->constructSQL('Computer', $_GET);
                         $_SESSION['glpilist_limit'] = $glpilist_limit;
                         while ($data = $DB->fetch_array($result)) {
                             $computers[] = $data['id'];
                         }
                         if (count($get_tmp) > 0) {
                             $_GET = $get_tmp;
                         }
                         break;
                 }
                 break;
         }
     }
     //Remove duplicatas from array
     //We are using isset for faster processing than array_unique because we might have many
     //entries in this list.
     $tmp_computers = array();
     foreach ($computers as $computer) {
         if (!isset($tmp_computers[$computer])) {
             $tmp_computers[$computer] = 1;
         }
     }
     $computers = array_keys($tmp_computers);
     $c_input = array();
     $c_input['plugin_fusioninventory_taskjobs_id'] = $job->fields['id'];
     $c_input['state'] = 0;
     $c_input['plugin_fusioninventory_agents_id'] = 0;
     $c_input['execution_id'] = $task->fields['execution_id'];
     $package = new PluginFusioninventoryDeployPackage();
     foreach ($computers as $computer_id) {
         //Unique Id match taskjobstatuses for an agent(computer)
         foreach ($definitions as $definition) {
             $uniqid = uniqid();
             $package->getFromDB($definition['PluginFusioninventoryDeployPackage']);
             $c_input['state'] = 0;
             $c_input['itemtype'] = 'PluginFusioninventoryDeployPackage';
             $c_input['items_id'] = $package->fields['id'];
             $c_input['date'] = date("Y-m-d H:i:s");
             $c_input['uniqid'] = $uniqid;
             //get agent for this computer
             $agents_id = $agent->getAgentWithComputerid($computer_id);
             if ($agents_id === FALSE) {
                 $jobstates_id = $jobstate->add($c_input);
                 $jobstate->changeStatusFinish($jobstates_id, 0, '', 1, "No agent found for [[Computer::" . $computer_id . "]]", 0, 0);
             } else {
                 if ($agentmodule->isAgentCanDo('DEPLOY', $agents_id)) {
                     $c_input['plugin_fusioninventory_agents_id'] = $agents_id;
                     $jobstates_running = $jobstate->find(implode(" ", array("    `itemtype` = 'PluginFusioninventoryDeployPackage'", "AND `items_id` = " . $package->fields['id'], "AND `state` <> " . PluginFusioninventoryTaskjobstate::FINISHED, "AND `plugin_fusioninventory_agents_id` = " . $agents_id)));
                     if (count($jobstates_running) == 0) {
                         # Push the agent, in the stack of agent to awake
                         if ($communication == "push") {
                             $_SESSION['glpi_plugin_fusioninventory']['agents'][$agents_id] = 1;
                         }
                         $jobstates_id = $jobstate->add($c_input);
                         //Add log of taskjob
                         $c_input['plugin_fusioninventory_taskjobstates_id'] = $jobstates_id;
                         $c_input['state'] = PluginFusioninventoryTaskjoblog::TASK_PREPARED;
                         $taskvalid++;
                         $joblog->add($c_input);
                         unset($c_input['state']);
                         unset($c_input['plugin_fusioninventory_agents_id']);
                     }
                 }
             }
         }
     }
     if ($taskvalid > 0) {
         $job->fields['status'] = 1;
         $job->update($job->fields);
     } else {
         $job->reinitializeTaskjobs($job->fields['plugin_fusioninventory_tasks_id']);
     }
 }
 function 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;
 }
  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-2015 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'], "taskjob_moduletypes.php")) {
    include "../../../inc/includes.php";
    header("Content-Type: text/html; charset=UTF-8");
    Html::header_nocache();
}
Session::checkCentralAccess();
$pfTaskjob = new PluginFusioninventoryTaskjob();
$pfTaskjob->ajaxModuleTypesDropdown($_GET);
?>

 /**
  * Change the status to finish
  *
  * @param $taskjobstates_id integer id of the taskjobstates
  * @param $items_id integer id of the item
  * @param $itemtype value type of the item
  * @param $error bool error
  * @param $message value message for the status
  * @param $unknown bool unmanaged or not device
  *
  * @return nothing
  *
  **/
 function changeStatusFinish($taskjobstates_id, $items_id, $itemtype, $error = 0, $message = '', $unmanaged = 0, $reinitialize = 1)
 {
     global $DB;
     $pfTaskjoblog = new PluginFusioninventoryTaskjoblog();
     $pfTaskjob = new PluginFusioninventoryTaskjob();
     $pfTask = new PluginFusioninventoryTask();
     $this->getFromDB($taskjobstates_id);
     $input = array();
     $input['id'] = $this->fields['id'];
     $input['state'] = self::FINISHED;
     $log_input = array();
     if ($unmanaged == "1") {
         $log_input['state'] = PluginFusioninventoryTaskjoblog::TASK_UNKNOWN;
         $input['state'] = self::FINISHED;
     } else {
         if ($error == "1") {
             $log_input['state'] = PluginFusioninventoryTaskjoblog::TASK_ERROR;
             $input['state'] = self::IN_ERROR;
         } else {
             $log_input['state'] = PluginFusioninventoryTaskjoblog::TASK_OK;
             $input['state'] = self::FINISHED;
         }
     }
     $this->update($input);
     $log_input['plugin_fusioninventory_taskjobstates_id'] = $taskjobstates_id;
     $log_input['items_id'] = $items_id;
     $log_input['itemtype'] = $itemtype;
     $log_input['date'] = date("Y-m-d H:i:s");
     $log_input['comment'] = $message;
     $pfTaskjoblog->add($log_input);
     $pfTaskjob->getFromDB($this->fields['plugin_fusioninventory_taskjobs_id']);
 }
 /**
  * @test
  */
 public function PrinterToInventoryWithoutIP()
 {
     self::restore_database();
     $printer = new Printer();
     $networkport = new NetworkPort();
     $networkName = new NetworkName();
     $pfPrinter = new PluginFusioninventoryPrinter();
     $pfTask = new PluginFusioninventoryTask();
     $pfTaskjob = new PluginFusioninventoryTaskjob();
     $computer = new Computer();
     $pfAgent = new PluginFusioninventoryAgent();
     $communication = new PluginFusioninventoryCommunication();
     // Create computers + agents
     $input = array('entities_id' => 0, 'name' => 'computer1');
     $computers_id = $computer->add($input);
     $input = array('entities_id' => 0, 'name' => 'computer1', 'version' => '{"INVENTORY":"v2.3.11"}', 'device_id' => 'computer1', 'useragent' => 'FusionInventory-Agent_v2.3.11', 'computers_id' => $computers_id);
     $pfAgent->add($input);
     // Create printer
     $input = array('name' => 'printer 001', 'entities_id' => 0);
     $printers_id = $printer->add($input);
     // Add port
     $networkports_id = $networkport->add(array('itemtype' => 'Printer', 'instantiation_type' => 'NetworkPortEthernet', 'items_id' => $printers_id, 'entities_id' => 0));
     $networknames_id = $networkName->add(array('entities_id' => 0, 'itemtype' => 'NetworkPort', 'items_id' => $networkports_id));
     $input = array('printers_id' => 1, 'plugin_fusioninventory_configsecurities_id' => 2);
     $pfPrinter->add($input);
     // Add task
     // create task
     $input = array('entities_id' => 0, 'name' => 'network inventory', 'is_active' => 1);
     $tasks_id = $pfTask->add($input);
     // create taskjob
     $input = array('plugin_fusioninventory_tasks_id' => $tasks_id, 'entities_id' => 0, 'name' => 'inventory', 'method' => 'networkinventory', 'targets' => '[{"Printer":"' . $printers_id . '"}]', 'actors' => '[{"PluginFusioninventoryAgent":"1"}]');
     $pfTaskjob->add($input);
     PluginFusioninventoryTask::cronTaskscheduler();
     $data = $pfTask->getJoblogs(array(1));
     // Task is prepared
     // Agent will get data
     $communication->getTaskAgent(1);
     $message = $communication->getMessage();
     $json = json_encode($message);
     $array = json_decode($json, TRUE);
     $ref = array();
     $this->assertEquals($ref, $array, 'XML of SNMP inventory task');
 }
  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    Walid Nouh
  @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'], "dropdownactionlist.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();
$pfTaskjob = new PluginFusioninventoryTaskjob();
$pfTaskjob->dropdownAction("ActionList", $_POST['ActionType'], $_POST['method'], $_POST['actiontypeid']);
    if ($iprange->checkip($_POST)) {
        $_POST['ip_start'] = (int) $_POST['ip_start0'] . "." . (int) $_POST['ip_start1'] . ".";
        $_POST['ip_start'] .= (int) $_POST['ip_start2'] . "." . (int) $_POST['ip_start3'];
        $_POST['ip_end'] = (int) $_POST['ip_end0'] . "." . (int) $_POST['ip_end1'] . ".";
        $_POST['ip_end'] .= (int) $_POST['ip_end2'] . "." . (int) $_POST['ip_end3'];
        $iprange->add($_POST);
        Html::back();
    } else {
        Html::back();
    }
} else {
    if (isset($_POST["update"])) {
        if (isset($_POST['communication'])) {
            //task permanent update
            $task = new PluginFusioninventoryTask();
            $taskjob = new PluginFusioninventoryTaskjob();
            $task->getFromDB($_POST['task_id']);
            $input_task = array();
            $input_task['id'] = $task->fields['id'];
            $taskjob->getFromDB($_POST['taskjob_id']);
            $input_taskjob = array();
            $input_taskjob['id'] = $taskjob->fields['id'];
            $input_task["is_active"] = $_POST['is_active'];
            $input_task["periodicity_count"] = $_POST['periodicity_count'];
            $input_task["periodicity_type"] = $_POST['periodicity_type'];
            if (!empty($_POST['action'])) {
                $a_actionDB = array();
                $a_actionDB[]['PluginFusioninventoryAgent'] = $_POST['action'];
                $input_taskjob["action"] = exportArrayToDB($a_actionDB);
            } else {
                $input_taskjob["action"] = '';
  along with FusionInventory. If not, see <http://www.gnu.org/licenses/>.

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

  @package   FusionInventory
  @author    David Durieux
  @co-author
  @copyright Copyright (c) 2010-2011 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'], "taskmethodupdate.php")) {
    include "../../../inc/includes.php";
    header("Content-Type: text/html; charset=UTF-8");
    Html::header_nocache();
}
Session::checkCentralAccess();
$value = 0;
$title = 0;
if (isset($_POST['value'])) {
    $value = $_POST['value'];
}
if ($_POST['method'] != '') {
    $pfTaskjob = new PluginFusioninventoryTaskjob();
    $pfTaskjob->updateMethod($_POST['method'], $_POST['taskjobs_id']);
}
 /**
  * @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);
 }
  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-2011 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'], "taskjob_moduleitems.php")) {
    include "../../../inc/includes.php";
    header("Content-Type: text/html; charset=UTF-8");
    Html::header_nocache();
}
Session::checkCentralAccess();
$pfTaskjob = new PluginFusioninventoryTaskjob();
$pfTaskjob->ajaxModuleItemsDropdown($_GET);
?>


  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'], "dropdowntypelist.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();
if ($_POST[$_POST['myname']] != '') {
    $pfTaskjob = new PluginFusioninventoryTaskjob();
    $pfTaskjob->dropdownValue($_POST['myname'], $_POST[$_POST['myname']], $_POST['method'], $_POST[$_POST['name'] . 'typeid'], $_POST['taskjobs_id']);
}
 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']);
     }
 }
 /**
  * @since version 0.85
  *
  * @see CommonDBTM::processMassiveActionsForOneItemtype()
  **/
 static function processMassiveActionsForOneItemtype(MassiveAction $ma, CommonDBTM $item, array $ids)
 {
     $pfTask = new self();
     $pfTaskjob = new PluginFusioninventoryTaskjob();
     switch ($ma->getAction()) {
         case "transfert":
             foreach ($ids as $key) {
                 if ($pfTask->getFromDB($key)) {
                     $a_taskjobs = $pfTaskjob->find("`plugin_fusioninventory_tasks_id`='" . $key . "'");
                     foreach ($a_taskjobs as $data1) {
                         $input = array();
                         $input['id'] = $data1['id'];
                         $input['entities_id'] = $_POST['entities_id'];
                         $pfTaskjob->update($input);
                     }
                     $input = array();
                     $input['id'] = $key;
                     $input['entities_id'] = $_POST['entities_id'];
                     if ($pfTask->update($input)) {
                         //set action massive ok for this item
                         $ma->itemDone($item->getType(), $key, MassiveAction::ACTION_OK);
                     } else {
                         // KO
                         $ma->itemDone($item->getType(), $key, MassiveAction::ACTION_KO);
                     }
                 }
             }
             break;
         case 'target_task':
             $taskjob = new PluginFusioninventoryTaskjob();
             $tasks = array();
             // prepare base insertion
             $input = array('plugin_fusioninventory_tasks_id' => $ma->POST['tasks_id'], 'entities_id' => 0, 'name' => 'deploy', 'method' => 'deployinstall', 'targets' => '[{"PluginFusioninventoryDeployPackage":"' . $ma->POST['packages_id'] . '"}]', 'actor' => array());
             if (array_key_exists('separate_jobs', $_POST)) {
                 foreach ($ids as $key) {
                     $input['actors'] = '[{"Computer":"' . $key . '"}]';
                     if ($pfTaskjob->add($input)) {
                         $ma->itemDone($item->getType(), $key, MassiveAction::ACTION_OK);
                     } else {
                         $ma->itemDone($item->getType(), $key, MassiveAction::ACTION_KO);
                     }
                 }
             } else {
                 foreach ($ids as $key) {
                     $input['actors'][] = array('Computer' => $key);
                     $ma->itemDone($item->getType(), $key, MassiveAction::ACTION_OK);
                 }
                 $input['actors'] = json_encode($input['actors']);
                 $pfTaskjob->add($input);
             }
             break;
     }
 }
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  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-2011 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'], "taskjob_form.php")) {
    include "../../../inc/includes.php";
    header("Content-Type: text/html; charset=UTF-8");
    Html::header_nocache();
}
Session::checkCentralAccess();
// $_GET['taskjobs_id'] => update taskjob
// $_GET['tasks_id'] => add new taskjob
$pfTaskjob = new PluginFusioninventoryTaskjob();
$pfTaskjob->ajaxGetForm($_GET);
  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-2015 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'], "taskjobaddtype.php")) {
    include "../../../inc/includes.php";
    header("Content-Type: text/html; charset=UTF-8");
    Html::header_nocache();
}
Session::checkCentralAccess();
$value = 0;
$title = 0;
if (isset($_POST['value'])) {
    $value = $_POST['value'];
}
$pfTaskjob = new PluginFusioninventoryTaskjob();
$pfTaskjob->additemtodefatc($_POST['type'], $_POST['itemtype'], $_POST['items_id'], $_POST['taskjobs_id']);
 /**
  * Submit Form values
  */
 public function submitForm($postvars)
 {
     if (isset($postvars['definition_add'])) {
         // * Add a definition
         $mytaskjob->getFromDB($postvars['id']);
         $a_listdef = importArrayFromDB($mytaskjob->fields['definition']);
         $add = 1;
         foreach ($a_listdef as $dataDB) {
             if (isset($dataDB[$postvars['DefinitionType']]) and $dataDB[$postvars['DefinitionType']] == $postvars['definitionselectiontoadd']) {
                 $add = 0;
                 break;
             }
         }
         if ($add == '1') {
             if (isset($postvars['DefinitionType']) and $postvars['DefinitionType'] != '') {
                 $a_listdef[] = array($postvars['DefinitionType'] => $postvars['definitionselectiontoadd']);
             }
         }
         $input = array();
         $input['id'] = $postvars['id'];
         $input['definition'] = exportArrayToDB($a_listdef);
         $mytaskjob->update($input);
         Html::back();
     } else {
         if (isset($postvars['action_add'])) {
             // * Add an action
             $mytaskjob->getFromDB($postvars['id']);
             $a_listact = importArrayFromDB($mytaskjob->fields['action']);
             $add = 1;
             foreach ($a_listact as $dataDB) {
                 if (isset($dataDB[$postvars['ActionType']]) and $dataDB[$postvars['ActionType']] == $postvars['actionselectiontoadd']) {
                     $add = 0;
                     break;
                 }
             }
             if ($add == '1') {
                 if (isset($postvars['ActionType']) and $postvars['ActionType'] != '') {
                     $a_listact[] = array($postvars['ActionType'] => $postvars['actionselectiontoadd']);
                 }
             }
             $input = array();
             $input['id'] = $postvars['id'];
             $input['action'] = exportArrayToDB($a_listact);
             $mytaskjob->update($input);
             Html::back();
         } else {
             if (isset($postvars['definition_delete'])) {
                 // * Delete definition
                 $mytaskjob->getFromDB($postvars['id']);
                 $a_listdef = importArrayFromDB($mytaskjob->fields['definition']);
                 foreach ($postvars['definition_to_delete'] as $itemdelete) {
                     $datadel = explode('-', $itemdelete);
                     foreach ($a_listdef as $num => $dataDB) {
                         if (isset($dataDB[$datadel[0]]) and $dataDB[$datadel[0]] == $datadel[1]) {
                             unset($a_listdef[$num]);
                         }
                     }
                 }
                 $input = array();
                 $input['id'] = $postvars['id'];
                 $input['definition'] = exportArrayToDB($a_listdef);
                 $mytaskjob->update($input);
                 Html::back();
             } else {
                 if (isset($postvars['action_delete'])) {
                     // * Delete action
                     $mytaskjob->getFromDB($postvars['id']);
                     $a_listact = importArrayFromDB($mytaskjob->fields['action']);
                     foreach ($postvars['action_to_delete'] as $itemdelete) {
                         $datadel = explode('-', $itemdelete);
                         foreach ($a_listact as $num => $dataDB) {
                             if (isset($dataDB[$datadel[0]]) and $dataDB[$datadel[0]] == $datadel[1]) {
                                 unset($a_listact[$num]);
                             }
                         }
                     }
                     $input = array();
                     $input['id'] = $postvars['id'];
                     $input['action'] = exportArrayToDB($a_listact);
                     $mytaskjob->update($input);
                     Html::back();
                     /**
                      * Wizard related method disabled for 0.85
                      * TODO: cf. TaskJob::showQuickForm()
                      */
                     //} else if (isset($postvars['quickform'])) {
                     //   $pfTask = new PluginFusioninventoryTask();
                     //   if (isset($postvars['update'])) {
                     //      $mytaskjob->getFromDB($postvars['id']);
                     //      $pfTask->getFromDB($mytaskjob->fields['plugin_fusioninventory_tasks_id']);
                     //   }
                     //   $inputtaskjob = array();
                     //   $inputtask = array();
                     //   if (isset($postvars['update'])) {
                     //      $inputtaskjob['id'] = $postvars['id'];
                     //      $inputtask['id'] = $mytaskjob->fields['plugin_fusioninventory_tasks_id'];
                     //   }
                     //   $inputtaskjob['name'] = $postvars['name'];
                     //   if (isset($postvars['add']) OR $pfTask->fields['name'] == '') {
                     //      $inputtask['name'] = $postvars['name'];
                     //   }
                     //   $inputtask['is_active'] = $postvars['is_active'];
                     //   $inputtaskjob['method'] = $postvars['method'];
                     //   $inputtask['communication'] = $postvars['communication'];
                     //   $inputtask['periodicity_count'] = $postvars['periodicity_count'];
                     //   $inputtask['periodicity_type'] = $postvars['periodicity_type'];
                     //   $inputtask['entities_id'] = $_SESSION['glpiactive_entity'];
                     //   $inputtaskjob['entities_id'] = $_SESSION['glpiactive_entity'];
                     //   if (isset($postvars['update'])) {
                     //      $mytaskjob->update($inputtaskjob);
                     //      $pfTask->update($inputtask);
                     //      Html::back();
                     //   } else if (isset($postvars['add'])) {
                     //      if (!isset($postvars['entities_id'])) {
                     //         $postvars['entities_id'] = $_SESSION['glpidefault_entity'];
                     //      }
                     //      // Get entity of task
                     //      if (isset($postvars['plugin_fusioninventory_tasks_id'])) {
                     //         $pfTask = new PluginFusioninventoryTask();
                     //         $pfTask->getFromDB($postvars['plugin_fusioninventory_tasks_id']);
                     //         $entities_list = getSonsOf('glpi_entities', $pfTask->fields['entities_id']);
                     //         if (!in_array($postvars['entities_id'], $entities_list)) {
                     //            $postvars['entities_id'] = $pfTask->fields['entities_id'];
                     //         }
                     //      } else {
                     //         $inputtask['date_scheduled'] = date("Y-m-d H:i:s");
                     //         $task_id = $pfTask->add($inputtask);
                     //         $inputtaskjob['plugin_fusioninventory_tasks_id'] = $task_id;
                     //      }
                     //      if (isset($postvars['method_id'])) {
                     //         $postvars['method']  = $postvars['method_id'];
                     //      }
                     //      $inputtaskjob['plugins_id'] = $postvars['method-'.$postvars['method']];
                     //      $taskjobs_id = $mytaskjob->add($inputtaskjob);
                     //      $redirect = $_SERVER['HTTP_REFERER'];
                     //      $redirect = str_replace('&id=0', '&id='.$taskjobs_id, $redirect);
                     //      Html::redirect($redirect);
                     //   }
                 } else {
                     if (isset($postvars['taskjobstoforcerun'])) {
                         // * Force running many tasks (wizard)
                         Session::checkRight('plugin_fusioninventory_task', UPDATE);
                         $pfTaskjob = new PluginFusioninventoryTaskjob();
                         $_SESSION["plugin_fusioninventory_forcerun"] = array();
                         foreach ($postvars['taskjobstoforcerun'] as $taskjobs_id) {
                             $pfTaskjob->getFromDB($taskjobs_id);
                             $uniqid = $pfTaskjob->forceRunningTask($pfTaskjob->fields['plugin_fusioninventory_tasks_id']);
                             $_SESSION["plugin_fusioninventory_forcerun"][$taskjobs_id] = $uniqid;
                         }
                         unset($_SESSION["MESSAGE_AFTER_REDIRECT"]);
                     } else {
                         if (isset($postvars['add']) || isset($postvars['update'])) {
                             // * Add and update taskjob
                             Session::checkRight('plugin_fusioninventory_task', CREATE);
                             if (isset($postvars['add'])) {
                                 if (!isset($postvars['entities_id'])) {
                                     $postvars['entities_id'] = $_SESSION['glpidefault_entity'];
                                 }
                                 // Get entity of task
                                 $pfTask = new PluginFusioninventoryTask();
                                 $pfTask->getFromDB($postvars['plugin_fusioninventory_tasks_id']);
                                 $entities_list = getSonsOf('glpi_entities', $pfTask->fields['entities_id']);
                                 if (!in_array($postvars['entities_id'], $entities_list)) {
                                     $postvars['entities_id'] = $pfTask->fields['entities_id'];
                                 }
                                 //$postvars['execution_id'] = $pfTask->fields['execution_id'];
                                 $this->add($postvars);
                             } else {
                                 if (isset($postvars['method_id'])) {
                                     $postvars['method'] = $postvars['method_id'];
                                 }
                                 $targets = array();
                                 if (array_key_exists('targets', $postvars) and is_array($postvars['targets']) and count($postvars['targets']) > 0) {
                                     foreach ($postvars['targets'] as $target) {
                                         list($itemtype, $itemid) = explode('-', $target);
                                         $targets[] = array($itemtype => $itemid);
                                     }
                                 }
                                 $postvars['targets'] = exportArrayToDB($targets);
                                 $actors = array();
                                 if (array_key_exists('actors', $postvars) and is_array($postvars['actors']) and count($postvars['actors']) > 0) {
                                     foreach ($postvars['actors'] as $actor) {
                                         list($itemtype, $itemid) = explode('-', $actor);
                                         $actors[] = array($itemtype => $itemid);
                                     }
                                 }
                                 $postvars['actors'] = exportArrayToDB($actors);
                                 //TODO: get rid of plugins_id and just use method
                                 //$postvars['plugins_id'] = $postvars['method-'.$postvars['method']];
                                 $this->update($postvars);
                             }
                         } else {
                             if (isset($postvars["delete"])) {
                                 // * delete taskjob
                                 Session::checkRight('plugin_fusioninventory_task', PURGE);
                                 $this->delete($postvars);
                             } elseif (isset($postvars['itemaddaction'])) {
                                 $array = explode("||", $postvars['methodaction']);
                                 $module = $array[0];
                                 $method = $array[1];
                                 // Add task
                                 $mytask = new PluginFusioninventoryTask();
                                 $input = array();
                                 $input['name'] = $method;
                                 $task_id = $mytask->add($input);
                                 // Add job with this device
                                 $input = array();
                                 $input['plugin_fusioninventory_tasks_id'] = $task_id;
                                 $input['name'] = $method;
                                 $input['datetime_start'] = $postvars['datetime_start'];
                                 $input['plugins_id'] = PluginFusioninventoryModule::getModuleId($module);
                                 $input['method'] = $method;
                                 $a_selectionDB = array();
                                 $a_selectionDB[][$postvars['itemtype']] = $postvars['items_id'];
                                 $input['definition'] = exportArrayToDB($a_selectionDB);
                                 $taskname = "plugin_" . $module . "_task_selection_type_" . $method;
                                 if (is_callable($taskname)) {
                                     $input['selection_type'] = call_user_func($taskname, $postvars['itemtype']);
                                 }
                                 $mytaskjob->add($input);
                                 // Upsate task to activate it
                                 $mytask->getFromDB($task_id);
                                 $mytask->fields['is_active'] = "1";
                                 $mytask->update($mytask->fields);
                                 // force running this job (?)
                             } elseif (isset($postvars['forceend'])) {
                                 $taskjobstate = new PluginFusioninventoryTaskjobstate();
                                 $pfTaskjob = new PluginFusioninventoryTaskjob();
                                 $mytaskjobstate->getFromDB($postvars['taskjobstates_id']);
                                 $jobstate = $mytaskjobstate->fields;
                                 $a_taskjobstates = $mytaskjobstate->find("`uniqid`='" . $mytaskjobstate->fields['uniqid'] . "'");
                                 foreach ($a_taskjobstates as $data) {
                                     if ($data['state'] != PluginFusioninventoryTaskjobstate::FINISHED) {
                                         $mytaskjobstate->changeStatusFinish($data['id'], 0, '', 1, "Action cancelled by user", 0, 0);
                                     }
                                 }
                                 $pfTaskjob->getFromDB($jobstate['plugin_fusioninventory_taskjobs_id']);
                                 $pfTaskjob->reinitializeTaskjobs($pfTaskjob->fields['plugin_fusioninventory_tasks_id']);
                             } elseif (isset($postvars['delete_taskjobs'])) {
                                 foreach ($postvars['taskjobs'] as $taskjob_id) {
                                     $input = array('id' => $taskjob_id);
                                     $this->delete($input, true);
                                 }
                             }
                         }
                     }
                 }
             }
         }
     }
 }
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);
                    }
                } else {
 static function displayTabContentForItem(CommonGLPI $item, $tabnum = 1, $withtemplate = 0)
 {
     if ($tabnum == 'task') {
         $pfTask = new PluginFusioninventoryTask();
         $pfTask->showJobLogs();
         $pfTaskjob = new PluginFusioninventoryTaskjob();
         $a_taskjobs = $pfTaskjob->find('`targets` LIKE \'%"PluginFusioninventoryIPRange":"' . $item->getID() . '"%\'');
         foreach ($a_taskjobs as $data) {
             //$pfTask->getFromDB($data['plugin_fusioninventory_tasks_id']);
         }
     }
 }
 public function submitForm($postvars)
 {
     if (isset($postvars['forcestart'])) {
         Session::checkRight('plugin_fusioninventory_task', UPDATE);
         /**
          * TODO: forcing the task execution should be done in the task object
          */
         $pfTaskjob = new PluginFusioninventoryTaskjob();
         $pfTaskjob->forceRunningTask($postvars['id']);
         Html::back();
     } else {
         if (isset($postvars["add"])) {
             Session::checkRight('plugin_fusioninventory_task', CREATE);
             $items_id = $this->add($postvars);
             Html::redirect(str_replace("add=1", "", $_SERVER['HTTP_REFERER']) . "?id=" . $items_id);
         } else {
             if (isset($postvars["purge"])) {
                 Session::checkRight('plugin_fusioninventory_task', PURGE);
                 $pfTaskJob = new PluginFusioninventoryTaskjob();
                 $taskjobs = $pfTaskJob->find("`plugin_fusioninventory_tasks_id` = '" . $postvars['id'] . "' ");
                 foreach ($taskjobs as $taskjob) {
                     $pfTaskJob->delete($taskjob);
                 }
                 $this->delete($postvars);
                 Html::redirect(Toolbox::getItemTypeSearchURL(get_class($this)));
             } else {
                 if (isset($_POST["update"])) {
                     Session::checkRight('plugin_fusioninventory_task', UPDATE);
                     $this->getFromDB($postvars['id']);
                     //Ensure empty value are set to NULL for datetime fields
                     if (isset($postvars['datetime_start']) and $postvars['datetime_start'] === '') {
                         $postvars['datetime_start'] = 'NULL';
                     }
                     if (isset($postvars['datetime_end']) and $postvars['datetime_end'] === '') {
                         $postvars['datetime_end'] = 'NULL';
                     }
                     $this->update($postvars);
                     Html::back();
                 }
             }
         }
     }
 }
  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-2015 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'], "taskjobdeletetype.php")) {
    include "../../../inc/includes.php";
    header("Content-Type: text/html; charset=UTF-8");
    Html::header_nocache();
}
Session::checkCentralAccess();
$value = 0;
$title = 0;
if (isset($_POST['value'])) {
    $value = $_POST['value'];
}
$pfTaskjob = new PluginFusioninventoryTaskjob();
$pfTaskjob->deleteitemtodefatc($_POST['type'], $_POST[$_POST['type'] . 'item'], $_POST['taskjobs_id']);
 /**
  * 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>";
 }
  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-2015 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'], "dropdowndefinitiontypelist.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();
$pfTaskjob = new PluginFusioninventoryTaskjob();
$pfTaskjob->dropdownDefinition("DefinitionList", $_POST['DefinitionType'], $_POST['method'], $_POST['deftypeid'], $_POST['taskjobs_id']);
  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-2015 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'], "dropdowndefinitionlist.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();
$pfTaskjob = new PluginFusioninventoryTaskjob();
$pfTaskjob->showDefinitions($_POST['taskjobs_id']);
 function run($jobstate)
 {
     $pfAgent = new PluginFusioninventoryAgent();
     $pfTaskjobstate = new PluginFusioninventoryTaskjobstate();
     $pfTaskjob = new PluginFusioninventoryTaskjob();
     $pfTaskjoblog = new PluginFusioninventoryTaskjoblog();
     $pfIPRange = new PluginFusioninventoryIPRange();
     $pfConfigSecurity = new PluginFusioninventoryConfigSecurity();
     $pfToolbox = new PluginFusioninventoryToolbox();
     $pfAgent->getFromDB($jobstate->fields['plugin_fusioninventory_agents_id']);
     $sxml_option = $this->message->addChild('OPTION');
     $sxml_option->addChild('NAME', 'NETDISCOVERY');
     $a_versions = importArrayFromDB($pfAgent->fields["version"]);
     // * Disabled by David Durieux, I think it's not required now * //
     //      if (((isset($a_versions["NETWORKDISCOVERY"])) AND ($a_versions["NETWORKDISCOVERY"] >= 1.3))
     //              OR !isset($a_versions["NETWORKDISCOVERY"])) {
     //         if (!file_exists(GLPI_PLUGIN_DOC_DIR."/fusioninventory/discovery.xml")) {
     //            PluginFusioninventorySnmpmodelImportExport::exportDictionnaryFile(FALSE);
     //         }
     //         $sxml_option->addChild('DICOHASH',
     //                                md5_file(GLPI_PLUGIN_DOC_DIR."/fusioninventory/discovery.xml"));
     //      }
     //      if (($pfAgent->fields["senddico"] == "1")) {
     //
     //         if (((isset($a_versions["NETWORKDISCOVERY"]))
     //                 AND ($a_versions["NETWORKDISCOVERY"] >= 1.3))) {
     //
     //            $sxml_option->addChild('DICO',
     //                                   file_get_contents(
     //                                           GLPI_PLUGIN_DOC_DIR."/fusioninventory/discovery.xml"));
     //         }
     //         $input = array();
     //         $input['id'] = $pfAgent->fields['id'];
     //         $input["senddico"] = "0";
     //         $pfAgent->update($input);
     //      }
     $sxml_param = $sxml_option->addChild('PARAM');
     $sxml_param->addAttribute('THREADS_DISCOVERY', $pfAgent->fields["threads_networkdiscovery"]);
     $sxml_param->addAttribute('TIMEOUT', $pfAgent->fields["timeout_networkdiscovery"]);
     $sxml_param->addAttribute('PID', $jobstate->fields['id']);
     $changestate = 0;
     //foreach ($a_Taskjobstates as $taskjobstate) {
     $taskjobstatedatas = $jobstate->fields;
     $sxml_rangeip = $sxml_option->addChild('RANGEIP');
     $pfTaskjob->getFromDB($taskjobstatedatas['plugin_fusioninventory_taskjobs_id']);
     $pfTaskjobstate->getFromDB($taskjobstatedatas['id']);
     $pfIPRange->getFromDB($taskjobstatedatas['items_id']);
     $sxml_rangeip->addAttribute('ID', $pfIPRange->fields['id']);
     if (!is_null($pfTaskjobstate->fields['specificity'])) {
         $a_split = explode("-", $pfTaskjobstate->fields['specificity']);
         $first_ip = $pfIPRange->getIp2long($pfIPRange->fields["ip_start"]);
         $last_ip = long2ip($first_ip + $a_split[1]);
         $first_ip = long2ip($first_ip + $a_split[0]);
         if ($first_ip != '0.0.0.0' && $last_ip != '0.0.0.0') {
             $sxml_rangeip->addAttribute('IPSTART', $first_ip);
             $sxml_rangeip->addAttribute('IPEND', $last_ip);
         }
     } else {
         $sxml_rangeip->addAttribute('IPSTART', $pfIPRange->fields["ip_start"]);
         $sxml_rangeip->addAttribute('IPEND', $pfIPRange->fields["ip_end"]);
     }
     $sxml_rangeip->addAttribute('ENTITY', $pfIPRange->fields["entities_id"]);
     if ($changestate == '0') {
         $pfTaskjobstate->changeStatus($pfTaskjobstate->fields['id'], 1);
         $pfTaskjoblog->addTaskjoblog($pfTaskjobstate->fields['id'], '0', 'PluginFusioninventoryAgent', '1', $pfAgent->fields["threads_networkdiscovery"] . ' threads', $pfAgent->fields["timeout_networkdiscovery"] . ' timeout');
         $changestate = $pfTaskjobstate->fields['id'];
     } else {
         $pfTaskjobstate->changeStatusFinish($pfTaskjobstate->fields['id'], $taskjobstatedatas['items_id'], $taskjobstatedatas['itemtype'], 0, "Merged with " . $changestate);
     }
     //}
     $pfIPRange_ConfigSecurity = new PluginFusioninventoryIPRange_ConfigSecurity();
     $a_auths = $pfIPRange_ConfigSecurity->find("`plugin_fusioninventory_ipranges_id`='" . $pfIPRange->fields['id'] . "'", "rank");
     foreach ($a_auths as $dataAuth) {
         $pfToolbox->addAuth($sxml_option, $dataAuth['plugin_fusioninventory_configsecurities_id']);
     }
     return $this->message;
 }
  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-2015 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'], "dropdowndefinitiontype.php")) {
    include "../../../inc/includes.php";
    header("Content-Type: text/html; charset=UTF-8");
    Html::header_nocache();
}
Session::checkCentralAccess();
$value = 0;
$title = 0;
if (isset($_POST['value'])) {
    $value = $_POST['value'];
}
$pfTaskjob = new PluginFusioninventoryTaskjob();
$pfTaskjob->dropdownDefinitionType("DefinitionType", $_POST['method'], $value, $_POST['taskjobs_id'], "");
 function getAgentsSubnet($nb_computers, $communication, $subnet = '', $ipstart = '', $ipend = '')
 {
     global $DB;
     $pfTaskjob = new PluginFusioninventoryTaskjob();
     $pfAgentmodule = new PluginFusioninventoryAgentmodule();
     // Number of computers min by agent
     $nb_computerByAgentMin = 20;
     $nb_agentsMax = ceil($nb_computers / $nb_computerByAgentMin);
     $a_agentList = array();
     if ($subnet != '') {
         $subnet = " AND `glpi_ipaddresses`.`name` LIKE '" . $subnet . "%' ";
     } else {
         if ($ipstart != '' and $ipend != '') {
             $subnet = " AND ( INET_ATON(`glpi_ipaddresses`.`name`) > INET_ATON('" . $ipstart . "')\n            AND  INET_ATON(`glpi_ipaddresses`.`name`) < INET_ATON('" . $ipend . "') ) ";
         }
     }
     $a_agents = $pfAgentmodule->getAgentsCanDo('NETWORKINVENTORY');
     $a_agentsid = array();
     foreach ($a_agents as $a_agent) {
         $a_agentsid[] = $a_agent['id'];
     }
     if (count($a_agentsid) == '0') {
         return $a_agentList;
     }
     $where = " AND `glpi_plugin_fusioninventory_agents`.`ID` IN (";
     $where .= implode(', ', $a_agentsid);
     $where .= ")\n         AND `glpi_ipaddresses`.`name` != '127.0.0.1' ";
     $query = "SELECT `glpi_plugin_fusioninventory_agents`.`id` as `a_id`,\n         `glpi_ipaddresses`.`name` as ip, token\n         FROM `glpi_plugin_fusioninventory_agents`\n         LEFT JOIN `glpi_networkports`\n            ON `glpi_networkports`.`items_id` = `glpi_plugin_fusioninventory_agents`.`computers_id`\n         LEFT JOIN `glpi_networknames`\n              ON `glpi_networknames`.`items_id`=`glpi_networkports`.`id`\n                 AND `glpi_networknames`.`itemtype`='NetworkPort'\n         LEFT JOIN `glpi_ipaddresses`\n              ON `glpi_ipaddresses`.`items_id`=`glpi_networknames`.`id`\n                 AND `glpi_ipaddresses`.`itemtype`='NetworkName'\n         LEFT JOIN `glpi_computers`\n            ON `glpi_computers`.`id` = `glpi_plugin_fusioninventory_agents`.`computers_id`\n         WHERE `glpi_networkports`.`itemtype`='Computer'\n            " . $subnet . "\n            " . $where . " ";
     Toolbox::logInFile('NET', $query);
     $result = $DB->query($query);
     if ($result) {
         while ($data = $DB->fetch_array($result)) {
             if ($communication == 'push') {
                 if ($pfTaskjob->isAgentAlive("1", $data['a_id'])) {
                     if (!in_array($a_agentList, $data['a_id'])) {
                         $a_agentList[] = $data['a_id'];
                         if (count($a_agentList) >= $nb_agentsMax) {
                             return $a_agentList;
                         }
                     }
                 }
             } else {
                 if ($communication == 'pull') {
                     if (!in_array($data['a_id'], $a_agentList)) {
                         $a_agentList[] = $data['a_id'];
                         if (count($a_agentList) > $nb_agentsMax) {
                             return $a_agentList;
                         }
                     }
                 }
             }
         }
     }
     return $a_agentList;
 }
 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>";
 }