+/**
+ * @brief Call the front end worker
+ */
+function call_worker() {
+ if (!Config::get("system", "frontend_worker") OR !Config::get("system", "worker")) {
+ return;
+ }
+
+ $url = get_app()->get_baseurl()."/worker";
+ fetch_url($url, false, $redirects, 1);
+}
+
+/**
+ * @brief Call the front end worker if there aren't any active
+ */
+function call_worker_if_idle() {
+ if (!Config::get("system", "frontend_worker") OR !Config::get("system", "worker")) {
+ return;
+ }
+
+ // Do we have "proc_open"? Then we can fork the poller
+ if (function_exists("proc_open")) {
+ // When was the last time that we called the worker?
+ // Less than one minute? Then we quit
+ if ((time() - get_config("system", "worker_started")) < 60) {
+ return;
+ }
+
+ set_config("system", "worker_started", time());
+
+ // Do we have enough running workers? Then we quit here.
+ if (poller_too_much_workers()) {
+ // Cleaning dead processes
+ poller_kill_stale_workers();
+ get_app()->remove_inactive_processes();
+
+ return;
+ }
+
+ poller_run_cron();
+
+ logger('Call poller', LOGGER_DEBUG);
+
+ $args = array("php", "include/poller.php", "no_cron");
+ $a = get_app();
+ $a->proc_run($args);
+ return;
+ }
+
+ // We cannot execute background processes.
+ // We now run the processes from the frontend.
+ // This won't work with long running processes.
+ poller_run_cron();
+
+ clear_worker_processes();
+
+ $workers = q("SELECT COUNT(*) AS `processes` FROM `process` WHERE `command` = 'worker.php'");
+
+ if ($workers[0]["processes"] == 0) {
+ call_worker();
+ }
+}
+
+/**
+ * @brief Removes long running worker processes
+ */
+function clear_worker_processes() {
+ $timeout = Config::get("system", "frontend_worker_timeout", 10);
+
+ /// @todo We should clean up the corresponding workerqueue entries as well
+ q("DELETE FROM `process` WHERE `created` < '%s' AND `command` = 'worker.php'",
+ dbesc(datetime_convert('UTC','UTC',"now - ".$timeout." minutes")));
+}
+
+/**
+ * @brief Runs the cron processes
+ */
+function poller_run_cron() {
+ logger('Add cron entries', LOGGER_DEBUG);
+
+ // Check for spooled items
+ proc_run(PRIORITY_HIGH, "include/spool_post.php");
+
+ // Run the cron job that calls all other jobs
+ proc_run(PRIORITY_MEDIUM, "include/cron.php");
+
+ // Run the cronhooks job separately from cron for being able to use a different timing
+ proc_run(PRIORITY_MEDIUM, "include/cronhooks.php");
+
+ // Cleaning dead processes
+ poller_kill_stale_workers();
+}
+