1<?php 2 3class Scheduler_Utils 4{ 5 6 /** 7 * Checks if a cron should run at a time. 8 * 9 * @param string|\DateTime $time Relative calculation date 10 * @param $cron string A cron time expression (ex.: 0 0 * * *) 11 * @return bool true if should run, false otherwise. 12 * @throws \Scheduler\Exception\CrontimeFormatException 13 */ 14 public static function is_time_cron($time, $cron) 15 { 16 if (! self::validate_cron_time_format($cron)) { 17 throw new Scheduler\Exception\CrontimeFormatException(tra('Invalid cron time format')); 18 } 19 20 $cronEx = Cron\CronExpression::factory($cron); 21 return $cronEx->isDue($time); 22 } 23 24 /** 25 * Validate a cron time string 26 * 27 * @param $cron string A cron time expression (ex.: 0 0 * * *) 28 * @return bool true if valid, false otherwise 29 */ 30 public static function validate_cron_time_format($cron) 31 { 32 return Cron\CronExpression::isValidExpression($cron); 33 } 34 35 /** 36 * Parse users/emails to send notifications 37 * 38 * @param string $prefName The name of the preference that contains the list of users/emails to parse 39 * 40 * @return array An array with valid users/emails to notify 41 * @throws Exception 42 */ 43 public static function getSchedulerNotificationUsers($prefName) 44 { 45 46 global $tikilib; 47 48 $notificationUsers = $tikilib->get_preference($prefName); 49 50 $usersLib = TikiLib::lib('user'); 51 $logsLib = TikiLib::lib('logs'); 52 53 $users = []; 54 $invalid = []; 55 56 if (empty($notificationUsers)) { 57 return $usersLib->get_group_users('Admins', 0, -1, '*'); 58 } 59 60 $parts = explode(',', $notificationUsers); 61 62 foreach ($parts as $target) { 63 $target = trim($target); 64 65 if ($usersLib->user_exists($target)) { 66 $user = $usersLib->get_user_info($target); 67 $users[] = $user; 68 continue; 69 } 70 71 if ($usersLib->user_exists_by_email($target)) { 72 $userLogin = $usersLib->get_user_by_email($target); 73 $user = $usersLib->get_user_info($userLogin); 74 $users[] = $user; 75 continue; 76 } 77 78 if (filter_var($target, FILTER_VALIDATE_EMAIL)) { 79 $users[] = [ 80 'email' => $target 81 ]; 82 continue; 83 }; 84 85 $invalid[] = $target; 86 } 87 88 if (! empty($invalid)) { 89 $error_message = tr("Found invalid user(s)/email(s) to send notification on preference %0. Invalid users/emails: %1", $prefName, implode(', ', $invalid)); 90 $logsLib->add_log('Scheduler error', $error_message); 91 } 92 93 return $users; 94 } 95 96 97 /** 98 * Get previous run date. 99 * 100 * @param $cron string A cron time expression (ex.: 0 0 * * *) 101 * @return number timestamp in seconds. 102 * @throws \Scheduler\Exception\CrontimeFormatException 103 */ 104 public static function get_previous_run_date($cron) 105 { 106 if (! self::validate_cron_time_format($cron)) { 107 throw new Scheduler\Exception\CrontimeFormatException(tra('Invalid cron time format')); 108 } 109 $cron = Cron\CronExpression::factory($cron); 110 return $cron->getPreviousRunDate()->getTimestamp(); 111 } 112} 113