[ Index ]

PHP Cross Reference of vtigercrm-6.1.0

title

Body

[close]

/vtlib/Vtiger/ -> Cron.php (source)

   1  <?php
   2  /*+**********************************************************************************
   3   * The contents of this file are subject to the vtiger CRM Public License Version 1.0
   4   * ("License"); You may not use this file except in compliance with the License
   5   * The Original Code is:  vtiger CRM Open Source
   6   * The Initial Developer of the Original Code is vtiger.
   7   * Portions created by vtiger are Copyright (C) vtiger.
   8   * All Rights Reserved.
   9   *********************************************************************************** */
  10  
  11  include_once  'vtlib/Vtiger/Utils.php';
  12  require_once ('include/database/PearDatabase.php');
  13  
  14  /**
  15   * Provides API to work with Cron tasks
  16   * @package vtlib
  17   */
  18  class Vtiger_Cron {
  19  
  20      protected static $schemaInitialized = false;
  21      protected static $instanceCache = array();
  22      static $STATUS_DISABLED = 0;
  23      static $STATUS_ENABLED = 1;
  24      static $STATUS_RUNNING = 2;
  25      static $STATUS_COMPLETED = 3;
  26      protected $data;
  27      protected $bulkMode = false;
  28  
  29      /**
  30       * Constructor
  31       */
  32      protected function __construct($values) {
  33          $this->data = $values;
  34          self::$instanceCache[$this->getName()] = $this;
  35      }
  36  
  37      /**
  38       * set the value to the data
  39       * @param type $value,$key
  40       */
  41      protected function set($key,$value){
  42          $this->data[$key] = $value;
  43          return $this;
  44      }
  45  
  46      /**
  47       * Get id reference of this instance.
  48       */
  49      function getId() {
  50          return $this->data['id'];
  51      }
  52  
  53      /**
  54       * Get name of this task instance.
  55       */
  56      function getName() {
  57          return decode_html($this->data['name']);
  58      }
  59  
  60      /**
  61       * Get the frequency set.
  62       */
  63      function getFrequency() {
  64          return intval($this->data['frequency']);
  65      }
  66  
  67      /**
  68       * Get the status
  69       */
  70      function getStatus() {
  71          return intval($this->data['status']);
  72      }
  73      /**
  74       * Get the timestamp lastrun started.
  75       */
  76      function getLastStart() {
  77          return intval($this->data['laststart']);
  78      }
  79  
  80      /**
  81       * Get the timestamp lastrun ended.
  82       */
  83      function getLastEnd() {
  84          return intval($this->data['lastend']);
  85      }
  86  
  87      /**
  88       * Get the user datetimefeild
  89       */
  90      function getLastEndDateTime() {
  91          if($this->data['lastend'] != NULL){
  92              $lastEndDateTime = new DateTimeField(date('Y-m-d H:i:s', $this->data['lastend']));
  93              return $lastEndDateTime->getDisplayDateTimeValue();
  94          } else {
  95              return '';
  96          }
  97      }
  98  
  99      /**
 100       *
 101       * get the last start datetime field
 102       */
 103      function getLastStartDateTime() {
 104          if($this->data['laststart'] != NULL){
 105              $lastStartDateTime = new DateTimeField(date('Y-m-d H:i:s', $this->data['laststart']));
 106              return $lastStartDateTime->getDisplayDateTimeValue();
 107          } else {
 108              return '';
 109          }
 110      }
 111  
 112      /**
 113       * Get Time taken to complete task
 114       */
 115      function getTimeDiff() {
 116          $lastStart = $this->getLastStart();
 117          $lastEnd   = $this->getLastEnd();
 118          $timeDiff  = $lastEnd - $lastStart;
 119          return $timeDiff;
 120      }
 121  
 122      /**
 123       * Get the configured handler file.
 124       */
 125      function getHandlerFile() {
 126          return $this->data['handler_file'];
 127      }
 128  
 129      /**
 130       *Get the Module name
 131       */
 132      function getModule() {
 133  
 134          return $this->data['module'];
 135      }
 136  
 137      /**
 138       * get the Sequence
 139       */
 140      function getSequence() {
 141          return $this->data['sequence'];
 142      }
 143  
 144      /**
 145       * get the description of cron
 146       */
 147      function getDescription(){
 148          return $this->data['description'];
 149      }
 150  
 151      /**
 152       * Check if task is right state for running.
 153       */
 154      function isRunnable() {
 155          $runnable = false;
 156  
 157          if (!$this->isDisabled()) {
 158              // Take care of last time (end - on success, start - if timedout)
 159              // Take care to start the cron im
 160              $lastTime = ($this->getLastStart() > 0) ? $this->getLastStart() : $this->getLastEnd();
 161              $elapsedTime = time() - $lastTime;
 162              $runnable = ($elapsedTime >= ($this->getFrequency()-60));
 163          }
 164          return $runnable;
 165      }
 166  
 167      /**
 168       * Helper function to check the status value.
 169       */
 170      function statusEqual($value) {
 171          $status = intval($this->data['status']);
 172          return $status == $value;
 173      }
 174  
 175      /**
 176       * Is task in running status?
 177       */
 178      function isRunning() {
 179          return $this->statusEqual(self::$STATUS_RUNNING);
 180      }
 181  
 182      /**
 183       * Is task enabled?
 184       */
 185      function isEnabled() {
 186          return $this->statusEqual(self::$STATUS_ENABLED);
 187      }
 188  
 189      /**
 190       * Is task disabled?
 191       */
 192      function isDisabled() {
 193          return $this->statusEqual(self::$STATUS_DISABLED);
 194      }
 195  
 196      /**
 197       * Update status
 198       */
 199      function updateStatus($status) {
 200          switch (intval($status)) {
 201              case self::$STATUS_DISABLED:
 202              case self::$STATUS_ENABLED:
 203              case self::$STATUS_RUNNING:
 204                  break;
 205              default:
 206                  throw new Exception('Invalid status');
 207          }
 208          self::querySilent('UPDATE vtiger_cron_task SET status=? WHERE id=?', array($status, $this->getId()));
 209      }
 210  
 211      /*
 212       * update frequency
 213      */
 214      function updateFrequency($frequency) {
 215          self::querySilent('UPDATE vtiger_cron_task SET frequency=? WHERE id=?', array($frequency, $this->getId()));
 216      }
 217  
 218      /**
 219       * Mark this instance as running.
 220       */
 221      function markRunning() {
 222          $time = time();
 223          self::querySilent('UPDATE vtiger_cron_task SET status=?, laststart=?, lastend=? WHERE id=?', array(self::$STATUS_RUNNING, $time, 0, $this->getId()));
 224          return $this->set('laststart',$time);
 225      }
 226  
 227      /**
 228       * Mark this instance as finished.
 229       */
 230      function markFinished() {
 231          $time = time();
 232          self::querySilent('UPDATE vtiger_cron_task SET status=?, lastend=? WHERE id=?', array(self::$STATUS_ENABLED, $time, $this->getId()));
 233          return $this->set('lastend',$time);
 234      }
 235  
 236      /**
 237       * Set the bulkMode flag
 238       */
 239      function setBulkMode($mode = null) {
 240          $this->bulkMode = $mode;
 241      }
 242  
 243      /**
 244       * Is task in bulk mode execution?
 245       */
 246      function inBulkMode() {
 247          return $this->bulkMode;
 248      }
 249  
 250      /**
 251       * Detect if the task was started by never finished.
 252       */
 253      function hadTimedout() {
 254          if($this->data['lastend'] === 0 && $this->data['laststart'] != 0)
 255          return intval($this->data['lastend']);
 256      }
 257  
 258      /**
 259       * Execute SQL query silently (even when table doesn't exist)
 260       */
 261      protected static function querySilent($sql, $params=false) {
 262          global $adb;
 263          $old_dieOnError = $adb->dieOnError;
 264  
 265          $adb->dieOnError = false;
 266          $result = $adb->pquery($sql, $params);
 267          $adb->dieOnError = $old_dieOnError;
 268          return $result;
 269      }
 270  
 271      /**
 272       * Initialize the schema.
 273       */
 274      protected static function initializeSchema() {
 275          if(!self::$schemaInitialized) {
 276              if(!Vtiger_Utils::CheckTable('vtiger_cron_task')) {
 277                  Vtiger_Utils::CreateTable('vtiger_cron_task',
 278                          '(id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
 279                      name VARCHAR(100) UNIQUE KEY, handler_file VARCHAR(100) UNIQUE KEY,
 280                      frequency int, laststart int(11) unsigned, lastend int(11) unsigned, status int,module VARCHAR(100),
 281                                          sequence int,description TEXT )',true);
 282              }
 283              self::$schemaInitialized = true;
 284          }
 285      }
 286  
 287      static function nextSequence() {
 288          global $adb;
 289          $result = self::querySilent('SELECT MAX(sequence) FROM vtiger_cron_task ORDER BY SEQUENCE');
 290          if ($result && $adb->num_rows($result)) {
 291              $row = $adb->fetch_array($result);
 292          }
 293          if($row == NULL) {
 294              $row['max(sequence)'] = 1;
 295          }
 296          return $row['max(sequence)']+1;
 297      }
 298  
 299      /**
 300       * Register cron task.
 301       */
 302      static function register($name, $handler_file, $frequency, $module = 'Home', $status = 1, $sequence = 0, $description = '') {
 303          self::initializeSchema();
 304          global $adb;
 305          $instance = self::getInstance($name);
 306          if($sequence == 0) {
 307              $sequence = self::nextSequence();
 308          }
 309          self::querySilent('INSERT INTO vtiger_cron_task (name, handler_file, frequency, status, sequence,module,description) VALUES(?,?,?,?,?,?,?)',
 310                  array($name, $handler_file, $frequency, $status, $sequence, $module,$description));
 311      }
 312  
 313      /**
 314       * De-register cron task.
 315       */
 316      static function deregister($name) {
 317          self::querySilent('DELETE FROM vtiger_cron_task WHERE name=?', array($name));
 318          if (isset(self::$instanceCache["$name"])) {
 319              unset(self::$instanceCache["$name"]);
 320          }
 321      }
 322  
 323      /**
 324       * Get instances that are active (not disabled)
 325       */
 326      static function listAllActiveInstances($byStatus = 0) {
 327          global $adb;
 328  
 329          $instances = array();
 330          if($byStatus == 0) {
 331              $result = self::querySilent('SELECT * FROM vtiger_cron_task WHERE status <> ? ORDER BY SEQUENCE',array(self::$STATUS_DISABLED   ));
 332          }
 333          else {
 334              $result = self::querySilent('SELECT * FROM vtiger_cron_task  ORDER BY SEQUENCE');
 335  
 336          }
 337          if ($result && $adb->num_rows($result)) {
 338              while ($row = $adb->fetch_array($result)) {
 339                  $instances[] = new Vtiger_Cron($row);
 340              }
 341          }
 342          return $instances;
 343      }
 344  
 345      /**
 346       * Get instance of cron task.
 347       */
 348      static function getInstance($name) {
 349          global $adb;
 350  
 351          $instance = false;
 352          if (isset(self::$instanceCache["$name"])) {
 353              $instance = self::$instanceCache["$name"];
 354          }
 355  
 356          if ($instance === false) {
 357              $result = self::querySilent('SELECT * FROM vtiger_cron_task WHERE name=?', array($name));
 358              if ($result && $adb->num_rows($result)) {
 359                  $instance = new Vtiger_Cron($adb->fetch_array($result));
 360              }
 361          }
 362          return $instance;
 363      }
 364  
 365  
 366      /**
 367       * Get instance of cron job by id
 368       */
 369      static function getInstanceById($id) {
 370          global $adb;
 371          $instance = false;
 372          if (isset(self::$instanceCache[$id])) {
 373              $instance = self::$instanceCache[$id];
 374          }
 375  
 376  
 377          if ($instance === false) {
 378              $result = self::querySilent('SELECT * FROM vtiger_cron_task WHERE id=?', array($id));
 379              if ($result && $adb->num_rows($result)) {
 380                  $instance = new Vtiger_Cron($adb->fetch_array($result));
 381              }
 382          }
 383          return $instance;
 384      }
 385  
 386      static function listAllInstancesByModule($module) {
 387          global $adb;
 388  
 389          $instances = array();
 390          $result = self::querySilent('SELECT * FROM vtiger_cron_task WHERE module=?',array($module));
 391          if ($result && $adb->num_rows($result)) {
 392              while ($row = $adb->fetch_array($result)) {
 393                  $instances[] = new Vtiger_Cron($row);
 394              }
 395          }
 396          return $instances;
 397      }
 398  
 399      /*
 400       * Fuction uses to log the cron when it is in running
 401       *  for long time
 402       *  @Params <boolean> Completed - flag when then the cron is completed after long time
 403       */
 404  	public function log($completed = false){
 405          global $adb;
 406           $result = self::querySilent('SELECT id,iteration from vtiger_cron_log where start = ? AND name=?',array($this->getLastStart(),$this->getName()));
 407            if ($result && $adb->num_rows($result) > 0) {
 408                $row = $adb->fetch_array($result);
 409                if($completed){
 410                    self::querySilent('UPDATE vtiger_cron_log set status = ?,end = ? where id = ?',array(self::$STATUS_COMPLETED,time(),$row['id']));
 411                } else{
 412  
 413                   self::querySilent('UPDATE vtiger_cron_log set iteration = ? where id = ?',array($row['iteration']+1,$row['id']));
 414                }
 415            } else {
 416                self::querySilent('INSERT INTO vtiger_cron_log (name,start,iteration,status) VALUES(?,?,?,?)',
 417                                   array($this->getName(),$this->getLastStart(),1,self::$STATUS_RUNNING));
 418            }
 419  
 420       }
 421  
 422       /*
 423        *  Function to verify where the log Mail is sent are not
 424        */
 425  	 public function isSentLogMail(){
 426           global $adb;
 427           $result = self::querySilent('SELECT 1 from vtiger_cron_log where start = ? AND name=? AND iteration >= 4 ',array($this->getLastStart(),$this->getName()));
 428           if ($result && $adb->num_rows($result)) {
 429               return true;
 430           }    else {
 431              return false;
 432           }
 433       }
 434  
 435       /*
 436        *  Function to get number of times a Cron task was skipped due to running state
 437        *        @returns <int> Iterations
 438        */
 439  	 public function getIterations(){
 440           global $adb;
 441           $result = self::querySilent('SELECT iteration from vtiger_cron_log where start = ? AND name=?',array($this->getLastStart(),$this->getName()));
 442           if ($result && $adb->num_rows($result)) {
 443               $row = $adb->fetch_array($result);
 444               return $row['iteration'];
 445           }
 446       }
 447  
 448       /*
 449        *  Function to get time to Complete the cron when it take
 450        *        @returns <string> competed time in hours and mins
 451        */
 452  	 public function getCompletedTime(){
 453           global $adb;
 454           $result = self::querySilent('SELECT start,end from vtiger_cron_log where start = ? AND name=?',array($this->getLastStart(),$this->getName()));
 455           if ($result && $adb->num_rows($result)) {
 456              $row = $adb->fetch_array($result);
 457              $duration = $row['end'] - $row['start'];
 458              $hours = (int) ($duration / 60);
 459              $minutes = $duration - ($hours * 60);
 460  
 461              return "$hours hours and $minutes minutes";
 462          }
 463       }
 464  }
 465  ?>


Generated: Fri Nov 28 20:08:37 2014 Cross-referenced by PHPXref 0.7.1