MDL-11515:
[moodle-linuxchix.git] / admin / cron.php
blobdbb0be0ce3e36b63abc705c05d68c91e8db2acd6
1 <?php // $Id$
3 /// This script looks through all the module directories for cron.php files
4 /// and runs them. These files can contain cleanup functions, email functions
5 /// or anything that needs to be run on a regular basis.
6 ///
7 /// This file is best run from cron on the host system (ie outside PHP).
8 /// The script can either be invoked via the web server or via a standalone
9 /// version of PHP compiled for CGI.
10 ///
11 /// eg wget -q -O /dev/null 'http://moodle.somewhere.edu/admin/cron.php'
12 /// or php /web/moodle/admin/cron.php
13 set_time_limit(0);
14 $starttime = microtime();
16 /// The following is a hack necessary to allow this script to work well
17 /// from the command line.
19 define('FULLME', 'cron');
22 /// Do not set moodle cookie because we do not need it here, it is better to emulate session
23 $nomoodlecookie = true;
25 /// The current directory in PHP version 4.3.0 and above isn't necessarily the
26 /// directory of the script when run from the command line. The require_once()
27 /// would fail, so we'll have to chdir()
29 if (!isset($_SERVER['REMOTE_ADDR']) && isset($_SERVER['argv'][0])) {
30 chdir(dirname($_SERVER['argv'][0]));
33 require_once(dirname(__FILE__) . '/../config.php');
34 require_once($CFG->libdir.'/adminlib.php');
35 require_once($CFG->libdir.'/gradelib.php');
37 /// Extra debugging (set in config.php)
38 if (!empty($CFG->showcronsql)) {
39 $db->debug = true;
41 if (!empty($CFG->showcrondebugging)) {
42 $CFG->debug = DEBUG_DEVELOPER;
43 $CFG->displaydebug = true;
46 /// extra safety
47 @session_write_close();
49 /// check if execution allowed
50 if (isset($_SERVER['REMOTE_ADDR'])) { // if the script is accessed via the web.
51 if (!empty($CFG->cronclionly)) {
52 // This script can only be run via the cli.
53 print_error('cronerrorclionly', 'admin');
54 exit;
56 // This script is being called via the web, so check the password if there is one.
57 if (!empty($CFG->cronremotepassword)) {
58 $pass = optional_param('password', '', PARAM_RAW);
59 if($pass != $CFG->cronremotepassword) {
60 // wrong password.
61 print_error('cronerrorpassword', 'admin');
62 exit;
68 /// emulate normal session
69 $SESSION = new object();
70 $USER = get_admin(); /// Temporarily, to provide environment for this script
72 /// ignore admins timezone, language and locale - use site deafult instead!
73 $USER->timezone = $CFG->timezone;
74 $USER->lang = '';
75 $USER->theme = '';
76 course_setup(SITEID);
78 /// send mime type and encoding
79 if (check_browser_version('MSIE')) {
80 //ugly IE hack to work around downloading instead of viewing
81 @header('Content-Type: text/html; charset=utf-8');
82 echo "<xmp>"; //<pre> is not good enough for us here
83 } else {
84 //send proper plaintext header
85 @header('Content-Type: text/plain; charset=utf-8');
88 /// no more headers and buffers
89 while(@ob_end_flush());
91 /// increase memory limit (PHP 5.2 does different calculation, we need more memory now)
92 @raise_memory_limit('128M');
94 /// Start output log
96 $timenow = time();
98 mtrace("Server Time: ".date('r',$timenow)."\n\n");
100 /// Run all cron jobs for each module
102 mtrace("Starting activity modules");
103 if ($mods = get_records_select("modules", "cron > 0 AND (($timenow - lastcron) > cron)")) {
104 foreach ($mods as $mod) {
105 $libfile = "$CFG->dirroot/mod/$mod->name/lib.php";
106 if (file_exists($libfile)) {
107 include_once($libfile);
108 $cron_function = $mod->name."_cron";
109 if (function_exists($cron_function)) {
110 mtrace("Processing module function $cron_function ...", '');
111 if (!empty($PERF->dbqueries)) {
112 $pre_dbqueries = $PERF->dbqueries;
113 $pre_time = microtime(1);
115 if ($cron_function()) {
116 if (! set_field("modules", "lastcron", $timenow, "id", $mod->id)) {
117 mtrace("Error: could not update timestamp for $mod->fullname");
120 if (isset($pre_dbqueries)) {
121 mtrace("... used " . ($PERF->dbqueries - $pre_dbqueries) . " dbqueries");
122 mtrace("... used " . (microtime(1) - $pre_time) . " seconds");
124 /// Reset possible changes by modules to time_limit. MDL-11597
125 @set_time_limit(0);
126 mtrace("done.");
131 mtrace("Finished activity modules");
133 mtrace("Starting blocks");
134 if ($blocks = get_records_select("block", "cron > 0 AND (($timenow - lastcron) > cron)")) {
135 // we will need the base class.
136 require_once($CFG->dirroot.'/blocks/moodleblock.class.php');
137 foreach ($blocks as $block) {
138 $blockfile = $CFG->dirroot.'/blocks/'.$block->name.'/block_'.$block->name.'.php';
139 if (file_exists($blockfile)) {
140 require_once($blockfile);
141 $classname = 'block_'.$block->name;
142 $blockobj = new $classname;
143 if (method_exists($blockobj,'cron')) {
144 mtrace("Processing cron function for ".$block->name.'....','');
145 if ($blockobj->cron()) {
146 if (!set_field('block','lastcron',$timenow,'id',$block->id)) {
147 mtrace('Error: could not update timestamp for '.$block->name);
150 /// Reset possible changes by blocks to time_limit. MDL-11597
151 @set_time_limit(0);
152 mtrace('done.');
158 mtrace('Finished blocks');
160 if (!empty($CFG->langcache)) {
161 mtrace('Updating languages cache');
162 get_list_of_languages(true);
165 mtrace('Removing expired enrolments ...', ''); // See MDL-8785
166 $timenow = time();
167 $somefound = false;
168 // The preferred way saves memory, dmllib.php
169 // find courses where limited enrolment is enabled
170 global $CFG;
171 $rs_enrol = get_recordset_sql("SELECT ra.roleid, ra.userid, ra.contextid
172 FROM {$CFG->prefix}course c
173 INNER JOIN {$CFG->prefix}context cx ON cx.instanceid = c.id
174 INNER JOIN {$CFG->prefix}role_assignments ra ON ra.contextid = cx.id
175 WHERE cx.contextlevel = '".CONTEXT_COURSE."'
176 AND ra.timeend > 0
177 AND ra.timeend < '$timenow'
178 AND c.enrolperiod > 0
180 while ($oldenrolment = rs_fetch_next_record($rs_enrol)) {
181 role_unassign($oldenrolment->roleid, $oldenrolment->userid, 0, $oldenrolment->contextid);
182 $somefound = true;
184 rs_close($rs_enrol);
185 if($somefound) {
186 mtrace('Done');
187 } else {
188 mtrace('none found');
192 mtrace('Starting grade job ...', '');
193 grade_cron();
194 mtrace('Done ...');
197 /// Run all core cron jobs, but not every time since they aren't too important.
198 /// These don't have a timer to reduce load, so we'll use a random number
199 /// to randomly choose the percentage of times we should run these jobs.
201 srand ((double) microtime() * 10000000);
202 $random100 = rand(0,100);
204 if ($random100 < 20) { // Approximately 20% of the time.
205 mtrace("Running clean-up tasks...");
207 /// Unenrol users who haven't logged in for $CFG->longtimenosee
209 if ($CFG->longtimenosee) { // value in days
210 $cuttime = $timenow - ($CFG->longtimenosee * 3600 * 24);
211 $rs = get_recordset_sql ("SELECT id, userid, courseid
212 FROM {$CFG->prefix}user_lastaccess
213 WHERE courseid != ".SITEID."
214 AND timeaccess < $cuttime ");
215 while ($assign = rs_fetch_next_record($rs)) {
216 if ($context = get_context_instance(CONTEXT_COURSE, $assign->courseid)) {
217 if (role_unassign(0, $assign->userid, 0, $context->id)) {
218 mtrace("Deleted assignment for user $assign->userid from course $assign->courseid");
222 rs_close($rs);
223 /// Execute the same query again, looking for remaining records and deleting them
224 /// if the user hasn't moodle/course:view in the CONTEXT_COURSE context (orphan records)
225 $rs = get_recordset_sql ("SELECT id, userid, courseid
226 FROM {$CFG->prefix}user_lastaccess
227 WHERE courseid != ".SITEID."
228 AND timeaccess < $cuttime ");
229 while ($assign = rs_fetch_next_record($rs)) {
230 if ($context = get_context_instance(CONTEXT_COURSE, $assign->courseid)) {
231 if (!has_capability('moodle/course:view', $context, $assign->userid)) {
232 delete_records('user_lastaccess', 'userid', $assign->userid, 'courseid', $assign->courseid);
233 mtrace("Deleted orphan user_lastaccess for user $assign->userid from course $assign->courseid");
237 rs_close($rs);
239 flush();
242 /// Delete users who haven't confirmed within required period
244 if (!empty($CFG->deleteunconfirmed)) {
245 $cuttime = $timenow - ($CFG->deleteunconfirmed * 3600);
246 $rs = get_recordset_sql ("SELECT id, firstname, lastname
247 FROM {$CFG->prefix}user
248 WHERE confirmed = 0
249 AND firstaccess > 0
250 AND firstaccess < $cuttime");
251 while ($user = rs_fetch_next_record($rs)) {
252 if (delete_records('user', 'id', $user->id)) {
253 mtrace("Deleted unconfirmed user for ".fullname($user, true)." ($user->id)");
256 rs_close($rs);
258 flush();
261 /// Delete users who haven't completed profile within required period
263 if (!empty($CFG->deleteunconfirmed)) {
264 $cuttime = $timenow - ($CFG->deleteunconfirmed * 3600);
265 $rs = get_recordset_sql ("SELECT id, username
266 FROM {$CFG->prefix}user
267 WHERE confirmed = 1
268 AND lastaccess > 0
269 AND lastaccess < $cuttime
270 AND deleted = 0
271 AND (lastname = '' OR firstname = '' OR email = '')");
272 while ($user = rs_fetch_next_record($rs)) {
273 if (delete_records('user', 'id', $user->id)) {
274 mtrace("Deleted not fully setup user $user->username ($user->id)");
277 rs_close($rs);
279 flush();
282 /// Delete old logs to save space (this might need a timer to slow it down...)
284 if (!empty($CFG->loglifetime)) { // value in days
285 $loglifetime = $timenow - ($CFG->loglifetime * 3600 * 24);
286 if (delete_records_select("log", "time < '$loglifetime'")) {
287 mtrace("Deleted old log records");
290 flush();
293 /// Delete old cached texts
295 if (!empty($CFG->cachetext)) { // Defined in config.php
296 $cachelifetime = time() - $CFG->cachetext - 60; // Add an extra minute to allow for really heavy sites
297 if (delete_records_select('cache_text', "timemodified < '$cachelifetime'")) {
298 mtrace("Deleted old cache_text records");
301 flush();
303 if (!empty($CFG->notifyloginfailures)) {
304 notify_login_failures();
305 mtrace('Notified login failured');
307 flush();
309 sync_metacourses();
310 mtrace('Synchronised metacourses');
313 // generate new password emails for users
315 mtrace('checking for create_password');
316 if (count_records('user_preferences', 'name', 'create_password', 'value', '1')) {
317 mtrace('creating passwords for new users');
318 $newusers = get_records_sql("SELECT u.id as id, u.email, u.firstname,
319 u.lastname, u.username,
320 p.id as prefid
321 FROM {$CFG->prefix}user u
322 JOIN {$CFG->prefix}user_preferences p ON u.id=p.userid
323 WHERE p.name='create_password' AND p.value=1 AND u.email !='' ");
325 foreach ($newusers as $newuserid => $newuser) {
326 $newuser->emailstop = 0; // send email regardless
327 // email user
328 if (setnew_password_and_mail($newuser)) {
329 // remove user pref
330 delete_records('user_preferences', 'id', $newuser->prefid);
331 } else {
332 trigger_error("Could not create and mail new user password!");
337 if(!empty($CFG->usetags)){
338 require_once($CFG->dirroot.'/tag/lib.php');
339 tag_cron();
340 mtrace ('Executed tag cron');
343 // Accesslib stuff
344 cleanup_contexts();
345 mtrace ('Cleaned up contexts');
346 gc_cache_flags();
347 mtrace ('Cleaned cache flags');
348 // If you suspect that the context paths are somehow corrupt
349 // replace the line below with: build_context_path(true);
350 build_context_path();
351 mtrace ('Built context paths');
353 mtrace("Finished clean-up tasks...");
355 } // End of occasional clean-up tasks
358 if (empty($CFG->disablescheduledbackups)) { // Defined in config.php
359 //Execute backup's cron
360 //Perhaps a long time and memory could help in large sites
361 @set_time_limit(0);
362 @raise_memory_limit("192M");
363 if (function_exists('apache_child_terminate')) {
364 // if we are running from Apache, give httpd a hint that
365 // it can recycle the process after it's done. Apache's
366 // memory management is truly awful but we can help it.
367 @apache_child_terminate();
369 if (file_exists("$CFG->dirroot/backup/backup_scheduled.php") and
370 file_exists("$CFG->dirroot/backup/backuplib.php") and
371 file_exists("$CFG->dirroot/backup/lib.php") and
372 file_exists("$CFG->libdir/blocklib.php")) {
373 include_once("$CFG->dirroot/backup/backup_scheduled.php");
374 include_once("$CFG->dirroot/backup/backuplib.php");
375 include_once("$CFG->dirroot/backup/lib.php");
376 require_once ("$CFG->libdir/blocklib.php");
377 mtrace("Running backups if required...");
379 if (! schedule_backup_cron()) {
380 mtrace("ERROR: Something went wrong while performing backup tasks!!!");
381 } else {
382 mtrace("Backup tasks finished.");
387 if (!empty($CFG->enablerssfeeds)) { //Defined in admin/variables page
388 include_once("$CFG->libdir/rsslib.php");
389 mtrace("Running rssfeeds if required...");
391 if ( ! cron_rss_feeds()) {
392 mtrace("Something went wrong while generating rssfeeds!!!");
393 } else {
394 mtrace("Rssfeeds finished");
398 /// Run the enrolment cron, if any
399 if (!($plugins = explode(',', $CFG->enrol_plugins_enabled))) {
400 $plugins = array($CFG->enrol);
402 require_once($CFG->dirroot .'/enrol/enrol.class.php');
403 foreach ($plugins as $p) {
404 $enrol = enrolment_factory::factory($p);
405 if (method_exists($enrol, 'cron')) {
406 $enrol->cron();
408 if (!empty($enrol->log)) {
409 mtrace($enrol->log);
411 unset($enrol);
414 /// Run the auth cron, if any
415 $auths = get_enabled_auth_plugins();
417 mtrace("Running auth crons if required...");
418 foreach ($auths as $auth) {
419 $authplugin = get_auth_plugin($auth);
420 if (method_exists($authplugin, 'cron')) {
421 mtrace("Running cron for auth/$auth...");
422 $authplugin->cron();
423 if (!empty($authplugin->log)) {
424 mtrace($authplugin->log);
427 unset($authplugin);
430 if (!empty($CFG->enablestats) and empty($CFG->disablestatsprocessing)) {
432 // check we're not before our runtime
433 $timetocheck = strtotime("$CFG->statsruntimestarthour:$CFG->statsruntimestartminute today");
435 if (time() > $timetocheck) {
436 $time = 60*60*20; // set it to 20 here for first run... (overridden by $CFG)
437 $clobber = true;
438 if (!empty($CFG->statsmaxruntime)) {
439 $time = $CFG->statsmaxruntime+(60*30); // add on half an hour just to make sure (it could take that long to break out of the loop)
441 if (!get_field_sql('SELECT id FROM '.$CFG->prefix.'stats_daily')) {
442 // first run, set another lock. we'll check for this in subsequent runs to set the timeout to later for the normal lock.
443 set_cron_lock('statsfirstrunlock',true,$time,true);
444 $firsttime = true;
446 $time = 60*60*2; // this time set to 2.. (overridden by $CFG)
447 if (!empty($CFG->statsmaxruntime)) {
448 $time = $CFG->statsmaxruntime+(60*30); // add on half an hour to make sure (it could take that long to break out of the loop)
450 if ($config = get_record('config','name','statsfirstrunlock')) {
451 if (!empty($config->value)) {
452 $clobber = false; // if we're on the first run, just don't clobber it.
455 if (set_cron_lock('statsrunning',true,$time, $clobber)) {
456 require_once($CFG->dirroot.'/lib/statslib.php');
457 $return = stats_cron_daily();
458 if (stats_check_runtime() && $return == STATS_RUN_COMPLETE) {
459 stats_cron_weekly();
461 if (stats_check_runtime() && $return == STATS_RUN_COMPLETE) {
462 $return = $return && stats_cron_monthly();
464 if (stats_check_runtime() && $return == STATS_RUN_COMPLETE) {
465 stats_clean_old();
467 set_cron_lock('statsrunning',false);
468 if (!empty($firsttime)) {
469 set_cron_lock('statsfirstrunlock',false);
475 // run gradebook import/export/report cron
476 if ($gradeimports = get_list_of_plugins('grade/import')) {
477 foreach ($gradeimports as $gradeimport) {
478 if (file_exists($CFG->dirroot.'/grade/import/lib.php')) {
479 require_once($CFG->dirroot.'/grade/import/lib.php');
480 $cron_function = 'gradeimport_'.$gradeimport.'_cron';
481 if (function_exists($cron_function)) {
482 mtrace("Processing gradebook import function $cron_function ...", '');
483 $cron_function;
489 if ($gradeexports = get_list_of_plugins('grade/export')) {
490 foreach ($gradeexports as $gradeexport) {
491 if (file_exists($CFG->dirroot.'/grade/export/lib.php')) {
492 require_once($CFG->dirroot.'/grade/export/lib.php');
493 $cron_function = 'gradeexport_'.$gradeexport.'_cron';
494 if (function_exists($cron_function)) {
495 mtrace("Processing gradebook export function $cron_function ...", '');
496 $cron_function;
502 if ($gradereports = get_list_of_plugins('grade/report')) {
503 foreach ($gradereports as $gradereport) {
504 if (file_exists($CFG->dirroot.'/grade/report/lib.php')) {
505 require_once($CFG->dirroot.'/grade/report/lib.php');
506 $cron_function = 'gradereport_'.$gradereport.'_cron';
507 if (function_exists($cron_function)) {
508 mtrace("Processing gradebook report function $cron_function ...", '');
509 $cron_function;
515 //Unset session variables and destroy it
516 @session_unset();
517 @session_destroy();
519 mtrace("Cron script completed correctly");
521 $difftime = microtime_diff($starttime, microtime());
522 mtrace("Execution took ".$difftime." seconds");
524 /// finishe the IE hack
525 if (check_browser_version('MSIE')) {
526 echo "</xmp>";