MDL-60425 blog: Remove empty line
[moodle.git] / lib / cronlib.php
blob589af74503f8a64f29694861bef77c1269264c4d
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * Cron functions.
20 * @package core
21 * @subpackage admin
22 * @copyright 1999 onwards Martin Dougiamas http://dougiamas.com
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26 /**
27 * Execute cron tasks
29 function cron_run() {
30 global $DB, $CFG, $OUTPUT;
32 if (CLI_MAINTENANCE) {
33 echo "CLI maintenance mode active, cron execution suspended.\n";
34 exit(1);
37 if (moodle_needs_upgrading()) {
38 echo "Moodle upgrade pending, cron execution suspended.\n";
39 exit(1);
42 require_once($CFG->libdir.'/adminlib.php');
44 if (!empty($CFG->showcronsql)) {
45 $DB->set_debug(true);
47 if (!empty($CFG->showcrondebugging)) {
48 set_debugging(DEBUG_DEVELOPER, true);
51 core_php_time_limit::raise();
52 $starttime = microtime();
54 // Increase memory limit
55 raise_memory_limit(MEMORY_EXTRA);
57 // Emulate normal session - we use admin accoutn by default
58 cron_setup_user();
60 // Start output log
61 $timenow = time();
62 mtrace("Server Time: ".date('r', $timenow)."\n\n");
64 // Run all scheduled tasks.
65 while (!\core\task\manager::static_caches_cleared_since($timenow) &&
66 $task = \core\task\manager::get_next_scheduled_task($timenow)) {
67 cron_run_inner_scheduled_task($task);
68 unset($task);
71 // Run all adhoc tasks.
72 while (!\core\task\manager::static_caches_cleared_since($timenow) &&
73 $task = \core\task\manager::get_next_adhoc_task($timenow)) {
74 cron_run_inner_adhoc_task($task);
75 unset($task);
78 mtrace("Cron script completed correctly");
80 gc_collect_cycles();
81 mtrace('Cron completed at ' . date('H:i:s') . '. Memory used ' . display_size(memory_get_usage()) . '.');
82 $difftime = microtime_diff($starttime, microtime());
83 mtrace("Execution took ".$difftime." seconds");
86 /**
87 * Shared code that handles running of a single scheduled task within the cron.
89 * Not intended for calling directly outside of this library!
91 * @param \core\task\task_base $task
93 function cron_run_inner_scheduled_task(\core\task\task_base $task) {
94 global $CFG, $DB;
96 $fullname = $task->get_name() . ' (' . get_class($task) . ')';
97 mtrace('Execute scheduled task: ' . $fullname);
98 cron_trace_time_and_memory();
99 $predbqueries = null;
100 $predbqueries = $DB->perf_get_queries();
101 $pretime = microtime(1);
102 try {
103 get_mailer('buffer');
104 cron_prepare_core_renderer();
105 $task->execute();
106 if ($DB->is_transaction_started()) {
107 throw new coding_exception("Task left transaction open");
109 if (isset($predbqueries)) {
110 mtrace("... used " . ($DB->perf_get_queries() - $predbqueries) . " dbqueries");
111 mtrace("... used " . (microtime(1) - $pretime) . " seconds");
113 mtrace('Scheduled task complete: ' . $fullname);
114 \core\task\manager::scheduled_task_complete($task);
115 } catch (Exception $e) {
116 if ($DB && $DB->is_transaction_started()) {
117 error_log('Database transaction aborted automatically in ' . get_class($task));
118 $DB->force_transaction_rollback();
120 if (isset($predbqueries)) {
121 mtrace("... used " . ($DB->perf_get_queries() - $predbqueries) . " dbqueries");
122 mtrace("... used " . (microtime(1) - $pretime) . " seconds");
124 mtrace('Scheduled task failed: ' . $fullname . ',' . $e->getMessage());
125 if ($CFG->debugdeveloper) {
126 if (!empty($e->debuginfo)) {
127 mtrace("Debug info:");
128 mtrace($e->debuginfo);
130 mtrace("Backtrace:");
131 mtrace(format_backtrace($e->getTrace(), true));
133 \core\task\manager::scheduled_task_failed($task);
134 } finally {
135 cron_prepare_core_renderer(true);
137 get_mailer('close');
141 * Shared code that handles running of a single adhoc task within the cron.
143 * @param \core\task\adhoc_task $task
145 function cron_run_inner_adhoc_task(\core\task\adhoc_task $task) {
146 global $DB, $CFG;
147 mtrace("Execute adhoc task: " . get_class($task));
148 cron_trace_time_and_memory();
149 $predbqueries = null;
150 $predbqueries = $DB->perf_get_queries();
151 $pretime = microtime(1);
153 if ($userid = $task->get_userid()) {
154 // This task has a userid specified.
155 if ($user = \core_user::get_user($userid)) {
156 // User found. Check that they are suitable.
157 try {
158 \core_user::require_active_user($user, true, true);
159 } catch (moodle_exception $e) {
160 mtrace("User {$userid} cannot be used to run an adhoc task: " . get_class($task) . ". Cancelling task.");
161 $user = null;
163 } else {
164 // Unable to find the user for this task.
165 // A user missing in the database will never reappear.
166 mtrace("User {$userid} could not be found for adhoc task: " . get_class($task) . ". Cancelling task.");
169 if (empty($user)) {
170 // A user missing in the database will never reappear so the task needs to be failed to ensure that locks are removed,
171 // and then removed to prevent future runs.
172 // A task running as a user should only be run as that user.
173 \core\task\manager::adhoc_task_failed($task);
174 $DB->delete_records('task_adhoc', ['id' => $task->get_id()]);
176 return;
179 cron_setup_user($user);
182 try {
183 get_mailer('buffer');
184 cron_prepare_core_renderer();
185 $task->execute();
186 if ($DB->is_transaction_started()) {
187 throw new coding_exception("Task left transaction open");
189 if (isset($predbqueries)) {
190 mtrace("... used " . ($DB->perf_get_queries() - $predbqueries) . " dbqueries");
191 mtrace("... used " . (microtime(1) - $pretime) . " seconds");
193 mtrace("Adhoc task complete: " . get_class($task));
194 \core\task\manager::adhoc_task_complete($task);
195 } catch (Exception $e) {
196 if ($DB && $DB->is_transaction_started()) {
197 error_log('Database transaction aborted automatically in ' . get_class($task));
198 $DB->force_transaction_rollback();
200 if (isset($predbqueries)) {
201 mtrace("... used " . ($DB->perf_get_queries() - $predbqueries) . " dbqueries");
202 mtrace("... used " . (microtime(1) - $pretime) . " seconds");
204 mtrace("Adhoc task failed: " . get_class($task) . "," . $e->getMessage());
205 if ($CFG->debugdeveloper) {
206 if (!empty($e->debuginfo)) {
207 mtrace("Debug info:");
208 mtrace($e->debuginfo);
210 mtrace("Backtrace:");
211 mtrace(format_backtrace($e->getTrace(), true));
213 \core\task\manager::adhoc_task_failed($task);
214 } finally {
215 // Reset back to the standard admin user.
216 cron_setup_user();
217 cron_prepare_core_renderer(true);
219 get_mailer('close');
223 * Runs a single cron task. This function assumes it is displaying output in pseudo-CLI mode.
225 * The function will fail if the task is disabled.
227 * Warning: Because this function closes the browser session, it may not be safe to continue
228 * with other processing (other than displaying the rest of the page) after using this function!
230 * @param \core\task\scheduled_task $task Task to run
231 * @return bool True if cron run successful
233 function cron_run_single_task(\core\task\scheduled_task $task) {
234 global $CFG, $DB, $USER;
236 if (CLI_MAINTENANCE) {
237 echo "CLI maintenance mode active, cron execution suspended.\n";
238 return false;
241 if (moodle_needs_upgrading()) {
242 echo "Moodle upgrade pending, cron execution suspended.\n";
243 return false;
246 // Check task and component is not disabled.
247 $taskname = get_class($task);
248 if ($task->get_disabled()) {
249 echo "Task is disabled ($taskname).\n";
250 return false;
252 $component = $task->get_component();
253 if ($plugininfo = core_plugin_manager::instance()->get_plugin_info($component)) {
254 if ($plugininfo->is_enabled() === false && !$task->get_run_if_component_disabled()) {
255 echo "Component is not enabled ($component).\n";
256 return false;
260 // Enable debugging features as per config settings.
261 if (!empty($CFG->showcronsql)) {
262 $DB->set_debug(true);
264 if (!empty($CFG->showcrondebugging)) {
265 set_debugging(DEBUG_DEVELOPER, true);
268 // Increase time and memory limits.
269 core_php_time_limit::raise();
270 raise_memory_limit(MEMORY_EXTRA);
272 // Switch to admin account for cron tasks, but close the session so we don't send this stuff
273 // to the browser.
274 session_write_close();
275 $realuser = clone($USER);
276 cron_setup_user(null, null, true);
278 // Get lock for cron task.
279 $cronlockfactory = \core\lock\lock_config::get_lock_factory('cron');
280 if (!$cronlock = $cronlockfactory->get_lock('core_cron', 1)) {
281 echo "Unable to get cron lock.\n";
282 return false;
284 if (!$lock = $cronlockfactory->get_lock($taskname, 1)) {
285 $cronlock->release();
286 echo "Unable to get task lock for $taskname.\n";
287 return false;
289 $task->set_lock($lock);
290 if (!$task->is_blocking()) {
291 $cronlock->release();
292 } else {
293 $task->set_cron_lock($cronlock);
296 // Run actual tasks.
297 cron_run_inner_scheduled_task($task);
299 // Go back to real user account.
300 cron_setup_user($realuser, null, true);
302 return true;
306 * Output some standard information during cron runs. Specifically current time
307 * and memory usage. This method also does gc_collect_cycles() (before displaying
308 * memory usage) to try to help PHP manage memory better.
310 function cron_trace_time_and_memory() {
311 gc_collect_cycles();
312 mtrace('... started ' . date('H:i:s') . '. Current memory use ' . display_size(memory_get_usage()) . '.');
316 * Executes cron functions for a specific type of plugin.
318 * @param string $plugintype Plugin type (e.g. 'report')
319 * @param string $description If specified, will display 'Starting (whatever)'
320 * and 'Finished (whatever)' lines, otherwise does not display
322 function cron_execute_plugin_type($plugintype, $description = null) {
323 global $DB;
325 // Get list from plugin => function for all plugins
326 $plugins = get_plugin_list_with_function($plugintype, 'cron');
328 // Modify list for backward compatibility (different files/names)
329 $plugins = cron_bc_hack_plugin_functions($plugintype, $plugins);
331 // Return if no plugins with cron function to process
332 if (!$plugins) {
333 return;
336 if ($description) {
337 mtrace('Starting '.$description);
340 foreach ($plugins as $component=>$cronfunction) {
341 $dir = core_component::get_component_directory($component);
343 // Get cron period if specified in version.php, otherwise assume every cron
344 $cronperiod = 0;
345 if (file_exists("$dir/version.php")) {
346 $plugin = new stdClass();
347 include("$dir/version.php");
348 if (isset($plugin->cron)) {
349 $cronperiod = $plugin->cron;
353 // Using last cron and cron period, don't run if it already ran recently
354 $lastcron = get_config($component, 'lastcron');
355 if ($cronperiod && $lastcron) {
356 if ($lastcron + $cronperiod > time()) {
357 // do not execute cron yet
358 continue;
362 mtrace('Processing cron function for ' . $component . '...');
363 cron_trace_time_and_memory();
364 $pre_dbqueries = $DB->perf_get_queries();
365 $pre_time = microtime(true);
367 $cronfunction();
369 mtrace("done. (" . ($DB->perf_get_queries() - $pre_dbqueries) . " dbqueries, " .
370 round(microtime(true) - $pre_time, 2) . " seconds)");
372 set_config('lastcron', time(), $component);
373 core_php_time_limit::raise();
376 if ($description) {
377 mtrace('Finished ' . $description);
382 * Used to add in old-style cron functions within plugins that have not been converted to the
383 * new standard API. (The standard API is frankenstyle_name_cron() in lib.php; some types used
384 * cron.php and some used a different name.)
386 * @param string $plugintype Plugin type e.g. 'report'
387 * @param array $plugins Array from plugin name (e.g. 'report_frog') to function name (e.g.
388 * 'report_frog_cron') for plugin cron functions that were already found using the new API
389 * @return array Revised version of $plugins that adds in any extra plugin functions found by
390 * looking in the older location
392 function cron_bc_hack_plugin_functions($plugintype, $plugins) {
393 global $CFG; // mandatory in case it is referenced by include()d PHP script
395 if ($plugintype === 'report') {
396 // Admin reports only - not course report because course report was
397 // never implemented before, so doesn't need BC
398 foreach (core_component::get_plugin_list($plugintype) as $pluginname=>$dir) {
399 $component = $plugintype . '_' . $pluginname;
400 if (isset($plugins[$component])) {
401 // We already have detected the function using the new API
402 continue;
404 if (!file_exists("$dir/cron.php")) {
405 // No old style cron file present
406 continue;
408 include_once("$dir/cron.php");
409 $cronfunction = $component . '_cron';
410 if (function_exists($cronfunction)) {
411 $plugins[$component] = $cronfunction;
412 } else {
413 debugging("Invalid legacy cron.php detected in $component, " .
414 "please use lib.php instead");
417 } else if (strpos($plugintype, 'grade') === 0) {
418 // Detect old style cron function names
419 // Plugin gradeexport_frog used to use grade_export_frog_cron() instead of
420 // new standard API gradeexport_frog_cron(). Also applies to gradeimport, gradereport
421 foreach(core_component::get_plugin_list($plugintype) as $pluginname=>$dir) {
422 $component = $plugintype.'_'.$pluginname;
423 if (isset($plugins[$component])) {
424 // We already have detected the function using the new API
425 continue;
427 if (!file_exists("$dir/lib.php")) {
428 continue;
430 include_once("$dir/lib.php");
431 $cronfunction = str_replace('grade', 'grade_', $plugintype) . '_' .
432 $pluginname . '_cron';
433 if (function_exists($cronfunction)) {
434 $plugins[$component] = $cronfunction;
439 return $plugins;
443 * Prepare the output renderer for the cron run.
445 * This involves creating a new $PAGE, and $OUTPUT fresh for each task and prevents any one task from influencing
446 * any other.
448 * @param bool $restore Whether to restore the original PAGE and OUTPUT
450 function cron_prepare_core_renderer($restore = false) {
451 global $OUTPUT, $PAGE;
453 // Store the original PAGE and OUTPUT values so that they can be reset at a later point to the original.
454 // This should not normally be required, but may be used in places such as the scheduled task tool's "Run now"
455 // functionality.
456 static $page = null;
457 static $output = null;
459 if (null === $page) {
460 $page = $PAGE;
463 if (null === $output) {
464 $output = $OUTPUT;
467 if (!empty($restore)) {
468 $PAGE = $page;
469 $page = null;
471 $OUTPUT = $output;
472 $output = null;
473 } else {
474 // Setup a new General renderer.
475 // Cron tasks may produce output to be used in web, so we must use the appropriate renderer target.
476 // This allows correct use of templates, etc.
477 $PAGE = new \moodle_page();
478 $OUTPUT = new \core_renderer($PAGE, RENDERER_TARGET_GENERAL);