MDL-10585:
[moodle-linuxchix.git] / admin / cron.php
blob2bc3cd32e98a7a6a2954e23c2c6e986c7236c465
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');
36 /// extra safety
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');
44 exit;
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;
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;
64 $USER->lang = '';
65 $USER->theme = '';
66 course_setup(SITEID);
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
73 } else {
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');
84 /// Start output log
86 $timenow = time();
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");
106 mtrace("done.");
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);
130 mtrace('done.');
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
144 $timenow = time();
145 $somefound = false;
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 if ($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);
153 $somefound = true;
158 if($somefound) {
159 mtrace('Done');
160 } else {
161 mtrace('none found');
165 /// Run all core cron jobs, but not every time since they aren't too important.
166 /// These don't have a timer to reduce load, so we'll use a random number
167 /// to randomly choose the percentage of times we should run these jobs.
169 srand ((double) microtime() * 10000000);
170 $random100 = rand(0,100);
172 if ($random100 < 20) { // Approximately 20% of the time.
173 mtrace("Running clean-up tasks...");
175 /// Unenrol users who haven't logged in for $CFG->longtimenosee
177 if ($CFG->longtimenosee) { // value in days
178 $longtime = $timenow - ($CFG->longtimenosee * 3600 * 24);
179 if ($assigns = get_users_longtimenosee($longtime)) {
180 foreach ($assigns as $assign) {
181 if ($context = get_context_instance(CONTEXT_COURSE, $assign->courseid)) {
182 if (role_unassign(0, $assign->id, 0, $context->id)) {
183 mtrace("Deleted assignment for user $assign->id from course $assign->courseid");
191 /// Delete users who haven't confirmed within required period
193 if (!empty($CFG->deleteunconfirmed)) {
194 $oneweek = $timenow - ($CFG->deleteunconfirmed * 3600);
195 if ($users = get_users_unconfirmed($oneweek)) {
196 foreach ($users as $user) {
197 if (delete_records('user', 'id', $user->id)) {
198 mtrace("Deleted unconfirmed user for ".fullname($user, true)." ($user->id)");
203 flush();
207 /// Delete users who haven't completed profile within required period
209 if (!empty($CFG->deleteunconfirmed)) {
210 $oneweek = $timenow - ($CFG->deleteunconfirmed * 3600);
211 if ($users = get_users_not_fully_set_up($oneweek)) {
212 foreach ($users as $user) {
213 if (delete_records('user', 'id', $user->id)) {
214 mtrace("Deleted not fully setup user $user->username ($user->id)");
219 flush();
223 /// Delete old logs to save space (this might need a timer to slow it down...)
225 if (!empty($CFG->loglifetime)) { // value in days
226 $loglifetime = $timenow - ($CFG->loglifetime * 3600 * 24);
227 delete_records_select("log", "time < '$loglifetime'");
229 flush();
231 /// Delete old cached texts
233 if (!empty($CFG->cachetext)) { // Defined in config.php
234 $cachelifetime = time() - $CFG->cachetext - 60; // Add an extra minute to allow for really heavy sites
235 delete_records_select('cache_text', "timemodified < '$cachelifetime'");
237 flush();
239 if (!empty($CFG->notifyloginfailures)) {
240 notify_login_failures();
242 flush();
244 sync_metacourses();
247 // generate new password emails for users
249 mtrace('checking for create_password');
250 if (count_records('user_preferences', 'name', 'create_password', 'value', '1')) {
251 mtrace('creating passwords for new users');
252 $newusers = get_records_sql("SELECT u.id as id, u.email, u.firstname,
253 u.lastname, u.username,
254 p.id as prefid
255 FROM {$CFG->prefix}user u
256 JOIN {$CFG->prefix}user_preferences p ON u.id=p.userid
257 WHERE p.name='create_password' AND p.value=1 AND u.email !='' ");
259 foreach ($newusers as $newuserid => $newuser) {
260 $newuser->emailstop = 0; // send email regardless
261 // email user
262 if (setnew_password_and_mail($newuser)) {
263 // remove user pref
264 delete_records('user_preferences', 'id', $newuser->prefid);
265 } else {
266 trigger_error("Could not create and mail new user password!");
271 } // End of occasional clean-up tasks
274 if (empty($CFG->disablescheduledbackups)) { // Defined in config.php
275 //Execute backup's cron
276 //Perhaps a long time and memory could help in large sites
277 @set_time_limit(0);
278 @raise_memory_limit("192M");
279 if (function_exists('apache_child_terminate')) {
280 // if we are running from Apache, give httpd a hint that
281 // it can recycle the process after it's done. Apache's
282 // memory management is truly awful but we can help it.
283 @apache_child_terminate();
285 if (file_exists("$CFG->dirroot/backup/backup_scheduled.php") and
286 file_exists("$CFG->dirroot/backup/backuplib.php") and
287 file_exists("$CFG->dirroot/backup/lib.php") and
288 file_exists("$CFG->libdir/blocklib.php")) {
289 include_once("$CFG->dirroot/backup/backup_scheduled.php");
290 include_once("$CFG->dirroot/backup/backuplib.php");
291 include_once("$CFG->dirroot/backup/lib.php");
292 require_once ("$CFG->libdir/blocklib.php");
293 mtrace("Running backups if required...");
295 if (! schedule_backup_cron()) {
296 mtrace("ERROR: Something went wrong while performing backup tasks!!!");
297 } else {
298 mtrace("Backup tasks finished.");
303 if (!empty($CFG->enablerssfeeds)) { //Defined in admin/variables page
304 include_once("$CFG->libdir/rsslib.php");
305 mtrace("Running rssfeeds if required...");
307 if ( ! cron_rss_feeds()) {
308 mtrace("Something went wrong while generating rssfeeds!!!");
309 } else {
310 mtrace("Rssfeeds finished");
314 /// Run the enrolment cron, if any
315 if (!($plugins = explode(',', $CFG->enrol_plugins_enabled))) {
316 $plugins = array($CFG->enrol);
318 require_once($CFG->dirroot .'/enrol/enrol.class.php');
319 foreach ($plugins as $p) {
320 $enrol = enrolment_factory::factory($p);
321 if (method_exists($enrol, 'cron')) {
322 $enrol->cron();
324 if (!empty($enrol->log)) {
325 mtrace($enrol->log);
327 unset($enrol);
330 /// Run the auth cron, if any
331 $auths = get_enabled_auth_plugins();
333 mtrace("Running auth crons if required...");
334 foreach ($auths as $auth) {
335 $authplugin = get_auth_plugin($auth);
336 if (method_exists($authplugin, 'cron')) {
337 mtrace("Running cron for auth/$auth...");
338 $authplugin->cron();
339 if (!empty($authplugin->log)) {
340 mtrace($authplugin->log);
343 unset($authplugin);
346 if (!empty($CFG->enablestats) and empty($CFG->disablestatsprocessing)) {
348 // check we're not before our runtime
349 $timetocheck = strtotime("$CFG->statsruntimestarthour:$CFG->statsruntimestartminute today");
351 if (time() > $timetocheck) {
352 $time = 60*60*20; // set it to 20 here for first run... (overridden by $CFG)
353 $clobber = true;
354 if (!empty($CFG->statsmaxruntime)) {
355 $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)
357 if (!get_field_sql('SELECT id FROM '.$CFG->prefix.'stats_daily')) {
358 // first run, set another lock. we'll check for this in subsequent runs to set the timeout to later for the normal lock.
359 set_cron_lock('statsfirstrunlock',true,$time,true);
360 $firsttime = true;
362 $time = 60*60*2; // this time set to 2.. (overridden by $CFG)
363 if (!empty($CFG->statsmaxruntime)) {
364 $time = $CFG->statsmaxruntime+(60*30); // add on half an hour to make sure (it could take that long to break out of the loop)
366 if ($config = get_record('config','name','statsfirstrunlock')) {
367 if (!empty($config->value)) {
368 $clobber = false; // if we're on the first run, just don't clobber it.
371 if (set_cron_lock('statsrunning',true,$time, $clobber)) {
372 require_once($CFG->dirroot.'/lib/statslib.php');
373 $return = stats_cron_daily();
374 if (stats_check_runtime() && $return == STATS_RUN_COMPLETE) {
375 stats_cron_weekly();
377 if (stats_check_runtime() && $return == STATS_RUN_COMPLETE) {
378 $return = $return && stats_cron_monthly();
380 if (stats_check_runtime() && $return == STATS_RUN_COMPLETE) {
381 stats_clean_old();
383 set_cron_lock('statsrunning',false);
384 if (!empty($firsttime)) {
385 set_cron_lock('statsfirstrunlock',false);
391 // run gradebook import/export/report cron
392 if ($gradeimports = get_list_of_plugins('grade/import')) {
393 foreach ($gradeimports as $gradeimport) {
394 if (file_exists($CFG->dirroot.'/grade/import/lib.php')) {
395 require_once($CFG->dirroot.'/grade/import/lib.php');
396 $cron_function = 'gradeimport_'.$gradeimport.'_cron';
397 if (function_exists($cron_function)) {
398 mtrace("Processing gradebook import function $cron_function ...", '');
399 $cron_function;
405 if ($gradeexports = get_list_of_plugins('grade/export')) {
406 foreach ($gradeexports as $gradeexport) {
407 if (file_exists($CFG->dirroot.'/grade/export/lib.php')) {
408 require_once($CFG->dirroot.'/grade/export/lib.php');
409 $cron_function = 'gradeexport_'.$gradeexport.'_cron';
410 if (function_exists($cron_function)) {
411 mtrace("Processing gradebook export function $cron_function ...", '');
412 $cron_function;
418 if ($gradereports = get_list_of_plugins('grade/report')) {
419 foreach ($gradereports as $gradereport) {
420 if (file_exists($CFG->dirroot.'/grade/report/lib.php')) {
421 require_once($CFG->dirroot.'/grade/report/lib.php');
422 $cron_function = 'gradereport_'.$gradereport.'_cron';
423 if (function_exists($cron_function)) {
424 mtrace("Processing gradebook report function $cron_function ...", '');
425 $cron_function;
431 //Unset session variables and destroy it
432 @session_unset();
433 @session_destroy();
435 mtrace("Cron script completed correctly");
437 $difftime = microtime_diff($starttime, microtime());
438 mtrace("Execution took ".$difftime." seconds");
440 /// finishe the IE hack
441 if (check_browser_version('MSIE')) {
442 echo "</xmp>";