Example #1
0
 public function testGetNextWithTimestamp()
 {
     $tz = new DateTimezone('Europe/Berlin');
     $dt = new DateTime('2014-12-31 23:42', $tz);
     $cron = new Cron('45 9 29 feb thu', $tz);
     $this->assertEquals(1709196300, $cron->getNext($dt->getTimestamp()));
 }
Example #2
0
 /**
  * Entry point for the back ground worker
  */
 public static function run()
 {
     $notifications = new Notifications();
     $subscriptions = new Subscriptions();
     $cron = new Cron($notifications, $subscriptions);
     $cron->pushNotifications();
 }
Example #3
0
 /**
  * Activate WP Currencies.
  *
  * What happens when WP Currencies is activated.
  *
  * @since 1.4.0
  */
 public static function activate()
 {
     self::create_tables();
     $cron = new Cron();
     $cron->schedule_updates();
     do_action('wp_currencies_activated');
 }
Example #4
0
 /**
  * @dataProvider isValidForProvider
  * @param int $time
  * @param string $expression
  * @param bool $expectedResult
  */
 public function testIsValidFor($time, $expression, $expectedResult)
 {
     $eventMock = $this->getMock('Magento\\Framework\\Event', [], [], '', false);
     $this->cron->setCronExpr($expression);
     $this->cron->setNow($time);
     $this->assertEquals($expectedResult, $this->cron->isValidFor($eventMock));
 }
Example #5
0
 function run($config)
 {
     $this->setConfig($config);
     $this->setDbAdapter();
     $this->setView();
     $this->setInit();
     $cron = new Cron($this->registry);
     $cron->index();
 }
Example #6
0
 static function poorMansCron()
 {
     $intervals = array("minute", "five", "fifteen", "hour", "week");
     foreach ($intervals as $interval) {
         $entity = getEntity(array("type" => "Cron", "metadata_name" => "interval", "metadata_value" => $interval));
         if (!$entity) {
             $entity = new Cron();
             $entity->interval = $interval;
             $entity->save();
         }
         Cron::run($interval, false);
     }
     return;
 }
Example #7
0
 static function run($interval, $ignore_last_run = true)
 {
     $phpbin = PHP_BINDIR . "/php";
     if ($ignore_last_run) {
         shell_exec('echo $phpbin -q ' . SITEPATH . 'cron/' . $interval . '.php | at now');
         return;
     }
     $entity = getEntity(array("type" => "Cron", "metadata_name" => "interval", "metadata_value" => $interval));
     if (!$entity) {
         $entity = new Cron();
         $entity->interval = $interval;
         $entity->save();
     }
     $last_ran = $entity->last_ran;
     if (!$last_ran) {
         $last_ran = 0;
     }
     switch ($interval) {
         case "minute":
             $seconds = 60;
             break;
         case "five":
             $seconds = 60 * 5;
             break;
         case "fifteen":
             $seconds = 60 * 15;
             break;
         case "hour":
             $seconds = 60 * 60;
             break;
         case "week":
         default:
             $seconds = 60 * 60 * 24 * 7;
             break;
     }
     $time = time();
     if ($time > $last_ran + $seconds) {
         $shell = $phpbin . ' -q ' . SITEPATH . 'cron/' . $interval . '.php > /dev/null 2>/dev/null &';
         shell_exec($shell);
         $last_ran = $time;
         $entity = getEntity(array("type" => "Cron", "metadata_name" => "interval", "metadata_value" => $interval));
         if ($entity) {
             $entity->last_ran = $last_ran;
             $entity->save();
         }
     }
     return;
 }
Example #8
0
 /**
  * 
  * Initializes configs for the APP to run
  */
 public static function initialize()
 {
     /**
      * Load all the configs from DB
      */
     //Change the default cache system, based on your config /config/cache.php
     Cache::$default = Core::config('cache.default');
     //is not loaded yet in Kohana::$config
     Kohana::$config->attach(new ConfigDB(), FALSE);
     //overwrite default Kohana init configs.
     Kohana::$base_url = Core::config('general.base_url');
     //enables friendly url @todo from config
     Kohana::$index_file = FALSE;
     //cookie salt for the app
     Cookie::$salt = Core::config('auth.cookie_salt');
     /* if (empty(Cookie::$salt)) {
     			// @TODO missing cookie salt : add warning message
     		} */
     // -- i18n Configuration and initialization -----------------------------------------
     I18n::initialize(Core::config('i18n.locale'), Core::config('i18n.charset'));
     //Loading the OC Routes
     // if (($init_routes = Kohana::find_file('config','routes')))
     // 	require_once $init_routes[0];//returns array of files but we need only 1 file
     //faster loading
     require_once APPPATH . 'config/routes.php';
     //getting the selected theme, and loading options
     Theme::initialize();
     //run crontab
     if (core::config('general.cron') == TRUE) {
         Cron::run();
     }
 }
Example #9
0
 function run()
 {
     global $ost;
     Cron::run();
     $ost->logDebug('Cron Job', 'Cron job executed [' . $_SERVER['REMOTE_ADDR'] . ']');
     $this->response(200, 'Completed');
 }
Example #10
0
 /**
  * 
  * Initializes configs for the APP to run
  */
 public static function initialize()
 {
     //enables friendly url
     Kohana::$index_file = FALSE;
     //temporary cookie salt in case of exception
     Cookie::$salt = 'cookie_oc_temp';
     //Change the default cache system, based on your config /config/cache.php
     Cache::$default = Core::config('cache.default');
     //loading configs from table config
     //is not loaded yet in Kohana::$config
     Kohana::$config->attach(new ConfigDB(), FALSE);
     //overwrite default Kohana init configs.
     Kohana::$base_url = Core::config('general.base_url');
     //cookie salt for the app
     Cookie::$salt = Core::config('auth.cookie_salt');
     // i18n Configuration and initialization
     I18n::initialize(Core::config('i18n.locale'), Core::config('i18n.charset'));
     //Loading the OC Routes
     require_once APPPATH . 'config/routes.php';
     //getting the selected theme, and loading options
     Theme::initialize();
     //run crontab
     if (core::config('general.cron') == TRUE) {
         Cron::run();
     }
 }
 public function __construct()
 {
     parent::__construct();
     $this->chmod();
     echo '<br />' . t('Done!') . '<br />';
     echo t('The Jobs Cron is working to complete successfully!');
 }
Example #12
0
 public function actionUpdate($id)
 {
     $form = new TestForm();
     if ($form->load($_POST)) {
         $test = Test::findOne($id);
         //Confere se usuário tem permissão para editar teste na origem OU no destino
         $source = $test->getSourceDomain()->one();
         $destination = $test->getDestinationDomain()->one();
         $permission = false;
         if ($source && RbacController::can('test/delete', $source->name)) {
             $permission = true;
         }
         if ($destination && RbacController::can('test/delete', $destination->name)) {
             $permission = true;
         }
         if (!$permission) {
             Yii::$app->getSession()->addFlash("warning", Yii::t("circuits", "You are not allowed to update a automated test involving these selected domains"));
             return false;
         }
         $cron = Cron::findOneTestTask($id);
         $cron->freq = $form->cron_value;
         $cron->status = Cron::STATUS_PROCESSING;
         if ($cron->save()) {
             Yii::$app->getSession()->addFlash("success", Yii::t("circuits", "Automated Test updated successfully"));
             return true;
         }
     }
     return false;
 }
Example #13
0
 function run()
 {
     //called by outside cron NOT autocron
     Cron::MailFetcher();
     Cron::TicketMonitor();
     cron::PurgeLogs();
 }
Example #14
0
 public static function newInstance()
 {
     if (!self::$instance instanceof self) {
         self::$instance = new self();
     }
     return self::$instance;
 }
Example #15
0
 public static function init()
 {
     if (!isset($_GET['cronTok'])) {
         return;
     }
     define('EDUCASK_ROOT', dirname(getcwd()));
     require_once EDUCASK_ROOT . '/core/classes/Bootstrap.php';
     Bootstrap::registerAutoloader();
     $database = Database::getInstance();
     $database->connect();
     if (!$database->isConnected()) {
         return;
     }
     Bootstrap::initializePlugins();
     $cron = new Cron($_GET['cronTok']);
     $cron->run();
 }
Example #16
0
 public function __construct()
 {
     if (isset(self::$current)) {
         throw new ConstructionException('Cannot construct more than one instance of singleton class Cron.');
     }
     $this->_parse_arguments();
     self::$current = $this;
 }
Example #17
0
function osc_runAlert($type = null, $last_exec = null)
{
    if (!in_array($type, array('HOURLY', 'DAILY', 'WEEKLY', 'INSTANT'))) {
        return;
    }
    if ($last_exec == null) {
        $cron = Cron::newInstance()->getCronByType($type);
        if (is_array($cron)) {
            $last_exec = $cron['d_last_exec'];
        } else {
            $last_exec = '0000-00-00 00:00:00';
        }
    }
    $internal_name = 'alert_email_hourly';
    switch ($type) {
        case 'HOURLY':
            $internal_name = 'alert_email_hourly';
            break;
        case 'DAILY':
            $internal_name = 'alert_email_daily';
            break;
        case 'WEEKLY':
            $internal_name = 'alert_email_weekly';
            break;
        case 'INSTANT':
            $internal_name = 'alert_email_instant';
            break;
    }
    $active = TRUE;
    $searches = Alerts::newInstance()->findByTypeGroup($type, $active);
    foreach ($searches as $s_search) {
        // Get if there're new ads on this search
        $json = $s_search['s_search'];
        $array_conditions = (array) json_decode($json);
        $new_search = Search::newInstance();
        $new_search->setJsonAlert($array_conditions);
        $new_search->addConditions(sprintf(" %st_item.dt_pub_date > '%s' ", DB_TABLE_PREFIX, $last_exec));
        $items = $new_search->doSearch();
        $totalItems = $new_search->count();
        if (count($items) > 0) {
            // If we have new items from last check
            // Catch the user subscribed to this search
            $users = Alerts::newInstance()->findUsersBySearchAndType($s_search['s_search'], $type, $active);
            if (count($users) > 0) {
                $ads = '';
                foreach ($items as $item) {
                    $ads .= '<a href="' . osc_item_url_ns($item['pk_i_id']) . '">' . $item['s_title'] . '</a><br/>';
                }
                foreach ($users as $user) {
                    osc_run_hook('hook_' . $internal_name, $user, $ads, $s_search, $items, $totalItems);
                    AlertsStats::newInstance()->increase(date('Y-m-d'));
                }
            }
        }
    }
}
Example #18
0
 /**
  * For simple expressions, zero out the time so the cron
  * matches user expectation and does not execute constantly.
  *
  * E.g., someone would not expect "Every day on Tuesday"
  * to run for every minute and hour on Tuesday.
  *
  * @param $field
  */
 protected function nilTime($field)
 {
     $order = array_search($field, $this->cron->ordered());
     if ($order > 1 && !$this->cron->hour->isDirty()) {
         $this->cron->hour->addSpecific(0);
     }
     if ($order > 0 && !$this->cron->minute->isDirty()) {
         $this->cron->minute->addSpecific(0);
     }
 }
Example #19
0
 static function start()
 {
     if (!Lock::isOn('cron-running-' . $_ENV['projectName'])) {
         if (Lock::on('cron-running-' . $_ENV['projectName'])) {
             Debug::out('Starting');
             Control::req('scripts/crons/config');
             while (!Lock::isOn('cron-off-' . $_ENV['projectName'])) {
                 $time = new Time();
                 //+	ensure running only every minute {
                 $parseTime = $time->format('YmdHi');
                 if (self::$lastParsedTime == $parseTime) {
                     sleep(2);
                     continue;
                 }
                 self::$lastParsedTime = $parseTime;
                 //+	}
                 //+	execute run items {
                 $run = self::getRun($time);
                 foreach ($run as $i) {
                     $item = self::$list[$i];
                     if (self::$running[$i]) {
                         $pid = pcntl_waitpid(self::$running[$i], $status, WNOHANG);
                         if ($pid == 0) {
                             //process is currently running, don't run again
                             continue;
                         } elseif ($pid == -1) {
                             Debug::out('Process error:', $item);
                             continue;
                         }
                     }
                     $pid = pcntl_fork();
                     if ($pid == -1) {
                         Debug::quit('Could not fork process', $item);
                     } elseif ($pid) {
                         //this is the parent
                         self::$running[$i] = $pid;
                     } else {
                         //this is the child
                         self::$args = $item[2];
                         $script = Config::userFileLocation($item[1], 'control/scripts/crons');
                         Control::req($script);
                         exit;
                     }
                 }
                 //+	}
             }
             Lock::off('cron-running-' . $_ENV['projectName']);
         } else {
             Debug::quit('Failed to lock "cron-running"');
         }
     } else {
         Debug::quit('Cron already running');
     }
 }
Example #20
0
 public function __construct()
 {
     $this->config = parse_ini_file(__DOCROOT__ . '/config.ini', true);
     Cron::$database_connect = mysql_connect($this->config['database']['host'], $this->config['database']['user'], $this->config['database']['password']);
     if (!Cron::$database_connect) {
         echo "Unable to connect to DB: " . mysql_error(Cron::$database_connect);
         exit;
     }
     mysql_query("SET NAMES 'UTF8'", Cron::$database_connect);
     if (!mysql_select_db($this->config['database']['name'], Cron::$database_connect)) {
         echo "Unable to select mydbname: " . mysql_error(Cron::$database_connect);
         exit;
     }
 }
 public function boot()
 {
     // Please note the different namespace
     // and please add a \ in front of your classes in the global namespace
     \Event::listen('cron.collectJobs', function () {
         \Cron::add('example1', '* * * * *', function () {
             $this->index();
             return 'No';
         });
         \Cron::add('example2', '*/2 * * * *', function () {
             // Do some crazy things successfully every two minute
             return null;
         });
         \Cron::add('disabled job', '0 * * * *', function () {
             // Do some crazy things successfully every hour
         }, false);
     });
 }
Example #22
0
 /**
  * @see CronInterface::run()
  */
 public static function run()
 {
     if (self::check() == true) {
         $last_run_daily_datetime = Registry::get_value("base_cron_last_run_daily_datetime");
         $last_run_weekly_datetime = Registry::get_value("base_cron_last_run_weekly_datetime");
         $last_run_daily_datetime_handler = new DatetimeHandler($last_run_daily_datetime);
         $last_run_weekly_datetime_handler = new DatetimeHandler($last_run_weekly_datetime);
         $current_datetime_handler = new DatetimeHandler(date("Y-m-d H:i:s"));
         if ($last_run_daily_datetime_handler->distance($current_datetime_handler) >= 86400) {
             $daily = true;
         } else {
             $daily = false;
         }
         if ($last_run_weekly_datetime_handler->distance($current_datetime_handler) >= 604800) {
             $weekly = true;
         } else {
             $weekly = false;
         }
         $cron_event = new CronEvent(self::$last_run_id, $daily, $weekly);
         $event_handler = new EventHandler($cron_event);
         if ($event_handler->get_success() == true) {
             if (self::$last_run_id + 1 > 256) {
                 Registry::set_value("base_cron_last_run_id", 1);
                 self::$last_run_id = 1;
             } else {
                 Registry::set_value("base_cron_last_run_id", self::$last_run_id + 1);
                 self::$last_run_id = self::$last_run_id + 1;
             }
             Registry::set_value("base_cron_last_run_datetime", date("Y-m-d H:i:s"));
             self::$last_run_datetime = date("Y-m-d H:i:s");
             if ($daily == true) {
                 Registry::set_value("base_cron_last_run_daily_datetime", date("Y-m-d H:i:s"));
             }
             if ($weekly == true) {
                 Registry::set_value("base_cron_last_run_weekly_datetime", date("Y-m-d H:i:s"));
             }
         }
     }
 }
Example #23
0
 function run_cron()
 {
     $cron = Cron::findByIdFrom('Cron', '1');
     $now = time();
     $last = $cron->getLastRunTime();
     if ($now - $last > POORMANSCRON_INTERVAL) {
         echo $cron->generateWebBug();
     }
 }
Example #24
0
 public function actionIndex()
 {
     $op = EnvUtil::getRequest("op");
     $id = intval(EnvUtil::getRequest("id"));
     if (EnvUtil::submitCheck("formhash")) {
         if ($op == "edit") {
             $dayNew = $_POST["weekdaynew"] != -1 ? -1 : $_POST["daynew"];
             if (strpos($_POST["minutenew"], ",") !== false) {
                 $minuteNew = explode(",", $_POST["minutenew"]);
                 foreach ($minuteNew as $key => $val) {
                     $minuteNew[$key] = $val = intval($val);
                     if ($val < 0 || 59 < $val) {
                         unset($minuteNew[$key]);
                     }
                 }
                 $minuteNew = array_slice(array_unique($minuteNew), 0, 12);
                 $minuteNew = implode("\t", $minuteNew);
             } else {
                 $minuteNew = intval($_POST["minutenew"]);
                 $minuteNew = 0 <= $minuteNew && $minuteNew < 60 ? $minuteNew : "";
             }
             $cronfile = $this->getRealCronFile($_POST["type"], $_POST["filenamenew"], $_POST["module"]);
             if (preg_match("/[\\\\\\/\\:\\*\\?\"\\<\\>\\|]+/", $_POST["filenamenew"])) {
                 $this->error(Ibos::lang("Crons filename illegal"));
             } elseif (!is_readable($cronfile)) {
                 $this->error(Ibos::lang("Crons filename invalid", "", array("{cronfile}" => $cronfile)));
             } else {
                 if ($_POST["weekdaynew"] == -1 && $dayNew == -1 && $_POST["hournew"] == -1 && $minuteNew === "") {
                     $this->error(Ibos::lang("Crons time invalid"));
                 }
             }
             $data = array("weekday" => $_POST["weekdaynew"], "day" => $dayNew, "hour" => $_POST["hournew"], "minute" => $minuteNew, "filename" => trim($_POST["filenamenew"]));
             $id && Cron::model()->modify($id, $data);
             Ibos::app()->cron->run($id);
         } elseif ($op == "delete") {
             if (!empty($_POST["delete"])) {
                 $ids = StringUtil::iImplode($_POST["delete"]);
                 Cron::model()->deleteAll(sprintf("cronid IN (%s) AND type='user'", $ids));
             }
         } else {
             if (isset($_POST["namenew"]) && !empty($_POST["namenew"])) {
                 foreach ($_POST["namenew"] as $id => $name) {
                     $newCron = array("name" => StringUtil::filterCleanHtml($_POST["namenew"][$id]), "available" => isset($_POST["availablenew"][$id]) ? 1 : 0);
                     if (isset($_POST["availablenew"][$id]) && empty($_POST["availablenew"][$id])) {
                         $newCron["nextrun"] = "0";
                     }
                     Cron::model()->modify($id, $newCron);
                 }
             }
             if (!empty($_POST["newname"])) {
                 $data = array("name" => StringUtil::ihtmlSpecialChars($_POST["newname"]), "type" => "user", "available" => "0", "weekday" => "-1", "day" => "-1", "hour" => "-1", "minute" => "", "nextrun" => TIMESTAMP);
                 Cron::model()->add($data);
             }
             $list = Cron::model()->fetchAll(array("select" => "cronid,filename,type,module"));
             foreach ($list as $cron) {
                 $cronFile = $this->getRealCronFile($cron["type"], $cron["filename"], $cron["module"]);
                 if (!file_exists($cronFile)) {
                     Cron::model()->modify($cron["cronid"], array("available" => 0, "nextrun" => 0));
                 }
             }
             CacheUtil::update("setting");
         }
         $this->success(Ibos::lang("Crons succeed"), $this->createUrl("cron/index"));
     } else {
         if ($op && in_array($op, array("edit", "run"))) {
             $cron = Cron::model()->fetchByPk($id);
             if (!$cron) {
                 $this->error("Cron not found");
             }
             $cron["filename"] = str_replace(array("..", "/", "\\"), array("", "", ""), $cron["filename"]);
             if ($op == "edit") {
                 $this->render("edit", array("cron" => $cron));
             } elseif ($op == "run") {
                 $file = $this->getRealCronFile($cron["type"], $cron["filename"], $cron["module"]);
                 if (!file_exists($file)) {
                     $this->error(Ibos::lang("Crons run invalid", "", array("{cronfile}" => $file)));
                 } else {
                     Ibos::app()->cron->run($cron["cronid"]);
                     $this->success(Ibos::lang("Crons run succeed"), $this->createUrl("cron/index"));
                 }
             }
         } else {
             $list = Cron::model()->fetchAll(array("order" => "type desc"));
             $this->handleCronList($list);
             $this->render("index", array("list" => $list));
         }
     }
 }
 function updatePref($var, &$errors)
 {
     if (!$var || $errors) {
         return false;
     }
     $f = array();
     $f['helpdesk_url'] = array('type' => 'string', 'required' => 1, 'error' => 'Assistência técnica URlnecessário');
     //TODO: Add url validation
     $f['helpdesk_title'] = array('type' => 'string', 'required' => 1, 'error' => 'Título da Assistência Técnica exigido');
     $f['default_dept_id'] = array('type' => 'int', 'required' => 1, 'error' => 'Departamento Padrão necessário');
     $f['default_email_id'] = array('type' => 'int', 'required' => 1, 'error' => 'E-mail padrão exigido');
     $f['default_template_id'] = array('type' => 'int', 'required' => 1, 'error' => 'Você deve selecionar modelo.');
     $f['staff_session_timeout'] = array('type' => 'int', 'required' => 1, 'error' => 'Digite tempo inativo em minutos');
     $f['client_session_timeout'] = array('type' => 'int', 'required' => 1, 'error' => 'Digite tempo inativo em minutos');
     $f['time_format'] = array('type' => 'string', 'required' => 1, 'error' => 'Formato de tempo necessário');
     //TODO: Add date format validation
     $f['date_format'] = array('type' => 'string', 'required' => 1, 'error' => 'Formato da data requerida');
     $f['datetime_format'] = array('type' => 'string', 'required' => 1, 'error' => 'Formato de data e hora necessária');
     $f['daydatetime_format'] = array('type' => 'string', 'required' => 1, 'error' => 'Formato dia, data e hora necessária');
     $f['admin_email'] = array('type' => 'email', 'required' => 1, 'error' => 'E-mail válido necessário');
     $f['autolock_minutes'] = array('type' => 'int', 'required' => 1, 'error' => 'Digite o tempo de bloqueio em minutos');
     //TODO: check option fields for validity.
     //do the validation.
     $val = new Validator();
     $val->setFields($f);
     if (!$val->validate($var)) {
         $errors = array_merge($errors, $val->errors());
     }
     if ($var['ticket_alert_active'] && (!isset($var['ticket_alert_admin']) && !isset($var['ticket_alert_dept_manager']) && !isset($var['ticket_alert_dept_members']))) {
         $errors['ticket_alert_active'] = 'Sem destinatário(s) selecionado';
     }
     if ($var['message_alert_active'] && (!isset($var['message_alert_laststaff']) && !isset($var['message_alert_assigned']) && !isset($var['message_alert_dept_manager']))) {
         $errors['message_alert_active'] = 'Sem destinatário(s) selecionado';
     }
     if ($var['note_alert_active'] && (!isset($var['note_alert_laststaff']) && !isset($var['note_alert_assigned']) && !isset($var['note_alert_dept_manager']))) {
         $errors['note_alert_active'] = 'Sem destinatário(s) selecionado';
     }
     if ($var['strip_quoted_reply'] && !$var['reply_separator']) {
         $errors['reply_separator'] = 'Separador de resposta necessário (?)';
     }
     if ($var['enable_captcha']) {
         if (!extension_loaded('gd')) {
             $errors['enable_captcha'] = 'Extensão GD necessária';
         } elseif (!function_exists('imagepng')) {
             $errors['enable_captcha'] = 'Suporte PNG necessário para a imagem captcha';
         }
     }
     if (!$errors['admin_email'] && Email::getIdByEmail($var['admin_email'])) {
         //Make sure admin email is not also a system email.
         $errors['admin_email'] = 'E-mail já está configurado como e-mail do sistema';
     }
     if ($errors) {
         return false;
     }
     //No go!
     //We are good to go...blanket update!
     $sql = 'UPDATE ' . CONFIG_TABLE . ' SET isonline=' . db_input($var['isonline']) . ',timezone_offset=' . db_input($var['timezone_offset']) . ',enable_daylight_saving=' . db_input(isset($var['enable_daylight_saving']) ? 1 : 0) . ',staff_ip_binding=' . db_input(isset($var['staff_ip_binding']) ? 1 : 0) . ',staff_max_logins=' . db_input($var['staff_max_logins']) . ',staff_login_timeout=' . db_input($var['staff_login_timeout']) . ',staff_session_timeout=' . db_input($var['staff_session_timeout']) . ',client_max_logins=' . db_input($var['client_max_logins']) . ',client_login_timeout=' . db_input($var['client_login_timeout']) . ',client_session_timeout=' . db_input($var['client_session_timeout']) . ',max_page_size=' . db_input($var['max_page_size']) . ',log_level=' . db_input($var['log_level']) . ',log_graceperiod=' . db_input($var['log_graceperiod']) . ',max_open_tickets=' . db_input($var['max_open_tickets']) . ',autolock_minutes=' . db_input($var['autolock_minutes']) . ',overdue_grace_period=' . db_input($var['overdue_grace_period']) . ',alert_email_id=' . db_input($var['alert_email_id']) . ',default_email_id=' . db_input($var['default_email_id']) . ',default_dept_id=' . db_input($var['default_dept_id']) . ',default_priority_id=' . db_input($var['default_priority_id']) . ',default_template_id=' . db_input($var['default_template_id']) . ',default_smtp_id=' . db_input($var['default_smtp_id']) . ',spoof_default_smtp=' . db_input($var['default_smtp'] && isset($var['spoof_default_smtp']) ? 1 : 0) . ',clickable_urls=' . db_input(isset($var['clickable_urls']) ? 1 : 0) . ',allow_priority_change=' . db_input(isset($var['allow_priority_change']) ? 1 : 0) . ',use_email_priority=' . db_input(isset($var['use_email_priority']) ? 1 : 0) . ',enable_captcha=' . db_input(isset($var['enable_captcha']) ? 1 : 0) . ',enable_auto_cron=' . db_input(isset($var['enable_auto_cron']) ? 1 : 0) . ',enable_mail_fetch=' . db_input(isset($var['enable_mail_fetch']) ? 1 : 0) . ',enable_email_piping=' . db_input(isset($var['enable_email_piping']) ? 1 : 0) . ',send_sql_errors=' . db_input(isset($var['send_sql_errors']) ? 1 : 0) . ',send_login_errors=' . db_input(isset($var['send_login_errors']) ? 1 : 0) . ',save_email_headers=' . db_input(isset($var['save_email_headers']) ? 1 : 0) . ',strip_quoted_reply=' . db_input(isset($var['strip_quoted_reply']) ? 1 : 0) . ',log_ticket_activity=' . db_input(isset($var['log_ticket_activity']) ? 1 : 0) . ',ticket_autoresponder=' . db_input($var['ticket_autoresponder']) . ',message_autoresponder=' . db_input($var['message_autoresponder']) . ',ticket_notice_active=' . db_input($var['ticket_notice_active']) . ',ticket_alert_active=' . db_input($var['ticket_alert_active']) . ',ticket_alert_admin=' . db_input(isset($var['ticket_alert_admin']) ? 1 : 0) . ',ticket_alert_dept_manager=' . db_input(isset($var['ticket_alert_dept_manager']) ? 1 : 0) . ',ticket_alert_dept_members=' . db_input(isset($var['ticket_alert_dept_members']) ? 1 : 0) . ',message_alert_active=' . db_input($var['message_alert_active']) . ',message_alert_laststaff=' . db_input(isset($var['message_alert_laststaff']) ? 1 : 0) . ',message_alert_assigned=' . db_input(isset($var['message_alert_assigned']) ? 1 : 0) . ',message_alert_dept_manager=' . db_input(isset($var['message_alert_dept_manager']) ? 1 : 0) . ',note_alert_active=' . db_input($var['note_alert_active']) . ',note_alert_laststaff=' . db_input(isset($var['note_alert_laststaff']) ? 1 : 0) . ',note_alert_assigned=' . db_input(isset($var['note_alert_assigned']) ? 1 : 0) . ',note_alert_dept_manager=' . db_input(isset($var['note_alert_dept_manager']) ? 1 : 0) . ',overdue_alert_active=' . db_input($var['overdue_alert_active']) . ',overdue_alert_assigned=' . db_input(isset($var['overdue_alert_assigned']) ? 1 : 0) . ',overdue_alert_dept_manager=' . db_input(isset($var['overdue_alert_dept_manager']) ? 1 : 0) . ',overdue_alert_dept_members=' . db_input(isset($var['overdue_alert_dept_members']) ? 1 : 0) . ',auto_assign_reopened_tickets=' . db_input(isset($var['auto_assign_reopened_tickets']) ? 1 : 0) . ',show_assigned_tickets=' . db_input(isset($var['show_assigned_tickets']) ? 1 : 0) . ',show_answered_tickets=' . db_input(isset($var['show_answered_tickets']) ? 1 : 0) . ',hide_staff_name=' . db_input(isset($var['hide_staff_name']) ? 1 : 0) . ',overlimit_notice_active=' . db_input($var['overlimit_notice_active']) . ',random_ticket_ids=' . db_input($var['random_ticket_ids']) . ',time_format=' . db_input($var['time_format']) . ',date_format=' . db_input($var['date_format']) . ',datetime_format=' . db_input($var['datetime_format']) . ',daydatetime_format=' . db_input($var['daydatetime_format']) . ',reply_separator=' . db_input(trim($var['reply_separator'])) . ',admin_email=' . db_input($var['admin_email']) . ',helpdesk_title=' . db_input($var['helpdesk_title']) . ',helpdesk_url=' . db_input($var['helpdesk_url']) . ' WHERE id=' . $this->getId();
     //echo $sql;
     if (db_query($sql)) {
         if (db_affected_rows()) {
             //Something actually changed!!!!
             $this->reload();
             //Reload the new info.
             require_once INCLUDE_DIR . 'class.cron.php';
             Sys::purgeLogs();
             //Cleanup the logs --- too bad if it was a mistaken config.
             Cron::TicketMonitor();
             //Age & cleanup
         }
         return true;
     }
     return false;
 }
Example #26
0
if ($sec < 180 || !$ost || $ost->isUpgradePending())
    ob_end_clean();

require_once(INCLUDE_DIR.'class.cron.php');

// Clear staff obj to avoid false credit internal notes & auto-assignment
$thisstaff = null;

// Release the session to prevent locking a future request while this is
// running
$_SESSION['lastcroncall'] = time();
session_write_close();

// Age tickets: We're going to age tickets regardless of cron settings.
Cron::TicketMonitor();

// Run file purging about every 20 cron runs (1h40 on a five minute cron)
if (mt_rand(1, 20) == 4)
    Cron::CleanOrphanedFiles();

if($cfg && $cfg->isAutoCronEnabled()) { //ONLY fetch tickets if autocron is enabled!
    Cron::MailFetcher();  //Fetch mail.
    $ost->logDebug(_S('Auto Cron'), sprintf(_S('Mail fetcher cron call [%s]'), $caller));
}

$data = array('autocron'=>true);
Signal::send('cron', $data);

ob_end_clean();
?>
Example #27
0
 public function gibbactuRaw()
 {
     $crons = new Cron($this->db);
     $cron = $crons->load(array('name = ?', 'gibbactu'));
     //On va récupérer les messages :
     $url = "http://forum.hardware.fr/forum2.php?post=177180&cat=5&config=hfr.inc&cache=&page=1&sondage=0&owntopic=0&word=GIBBACTU&firstnum=" . $cron->last_id . "&currentnum=0&filter=1";
     //echo $url."<br/>";
     $ch = curl_init();
     curl_setopt($ch, CURLOPT_URL, $url);
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
     $html = curl_exec($ch);
     libxml_use_internal_errors(true);
     $dom = new DOMDocument();
     @$dom->loadHTML($html);
     @($xpath = new DomXpath($dom));
     $divsMessage = $xpath->query("//table[@class='messagetable']");
     $newActus = array();
     $last_id = $cron->last_id;
     foreach ($divsMessage as $key => $node) {
         $newActu = array();
         //echo $dom->saveHTML($node);
         //var_dump($xpath->query('.//td[@class = "messCase2"]//a[contains(@href, "profil-")]', $node)->item(0)->getAttribute('href')) ;
         //Le contenu du message
         $divActus = $xpath->query('.//div[starts-with(@id, "para")]', $node);
         if (!$divActus->length) {
             //c'est la pub, on skip
             //echo "<< la pub\n";
             continue;
         }
         //Check le smiley [:gibbactu]
         $checkSmileyGA = $xpath->query('.//img[contains(@title, "[:gibbactu]")]', $node)->item(0);
         if (!$checkSmileyGA) {
             //pas de smiley, on skip
             //echo "<< pas de smiley\n";
             continue;
         }
         //le message est candidat à l'actu, on sauvegarde le contenu du message pour le post Process
         $newActu['content_raw'] = $dom->saveHTML($node);
         $newActus[] = $newActu;
         //On enregistre l'ID du message pour le cron.
         $divURL = $xpath->query('.//a[@class="cLink"]', $node);
         $newActu['hfr_url'] = $divURL->item(0)->getAttribute('href');
         $last_id = str_replace('t', '', parse_url($newActu['hfr_url'])['fragment']) + 1;
         echo $last_id . "\n";
     }
     //Mise à jour du CRON avec le last_ID
     $cron->date_last_executed = date('Y-m-d H:i:s');
     $cron->last_id = $last_id;
     $cron->save();
     //On ajoute en les actus pour le PostProcess
     $actu = new Actu($this->db);
     foreach ($newActus as $actus) {
         $actu->content_raw = $actus['content_raw'];
         $actu->content_raw = $actus['content_raw'];
         $actu->save();
         $actu->reset();
     }
     libxml_use_internal_errors(false);
     $this->f3->set('report', 'Actu(s) ajoutée(s) :' . count($newActus));
     echo Template::instance()->render('cron.htm');
 }
Example #28
0
 /**
  *  Tests the Cron run route with setting up the security key and with sending the right key
  *
  *  @covers \Liebig\Cron\CronServiceProvider
  */
 public function testRunRouteWithKeyWithCorrectSendKey()
 {
     \Event::listen('cron.collectJobs', function () {
         Cron::add('test1', "* * * * *", function () {
         });
         Cron::add('test2', "* * * * *", function () {
             return 'No';
         });
     });
     if ($this->laravelVersion >= 5) {
         \Config::set('liebigCron.cronKey', 'yT7yt3sa4tg5vtlLWbofF95v65FSWWZ8');
         \Config::set('liebigCron.logOnlyErrorJobsToDatabase', false);
     } else {
         \Config::set('cron::cronKey', 'yT7yt3sa4tg5vtlLWbofF95v65FSWWZ8');
         \Config::set('cron::logOnlyErrorJobsToDatabase', false);
     }
     $response = $this->call('GET', 'cron.php', array('key' => 'yT7yt3sa4tg5vtlLWbofF95v65FSWWZ8'));
     $this->assertEquals(200, $response->getStatusCode());
     $this->assertEquals(1, \Liebig\Cron\Models\Manager::count());
     $this->assertEquals(2, \Liebig\Cron\Models\Job::count());
     $jobs = \Liebig\Cron\Models\Job::all();
     $this->assertEquals(2, count($jobs));
     $this->assertEquals('test1', $jobs[0]->name);
     $this->assertEquals('', $jobs[0]->return);
     $this->assertEquals('test2', $jobs[1]->name);
     $this->assertEquals('No', $jobs[1]->return);
 }
Example #29
0
            $next += 24 * 3600;
        }
        $next_text = date('Y-m-d H:i:s', $next);
        Cron::newInstance()->update(array('d_last_exec' => $now_text, 'd_next_exec' => $next_text), array('e_type' => 'DAILY'));
    } else {
        //too early for crons
    }
}
// WEEKLY CRONS
$crons = Cron::newInstance()->getCronByType('WEEKLY');
if (isset($crons[0])) {
    $cron = $crons[0];
    unset($crons);
    $now_text = date('Y-m-d H:i:s');
    $now = strtotime($now_text);
    $next = strtotime($cron['d_next_exec']);
    if ($now - $next >= -10) {
        //(7*24*3600-10)) {
        // executing HOURLY crons
        include_once "cron.weekly.php";
        // update the database
        while ($next <= $now) {
            $next += 7 * 24 * 3600;
        }
        $next_text = date('Y-m-d H:i:s', $next);
        Cron::newInstance()->update(array('d_last_exec' => $now_text, 'd_next_exec' => $next_text), array('e_type' => 'WEEKLY'));
    } else {
        //too early for crons
    }
}
osc_run_hook('cron');
Example #30
0
#!/usr/bin/php -q

<?php 
set_time_limit(0);
if (!@$argc) {
    die("<p>script can only be run from command line");
}
#error_reporting(0);
define("_ABSPATH", dirname(dirname(__FILE__)));
require_once _ABSPATH . '/lib/Cron.php';
define_syslog_variables();
$cron = new Cron();
$cron->run();