MDL-14589 remove old user icons after upgrade
[moodle.git] / lib / db / upgradelib.php
CommitLineData
117bd748 1<?php
42ff9ce6 2
3/*
4 * This file is used for special upgrade functions - for example groups and gradebook.
56a1a882 5 * These functions must use SQL and database related functions only- no other Moodle API,
42ff9ce6 6 * because it might depend on db structures that are not yet present during upgrade.
7 * (Do not use functions from accesslib.php, grades classes or group functions at all!)
8 */
9
863850d2 10function upgrade_fix_category_depths() {
f33e1ed4 11 global $CFG, $DB;
863850d2 12
13 // first fix incorrect parents
14 $sql = "SELECT c.id
f33e1ed4 15 FROM {course_categories} c
16 WHERE c.parent > 0 AND c.parent NOT IN (SELECT pc.id FROM {course_categories} pc)";
17 if ($rs = $DB->get_recordset_sql($sql)) {
18 foreach ($rs as $cat) {
863850d2 19 $cat->depth = 1;
20 $cat->path = '/'.$cat->id;
21 $cat->parent = 0;
f33e1ed4 22 $DB->update_record('course_categories', $cat);
863850d2 23 }
f33e1ed4 24 $rs->close();
863850d2 25 }
26
27 // now add path and depth to top level categories
f33e1ed4 28 $sql = "UPDATE {course_categories}
245ac557 29 SET depth = 1, path = ".$DB->sql_concat("'/'", "id")."
863850d2 30 WHERE parent = 0";
f33e1ed4 31 $DB->execute($sql);
863850d2 32
33 // now fix all other levels - slow but works in all supported dbs
34 $parentdepth = 1;
f33e1ed4 35 while ($DB->record_exists('course_categories', array('depth'=>0))) {
863850d2 36 $sql = "SELECT c.id, pc.path
f33e1ed4 37 FROM {course_categories} c, {course_categories} pc
38 WHERE c.parent=pc.id AND c.depth=0 AND pc.depth=?";
39 if ($rs = $DB->get_recordset_sql($sql, array($parentdepth))) {
f33e1ed4 40 foreach ($rs as $cat) {
863850d2 41 $cat->depth = $parentdepth+1;
42 $cat->path = $cat->path.'/'.$cat->id;
f33e1ed4 43 $DB->update_record('course_categories', $cat);
863850d2 44 }
f33e1ed4 45 $rs->close();
863850d2 46 }
47 $parentdepth++;
48 if ($parentdepth > 100) {
49 //something must have gone wrong - nobody can have more than 100 levels of categories, right?
50 debugging('Unknown error fixing category depths');
51 break;
52 }
53 }
863850d2 54}
55
172dd12c 56/**
57 * Moves all course files except the moddata to new file storage
58 *
59 * Unfortunately this function uses core file related functions - it might be necessary to tweak it if something changes there :-(
60 */
61function upgrade_migrate_files_courses() {
62 global $DB, $CFG;
63 require_once($CFG->libdir.'/filelib.php');
64
65 $count = $DB->count_records('course');
66 $pbar = new progress_bar('migratecoursefiles', 500, true);
67
68 $rs = $DB->get_recordset('course');
172dd12c 69 $i = 0;
70 foreach ($rs as $course) {
71 $i++;
775f811a 72 upgrade_set_timeout(60*5); // set up timeout, may also abort execution
172dd12c 73 $context = get_context_instance(CONTEXT_COURSE, $course->id);
74 upgrade_migrate_files_course($context, '/', true);
75 $pbar->update($i, $count, "Migrated course files - course $i/$count.");
76 }
172dd12c 77 $rs->close();
78
79 return true;
80}
81
edfd6a5e
PS
82/**
83 * Internal function - do not use directly
84 */
85function upgrade_migrate_user_icons() {
86 global $CFG, $OUTPUT, $DB;
87
88 $fs = get_file_storage();
89
90 $icon = array('component'=>'user', 'filearea'=>'icon', 'itemid'=>0, 'filepath'=>'/');
91
92 $count = $DB->count_records('user', array('picture'=>1, 'deleted'=>0));
93 $pbar = new progress_bar('migratecoursefiles', 500, true);
94
95 $rs = $DB->get_recordset('user', array('picture'=>1, 'deleted'=>0), 'id ASC', 'id, picture');
96 $i = 0;
97 foreach ($rs as $user) {
98 $i++;
99 upgrade_set_timeout(60); /// Give upgrade at least 60 more seconds
100 $pbar->update($i, $count, "Migrated course files - course $i/$count.");
101
102 $context = get_context_instance(CONTEXT_USER, $user->id);
103
104 if ($fs->file_exists($context->id, 'user', 'icon', 0, '/', 'f1.jpg')) {
105 // already converted!
106 continue;
107 }
108
109 $level1 = floor($user->id / 1000) * 1000;
110 $userdir = "$CFG->dataroot/user/$level1/$user->id";
111 if (!file_exists("$userdir/f1.jpg") or !file_exists("$userdir/f2.jpg")) {
112 $userdir = "$CFG->dataroot/users/$user->id";
113 if (!file_exists("$userdir/f1.jpg") or !file_exists("$userdir/f2.jpg")) {
114 // no image found, sorry
115 $user->picture = 0;
116 $DB->update_record('user', $user);
117 continue;
118 }
119 }
120
121 $icon['contextid'] = $context->id;
122 $icon['filename'] = 'f1.jpg';
123 $fs->create_file_from_pathname($icon, "$userdir/f1.jpg");
124 $icon['filename'] = 'f2.jpg';
125 $fs->create_file_from_pathname($icon, "$userdir/f2.jpg");
126 }
127 $rs->close();
128
129 // purge all old user image dirs
c7744f12
PS
130 remove_dir("$CFG->dataroot/user");
131 remove_dir("$CFG->dataroot/users");
edfd6a5e
PS
132}
133
172dd12c 134/**
135 * Internal function - do not use directly
136 */
137function upgrade_migrate_files_course($context, $path, $delete) {
aa9a6867 138 global $CFG, $OUTPUT;
172dd12c 139
140 $fullpathname = $CFG->dataroot.'/'.$context->instanceid.$path;
141 if (!file_exists($fullpathname)) {
142 return;
143 }
144 $items = new DirectoryIterator($fullpathname);
145 $fs = get_file_storage();
146
147 foreach ($items as $item) {
148 if ($item->isDot()) {
149 continue;
150 }
151
152 if ($item->isLink()) {
775f811a 153 // do not delete symbolic links or its children
172dd12c 154 $delete_this = false;
155 } else {
156 $delete_this = $delete;
157 }
158
159 if (strpos($path, '/backupdata/') === 0) {
64f93798
PS
160 $component = 'backup';
161 $filearea = 'course';
162 $filepath = substr($path, strlen('/backupdata'));
172dd12c 163 } else {
64f93798
PS
164 $component = 'course';
165 $filearea = 'legacy';
166 $filepath = $path;
172dd12c 167 }
168
169 if ($item->isFile()) {
170 if (!$item->isReadable()) {
aa9a6867 171 echo $OUTPUT->notification(" File not readable, skipping: ".$fullpathname.$item->getFilename());
172dd12c 172 continue;
173 }
174
175 $filepath = clean_param($filepath, PARAM_PATH);
176 $filename = clean_param($item->getFilename(), PARAM_FILE);
177
178 if ($filename === '') {
aa54ed7b 179 //unsupported chars, sorry
172dd12c 180 continue;
181 }
182
64f93798
PS
183 if (!$fs->file_exists($context->id, $component, $filearea, '0', $filepath, $filename)) {
184 $file_record = array('contextid'=>$context->id, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>0, 'filepath'=>$filepath, 'filename'=>$filename,
172dd12c 185 'timecreated'=>$item->getCTime(), 'timemodified'=>$item->getMTime());
186 if ($fs->create_file_from_pathname($file_record, $fullpathname.$item->getFilename())) {
187 if ($delete_this) {
188 @unlink($fullpathname.$item->getFilename());
189 }
190 }
191 }
192
193 } else {
194 if ($path == '/' and $item->getFilename() == 'moddata') {
195 continue; // modules are responsible
196 }
197
aa54ed7b 198 $dirname = clean_param($item->getFilename(), PARAM_PATH);
199 if ($dirname === '') {
200 //unsupported chars, sorry
201 continue;
202 }
203 $filepath = ($filepath.$dirname.'/');
172dd12c 204 if ($filepath !== '/backupdata/') {
64f93798 205 $fs->create_directory($context->id, $component, $filearea, 0, $filepath);
172dd12c 206 }
207
208 //migrate recursively all subdirectories
209 upgrade_migrate_files_course($context, $path.$item->getFilename().'/', $delete_this);
210 if ($delete_this) {
211 // delete dir if empty
212 @rmdir($fullpathname.$item->getFilename());
213 }
214 }
215 }
216 unset($items); //release file handles
217}
218
219/**
220 * Moves all block attachments
221 *
222 * Unfortunately this function uses core file related functions - it might be necessary to tweak it if something changes there :-(
223 */
224function upgrade_migrate_files_blog() {
aa9a6867 225 global $DB, $CFG, $OUTPUT;
172dd12c 226
227 $fs = get_file_storage();
228
a1442d4e 229 $count = $DB->count_records_select('post', "module='blog' AND attachment IS NOT NULL AND attachment <> '1'");
172dd12c 230
a1442d4e 231 if ($rs = $DB->get_recordset_select('post', "module='blog' AND attachment IS NOT NULL AND attachment <> '1'")) {
172dd12c 232
775f811a 233 upgrade_set_timeout(60*20); // set up timeout, may also abort execution
234
172dd12c 235 $pbar = new progress_bar('migrateblogfiles', 500, true);
236
172dd12c 237 $i = 0;
238 foreach ($rs as $entry) {
239 $i++;
240 $pathname = "$CFG->dataroot/blog/attachments/$entry->id/$entry->attachment";
241 if (!file_exists($pathname)) {
775f811a 242 $entry->attachment = NULL;
243 $DB->update_record('post', $entry);
172dd12c 244 continue;
245 }
246
247 $filename = clean_param($entry->attachment, PARAM_FILE);
248 if ($filename === '') {
249 // weird file name, ignore it
250 $entry->attachment = NULL;
251 $DB->update_record('post', $entry);
252 continue;
253 }
254
255 if (!is_readable($pathname)) {
aa9a6867 256 echo $OUTPUT->notification(" File not readable, skipping: ".$pathname);
172dd12c 257 continue;
258 }
259
64f93798
PS
260 if (!$fs->file_exists(SYSCONTEXTID, 'blog', 'attachment', $entry->id, '/', $filename)) {
261 $file_record = array('contextid'=>SYSCONTEXTID, 'component'=>'blog', 'filearea'=>'attachment', 'itemid'=>$entry->id, 'filepath'=>'/', 'filename'=>$filename,
775f811a 262 'timecreated'=>filectime($pathname), 'timemodified'=>filemtime($pathname), 'userid'=>$entry->userid);
172dd12c 263 $fs->create_file_from_pathname($file_record, $pathname);
264 }
265 @unlink($pathname);
266 @rmdir("$CFG->dataroot/blog/attachments/$entry->id/");
267
268 $entry->attachment = 1; // file name not needed there anymore
269 $DB->update_record('post', $entry);
270 $pbar->update($i, $count, "Migrated blog attachments - $i/$count.");
271 }
172dd12c 272 $rs->close();
273 }
775f811a 274
172dd12c 275 @rmdir("$CFG->dataroot/blog/attachments/");
276 @rmdir("$CFG->dataroot/blog/");
277}
02caf1e7 278
279/**
280 * This function will fix the status of the localhost/all records in the mnet_host table
281 * checking they exist and adding them if missing + redefine CFG->mnet_localhost_id and
282 * CFG->mnet_all_hosts_id if needed + update all the users having non-existent mnethostid
283 * to correct CFG->mnet_localhost_id
284 *
285 * Implemented because, at some point, specially in old installations upgraded along
286 * multiple versions, sometimes the stuff above has ended being inconsistent, causing
c0002023 287 * problems here and there (noticeably in backup/restore). MDL-16879
02caf1e7 288 */
289function upgrade_fix_incorrect_mnethostids() {
290
291 global $CFG, $DB;
292
293/// Get current $CFG/mnet_host records
294 $old_mnet_localhost_id = !empty($CFG->mnet_localhost_id) ? $CFG->mnet_localhost_id : 0;
295 $old_mnet_all_hosts_id = !empty($CFG->mnet_all_hosts_id) ? $CFG->mnet_all_hosts_id : 0;
296
297 $current_mnet_localhost_host = $DB->get_record('mnet_host', array('wwwroot' => $CFG->wwwroot)); /// By wwwroot
298 $current_mnet_all_hosts_host = $DB->get_record_select('mnet_host', $DB->sql_isempty('mnet_host', 'wwwroot', false, false)); /// By empty wwwroot
299
7062a798
PL
300 if (!$moodleapplicationid = $DB->get_field('mnet_application', 'id', array('name' => 'moodle'))) {
301 $m = (object)array(
302 'name' => 'moodle',
303 'display_name' => 'Moodle',
304 'xmlrpc_server_url' => '/mnet/xmlrpc/server.php',
305 'sso_land_url' => '/auth/mnet/land.php',
c9606565 306 'sso_jump_url' => '/auth/mnet/jump.php',
7062a798
PL
307 );
308 $moodleapplicationid = $DB->insert_record('mnet_application', $m);
309 }
310
02caf1e7 311/// Create localhost_host if necessary (pretty improbable but better to be 100% in the safe side)
312/// Code stolen from mnet_environment->init
313 if (!$current_mnet_localhost_host) {
314 $current_mnet_localhost_host = new stdClass();
315 $current_mnet_localhost_host->wwwroot = $CFG->wwwroot;
316 $current_mnet_localhost_host->ip_address = '';
317 $current_mnet_localhost_host->public_key = '';
318 $current_mnet_localhost_host->public_key_expires = 0;
319 $current_mnet_localhost_host->last_connect_time = 0;
320 $current_mnet_localhost_host->last_log_id = 0;
321 $current_mnet_localhost_host->deleted = 0;
322 $current_mnet_localhost_host->name = '';
7062a798 323 $current_mnet_localhost_host->applicationid = $moodleapplicationid;
02caf1e7 324 /// Get the ip of the server
325 if (empty($_SERVER['SERVER_ADDR'])) {
326 /// SERVER_ADDR is only returned by Apache-like webservers
327 $count = preg_match("@^(?:http[s]?://)?([A-Z0-9\-\.]+).*@i", $current_mnet_localhost_host->wwwroot, $matches);
328 $my_hostname = $count > 0 ? $matches[1] : false;
329 $my_ip = gethostbyname($my_hostname); // Returns unmodified hostname on failure. DOH!
330 if ($my_ip == $my_hostname) {
331 $current_mnet_localhost_host->ip_address = 'UNKNOWN';
332 } else {
333 $current_mnet_localhost_host->ip_address = $my_ip;
334 }
335 } else {
336 $current_mnet_localhost_host->ip_address = $_SERVER['SERVER_ADDR'];
337 }
338 $current_mnet_localhost_host->id = $DB->insert_record('mnet_host', $current_mnet_localhost_host, true);
339 }
340
341/// Create all_hosts_host if necessary (pretty improbable but better to be 100% in the safe side)
342/// Code stolen from mnet_environment->init
343 if (!$current_mnet_all_hosts_host) {
344 $current_mnet_all_hosts_host = new stdClass();
345 $current_mnet_all_hosts_host->wwwroot = '';
346 $current_mnet_all_hosts_host->ip_address = '';
347 $current_mnet_all_hosts_host->public_key = '';
348 $current_mnet_all_hosts_host->public_key_expires = 0;
349 $current_mnet_all_hosts_host->last_connect_time = 0;
350 $current_mnet_all_hosts_host->last_log_id = 0;
351 $current_mnet_all_hosts_host->deleted = 0;
352 $current_mnet_all_hosts_host->name = 'All Hosts';
7062a798 353 $current_mnet_all_hosts_host->applicationid = $moodleapplicationid;
02caf1e7 354 $current_mnet_all_hosts_host->id = $DB->insert_record('mnet_host', $current_mnet_all_hosts_host, true);
355 }
356
357/// Compare old_mnet_localhost_id and current_mnet_localhost_host
358
359 if ($old_mnet_localhost_id != $current_mnet_localhost_host->id) { /// Different = problems
360 /// Update $CFG->mnet_localhost_id to correct value
361 set_config('mnet_localhost_id', $current_mnet_localhost_host->id);
362
363 /// Delete $old_mnet_localhost_id if exists (users will be assigned to new one below)
364 $DB->delete_records('mnet_host', array('id' => $old_mnet_localhost_id));
365 }
366
367/// Compare old_mnet_all_hosts_id and current_mnet_all_hosts_host
368
369 if ($old_mnet_all_hosts_id != $current_mnet_all_hosts_host->id) { /// Different = problems
370 /// Update $CFG->mnet_localhost_id to correct value
371 set_config('mnet_all_hosts_id', $current_mnet_all_hosts_host->id);
372
373 /// Delete $old_mnet_all_hosts_id if exists
374 $DB->delete_records('mnet_host', array('id' => $old_mnet_all_hosts_id));
375 }
376
377/// Finally, update all the incorrect user->mnethostid to the correct CFG->mnet_localhost_id, preventing UIX dupes
378 $hosts = $DB->get_records_menu('mnet_host', null, '', 'id, id AS id2');
379 list($in_sql, $in_params) = $DB->get_in_or_equal($hosts, SQL_PARAMS_QM, null, false);
380
381 $sql = "SELECT id
ba73136e 382 FROM {user} u1
02caf1e7 383 WHERE u1.mnethostid $in_sql
384 AND NOT EXISTS (
385 SELECT 'x'
ba73136e 386 FROM {user} u2
02caf1e7 387 WHERE u2.username = u1.username
388 AND u2.mnethostid = ?)";
389
390 $params = array_merge($in_params, array($current_mnet_localhost_host->id));
391
392 if ($rs = $DB->get_recordset_sql($sql, $params)) {
393 foreach ($rs as $rec) {
394 $DB->set_field('user', 'mnethostid', $current_mnet_localhost_host->id, array('id' => $rec->id));
395 upgrade_set_timeout(60); /// Give upgrade at least 60 more seconds
396 }
397 $rs->close();
398 }
7062a798
PL
399
400 // fix up any host records that have incorrect ids
401 $DB->set_field_select('mnet_host', 'applicationid', $moodleapplicationid, 'id = ? or id = ?', array($current_mnet_localhost_host->id, $current_mnet_all_hosts_host->id));
402
02caf1e7 403}
404
7d2a0492 405/**
406 * This function is used as part of the great navigation upgrade of 20090828
407 * It is used to clean up contexts that are unique to a blocks that are about
408 * to be removed.
409 *
410 *
411 * Look at {@link blocklib.php::blocks_delete_instance()} the function from
412 * which I based this code. It is important to mention one very important fact
413 * before doing this I checked that the blocks did not override the
414 * {@link block_base::instance_delete()} method. Should this function ever
415 * be repeated check this again
117bd748 416 *
7d2a0492 417 * @link lib/db/upgrade.php
418 *
419 * @since navigation upgrade 20090828
420 * @param array $contextidarray An array of block instance context ids
61676608 421 * @return void
7d2a0492 422 */
423function upgrade_cleanup_unwanted_block_contexts($contextidarray) {
424 global $DB;
425
426 if (!is_array($contextidarray) || count($contextidarray)===0) {
427 // Ummmm no instances?
61676608 428 return;
7d2a0492 429 }
430
431 $contextidstring = join(',', $contextidarray);
432
433 $blockcontexts = $DB->get_recordset_select('context', 'contextlevel = '.CONTEXT_BLOCK.' AND id IN ('.$contextidstring.')', array(), '', 'id, contextlevel');
434 $blockcontextids = array();
435 foreach ($blockcontexts as $blockcontext) {
436 $blockcontextids[] = $blockcontext->id;
437 }
438
439 if (count($blockcontextids)===0) {
440 // None of the instances have unique contexts
61676608 441 return;
7d2a0492 442 }
443
444 $blockcontextidsstring = join(',', $blockcontextids);
445
61676608
PS
446 $DB->delete_records_select('role_assignments', 'contextid IN ('.$blockcontextidsstring.')');
447 $DB->delete_records_select('role_capabilities', 'contextid IN ('.$blockcontextidsstring.')');
448 $DB->delete_records_select('role_names', 'contextid IN ('.$blockcontextidsstring.')');
449 $DB->delete_records_select('context', 'id IN ('.$blockcontextidsstring.')');
67e4713c 450}