new ratings functionality
[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
652fd672 29 require_once("../config.php");
f3221af9 30 require_once($CFG->dirroot.'/lib/adminlib.php');
f9903ed0 31
01f29000 32 if (!$alreadyadmin = isadmin()) {
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
428b6fec 45/// Start output log
f9903ed0 46
f9903ed0 47 $timenow = time();
428b6fec 48
49 mtrace("<pre>");
defaac4c 50 mtrace("Server Time: ".date('r',$timenow)."\n\n");
f9903ed0 51
b2ce450a 52/// Run all cron jobs for each module
c88f014a 53
defaac4c 54 mtrace("Starting activity modules");
9fa49e22 55 if ($mods = get_records_select("modules", "cron > 0 AND (($timenow - lastcron) > cron)")) {
f9903ed0 56 foreach ($mods as $mod) {
673de292 57 $libfile = "$CFG->dirroot/mod/$mod->name/lib.php";
58 if (file_exists($libfile)) {
59 include_once($libfile);
60 $cron_function = $mod->name."_cron";
61 if (function_exists($cron_function)) {
defaac4c 62 mtrace("Processing module function $cron_function ...", '');
673de292 63 if ($cron_function()) {
64 if (! set_field("modules", "lastcron", $timenow, "id", $mod->id)) {
defaac4c 65 mtrace("Error: could not update timestamp for $mod->fullname");
673de292 66 }
67 }
defaac4c 68 mtrace("done.");
f9903ed0 69 }
70 }
71 }
72 }
defaac4c 73 mtrace("Finished activity modules");
c88f014a 74
d6ead3a2 75 if (!empty($CFG->langcache)) {
76 mtrace('Updating languages cache');
77 get_list_of_languages();
78 }
79
80
b2ce450a 81/// Run all core cron jobs, but not every time since they aren't too important.
82/// These don't have a timer to reduce load, so we'll use a random number
83/// to randomly choose the percentage of times we should run these jobs.
c88f014a 84
b2ce450a 85 srand ((double) microtime() * 10000000);
86 $random100 = rand(0,100);
c88f014a 87
b2ce450a 88 if ($random100 < 20) { // Approximately 20% of the time.
defaac4c 89 mtrace("Running clean-up tasks...");
b2ce450a 90
91 /// Unenrol users who haven't logged in for $CFG->longtimenosee
92
93 if ($CFG->longtimenosee) { // value in days
94 $longtime = $timenow - ($CFG->longtimenosee * 3600 * 24);
937ae59c 95 if ($students = get_users_longtimenosee($longtime)) {
96 foreach ($students as $student) {
97 if (unenrol_student($student->userid, $student->course)) {
defaac4c 98 mtrace("Deleted student enrolment for user $student->userid from course $student->course");
b2ce450a 99 }
100 }
101 }
102 }
103
104
6c61fd04 105 /// Delete users who haven't confirmed within required period
c6c43ae9 106
c6c43ae9 107 $oneweek = $timenow - ($CFG->deleteunconfirmed * 3600);
b2ce450a 108 if ($users = get_users_unconfirmed($oneweek)) {
6cb86b39 109 foreach ($users as $user) {
7b8cc339 110 if (delete_records('user', 'id', $user->id)) {
428b6fec 111 mtrace("Deleted unconfirmed user for ".fullname($user, true)." ($user->id)");
f282e631 112 }
6cb86b39 113 }
114 }
69f78bcb 115 flush();
7b8cc339 116
117
118
119 /// Delete users who haven't completed profile within required period
120
121 $oneweek = $timenow - ($CFG->deleteunconfirmed * 3600);
122 if ($users = get_users_not_fully_set_up($oneweek)) {
123 foreach ($users as $user) {
124 if (delete_records('user', 'id', $user->id)) {
125 mtrace("Deleted not fully setup user $user->username ($user->id)");
126 }
127 }
128 }
129 flush();
130
131
b2ce450a 132
b2ce450a 133 /// Delete old logs to save space (this might need a timer to slow it down...)
134
135 if (!empty($CFG->loglifetime)) { // value in days
136 $loglifetime = $timenow - ($CFG->loglifetime * 3600 * 24);
137 delete_records_select("log", "time < '$loglifetime'");
138 }
69f78bcb 139 flush();
cb3a4484 140
141 /// Delete old cached texts
142
143 if (!empty($CFG->cachetext)) { // Defined in config.php
144 $cachelifetime = time() - $CFG->cachetext;
e3812d2a 145 delete_records_select("cache_text", "timemodified < '$cachelifetime'");
cb3a4484 146 }
69f78bcb 147 flush();
d846e50a 148
149 if (!empty($CFG->notifyloginfailures)) {
150 notify_login_failures();
151 }
69f78bcb 152 flush();
d846e50a 153
b61efafb 154 sync_metacourses();
155
e3b6b2b0 156 //
157 // generate new password emails for users
158 //
159 mtrace('checking for create_password');
160 if (count_records('user_preferences', 'name', 'create_password', 'value', '1')) {
161 mtrace('creating passwords for new users');
162 $newusers = get_records_sql("SELECT u.id as id, u.email, u.firstname,
163 u.lastname, u.username,
164 p.id as prefid
165 FROM {$CFG->prefix}user u
166 JOIN {$CFG->prefix}user_preferences p ON u.id=p.userid
167 WHERE p.name='create_password' AND p.value=1 AND u.email !='' ");
168
169 foreach ($newusers as $newuserid => $newuser) {
170 $newuser->emailstop = 0; // send email regardless
171 // email user
172 if (setnew_password_and_mail($newuser)) {
173 // remove user pref
174 delete_records('user_preferences', 'id', $newuser->prefid);
175 } else {
176 trigger_error("Could not create and mail new user password!");
177 }
178 }
179 }
180
d846e50a 181 } // End of occasional clean-up tasks
540bab47 182
750eeaeb 183
12fb4682 184 if (!isset($CFG->disablescheduledbackups)) { // Defined in config.php
74736e49 185 //Execute backup's cron
186 //Perhaps a long time and memory could help in large sites
a71bfa1c 187 @set_time_limit(0);
1fae4967 188 @raise_memory_limit("128M");
a2ce7344 189 if (function_exists('apache_child_terminate')) {
190 // if we are running from Apache, give httpd a hint that
191 // it can recycle the process after it's done. Apache's
192 // memory management is truly awful but we can help it.
193 @apache_child_terminate();
194 }
74736e49 195 if (file_exists("$CFG->dirroot/backup/backup_scheduled.php") and
196 file_exists("$CFG->dirroot/backup/backuplib.php") and
e91e2b6a 197 file_exists("$CFG->dirroot/backup/lib.php") and
198 file_exists("$CFG->libdir/blocklib.php")) {
74736e49 199 include_once("$CFG->dirroot/backup/backup_scheduled.php");
200 include_once("$CFG->dirroot/backup/backuplib.php");
201 include_once("$CFG->dirroot/backup/lib.php");
e91e2b6a 202 require_once ("$CFG->libdir/blocklib.php");
defaac4c 203 mtrace("Running backups if required...");
74736e49 204
205 if (! schedule_backup_cron()) {
defaac4c 206 mtrace("ERORR: Something went wrong while performing backup tasks!!!");
74736e49 207 } else {
defaac4c 208 mtrace("Backup tasks finished.");
74736e49 209 }
e6d273eb 210 }
d3159192 211 }
212
8adcb49f 213 if (!empty($CFG->enablerssfeeds)) { //Defined in admin/variables page
3c02d134 214 include_once("$CFG->libdir/rsslib.php");
215 mtrace("Running rssfeeds if required...");
8adcb49f 216
3c02d134 217 if ( ! cron_rss_feeds()) {
218 mtrace("Something went wrong while generating rssfeeds!!!");
219 } else {
220 mtrace("Rssfeeds finished");
8adcb49f 221 }
222 }
223
04e44325 224/// Run the enrolment cron, if any
225 require_once("$CFG->dirroot/enrol/$CFG->enrol/enrol.php");
226 $enrol = new enrolment_plugin();
227 $enrol->cron();
7e192c78 228 if (!empty($enrol->log)) {
defaac4c 229 mtrace($enrol->log);
7e192c78 230 }
04e44325 231
f3221af9 232 if (!empty($CFG->enablestats)) {
4900433c 233
234 // check we're not before our runtime
235 $timetocheck = strtotime("$CFG->statsruntimestarthour:$CFG->statsruntimestartminute today");
236
237 if (time() > $timetocheck) {
238 $time = 60*60*20; // set it to 20 here for first run... (overridden by $CFG)
239 $clobber = true;
240 if (!empty($CFG->statsmaxruntime)) {
241 $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 242 }
4900433c 243 if (!get_field_sql('SELECT id FROM '.$CFG->prefix.'stats_daily LIMIT 1')) {
244 // first run, set another lock. we'll check for this in subsequent runs to set the timeout to later for the normal lock.
245 set_cron_lock('statsfirstrunlock',true,$time,true);
246 $firsttime = true;
f3221af9 247 }
4900433c 248 $time = 60*60*2; // this time set to 2.. (overridden by $CFG)
249 if (!empty($CFG->statsmaxruntime)) {
250 $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 251 }
4900433c 252 if ($config = get_record('config','name','statsfirstrunlock')) {
253 if (!empty($config->value)) {
254 $clobber = false; // if we're on the first run, just don't clobber it.
255 }
aff25119 256 }
4900433c 257 if (set_cron_lock('statsrunning',true,$time, $clobber)) {
258 require_once($CFG->dirroot.'/lib/statslib.php');
259 $return = stats_cron_daily();
260 if (stats_check_runtime() && $return == STATS_RUN_COMPLETE) {
261 stats_cron_weekly();
262 }
263 if (stats_check_runtime() && $return == STATS_RUN_COMPLETE) {
264 $return = $return && stats_cron_monthly();
265 }
266 if (stats_check_runtime() && $return == STATS_RUN_COMPLETE) {
267 stats_clean_old();
268 }
269 set_cron_lock('statsrunning',false);
270 if (!empty($firsttime)) {
271 set_cron_lock('statsfirstrunlock',false);
272 }
f3221af9 273 }
274 }
275 }
276
db6b033d 277 //Unset session variables and destroy it
278 @session_unset();
279 @session_destroy();
280
defaac4c 281 mtrace("Cron script completed correctly");
f9903ed0 282
498d4032 283 $difftime = microtime_diff($starttime, microtime());
defaac4c 284 mtrace("Execution took ".$difftime." seconds");
498d4032 285
f9903ed0 286?>