diff --git a/lib/classes/module/console/schedulerStart.class.php b/lib/classes/module/console/schedulerStart.class.php index 432036e060..aa5d9f8a31 100644 --- a/lib/classes/module/console/schedulerStart.class.php +++ b/lib/classes/module/console/schedulerStart.class.php @@ -53,7 +53,7 @@ class module_console_schedulerStart extends Command return $this; } - public function execute(InputInterface $zinput, OutputInterface $output) + public function execute(InputInterface $input, OutputInterface $output) { if ( ! setup::is_installed()) { $output->writeln('Phraseanet is not set up'); @@ -65,8 +65,9 @@ class module_console_schedulerStart extends Command try { $scheduler = new task_Scheduler(); - $scheduler->run($zinput, $output); + $scheduler->run($input, $output); } catch (\Exception $e) { + return $e->getCode(); } } diff --git a/lib/classes/module/console/schedulerStop.class.php b/lib/classes/module/console/schedulerStop.class.php index ec19345640..b721a276dc 100644 --- a/lib/classes/module/console/schedulerStop.class.php +++ b/lib/classes/module/console/schedulerStop.class.php @@ -47,10 +47,11 @@ class module_console_schedulerStop extends Command try { $appbox = appbox::get_instance(\bootstrap::getCore()); $task_manager = new task_manager($appbox); - $task_manager->set_sched_status(task_manager::STATUS_SCHED_TOSTOP); + $task_manager->setSchedulerState(task_manager::STATUS_SCHED_TOSTOP); return 0; } catch (\Exception $e) { + return 1; } diff --git a/lib/classes/module/console/tasklist.class.php b/lib/classes/module/console/tasklist.class.php index 806eac5c5b..f9922a9809 100644 --- a/lib/classes/module/console/tasklist.class.php +++ b/lib/classes/module/console/tasklist.class.php @@ -48,14 +48,14 @@ class module_console_tasklist extends Command try { $appbox = appbox::get_instance(\bootstrap::getCore()); $task_manager = new task_manager($appbox); - $tasks = $task_manager->get_tasks(); + $tasks = $task_manager->getTasks(); if (count($tasks) === 0) { $output->writeln('No tasks on your install !'); } foreach ($tasks as $task) { - $this->print_task($task, $output); + $this->printTask($task, $output); } return 0; @@ -64,9 +64,9 @@ class module_console_tasklist extends Command } } - protected function print_task(task_abstract $task, OutputInterface &$output) + protected function printTask(task_abstract $task, OutputInterface &$output) { - $message = $task->get_task_id() . "\t" . ($task->get_status() ) . "\t" . $task->get_title(); + $message = $task->getID() . "\t" . ($task->getState() ) . "\t" . $task->getTitle(); $output->writeln($message); return $this; diff --git a/lib/classes/module/console/taskrun.class.php b/lib/classes/module/console/taskrun.class.php index 716510cca7..4d6c9de373 100755 --- a/lib/classes/module/console/taskrun.class.php +++ b/lib/classes/module/console/taskrun.class.php @@ -61,7 +61,7 @@ class module_console_taskrun extends Command if ($this->task) { $this->task->log(sprintf("signal %s received", $signo)); if ($signo == SIGTERM) - $this->task->set_running(false); + $this->task->setRunning(false); } } @@ -78,11 +78,10 @@ class module_console_taskrun extends Command $appbox = \appbox::get_instance(\bootstrap::getCore()); $task_manager = new task_manager($appbox); - $this->task = $task_manager->get_task($task_id); + $this->task = $task_manager->getTask($task_id); if ($input->getOption('runner') === task_abstract::RUNNER_MANUAL) { - $schedStatus = $task_manager->get_scheduler_state(); -// printf("%s (%d) schedStatus=%s \n", __FILE__, __LINE__, var_export($schedStatus, true)); + $schedStatus = $task_manager->getSchedulerState(); if ($schedStatus && $schedStatus['status'] == 'running' && $schedStatus['pid']) $this->shedulerPID = $schedStatus['pid']; @@ -90,7 +89,7 @@ class module_console_taskrun extends Command } else { $runner = task_abstract::RUNNER_SCHEDULER; - $schedStatus = $task_manager->get_scheduler_state(); + $schedStatus = $task_manager->getSchedulerState(); if ($schedStatus && $schedStatus['status'] == 'running' && $schedStatus['pid']) $this->shedulerPID = $schedStatus['pid']; } @@ -102,7 +101,6 @@ class module_console_taskrun extends Command try { $this->task->run($runner, $input, $output); -// $this->task->log(sprintf("%s [%d] taskrun : returned from 'run()', get_status()=%s \n", __FILE__, __LINE__, $this->task->get_status())); } catch (Exception $e) { $this->task->log(sprintf("taskrun : exception from 'run()', %s \n", $e->getMessage())); return($e->getCode()); @@ -122,13 +120,12 @@ class module_console_taskrun extends Command } if (time() - $start > 0) { -// printf("%s (%d) : tick\n", __FILE__, __LINE__); if ($this->shedulerPID) { if ( ! posix_kill($this->shedulerPID, 0)) { if (method_exists($this->task, 'signal')) $this->task->signal('SIGNAL_SCHEDULER_DIED'); else - $this->task->set_status(task_abstract::STATUS_TOSTOP); + $this->task->setState(task_abstract::STATUS_TOSTOP); } diff --git a/lib/classes/task/Scheduler.class.php b/lib/classes/task/Scheduler.class.php index ac34797780..190da1cfc6 100755 --- a/lib/classes/task/Scheduler.class.php +++ b/lib/classes/task/Scheduler.class.php @@ -127,14 +127,14 @@ class task_Scheduler $task_manager = new task_manager($appbox); // set every 'auto-start' task to start - foreach ($task_manager->get_tasks() as $task) { - if ($task->is_active()) { - $tid = $task->get_task_id(); + foreach ($task_manager->getTasks() as $task) { + if ($task->isActive()) { + $tid = $task->getID(); - if ( ! $task->get_pid()) { + if ( ! $task->getPID()) { /* @var $task task_abstract */ - $task->reset_crash_counter(); - $task->set_status(task_abstract::STATUS_TOSTART); + $task->resetCrashCounter(); + $task->setState(task_abstract::STATUS_TOSTART); } } } @@ -224,13 +224,13 @@ class task_Scheduler foreach ($taskPoll as $tkey => $task) $taskPoll[$tkey]["todel"] = true; - foreach ($task_manager->get_tasks(true) as $task) { - $tkey = "t_" . $task->get_task_id(); - $status = $task->get_status(); + foreach ($task_manager->getTasks(true) as $task) { + $tkey = "t_" . $task->getID(); + $status = $task->getState(); - logs::rotate($logdir . "task_t_" . $task->get_task_id() . ".log"); - logs::rotate($logdir . "task_o_" . $task->get_task_id() . ".log"); - logs::rotate($logdir . "task_e_" . $task->get_task_id() . ".log"); + logs::rotate($logdir . "task_t_" . $task->getID() . ".log"); + logs::rotate($logdir . "task_o_" . $task->getID() . ".log"); + logs::rotate($logdir . "task_e_" . $task->getID() . ".log"); if ( ! isset($taskPoll[$tkey])) { // the task is not in the poll, add it @@ -238,7 +238,7 @@ class task_Scheduler switch ($system) { case "WINDOWS": $cmd = $phpcli; - $args = array('-f', $registry->get('GV_RootPath') . 'bin/console', '--', '-q', 'task:run', $task->get_task_id(), '--runner=scheduler'); + $args = array('-f', $registry->get('GV_RootPath') . 'bin/console', '--', '-q', 'task:run', $task->getID(), '--runner=scheduler'); if ($this->input && ($this->input->getOption('notasklog'))) $args[] = 'notasklog'; break; @@ -246,7 +246,7 @@ class task_Scheduler case "DARWIN": case "LINUX": $cmd = $phpcli; - $args = array('-f', $registry->get('GV_RootPath') . 'bin/console', '--', '-q', 'task:run', $task->get_task_id(), '--runner=scheduler'); + $args = array('-f', $registry->get('GV_RootPath') . 'bin/console', '--', '-q', 'task:run', $task->getID(), '--runner=scheduler'); if ($this->input && ($this->input->getOption('notasklog'))) $args[] = 'notasklog'; break; @@ -268,7 +268,7 @@ class task_Scheduler $this->log( sprintf( "new Task %s, status=%s" - , $taskPoll[$tkey]["task"]->get_task_id() + , $taskPoll[$tkey]["task"]->getID() , $status ) ); @@ -278,7 +278,7 @@ class task_Scheduler $this->log( sprintf( "Task %s, oldstatus=%s, newstatus=%s" - , $taskPoll[$tkey]["task"]->get_task_id() + , $taskPoll[$tkey]["task"]->getID() , $taskPoll[$tkey]["current_status"] , $status ) @@ -298,7 +298,7 @@ class task_Scheduler // remove not-existing task from poll foreach ($taskPoll as $tkey => $task) { if ($task["todel"]) { - $this->log(sprintf("Task %s deleted", $taskPoll[$tkey]["task"]->get_task_id())); + $this->log(sprintf("Task %s deleted", $taskPoll[$tkey]["task"]->getID())); unset($taskPoll[$tkey]); } } @@ -307,14 +307,14 @@ class task_Scheduler $runningtask = 0; foreach ($taskPoll as $tkey => $tv) { - $status = $tv['task']->get_status(); + $status = $tv['task']->getState(); switch ($status) { default: $this->log(sprintf('Unknow status `%s`', $status)); break; case task_abstract::STATUS_TORESTART: - if ( ! $taskPoll[$tkey]['task']->get_pid()) { + if ( ! $taskPoll[$tkey]['task']->getPID()) { if ($this->method == self::METHOD_PROC_OPEN) { @fclose($taskPoll[$tkey]["pipes"][1]); @fclose($taskPoll[$tkey]["pipes"][2]); @@ -323,7 +323,7 @@ class task_Scheduler $taskPoll[$tkey]["process"] = null; } if ($schedstatus == 'started') { - $taskPoll[$tkey]["task"]->set_status(task_abstract::STATUS_TOSTART); + $taskPoll[$tkey]["task"]->setState(task_abstract::STATUS_TOSTART); } // trick to start the task immediatly : DON'T break if ending with 'tostart' // so it will continue with 'tostart' case ! @@ -340,8 +340,8 @@ class task_Scheduler if ($this->method == self::METHOD_PROC_OPEN) { if ( ! $taskPoll[$tkey]["process"]) { - $descriptors[1] = array('file', $logdir . "task_o_" . $taskPoll[$tkey]['task']->get_task_id() . ".log", 'a+'); - $descriptors[2] = array('file', $logdir . "task_e_" . $taskPoll[$tkey]['task']->get_task_id() . ".log", 'a+'); + $descriptors[1] = array('file', $logdir . "task_o_" . $taskPoll[$tkey]['task']->getID() . ".log", 'a+'); + $descriptors[2] = array('file', $logdir . "task_e_" . $taskPoll[$tkey]['task']->getID() . ".log", 'a+'); $taskPoll[$tkey]["process"] = proc_open( $taskPoll[$tkey]["cmd"] . ' ' . implode(' ', $taskPoll[$tkey]["args"]) @@ -356,18 +356,18 @@ class task_Scheduler sleep(2); // let the process lock and write it's pid } - if (is_resource($taskPoll[$tkey]["process"]) && $taskPoll[$tkey]['task']->get_pid() !== null) { + if (is_resource($taskPoll[$tkey]["process"]) && $taskPoll[$tkey]['task']->getPID() !== null) { $this->log( sprintf( "Task %s '%s' started (pid=%s)" - , $taskPoll[$tkey]['task']->get_task_id() + , $taskPoll[$tkey]['task']->getID() , $taskPoll[$tkey]["cmd"] . ' ' . implode(' ', $taskPoll[$tkey]["args"]) - , $taskPoll[$tkey]['task']->get_pid() + , $taskPoll[$tkey]['task']->getPID() ) ); $runningtask ++; } else { - $taskPoll[$tkey]["task"]->increment_crash_counter(); + $taskPoll[$tkey]["task"]->incrementCrashCounter(); @fclose($taskPoll[$tkey]["pipes"][1]); @fclose($taskPoll[$tkey]["pipes"][2]); @@ -377,16 +377,16 @@ class task_Scheduler $this->log( sprintf( "Task %s '%s' failed to start %d times" - , $taskPoll[$tkey]["task"]->get_task_id() + , $taskPoll[$tkey]["task"]->getID() , $taskPoll[$tkey]["cmd"] - , $taskPoll[$tkey]["task"]->get_crash_counter() + , $taskPoll[$tkey]["task"]->getCrashCounter() ) ); - if ($taskPoll[$tkey]["task"]->get_crash_counter() > 5) - $taskPoll[$tkey]["task"]->set_status(task_abstract::STATUS_STOPPED); + if ($taskPoll[$tkey]["task"]->getCrashCounter() > 5) + $taskPoll[$tkey]["task"]->setState(task_abstract::STATUS_STOPPED); else - $taskPoll[$tkey]["task"]->set_status(task_abstract::STATUS_TOSTART); + $taskPoll[$tkey]["task"]->setState(task_abstract::STATUS_TOSTART); } } } @@ -407,8 +407,8 @@ class task_Scheduler fclose(STDOUT); fclose(STDERR); $fdIN = fopen($nullfile, 'r'); - $fdOUT = fopen($logdir . "task_o_" . $taskPoll[$tkey]["task"]->get_task_id() . ".log", 'a+'); - $fdERR = fopen($logdir . "task_e_" . $taskPoll[$tkey]["task"]->get_task_id() . ".log", 'a+'); + $fdOUT = fopen($logdir . "task_o_" . $taskPoll[$tkey]["task"]->getID() . ".log", 'a+'); + $fdERR = fopen($logdir . "task_e_" . $taskPoll[$tkey]["task"]->getID() . ".log", 'a+'); $this->log(sprintf("exec('%s %s')", $taskPoll[$tkey]["cmd"], implode(' ', $taskPoll[$tkey]["args"]))); pcntl_exec($taskPoll[$tkey]["cmd"], $taskPoll[$tkey]["args"]); @@ -445,7 +445,7 @@ class task_Scheduler } } - if ( ! $crashed && ! $taskPoll[$tkey]['task']->get_pid()) { + if ( ! $crashed && ! $taskPoll[$tkey]['task']->getPID()) { // printf("=== %d ===\n", __LINE__); $crashed = true; } @@ -456,7 +456,7 @@ class task_Scheduler } else { // printf("=== %d ===\n", __LINE__); // crashed ! - $taskPoll[$tkey]["task"]->increment_crash_counter(); + $taskPoll[$tkey]["task"]->incrementCrashCounter(); if ($this->method == self::METHOD_PROC_OPEN) { @fclose($taskPoll[$tkey]["pipes"][1]); @@ -467,15 +467,15 @@ class task_Scheduler $this->log( sprintf( "Task %s crashed %d times" - , $taskPoll[$tkey]["task"]->get_task_id() - , $taskPoll[$tkey]["task"]->get_crash_counter() + , $taskPoll[$tkey]["task"]->getID() + , $taskPoll[$tkey]["task"]->getCrashCounter() ) ); - if ($taskPoll[$tkey]["task"]->get_crash_counter() > 5) - $taskPoll[$tkey]["task"]->set_status(task_abstract::STATUS_STOPPED); + if ($taskPoll[$tkey]["task"]->getCrashCounter() > 5) + $taskPoll[$tkey]["task"]->setState(task_abstract::STATUS_STOPPED); else - $taskPoll[$tkey]["task"]->set_status(task_abstract::STATUS_TOSTART); + $taskPoll[$tkey]["task"]->setState(task_abstract::STATUS_TOSTART); } break; @@ -484,7 +484,7 @@ class task_Scheduler if ($taskPoll[$tkey]["killat"] === NULL) $taskPoll[$tkey]["killat"] = time() + self::TASKDELAYTOQUIT; - $pid = $taskPoll[$tkey]['task']->get_pid(); + $pid = $taskPoll[$tkey]['task']->getPID(); if ($pid) { // send ctrl-c to tell the task to CLEAN quit // (just in case the task doesn't pool his status 'tostop' fast enough) @@ -494,7 +494,7 @@ class task_Scheduler $this->log( sprintf( "SIGTERM sent to task %s (pid=%s)" - , $taskPoll[$tkey]["task"]->get_task_id() + , $taskPoll[$tkey]["task"]->getID() , $pid ) ); @@ -511,7 +511,7 @@ class task_Scheduler $this->log( sprintf( "proc_terminate(...) done on task %s (pid=%s)" - , $taskPoll[$tkey]["task"]->get_task_id() + , $taskPoll[$tkey]["task"]->getID() , $pid ) ); @@ -520,23 +520,23 @@ class task_Scheduler $this->log( sprintf( "SIGKILL sent to task %s (pid=%s)" - , $taskPoll[$tkey]["task"]->get_task_id() + , $taskPoll[$tkey]["task"]->getID() , $pid ) ); } /* - unlink($lockdir . 'task_' . $taskPoll[$tkey]['task']->get_task_id() . '.lock'); + unlink($lockdir . 'task_' . $taskPoll[$tkey]['task']->getID() . '.lock'); - $taskPoll[$tkey]["task"]->increment_crash_counter(); + $taskPoll[$tkey]["task"]->incrementCrashCounter(); // $taskPoll[$tkey]["task"]->set_pid(null); - $taskPoll[$tkey]["task"]->set_status(task_abstract::STATUS_STOPPED); + $taskPoll[$tkey]["task"]->setState(task_abstract::STATUS_STOPPED); */ } else { $this->log( sprintf( "waiting task %s to quit (kill in %d seconds)" - , $taskPoll[$tkey]["task"]->get_task_id() + , $taskPoll[$tkey]["task"]->getID() , $dt ) ); @@ -546,10 +546,10 @@ class task_Scheduler $this->log( sprintf( "task %s has quit" - , $taskPoll[$tkey]["task"]->get_task_id() + , $taskPoll[$tkey]["task"]->getID() ) ); - $taskPoll[$tkey]["task"]->set_status(task_abstract::STATUS_STOPPED); + $taskPoll[$tkey]["task"]->setState(task_abstract::STATUS_STOPPED); } break; diff --git a/lib/classes/task/abstract.class.php b/lib/classes/task/abstract.class.php index d6baae19ac..943f0a6aab 100755 --- a/lib/classes/task/abstract.class.php +++ b/lib/classes/task/abstract.class.php @@ -101,8 +101,17 @@ abstract class task_abstract protected $completed_percentage; + protected $period = 60; - public function get_status() + protected $taskid = NULL; + + protected $system = ''; // "DARWIN", "WINDOWS" , "LINUX"... + + protected $argt = array( + "--help" => array("set" => false, "values" => array(), "usage" => " (no help available)") + ); + + public function getState() { $conn = connection::getPDOConnection(); $sql = 'SELECT status FROM task2 WHERE task_id = :taskid LIMIT 1'; @@ -130,7 +139,7 @@ abstract class task_abstract return false; } - public function set_status($status) + public function setState($status) { $av_status = array( self::STATUS_STARTED @@ -149,19 +158,19 @@ abstract class task_abstract $sql = 'UPDATE task2 SET status = :status WHERE task_id = :taskid'; $stmt = $conn->prepare($sql); - $stmt->execute(array(':status' => $status, ':taskid' => $this->get_task_id())); + $stmt->execute(array(':status' => $status, ':taskid' => $this->getID())); $stmt->closeCursor(); - $this->log(sprintf("task %d <- %s", $this->get_task_id(), $status)); + $this->log(sprintf("task %d <- %s", $this->getID(), $status)); } // 'active' means 'auto-start when scheduler starts' - public function set_active($boolean) + public function setActive($boolean) { $conn = connection::getPDOConnection(); $sql = 'UPDATE task2 SET active = :active WHERE task_id = :taskid'; $stmt = $conn->prepare($sql); - $stmt->execute(array(':active' => ($boolean ? '1' : '0'), ':taskid' => $this->get_task_id())); + $stmt->execute(array(':active' => ($boolean ? '1' : '0'), ':taskid' => $this->getID())); $stmt->closeCursor(); $this->active = ! ! $boolean; @@ -169,14 +178,14 @@ abstract class task_abstract return $this; } - public function set_title($title) + public function setTitle($title) { $title = strip_tags($title); $conn = connection::getPDOConnection(); $sql = 'UPDATE task2 SET name = :title WHERE task_id = :taskid'; $stmt = $conn->prepare($sql); - $stmt->execute(array(':title' => $title, ':taskid' => $this->get_task_id())); + $stmt->execute(array(':title' => $title, ':taskid' => $this->getID())); $stmt->closeCursor(); $this->title = $title; @@ -184,29 +193,27 @@ abstract class task_abstract return $this; } - public function set_settings($settings) + public function setSettings($settings) { $conn = connection::getPDOConnection(); $sql = 'UPDATE task2 SET settings = :settings WHERE task_id = :taskid'; $stmt = $conn->prepare($sql); - $stmt->execute(array(':settings' => $settings, ':taskid' => $this->get_task_id())); + $stmt->execute(array(':settings' => $settings, ':taskid' => $this->getID())); $stmt->closeCursor(); $this->settings = $settings; - $this->load_settings(simplexml_load_string($settings)); - - return $this; + $this->loadSettings(simplexml_load_string($settings)); } - public function reset_crash_counter() + public function resetCrashCounter() { $conn = connection::getPDOConnection(); $sql = 'UPDATE task2 SET crashed = 0 WHERE task_id = :taskid'; $stmt = $conn->prepare($sql); - $stmt->execute(array(':taskid' => $this->get_task_id())); + $stmt->execute(array(':taskid' => $this->getID())); $stmt->closeCursor(); $this->crash_counter = 0; @@ -214,47 +221,38 @@ abstract class task_abstract return $this; } - public function get_crash_counter() + public function getCrashCounter() { return $this->crash_counter; } - public function increment_crash_counter() + public function incrementCrashCounter() { $conn = connection::getPDOConnection(); $sql = 'UPDATE task2 SET crashed = crashed + 1 WHERE task_id = :taskid'; $stmt = $conn->prepare($sql); - $stmt->execute(array(':taskid' => $this->get_task_id())); + $stmt->execute(array(':taskid' => $this->getID())); $stmt->closeCursor(); return $this->crash_counter ++; } - public function get_settings() + public function getSettings() { return $this->settings; } // 'active' means 'auto-start when scheduler starts' - public function is_active() + public function isActive() { return $this->active; } - public function get_completed_percentage() + public function getCompletedPercentage() { return $this->completed_percentage; } - protected $period = 60; - - protected $taskid = NULL; - - protected $system = ''; // "DARWIN", "WINDOWS" , "LINUX"... - - protected $argt = array( - "--help" => array("set" => false, "values" => array(), "usage" => " (no help available)") - ); abstract public function getName(); @@ -297,7 +295,7 @@ abstract class task_abstract $sql = 'SELECT crashed, pid, status, active, settings, name, completed, runner FROM task2 WHERE task_id = :taskid LIMIT 1'; $stmt = $conn->prepare($sql); - $stmt->execute(array(':taskid' => $this->get_task_id())); + $stmt->execute(array(':taskid' => $this->getID())); $row = $stmt->fetch(PDO::FETCH_ASSOC); $stmt->closeCursor(); if ( ! $row) @@ -308,17 +306,15 @@ abstract class task_abstract $this->settings = $row['settings']; $this->runner = $row['runner']; $this->completed_percentage = (int) $row['completed']; - $this->load_settings(simplexml_load_string($row['settings'])); - - return $this; + $this->loadSettings(simplexml_load_string($row['settings'])); } - public function get_runner() + public function getRunner() { return $this->runner; } - public function set_runner($runner) + public function setRunner($runner) { $this->runner = $runner; @@ -326,55 +322,42 @@ abstract class task_abstract $sql = 'UPDATE task2 SET runner = :runner WHERE task_id = :taskid'; $params = array( - ':taskid' => $this->get_task_id() + ':taskid' => $this->getID() , ':runner' => $this->runner ); $stmt = $conn->prepare($sql); $stmt->execute($params); $stmt->closeCursor(); - - return $this; } - public function get_title() + public function getTitle() { return $this->title; } public function delete() { - if ( ! $this->get_pid()) { // do not delete a running task + if ( ! $this->getPID()) { // do not delete a running task $conn = connection::getPDOConnection(); $registry = registry::get_instance(); $sql = "DELETE FROM task2 WHERE task_id = :task_id"; $stmt = $conn->prepare($sql); - $stmt->execute(array(':task_id' => $this->get_task_id())); + $stmt->execute(array(':task_id' => $this->getID())); $stmt->closeCursor(); - $lock_file = $registry->get('GV_RootPath') . 'tmp/locks/task_' . $this->get_task_id() . '.lock'; + $lock_file = $registry->get('GV_RootPath') . 'tmp/locks/task_' . $this->getID() . '.lock'; @unlink($lock_file); } } - protected function check_records_done() - { - if ($this->records_done >= (int) ($this->maxrecs)) { - $this->current_state = self::STATE_MAXRECSDONE; - } - - return $this; - } - - public function set_last_exec_time() + public function setLastExecTime() { $conn = connection::getPDOConnection(); $sql = 'UPDATE task2 SET last_exec_time=NOW() WHERE task_id = :taskid'; $stmt = $conn->prepare($sql); - $stmt->execute(array(':taskid' => $this->get_task_id())); + $stmt->execute(array(':taskid' => $this->getID())); $stmt->closeCursor(); - - return $this; } /** @@ -393,10 +376,10 @@ abstract class task_abstract return isset($row['last_exec_time']) ? $row['last_exec_time'] : ''; } - public function get_pid() + public function getPID() { $pid = NULL; - $taskid = $this->get_task_id(); + $taskid = $this->getID(); $registry = registry::get_instance(); system_file::mkdir($lockdir = $registry->get('GV_RootPath') . 'tmp/locks/'); @@ -414,7 +397,7 @@ abstract class task_abstract return $pid; } - public function set_running($stat) + public function setRunning($stat) { $this->running = $stat; } @@ -429,9 +412,9 @@ abstract class task_abstract // $conn->close(); // unset($conn); for ($t = $this->period - $when_started; $this->running && $t > 0; $t -- ) { // DON'T do sleep($this->period - $when_started) because it prevents ticks ! - $s = $this->get_status(); + $s = $this->getState(); if ($s == self::STATUS_TOSTOP) { - $this->set_status(self::STATUS_STOPPED); + $this->setState(self::STATUS_STOPPED); $this->running = FALSE; } else { sleep(1); @@ -446,7 +429,7 @@ abstract class task_abstract $this->input = $input; $this->output = $output; - $taskid = $this->get_task_id(); + $taskid = $this->getID(); $conn = connection::getPDOConnection(); $registry = registry::get_instance(); @@ -472,8 +455,8 @@ abstract class task_abstract flock($tasklock, LOCK_UN); flock($tasklock, LOCK_SH); - $this->set_runner($runner); - $this->set_status(self::STATUS_STARTED); + $this->setRunner($runner); + $this->setState(self::STATUS_STARTED); // run the real code of the task -into the task's class- (may throw an exception) $exception = NULL; @@ -489,12 +472,12 @@ abstract class task_abstract fclose($tasklock); @unlink($lockfile); - switch ($this->get_status()) { + switch ($this->getState()) { case self::STATUS_TODELETE: $this->delete(); break; case self::STATUS_TOSTOP: - $this->set_status(self::STATUS_STOPPED); + $this->setState(self::STATUS_STOPPED); break; } @@ -505,7 +488,7 @@ abstract class task_abstract abstract protected function run2(); - protected function load_settings(SimpleXMLElement $sx_task_settings) + protected function loadSettings(SimpleXMLElement $sx_task_settings) { $this->period = (int) $sx_task_settings->period; if ($this->period <= 0 || $this->period >= 60 * 60) @@ -520,21 +503,17 @@ abstract class task_abstract $this->record_buffer_size = (int) $sx_task_settings->flush; if ($sx_task_settings->flush < 1 || $sx_task_settings->flush > 100) $this->record_buffer_size = 10; - - return $this; } - protected function increment_loops() + protected function incrementLoops() { - if ($this->get_runner() == self::RUNNER_SCHEDULER && ++ $this->loop >= $this->maxloops) { + if ($this->getRunner() == self::RUNNER_SCHEDULER && ++ $this->loop >= $this->maxloops) { $this->log(sprintf(('%d loops done, restarting'), $this->loop)); - $this->set_status(self::STATUS_TORESTART); + $this->setState(self::STATUS_TORESTART); // $this->return_xxxvalue = self::RETURNSTATUS_TORESTART; $this->running = false; } - - return $this; } function traceRam($msg='') @@ -630,12 +609,8 @@ abstract class task_abstract return($t); } - public function get_argt() - { - return $this->argt; - } - public function get_task_id() + public function getID() { return $this->taskid; } @@ -648,7 +623,7 @@ abstract class task_abstract $conn = connection::getPDOConnection(); $sql = 'UPDATE task2 SET completed = :p WHERE task_id = :taskid'; $stmt = $conn->prepare($sql); - $stmt->execute(array(':p' => $p, ':taskid' => $this->get_task_id())); + $stmt->execute(array(':p' => $p, ':taskid' => $this->getID())); $stmt->closeCursor(); $this->completed_percentage = $p; } catch (Exception $e) { diff --git a/lib/classes/task/appboxAbstract.class.php b/lib/classes/task/appboxAbstract.class.php index ba714cdb1f..011f8529bf 100755 --- a/lib/classes/task/appboxAbstract.class.php +++ b/lib/classes/task/appboxAbstract.class.php @@ -17,23 +17,21 @@ abstract class task_appboxAbstract extends task_abstract { - abstract protected function retrieve_content(appbox $appbox); + abstract protected function retrieveContent(appbox $appbox); - abstract protected function process_one_content(appbox $appbox, Array $row); + abstract protected function processOneContent(appbox $appbox, Array $row); - abstract protected function post_process_one_content(appbox $appbox, Array $row); + abstract protected function postProcessOneContent(appbox $appbox, Array $row); protected function run2() { -// printf("%s(%d)\n", __FILE__, __LINE__); $this->running = TRUE; while ($this->running) { -// printf("%s(%d)\n", __FILE__, __LINE__); try { $conn = connection::getPDOConnection(); } catch (Exception $e) { $this->log($e->getMessage()); - if ($this->get_runner() == self::RUNNER_SCHEDULER) { + if ($this->getRunner() == self::RUNNER_SCHEDULER) { $this->log(("Warning : abox connection lost, restarting in 10 min.")); for ($t = 60 * 10; $this->running && $t; $t -- ) // DON'T do sleep(600) because it prevents ticks ! @@ -45,60 +43,57 @@ abstract class task_appboxAbstract extends task_abstract // runner = manual : can't restart so simply quit } $this->running = FALSE; + return; } -// printf("%s(%d)\n", __FILE__, __LINE__); - $this->set_last_exec_time(); + $this->setLastExecTime(); try { $sql = 'SELECT task2.* FROM task2 WHERE task_id = :taskid LIMIT 1'; $stmt = $conn->prepare($sql); - $stmt->execute(array(':taskid' => $this->get_task_id())); + $stmt->execute(array(':taskid' => $this->getID())); $row = $stmt->fetch(PDO::FETCH_ASSOC); $stmt->closeCursor(); $this->records_done = 0; $duration = time(); } catch (Exception $e) { -// printf("%s(%d)\n", __FILE__, __LINE__); // failed sql, simply return $this->running = FALSE; + return; } -// printf("%s(%d)\n", __FILE__, __LINE__); + if ($row) { if ( ! $this->running) break; $appbox = appbox::get_instance(\bootstrap::getCore()); try { - $this->load_settings(simplexml_load_string($row['settings'])); + $this->loadSettings(simplexml_load_string($row['settings'])); } catch (Exception $e) { $this->log($e->getMessage()); continue; } -// printf("%s(%d)\n", __FILE__, __LINE__); $process_ret = $this->process($appbox); -// printf("%s (%d) process_ret=%s \n", __FILE__, __LINE__, var_export($process_ret, true)); - // $this->check_current_xxxstate(); switch ($process_ret) { case self::STATE_MAXMEGSREACHED: case self::STATE_MAXRECSDONE: - if ($this->get_runner() == self::RUNNER_SCHEDULER) { - $this->set_status(self::STATUS_TORESTART); + if ($this->getRunner() == self::RUNNER_SCHEDULER) { + $this->setState(self::STATUS_TORESTART); $this->running = FALSE; } break; case self::STATUS_TOSTOP: - $this->set_status(self::STATUS_TOSTOP); + $this->setState(self::STATUS_TOSTOP); $this->running = FALSE; break; case self::STATUS_TODELETE: // formal 'suicidable' - $this->set_status(self::STATUS_TODELETE); + $this->setState(self::STATUS_TODELETE); $this->running = FALSE; break; @@ -107,7 +102,7 @@ abstract class task_appboxAbstract extends task_abstract } } // if(row) - $this->increment_loops(); + $this->incrementLoops(); $this->pause($duration); } // while running @@ -120,20 +115,17 @@ abstract class task_appboxAbstract extends task_abstract */ protected function process(appbox $appbox) { -// printf("%s(%d)\n", __FILE__, __LINE__); $ret = self::STATE_OK; $conn = $appbox->get_connection(); $tsub = array(); try { // get the records to process -// printf("%s(%d)\n", __FILE__, __LINE__); - $rs = $this->retrieve_content($appbox); + $rs = $this->retrieveContent($appbox); } catch (Exception $e) { $this->log('Error : ' . $e->getMessage()); $rs = array(); } -// printf("%s(%d)\n", __FILE__, __LINE__); $rowstodo = count($rs); $rowsdone = 0; @@ -144,7 +136,7 @@ abstract class task_appboxAbstract extends task_abstract foreach ($rs as $row) { try { // process one record - $this->process_one_content($appbox, $row); + $this->processOneContent($appbox, $row); } catch (Exception $e) { $this->log("Exception : " . $e->getMessage() . " " . basename($e->getFile()) . " " . $e->getLine()); } @@ -153,7 +145,7 @@ abstract class task_appboxAbstract extends task_abstract $this->setProgress($rowsdone, $rowstodo); // post-process - $this->post_process_one_content($appbox, $row); + $this->post_processOneContent($appbox, $row); // $this->check_memory_usage(); $current_memory = memory_get_usage(); @@ -163,7 +155,6 @@ abstract class task_appboxAbstract extends task_abstract $ret = self::STATE_MAXMEGSREACHED; } - // $this->check_records_done(); if ($this->records_done >= (int) ($this->maxrecs)) { $this->log(sprintf("Max records done (%s) reached (actual is %s)", $this->maxrecs, $this->records_done)); $this->running = FALSE; @@ -172,8 +163,7 @@ abstract class task_appboxAbstract extends task_abstract // $this->check_task_status(); try { - $status = $this->get_status(); -// printf("%s (%d) status=%s \n", __FILE__, __LINE__, var_export($status, true)); + $status = $this->getState(); if ($status == self::STATUS_TOSTOP) { $this->running = FALSE; $ret = self::STATUS_TOSTOP; @@ -196,7 +186,6 @@ abstract class task_appboxAbstract extends task_abstract $ret = self::STATE_MAXMEGSREACHED; } - // $this->check_records_done(); if ($this->records_done >= (int) ($this->maxrecs)) { $this->log(sprintf("Max records done (%s) reached (actual is %s)", $this->maxrecs, $this->records_done)); $this->running = FALSE; @@ -205,8 +194,7 @@ abstract class task_appboxAbstract extends task_abstract // $this->check_task_status(); try { - $status = $this->get_status(); -// printf("%s (%d) status=%s \n", __FILE__, __LINE__, var_export($status, true)); + $status = $this->getState(); if ($status == self::STATUS_TOSTOP) { $this->running = FALSE; $ret = self::STATUS_TOSTOP; diff --git a/lib/classes/task/databoxAbstract.class.php b/lib/classes/task/databoxAbstract.class.php index 75b7675eb4..ab9a270b37 100755 --- a/lib/classes/task/databoxAbstract.class.php +++ b/lib/classes/task/databoxAbstract.class.php @@ -22,13 +22,13 @@ abstract class task_databoxAbstract extends task_abstract protected $mono_sbas_id; - abstract protected function retrieve_sbas_content(databox $databox); + abstract protected function retrieveSbasContent(databox $databox); - abstract protected function process_one_content(databox $databox, Array $row); + abstract protected function processOneContent(databox $databox, Array $row); - abstract protected function flush_records_sbas(); + abstract protected function flushRecordsSbas(); - abstract protected function post_process_one_content(databox $databox, Array $row); + abstract protected function postProcessOneContent(databox $databox, Array $row); protected function run2() { @@ -39,7 +39,7 @@ abstract class task_databoxAbstract extends task_abstract $conn = connection::getPDOConnection(); } catch (Exception $e) { $this->log($e->getMessage()); - if ($this->get_runner() == self::RUNNER_SCHEDULER) { + if ($this->getRunner() == self::RUNNER_SCHEDULER) { $this->log(("Warning : abox connection lost, restarting in 10 min.")); for ($t = 60 * 10; $this->running && $t; $t -- ) // DON'T do sleep(600) because it prevents ticks ! @@ -54,16 +54,16 @@ abstract class task_databoxAbstract extends task_abstract return; } - $this->set_last_exec_time(); + $this->setLastExecTime(); try { if ($this->mono_sbas_id) { $sql = 'SELECT sbas_id, task2.* FROM sbas, task2 WHERE task_id=:taskid AND sbas_id=:sbas_id'; $stmt = $conn->prepare($sql); - $stmt->execute(array(':taskid' => $this->get_task_id(), ':sbas_id' => $this->mono_sbas_id)); + $stmt->execute(array(':taskid' => $this->getID(), ':sbas_id' => $this->mono_sbas_id)); } else { $sql = 'SELECT sbas_id, task2.* FROM sbas, task2 WHERE task_id = :taskid'; $stmt = $conn->prepare($sql); - $stmt->execute(array(':taskid' => $this->get_task_id())); + $stmt->execute(array(':taskid' => $this->getID())); } $rs = $stmt->fetchAll(PDO::FETCH_ASSOC); $stmt->closeCursor(); @@ -83,33 +83,33 @@ abstract class task_databoxAbstract extends task_abstract $this->log('This task works now on ' . phrasea::sbas_names($this->sbas_id)); try { - $this->load_settings(simplexml_load_string($row['settings'])); + $this->loadSettings(simplexml_load_string($row['settings'])); } catch (Exception $e) { $this->log($e->getMessage()); continue; } - $process_ret = $this->process_sbas(); + $process_ret = $this->processSbas(); // printf("%s (%d) process_ret=%s \n", __FILE__, __LINE__, var_export($process_ret, true)); // $this->check_current_xxxstate(); switch ($process_ret) { case self::STATE_MAXMEGSREACHED: case self::STATE_MAXRECSDONE: - if ($this->get_runner() == self::RUNNER_SCHEDULER) { - $this->set_status(self::STATUS_TORESTART); + if ($this->getRunner() == self::RUNNER_SCHEDULER) { + $this->setState(self::STATUS_TORESTART); $this->running = FALSE; } break; case self::STATUS_TOSTOP: - $this->set_status(self::STATUS_TOSTOP); + $this->setState(self::STATUS_TOSTOP); $this->running = FALSE; break; case self::STATUS_TODELETE: // formal 'suicidable' // DO NOT SUICIDE IN THE LOOP, may have to work on other sbas !!! - // $this->set_status(self::STATUS_TODELETE); + // $this->setState(self::STATUS_TODELETE); // $this->log('task will self delete'); // $this->running = FALSE; $task_must_delete = TRUE; @@ -119,15 +119,15 @@ abstract class task_databoxAbstract extends task_abstract break; } - $this->flush_records_sbas(); + $this->flushRecordsSbas(); } // foreach sbas - $this->increment_loops(); + $this->incrementLoops(); $this->pause($duration); } // while($this->running) if ($task_must_delete) { - $this->set_status(self::STATUS_TODELETE); + $this->setState(self::STATUS_TODELETE); $this->log('task will self delete'); } return; @@ -137,7 +137,7 @@ abstract class task_databoxAbstract extends task_abstract * * @return */ - protected function process_sbas() + protected function processSbas() { $ret = self::STATE_OK; @@ -148,7 +148,7 @@ abstract class task_databoxAbstract extends task_abstract // get the records to process $databox = databox::get_instance($this->sbas_id); $connbas = $databox->get_connection(); - $rs = $this->retrieve_sbas_content($databox); + $rs = $this->retrieveSbasContent($databox); } catch (Exception $e) { $this->log('Error : ' . $e->getMessage()); $rs = array(); @@ -163,7 +163,7 @@ abstract class task_databoxAbstract extends task_abstract foreach ($rs as $row) { try { // process one record - $this->process_one_content($databox, $row); + $this->processOneContent($databox, $row); } catch (Exception $e) { $this->log("Exception : " . $e->getMessage() . " " . basename($e->getFile()) . " " . $e->getLine()); } @@ -172,7 +172,7 @@ abstract class task_databoxAbstract extends task_abstract $this->setProgress($rowsdone, $rowstodo); // post-process - $this->post_process_one_content($databox, $row); + $this->postProcessOneContent($databox, $row); // $this->check_memory_usage(); $current_memory = memory_get_usage(); @@ -182,7 +182,6 @@ abstract class task_databoxAbstract extends task_abstract $ret = self::STATE_MAXMEGSREACHED; } - // $this->check_records_done(); if ($this->records_done >= (int) ($this->maxrecs)) { $this->log(sprintf("Max records done (%s) reached (actual is %s)", $this->maxrecs, $this->records_done)); $this->running = FALSE; @@ -191,7 +190,7 @@ abstract class task_databoxAbstract extends task_abstract // $this->check_task_status(); try { - $status = $this->get_status(); + $status = $this->getState(); // printf("%s (%d) status=%s \n", __FILE__, __LINE__, var_export($status, true)); if ($status == self::STATUS_TOSTOP) { $this->running = FALSE; @@ -219,7 +218,6 @@ abstract class task_databoxAbstract extends task_abstract $ret = self::STATE_MAXMEGSREACHED; } - // $this->check_records_done(); if ($this->records_done >= (int) ($this->maxrecs)) { $this->log(sprintf("Max records done (%s) reached (actual is %s)", $this->maxrecs, $this->records_done)); $this->running = FALSE; @@ -228,7 +226,7 @@ abstract class task_databoxAbstract extends task_abstract // $this->check_task_status(); try { - $status = $this->get_status(); + $status = $this->getState(); // printf("%s (%d) status=%s \n", __FILE__, __LINE__, var_export($status, true)); if ($status == self::STATUS_TOSTOP) { $this->running = FALSE; diff --git a/lib/classes/task/manager.class.php b/lib/classes/task/manager.class.php index f85459323a..a96f3c32e0 100755 --- a/lib/classes/task/manager.class.php +++ b/lib/classes/task/manager.class.php @@ -22,6 +22,7 @@ class task_manager const STATUS_SCHED_TOSTOP = 'tostop'; protected $appbox; + protected $tasks; public function __construct(appbox &$appbox) @@ -31,35 +32,7 @@ class task_manager return $this; } - public function old_get_tasks($refresh = false) - { - if ($this->tasks && ! $refresh) - return $this->tasks; - $sql = "SELECT task2.* FROM task2 ORDER BY task_id ASC"; - $stmt = $this->appbox->get_connection()->prepare($sql); - $stmt->execute(); - $rs = $stmt->fetchAll(PDO::FETCH_ASSOC); - $stmt->closeCursor(); - - $tasks = array(); - - foreach ($rs as $row) { - $classname = $row['class']; - if ( ! class_exists($classname)) - continue; - try { - $tasks[$row['task_id']] = new $classname($row['task_id']); - } catch (Exception $e) { - - } - } - - $this->tasks = $tasks; - - return $this->tasks; - } - - public function get_tasks($refresh = false) + public function getTasks($refresh = false) { if ($this->tasks && ! $refresh) return $this->tasks; @@ -109,12 +82,12 @@ class task_manager /** * - * @param $task_id + * @param int $task_id * @return task_abstract */ - public function get_task($task_id) + public function getTask($task_id) { - $tasks = $this->get_tasks(); + $tasks = $this->getTasks(); if ( ! isset($tasks[$task_id])) { throw new Exception_NotFound('Unknown task_id'); @@ -123,7 +96,7 @@ class task_manager return $tasks[$task_id]; } - public function set_sched_status($status) + public function setSchedulerState($status) { $av_status = array( self::STATUS_SCHED_STARTED @@ -143,7 +116,7 @@ class task_manager return $this; } - public function get_scheduler_state() + public function getSchedulerState() { $appbox = appbox::get_instance(\bootstrap::getCore()); diff --git a/lib/classes/task/period/apibridge.class.php b/lib/classes/task/period/apibridge.class.php index 4ca04646b7..caed91b74e 100755 --- a/lib/classes/task/period/apibridge.class.php +++ b/lib/classes/task/period/apibridge.class.php @@ -40,7 +40,7 @@ class task_period_apibridge extends task_appboxAbstract * @param appbox $appbox * @return Array */ - protected function retrieve_content(appbox $appbox) + protected function retrieveContent(appbox $appbox) { $status = array(Bridge_Element::STATUS_PENDING, Bridge_Element::STATUS_PROCESSING, Bridge_Element::STATUS_PROCESSING_SERVER); @@ -52,8 +52,8 @@ class task_period_apibridge extends task_appboxAbstract $n ++; } - $sql = 'SELECT id, account_id FROM bridge_elements - WHERE (status = ' . implode(' OR status = ', array_keys($params)) . ')'; + $sql = 'SELECT id, account_id FROM bridge_elements' + . ' WHERE (status = ' . implode(' OR status = ', array_keys($params)) . ')'; $stmt = $appbox->get_connection()->prepare($sql); $stmt->execute($params); @@ -69,7 +69,7 @@ class task_period_apibridge extends task_appboxAbstract * @param array $row * @return task_period_apibridge */ - protected function process_one_content(appbox $appbox, Array $row) + protected function processOneContent(appbox $appbox, Array $row) { try { $account = Bridge_Account::load_account($appbox, $row['account_id']); @@ -86,7 +86,7 @@ class task_period_apibridge extends task_appboxAbstract $params = array( ':status' => Bridge_Element::STATUS_ERROR - , ':id' => $row['id'] + , ':id' => $row['id'] ); $stmt = $appbox->get_connection()->prepare($sql); @@ -103,7 +103,7 @@ class task_period_apibridge extends task_appboxAbstract * @param array $row * @return task_period_apibridge */ - protected function post_process_one_content(appbox $appbox, Array $row) + protected function postProcessOneContent(appbox $appbox, Array $row) { return $this; } @@ -160,11 +160,11 @@ class task_period_apibridge extends task_appboxAbstract case Bridge_Element::STATUS_ERROR: $params = array( - 'usr_id' => $account->get_user()->get_id() - , 'reason' => $error_message + 'usr_id' => $account->get_user()->get_id() + , 'reason' => $error_message , 'account_id' => $account->get_id() - , 'sbas_id' => $element->get_record()->get_sbas_id() - , 'record_id' => $element->get_record()->get_record_id() + , 'sbas_id' => $element->get_record()->get_sbas_id() + , 'record_id' => $element->get_record()->get_record_id() ); $events_mngr = eventsmanager_broker::getInstance(appbox::get_instance(\bootstrap::getCore()), $Core); $events_mngr->trigger('__BRIDGE_UPLOAD_FAIL__', $params); diff --git a/lib/classes/task/period/archive.class.php b/lib/classes/task/period/archive.class.php index b6e8cf0802..496f764c63 100755 --- a/lib/classes/task/period/archive.class.php +++ b/lib/classes/task/period/archive.class.php @@ -363,7 +363,7 @@ class task_period_archive extends task_abstract $conn = connection::getPDOConnection(); } catch (Exception $e) { $this->log($e->getMessage()); - if ($this->get_runner() == self::RUNNER_SCHEDULER) { + if ($this->getRunner() == self::RUNNER_SCHEDULER) { $this->log(("Warning : abox connection lost, restarting in 10 min.")); for ($t = 60 * 10; $this->running && $t; $t -- ) // DON'T do sleep(600) because it prevents ticks ! @@ -381,28 +381,28 @@ class task_period_archive extends task_abstract $path_in = (string) ($this->sxTaskSettings->hotfolder); if ( ! @is_dir($path_in)) { - if ($this->get_runner() == self::RUNNER_SCHEDULER) { + if ($this->getRunner() == self::RUNNER_SCHEDULER) { $this->log(sprintf(('Warning : missing hotfolder \'%s\', restarting in 10 min.'), $path_in)); for ($t = 60 * 10; $this->running && $t; $t -- ) // DON'T do sleep(600) because it prevents ticks ! sleep(1); - $this->set_status(self::STATUS_TORESTART); + $this->setState(self::STATUS_TORESTART); } else { $this->log(sprintf(('Error : missing hotfolder \'%s\', stopping.'), $path_in)); // runner = manual : can't restart so simply quit - $this->set_status(self::STATUS_STOPPED); + $this->setState(self::STATUS_STOPPED); } $this->running = FALSE; return; } - $this->set_last_exec_time(); + $this->setLastExecTime(); $row = NULL; try { $sql = "SELECT * FROM task2 WHERE task_id = :task_id"; $stmt = $conn->prepare($sql); - $stmt->execute(array(':task_id' => $this->get_task_id())); + $stmt->execute(array(':task_id' => $this->getID())); $row = $stmt->fetch(PDO::FETCH_ASSOC); $stmt->closeCursor(); if ($row && $this->sxTaskSettings = @simplexml_load_string($row['settings'])) { @@ -418,19 +418,19 @@ class task_period_archive extends task_abstract $cold = 60; } else { - throw new Exception(sprintf('Error fetching or reading settings of the task \'%d\'', $this->get_task_id())); + throw new Exception(sprintf('Error fetching or reading settings of the task \'%d\'', $this->getID())); } } catch (Exception $e) { - if ($this->get_runner() == self::RUNNER_SCHEDULER) { - $this->log(sprintf(('Warning : error fetching or reading settings of the task \'%d\', restarting in 10 min.'), $this->get_task_id())); + if ($this->getRunner() == self::RUNNER_SCHEDULER) { + $this->log(sprintf(('Warning : error fetching or reading settings of the task \'%d\', restarting in 10 min.'), $this->getID())); for ($t = 60 * 10; $this->running && $t; $t -- ) // DON'T do sleep(600) because it prevents ticks ! sleep(1); - $this->set_status(self::STATUS_TORESTART); + $this->setState(self::STATUS_TORESTART); } else { - $this->log(sprintf(('Error : error fetching task \'%d\', stopping.'), $this->get_task_id())); + $this->log(sprintf(('Error : error fetching task \'%d\', stopping.'), $this->getID())); // runner = manual : can't restart so simply quit - $this->set_status(self::STATUS_STOPPED); + $this->setState(self::STATUS_STOPPED); } $this->running = FALSE; return; @@ -449,15 +449,15 @@ class task_period_archive extends task_abstract switch ($r) { case 'TOSTOP': - $this->set_status(self::STATUS_STOPPED); + $this->setState(self::STATUS_STOPPED); $this->running = FALSE; break; case 'WAIT': - $this->set_status(self::STATUS_STOPPED); + $this->setState(self::STATUS_STOPPED); $this->running = FALSE; break; case 'BAD': - $this->set_status(self::STATUS_STOPPED); + $this->setState(self::STATUS_STOPPED); $this->running = FALSE; break; case 'NORECSTODO': @@ -472,9 +472,9 @@ class task_period_archive extends task_abstract sleep(5); */ for ($i = 0; $i < (($period + $cold) - $duration) && $this->running; $i ++ ) { - $s = $this->get_status(); + $s = $this->getState(); if ($s == self::STATUS_TOSTOP) { - $this->set_status(self::STATUS_STOPPED); + $this->setState(self::STATUS_STOPPED); $this->running = FALSE; } else { @@ -489,14 +489,14 @@ class task_period_archive extends task_abstract case 'MAXRECSDONE': case 'MAXMEMORY': case 'MAXLOOP': - if ($row['status'] == self::STATUS_STARTED && $this->get_runner() !== self::RUNNER_MANUAL) { - $this->set_status(self::STATUS_TORESTART); + if ($row['status'] == self::STATUS_STARTED && $this->getRunner() !== self::RUNNER_MANUAL) { + $this->setState(self::STATUS_TORESTART); $this->running = FALSE; } break; default: if ($row['status'] == self::STATUS_STARTED) { - $this->set_status(self::STATUS_STOPPED); + $this->setState(self::STATUS_STOPPED); $this->running = FALSE; } break; @@ -569,7 +569,7 @@ class task_period_archive extends task_abstract $cold = 60; while ($cold > 0) { - $s = $this->get_status(); + $s = $this->getState(); if ($s == self::STATUS_TOSTOP) return('TOSTOP'); sleep(2); @@ -723,7 +723,7 @@ class task_period_archive extends task_abstract $time0 = time(); while (($file = $listFolder->read()) !== NULL) { if (time() - $time0 >= 2) { // each 2 secs, check the status of the task - $s = $this->get_status(); + $s = $this->getState(); if ($s == self::STATUS_TOSTOP) { $nnew = 'TOSTOP'; // since we will return a string... break; // ...we can check it against numerical result diff --git a/lib/classes/task/period/batchupload.class.php b/lib/classes/task/period/batchupload.class.php index 7678f4a29e..e06c11f538 100755 --- a/lib/classes/task/period/batchupload.class.php +++ b/lib/classes/task/period/batchupload.class.php @@ -28,21 +28,21 @@ class task_period_batchupload extends task_appboxAbstract return(("Hello I'm the batch upload process.")); } - protected function retrieve_content(appbox $appbox) + protected function retrieveContent(appbox $appbox) { $conn = $appbox->get_connection(); - $sql = 'UPDATE uplfile AS f INNER JOIN uplbatch AS u USING(uplbatch_id) - SET f.error="1", u.error="1" - WHERE u.error=0 AND u.base_id NOT IN(SELECT base_id FROM bas)'; + $sql = 'UPDATE uplfile AS f INNER JOIN uplbatch AS u USING(uplbatch_id)' + . ' SET f.error="1", u.error="1"' + . ' WHERE u.error=0 AND u.base_id NOT IN(SELECT base_id FROM bas)'; $stmt = $conn->prepare($sql); $stmt->execute(); $stmt->closeCursor(); - $sql = 'SELECT uplbatch_id, sbas_id, server_coll_id, usr_id - FROM (uplbatch u INNER JOIN bas b USING(base_id)) - WHERE complete="1" AND error="0" ORDER BY uplbatch_id'; + $sql = 'SELECT uplbatch_id, sbas_id, server_coll_id, usr_id' + . ' FROM (uplbatch u INNER JOIN bas b USING(base_id))' + . ' WHERE complete="1" AND error="0" ORDER BY uplbatch_id'; $stmt = $conn->prepare($sql); $stmt->execute(); @@ -52,7 +52,7 @@ class task_period_batchupload extends task_appboxAbstract return $rs; } - protected function process_one_content(appbox $appbox, Array $row) + protected function processOneContent(appbox $appbox, Array $row) { $appbox = appbox::get_instance(\bootstrap::getCore()); $registry = $appbox->get_registry(); @@ -114,9 +114,9 @@ class task_period_batchupload extends task_appboxAbstract } catch (Exception $e) { $this->log($e->getMessage()); - $sql = 'UPDATE uplfile AS f INNER JOIN uplbatch AS u USING(uplbatch_id) - SET f.error="1", u.error="1" - WHERE u.uplbatch_id = :batch_id'; + $sql = 'UPDATE uplfile AS f INNER JOIN uplbatch AS u USING(uplbatch_id)' + . ' SET f.error="1", u.error="1"' + . ' WHERE u.uplbatch_id = :batch_id'; $stmt = $conn->prepare($sql); $stmt->execute(array(':batch_id' => $batch_id)); @@ -124,10 +124,10 @@ class task_period_batchupload extends task_appboxAbstract $errors = '1'; } - $sql = 'UPDATE uplbatch SET complete="2", error = :error - WHERE uplbatch_id = :batch_id'; + $sql = 'UPDATE uplbatch SET complete="2", error = :error' + . ' WHERE uplbatch_id = :batch_id'; $stmt = $conn->prepare($sql); - $stmt->execute(array(':error' => $errors, ':batch_id' => $batch_id)); + $stmt->execute(array(':error' => $errors, ':batch_id' => $batch_id)); $stmt->closeCursor(); $this->log(sprintf(('finishing batch %s'), $row['uplbatch_id'])); @@ -135,7 +135,7 @@ class task_period_batchupload extends task_appboxAbstract return $this; } - protected function post_process_one_content(appbox $appbox, Array $row) + protected function postProcessOneContent(appbox $appbox, Array $row) { return $this; } diff --git a/lib/classes/task/period/cindexer.class.php b/lib/classes/task/period/cindexer.class.php index 16741be4c6..b4b9b048f6 100755 --- a/lib/classes/task/period/cindexer.class.php +++ b/lib/classes/task/period/cindexer.class.php @@ -338,7 +338,7 @@ class task_period_cindexer extends task_abstract * @param SimpleXMLElement $sx_task_settings * @return task_cindexer */ - protected function load_settings(SimpleXMLElement $sx_task_settings) + protected function loadSettings(SimpleXMLElement $sx_task_settings) { $this->host = trim($sx_task_settings->host); $this->port = trim($sx_task_settings->port); @@ -353,9 +353,7 @@ class task_period_cindexer extends task_abstract $this->winsvc_run = p4field::isyes(trim($sx_task_settings->winsvc_run)); $this->binpath = p4string::addEndSlash(trim($sx_task_settings->binpath)); - parent::load_settings($sx_task_settings); - - return $this; + parent::loadSettings($sx_task_settings); } /** @@ -383,7 +381,7 @@ class task_period_cindexer extends task_abstract } if ( ! file_exists($cmd) || ! is_executable($cmd)) { - $this->set_status(self::STATUS_STOPPED); + $this->setState(self::STATUS_STOPPED); $this->log(sprintf(_('task::cindexer:file \'%s\' does not exists'), $cmd)); throw new Exception('cindexer executable not found', self::ERR_EXECUTABLE_NOT_FOUND); return; @@ -433,7 +431,7 @@ class task_period_cindexer extends task_abstract } if ($this->new_status !== NULL) - $this->set_status($this->new_status); + $this->setState($this->new_status); if ($this->exception) throw $this->exception; @@ -444,8 +442,8 @@ class task_period_cindexer extends task_abstract $nullfile = $this->system == 'WINDOWS' ? 'NUL' : '/dev/null'; $descriptors = array(); - // $descriptors[1] = array("file", $logdir . "/phraseanet_indexer_" . $this->get_task_id() . ".log", "a+"); - // $descriptors[2] = array("file", $logdir . "/phraseanet_indexer_" . $this->get_task_id() . ".error.log", "a+"); + // $descriptors[1] = array("file", $logdir . "/phraseanet_indexer_" . $this->getID() . ".log", "a+"); + // $descriptors[2] = array("file", $logdir . "/phraseanet_indexer_" . $this->getID() . ".error.log", "a+"); $descriptors[1] = array("file", $nullfile, "a+"); $descriptors[2] = array("file", $nullfile, "a+"); @@ -467,7 +465,7 @@ class task_period_cindexer extends task_abstract $this->running = true; while ($this->running) { - if ($this->get_status() == self::STATUS_TOSTOP && $this->socket > 0) { + if ($this->getState() == self::STATUS_TOSTOP && $this->socket > 0) { // must quit task, so send 'Q' to port 127.0.0.1:XXXX to cindexer if ( ! $qsent && (($sock = socket_create(AF_INET, SOCK_STREAM, 0)) !== false)) { if (socket_connect($sock, '127.0.0.1', $this->socket) === true) { @@ -564,7 +562,7 @@ class task_period_cindexer extends task_abstract } } - if ($this->get_status() == self::STATUS_TOSTOP) { + if ($this->getState() == self::STATUS_TOSTOP) { posix_kill($pid, ($sigsent = SIGINT)); sleep(2); } diff --git a/lib/classes/task/period/emptyColl.class.php b/lib/classes/task/period/emptyColl.class.php index e2dbb8b639..8939f726e1 100755 --- a/lib/classes/task/period/emptyColl.class.php +++ b/lib/classes/task/period/emptyColl.class.php @@ -18,8 +18,11 @@ class task_period_emptyColl extends task_appboxAbstract { protected $base_id; + protected $suicidable = true; + protected $total_records = 0; + public function getName() { return(_("Vidage de collection")); @@ -35,16 +38,13 @@ class task_period_emptyColl extends task_appboxAbstract return("Vide une collection"); } - protected function load_settings(SimpleXMLElement $sx_task_settings) + protected function loadSettings(SimpleXMLElement $sx_task_settings) { $this->base_id = (int) $sx_task_settings->base_id; - parent::load_settings($sx_task_settings); - - return $this; + parent::loadSettings($sx_task_settings); } - protected $total_records = 0; - protected function retrieve_content(appbox $appbox) + protected function retrieveContent(appbox $appbox) { if ( ! $this->base_id) { $this->current_state = self::STATE_FINISHED; @@ -54,7 +54,7 @@ class task_period_emptyColl extends task_appboxAbstract $collection = collection::get_from_base_id($this->base_id); $this->total_records = $collection->get_record_amount(); $collection->empty_collection(200); - $this->records_done +=$this->total_records; + $this->records_done += $this->total_records; $this->setProgress($this->records_done, $this->total_records); if ($this->total_records == 0) { @@ -65,12 +65,12 @@ class task_period_emptyColl extends task_appboxAbstract return array(); } - protected function process_one_content(appbox $appbox, Array $row) + protected function processOneContent(appbox $appbox, Array $row) { return $this; } - protected function post_process_one_content(appbox $appbox, Array $row) + protected function postProcessOneContent(appbox $appbox, Array $row) { return $this; } diff --git a/lib/classes/task/period/ftp.class.php b/lib/classes/task/period/ftp.class.php index 05e0fda46b..20df485ffe 100755 --- a/lib/classes/task/period/ftp.class.php +++ b/lib/classes/task/period/ftp.class.php @@ -16,6 +16,11 @@ */ class task_period_ftp extends task_appboxAbstract { + protected $proxy; + + protected $proxyport; + + protected $debug; /** * @@ -49,13 +54,13 @@ class task_period_ftp extends task_appboxAbstract , "proxyport" , "period" ); - if ($dom = @DOMDocument::loadXML($oldxml)) { + if (($dom = @DOMDocument::loadXML($oldxml))) { $xmlchanged = false; foreach (array("str:proxy", "str:proxyport", "str:period") as $pname) { $ptype = substr($pname, 0, 3); $pname = substr($pname, 4); $pvalue = $parm2[$pname]; - if ($ns = $dom->getElementsByTagName($pname)->item(0)) { + if (($ns = $dom->getElementsByTagName($pname)->item(0))) { // le champ existait dans le xml, on supprime son ancienne valeur (tout le contenu) while (($n = $ns->firstChild)) $ns->removeChild($n); @@ -93,12 +98,11 @@ class task_period_ftp extends task_appboxAbstract // ... but we could check for safe values (ex. 0 < period < 3600) ?>

- +

- +

-  :  +  :   
@@ -176,11 +181,11 @@ class task_period_ftp extends task_appboxAbstract if ($parm["xml"] === null) { // pas de xml 'raw' : on accepte les champs 'graphic view' - if ($domTaskSettings = @DOMDocument::loadXML($taskrow["settings"])) { + if (($domTaskSettings = @DOMDocument::loadXML($taskrow["settings"]))) { $xmlchanged = false; foreach (array("proxy", "proxyport", "period") as $f) { if ($parm[$f] !== NULL) { - if ($ns = $domTaskSettings->getElementsByTagName($f)->item(0)) { + if (($ns = $domTaskSettings->getElementsByTagName($f)->item(0))) { // le champ existait dans le xml, on supprime son ancienne valeur (tout le contenu) while (($n = $ns->firstChild)) $ns->removeChild($n); @@ -235,21 +240,16 @@ class task_period_ftp extends task_appboxAbstract return true; } } - protected $proxy; - protected $proxyport; - protected $debug; - protected function load_settings(SimpleXMLElement $sx_task_settings) + protected function loadSettings(SimpleXMLElement $sx_task_settings) { $this->proxy = (string) $sx_task_settings->proxy; $this->proxyport = (string) $sx_task_settings->proxyport; - parent::load_settings($sx_task_settings); - - return $this; + parent::loadSettings($sx_task_settings); } - protected function retrieve_content(appbox $appbox) + protected function retrieveContent(appbox $appbox) { $conn = $appbox->get_connection(); @@ -309,7 +309,7 @@ class task_period_ftp extends task_appboxAbstract return $ftp_exports; } - protected function process_one_content(appbox $appbox, Array $ftp_export) + protected function processOneContent(appbox $appbox, Array $ftp_export) { $conn = $appbox->get_connection(); $registry = $appbox->get_registry(); @@ -463,7 +463,7 @@ class task_period_ftp extends task_appboxAbstract $obj[] = array( - "name" => $subdef, "size" => filesize($localfile), + "name" => $subdef, "size" => filesize($localfile), "shortXml" => ($sdcaption ? $sdcaption : '') ); @@ -471,8 +471,8 @@ class task_period_ftp extends task_appboxAbstract unlink($localfile); } - $sql = "UPDATE ftp_export_elements - SET done='1', error='0' WHERE id = :file_id"; + $sql = "UPDATE ftp_export_elements" + . " SET done='1', error='0' WHERE id = :file_id"; $stmt = $conn->prepare($sql); $stmt->execute(array(':file_id' => $file['id'])); $stmt->closeCursor(); @@ -488,10 +488,10 @@ class task_period_ftp extends task_appboxAbstract $done = $file['error']; - $sql = "UPDATE ftp_export_elements - SET done = :done, error='1' WHERE id = :file_id"; + $sql = "UPDATE ftp_export_elements" + . " SET done = :done, error='1' WHERE id = :file_id"; $stmt = $conn->prepare($sql); - $stmt->execute(array(':done' => $done, ':file_id' => $file['id'])); + $stmt->execute(array(':done' => $done, ':file_id' => $file['id'])); $stmt->closeCursor(); } } @@ -503,10 +503,10 @@ class task_period_ftp extends task_appboxAbstract $date = new DateTime(); $remote_file = $date->format('U'); - $sql = 'SELECT filename, folder - FROM ftp_export_elements - WHERE ftp_export_id = :ftp_export_id - AND error = "0" AND done="1"'; + $sql = 'SELECT filename, folder' + . ' FROM ftp_export_elements' + . ' WHERE ftp_export_id = :ftp_export_id' + . ' AND error = "0" AND done="1"'; $stmt = $conn->prepare($sql); $stmt->execute(array(':ftp_export_id' => $id)); @@ -545,8 +545,8 @@ class task_period_ftp extends task_appboxAbstract if ($this->debug) echo $line; - $sql = "UPDATE ftp_export SET crash=crash+1,date=now() - WHERE id = :export_id"; + $sql = "UPDATE ftp_export SET crash=crash+1,date=now()" + . " WHERE id = :export_id"; $stmt = $conn->prepare($sql); $stmt->execute(array(':export_id' => $ftp_export['id'])); $stmt->closeCursor(); @@ -557,7 +557,7 @@ class task_period_ftp extends task_appboxAbstract phrasea_close_session($ses_id); } - protected function post_process_one_content(appbox $appbox, Array $row) + protected function postProcessOneContent(appbox $appbox, Array $row) { return $this; } @@ -566,8 +566,8 @@ class task_period_ftp extends task_appboxAbstract { $conn = $appbox->get_connection(); - $sql = 'SELECT crash, nbretry FROM ftp_export - WHERE id = :export_id'; + $sql = 'SELECT crash, nbretry FROM ftp_export' + . ' WHERE id = :export_id'; $stmt = $conn->prepare($sql); $stmt->execute(array(':export_id' => $id)); @@ -580,8 +580,8 @@ class task_period_ftp extends task_appboxAbstract return $this; } - $sql = 'SELECT count(id) as total, sum(error) as errors, sum(done) as done - FROM ftp_export_elements WHERE ftp_export_id = :export_id'; + $sql = 'SELECT count(id) as total, sum(error) as errors, sum(done) as done' + . ' FROM ftp_export_elements WHERE ftp_export_id = :export_id'; $stmt = $conn->prepare($sql); $stmt->execute(array(':export_id' => $id)); $row = $stmt->fetch(PDO::FETCH_ASSOC); @@ -619,8 +619,8 @@ class task_period_ftp extends task_appboxAbstract $conn = $appbox->get_connection(); $registry = registry::get_instance(); - $sql = 'SELECT filename, base_id, record_id, subdef, error, done - FROM ftp_export_elements WHERE ftp_export_id = :export_id'; + $sql = 'SELECT filename, base_id, record_id, subdef, error, done' + . ' FROM ftp_export_elements WHERE ftp_export_id = :export_id'; $transferts = array(); @@ -648,8 +648,8 @@ class task_period_ftp extends task_appboxAbstract } } - $sql = 'SELECT addr, crash, nbretry, sendermail, mail, text_mail_sender, text_mail_receiver - FROM ftp_export WHERE id = :export_id'; + $sql = 'SELECT addr, crash, nbretry, sendermail, mail, text_mail_sender, text_mail_receiver' + . ' FROM ftp_export WHERE id = :export_id'; $stmt = $conn->prepare($sql); $stmt->execute(array(':export_id' => $id)); diff --git a/lib/classes/task/period/ftpPull.class.php b/lib/classes/task/period/ftpPull.class.php index 02d349f954..ffa070b309 100755 --- a/lib/classes/task/period/ftpPull.class.php +++ b/lib/classes/task/period/ftpPull.class.php @@ -16,404 +16,366 @@ */ class task_period_ftpPull extends task_appboxAbstract { + protected $debug = false; - protected $debug = false; - protected $proxy; - protected $proxyport; - protected $host; - protected $port; - protected $user; - protected $password; - protected $ssl; - protected $passive; - protected $ftppath; - protected $localpath; + protected $proxy; - public function getName() - { - return(_("task::ftp:FTP Pull")); - } + protected $proxyport; - public function help() - { - return ''; - } + protected $host; - public function graphic2xml($oldxml) - { - $request = http_request::getInstance(); + protected $port; - $parm2 = $request->get_parms( - "proxy", "proxyport", "host", "port", "user" - , "password", "ssl", "ftppath", "localpath" - , "passive", "period" - ); - if ($dom = @DOMDocument::loadXML($oldxml)) + protected $user; + + protected $password; + + protected $ssl; + + protected $passive; + + protected $ftppath; + + protected $localpath; + + public function getName() { - $xmlchanged = false; - foreach (array("str:proxy", "str:proxyport", "str:period", "boo:passive", "boo:ssl", "str:password", "str:user", "str:ftppath", "str:localpath", "str:port", "str:host") as $pname) - { - $ptype = substr($pname, 0, 3); - $pname = substr($pname, 4); - $pvalue = $parm2[$pname]; - if ($ns = $dom->getElementsByTagName($pname)->item(0)) - { - // le champ existait dans le xml, on supprime son ancienne valeur (tout le contenu) - while (($n = $ns->firstChild)) - $ns->removeChild($n); - } - else - { - // le champ n'existait pas dans le xml, on le cree - $dom->documentElement->appendChild($dom->createTextNode("\t")); - $ns = $dom->documentElement->appendChild($dom->createElement($pname)); - $dom->documentElement->appendChild($dom->createTextNode("\n")); - } - // on fixe sa valeur - switch ($ptype) - { - case "str": - $ns->appendChild($dom->createTextNode($pvalue)); - break; - case "boo": - $ns->appendChild($dom->createTextNode($pvalue ? '1' : '0')); - break; - } - $xmlchanged = true; - } + return(_("task::ftp:FTP Pull")); } - return($dom->saveXML()); - } - - public function xml2graphic($xml, $form) - { - if (($sxml = simplexml_load_string($xml))) // in fact XML IS always valid here... + public function help() { - // ... but we could check for safe values (ex. 0 < period < 3600) -?> - - - - -
-
- -
-
- -
-
- - -
-
- -
-
- -
-
- -
-
- -
-
- -
-
- - - -
- - -
- - -  
-
-get_parms( - "xml", "name", "active", "proxy", "proxyport", "period" - , "localpath", "ftppath", "port", "host", "user" - , "password", "passive", "ssl", "debug" - ); - - if ($parm["xml"] === null) - { - // pas de xml 'raw' : on accepte les champs 'graphic view' - if ($domTaskSettings = DOMDocument::loadXML($taskrow["settings"])) - { - $xmlchanged = false; - foreach (array("proxy", "proxyport", "period", "host", "port", "user", "password", "ssl", "passive", "localpath", "ftppath") as $f) - { - if ($parm[$f] !== NULL) - { - if ($ns = $domTaskSettings->getElementsByTagName($f)->item(0)) - { - // le champ existait dans le xml, on supprime son ancienne valeur (tout le contenu) - while (($n = $ns->firstChild)) - $ns->removeChild($n); + $parm2 = $request->get_parms( + "proxy", "proxyport", "host", "port", "user" + , "password", "ssl", "ftppath", "localpath" + , "passive", "period" + ); + if ($dom = @DOMDocument::loadXML($oldxml)) { + $xmlchanged = false; + foreach (array("str:proxy", "str:proxyport", "str:period", "boo:passive", "boo:ssl", "str:password", "str:user", "str:ftppath", "str:localpath", "str:port", "str:host") as $pname) { + $ptype = substr($pname, 0, 3); + $pname = substr($pname, 4); + $pvalue = $parm2[$pname]; + if ($ns = $dom->getElementsByTagName($pname)->item(0)) { + // le champ existait dans le xml, on supprime son ancienne valeur (tout le contenu) + while (($n = $ns->firstChild)) + $ns->removeChild($n); + } else { + // le champ n'existait pas dans le xml, on le cree + $dom->documentElement->appendChild($dom->createTextNode("\t")); + $ns = $dom->documentElement->appendChild($dom->createElement($pname)); + $dom->documentElement->appendChild($dom->createTextNode("\n")); + } + // on fixe sa valeur + switch ($ptype) { + case "str": + $ns->appendChild($dom->createTextNode($pvalue)); + break; + case "boo": + $ns->appendChild($dom->createTextNode($pvalue ? '1' : '0')); + break; + } + $xmlchanged = true; } - else - { - // le champ n'existait pas dans le xml, on le cree - $domTaskSettings->documentElement->appendChild($domTaskSettings->createTextNode("\t")); - $ns = $domTaskSettings->documentElement->appendChild($domTaskSettings->createElement($f)); - $domTaskSettings->documentElement->appendChild($domTaskSettings->createTextNode("\n")); - } - // on fixe sa valeur - $ns->appendChild($domTaskSettings->createTextNode($parm[$f])); - $xmlchanged = true; - } } - if ($xmlchanged) - $parm["xml"] = $domTaskSettings->saveXML(); - } + + return($dom->saveXML()); } - // si on doit changer le xml, on verifie qu'il est valide - if ($parm["xml"] && !DOMDocument::loadXML($parm["xml"])) + public function xml2graphic($xml, $form) + { + if (($sxml = simplexml_load_string($xml))) { // in fact XML IS always valid here... + // ... but we could check for safe values (ex. 0 < period < 3600) + ?> + + prepare($sql); - $stmt->execute($params); - $stmt->closeCursor(); + global $parm; + ?> + + +
+
+ +
+
+ +
+
+ + +
+
+ +
+
+ +
+
+ +
+
+ +
+
+ +
+
+ + + +
+ + +
+ + +  
+
+ proxy = (string) $sx_task_settings->proxy; - $this->proxyport = (string) $sx_task_settings->proxyport; - $this->host = (string) ($sx_task_settings->host); - $this->port = (string) ($sx_task_settings->port); - $this->user = (string) ($sx_task_settings->user); - $this->password = (string) ($sx_task_settings->password); - $this->ssl = !!((string) ($sx_task_settings->ssl)); - $this->passive = !!((string) ($sx_task_settings->passive)); - $this->ftppath = (string) ($sx_task_settings->ftppath); - $this->localpath = (string) ($sx_task_settings->localpath); - - parent::load_settings($sx_task_settings); - - return $this; - } - - protected function retrieve_content(appbox $appbox) - { - foreach(array('localpath', 'host', 'port', 'user', 'password', 'ftppath') as $f) - { - if(trim((string)($this->{$f})) === '') - { - $this->log('setting \''.$f.'\' must be set'); - $this->running = FALSE; - } - } - if (!is_dir($this->localpath) || !system_file::mkdir($this->localpath)) - { - $this->log('\''.$this->localpath.'\' does not exists'); - $this->running = FALSE; - } - if (!is_writeable($this->localpath)) - { - $this->log('\''.$this->localpath.'\' is not writeable'); - $this->running = FALSE; - } - if(!$this->running ) - { - $this->set_status(self::STATUS_STOPPED); - return array(); - } - - try + public function saveChanges(connection_pdo $conn, $taskid, &$taskrow) { - $ftp = new ftpclient($this->host, $port, 90, $this->ssl, $this->proxy, $this->proxyport); - $ftp->login($this->user, $this->password); - $ftp->chdir($this->ftppath); - $list_1 = $ftp->list_directory(true); + $request = http_request::getInstance(); - $todo = count($list_1); - $this->setProgress($done, $todo); + $parm = $request->get_parms( + "xml", "name", "active", "proxy", "proxyport", "period" + , "localpath", "ftppath", "port", "host", "user" + , "password", "passive", "ssl", "debug" + ); - if ($this->debug) - echo "attente de 25sec pour avoir les fichiers froids...\n"; - for($t = 25; $this->running && $t > 0; $t--) // DON'T do sleep($this->period - $when_started) because it prevents ticks ! - { - $s = $this->get_status(); - if($s == self::STATUS_TOSTOP) - { - if (isset($ftp) && $ftp instanceof ftpclient) - $ftp->close(); - $this->set_status(self::STATUS_STOPPED); - $this->running = FALSE; - return array(); - } - else - { - sleep(1); - } - } - - $list_2 = $ftp->list_directory(true); - - foreach ($list_1 as $filepath => $timestamp) - { - $done++; - $this->setProgress($done, $todo); - - if (!isset($list_2[$filepath])) - { - if ($this->debug) - echo "le fichier $filepath a disparu...\n"; - continue; - } - if ($list_2[$filepath] !== $timestamp) - { - if ($this->debug) - echo "le fichier $filepath a ete modifie depuis le dernier passage...\n"; - continue; + if ($parm["xml"] === null) { + // pas de xml 'raw' : on accepte les champs 'graphic view' + if ($domTaskSettings = DOMDocument::loadXML($taskrow["settings"])) { + $xmlchanged = false; + foreach (array("proxy", "proxyport", "period", "host", "port", "user", "password", "ssl", "passive", "localpath", "ftppath") as $f) { + if ($parm[$f] !== NULL) { + if ($ns = $domTaskSettings->getElementsByTagName($f)->item(0)) { + // le champ existait dans le xml, on supprime son ancienne valeur (tout le contenu) + while (($n = $ns->firstChild)) + $ns->removeChild($n); + } else { + // le champ n'existait pas dans le xml, on le cree + $domTaskSettings->documentElement->appendChild($domTaskSettings->createTextNode("\t")); + $ns = $domTaskSettings->documentElement->appendChild($domTaskSettings->createElement($f)); + $domTaskSettings->documentElement->appendChild($domTaskSettings->createTextNode("\n")); + } + // on fixe sa valeur + $ns->appendChild($domTaskSettings->createTextNode($parm[$f])); + $xmlchanged = true; + } + } + if ($xmlchanged) + $parm["xml"] = $domTaskSettings->saveXML(); + } } - $finalpath = p4string::addEndSlash($this->localpath) . ($filepath[0] == '/' ? mb_substr($filepath, 1) : $filepath); - echo "Ok pour rappatriement de $filepath vers $finalpath\n"; + // si on doit changer le xml, on verifie qu'il est valide + if ($parm["xml"] && ! DOMDocument::loadXML($parm["xml"])) + return(false); - try - { - if (file_exists($finalpath)) - throw new Exception("Un fichier du meme nom ($finalpath) existe deja..."); - - system_file::mkdir(dirname($finalpath)); - - $ftp->get($finalpath, $filepath); - $ftp->delete($filepath); + $sql = ""; + $params = array(':task_id' => $taskid); + if ($parm["xml"] !== NULL) { + $sql .= ( $sql ? " ," : "") . "settings = :settings"; + $params[':settings'] = $parm['xml']; } - catch (Exception $e) - { - if ($this->debug) - echo "Erreur lors du rappatriement de $filepath : " . $e->getMessage() . "\n"; + if ($parm["name"] !== NULL) { + $sql .= ( $sql ? " ," : "") . "name = :name"; + $params[':name'] = $parm['name']; + } + if ($parm["active"] !== NULL) { + $sql .= ( $sql ? " ," : "") . "active = :active"; + $params[':active'] = $parm['active']; } - } - $ftp->close(); + if ($sql) { + try { + $sql = "UPDATE task2 SET $sql WHERE task_id = :task_id"; + $stmt = $conn->prepare($sql); + $stmt->execute($params); + $stmt->closeCursor(); - $this->setProgress(0, 0); + return true; + } catch (Exception $e) { + return false; + } + } else { + return true; + } } - catch (Exception $e) + + protected function loadSettings(SimpleXMLElement $sx_task_settings) { - if (isset($ftp) && $ftp instanceof ftpclient) - $ftp->close(); - echo $e->getMessage() . "\n"; - return array(); + $this->proxy = (string) $sx_task_settings->proxy; + $this->proxyport = (string) $sx_task_settings->proxyport; + $this->host = (string) ($sx_task_settings->host); + $this->port = (string) ($sx_task_settings->port); + $this->user = (string) ($sx_task_settings->user); + $this->password = (string) ($sx_task_settings->password); + $this->ssl = ! ! ((string) ($sx_task_settings->ssl)); + $this->passive = ! ! ((string) ($sx_task_settings->passive)); + $this->ftppath = (string) ($sx_task_settings->ftppath); + $this->localpath = (string) ($sx_task_settings->localpath); + + parent::loadSettings($sx_task_settings); } - } - protected function process_one_content(appbox $appbox, Array $row) - { + protected function retrieveContent(appbox $appbox) + { + foreach (array('localpath', 'host', 'port', 'user', 'password', 'ftppath') as $f) { + if (trim((string) ($this->{$f})) === '') { + $this->log('setting \'' . $f . '\' must be set'); + $this->running = FALSE; + } + } + if ( ! is_dir($this->localpath) || ! system_file::mkdir($this->localpath)) { + $this->log('\'' . $this->localpath . '\' does not exists'); + $this->running = FALSE; + } + if ( ! is_writeable($this->localpath)) { + $this->log('\'' . $this->localpath . '\' is not writeable'); + $this->running = FALSE; + } + if ( ! $this->running) { + $this->set_status(self::STATUS_STOPPED); + return array(); + } - } + try { + $ftp = new ftpclient($this->host, $port, 90, $this->ssl, $this->proxy, $this->proxyport); + $ftp->login($this->user, $this->password); + $ftp->chdir($this->ftppath); + $list_1 = $ftp->list_directory(true); - protected function post_process_one_content(appbox $appbox, Array $row) - { + $todo = count($list_1); + $this->setProgress($done, $todo); - } + if ($this->debug) + echo "attente de 25sec pour avoir les fichiers froids...\n"; + for ($t = 25; $this->running && $t > 0; $t -- ) { // DON'T do sleep($this->period - $when_started) because it prevents ticks ! + $s = $this->getState(); + if ($s == self::STATUS_TOSTOP) { + if (isset($ftp) && $ftp instanceof ftpclient) + $ftp->close(); + $this->set_status(self::STATUS_STOPPED); + $this->running = FALSE; + return array(); + } + else { + sleep(1); + } + } + $list_2 = $ftp->list_directory(true); + + foreach ($list_1 as $filepath => $timestamp) { + $done ++; + $this->setProgress($done, $todo); + + if ( ! isset($list_2[$filepath])) { + if ($this->debug) + echo "le fichier $filepath a disparu...\n"; + continue; + } + if ($list_2[$filepath] !== $timestamp) { + if ($this->debug) + echo "le fichier $filepath a ete modifie depuis le dernier passage...\n"; + continue; + } + + $finalpath = p4string::addEndSlash($this->localpath) . ($filepath[0] == '/' ? mb_substr($filepath, 1) : $filepath); + echo "Ok pour rappatriement de $filepath vers $finalpath\n"; + + try { + if (file_exists($finalpath)) + throw new Exception("Un fichier du meme nom ($finalpath) existe deja..."); + + system_file::mkdir(dirname($finalpath)); + + $ftp->get($finalpath, $filepath); + $ftp->delete($filepath); + } catch (Exception $e) { + if ($this->debug) + echo "Erreur lors du rappatriement de $filepath : " . $e->getMessage() . "\n"; + } + } + + $ftp->close(); + + $this->setProgress(0, 0); + } catch (Exception $e) { + if (isset($ftp) && $ftp instanceof ftpclient) + $ftp->close(); + echo $e->getMessage() . "\n"; + return array(); + } + } + + protected function processOneContent(appbox $appbox, Array $row) + { + + } + + protected function postProcessOneContent(appbox $appbox, Array $row) + { + + } } diff --git a/lib/classes/task/period/outofdate.class.php b/lib/classes/task/period/outofdate.class.php index c3127763cf..cd0f7885da 100755 --- a/lib/classes/task/period/outofdate.class.php +++ b/lib/classes/task/period/outofdate.class.php @@ -17,24 +17,24 @@ class task_period_outofdate extends task_abstract { - // ==================================================================== - // getName : must return the name for this kind of task - // MANDATORY - // ==================================================================== - public function getName() - { - return(_('Documents perimes')); - } + // ==================================================================== + // getName : must return the name for this kind of task + // MANDATORY + // ==================================================================== + public function getName() + { + return(_('Documents perimes')); + } - // ==================================================================== - // graphic2xml : must return the xml (text) version of the form - // ==================================================================== - public function graphic2xml($oldxml) - { + // ==================================================================== + // graphic2xml : must return the xml (text) version of the form + // ==================================================================== + public function graphic2xml($oldxml) + { // global $parm; - $request = http_request::getInstance(); + $request = http_request::getInstance(); - $parm2 = $request->get_parms( + $parm2 = $request->get_parms( "sbas_id" , "period" , 'field1' @@ -49,892 +49,753 @@ class task_period_outofdate extends task_abstract , 'coll1' , 'status2' , 'coll2' - ); - $dom = new DOMDocument(); - $dom->preserveWhiteSpace = false; - $dom->formatOutput = true; - if($dom->loadXML($oldxml)) - { - $xmlchanged = false; - // foreach($parm2 as $pname=>$pvalue) - foreach(array( - "str:sbas_id", - "str:period", - 'str:field1', - 'str:fieldDs1', - 'str:fieldDv1', - 'str:field2', - 'str:fieldDs2', - 'str:fieldDv2', - 'str:status0', - 'str:coll0', - 'str:status1', - 'str:coll1', - 'str:status2', - 'str:coll2' - ) as $pname) - { - $ptype = substr($pname, 0, 3); - $pname = substr($pname, 4); - $pvalue = $parm2[$pname]; - if(($ns = $dom->getElementsByTagName($pname)->item(0))) - { - // le champ existait dans le xml, on supprime son ancienne valeur (tout le contenu) - while(($n = $ns->firstChild)) - $ns->removeChild($n); - } - else - { - // le champ n'existait pas dans le xml, on le cree - $dom->documentElement->appendChild($dom->createTextNode("\t")); - $ns = $dom->documentElement->appendChild($dom->createElement($pname)); - $dom->documentElement->appendChild($dom->createTextNode("\n")); - } - // on fixe sa valeur - switch($ptype) - { - case "str": - $ns->appendChild($dom->createTextNode($pvalue)); - break; - case "boo": - $ns->appendChild($dom->createTextNode($pvalue ? '1' : '0')); - break; - } - $xmlchanged = true; - } - } - - return($dom->saveXML()); - } - - // ==================================================================== - // xml2graphic : must fill the graphic form (using js) from xml - // ==================================================================== - public function xml2graphic($xml, $form) - { - if(($sxml = simplexml_load_string($xml))) // in fact XML IS always valid here... - { - // ... but we could check for safe values - if((int) ($sxml->period) < 10) - $sxml->period = 10; - elseif((int) ($sxml->period) > 1440) // 1 jour - $sxml->period = 1440; - - if((string) ($sxml->delay) == '') - $sxml->delay = 0; - ?> - - saveXML()); } - else // ... so we NEVER come here + + // ==================================================================== + // xml2graphic : must fill the graphic form (using js) from xml + // ==================================================================== + public function xml2graphic($xml, $form) { - // bad xml - return("BAD XML"); + if (($sxml = simplexml_load_string($xml))) { // in fact XML IS always valid here... + // ... but we could check for safe values + if ((int) ($sxml->period) < 10) + $sxml->period = 10; + elseif ((int) ($sxml->period) > 1440) // 1 jour + $sxml->period = 1440; + + if ((string) ($sxml->delay) == '') + $sxml->delay = 0; + ?> + + - - - - get_session(); - $user = User_Adapter::getInstance($session->get_usr_id(), $appbox); - ob_start(); - - $sbas_list = $user->ACL()->get_granted_sbas(array('bas_manage')); - ?> -
-  :  - - + + -
- -  :  - -
-
- - - - - - - - - - - - - - - - - - - - - - -
-   - -   - - -
- -   -
-   - - -
- -   -
-   -
-  : - - - - - - -
-  :
-
- - - - - -
-
-
-
-
cmd
-
- array("set"=>false, "values"=>array(), "usage"=>" : usage du truc") - ); - - // ====================================================================================================== - // ===== help() : text displayed if --help (optional) - // ====================================================================================================== - function help() - { - return(_("task::outofdate:deplacement de docs suivant valeurs de champs 'date'")); - } - - // ====================================================================================================== - // ===== run() : le code d'execution de la tache proprement dite - // ====================================================================================================== - - protected $sxTaskSettings = null; // les settings de la tache en simplexml - private $connbas = null; // cnx a la base - private $msg = ""; - private $sbas_id; - - protected function run2() - { - $ret = ''; - $conn = connection::getPDOConnection(); - - $this->sxTaskSettings = simplexml_load_string($this->settings); - - $this->sbas_id = (int) ($this->sxTaskSettings->sbas_id); - - $this->connbas = connection::getPDOConnection($this->sbas_id); - - $this->running = true; - $this->tmask = array(); - $this->tmaskgrp = array(); - $this->period = 60; - - - // ici la tache tourne tant qu'elle est active - $last_exec = 0; - $loop = 0; - while($this->running) + // ==================================================================== + // printInterfaceJS() : generer le code js de l'interface 'graphic view' + // ==================================================================== + public function printInterfaceJS() { - if(!$conn->ping()) - { - $this->log(("Warning : abox connection lost, restarting in 10 min.")); - for($i=0; $i<60 * 10; $i++) - sleep(1); - $this->running = false; + global $parm; + ?> + + get_session(); + $user = User_Adapter::getInstance($session->get_usr_id(), $appbox); + ob_start(); + + $sbas_list = $user->ACL()->get_granted_sbas(array('bas_manage')); + ?> +
+  :  + + + +   + +
+
+ +  :  + +
+
+ + + + + + + + + + + + + + + + + + + + + + +
+   + +   + + +
+ +   +
+   + + +
+ +   +
+   +
+  : + + + + + + +
+  :
+
+ + + + + +
+
+
+
+
cmd
+
+ array("set"=>false, "values"=>array(), "usage"=>" : usage du truc") + ); + + // ====================================================================================================== + // ===== help() : text displayed if --help (optional) + // ====================================================================================================== + function help() + { + return(_("task::outofdate:deplacement de docs suivant valeurs de champs 'date'")); + } + // ====================================================================================================== + // ===== run() : le code d'execution de la tache proprement dite + // ====================================================================================================== + + protected $sxTaskSettings = null; // les settings de la tache en simplexml + + private $connbas = null; // cnx a la base + + private $msg = ""; + + private $sbas_id; + + protected function run2() + { + $ret = ''; + $conn = connection::getPDOConnection(); + + $this->sxTaskSettings = simplexml_load_string($this->settings); + + $this->sbas_id = (int) ($this->sxTaskSettings->sbas_id); + + $this->connbas = connection::getPDOConnection($this->sbas_id); + + $this->running = true; + $this->tmask = array(); + $this->tmaskgrp = array(); + $this->period = 60; + + + // ici la tache tourne tant qu'elle est active + $last_exec = 0; + $loop = 0; + while ($this->running) { + if ( ! $conn->ping()) { + $this->log(("Warning : abox connection lost, restarting in 10 min.")); + for ($i = 0; $i < 60 * 10; $i ++ ) + sleep(1); $this->running = false; - } - break; - default: - if($row['status'] == self::STATUS_STARTED) - { + + return(self::STATUS_TORESTART); + } + + try { + $connbas = connection::getPDOConnection($this->sbas_id); + if ( ! $connbas->ping()) + throw new Exception('Mysql has gone away'); + } catch (Exception $e) { + $this->log(("dbox connection lost, restarting in 10 min.")); + for ($i = 0; $i < 60 * 10; $i ++ ) + sleep(1); + $this->running = false; + + return(self::STATUS_TORESTART); + } + + $this->setLastExecTime(); + + $databox = databox::get_instance($this->sbas_id); + + $sql = "SELECT * FROM task2 WHERE task_id = :task_id"; + $stmt = $conn->prepare($sql); + $stmt->execute(array(':task_id' => $this->getID())); + $row = $stmt->fetch(PDO::FETCH_ASSOC); + $stmt->closeCursor(); + + if ($row) { + if ($row['status'] == 'tostop') { + $ret = self::STATUS_STOPPED; + $this->running = false; + } else { + if (($this->sxTaskSettings = simplexml_load_string($row['settings']))) { + $period = (int) ($this->sxTaskSettings->period); + if ($period <= 0 || $period >= 24 * 60) + $period = 60; + } + else { + $period = 60; + } + $this->connbas = connection::getPDOConnection($this->sbas_id); + + $duration = time(); + + $r = $this->doRecords(); + + switch ($r) { + case 'WAIT': + $ret = self::STATUS_STOPPED; + $this->running = false; + break; + case 'BAD': + $ret = self::STATUS_STOPPED; + $this->running = false; + break; + case 'NORECSTODO': + $duration = time() - $duration; + if ($duration < $period) { + sleep($period - $duration); + $conn = connection::getPDOConnection(); + } + break; + case 'MAXRECSDONE': + case 'MAXMEMORY': + case 'MAXLOOP': + if ($row['status'] == self::STATUS_STARTED && $this->getRunner() !== self::RUNNER_MANUAL) { + $ret = self::STATUS_TORESTART; + $this->running = false; + } + break; + default: + if ($row['status'] == self::STATUS_STARTED) { + $ret = self::STATUS_STOPPED; + $this->running = false; + } + break; + } + } + } else { $ret = self::STATUS_STOPPED; $this->running = false; - } - break; - } + } + $loop ++; } - } - else - { - $ret = self::STATUS_STOPPED; - $this->running = false; - } - $loop++; } - } - function doRecords() - { - $ndone = 0; - $ret = 'NORECSTODO'; - - $tsql = $this->calcSQL($this->sxTaskSettings); - - $nchanged = 0; - foreach($tsql as $xsql) + function doRecords() { - try - { - $stmt = $this->connbas->prepare($xsql['sql']); - if($stmt->execute($xsql['params'])) - { - $n = $stmt->rowCount(); - $stmt->closeCursor(); + $ndone = 0; + $ret = 'NORECSTODO'; - $nchanged += $n; - if($n > 0) - $this->log(sprintf("SQL='%s' ; parms=%s - %s changes", $xsql['sql'], var_export($xsql['params']), $n)); + $tsql = $this->calcSQL($this->sxTaskSettings); + + $nchanged = 0; + foreach ($tsql as $xsql) { + try { + $stmt = $this->connbas->prepare($xsql['sql']); + if ($stmt->execute($xsql['params'])) { + $n = $stmt->rowCount(); + $stmt->closeCursor(); + + $nchanged += $n; + if ($n > 0) + $this->log(sprintf("SQL='%s' ; parms=%s - %s changes", $xsql['sql'], var_export($xsql['params']), $n)); + } + else { + $this->log(sprintf("ERROR SQL='%s' ; parms=%s", $xsql['sql'], var_export($xsql['params'], true))); + } + } catch (ErrorException $e) { + $this->log(sprintf("ERROR SQL='%s' ; parms=%s", $xsql['sql'], var_export($xsql['params'], true))); + } } - else - { - $this->log(sprintf("ERROR SQL='%s' ; parms=%s", $xsql['sql'], var_export($xsql['params'], true))); - } - } - catch (ErrorException $e) - { - $this->log(sprintf("ERROR SQL='%s' ; parms=%s", $xsql['sql'], var_export($xsql['params'], true))); - } + + $ret = ($nchanged > 0 ? $nchanged : 'NORECSTODO'); + + return($ret); } - $ret = ($nchanged > 0 ? $nchanged : 'NORECSTODO'); - - return($ret); - } - - - private function calcSQL($sxTaskSettings) - { - $ret = array(); - - $this->sxTaskSettings = $sxTaskSettings; - - $date1 = $date2 = NULL; - $field1 = $field2 = ''; - - // test : DATE 1 - if(($field1 = trim($this->sxTaskSettings->field1)) != '') + private function calcSQL($sxTaskSettings) { - $date1 = time(); - if(($delta = (int) ($this->sxTaskSettings->fieldDv1)) > 0) - { - if($this->sxTaskSettings->fieldDs1 == '-') - $date1 += 86400 * $delta; - else - $date1 -= 86400 * $delta; - } - $date1 = date("YmdHis", $date1); + $ret = array(); + + $this->sxTaskSettings = $sxTaskSettings; + + $date1 = $date2 = NULL; + $field1 = $field2 = ''; + + // test : DATE 1 + if (($field1 = trim($this->sxTaskSettings->field1)) != '') { + $date1 = time(); + if (($delta = (int) ($this->sxTaskSettings->fieldDv1)) > 0) { + if ($this->sxTaskSettings->fieldDs1 == '-') + $date1 += 86400 * $delta; + else + $date1 -= 86400 * $delta; + } + $date1 = date("YmdHis", $date1); + } + // test : DATE 2 + if (($field2 = trim($this->sxTaskSettings->field2)) != '') { + $date2 = time(); + if (($delta = (int) ($this->sxTaskSettings->fieldDv2)) > 0) { + if ($this->sxTaskSettings->fieldDs2 == '-') + $date2 += 86400 * $delta; + else + $date2 -= 86400 * $delta; + } + $date2 = date("YmdHis", $date2); + } + + + $sqlset = $params = $tmp_params = array(); + for ($i = 0; $i <= 2; $i ++ ) { + $sqlwhere[$i] = ''; + $sqlset[$i] = ''; + $x = 'status' . $i; + @list($tostat, $statval) = explode('_', (string) ($this->sxTaskSettings->{$x})); + if ($tostat >= 4 && $tostat <= 63) { + if ($statval == '0') { + $sqlset[$i] = 'status=status & ~(1<<' . $tostat . ')'; + $sqlwhere[$i] .= '(status & (1<<' . $tostat . ') = 0)'; + } elseif ($statval == '1') { + $sqlset[$i] = 'status=status|(1<<' . $tostat . ')'; + $sqlwhere[$i] .= '(status & (1<<' . $tostat . ') != 0)'; + } + } + $x = 'coll' . $i; + if (($tocoll = (string) ($this->sxTaskSettings->{$x})) != '') { + $sqlset[$i] .= ( $sqlset[$i] ? ', ' : '') . ('coll_id = :coll_id_set' . $i); + $sqlwhere[$i] .= ( $sqlwhere[$i] ? ' AND ' : '') . '(coll_id = :coll_id_where' . $i . ')'; + $tmp_params[':coll_id_set' . $i] = $tocoll; + $tmp_params[':coll_id_where' . $i] = $tocoll; + } + } + + if ($date1 && $sqlset[0]) { + $params = array(); + $params[':name1'] = $field1; + $params[':date1'] = $date1; + $params[':coll_id_set0'] = $tmp_params[':coll_id_set0']; + + $w = 'p1.name = :name1 AND :date1 <= p1.value'; + if ($sqlwhere[1] && $sqlwhere[2]) { + $w .= ' AND ((' . $sqlwhere[1] . ') OR (' . $sqlwhere[2] . '))'; + $params[':coll_id_where1'] = $tmp_params[':coll_id_where1']; + $params[':coll_id_where2'] = $tmp_params[':coll_id_where2']; + } else { + if ($sqlwhere[1]) { + $w .= ' AND ' . $sqlwhere[1]; + $params[':coll_id_where1'] = $tmp_params[':coll_id_where1']; + } elseif ($sqlwhere[2]) { + $w .= ' AND ' . $sqlwhere[2]; + $params[':coll_id_where2'] = $tmp_params[':coll_id_where2']; + } + } + + $sql = "UPDATE prop AS p1 INNER JOIN record USING(record_id)" + . " SET " . $sqlset[0] + . " WHERE " . $w; + + $ret[] = array('sql' => $sql, 'params' => $params); + } + + + if ($date1 && $date2) { + $params = array(); + $params[':name1'] = $field1; + $params[':name2'] = $field2; + $params[':date1'] = $date1; + $params[':date2'] = $date2; + $params[':coll_id_set1'] = $tmp_params[':coll_id_set1']; + + $w = 'p1.name = :name1 AND p2.name = :name2 AND :date1 > p1.value AND :date2 <= p2.value'; + if ($sqlwhere[0] && $sqlwhere[2]) { + $w .= ' AND ((' . $sqlwhere[0] . ') OR (' . $sqlwhere[2] . '))'; + $params[':coll_id_where0'] = $tmp_params[':coll_id_where0']; + $params[':coll_id_where2'] = $tmp_params[':coll_id_where2']; + } else { + if ($sqlwhere[0]) { + $w .= ' AND ' . $sqlwhere[0]; + $params[':coll_id_where0'] = $tmp_params[':coll_id_where0']; + } elseif ($sqlwhere[2]) { + $w .= ' AND ' . $sqlwhere[2]; + $params[':coll_id_where2'] = $tmp_params[':coll_id_where2']; + } + } + + $sql = "UPDATE (prop AS p1 INNER JOIN prop AS p2 USING(record_id))" + . " INNER JOIN record USING(record_id)" + . " SET " . $sqlset[1] + . " WHERE " . $w; + + $ret[] = array('sql' => $sql, 'params' => $params); + } + + + if ($date2 && $sqlset[2]) { + $params = array(); + $params[':name2'] = $field2; + $params[':date2'] = $date2; + $params[':coll_id_set2'] = $tmp_params[':coll_id_set2']; + + $w = 'p2.name = :name2 AND :date2 > p2.value'; + if ($sqlwhere[0] && $sqlwhere[1]) { + $w .= ' AND ((' . $sqlwhere[0] . ') OR (' . $sqlwhere[1] . '))'; + $params[':coll_id_where0'] = $tmp_params[':coll_id_where0']; + $params[':coll_id_where1'] = $tmp_params[':coll_id_where1']; + } else { + if ($sqlwhere[0]) { + $w .= ' AND ' . $sqlwhere[0]; + $params[':coll_id_where0'] = $tmp_params[':coll_id_where0']; + } elseif ($sqlwhere[1]) { + $w .= ' AND ' . $sqlwhere[1]; + $params[':coll_id_where1'] = $tmp_params[':coll_id_where1']; + } + } + + $sql = "UPDATE prop AS p2 INNER JOIN record USING(record_id)" + . " SET " . $sqlset[2] + . " WHERE " . $w; + + $ret[] = array('sql' => $sql, 'params' => $params); + } + + return($ret); } - // test : DATE 2 - if(($field2 = trim($this->sxTaskSettings->field2)) != '') + + public function facility() { - $date2 = time(); - if(($delta = (int) ($this->sxTaskSettings->fieldDv2)) > 0) - { - if($this->sxTaskSettings->fieldDs2 == '-') - $date2 += 86400 * $delta; - else - $date2 -= 86400 * $delta; - } - $date2 = date("YmdHis", $date2); - } + $ret = NULL; - - $sqlset = $params = $tmp_params = array(); - for($i = 0; $i <= 2; $i++) - { - $sqlwhere[$i] = ''; - $sqlset[$i] = ''; - $x = 'status' . $i; - @list($tostat, $statval) = explode('_', (string) ($this->sxTaskSettings->{$x})); - if($tostat >= 4 && $tostat <= 63) - { - if($statval == '0') - { - $sqlset[$i] = 'status=status & ~(1<<' . $tostat . ')'; - $sqlwhere[$i] .= '(status & (1<<' . $tostat . ') = 0)'; - } - elseif($statval == '1') - { - $sqlset[$i] = 'status=status|(1<<' . $tostat . ')'; - $sqlwhere[$i] .= '(status & (1<<' . $tostat . ') != 0)'; - } - } - $x = 'coll' . $i; - if(($tocoll = (string) ($this->sxTaskSettings->{$x})) != '') - { - $sqlset[$i] .= ( $sqlset[$i] ? ', ' : '') . ('coll_id = :coll_id_set' . $i); - $sqlwhere[$i] .= ( $sqlwhere[$i] ? ' AND ' : '') . '(coll_id = :coll_id_where' . $i . ')'; - $tmp_params[':coll_id_set' . $i] = $tocoll; - $tmp_params[':coll_id_where' . $i] = $tocoll; - } - } - - if($date1 && $sqlset[0]) - { - $params = array(); - $params[':name1'] = $field1; - $params[':date1'] = $date1; - $params[':coll_id_set0'] = $tmp_params[':coll_id_set0']; - - $w = 'p1.name = :name1 AND :date1 <= p1.value'; - if($sqlwhere[1] && $sqlwhere[2]) - { - $w .= ' AND ((' . $sqlwhere[1] . ') OR (' . $sqlwhere[2] . '))'; - $params[':coll_id_where1'] = $tmp_params[':coll_id_where1']; - $params[':coll_id_where2'] = $tmp_params[':coll_id_where2']; - } - else - { - if($sqlwhere[1]) - { - $w .= ' AND ' . $sqlwhere[1]; - $params[':coll_id_where1'] = $tmp_params[':coll_id_where1']; - } - elseif($sqlwhere[2]) - { - $w .= ' AND ' . $sqlwhere[2]; - $params[':coll_id_where2'] = $tmp_params[':coll_id_where2']; - } - } - - $sql = "UPDATE prop AS p1 INNER JOIN record USING(record_id) - SET " . $sqlset[0] . - " WHERE " . $w; - - $ret[] = array('sql'=>$sql, 'params'=>$params); - } - - - if($date1 && $date2) - { - $params = array(); - $params[':name1'] = $field1; - $params[':name2'] = $field2; - $params[':date1'] = $date1; - $params[':date2'] = $date2; - $params[':coll_id_set1'] = $tmp_params[':coll_id_set1']; - - $w = 'p1.name = :name1 AND p2.name = :name2 AND :date1 > p1.value AND :date2 <= p2.value'; - if($sqlwhere[0] && $sqlwhere[2]) - { - $w .= ' AND ((' . $sqlwhere[0] . ') OR (' . $sqlwhere[2] . '))'; - $params[':coll_id_where0'] = $tmp_params[':coll_id_where0']; - $params[':coll_id_where2'] = $tmp_params[':coll_id_where2']; - } - else - { - if($sqlwhere[0]) - { - $w .= ' AND ' . $sqlwhere[0]; - $params[':coll_id_where0'] = $tmp_params[':coll_id_where0']; - } - elseif($sqlwhere[2]) - { - $w .= ' AND ' . $sqlwhere[2]; - $params[':coll_id_where2'] = $tmp_params[':coll_id_where2']; - } - } - - $sql = "UPDATE (prop AS p1 INNER JOIN prop AS p2 USING(record_id)) - INNER JOIN record USING(record_id) - SET " . $sqlset[1] . - " WHERE " . $w; - - $ret[] = array('sql'=>$sql, 'params'=>$params); - } - - - if($date2 && $sqlset[2]) - { - $params = array(); - $params[':name2'] = $field2; - $params[':date2'] = $date2; - $params[':coll_id_set2'] = $tmp_params[':coll_id_set2']; - - $w = 'p2.name = :name2 AND :date2 > p2.value'; - if($sqlwhere[0] && $sqlwhere[1]) - { - $w .= ' AND ((' . $sqlwhere[0] . ') OR (' . $sqlwhere[1] . '))'; - $params[':coll_id_where0'] = $tmp_params[':coll_id_where0']; - $params[':coll_id_where1'] = $tmp_params[':coll_id_where1']; - } - else - { - if($sqlwhere[0]) - { - $w .= ' AND ' . $sqlwhere[0]; - $params[':coll_id_where0'] = $tmp_params[':coll_id_where0']; - } - elseif($sqlwhere[1]) - { - $w .= ' AND ' . $sqlwhere[1]; - $params[':coll_id_where1'] = $tmp_params[':coll_id_where1']; - } - } - - $sql = "UPDATE prop AS p2 INNER JOIN record USING(record_id) - SET " . $sqlset[2] . - " WHERE " . $w; - - $ret[] = array('sql'=>$sql, 'params'=>$params); - } - - return($ret); - } - - - - public function facility() - { - $ret = NULL; - - $request = http_request::getInstance(); - $parm2 = $request->get_parms( + $request = http_request::getInstance(); + $parm2 = $request->get_parms( 'ACT', 'bid' - ); + ); - phrasea::headers(200, true, 'application/json', 'UTF-8', false); - $ret = NULL; - switch($parm2['ACT']) - { - case 'CALCSQL': - $xml = $this->graphic2xml(''); - $sxml = simplexml_load_string($xml); - $ret = $this->calcSQL($sxml); - break; - case 'GETBASE': - $ret = array('date_fields' => array(), 'status_bits' => array(), 'collections' => array()); + phrasea::headers(200, true, 'application/json', 'UTF-8', false); + $ret = NULL; + switch ($parm2['ACT']) { + case 'CALCSQL': + $xml = $this->graphic2xml(''); + $sxml = simplexml_load_string($xml); + $ret = $this->calcSQL($sxml); + break; + case 'GETBASE': + $ret = array('date_fields' => array(), 'status_bits' => array(), 'collections' => array()); - if($parm2['bid'] != '') - { - $sbas_id = (int) $parm2['bid']; - try - { - $databox = databox::get_instance($sbas_id); - $meta_struct = $databox->get_meta_structure(); + if ($parm2['bid'] != '') { + $sbas_id = (int) $parm2['bid']; + try { + $databox = databox::get_instance($sbas_id); + $meta_struct = $databox->get_meta_structure(); - foreach($meta_struct as $meta) - { - if(mb_strtolower($meta->get_type()) == 'date') - $ret['date_fields'][] = $meta->get_name(); - } + foreach ($meta_struct as $meta) { + if (mb_strtolower($meta->get_type()) == 'date') + $ret['date_fields'][] = $meta->get_name(); + } - $status = $databox->get_statusbits(); - foreach($status as $n => $stat) - { - $labelon = $stat['labelon'] ? $stat['labelon'] : ($n . '-ON'); - $labeloff = $stat['labeloff'] ? $stat['labeloff'] : ($n . '-OFF'); - $ret['status_bits'][] = array('n' => $n, 'value' => 0, 'label' => $labeloff); - $ret['status_bits'][] = array('n' => $n, 'value' => 1, 'label' => $labelon); - } + $status = $databox->get_statusbits(); + foreach ($status as $n => $stat) { + $labelon = $stat['labelon'] ? $stat['labelon'] : ($n . '-ON'); + $labeloff = $stat['labeloff'] ? $stat['labeloff'] : ($n . '-OFF'); + $ret['status_bits'][] = array('n' => $n, 'value' => 0, 'label' => $labeloff); + $ret['status_bits'][] = array('n' => $n, 'value' => 1, 'label' => $labelon); + } - foreach($databox->get_collections() as $collection) - $ret['collections'][] = array('id' => $collection->get_coll_id(), 'name' => $collection->get_name()); - } - catch(Exception $e) - { + foreach ($databox->get_collections() as $collection) + $ret['collections'][] = array('id' => $collection->get_coll_id(), 'name' => $collection->get_name()); + } catch (Exception $e) { - } + } + } + break; } - break; + print(json_encode($ret)); } - print(json_encode($ret)); - } } - ?> diff --git a/lib/classes/task/period/subdef.class.php b/lib/classes/task/period/subdef.class.php index 60f89375b2..f2cb8167ff 100755 --- a/lib/classes/task/period/subdef.class.php +++ b/lib/classes/task/period/subdef.class.php @@ -78,7 +78,7 @@ class task_period_subdef extends task_databoxAbstract $ptype = substr($pname, 0, 3); $pname = substr($pname, 4); $pvalue = $parm2[$pname]; - if ($ns = $dom->getElementsByTagName($pname)->item(0)) { + if (($ns = $dom->getElementsByTagName($pname)->item(0))) { while (($n = $ns->firstChild)) $ns->removeChild($n); } else { @@ -215,105 +215,104 @@ class task_period_subdef extends task_databoxAbstract ?>

-  :  +  :  -
+

- '); ?> + '); ?>

-   +     Mo
- get_connection(); + public function retrieveSbasContent(databox $databox) + { + $connbas = $databox->get_connection(); - $sql = 'SELECT coll_id, record_id + $sql = 'SELECT coll_id, record_id FROM record WHERE jeton & ' . JETON_MAKE_SUBDEF . ' > 0 AND parent_record_id = 0 ORDER BY record_id DESC LIMIT 0, 20'; - $stmt = $connbas->prepare($sql); - $stmt->execute(); - $rs = $stmt->fetchAll(PDO::FETCH_ASSOC); - $stmt->closeCursor(); + $stmt = $connbas->prepare($sql); + $stmt->execute(); + $rs = $stmt->fetchAll(PDO::FETCH_ASSOC); + $stmt->closeCursor(); - return $rs; + return $rs; + } + + public function processOneContent(databox $databox, Array $row) + { + $record_id = $row['record_id']; + $this->log(sprintf( + "Generate subdefs for : sbas_id %s / record %s " + , $this->sbas_id, $record_id)); + $record = new record_adapter($this->sbas_id, $record_id); + + $record->generate_subdefs($databox, null, $this->debug); + + $this->recs_to_write[] = $record->get_record_id(); + + if (count($this->recs_to_write) >= $this->record_buffer_size) { + $this->flushRecordsSbas(); } + unset($record); - public function process_one_content(databox $databox, Array $row) - { - $record_id = $row['record_id']; - $this->log(sprintf( - "Generate subdefs for : sbas_id %s / record %s " - , $this->sbas_id, $record_id)); - $record = new record_adapter($this->sbas_id, $record_id); + return $this; + } - $record->generate_subdefs($databox, null, $this->debug); - - $this->recs_to_write[] = $record->get_record_id(); - - if (count($this->recs_to_write) >= $this->record_buffer_size) { - $this->flush_records_sbas(); - } - unset($record); - - return $this; - } - - protected function post_process_one_content(databox $databox, Array $row) - { - $connbas = $databox->get_connection(); - $sql = 'UPDATE record + protected function postProcessOneContent(databox $databox, Array $row) + { + $connbas = $databox->get_connection(); + $sql = 'UPDATE record SET jeton=(jeton & ~' . JETON_MAKE_SUBDEF . '), moddate=NOW() WHERE record_id=:record_id'; - $stmt = $connbas->prepare($sql); - $stmt->execute(array(':record_id' => $row['record_id'])); - $stmt->closeCursor(); + $stmt = $connbas->prepare($sql); + $stmt->execute(array(':record_id' => $row['record_id'])); + $stmt->closeCursor(); - return $this; - } + return $this; + } - protected function flush_records_sbas() - { - $sql = implode(', ', $this->recs_to_write); + protected function flushRecordsSbas() + { + $sql = implode(', ', $this->recs_to_write); - if ($sql != '') { - $this->log(sprintf( - 'setting %d record(s) to subdef meta writing' - , count($this->recs_to_write) - )); + if ($sql != '') { + $this->log(sprintf( + 'setting %d record(s) to subdef meta writing' + , count($this->recs_to_write) + )); - try { - $connbas = connection::getPDOConnection($this->sbas_id); - $sql = 'UPDATE record + try { + $connbas = connection::getPDOConnection($this->sbas_id); + $sql = 'UPDATE record SET status=(status & ~0x03), jeton=(jeton | ' . JETON_WRITE_META_SUBDEF . ') WHERE record_id IN (' . $sql . ')'; - $stmt = $connbas->prepare($sql); - $stmt->execute(); - $stmt->closeCursor(); - } catch (Exception $e) { - $this->log($e->getMessage()); - } + $stmt = $connbas->prepare($sql); + $stmt->execute(); + $stmt->closeCursor(); + } catch (Exception $e) { + $this->log($e->getMessage()); } - $this->recs_to_write = array(); - - return $this; } - } + $this->recs_to_write = array(); + + return $this; + } +} - \ No newline at end of file diff --git a/lib/classes/task/period/workflow01.class.php b/lib/classes/task/period/workflow01.class.php index 872b56bac2..8ae16bd513 100755 --- a/lib/classes/task/period/workflow01.class.php +++ b/lib/classes/task/period/workflow01.class.php @@ -17,529 +17,480 @@ class task_period_workflow01 extends task_databoxAbstract { - public function getName() - { - return(_('task::workflow01')); - } - - public function graphic2xml($oldxml) - { - $request = http_request::getInstance(); - - $parm2 = $request->get_parms( - "sbas_id" - , "period" - , 'status0' - , 'coll0' - , 'status1' - , 'coll1' - ); - $dom = new DOMDocument(); - $dom->preserveWhiteSpace = false; - $dom->formatOutput = true; - if ($dom->loadXML($oldxml)) + public function getName() { - $xmlchanged = false; - // foreach($parm2 as $pname=>$pvalue) - foreach (array( - "str:sbas_id", - "str:period", - 'str:status0', - 'str:coll0', - 'str:status1', - 'str:coll1', - ) as $pname) - { - $ptype = substr($pname, 0, 3); - $pname = substr($pname, 4); - $pvalue = $parm2[$pname]; - if ($ns = $dom->getElementsByTagName($pname)->item(0)) - { - // le champ existait dans le xml, on supprime son ancienne valeur (tout le contenu) - while (($n = $ns->firstChild)) - $ns->removeChild($n); - } - else - { - // le champ n'existait pas dans le xml, on le cree - $dom->documentElement->appendChild($dom->createTextNode("\t")); - $ns = $dom->documentElement->appendChild($dom->createElement($pname)); - $dom->documentElement->appendChild($dom->createTextNode("\n")); - } - // on fixe sa valeur - switch ($ptype) - { - case "str": - $ns->appendChild($dom->createTextNode($pvalue)); - break; - case "boo": - $ns->appendChild($dom->createTextNode($pvalue ? '1' : '0')); - break; - } - $xmlchanged = true; - } + return(_('task::workflow01')); } - return($dom->saveXML()); - } - - public function xml2graphic($xml, $form) - { - if (($sxml = simplexml_load_string($xml))) // in fact XML IS always valid here... + public function graphic2xml($oldxml) { - // ... but we could check for safe values - if ((int) ($sxml->period) < 1) - $sxml->period = 1; - elseif ((int) ($sxml->period) > 1440) // 1 jour - $sxml->period = 1440; + $request = http_request::getInstance(); - if ((string) ($sxml->delay) == '') - $sxml->delay = 0; -?> - -saveXML()); } - else // ... so we NEVER come here + + public function xml2graphic($xml, $form) { - // bad xml - return("BAD XML"); + if (($sxml = simplexml_load_string($xml))) { // in fact XML IS always valid here... + // ... but we could check for safe values + if ((int) ($sxml->period) < 1) + $sxml->period = 1; + elseif ((int) ($sxml->period) > 1440) // 1 jour + $sxml->period = 1440; + + if ((string) ($sxml->delay) == '') + $sxml->delay = 0; + ?> + + - - - + get_session(); + $user = User_Adapter::getInstance($session->get_usr_id(), $appbox); + ob_start(); + ?> +
+  :  + + - function chgxmltxt(textinput, fieldname) - { - var limits = { 'period':{min:1, 'max':1440} , 'delay':{min:0} } ; - if(typeof(limits[fieldname])!='undefined') - { - var v = 0|textinput.value; - if(limits[fieldname].min && v < limits[fieldname].min) - v = limits[fieldname].min; - else if(limits[fieldname].max && v > limits[fieldname].max) - v = limits[fieldname].max; - textinput.value = v; +   + +
+
+ +  :  + +
+
+ + + + + + + + + + + + + +
+ Collection : + + + +   ====>   + + +
+ Status : + + + + +
+
+
+
+
cmd
+
+ status_origine = (string) $sx_task_settings->status0; + $this->status_destination = (string) $sx_task_settings->status1; + + $this->coll_origine = (int) $sx_task_settings->coll0; + $this->coll_destination = (int) $sx_task_settings->coll1; + + parent::loadSettings($sx_task_settings); + + $this->mono_sbas_id = (int) $sx_task_settings->sbas_id; + // in minutes + $this->period = (int) $sx_task_settings->period * 60; + + if ($this->period <= 0 || $this->period >= 24 * 60) + $this->period = 60; + } + + protected function retrieveSbasContent(databox $databox) + { + static $firstCall = true; + + $connbas = $databox->get_connection(); + + $sql_s = $sql_w = ''; + $sql_parms = array(); + if ($this->coll_origine != '') { + $sql_w .= ($sql_w ? ' AND ' : '') + . '(coll_id=:coll_org)'; + $sql_parms[':coll_org'] = $this->coll_origine; + } + if ($this->status_origine != '') { + $x = explode('_', $this->status_origine); + if (count($x) !== 2) + throw new Exception('Error in settings for status origine'); + $sql_w .= ($sql_w ? ' AND ' : '') + . '((status >> :stat_org_n & 1) = :stat_org_v)'; + $sql_parms[':stat_org_n'] = $x[0]; + $sql_parms[':stat_org_v'] = $x[1]; + } + if ($this->coll_destination != '') { + $sql_s .= ($sql_s ? ', ' : '') + . 'coll_id=:coll_dst'; + $sql_parms[':coll_dst'] = $this->coll_destination; + } + if ($this->status_destination != '') { + $x = explode('_', $this->status_destination); + if (count($x) !== 2) + throw new Exception('Error in settings for status destination'); + $sql_s .= ($sql_s ? ', ' : ''); + if ((int) $x[1] === 0) + $sql_s .= 'status = status &~(1 << :stat_dst)'; + else + $sql_s .= 'status = status |(1 << :stat_dst)'; + $sql_parms[':stat_dst'] = (int) $x[0]; } - setDirty(); - calccmd(); - } - function chgxmlck(checkinput, fieldname) - { - setDirty(); - calccmd(); - } - function chgxmlpopup(popupinput, fieldname) - { - setDirty(); - calccmd(); - } - function chgsbas(sbaspopup) - { - for(fld=0; fld<=1; fld++) - { - var p = document.getElementById("status"+fld); - while( (f=p.firstChild) ) - p.removeChild(f); - var o = p.appendChild(document.createElement('option')); - o.setAttribute('value', ''); - o.appendChild(document.createTextNode("...")); - var p = document.getElementById("coll"+fld); - while( (f=p.firstChild) ) - p.removeChild(f); - var o = p.appendChild(document.createElement('option')); - o.setAttribute('value', ''); - o.appendChild(document.createTextNode("...")); - } - if(sbaspopup.value > 0) - { - $.ajax({ - url:"/admin/taskfacility.php" - , async:false - , data:{'cls':'workflow01', 'taskid':get_task_id() ?>, 'bid':sbaspopup.value} - , success:function(data){ - for(fld=0; fld<=1; fld++) - { - var p = document.getElementById("status"+fld); - for(i in data.status_bits) - { - var o = p.appendChild(document.createElement('option')); - o.setAttribute('value', data.status_bits[i].n + "_" + data.status_bits[i].value); - o.appendChild(document.createTextNode(data.status_bits[i].label)); - o.setAttribute('class', "jsFilled"); - } - } + if ($sql_w && $sql_s) { + $sql = 'UPDATE record SET ' . $sql_s . ' WHERE ' . $sql_w; + $stmt = $connbas->prepare($sql); + $stmt->execute($sql_parms); - for(fld=0; fld<=1; fld++) - { - var p = document.getElementById("coll"+fld); - for(i in data.collections) - { - var o = p.appendChild(document.createElement('option')); - o.setAttribute('value', ""+data.collections[i].id); - o.appendChild(document.createTextNode(data.collections[i].name)); - o.setAttribute('class', "jsFilled"); - } - } - }}); - } - calccmd(); - } - -rowCount() != 0) { + $this->log(sprintf(("SQL=%s\n (parms=%s)\n - %s changes"), str_replace(array("\r\n", "\n", "\r", "\t"), " ", $sql) + , str_replace(array("\r\n", "\n", "\r", "\t"), " ", var_export($sql_parms, true)) + , $stmt->rowCount())); + $firstCall = false; + } + $stmt->closeCursor(); + } - function getGraphicForm() - { - return true; - } - - public function printInterfaceHTML() - { - $appbox = appbox::get_instance(\bootstrap::getCore()); - $session = $appbox->get_session(); - $user = User_Adapter::getInstance($session->get_usr_id(), $appbox); - ob_start(); -?> -
-  :  - - -   - -
-
- -  :  - -
-
- - - - - - - - - - - - - -
- Collection : - - - -   ====>   - - -
- Status : - - - - -
-
-
-
-
cmd
-
-status_origine = (string) $sx_task_settings->status0; - $this->status_destination = (string) $sx_task_settings->status1; - - $this->coll_origine = (int) $sx_task_settings->coll0; - $this->coll_destination = (int) $sx_task_settings->coll1; - - parent::load_settings($sx_task_settings); - - $this->mono_sbas_id = (int) $sx_task_settings->sbas_id; - // in minutes - $this->period = (int) $sx_task_settings->period * 60; - - if ($this->period <= 0 || $this->period >= 24 * 60) - $this->period = 60; - - return $this; - } - - protected function retrieve_sbas_content(databox $databox) - { - static $firstCall = true; - - $connbas = $databox->get_connection(); - - $sql_s = $sql_w = ''; - $sql_parms = array(); - if($this->coll_origine != '') - { - $sql_w .= ($sql_w?' AND ':'') - .'(coll_id=:coll_org)'; - $sql_parms[':coll_org'] = $this->coll_origine; - } - if($this->status_origine != '') - { - $x = explode('_', $this->status_origine); - if (count($x) !== 2) - throw new Exception('Error in settings for status origine'); - $sql_w .= ($sql_w?' AND ':'') - .'((status >> :stat_org_n & 1) = :stat_org_v)'; - $sql_parms[':stat_org_n'] = $x[0]; - $sql_parms[':stat_org_v'] = $x[1]; - } - if($this->coll_destination != '') - { - $sql_s .= ($sql_s?', ':'') - .'coll_id=:coll_dst'; - $sql_parms[':coll_dst'] = $this->coll_destination; - } - if($this->status_destination != '') - { - $x = explode('_', $this->status_destination); - if (count($x) !== 2) - throw new Exception('Error in settings for status destination'); - $sql_s .= ($sql_s?', ':''); - if((int)$x[1] === 0) - $sql_s .= 'status = status &~(1 << :stat_dst)'; - else - $sql_s .= 'status = status |(1 << :stat_dst)'; - $sql_parms[':stat_dst'] = (int)$x[0]; - } - - if($sql_w && $sql_s) - { - $sql = 'UPDATE record SET ' . $sql_s . ' WHERE ' . $sql_w; - $stmt = $connbas->prepare($sql); - $stmt->execute($sql_parms); - - if($firstCall || $stmt->rowCount() != 0) - { - $this->log(sprintf(("SQL=%s\n (parms=%s)\n - %s changes"), - str_replace(array("\r\n","\n","\r", "\t"), " ", $sql) - , str_replace(array("\r\n","\n","\r","\t"), " ", var_export($sql_parms, true)) - , $stmt->rowCount())); - $firstCall = false; - } - $stmt->closeCursor(); - } - - return array(); - } - - protected function process_one_content(databox $databox, Array $row) - { - return $this; - } - - protected function flush_records_sbas() - { - return $this; - } - - protected function post_process_one_content(databox $databox, Array $row) - { - return $this; - } - - public function facility() - { - $request = http_request::getInstance(); - - $appbox = appbox::get_instance(\bootstrap::getCore()); - $session = $appbox->get_session(); - $user = User_Adapter::getInstance($session->get_usr_id(), $appbox); - - $parm = $request->get_parms("bid"); - - phrasea::headers(200, true, 'text/json', 'UTF-8', false); - - $ret = new DOMDocument("1.0", "UTF-8"); - $ret->standalone = true; - $ret->preserveWhiteSpace = false; - - $retjs = array('result'=>NULL, - 'date_fields'=>array(), - 'status_bits'=>array(), - 'collections'=>array() - ); - - $element = $ret->createElement('result'); - - $root = $ret->appendChild($element); - $root->appendChild($ret->createCDATASection(var_export($parm, true))); - $dfields = $root->appendChild($ret->createElement("date_fields")); - $statbits = $root->appendChild($ret->createElement("status_bits")); - $coll = $root->appendChild($ret->createElement("collections")); - - $sbas_id = (int)$parm['bid']; - try + protected function processOneContent(databox $databox, Array $row) { - $databox = databox::get_instance($sbas_id); - foreach ($databox->get_meta_structure() as $meta) - { - if ($meta->get_type() !== 'date') - continue; - $dfields->appendChild($ret->createElement("field")) - ->appendChild($ret->createTextNode($meta->get_name())); - $retjs['date_fields'][] = $meta->get_name(); - } - - $status = $databox->get_statusbits(); - - foreach ($status as $n => $s) - { - $node = $statbits->appendChild($ret->createElement("bit")); - $node->setAttribute('n', $n); - $node->setAttribute('value', '0'); - $node->setAttribute('label', $s['labeloff']); - $node->appendChild($ret->createTextNode($s['labeloff'])); - $node = $statbits->appendChild($ret->createElement("bit")); - $node->setAttribute('n', $n); - $node->setAttribute('value', '1'); - $node->setAttribute('label', $s['labelon']); - $node->appendChild($ret->createTextNode($s['labelon'])); - - $retjs['status_bits'][] = array( - 'n'=>$n, - 'value'=>0, - 'label'=>$s['labeloff'] ? $s['labeloff'] : 'non '.$s['name'] ); - $retjs['status_bits'][] = array( - 'n'=>$n, - 'value'=>1, - 'label'=>$s['labelon'] ? $s['labelon'] : $s['name'] ); - } - - $base_ids = $user->ACL()->get_granted_base(array(), array($sbas_id)); - - foreach ($base_ids as $base_id=>$collection) - { - $node = $coll->appendChild($ret->createElement("collection")); - $node->setAttribute('id', $collection->get_coll_id()); - $node->appendChild($ret->createTextNode($collection->get_name())); - - $retjs['collections'][] = array('id'=>(string)($collection->get_coll_id()), 'name'=>$collection->get_name()); - } + return $this; } - catch (Exception $e) + + protected function flushRecordsSbas() { - + return $this; + } + + protected function postProcessOneContent(databox $databox, Array $row) + { + return $this; + } + + public function facility() + { + $request = http_request::getInstance(); + + $appbox = appbox::get_instance(\bootstrap::getCore()); + $session = $appbox->get_session(); + $user = User_Adapter::getInstance($session->get_usr_id(), $appbox); + + $parm = $request->get_parms("bid"); + + phrasea::headers(200, true, 'text/json', 'UTF-8', false); + + $retjs = array('result' => NULL, + 'date_fields' => array(), + 'status_bits' => array(), + 'collections' => array() + ); + + $sbas_id = (int) $parm['bid']; + try { + $databox = databox::get_instance($sbas_id); + foreach ($databox->get_meta_structure() as $meta) { + if ($meta->get_type() !== 'date') + continue; + $retjs['date_fields'][] = $meta->get_name(); + } + + $status = $databox->get_statusbits(); + + foreach ($status as $n => $s) { + $retjs['status_bits'][] = array( + 'n' => $n, + 'value' => 0, + 'label' => $s['labeloff'] ? $s['labeloff'] : 'non ' . $s['name']); + $retjs['status_bits'][] = array( + 'n' => $n, + 'value' => 1, + 'label' => $s['labelon'] ? $s['labelon'] : $s['name']); + } + + $base_ids = $user->ACL()->get_granted_base(array(), array($sbas_id)); + foreach ($base_ids as $base_id => $collection) { + $retjs['collections'][] = array('id' => (string) ($collection->get_coll_id()), 'name' => $collection->get_name()); + } + } catch (Exception $e) { + + } + return p4string::jsonencode($retjs); } - return p4string::jsonencode($retjs); - } } diff --git a/lib/classes/task/period/writemeta.class.php b/lib/classes/task/period/writemeta.class.php index 6910851b25..40341d0621 100644 --- a/lib/classes/task/period/writemeta.class.php +++ b/lib/classes/task/period/writemeta.class.php @@ -23,6 +23,7 @@ use PHPExiftool\Writer; class task_period_writemeta extends task_databoxAbstract { protected $clear_doc; + protected $metasubdefs = array(); function help() @@ -30,12 +31,10 @@ class task_period_writemeta extends task_databoxAbstract return(_("task::writemeta:(re)ecriture des metadatas dans les documents (et subdefs concernees)")); } - protected function load_settings(SimpleXMLElement $sx_task_settings) + protected function loadSettings(SimpleXMLElement $sx_task_settings) { $this->clear_doc = p4field::isyes($sx_task_settings->cleardoc); - parent::load_settings($sx_task_settings); - - return $this; + parent::loadSettings($sx_task_settings); } public function getName() @@ -118,7 +117,6 @@ class task_period_writemeta extends task_databoxAbstract .maxmegs.value = "maxmegs, "js", '"') ?>"; get_connection(); $subdefgroups = $databox->get_subdef_structure(); @@ -239,7 +237,7 @@ class task_period_writemeta extends task_databoxAbstract return $rs; } - protected function process_one_content(databox $databox, Array $row) + protected function processOneContent(databox $databox, Array $row) { $record_id = $row['record_id']; $jeton = $row['jeton']; @@ -327,12 +325,12 @@ class task_period_writemeta extends task_databoxAbstract return $this; } - protected function flush_records_sbas() + protected function flushRecordsSbas() { return $this; } - protected function post_process_one_content(databox $databox, Array $row) + protected function postProcessOneContent(databox $databox, Array $row) { $connbas = $databox->get_connection(); diff --git a/templates/web/admin/task.html b/templates/web/admin/task.html index 008f3f7044..3872d4ba27 100644 --- a/templates/web/admin/task.html +++ b/templates/web/admin/task.html @@ -166,7 +166,7 @@ currentView : null, - oldXML:"{{task.get_settings()|stripdoublequotes}}", + oldXML:"{{task.getSettings()|stripdoublequotes}}", view:function(type) { @@ -300,7 +300,7 @@ }; } - var url = "/admin/adminFeedback.php?action=RESETTASKCRASHCOUNTER&task_id={{task.get_task_id()}}"; + var url = "/admin/adminFeedback.php?action=RESETTASKCRASHCOUNTER&task_id={{task.getID()}}"; this.resetCrashCounter.x.xmlhttp.onreadystatechange = this.resetCrashCounter.x.cb; // ping_stateChange; this.resetCrashCounter.x.xmlhttp.open("POST", url, true); this.resetCrashCounter.x.xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); @@ -356,7 +356,7 @@ o.setAttribute("id", "__gtid"); o.setAttribute("name", "__tid"); o.setAttribute("type", "hidden"); - o.setAttribute("value", "{{task.get_task_id()}}"); + o.setAttribute("value", "{{task.getID()}}"); f.appendChild(o); } redrawme(); @@ -380,15 +380,15 @@
-

{{task.getName()}} id : {{task.get_task_id()}}

+

{{task.getName()}} id : {{task.getID()}}

- - + +
-
- {% trans 'admin::tasks: Nombre de crashes : ' %} {{task.get_crash_counter()}} +
+ {% trans 'admin::tasks: Nombre de crashes : ' %} {{task.getCrashCounter()}} {% trans 'admin::tasks: reinitialiser el compteur de crashes' %} @@ -422,10 +422,10 @@
- + - +
diff --git a/tests/module/console/module_console_schedulerStateTest.php b/tests/module/console/module_console_schedulerStateTest.php index 59eb190023..ee01841d89 100644 --- a/tests/module/console/module_console_schedulerStateTest.php +++ b/tests/module/console/module_console_schedulerStateTest.php @@ -19,7 +19,7 @@ class module_console_schedulerStateTest extends PHPUnit_Framework_TestCase $commandTester->execute(array('command' => $command->getName())); $task_manager = new task_manager(appbox::get_instance(\bootstrap::getCore())); - $state = $task_manager->get_scheduler_state(); + $state = $task_manager->getSchedulerState(); $sentence = sprintf('Scheduler is %s', $state['status']); $this->assertTrue(strpos($commandTester->getDisplay(), $sentence) !== false); diff --git a/tests/module/console/module_console_taskStateTest.php b/tests/module/console/module_console_taskStateTest.php new file mode 100644 index 0000000000..8ae3d597f1 --- /dev/null +++ b/tests/module/console/module_console_taskStateTest.php @@ -0,0 +1,68 @@ +add(new module_console_taskState('system:taskState')); + + $command = $application->find('system:taskState'); + $commandTester = new CommandTester($command); + + // test a bad argument + $commandTester->execute(array('command' => $command->getName(), 'task_id' => 'not_a_number')); + $sentence = 'Argument must be an ID'; + $this->assertTrue(strpos($commandTester->getDisplay(), $sentence) !== false); + + $commandTester->execute(array('command' => $command->getName(), 'task_id' => 'not_a_number', '--short' => true)); + $sentence = 'bad_id'; + $this->assertTrue(strpos($commandTester->getDisplay(), $sentence) !== false); + + // test good tasks ids + $task_manager = new task_manager(appbox::get_instance(\bootstrap::getCore())); + $tasks = $task_manager->getTasks(); + $tids = array(); // list known ids of tasks so we can generate a 'unknown id' later + foreach ($tasks as $task) { + $tids[] = $task->getID(); + $task = $task_manager->getTask($task->getID()); + $state = $task->getState(); + $pid = $task->getPID(); + + $commandTester->execute(array('command' => $command->getName(), 'task_id' => $task->getID())); + $sentence = sprintf('Task %d is %s', $task->getID(), $state); + $this->assertTrue(strpos($commandTester->getDisplay(), $sentence) !== false); + + $commandTester->execute(array('command' => $command->getName(), 'task_id' => $task->getID(), '--short' => true)); + $sentence = sprintf('%s(%s)', $state, ($pid !== NULL ? $pid : '')); + $this->assertTrue(strpos($commandTester->getDisplay(), $sentence) !== false); + } + + // test an unknown id + for ($badid = 999; in_array($badid, $tids); $badid += 10) { + ; + } + /* we may not test the 'long' error message since it comes from the upper level exception and might be translated + $commandTester->execute(array('command' => $command->getName(), 'task_id' => $badid)); + $sentence = sprintf('Unknown task_id %d', $task->getID()); + $this->assertTrue(strpos($commandTester->getDisplay(), $sentence) !== false); + */ + $commandTester->execute(array('command' => $command->getName(), 'task_id' => $badid, '--short' => true)); + $sentence = 'unknown_id'; + $this->assertTrue(strpos($commandTester->getDisplay(), $sentence) !== false); + + } +} + +?> diff --git a/tests/module/console/module_console_tasklistTest.php b/tests/module/console/module_console_tasklistTest.php index 584bb49b84..59314a2003 100644 --- a/tests/module/console/module_console_tasklistTest.php +++ b/tests/module/console/module_console_tasklistTest.php @@ -24,13 +24,13 @@ class module_console_tasklistTest extends PHPUnit_Framework_TestCase $task_manager = new task_manager(appbox::get_instance(\bootstrap::getCore())); $lines = explode("\n", trim($commandTester->getDisplay())); - if (count($task_manager->get_tasks()) > 0) { - $this->assertEquals(count($task_manager->get_tasks()), count($lines)); - foreach ($task_manager->get_tasks() as $task) { + if (count($task_manager->getTasks()) > 0) { + $this->assertEquals(count($task_manager->getTasks()), count($lines)); + foreach ($task_manager->getTasks() as $task) { $this->assertTrue(strpos($commandTester->getDisplay(), $task->get_title()) !== false); } } else { - $this->assertEquals(1, $n_lines); + $this->assertEquals(1, count($lines)); } } } diff --git a/www/admin/adminFeedback.php b/www/admin/adminFeedback.php index f169a0baca..e6d274b1f8 100755 --- a/www/admin/adminFeedback.php +++ b/www/admin/adminFeedback.php @@ -130,9 +130,9 @@ switch ($parm['action']) try { $task_manager = new task_manager($appbox); - $task = $task_manager->get_task($parm['task_id']); - $pid = (int)($task->get_pid()); - $task->set_status($parm["status"]); + $task = $task_manager->getTask($parm['task_id']); + $pid = (int)($task->getPID()); + $task->setState($parm["status"]); $signal = (int)($parm['signal']); if( $signal > 0 && $pid ) posix_kill($pid, $signal); @@ -150,7 +150,7 @@ switch ($parm['action']) { $task_manager = new task_manager($appbox); - $task_manager->set_sched_status($parm['status']); + $task_manager->setSchedulerState($parm['status']); } catch (Exception $e) { @@ -163,8 +163,8 @@ switch ($parm['action']) try { $task_manager = new task_manager($appbox); - $task = $task_manager->get_task($parm['task_id']); - $task->reset_crash_counter(); + $task = $task_manager->getTask($parm['task_id']); + $task->resetCrashCounter(); } catch (Exception $e) { @@ -191,11 +191,11 @@ switch ($parm['action']) try { $task_manager = new task_manager($appbox); - $task = $task_manager->get_task($parm["task_id"]); + $task = $task_manager->getTask($parm["task_id"]); /** * @todo checker, cette methode n'est pas implementee partout */ - $root->setAttribute("crashed", $task->get_crash_counter()); + $root->setAttribute("crashed", $task->getCrashCounter()); if ($task->saveChanges($conn, $parm["task_id"], $row)) $root->setAttribute("saved", "1"); } @@ -210,24 +210,24 @@ switch ($parm['action']) $ret = array('time'=> date("H:i:s") ); $task_manager = new task_manager($appbox); - $ret['scheduler'] = $task_manager->get_scheduler_state(); + $ret['scheduler'] = $task_manager->getSchedulerState(); $ret['tasks'] = array(); - foreach ($task_manager->get_tasks(true) as $task) + foreach ($task_manager->getTasks(true) as $task) { - if($task->get_status()==task_abstract::STATUS_TOSTOP && $task->get_pid()===NULL) + if($task->getState()==task_abstract::STATUS_TOSTOP && $task->getPID()===NULL) { // fix - $task->set_status(task_abstract::STATUS_STOPPED); + $task->setState(task_abstract::STATUS_STOPPED); } - $id = $task->get_task_id(); + $id = $task->getID(); $ret['tasks'][$id] = array( 'id'=>$id - , 'pid' =>$task->get_pid() - , 'crashed'=>$task->get_crash_counter() - , 'completed'=>$task->get_completed_percentage() - , 'status'=>$task->get_status() + , 'pid' =>$task->getPID() + , 'crashed'=>$task->getCrashCounter() + , 'completed'=>$task->getCompletedPercentage() + , 'status'=>$task->getState() ); } diff --git a/www/admin/task2.php b/www/admin/task2.php index 5f9d0b4a3f..f67686c317 100644 --- a/www/admin/task2.php +++ b/www/admin/task2.php @@ -43,7 +43,7 @@ try { $task = task_abstract::create($appbox, $parm['tcl']); break; case 'EDITTASK': // existing task - $task = $task_manager->get_task($parm['tid']); + $task = $task_manager->getTask($parm['tid']); break; default: throw new Exception('Unknown action'); diff --git a/www/admin/task2utils.php b/www/admin/task2utils.php index dffcf7aa7c..20f064ba3a 100644 --- a/www/admin/task2utils.php +++ b/www/admin/task2utils.php @@ -36,7 +36,7 @@ phrasea::headers(); get_task($parm['__tid']); + $ztask = $task_manager->getTask($parm['__tid']); switch ($parm['__act']) { case 'FORM2XML': if (method_exists($ztask, 'printInterfaceHTML')) { @@ -117,11 +117,11 @@ phrasea::headers(); } $task_manager = new task_manager($appbox); $tid = $parm['__tid']; - $task = $task_manager->get_task($tid); + $task = $task_manager->getTask($tid); - $task->set_active($parm['__tactive']); - $task->set_title($parm['__tname']); - $task->set_settings($parm['txtareaxml']); + $task->setActive($parm['__tactive']); + $task->setTitle($parm['__tname']); + $task->setSettings($parm['txtareaxml']); ?> - +

-'); ?> + '); ?>

@@ -381,12 +381,12 @@ foreach ($tasks as $t) {   TaskManager -get_tasks($refresh_tasklist) as $task) { - $n ++; - $tid = $task->get_task_id() - ?> + getTasks($refresh_tasklist) as $task) { + $n ++; + $tid = $task->getID() + ?> @@ -403,11 +403,11 @@ foreach ($task_manager->get_tasks($refresh_tasklist) as $task) {
- get_title()) ?> [] + getTitle()) ?> [] - + @@ -415,7 +415,7 @@ foreach ($task_manager->get_tasks($refresh_tasklist) as $task) { - + @@ -426,7 +426,7 @@ foreach ($task_manager->get_tasks($refresh_tasklist) as $task) { --> - +