[ Index ]

PHP Cross Reference of vtigercrm-6.1.0

title

Body

[close]

/modules/com_vtiger_workflow/ -> VTWorkflowManager.inc (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      require_once ("VTJsonCondition.inc");
  11      require_once  'include/utils/ConfigReader.php';
  12      require_once  'includes/runtime/Cache.php';
  13  
  14      class VTWorkflowManager{
  15  
  16          static $ON_FIRST_SAVE = 1;
  17          static $ONCE = 2;
  18          static $ON_EVERY_SAVE = 3;
  19          static $ON_MODIFY = 4;
  20          // Reserving 5 & 6 for ON_DELETE and ON_SCHEDULED types.
  21          static $ON_SCHEDULE=6;
  22          static $MANUAL = 7;
  23  
  24  		function __construct($adb){
  25              $this->adb = $adb;
  26          }
  27  
  28  		function save($workflow){
  29              $adb=$this->adb;
  30              if(isset($workflow->id)){
  31                  $wf=$workflow;
  32                  if($wf->filtersavedinnew == null) $wf->filtersavedinnew = 5;
  33                  $adb->pquery("update com_vtiger_workflows set
  34                                  module_name=?, summary=?, test=?, execution_condition=?, defaultworkflow=?, filtersavedinnew=?,
  35                                  schtypeid=?, schtime=?, schdayofmonth=?, schdayofweek=?, schannualdates=?, nexttrigger_time=? where workflow_id=?",
  36                      array($wf->moduleName, $wf->description, $wf->test, $wf->executionCondition, $wf->defaultworkflow, $wf->filtersavedinnew,
  37                          $wf->schtypeid, $wf->schtime, $wf->schdayofmonth, $wf->schdayofweek, $wf->schannualdates, $wf->nexttrigger_time, $wf->id));
  38              }else{
  39                  $workflowId = $adb->getUniqueID("com_vtiger_workflows");
  40                  $workflow->id = $workflowId;
  41                  $wf=$workflow;
  42                  if($wf->filtersavedinnew == null) $wf->filtersavedinnew = 5;
  43  
  44                  $result=$adb->getColumnNames("com_vtiger_workflows");
  45                  if(in_array("type",$result)) {
  46                      $adb->pquery("insert into com_vtiger_workflows
  47                                  (workflow_id, module_name, summary, test, execution_condition, type, defaultworkflow, filtersavedinnew,
  48                                  schtypeid, schtime, schdayofmonth, schdayofweek, schannualdates, nexttrigger_time) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
  49                              array($workflowId, $wf->moduleName, $wf->description, $wf->test,  $wf->executionCondition, $wf->type, $wf->defaultworkflow, $wf->filtersavedinnew,
  50                              $wf->schtypeid, $wf->schtime, $wf->schdayofmonth, $wf->schdayofweek, $wf->schannualdates, $wf->nexttrigger_time));
  51                  } else {
  52                      $adb->pquery("insert into com_vtiger_workflows
  53                                  (workflow_id, module_name, summary, test, execution_condition, defaultworkflow,filtersavedinnew,
  54                                  schtypeid, schtime, schdayofmonth, schdayofweek, schannualdates, nexttrigger_time) values (?,?,?,?,?,?,?,?,?,?,?,?,?)",
  55                              array($workflowId, $wf->moduleName, $wf->description, $wf->test,  $wf->executionCondition, $wf->defaultworkflow, $wf->filtersavedinnew,
  56                              $wf->schtypeid, $wf->schtime, $wf->schdayofmonth, $wf->schdayofweek, $wf->schannualdates, $wf->nexttrigger_time));
  57                  }
  58              }
  59          }
  60  
  61  
  62  		function getWorkflows(){
  63              $adb=$this->adb;
  64  
  65              $result=$adb->getColumnNames("com_vtiger_workflows");
  66              if(in_array("defaultworkflow",$result)){
  67                  $result = $adb->query("select workflow_id, module_name, summary, test, execution_condition,defaultworkflow, type, filtersavedinnew
  68                                      from com_vtiger_workflows ");
  69              }else{
  70  
  71                  $result = $adb->query("select workflow_id, module_name, summary, test, execution_condition, type, filtersavedinnew
  72                                      from com_vtiger_workflows");
  73              }
  74              return $this->getWorkflowsForResult($result);
  75  
  76          }
  77  
  78          /**
  79           * Function returns scheduled workflows
  80           * @param DateTime $referenceTime
  81           * @return Workflow
  82           */
  83  		function getScheduledWorkflows($referenceTime='') {
  84              $adb=$this->adb;
  85              $query = 'SELECT * FROM com_vtiger_workflows WHERE execution_condition = ?';
  86              $params = array(VTWorkflowManager::$ON_SCHEDULE);
  87              if($referenceTime != '') {
  88                  $query .= " AND (nexttrigger_time = '' OR nexttrigger_time IS NULL OR nexttrigger_time <= ?)";
  89                  array_push($params, $referenceTime);
  90              }
  91              $result = $adb->pquery($query, $params);
  92              return $this->getWorkflowsForResult($result);
  93  
  94          }
  95  
  96          /**
  97           * Function to get the number of scheduled workflows
  98           * @return Integer
  99           */
 100  		function getScheduledWorkflowsCount() {
 101              $adb=$this->adb;
 102              $query = 'SELECT count(*) AS count FROM com_vtiger_workflows WHERE execution_condition = ?';
 103              $params = array(VTWorkflowManager::$ON_SCHEDULE);
 104              $result = $adb->pquery($query, $params);
 105              return $adb->query_result($result, 0, 'count');
 106          }
 107  
 108          /**
 109           * Function returns the maximum allowed scheduled workflows
 110           * @return int
 111           */
 112  		function getMaxAllowedScheduledWorkflows() {
 113              return 10;
 114          }
 115  
 116  		function getWorkflowsForModule($moduleName){
 117              $adb=$this->adb;
 118              $cache= Vtiger_Cache::getInstance();
 119              if($cache->getWorkflowForModule($moduleName)){
 120                  return $this->getWorkflowsForResult($cache->getWorkflowForModule($moduleName));
 121              } else {
 122              //my changes
 123              $result=$adb->getColumnNames("com_vtiger_workflows");
 124              if(in_array(defaultworkflow,$result)){
 125                  $result = $adb->pquery("select workflow_id, module_name, summary, test, execution_condition, defaultworkflow, type, filtersavedinnew
 126                                      from com_vtiger_workflows where module_name=?",array($moduleName));
 127              }
 128              else{
 129                  $result = $adb->pquery("select workflow_id, module_name, summary, test, execution_condition, type, filtersavedinnew
 130                                      from com_vtiger_workflows where module_name=?",array($moduleName));
 131              }
 132                  $cache->setWorkflowForModule($moduleName,$result);
 133              return $this->getWorkflowsForResult($result);
 134              }
 135          }
 136  
 137  		protected function getWorkflowsForResult($result){
 138              $adb=$this->adb;
 139  
 140              $it = new SqlResultIterator($adb, $result);
 141              $workflows=array();
 142              $i=0;
 143              foreach($it as $row){
 144                  $workflow = $this->getWorkflowInstance($row->type);
 145                  $workflow->setup($row->data);
 146  
 147                  if(!is_a($workflow, 'Workflow')) continue;
 148  
 149                  $workflows[$i++]=$workflow;
 150              }
 151              return $workflows;
 152          }
 153  
 154  		protected function getWorkflowInstance($type='basic') {
 155              $configReader = new ConfigReader('modules/com_vtiger_workflow/config.inc', 'workflowConfig');
 156              $workflowTypeConfig = $configReader->getConfig($type);
 157              $workflowClassPath = $workflowTypeConfig['classpath'];
 158              $workflowClass = $workflowTypeConfig['class'];
 159  
 160              require_once $workflowClassPath;
 161              $workflow = new $workflowClass();
 162              return $workflow;
 163          }
 164  
 165          /**
 166           * Retrieve a workflow from the database
 167           *
 168           * Returns null if the workflow doesn't exist.
 169           *
 170           * @param The id of the workflow
 171           * @return A workflow object.
 172           */
 173  		function retrieve($id){
 174              $adb=$this->adb;
 175              $result = $adb->pquery("select * from com_vtiger_workflows where workflow_id=?", array($id));
 176  
 177              if($adb->num_rows($result)){
 178                  $data = $adb->raw_query_result_rowdata($result, 0);
 179                  $workflow = $this->getWorkflowInstance($data['type']);
 180                  $workflow->setup($data);
 181                  return $workflow;
 182              }else{
 183                  return null;
 184              }
 185          }
 186  
 187  		function delete($id){
 188              $adb=$this->adb;
 189              $adb->pquery("DELETE FROM com_vtiger_workflowtasks WHERE workflow_id IN
 190                              (SELECT workflow_id FROM com_vtiger_workflows WHERE workflow_id=? AND (defaultworkflow IS NULL OR defaultworkflow != 1))",
 191                          array($id));
 192              $adb->pquery("DELETE FROM com_vtiger_workflows WHERE workflow_id=? AND (defaultworkflow IS NULL OR defaultworkflow != 1)", array($id));
 193          }
 194  
 195  		function newWorkflow($moduleName){
 196              $workflow = $this->getWorkflowInstance();
 197              $workflow->moduleName = $moduleName;
 198              $workflow->executionCondition = self::$ON_EVERY_SAVE;
 199              $workflow->type = 'basic';
 200              return $workflow;
 201  
 202          }
 203  
 204  
 205          /**
 206           * Export a workflow as a json encoded string
 207           *
 208           * @param $workflow The workflow instance to export.
 209           */
 210  		public function serializeWorkflow($workflow){
 211              $exp = array();
 212              $exp['moduleName'] = $workflow->moduleName;
 213              $exp['description'] = $workflow->description;
 214              $exp['test'] = $workflow->test;
 215              $exp['executionCondition'] = $workflow->executionCondition;
 216              $exp['schtypeid'] = $workflow->schtypeid;
 217              $exp['schtime'] = $workflow->schtime;
 218              $exp['schdayofmonth'] = $workflow->schdayofmonth;
 219              $exp['schdayofweek'] = $workflow->schdayofweek;
 220              $exp['schannualdates'] = $workflow->schannualdates;
 221              $exp['tasks'] = array();
 222              $tm = new VTTaskManager($this->adb);
 223              $tasks = $tm->getTasksForWorkflow($workflow->id);
 224              foreach($tasks as $task){
 225                  unset($task->id);
 226                  unset($task->workflowId);
 227                  $exp['tasks'][] = serialize($task);
 228              }
 229              return  Zend_Json::encode($exp);
 230          }
 231  
 232          /**
 233           * Import a json encoded string as a workflow object
 234           *
 235           * @return The Workflow instance representing the imported workflow.
 236           */
 237  		public function deserializeWorkflow($str){
 238              $data =  Zend_Json::decode($str);
 239              $workflow = $this->newWorkflow($data['moduleName']);
 240              $workflow->description = $data['description'];
 241              $workflow->test = $data['test'];
 242              $workflow->executionCondition = $data['executionCondition'];
 243              $workflow->schtypeid = $data['schtypeid'];
 244              $workflow->schtime = $data['schtime'];
 245              $workflow->schdayofmonth = $data['schdayofmonth'];
 246              $workflow->schdayofweek = $data['schdayofweek'];
 247              $workflow->schannualdates = $data['schannualdates'];
 248              $this->save($workflow);
 249              $tm = new VTTaskManager($this->adb);
 250              $tasks = $data['tasks'];
 251              foreach($tasks as $taskStr){
 252                  $task = $tm->unserializeTask($taskStr);
 253                  $task->workflowId = $workflow->id;
 254                  $tm->saveTask($task);
 255              }
 256              return $workflow;
 257          }
 258          /**
 259           * Update the Next trigger timestamp for a workflow
 260           */
 261  		public function updateNexTriggerTime($workflow) {
 262              $nextTriggerTime = $workflow->getNextTriggerTime();
 263              $workflow->setNextTriggerTime($nextTriggerTime);
 264          }
 265  
 266          /**
 267           * Function to get workflows modules those are supporting comments
 268           * @param <String> $moduleName
 269           * @return <Array> list of Workflow models
 270           */
 271  		public function getWorkflowsForModuleSupportingComments($moduleName) {
 272              $adb = $this->adb;
 273              $cache = Vtiger_Cache::getInstance();
 274  
 275              if($cache->getWorkflowForModuleSupportingComments($moduleName)) {
 276                  return $cache->getWorkflowForModuleSupportingComments($moduleName);
 277              }
 278  
 279              $result = $adb->getColumnNames('com_vtiger_workflows');
 280              if(in_array('defaultworkflow', $result)) {
 281                  $result = $adb->pquery('SELECT workflow_id, module_name, summary, test, execution_condition, defaultworkflow, type, filtersavedinnew
 282                                      FROM com_vtiger_workflows WHERE module_name = ? AND test LIKE (?)', array($moduleName, '%_VT_add_comment%'));
 283              } else {
 284                  $result = $adb->pquery('SELECT workflow_id, module_name, summary, test, execution_condition, type, filtersavedinnew
 285                                      FROM com_vtiger_workflows where module_name = ? AND test LIKE (?)', array($moduleName, '%_VT_add_comment%'));
 286              }
 287              $workflowModels = $this->getWorkflowsForResult($result);
 288  
 289              $commentSupportedWorkflowModels = array();
 290              foreach ($workflowModels as $workflowId => $workflowModel) {
 291                  $conditions = Zend_Json::decode($workflowModel->test);
 292                  if (is_array($conditions)) {
 293                      foreach ($conditions as $key => $conditionInfo) {
 294                          if ($conditionInfo['fieldname'] === '_VT_add_comment') {
 295                              unset($conditions[$key]);
 296                              $workflowModel->test = Zend_Json::encode($conditions);
 297                              $commentSupportedWorkflowModels[$workflowId] = $workflowModel;
 298                          }
 299                      }
 300                  }
 301  
 302              }
 303              $cache->setWorkflowForModuleSupportingComments($moduleName, $commentSupportedWorkflowModels);
 304              return $commentSupportedWorkflowModels;
 305          }
 306      }
 307  
 308      class Workflow{
 309          static $SCHEDULED_HOURLY = 1;
 310          static $SCHEDULED_DAILY = 2;
 311          static $SCHEDULED_WEEKLY = 3;
 312          static $SCHEDULED_ON_SPECIFIC_DATE = 4;
 313          static $SCHEDULED_MONTHLY_BY_DATE = 5;
 314          static $SCHEDULED_MONTHLY_BY_WEEKDAY = 6;
 315          static $SCHEDULED_ANNUALLY = 7;
 316  
 317  		function __construct(){
 318              $this->conditionStrategy = new VTJsonCondition();
 319          }
 320  
 321  		function setup($row) {
 322              $this->id = $row['workflow_id'];
 323              $this->moduleName = $row['module_name'];
 324              $this->description = to_html($row['summary']);
 325              $this->test = $row['test'];
 326              $this->executionCondition = $row['execution_condition'];
 327              $this->schtypeid = $row['schtypeid'];
 328              $this->schtime = $row['schtime'];
 329              $this->schdayofmonth = $row['schdayofmonth'];
 330              $this->schdayofweek = $row['schdayofweek'];
 331              $this->schannualdates = $row['schannualdates'];
 332              if($row['defaultworkflow']){
 333                  $this->defaultworkflow=$row['defaultworkflow'];
 334              }
 335              $this->filtersavedinnew = $row['filtersavedinnew'];
 336              $this->nexttrigger_time = $row['nexttrigger_time'];
 337          }
 338  
 339  		function evaluate($entityCache, $id){
 340              if($this->test==""){
 341                  return true;
 342              }else{
 343                  $cs = $this->conditionStrategy;
 344                  return $cs->evaluate($this->test,
 345                                       $entityCache, $id);
 346              }
 347          }
 348  
 349  		function isCompletedForRecord($recordId) {
 350              global $adb;
 351  
 352              $result = $adb->pquery("SELECT * FROM com_vtiger_workflow_activatedonce
 353                              WHERE entity_id=? and workflow_id=?", array($recordId, $this->id));
 354  
 355              $result2=$adb->pquery("SELECT * FROM com_vtiger_workflowtasks
 356                              INNER JOIN com_vtiger_workflowtask_queue
 357                              ON com_vtiger_workflowtasks.task_id= com_vtiger_workflowtask_queue.task_id
 358                              WHERE workflow_id=? AND entity_id=?",
 359                              array($this->id,$recordId));
 360  
 361              if($adb->num_rows($result)===0 && $adb->num_rows($result2)===0) { // Workflow not done for specified record
 362                  return false;
 363              } else {
 364                  return true;
 365              }
 366          }
 367  
 368  		function markAsCompletedForRecord($recordId) {
 369              global $adb;
 370  
 371              $adb->pquery("INSERT INTO com_vtiger_workflow_activatedonce (entity_id, workflow_id)
 372                  VALUES (?,?)", array($recordId, $this->id));
 373          }
 374  
 375  		function performTasks($entityData) {
 376              global $adb;
 377              $data = $entityData->getData();
 378  
 379              require_once ('modules/com_vtiger_workflow/VTTaskManager.inc');
 380              require_once ('modules/com_vtiger_workflow/VTTaskQueue.inc');
 381  
 382              $tm = new VTTaskManager($adb);
 383              $taskQueue = new VTTaskQueue($adb);
 384              $tasks = $tm->getTasksForWorkflow($this->id);
 385  
 386              foreach($tasks as $task){
 387                  if($task->active) {
 388                      $trigger = $task->trigger;
 389                      if($trigger != null){
 390                          $delay = strtotime($data[$trigger['field']])+$trigger['days']*86400;
 391                      }else{
 392                          $delay = 0;
 393                      }
 394                      if($task->executeImmediately==true){
 395                          $task->doTask($entityData);
 396                      } else {
 397                          $hasContents = $task->hasContents($entityData);
 398                          if ($hasContents) {
 399                              $taskQueue->queueTask($task->id,$entityData->getId(), $delay, $task->getContents($entityData));
 400                          }
 401                      }
 402                  }
 403              }
 404          }
 405  
 406  		function executionConditionAsLabel($label=null){
 407              if($label==null){
 408                  $arr = array('ON_FIRST_SAVE', 'ONCE', 'ON_EVERY_SAVE', 'ON_MODIFY', '', '', 'MANUAL');
 409                  return $arr[$this->executionCondition-1];
 410              }else{
 411                  $arr = array('ON_FIRST_SAVE'=>1, 'ONCE'=>2, 'ON_EVERY_SAVE'=>3, 'ON_MODIFY'=>4, 'MANUAL'=>7);
 412                  $this->executionCondition = $arr[$label];
 413              }
 414          }
 415  		function setNextTriggerTime($time) {
 416              if($time) {
 417                  $db = PearDatabase::getInstance();
 418                  $db->pquery("UPDATE com_vtiger_workflows SET nexttrigger_time=? WHERE workflow_id=?", array($time, $this->id));
 419                  $this->nexttrigger_time = $time;
 420              }
 421          }
 422  
 423  		function getNextTriggerTimeValue() {
 424              return $this->nexttrigger_time;
 425          }
 426  
 427  		function getWFScheduleType(){
 428              return ($this->executionCondition == 6 ? $this->schtypeid : 0);
 429          }
 430  
 431  		function getWFScheduleTime(){
 432              return $this->schtime;
 433          }
 434  
 435  		function getWFScheduleDay(){
 436              return $this->schdayofmonth;
 437          }
 438  
 439  		function getWFScheduleWeek(){
 440              return $this->schdayofweek;
 441          }
 442  
 443  		function getWFScheduleAnnualDates(){
 444              return $this->schannualdates;
 445          }
 446  
 447          /**
 448           * Function gets the next trigger for the workflows
 449           * @global <String> $default_timezone
 450           * @return type
 451           */
 452  		function getNextTriggerTime() {
 453              global $default_timezone;
 454              $admin = Users::getActiveAdminUser();
 455              $adminTimeZone = $admin->time_zone;
 456              @date_default_timezone_set($adminTimeZone);
 457  
 458              $scheduleType = $this->getWFScheduleType();
 459              $nextTime = null;
 460  
 461              if($scheduleType == Workflow::$SCHEDULED_HOURLY) {
 462                  $nextTime = date("Y-m-d H:i:s",strtotime("+1 hour"));
 463              }
 464  
 465              if($scheduleType == Workflow::$SCHEDULED_DAILY) {
 466                  $nextTime = $this->getNextTriggerTimeForDaily($this->getWFScheduleTime());
 467              }
 468  
 469              if($scheduleType == Workflow::$SCHEDULED_WEEKLY) {
 470                  $nextTime = $this->getNextTriggerTimeForWeekly($this->getWFScheduleWeek(), $this->getWFScheduleTime());
 471              }
 472  
 473              if($scheduleType == Workflow::$SCHEDULED_ON_SPECIFIC_DATE) {
 474                  $nextTime = date('Y-m-d H:i:s', strtotime('+10 year'));
 475              }
 476  
 477              if($scheduleType == Workflow::$SCHEDULED_MONTHLY_BY_DATE) {
 478                  $nextTime = $this->getNextTriggerTimeForMonthlyByDate($this->getWFScheduleDay(), $this->getWFScheduleTime());
 479              }
 480  
 481              if($scheduleType == Workflow::$SCHEDULED_MONTHLY_BY_WEEKDAY) {
 482                  $nextTime = $this->getNextTriggerTimeForMonthlyByWeekDay($this->getWFScheduleDay(), $this->getWFScheduleTime());
 483              }
 484  
 485              if($scheduleType == Workflow::$SCHEDULED_ANNUALLY) {
 486                  $nextTime = $this->getNextTriggerTimeForAnnualDates($this->getWFScheduleAnnualDates(), $this->getWFScheduleTime());
 487              }
 488              @date_default_timezone_set($default_timezone);
 489              return $nextTime;
 490          }
 491          /**
 492           * get next trigger time for daily
 493           * @param type $schTime
 494           * @return time
 495           */
 496  		function getNextTriggerTimeForDaily($scheduledTime) {
 497              $now = strtotime(date("Y-m-d H:i:s"));
 498              $todayScheduledTime = strtotime(date("Y-m-d H:i:s", strtotime($scheduledTime)));
 499              if ($now > $todayScheduledTime) {
 500                  $nextTime = date("Y-m-d H:i:s", strtotime('+1 day ' . $scheduledTime));
 501              } else {
 502                  $nextTime = date("Y-m-d H:i:s", $todayScheduledTime);
 503              }
 504              return $nextTime;
 505          }
 506  
 507          /**
 508           * get next trigger Time For weekly
 509           * @param type $scheduledDaysOfWeek
 510           * @param type $scheduledTime
 511           * @return <time>
 512           */
 513  		function getNextTriggerTimeForWeekly($scheduledDaysOfWeek, $scheduledTime) {
 514              $weekDays = array('1' => 'Monday', '2' => 'Tuesday', '3' => 'Wednesday', '4' => 'Thursday', '5' => 'Friday', '6' => 'Saturday', '7' => 'Sunday');
 515              $currentTime = time();
 516              $currentWeekDay = date('N', $currentTime);
 517              if ($scheduledDaysOfWeek) {
 518                  $scheduledDaysOfWeek = Zend_Json::decode($scheduledDaysOfWeek);
 519                  if (is_array($scheduledDaysOfWeek)) {
 520                      // algorithm :
 521                      //1. First sort all the weekdays(stored as 0,1,2,3 etc in db) and find the closest weekday which is greater than currentWeekDay
 522                      //2. If found, set the next trigger date to the next weekday value in the same week.
 523                      //3. If not found, set the trigger date to the next first value.
 524                      $nextTriggerWeekDay = null;
 525                      sort($scheduledDaysOfWeek);
 526                      foreach ($scheduledDaysOfWeek as $index => $weekDay) {
 527                          if ($weekDay == $currentWeekDay) { //if today is the weekday selected
 528                              $scheduleWeekDayInTime = strtotime(date('Y-m-d', strtotime($weekDays[$currentWeekDay])) . ' ' . $scheduledTime);
 529                              if ($currentTime < $scheduleWeekDayInTime) { //if the scheduled time is greater than current time, selected today
 530                                  $nextTriggerWeekDay = $weekDay;
 531                                  break;
 532                              } else {
 533                                  //current time greater than scheduled time, get the next weekday
 534                                  if (count($scheduledDaysOfWeek) == 1) { //if only one weekday selected, then get next week
 535                                      $nextTime = date('Y-m-d', strtotime('next ' . $weekDays[$weekDay])) . ' ' . $scheduledTime;
 536                                  } else {
 537                                      $nextWeekDay = $scheduledDaysOfWeek[$index + 1]; // its the last day of the week i.e. sunday
 538                                      if (empty($nextWeekDay)) {
 539                                          $nextWeekDay = $scheduledDaysOfWeek[0];
 540                                      }
 541                                      $nextTime = date('Y-m-d', strtotime('next ' . $weekDays[$nextWeekDay])) . ' ' . $scheduledTime;
 542                                  }
 543                              }
 544                          } else if ($weekDay > $currentWeekDay) {
 545                              $nextTriggerWeekDay = $weekDay;
 546                              break;
 547                          }
 548                      }
 549  
 550                      if ($nextTime == null) {
 551                          if (!empty($nextTriggerWeekDay)) {
 552                              $nextTime = date("Y-m-d H:i:s", strtotime($weekDays[$nextTriggerWeekDay] . ' ' . $scheduledTime));
 553                          } else {
 554                              $nextTime = date("Y-m-d H:i:s", strtotime($weekDays[$scheduledDaysOfWeek[0]] . ' ' . $scheduledTime));
 555                          }
 556                      }
 557                  }
 558              }
 559              return $nextTime;
 560          }
 561          
 562          /**
 563           * get next triggertime for monthly
 564           * @param type $scheduledDayOfMonth
 565           * @param type $scheduledTime
 566           * @return <time>
 567           */
 568  		function getNextTriggerTimeForMonthlyByDate($scheduledDayOfMonth, $scheduledTime){
 569              $currentDayOfMonth = date('j', time());
 570              if($scheduledDayOfMonth) {
 571                  $scheduledDaysOfMonth = Zend_Json::decode($scheduledDayOfMonth);
 572                  if(is_array($scheduledDaysOfMonth)) {
 573                      // algorithm :
 574                      //1. First sort all the days in ascending order and find the closest day which is greater than currentDayOfMonth
 575                      //2. If found, set the next trigger date to the found value which is in the same month.
 576                      //3. If not found, set the trigger date to the next month's first selected value.
 577                      $nextTriggerDay = null;
 578                      sort($scheduledDaysOfMonth);
 579                      foreach ($scheduledDaysOfMonth as $day) {
 580                          if($day == $currentDayOfMonth) {
 581                              $currentTime = time();
 582                              $schTime = strtotime($date = date('Y').'-'.date('m').'-'.$day.' '.$scheduledTime);
 583                              if($schTime > $currentTime) {
 584                                  $nextTriggerDay = $day;
 585                                  break;
 586                              }
 587                          } elseif ($day > $currentDayOfMonth) {
 588                              $nextTriggerDay = $day;
 589                              break;
 590                          }
 591                      }
 592                      if(!empty($nextTriggerDay)) {
 593                          $firstDayofNextMonth = date('Y:m:d H:i:s', strtotime('first day of this month'));
 594                          $nextTime = date('Y:m:d', strtotime($firstDayofNextMonth.' + '.($nextTriggerDay-1).' days'));
 595                          $nextTime = $nextTime.' '.$scheduledTime;
 596                      } else {
 597                          $firstDayofNextMonth = date('Y:m:d H:i:s', strtotime('first day of next month'));
 598                          $nextTime = date('Y:m:d', strtotime($firstDayofNextMonth.' + '.($scheduledDaysOfMonth[0]-1).' days'));
 599                          $nextTime = $nextTime.' '.$scheduledTime;
 600                      }
 601                  }
 602              }
 603              return $nextTime;
 604          }
 605          
 606          /**
 607           * to get next trigger time for weekday of the month
 608           * @param type $scheduledWeekDayOfMonth
 609           * @param type $scheduledTime
 610           * @return <time>
 611           */
 612  		function getNextTriggerTimeForMonthlyByWeekDay($scheduledWeekDayOfMonth, $scheduledTime){
 613              $currentTime = time();
 614              $currentDayOfMonth = date('j',$currentTime);
 615              $scheduledTime = $this->getWFScheduleTime();
 616              if($scheduledWeekDayOfMonth == $currentDayOfMonth) {
 617                  $nextTime = date("Y-m-d H:i:s",strtotime('+1 month '.$scheduledTime));
 618              } else {
 619                  $monthInFullText = date('F',$currentTime);
 620                  $yearFullNumberic = date('Y',$currentTime);
 621                  if($scheduledWeekDayOfMonth < $currentDayOfMonth) {
 622                      $nextMonth = date("Y-m-d H:i:s",strtotime('next month'));
 623                      $monthInFullText = date('F',strtotime($nextMonth));
 624                  }
 625                  $nextTime = date("Y-m-d H:i:s",strtotime($scheduledWeekDayOfMonth.' '.$monthInFullText.' '.$yearFullNumberic.' '.$scheduledTime));
 626              }
 627              return $nextTime;
 628          }
 629          
 630          /**
 631           * to get next trigger time
 632           * @param type $annualDates
 633           * @param type $scheduledTime
 634           * @return <time>
 635           */
 636  		function getNextTriggerTimeForAnnualDates($annualDates, $scheduledTime){
 637              if($annualDates) {
 638                  $today = date('Y-m-d');
 639                  $annualDates = Zend_Json::decode($annualDates);
 640                  $nextTriggerDay = null;
 641                  // sort the dates
 642                  sort($annualDates);
 643                  $currentTime = time();
 644                  $currentDayOfMonth = date('Y-m-d',$currentTime);
 645                  foreach ($annualDates as $day) {
 646                      if($day == $currentDayOfMonth) {
 647                          $schTime = strtotime($day.' '.$scheduledTime);
 648                          if($schTime > $currentTime) {
 649                              $nextTriggerDay = $day;
 650                              break;
 651                          }
 652                      }else if ($day > $today) {
 653                          $nextTriggerDay = $day;
 654                          break;
 655                      }
 656                  }
 657                  if(!empty($nextTriggerDay)) {
 658                      $nextTime = date('Y:m:d H:i:s', strtotime($nextTriggerDay.' '.$scheduledTime));
 659                  } else {
 660                      $nextTriggerDay = $annualDates[0];
 661                      $nextTime = date('Y:m:d H:i:s', strtotime($nextTriggerDay.' '.$scheduledTime.'+1 year'));
 662                  }
 663              }
 664              return $nextTime;
 665          }
 666      }
 667  ?>


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