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