MDL-11278 Implementation is complete, but grade_categories records in DB are not...
[moodle-pu.git] / admin / cron.php
blobd001e2e8075883eead3b8676d4a6c7225036abb4
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 (!empty($PERF->dbqueries)) {
103 $pre_dbqueries = $PERF->dbqueries;
104 $pre_time = microtime(1);
106 if ($cron_function()) {
107 if (! set_field("modules", "lastcron", $timenow, "id", $mod->id)) {
108 mtrace("Error: could not update timestamp for $mod->fullname");
111 if (isset($pre_dbqueries)) {
112 mtrace("... used " . ($PERF->dbqueries - $pre_dbqueries) . " dbqueries");
113 mtrace("... used " . (microtime(1) - $pre_time) . " seconds");
115 mtrace("done.");
120 mtrace("Finished activity modules");
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);
139 mtrace('done.');
145 mtrace('Finished blocks');
147 if (!empty($CFG->langcache)) {
148 mtrace('Updating languages cache');
149 get_list_of_languages(true);
152 mtrace('Removing expired enrolments ...', ''); // See MDL-8785
153 $timenow = time();
154 $somefound = false;
155 // The preferred way saves memory, dmllib.php
156 // find courses where limited enrolment is enabled
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
167 while ($oldenrolment = rs_fetch_next_record($rs_enrol)) {
168 role_unassign($oldenrolment->roleid, $oldenrolment->userid, 0, $oldenrolment->contextid);
169 $somefound = true;
171 rs_close($rs_enrol);
172 if($somefound) {
173 mtrace('Done');
174 } else {
175 mtrace('none found');
179 mtrace('Starting grade job ...', '');
180 grade_cron();
181 mtrace('Done ...', '');
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.
189 srand ((double) microtime() * 10000000);
190 $random100 = rand(0,100);
192 if ($random100 < 20) { // Approximately 20% of the time.
193 mtrace("Running clean-up tasks...");
195 /// Unenrol users who haven't logged in for $CFG->longtimenosee
197 if ($CFG->longtimenosee) { // value in days
198 $longtime = $timenow - ($CFG->longtimenosee * 3600 * 24);
199 if ($assigns = get_users_longtimenosee($longtime)) {
200 foreach ($assigns as $assign) {
201 if ($context = get_context_instance(CONTEXT_COURSE, $assign->courseid)) {
202 if (role_unassign(0, $assign->id, 0, $context->id)) {
203 mtrace("Deleted assignment for user $assign->id from course $assign->courseid");
211 /// Delete users who haven't confirmed within required period
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)");
223 flush();
227 /// Delete users who haven't completed profile within required period
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)");
239 flush();
243 /// Delete old logs to save space (this might need a timer to slow it down...)
245 if (!empty($CFG->loglifetime)) { // value in days
246 $loglifetime = $timenow - ($CFG->loglifetime * 3600 * 24);
247 delete_records_select("log", "time < '$loglifetime'");
249 flush();
251 /// Delete old cached texts
253 if (!empty($CFG->cachetext)) { // Defined in config.php
254 $cachelifetime = time() - $CFG->cachetext - 60; // Add an extra minute to allow for really heavy sites
255 delete_records_select('cache_text', "timemodified < '$cachelifetime'");
257 flush();
259 if (!empty($CFG->notifyloginfailures)) {
260 notify_login_failures();
262 flush();
264 sync_metacourses();
267 // generate new password emails for users
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 !='' ");
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!");
291 if(!empty($CFG->usetags)){
292 require_once($CFG->dirroot.'/tag/lib.php');
293 tag_cron();
296 } // End of occasional clean-up tasks
299 if (empty($CFG->disablescheduledbackups)) { // Defined in config.php
300 //Execute backup's cron
301 //Perhaps a long time and memory could help in large sites
302 @set_time_limit(0);
303 @raise_memory_limit("192M");
304 if (function_exists('apache_child_terminate')) {
305 // if we are running from Apache, give httpd a hint that
306 // it can recycle the process after it's done. Apache's
307 // memory management is truly awful but we can help it.
308 @apache_child_terminate();
310 if (file_exists("$CFG->dirroot/backup/backup_scheduled.php") and
311 file_exists("$CFG->dirroot/backup/backuplib.php") and
312 file_exists("$CFG->dirroot/backup/lib.php") and
313 file_exists("$CFG->libdir/blocklib.php")) {
314 include_once("$CFG->dirroot/backup/backup_scheduled.php");
315 include_once("$CFG->dirroot/backup/backuplib.php");
316 include_once("$CFG->dirroot/backup/lib.php");
317 require_once ("$CFG->libdir/blocklib.php");
318 mtrace("Running backups if required...");
320 if (! schedule_backup_cron()) {
321 mtrace("ERROR: Something went wrong while performing backup tasks!!!");
322 } else {
323 mtrace("Backup tasks finished.");
328 if (!empty($CFG->enablerssfeeds)) { //Defined in admin/variables page
329 include_once("$CFG->libdir/rsslib.php");
330 mtrace("Running rssfeeds if required...");
332 if ( ! cron_rss_feeds()) {
333 mtrace("Something went wrong while generating rssfeeds!!!");
334 } else {
335 mtrace("Rssfeeds finished");
339 /// Run the enrolment cron, if any
340 if (!($plugins = explode(',', $CFG->enrol_plugins_enabled))) {
341 $plugins = array($CFG->enrol);
343 require_once($CFG->dirroot .'/enrol/enrol.class.php');
344 foreach ($plugins as $p) {
345 $enrol = enrolment_factory::factory($p);
346 if (method_exists($enrol, 'cron')) {
347 $enrol->cron();
349 if (!empty($enrol->log)) {
350 mtrace($enrol->log);
352 unset($enrol);
355 /// Run the auth cron, if any
356 $auths = get_enabled_auth_plugins();
358 mtrace("Running auth crons if required...");
359 foreach ($auths as $auth) {
360 $authplugin = get_auth_plugin($auth);
361 if (method_exists($authplugin, 'cron')) {
362 mtrace("Running cron for auth/$auth...");
363 $authplugin->cron();
364 if (!empty($authplugin->log)) {
365 mtrace($authplugin->log);
368 unset($authplugin);
371 if (!empty($CFG->enablestats) and empty($CFG->disablestatsprocessing)) {
373 // check we're not before our runtime
374 $timetocheck = strtotime("$CFG->statsruntimestarthour:$CFG->statsruntimestartminute today");
376 if (time() > $timetocheck) {
377 $time = 60*60*20; // set it to 20 here for first run... (overridden by $CFG)
378 $clobber = true;
379 if (!empty($CFG->statsmaxruntime)) {
380 $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)
382 if (!get_field_sql('SELECT id FROM '.$CFG->prefix.'stats_daily')) {
383 // first run, set another lock. we'll check for this in subsequent runs to set the timeout to later for the normal lock.
384 set_cron_lock('statsfirstrunlock',true,$time,true);
385 $firsttime = true;
387 $time = 60*60*2; // this time set to 2.. (overridden by $CFG)
388 if (!empty($CFG->statsmaxruntime)) {
389 $time = $CFG->statsmaxruntime+(60*30); // add on half an hour to make sure (it could take that long to break out of the loop)
391 if ($config = get_record('config','name','statsfirstrunlock')) {
392 if (!empty($config->value)) {
393 $clobber = false; // if we're on the first run, just don't clobber it.
396 if (set_cron_lock('statsrunning',true,$time, $clobber)) {
397 require_once($CFG->dirroot.'/lib/statslib.php');
398 $return = stats_cron_daily();
399 if (stats_check_runtime() && $return == STATS_RUN_COMPLETE) {
400 stats_cron_weekly();
402 if (stats_check_runtime() && $return == STATS_RUN_COMPLETE) {
403 $return = $return && stats_cron_monthly();
405 if (stats_check_runtime() && $return == STATS_RUN_COMPLETE) {
406 stats_clean_old();
408 set_cron_lock('statsrunning',false);
409 if (!empty($firsttime)) {
410 set_cron_lock('statsfirstrunlock',false);
416 // run gradebook import/export/report cron
417 if ($gradeimports = get_list_of_plugins('grade/import')) {
418 foreach ($gradeimports as $gradeimport) {
419 if (file_exists($CFG->dirroot.'/grade/import/lib.php')) {
420 require_once($CFG->dirroot.'/grade/import/lib.php');
421 $cron_function = 'gradeimport_'.$gradeimport.'_cron';
422 if (function_exists($cron_function)) {
423 mtrace("Processing gradebook import function $cron_function ...", '');
424 $cron_function;
430 if ($gradeexports = get_list_of_plugins('grade/export')) {
431 foreach ($gradeexports as $gradeexport) {
432 if (file_exists($CFG->dirroot.'/grade/export/lib.php')) {
433 require_once($CFG->dirroot.'/grade/export/lib.php');
434 $cron_function = 'gradeexport_'.$gradeexport.'_cron';
435 if (function_exists($cron_function)) {
436 mtrace("Processing gradebook export function $cron_function ...", '');
437 $cron_function;
443 if ($gradereports = get_list_of_plugins('grade/report')) {
444 foreach ($gradereports as $gradereport) {
445 if (file_exists($CFG->dirroot.'/grade/report/lib.php')) {
446 require_once($CFG->dirroot.'/grade/report/lib.php');
447 $cron_function = 'gradereport_'.$gradereport.'_cron';
448 if (function_exists($cron_function)) {
449 mtrace("Processing gradebook report function $cron_function ...", '');
450 $cron_function;
456 //Unset session variables and destroy it
457 @session_unset();
458 @session_destroy();
460 mtrace("Cron script completed correctly");
462 $difftime = microtime_diff($starttime, microtime());
463 mtrace("Execution took ".$difftime." seconds");
465 /// finishe the IE hack
466 if (check_browser_version('MSIE')) {
467 echo "</xmp>";