Open Journal Systems  3.3.0
ScheduledTaskHelper.inc.php
1 <?php
2 
16 define('SCHEDULED_TASK_MESSAGE_TYPE_COMPLETED', 'common.completed');
17 define('SCHEDULED_TASK_MESSAGE_TYPE_ERROR', 'common.error');
18 define('SCHEDULED_TASK_MESSAGE_TYPE_WARNING', 'common.warning');
19 define('SCHEDULED_TASK_MESSAGE_TYPE_NOTICE', 'common.notice');
20 define('SCHEDULED_TASK_EXECUTION_LOG_DIR', 'scheduledTaskLogs');
21 
23 
25  var $_contactEmail;
26 
29 
36  function __construct($email = '', $contactName = '') {
37  if (!$email || !$contactName) {
38  $siteDao = DAORegistry::getDAO('SiteDAO'); /* @var $siteDao SiteDAO */
39  $site = $siteDao->getSite(); /* @var $site Site */
40  $email = $site->getLocalizedContactEmail();
41  $contactName = $site->getLocalizedContactName();
42  }
43 
44  $this->_contactEmail = $email;
45  $this->_contactName = $contactName;
46 
47  }
48 
53  function getMail() {
54  // Instantiate a mail object.
55  import('lib.pkp.classes.mail.Mail');
56  return new Mail();
57  }
58 
64  static function getTaskArgs($task) {
65  $args = array();
66  $index = 0;
67 
68  while(($arg = $task->getChildByName('arg', $index)) != null) {
69  array_push($args, $arg->getValue());
70  $index++;
71  }
72 
73  return $args;
74  }
75 
83  static function checkFrequency($className, $frequency) {
84  $isValid = true;
85  $taskDao = DAORegistry::getDAO('ScheduledTaskDAO'); /* @var $taskDao ScheduledTaskDAO */
86  $lastRunTime = $taskDao->getLastRunTime($className);
87 
88  // Check day of week
89  $dayOfWeek = $frequency->getAttribute('dayofweek');
90  if (isset($dayOfWeek)) {
91  $isValid = self::_isInRange($dayOfWeek, (int)date('w'), $lastRunTime, 'day', strtotime('-1 week'), strtotime('-1 day'));
92  }
93 
94  if ($isValid) {
95  // Check month
96  $month = $frequency->getAttribute('month');
97  if (isset($month)) {
98  $isValid = self::_isInRange($month, (int)date('n'), $lastRunTime, 'month', strtotime('-1 year'), strtotime('-1 month'));
99  }
100  }
101 
102  if ($isValid) {
103  // Check day
104  $day = $frequency->getAttribute('day');
105  if (isset($day)) {
106  $isValid = self::_isInRange($day, (int)date('j'), $lastRunTime, 'day', strtotime('-1 month'), strtotime('-1 day'));
107  }
108  }
109 
110  if ($isValid) {
111  // Check hour
112  $hour = $frequency->getAttribute('hour');
113  if (isset($hour)) {
114  $isValid = self::_isInRange($hour, (int)date('G'), $lastRunTime, 'hour', strtotime('-1 day'), strtotime('-1 hour'));
115  }
116  }
117 
118  if ($isValid) {
119  // Check minute
120  $minute = $frequency->getAttribute('minute');
121  if (isset($minute)) {
122  $isValid = self::_isInRange($minute, (int)date('i'), $lastRunTime, 'min', strtotime('-1 hour'), strtotime('-1 minute'));
123  }
124  }
125 
126  return $isValid;
127  }
128 
138  function notifyExecutionResult($id, $name, $result, $executionLogFile = '') {
139  $reportErrorOnly = Config::getVar('general', 'scheduled_tasks_report_error_only', true);
140 
141  if (!$result || !$reportErrorOnly) {
142  $message = $this->getMessage($executionLogFile);
143 
144  if ($result) {
145  // Success.
146  $type = SCHEDULED_TASK_MESSAGE_TYPE_COMPLETED;
147  } else {
148  // Error.
149  $type = SCHEDULED_TASK_MESSAGE_TYPE_ERROR;
150  }
151 
152  $subject = $name . ' - ' . $id . ' - ' . __($type);
153  return $this->_sendEmail($message, $subject);
154  }
155 
156  return false;
157  }
158 
164  function getMessage($executionLogFile) {
165  if (!$executionLogFile) {
166  return __('admin.scheduledTask.noLog');
167  }
168 
169  $request = Application::get()->getRequest();
170  $router = $request->getRouter();
171  $downloadLogUrl = $router->url($request, 'index', 'admin', 'downloadScheduledTaskLogFile', null, array('file' => basename($executionLogFile)));
172  return __('admin.scheduledTask.downloadLog', array(
173  'url' => $downloadLogUrl,
174  'softwareName' => __(Application::getNameKey()),
175  ));
176  }
177 
178  //
179  // Static methods.
180  //
184  static function clearExecutionLogs() {
185  import('lib.pkp.classes.file.PrivateFileManager');
186  $fileMgr = new PrivateFileManager();
187 
188  $fileMgr->rmtree($fileMgr->getBasePath() . DIRECTORY_SEPARATOR . SCHEDULED_TASK_EXECUTION_LOG_DIR);
189  }
190 
195  static function downloadExecutionLog($file) {
196  import('lib.pkp.classes.file.PrivateFileManager');
197  $fileMgr = new PrivateFileManager();
198 
199  $fileMgr->downloadByPath($fileMgr->getBasePath() . DIRECTORY_SEPARATOR . SCHEDULED_TASK_EXECUTION_LOG_DIR . DIRECTORY_SEPARATOR . $file);
200  }
201 
202 
203  //
204  // Private helper methods.
205  //
212  private function _sendEmail($message, $subject) {
213  $mail = $this->getMail();
214  $mail->addRecipient($this->_contactEmail, $this->_contactName);
215  $mail->setSubject($subject);
216  $mail->setBody($message);
217 
218  return $mail->send();
219  }
220 
231  private static function _isInRange($rangeStr, $currentValue, $lastTimestamp, $timeCompareStr, $passTimestamp, $blockTimestamp) {
232  $isValid = false;
233  $rangeArray = explode(',', $rangeStr);
234 
235  // If the last task run is newer than the block timestamp, do not execute the task again yet.
236  if ($lastTimestamp > $blockTimestamp) {
237  return false;
238  }
239 
240  // If the last task run is older than the pass timestamp, consider running the task.
241  if ($passTimestamp > $lastTimestamp) {
242  $isValid = true;
243  }
244 
245  for ($i = 0, $count = count($rangeArray); !$isValid && ($i < $count); $i++) {
246  if ($rangeArray[$i] == '*') {
247  // Is wildcard
248  $isValid = true;
249 
250  } if (is_numeric($rangeArray[$i])) {
251  // Is just a value
252  $isValid = ($currentValue == (int)$rangeArray[$i]);
253 
254  } else if (preg_match('/^(\d*)\-(\d*)$/', $rangeArray[$i], $matches)) {
255  // Is a range
256  $isValid = self::_isInNumericRange($currentValue, (int)$matches[1], (int)$matches[2]);
257 
258  } else if (preg_match('/^(.+)\/(\d+)$/', $rangeArray[$i], $matches)) {
259  // Is a range with a skip factor
260  $skipRangeStr = $matches[1];
261  $skipFactor = (int)$matches[2];
262 
263  if ($skipRangeStr == '*') {
264  $isValid = true;
265 
266  } else if (preg_match('/^(\d*)\-(\d*)$/', $skipRangeStr, $matches)) {
267  $isValid = self::_isInNumericRange($currentValue, (int)$matches[1], (int)$matches[2]);
268  }
269 
270  if ($isValid) {
271  // Check against skip factor
272  $isValid = (strtotime("-$skipFactor $timeCompareStr") > $lastTimestamp);
273  }
274  }
275  }
276 
277  return $isValid;
278  }
279 
287  private static function _isInNumericRange($value, $min, $max) {
288  return ($value >= $min && $value <= $max);
289  }
290 
291 }
292 
293 
PrivateFileManager
Class defining operations for private file management.
Definition: PrivateFileManager.inc.php:18
ScheduledTaskHelper\notifyExecutionResult
notifyExecutionResult($id, $name, $result, $executionLogFile='')
Definition: ScheduledTaskHelper.inc.php:144
DAORegistry\getDAO
static & getDAO($name, $dbconn=null)
Definition: DAORegistry.inc.php:57
Application\getNameKey
getNameKey()
Definition: Application.inc.php:68
ScheduledTaskHelper\downloadExecutionLog
static downloadExecutionLog($file)
Definition: ScheduledTaskHelper.inc.php:201
ScheduledTaskHelper
Helper class for common scheduled tasks operations.
Definition: ScheduledTaskHelper.inc.php:22
ScheduledTaskHelper\__construct
__construct($email='', $contactName='')
Definition: ScheduledTaskHelper.inc.php:42
ScheduledTaskHelper\getMail
getMail()
Definition: ScheduledTaskHelper.inc.php:59
ScheduledTaskHelper\clearExecutionLogs
static clearExecutionLogs()
Definition: ScheduledTaskHelper.inc.php:190
ScheduledTaskHelper\checkFrequency
static checkFrequency($className, $frequency)
Definition: ScheduledTaskHelper.inc.php:89
ScheduledTaskHelper\$_contactName
$_contactName
Definition: ScheduledTaskHelper.inc.php:34
Mail
Class defining basic operations for handling and sending emails.
Definition: Mail.inc.php:23
Config\getVar
static getVar($section, $key, $default=null)
Definition: Config.inc.php:35
ScheduledTaskHelper\$_contactEmail
$_contactEmail
Definition: ScheduledTaskHelper.inc.php:28
Seboettg\Collection\count
count()
Definition: ArrayListTrait.php:253
PKPApplication\get
static get()
Definition: PKPApplication.inc.php:235
ScheduledTaskHelper\getMessage
getMessage($executionLogFile)
Definition: ScheduledTaskHelper.inc.php:170
ScheduledTaskHelper\getTaskArgs
static getTaskArgs($task)
Definition: ScheduledTaskHelper.inc.php:70