Merge branch 'MDL-41756-master' of https://github.com/jamiepratt/moodle
[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, $SITE, $COURSE;
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 < 2012030900.01) {
231         // Migrate all numbers to signed & all texts and binaries to big size.
232         // It should be safe to interrupt this and continue later.
233         upgrade_mysql_fix_unsigned_and_lob_columns();
235         // Main savepoint reached
236         upgrade_main_savepoint(true, 2012030900.01);
237     }
239     if ($oldversion < 2012031500.01) {
240         // Upgrade old course_allowed_modules data to be permission overrides.
241         if ($CFG->restrictmodulesfor === 'all') {
242             $courses = $DB->get_records_menu('course', array(), 'id', 'id, 1');
243         } else if ($CFG->restrictmodulesfor === 'requested') {
244             $courses = $DB->get_records_menu('course', array('restrictmodules' => 1), 'id', 'id, 1');
245         } else {
246             $courses = array();
247         }
249         if (!$dbman->table_exists('course_allowed_modules')) {
250             // Upgrade must already have been run on this server. This might happen,
251             // for example, during development of these changes.
252             $courses = array();
253         }
255         $modidtoname = $DB->get_records_menu('modules', array(), 'id', 'id, name');
257         $coursecount = count($courses);
258         if ($coursecount) {
259             $pbar = new progress_bar('allowedmods', 500, true);
260             $transaction = $DB->start_delegated_transaction();
261         }
263         $i = 0;
264         foreach ($courses as $courseid => $notused) {
265             $i += 1;
266             upgrade_set_timeout(60); // 1 minute per course should be fine.
268             $allowedmoduleids = $DB->get_records_menu('course_allowed_modules',
269             array('course' => $courseid), 'module', 'module, 1');
270             if (empty($allowedmoduleids)) {
271                 // This seems to be the best match for backwards compatibility,
272                 // not necessarily with the old code in course_allowed_module function,
273                 // but with the code that used to be in the coures settings form.
274                 $allowedmoduleids = explode(',', $CFG->defaultallowedmodules);
275                 $allowedmoduleids = array_combine($allowedmoduleids, $allowedmoduleids);
276             }
278             $context = context_course::instance($courseid);
280             list($roleids) = get_roles_with_cap_in_context($context, 'moodle/course:manageactivities');
281             list($managerroleids) = get_roles_with_cap_in_context($context, 'moodle/site:config');
282             foreach ($managerroleids as $roleid) {
283                 unset($roleids[$roleid]);
284             }
286             foreach ($modidtoname as $modid => $modname) {
287                 if (isset($allowedmoduleids[$modid])) {
288                     // Module is allowed, no worries.
289                     continue;
290                 }
292                 $capability = 'mod/' . $modname . ':addinstance';
293                 foreach ($roleids as $roleid) {
294                     assign_capability($capability, CAP_PREVENT, $roleid, $context);
295                 }
296             }
298             $pbar->update($i, $coursecount, "Upgrading legacy course_allowed_modules data - $i/$coursecount.");
299         }
301         if ($coursecount) {
302             $transaction->allow_commit();
303         }
305         upgrade_main_savepoint(true, 2012031500.01);
306     }
308     if ($oldversion < 2012031500.02) {
310         // Define field restrictmodules to be dropped from course
311         $table = new xmldb_table('course');
312         $field = new xmldb_field('restrictmodules');
314         // Conditionally launch drop field requested
315         if ($dbman->field_exists($table, $field)) {
316             $dbman->drop_field($table, $field);
317         }
319         // Since structure of 'course' table has changed we need to re-read $SITE from DB.
320         $SITE = $DB->get_record('course', array('id' => $SITE->id));
321         $COURSE = clone($SITE);
323         upgrade_main_savepoint(true, 2012031500.02);
324     }
326     if ($oldversion < 2012031500.03) {
328         // Define table course_allowed_modules to be dropped
329         $table = new xmldb_table('course_allowed_modules');
331         // Conditionally launch drop table for course_allowed_modules
332         if ($dbman->table_exists($table)) {
333             $dbman->drop_table($table);
334         }
336         upgrade_main_savepoint(true, 2012031500.03);
337     }
339     if ($oldversion < 2012031500.04) {
340         // Clean up the old admin settings.
341         unset_config('restrictmodulesfor');
342         unset_config('restrictbydefault');
343         unset_config('defaultallowedmodules');
345         upgrade_main_savepoint(true, 2012031500.04);
346     }
348     if ($oldversion < 2012032300.02) {
349         // Migrate the old admin debug setting.
350         if ($CFG->debug == 38911) {
351             set_config('debug', DEBUG_DEVELOPER);
352         } else if ($CFG->debug == 6143) {
353             set_config('debug', DEBUG_ALL);
354         }
355         upgrade_main_savepoint(true, 2012032300.02);
356     }
358     if ($oldversion < 2012042300.00) {
359         // This change makes the course_section index unique.
361         // xmldb does not allow changing index uniqueness - instead we must drop
362         // index then add it again
363         $table = new xmldb_table('course_sections');
364         $index = new xmldb_index('course_section', XMLDB_INDEX_NOTUNIQUE, array('course', 'section'));
366         // Conditionally launch drop index course_section
367         if ($dbman->index_exists($table, $index)) {
368             $dbman->drop_index($table, $index);
369         }
371         // Look for any duplicate course_sections entries. There should not be
372         // any but on some busy systems we found a few, maybe due to previous
373         // bugs.
374         $transaction = $DB->start_delegated_transaction();
375         $rs = $DB->get_recordset_sql('
376                 SELECT DISTINCT
377                     cs.id, cs.course
378                 FROM
379                     {course_sections} cs
380                     INNER JOIN {course_sections} older
381                         ON cs.course = older.course AND cs.section = older.section
382                         AND older.id < cs.id');
383         foreach ($rs as $rec) {
384             $DB->delete_records('course_sections', array('id' => $rec->id));
385             // We can't use rebuild_course_cache() here because introducing sectioncache later
386             // so reset modinfo manually.
387             $DB->set_field('course', 'modinfo', null, array('id' => $rec->course));
388         }
389         $rs->close();
390         $transaction->allow_commit();
392         // Define index course_section (unique) to be added to course_sections
393         $index = new xmldb_index('course_section', XMLDB_INDEX_UNIQUE, array('course', 'section'));
395         // Conditionally launch add index course_section
396         if (!$dbman->index_exists($table, $index)) {
397             $dbman->add_index($table, $index);
398         }
400         // Main savepoint reached
401         upgrade_main_savepoint(true, 2012042300.00);
402     }
404     if ($oldversion < 2012042300.02) {
405         require_once($CFG->dirroot.'/completion/criteria/completion_criteria.php');
406         // Delete orphaned criteria which were left when modules were removed
407         if ($DB->get_dbfamily() === 'mysql') {
408             $sql = "DELETE cc FROM {course_completion_criteria} cc
409                     LEFT JOIN {course_modules} cm ON cm.id = cc.moduleinstance
410                     WHERE cm.id IS NULL AND cc.criteriatype = ".COMPLETION_CRITERIA_TYPE_ACTIVITY;
411         } else {
412             $sql = "DELETE FROM {course_completion_criteria}
413                     WHERE NOT EXISTS (
414                         SELECT 'x' FROM {course_modules}
415                         WHERE {course_modules}.id = {course_completion_criteria}.moduleinstance)
416                     AND {course_completion_criteria}.criteriatype = ".COMPLETION_CRITERIA_TYPE_ACTIVITY;
417         }
418         $DB->execute($sql);
420         // Main savepoint reached
421         upgrade_main_savepoint(true, 2012042300.02);
422     }
424     if ($oldversion < 2012050300.01) {
425         // Make sure deleted users do not have picture flag.
426         $DB->set_field('user', 'picture', 0, array('deleted'=>1, 'picture'=>1));
427         upgrade_main_savepoint(true, 2012050300.01);
428     }
430     if ($oldversion < 2012050300.02) {
432         // Changing precision of field picture on table user to (10)
433         $table = new xmldb_table('user');
434         $field = new xmldb_field('picture', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0', 'secret');
436         // Launch change of precision for field picture
437         $dbman->change_field_precision($table, $field);
439         // Main savepoint reached
440         upgrade_main_savepoint(true, 2012050300.02);
441     }
443     if ($oldversion < 2012050300.03) {
445         // Define field coursedisplay to be added to course
446         $table = new xmldb_table('course');
447         $field = new xmldb_field('coursedisplay', XMLDB_TYPE_INTEGER, '2', null, XMLDB_NOTNULL, null, '0', 'completionnotify');
449         // Conditionally launch add field coursedisplay
450         if (!$dbman->field_exists($table, $field)) {
451             $dbman->add_field($table, $field);
452         }
454         // Since structure of 'course' table has changed we need to re-read $SITE from DB.
455         $SITE = $DB->get_record('course', array('id' => $SITE->id));
456         $COURSE = clone($SITE);
458         // Main savepoint reached
459         upgrade_main_savepoint(true, 2012050300.03);
460     }
462     if ($oldversion < 2012050300.04) {
464         // Define table course_display to be dropped
465         $table = new xmldb_table('course_display');
467         // Conditionally launch drop table for course_display
468         if ($dbman->table_exists($table)) {
469             $dbman->drop_table($table);
470         }
472         // Main savepoint reached
473         upgrade_main_savepoint(true, 2012050300.04);
474     }
476     if ($oldversion < 2012050300.05) {
478         // Clean up removed admin setting.
479         unset_config('navlinkcoursesections');
481         upgrade_main_savepoint(true, 2012050300.05);
482     }
484     if ($oldversion < 2012050400.01) {
486         // Define index sortorder (not unique) to be added to course
487         $table = new xmldb_table('course');
488         $index = new xmldb_index('sortorder', XMLDB_INDEX_NOTUNIQUE, array('sortorder'));
490         // Conditionally launch add index sortorder
491         if (!$dbman->index_exists($table, $index)) {
492             $dbman->add_index($table, $index);
493         }
495         // Main savepoint reached
496         upgrade_main_savepoint(true, 2012050400.01);
497     }
499     if ($oldversion < 2012050400.02) {
501         // Clean up removed admin setting.
502         unset_config('enablecourseajax');
504         upgrade_main_savepoint(true, 2012050400.02);
505     }
507     if ($oldversion < 2012051100.01) {
509         // Define field idnumber to be added to groups
510         $table = new xmldb_table('groups');
511         $field = new xmldb_field('idnumber', XMLDB_TYPE_CHAR, '100', null, XMLDB_NOTNULL, null, null, 'courseid');
512         $index = new xmldb_index('idnumber', XMLDB_INDEX_NOTUNIQUE, array('idnumber'));
514         // Conditionally launch add field idnumber
515         if (!$dbman->field_exists($table, $field)) {
516             $dbman->add_field($table, $field);
517         }
519         // Conditionally launch add index idnumber
520         if (!$dbman->index_exists($table, $index)) {
521             $dbman->add_index($table, $index);
522         }
524         // Define field idnumber to be added to groupings
525         $table = new xmldb_table('groupings');
526         $field = new xmldb_field('idnumber', XMLDB_TYPE_CHAR, '100', null, XMLDB_NOTNULL, null, null, 'name');
527         $index = new xmldb_index('idnumber', XMLDB_INDEX_NOTUNIQUE, array('idnumber'));
529         // Conditionally launch add field idnumber
530         if (!$dbman->field_exists($table, $field)) {
531             $dbman->add_field($table, $field);
532         }
534         // Conditionally launch add index idnumber
535         if (!$dbman->index_exists($table, $index)) {
536             $dbman->add_index($table, $index);
537         }
539         // Main savepoint reached
540         upgrade_main_savepoint(true, 2012051100.01);
541     }
543     if ($oldversion < 2012051100.03) {
545         // Amend course table to add sectioncache cache
546         $table = new xmldb_table('course');
547         $field = new xmldb_field('sectioncache', XMLDB_TYPE_TEXT, null, null, null, null, null, 'showgrades');
548         if (!$dbman->field_exists($table, $field)) {
549             $dbman->add_field($table, $field);
550         }
552         // Amend course_sections to add date, time and groupingid availability
553         // conditions and a setting about whether to show them
554         $table = new xmldb_table('course_sections');
555         $field = new xmldb_field('availablefrom', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0', 'visible');
556         if (!$dbman->field_exists($table, $field)) {
557             $dbman->add_field($table, $field);
558         }
559         $field = new xmldb_field('availableuntil', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0', 'availablefrom');
560         if (!$dbman->field_exists($table, $field)) {
561             $dbman->add_field($table, $field);
562         }
563         $field = new xmldb_field('showavailability', XMLDB_TYPE_INTEGER, '1', null, XMLDB_NOTNULL, null, '0', 'availableuntil');
564         // Conditionally launch add field showavailability
565         if (!$dbman->field_exists($table, $field)) {
566             $dbman->add_field($table, $field);
567         }
568         $field = new xmldb_field('groupingid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0', 'showavailability');
569         // Conditionally launch add field groupingid
570         if (!$dbman->field_exists($table, $field)) {
571             $dbman->add_field($table, $field);
572         }
574         // Since structure of 'course' table has changed we need to re-read $SITE from DB.
575         $SITE = $DB->get_record('course', array('id' => $SITE->id));
576         $COURSE = clone($SITE);
578         // Add course_sections_availability to add completion & grade availability conditions
579         $table = new xmldb_table('course_sections_availability');
581         $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
582         $table->add_field('coursesectionid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null);
583         $table->add_field('sourcecmid', XMLDB_TYPE_INTEGER, '10', null, null, null, null);
584         $table->add_field('requiredcompletion', XMLDB_TYPE_INTEGER, '1', null, null, null, null);
585         $table->add_field('gradeitemid', XMLDB_TYPE_INTEGER, '10', null, null, null, null);
586         $table->add_field('grademin', XMLDB_TYPE_NUMBER, '10, 5', null, null, null, null);
587         $table->add_field('grademax', XMLDB_TYPE_NUMBER, '10, 5', null, null, null, null);
589         $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
590         $table->add_key('coursesectionid', XMLDB_KEY_FOREIGN, array('coursesectionid'), 'course_sections', array('id'));
591         $table->add_key('sourcecmid', XMLDB_KEY_FOREIGN, array('sourcecmid'), 'course_modules', array('id'));
592         $table->add_key('gradeitemid', XMLDB_KEY_FOREIGN, array('gradeitemid'), 'grade_items', array('id'));
594         if (!$dbman->table_exists($table)) {
595             $dbman->create_table($table);
596         }
598         // Main savepoint reached
599         upgrade_main_savepoint(true, 2012051100.03);
600     }
602     if ($oldversion < 2012052100.00) {
604         // Define field referencefileid to be added to files.
605         $table = new xmldb_table('files');
607         // Define field referencefileid to be added to files.
608         $field = new xmldb_field('referencefileid', XMLDB_TYPE_INTEGER, '10', null, null, null, null, 'sortorder');
610         // Conditionally launch add field referencefileid.
611         if (!$dbman->field_exists($table, $field)) {
612             $dbman->add_field($table, $field);
613         }
615         // Define field referencelastsync to be added to files.
616         $field = new xmldb_field('referencelastsync', XMLDB_TYPE_INTEGER, '10', null, null, null, null, 'referencefileid');
618         // Conditionally launch add field referencelastsync.
619         if (!$dbman->field_exists($table, $field)) {
620             $dbman->add_field($table, $field);
621         }
623         // Define field referencelifetime to be added to files.
624         $field = new xmldb_field('referencelifetime', XMLDB_TYPE_INTEGER, '10', null, null, null, null, 'referencelastsync');
626         // Conditionally launch add field referencelifetime.
627         if (!$dbman->field_exists($table, $field)) {
628             $dbman->add_field($table, $field);
629         }
631         $key = new xmldb_key('referencefileid', XMLDB_KEY_FOREIGN, array('referencefileid'), 'files_reference', array('id'));
632         // Launch add key referencefileid
633         $dbman->add_key($table, $key);
635         // Define table files_reference to be created.
636         $table = new xmldb_table('files_reference');
638         // Adding fields to table files_reference.
639         $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
640         $table->add_field('repositoryid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null);
641         $table->add_field('lastsync', XMLDB_TYPE_INTEGER, '10', null, null, null, null);
642         $table->add_field('lifetime', XMLDB_TYPE_INTEGER, '10', null, null, null, null);
643         $table->add_field('reference', XMLDB_TYPE_TEXT, null, null, null, null, null);
645         // Adding keys to table files_reference.
646         $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
647         $table->add_key('repositoryid', XMLDB_KEY_FOREIGN, array('repositoryid'), 'repository_instances', array('id'));
649         // Conditionally launch create table for files_reference
650         if (!$dbman->table_exists($table)) {
651             $dbman->create_table($table);
652         }
654         // Main savepoint reached
655         upgrade_main_savepoint(true, 2012052100.00);
656     }
658     if ($oldversion < 2012052500.03) { // fix invalid course_completion_records MDL-27368
659         //first get all instances of duplicate records
660         $sql = 'SELECT userid, course FROM {course_completions} WHERE (deleted IS NULL OR deleted <> 1) GROUP BY userid, course HAVING (count(id) > 1)';
661         $duplicates = $DB->get_recordset_sql($sql, array());
663         foreach ($duplicates as $duplicate) {
664             $pointer = 0;
665             //now get all the records for this user/course
666             $sql = 'userid = ? AND course = ? AND (deleted IS NULL OR deleted <> 1)';
667             $completions = $DB->get_records_select('course_completions', $sql,
668                 array($duplicate->userid, $duplicate->course), 'timecompleted DESC, timestarted DESC');
669             $needsupdate = false;
670             $origcompletion = null;
671             foreach ($completions as $completion) {
672                 $pointer++;
673                 if ($pointer === 1) { //keep 1st record but delete all others.
674                     $origcompletion = $completion;
675                 } else {
676                     //we need to keep the "oldest" of all these fields as the valid completion record.
677                     $fieldstocheck = array('timecompleted', 'timestarted', 'timeenrolled');
678                     foreach ($fieldstocheck as $f) {
679                         if ($origcompletion->$f > $completion->$f) {
680                             $origcompletion->$f = $completion->$f;
681                             $needsupdate = true;
682                         }
683                     }
684                     $DB->delete_records('course_completions', array('id'=>$completion->id));
685                 }
686             }
687             if ($needsupdate) {
688                 $DB->update_record('course_completions', $origcompletion);
689             }
690         }
692         // Main savepoint reached
693         upgrade_main_savepoint(true, 2012052500.03);
694     }
696     if ($oldversion < 2012052900.00) {
697         // Clean up all duplicate records in the course_completions table in preparation
698         // for adding a new index there.
699         upgrade_course_completion_remove_duplicates(
700             'course_completions',
701             array('userid', 'course'),
702             array('timecompleted', 'timestarted', 'timeenrolled')
703         );
705         // Main savepoint reached
706         upgrade_main_savepoint(true, 2012052900.00);
707     }
709     if ($oldversion < 2012052900.01) {
710         // Add indexes to prevent new duplicates in the course_completions table.
711         // Define index useridcourse (unique) to be added to course_completions
712         $table = new xmldb_table('course_completions');
713         $index = new xmldb_index('useridcourse', XMLDB_INDEX_UNIQUE, array('userid', 'course'));
715         // Conditionally launch add index useridcourse
716         if (!$dbman->index_exists($table, $index)) {
717             $dbman->add_index($table, $index);
718         }
720         // Main savepoint reached
721         upgrade_main_savepoint(true, 2012052900.01);
722     }
724     if ($oldversion < 2012052900.02) {
725         // Clean up all duplicate records in the course_completion_crit_compl table in preparation
726         // for adding a new index there.
727         upgrade_course_completion_remove_duplicates(
728             'course_completion_crit_compl',
729             array('userid', 'course', 'criteriaid'),
730             array('timecompleted')
731         );
733         // Main savepoint reached
734         upgrade_main_savepoint(true, 2012052900.02);
735     }
737     if ($oldversion < 2012052900.03) {
738         // Add indexes to prevent new duplicates in the course_completion_crit_compl table.
739         // Define index useridcoursecriteraid (unique) to be added to course_completion_crit_compl
740         $table = new xmldb_table('course_completion_crit_compl');
741         $index = new xmldb_index('useridcoursecriteraid', XMLDB_INDEX_UNIQUE, array('userid', 'course', 'criteriaid'));
743         // Conditionally launch add index useridcoursecriteraid
744         if (!$dbman->index_exists($table, $index)) {
745             $dbman->add_index($table, $index);
746         }
748         // Main savepoint reached
749         upgrade_main_savepoint(true, 2012052900.03);
750     }
752     if ($oldversion < 2012052900.04) {
753         // Clean up all duplicate records in the course_completion_aggr_methd table in preparation
754         // for adding a new index there.
755         upgrade_course_completion_remove_duplicates(
756             'course_completion_aggr_methd',
757             array('course', 'criteriatype')
758         );
760         // Main savepoint reached
761         upgrade_main_savepoint(true, 2012052900.04);
762     }
764     if ($oldversion < 2012052900.05) {
765         // Add indexes to prevent new duplicates in the course_completion_aggr_methd table.
766         // Define index coursecriteratype (unique) to be added to course_completion_aggr_methd
767         $table = new xmldb_table('course_completion_aggr_methd');
768         $index = new xmldb_index('coursecriteriatype', XMLDB_INDEX_UNIQUE, array('course', 'criteriatype'));
770         // Conditionally launch add index coursecriteratype
771         if (!$dbman->index_exists($table, $index)) {
772             $dbman->add_index($table, $index);
773         }
775         // Main savepoint reached
776         upgrade_main_savepoint(true, 2012052900.05);
777     }
779     if ($oldversion < 2012060600.01) {
780         // Add field referencehash to files_reference
781         $table = new xmldb_table('files_reference');
782         $field = new xmldb_field('referencehash', XMLDB_TYPE_CHAR, '40', null, XMLDB_NOTNULL, null, null, 'reference');
783         if (!$dbman->field_exists($table, $field)) {
784             $dbman->add_field($table, $field);
785         }
786         upgrade_main_savepoint(true, 2012060600.01);
787     }
789     if ($oldversion < 2012060600.02) {
790         // Populate referencehash field with SHA1 hash of the reference - this shoudl affect only 2.3dev sites
791         // that were using the feature for testing. Production sites have the table empty.
792         $rs = $DB->get_recordset('files_reference', null, '', 'id, reference');
793         foreach ($rs as $record) {
794             $hash = sha1($record->reference);
795             $DB->set_field('files_reference', 'referencehash', $hash, array('id' => $record->id));
796         }
797         $rs->close();
799         upgrade_main_savepoint(true, 2012060600.02);
800     }
802     if ($oldversion < 2012060600.03) {
803         // Merge duplicate records in files_reference that were created during the development
804         // phase at 2.3dev sites. This is needed so we can create the unique index over
805         // (repositoryid, referencehash) fields.
806         $sql = "SELECT repositoryid, referencehash, MIN(id) AS minid
807                   FROM {files_reference}
808               GROUP BY repositoryid, referencehash
809                 HAVING COUNT(*) > 1";
810         $duprs = $DB->get_recordset_sql($sql);
811         foreach ($duprs as $duprec) {
812             // get the list of all ids in {files_reference} that need to be remapped
813             $dupids = $DB->get_records_select('files_reference', "repositoryid = ? AND referencehash = ? AND id > ?",
814                 array($duprec->repositoryid, $duprec->referencehash, $duprec->minid), '', 'id');
815             $dupids = array_keys($dupids);
816             // relink records in {files} that are now referring to a duplicate record
817             // in {files_reference} to refer to the first one
818             list($subsql, $subparams) = $DB->get_in_or_equal($dupids);
819             $DB->set_field_select('files', 'referencefileid', $duprec->minid, "referencefileid $subsql", $subparams);
820             // and finally remove all orphaned records from {files_reference}
821             $DB->delete_records_list('files_reference', 'id', $dupids);
822         }
823         $duprs->close();
825         upgrade_main_savepoint(true, 2012060600.03);
826     }
828     if ($oldversion < 2012060600.04) {
829         // Add a unique index over repositoryid and referencehash fields in files_reference table
830         $table = new xmldb_table('files_reference');
831         $index = new xmldb_index('uq_external_file', XMLDB_INDEX_UNIQUE, array('repositoryid', 'referencehash'));
833         if (!$dbman->index_exists($table, $index)) {
834             $dbman->add_index($table, $index);
835         }
837         upgrade_main_savepoint(true, 2012060600.04);
838     }
840     if ($oldversion < 2012061800.01) {
842         // Define field screenreader to be dropped from user
843         $table = new xmldb_table('user');
844         $field = new xmldb_field('ajax');
846         // Conditionally launch drop field screenreader
847         if ($dbman->field_exists($table, $field)) {
848             $dbman->drop_field($table, $field);
849         }
851         // Main savepoint reached
852         upgrade_main_savepoint(true, 2012061800.01);
853     }
855     if ($oldversion < 2012062000.00) {
856         // Add field newcontextid to backup_files_template
857         $table = new xmldb_table('backup_files_template');
858         $field = new xmldb_field('newcontextid', XMLDB_TYPE_INTEGER, '10', null, null, null, null, 'info');
860         if (!$dbman->field_exists($table, $field)) {
861             $dbman->add_field($table, $field);
862         }
864         upgrade_main_savepoint(true, 2012062000.00);
865     }
867     if ($oldversion < 2012062000.01) {
868         // Add field newitemid to backup_files_template
869         $table = new xmldb_table('backup_files_template');
870         $field = new xmldb_field('newitemid', XMLDB_TYPE_INTEGER, '10', null, null, null, null, 'newcontextid');
872         if (!$dbman->field_exists($table, $field)) {
873             $dbman->add_field($table, $field);
874         }
876         upgrade_main_savepoint(true, 2012062000.01);
877     }
879     // Moodle v2.3.0 release upgrade line
880     // Put any upgrade step following this
882     if ($oldversion < 2012062500.02) {
883         // Drop some old backup tables, not used anymore
885         // Define table backup_files to be dropped
886         $table = new xmldb_table('backup_files');
888         // Conditionally launch drop table for backup_files
889         if ($dbman->table_exists($table)) {
890             $dbman->drop_table($table);
891         }
893         // Define table backup_ids to be dropped
894         $table = new xmldb_table('backup_ids');
896         // Conditionally launch drop table for backup_ids
897         if ($dbman->table_exists($table)) {
898             $dbman->drop_table($table);
899         }
901         // Main savepoint reached
902         upgrade_main_savepoint(true, 2012062500.02);
903     }
905     if ($oldversion < 2012070600.04) {
906         // Define table course_modules_avail_fields to be created
907         $table = new xmldb_table('course_modules_avail_fields');
909         // Adding fields to table course_modules_avail_fields
910         $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
911         $table->add_field('coursemoduleid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null);
912         $table->add_field('userfield', XMLDB_TYPE_CHAR, '50', null, null, null, null);
913         $table->add_field('customfieldid', XMLDB_TYPE_INTEGER, '10', null, null, null, null);
914         $table->add_field('operator', XMLDB_TYPE_CHAR, '20', null, XMLDB_NOTNULL, null, null);
915         $table->add_field('value', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null);
917         // Adding keys to table course_modules_avail_fields
918         $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
919         $table->add_key('coursemoduleid', XMLDB_KEY_FOREIGN, array('coursemoduleid'), 'course_modules', array('id'));
921         // Conditionally launch create table for course_modules_avail_fields
922         if (!$dbman->table_exists($table)) {
923             $dbman->create_table($table);
924         }
926         // Main savepoint reached
927         upgrade_main_savepoint(true, 2012070600.04);
928     }
930     if ($oldversion < 2012070600.05) {
931         // Define table course_sections_avail_fields to be created
932         $table = new xmldb_table('course_sections_avail_fields');
934         // Adding fields to table course_sections_avail_fields
935         $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
936         $table->add_field('coursesectionid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null);
937         $table->add_field('userfield', XMLDB_TYPE_CHAR, '50', null, null, null, null);
938         $table->add_field('customfieldid', XMLDB_TYPE_INTEGER, '10', null, null, null, null);
939         $table->add_field('operator', XMLDB_TYPE_CHAR, '20', null, XMLDB_NOTNULL, null, null);
940         $table->add_field('value', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null);
942         // Adding keys to table course_sections_avail_fields
943         $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
944         $table->add_key('coursesectionid', XMLDB_KEY_FOREIGN, array('coursesectionid'), 'course_sections', array('id'));
946         // Conditionally launch create table for course_sections_avail_fields
947         if (!$dbman->table_exists($table)) {
948             $dbman->create_table($table);
949         }
951         // Main savepoint reached
952         upgrade_main_savepoint(true, 2012070600.05);
953     }
955     if ($oldversion < 2012070600.06) {
957         // Drop "deleted" fields
958         $table = new xmldb_table('course_completions');
959         $field = new xmldb_field('timenotified');
960         $field = new xmldb_field('deleted');
962         // Conditionally launch drop field deleted from course_completions
963         if ($dbman->field_exists($table, $field)) {
964             $dbman->drop_field($table, $field);
965         }
967         $field = new xmldb_field('timenotified');
968         // Conditionally launch drop field timenotified from course_completions
969         if ($dbman->field_exists($table, $field)) {
970             $dbman->drop_field($table, $field);
971         }
973         // Main savepoint reached
974         upgrade_main_savepoint(true, 2012070600.06);
975     }
977     if ($oldversion < 2012070600.07) {
978         $table = new xmldb_table('course_completion_crit_compl');
979         $field = new xmldb_field('deleted');
981         // Conditionally launch drop field deleted from course_completion_crit_compl
982         if ($dbman->field_exists($table, $field)) {
983             $dbman->drop_field($table, $field);
984         }
985         // Main savepoint reached
986         upgrade_main_savepoint(true, 2012070600.07);
987     }
989     if ($oldversion < 2012070600.08) {
991         // Drop unused table "course_completion_notify"
992         $table = new xmldb_table('course_completion_notify');
994         // Conditionally launch drop table course_completion_notify
995         if ($dbman->table_exists($table)) {
996             $dbman->drop_table($table);
997         }
999         // Main savepoint reached
1000         upgrade_main_savepoint(true, 2012070600.08);
1001      }
1003     if ($oldversion < 2012070600.09) {
1005         // Define index path (not unique) to be added to context
1006         $table = new xmldb_table('context');
1007         $index = new xmldb_index('path', XMLDB_INDEX_NOTUNIQUE, array('path'), array('varchar_pattern_ops'));
1009         // Recreate index with new pattern hint
1010         if ($DB->get_dbfamily() === 'postgres') {
1011             if ($dbman->index_exists($table, $index)) {
1012                 $dbman->drop_index($table, $index);
1013             }
1014             $dbman->add_index($table, $index);
1015         }
1017         // Main savepoint reached
1018         upgrade_main_savepoint(true, 2012070600.09);
1019     }
1021     if ($oldversion < 2012070600.10) {
1023         // Define index name (unique) to be dropped form role
1024         $table = new xmldb_table('role');
1025         $index = new xmldb_index('name', XMLDB_INDEX_UNIQUE, array('name'));
1027         // Conditionally launch drop index name
1028         if ($dbman->index_exists($table, $index)) {
1029             $dbman->drop_index($table, $index);
1030         }
1032         // Main savepoint reached
1033         upgrade_main_savepoint(true, 2012070600.10);
1034     }
1036     if ($oldversion < 2012070600.11) {
1038         // Define index component-itemid-userid (not unique) to be added to role_assignments
1039         $table = new xmldb_table('role_assignments');
1040         $index = new xmldb_index('component-itemid-userid', XMLDB_INDEX_NOTUNIQUE, array('component', 'itemid', 'userid'));
1042         // Conditionally launch add index component-itemid-userid
1043         if (!$dbman->index_exists($table, $index)) {
1044             $dbman->add_index($table, $index);
1045         }
1047         // Main savepoint reached
1048         upgrade_main_savepoint(true, 2012070600.11);
1049     }
1051     if ($oldversion < 2012071900.01) {
1052         // Cleanup after simpeltests tool
1053         capabilities_cleanup('tool_unittest');
1054         unset_all_config_for_plugin('tool_unittest');
1056         upgrade_main_savepoint(true, 2012071900.01);
1057     }
1059     if ($oldversion < 2012072400.00) {
1060         // Remove obsolete xhtml strict setting - use THEME->doctype in theme config if necessary,
1061         // see theme_config->doctype in lib/outputlib.php for more details.
1062         unset_config('xmlstrictheaders');
1063         upgrade_main_savepoint(true, 2012072400.00);
1064     }
1066     if ($oldversion < 2012072401.00) {
1068         // Saves orphaned questions from the Dark Side
1069         upgrade_save_orphaned_questions();
1071         // Main savepoint reached
1072         upgrade_main_savepoint(true, 2012072401.00);
1073     }
1075     if ($oldversion < 2012072600.01) {
1076         // Handle events with empty eventtype //MDL-32827
1078         $DB->set_field('event', 'eventtype', 'site', array('eventtype' => '', 'courseid' => $SITE->id));
1079         $DB->set_field_select('event', 'eventtype', 'due', "eventtype = '' AND courseid != 0 AND groupid = 0 AND (modulename = 'assignment' OR modulename = 'assign')");
1080         $DB->set_field_select('event', 'eventtype', 'course', "eventtype = '' AND courseid != 0 AND groupid = 0");
1081         $DB->set_field_select('event', 'eventtype', 'group', "eventtype = '' AND groupid != 0");
1082         $DB->set_field_select('event', 'eventtype', 'user', "eventtype = '' AND userid != 0");
1084         // Main savepoint reached
1085         upgrade_main_savepoint(true, 2012072600.01);
1086     }
1088     if ($oldversion < 2012080200.02) {
1089         // Drop obsolete question upgrade field that should have been added to the install.xml.
1090         $table = new xmldb_table('question');
1091         $field = new xmldb_field('oldquestiontextformat', XMLDB_TYPE_INTEGER, '2', null, XMLDB_NOTNULL, null, '0');
1093         if ($dbman->field_exists($table, $field)) {
1094             $dbman->drop_field($table, $field);
1095         }
1097         upgrade_main_savepoint(true, 2012080200.02);
1098     }
1100     if ($oldversion < 2012081400.01) {
1101         // Move the ability to disable blogs to its own setting MDL-25012.
1103         if (isset($CFG->bloglevel)) {
1104             // Only change settings if existing setting was set.
1105             if (empty($CFG->bloglevel)) {
1106                 set_config('enableblogs', 0);
1107                 // Now set the bloglevel to a valid setting as the disabled setting has been removed.
1108                 // This prevents confusing results when users enable the blog system in future.
1109                 set_config('bloglevel', BLOG_USER_LEVEL);
1110             } else {
1111                 set_config('enableblogs', 1);
1112             }
1113         }
1115         // Main savepoint reached
1116         upgrade_main_savepoint(true, 2012081400.01);
1117     }
1119     if ($oldversion < 2012081600.01) {
1120         // Delete removed setting - Google Maps API V2 will not work in 2013.
1121         unset_config('googlemapkey');
1122         upgrade_main_savepoint(true, 2012081600.01);
1123     }
1125     if ($oldversion < 2012082300.01) {
1126         // Add more custom enrol fields.
1127         $table = new xmldb_table('enrol');
1128         $field = new xmldb_field('customint5', XMLDB_TYPE_INTEGER, '10', null, null, null, null, 'customint4');
1130         if (!$dbman->field_exists($table, $field)) {
1131             $dbman->add_field($table, $field);
1132         }
1134         $field = new xmldb_field('customint6', XMLDB_TYPE_INTEGER, '10', null, null, null, null, 'customint5');
1135         if (!$dbman->field_exists($table, $field)) {
1136             $dbman->add_field($table, $field);
1137         }
1139         $field = new xmldb_field('customint7', XMLDB_TYPE_INTEGER, '10', null, null, null, null, 'customint6');
1140         if (!$dbman->field_exists($table, $field)) {
1141             $dbman->add_field($table, $field);
1142         }
1144         $field = new xmldb_field('customint8', XMLDB_TYPE_INTEGER, '10', null, null, null, null, 'customint7');
1145         if (!$dbman->field_exists($table, $field)) {
1146             $dbman->add_field($table, $field);
1147         }
1149         $field = new xmldb_field('customchar3', XMLDB_TYPE_CHAR, '1333', null, null, null, null, 'customchar2');
1150         if (!$dbman->field_exists($table, $field)) {
1151             $dbman->add_field($table, $field);
1152         }
1154         $field = new xmldb_field('customtext3', XMLDB_TYPE_TEXT, null, null, null, null, null, 'customtext2');
1155         if (!$dbman->field_exists($table, $field)) {
1156             $dbman->add_field($table, $field);
1157         }
1159         $field = new xmldb_field('customtext4', XMLDB_TYPE_TEXT, null, null, null, null, null, 'customtext3');
1160         if (!$dbman->field_exists($table, $field)) {
1161             $dbman->add_field($table, $field);
1162         }
1164         // Main savepoint reached.
1165         upgrade_main_savepoint(true, 2012082300.01);
1166     }
1168     if ($oldversion < 2012082300.02) {
1169         // Define field component to be added to groups_members
1170         $table = new xmldb_table('groups_members');
1171         $field = new xmldb_field('component', XMLDB_TYPE_CHAR, '100', null, XMLDB_NOTNULL, null, null, 'timeadded');
1173         // Conditionally launch add field component
1174         if (!$dbman->field_exists($table, $field)) {
1175             $dbman->add_field($table, $field);
1176         }
1178         // Define field itemid to be added to groups_members
1179         $field = new xmldb_field('itemid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0', 'component');
1181         // Conditionally launch add field itemid
1182         if (!$dbman->field_exists($table, $field)) {
1183             $dbman->add_field($table, $field);
1184         }
1186         // Main savepoint reached
1187         upgrade_main_savepoint(true, 2012082300.02);
1188     }
1190     if ($oldversion < 2012090500.00) {
1191         $subquery = 'SELECT b.id FROM {blog_external} b where b.id = ' . $DB->sql_cast_char2int('{post}.content', true);
1192         $sql = 'DELETE FROM {post}
1193                       WHERE {post}.module = \'blog_external\'
1194                             AND NOT EXISTS (' . $subquery . ')
1195                             AND ' . $DB->sql_isnotempty('post', 'uniquehash', false, false);
1196         $DB->execute($sql);
1197         upgrade_main_savepoint(true, 2012090500.00);
1198     }
1200     if ($oldversion < 2012090700.01) {
1201         // Add a category field in the course_request table
1202         $table = new xmldb_table('course_request');
1203         $field = new xmldb_field('category', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, 0, 'summaryformat');
1204         if (!$dbman->field_exists($table, $field)) {
1205             $dbman->add_field($table, $field);
1206         }
1208         // Main savepoint reached.
1209         upgrade_main_savepoint(true, 2012090700.01);
1210     }
1212     if ($oldversion < 2012091700.00) {
1214         // Dropping screenreader field from user.
1215         $table = new xmldb_table('user');
1216         $field = new xmldb_field('screenreader');
1218         if ($dbman->field_exists($table, $field)) {
1219             $dbman->drop_field($table, $field);
1220         }
1222         // Main savepoint reached.
1223         upgrade_main_savepoint(true, 2012091700.00);
1224     }
1226     if ($oldversion < 2012092100.01) {
1227         // Some folders still have a sortorder set, which is used for main files but is not
1228         // supported by the folder resource. We reset the value here.
1229         $sql = 'UPDATE {files} SET sortorder = ? WHERE component = ? AND filearea = ? AND sortorder <> ?';
1230         $DB->execute($sql, array(0, 'mod_folder', 'content', 0));
1232         // Main savepoint reached.
1233         upgrade_main_savepoint(true, 2012092100.01);
1234     }
1236     if ($oldversion < 2012092600.00) {
1237         // Define index idname (unique) to be added to tag
1238         $table = new xmldb_table('tag');
1239         $index = new xmldb_index('idname', XMLDB_INDEX_UNIQUE, array('id', 'name'));
1241         // Conditionally launch add index idname
1242         if (!$dbman->index_exists($table, $index)) {
1243             $dbman->add_index($table, $index);
1244         }
1246         // Main savepoint reached
1247         upgrade_main_savepoint(true, 2012092600.00);
1248     }
1250     if ($oldversion < 2012101500.01) {
1251         // Find all orphaned blog associations that might exist.
1252         $sql = "SELECT ba.id
1253                   FROM {blog_association} ba
1254              LEFT JOIN {post} p
1255                     ON p.id = ba.blogid
1256                  WHERE p.id IS NULL";
1257         $orphanedrecordids = $DB->get_records_sql($sql);
1258         // Now delete these associations.
1259         foreach ($orphanedrecordids as $orphanedrecord) {
1260             $DB->delete_records('blog_association', array('id' => $orphanedrecord->id));
1261         }
1263         upgrade_main_savepoint(true, 2012101500.01);
1264     }
1266     if ($oldversion < 2012101800.02) {
1267         // Renaming backups using previous file naming convention.
1268         upgrade_rename_old_backup_files_using_shortname();
1270         // Main savepoint reached.
1271         upgrade_main_savepoint(true, 2012101800.02);
1272     }
1274     if ($oldversion < 2012103001.00) {
1275         // create new event_subscriptions table
1276         $table = new xmldb_table('event_subscriptions');
1277         $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
1278         $table->add_field('url', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null);
1279         $table->add_field('courseid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0');
1280         $table->add_field('groupid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0');
1281         $table->add_field('userid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0');
1282         $table->add_field('pollinterval', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0');
1283         $table->add_field('lastupdated', XMLDB_TYPE_INTEGER, '10', null, null, null, null);
1284         $table->add_field('name', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null);
1285         $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
1286         if (!$dbman->table_exists($table)) {
1287             $dbman->create_table($table);
1288         }
1289         // Main savepoint reached
1290         upgrade_main_savepoint(true, 2012103001.00);
1291     }
1293     if ($oldversion < 2012103002.00) {
1294         // Add subscription field to the event table
1295         $table = new xmldb_table('event');
1296         $field = new xmldb_field('subscriptionid', XMLDB_TYPE_INTEGER, '10', null, null, null, null, 'timemodified');
1298         // Conditionally launch add field subscriptionid
1299         if (!$dbman->field_exists($table, $field)) {
1300             $dbman->add_field($table, $field);
1301         }
1302         upgrade_main_savepoint(true, 2012103002.00);
1303     }
1305     if ($oldversion < 2012103003.00) {
1306         // Fix uuid field in event table to match RFC-2445 UID property.
1307         $table = new xmldb_table('event');
1308         $field = new xmldb_field('uuid', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, 'visible');
1309         // The column already exists, so make sure there are no nulls (crazy mysql).
1310         $DB->set_field_select('event', 'uuid', '', "uuid IS NULL");
1311         // Changing precision of field uuid on table event to (255).
1312         $dbman->change_field_precision($table, $field);
1313         // Main savepoint reached
1314         upgrade_main_savepoint(true, 2012103003.00);
1315     }
1317     if ($oldversion < 2012110200.00) {
1319         // Define table course_format_options to be created
1320         $table = new xmldb_table('course_format_options');
1322         // Adding fields to table course_format_options
1323         $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
1324         $table->add_field('courseid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null);
1325         $table->add_field('format', XMLDB_TYPE_CHAR, '21', null, XMLDB_NOTNULL, null, null);
1326         $table->add_field('sectionid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0', 'format');
1327         $table->add_field('name', XMLDB_TYPE_CHAR, '100', null, XMLDB_NOTNULL, null, null);
1328         $table->add_field('value', XMLDB_TYPE_TEXT, null, null, null, null, null);
1330         // Adding keys to table course_format_options
1331         $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
1332         $table->add_key('courseid', XMLDB_KEY_FOREIGN, array('courseid'), 'course', array('id'));
1334         // Adding indexes to table course_format_options
1335         $table->add_index('formatoption', XMLDB_INDEX_UNIQUE, array('courseid', 'format', 'sectionid', 'name'));
1337         // Conditionally launch create table for course_format_options
1338         if (!$dbman->table_exists($table)) {
1339             $dbman->create_table($table);
1340         }
1342         // Changing type of field format on table course to char with length 21
1343         $table = new xmldb_table('course');
1344         $field = new xmldb_field('format', XMLDB_TYPE_CHAR, '21', null, XMLDB_NOTNULL, null, 'topics', 'summaryformat');
1346         // Launch change of type for field format
1347         $dbman->change_field_type($table, $field);
1349         // Since structure of 'course' table has changed we need to re-read $SITE from DB.
1350         $SITE = $DB->get_record('course', array('id' => $SITE->id));
1351         $COURSE = clone($SITE);
1353         // Main savepoint reached
1354         upgrade_main_savepoint(true, 2012110200.00);
1355     }
1357     if ($oldversion < 2012110201.00) {
1359         // Copy fields 'coursedisplay', 'numsections', 'hiddensections' from table {course}
1360         // to table {course_format_options} as the additional format options
1361         $fields = array();
1362         $table = new xmldb_table('course');
1363         foreach (array('coursedisplay', 'numsections', 'hiddensections') as $fieldname) {
1364             // first check that fields still exist
1365             $field = new xmldb_field($fieldname);
1366             if ($dbman->field_exists($table, $field)) {
1367                 $fields[] = $fieldname;
1368             }
1369         }
1371         if (!empty($fields)) {
1372             $transaction = $DB->start_delegated_transaction();
1373             $rs = $DB->get_recordset_sql('SELECT id, format, '. join(',', $fields).'
1374                 FROM {course}
1375                 WHERE format <> ? AND format <> ?',
1376                 array('scorm', 'social'));
1377             // (do not copy fields from scrom and social formats, we already know that they are not used)
1378             foreach ($rs as $rec) {
1379                 foreach ($fields as $field) {
1380                     try {
1381                         $DB->insert_record('course_format_options',
1382                                 array(
1383                                     'courseid'  => $rec->id,
1384                                     'format'    => $rec->format,
1385                                     'sectionid' => 0,
1386                                     'name'      => $field,
1387                                     'value'     => $rec->$field
1388                                 ));
1389                     } catch (dml_exception $e) {
1390                         // index 'courseid,format,sectionid,name' violation
1391                         // continue; the entry in course_format_options already exists, use it
1392                     }
1393                 }
1394             }
1395             $rs->close();
1396             $transaction->allow_commit();
1398             // Drop fields from table course
1399             foreach ($fields as $fieldname) {
1400                 $field = new xmldb_field($fieldname);
1401                 $dbman->drop_field($table, $field);
1402             }
1403         }
1405         // Since structure of 'course' table has changed we need to re-read $SITE from DB.
1406         $SITE = $DB->get_record('course', array('id' => $SITE->id));
1407         $COURSE = clone($SITE);
1409         // Main savepoint reached
1410         upgrade_main_savepoint(true, 2012110201.00);
1411     }
1413     if ($oldversion < 2012110700.01) {
1415         // Define field caller_component to be added to portfolio_log.
1416         $table = new xmldb_table('portfolio_log');
1417         $field = new xmldb_field('caller_component', XMLDB_TYPE_CHAR, '255', null, null, null, null, 'caller_file');
1419         // Conditionally launch add field caller_component.
1420         if (!$dbman->field_exists($table, $field)) {
1421             $dbman->add_field($table, $field);
1422         }
1424         // Main savepoint reached.
1425         upgrade_main_savepoint(true, 2012110700.01);
1426     }
1428     if ($oldversion < 2012111200.00) {
1430         // Define table temp_enroled_template to be created
1431         $table = new xmldb_table('temp_enroled_template');
1433         // Adding fields to table temp_enroled_template
1434         $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
1435         $table->add_field('userid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0');
1436         $table->add_field('courseid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0');
1437         $table->add_field('roleid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null);
1439         // Adding keys to table temp_enroled_template
1440         $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
1442         // Adding indexes to table temp_enroled_template
1443         $table->add_index('userid', XMLDB_INDEX_NOTUNIQUE, array('userid'));
1444         $table->add_index('courseid', XMLDB_INDEX_NOTUNIQUE, array('courseid'));
1445         $table->add_index('roleid', XMLDB_INDEX_NOTUNIQUE, array('roleid'));
1447         // Conditionally launch create table for temp_enroled_template
1448         if (!$dbman->table_exists($table)) {
1449             $dbman->create_table($table);
1450         }
1452         // Define table temp_log_template to be created
1453         $table = new xmldb_table('temp_log_template');
1455         // Adding fields to table temp_log_template
1456         $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
1457         $table->add_field('userid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0');
1458         $table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0');
1459         $table->add_field('action', XMLDB_TYPE_CHAR, '40', null, XMLDB_NOTNULL, null, null);
1461         // Adding keys to table temp_log_template
1462         $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
1464         // Adding indexes to table temp_log_template
1465         $table->add_index('action', XMLDB_INDEX_NOTUNIQUE, array('action'));
1466         $table->add_index('course', XMLDB_INDEX_NOTUNIQUE, array('course'));
1467         $table->add_index('user', XMLDB_INDEX_NOTUNIQUE, array('userid'));
1468         $table->add_index('usercourseaction', XMLDB_INDEX_NOTUNIQUE, array('userid', 'course', 'action'));
1470         // Conditionally launch create table for temp_log_template
1471         if (!$dbman->table_exists($table)) {
1472             $dbman->create_table($table);
1473         }
1475         // Main savepoint reached
1476         upgrade_main_savepoint(true, 2012111200.00);
1477     }
1479     if ($oldversion < 2012111200.01) {
1480         // Force the rebuild of the cache of every courses, some cached information could contain wrong icon references.
1481         $DB->execute('UPDATE {course} set modinfo = ?, sectioncache = ?', array(null, null));
1483         // Main savepoint reached.
1484         upgrade_main_savepoint(true, 2012111200.01);
1485     }
1487     if ($oldversion < 2012111601.01) {
1488         // Clea up after old shared memory caching support.
1489         unset_config('cachetype');
1490         unset_config('rcache');
1491         unset_config('rcachettl');
1492         unset_config('intcachemax');
1493         unset_config('memcachedhosts');
1494         unset_config('memcachedpconn');
1496         // Main savepoint reached.
1497         upgrade_main_savepoint(true, 2012111601.01);
1498     }
1500     if ($oldversion < 2012112100.00) {
1502         // Define field eventtype to be added to event_subscriptions.
1503         $table = new xmldb_table('event_subscriptions');
1504         $field = new xmldb_field('eventtype', XMLDB_TYPE_CHAR, '20', null, XMLDB_NOTNULL, null, null, 'userid');
1506         // Conditionally launch add field eventtype.
1507         if (!$dbman->field_exists($table, $field)) {
1508             $dbman->add_field($table, $field);
1509         }
1511         // Main savepoint reached.
1512         upgrade_main_savepoint(true, 2012112100.00);
1513     }
1515     // Moodle v2.4.0 release upgrade line
1516     // Put any upgrade step following this
1518     if ($oldversion < 2012120300.01) {
1519         // Make sure site-course has format='site' //MDL-36840
1521         if ($SITE->format !== 'site') {
1522             $DB->set_field('course', 'format', 'site', array('id' => $SITE->id));
1523             $SITE->format = 'site';
1524             $COURSE->format = 'site';
1525         }
1527         // Main savepoint reached
1528         upgrade_main_savepoint(true, 2012120300.01);
1529     }
1531     if ($oldversion < 2012120300.04) {
1532         // Remove "_utf8" suffix from all langs in course table.
1533         $langs = $DB->get_records_sql("SELECT DISTINCT lang FROM {course} WHERE lang LIKE ?", array('%_utf8'));
1535         foreach ($langs as $lang=>$unused) {
1536             $newlang = str_replace('_utf8', '', $lang);
1537             $sql = "UPDATE {course} SET lang = :newlang WHERE lang = :lang";
1538             $DB->execute($sql, array('newlang'=>$newlang, 'lang'=>$lang));
1539         }
1541         // Main savepoint reached.
1542         upgrade_main_savepoint(true, 2012120300.04);
1543     }
1545     if ($oldversion < 2012123000.00) {
1546         // Purge removed module filters and all their settings.
1548         $tables = array('filter_active', 'filter_config');
1549         foreach ($tables as $table) {
1550             $DB->delete_records_select($table, "filter LIKE 'mod/%'");
1551             $filters = $DB->get_records_sql("SELECT DISTINCT filter FROM {{$table}} WHERE filter LIKE 'filter/%'");
1552             foreach ($filters as $filter) {
1553                 $DB->set_field($table, 'filter', substr($filter->filter, 7), array('filter'=>$filter->filter));
1554             }
1555         }
1557         $configs = array('stringfilters', 'filterall');
1558         foreach ($configs as $config) {
1559             if ($filters = get_config(null, $config)) {
1560                 $filters = explode(',', $filters);
1561                 $newfilters = array();
1562                 foreach($filters as $filter) {
1563                     if (strpos($filter, '/') === false) {
1564                         $newfilters[] = $filter;
1565                     } else if (strpos($filter, 'filter/') === 0) {
1566                         $newfilters[] = substr($filter, 7);
1567                     }
1568                 }
1569                 $filters = implode(',', $newfilters);
1570                 set_config($config, $filters);
1571             }
1572         }
1574         unset($tables);
1575         unset($table);
1576         unset($configs);
1577         unset($newfilters);
1578         unset($filters);
1579         unset($filter);
1581         // Main savepoint reached.
1582         upgrade_main_savepoint(true, 2012123000.00);
1583     }
1585     if ($oldversion < 2013021100.01) {
1587         // Changing precision of field password on table user to (255).
1588         $table = new xmldb_table('user');
1589         $field = new xmldb_field('password', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, 'username');
1591         // Launch change of precision for field password.
1592         $dbman->change_field_precision($table, $field);
1594         // Main savepoint reached.
1595         upgrade_main_savepoint(true, 2013021100.01);
1596     }
1598     if ($oldversion < 2013021800.00) {
1599         // Add the site identifier to the cache config's file.
1600         $siteidentifier = $DB->get_field('config', 'value', array('name' => 'siteidentifier'));
1601         cache_helper::update_site_identifier($siteidentifier);
1603         // Main savepoint reached.
1604         upgrade_main_savepoint(true, 2013021800.00);
1605     }
1607     if ($oldversion < 2013021801.00) {
1608         // Fixing possible wrong MIME types for SMART Notebook files.
1609         $extensions = array('%.gallery', '%.galleryitem', '%.gallerycollection', '%.nbk', '%.notebook', '%.xbk');
1610         $select = $DB->sql_like('filename', '?', false);
1611         foreach ($extensions as $extension) {
1612             $DB->set_field_select(
1613                 'files',
1614                 'mimetype',
1615                 'application/x-smarttech-notebook',
1616                 $select,
1617                 array($extension)
1618             );
1619         }
1620         upgrade_main_savepoint(true, 2013021801.00);
1621     }
1623     if ($oldversion < 2013021801.01) {
1624         // This upgrade step is re-written under MDL-38228 (see below).
1625         /*
1626         // Retrieve the list of course_sections as a recordset to save memory
1627         $coursesections = $DB->get_recordset('course_sections', null, 'course, id', 'id, course, sequence');
1628         foreach ($coursesections as $coursesection) {
1629             // Retrieve all of the actual modules in this course and section combination to reduce DB calls
1630             $actualsectionmodules = $DB->get_records('course_modules',
1631                     array('course' => $coursesection->course, 'section' => $coursesection->id), '', 'id, section');
1633             // Break out the current sequence so that we can compare it
1634             $currentsequence = explode(',', $coursesection->sequence);
1635             $newsequence = array();
1637             // Check each of the modules in the current sequence
1638             foreach ($currentsequence as $module) {
1639                 if (isset($actualsectionmodules[$module])) {
1640                     $newsequence[] = $module;
1641                     // We unset the actualsectionmodules so that we don't get duplicates and that we can add orphaned
1642                     // modules later
1643                     unset($actualsectionmodules[$module]);
1644                 }
1645             }
1647             // Append any modules which have somehow been orphaned
1648             foreach ($actualsectionmodules as $module) {
1649                 $newsequence[] = $module->id;
1650             }
1652             // Piece it all back together
1653             $sequence = implode(',', $newsequence);
1655             // Only update if there have been changes
1656             if ($sequence !== $coursesection->sequence) {
1657                 $coursesection->sequence = $sequence;
1658                 $DB->update_record('course_sections', $coursesection);
1660                 // And clear the sectioncache and modinfo cache - they'll be regenerated on next use
1661                 $course = new stdClass();
1662                 $course->id = $coursesection->course;
1663                 $course->sectioncache = null;
1664                 $course->modinfo = null;
1665                 $DB->update_record('course', $course);
1666             }
1667         }
1668         $coursesections->close();
1669         */
1670         // Main savepoint reached.
1671         upgrade_main_savepoint(true, 2013021801.01);
1672     }
1674     if ($oldversion < 2013021902.00) {
1675         // ISO country change: Netherlands Antilles is split into BQ, CW & SX
1676         // http://www.iso.org/iso/iso_3166-1_newsletter_vi-8_split_of_the_dutch_antilles_final-en.pdf
1677         $sql = "UPDATE {user} SET country = '' WHERE country = ?";
1678         $DB->execute($sql, array('AN'));
1680         upgrade_main_savepoint(true, 2013021902.00);
1681     }
1683     if ($oldversion < 2013022600.00) {
1684         // Delete entries regarding invalid 'interests' option which breaks course.
1685         $DB->delete_records('course_sections_avail_fields', array('userfield' => 'interests'));
1686         $DB->delete_records('course_modules_avail_fields', array('userfield' => 'interests'));
1687         // Clear course cache (will be rebuilt on first visit) in case of changes to these.
1688         $DB->execute('UPDATE {course} set modinfo = ?, sectioncache = ?', array(null, null));
1690         upgrade_main_savepoint(true, 2013022600.00);
1691     }
1693     // Add index to field "timemodified" for grade_grades_history table.
1694     if ($oldversion < 2013030400.00) {
1695         $table = new xmldb_table('grade_grades_history');
1696         $field = new xmldb_field('timemodified');
1698         if ($dbman->field_exists($table, $field)) {
1699             $index = new xmldb_index('timemodified', XMLDB_INDEX_NOTUNIQUE, array('timemodified'));
1700             if (!$dbman->index_exists($table, $index)) {
1701                 $dbman->add_index($table, $index);
1702             }
1703         }
1705         // Main savepoint reached.
1706         upgrade_main_savepoint(true, 2013030400.00);
1707     }
1709     if ($oldversion < 2013030400.02) {
1710         // Cleanup qformat blackboard settings.
1711         unset_all_config_for_plugin('qformat_blackboard');
1713         upgrade_main_savepoint(true, 2013030400.02);
1714     }
1716     // This is checking to see if the site has been running a specific version with a bug in it
1717     // because this upgrade step is slow and is only needed if the site has been running with the affected versions.
1718     if ($oldversion >= 2012062504.08 && $oldversion < 2012062504.13) {
1719         // This upgrade step is re-written under MDL-38228 (see below).
1721         /*
1722         // Retrieve the list of course_sections as a recordset to save memory.
1723         // This is to fix a regression caused by MDL-37939.
1724         // In this case the upgrade step is fixing records where:
1725         // The data in course_sections.sequence contains the correct module id
1726         // The section field for on the course modules table may have been updated to point to the incorrect id.
1728         // This query is looking for sections where the sequence is not in sync with the course_modules table.
1729         // The syntax for the like query is looking for a value in a comma separated list.
1730         // It adds a comma to either site of the list and then searches for LIKE '%,id,%'.
1731         $sequenceconcat = $DB->sql_concat("','", 's.sequence', "','");
1732         $moduleconcat = $DB->sql_concat("'%,'", 'cm.id', "',%'");
1733         $sql = 'SELECT s2.id, s2.course, s2.sequence
1734                 FROM {course_sections} s2
1735                 JOIN(
1736                     SELECT DISTINCT s.id
1737                     FROM
1738                     {course_modules} cm
1739                     JOIN {course_sections} s
1740                     ON
1741                         cm.course = s.course
1742                     WHERE cm.section != s.id AND ' . $sequenceconcat . ' LIKE ' . $moduleconcat . '
1743                 ) d
1744                 ON s2.id = d.id';
1745         $coursesections = $DB->get_recordset_sql($sql);
1747         foreach ($coursesections as $coursesection) {
1748             // Retrieve all of the actual modules in this course and section combination to reduce DB calls.
1749             $actualsectionmodules = $DB->get_records('course_modules',
1750                     array('course' => $coursesection->course, 'section' => $coursesection->id), '', 'id, section');
1752             // Break out the current sequence so that we can compare it.
1753             $currentsequence = explode(',', $coursesection->sequence);
1754             $orphanlist = array();
1756             // Check each of the modules in the current sequence.
1757             foreach ($currentsequence as $cmid) {
1758                 if (!empty($cmid) && !isset($actualsectionmodules[$cmid])) {
1759                     $orphanlist[] = $cmid;
1760                 }
1761             }
1763             if (!empty($orphanlist)) {
1764                 list($sql, $params) = $DB->get_in_or_equal($orphanlist, SQL_PARAMS_NAMED);
1765                 $sql = "id $sql";
1767                 $DB->set_field_select('course_modules', 'section', $coursesection->id, $sql, $params);
1769                 // And clear the sectioncache and modinfo cache - they'll be regenerated on next use.
1770                 $course = new stdClass();
1771                 $course->id = $coursesection->course;
1772                 $course->sectioncache = null;
1773                 $course->modinfo = null;
1774                 $DB->update_record('course', $course);
1775             }
1776         }
1777         $coursesections->close();
1779         // No savepoint needed for this change.
1780          */
1781     }
1783     if ($oldversion < 2013032200.01) {
1784         // GD is now always available
1785         set_config('gdversion', 2);
1787         upgrade_main_savepoint(true, 2013032200.01);
1788     }
1790     if ($oldversion < 2013032600.03) {
1791         // Fixing possible wrong MIME type for MIME HTML (MHTML) files.
1792         $extensions = array('%.mht', '%.mhtml');
1793         $select = $DB->sql_like('filename', '?', false);
1794         foreach ($extensions as $extension) {
1795             $DB->set_field_select(
1796                 'files',
1797                 'mimetype',
1798                 'message/rfc822',
1799                 $select,
1800                 array($extension)
1801             );
1802         }
1803         upgrade_main_savepoint(true, 2013032600.03);
1804     }
1806     if ($oldversion < 2013032600.04) {
1807         // MDL-31983 broke the quiz version number. Fix it.
1808         $DB->set_field('modules', 'version', '2013021500',
1809                 array('name' => 'quiz', 'version' => '2013310100'));
1810         upgrade_main_savepoint(true, 2013032600.04);
1811     }
1813     if ($oldversion < 2013040200.00) {
1814         // Add openbadges tables.
1816         // Define table 'badge' to be created.
1817         $table = new xmldb_table('badge');
1819         // Adding fields to table 'badge'.
1820         $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null);
1821         $table->add_field('name', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, 'id');
1822         $table->add_field('description', XMLDB_TYPE_TEXT, null, null, null, null, null, 'name');
1823         $table->add_field('image', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, 'description');
1824         $table->add_field('timecreated', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0', 'image');
1825         $table->add_field('timemodified', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0', 'timecreated');
1826         $table->add_field('usercreated', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, 'timemodified');
1827         $table->add_field('usermodified', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, 'usercreated');
1828         $table->add_field('issuername', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, 'usermodified');
1829         $table->add_field('issuerurl', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, 'issuername');
1830         $table->add_field('issuercontact', XMLDB_TYPE_CHAR, '255', null, null, null, null, 'issuerurl');
1831         $table->add_field('expiredate', XMLDB_TYPE_INTEGER, '10', null, null, null, null, 'issuercontact');
1832         $table->add_field('expireperiod', XMLDB_TYPE_INTEGER, '10', null, null, null, null, 'expiredate');
1833         $table->add_field('type', XMLDB_TYPE_INTEGER, '1', null, XMLDB_NOTNULL, null, '1', 'expireperiod');
1834         $table->add_field('courseid', XMLDB_TYPE_INTEGER, '10', null, null, null, null, 'type');
1835         $table->add_field('message', XMLDB_TYPE_TEXT, null, null, XMLDB_NOTNULL, null, null, 'courseid');
1836         $table->add_field('messagesubject', XMLDB_TYPE_TEXT, null, null, XMLDB_NOTNULL, null, null, 'message');
1837         $table->add_field('attachment', XMLDB_TYPE_INTEGER, '1', null, XMLDB_NOTNULL, null, '1', 'messagesubject');
1838         $table->add_field('notification', XMLDB_TYPE_INTEGER, '1', null, XMLDB_NOTNULL, null, '1', 'attachment');
1839         $table->add_field('status', XMLDB_TYPE_INTEGER, '1', null, XMLDB_NOTNULL, null, '0', 'notification');
1840         $table->add_field('nextcron', XMLDB_TYPE_INTEGER, '10', null, null, null, null, 'status');
1842         // Adding keys to table 'badge'.
1843         $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
1844         $table->add_key('fk_courseid', XMLDB_KEY_FOREIGN, array('courseid'), 'course', array('id'));
1845         $table->add_key('fk_usermodified', XMLDB_KEY_FOREIGN, array('usermodified'), 'user', array('id'));
1846         $table->add_key('fk_usercreated', XMLDB_KEY_FOREIGN, array('usercreated'), 'user', array('id'));
1848         // Adding indexes to table 'badge'.
1849         $table->add_index('type', XMLDB_INDEX_NOTUNIQUE, array('type'));
1851         // Conditionally launch create table for 'badge'.
1852         if (!$dbman->table_exists($table)) {
1853             $dbman->create_table($table);
1854         }
1856         // Define table 'badge_criteria' to be created.
1857         $table = new xmldb_table('badge_criteria');
1859         // Adding fields to table 'badge_criteria'.
1860         $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null);
1861         $table->add_field('badgeid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0', 'id');
1862         $table->add_field('criteriatype', XMLDB_TYPE_INTEGER, '10', null, null, null, null, 'badgeid');
1863         $table->add_field('method', XMLDB_TYPE_INTEGER, '1', null, XMLDB_NOTNULL, null, '1', 'criteriatype');
1865         // Adding keys to table 'badge_criteria'.
1866         $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
1867         $table->add_key('fk_badgeid', XMLDB_KEY_FOREIGN, array('badgeid'), 'badge', array('id'));
1869         // Adding indexes to table 'badge_criteria'.
1870         $table->add_index('criteriatype', XMLDB_INDEX_NOTUNIQUE, array('criteriatype'));
1871         $table->add_index('badgecriteriatype', XMLDB_INDEX_UNIQUE, array('badgeid', 'criteriatype'));
1873         // Conditionally launch create table for 'badge_criteria'.
1874         if (!$dbman->table_exists($table)) {
1875             $dbman->create_table($table);
1876         }
1878         // Define table 'badge_criteria_param' to be created.
1879         $table = new xmldb_table('badge_criteria_param');
1881         // Adding fields to table 'badge_criteria_param'.
1882         $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null);
1883         $table->add_field('critid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, 'id');
1884         $table->add_field('name', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, 'critid');
1885         $table->add_field('value', XMLDB_TYPE_CHAR, '255', null, null, null, null, 'name');
1887         // Adding keys to table 'badge_criteria_param'.
1888         $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
1889         $table->add_key('fk_critid', XMLDB_KEY_FOREIGN, array('critid'), 'badge_criteria', array('id'));
1891         // Conditionally launch create table for 'badge_criteria_param'.
1892         if (!$dbman->table_exists($table)) {
1893             $dbman->create_table($table);
1894         }
1896         // Define table 'badge_issued' to be created.
1897         $table = new xmldb_table('badge_issued');
1899         // Adding fields to table 'badge_issued'.
1900         $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null);
1901         $table->add_field('badgeid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0', 'id');
1902         $table->add_field('userid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0', 'badgeid');
1903         $table->add_field('uniquehash', XMLDB_TYPE_TEXT, null, null, XMLDB_NOTNULL, null, null, 'userid');
1904         $table->add_field('dateissued', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0', 'uniquehash');
1905         $table->add_field('dateexpire', XMLDB_TYPE_INTEGER, '10', null, null, null, null, 'dateissued');
1906         $table->add_field('visible', XMLDB_TYPE_INTEGER, '1', null, XMLDB_NOTNULL, null, '0', 'dateexpire');
1907         $table->add_field('issuernotified', XMLDB_TYPE_INTEGER, '10', null, null, null, null, 'visible');
1909         // Adding keys to table 'badge_issued'.
1910         $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
1911         $table->add_key('fk_badgeid', XMLDB_KEY_FOREIGN, array('badgeid'), 'badge', array('id'));
1912         $table->add_key('fk_userid', XMLDB_KEY_FOREIGN, array('userid'), 'user', array('id'));
1914         $table->add_index('badgeuser', XMLDB_INDEX_UNIQUE, array('badgeid', 'userid'));
1916         // Conditionally launch create table for 'badge_issued'.
1917         if (!$dbman->table_exists($table)) {
1918             $dbman->create_table($table);
1919         }
1921         // Define table 'badge_criteria_met' to be created.
1922         $table = new xmldb_table('badge_criteria_met');
1924         // Adding fields to table 'badge_criteria_met'.
1925         $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null);
1926         $table->add_field('issuedid', XMLDB_TYPE_INTEGER, '10', null, null, null, null, 'id');
1927         $table->add_field('critid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, 'issuedid');
1928         $table->add_field('userid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, 'critid');
1929         $table->add_field('datemet', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, 'userid');
1931         // Adding keys to table 'badge_criteria_met'
1932         $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
1933         $table->add_key('fk_critid', XMLDB_KEY_FOREIGN, array('critid'), 'badge_criteria', array('id'));
1934         $table->add_key('fk_userid', XMLDB_KEY_FOREIGN, array('userid'), 'user', array('id'));
1935         $table->add_key('fk_issuedid', XMLDB_KEY_FOREIGN, array('issuedid'), 'badge_issued', array('id'));
1937         // Conditionally launch create table for 'badge_criteria_met'.
1938         if (!$dbman->table_exists($table)) {
1939             $dbman->create_table($table);
1940         }
1942         // Define table 'badge_manual_award' to be created.
1943         $table = new xmldb_table('badge_manual_award');
1945         // Adding fields to table 'badge_manual_award'.
1946         $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null);
1947         $table->add_field('badgeid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, 'id');
1948         $table->add_field('recipientid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, 'badgeid');
1949         $table->add_field('issuerid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, 'recipientid');
1950         $table->add_field('issuerrole', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, 'issuerid');
1951         $table->add_field('datemet', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, 'issuerrole');
1953         // Adding keys to table 'badge_manual_award'.
1954         $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
1955         $table->add_key('fk_badgeid', XMLDB_KEY_FOREIGN, array('badgeid'), 'badge', array('id'));
1956         $table->add_key('fk_recipientid', XMLDB_KEY_FOREIGN, array('recipientid'), 'user', array('id'));
1957         $table->add_key('fk_issuerid', XMLDB_KEY_FOREIGN, array('issuerid'), 'user', array('id'));
1958         $table->add_key('fk_issuerrole', XMLDB_KEY_FOREIGN, array('issuerrole'), 'role', array('id'));
1960         // Conditionally launch create table for 'badge_manual_award'.
1961         if (!$dbman->table_exists($table)) {
1962             $dbman->create_table($table);
1963         }
1965         // Define table 'badge_backpack' to be created.
1966         $table = new xmldb_table('badge_backpack');
1968         // Adding fields to table 'badge_backpack'.
1969         $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null);
1970         $table->add_field('userid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0', 'id');
1971         $table->add_field('email', XMLDB_TYPE_CHAR, '100', null, XMLDB_NOTNULL, null, null, 'userid');
1972         $table->add_field('backpackurl', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, 'email');
1973         $table->add_field('backpackuid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, 'backpackurl');
1974         $table->add_field('backpackgid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, 'backpackuid');
1975         $table->add_field('autosync', XMLDB_TYPE_INTEGER, '1', null, XMLDB_NOTNULL, null, '0', 'backpackgid');
1976         $table->add_field('password', XMLDB_TYPE_CHAR, '50', null, null, null, null, 'autosync');
1978         // Adding keys to table 'badge_backpack'.
1979         $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
1980         $table->add_key('fk_userid', XMLDB_KEY_FOREIGN, array('userid'), 'user', array('id'));
1982         // Conditionally launch create table for 'badge_backpack'.
1983         if (!$dbman->table_exists($table)) {
1984             $dbman->create_table($table);
1985         }
1987         // Main savepoint reached.
1988         upgrade_main_savepoint(true, 2013040200.00);
1989     }
1991     if ($oldversion < 2013040201.00) {
1992         // Convert name field in event table to text type as RFC-2445 doesn't have any limitation on it.
1993         $table = new xmldb_table('event');
1994         $field = new xmldb_field('name', XMLDB_TYPE_TEXT, null, null, XMLDB_NOTNULL, null, null);
1995         if ($dbman->field_exists($table, $field)) {
1996             $dbman->change_field_type($table, $field);
1997         }
1998         // Main savepoint reached.
1999         upgrade_main_savepoint(true, 2013040201.00);
2000     }
2002     if ($oldversion < 2013040300.01) {
2004         // Define field completionstartonenrol to be dropped from course.
2005         $table = new xmldb_table('course');
2006         $field = new xmldb_field('completionstartonenrol');
2008         // Conditionally launch drop field completionstartonenrol.
2009         if ($dbman->field_exists($table, $field)) {
2010             $dbman->drop_field($table, $field);
2011         }
2013         // Since structure of 'course' table has changed we need to re-read $SITE from DB.
2014         $SITE = $DB->get_record('course', array('id' => $SITE->id));
2015         $COURSE = clone($SITE);
2017         // Main savepoint reached.
2018         upgrade_main_savepoint(true, 2013040300.01);
2019     }
2021     if ($oldversion < 2013041200.00) {
2022         // MDL-29877 Some bad restores created grade items with no category information.
2023         $sql = "UPDATE {grade_items}
2024                    SET categoryid = courseid
2025                  WHERE itemtype <> 'course' and itemtype <> 'category'
2026                        AND categoryid IS NULL";
2027         $DB->execute($sql);
2028         upgrade_main_savepoint(true, 2013041200.00);
2029     }
2031     if ($oldversion < 2013041600.00) {
2032         // Copy constants from /course/lib.php instead of including the whole library:
2033         $c = array( 'FRONTPAGENEWS'                 => 0,
2034                     'FRONTPAGECOURSELIST'           => 1,
2035                     'FRONTPAGECATEGORYNAMES'        => 2,
2036                     'FRONTPAGETOPICONLY'            => 3,
2037                     'FRONTPAGECATEGORYCOMBO'        => 4,
2038                     'FRONTPAGEENROLLEDCOURSELIST'   => 5,
2039                     'FRONTPAGEALLCOURSELIST'        => 6,
2040                     'FRONTPAGECOURSESEARCH'         => 7);
2041         // Update frontpage settings $CFG->frontpage and $CFG->frontpageloggedin. In 2.4 there was too much of hidden logic about them.
2042         // This script tries to make sure that with the new (more user-friendly) frontpage settings the frontpage looks as similar as possible to what it was before upgrade.
2043         $ncourses = $DB->count_records('course');
2044         foreach (array('frontpage', 'frontpageloggedin') as $configkey) {
2045             if ($frontpage = explode(',', $CFG->{$configkey})) {
2046                 $newfrontpage = array();
2047                 foreach ($frontpage as $v) {
2048                     switch ($v) {
2049                         case $c['FRONTPAGENEWS']:
2050                             // Not related to course listings, leave as it is.
2051                             $newfrontpage[] = $c['FRONTPAGENEWS'];
2052                             break;
2053                         case $c['FRONTPAGECOURSELIST']:
2054                             if ($configkey === 'frontpageloggedin' && empty($CFG->disablemycourses)) {
2055                                 // In 2.4 unless prohibited in config, the "list of courses" was considered "list of enrolled courses" plus course search box.
2056                                 $newfrontpage[] = $c['FRONTPAGEENROLLEDCOURSELIST'];
2057                             } else if ($ncourses <= 200) {
2058                                 // Still list of courses was only displayed in there were less than 200 courses in system. Otherwise - search box only.
2059                                 $newfrontpage[] = $c['FRONTPAGEALLCOURSELIST'];
2060                                 break; // skip adding search box
2061                             }
2062                             if (!in_array($c['FRONTPAGECOURSESEARCH'], $newfrontpage)) {
2063                                 $newfrontpage[] = $c['FRONTPAGECOURSESEARCH'];
2064                             }
2065                             break;
2066                         case $c['FRONTPAGECATEGORYNAMES']:
2067                             // In 2.4 search box was displayed automatically after categories list. In 2.5 it is displayed as a separate setting.
2068                             $newfrontpage[] = $c['FRONTPAGECATEGORYNAMES'];
2069                             if (!in_array($c['FRONTPAGECOURSESEARCH'], $newfrontpage)) {
2070                                 $newfrontpage[] = $c['FRONTPAGECOURSESEARCH'];
2071                             }
2072                             break;
2073                         case $c['FRONTPAGECATEGORYCOMBO']:
2074                             $maxcourses = empty($CFG->numcoursesincombo) ? 500 : $CFG->numcoursesincombo;
2075                             // In 2.4 combo list was not displayed if there are more than $CFG->numcoursesincombo courses in the system.
2076                             if ($ncourses < $maxcourses) {
2077                                 $newfrontpage[] = $c['FRONTPAGECATEGORYCOMBO'];
2078                             }
2079                             if (!in_array($c['FRONTPAGECOURSESEARCH'], $newfrontpage)) {
2080                                 $newfrontpage[] = $c['FRONTPAGECOURSESEARCH'];
2081                             }
2082                             break;
2083                     }
2084                 }
2085                 set_config($configkey, join(',', $newfrontpage));
2086             }
2087         }
2088         // $CFG->numcoursesincombo no longer affects whether the combo list is displayed. Setting is deprecated.
2089         unset_config('numcoursesincombo');
2091         upgrade_main_savepoint(true, 2013041600.00);
2092     }
2094     if ($oldversion < 2013041601.00) {
2095         // Create a new 'badge_external' table first.
2096         // Define table 'badge_external' to be created.
2097         $table = new xmldb_table('badge_external');
2099         // Adding fields to table 'badge_external'.
2100         $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null);
2101         $table->add_field('backpackid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, 'id');
2102         $table->add_field('collectionid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, 'backpackid');
2104         // Adding keys to table 'badge_external'.
2105         $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
2106         $table->add_key('fk_backpackid', XMLDB_KEY_FOREIGN, array('backpackid'), 'badge_backpack', array('id'));
2108         // Conditionally launch create table for 'badge_external'.
2109         if (!$dbman->table_exists($table)) {
2110             $dbman->create_table($table);
2111         }
2113         // Perform user data migration.
2114         $usercollections = $DB->get_records('badge_backpack');
2115         foreach ($usercollections as $usercollection) {
2116             $collection = new stdClass();
2117             $collection->backpackid = $usercollection->id;
2118             $collection->collectionid = $usercollection->backpackgid;
2119             $DB->insert_record('badge_external', $collection);
2120         }
2122         // Finally, drop the column.
2123         // Define field backpackgid to be dropped from 'badge_backpack'.
2124         $table = new xmldb_table('badge_backpack');
2125         $field = new xmldb_field('backpackgid');
2127         // Conditionally launch drop field backpackgid.
2128         if ($dbman->field_exists($table, $field)) {
2129             $dbman->drop_field($table, $field);
2130         }
2132         // Main savepoint reached.
2133         upgrade_main_savepoint(true, 2013041601.00);
2134     }
2136     if ($oldversion < 2013041601.01) {
2137         // Changing the default of field descriptionformat on table user to 1.
2138         $table = new xmldb_table('user');
2139         $field = new xmldb_field('descriptionformat', XMLDB_TYPE_INTEGER, '2', null, XMLDB_NOTNULL, null, '1', 'description');
2141         // Launch change of default for field descriptionformat.
2142         $dbman->change_field_default($table, $field);
2144         // Main savepoint reached.
2145         upgrade_main_savepoint(true, 2013041601.01);
2146     }
2148     if ($oldversion < 2013041900.00) {
2149         require_once($CFG->dirroot . '/cache/locallib.php');
2150         // The features bin needs updating.
2151         cache_config_writer::update_default_config_stores();
2152         // Main savepoint reached.
2153         upgrade_main_savepoint(true, 2013041900.00);
2154     }
2156     if ($oldversion < 2013042300.00) {
2157         // Adding index to unreadmessageid field of message_working table (MDL-34933)
2158         $table = new xmldb_table('message_working');
2159         $index = new xmldb_index('unreadmessageid_idx', XMLDB_INDEX_NOTUNIQUE, array('unreadmessageid'));
2161         // Conditionally launch add index unreadmessageid
2162         if (!$dbman->index_exists($table, $index)) {
2163             $dbman->add_index($table, $index);
2164         }
2166         // Main savepoint reached.
2167         upgrade_main_savepoint(true, 2013042300.00);
2168     }
2170     // Moodle v2.5.0 release upgrade line.
2171     // Put any upgrade step following this.
2173     if ($oldversion < 2013051400.01) {
2174         // Fix incorrect cc-nc url. Unfortunately the license 'plugins' do
2175         // not give a mechanism to do this.
2177         $sql = "UPDATE {license}
2178                    SET source = :url, version = :newversion
2179                  WHERE shortname = :shortname AND version = :oldversion";
2181         $params = array(
2182             'url' => 'http://creativecommons.org/licenses/by-nc/3.0/',
2183             'shortname' => 'cc-nc',
2184             'newversion' => '2013051500',
2185             'oldversion' => '2010033100'
2186         );
2188         $DB->execute($sql, $params);
2190         // Main savepoint reached.
2191         upgrade_main_savepoint(true, 2013051400.01);
2192     }
2194     if ($oldversion < 2013061400.01) {
2195         // Clean up old tokens which haven't been deleted.
2196         $DB->execute("DELETE FROM {user_private_key} WHERE NOT EXISTS
2197                          (SELECT 'x' FROM {user} WHERE deleted = 0 AND id = userid)");
2199         // Main savepoint reached.
2200         upgrade_main_savepoint(true, 2013061400.01);
2201     }
2203     if ($oldversion < 2013061700.00) {
2204         // MDL-40103: Remove unused template tables from the database.
2205         // These are now created inline with xmldb_table.
2207         $tablestocleanup = array('temp_enroled_template','temp_log_template','backup_files_template','backup_ids_template');
2208         $dbman = $DB->get_manager();
2210         foreach ($tablestocleanup as $table) {
2211             $xmltable = new xmldb_table($table);
2212             if ($dbman->table_exists($xmltable)) {
2213                 $dbman->drop_table($xmltable);
2214             }
2215         }
2217         // Main savepoint reached.
2218         upgrade_main_savepoint(true, 2013061700.00);
2219     }
2221     if ($oldversion < 2013070800.00) {
2223         // Remove orphan repository instances.
2224         if ($DB->get_dbfamily() === 'mysql') {
2225             $sql = "DELETE {repository_instances} FROM {repository_instances}
2226                     LEFT JOIN {context} ON {context}.id = {repository_instances}.contextid
2227                     WHERE {context}.id IS NULL";
2228         } else {
2229             $sql = "DELETE FROM {repository_instances}
2230                     WHERE NOT EXISTS (
2231                         SELECT 'x' FROM {context}
2232                         WHERE {context}.id = {repository_instances}.contextid)";
2233         }
2234         $DB->execute($sql);
2236         // Main savepoint reached.
2237         upgrade_main_savepoint(true, 2013070800.00);
2238     }
2240     if ($oldversion < 2013070800.01) {
2242         // Define field lastnamephonetic to be added to user.
2243         $table = new xmldb_table('user');
2244         $field = new xmldb_field('lastnamephonetic', XMLDB_TYPE_CHAR, '255', null, null, null, null, 'imagealt');
2245         $index = new xmldb_index('lastnamephonetic', XMLDB_INDEX_NOTUNIQUE, array('lastnamephonetic'));
2247         // Conditionally launch add field lastnamephonetic.
2248         if (!$dbman->field_exists($table, $field)) {
2249             $dbman->add_field($table, $field);
2250             $dbman->add_index($table, $index);
2251         }
2253         // Define field firstnamephonetic to be added to user.
2254         $table = new xmldb_table('user');
2255         $field = new xmldb_field('firstnamephonetic', XMLDB_TYPE_CHAR, '255', null, null, null, null, 'lastnamephonetic');
2256         $index = new xmldb_index('firstnamephonetic', XMLDB_INDEX_NOTUNIQUE, array('firstnamephonetic'));
2258         // Conditionally launch add field firstnamephonetic.
2259         if (!$dbman->field_exists($table, $field)) {
2260             $dbman->add_field($table, $field);
2261             $dbman->add_index($table, $index);
2262         }
2264         // Define field alternatename to be added to user.
2265         $table = new xmldb_table('user');
2266         $field = new xmldb_field('middlename', XMLDB_TYPE_CHAR, '255', null, null, null, null, 'firstnamephonetic');
2267         $index = new xmldb_index('middlename', XMLDB_INDEX_NOTUNIQUE, array('middlename'));
2269         // Conditionally launch add field firstnamephonetic.
2270         if (!$dbman->field_exists($table, $field)) {
2271             $dbman->add_field($table, $field);
2272             $dbman->add_index($table, $index);
2273         }
2275         // Define field alternatename to be added to user.
2276         $table = new xmldb_table('user');
2277         $field = new xmldb_field('alternatename', XMLDB_TYPE_CHAR, '255', null, null, null, null, 'middlename');
2278         $index = new xmldb_index('alternatename', XMLDB_INDEX_NOTUNIQUE, array('alternatename'));
2280         // Conditionally launch add field alternatename.
2281         if (!$dbman->field_exists($table, $field)) {
2282             $dbman->add_field($table, $field);
2283             $dbman->add_index($table, $index);
2284         }
2286         // Main savepoint reached.
2287         upgrade_main_savepoint(true, 2013070800.01);
2288     }
2290     if ($oldversion < 2013071500.01) {
2291         // The enrol_authorize plugin has been removed, if there are no records
2292         // and no plugin files then remove the plugin data.
2293         $enrolauthorize = new xmldb_table('enrol_authorize');
2294         $enrolauthorizerefunds = new xmldb_table('enrol_authorize_refunds');
2296         if (!file_exists($CFG->dirroot.'/enrol/authorize/version.php') &&
2297             $dbman->table_exists($enrolauthorize) &&
2298             $dbman->table_exists($enrolauthorizerefunds)) {
2300             $enrolauthorizecount = $DB->count_records('enrol_authorize');
2301             $enrolauthorizerefundcount = $DB->count_records('enrol_authorize_refunds');
2303             if (empty($enrolauthorizecount) && empty($enrolauthorizerefundcount)) {
2305                 // Drop the database tables.
2306                 $dbman->drop_table($enrolauthorize);
2307                 $dbman->drop_table($enrolauthorizerefunds);
2309                 // Drop the message provider and associated data manually.
2310                 $DB->delete_records('message_providers', array('component' => 'enrol_authorize'));
2311                 $DB->delete_records_select('config_plugins', "plugin = 'message' AND ".$DB->sql_like('name', '?', false), array("%_provider_enrol_authorize_%"));
2312                 $DB->delete_records_select('user_preferences', $DB->sql_like('name', '?', false), array("message_provider_enrol_authorize_%"));
2314                 // Remove capabilities.
2315                 capabilities_cleanup('enrol_authorize');
2317                 // Remove all other associated config.
2318                 unset_all_config_for_plugin('enrol_authorize');
2319             }
2320         }
2321         upgrade_main_savepoint(true, 2013071500.01);
2322     }
2324     if ($oldversion < 2013071500.02) {
2325         // Define field attachment to be dropped from badge.
2326         $table = new xmldb_table('badge');
2327         $field = new xmldb_field('image');
2329         // Conditionally launch drop field eventtype.
2330         if ($dbman->field_exists($table, $field)) {
2331             $dbman->drop_field($table, $field);
2332         }
2334         upgrade_main_savepoint(true, 2013071500.02);
2335     }
2337     if ($oldversion < 2013072600.01) {
2338         upgrade_mssql_nvarcharmax();
2339         upgrade_mssql_varbinarymax();
2341         upgrade_main_savepoint(true, 2013072600.01);
2342     }
2344     if ($oldversion < 2013081200.00) {
2345         // Define field uploadfiles to be added to external_services.
2346         $table = new xmldb_table('external_services');
2347         $field = new xmldb_field('uploadfiles', XMLDB_TYPE_INTEGER, '1', null, XMLDB_NOTNULL, null, '0', 'downloadfiles');
2349         // Conditionally launch add field uploadfiles.
2350         if (!$dbman->field_exists($table, $field)) {
2351             $dbman->add_field($table, $field);
2352         }
2354         // Main savepoint reached.
2355         upgrade_main_savepoint(true, 2013081200.00);
2356     }
2358     if ($oldversion < 2013082300.01) {
2359         // Define the table 'backup_logs' and the field 'message' which we will be changing from a char to a text field.
2360         $table = new xmldb_table('backup_logs');
2361         $field = new xmldb_field('message', XMLDB_TYPE_TEXT, null, null, XMLDB_NOTNULL, null, null, 'loglevel');
2363         // Perform the change.
2364         $dbman->change_field_type($table, $field);
2366         // Main savepoint reached.
2367         upgrade_main_savepoint(true, 2013082300.01);
2368     }
2370     // Convert SCORM course format courses to singleactivity.
2371     if ($oldversion < 2013082700.00) {
2372         // First set relevant singleactivity settings.
2373         $formatoptions = new stdClass();
2374         $formatoptions->format = 'singleactivity';
2375         $formatoptions->sectionid = 0;
2376         $formatoptions->name = 'activitytype';
2377         $formatoptions->value = 'scorm';
2379         $courses = $DB->get_recordset('course', array('format' => 'scorm'), 'id');
2380         foreach ($courses as $course) {
2381             $formatoptions->courseid = $course->id;
2382             $DB->insert_record('course_format_options', $formatoptions);
2383         }
2384         $courses->close();
2386         // Now update course format for these courses.
2387         $sql = "UPDATE {course}
2388                    SET format = 'singleactivity', modinfo = '', sectioncache = ''
2389                  WHERE format = 'scorm'";
2390         $DB->execute($sql);
2391         upgrade_main_savepoint(true, 2013082700.00);
2392     }
2394     if ($oldversion < 2013090500.01) {
2395         // Define field calendartype to be added to course.
2396         $table = new xmldb_table('course');
2397         $field = new xmldb_field('calendartype', XMLDB_TYPE_CHAR, '30', null, XMLDB_NOTNULL, null, null);
2399         // Conditionally launch add field calendartype.
2400         if (!$dbman->field_exists($table, $field)) {
2401             $dbman->add_field($table, $field);
2402         }
2404         // Since structure of 'course' table has changed we need to re-read $SITE from DB.
2405         $SITE = $DB->get_record('course', array('id' => $SITE->id));
2406         $COURSE = clone($SITE);
2408         // Define field calendartype to be added to user.
2409         $table = new xmldb_table('user');
2410         $field = new xmldb_field('calendartype', XMLDB_TYPE_CHAR, '30', null, XMLDB_NOTNULL, null, 'gregorian');
2412         // Conditionally launch add field calendartype.
2413         if (!$dbman->field_exists($table, $field)) {
2414             $dbman->add_field($table, $field);
2415         }
2417         // Main savepoint reached.
2418         upgrade_main_savepoint(true, 2013090500.01);
2419     }
2421     if ($oldversion < 2013091000.02) {
2423         // Define field cacherev to be added to course.
2424         $table = new xmldb_table('course');
2425         $field = new xmldb_field('cacherev', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0', 'completionnotify');
2427         // Conditionally launch add field cacherev.
2428         if (!$dbman->field_exists($table, $field)) {
2429             $dbman->add_field($table, $field);
2430         }
2432         // Since structure of 'course' table has changed we need to re-read $SITE from DB.
2433         $SITE = $DB->get_record('course', array('id' => $SITE->id));
2434         $COURSE = clone($SITE);
2436         // Main savepoint reached.
2437         upgrade_main_savepoint(true, 2013091000.02);
2438     }
2440     if ($oldversion < 2013091000.03) {
2442         // Define field modinfo to be dropped from course.
2443         $table = new xmldb_table('course');
2444         $field = new xmldb_field('modinfo');
2446         // Conditionally launch drop field modinfo.
2447         if ($dbman->field_exists($table, $field)) {
2448             $dbman->drop_field($table, $field);
2449         }
2451         // Define field sectioncache to be dropped from course.
2452         $field = new xmldb_field('sectioncache');
2454         // Conditionally launch drop field sectioncache.
2455         if ($dbman->field_exists($table, $field)) {
2456             $dbman->drop_field($table, $field);
2457         }
2459         // Since structure of 'course' table has changed we need to re-read $SITE from DB.
2460         $SITE = $DB->get_record('course', array('id' => $SITE->id));
2461         $COURSE = clone($SITE);
2463         // Main savepoint reached.
2464         upgrade_main_savepoint(true, 2013091000.03);
2465     }
2467     if ($oldversion < 2013091300.01) {
2469         $table = new xmldb_table('user');
2471         // Changing precision of field institution on table user to (255).
2472         $field = new xmldb_field('institution', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, 'phone2');
2474         // Launch change of precision for field institution.
2475         $dbman->change_field_precision($table, $field);
2477         // Changing precision of field department on table user to (255).
2478         $field = new xmldb_field('department', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, 'institution');
2480         // Launch change of precision for field department.
2481         $dbman->change_field_precision($table, $field);
2483         // Changing precision of field address on table user to (255).
2484         $field = new xmldb_field('address', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, 'department');
2486         // Launch change of precision for field address.
2487         $dbman->change_field_precision($table, $field);
2489         // Main savepoint reached.
2490         upgrade_main_savepoint(true, 2013091300.01);
2491     }
2493     if ($oldversion < 2013092000.01) {
2495         // Define table question_statistics to be created.
2496         $table = new xmldb_table('question_statistics');
2498         // Adding fields to table question_statistics.
2499         $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
2500         $table->add_field('hashcode', XMLDB_TYPE_CHAR, '40', null, XMLDB_NOTNULL, null, null);
2501         $table->add_field('timemodified', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null);
2502         $table->add_field('questionid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null);
2503         $table->add_field('slot', XMLDB_TYPE_INTEGER, '10', null, null, null, null);
2504         $table->add_field('subquestion', XMLDB_TYPE_INTEGER, '4', null, XMLDB_NOTNULL, null, null);
2505         $table->add_field('s', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0');
2506         $table->add_field('effectiveweight', XMLDB_TYPE_NUMBER, '15, 5', null, null, null, null);
2507         $table->add_field('negcovar', XMLDB_TYPE_INTEGER, '2', null, XMLDB_NOTNULL, null, '0');
2508         $table->add_field('discriminationindex', XMLDB_TYPE_NUMBER, '15, 5', null, null, null, null);
2509         $table->add_field('discriminativeefficiency', XMLDB_TYPE_NUMBER, '15, 5', null, null, null, null);
2510         $table->add_field('sd', XMLDB_TYPE_NUMBER, '15, 10', null, null, null, null);
2511         $table->add_field('facility', XMLDB_TYPE_NUMBER, '15, 10', null, null, null, null);
2512         $table->add_field('subquestions', XMLDB_TYPE_TEXT, null, null, null, null, null);
2513         $table->add_field('maxmark', XMLDB_TYPE_NUMBER, '12, 7', null, null, null, null);
2514         $table->add_field('positions', XMLDB_TYPE_TEXT, null, null, null, null, null);
2515         $table->add_field('randomguessscore', XMLDB_TYPE_NUMBER, '12, 7', null, null, null, null);
2517         // Adding keys to table question_statistics.
2518         $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
2520         // Conditionally launch create table for question_statistics.
2521         if (!$dbman->table_exists($table)) {
2522             $dbman->create_table($table);
2523         }
2525         // Define table question_response_analysis to be created.
2526         $table = new xmldb_table('question_response_analysis');
2528         // Adding fields to table question_response_analysis.
2529         $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
2530         $table->add_field('hashcode', XMLDB_TYPE_CHAR, '40', null, XMLDB_NOTNULL, null, null);
2531         $table->add_field('timemodified', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null);
2532         $table->add_field('questionid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null);
2533         $table->add_field('subqid', XMLDB_TYPE_CHAR, '100', null, XMLDB_NOTNULL, null, null);
2534         $table->add_field('aid', XMLDB_TYPE_CHAR, '100', null, null, null, null);
2535         $table->add_field('response', XMLDB_TYPE_TEXT, null, null, null, null, null);
2536         $table->add_field('rcount', XMLDB_TYPE_INTEGER, '10', null, null, null, null);
2537         $table->add_field('credit', XMLDB_TYPE_NUMBER, '15, 5', null, XMLDB_NOTNULL, null, null);
2539         // Adding keys to table question_response_analysis.
2540         $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
2542         // Conditionally launch create table for question_response_analysis.
2543         if (!$dbman->table_exists($table)) {
2544             $dbman->create_table($table);
2545         }
2547         // Main savepoint reached.
2548         upgrade_main_savepoint(true, 2013092000.01);
2549     }
2551     if ($oldversion < 2013092001.01) {
2552         // Force uninstall of deleted tool.
2553         if (!file_exists("$CFG->dirroot/$CFG->admin/tool/bloglevelupgrade")) {
2554             // Remove capabilities.
2555             capabilities_cleanup('tool_bloglevelupgrade');
2556             // Remove all other associated config.
2557             unset_all_config_for_plugin('tool_bloglevelupgrade');
2558         }
2559         upgrade_main_savepoint(true, 2013092001.01);
2560     }
2562     if ($oldversion < 2013092001.02) {
2563         // Define field version to be dropped from modules.
2564         $table = new xmldb_table('modules');
2565         $field = new xmldb_field('version');
2567         // Conditionally launch drop field version.
2568         if ($dbman->field_exists($table, $field)) {
2569             // Migrate all plugin version info to config_plugins table.
2570             $modules = $DB->get_records('modules');
2571             foreach ($modules as $module) {
2572                 set_config('version', $module->version, 'mod_'.$module->name);
2573             }
2574             unset($modules);
2576             $dbman->drop_field($table, $field);
2577         }
2579         // Define field version to be dropped from block.
2580         $table = new xmldb_table('block');
2581         $field = new xmldb_field('version');
2583         // Conditionally launch drop field version.
2584         if ($dbman->field_exists($table, $field)) {
2585             $blocks = $DB->get_records('block');
2586             foreach ($blocks as $block) {
2587                 set_config('version', $block->version, 'block_'.$block->name);
2588             }
2589             unset($blocks);
2591             $dbman->drop_field($table, $field);
2592         }
2594         // Main savepoint reached.
2595         upgrade_main_savepoint(true, 2013092001.02);
2596     }
2598     if ($oldversion < 2013092700.01) {
2600         $table = new xmldb_table('files');
2602         // Define field referencelastsync to be dropped from files.
2603         $field = new xmldb_field('referencelastsync');
2605         // Conditionally launch drop field referencelastsync.
2606         if ($dbman->field_exists($table, $field)) {
2607             $dbman->drop_field($table, $field);
2608         }
2610         // Define field referencelifetime to be dropped from files.
2611         $field = new xmldb_field('referencelifetime');
2613         // Conditionally launch drop field referencelifetime.
2614         if ($dbman->field_exists($table, $field)) {
2615             $dbman->drop_field($table, $field);
2616         }
2618         // Main savepoint reached.
2619         upgrade_main_savepoint(true, 2013092700.01);
2620     }
2622     if ($oldversion < 2013100400.01) {
2623         // Add user_devices core table.
2625         // Define field id to be added to user_devices.
2626         $table = new xmldb_table('user_devices');
2628         $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null);
2629         $table->add_field('userid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0', 'id');
2630         $table->add_field('appid', XMLDB_TYPE_CHAR, '128', null, XMLDB_NOTNULL, null, null, 'userid');
2631         $table->add_field('name', XMLDB_TYPE_CHAR, '32', null, XMLDB_NOTNULL, null, null, 'appid');
2632         $table->add_field('model', XMLDB_TYPE_CHAR, '32', null, XMLDB_NOTNULL, null, null, 'name');
2633         $table->add_field('platform', XMLDB_TYPE_CHAR, '32', null, XMLDB_NOTNULL, null, null, 'model');
2634         $table->add_field('version', XMLDB_TYPE_CHAR, '32', null, XMLDB_NOTNULL, null, null, 'platform');
2635         $table->add_field('pushid', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, 'version');
2636         $table->add_field('uuid', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, 'pushid');
2637         $table->add_field('timecreated', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, 'uuid');
2638         $table->add_field('timemodified', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, 'timecreated');
2640         $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
2641         $table->add_key('pushid-userid', XMLDB_KEY_UNIQUE, array('pushid', 'userid'));
2642         $table->add_key('pushid-platform', XMLDB_KEY_UNIQUE, array('pushid', 'platform'));
2643         $table->add_key('userid', XMLDB_KEY_FOREIGN, array('userid'), 'user', array('id'));
2645         if (!$dbman->table_exists($table)) {
2646             $dbman->create_table($table);
2647         }
2649         // Main savepoint reached.
2650         upgrade_main_savepoint(true, 2013100400.01);
2651     }
2653     if ($oldversion < 2013100800.00) {
2655         // Define field maxfraction to be added to question_attempts.
2656         $table = new xmldb_table('question_attempts');
2657         $field = new xmldb_field('maxfraction', XMLDB_TYPE_NUMBER, '12, 7', null, XMLDB_NOTNULL, null, '1', 'minfraction');
2659         // Conditionally launch add field maxfraction.
2660         if (!$dbman->field_exists($table, $field)) {
2661             $dbman->add_field($table, $field);
2662         }
2664         // Main savepoint reached.
2665         upgrade_main_savepoint(true, 2013100800.00);
2666     }
2668     if ($oldversion < 2013100800.01) {
2669         // Create a new 'user_password_resets' table.
2670         $table = new xmldb_table('user_password_resets');
2671         $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null);
2672         $table->add_field('userid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, null);
2673         $table->add_field('timerequested', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, null);
2674         $table->add_field('timererequested', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, 0, null);
2675         $table->add_field('token', XMLDB_TYPE_CHAR, '32', null, XMLDB_NOTNULL, null, null, null);
2677         // Adding keys to table.
2678         $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
2679         $table->add_key('fk_userid', XMLDB_KEY_FOREIGN, array('userid'), 'user', array('id'));
2681         // Conditionally launch create table.
2682         if (!$dbman->table_exists($table)) {
2683             $dbman->create_table($table);
2684         }
2685         upgrade_main_savepoint(true, 2013100800.01);
2686     }
2688     if ($oldversion < 2013100800.02) {
2689         $sql = "INSERT INTO {user_preferences}(userid, name, value)
2690                 SELECT id, 'htmleditor', 'textarea' FROM {user} u where u.htmleditor = 0";
2691         $DB->execute($sql);
2693         // Define field htmleditor to be dropped from user
2694         $table = new xmldb_table('user');
2695         $field = new xmldb_field('htmleditor');
2697         // Conditionally launch drop field requested
2698         if ($dbman->field_exists($table, $field)) {
2699             $dbman->drop_field($table, $field);
2700         }
2701         // Main savepoint reached.
2702         upgrade_main_savepoint(true, 2013100800.02);
2703     }
2705     if ($oldversion < 2013100900.00) {
2707         // Define field lifetime to be dropped from files_reference.
2708         $table = new xmldb_table('files_reference');
2709         $field = new xmldb_field('lifetime');
2711         // Conditionally launch drop field lifetime.
2712         if ($dbman->field_exists($table, $field)) {
2713             $dbman->drop_field($table, $field);
2714         }
2716         // Main savepoint reached.
2717         upgrade_main_savepoint(true, 2013100900.00);
2718     }
2720     if ($oldversion < 2013100901.00) {
2721         // Fixing possible wrong MIME type for Java Network Launch Protocol (JNLP) files.
2722         $select = $DB->sql_like('filename', '?', false);
2723         $DB->set_field_select(
2724             'files',
2725             'mimetype',
2726             'application/x-java-jnlp-file',
2727             $select,
2728             array('%.jnlp')
2729         );
2731         // Main savepoint reached.
2732         upgrade_main_savepoint(true, 2013100901.00);
2733     }
2735     if ($oldversion < 2013102100.00) {
2736         // Changing default value for the status of a course backup.
2737         $table = new xmldb_table('backup_courses');
2738         $field = new xmldb_field('laststatus', XMLDB_TYPE_CHAR, '1', null, XMLDB_NOTNULL, null, '5', 'lastendtime');
2740         // Launch change of precision for field value
2741         $dbman->change_field_precision($table, $field);
2743         // Main savepoint reached.
2744         upgrade_main_savepoint(true, 2013102100.00);
2745     }
2747     if ($oldversion < 2013102201.00) {
2748         $params = array('plugin' => 'editor_atto', 'name' => 'version');
2749         $attoversion = $DB->get_record('config_plugins',
2750                                        $params,
2751                                        'value',
2752                                        IGNORE_MISSING);
2754         if ($attoversion) {
2755             $attoversion = floatval($attoversion->value);
2756         }
2757         // Only these versions that were part of 2.6 beta should be removed.
2758         // Manually installed versions of 2.5 - or later releases for 2.6 installed
2759         // via the plugins DB should not be uninstalled.
2760         if ($attoversion && $attoversion > 2013051500.00 && $attoversion < 2013102201.00) {
2761             // Remove all other associated config.
2762             unset_all_config_for_plugin('editor_atto');
2763             unset_all_config_for_plugin('atto_bold');
2764             unset_all_config_for_plugin('atto_clear');
2765             unset_all_config_for_plugin('atto_html');
2766             unset_all_config_for_plugin('atto_image');
2767             unset_all_config_for_plugin('atto_indent');
2768             unset_all_config_for_plugin('atto_italic');
2769             unset_all_config_for_plugin('atto_link');
2770             unset_all_config_for_plugin('atto_media');
2771             unset_all_config_for_plugin('atto_orderedlist');
2772             unset_all_config_for_plugin('atto_outdent');
2773             unset_all_config_for_plugin('atto_strike');
2774             unset_all_config_for_plugin('atto_title');
2775             unset_all_config_for_plugin('atto_underline');
2776             unset_all_config_for_plugin('atto_unlink');
2777             unset_all_config_for_plugin('atto_unorderedlist');
2779         }
2781         // Main savepoint reached.
2782         upgrade_main_savepoint(true, 2013102201.00);
2783     }
2785     if ($oldversion < 2013102500.01) {
2786         // Find all fileareas that have missing root folder entry and add the root folder entry.
2787         if (empty($CFG->filesrootrecordsfixed)) {
2788             $sql = "SELECT distinct f1.contextid, f1.component, f1.filearea, f1.itemid
2789                 FROM {files} f1 left JOIN {files} f2
2790                     ON f1.contextid = f2.contextid
2791                     AND f1.component = f2.component
2792                     AND f1.filearea = f2.filearea
2793                     AND f1.itemid = f2.itemid
2794                     AND f2.filename = '.'
2795                     AND f2.filepath = '/'
2796                 WHERE (f1.component <> 'user' or f1.filearea <> 'draft')
2797                 and f2.id is null";
2798             $rs = $DB->get_recordset_sql($sql);
2799             $defaults = array('filepath' => '/',
2800                             'filename' => '.',
2801                             'userid' => $USER->id,
2802                             'filesize' => 0,
2803                             'timecreated' => time(),
2804                             'timemodified' => time(),
2805                             'contenthash' => sha1(''));
2806             foreach ($rs as $r) {
2807                 $pathhash = sha1("/$r->contextid/$r->component/$r->filearea/$r->itemid".'/.');
2808                 $DB->insert_record('files', (array)$r + $defaults +
2809                         array('pathnamehash' => $pathhash));
2810             }
2811             $rs->close();
2812             // To skip running the same script on the upgrade to the next major release.
2813             set_config('filesrootrecordsfixed', 1);
2814         }
2816         // Main savepoint reached.
2817         upgrade_main_savepoint(true, 2013102500.01);
2818     }
2820     if ($oldversion < 2013110500.01) {
2821         // MDL-38228. Corrected course_modules upgrade script instead of 2013021801.01.
2823         // This upgrade script fixes the mismatches between DB fields course_modules.section
2824         // and course_sections.sequence. It makes sure that each module is included
2825         // in the sequence of at least one section.
2826         // There is also a separate script for admins: admin/cli/fix_course_sortorder.php
2828         // This script in included in each major version upgrade process so make sure we don't run it twice.
2829         if (empty($CFG->movingmoduleupgradescriptwasrun)) {
2830             upgrade_course_modules_sequences();
2832             // To skip running the same script on the upgrade to the next major release.
2833             set_config('movingmoduleupgradescriptwasrun', 1);
2834         }
2836         // Main savepoint reached.
2837         upgrade_main_savepoint(true, 2013110500.01);
2838     }
2840     if ($oldversion < 2013110600.01) {
2842         if (!file_exists($CFG->dirroot . '/theme/mymobile')) {
2843             // Replace the mymobile settings.
2844             $DB->set_field('course', 'theme', 'clean', array('theme' => 'mymobile'));
2845             $DB->set_field('course_categories', 'theme', 'clean', array('theme' => 'mymobile'));
2846             $DB->set_field('user', 'theme', 'clean', array('theme' => 'mymobile'));
2847             $DB->set_field('mnet_host', 'theme', 'clean', array('theme' => 'mymobile'));
2849             // Replace the theme configs.
2850             if (get_config('core', 'theme') === 'mymobile') {
2851                 set_config('theme', 'clean');
2852             }
2853             if (get_config('core', 'thememobile') === 'mymobile') {
2854                 set_config('thememobile', 'clean');
2855             }
2856             if (get_config('core', 'themelegacy') === 'mymobile') {
2857                 set_config('themelegacy', 'clean');
2858             }
2859             if (get_config('core', 'themetablet') === 'mymobile') {
2860                 set_config('themetablet', 'clean');
2861             }
2863             // Hacky emulation of plugin uninstallation.
2864             unset_all_config_for_plugin('theme_mymobile');
2865         }
2867         // Main savepoint reached.
2868         upgrade_main_savepoint(true, 2013110600.01);
2869     }
2871     if ($oldversion < 2013110600.02) {
2873         // If the user is logged in, we ensure that the alternate name fields are present
2874         // in the session. It will not be the case when upgrading from 2.5 downwards.
2875         if (!empty($USER->id)) {
2876             $refreshuser = $DB->get_record('user', array('id' => $USER->id));
2877             $fields = array('firstnamephonetic', 'lastnamephonetic', 'middlename', 'alternatename', 'firstname', 'lastname');
2878             foreach ($fields as $field) {
2879                 $USER->{$field} = $refreshuser->{$field};
2880             }
2881         }
2883         // Main savepoint reached.
2884         upgrade_main_savepoint(true, 2013110600.02);
2885     }
2887     // Moodle v2.6.0 release upgrade line.
2888     // Put any upgrade step following this.
2889     if ($oldversion < 2013111800.01) {
2891         // Delete notes of deleted courses.
2892         $sql = "DELETE FROM {post}
2893                  WHERE NOT EXISTS (SELECT {course}.id FROM {course}
2894                                     WHERE {course}.id = {post}.courseid)
2895                        AND {post}.module = ?";
2896         $DB->execute($sql, array('notes'));
2898         // Main savepoint reached.
2899         upgrade_main_savepoint(true, 2013111800.01);
2900     }
2902     if ($oldversion < 2013122400.01) {
2903         // Purge stored passwords from config_log table, ideally this should be in each plugin
2904         // but that would complicate backporting...
2905         $items = array(
2906             'core/cronremotepassword', 'core/proxypassword', 'core/smtppass', 'core/jabberpassword',
2907             'enrol_database/dbpass', 'enrol_ldap/bind_pw', 'url/secretphrase');
2908         foreach ($items as $item) {
2909             list($plugin, $name) = explode('/', $item);
2910             $sqlcomparevalue =  $DB->sql_compare_text('value');
2911             $sqlcompareoldvalue = $DB->sql_compare_text('oldvalue');
2912             if ($plugin === 'core') {
2913                 $sql = "UPDATE {config_log}
2914                            SET value = :value
2915                          WHERE name = :name AND plugin IS NULL AND $sqlcomparevalue <> :empty";
2916                 $params = array('value' => '********', 'name' => $name, 'empty' => '');
2917                 $DB->execute($sql, $params);
2919                 $sql = "UPDATE {config_log}
2920                            SET oldvalue = :value
2921                          WHERE name = :name AND plugin IS NULL AND $sqlcompareoldvalue <> :empty";
2922                 $params = array('value' => '********', 'name' => $name, 'empty' => '');
2923                 $DB->execute($sql, $params);
2925             } else {
2926                 $sql = "UPDATE {config_log}
2927                            SET value = :value
2928                          WHERE name = :name AND plugin = :plugin AND $sqlcomparevalue <> :empty";
2929                 $params = array('value' => '********', 'name' => $name, 'plugin' => $plugin, 'empty' => '');
2930                 $DB->execute($sql, $params);
2932                 $sql = "UPDATE {config_log}
2933                            SET oldvalue = :value
2934                          WHERE name = :name AND plugin = :plugin AND  $sqlcompareoldvalue <> :empty";
2935                 $params = array('value' => '********', 'name' => $name, 'plugin' => $plugin, 'empty' => '');
2936                 $DB->execute($sql, $params);
2937             }
2938         }
2939         // Main savepoint reached.
2940         upgrade_main_savepoint(true, 2013122400.01);
2941     }
2943     if ($oldversion < 2014011000.01) {
2945         // Define table cache_text to be dropped.
2946         $table = new xmldb_table('cache_text');
2948         // Conditionally launch drop table for cache_text.
2949         if ($dbman->table_exists($table)) {
2950             $dbman->drop_table($table);
2951         }
2953         unset_config('cachetext');
2955         // Main savepoint reached.
2956         upgrade_main_savepoint(true, 2014011000.01);
2957     }
2959     if ($oldversion < 2014011701.00) {
2960         // Fix gradebook sortorder duplicates.
2961         upgrade_grade_item_fix_sortorder();
2963         // Main savepoint reached.
2964         upgrade_main_savepoint(true, 2014011701.00);
2965     }
2967     if ($oldversion < 2014012300.01) {
2968         // Remove deleted users home pages.
2969         $sql = "DELETE FROM {my_pages}
2970                 WHERE EXISTS (SELECT {user}.id
2971                                   FROM {user}
2972                                   WHERE {user}.id = {my_pages}.userid
2973                                   AND {user}.deleted = 1)
2974                 AND {my_pages}.private = 1";
2975         $DB->execute($sql);
2977         // Reached main savepoint.
2978         upgrade_main_savepoint(true, 2014012300.01);
2979     }
2981     if ($oldversion < 2014012400.00) {
2982         // Define table lock_db to be created.
2983         $table = new xmldb_table('lock_db');
2985         // Adding fields to table lock_db.
2986         $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
2987         $table->add_field('resourcekey', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null);
2988         $table->add_field('expires', XMLDB_TYPE_INTEGER, '10', null, null, null, null);
2989         $table->add_field('owner', XMLDB_TYPE_CHAR, '36', null, null, null, null);
2991         // Adding keys to table lock_db.
2992         $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
2994         // Adding indexes to table lock_db.
2995         $table->add_index('resourcekey_uniq', XMLDB_INDEX_UNIQUE, array('resourcekey'));
2996         $table->add_index('expires_idx', XMLDB_INDEX_NOTUNIQUE, array('expires'));
2997         $table->add_index('owner_idx', XMLDB_INDEX_NOTUNIQUE, array('owner'));
2999         // Conditionally launch create table for lock_db.
3000         if (!$dbman->table_exists($table)) {
3001             $dbman->create_table($table);
3002         }
3004         // Main savepoint reached.
3005         upgrade_main_savepoint(true, 2014012400.00);
3006     }
3008     if ($oldversion < 2014020500.00) {
3009         // Define field variant to be added to question_statistics.
3010         $table = new xmldb_table('question_statistics');
3011         $field = new xmldb_field('variant', XMLDB_TYPE_INTEGER, '10', null, null, null, null, 'subquestion');
3013         // Conditionally launch add field variant.
3014         if (!$dbman->field_exists($table, $field)) {
3015             $dbman->add_field($table, $field);
3016         }
3018         // Main savepoint reached.
3019         upgrade_main_savepoint(true, 2014020500.00);
3020     }
3022     return true;