new task workflow02

fix bugs
This commit is contained in:
jygaulier
2012-06-04 16:44:59 +02:00
parent 969fed45d6
commit 893324dfcd
18 changed files with 964 additions and 193 deletions

View File

@@ -59,7 +59,7 @@ class module_console_taskrun extends Command
{
if ($this->task) {
$this->task->log(sprintf("signal %s received", $signo));
if ($signo == SIGTERM) {
if ($signo == SIGTERM || $signo == SIGINT) {
$this->task->setRunning(false);
}
}
@@ -113,7 +113,6 @@ class module_console_taskrun extends Command
$logfile = __DIR__ . '/../../../../logs/task_' . $task_id . '.log';
$handler = new Handler\RotatingFileHandler($logfile, 10);
$logger->pushHandler($handler);
$this->task = $task_manager->getTask($task_id, $logger);
register_tick_function(array($this, 'tick_handler'), true);
@@ -121,6 +120,8 @@ class module_console_taskrun extends Command
if (function_exists('pcntl_signal')) {
pcntl_signal(SIGTERM, array($this, 'sig_handler'));
pcntl_signal(SIGINT, array($this, 'sig_handler'));
// pcntl_signal(SIGKILL, array($this, 'sig_handler'));
}
try {

View File

@@ -97,7 +97,8 @@ abstract class task_abstract
protected $taskid = NULL;
protected $system = ''; // "DARWIN", "WINDOWS" , "LINUX"...
protected $argt = array(
"--help" => array("set" => false, "values" => array(), "usage" => " (no help available)")
"--help" => array(
'set' => false, "values" => array(), "usage" => " (no help available)")
);
/**
@@ -107,51 +108,45 @@ abstract class task_abstract
*/
public function getState()
{
static $stmt = NULL;
$conn = connection::getPDOConnection();
if ( ! $stmt) {
$sql = 'SELECT status FROM task2 WHERE task_id = :taskid';
$stmt = $conn->prepare($sql);
}
$stmt->execute(array(':taskid' => $this->taskid));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$stmt->closeCursor();
if ( ! $row) {
throw new Exception('Unknown task id');
}
unset($conn);
return $row['status'];
}
/**
* to be overwritten by tasks : echo text to be included in <head> in task interface
* to be overwritten by tasks : ECHO text to be included in <head> in task interface
*/
public function printInterfaceHEAD()
{
return false;
}
/**
* to be overwritten by tasks : echo javascript to be included in <head> in task interface
* to be overwritten by tasks : ECHO javascript to be included in <head> in task interface
*/
public function printInterfaceJS()
{
return false;
}
/**
*
* @return boolean
*/
public function printInterfaceHTML()
public function hasInterfaceHTML()
{
return false;
}
/**
*
* @return boolean
*/
public function getGraphicForm()
{
return false;
return method_exists($this, "getInterfaceHTML");
}
/**
@@ -163,12 +158,12 @@ abstract class task_abstract
public function setState($status)
{
$av_status = array(
self::STATE_STARTED
, self::STATE_TOSTOP
, self::STATE_STOPPED
, self::STATE_TORESTART
, self::STATE_TOSTART
, self::STATE_TODELETE
self::STATE_STARTED,
self::STATE_TOSTOP,
self::STATE_STOPPED,
self::STATE_TORESTART,
self::STATE_TOSTART,
self::STATE_TODELETE
);
if ( ! in_array($status, $av_status)) {
@@ -184,21 +179,30 @@ abstract class task_abstract
$this->log(sprintf("task %d <- %s", $this->getID(), $status));
}
// 'active' means 'auto-start when scheduler starts'
public function setActive($boolean)
/**
*
* @param boolean $active 'active' means 'auto-start when scheduler starts'
* @return \task_abstract
*/
public function setActive($active)
{
$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->getID()));
$stmt->execute(array(':active' => ($active ? '1' : '0'), ':taskid' => $this->getID()));
$stmt->closeCursor();
$this->active = ! ! $boolean;
$this->active = ! ! $active;
return $this;
}
/**
*
* @param string $title
* @return \task_abstract
*/
public function setTitle($title)
{
$title = strip_tags($title);
@@ -214,6 +218,12 @@ abstract class task_abstract
return $this;
}
/**
*
* @param string $settings xml settings as STRING
* @throws Exception_InvalidArgument if not proper xml
* @return \task_abstract
*/
public function setSettings($settings)
{
if (@simplexml_load_string($settings) === FALSE) {
@@ -230,8 +240,14 @@ abstract class task_abstract
$this->settings = $settings;
$this->loadSettings(simplexml_load_string($settings));
return $this;
}
/**
*
* @return \task_abstract
*/
public function resetCrashCounter()
{
$conn = connection::getPDOConnection();
@@ -246,11 +262,19 @@ abstract class task_abstract
return $this;
}
/**
*
* @return int
*/
public function getCrashCounter()
{
return $this->crash_counter;
}
/**
*
* @return int
*/
public function incrementCrashCounter()
{
$conn = connection::getPDOConnection();
@@ -260,20 +284,32 @@ abstract class task_abstract
$stmt->execute(array(':taskid' => $this->getID()));
$stmt->closeCursor();
return $this->crash_counter ++;
return ++ $this->crash_counter;
}
/**
*
* @return string
*/
public function getSettings()
{
return $this->settings;
}
// 'active' means 'auto-start when scheduler starts'
/**
*
* @return boolean
* 'active' means 'auto-start when scheduler starts'
*/
public function isActive()
{
return $this->active;
}
/**
*
* @return int
*/
public function getCompletedPercentage()
{
return $this->completed_percentage;
@@ -319,15 +355,30 @@ abstract class task_abstract
$this->active = ! ! $row['active'];
$this->settings = $row['settings'];
$this->runner = $row['runner'];
$this->completed_percentage = (integer) $row['completed'];
$this->loadSettings(simplexml_load_string($row['settings']));
$this->completed_percentage = (int) $row['completed'];
$this->settings = $row['settings'];
$sx = @simplexml_load_string($this->settings);
if ($sx) {
$this->loadSettings($sx);
}
}
/**
*
* @return enum (self::RUNNER_MANUAL or self::RUNNER_SCHEDULER)
*/
public function getRunner()
{
return $this->runner;
}
/**
*
* @param enum $runner (self::RUNNER_MANUAL or self::RUNNER_SCHEDULER)
* @throws Exception_InvalidArgument
* @return \task_abstract
*/
public function setRunner($runner)
{
if ($runner != self::RUNNER_MANUAL && $runner != self::RUNNER_SCHEDULER) {
@@ -347,13 +398,22 @@ abstract class task_abstract
$stmt = $conn->prepare($sql);
$stmt->execute($params);
$stmt->closeCursor();
return $this;
}
/**
*
* @return string
*/
public function getTitle()
{
return $this->title;
}
/**
*
*/
public function delete()
{
if ( ! $this->getPID()) { // do not delete a running task
@@ -369,6 +429,9 @@ abstract class task_abstract
}
}
/**
* set last execution time to now()
*/
public function setLastExecTime()
{
$conn = connection::getPDOConnection();
@@ -401,6 +464,12 @@ abstract class task_abstract
return $time;
}
/**
*
* @return variant
* pid (int) of the task, or NULL if the pid file
* NULL : the pid file is not locked (task no running)
*/
public function getPID()
{
$pid = NULL;
@@ -421,6 +490,11 @@ abstract class task_abstract
return $pid;
}
/**
*
* @param boolean $stat
* set to false to ask the task to quit its loop
*/
public function setRunning($stat)
{
$this->running = $stat;
@@ -445,6 +519,12 @@ abstract class task_abstract
}
}
/**
* sleep n seconds
*
* @param int $nsec
* @throws \InvalidArgumentException
*/
protected function sleep($nsec)
{
$nsec = (integer) $nsec;
@@ -455,16 +535,25 @@ abstract class task_abstract
}
}
/**
*
* @return string fullpath to the pid file for the task
*/
private function getLockfilePath()
{
$core = \bootstrap::getCore();
$lockdir = $core->getRegistry()->get('GV_RootPath') . 'tmp/locks/';
$lockfile = ($lockdir . 'task_' . $this->getID() . '.lock');
$lockfilePath = ($lockdir . 'task_' . $this->getID() . '.lock');
return($lockfile);
return($lockfilePath);
}
/**
*
* @return resource file descriptor of the OPENED pid file
* @throws Exception if file is already locked (task running)
*/
private function lockTask()
{
$lockfile = $this->getLockfilePath();
@@ -507,6 +596,9 @@ abstract class task_abstract
}
if ($this->getState() === self::STATE_STARTED && $this->runner === self::RUNNER_MANUAL)
$this->setState(self::STATE_STOPPED);
// in any case, exception or not, the task is ending so unlock the pid file
$this->unlockTask($lockFD);
@@ -516,7 +608,11 @@ abstract class task_abstract
}
}
public function unlockTask($lockFD)
/**
*
* @param resource $lockFD file descriptor of the OPENED lock file
*/
private function unlockTask($lockFD)
{
flock($lockFD, LOCK_UN | LOCK_NB);
ftruncate($lockFD, 0);
@@ -563,9 +659,11 @@ abstract class task_abstract
// post-process
$this->postProcessOneContent($box, $row);
$rowsdone ++;
$current_memory = memory_get_usage();
if ($current_memory >> 20 >= $this->maxmegs) {
$this->log(sprintf("Max memory (%s M) reached (actual is %s M)", $this->maxmegs, $current_memory));
$this->log(sprintf("Max memory (%s M) reached (actual is %.02f M)", $this->maxmegs, ($current_memory >> 10) / 1024));
$this->running = FALSE;
$ret = self::STATE_MAXMEGSREACHED;
}
@@ -577,8 +675,7 @@ abstract class task_abstract
}
try {
$status = $this->getState();
if ($status == self::STATE_TOSTOP) {
if ($this->getState() == self::STATE_TOSTOP) {
$this->running = FALSE;
$ret = self::STATE_TOSTOP;
}
@@ -592,11 +689,11 @@ abstract class task_abstract
}
//
// if nothing was done, at least check the status
if (count($rs) == 0 && $this->running) {
if ($rowsdone == 0 && $this->running) {
$current_memory = memory_get_usage();
if ($current_memory >> 20 >= $this->maxmegs) {
$this->log(sprintf("Max memory (%s M) reached (current is %s M)", $this->maxmegs, $current_memory));
$this->log(sprintf("Max memory (%s M) reached (current is %.02f M)", $this->maxmegs, ($current_memory >> 10) / 1024));
$this->running = FALSE;
$ret = self::STATE_MAXMEGSREACHED;
}
@@ -689,8 +786,8 @@ abstract class task_abstract
/**
*
* @param appbox $appbox
* @param type $class_name
* @param type $settings
* @param string $class_name
* @param string $settings (xml string)
* @return task_abstract
*/
public static function create(appbox $appbox, $class_name, $settings = null)
@@ -741,11 +838,21 @@ abstract class task_abstract
return($t);
}
/**
*
* @return int id of the task
*/
public function getID()
{
return $this->taskid;
}
/**
*
* @param int $done
* @param int $todo
* @return \task_abstract
*/
public function setProgress($done, $todo)
{
$p = ($todo > 0) ? ((100 * $done) / $todo) : -1;
@@ -754,7 +861,10 @@ 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->getID()));
$stmt->execute(array(
':p' => $p,
':taskid' => $this->getID()
));
$stmt->closeCursor();
$this->completed_percentage = $p;
} catch (Exception $e) {

View File

@@ -84,6 +84,7 @@ abstract class task_appboxAbstract extends task_abstract
switch ($process_ret) {
case self::STATE_MAXMEGSREACHED:
case self::STATE_MAXRECSDONE:
case self::STATE_OK:
if ($this->getRunner() == self::RUNNER_SCHEDULER) {
$this->setState(self::STATE_TORESTART);
$this->running = FALSE;
@@ -99,9 +100,6 @@ abstract class task_appboxAbstract extends task_abstract
$this->setState(self::STATE_TODELETE);
$this->running = FALSE;
break;
case self::STATE_OK:
break;
}
} // if(row)
@@ -126,7 +124,6 @@ abstract class task_appboxAbstract extends task_abstract
// process the records
$ret = $this->processLoop($appbox, $rs);
} catch (Exception $e) {
$this->log('Error : ' . $e->getMessage());
}

View File

@@ -111,6 +111,7 @@ abstract class task_databoxAbstract extends task_abstract
switch ($process_ret) {
case self::STATE_MAXMEGSREACHED:
case self::STATE_MAXRECSDONE:
case self::STATE_OK:
if ($this->getRunner() == self::RUNNER_SCHEDULER) {
$this->setState(self::STATE_TORESTART);
$this->running = FALSE;
@@ -126,9 +127,6 @@ abstract class task_databoxAbstract extends task_abstract
// DO NOT SUICIDE IN THE LOOP, may have to work on other sbas !!!
$task_must_delete = TRUE;
break;
case self::STATE_OK:
break;
}
$this->flushRecordsSbas();
@@ -160,7 +158,6 @@ abstract class task_databoxAbstract extends task_abstract
// process the records
$ret = $this->processLoop($databox, $rs);
} catch (Exception $e) {
$this->log('Error : ' . $e->getMessage());
}

View File

@@ -212,20 +212,11 @@ class task_period_archive extends task_abstract
}
/**
*
* @return string
*/
public function getGraphicForm()
{
return true;
}
/**
* printInterfaceHTML(..) : generer l'interface 'graphic view'
* getInterfaceHTML(..) : retourner l'interface 'graphic view'
*
* @return Void
*/
public function printInterfaceHTML()
public function getInterfaceHTML()
{
$appbox = appbox::get_instance(\bootstrap::getCore());
@@ -264,9 +255,8 @@ class task_period_archive extends task_abstract
<input type="checkbox" name="delfolder" onchange="chgxmlck(this, 'delfolder');">&nbsp;<?php echo _('task::archive:supprimer les repertoires apres archivage') ?><br/>
</form>
<?php
$out = ob_get_clean();
return $out;
return ob_get_clean();
}
/**
@@ -277,6 +267,7 @@ class task_period_archive extends task_abstract
{
return(_("task::archive:Archiving files found into a 'hotfolder'"));
}
protected $sbas_id;
/**

View File

@@ -261,20 +261,11 @@ class task_period_cindexer extends task_abstract
return;
}
/**
*
* @return string
*/
public function getGraphicForm()
{
return true;
}
/**
*
* @return return
*/
public function printInterfaceHTML()
public function getInterfaceHTML()
{
$appname = 'phraseanet_indexer';
if (defined('PHP_WINDOWS_VERSION_BUILD')) {
@@ -333,9 +324,8 @@ class task_period_cindexer extends task_abstract
<div style="margin:10px; padding:5px; border:1px #000000 solid; font-family:monospace; font-size:16px; text-align:left; color:#00e000; background-color:#404040" id="cmd">cmd</div>
</center>
<?php
$out = ob_get_clean();
return $out;
return ob_get_clean();
}
/**

View File

@@ -140,16 +140,7 @@ class task_period_ftp extends task_appboxAbstract
*
* @return string
*/
public function getGraphicForm()
{
return true;
}
/**
*
* @return string
*/
public function printInterfaceHTML()
public function getInterfaceHTML()
{
ob_start();
?>
@@ -167,9 +158,8 @@ class task_period_ftp extends task_appboxAbstract
&nbsp;<?php echo('task::_common_:secondes (unite temporelle)') ?><br/>
</form>
<?php
$out = ob_get_clean();
return $out;
return ob_get_clean();
}
public function saveChanges(connection_pdo $conn, $taskid, &$taskrow)

View File

@@ -129,12 +129,7 @@ class task_period_ftpPull extends task_appboxAbstract
<?php
}
public function getGraphicForm()
{
return true;
}
public function printInterfaceHTML()
public function getInterfaceHTML()
{
global $parm;
ob_start();
@@ -178,9 +173,8 @@ class task_period_ftpPull extends task_appboxAbstract
&nbsp;<?php echo('task::_common_:minutes (unite temporelle)') ?><br/>
</form>
<?php
$out = ob_get_clean();
return $out;
return ob_get_clean();
}
public function saveChanges(connection_pdo $conn, $taskid, &$taskrow)

View File

@@ -154,7 +154,6 @@ class task_period_outofdate extends task_abstract
parent.calcSQL();
</script>
<?php
return("");
} else { // ... so we NEVER come here
// bad xml
@@ -306,18 +305,9 @@ class task_period_outofdate extends task_abstract
}
// ====================================================================
// callback : must return the name graphic form to submit
// if not implemented, assume 'graphicForm'
// getInterfaceHTML(..) : retourner l'interface 'graphic view' !! EN UTF-8 !!
// ====================================================================
public function getGraphicForm()
{
return true;
}
// ====================================================================
// printInterfaceHTML(..) : generer l'interface 'graphic view' !! EN UTF-8 !!
// ====================================================================
public function printInterfaceHTML()
public function getInterfaceHTML()
{
$appbox = appbox::get_instance(\bootstrap::getCore());
$session = $appbox->get_session();
@@ -417,9 +407,7 @@ class task_period_outofdate extends task_abstract
<div style="margin:10px; padding:5px; border:1px #000000 solid; background-color:#404040" id="cmd">cmd</div>
</center>
<?php
$out = ob_get_clean();
return $out;
return ob_get_clean();
}
// ====================================================================
// $argt : command line args specifics to this task (optional)

View File

@@ -149,7 +149,6 @@ class task_period_subdef extends task_databoxAbstract
</script>
<?php
return("");
} else {
return("BAD XML");
@@ -203,16 +202,12 @@ class task_period_subdef extends task_databoxAbstract
<?php
}
public function getGraphicForm()
{
return true;
}
/**
* generates interface 'graphic view'
* return interface 'graphic view'
*
*/
public function printInterfaceHTML()
public function getInterfaceHTML()
{
ob_start();
?>
@@ -233,9 +228,8 @@ class task_period_subdef extends task_databoxAbstract
<br/>
</form>
<?php
$out = ob_get_clean();
return $out;
return ob_get_clean();
}
public function retrieveSbasContent(databox $databox)

View File

@@ -259,12 +259,7 @@ class task_period_workflow01 extends task_databoxAbstract
<?php
}
public function getGraphicForm()
{
return true;
}
public function printInterfaceHTML()
public function getInterfaceHTML()
{
$appbox = appbox::get_instance(\bootstrap::getCore());
$session = $appbox->get_session();
@@ -327,9 +322,8 @@ class task_period_workflow01 extends task_databoxAbstract
<div style="margin:10px; padding:5px; border:1px #000000 solid; font-family:monospace; font-size:16px; text-align:left; color:#00e000; background-color:#404040" id="cmd">cmd</div>
</center>
<?php
$out = ob_get_clean();
return $out;
return ob_get_clean();
}
public function help()

View File

@@ -0,0 +1,741 @@
<?php
/*
* This file is part of Phraseanet
*
* (c) 2005-2012 Alchemy
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
*
* @license http://opensource.org/licenses/gpl-3.0 GPLv3
* @link www.phraseanet.com
*/
class task_period_workflow02 extends task_appboxAbstract
{
/**
*
* @return string
*/
public function getName()
{
return(_("task::workflow02"));
}
/**
*
* @return string
*/
public function help()
{
return '';
}
// ====================================================================
// graphic2xml : must return the xml (text) version of the form
// ====================================================================
public function graphic2xml($oldxml)
{
$request = http_request::getInstance();
$parm2 = $request->get_parms(
"period", "logsql"
);
$dom = new DOMDocument();
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
if ($dom->loadXML($oldxml)) {
$xmlchanged = false;
// foreach($parm2 as $pname=>$pvalue)
foreach (array(
"str:period",
"boo:logsql"
) 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 cr<63>e
$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;
?>
<script type="text/javascript">
<?php echo $form ?>.period.value = "<?php echo p4string::MakeString($sxml->period, "js", '"') ?>";
<?php echo $form ?>.logsql.checked = <?php echo ($sxml->logsql > 0 ? 'true' : 'false'); ?>;
parent.$("#sqlu").text("");
parent.$("#sqls").text("");
var data = {};
data["ACT"] = "CALCTEST";
data["taskid"]=<?php echo $this->getID(); ?>;
data["cls"]="workflow02";
data["xml"] = "<?php echo p4string::MakeString($sxml->saveXML(), "js", '"') ?>";
parent.$.ajax({ url: "/admin/taskfacility.php"
, data: data
, dataType:'json'
, type:"POST"
, async:true
, success:function(data)
{
t = "";
for(i in data.tasks)
{
t += "<div class=\"title\">&nbsp;";
if(data.tasks[i].name_htmlencoded)
t += "<b>" + data.tasks[i].name_htmlencoded + "</b>";
else
t += "<b><i>sans nom</i></b>";
if(data.tasks[i].basename_htmlencoded)
t += " (action=" + data.tasks[i].action + ' on ' + data.tasks[i].basename_htmlencoded + ')';
else
t += " (action=" + data.tasks[i].action + ' on <i>Unknown</i>)';
t += "</div>";
if(data.tasks[i].err_htmlencoded) ;
t += "<div class=\"err\">" + data.tasks[i].err_htmlencoded + "</div>";
t += "<div class=\"sql\">";
if(data.tasks[i].sql.test.sql_htmlencoded)
t += "<div class=\"sqltest\">" + data.tasks[i].sql.test.sql_htmlencoded + "</div>";
t += "--&gt; <span id=\"SQLRET"+i+"\"><i>wait...</i></span><br/>";
t += "</div>";
}
parent.$("#sqla").html(t);
var data = {};
data["ACT"] = "PLAYTEST";
data["taskid"]=<?php echo $this->getID(); ?>;
data["cls"]="workflow02";
data["xml"] = "<?php echo p4string::MakeString($sxml->saveXML(), "js", '"') ?>";
parent.$.ajax({ url: "/admin/taskfacility.php"
, data: data
, dataType:'json'
, type:"POST"
, async:true
, success:function(data)
{
for(i in data.tasks)
{
if(data.tasks[i].sql.test.err)
{
parent.$("#SQLRET"+i).html("err: " + data.tasks[i].sql.test.err);
}
else
{
t = '';
for(j in data.tasks[i].sql.test.result.rids)
t += (t?', ':'') + data.tasks[i].sql.test.result.rids[j];
if(data.tasks[i].sql.test.result.rids.length < data.tasks[i].sql.test.result.n)
t += ', ...';
parent.$("#SQLRET"+i).html("n=" + data.tasks[i].sql.test.result.n + ", rids:(" + t + ")");
}
}
}
});
}
});
</script>
<?php
return("");
}
else { // ... so we NEVER come here
// bad xml
return("BAD XML");
}
}
// ====================================================================
// printInterfaceHEAD() :
// ====================================================================
public function printInterfaceHEAD()
{
?>
<style>
OPTION.jsFilled
{
padding-left:10px;
padding-right:20px;
}
#OUTOFDATETAB TD
{
text-align:center;
}
DIV.terminal
{
margin:5px;
border:1px #000000 solid;
font-family:monospace;
font-size:13px;
text-align:left;
color:#00FF00;
background-color:#182018
}
DIV.terminal DIV.title
{
color:#303830;
background-color:#00C000;
padding:2px;
}
DIV.terminal DIV.sql
{
padding:5px;
}
DIV.terminal DIV.sqltest
{
padding-left:45px;
padding-right:25px;
}
</style>
<?php
}
// ====================================================================
// printInterfaceJS() : generer le code js de l'interface 'graphic view'
// ====================================================================
public function printInterfaceJS()
{
?>
<script type="text/javascript">
$(document).ready(
function(){
});
(function( $ ){
$.fn.serializeJSON=function() {
var json = {};
jQuery.map($(this).serializeArray(), function(n, i){
json[n['name']] = n['value'];
});
return json;
};
})( jQuery );
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;
}
setDirty();
}
function chgxmlck(checkinput, fieldname)
{
setDirty();
}
</script>
<?php
}
// ====================================================================
// getInterfaceHTML(..) : retourner l'interface 'graphic view' !! EN UTF-8 !!
// ====================================================================
public function getInterfaceHTML()
{
ob_start();
?>
<form name="graphicForm" onsubmit="return(false);" method="post">
P&eacute;riodicit&eacute;&nbsp;:&nbsp;
<input type="text" name="period" style="width:40px;" onchange="chgxmltxt(this, 'period');" value="" />
minutes
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<input type="checkbox" name="logsql" onchange="chgxmlck(this, 'logsql');" />&nbsp;log changes
</form>
<center>
<div class="terminal" id="sqla"></div>
</center>
<?php
return ob_get_clean();
}
// ======================================================================================================
// ===== run() : le code d'<27>x<EFBFBD>cution de la t<>che proprement dite
// ======================================================================================================
private $sxTaskSettings = null; // les settings de la tache en simplexml
protected function retrieveContent(appbox $appbox)
{
$this->maxrecs = 1000;
$this->sxTaskSettings = @simplexml_load_string($this->getSettings());
if ( ! $this->sxTaskSettings)
return array();
$ret = array();
$logsql = (int) ($this->sxTaskSettings->logsql) > 0;
foreach ($this->sxTaskSettings->tasks->task as $sxtask) {
if ( ! $this->running) {
break;
}
$task = $this->calcSQL($sxtask);
if ($logsql) {
$this->log(sprintf("playing task '%s' on base '%s'"
, $task['name']
, $task['basename'] ? $task['basename'] : '<unknown>'));
}
try {
$connbas = connection::getPDOConnection($task['sbas_id']);
} catch (Exception $e) {
$this->log(sprintf("can't connect sbas %s", $task['sbas_id']));
continue;
}
$stmt = $connbas->prepare($task['sql']['real']['sql']);
if ($stmt->execute(array())) {
while ($this->running && ($row = $stmt->fetch(PDO::FETCH_ASSOC)) !== FALSE) {
$tmp = array('sbas_id' => $task['sbas_id'], 'record_id' => $row['record_id'], 'action' => $task['action']);
$rec = new record_adapter($task['sbas_id'], $row['record_id']);
switch ($task['action']) {
case 'UPDATE':
// change collection ?
if (($x = (int) ($sxtask->to->coll['id'])) > 0) {
$tmp['coll'] = $x;
}
// change sb ?
if (($x = $sxtask->to->status['mask'])) {
$tmp['sb'] = $x;
}
$ret[] = $tmp;
break;
case 'DELETE':
$tmp['deletechildren'] = false;
if ($sxtask['deletechildren'] && $rec->is_grouping()) {
$tmp['deletechildren'] = true;
}
$ret[] = $tmp;
break;
}
}
$stmt->closeCursor();
}
}
return $ret;
}
protected function processOneContent(appbox $appbox, Array $row)
{
$logsql = (int) ($this->sxTaskSettings->logsql) > 0;
$dbox = databox::get_instance($row['sbas_id']);
$rec = new record_adapter($row['sbas_id'], $row['record_id']);
switch ($row['action']) {
case 'UPDATE':
// change collection ?
if (array_key_exists('coll', $row)) {
$coll = collection::get_from_coll_id($dbox, $row['coll']);
// $rec->move_to_collection($coll, $appbox);
if ($logsql) {
$this->log(sprintf("on sbas %s move rid %s to coll %s \n", $row['sbas_id'], $row['record_id'], $coll->get_coll_id()));
}
}
// change sb ?
if (array_key_exists('sb', $row)) {
$status = str_split($rec->get_status());
foreach (str_split(strrev($row['sb'])) as $bit => $val) {
if ($val == '0' || $val == '1') {
$status[63 - $bit] = $val;
}
}
$status = implode('', $status);
// $rec->set_binary_status($status);
if ($logsql) {
$this->log(sprintf("on sbas %s set rid %s status to %s \n", $row['sbas_id'], $row['record_id'], $status));
}
}
break;
case 'DELETE':
if ($row['deletechildren'] && $rec->is_grouping()) {
foreach ($rec->get_children() as $child) {
// $child->delete();
if ($logsql) {
$this->log(sprintf("on sbas %s delete (grp child) rid %s \n", $row['sbas_id'], $child->get_record_id()));
}
}
}
// $rec->delete();
if ($logsql) {
$this->log(sprintf("on sbas %s delete rid %s \n", $row['sbas_id'], $rec->get_record_id()));
}
break;
}
return $this;
}
protected function postProcessOneContent(appbox $appbox, Array $row)
{
return $this;
}
private function calcSQL($sxtask, $playTest = false)
{
$appbox = appbox::get_instance(\bootstrap::getCore());
$sbas_id = (int) ($sxtask['sbas_id']);
$ret = array(
'name' => $sxtask['name'] ? (string) $sxtask['name'] : 'sans nom',
'name_htmlencoded' => htmlentities($sxtask['name'] ? $sxtask['name'] : 'sans nom'),
'sbas_id' => $sbas_id,
'basename' => '',
'basename_htmlencoded' => '',
'action' => strtoupper($sxtask['action']),
'sql' => NULL,
'err' => '',
'err_htmlencoded' => '',
);
try {
$dbox = $appbox->get_databox($sbas_id);
$ret['basename'] = $dbox->get_viewname();
$ret['basename_htmlencoded'] = htmlentities($ret['basename']);
switch ($ret['action']) {
case 'UPDATE':
$ret['sql'] = $this->calcUPDATE($sbas_id, $sxtask, $playTest);
break;
case 'DELETE':
$ret['sql'] = $this->calcDELETE($sbas_id, $sxtask, $playTest);
$ret['deletechildren'] = (int) ($sxtask['deletechildren']);
break;
default:
$ret['err'] = "bad action '" . $ret['action'] . "'";
$ret['err_htmlencoded'] = htmlentities($ret['err']);
break;
}
} catch (Exception $e) {
$ret['err'] = "bad sbas '" . $sbas_id . "'";
$ret['err_htmlencoded'] = htmlentities($ret['err']);
}
return($ret);
}
/*
* compute entry for a UPDATE query
*/
private function calcUPDATE($sbas_id, &$sxtask, $playTest)
{
$tws = array(); // NEGATION of updates, used to build the 'test' sql
//
// set coll_id ?
if (($x = (int) ($sxtask->to->coll['id'])) > 0) {
$tws[] = 'coll_id!=' . $x;
}
// set status ?
$x = $sxtask->to->status['mask'];
$mx = str_replace(' ', '0', ltrim(str_replace(array('0', 'x'), array(' ', ' '), $x)));
$ma = str_replace(' ', '0', ltrim(str_replace(array('x', '0'), array(' ', '1'), $x)));
if ($mx && $ma)
$tws[] = '((status ^ 0b' . $mx . ') & 0b' . $ma . ')!=0';
elseif ($mx)
$tws[] = '(status ^ 0b' . $mx . ')!=0';
elseif ($ma)
$tws[] = '(status & 0b' . $ma . ')!=0';
// compute the 'where' clause
list($tw, $join) = $this->calcWhere($sbas_id, $sxtask);
// ... complete the where to buid the TEST
if (count($tws) == 1)
$tw[] = $tws[0];
elseif (count($tws) > 1)
$tw[] = '(' . implode(') OR (', $tws) . ')';
if (count($tw) == 1)
$where = $tw[0];
if (count($tw) > 1)
$where = '(' . implode(') AND (', $tw) . ')';
// build the TEST sql (select)
$sql_test = 'SELECT SQL_CALC_FOUND_ROWS record_id FROM record' . $join;
if (count($tw) > 0)
$sql_test .= ' WHERE ' . ((count($tw) == 1) ? $tw[0] : '(' . implode(') AND (', $tw) . ')');
$sql_test .= ' LIMIT 10';
// build the real sql (select)
$sql = 'SELECT record_id FROM record' . $join;
if (count($tw) > 0)
$sql .= ' WHERE ' . ((count($tw) == 1) ? $tw[0] : '(' . implode(') AND (', $tw) . ')');
$ret = array(
'real' => array(
'sql' => $sql,
'sql_htmlencoded' => htmlentities($sql),
),
'test' => array(
'sql' => $sql_test,
'sql_htmlencoded' => htmlentities($sql_test),
'result' => NULL,
'err' => NULL
)
);
if ($playTest) {
$ret['test']['result'] = $this->playTest($sbas_id, $sql_test);
}
return($ret);
}
/*
* compute entry for a DELETE task
*/
private function calcDELETE($sbas_id, &$sxtask, $playTest)
{
// compute the 'where' clause
list($tw, $join) = $this->calcWhere($sbas_id, $sxtask);
// build the TEST sql (select)
$sql_test = 'SELECT SQL_CALC_FOUND_ROWS record_id FROM record' . $join;
if (count($tw) > 0)
$sql_test .= ' WHERE ' . ((count($tw) == 1) ? $tw[0] : '(' . implode(') AND (', $tw) . ')');
$sql_test .= ' LIMIT 10';
// build the real sql (select)
$sql = 'SELECT record_id FROM record' . $join;
if (count($tw) > 0)
$sql .= ' WHERE ' . ((count($tw) == 1) ? $tw[0] : '(' . implode(') AND (', $tw) . ')');
$ret = array(
'real' => array(
'sql' => $sql,
'sql_htmlencoded' => htmlentities($sql),
),
'test' => array(
'sql' => $sql_test,
'sql_htmlencoded' => htmlentities($sql_test),
'result' => NULL,
'err' => NULL
)
);
if ($playTest) {
$ret['test']['result'] = $this->playTest($sbas_id, $sql_test);
}
return($ret);
}
/*
* compute the 'where' clause
* returns an array of clauses to be joined by 'and'
* and a 'join' to needed tables
*/
private function calcWhere($sbas_id, &$sxtask)
{
$connbas = connection::getPDOConnection($sbas_id);
$tw = array();
$join = '';
$ijoin = 0;
// criteria <type type="XXX" />
if (($x = $sxtask->from->type['type']) !== NULL) {
switch (strtoupper($x)) {
case 'RECORD':
$tw[] = 'parent_record_id!=record_id';
break;
case 'REGROUP':
$tw[] = 'parent_record_id=record_id';
break;
}
}
// criteria <text field="XXX" compare="OP" value="ZZZ" />
foreach ($sxtask->from->text as $x) {
$ijoin ++;
$comp = strtoupper($x['compare']);
if (in_array($comp, array('<', '>', '<=', '>=', '=', '!='))) {
$s = 'p' . $ijoin . '.name=\'' . $x['field'] . '\' AND p' . $ijoin . '.value' . $comp;
$s .= '' . $connbas->quote($x['value']) . '';
$tw[] = $s;
$join .= ' INNER JOIN prop AS p' . $ijoin . ' USING(record_id)';
} else {
// bad comparison operator
}
}
// criteria <date direction ="XXX" field="YYY" delta="Z" />
foreach ($sxtask->from->date as $x) {
$ijoin ++;
$s = 'p' . $ijoin . '.name=\'' . $x['field'] . '\' AND NOW()';
$s .= strtoupper($x['direction']) == 'BEFORE' ? '<' : '>=';
$delta = (int) ($x['delta']);
if ($delta > 0)
$s .= '(p' . $ijoin . '.value+INTERVAL ' . $delta . ' DAY)';
elseif ($delta < 0)
$s .= '(p' . $ijoin . '.value-INTERVAL ' . -$delta . ' DAY)';
else
$s .= 'p' . $ijoin . '.value';
$tw[] = $s;
$join .= ' INNER JOIN prop AS p' . $ijoin . ' USING(record_id)';
}
// criteria <coll compare="OP" id="X,Y,Z" />
if (($x = $sxtask->from->coll) !== NULL) {
$tcoll = explode(',', $x['id']);
foreach ($tcoll as $i => $c)
$tcoll[$i] = (int) $c;
if ($x['compare'] == '=') {
if (count($tcoll) == 1) {
$tw[] = 'coll_id = ' . $tcoll[0];
} else {
$tw[] = 'coll_id IN(' . implode(',', $tcoll) . ')';
}
} elseif ($x['compare'] == '!=') {
if (count($tcoll) == 1) {
$tw[] = 'coll_id != ' . $tcoll[0];
} else {
$tw[] = 'coll_id NOT IN(' . implode(',', $tcoll) . ')';
}
} else {
// bad operator
}
}
// criteria <status mask="XXXXX" />
$x = $sxtask->from->status['mask'];
$mx = str_replace(' ', '0', ltrim(str_replace(array('0', 'x'), array(' ', ' '), $x)));
$ma = str_replace(' ', '0', ltrim(str_replace(array('x', '0'), array(' ', '1'), $x)));
if ($mx && $ma) {
$tw[] = '((status^0b' . $mx . ')&0b' . $ma . ')=0';
} elseif ($mx) {
$tw[] = '(status^0b' . $mx . ')=0';
} elseif ($ma) {
$tw[] = '(status&0b' . $ma . ")=0";
}
if (count($tw) == 1) {
$where = $tw[0];
}
if (count($tw) > 1) {
$where = '(' . implode(') AND (', $tw) . ')';
}
return(array($tw, $join));
}
/*
* play a 'test' sql on sbas, return the number of records and the 10 first rids
*/
private function playTest($sbas_id, $sql)
{
$connbas = connection::getPDOConnection($sbas_id);
$result = array('rids' => array(), 'err' => '', 'n' => null);
$stmt = $connbas->prepare($sql);
if ($stmt->execute(array())) {
$result['n'] = $connbas->query("SELECT FOUND_ROWS()")->fetchColumn();
while (($row = $stmt->fetch(PDO::FETCH_ASSOC))) {
$result['rids'][] = $row['record_id'];
}
$stmt->closeCursor();
} else {
$result['err'] = $connbas->last_error();
}
return($result);
}
public function facility()
{
$request = http_request::getInstance();
$parm2 = $request->get_parms(
'ACT', 'xml'
);
$ret = array('tasks' => array());
switch ($parm2['ACT']) {
case 'CALCTEST':
$sxml = simplexml_load_string($parm2['xml']);
foreach ($sxml->tasks->task as $sxtask) {
$ret['tasks'][] = $this->calcSQL($sxtask, false);
}
break;
case 'PLAYTEST':
$sxml = simplexml_load_string($parm2['xml']);
foreach ($sxml->tasks->task as $sxtask) {
$ret['tasks'][] = $this->calcSQL($sxtask, true);
}
break;
case 'CALCSQL':
$xml = $this->graphic2xml('<?xml version="1.0" encoding="UTF-8"?><tasksettings/>');
$sxml = simplexml_load_string($xml);
foreach ($sxml->tasks->task as $sxtask) {
$ret['tasks'][] = $this->calcSQL($sxtask, false);
}
break;
}
print(json_encode($ret));
}
}
?>

View File

@@ -170,12 +170,7 @@ class task_period_writemeta extends task_databoxAbstract
<?php
}
public function getGraphicForm()
{
return true;
}
public function printInterfaceHTML()
public function getInterfaceHTML()
{
$appbox = appbox::get_instance(\bootstrap::getCore());
$session = $appbox->get_session();
@@ -204,9 +199,8 @@ class task_period_writemeta extends task_databoxAbstract
</form>
<?php
}
$out = ob_get_clean();
return $out;
return ob_get_clean();
}
protected function retrieveSbasContent(databox $databox)

View File

@@ -175,7 +175,7 @@
switch(type)
{
case 'PRE_XML':
{% if task.getGraphicForm() %}
{% if task.hasInterfaceHTML() %}
document.getElementById('divGraph').style.display = "none";
document.getElementById('divXml').style.display = "";
document.getElementById('linkviewxml').className = "tabFront";
@@ -183,6 +183,7 @@
{% endif %}
this.currentView = "XML";
break;
case 'XML':
if( (f = document.forms['graphicForm']) )
{
@@ -360,7 +361,11 @@
f.appendChild(o);
}
redrawme();
jsTaskObj.view("PRE_{{view}}");
{% if task.hasInterfaceHTML() %}
jsTaskObj.view("PRE_GRAPHIC");
{% else %}
jsTaskObj.view("PRE_XML");
{% endif %}
if( (o = document.getElementById("iddivloading")) )
o.style.visibility = "hidden";
}
@@ -398,27 +403,24 @@
<div style="position:absolute; top:65px; bottom:30px; left:0px; width:100%;">
<div id="idBox2" style="position:absolute; top:20px; left:5px; bottom:5px; right:5px; z-index:2; border-top:#ffffff 1px solid; border-left:#ffffff 1px solid; border-bottom:#000000 1px solid; border-right:#000000 1px solid;">
<div class="divTab">
{% if task.printInterfaceHTML %}
{% if task.hasInterfaceHTML() %}
<div id="linkviewgraph" class="tabFront" onClick="jsTaskObj.view('GRAPHIC');" style="width:100px;">
{% trans 'boutton::vue graphique' %}
</div>
{% endif %}
<div id="linkviewxml" class="{% if task.printInterfaceHTML %}tabBack{% else %}tabFront{% endif %}" onClick="jsTaskObj.view('XML');" style="width:100px;">
<div id="linkviewxml" class="{% if task.hasInterfaceHTML() %}tabBack{% else %}tabFront{% endif %}" onClick="jsTaskObj.view('XML');" style="width:100px;">
{% trans 'boutton::vue xml' %}
</div>
</div>
{% if task.getGraphicForm %}
{% if task.hasInterfaceHTML() %}
<!-- ______________ graphic interface '{{task.getName()}}' ___________________ -->
<div id="divGraph" style="position:absolute; top:5px; left:5px; bottom:5px; right:5px; display:auto; overflow:scroll;" >
{% if task.printInterfaceHTML %}
{{task.printInterfaceHTML()|raw}}
{% else %}
<form name="graphicForm" onsubmit="return false;"></form>
{% endif %}
{{task.getInterfaceHTML()|raw}}
</div>
<!-- _____________ end graphic interface '{{task.getName()}}' _________________ -->
{% endif %}
<!-- _____________ xml interface _____________ -->
<div id="divXml" style="position:absolute; top:5px; left:5px; bottom:5px; right:5px; {% if task.printInterfaceHTML %}display:none;{% endif %}">
<div id="divXml" style="position:absolute; top:5px; left:5px; bottom:5px; right:5px; {% if task.hasInterfaceHTML() %}display:none;{% endif %}">
<form style="position:absolute; top:0px; left:0px; right:4px; bottom:20px;" action="./task2utils.php" onsubmit="return(false);" name="fxml" method="post">
<input type="hidden" name="__act" value="???" />
<input type="hidden" name="__class" value="{{ task|get_class }}" />

View File

@@ -76,22 +76,10 @@ class task_period_archiveTest extends \PhraseanetPHPUnitAbstract
}
/**
* @covers task_period_archive::getGraphicForm
* @todo Implement testGetGraphicForm().
* @covers task_period_archive::getInterfaceHTML
* @todo Implement testGetInterfaceHTML().
*/
public function testGetGraphicForm()
{
// Remove the following lines when you implement this test.
$this->markTestIncomplete(
'This test has not been implemented yet.'
);
}
/**
* @covers task_period_archive::printInterfaceHTML
* @todo Implement testPrintInterfaceHTML().
*/
public function testPrintInterfaceHTML()
public function testGetInterfaceHTML()
{
// Remove the following lines when you implement this test.
$this->markTestIncomplete(

View File

@@ -56,9 +56,8 @@ try {
$zGraphicForm = 'graphicForm';
$hasGraphicMode = false;
if (method_exists($task, 'getGraphicForm')) {
if ($task->hasInterfaceHTML()) {
$hasGraphicMode = true;
$zGraphicForm = $task->getGraphicForm();
} else {
$parm['view'] = 'XML';
}
@@ -67,15 +66,11 @@ function stripdoublequotes($value)
{
return str_replace(array("\r\n", "\r", "\n", "\""), array('', '', '', '\"'), $value);
}
if ( ! $task->getGraphicForm()) {
$parm['view'] = 'XML';
}
$core = \bootstrap::getCore();
$twig = $core->getTwig();
if ( ! $task->getGraphicForm()) {
$parm['view'] = 'XML';
}
echo $twig->render('admin/task.html', array('task' => $task, 'view' => $parm['view']));

View File

@@ -39,8 +39,8 @@ phrasea::headers();
$ztask = $task_manager->getTask($parm['__tid']);
switch ($parm['__act']) {
case 'FORM2XML':
if (method_exists($ztask, 'printInterfaceHTML')) {
if ($ztask->getGraphicForm()) {
if ($ztask->hasInterfaceHTML()) {
if (1) {
$xml = p4string::MakeString($ztask->graphic2xml($parm['__xml']), "js");
} else {
$xml = p4string::MakeString($parm['__xml'], "js");
@@ -61,9 +61,9 @@ phrasea::headers();
break;
case 'XML2FORM':
if (method_exists($ztask, 'printInterfaceHTML')) {
if ($ztask->hasInterfaceHTML()) {
if ((simplexml_load_string($parm['txtareaxml']))) {
if ($ztask->getGraphicForm()) {
if (1) {
if (($msg = ($ztask->xml2graphic($parm['txtareaxml'], "parent.document.forms['graphicForm']"))) == "") {
?>
<script type="text/javascript">

View File

@@ -191,7 +191,6 @@ foreach ($tasks as $t) {
?>
];
$('#newTaskButton').contextMenu(
menuNewTask,
{
@@ -254,8 +253,6 @@ foreach ($tasks as $t) {
}
);
$('.task_manager .dropdown.task').contextMenu(
[
{
@@ -316,24 +313,32 @@ foreach ($tasks as $t) {
$(this.menu).find('.context-menu-item:eq('+this.optionsIdx['edit']+')').removeClass("context-menu-item-disabled");
if(retPing.tasks[tid].status == 'started' || retPing.tasks[tid].status == 'torestart')
{
$(this.menu).find('.context-menu-item:eq('+this.optionsIdx['stop']+')').removeClass("context-menu-item-disabled");
}
else
{
$(this.menu).find('.context-menu-item:eq('+this.optionsIdx['stop']+')').addClass("context-menu-item-disabled");
$(this.menu).find('.context-menu-item:eq('+this.optionsIdx['delete']+')').removeClass("context-menu-item-disabled");
if(retPing.scheduler && retPing.scheduler.pid)
$(this.menu).find('.context-menu-item:eq('+this.optionsIdx['start']+')').removeClass("context-menu-item-disabled");
else
$(this.menu).find('.context-menu-item:eq('+this.optionsIdx['start']+')').addClass("context-menu-item-disabled");
}
$(this.menu).find('.context-menu-item:eq('+this.optionsIdx['delete']+')').removeClass("context-menu-item-disabled");
if(retPing.scheduler && retPing.scheduler.pid && !(retPing.tasks[tid].status == 'started' || retPing.tasks[tid].status == 'torestart'))
{
$(this.menu).find('.context-menu-item:eq('+this.optionsIdx['start']+')').removeClass("context-menu-item-disabled");
}
else
{
$(this.menu).find('.context-menu-item:eq('+this.optionsIdx['start']+')').addClass("context-menu-item-disabled");
}
}
}
}
);
self.setTimeout("pingScheduler(true);", 100); // true : loop forever each 2 sec
})
}
)
</script>
</head>
<body>