/**
  * 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);
                                 }
                             }
                         }
                     }
                 }
             }
         }
     }
 }
 /**
  * @test
  */
 public function prepareTaskDisabled()
 {
     global $DB;
     $DB->connect();
     $pfTask = new PluginFusioninventoryTask();
     $pfTask->update(array('id' => 1, 'is_active' => 0));
     PluginFusioninventoryTask::cronTaskscheduler();
     $data = $pfTask->getJoblogs(array(1));
     $ref = array();
     $this->assertEquals($ref, $data['agents'], 'Task inactive, so no agent prepared');
     $ref_prepared = array();
     $this->assertEquals($ref_prepared, $data['tasks']);
 }
         $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"] = '';
         }
         $a_definition = array();
         $a_definition[]['PluginFusioninventoryIPRange'] = $_POST['iprange'];
         $input_taskjob['definition'] = exportArrayToDB($a_definition);
         $input_task["communication"] = $_POST['communication'];
         $task->update($input_task);
         $taskjob->update($input_taskjob);
     } else {
         Session::checkRight('plugin_fusioninventory_iprange', UPDATE);
         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->update($_POST);
         }
     }
     Html::back();
 } else {
     if (isset($_POST["delete"])) {
         if (isset($_POST['communication'])) {
 /**
  * re initialize all taskjob of a taskjob
  *
  * @param $tasks_id integer id of the task
  *
  * @return bool TRUE if all taskjob are ready (so finished from old runnning job)
  *
  **/
 function reinitializeTaskjobs($tasks_id, $disableTimeVerification = 0)
 {
     global $DB;
     $pfTask = new PluginFusioninventoryTask();
     $pfTaskjob = new PluginFusioninventoryTaskjob();
     $pfTaskjobstate = new PluginFusioninventoryTaskjobstate();
     $pfTaskjoblog = new PluginFusioninventoryTaskjoblog();
     $query = "SELECT *, UNIX_TIMESTAMP(datetime_start) as date_scheduled_timestamp\n            FROM `" . $pfTask->getTable() . "`\n         WHERE `id`='" . $tasks_id . "'\n         LIMIT 1";
     $result = $DB->query($query);
     $data = $DB->fetch_assoc($result);
     $period = $pfTaskjob->periodicityToTimestamp($data['periodicity_type'], $data['periodicity_count']);
     // Calculate next execution from last
     $queryJob = "SELECT * FROM `" . $pfTaskjob->getTable() . "`\n         WHERE `plugin_fusioninventory_tasks_id`='" . $tasks_id . "'\n         ORDER BY `id` DESC";
     $resultJob = $DB->query($queryJob);
     $nb_taskjobs = $DB->numrows($resultJob);
     // get only with execution_id (same +1) as task
     $queryJob = "SELECT * FROM `" . $pfTaskjob->getTable() . "`\n         WHERE `plugin_fusioninventory_tasks_id`='" . $tasks_id . "'\n            AND `execution_id`='" . ($data['execution_id'] + 1) . "'\n         ORDER BY `id` DESC";
     $finished = 2;
     $resultJob = $DB->query($queryJob);
     $nb_finished = 0;
     while ($dataJob = $DB->fetch_array($resultJob)) {
         $a_taskjobstateuniqs = $pfTaskjobstate->find("`plugin_fusioninventory_taskjobs_id`='" . $dataJob['id'] . "'", 'id DESC', 1);
         $a_taskjobstateuniq = current($a_taskjobstateuniqs);
         $a_taskjobstate = $pfTaskjobstate->find("`plugin_fusioninventory_taskjobs_id`='" . $dataJob['id'] . "'\n                              AND `uniqid`='" . $a_taskjobstateuniq['uniqid'] . "'");
         $taskjobstatefinished = 0;
         foreach ($a_taskjobstate as $statedata) {
             $a_joblog = $pfTaskjoblog->find("`plugin_fusioninventory_taskjobstates_id`='" . $statedata['id'] . "'\n                              AND (`state`='2' OR `state`='4' OR `state`='5')");
             if (count($a_joblog) > 0) {
                 $taskjobstatefinished++;
             }
         }
         if (count($a_taskjobstate) == $taskjobstatefinished and count($a_taskjobstate) > 0) {
             if ($finished == '2') {
                 $finished = 1;
             }
             $nb_finished++;
         } else {
             $finished = 0;
         }
     }
     if ($nb_finished != $nb_taskjobs) {
         if ($disableTimeVerification == '1') {
             // Forcerun
             $queryJob2 = "SELECT * FROM `" . $pfTaskjob->getTable() . "`\n            WHERE `plugin_fusioninventory_tasks_id`='" . $tasks_id . "'\n               AND `execution_id`='" . $data['execution_id'] . "'\n            ORDER BY `id` DESC";
             $resultJob2 = $DB->query($queryJob2);
             if ($DB->numrows($resultJob2) == $nb_taskjobs) {
                 $finished = 1;
                 return TRUE;
             } else {
                 $finished = 0;
             }
         } else {
             $finished = 0;
         }
     }
     // if all jobs are finished, we calculate if we reinitialize all jobs
     if ($finished == "1") {
         $exe = $data['execution_id'];
         unset($data['execution_id']);
         $queryUpdate = "UPDATE `" . $pfTaskjob->getTable() . "`\n            SET `status`='0'\n            WHERE `plugin_fusioninventory_tasks_id`='" . $data['id'] . "'";
         $DB->query($queryUpdate);
         if ($period != '0') {
             if (is_null($data['date_scheduled_timestamp'])) {
                 $data['date_scheduled_timestamp'] = date('U');
             }
             if ($data['date_scheduled_timestamp'] + $period <= date('U') and $period = !'0') {
                 $periodtotal = $period;
                 for ($i = 2; $data['date_scheduled_timestamp'] + $periodtotal <= date('U'); $i++) {
                     $periodtotal = $period * $i;
                 }
                 $data['datetime_start'] = date("Y-m-d H:i:s", $data['date_scheduled_timestamp'] + $periodtotal);
             } else {
                 if ($data['date_scheduled_timestamp'] > date('U')) {
                     // Don't update date next execution
                 } else {
                     $data['datetime_start'] = date("Y-m-d H:i:s", $data['date_scheduled_timestamp'] + $period);
                 }
             }
         }
         $data['execution_id'] = $exe + 1;
         unset($data['comment']);
         $pfTask->update($data);
         return TRUE;
     } else {
         return FALSE;
     }
 }