MDL-11344 Reverting commit 1.145 and keeping deprecated $string['editlang'] for backw...
[moodle.git] / admin / cron.php
CommitLineData
f9903ed0 1<?PHP // $Id$
2
540bab47 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
168df8f3 13 set_time_limit(0);
498d4032 14 $starttime = microtime();
f9f4d999 15
16/// The following is a hack necessary to allow this script to work well
17/// from the command line.
18
19 define('FULLME', 'cron');
9152fc99 20
21
22/// Do not set moodle cookie because we do not need it here, it is better to emulate session
23 $nomoodlecookie = true;
24
d5f286f1 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()
28
29 if (!isset($_SERVER['REMOTE_ADDR']) && isset($_SERVER['argv'][0])) {
30 chdir(dirname($_SERVER['argv'][0]));
31 }
498d4032 32
331ca297 33 require_once(dirname(__FILE__) . '/../config.php');
6e4dc10f 34 require_once($CFG->libdir.'/adminlib.php');
2650c51e 35 require_once($CFG->libdir.'/gradelib.php');
f9903ed0 36
9152fc99 37/// extra safety
38 @session_write_close();
39
40/// check if execution allowed
e08df351 41 if (isset($_SERVER['REMOTE_ADDR'])) { // if the script is accessed via the web.
42 if (!empty($CFG->cronclionly)) {
43 // This script can only be run via the cli.
44 print_error('cronerrorclionly', 'admin');
45 exit;
46 }
47 // This script is being called via the web, so check the password if there is one.
48 if (!empty($CFG->cronremotepassword)) {
49 $pass = optional_param('password', '', PARAM_RAW);
50 if($pass != $CFG->cronremotepassword) {
51 // wrong password.
52 print_error('cronerrorpassword', 'admin');
53 exit;
54 }
55 }
56 }
57
afabdb14 58
9152fc99 59/// emulate normal session
60 $SESSION = new object();
61 $USER = get_admin(); /// Temporarily, to provide environment for this script
00de82df 62
9152fc99 63/// ignore admins timezone, language and locale - use site deafult instead!
64 $USER->timezone = $CFG->timezone;
5e601222 65 $USER->lang = '';
9152fc99 66 $USER->theme = '';
67 course_setup(SITEID);
5e601222 68
69/// send mime type and encoding
58e8f85b 70 if (check_browser_version('MSIE')) {
71 //ugly IE hack to work around downloading instead of viewing
810944af 72 @header('Content-Type: text/html; charset=utf-8');
58e8f85b 73 echo "<xmp>"; //<pre> is not good enough for us here
74 } else {
75 //send proper plaintext header
810944af 76 @header('Content-Type: text/plain; charset=utf-8');
58e8f85b 77 }
5e601222 78
9152fc99 79/// no more headers and buffers
80 while(@ob_end_flush());
81
4eefee97 82/// increase memory limit (PHP 5.2 does different calculation, we need more memory now)
83 @raise_memory_limit('128M');
84
428b6fec 85/// Start output log
f9903ed0 86
f9903ed0 87 $timenow = time();
428b6fec 88
defaac4c 89 mtrace("Server Time: ".date('r',$timenow)."\n\n");
f9903ed0 90
b2ce450a 91/// Run all cron jobs for each module
c88f014a 92
defaac4c 93 mtrace("Starting activity modules");
9fa49e22 94 if ($mods = get_records_select("modules", "cron > 0 AND (($timenow - lastcron) > cron)")) {
f9903ed0 95 foreach ($mods as $mod) {
673de292 96 $libfile = "$CFG->dirroot/mod/$mod->name/lib.php";
97 if (file_exists($libfile)) {
98 include_once($libfile);
99 $cron_function = $mod->name."_cron";
100 if (function_exists($cron_function)) {
defaac4c 101 mtrace("Processing module function $cron_function ...", '');
ff991c05 102 if (!empty($PERF->dbqueries)) {
103 $pre_dbqueries = $PERF->dbqueries;
104 $pre_time = microtime(1);
105 }
673de292 106 if ($cron_function()) {
107 if (! set_field("modules", "lastcron", $timenow, "id", $mod->id)) {
defaac4c 108 mtrace("Error: could not update timestamp for $mod->fullname");
673de292 109 }
110 }
ff991c05 111 if (isset($pre_dbqueries)) {
112 mtrace("... used " . ($PERF->dbqueries - $pre_dbqueries) . " dbqueries");
113 mtrace("... used " . (microtime(1) - $pre_time) . " seconds");
114 }
defaac4c 115 mtrace("done.");
f9903ed0 116 }
117 }
118 }
119 }
defaac4c 120 mtrace("Finished activity modules");
c88f014a 121
f9648e77 122 mtrace("Starting blocks");
123 if ($blocks = get_records_select("block", "cron > 0 AND (($timenow - lastcron) > cron)")) {
124 // we will need the base class.
125 require_once($CFG->dirroot.'/blocks/moodleblock.class.php');
126 foreach ($blocks as $block) {
127 $blockfile = $CFG->dirroot.'/blocks/'.$block->name.'/block_'.$block->name.'.php';
128 if (file_exists($blockfile)) {
129 require_once($blockfile);
130 $classname = 'block_'.$block->name;
131 $blockobj = new $classname;
132 if (method_exists($blockobj,'cron')) {
133 mtrace("Processing cron function for ".$block->name.'....','');
134 if ($blockobj->cron()) {
135 if (!set_field('block','lastcron',$timenow,'id',$block->id)) {
136 mtrace('Error: could not update timestamp for '.$block->name);
137 }
138 }
139 mtrace('done.');
140 }
141 }
142
143 }
144 }
0616d3e8 145 mtrace('Finished blocks');
f9648e77 146
d6ead3a2 147 if (!empty($CFG->langcache)) {
148 mtrace('Updating languages cache');
0a5ce9dd 149 get_list_of_languages(true);
d6ead3a2 150 }
151
0616d3e8 152 mtrace('Removing expired enrolments ...', ''); // See MDL-8785
153 $timenow = time();
cf057534 154 $somefound = false;
c5898fad 155 // The preferred way saves memory, dmllib.php
cf057534 156 // find courses where limited enrolment is enabled
c5898fad 157 global $CFG;
158 $rs_enrol = get_recordset_sql("SELECT ra.roleid, ra.userid, ra.contextid
159 FROM {$CFG->prefix}course c
160 INNER JOIN {$CFG->prefix}context cx ON cx.instanceid = c.id
161 INNER JOIN {$CFG->prefix}role_assignments ra ON ra.contextid = cx.id
162 WHERE cx.contextlevel = '".CONTEXT_COURSE."'
163 AND ra.timeend > 0
164 AND ra.timeend < '$timenow'
165 AND c.enrolperiod > 0
166 ");
167 while ($oldenrolment = rs_fetch_next_record($rs_enrol)) {
168 role_unassign($oldenrolment->roleid, $oldenrolment->userid, 0, $oldenrolment->contextid);
169 $somefound = true;
cf057534 170 }
c5898fad 171 rs_close($rs_enrol);
cf057534 172 if($somefound) {
0616d3e8 173 mtrace('Done');
174 } else {
175 mtrace('none found');
176 }
177
d6ead3a2 178
2650c51e 179 mtrace('Starting grade job ...', '');
180 grade_cron();
181 mtrace('Done ...', '');
182
183
184
b2ce450a 185/// Run all core cron jobs, but not every time since they aren't too important.
186/// These don't have a timer to reduce load, so we'll use a random number
187/// to randomly choose the percentage of times we should run these jobs.
c88f014a 188
b2ce450a 189 srand ((double) microtime() * 10000000);
190 $random100 = rand(0,100);
c88f014a 191
b2ce450a 192 if ($random100 < 20) { // Approximately 20% of the time.
defaac4c 193 mtrace("Running clean-up tasks...");
b2ce450a 194
195 /// Unenrol users who haven't logged in for $CFG->longtimenosee
196
197 if ($CFG->longtimenosee) { // value in days
198 $longtime = $timenow - ($CFG->longtimenosee * 3600 * 24);
6e208cd2 199 if ($assigns = get_users_longtimenosee($longtime)) {
200 foreach ($assigns as $assign) {
201 if ($context = get_context_instance(CONTEXT_COURSE, $assign->courseid)) {
1afb11e7 202 if (role_unassign(0, $assign->userid, 0, $context->id)) {
203 mtrace("Deleted assignment for user $assign->userid from course $assign->courseid");
6e208cd2 204 }
b2ce450a 205 }
206 }
207 }
208 }
209
210
6c61fd04 211 /// Delete users who haven't confirmed within required period
c6c43ae9 212
8c182006 213 if (!empty($CFG->deleteunconfirmed)) {
214 $oneweek = $timenow - ($CFG->deleteunconfirmed * 3600);
215 if ($users = get_users_unconfirmed($oneweek)) {
216 foreach ($users as $user) {
217 if (delete_records('user', 'id', $user->id)) {
218 mtrace("Deleted unconfirmed user for ".fullname($user, true)." ($user->id)");
219 }
f282e631 220 }
6cb86b39 221 }
222 }
69f78bcb 223 flush();
7b8cc339 224
225
226
227 /// Delete users who haven't completed profile within required period
228
8c182006 229 if (!empty($CFG->deleteunconfirmed)) {
230 $oneweek = $timenow - ($CFG->deleteunconfirmed * 3600);
231 if ($users = get_users_not_fully_set_up($oneweek)) {
232 foreach ($users as $user) {
233 if (delete_records('user', 'id', $user->id)) {
234 mtrace("Deleted not fully setup user $user->username ($user->id)");
235 }
7b8cc339 236 }
237 }
238 }
239 flush();
240
241
b2ce450a 242
b2ce450a 243 /// Delete old logs to save space (this might need a timer to slow it down...)
244
245 if (!empty($CFG->loglifetime)) { // value in days
246 $loglifetime = $timenow - ($CFG->loglifetime * 3600 * 24);
247 delete_records_select("log", "time < '$loglifetime'");
248 }
69f78bcb 249 flush();
cb3a4484 250
251 /// Delete old cached texts
252
253 if (!empty($CFG->cachetext)) { // Defined in config.php
a9743837 254 $cachelifetime = time() - $CFG->cachetext - 60; // Add an extra minute to allow for really heavy sites
255 delete_records_select('cache_text', "timemodified < '$cachelifetime'");
cb3a4484 256 }
69f78bcb 257 flush();
d846e50a 258
259 if (!empty($CFG->notifyloginfailures)) {
260 notify_login_failures();
261 }
69f78bcb 262 flush();
d846e50a 263
b61efafb 264 sync_metacourses();
265
e3b6b2b0 266 //
267 // generate new password emails for users
268 //
269 mtrace('checking for create_password');
270 if (count_records('user_preferences', 'name', 'create_password', 'value', '1')) {
271 mtrace('creating passwords for new users');
272 $newusers = get_records_sql("SELECT u.id as id, u.email, u.firstname,
273 u.lastname, u.username,
274 p.id as prefid
275 FROM {$CFG->prefix}user u
276 JOIN {$CFG->prefix}user_preferences p ON u.id=p.userid
277 WHERE p.name='create_password' AND p.value=1 AND u.email !='' ");
278
279 foreach ($newusers as $newuserid => $newuser) {
280 $newuser->emailstop = 0; // send email regardless
281 // email user
282 if (setnew_password_and_mail($newuser)) {
283 // remove user pref
284 delete_records('user_preferences', 'id', $newuser->prefid);
285 } else {
286 trigger_error("Could not create and mail new user password!");
287 }
288 }
289 }
7ea9b095 290
19e41f75 291 if(!empty($CFG->usetags)){
292 require_once($CFG->dirroot.'/tag/lib.php');
293 tag_cron();
294 }
295
ad72d0d7 296 // Accesslib stuff
297 cleanup_contexts();
298 cleanup_dirty_contexts();
299 // If you suspect that the context paths are somehow corrupt
300 // replace the line below with: build_context_path(true);
301 build_context_path();
302
d846e50a 303 } // End of occasional clean-up tasks
540bab47 304
750eeaeb 305
50999a0b 306 if (empty($CFG->disablescheduledbackups)) { // Defined in config.php
74736e49 307 //Execute backup's cron
308 //Perhaps a long time and memory could help in large sites
a71bfa1c 309 @set_time_limit(0);
8891e81c 310 @raise_memory_limit("192M");
a2ce7344 311 if (function_exists('apache_child_terminate')) {
312 // if we are running from Apache, give httpd a hint that
313 // it can recycle the process after it's done. Apache's
314 // memory management is truly awful but we can help it.
315 @apache_child_terminate();
316 }
74736e49 317 if (file_exists("$CFG->dirroot/backup/backup_scheduled.php") and
318 file_exists("$CFG->dirroot/backup/backuplib.php") and
e91e2b6a 319 file_exists("$CFG->dirroot/backup/lib.php") and
320 file_exists("$CFG->libdir/blocklib.php")) {
74736e49 321 include_once("$CFG->dirroot/backup/backup_scheduled.php");
322 include_once("$CFG->dirroot/backup/backuplib.php");
323 include_once("$CFG->dirroot/backup/lib.php");
e91e2b6a 324 require_once ("$CFG->libdir/blocklib.php");
defaac4c 325 mtrace("Running backups if required...");
74736e49 326
327 if (! schedule_backup_cron()) {
04ddd06c 328 mtrace("ERROR: Something went wrong while performing backup tasks!!!");
74736e49 329 } else {
defaac4c 330 mtrace("Backup tasks finished.");
74736e49 331 }
e6d273eb 332 }
d3159192 333 }
334
8adcb49f 335 if (!empty($CFG->enablerssfeeds)) { //Defined in admin/variables page
3c02d134 336 include_once("$CFG->libdir/rsslib.php");
337 mtrace("Running rssfeeds if required...");
8adcb49f 338
3c02d134 339 if ( ! cron_rss_feeds()) {
340 mtrace("Something went wrong while generating rssfeeds!!!");
341 } else {
342 mtrace("Rssfeeds finished");
8adcb49f 343 }
344 }
345
04e44325 346/// Run the enrolment cron, if any
f9667a5a 347 if (!($plugins = explode(',', $CFG->enrol_plugins_enabled))) {
348 $plugins = array($CFG->enrol);
349 }
350 require_once($CFG->dirroot .'/enrol/enrol.class.php');
351 foreach ($plugins as $p) {
352 $enrol = enrolment_factory::factory($p);
353 if (method_exists($enrol, 'cron')) {
354 $enrol->cron();
355 }
356 if (!empty($enrol->log)) {
357 mtrace($enrol->log);
358 }
359 unset($enrol);
7e192c78 360 }
04e44325 361
d14383e0 362/// Run the auth cron, if any
c7b10b5f 363 $auths = get_enabled_auth_plugins();
364
d14383e0 365 mtrace("Running auth crons if required...");
366 foreach ($auths as $auth) {
367 $authplugin = get_auth_plugin($auth);
368 if (method_exists($authplugin, 'cron')) {
369 mtrace("Running cron for auth/$auth...");
370 $authplugin->cron();
371 if (!empty($authplugin->log)) {
372 mtrace($authplugin->log);
373 }
374 }
375 unset($authplugin);
376 }
377
72df7e1e 378 if (!empty($CFG->enablestats) and empty($CFG->disablestatsprocessing)) {
4900433c 379
380 // check we're not before our runtime
381 $timetocheck = strtotime("$CFG->statsruntimestarthour:$CFG->statsruntimestartminute today");
382
383 if (time() > $timetocheck) {
384 $time = 60*60*20; // set it to 20 here for first run... (overridden by $CFG)
385 $clobber = true;
386 if (!empty($CFG->statsmaxruntime)) {
387 $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)
f3221af9 388 }
37c47aba 389 if (!get_field_sql('SELECT id FROM '.$CFG->prefix.'stats_daily')) {
4900433c 390 // first run, set another lock. we'll check for this in subsequent runs to set the timeout to later for the normal lock.
391 set_cron_lock('statsfirstrunlock',true,$time,true);
392 $firsttime = true;
f3221af9 393 }
4900433c 394 $time = 60*60*2; // this time set to 2.. (overridden by $CFG)
395 if (!empty($CFG->statsmaxruntime)) {
396 $time = $CFG->statsmaxruntime+(60*30); // add on half an hour to make sure (it could take that long to break out of the loop)
f3221af9 397 }
4900433c 398 if ($config = get_record('config','name','statsfirstrunlock')) {
399 if (!empty($config->value)) {
400 $clobber = false; // if we're on the first run, just don't clobber it.
401 }
aff25119 402 }
4900433c 403 if (set_cron_lock('statsrunning',true,$time, $clobber)) {
404 require_once($CFG->dirroot.'/lib/statslib.php');
405 $return = stats_cron_daily();
406 if (stats_check_runtime() && $return == STATS_RUN_COMPLETE) {
407 stats_cron_weekly();
408 }
409 if (stats_check_runtime() && $return == STATS_RUN_COMPLETE) {
410 $return = $return && stats_cron_monthly();
411 }
412 if (stats_check_runtime() && $return == STATS_RUN_COMPLETE) {
413 stats_clean_old();
414 }
415 set_cron_lock('statsrunning',false);
416 if (!empty($firsttime)) {
417 set_cron_lock('statsfirstrunlock',false);
418 }
f3221af9 419 }
420 }
421 }
ce34ed3a 422
423 // run gradebook import/export/report cron
424 if ($gradeimports = get_list_of_plugins('grade/import')) {
425 foreach ($gradeimports as $gradeimport) {
426 if (file_exists($CFG->dirroot.'/grade/import/lib.php')) {
427 require_once($CFG->dirroot.'/grade/import/lib.php');
428 $cron_function = 'gradeimport_'.$gradeimport.'_cron';
429 if (function_exists($cron_function)) {
430 mtrace("Processing gradebook import function $cron_function ...", '');
431 $cron_function;
432 }
433 }
434 }
435 }
436
437 if ($gradeexports = get_list_of_plugins('grade/export')) {
438 foreach ($gradeexports as $gradeexport) {
439 if (file_exists($CFG->dirroot.'/grade/export/lib.php')) {
440 require_once($CFG->dirroot.'/grade/export/lib.php');
441 $cron_function = 'gradeexport_'.$gradeexport.'_cron';
442 if (function_exists($cron_function)) {
443 mtrace("Processing gradebook export function $cron_function ...", '');
444 $cron_function;
445 }
446 }
447 }
448 }
449
450 if ($gradereports = get_list_of_plugins('grade/report')) {
451 foreach ($gradereports as $gradereport) {
452 if (file_exists($CFG->dirroot.'/grade/report/lib.php')) {
453 require_once($CFG->dirroot.'/grade/report/lib.php');
454 $cron_function = 'gradereport_'.$gradereport.'_cron';
455 if (function_exists($cron_function)) {
456 mtrace("Processing gradebook report function $cron_function ...", '');
457 $cron_function;
458 }
459 }
460 }
461 }
f3221af9 462
db6b033d 463 //Unset session variables and destroy it
464 @session_unset();
465 @session_destroy();
466
defaac4c 467 mtrace("Cron script completed correctly");
f9903ed0 468
498d4032 469 $difftime = microtime_diff($starttime, microtime());
defaac4c 470 mtrace("Execution took ".$difftime." seconds");
498d4032 471
58e8f85b 472/// finishe the IE hack
473 if (check_browser_version('MSIE')) {
474 echo "</xmp>";
475 }
476
1afb11e7 477?>