function prepareRun($taskjobs_id)
 {
     $pfTask = new PluginFusioninventoryTask();
     $pfTaskjob = new PluginFusioninventoryTaskjob();
     $pfTaskjoblog = new PluginFusioninventoryTaskjoblog();
     $pfTaskjobstate = new PluginFusioninventoryTaskjobstate();
     $pfAgentmodule = new PluginFusioninventoryAgentmodule();
     $pfIPRange = new PluginFusioninventoryIPRange();
     $pfAgent = new PluginFusioninventoryAgent();
     $uniqid = uniqid();
     $pfTaskjob->getFromDB($taskjobs_id);
     $pfTask->getFromDB($pfTaskjob->fields['plugin_fusioninventory_tasks_id']);
     $communication = $pfTask->fields['communication'];
     //list all iprange
     $a_iprange = importArrayFromDB($pfTaskjob->fields['definition']);
     $count_ip = 0;
     $a_iprangelist = array();
     $a_subnet_nbip = array();
     foreach ($a_iprange as $iprange) {
         $iprange_id = current($iprange);
         $a_iprangelist[] = $iprange_id;
         $pfIPRange->getFromDB($iprange_id);
         $s = $pfIPRange->getIp2long($pfIPRange->fields['ip_start']);
         $e = $pfIPRange->getIp2long($pfIPRange->fields['ip_end']);
         $a_subnet_nbip[$iprange_id] = $e - $s;
         $count_ip += $e - $s;
     }
     //list all agents
     $a_agent = importArrayFromDB($pfTaskjob->fields['action']);
     $dynagent = 0;
     $a_agentlist = array();
     foreach ($a_agent as $agent) {
         $agent_id = current($agent);
         if ($agent_id == '.1') {
             $dynagent = 1;
         } else {
             if ($agent_id == '.2') {
                 $dynagent = 2;
             } else {
                 // Detect if agent exists
                 if ($pfAgent->getFromDB($agent_id)) {
                     if ($pfTask->fields['communication'] == 'pull') {
                         $a_agentlist[$agent_id] = 1;
                     } else {
                         if ($pfTaskjob->isAgentAlive('1', $agent_id)) {
                             $a_agentlist[$agent_id] = 1;
                         }
                     }
                 }
             }
         }
     }
     if ($dynagent == '1') {
         $a_agents = $pfAgentmodule->getAgentsCanDo('NETWORKDISCOVERY');
         foreach ($a_agents as $data) {
             if ($count_ip / 10 >= count($a_agentlist)) {
                 $pfAgent->getFromDB($data['id']);
                 $a_ip = $pfAgent->getIPs();
                 foreach ($a_ip as $ip) {
                     if ($pfTask->fields['communication'] == 'push') {
                         if ($pfTaskjob->isAgentAlive('1', $data['id'])) {
                             $a_agentlist[$data['id']] = 1;
                         }
                     } else {
                         if ($pfTask->fields['communication'] == 'pull') {
                             $a_agentlist[$data['id']] = 1;
                         }
                     }
                 }
             }
         }
     }
     if ($dynagent == '2') {
         // Dynamic with subnet
         $pfSnmpinventory = new PluginFusioninventoryNetworkinventory();
         $taskvalid = 0;
         foreach ($a_subnet_nbip as $iprange_id => $nbips) {
             //$maxagentpossible = $nbips/10;
             $pfIPRange->getFromDB($iprange_id);
             $a_agentListComplete = array();
             $a_agentList = $pfSnmpinventory->getAgentsSubnet($nbips, "push", "", $pfIPRange->fields['ip_start'], $pfIPRange->fields['ip_end']);
             if (isset($a_agentList)) {
                 $a_agentListComplete = array_merge($a_agentListComplete, $a_agentList);
             }
             if (!isset($a_agentListComplete) or empty($a_agentListComplete)) {
                 $a_input = array();
                 $a_input['plugin_fusioninventory_taskjobs_id'] = $taskjobs_id;
                 $a_input['plugin_fusioninventory_agents_id'] = 0;
                 $a_input['state'] = 1;
                 $a_input['itemtype'] = 'PluginFusioninventoryIPRange';
                 $a_input['items_id'] = $iprange_id;
                 $a_input['uniqid'] = $uniqid;
                 $a_input['execution_id'] = $task->fields['execution_id'];
                 $Taskjobstates_id = $pfTaskjobstate->add($a_input);
                 //Add log of taskjob
                 $a_input['plugin_fusioninventory_taskjobstates_id'] = $Taskjobstates_id;
                 $a_input['state'] = 7;
                 $a_input['date'] = date("Y-m-d H:i:s");
                 $pfTaskjoblog->add($a_input);
                 $pfTaskjobstate->changeStatusFinish($Taskjobstates_id, 0, 'PluginFusioninventoryIPRange', 1, "Unable to find agent to run this job");
                 $input_taskjob = array();
                 $input_taskjob['id'] = $pfTaskjob->fields['id'];
                 //$input_taskjob['status'] = 1;
                 $pfTaskjob->update($input_taskjob);
             } else {
                 $s = $pfIPRange->getIp2long($pfIPRange->fields['ip_start']);
                 $e = $pfIPRange->getIp2long($pfIPRange->fields['ip_end']);
                 $nbIpAgent = ceil(($e - $s) / count($a_agentListComplete));
                 $iptimes = 0;
                 foreach ($a_agentListComplete as $agent_id) {
                     $_SESSION['glpi_plugin_fusioninventory']['agents'][$agent_id] = 1;
                     //Add jobstate and put status (waiting on server = 0)
                     $a_input = array();
                     $a_input['plugin_fusioninventory_taskjobs_id'] = $taskjobs_id;
                     $a_input['state'] = 0;
                     $a_input['plugin_fusioninventory_agents_id'] = $agent_id;
                     $a_input['itemtype'] = 'PluginFusioninventoryIPRange';
                     $a_input['uniqid'] = $uniqid;
                     $a_input['execution_id'] = $task->fields['execution_id'];
                     $a_input['items_id'] = $iprange_id;
                     if ($iptimes + $nbIpAgent > $e - $s) {
                         $a_input['specificity'] = $iptimes . "-" . ($e - $s);
                     } else {
                         $a_input['specificity'] = $iptimes . "-" . ($iptimes + $nbIpAgent);
                     }
                     $taskvalid++;
                     $Taskjobstates_id = $pfTaskjobstate->add($a_input);
                     //Add log of taskjob
                     $a_input['plugin_fusioninventory_taskjobstates_id'] = $Taskjobstates_id;
                     $a_input['state'] = 7;
                     $a_input['date'] = date("Y-m-d H:i:s");
                     $pfTaskjoblog->add($a_input);
                     unset($a_input['state']);
                     $iptimes += $nbIpAgent + 1;
                     if ($iptimes >= $e - $s + 1) {
                         break;
                     }
                     $input_taskjob = array();
                     $input_taskjob['id'] = $pfTaskjob->fields['id'];
                     $input_taskjob['status'] = 1;
                     $pfTaskjob->update($input_taskjob);
                 }
             }
         }
         if ($taskvalid == "0") {
             $pfTaskjob->reinitializeTaskjobs($pfTaskjob->fields['plugin_fusioninventory_tasks_id']);
         }
         // *** Add jobstate
     } else {
         if (count($a_agentlist) == 0) {
             $a_input = array();
             $a_input['plugin_fusioninventory_taskjobs_id'] = $taskjobs_id;
             $a_input['state'] = 1;
             $a_input['plugin_fusioninventory_agents_id'] = 0;
             $a_input['itemtype'] = 'PluginFusioninventoryIPRange';
             $a_input['items_id'] = 0;
             $a_input['uniqid'] = $uniqid;
             $a_input['execution_id'] = $task->fields['execution_id'];
             $Taskjobstates_id = $pfTaskjobstate->add($a_input);
             //Add log of taskjob
             $a_input['plugin_fusioninventory_taskjobstates_id'] = $Taskjobstates_id;
             $a_input['state'] = 7;
             $a_input['date'] = date("Y-m-d H:i:s");
             $pfTaskjoblog->add($a_input);
             $pfTaskjobstate->changeStatusFinish($Taskjobstates_id, 0, 'PluginFusioninventoryIPRange', 1, "Unable to find agent to run this job");
             $input_taskjob = array();
             $input_taskjob['id'] = $pfTaskjob->fields['id'];
             //$input_taskjob['status'] = 1;
             $pfTaskjob->update($input_taskjob);
         } else {
             $iptimes = 0;
             $nbIpadded = 0;
             $break = 0;
             $numberIpByAgent = ceil($count_ip / count($a_agentlist));
             $a_iprangelistTmp = $a_iprangelist;
             $ip_id = array_shift($a_iprangelistTmp);
             foreach ($a_agentlist as $agent_id => $ip) {
                 //Add jobstate and put status (waiting on server = 0)
                 $a_input = array();
                 $a_input['plugin_fusioninventory_taskjobs_id'] = $taskjobs_id;
                 $a_input['state'] = 0;
                 $a_input['plugin_fusioninventory_agents_id'] = $agent_id;
                 $a_input['itemtype'] = 'PluginFusioninventoryIPRange';
                 $a_input['uniqid'] = $uniqid;
                 $a_input['execution_id'] = $task->fields['execution_id'];
                 //            $nbIpAgent = $numberIpByAgent;
                 $nbIpadded = 0;
                 foreach ($a_iprangelist as $iprange_id) {
                     if ($ip_id == $iprange_id) {
                         $pfIPRange->getFromDB($iprange_id);
                         $s = $pfIPRange->getIp2long($pfIPRange->fields['ip_start']);
                         $e = $pfIPRange->getIp2long($pfIPRange->fields['ip_end']);
                         if ($communication == "push") {
                             $_SESSION['glpi_plugin_fusioninventory']['agents'][$agent_id] = 1;
                         }
                         $a_input['items_id'] = $iprange_id;
                         $nbIpAgent = $numberIpByAgent - $nbIpadded;
                         if ($iptimes + $nbIpAgent > $e - $s) {
                             $a_input['specificity'] = $iptimes . "-" . ($e - $s);
                             $nbIpadded = $e - $s - $iptimes;
                             $ip_id = array_shift($a_iprangelistTmp);
                             $iptimes = 0;
                         } else {
                             $a_input['specificity'] = $iptimes . "-" . ($iptimes + $nbIpAgent);
                             $iptimes += $nbIpAgent + 1;
                             $nbIpadded = 0;
                             $break = 1;
                         }
                         $Taskjobstates_id = $pfTaskjobstate->add($a_input);
                         //Add log of taskjob
                         $a_input['plugin_fusioninventory_taskjobstates_id'] = $Taskjobstates_id;
                         $a_input['state'] = 7;
                         $a_input['date'] = date("Y-m-d H:i:s");
                         $pfTaskjoblog->add($a_input);
                         unset($a_input['state']);
                     }
                 }
                 $input_taskjob = array();
                 $input_taskjob['id'] = $pfTaskjob->fields['id'];
                 $input_taskjob['status'] = 1;
                 $pfTaskjob->update($input_taskjob);
             }
         }
     }
     return $uniqid;
 }
 function prepareRun($taskjobs_id)
 {
     global $DB;
     $pfTask = new PluginFusioninventoryTask();
     $pfTaskjob = new PluginFusioninventoryTaskjob();
     $pfTaskjoblog = new PluginFusioninventoryTaskjoblog();
     $pfTaskjobstate = new PluginFusioninventoryTaskjobstate();
     $pfIPRange = new PluginFusioninventoryIPRange();
     $pfAgent = new PluginFusioninventoryAgent();
     $a_specificity = array();
     $a_specificity['DEVICE'] = array();
     $uniqid = uniqid();
     $pfTaskjob->getFromDB($taskjobs_id);
     $pfTask->getFromDB($pfTaskjob->fields['plugin_fusioninventory_tasks_id']);
     $NetworkEquipment = new NetworkEquipment();
     $NetworkPort = new NetworkPort();
     /*
      * * Different possibilities  :
      * IP RANGE
      * NetworkEquipment
      * Printer
      *
      * We will count total number of devices to query
      */
     // get all snmpauth
     $a_snmpauth = getAllDatasFromTable("glpi_plugin_fusioninventory_configsecurities");
     // get items_id by type
     $a_iprange = array();
     $a_NetworkEquipment = array();
     $a_Printer = array();
     $communication = $pfTask->fields['communication'];
     $a_definition = importArrayFromDB($pfTaskjob->fields['definition']);
     foreach ($a_definition as $datas) {
         $itemtype = key($datas);
         $items_id = current($datas);
         switch ($itemtype) {
             case 'PluginFusioninventoryIPRange':
                 $a_iprange[] = $items_id;
                 break;
             case 'NetworkEquipment':
                 $query = "SELECT `glpi_networkequipments`.`id` AS `gID`,\n                         `glpi_ipaddresses`.`name` AS `gnifaddr`,\n                         `plugin_fusioninventory_configsecurities_id`,\n                  FROM `glpi_networkequipments`\n                  LEFT JOIN `glpi_plugin_fusioninventory_networkequipments`\n                       ON `networkequipments_id`=`glpi_networkequipments`.`id`\n                  LEFT JOIN `glpi_networkports`\n                       ON `glpi_networkports`.`items_id`=`glpi_networkequipments`.`id`\n                          AND `glpi_networkports`.`itemtype`='NetworkEquipment'\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                  WHERE `glpi_networkequipments`.`is_deleted`='0'\n                       AND `plugin_fusioninventory_configsecurities_id`!='0'\n                       AND `glpi_networkequipments`.`id` = '" . $items_id . "'\n                       AND `glpi_ipaddresses`.`name`!=''\n                  LIMIT 1";
                 $result = $DB->query($query);
                 while ($data = $DB->fetch_array($result)) {
                     if (isset($a_snmpauth[$data['plugin_fusioninventory_configsecurities_id']])) {
                         $input = array();
                         $input['TYPE'] = 'NETWORKING';
                         $input['ID'] = $data['gID'];
                         $input['IP'] = $data['gnifaddr'];
                         $input['AUTHSNMP_ID'] = $data['plugin_fusioninventory_configsecurities_id'];
                         $a_specificity['DEVICE']['NetworkEquipment' . $data['gID']] = $input;
                         $a_NetworkEquipment[] = $items_id;
                     }
                 }
                 break;
             case 'Printer':
                 $query = "SELECT `glpi_printers`.`id` AS `gID`,\n                         `glpi_ipaddresses`.`name` AS `gnifaddr`,\n                         `plugin_fusioninventory_configsecurities_id`,\n                  FROM `glpi_printers`\n                  LEFT JOIN `glpi_plugin_fusioninventory_printers`\n                          ON `printers_id`=`glpi_printers`.`id`\n                  LEFT JOIN `glpi_networkports`\n                       ON `glpi_networkports`.`items_id`=`glpi_printers`.`id`\n                          AND `glpi_networkports`.`itemtype`='Printer'\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                  WHERE `glpi_printers`.`is_deleted`=0\n                        AND `plugin_fusioninventory_configsecurities_id`!='0'\n                        AND `glpi_printers`.`id` = '" . $items_id . "'\n                        AND `glpi_ipaddresses`.`name`!=''\n                  LIMIT 1";
                 $result = $DB->query($query);
                 while ($data = $DB->fetch_array($result)) {
                     if (isset($a_snmpauth[$data['plugin_fusioninventory_configsecurities_id']])) {
                         $input = array();
                         $input['TYPE'] = 'PRINTER';
                         $input['ID'] = $data['gID'];
                         $input['IP'] = $data['gnifaddr'];
                         $input['AUTHSNMP_ID'] = $data['plugin_fusioninventory_configsecurities_id'];
                         $a_specificity['DEVICE']['Printer' . $data['gID']] = $input;
                         $a_Printer[] = $items_id;
                     }
                 }
                 break;
         }
     }
     // Get all devices on each iprange
     foreach ($a_iprange as $items_id) {
         $pfIPRange->getFromDB($items_id);
         // Search NetworkEquipment
         $query = "SELECT `glpi_networkequipments`.`id` AS `gID`,\n                            `glpi_ipaddresses`.`name` AS `gnifaddr`,\n                            `plugin_fusioninventory_configsecurities_id`,\n                     FROM `glpi_networkequipments`\n                     LEFT JOIN `glpi_plugin_fusioninventory_networkequipments`\n                          ON `networkequipments_id`=`glpi_networkequipments`.`id`\n                     LEFT JOIN `glpi_networkports`\n                          ON `glpi_networkports`.`items_id`=`glpi_networkequipments`.`id`\n                             AND `glpi_networkports`.`itemtype`='NetworkEquipment'\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                     WHERE `glpi_networkequipments`.`is_deleted`='0'\n                          AND `plugin_fusioninventory_configsecurities_id`!='0'";
         if ($pfIPRange->fields['entities_id'] != '-1') {
             $entities = "(" . $this->fields['entities_id'];
             foreach (getAncestorsOf("glpi_entities", $pfIPRange->fields['entities_id']) as $parent) {
                 $entities .= ",{$parent}";
             }
             $entities .= ")";
             $query .= " AND `glpi_networkequipments`.`entities_id` IN " . $entities . " ";
         }
         $query .= " AND inet_aton(`glpi_ipaddresses`.`name`)\n                         BETWEEN inet_aton('" . $pfIPRange->fields['ip_start'] . "')\n                         AND inet_aton('" . $pfIPRange->fields['ip_end'] . "') ";
         $query .= " GROUP BY `glpi_networkequipments`.`id`";
         $result = $DB->query($query);
         while ($data = $DB->fetch_array($result)) {
             if (isset($a_snmpauth[$data['plugin_fusioninventory_configsecurities_id']])) {
                 $input = array();
                 $input['TYPE'] = 'NETWORKING';
                 $input['ID'] = $data['gID'];
                 $input['IP'] = $data['gnifaddr'];
                 $input['AUTHSNMP_ID'] = $data['plugin_fusioninventory_configsecurities_id'];
                 $a_specificity['DEVICE']['NetworkEquipment' . $data['gID']] = $input;
                 $a_NetworkEquipment[] = $data['gID'];
             }
         }
         // Search Printer
         $query = "SELECT `glpi_printers`.`id` AS `gID`,\n                         `glpi_ipaddresses`.`name` AS `gnifaddr`,\n                         `plugin_fusioninventory_configsecurities_id`,\n                  FROM `glpi_printers`\n                  LEFT JOIN `glpi_plugin_fusioninventory_printers`\n                          ON `printers_id`=`glpi_printers`.`id`\n                  LEFT JOIN `glpi_networkports`\n                       ON `glpi_networkports`.`items_id`=`glpi_printers`.`id`\n                          AND `glpi_networkports`.`itemtype`='Printer'\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                  WHERE `glpi_printers`.`is_deleted`=0\n                        AND `plugin_fusioninventory_configsecurities_id`!='0'";
         if ($pfIPRange->fields['entities_id'] != '-1') {
             $entities = "(" . $this->fields['entities_id'];
             foreach (getAncestorsOf("glpi_entities", $pfIPRange->fields['entities_id']) as $parent) {
                 $entities .= ",{$parent}";
             }
             $entities .= ")";
             $query .= "AND `glpi_printers`.`entities_id` IN " . $entities . " ";
         }
         $query .= " AND inet_aton(`glpi_ipaddresses`.`name`)\n                      BETWEEN inet_aton('" . $pfIPRange->fields['ip_start'] . "')\n                      AND inet_aton('" . $pfIPRange->fields['ip_end'] . "') ";
         $query .= " GROUP BY `glpi_printers`.`id`";
         $result = $DB->query($query);
         while ($data = $DB->fetch_array($result)) {
             if (isset($a_snmpauth[$data['plugin_fusioninventory_configsecurities_id']])) {
                 $input = array();
                 $input['TYPE'] = 'PRINTER';
                 $input['ID'] = $data['gID'];
                 $input['IP'] = $data['gnifaddr'];
                 $input['AUTHSNMP_ID'] = $data['plugin_fusioninventory_configsecurities_id'];
                 $a_specificity['DEVICE']['Printer' . $data['gID']] = $input;
                 $a_Printer[] = $data['gID'];
             }
         }
     }
     $count_device = count($a_NetworkEquipment) + count($a_Printer);
     $a_actions = importArrayFromDB($pfTaskjob->fields['action']);
     // *** For dynamic agent same subnet, it's an another management ***
     if (strstr($pfTaskjob->fields['action'], '".2"')) {
         $a_subnet = array();
         $a_agentList = array();
         $a_devicesubnet = array();
         foreach ($a_NetworkEquipment as $items_id) {
             $NetworkEquipment->getFromDB($items_id);
             $a_ip = explode(".", $NetworkEquipment->fields['ip']);
             $ip_subnet = $a_ip[0] . "." . $a_ip[1] . "." . $a_ip[2] . ".";
             if (!isset($a_subnet[$ip_subnet])) {
                 $a_subnet[$ip_subnet] = 0;
             }
             $a_subnet[$ip_subnet]++;
             $a_devicesubnet[$ip_subnet]['NetworkEquipment'][$items_id] = 1;
         }
         foreach ($a_Printer as $items_id) {
             $a_ports = $NetworkPort->find("`itemtype`='Printer'\n                                          AND `items_id`='" . $items_id . "'\n                                          AND `ip`!='127.0.0.1'");
             foreach ($a_ports as $a_port) {
                 $a_ip = explode(".", $a_port['ip']);
                 $ip_subnet = $a_ip[0] . "." . $a_ip[1] . "." . $a_ip[2] . ".";
                 if (!isset($a_subnet[$ip_subnet])) {
                     $a_subnet[$ip_subnet] = 0;
                 }
                 $a_subnet[$ip_subnet]++;
                 $a_devicesubnet[$ip_subnet]['Printer'][$items_id] = 1;
             }
         }
         $a_agentsubnet = array();
         foreach ($a_subnet as $subnet => $num) {
             $a_agentList = $this->getAgentsSubnet($num, $communication, $subnet);
             if (!isset($a_agentList)) {
                 $a_agentsubnet[$subnet] = '';
             } else {
                 $a_agentsubnet[$subnet] = $a_agentList;
             }
         }
         $a_input = array();
         $a_input['plugin_fusioninventory_taskjobs_id'] = $taskjobs_id;
         $a_input['state'] = 1;
         $a_input['plugin_fusioninventory_agents_id'] = 0;
         $a_input['itemtype'] = '';
         $a_input['items_id'] = 0;
         $a_input['uniqid'] = $uniqid;
         $a_input['execution_id'] = $task->fields['execution_id'];
         $taskvalid = 0;
         foreach ($a_agentsubnet as $subnet => $a_agentList) {
             if (!isset($a_agentList) or isset($a_agentList) && is_array($a_agentList) && count($a_agentList) == '0' or isset($a_agentList) && !is_array($a_agentList) && $a_agentList == '') {
                 // No agent available for this subnet
                 for ($i = 0; $i < 2; $i++) {
                     $itemtype = 'Printer';
                     if ($i == '0') {
                         $itemtype = 'NetworkEquipment';
                     }
                     if (isset($a_devicesubnet[$subnet][$itemtype])) {
                         foreach ($a_devicesubnet[$subnet][$itemtype] as $items_id => $num) {
                             $a_input['itemtype'] = $itemtype;
                             $a_input['items_id'] = $items_id;
                             $a_input['specificity'] = exportArrayToDB($a_specificity['DEVICE'][$itemtype . $items_id]);
                             $Taskjobstates_id = $pfTaskjobstate->add($a_input);
                             //Add log of taskjob
                             $a_input['plugin_fusioninventory_taskjobstates_id'] = $Taskjobstates_id;
                             $a_input['state'] = 7;
                             $a_input['date'] = date("Y-m-d H:i:s");
                             $pfTaskjoblog->add($a_input);
                             $pfTaskjobstate->changeStatusFinish($Taskjobstates_id, 0, '', 1, "Unable to find agent to inventory " . "this " . $itemtype, 0, 0);
                             $a_input['state'] = 1;
                         }
                     }
                 }
             } else {
                 // add taskjobstate
                 $count_device_subnet = 0;
                 if (isset($a_devicesubnet[$subnet]['NetworkEquipment'])) {
                     $count_device_subnet += count($a_devicesubnet[$subnet]['NetworkEquipment']);
                 }
                 if (isset($a_devicesubnet[$subnet]['Printer'])) {
                     $count_device_subnet += count($a_devicesubnet[$subnet]['Printer']);
                 }
                 $nb_devicebyagent = ceil($count_device_subnet / count($a_agentList));
                 $nbagent = 0;
                 $agent_id = array_pop($a_agentList);
                 $a_input['state'] = 0;
                 for ($i = 0; $i < 2; $i++) {
                     $itemtype = 'Printer';
                     if ($i == '0') {
                         $itemtype = 'NetworkEquipment';
                     }
                     if (isset($a_devicesubnet[$subnet][$itemtype])) {
                         foreach ($a_devicesubnet[$subnet][$itemtype] as $items_id => $num) {
                             $a_input['itemtype'] = $itemtype;
                             $a_input['items_id'] = $items_id;
                             $a_input['specificity'] = exportArrayToDB($a_specificity['DEVICE'][$itemtype . $items_id]);
                             if ($nbagent == $nb_devicebyagent) {
                                 $agent_id = array_pop($a_agentList);
                                 $nbagent = 0;
                             }
                             $a_input['plugin_fusioninventory_agents_id'] = $agent_id;
                             $nbagent++;
                             $taskvalid++;
                             $Taskjobstates_id = $pfTaskjobstate->add($a_input);
                             //Add log of taskjob
                             $a_input['plugin_fusioninventory_taskjobstates_id'] = $Taskjobstates_id;
                             $a_input['state'] = 7;
                             $a_input['date'] = date("Y-m-d H:i:s");
                             $pfTaskjoblog->add($a_input);
                             unset($a_input['state']);
                             $a_input['plugin_fusioninventory_agents_id'] = 0;
                             $a_input['state'] = 0;
                             if ($communication == "push") {
                                 $_SESSION['glpi_plugin_fusioninventory']['agents'][$agent_id] = 1;
                             }
                         }
                     }
                 }
             }
         }
         if ($taskvalid == "0") {
             $pfTaskjob->reinitializeTaskjobs($pfTaskjob->fields['plugin_fusioninventory_tasks_id']);
         }
     } else {
         $a_agentList = array();
         // *** Only agents not dynamic ***
         if (!strstr($pfTaskjob->fields['action'], '".1"') and !strstr($pfTaskjob->fields['action'], '".2"')) {
             $agent_require_model = 0;
             foreach ($a_actions as $a_action) {
                 if (!in_array('.1', $a_action) and !in_array('.2', $a_action)) {
                     $agent_id = current($a_action);
                     if ($pfAgent->getFromDB($agent_id)) {
                         $agent_version = $pfAgent->getAgentVersion($agent_id);
                         if (strnatcmp($agent_version, '2.3.4') < 0) {
                             $agent_require_model = 1;
                         }
                         if ($communication == 'pull') {
                             $a_agentList[] = $agent_id;
                         } else {
                             if ($pfTaskjob->isAgentAlive('1', $agent_id)) {
                                 $a_agentList[] = $agent_id;
                             }
                         }
                     }
                 }
             }
         } else {
             if (strstr($pfTaskjob->fields['action'], '".1"')) {
                 $a_agentList = $this->getAgentsSubnet($count_device, $communication);
             }
         }
         /*
          * Manage agents
          */
         if (count($a_agentList) == 0) {
             $a_input = array();
             $a_input['plugin_fusioninventory_taskjobs_id'] = $taskjobs_id;
             $a_input['state'] = 1;
             $a_input['plugin_fusioninventory_agents_id'] = 0;
             $a_input['itemtype'] = '';
             $a_input['items_id'] = 0;
             $a_input['uniqid'] = $uniqid;
             $a_input['execution_id'] = $task->fields['execution_id'];
             $Taskjobstates_id = $pfTaskjobstate->add($a_input);
             //Add log of taskjob
             $a_input['plugin_fusioninventory_taskjobstates_id'] = $Taskjobstates_id;
             $a_input['state'] = 7;
             $a_input['date'] = date("Y-m-d H:i:s");
             $pfTaskjoblog->add($a_input);
             $pfTaskjobstate->changeStatusFinish($Taskjobstates_id, 0, '', 1, "Unable to find agent to run this job");
             $input_taskjob = array();
             $input_taskjob['id'] = $pfTaskjob->fields['id'];
             //$input_taskjob['status'] = 0;
             $pfTaskjob->update($input_taskjob);
         } elseif ($count_device == 0) {
             $a_input = array();
             $a_input['plugin_fusioninventory_taskjobs_id'] = $taskjobs_id;
             $a_input['state'] = 1;
             $a_input['plugin_fusioninventory_agents_id'] = 0;
             $a_input['itemtype'] = '';
             $a_input['items_id'] = 0;
             $a_input['uniqid'] = $uniqid;
             $Taskjobstates_id = $pfTaskjobstate->add($a_input);
             //Add log of taskjob
             $a_input['plugin_fusioninventory_taskjobstates_id'] = $Taskjobstates_id;
             $a_input['state'] = 7;
             $a_input['date'] = date("Y-m-d H:i:s");
             $pfTaskjoblog->add($a_input);
             $pfTaskjobstate->changeStatusFinish($Taskjobstates_id, 0, '', 0, "No suitable devices to inventory");
             $input_taskjob = array();
             $input_taskjob['id'] = $pfTaskjob->fields['id'];
             //$input_taskjob['status'] = 1;
             $pfTaskjob->update($input_taskjob);
         } else {
             foreach ($a_agentList as $agent_id) {
                 //Add jobstate and put status (waiting on server = 0)
                 $a_input = array();
                 $a_input['plugin_fusioninventory_taskjobs_id'] = $taskjobs_id;
                 $a_input['state'] = 0;
                 $a_input['plugin_fusioninventory_agents_id'] = $agent_id;
                 $a_input['uniqid'] = $uniqid;
                 $a_input['execution_id'] = $task->fields['execution_id'];
                 $alternate = 0;
                 for ($d = 0; $d < ceil($count_device / count($a_agentList)); $d++) {
                     if (count($a_NetworkEquipment) + count($a_Printer) > 0) {
                         $getdevice = "NetworkEquipment";
                         if ($alternate == "1") {
                             $getdevice = "Printer";
                             $alternate = 0;
                         } else {
                             $getdevice = "NetworkEquipment";
                             $alternate++;
                         }
                         if (count($a_NetworkEquipment) == '0') {
                             $getdevice = "Printer";
                         } else {
                             if (count($a_Printer) == '0') {
                                 $getdevice = "NetworkEquipment";
                             }
                         }
                         $a_input['itemtype'] = $getdevice;
                         switch ($getdevice) {
                             case 'NetworkEquipment':
                                 $a_input['items_id'] = array_pop($a_NetworkEquipment);
                                 $a_input['specificity'] = exportArrayToDB($a_specificity['DEVICE']['NetworkEquipment' . $a_input['items_id']]);
                                 break;
                             case 'Printer':
                                 $a_input['items_id'] = array_pop($a_Printer);
                                 $a_input['specificity'] = exportArrayToDB($a_specificity['DEVICE']['Printer' . $a_input['items_id']]);
                                 break;
                         }
                         $Taskjobstates_id = $pfTaskjobstate->add($a_input);
                         //Add log of taskjob
                         $a_input['plugin_fusioninventory_taskjobstates_id'] = $Taskjobstates_id;
                         $a_input['state'] = 7;
                         $a_input['date'] = date("Y-m-d H:i:s");
                         $pfTaskjoblog->add($a_input);
                         unset($a_input['state']);
                         if ($communication == "push") {
                             $_SESSION['glpi_plugin_fusioninventory']['agents'][$agent_id] = 1;
                         }
                     }
                 }
             }
             $input_taskjob = array();
             $input_taskjob['id'] = $pfTaskjob->fields['id'];
             $input_taskjob['status'] = 1;
             $pfTaskjob->update($input_taskjob);
         }
     }
     return $uniqid;
 }
 /**
  * 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);
                                 }
                             }
                         }
                     }
                 }
             }
         }
     }
 }
 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 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']);
     }
 }