MDL-49399 core: Allow creation of a new per-request basedir
[moodle.git] / lib / cronlib.php
CommitLineData
28bd3d9a 1<?php
28bd3d9a
PS
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.
13//
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/>.
16
17/**
18 * Cron functions.
19 *
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
24 */
25
50ed196e
PS
26/**
27 * Execute cron tasks
28 */
28bd3d9a
PS
29function cron_run() {
30 global $DB, $CFG, $OUTPUT;
31
9957af68
PS
32 if (CLI_MAINTENANCE) {
33 echo "CLI maintenance mode active, cron execution suspended.\n";
34 exit(1);
35 }
36
4c56c7bf
PS
37 if (moodle_needs_upgrading()) {
38 echo "Moodle upgrade pending, cron execution suspended.\n";
39 exit(1);
40 }
41
28bd3d9a 42 require_once($CFG->libdir.'/adminlib.php');
28bd3d9a
PS
43
44 if (!empty($CFG->showcronsql)) {
45 $DB->set_debug(true);
46 }
47 if (!empty($CFG->showcrondebugging)) {
96f81ea3 48 set_debugging(DEBUG_DEVELOPER, true);
28bd3d9a
PS
49 }
50
3ef7279f 51 core_php_time_limit::raise();
28bd3d9a
PS
52 $starttime = microtime();
53
50ed196e 54 // Increase memory limit
346c5887 55 raise_memory_limit(MEMORY_EXTRA);
28bd3d9a 56
50ed196e 57 // Emulate normal session - we use admin accoutn by default
28bd3d9a
PS
58 cron_setup_user();
59
50ed196e 60 // Start output log
28bd3d9a 61 $timenow = time();
658b9372 62 mtrace("Server Time: ".date('r', $timenow)."\n\n");
28bd3d9a 63
309ae892
DW
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)) {
38fa1ca5 67 cron_run_inner_scheduled_task($task);
309ae892 68 unset($task);
50ed196e
PS
69 }
70
309ae892
DW
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)) {
7e4c4b6f 74 cron_run_inner_adhoc_task($task);
309ae892 75 unset($task);
50ed196e
PS
76 }
77
28bd3d9a
PS
78 mtrace("Cron script completed correctly");
79
658b9372
TH
80 gc_collect_cycles();
81 mtrace('Cron completed at ' . date('H:i:s') . '. Memory used ' . display_size(memory_get_usage()) . '.');
28bd3d9a
PS
82 $difftime = microtime_diff($starttime, microtime());
83 mtrace("Execution took ".$difftime." seconds");
cbb9e9b8 84}
b5541735 85
38fa1ca5 86/**
87 * Shared code that handles running of a single scheduled task within the cron.
88 *
89 * Not intended for calling directly outside of this library!
90 *
91 * @param \core\task\task_base $task
92 */
93function cron_run_inner_scheduled_task(\core\task\task_base $task) {
94 global $CFG, $DB;
95
4b71596f
AN
96 \core\task\logmanager::start_logging($task);
97
38fa1ca5 98 $fullname = $task->get_name() . ' (' . get_class($task) . ')';
99 mtrace('Execute scheduled task: ' . $fullname);
100 cron_trace_time_and_memory();
101 $predbqueries = null;
102 $predbqueries = $DB->perf_get_queries();
103 $pretime = microtime(1);
104 try {
105 get_mailer('buffer');
cd305dc2 106 cron_prepare_core_renderer();
38fa1ca5 107 $task->execute();
108 if ($DB->is_transaction_started()) {
109 throw new coding_exception("Task left transaction open");
110 }
111 if (isset($predbqueries)) {
112 mtrace("... used " . ($DB->perf_get_queries() - $predbqueries) . " dbqueries");
113 mtrace("... used " . (microtime(1) - $pretime) . " seconds");
114 }
115 mtrace('Scheduled task complete: ' . $fullname);
116 \core\task\manager::scheduled_task_complete($task);
117 } catch (Exception $e) {
118 if ($DB && $DB->is_transaction_started()) {
119 error_log('Database transaction aborted automatically in ' . get_class($task));
120 $DB->force_transaction_rollback();
121 }
122 if (isset($predbqueries)) {
123 mtrace("... used " . ($DB->perf_get_queries() - $predbqueries) . " dbqueries");
124 mtrace("... used " . (microtime(1) - $pretime) . " seconds");
125 }
126 mtrace('Scheduled task failed: ' . $fullname . ',' . $e->getMessage());
127 if ($CFG->debugdeveloper) {
128 if (!empty($e->debuginfo)) {
129 mtrace("Debug info:");
130 mtrace($e->debuginfo);
131 }
132 mtrace("Backtrace:");
133 mtrace(format_backtrace($e->getTrace(), true));
134 }
135 \core\task\manager::scheduled_task_failed($task);
cd305dc2
AN
136 } finally {
137 cron_prepare_core_renderer(true);
38fa1ca5 138 }
139 get_mailer('close');
140}
141
7e4c4b6f
AN
142/**
143 * Shared code that handles running of a single adhoc task within the cron.
144 *
145 * @param \core\task\adhoc_task $task
146 */
147function cron_run_inner_adhoc_task(\core\task\adhoc_task $task) {
148 global $DB, $CFG;
4b71596f
AN
149
150 \core\task\logmanager::start_logging($task);
151
7e4c4b6f
AN
152 mtrace("Execute adhoc task: " . get_class($task));
153 cron_trace_time_and_memory();
154 $predbqueries = null;
155 $predbqueries = $DB->perf_get_queries();
156 $pretime = microtime(1);
157
158 if ($userid = $task->get_userid()) {
159 // This task has a userid specified.
160 if ($user = \core_user::get_user($userid)) {
161 // User found. Check that they are suitable.
162 try {
163 \core_user::require_active_user($user, true, true);
164 } catch (moodle_exception $e) {
165 mtrace("User {$userid} cannot be used to run an adhoc task: " . get_class($task) . ". Cancelling task.");
166 $user = null;
167 }
168 } else {
169 // Unable to find the user for this task.
170 // A user missing in the database will never reappear.
171 mtrace("User {$userid} could not be found for adhoc task: " . get_class($task) . ". Cancelling task.");
172 }
173
174 if (empty($user)) {
175 // A user missing in the database will never reappear so the task needs to be failed to ensure that locks are removed,
176 // and then removed to prevent future runs.
177 // A task running as a user should only be run as that user.
178 \core\task\manager::adhoc_task_failed($task);
179 $DB->delete_records('task_adhoc', ['id' => $task->get_id()]);
180
181 return;
182 }
183
184 cron_setup_user($user);
185 }
186
187 try {
188 get_mailer('buffer');
cd305dc2 189 cron_prepare_core_renderer();
7e4c4b6f
AN
190 $task->execute();
191 if ($DB->is_transaction_started()) {
192 throw new coding_exception("Task left transaction open");
193 }
194 if (isset($predbqueries)) {
195 mtrace("... used " . ($DB->perf_get_queries() - $predbqueries) . " dbqueries");
196 mtrace("... used " . (microtime(1) - $pretime) . " seconds");
197 }
198 mtrace("Adhoc task complete: " . get_class($task));
199 \core\task\manager::adhoc_task_complete($task);
200 } catch (Exception $e) {
201 if ($DB && $DB->is_transaction_started()) {
202 error_log('Database transaction aborted automatically in ' . get_class($task));
203 $DB->force_transaction_rollback();
204 }
205 if (isset($predbqueries)) {
206 mtrace("... used " . ($DB->perf_get_queries() - $predbqueries) . " dbqueries");
207 mtrace("... used " . (microtime(1) - $pretime) . " seconds");
208 }
209 mtrace("Adhoc task failed: " . get_class($task) . "," . $e->getMessage());
210 if ($CFG->debugdeveloper) {
211 if (!empty($e->debuginfo)) {
212 mtrace("Debug info:");
213 mtrace($e->debuginfo);
214 }
215 mtrace("Backtrace:");
216 mtrace(format_backtrace($e->getTrace(), true));
217 }
218 \core\task\manager::adhoc_task_failed($task);
219 } finally {
220 // Reset back to the standard admin user.
221 cron_setup_user();
cd305dc2 222 cron_prepare_core_renderer(true);
7e4c4b6f
AN
223 }
224 get_mailer('close');
225}
226
38fa1ca5 227/**
228 * Runs a single cron task. This function assumes it is displaying output in pseudo-CLI mode.
229 *
230 * The function will fail if the task is disabled.
231 *
232 * Warning: Because this function closes the browser session, it may not be safe to continue
233 * with other processing (other than displaying the rest of the page) after using this function!
234 *
235 * @param \core\task\scheduled_task $task Task to run
236 * @return bool True if cron run successful
237 */
238function cron_run_single_task(\core\task\scheduled_task $task) {
239 global $CFG, $DB, $USER;
240
241 if (CLI_MAINTENANCE) {
242 echo "CLI maintenance mode active, cron execution suspended.\n";
243 return false;
244 }
245
246 if (moodle_needs_upgrading()) {
247 echo "Moodle upgrade pending, cron execution suspended.\n";
248 return false;
249 }
250
251 // Check task and component is not disabled.
252 $taskname = get_class($task);
253 if ($task->get_disabled()) {
254 echo "Task is disabled ($taskname).\n";
255 return false;
256 }
257 $component = $task->get_component();
258 if ($plugininfo = core_plugin_manager::instance()->get_plugin_info($component)) {
6d7c06a9 259 if ($plugininfo->is_enabled() === false && !$task->get_run_if_component_disabled()) {
38fa1ca5 260 echo "Component is not enabled ($component).\n";
261 return false;
262 }
263 }
264
265 // Enable debugging features as per config settings.
266 if (!empty($CFG->showcronsql)) {
267 $DB->set_debug(true);
268 }
269 if (!empty($CFG->showcrondebugging)) {
270 set_debugging(DEBUG_DEVELOPER, true);
271 }
272
273 // Increase time and memory limits.
274 core_php_time_limit::raise();
275 raise_memory_limit(MEMORY_EXTRA);
276
277 // Switch to admin account for cron tasks, but close the session so we don't send this stuff
278 // to the browser.
279 session_write_close();
280 $realuser = clone($USER);
281 cron_setup_user(null, null, true);
282
283 // Get lock for cron task.
284 $cronlockfactory = \core\lock\lock_config::get_lock_factory('cron');
285 if (!$cronlock = $cronlockfactory->get_lock('core_cron', 1)) {
286 echo "Unable to get cron lock.\n";
287 return false;
288 }
289 if (!$lock = $cronlockfactory->get_lock($taskname, 1)) {
290 $cronlock->release();
291 echo "Unable to get task lock for $taskname.\n";
292 return false;
293 }
294 $task->set_lock($lock);
295 if (!$task->is_blocking()) {
296 $cronlock->release();
297 } else {
298 $task->set_cron_lock($cronlock);
299 }
300
301 // Run actual tasks.
302 cron_run_inner_scheduled_task($task);
303
304 // Go back to real user account.
305 cron_setup_user($realuser, null, true);
306
307 return true;
308}
309
309ae892
DW
310/**
311 * Output some standard information during cron runs. Specifically current time
312 * and memory usage. This method also does gc_collect_cycles() (before displaying
313 * memory usage) to try to help PHP manage memory better.
314 */
315function cron_trace_time_and_memory() {
316 gc_collect_cycles();
317 mtrace('... started ' . date('H:i:s') . '. Current memory use ' . display_size(memory_get_usage()) . '.');
318}
319
e4a626b9 320/**
321 * Executes cron functions for a specific type of plugin.
50ed196e 322 *
e4a626b9 323 * @param string $plugintype Plugin type (e.g. 'report')
324 * @param string $description If specified, will display 'Starting (whatever)'
325 * and 'Finished (whatever)' lines, otherwise does not display
326 */
b5541735
PS
327function cron_execute_plugin_type($plugintype, $description = null) {
328 global $DB;
329
e4a626b9 330 // Get list from plugin => function for all plugins
331 $plugins = get_plugin_list_with_function($plugintype, 'cron');
332
333 // Modify list for backward compatibility (different files/names)
334 $plugins = cron_bc_hack_plugin_functions($plugintype, $plugins);
b5541735 335
e4a626b9 336 // Return if no plugins with cron function to process
b5541735
PS
337 if (!$plugins) {
338 return;
339 }
340
341 if ($description) {
342 mtrace('Starting '.$description);
343 }
344
345 foreach ($plugins as $component=>$cronfunction) {
b0d1d941 346 $dir = core_component::get_component_directory($component);
e4a626b9 347
348 // Get cron period if specified in version.php, otherwise assume every cron
b5541735
PS
349 $cronperiod = 0;
350 if (file_exists("$dir/version.php")) {
351 $plugin = new stdClass();
352 include("$dir/version.php");
353 if (isset($plugin->cron)) {
354 $cronperiod = $plugin->cron;
355 }
356 }
357
e4a626b9 358 // Using last cron and cron period, don't run if it already ran recently
b5541735 359 $lastcron = get_config($component, 'lastcron');
e4a626b9 360 if ($cronperiod && $lastcron) {
b5541735
PS
361 if ($lastcron + $cronperiod > time()) {
362 // do not execute cron yet
363 continue;
364 }
365 }
366
e4a626b9 367 mtrace('Processing cron function for ' . $component . '...');
658b9372 368 cron_trace_time_and_memory();
b5541735 369 $pre_dbqueries = $DB->perf_get_queries();
e4a626b9 370 $pre_time = microtime(true);
b5541735
PS
371
372 $cronfunction();
373
e4a626b9 374 mtrace("done. (" . ($DB->perf_get_queries() - $pre_dbqueries) . " dbqueries, " .
375 round(microtime(true) - $pre_time, 2) . " seconds)");
b5541735
PS
376
377 set_config('lastcron', time(), $component);
3ef7279f 378 core_php_time_limit::raise();
b5541735
PS
379 }
380
381 if ($description) {
e4a626b9 382 mtrace('Finished ' . $description);
b5541735
PS
383 }
384}
385
e4a626b9 386/**
387 * Used to add in old-style cron functions within plugins that have not been converted to the
388 * new standard API. (The standard API is frankenstyle_name_cron() in lib.php; some types used
389 * cron.php and some used a different name.)
50ed196e 390 *
e4a626b9 391 * @param string $plugintype Plugin type e.g. 'report'
392 * @param array $plugins Array from plugin name (e.g. 'report_frog') to function name (e.g.
393 * 'report_frog_cron') for plugin cron functions that were already found using the new API
394 * @return array Revised version of $plugins that adds in any extra plugin functions found by
395 * looking in the older location
396 */
397function cron_bc_hack_plugin_functions($plugintype, $plugins) {
398 global $CFG; // mandatory in case it is referenced by include()d PHP script
399
400 if ($plugintype === 'report') {
401 // Admin reports only - not course report because course report was
402 // never implemented before, so doesn't need BC
bd3b3bba 403 foreach (core_component::get_plugin_list($plugintype) as $pluginname=>$dir) {
e4a626b9 404 $component = $plugintype . '_' . $pluginname;
b5541735 405 if (isset($plugins[$component])) {
e4a626b9 406 // We already have detected the function using the new API
b5541735
PS
407 continue;
408 }
409 if (!file_exists("$dir/cron.php")) {
e4a626b9 410 // No old style cron file present
b5541735
PS
411 continue;
412 }
413 include_once("$dir/cron.php");
e4a626b9 414 $cronfunction = $component . '_cron';
b5541735
PS
415 if (function_exists($cronfunction)) {
416 $plugins[$component] = $cronfunction;
417 } else {
e4a626b9 418 debugging("Invalid legacy cron.php detected in $component, " .
419 "please use lib.php instead");
b5541735
PS
420 }
421 }
b5541735 422 } else if (strpos($plugintype, 'grade') === 0) {
e4a626b9 423 // Detect old style cron function names
424 // Plugin gradeexport_frog used to use grade_export_frog_cron() instead of
425 // new standard API gradeexport_frog_cron(). Also applies to gradeimport, gradereport
bd3b3bba 426 foreach(core_component::get_plugin_list($plugintype) as $pluginname=>$dir) {
b5541735
PS
427 $component = $plugintype.'_'.$pluginname;
428 if (isset($plugins[$component])) {
e4a626b9 429 // We already have detected the function using the new API
b5541735
PS
430 continue;
431 }
432 if (!file_exists("$dir/lib.php")) {
433 continue;
434 }
435 include_once("$dir/lib.php");
e4a626b9 436 $cronfunction = str_replace('grade', 'grade_', $plugintype) . '_' .
437 $pluginname . '_cron';
b5541735
PS
438 if (function_exists($cronfunction)) {
439 $plugins[$component] = $cronfunction;
440 }
441 }
442 }
443
444 return $plugins;
50ed196e 445}
cd305dc2
AN
446
447/**
448 * Prepare the output renderer for the cron run.
449 *
450 * This involves creating a new $PAGE, and $OUTPUT fresh for each task and prevents any one task from influencing
451 * any other.
452 *
453 * @param bool $restore Whether to restore the original PAGE and OUTPUT
454 */
455function cron_prepare_core_renderer($restore = false) {
456 global $OUTPUT, $PAGE;
457
458 // Store the original PAGE and OUTPUT values so that they can be reset at a later point to the original.
459 // This should not normally be required, but may be used in places such as the scheduled task tool's "Run now"
460 // functionality.
461 static $page = null;
462 static $output = null;
463
464 if (null === $page) {
465 $page = $PAGE;
466 }
467
468 if (null === $output) {
469 $output = $OUTPUT;
470 }
471
472 if (!empty($restore)) {
473 $PAGE = $page;
474 $page = null;
475
476 $OUTPUT = $output;
477 $output = null;
478 } else {
479 // Setup a new General renderer.
480 // Cron tasks may produce output to be used in web, so we must use the appropriate renderer target.
481 // This allows correct use of templates, etc.
482 $PAGE = new \moodle_page();
483 $OUTPUT = new \core_renderer($PAGE, RENDERER_TARGET_GENERAL);
484 }
485}