separating the site course context and the site context, could be buggy, please repor...
[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
f9903ed0 13
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');
d5f286f1 20
21/// The current directory in PHP version 4.3.0 and above isn't necessarily the
22/// directory of the script when run from the command line. The require_once()
23/// would fail, so we'll have to chdir()
24
25 if (!isset($_SERVER['REMOTE_ADDR']) && isset($_SERVER['argv'][0])) {
26 chdir(dirname($_SERVER['argv'][0]));
27 }
498d4032 28
331ca297 29 require_once(dirname(__FILE__) . '/../config.php');
6e4dc10f 30 require_once($CFG->libdir.'/adminlib.php');
f9903ed0 31
41d7209c 32 if (!$alreadyadmin = has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM, SITEID))) {
10c6c606 33 unset($_SESSION['USER']);
34 unset($USER);
35 unset($_SESSION['SESSION']);
36 unset($SESSION);
01f29000 37 $USER = get_admin(); /// Temporarily, to provide environment for this script
13309059 38 // we need to override the admin timezone to the moodle timezone!
39 $USER->timezone = $CFG->timezone;
01f29000 40 }
afabdb14 41
00de82df 42 //unset test cookie, user must login again anyway
43 setcookie('MoodleSessionTest'.$CFG->sessioncookie, '', time() - 3600, '/');
44
5e601222 45/// switch to site language and locale
5ec8a4f0 46 if (!empty($CFG->courselang)) {
5e601222 47 unset ($CFG->courselang);
5ec8a4f0 48 }
5e601222 49 if (!empty($SESSION->lang)) {
50 unset ($SESSION->lang);
51 }
52 $USER->lang = '';
53 moodle_setlocale();
54
55/// send mime type and encoding
58e8f85b 56 if (check_browser_version('MSIE')) {
57 //ugly IE hack to work around downloading instead of viewing
810944af 58 @header('Content-Type: text/html; charset=utf-8');
58e8f85b 59 echo "<xmp>"; //<pre> is not good enough for us here
60 } else {
61 //send proper plaintext header
810944af 62 @header('Content-Type: text/plain; charset=utf-8');
58e8f85b 63 }
5e601222 64
428b6fec 65/// Start output log
f9903ed0 66
f9903ed0 67 $timenow = time();
428b6fec 68
defaac4c 69 mtrace("Server Time: ".date('r',$timenow)."\n\n");
f9903ed0 70
b2ce450a 71/// Run all cron jobs for each module
c88f014a 72
defaac4c 73 mtrace("Starting activity modules");
9fa49e22 74 if ($mods = get_records_select("modules", "cron > 0 AND (($timenow - lastcron) > cron)")) {
f9903ed0 75 foreach ($mods as $mod) {
673de292 76 $libfile = "$CFG->dirroot/mod/$mod->name/lib.php";
77 if (file_exists($libfile)) {
78 include_once($libfile);
79 $cron_function = $mod->name."_cron";
80 if (function_exists($cron_function)) {
defaac4c 81 mtrace("Processing module function $cron_function ...", '');
673de292 82 if ($cron_function()) {
83 if (! set_field("modules", "lastcron", $timenow, "id", $mod->id)) {
defaac4c 84 mtrace("Error: could not update timestamp for $mod->fullname");
673de292 85 }
86 }
defaac4c 87 mtrace("done.");
f9903ed0 88 }
89 }
90 }
91 }
defaac4c 92 mtrace("Finished activity modules");
c88f014a 93
f9648e77 94 mtrace("Starting blocks");
95 if ($blocks = get_records_select("block", "cron > 0 AND (($timenow - lastcron) > cron)")) {
96 // we will need the base class.
97 require_once($CFG->dirroot.'/blocks/moodleblock.class.php');
98 foreach ($blocks as $block) {
99 $blockfile = $CFG->dirroot.'/blocks/'.$block->name.'/block_'.$block->name.'.php';
100 if (file_exists($blockfile)) {
101 require_once($blockfile);
102 $classname = 'block_'.$block->name;
103 $blockobj = new $classname;
104 if (method_exists($blockobj,'cron')) {
105 mtrace("Processing cron function for ".$block->name.'....','');
106 if ($blockobj->cron()) {
107 if (!set_field('block','lastcron',$timenow,'id',$block->id)) {
108 mtrace('Error: could not update timestamp for '.$block->name);
109 }
110 }
111 mtrace('done.');
112 }
113 }
114
115 }
116 }
117 mtrace("Finished blocks");
118
d6ead3a2 119 if (!empty($CFG->langcache)) {
120 mtrace('Updating languages cache');
121 get_list_of_languages();
122 }
123
124
b2ce450a 125/// Run all core cron jobs, but not every time since they aren't too important.
126/// These don't have a timer to reduce load, so we'll use a random number
127/// to randomly choose the percentage of times we should run these jobs.
c88f014a 128
b2ce450a 129 srand ((double) microtime() * 10000000);
130 $random100 = rand(0,100);
c88f014a 131
b2ce450a 132 if ($random100 < 20) { // Approximately 20% of the time.
defaac4c 133 mtrace("Running clean-up tasks...");
b2ce450a 134
135 /// Unenrol users who haven't logged in for $CFG->longtimenosee
136
137 if ($CFG->longtimenosee) { // value in days
138 $longtime = $timenow - ($CFG->longtimenosee * 3600 * 24);
6e208cd2 139 if ($assigns = get_users_longtimenosee($longtime)) {
140 foreach ($assigns as $assign) {
141 if ($context = get_context_instance(CONTEXT_COURSE, $assign->courseid)) {
9de47873 142 if (role_unassign(0, $assign->id, 0, $context->id)) {
143 mtrace("Deleted student enrolment for user $assign->id from course $assign->courseid");
6e208cd2 144 }
b2ce450a 145 }
146 }
147 }
148 }
149
150
6c61fd04 151 /// Delete users who haven't confirmed within required period
c6c43ae9 152
8c182006 153 if (!empty($CFG->deleteunconfirmed)) {
154 $oneweek = $timenow - ($CFG->deleteunconfirmed * 3600);
155 if ($users = get_users_unconfirmed($oneweek)) {
156 foreach ($users as $user) {
157 if (delete_records('user', 'id', $user->id)) {
158 mtrace("Deleted unconfirmed user for ".fullname($user, true)." ($user->id)");
159 }
f282e631 160 }
6cb86b39 161 }
162 }
69f78bcb 163 flush();
7b8cc339 164
165
166
167 /// Delete users who haven't completed profile within required period
168
8c182006 169 if (!empty($CFG->deleteunconfirmed)) {
170 $oneweek = $timenow - ($CFG->deleteunconfirmed * 3600);
171 if ($users = get_users_not_fully_set_up($oneweek)) {
172 foreach ($users as $user) {
173 if (delete_records('user', 'id', $user->id)) {
174 mtrace("Deleted not fully setup user $user->username ($user->id)");
175 }
7b8cc339 176 }
177 }
178 }
179 flush();
180
181
b2ce450a 182
b2ce450a 183 /// Delete old logs to save space (this might need a timer to slow it down...)
184
185 if (!empty($CFG->loglifetime)) { // value in days
186 $loglifetime = $timenow - ($CFG->loglifetime * 3600 * 24);
187 delete_records_select("log", "time < '$loglifetime'");
188 }
69f78bcb 189 flush();
cb3a4484 190
191 /// Delete old cached texts
192
193 if (!empty($CFG->cachetext)) { // Defined in config.php
a9743837 194 $cachelifetime = time() - $CFG->cachetext - 60; // Add an extra minute to allow for really heavy sites
195 delete_records_select('cache_text', "timemodified < '$cachelifetime'");
cb3a4484 196 }
69f78bcb 197 flush();
d846e50a 198
199 if (!empty($CFG->notifyloginfailures)) {
200 notify_login_failures();
201 }
69f78bcb 202 flush();
d846e50a 203
b61efafb 204 sync_metacourses();
205
e3b6b2b0 206 //
207 // generate new password emails for users
208 //
209 mtrace('checking for create_password');
210 if (count_records('user_preferences', 'name', 'create_password', 'value', '1')) {
211 mtrace('creating passwords for new users');
212 $newusers = get_records_sql("SELECT u.id as id, u.email, u.firstname,
213 u.lastname, u.username,
214 p.id as prefid
215 FROM {$CFG->prefix}user u
216 JOIN {$CFG->prefix}user_preferences p ON u.id=p.userid
217 WHERE p.name='create_password' AND p.value=1 AND u.email !='' ");
218
219 foreach ($newusers as $newuserid => $newuser) {
220 $newuser->emailstop = 0; // send email regardless
221 // email user
222 if (setnew_password_and_mail($newuser)) {
223 // remove user pref
224 delete_records('user_preferences', 'id', $newuser->prefid);
225 } else {
226 trigger_error("Could not create and mail new user password!");
227 }
228 }
229 }
230
d846e50a 231 } // End of occasional clean-up tasks
540bab47 232
750eeaeb 233
50999a0b 234 if (empty($CFG->disablescheduledbackups)) { // Defined in config.php
74736e49 235 //Execute backup's cron
236 //Perhaps a long time and memory could help in large sites
a71bfa1c 237 @set_time_limit(0);
1fae4967 238 @raise_memory_limit("128M");
a2ce7344 239 if (function_exists('apache_child_terminate')) {
240 // if we are running from Apache, give httpd a hint that
241 // it can recycle the process after it's done. Apache's
242 // memory management is truly awful but we can help it.
243 @apache_child_terminate();
244 }
74736e49 245 if (file_exists("$CFG->dirroot/backup/backup_scheduled.php") and
246 file_exists("$CFG->dirroot/backup/backuplib.php") and
e91e2b6a 247 file_exists("$CFG->dirroot/backup/lib.php") and
248 file_exists("$CFG->libdir/blocklib.php")) {
74736e49 249 include_once("$CFG->dirroot/backup/backup_scheduled.php");
250 include_once("$CFG->dirroot/backup/backuplib.php");
251 include_once("$CFG->dirroot/backup/lib.php");
e91e2b6a 252 require_once ("$CFG->libdir/blocklib.php");
defaac4c 253 mtrace("Running backups if required...");
74736e49 254
255 if (! schedule_backup_cron()) {
04ddd06c 256 mtrace("ERROR: Something went wrong while performing backup tasks!!!");
74736e49 257 } else {
defaac4c 258 mtrace("Backup tasks finished.");
74736e49 259 }
e6d273eb 260 }
d3159192 261 }
262
8adcb49f 263 if (!empty($CFG->enablerssfeeds)) { //Defined in admin/variables page
3c02d134 264 include_once("$CFG->libdir/rsslib.php");
265 mtrace("Running rssfeeds if required...");
8adcb49f 266
3c02d134 267 if ( ! cron_rss_feeds()) {
268 mtrace("Something went wrong while generating rssfeeds!!!");
269 } else {
270 mtrace("Rssfeeds finished");
8adcb49f 271 }
272 }
273
04e44325 274/// Run the enrolment cron, if any
f9667a5a 275 if (!($plugins = explode(',', $CFG->enrol_plugins_enabled))) {
276 $plugins = array($CFG->enrol);
277 }
278 require_once($CFG->dirroot .'/enrol/enrol.class.php');
279 foreach ($plugins as $p) {
280 $enrol = enrolment_factory::factory($p);
281 if (method_exists($enrol, 'cron')) {
282 $enrol->cron();
283 }
284 if (!empty($enrol->log)) {
285 mtrace($enrol->log);
286 }
287 unset($enrol);
7e192c78 288 }
04e44325 289
72df7e1e 290 if (!empty($CFG->enablestats) and empty($CFG->disablestatsprocessing)) {
4900433c 291
292 // check we're not before our runtime
293 $timetocheck = strtotime("$CFG->statsruntimestarthour:$CFG->statsruntimestartminute today");
294
295 if (time() > $timetocheck) {
296 $time = 60*60*20; // set it to 20 here for first run... (overridden by $CFG)
297 $clobber = true;
298 if (!empty($CFG->statsmaxruntime)) {
299 $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 300 }
37c47aba 301 if (!get_field_sql('SELECT id FROM '.$CFG->prefix.'stats_daily')) {
4900433c 302 // first run, set another lock. we'll check for this in subsequent runs to set the timeout to later for the normal lock.
303 set_cron_lock('statsfirstrunlock',true,$time,true);
304 $firsttime = true;
f3221af9 305 }
4900433c 306 $time = 60*60*2; // this time set to 2.. (overridden by $CFG)
307 if (!empty($CFG->statsmaxruntime)) {
308 $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 309 }
4900433c 310 if ($config = get_record('config','name','statsfirstrunlock')) {
311 if (!empty($config->value)) {
312 $clobber = false; // if we're on the first run, just don't clobber it.
313 }
aff25119 314 }
4900433c 315 if (set_cron_lock('statsrunning',true,$time, $clobber)) {
316 require_once($CFG->dirroot.'/lib/statslib.php');
317 $return = stats_cron_daily();
318 if (stats_check_runtime() && $return == STATS_RUN_COMPLETE) {
319 stats_cron_weekly();
320 }
321 if (stats_check_runtime() && $return == STATS_RUN_COMPLETE) {
322 $return = $return && stats_cron_monthly();
323 }
324 if (stats_check_runtime() && $return == STATS_RUN_COMPLETE) {
325 stats_clean_old();
326 }
327 set_cron_lock('statsrunning',false);
328 if (!empty($firsttime)) {
329 set_cron_lock('statsfirstrunlock',false);
330 }
f3221af9 331 }
332 }
333 }
334
db6b033d 335 //Unset session variables and destroy it
336 @session_unset();
337 @session_destroy();
338
defaac4c 339 mtrace("Cron script completed correctly");
f9903ed0 340
498d4032 341 $difftime = microtime_diff($starttime, microtime());
defaac4c 342 mtrace("Execution took ".$difftime." seconds");
498d4032 343
58e8f85b 344/// finishe the IE hack
345 if (check_browser_version('MSIE')) {
346 echo "</xmp>";
347 }
348
f9903ed0 349?>