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.
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.
11 /// eg wget -q -O /dev/null 'http://moodle.somewhere.edu/admin/cron.php'
12 /// or php /web/moodle/admin/cron.php
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');
37 @session_write_close
();
39 /// check if execution allowed
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');
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
) {
51 print_error('cronerrorpassword', 'admin');
58 /// emulate normal session
59 $SESSION = new object();
60 $USER = get_admin(); /// Temporarily, to provide environment for this script
62 /// ignore admins timezone, language and locale - use site deafult instead!
63 $USER->timezone
= $CFG->timezone
;
68 /// send mime type and encoding
69 if (check_browser_version('MSIE')) {
70 //ugly IE hack to work around downloading instead of viewing
71 @header
('Content-Type: text/html; charset=utf-8');
72 echo "<xmp>"; //<pre> is not good enough for us here
74 //send proper plaintext header
75 @header
('Content-Type: text/plain; charset=utf-8');
78 /// no more headers and buffers
79 while(@ob_end_flush
());
81 /// increase memory limit (PHP 5.2 does different calculation, we need more memory now)
82 @raise_memory_limit
('128M');
88 mtrace("Server Time: ".date('r',$timenow)."\n\n");
90 /// Run all cron jobs for each module
92 mtrace("Starting activity modules");
93 if ($mods = get_records_select("modules", "cron > 0 AND (($timenow - lastcron) > cron)")) {
94 foreach ($mods as $mod) {
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)) {
100 mtrace("Processing module function $cron_function ...", '');
101 if ($cron_function()) {
102 if (! set_field("modules", "lastcron", $timenow, "id", $mod->id
)) {
103 mtrace("Error: could not update timestamp for $mod->fullname");
111 mtrace("Finished activity modules");
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
);
136 mtrace('Finished blocks');
138 if (!empty($CFG->langcache
)) {
139 mtrace('Updating languages cache');
140 get_list_of_languages(true);
143 mtrace('Removing expired enrolments ...', ''); // See MDL-8785
146 // find courses where limited enrolment is enabled
147 if($limitedcourses = get_records_select('course', 'enrolperiod > 0')) {
148 foreach($limitedcourses as $course) {
149 $context = get_context_instance(CONTEXT_COURSE
, $course->id
);
150 $oldenrolments = get_records_select('role_assignments', 'timeend > 0 AND timeend < ' . $timenow . ' AND contextid = ' . $context->id
);
151 foreach ($oldenrolments as $oldenrolment) {
152 role_unassign($oldenrolment->roleid
, $oldenrolment->userid
, 0, $oldenrolment->contextid
);
160 mtrace('none found');
164 /// Run all core cron jobs, but not every time since they aren't too important.
165 /// These don't have a timer to reduce load, so we'll use a random number
166 /// to randomly choose the percentage of times we should run these jobs.
168 srand ((double) microtime() * 10000000);
169 $random100 = rand(0,100);
171 if ($random100 < 20) { // Approximately 20% of the time.
172 mtrace("Running clean-up tasks...");
174 /// Unenrol users who haven't logged in for $CFG->longtimenosee
176 if ($CFG->longtimenosee
) { // value in days
177 $longtime = $timenow - ($CFG->longtimenosee
* 3600 * 24);
178 if ($assigns = get_users_longtimenosee($longtime)) {
179 foreach ($assigns as $assign) {
180 if ($context = get_context_instance(CONTEXT_COURSE
, $assign->courseid
)) {
181 if (role_unassign(0, $assign->id
, 0, $context->id
)) {
182 mtrace("Deleted assignment for user $assign->id from course $assign->courseid");
190 /// Delete users who haven't confirmed within required period
192 if (!empty($CFG->deleteunconfirmed
)) {
193 $oneweek = $timenow - ($CFG->deleteunconfirmed
* 3600);
194 if ($users = get_users_unconfirmed($oneweek)) {
195 foreach ($users as $user) {
196 if (delete_records('user', 'id', $user->id
)) {
197 mtrace("Deleted unconfirmed user for ".fullname($user, true)." ($user->id)");
206 /// Delete users who haven't completed profile within required period
208 if (!empty($CFG->deleteunconfirmed
)) {
209 $oneweek = $timenow - ($CFG->deleteunconfirmed
* 3600);
210 if ($users = get_users_not_fully_set_up($oneweek)) {
211 foreach ($users as $user) {
212 if (delete_records('user', 'id', $user->id
)) {
213 mtrace("Deleted not fully setup user $user->username ($user->id)");
222 /// Delete old logs to save space (this might need a timer to slow it down...)
224 if (!empty($CFG->loglifetime
)) { // value in days
225 $loglifetime = $timenow - ($CFG->loglifetime
* 3600 * 24);
226 delete_records_select("log", "time < '$loglifetime'");
230 /// Delete old cached texts
232 if (!empty($CFG->cachetext
)) { // Defined in config.php
233 $cachelifetime = time() - $CFG->cachetext
- 60; // Add an extra minute to allow for really heavy sites
234 delete_records_select('cache_text', "timemodified < '$cachelifetime'");
238 if (!empty($CFG->notifyloginfailures
)) {
239 notify_login_failures();
246 // generate new password emails for users
248 mtrace('checking for create_password');
249 if (count_records('user_preferences', 'name', 'create_password', 'value', '1')) {
250 mtrace('creating passwords for new users');
251 $newusers = get_records_sql("SELECT u.id as id, u.email, u.firstname,
252 u.lastname, u.username,
254 FROM {$CFG->prefix}user u
255 JOIN {$CFG->prefix}user_preferences p ON u.id=p.userid
256 WHERE p.name='create_password' AND p.value=1 AND u.email !='' ");
258 foreach ($newusers as $newuserid => $newuser) {
259 $newuser->emailstop
= 0; // send email regardless
261 if (setnew_password_and_mail($newuser)) {
263 delete_records('user_preferences', 'id', $newuser->prefid
);
265 trigger_error("Could not create and mail new user password!");
270 } // End of occasional clean-up tasks
273 if (empty($CFG->disablescheduledbackups
)) { // Defined in config.php
274 //Execute backup's cron
275 //Perhaps a long time and memory could help in large sites
277 @raise_memory_limit
("192M");
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
();
284 if (file_exists("$CFG->dirroot/backup/backup_scheduled.php") and
285 file_exists("$CFG->dirroot/backup/backuplib.php") and
286 file_exists("$CFG->dirroot/backup/lib.php") and
287 file_exists("$CFG->libdir/blocklib.php")) {
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");
291 require_once ("$CFG->libdir/blocklib.php");
292 mtrace("Running backups if required...");
294 if (! schedule_backup_cron()) {
295 mtrace("ERROR: Something went wrong while performing backup tasks!!!");
297 mtrace("Backup tasks finished.");
302 if (!empty($CFG->enablerssfeeds
)) { //Defined in admin/variables page
303 include_once("$CFG->libdir/rsslib.php");
304 mtrace("Running rssfeeds if required...");
306 if ( ! cron_rss_feeds()) {
307 mtrace("Something went wrong while generating rssfeeds!!!");
309 mtrace("Rssfeeds finished");
313 /// Run the enrolment cron, if any
314 if (!($plugins = explode(',', $CFG->enrol_plugins_enabled
))) {
315 $plugins = array($CFG->enrol
);
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')) {
323 if (!empty($enrol->log
)) {
329 /// Run the auth cron, if any
330 $auths = get_enabled_auth_plugins();
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...");
338 if (!empty($authplugin->log
)) {
339 mtrace($authplugin->log
);
345 if (!empty($CFG->enablestats
) and empty($CFG->disablestatsprocessing
)) {
347 // check we're not before our runtime
348 $timetocheck = strtotime("$CFG->statsruntimestarthour:$CFG->statsruntimestartminute today");
350 if (time() > $timetocheck) {
351 $time = 60*60*20; // set it to 20 here for first run... (overridden by $CFG)
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)
356 if (!get_field_sql('SELECT id FROM '.$CFG->prefix
.'stats_daily')) {
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);
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)
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.
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
) {
376 if (stats_check_runtime() && $return == STATS_RUN_COMPLETE
) {
377 $return = $return && stats_cron_monthly();
379 if (stats_check_runtime() && $return == STATS_RUN_COMPLETE
) {
382 set_cron_lock('statsrunning',false);
383 if (!empty($firsttime)) {
384 set_cron_lock('statsfirstrunlock',false);
390 // run gradebook import/export/report cron
391 if ($gradeimports = get_list_of_plugins('grade/import')) {
392 foreach ($gradeimports as $gradeimport) {
393 if (file_exists($CFG->dirroot
.'/grade/import/lib.php')) {
394 require_once($CFG->dirroot
.'/grade/import/lib.php');
395 $cron_function = 'gradeimport_'.$gradeimport.'_cron';
396 if (function_exists($cron_function)) {
397 mtrace("Processing gradebook import function $cron_function ...", '');
404 if ($gradeexports = get_list_of_plugins('grade/export')) {
405 foreach ($gradeexports as $gradeexport) {
406 if (file_exists($CFG->dirroot
.'/grade/export/lib.php')) {
407 require_once($CFG->dirroot
.'/grade/export/lib.php');
408 $cron_function = 'gradeexport_'.$gradeexport.'_cron';
409 if (function_exists($cron_function)) {
410 mtrace("Processing gradebook export function $cron_function ...", '');
417 if ($gradereports = get_list_of_plugins('grade/report')) {
418 foreach ($gradereports as $gradereport) {
419 if (file_exists($CFG->dirroot
.'/grade/report/lib.php')) {
420 require_once($CFG->dirroot
.'/grade/report/lib.php');
421 $cron_function = 'gradereport_'.$gradereport.'_cron';
422 if (function_exists($cron_function)) {
423 mtrace("Processing gradebook report function $cron_function ...", '');
430 //Unset session variables and destroy it
434 mtrace("Cron script completed correctly");
436 $difftime = microtime_diff($starttime, microtime());
437 mtrace("Execution took ".$difftime." seconds");
439 /// finishe the IE hack
440 if (check_browser_version('MSIE')) {