f303a26b3d66e62e986b4adb7f69b669417a1703
[moodle.git] / lib / db / upgrade.php
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 // GNU General Public License for more details.
13 //
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
17 /**
18  * This file keeps track of upgrades to Moodle.
19  *
20  * Sometimes, changes between versions involve
21  * alterations to database structures and other
22  * major things that may break installations.
23  *
24  * The upgrade function in this file will attempt
25  * to perform all the necessary actions to upgrade
26  * your older installation to the current version.
27  *
28  * If there's something it cannot do itself, it
29  * will tell you what you need to do.
30  *
31  * The commands in here will all be database-neutral,
32  * using the methods of database_manager class
33  *
34  * Please do not forget to use upgrade_set_timeout()
35  * before any action that may take longer time to finish.
36  *
37  * @package   core_install
38  * @category  upgrade
39  * @copyright 2006 onwards Martin Dougiamas  http://dougiamas.com
40  * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
41  */
43 defined('MOODLE_INTERNAL') || die();
45 /**
46  * Main upgrade tasks to be executed on Moodle version bump
47  *
48  * This function is automatically executed after one bump in the Moodle core
49  * version is detected. It's in charge of performing the required tasks
50  * to raise core from the previous version to the next one.
51  *
52  * It's a collection of ordered blocks of code, named "upgrade steps",
53  * each one performing one isolated (from the rest of steps) task. Usually
54  * tasks involve creating new DB objects or performing manipulation of the
55  * information for cleanup/fixup purposes.
56  *
57  * Each upgrade step has a fixed structure, that can be summarised as follows:
58  *
59  * if ($oldversion < XXXXXXXXXX.XX) {
60  *     // Explanation of the update step, linking to issue in the Tracker if necessary
61  *     upgrade_set_timeout(XX); // Optional for big tasks
62  *     // Code to execute goes here, usually the XMLDB Editor will
63  *     // help you here. See {@link http://docs.moodle.org/dev/XMLDB_editor}.
64  *     upgrade_main_savepoint(true, XXXXXXXXXX.XX);
65  * }
66  *
67  * All plugins within Moodle (modules, blocks, reports...) support the existence of
68  * their own upgrade.php file, using the "Frankenstyle" component name as
69  * defined at {@link http://docs.moodle.org/dev/Frankenstyle}, for example:
70  *     - {@link xmldb_page_upgrade($oldversion)}. (modules don't require the plugintype ("mod_") to be used.
71  *     - {@link xmldb_auth_manual_upgrade($oldversion)}.
72  *     - {@link xmldb_workshopform_accumulative_upgrade($oldversion)}.
73  *     - ....
74  *
75  * In order to keep the contents of this file reduced, it's allowed to create some helper
76  * functions to be used here in the {@link upgradelib.php} file at the same directory. Note
77  * that such a file must be manually included from upgrade.php, and there are some restrictions
78  * about what can be used within it.
79  *
80  * For more information, take a look to the documentation available:
81  *     - Data definition API: {@link http://docs.moodle.org/dev/Data_definition_API}
82  *     - Upgrade API: {@link http://docs.moodle.org/dev/Upgrade_API}
83  *
84  * @param int $oldversion
85  * @return bool always true
86  */
87 function xmldb_main_upgrade($oldversion) {
88     global $CFG, $USER, $DB, $OUTPUT;
90     require_once($CFG->libdir.'/db/upgradelib.php'); // Core Upgrade-related functions
92     $dbman = $DB->get_manager(); // loads ddl manager and xmldb classes
94     if ($oldversion < 2011120500) {
95         // just in case somebody hacks upgrade scripts or env, we really can not continue
96         echo("You need to upgrade to 2.2.x first!\n");
97         exit(1);
98         // Note this savepoint is 100% unreachable, but needed to pass the upgrade checks
99         upgrade_main_savepoint(true, 2011120500);
100     }
102     // Moodle v2.2.0 release upgrade line
103     // Put any upgrade step following this
105     if ($oldversion < 2011120500.02) {
107         upgrade_set_timeout(60*20); // This may take a while
108         // MDL-28180. Some missing restrictions in certain backup & restore operations
109         // were causing incorrect duplicates in the course_completion_aggr_methd table.
110         // This upgrade step takes rid of them.
111         $sql = 'SELECT course, criteriatype, MIN(id) AS minid
112                   FROM {course_completion_aggr_methd}
113               GROUP BY course, criteriatype
114                 HAVING COUNT(*) > 1';
115         $duprs = $DB->get_recordset_sql($sql);
116         foreach ($duprs as $duprec) {
117             // We need to handle NULLs in criteriatype diferently
118             if (is_null($duprec->criteriatype)) {
119                 $where = 'course = ? AND criteriatype IS NULL AND id > ?';
120                 $params = array($duprec->course, $duprec->minid);
121             } else {
122                 $where = 'course = ? AND criteriatype = ? AND id > ?';
123                 $params = array($duprec->course, $duprec->criteriatype, $duprec->minid);
124             }
125             $DB->delete_records_select('course_completion_aggr_methd', $where, $params);
126         }
127         $duprs->close();
129         // Main savepoint reached
130         upgrade_main_savepoint(true, 2011120500.02);
131     }
133     if ($oldversion < 2011120500.03) {
135         // Changing precision of field value on table user_preferences to (1333)
136         $table = new xmldb_table('user_preferences');
137         $field = new xmldb_field('value', XMLDB_TYPE_CHAR, '1333', null, XMLDB_NOTNULL, null, null, 'name');
139         // Launch change of precision for field value
140         $dbman->change_field_precision($table, $field);
142         // Main savepoint reached
143         upgrade_main_savepoint(true, 2011120500.03);
144     }
146     if ($oldversion < 2012020200.03) {
148         // Define index rolecontext (not unique) to be added to role_assignments
149         $table = new xmldb_table('role_assignments');
150         $index = new xmldb_index('rolecontext', XMLDB_INDEX_NOTUNIQUE, array('roleid', 'contextid'));
152         // Conditionally launch add index rolecontext
153         if (!$dbman->index_exists($table, $index)) {
154             $dbman->add_index($table, $index);
155         }
157         // Define index usercontextrole (not unique) to be added to role_assignments
158         $index = new xmldb_index('usercontextrole', XMLDB_INDEX_NOTUNIQUE, array('userid', 'contextid', 'roleid'));
160         // Conditionally launch add index usercontextrole
161         if (!$dbman->index_exists($table, $index)) {
162             $dbman->add_index($table, $index);
163         }
165         // Main savepoint reached
166         upgrade_main_savepoint(true, 2012020200.03);
167     }
169     if ($oldversion < 2012020200.06) {
170         // Previously we always allowed users to override their email address via the messaging system
171         // We have now added a setting to allow admins to turn this this ability on and off
172         // While this setting defaults to 0 (off) we're setting it to 1 (on) to maintain the behaviour for upgrading sites
173         set_config('messagingallowemailoverride', 1);
175         // Main savepoint reached
176         upgrade_main_savepoint(true, 2012020200.06);
177     }
179     if ($oldversion < 2012021700.01) {
180         // Changing precision of field uniquehash on table post to 255
181         $table = new xmldb_table('post');
182         $field = new xmldb_field('uniquehash', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, 'content');
184         // Launch change of precision for field uniquehash
185         $dbman->change_field_precision($table, $field);
187         // Main savepoint reached
188         upgrade_main_savepoint(true, 2012021700.01);
189     }
191     if ($oldversion < 2012021700.02) {
192         // Somewhere before 1.9 summary and content column in post table were not null. In 1.9+
193         // not null became false.
194         $columns = $DB->get_columns('post');
196         // Fix discrepancies in summary field after upgrade from 1.9
197         if (array_key_exists('summary', $columns) && $columns['summary']->not_null != false) {
198             $table = new xmldb_table('post');
199             $summaryfield = new xmldb_field('summary', XMLDB_TYPE_TEXT, 'big', null, null, null, null, 'subject');
201             if ($dbman->field_exists($table, $summaryfield)) {
202                 $dbman->change_field_notnull($table, $summaryfield);
203             }
205         }
207         // Fix discrepancies in content field after upgrade from 1.9
208         if (array_key_exists('content', $columns) && $columns['content']->not_null != false) {
209             $table = new xmldb_table('post');
210             $contentfield = new xmldb_field('content', XMLDB_TYPE_TEXT, 'big', null, null, null, null, 'summary');
212             if ($dbman->field_exists($table, $contentfield)) {
213                 $dbman->change_field_notnull($table, $contentfield);
214             }
216         }
218         upgrade_main_savepoint(true, 2012021700.02);
219     }
221     // The ability to backup user (private) files is out completely - MDL-29248
222     if ($oldversion < 2012030100.01) {
223         unset_config('backup_general_user_files', 'backup');
224         unset_config('backup_general_user_files_locked', 'backup');
225         unset_config('backup_auto_user_files', 'backup');
227         upgrade_main_savepoint(true, 2012030100.01);
228     }
230     if ($oldversion < 2012030100.02) {
231         // migrate all numbers to signed - it should be safe to interrupt this and continue later
232         upgrade_mysql_fix_unsigned_columns();
234         // Main savepoint reached
235         upgrade_main_savepoint(true, 2012030100.02);
236     }
238     if ($oldversion < 2012030900.01) {
239         // migrate all texts and binaries to big size - it should be safe to interrupt this and continue later
240         upgrade_mysql_fix_lob_columns();
242         // Main savepoint reached
243         upgrade_main_savepoint(true, 2012030900.01);
244     }
246     if ($oldversion < 2012031500.01) {
247         // Upgrade old course_allowed_modules data to be permission overrides.
248         if ($CFG->restrictmodulesfor === 'all') {
249             $courses = $DB->get_records_menu('course', array(), 'id', 'id, 1');
250         } else if ($CFG->restrictmodulesfor === 'requested') {
251             $courses = $DB->get_records_menu('course', array('retrictmodules' => 1), 'id', 'id, 1');
252         } else {
253             $courses = array();
254         }
256         if (!$dbman->table_exists('course_allowed_modules')) {
257             // Upgrade must already have been run on this server. This might happen,
258             // for example, during development of these changes.
259             $courses = array();
260         }
262         $modidtoname = $DB->get_records_menu('modules', array(), 'id', 'id, name');
264         $coursecount = count($courses);
265         if ($coursecount) {
266             $pbar = new progress_bar('allowedmods', 500, true);
267             $transaction = $DB->start_delegated_transaction();
268         }
270         $i = 0;
271         foreach ($courses as $courseid => $notused) {
272             $i += 1;
273             upgrade_set_timeout(60); // 1 minute per course should be fine.
275             $allowedmoduleids = $DB->get_records_menu('course_allowed_modules',
276             array('course' => $courseid), 'module', 'module, 1');
277             if (empty($allowedmoduleids)) {
278                 // This seems to be the best match for backwards compatibility,
279                 // not necessarily with the old code in course_allowed_module function,
280                 // but with the code that used to be in the coures settings form.
281                 $allowedmoduleids = explode(',', $CFG->defaultallowedmodules);
282                 $allowedmoduleids = array_combine($allowedmoduleids, $allowedmoduleids);
283             }
285             $context = context_course::instance($courseid);
287             list($roleids) = get_roles_with_cap_in_context($context, 'moodle/course:manageactivities');
288             list($managerroleids) = get_roles_with_cap_in_context($context, 'moodle/site:config');
289             foreach ($managerroleids as $roleid) {
290                 unset($roleids[$roleid]);
291             }
293             foreach ($modidtoname as $modid => $modname) {
294                 if (isset($allowedmoduleids[$modid])) {
295                     // Module is allowed, no worries.
296                     continue;
297                 }
299                 $capability = 'mod/' . $modname . ':addinstance';
300                 foreach ($roleids as $roleid) {
301                     assign_capability($capability, CAP_PREVENT, $roleid, $context);
302                 }
303             }
305             $pbar->update($i, $coursecount, "Upgrading legacy course_allowed_modules data - $i/$coursecount.");
306         }
308         if ($coursecount) {
309             $transaction->allow_commit();
310         }
312         upgrade_main_savepoint(true, 2012031500.01);
313     }
315     if ($oldversion < 2012031500.02) {
317         // Define field retrictmodules to be dropped from course
318         $table = new xmldb_table('course');
319         $field = new xmldb_field('restrictmodules');
321         // Conditionally launch drop field requested
322         if ($dbman->field_exists($table, $field)) {
323             $dbman->drop_field($table, $field);
324         }
326         upgrade_main_savepoint(true, 2012031500.02);
327     }
329     if ($oldversion < 2012031500.03) {
331         // Define table course_allowed_modules to be dropped
332         $table = new xmldb_table('course_allowed_modules');
334         // Conditionally launch drop table for course_allowed_modules
335         if ($dbman->table_exists($table)) {
336             $dbman->drop_table($table);
337         }
339         upgrade_main_savepoint(true, 2012031500.03);
340     }
342     if ($oldversion < 2012031500.04) {
343         // Clean up the old admin settings.
344         unset_config('restrictmodulesfor');
345         unset_config('restrictbydefault');
346         unset_config('defaultallowedmodules');
348         upgrade_main_savepoint(true, 2012031500.04);
349     }
351     if ($oldversion < 2012032300.02) {
352         // Migrate the old admin debug setting.
353         if ($CFG->debug == 38911) {
354             set_config('debug', DEBUG_DEVELOPER);
355         } else if ($CFG->debug == 6143) {
356             set_config('debug', DEBUG_ALL);
357         }
358         upgrade_main_savepoint(true, 2012032300.02);
359     }
361     if ($oldversion < 2012042300.00) {
362         // This change makes the course_section index unique.
364         // xmldb does not allow changing index uniqueness - instead we must drop
365         // index then add it again
366         $table = new xmldb_table('course_sections');
367         $index = new xmldb_index('course_section', XMLDB_INDEX_NOTUNIQUE, array('course', 'section'));
369         // Conditionally launch drop index course_section
370         if ($dbman->index_exists($table, $index)) {
371             $dbman->drop_index($table, $index);
372         }
374         // Look for any duplicate course_sections entries. There should not be
375         // any but on some busy systems we found a few, maybe due to previous
376         // bugs.
377         $transaction = $DB->start_delegated_transaction();
378         $rs = $DB->get_recordset_sql('
379                 SELECT DISTINCT
380                     cs.id, cs.course
381                 FROM
382                     {course_sections} cs
383                     INNER JOIN {course_sections} older
384                         ON cs.course = older.course AND cs.section = older.section
385                         AND older.id < cs.id');
386         foreach ($rs as $rec) {
387             $DB->delete_records('course_sections', array('id' => $rec->id));
388             rebuild_course_cache($rec->course, true);
389         }
390         $rs->close();
391         $transaction->allow_commit();
393         // Define index course_section (unique) to be added to course_sections
394         $index = new xmldb_index('course_section', XMLDB_INDEX_UNIQUE, array('course', 'section'));
396         // Conditionally launch add index course_section
397         if (!$dbman->index_exists($table, $index)) {
398             $dbman->add_index($table, $index);
399         }
401         // Main savepoint reached
402         upgrade_main_savepoint(true, 2012042300.00);
403     }
405     if ($oldversion < 2012042300.02) {
406         require_once($CFG->libdir . '/completion/completion_criteria.php');
407         // Delete orphaned criteria which were left when modules were removed
408         if ($DB->get_dbfamily() === 'mysql') {
409             $sql = "DELETE cc FROM {course_completion_criteria} cc
410                     LEFT JOIN {course_modules} cm ON cm.id = cc.moduleinstance
411                     WHERE cm.id IS NULL AND cc.criteriatype = ".COMPLETION_CRITERIA_TYPE_ACTIVITY;
412         } else {
413             $sql = "DELETE FROM {course_completion_criteria}
414                     WHERE NOT EXISTS (
415                         SELECT 'x' FROM {course_modules}
416                         WHERE {course_modules}.id = {course_completion_criteria}.moduleinstance)
417                     AND {course_completion_criteria}.criteriatype = ".COMPLETION_CRITERIA_TYPE_ACTIVITY;
418         }
419         $DB->execute($sql);
421         // Main savepoint reached
422         upgrade_main_savepoint(true, 2012042300.02);
423     }
425     if ($oldversion < 2012050300.01) {
426         // Make sure deleted users do not have picture flag.
427         $DB->set_field('user', 'picture', 0, array('deleted'=>1, 'picture'=>1));
428         upgrade_main_savepoint(true, 2012050300.01);
429     }
431     if ($oldversion < 2012050300.02) {
433         // Changing precision of field picture on table user to (10)
434         $table = new xmldb_table('user');
435         $field = new xmldb_field('picture', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0', 'secret');
437         // Launch change of precision for field picture
438         $dbman->change_field_precision($table, $field);
440         // Main savepoint reached
441         upgrade_main_savepoint(true, 2012050300.02);
442     }
444     if ($oldversion < 2012050300.03) {
446         // Define field coursedisplay to be added to course
447         $table = new xmldb_table('course');
448         $field = new xmldb_field('coursedisplay', XMLDB_TYPE_INTEGER, '2', null, XMLDB_NOTNULL, null, '0', 'completionnotify');
450         // Conditionally launch add field coursedisplay
451         if (!$dbman->field_exists($table, $field)) {
452             $dbman->add_field($table, $field);
453         }
455         // Main savepoint reached
456         upgrade_main_savepoint(true, 2012050300.03);
457     }
459     if ($oldversion < 2012050300.04) {
461         // Define table course_display to be dropped
462         $table = new xmldb_table('course_display');
464         // Conditionally launch drop table for course_display
465         if ($dbman->table_exists($table)) {
466             $dbman->drop_table($table);
467         }
469         // Main savepoint reached
470         upgrade_main_savepoint(true, 2012050300.04);
471     }
473     if ($oldversion < 2012050300.05) {
475         // Clean up removed admin setting.
476         unset_config('navlinkcoursesections');
478         upgrade_main_savepoint(true, 2012050300.05);
479     }
481     if ($oldversion < 2012050400.01) {
483         // Define index sortorder (not unique) to be added to course
484         $table = new xmldb_table('course');
485         $index = new xmldb_index('sortorder', XMLDB_INDEX_NOTUNIQUE, array('sortorder'));
487         // Conditionally launch add index sortorder
488         if (!$dbman->index_exists($table, $index)) {
489             $dbman->add_index($table, $index);
490         }
492         // Main savepoint reached
493         upgrade_main_savepoint(true, 2012050400.01);
494     }
496     if ($oldversion < 2012050400.02) {
498         // Clean up removed admin setting.
499         unset_config('enablecourseajax');
501         upgrade_main_savepoint(true, 2012050400.02);
502     }
504     if ($oldversion < 2012051100.01) {
506         // Define field idnumber to be added to groups
507         $table = new xmldb_table('groups');
508         $field = new xmldb_field('idnumber', XMLDB_TYPE_CHAR, '100', null, XMLDB_NOTNULL, null, null, 'courseid');
509         $index = new xmldb_index('idnumber', XMLDB_INDEX_NOTUNIQUE, array('idnumber'));
511         // Conditionally launch add field idnumber
512         if (!$dbman->field_exists($table, $field)) {
513             $dbman->add_field($table, $field);
514         }
516         // Conditionally launch add index idnumber
517         if (!$dbman->index_exists($table, $index)) {
518             $dbman->add_index($table, $index);
519         }
521         // Define field idnumber to be added to groupings
522         $table = new xmldb_table('groupings');
523         $field = new xmldb_field('idnumber', XMLDB_TYPE_CHAR, '100', null, XMLDB_NOTNULL, null, null, 'name');
524         $index = new xmldb_index('idnumber', XMLDB_INDEX_NOTUNIQUE, array('idnumber'));
526         // Conditionally launch add field idnumber
527         if (!$dbman->field_exists($table, $field)) {
528             $dbman->add_field($table, $field);
529         }
531         // Conditionally launch add index idnumber
532         if (!$dbman->index_exists($table, $index)) {
533             $dbman->add_index($table, $index);
534         }
536         // Main savepoint reached
537         upgrade_main_savepoint(true, 2012051100.01);
538     }
540     if ($oldversion < 2012051100.03) {
542         // Amend course table to add sectioncache cache
543         $table = new xmldb_table('course');
544         $field = new xmldb_field('sectioncache', XMLDB_TYPE_TEXT, null, null, null, null, null, 'showgrades');
545         if (!$dbman->field_exists($table, $field)) {
546             $dbman->add_field($table, $field);
547         }
549         // Amend course_sections to add date, time and groupingid availability
550         // conditions and a setting about whether to show them
551         $table = new xmldb_table('course_sections');
552         $field = new xmldb_field('availablefrom', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0', 'visible');
553         if (!$dbman->field_exists($table, $field)) {
554             $dbman->add_field($table, $field);
555         }
556         $field = new xmldb_field('availableuntil', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0', 'availablefrom');
557         if (!$dbman->field_exists($table, $field)) {
558             $dbman->add_field($table, $field);
559         }
560         $field = new xmldb_field('showavailability', XMLDB_TYPE_INTEGER, '1', null, XMLDB_NOTNULL, null, '0', 'availableuntil');
561         // Conditionally launch add field showavailability
562         if (!$dbman->field_exists($table, $field)) {
563             $dbman->add_field($table, $field);
564         }
565         $field = new xmldb_field('groupingid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0', 'showavailability');
566         // Conditionally launch add field groupingid
567         if (!$dbman->field_exists($table, $field)) {
568             $dbman->add_field($table, $field);
569         }
571         // Add course_sections_availability to add completion & grade availability conditions
572         $table = new xmldb_table('course_sections_availability');
574         $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
575         $table->add_field('coursesectionid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null);
576         $table->add_field('sourcecmid', XMLDB_TYPE_INTEGER, '10', null, null, null, null);
577         $table->add_field('requiredcompletion', XMLDB_TYPE_INTEGER, '1', null, null, null, null);
578         $table->add_field('gradeitemid', XMLDB_TYPE_INTEGER, '10', null, null, null, null);
579         $table->add_field('grademin', XMLDB_TYPE_NUMBER, '10, 5', null, null, null, null);
580         $table->add_field('grademax', XMLDB_TYPE_NUMBER, '10, 5', null, null, null, null);
582         $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
583         $table->add_key('coursesectionid', XMLDB_KEY_FOREIGN, array('coursesectionid'), 'course_sections', array('id'));
584         $table->add_key('sourcecmid', XMLDB_KEY_FOREIGN, array('sourcecmid'), 'course_modules', array('id'));
585         $table->add_key('gradeitemid', XMLDB_KEY_FOREIGN, array('gradeitemid'), 'grade_items', array('id'));
587         if (!$dbman->table_exists($table)) {
588             $dbman->create_table($table);
589         }
591         // Main savepoint reached
592         upgrade_main_savepoint(true, 2012051100.03);
593     }
595     if ($oldversion < 2012052100.00) {
597         // Define field referencefileid to be added to files.
598         $table = new xmldb_table('files');
600         // Define field referencefileid to be added to files.
601         $field = new xmldb_field('referencefileid', XMLDB_TYPE_INTEGER, '10', null, null, null, null, 'sortorder');
603         // Conditionally launch add field referencefileid.
604         if (!$dbman->field_exists($table, $field)) {
605             $dbman->add_field($table, $field);
606         }
608         // Define field referencelastsync to be added to files.
609         $field = new xmldb_field('referencelastsync', XMLDB_TYPE_INTEGER, '10', null, null, null, null, 'referencefileid');
611         // Conditionally launch add field referencelastsync.
612         if (!$dbman->field_exists($table, $field)) {
613             $dbman->add_field($table, $field);
614         }
616         // Define field referencelifetime to be added to files.
617         $field = new xmldb_field('referencelifetime', XMLDB_TYPE_INTEGER, '10', null, null, null, null, 'referencelastsync');
619         // Conditionally launch add field referencelifetime.
620         if (!$dbman->field_exists($table, $field)) {
621             $dbman->add_field($table, $field);
622         }
624         $key = new xmldb_key('referencefileid', XMLDB_KEY_FOREIGN, array('referencefileid'), 'files_reference', array('id'));
625         // Launch add key referencefileid
626         $dbman->add_key($table, $key);
628         // Define table files_reference to be created.
629         $table = new xmldb_table('files_reference');
631         // Adding fields to table files_reference.
632         $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
633         $table->add_field('repositoryid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null);
634         $table->add_field('lastsync', XMLDB_TYPE_INTEGER, '10', null, null, null, null);
635         $table->add_field('lifetime', XMLDB_TYPE_INTEGER, '10', null, null, null, null);
636         $table->add_field('reference', XMLDB_TYPE_TEXT, null, null, null, null, null);
638         // Adding keys to table files_reference.
639         $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
640         $table->add_key('repositoryid', XMLDB_KEY_FOREIGN, array('repositoryid'), 'repository_instances', array('id'));
642         // Conditionally launch create table for files_reference
643         if (!$dbman->table_exists($table)) {
644             $dbman->create_table($table);
645         }
647         // Main savepoint reached
648         upgrade_main_savepoint(true, 2012052100.00);
649     }
651     if ($oldversion < 2012052500.03) { // fix invalid course_completion_records MDL-27368
652         //first get all instances of duplicate records
653         $sql = 'SELECT userid, course FROM {course_completions} WHERE (deleted IS NULL OR deleted <> 1) GROUP BY userid, course HAVING (count(id) > 1)';
654         $duplicates = $DB->get_recordset_sql($sql, array());
656         foreach ($duplicates as $duplicate) {
657             $pointer = 0;
658             //now get all the records for this user/course
659             $sql = 'userid = ? AND course = ? AND (deleted IS NULL OR deleted <> 1)';
660             $completions = $DB->get_records_select('course_completions', $sql,
661                 array($duplicate->userid, $duplicate->course), 'timecompleted DESC, timestarted DESC');
662             $needsupdate = false;
663             $origcompletion = null;
664             foreach ($completions as $completion) {
665                 $pointer++;
666                 if ($pointer === 1) { //keep 1st record but delete all others.
667                     $origcompletion = $completion;
668                 } else {
669                     //we need to keep the "oldest" of all these fields as the valid completion record.
670                     $fieldstocheck = array('timecompleted', 'timestarted', 'timeenrolled');
671                     foreach ($fieldstocheck as $f) {
672                         if ($origcompletion->$f > $completion->$f) {
673                             $origcompletion->$f = $completion->$f;
674                             $needsupdate = true;
675                         }
676                     }
677                     $DB->delete_records('course_completions', array('id'=>$completion->id));
678                 }
679             }
680             if ($needsupdate) {
681                 $DB->update_record('course_completions', $origcompletion);
682             }
683         }
685         // Main savepoint reached
686         upgrade_main_savepoint(true, 2012052500.03);
687     }
689     if ($oldversion < 2012052900.00) {
690         // Clean up all duplicate records in the course_completions table in preparation
691         // for adding a new index there.
692         upgrade_course_completion_remove_duplicates(
693             'course_completions',
694             array('userid', 'course'),
695             array('timecompleted', 'timestarted', 'timeenrolled')
696         );
698         // Main savepoint reached
699         upgrade_main_savepoint(true, 2012052900.00);
700     }
702     if ($oldversion < 2012052900.01) {
703         // Add indexes to prevent new duplicates in the course_completions table.
704         // Define index useridcourse (unique) to be added to course_completions
705         $table = new xmldb_table('course_completions');
706         $index = new xmldb_index('useridcourse', XMLDB_INDEX_UNIQUE, array('userid', 'course'));
708         // Conditionally launch add index useridcourse
709         if (!$dbman->index_exists($table, $index)) {
710             $dbman->add_index($table, $index);
711         }
713         // Main savepoint reached
714         upgrade_main_savepoint(true, 2012052900.01);
715     }
717     if ($oldversion < 2012052900.02) {
718         // Clean up all duplicate records in the course_completion_crit_compl table in preparation
719         // for adding a new index there.
720         upgrade_course_completion_remove_duplicates(
721             'course_completion_crit_compl',
722             array('userid', 'course', 'criteriaid'),
723             array('timecompleted')
724         );
726         // Main savepoint reached
727         upgrade_main_savepoint(true, 2012052900.02);
728     }
730     if ($oldversion < 2012052900.03) {
731         // Add indexes to prevent new duplicates in the course_completion_crit_compl table.
732         // Define index useridcoursecriteraid (unique) to be added to course_completion_crit_compl
733         $table = new xmldb_table('course_completion_crit_compl');
734         $index = new xmldb_index('useridcoursecriteraid', XMLDB_INDEX_UNIQUE, array('userid', 'course', 'criteriaid'));
736         // Conditionally launch add index useridcoursecriteraid
737         if (!$dbman->index_exists($table, $index)) {
738             $dbman->add_index($table, $index);
739         }
741         // Main savepoint reached
742         upgrade_main_savepoint(true, 2012052900.03);
743     }
745     if ($oldversion < 2012052900.04) {
746         // Clean up all duplicate records in the course_completion_aggr_methd table in preparation
747         // for adding a new index there.
748         upgrade_course_completion_remove_duplicates(
749             'course_completion_aggr_methd',
750             array('course', 'criteriatype')
751         );
753         // Main savepoint reached
754         upgrade_main_savepoint(true, 2012052900.04);
755     }
757     if ($oldversion < 2012052900.05) {
758         // Add indexes to prevent new duplicates in the course_completion_aggr_methd table.
759         // Define index coursecriteratype (unique) to be added to course_completion_aggr_methd
760         $table = new xmldb_table('course_completion_aggr_methd');
761         $index = new xmldb_index('coursecriteriatype', XMLDB_INDEX_UNIQUE, array('course', 'criteriatype'));
763         // Conditionally launch add index coursecriteratype
764         if (!$dbman->index_exists($table, $index)) {
765             $dbman->add_index($table, $index);
766         }
768         // Main savepoint reached
769         upgrade_main_savepoint(true, 2012052900.05);
770     }
772     if ($oldversion < 2012060600.01) {
773         // Add field referencehash to files_reference
774         $table = new xmldb_table('files_reference');
775         $field = new xmldb_field('referencehash', XMLDB_TYPE_CHAR, '40', null, XMLDB_NOTNULL, null, null, 'reference');
776         if (!$dbman->field_exists($table, $field)) {
777             $dbman->add_field($table, $field);
778         }
779         upgrade_main_savepoint(true, 2012060600.01);
780     }
782     if ($oldversion < 2012060600.02) {
783         // Populate referencehash field with SHA1 hash of the reference - this shoudl affect only 2.3dev sites
784         // that were using the feature for testing. Production sites have the table empty.
785         $rs = $DB->get_recordset('files_reference', null, '', 'id, reference');
786         foreach ($rs as $record) {
787             $hash = sha1($record->reference);
788             $DB->set_field('files_reference', 'referencehash', $hash, array('id' => $record->id));
789         }
790         $rs->close();
792         upgrade_main_savepoint(true, 2012060600.02);
793     }
795     if ($oldversion < 2012060600.03) {
796         // Merge duplicate records in files_reference that were created during the development
797         // phase at 2.3dev sites. This is needed so we can create the unique index over
798         // (repositoryid, referencehash) fields.
799         $sql = "SELECT repositoryid, referencehash, MIN(id) AS minid
800                   FROM {files_reference}
801               GROUP BY repositoryid, referencehash
802                 HAVING COUNT(*) > 1;";
803         $duprs = $DB->get_recordset_sql($sql);
804         foreach ($duprs as $duprec) {
805             // get the list of all ids in {files_reference} that need to be remapped
806             $dupids = $DB->get_records_select('files_reference', "repositoryid = ? AND referencehash = ? AND id > ?",
807                 array($duprec->repositoryid, $duprec->referencehash, $duprec->minid), '', 'id');
808             $dupids = array_keys($dupids);
809             // relink records in {files} that are now referring to a duplicate record
810             // in {files_reference} to refer to the first one
811             list($subsql, $subparams) = $DB->get_in_or_equal($dupids);
812             $DB->set_field_select('files', 'referencefileid', $duprec->minid, "referencefileid $subsql", $subparams);
813             // and finally remove all orphaned records from {files_reference}
814             $DB->delete_records_list('files_reference', 'id', $dupids);
815         }
816         $duprs->close();
818         upgrade_main_savepoint(true, 2012060600.03);
819     }
821     if ($oldversion < 2012060600.04) {
822         // Add a unique index over repositoryid and referencehash fields in files_reference table
823         $table = new xmldb_table('files_reference');
824         $index = new xmldb_index('uq_external_file', XMLDB_INDEX_UNIQUE, array('repositoryid', 'referencehash'));
826         if (!$dbman->index_exists($table, $index)) {
827             $dbman->add_index($table, $index);
828         }
830         upgrade_main_savepoint(true, 2012060600.04);
831     }
833     return true;