MDL-10870 A few more fixes to the file.php page's navigation
[moodle-pu.git] / admin / cron.php
blob249e4f978bf1d346b3a249d23a78c9f5e0282aeb
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 safety
38 @session_write_close();
40 /// check if execution allowed
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;
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;
59 /// emulate normal session
60 $SESSION = new object();
61 $USER = get_admin(); /// Temporarily, to provide environment for this script
63 /// ignore admins timezone, language and locale - use site deafult instead!
64 $USER->timezone = $CFG->timezone;
65 $USER->lang = '';
66 $USER->theme = '';
67 course_setup(SITEID);
69 /// send mime type and encoding
70 if (check_browser_version('MSIE')) {
71 //ugly IE hack to work around downloading instead of viewing
72 @header('Content-Type: text/html; charset=utf-8');
73 echo "<xmp>"; //<pre> is not good enough for us here
74 } else {
75 //send proper plaintext header
76 @header('Content-Type: text/plain; charset=utf-8');
79 /// no more headers and buffers
80 while(@ob_end_flush());
82 /// increase memory limit (PHP 5.2 does different calculation, we need more memory now)
83 @raise_memory_limit('128M');
85 /// Start output log
87 $timenow = time();
89 mtrace("Server Time: ".date('r',$timenow)."\n\n");
91 /// Run all cron jobs for each module
93 mtrace("Starting activity modules");
94 if ($mods = get_records_select("modules", "cron > 0 AND (($timenow - lastcron) > cron)")) {
95 foreach ($mods as $mod) {
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)) {
101 mtrace("Processing module function $cron_function ...", '');
102 if ($cron_function()) {
103 if (! set_field("modules", "lastcron", $timenow, "id", $mod->id)) {
104 mtrace("Error: could not update timestamp for $mod->fullname");
107 mtrace("done.");
112 mtrace("Finished activity modules");
114 mtrace("Starting blocks");
115 if ($blocks = get_records_select("block", "cron > 0 AND (($timenow - lastcron) > cron)")) {
116 // we will need the base class.
117 require_once($CFG->dirroot.'/blocks/moodleblock.class.php');
118 foreach ($blocks as $block) {
119 $blockfile = $CFG->dirroot.'/blocks/'.$block->name.'/block_'.$block->name.'.php';
120 if (file_exists($blockfile)) {
121 require_once($blockfile);
122 $classname = 'block_'.$block->name;
123 $blockobj = new $classname;
124 if (method_exists($blockobj,'cron')) {
125 mtrace("Processing cron function for ".$block->name.'....','');
126 if ($blockobj->cron()) {
127 if (!set_field('block','lastcron',$timenow,'id',$block->id)) {
128 mtrace('Error: could not update timestamp for '.$block->name);
131 mtrace('done.');
137 mtrace('Finished blocks');
139 if (!empty($CFG->langcache)) {
140 mtrace('Updating languages cache');
141 get_list_of_languages(true);
144 mtrace('Removing expired enrolments ...', ''); // See MDL-8785
145 $timenow = time();
146 $somefound = false;
147 // find courses where limited enrolment is enabled
148 if($limitedcourses = get_records_select('course', 'enrolperiod > 0')) {
149 foreach($limitedcourses as $course) {
150 $context = get_context_instance(CONTEXT_COURSE, $course->id);
151 if ($oldenrolments = get_records_select('role_assignments', 'timeend > 0 AND timeend < ' . $timenow . ' AND contextid = ' . $context->id)) {
152 foreach ($oldenrolments as $oldenrolment) {
153 role_unassign($oldenrolment->roleid, $oldenrolment->userid, 0, $oldenrolment->contextid);
154 $somefound = true;
159 if($somefound) {
160 mtrace('Done');
161 } else {
162 mtrace('none found');
166 mtrace('Starting grade job ...', '');
167 grade_cron();
168 mtrace('Done ...', '');
172 /// Run all core cron jobs, but not every time since they aren't too important.
173 /// These don't have a timer to reduce load, so we'll use a random number
174 /// to randomly choose the percentage of times we should run these jobs.
176 srand ((double) microtime() * 10000000);
177 $random100 = rand(0,100);
179 if ($random100 < 20) { // Approximately 20% of the time.
180 mtrace("Running clean-up tasks...");
182 /// Unenrol users who haven't logged in for $CFG->longtimenosee
184 if ($CFG->longtimenosee) { // value in days
185 $longtime = $timenow - ($CFG->longtimenosee * 3600 * 24);
186 if ($assigns = get_users_longtimenosee($longtime)) {
187 foreach ($assigns as $assign) {
188 if ($context = get_context_instance(CONTEXT_COURSE, $assign->courseid)) {
189 if (role_unassign(0, $assign->id, 0, $context->id)) {
190 mtrace("Deleted assignment for user $assign->id from course $assign->courseid");
198 /// Delete users who haven't confirmed within required period
200 if (!empty($CFG->deleteunconfirmed)) {
201 $oneweek = $timenow - ($CFG->deleteunconfirmed * 3600);
202 if ($users = get_users_unconfirmed($oneweek)) {
203 foreach ($users as $user) {
204 if (delete_records('user', 'id', $user->id)) {
205 mtrace("Deleted unconfirmed user for ".fullname($user, true)." ($user->id)");
210 flush();
214 /// Delete users who haven't completed profile within required period
216 if (!empty($CFG->deleteunconfirmed)) {
217 $oneweek = $timenow - ($CFG->deleteunconfirmed * 3600);
218 if ($users = get_users_not_fully_set_up($oneweek)) {
219 foreach ($users as $user) {
220 if (delete_records('user', 'id', $user->id)) {
221 mtrace("Deleted not fully setup user $user->username ($user->id)");
226 flush();
230 /// Delete old logs to save space (this might need a timer to slow it down...)
232 if (!empty($CFG->loglifetime)) { // value in days
233 $loglifetime = $timenow - ($CFG->loglifetime * 3600 * 24);
234 delete_records_select("log", "time < '$loglifetime'");
236 flush();
238 /// Delete old cached texts
240 if (!empty($CFG->cachetext)) { // Defined in config.php
241 $cachelifetime = time() - $CFG->cachetext - 60; // Add an extra minute to allow for really heavy sites
242 delete_records_select('cache_text', "timemodified < '$cachelifetime'");
244 flush();
246 if (!empty($CFG->notifyloginfailures)) {
247 notify_login_failures();
249 flush();
251 sync_metacourses();
254 // generate new password emails for users
256 mtrace('checking for create_password');
257 if (count_records('user_preferences', 'name', 'create_password', 'value', '1')) {
258 mtrace('creating passwords for new users');
259 $newusers = get_records_sql("SELECT u.id as id, u.email, u.firstname,
260 u.lastname, u.username,
261 p.id as prefid
262 FROM {$CFG->prefix}user u
263 JOIN {$CFG->prefix}user_preferences p ON u.id=p.userid
264 WHERE p.name='create_password' AND p.value=1 AND u.email !='' ");
266 foreach ($newusers as $newuserid => $newuser) {
267 $newuser->emailstop = 0; // send email regardless
268 // email user
269 if (setnew_password_and_mail($newuser)) {
270 // remove user pref
271 delete_records('user_preferences', 'id', $newuser->prefid);
272 } else {
273 trigger_error("Could not create and mail new user password!");
278 if(!empty($CFG->usetags)){
279 require_once($CFG->dirroot.'/tag/lib.php');
280 tag_cron();
283 } // End of occasional clean-up tasks
286 if (empty($CFG->disablescheduledbackups)) { // Defined in config.php
287 //Execute backup's cron
288 //Perhaps a long time and memory could help in large sites
289 @set_time_limit(0);
290 @raise_memory_limit("192M");
291 if (function_exists('apache_child_terminate')) {
292 // if we are running from Apache, give httpd a hint that
293 // it can recycle the process after it's done. Apache's
294 // memory management is truly awful but we can help it.
295 @apache_child_terminate();
297 if (file_exists("$CFG->dirroot/backup/backup_scheduled.php") and
298 file_exists("$CFG->dirroot/backup/backuplib.php") and
299 file_exists("$CFG->dirroot/backup/lib.php") and
300 file_exists("$CFG->libdir/blocklib.php")) {
301 include_once("$CFG->dirroot/backup/backup_scheduled.php");
302 include_once("$CFG->dirroot/backup/backuplib.php");
303 include_once("$CFG->dirroot/backup/lib.php");
304 require_once ("$CFG->libdir/blocklib.php");
305 mtrace("Running backups if required...");
307 if (! schedule_backup_cron()) {
308 mtrace("ERROR: Something went wrong while performing backup tasks!!!");
309 } else {
310 mtrace("Backup tasks finished.");
315 if (!empty($CFG->enablerssfeeds)) { //Defined in admin/variables page
316 include_once("$CFG->libdir/rsslib.php");
317 mtrace("Running rssfeeds if required...");
319 if ( ! cron_rss_feeds()) {
320 mtrace("Something went wrong while generating rssfeeds!!!");
321 } else {
322 mtrace("Rssfeeds finished");
326 /// Run the enrolment cron, if any
327 if (!($plugins = explode(',', $CFG->enrol_plugins_enabled))) {
328 $plugins = array($CFG->enrol);
330 require_once($CFG->dirroot .'/enrol/enrol.class.php');
331 foreach ($plugins as $p) {
332 $enrol = enrolment_factory::factory($p);
333 if (method_exists($enrol, 'cron')) {
334 $enrol->cron();
336 if (!empty($enrol->log)) {
337 mtrace($enrol->log);
339 unset($enrol);
342 /// Run the auth cron, if any
343 $auths = get_enabled_auth_plugins();
345 mtrace("Running auth crons if required...");
346 foreach ($auths as $auth) {
347 $authplugin = get_auth_plugin($auth);
348 if (method_exists($authplugin, 'cron')) {
349 mtrace("Running cron for auth/$auth...");
350 $authplugin->cron();
351 if (!empty($authplugin->log)) {
352 mtrace($authplugin->log);
355 unset($authplugin);
358 if (!empty($CFG->enablestats) and empty($CFG->disablestatsprocessing)) {
360 // check we're not before our runtime
361 $timetocheck = strtotime("$CFG->statsruntimestarthour:$CFG->statsruntimestartminute today");
363 if (time() > $timetocheck) {
364 $time = 60*60*20; // set it to 20 here for first run... (overridden by $CFG)
365 $clobber = true;
366 if (!empty($CFG->statsmaxruntime)) {
367 $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)
369 if (!get_field_sql('SELECT id FROM '.$CFG->prefix.'stats_daily')) {
370 // first run, set another lock. we'll check for this in subsequent runs to set the timeout to later for the normal lock.
371 set_cron_lock('statsfirstrunlock',true,$time,true);
372 $firsttime = true;
374 $time = 60*60*2; // this time set to 2.. (overridden by $CFG)
375 if (!empty($CFG->statsmaxruntime)) {
376 $time = $CFG->statsmaxruntime+(60*30); // add on half an hour to make sure (it could take that long to break out of the loop)
378 if ($config = get_record('config','name','statsfirstrunlock')) {
379 if (!empty($config->value)) {
380 $clobber = false; // if we're on the first run, just don't clobber it.
383 if (set_cron_lock('statsrunning',true,$time, $clobber)) {
384 require_once($CFG->dirroot.'/lib/statslib.php');
385 $return = stats_cron_daily();
386 if (stats_check_runtime() && $return == STATS_RUN_COMPLETE) {
387 stats_cron_weekly();
389 if (stats_check_runtime() && $return == STATS_RUN_COMPLETE) {
390 $return = $return && stats_cron_monthly();
392 if (stats_check_runtime() && $return == STATS_RUN_COMPLETE) {
393 stats_clean_old();
395 set_cron_lock('statsrunning',false);
396 if (!empty($firsttime)) {
397 set_cron_lock('statsfirstrunlock',false);
403 // run gradebook import/export/report cron
404 if ($gradeimports = get_list_of_plugins('grade/import')) {
405 foreach ($gradeimports as $gradeimport) {
406 if (file_exists($CFG->dirroot.'/grade/import/lib.php')) {
407 require_once($CFG->dirroot.'/grade/import/lib.php');
408 $cron_function = 'gradeimport_'.$gradeimport.'_cron';
409 if (function_exists($cron_function)) {
410 mtrace("Processing gradebook import function $cron_function ...", '');
411 $cron_function;
417 if ($gradeexports = get_list_of_plugins('grade/export')) {
418 foreach ($gradeexports as $gradeexport) {
419 if (file_exists($CFG->dirroot.'/grade/export/lib.php')) {
420 require_once($CFG->dirroot.'/grade/export/lib.php');
421 $cron_function = 'gradeexport_'.$gradeexport.'_cron';
422 if (function_exists($cron_function)) {
423 mtrace("Processing gradebook export function $cron_function ...", '');
424 $cron_function;
430 if ($gradereports = get_list_of_plugins('grade/report')) {
431 foreach ($gradereports as $gradereport) {
432 if (file_exists($CFG->dirroot.'/grade/report/lib.php')) {
433 require_once($CFG->dirroot.'/grade/report/lib.php');
434 $cron_function = 'gradereport_'.$gradereport.'_cron';
435 if (function_exists($cron_function)) {
436 mtrace("Processing gradebook report function $cron_function ...", '');
437 $cron_function;
443 //Unset session variables and destroy it
444 @session_unset();
445 @session_destroy();
447 mtrace("Cron script completed correctly");
449 $difftime = microtime_diff($starttime, microtime());
450 mtrace("Execution took ".$difftime." seconds");
452 /// finishe the IE hack
453 if (check_browser_version('MSIE')) {
454 echo "</xmp>";