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