Proyectos de Subversion Moodle

Rev

Rev 11 | | Comparar con el anterior | Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1 efrain 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/>.
16
 
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
 */
42
 
43
/**
44
 * Main upgrade tasks to be executed on Moodle version bump
45
 *
46
 * This function is automatically executed after one bump in the Moodle core
47
 * version is detected. It's in charge of performing the required tasks
48
 * to raise core from the previous version to the next one.
49
 *
50
 * It's a collection of ordered blocks of code, named "upgrade steps",
51
 * each one performing one isolated (from the rest of steps) task. Usually
52
 * tasks involve creating new DB objects or performing manipulation of the
53
 * information for cleanup/fixup purposes.
54
 *
55
 * Each upgrade step has a fixed structure, that can be summarised as follows:
56
 *
57
 * if ($oldversion < XXXXXXXXXX.XX) {
58
 *     // Explanation of the update step, linking to issue in the Tracker if necessary
59
 *     upgrade_set_timeout(XX); // Optional for big tasks
60
 *     // Code to execute goes here, usually the XMLDB Editor will
61
 *     // help you here. See {@link https://moodledev.io/general/development/tools/xmldb}.
62
 *     upgrade_main_savepoint(true, XXXXXXXXXX.XX);
63
 * }
64
 *
65
 * All plugins within Moodle (modules, blocks, reports...) support the existence of
66
 * their own upgrade.php file, using the "Frankenstyle" component name as
67
 * defined at {@link https://moodledev.io/general/development/policies/codingstyle/frankenstyle}, for example:
68
 *     - {@see xmldb_page_upgrade($oldversion)}. (modules don't require the plugintype ("mod_") to be used.
69
 *     - {@see xmldb_auth_manual_upgrade($oldversion)}.
70
 *     - {@see xmldb_workshopform_accumulative_upgrade($oldversion)}.
71
 *     - ....
72
 *
73
 * In order to keep the contents of this file reduced, it's allowed to create some helper
74
 * functions to be used here in the {@see upgradelib.php} file at the same directory. Note
75
 * that such a file must be manually included from upgrade.php, and there are some restrictions
76
 * about what can be used within it.
77
 *
78
 * For more information, take a look to the documentation available:
79
 *     - Data definition API: {@link https://moodledev.io/docs/apis/core/dml/ddl}
80
 *     - Upgrade API: {@link https://moodledev.io/docs/guides/upgrade}
81
 *
82
 * @param int $oldversion
83
 * @return bool always true
84
 */
85
function xmldb_main_upgrade($oldversion) {
86
    global $CFG, $DB;
87
 
88
    require_once($CFG->libdir . '/db/upgradelib.php'); // Core Upgrade-related functions.
89
 
90
    $dbman = $DB->get_manager(); // Loads ddl manager and xmldb classes.
91
 
92
    // Always keep this upgrade step with version being the minimum
93
    // allowed version to upgrade from (v4.1.2 right now).
94
    if ($oldversion < 2022112802) {
95
        // Just in case somebody hacks upgrade scripts or env, we really can not continue.
96
        echo("You need to upgrade to 4.1.2 or higher first!\n");
97
        exit(1);
98
        // Note this savepoint is 100% unreachable, but needed to pass the upgrade checks.
99
        upgrade_main_savepoint(true, 2022112802);
100
    }
101
 
102
    // Automatically generated Moodle v4.2.0 release upgrade line.
103
    // Put any upgrade step following this.
104
 
105
    if ($oldversion < 2023051500.00) {
106
        // Define communication table.
107
        $table = new xmldb_table('communication');
108
 
109
        // Adding fields to table communication.
110
        $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE);
111
        $table->add_field('instanceid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, 'id');
112
        $table->add_field('component', XMLDB_TYPE_CHAR, '100', null, XMLDB_NOTNULL, null, null, 'instanceid');
113
        $table->add_field('instancetype', XMLDB_TYPE_CHAR, '100', null, XMLDB_NOTNULL, null, null, 'component');
114
        $table->add_field('provider', XMLDB_TYPE_CHAR, '100', null, XMLDB_NOTNULL, null, null, 'instancerype');
115
        $table->add_field('roomname', XMLDB_TYPE_CHAR, '255', null, null, null, null, 'provider');
116
        $table->add_field('avatarfilename', XMLDB_TYPE_CHAR, '100', null, null, null, null, 'roomname');
117
        $table->add_field('active', XMLDB_TYPE_INTEGER, '1', null, XMLDB_NOTNULL, null, 1, 'avatarfilename');
118
 
119
        // Add key.
120
        $table->add_key('primary', XMLDB_KEY_PRIMARY, ['id']);
121
 
122
        // Conditionally launch create table for communication.
123
        if (!$dbman->table_exists($table)) {
124
            $dbman->create_table($table);
125
        }
126
 
127
        // Define communication user table.
128
        $table = new xmldb_table('communication_user');
129
 
130
        // Adding fields to table communication.
131
        $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE);
132
        $table->add_field('commid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, 'id');
133
        $table->add_field('userid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null, 'commid');
134
        $table->add_field('synced', XMLDB_TYPE_INTEGER, '1', null, XMLDB_NOTNULL, null, 0, 'userid');
135
        $table->add_field('deleted', XMLDB_TYPE_INTEGER, '1', null, XMLDB_NOTNULL, null, 0, 'synced');
136
 
137
        // Add keys.
138
        $table->add_key('primary', XMLDB_KEY_PRIMARY, ['id']);
139
        $table->add_key('commid', XMLDB_KEY_FOREIGN, ['commid'], 'communication', ['id']);
140
        $table->add_key('userid', XMLDB_KEY_FOREIGN, ['userid'], 'user', ['id']);
141
 
142
        // Conditionally launch create table for communication.
143
        if (!$dbman->table_exists($table)) {
144
            $dbman->create_table($table);
145
        }
146
 
147
        // Main savepoint reached.
148
        upgrade_main_savepoint(true, 2023051500.00);
149
    }
150
 
151
    if ($oldversion < 2023062200.00) {
152
        // Remove device specific fields for themes from config table.
153
        unset_config('thememobile');
154
        unset_config('themelegacy');
155
        unset_config('themetablet');
156
 
157
        upgrade_main_savepoint(true, 2023062200.00);
158
    }
159
 
160
    if ($oldversion < 2023062700.01) {
161
        // Define field name to be added to external_tokens.
162
        $table = new xmldb_table('external_tokens');
163
        $field = new xmldb_field('name', XMLDB_TYPE_CHAR, '255', null, null, null, null, 'lastaccess');
164
        // Conditionally launch add field name.
165
        if (!$dbman->field_exists($table, $field)) {
166
            $dbman->add_field($table, $field);
167
        }
168
        // Update the old external tokens.
169
        $sql = 'UPDATE {external_tokens}
170
                   SET name = ' . $DB->sql_concat(
171
                       // We only need the prefix, so leave the third param with an empty string.
172
                        "'" . get_string('tokennameprefix', 'webservice', '') . "'",
173
                        "id"
174
                    );
175
        $DB->execute($sql);
176
        // Main savepoint reached.
177
        upgrade_main_savepoint(true, 2023062700.01);
178
    }
179
 
180
    if ($oldversion < 2023062900.01) {
181
        // Define field avatarsynced to be added to communication.
182
        $table = new xmldb_table('communication');
183
        $field = new xmldb_field('avatarsynced', XMLDB_TYPE_INTEGER, '1', null, XMLDB_NOTNULL, null, 0, 'active');
184
 
185
        // Conditionally launch add field avatarsynced.
186
        if (!$dbman->field_exists($table, $field)) {
187
            $dbman->add_field($table, $field);
188
        }
189
 
190
        // Main savepoint reached.
191
        upgrade_main_savepoint(true, 2023062900.01);
192
    }
193
 
194
    if ($oldversion < 2023080100.00) {
195
        // Upgrade yaml mime type for existing yaml and yml files.
196
        $filetypes = [
197
            '%.yaml' => 'application/yaml',
198
            '%.yml' => 'application/yaml,',
199
        ];
200
 
201
        $select = $DB->sql_like('filename', '?', false);
202
        foreach ($filetypes as $extension => $mimetype) {
203
            $DB->set_field_select(
204
                'files',
205
                'mimetype',
206
                $mimetype,
207
                $select,
208
                [$extension]
209
            );
210
        }
211
 
212
        // Main savepoint reached.
213
        upgrade_main_savepoint(true, 2023080100.00);
214
    }
215
 
216
    if ($oldversion < 2023081500.00) {
217
        upgrade_core_licenses();
218
        upgrade_main_savepoint(true, 2023081500.00);
219
    }
220
 
221
    if ($oldversion < 2023081800.01) {
222
        // Remove enabledevicedetection and devicedetectregex from config table.
223
        unset_config('enabledevicedetection');
224
        unset_config('devicedetectregex');
225
        // Main savepoint reached.
226
        upgrade_main_savepoint(true, 2023081800.01);
227
    }
228
 
229
    if ($oldversion < 2023082200.01) {
230
        // Some MIME icons have been removed and replaced with existing icons. They need to be upgraded for custom MIME types.
231
        $replacedicons = [
232
            'avi' => 'video',
233
            'base' => 'database',
234
            'bmp' => 'image',
235
            'html' => 'markup',
236
            'jpeg' => 'image',
237
            'mov' => 'video',
238
            'mp3' => 'audio',
239
            'mpeg' => 'video',
240
            'png' => 'image',
241
            'quicktime' => 'video',
242
            'tiff' => 'image',
243
            'wav' => 'audio',
244
            'wmv' => 'video',
245
        ];
246
 
247
        $custom = [];
248
        if (!empty($CFG->customfiletypes)) {
249
            if (array_key_exists('customfiletypes', $CFG->config_php_settings)) {
250
                // It's set in config.php, so the MIME icons can't be upgraded automatically.
251
                echo("\nYou need to manually check customfiletypes in config.php because some MIME icons have been removed!\n");
252
            } else {
253
                // It's a JSON string in the config table.
254
                $custom = json_decode($CFG->customfiletypes);
255
            }
256
        }
257
 
258
        $changed = false;
259
        foreach ($custom as $customentry) {
260
            if (!empty($customentry->icon) && array_key_exists($customentry->icon, $replacedicons)) {
261
                $customentry->icon = $replacedicons[$customentry->icon];
262
                $changed = true;
263
            }
264
        }
265
 
266
        if ($changed) {
267
            // Save the new customfiletypes.
268
            set_config('customfiletypes', json_encode($custom));
269
        }
270
 
271
        // Main savepoint reached.
272
        upgrade_main_savepoint(true, 2023082200.01);
273
    }
274
 
275
    if ($oldversion < 2023082200.02) {
276
        // Some MIME icons have been removed. They need to be replaced to 'unknown' for custom MIME types.
277
        $removedicons = array_flip([
278
            'clip-353',
279
            'edit',
280
            'env',
281
            'explore',
282
            'folder-open',
283
            'help',
284
            'move',
285
            'parent',
286
        ]);
287
 
288
        $custom = [];
289
        if (!empty($CFG->customfiletypes)) {
290
            if (array_key_exists('customfiletypes', $CFG->config_php_settings)) {
291
                // It's set in config.php, so the MIME icons can't be upgraded automatically.
292
                echo("\nYou need to manually check customfiletypes in config.php because some MIME icons have been removed!\n");
293
            } else {
294
                // It's a JSON string in the config table.
295
                $custom = json_decode($CFG->customfiletypes);
296
            }
297
        }
298
 
299
        $changed = false;
300
        foreach ($custom as $customentry) {
301
            if (!empty($customentry->icon) && array_key_exists($customentry->icon, $removedicons)) {
302
                // The icon has been removed, so set it to unknown.
303
                $customentry->icon = 'unknown';
304
                $changed = true;
305
            }
306
        }
307
 
308
        if ($changed) {
309
            // Save the new customfiletypes.
310
            set_config('customfiletypes', json_encode($custom));
311
        }
312
 
313
        // Main savepoint reached.
314
        upgrade_main_savepoint(true, 2023082200.02);
315
    }
316
 
317
    if ($oldversion < 2023082200.04) {
318
        // Remove any non-unique filters/conditions.
319
        $duplicates = $DB->get_records_sql("
320
            SELECT MIN(id) AS id, reportid, uniqueidentifier, iscondition
321
              FROM {reportbuilder_filter}
322
          GROUP BY reportid, uniqueidentifier, iscondition
323
            HAVING COUNT(*) > 1");
324
 
325
        foreach ($duplicates as $duplicate) {
326
            $DB->delete_records_select(
327
                'reportbuilder_filter',
328
                'id <> :id AND reportid = :reportid AND uniqueidentifier = :uniqueidentifier AND iscondition = :iscondition',
329
                (array) $duplicate
330
            );
331
        }
332
 
333
        // Define index report-filter (unique) to be added to reportbuilder_filter.
334
        $table = new xmldb_table('reportbuilder_filter');
335
        $index = new xmldb_index('report-filter', XMLDB_INDEX_UNIQUE, ['reportid', 'uniqueidentifier', 'iscondition']);
336
 
337
        // Conditionally launch add index report-filter.
338
        if (!$dbman->index_exists($table, $index)) {
339
            $dbman->add_index($table, $index);
340
        }
341
 
342
        // Main savepoint reached.
343
        upgrade_main_savepoint(true, 2023082200.04);
344
    }
345
 
346
    if ($oldversion < 2023082600.02) {
347
        // Get all the ids of users who still have md5 hashed passwords.
348
        if ($DB->sql_regex_supported()) {
349
            // If the database supports regex, we can add an exact check for md5.
350
            $condition = 'password ' . $DB->sql_regex() . ' :pattern';
351
            $params = ['pattern' => "^[a-fA-F0-9]{32}$"];
352
        } else {
353
            // Otherwise, we need to use a NOT LIKE condition and rule out bcrypt.
354
            $condition = $DB->sql_like('password', ':pattern', true, false, true);
355
            $params = ['pattern' => '$2y$%'];
356
        }
357
 
358
        // Regardless of database regex support we check the hash length which should be enough.
359
        // But extra regex or like matching makes sure.
360
        $sql = "SELECT id FROM {user} WHERE " . $DB->sql_length('password') . " = 32 AND $condition";
361
        $userids = $DB->get_fieldset_sql($sql, $params);
362
 
363
        // Update the password for each user with a new SHA-512 hash.
364
        // Users won't know this password, but they can reset it. This is a security measure,
365
        // in case the database is compromised or the hash has been leaked elsewhere.
366
        foreach ($userids as $userid) {
367
            $password = base64_encode(random_bytes(24)); // Generate a new password for the user.
368
 
369
            $user = new \stdClass();
370
            $user->id = $userid;
371
            $user->password = hash_internal_user_password($password);
372
            $DB->update_record('user', $user, true);
373
        }
374
 
375
        // Main savepoint reached.
376
        upgrade_main_savepoint(true, 2023082600.02);
377
    }
378
 
379
    if ($oldversion < 2023082600.03) {
380
        // The previous default configuration had a typo, check for its presence and correct if necessary.
381
        $sensiblesettings = get_config('adminpresets', 'sensiblesettings');
382
        if (strpos($sensiblesettings, 'smtppass@none') !== false) {
383
            $newsensiblesettings = str_replace('smtppass@none', 'smtppass@@none', $sensiblesettings);
384
            set_config('sensiblesettings', $newsensiblesettings, 'adminpresets');
385
        }
386
 
387
        // Main savepoint reached.
388
        upgrade_main_savepoint(true, 2023082600.03);
389
    }
390
 
391
    if ($oldversion < 2023082600.05) {
392
        unset_config('completiondefault');
393
 
394
        // Main savepoint reached.
395
        upgrade_main_savepoint(true, 2023082600.05);
396
    }
397
 
398
    if ($oldversion < 2023090100.00) {
399
        // Upgrade MIME type for existing PSD files.
400
        $DB->set_field_select(
401
            'files',
402
            'mimetype',
403
            'image/vnd.adobe.photoshop',
404
            $DB->sql_like('filename', '?', false),
405
            ['%.psd']
406
        );
407
 
408
        // Main savepoint reached.
409
        upgrade_main_savepoint(true, 2023090100.00);
410
    }
411
 
412
    if ($oldversion < 2023090200.01) {
413
        // Define table moodlenet_share_progress to be created.
414
        $table = new xmldb_table('moodlenet_share_progress');
415
 
416
        // Adding fields to table moodlenet_share_progress.
417
        $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
418
        $table->add_field('type', XMLDB_TYPE_INTEGER, '2', null, XMLDB_NOTNULL, null, null);
419
        $table->add_field('courseid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null);
420
        $table->add_field('cmid', XMLDB_TYPE_INTEGER, '10', null, null, null, null);
421
        $table->add_field('userid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null);
422
        $table->add_field('timecreated', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null);
423
        $table->add_field('resourceurl', XMLDB_TYPE_CHAR, '255', null, null, null, null);
424
        $table->add_field('status', XMLDB_TYPE_INTEGER, '2', null, null, null, null);
425
 
426
        // Adding keys to table moodlenet_share_progress.
427
        $table->add_key('primary', XMLDB_KEY_PRIMARY, ['id']);
428
 
429
        // Conditionally launch create table for moodlenet_share_progress.
430
        if (!$dbman->table_exists($table)) {
431
            $dbman->create_table($table);
432
        }
433
 
434
        // Main savepoint reached.
435
        upgrade_main_savepoint(true, 2023090200.01);
436
    }
437
 
438
    if ($oldversion < 2023091300.03) {
439
        // Delete all the searchanywhere prefs in user_preferences table.
440
        $DB->delete_records('user_preferences', ['name' => 'userselector_searchanywhere']);
441
        // Main savepoint reached.
442
        upgrade_main_savepoint(true, 2023091300.03);
443
    }
444
 
445
    if ($oldversion < 2023100400.01) {
446
        // Delete datakey with datavalue -1.
447
        $DB->delete_records('messageinbound_datakeys', ['datavalue' => '-1']);
448
        // Main savepoint reached.
449
        upgrade_main_savepoint(true, 2023100400.01);
450
    }
451
 
452
    if ($oldversion < 2023100400.03) {
453
        // Define field id to be added to communication.
454
        $table = new xmldb_table('communication');
455
 
456
        // Add the field and allow it to be nullable.
457
        // We need to backfill data before setting it to NOT NULL.
458
        $field = new xmldb_field(
459
            name: 'contextid',
460
            type: XMLDB_TYPE_INTEGER,
461
            precision: '10',
462
            notnull: null,
463
            previous: 'id',
464
        );
465
 
466
        // Conditionally launch add field id.
467
        if (!$dbman->field_exists($table, $field)) {
468
            $dbman->add_field($table, $field);
469
        }
470
 
471
        // Fill the existing data.
472
        $sql = <<<EOF
473
                    SELECT comm.id, c.id AS contextid
474
                      FROM {communication} comm
475
                INNER JOIN {context} c ON c.instanceid = comm.instanceid AND c.contextlevel = :contextcourse
476
                     WHERE comm.contextid IS NULL
477
                       AND comm.instancetype = :instancetype
478
        EOF;
479
        $rs = $DB->get_recordset_sql(
480
            sql: $sql,
481
            params: [
482
                'contextcourse' => CONTEXT_COURSE,
483
                'instancetype' => 'coursecommunication',
484
            ],
485
        );
486
        foreach ($rs as $comm) {
487
            $DB->set_field(
488
                table: 'communication',
489
                newfield: 'contextid',
490
                newvalue: $comm->contextid,
491
                conditions: [
492
                    'id' => $comm->id,
493
                ],
494
            );
495
        }
496
        $rs->close();
497
 
498
        $systemcontext = \core\context\system::instance();
499
        $DB->set_field_select(
500
            table: 'communication',
501
            newfield: 'contextid',
502
            newvalue: $systemcontext->id,
503
            select: 'contextid IS NULL',
504
        );
505
 
506
        // Now make it NOTNULL.
507
        $field = new xmldb_field(
508
            name: 'contextid',
509
            type: XMLDB_TYPE_INTEGER,
510
            precision: '10',
511
            notnull:  XMLDB_NOTNULL,
512
        );
513
        $dbman->change_field_notnull($table, $field);
514
 
515
        // Add the contextid constraint.
516
        $key = new xmldb_key('contextid', XMLDB_KEY_FOREIGN, ['contextid'], 'context', ['id']);
517
        $dbman->add_key($table, $key);
518
 
519
        // Main savepoint reached.
520
        upgrade_main_savepoint(true, 2023100400.03);
521
    }
522
 
523
    // Automatically generated Moodle v4.3.0 release upgrade line.
524
    // Put any upgrade step following this.
525
 
526
    if ($oldversion < 2023110900.00) {
527
        // Reorder the editors to make Tiny the default for all upgrades.
528
        $editors = [];
529
        array_push($editors, 'tiny');
530
        $list = explode(',', $CFG->texteditors);
531
        foreach ($list as $editor) {
532
            if ($editor != 'tiny') {
533
                array_push($editors, $editor);
534
            }
535
        }
536
        set_config('texteditors', implode(',', $editors));
537
 
538
        // Main savepoint reached.
539
        upgrade_main_savepoint(true, 2023110900.00);
540
    }
541
 
542
    if ($oldversion < 2023120100.01) {
543
        // The $CFG->linkcoursesections setting has been removed because it's not required anymore.
544
        // From now, sections will be always linked because a new page, section.php, has been created to display a single section.
545
        unset_config('linkcoursesections');
546
 
547
        upgrade_main_savepoint(true, 2023120100.01);
548
    }
549
 
550
    if ($oldversion < 2023121800.02) {
551
        // Define field attemptsavailable to be added to task_adhoc.
552
        $table = new xmldb_table('task_adhoc');
553
        $field = new xmldb_field(
554
            name: 'attemptsavailable',
555
            type: XMLDB_TYPE_INTEGER,
556
            precision: '2',
557
            unsigned: null,
558
            notnull: null,
559
            sequence: null,
560
            default: null,
561
            previous: 'pid',
562
        );
563
 
564
        // Conditionally launch add field attemptsavailable.
565
        if (!$dbman->field_exists($table, $field)) {
566
            $dbman->add_field($table, $field);
567
        }
568
 
569
        // Set attemptsavailable to 0 for the tasks that have not been run before.
570
        // Set attemptsavailable to 1 for the tasks that have been run and failed before.
571
        $DB->execute('
572
            UPDATE {task_adhoc}
573
               SET attemptsavailable = CASE
574
                                            WHEN faildelay = 0 THEN 1
575
                                            WHEN faildelay > 0 THEN 0
576
                                       END
577
        ');
578
 
579
        // Main savepoint reached.
580
        upgrade_main_savepoint(true, 2023121800.02);
581
    }
582
 
583
    if ($oldversion < 2023122100.01) {
584
 
585
        // Define field component to be added to course_sections.
586
        $table = new xmldb_table('course_sections');
587
        $field = new xmldb_field('component', XMLDB_TYPE_CHAR, '100', null, null, null, null, 'availability');
588
 
589
        // Conditionally launch add field component.
590
        if (!$dbman->field_exists($table, $field)) {
591
            $dbman->add_field($table, $field);
592
        }
593
 
594
        // Define field itemid to be added to course_sections.
595
        $field = new xmldb_field('itemid', XMLDB_TYPE_INTEGER, '10', null, null, null, null, 'component');
596
 
597
        // Conditionally launch add field itemid.
598
        if (!$dbman->field_exists($table, $field)) {
599
            $dbman->add_field($table, $field);
600
        }
601
 
602
        // Main savepoint reached.
603
        upgrade_main_savepoint(true, 2023122100.01);
604
    }
605
 
606
    if ($oldversion < 2023122100.02) {
607
        $sqllike = $DB->sql_like('filtercondition', '?');
608
        $params[] = '%includesubcategories%';
609
 
610
        $sql = "SELECT qsr.* FROM {question_set_references} qsr WHERE $sqllike";
611
        $results = $DB->get_recordset_sql($sql, $params);
612
        foreach ($results as $result) {
613
            $filtercondition = json_decode($result->filtercondition);
614
            if (isset($filtercondition->filter->category->includesubcategories)) {
615
                $filtercondition->filter->category->filteroptions =
616
                    ['includesubcategories' => $filtercondition->filter->category->includesubcategories];
617
                unset($filtercondition->filter->category->includesubcategories);
618
                $result->filtercondition = json_encode($filtercondition);
619
                $DB->update_record('question_set_references', $result);
620
            }
621
        }
622
        $results->close();
623
 
624
        upgrade_main_savepoint(true, 2023122100.02);
625
    }
626
 
627
    if ($oldversion < 2024010400.01) {
628
 
629
        // Define index timecreated (not unique) to be added to notifications.
630
        $table = new xmldb_table('notifications');
631
        $createdindex = new xmldb_index('timecreated', XMLDB_INDEX_NOTUNIQUE, ['timecreated']);
632
 
633
        // Conditionally launch add index timecreated.
634
        if (!$dbman->index_exists($table, $createdindex)) {
635
            $dbman->add_index($table, $createdindex);
636
        }
637
 
638
        // Define index timeread (not unique) to be added to notifications.
639
        $readindex = new xmldb_index('timeread', XMLDB_INDEX_NOTUNIQUE, ['timeread']);
640
 
641
        // Conditionally launch add index timeread.
642
        if (!$dbman->index_exists($table, $readindex)) {
643
            $dbman->add_index($table, $readindex);
644
        }
645
 
646
        // Main savepoint reached.
647
        upgrade_main_savepoint(true, 2024010400.01);
648
    }
649
 
650
    if ($oldversion < 2024012300.00) {
651
 
652
        // Define field valuetrust to be added to customfield_data.
653
        $table = new xmldb_table('customfield_data');
654
        $field = new xmldb_field('valuetrust', XMLDB_TYPE_INTEGER, '2', null, XMLDB_NOTNULL, null, '0', 'valueformat');
655
 
656
        // Conditionally launch add field valuetrust.
657
        if (!$dbman->field_exists($table, $field)) {
658
            $dbman->add_field($table, $field);
659
        }
660
 
661
        // Main savepoint reached.
662
        upgrade_main_savepoint(true, 2024012300.00);
663
    }
664
 
665
    if ($oldversion < 2024020200.01) {
666
        // If h5plib_v124 is no longer present, remove it.
667
        if (!file_exists($CFG->dirroot . '/h5p/h5plib/v124/version.php')) {
668
            // Clean config.
669
            uninstall_plugin('h5plib', 'v124');
670
        }
671
 
672
        // If h5plib_v126 is present, set it as the default one.
673
        if (file_exists($CFG->dirroot . '/h5p/h5plib/v126/version.php')) {
674
            set_config('h5plibraryhandler', 'h5plib_v126');
675
        }
676
 
677
        upgrade_main_savepoint(true, 2024020200.01);
678
    }
679
 
680
    if ($oldversion < 2024021500.01) {
681
        // Change default course formats order for sites never changed the default order.
682
        if (!get_config('core', 'format_plugins_sortorder')) {
683
            set_config('format_plugins_sortorder', 'topics,weeks,singleactivity,social');
684
        }
685
 
686
        // Main savepoint reached.
687
        upgrade_main_savepoint(true, 2024021500.01);
688
    }
689
 
690
    if ($oldversion < 2024021500.02) {
691
        // A [name => url] map of new OIDC endpoints to be updated/created.
692
        $endpointuris = [
693
            'authorization_endpoint' => 'https://clever.com/oauth/authorize',
694
            'token_endpoint' => 'https://clever.com/oauth/tokens',
695
            'userinfo_endpoint' => 'https://api.clever.com/userinfo',
696
            'jwks_uri' => 'https://clever.com/oauth/certs',
697
        ];
698
 
699
        // A [internalfield => externalfield] map of new OIDC-based user field mappings to be updated/created.
700
        $userfieldmappings = [
701
            'idnumber' => 'sub',
702
            'firstname' => 'given_name',
703
            'lastname' => 'family_name',
704
            'email' => 'email',
705
        ];
706
 
707
        $admin = get_admin();
708
        $adminid = $admin ? $admin->id : '0';
709
 
710
        $cleverservices = $DB->get_records('oauth2_issuer', ['servicetype' => 'clever']);
711
        foreach ($cleverservices as $cleverservice) {
712
            $time = time();
713
 
714
            // Insert/update the new endpoints.
715
            foreach ($endpointuris as $endpointname => $endpointuri) {
716
                $endpoint = ['issuerid' => $cleverservice->id, 'name' => $endpointname];
717
                $endpointid = $DB->get_field('oauth2_endpoint', 'id', $endpoint);
718
 
719
                if ($endpointid) {
720
                    $endpoint = array_merge($endpoint, [
721
                        'id' => $endpointid,
722
                        'url' => $endpointuri,
723
                        'timemodified' => $time,
724
                        'usermodified' => $adminid,
725
                    ]);
726
                    $DB->update_record('oauth2_endpoint', $endpoint);
727
                } else {
728
                    $endpoint = array_merge($endpoint, [
729
                        'url' => $endpointuri,
730
                        'timecreated' => $time,
731
                        'timemodified' => $time,
732
                        'usermodified' => $adminid,
733
                    ]);
734
                    $DB->insert_record('oauth2_endpoint', $endpoint);
735
                }
736
            }
737
 
738
            // Insert/update new user field mappings.
739
            foreach ($userfieldmappings as $internalfieldname => $externalfieldname) {
740
                $fieldmap = ['issuerid' => $cleverservice->id, 'internalfield' => $internalfieldname];
741
                $fieldmapid = $DB->get_field('oauth2_user_field_mapping', 'id', $fieldmap);
742
 
743
                if ($fieldmapid) {
744
                    $fieldmap = array_merge($fieldmap, [
745
                        'id' => $fieldmapid,
746
                        'externalfield' => $externalfieldname,
747
                        'timemodified' => $time,
748
                        'usermodified' => $adminid,
749
                    ]);
750
                    $DB->update_record('oauth2_user_field_mapping', $fieldmap);
751
                } else {
752
                    $fieldmap = array_merge($fieldmap, [
753
                        'externalfield' => $externalfieldname,
754
                        'timecreated' => $time,
755
                        'timemodified' => $time,
756
                        'usermodified' => $adminid,
757
                    ]);
758
                    $DB->insert_record('oauth2_user_field_mapping', $fieldmap);
759
                }
760
            }
761
 
762
            // Update the baseurl for the issuer.
763
            $cleverservice->baseurl = 'https://clever.com';
764
            $cleverservice->timemodified = $time;
765
            $cleverservice->usermodified = $adminid;
766
            $DB->update_record('oauth2_issuer', $cleverservice);
767
        }
768
 
769
        upgrade_main_savepoint(true, 2024021500.02);
770
    }
771
 
772
    if ($oldversion < 2024022300.02) {
773
        // Removed advanced grade item settings.
774
        unset_config('grade_item_advanced');
775
 
776
        upgrade_main_savepoint(true, 2024022300.02);
777
    }
778
 
779
    if ($oldversion < 2024030500.01) {
780
 
781
        // Define field firststartingtime to be added to task_adhoc.
782
        $table = new xmldb_table('task_adhoc');
783
        $field = new xmldb_field('firststartingtime', XMLDB_TYPE_INTEGER, '10', null, null, null, null, 'attemptsavailable');
784
 
785
        // Conditionally launch add field firststartingtime.
786
        if (!$dbman->field_exists($table, $field)) {
787
            $dbman->add_field($table, $field);
788
            // Main savepoint reached.
789
            upgrade_main_savepoint(true, 2024030500.01);
790
        }
791
 
792
    }
793
 
794
    if ($oldversion < 2024030500.02) {
795
 
796
        // Get all "select" custom field shortnames.
797
        $fieldshortnames = $DB->get_fieldset('customfield_field', 'shortname', ['type' => 'select']);
798
 
799
        // Ensure any used in custom reports columns are not using integer type aggregation.
800
        foreach ($fieldshortnames as $fieldshortname) {
801
            $DB->execute("
802
                UPDATE {reportbuilder_column}
803
                   SET aggregation = NULL
804
                 WHERE " . $DB->sql_like('uniqueidentifier', ':uniqueidentifier', false) . "
805
                   AND aggregation IN ('avg', 'max', 'min', 'sum')
806
            ", [
807
                'uniqueidentifier' => '%' . $DB->sql_like_escape(":customfield_{$fieldshortname}"),
808
            ]);
809
        }
810
 
811
        // Main savepoint reached.
812
        upgrade_main_savepoint(true, 2024030500.02);
813
    }
814
 
815
    if ($oldversion < 2024032600.01) {
816
 
817
        // Changing precision of field attemptsavailable on table task_adhoc to (2).
818
        $table = new xmldb_table('task_adhoc');
819
        $field = new xmldb_field('attemptsavailable', XMLDB_TYPE_INTEGER, '2', null, null, null, null, 'pid');
820
 
821
        // Launch change of precision for field.
822
        if (!$dbman->field_exists($table, $field)) {
823
            $dbman->change_field_precision($table, $field);
824
        }
825
 
826
        // Main savepoint reached.
827
        upgrade_main_savepoint(true, 2024032600.01);
828
    }
829
 
830
    if ($oldversion < 2024041200.00) {
831
        // Define field blocking to be dropped from task_adhoc.
832
        $table = new xmldb_table('task_adhoc');
833
        $field = new xmldb_field('blocking');
834
 
835
        // Conditionally launch drop field blocking.
836
        if ($dbman->field_exists($table, $field)) {
837
            $dbman->drop_field($table, $field);
838
        }
839
 
840
        // Define field blocking to be dropped from task_scheduled.
841
        $table = new xmldb_table('task_scheduled');
842
        $field = new xmldb_field('blocking');
843
 
844
        // Conditionally launch drop field blocking.
845
        if ($dbman->field_exists($table, $field)) {
846
            $dbman->drop_field($table, $field);
847
        }
848
 
849
        // Main savepoint reached.
850
        upgrade_main_savepoint(true, 2024041200.00);
851
    }
852
 
853
    // Automatically generated Moodle v4.4.0 release upgrade line.
854
    // Put any upgrade step following this.
855
 
1441 ariadna 856
    if ($oldversion < 2024070500.01) {
857
        // Remove the site_contactable config of the hub plugin from config plugin table.
858
        unset_config('site_contactable', 'hub');
11 efrain 859
 
1441 ariadna 860
        // Main savepoint reached.
861
        upgrade_main_savepoint(true, 2024070500.01);
862
    }
863
 
864
    if ($oldversion < 2024071900.01) {
865
        // Define table stored_progress to be created.
866
        $table = new xmldb_table('stored_progress');
867
 
868
        // Adding fields to table stored_progress.
869
        $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
870
        $table->add_field('idnumber', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null);
871
        $table->add_field('timestart', XMLDB_TYPE_INTEGER, '20', null, null, null, null);
872
        $table->add_field('lastupdate', XMLDB_TYPE_INTEGER, '20', null, null, null, null);
873
        $table->add_field('percentcompleted', XMLDB_TYPE_NUMBER, '5, 2', null, null, null, '0');
874
        $table->add_field('message', XMLDB_TYPE_CHAR, '255', null, null, null, null);
875
        $table->add_field('haserrored', XMLDB_TYPE_INTEGER, '1', null, XMLDB_NOTNULL, null, '0');
876
 
877
        // Adding keys to table stored_progress.
878
        $table->add_key('primary', XMLDB_KEY_PRIMARY, ['id']);
879
 
880
        // Adding indexes to table stored_progress.
881
        $table->add_index('uid_index', XMLDB_INDEX_NOTUNIQUE, ['idnumber']);
882
 
883
        // Conditionally launch create table for stored_progress.
884
        if (!$dbman->table_exists($table)) {
885
            $dbman->create_table($table);
886
        }
887
 
888
        // Main savepoint reached.
889
        upgrade_main_savepoint(true, 2024071900.01);
890
    }
891
 
892
    if ($oldversion < 2024072600.01) {
893
        // If tool_innodb is no longer present, remove it.
894
        if (!file_exists($CFG->dirroot . '/admin/tool/innodb/version.php')) {
895
            // Delete tool_innodb.
896
            uninstall_plugin('tool', 'innodb');
897
        }
898
 
899
        // Main savepoint reached.
900
        upgrade_main_savepoint(true, 2024072600.01);
901
    }
902
 
903
    if ($oldversion < 2024080500.00) {
904
 
11 efrain 905
        // Fix missing default admin presets "sensible settings" (those that should be treated as sensitive).
906
        $newsensiblesettings = [
907
            'bigbluebuttonbn_shared_secret@@none',
908
            'apikey@@tiny_premium',
909
            'matrixaccesstoken@@communication_matrix',
910
            'api_secret@@factor_sms',
911
        ];
912
 
913
        $sensiblesettings = get_config('adminpresets', 'sensiblesettings');
914
        foreach ($newsensiblesettings as $newsensiblesetting) {
915
            if (strpos($sensiblesettings, $newsensiblesetting) === false) {
916
                $sensiblesettings .= ", {$newsensiblesetting}";
917
            }
918
        }
919
 
920
        set_config('sensiblesettings', $sensiblesettings, 'adminpresets');
921
 
922
        // Main savepoint reached.
1441 ariadna 923
        upgrade_main_savepoint(true, 2024080500.00);
11 efrain 924
    }
925
 
1441 ariadna 926
    if ($oldversion < 2024082900.01) {
927
        // If filter_tidy is no longer present, remove it.
928
        if (!file_exists($CFG->dirroot . '/filter/tidy/version.php')) {
929
            // Clean config.
930
            uninstall_plugin('filter', 'tidy');
931
        }
932
 
933
        upgrade_main_savepoint(true, 2024082900.01);
934
    }
935
 
936
    if ($oldversion < 2024091000.01) {
937
        // Define table ai_policy_register to be created.
938
        $table = new xmldb_table('ai_policy_register');
939
 
940
        // Adding fields to table ai_policy_register.
941
        $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
942
        $table->add_field('userid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null);
943
        $table->add_field('contextid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null);
944
        $table->add_field('timeaccepted', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null);
945
 
946
        // Adding keys to table ai_policy_register.
947
        $table->add_key('primary', XMLDB_KEY_PRIMARY, ['id']);
948
        $table->add_key('userid', XMLDB_KEY_FOREIGN_UNIQUE, ['userid'], 'user', ['id']);
949
 
950
        // Conditionally launch create table for ai_policy_register.
951
        if (!$dbman->table_exists($table)) {
952
            $dbman->create_table($table);
953
        }
954
 
955
        // Define table ai_action_generate_image to be created.
956
        $table = new xmldb_table('ai_action_generate_image');
957
 
958
        // Adding fields to table ai_action_generate_image.
959
        $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
960
        $table->add_field('prompt', XMLDB_TYPE_TEXT, null, null, null, null, null);
961
        $table->add_field('numberimages', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null);
962
        $table->add_field('quality', XMLDB_TYPE_CHAR, '21', null, XMLDB_NOTNULL, null, null);
963
        $table->add_field('aspectratio', XMLDB_TYPE_CHAR, '20', null, null, null, null);
964
        $table->add_field('style', XMLDB_TYPE_CHAR, '20', null, null, null, null);
965
        $table->add_field('sourceurl', XMLDB_TYPE_TEXT, null, null, null, null, null);
966
        $table->add_field('revisedprompt', XMLDB_TYPE_TEXT, null, null, null, null, null);
967
 
968
        // Adding keys to table ai_action_generate_image.
969
        $table->add_key('primary', XMLDB_KEY_PRIMARY, ['id']);
970
 
971
        // Conditionally launch create table for ai_action_generate_image.
972
        if (!$dbman->table_exists($table)) {
973
            $dbman->create_table($table);
974
        }
975
 
976
        // Define table ai_action_register to be created.
977
        $table = new xmldb_table('ai_action_register');
978
 
979
        // Adding fields to table ai_action_register.
980
        $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
981
        $table->add_field('actionname', XMLDB_TYPE_CHAR, '100', null, XMLDB_NOTNULL, null, null);
982
        $table->add_field('actionid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null);
983
        $table->add_field('success', XMLDB_TYPE_INTEGER, '1', null, XMLDB_NOTNULL, null, '0');
984
        $table->add_field('userid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null);
985
        $table->add_field('contextid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null);
986
        $table->add_field('provider', XMLDB_TYPE_CHAR, '100', null, XMLDB_NOTNULL, null, null);
987
        $table->add_field('errorcode', XMLDB_TYPE_INTEGER, '4', null, null, null, null);
988
        $table->add_field('errormessage', XMLDB_TYPE_TEXT, null, null, null, null, null);
989
        $table->add_field('timecreated', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null);
990
        $table->add_field('timecompleted', XMLDB_TYPE_INTEGER, '10', null, null, null, null);
991
 
992
        // Adding keys to table ai_action_register.
993
        $table->add_key('primary', XMLDB_KEY_PRIMARY, ['id']);
994
        $table->add_key('userid', XMLDB_KEY_FOREIGN, ['userid'], 'user', ['id']);
995
 
996
        // Adding indexes to table ai_action_register.
997
        $table->add_index('action', XMLDB_INDEX_UNIQUE, ['actionname', 'actionid']);
998
        $table->add_index('provider', XMLDB_INDEX_NOTUNIQUE, ['actionname', 'provider']);
999
 
1000
        // Conditionally launch create table for ai_action_register.
1001
        if (!$dbman->table_exists($table)) {
1002
            $dbman->create_table($table);
1003
        }
1004
 
1005
        // Define table ai_action_generate_text to be created.
1006
        $table = new xmldb_table('ai_action_generate_text');
1007
 
1008
        // Adding fields to table ai_action_generate_text.
1009
        $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
1010
        $table->add_field('prompt', XMLDB_TYPE_TEXT, null, null, null, null, null);
1011
        $table->add_field('responseid', XMLDB_TYPE_CHAR, '128', null, null, null, null);
1012
        $table->add_field('fingerprint', XMLDB_TYPE_CHAR, '128', null, null, null, null);
1013
        $table->add_field('generatedcontent', XMLDB_TYPE_TEXT, null, null, null, null, null);
1014
        $table->add_field('finishreason', XMLDB_TYPE_CHAR, '128', null, null, null, null);
1015
        $table->add_field('prompttokens', XMLDB_TYPE_INTEGER, '10', null, null, null, null);
1016
        $table->add_field('completiontoken', XMLDB_TYPE_INTEGER, '10', null, null, null, null);
1017
 
1018
        // Adding keys to table ai_action_generate_text.
1019
        $table->add_key('primary', XMLDB_KEY_PRIMARY, ['id']);
1020
 
1021
        // Conditionally launch create table for ai_action_generate_text.
1022
        if (!$dbman->table_exists($table)) {
1023
            $dbman->create_table($table);
1024
        }
1025
 
1026
        // Define table ai_action_summarise_text to be created.
1027
        $table = new xmldb_table('ai_action_summarise_text');
1028
 
1029
        // Adding fields to table ai_action_summarise_text.
1030
        $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
1031
        $table->add_field('prompt', XMLDB_TYPE_TEXT, null, null, null, null, null);
1032
        $table->add_field('responseid', XMLDB_TYPE_CHAR, '128', null, null, null, null);
1033
        $table->add_field('fingerprint', XMLDB_TYPE_CHAR, '128', null, null, null, null);
1034
        $table->add_field('generatedcontent', XMLDB_TYPE_TEXT, null, null, null, null, null);
1035
        $table->add_field('finishreason', XMLDB_TYPE_CHAR, '128', null, null, null, null);
1036
        $table->add_field('prompttokens', XMLDB_TYPE_INTEGER, '10', null, null, null, null);
1037
        $table->add_field('completiontoken', XMLDB_TYPE_INTEGER, '10', null, null, null, null);
1038
 
1039
        // Adding keys to table ai_action_summarise_text.
1040
        $table->add_key('primary', XMLDB_KEY_PRIMARY, ['id']);
1041
 
1042
        // Conditionally launch create table for ai_action_summarise_text.
1043
        if (!$dbman->table_exists($table)) {
1044
            $dbman->create_table($table);
1045
        }
1046
 
1047
        // Main savepoint reached.
1048
        upgrade_main_savepoint(true, 2024091000.01);
1049
    }
1050
 
1051
    if ($oldversion < 2024091700.01) {
1052
        // Convert the ai_action_register.success column to an integer, if necessary.
1053
        upgrade_change_binary_column_to_int('ai_action_register', 'success', XMLDB_NOTNULL, 'actionid');
1054
 
1055
        // Main savepoint reached.
1056
        upgrade_main_savepoint(true, 2024091700.01);
1057
    }
1058
 
1059
    if ($oldversion < 2024092000.01) {
1060
 
1061
        // Define table sms_messages to be created.
1062
        $table = new xmldb_table('sms_messages');
1063
 
1064
        // Adding fields to table sms_messages.
1065
        $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
1066
        $table->add_field('recipientnumber', XMLDB_TYPE_CHAR, '30', null, XMLDB_NOTNULL, null, null);
1067
        $table->add_field('content', XMLDB_TYPE_TEXT, null, null, null, null, null);
1068
        $table->add_field('component', XMLDB_TYPE_CHAR, '100', null, XMLDB_NOTNULL, null, null);
1069
        $table->add_field('messagetype', XMLDB_TYPE_CHAR, '100', null, XMLDB_NOTNULL, null, null);
1070
        $table->add_field('recipientuserid', XMLDB_TYPE_INTEGER, '10', null, null, null, null);
1071
        $table->add_field('issensitive', XMLDB_TYPE_INTEGER, '2', null, XMLDB_NOTNULL, null, '0');
1072
        $table->add_field('gatewayid', XMLDB_TYPE_INTEGER, '10', null, null, null, null);
1073
        $table->add_field('status', XMLDB_TYPE_CHAR, '100', null, null, null, null);
1074
        $table->add_field('timecreated', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null);
1075
 
1076
        // Adding keys to table sms_messages.
1077
        $table->add_key('primary', XMLDB_KEY_PRIMARY, ['id']);
1078
        $table->add_key('gateway', XMLDB_KEY_FOREIGN, ['gatewayid'], 'sms_gateways', ['id']);
1079
 
1080
        // Conditionally launch create table for sms_messages.
1081
        if (!$dbman->table_exists($table)) {
1082
            $dbman->create_table($table);
1083
        }
1084
 
1085
        // Define table sms_gateways to be created.
1086
        $table = new xmldb_table('sms_gateways');
1087
 
1088
        // Adding fields to table sms_gateways.
1089
        $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
1090
        $table->add_field('name', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null);
1091
        $table->add_field('gateway', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null);
1092
        $table->add_field('enabled', XMLDB_TYPE_INTEGER, '2', null, XMLDB_NOTNULL, null, '1');
1093
        $table->add_field('config', XMLDB_TYPE_TEXT, null, null, XMLDB_NOTNULL, null, null);
1094
 
1095
        // Adding keys to table sms_gateways.
1096
        $table->add_key('primary', XMLDB_KEY_PRIMARY, ['id']);
1097
 
1098
        // Conditionally launch create table for sms_gateways.
1099
        if (!$dbman->table_exists($table)) {
1100
            $dbman->create_table($table);
1101
        }
1102
 
1103
        // Main savepoint reached.
1104
        upgrade_main_savepoint(true, 2024092000.01);
1105
    }
1106
 
1107
    if ($oldversion < 2024092600.00) {
1108
        // If h5plib_v126 is no longer present, remove it.
1109
        if (!file_exists($CFG->dirroot . '/h5p/h5plib/v126/version.php')) {
1110
            // Clean config.
1111
            uninstall_plugin('h5plib', 'v126');
1112
        }
1113
 
1114
        // If h5plib_v127 is present, set it as the default one.
1115
        if (file_exists($CFG->dirroot . '/h5p/h5plib/v127/version.php')) {
1116
            set_config('h5plibraryhandler', 'h5plib_v127');
1117
        }
1118
        // Main savepoint reached.
1119
        upgrade_main_savepoint(true, 2024092600.00);
1120
    }
1121
 
1122
    if ($oldversion < 2024100100.02) {
1123
        upgrade_store_relative_url_sitehomepage();
1124
 
1125
        // Main savepoint reached.
1126
        upgrade_main_savepoint(true, 2024100100.02);
1127
    }
1128
 
1129
    // Automatically generated Moodle v4.5.0 release upgrade line.
1130
    // Put any upgrade step following this.
1131
 
1132
    if ($oldversion < 2024110400.00) {
1133
 
1134
        // Define field model to be added to ai_action_register.
1135
        $table = new xmldb_table('ai_action_register');
1136
        $field = new xmldb_field('model', XMLDB_TYPE_CHAR, '50', null, null, null, null, null);
1137
 
1138
        // Conditionally launch add field model.
1139
        if (!$dbman->field_exists($table, $field)) {
1140
            $dbman->add_field($table, $field);
1141
        }
1142
 
1143
        // Main savepoint reached.
1144
        upgrade_main_savepoint(true, 2024110400.00);
1145
    }
1146
    if ($oldversion < 2024110800.00) {
1147
        // Delete settings that were removed from code.
1148
        $settings = ['backup_general_questionbank', 'backup_import_questionbank', 'backup_auto_questionbank'];
1149
        array_walk($settings, static fn($setting) => unset_config($setting, 'backup'));
1150
 
1151
        // Main savepoint reached.
1152
        upgrade_main_savepoint(true, 2024110800.00);
1153
    }
1154
 
1155
    if ($oldversion < 2024110800.02) {
1156
        // Changing type of field value on table user_preferences to text.
1157
        $table = new xmldb_table('user_preferences');
1158
        $field = new xmldb_field('value', XMLDB_TYPE_TEXT, null, null, XMLDB_NOTNULL, null, null, 'name');
1159
 
1160
        // Launch change of type for field value.
1161
        $dbman->change_field_type($table, $field);
1162
 
1163
        // Main savepoint reached.
1164
        upgrade_main_savepoint(true, 2024110800.02);
1165
    }
1166
 
1167
    if ($oldversion < 2024111500.00) {
1168
 
1169
        // Changing precision of field fullname on table course to (1333).
1170
        $table = new xmldb_table('course');
1171
        $field = new xmldb_field('fullname', XMLDB_TYPE_CHAR, '1333', null, XMLDB_NOTNULL, null, null, 'sortorder');
1172
 
1173
        // Launch change of precision for field fullname.
1174
        $dbman->change_field_precision($table, $field);
1175
 
1176
        // Main savepoint reached.
1177
        upgrade_main_savepoint(true, 2024111500.00);
1178
    }
1179
 
1180
    if ($oldversion < 2024111500.01) {
1181
 
1182
        // Changing precision of field fullname on table course_request to (1333).
1183
        $table = new xmldb_table('course_request');
1184
        $field = new xmldb_field('fullname', XMLDB_TYPE_CHAR, '1333', null, XMLDB_NOTNULL, null, null, 'id');
1185
 
1186
        // Launch change of precision for field fullname.
1187
        $dbman->change_field_precision($table, $field);
1188
 
1189
        // Main savepoint reached.
1190
        upgrade_main_savepoint(true, 2024111500.01);
1191
    }
1192
 
1193
    // Now we want to change the precision of course_request.shortname.
1194
    // To do this, we need to first drop the index, then re-create it.
1195
    if ($oldversion < 2024111500.02) {
1196
 
1197
        // Define index shortname (not unique) to be dropped form course_request.
1198
        $table = new xmldb_table('course_request');
1199
        $index = new xmldb_index('shortname', XMLDB_INDEX_NOTUNIQUE, ['shortname']);
1200
 
1201
        // Conditionally launch drop index shortname.
1202
        if ($dbman->index_exists($table, $index)) {
1203
            $dbman->drop_index($table, $index);
1204
        }
1205
 
1206
        // Main savepoint reached.
1207
        upgrade_main_savepoint(true, 2024111500.02);
1208
    }
1209
 
1210
    if ($oldversion < 2024111500.03) {
1211
 
1212
        // Changing precision of field shortname on table course_request to (255).
1213
        $table = new xmldb_table('course_request');
1214
        $field = new xmldb_field('shortname', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, 'fullname');
1215
 
1216
        // Launch change of precision for field shortname.
1217
        $dbman->change_field_precision($table, $field);
1218
 
1219
        // Main savepoint reached.
1220
        upgrade_main_savepoint(true, 2024111500.03);
1221
    }
1222
 
1223
    if ($oldversion < 2024111500.04) {
1224
 
1225
        // Define index shortname (not unique) to be added to course_request.
1226
        $table = new xmldb_table('course_request');
1227
        $index = new xmldb_index('shortname', XMLDB_INDEX_NOTUNIQUE, ['shortname']);
1228
 
1229
        // Conditionally launch add index shortname.
1230
        if (!$dbman->index_exists($table, $index)) {
1231
            $dbman->add_index($table, $index);
1232
        }
1233
 
1234
        // Main savepoint reached.
1235
        upgrade_main_savepoint(true, 2024111500.04);
1236
    }
1237
 
1238
    if ($oldversion < 2024112900.01) {
1239
 
1240
        // Define table reportbuilder_user_filter to be created.
1241
        $table = new xmldb_table('reportbuilder_user_filter');
1242
 
1243
        // Adding fields to table reportbuilder_user_filter.
1244
        $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
1245
        $table->add_field('reportid', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0');
1246
        $table->add_field('filterdata', XMLDB_TYPE_TEXT, null, null, XMLDB_NOTNULL, null, null);
1247
        $table->add_field('usercreated', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0');
1248
        $table->add_field('usermodified', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0');
1249
        $table->add_field('timecreated', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0');
1250
        $table->add_field('timemodified', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0');
1251
 
1252
        // Adding keys to table reportbuilder_user_filter.
1253
        $table->add_key('primary', XMLDB_KEY_PRIMARY, ['id']);
1254
        $table->add_key('reportid', XMLDB_KEY_FOREIGN, ['reportid'], 'reportbuilder_report', ['id']);
1255
        $table->add_key('usercreated', XMLDB_KEY_FOREIGN, ['usercreated'], 'user', ['id']);
1256
        $table->add_key('usermodified', XMLDB_KEY_FOREIGN, ['usermodified'], 'user', ['id']);
1257
 
1258
        // Adding indexes to table reportbuilder_user_filter.
1259
        $table->add_index('report-user', XMLDB_INDEX_UNIQUE, ['reportid', 'usercreated']);
1260
 
1261
        // Conditionally launch create table for reportbuilder_user_filter.
1262
        if (!$dbman->table_exists($table)) {
1263
            $dbman->create_table($table);
1264
        }
1265
 
1266
        // Main savepoint reached.
1267
        upgrade_main_savepoint(true, 2024112900.01);
1268
    }
1269
 
1270
    if ($oldversion < 2024112900.02) {
1271
 
1272
        // Structure to collect current user filter preferences.
1273
        $userfilterdata = [];
1274
 
1275
        $select = $DB->sql_like('name', '?');
1276
        $params = [$DB->sql_like_escape('reportbuilder-report-') . '%'];
1277
 
1278
        $preferences = $DB->get_records_select('user_preferences', $select, $params, 'userid, name');
1279
        foreach ($preferences as $preference) {
1280
            preg_match('/^reportbuilder-report-(?<reportid>\d+)-/', $preference->name, $matches);
1281
            $userfilterdata[$preference->userid][$matches['reportid']][] = $preference->value;
1282
        }
1283
 
1284
        // Migrate user filter preferences to new schema (combining previously chunked values due to size limitation).
1285
        foreach ($userfilterdata as $userid => $reportfilterdata) {
1286
            foreach ($reportfilterdata as $reportid => $filterdata) {
1287
                $DB->insert_record('reportbuilder_user_filter', (object) [
1288
                    'reportid' => $reportid,
1289
                    'filterdata' => implode('', $filterdata),
1290
                    'usercreated' => $userid,
1291
                    'usermodified' => $userid,
1292
                    'timecreated' => time(),
1293
                    'timemodified' => time(),
1294
                ]);
1295
            }
1296
        }
1297
 
1298
        // Clean up old user filter preferences.
1299
        $DB->delete_records_select('user_preferences', $select, $params);
1300
 
1301
        // Main savepoint reached.
1302
        upgrade_main_savepoint(true, 2024112900.02);
1303
    }
1304
 
1305
    // Moodle 5.0 Upgrade.
1306
    if ($oldversion < 2024121800.00) {
1307
        $smsgateways = $DB->get_records('sms_gateways');
1308
        foreach ($smsgateways as $gateway) {
1309
            $newconfig = json_decode($gateway->config);
1310
            // Continue only if either the `returnurl` OR the `saveandreturn` property exists.
1311
            if (property_exists($newconfig, "returnurl") || property_exists($newconfig, "saveandreturn")) {
1312
                // Remove unnecessary data in the config.
1313
                unset($newconfig->returnurl, $newconfig->saveandreturn);
1314
 
1315
                // Update the record with the new config.
1316
                $gateway->config = json_encode($newconfig);
1317
                $DB->update_record('sms_gateways', $gateway);
1318
            }
1319
        }
1320
 
1321
        // Main savepoint reached.
1322
        upgrade_main_savepoint(true, 2024121800.00);
1323
    }
1324
 
1325
    if ($oldversion < 2024121900.01) {
1326
        // Enable mod_subsection unless 'keepsubsectiondisabled' is set.
1327
        if ((empty($CFG->keepsubsectiondisabled) || !$CFG->keepsubsectiondisabled)
1328
                && $DB->get_record('modules', ['name' => 'subsection'])) {
1329
            $manager = \core_plugin_manager::resolve_plugininfo_class('mod');
1330
            $manager::enable_plugin('subsection', 1);
1331
        }
1332
 
1333
        // Main savepoint reached.
1334
        upgrade_main_savepoint(true, 2024121900.01);
1335
    }
1336
 
1337
    if ($oldversion < 2025011700.02) {
1338
        // Define table ai_providers to be created.
1339
        $table = new xmldb_table('ai_providers');
1340
 
1341
        // Adding fields to table ai_providers.
1342
        $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
1343
        $table->add_field('name', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null);
1344
        $table->add_field('provider', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null);
1345
        $table->add_field('enabled', XMLDB_TYPE_INTEGER, '1', null, XMLDB_NOTNULL, null, '1');
1346
        $table->add_field('config', XMLDB_TYPE_TEXT, null, null, XMLDB_NOTNULL, null, null);
1347
        $table->add_field('actionconfig', XMLDB_TYPE_TEXT, null, null, null, null, null);
1348
 
1349
        // Adding keys to table ai_provider.
1350
        $table->add_key('primary', XMLDB_KEY_PRIMARY, ['id']);
1351
 
1352
        // Adding indexes to table ai_provider.
1353
        $table->add_index('provider', XMLDB_INDEX_NOTUNIQUE, ['provider']);
1354
 
1355
        // Conditionally launch create table for ai_provider.
1356
        if (!$dbman->table_exists($table)) {
1357
            $dbman->create_table($table);
1358
        }
1359
 
1360
        // Now the instance table exists, migrate the existing providers.
1361
        upgrade_convert_ai_providers_to_instances();
1362
 
1363
        // Main savepoint reached.
1364
        upgrade_main_savepoint(true, 2025011700.02);
1365
    }
1366
 
1367
    if ($oldversion < 2025012400.01) {
1368
        // Remove the default value for the apiversion field.
1369
        $table = new xmldb_table('badge_external_backpack');
1370
        $apiversionfield = new xmldb_field('apiversion', XMLDB_TYPE_CHAR, '12', null, XMLDB_NOTNULL, null, null);
1371
        $dbman->change_field_default($table, $apiversionfield);
1372
 
1373
        // Main savepoint reached.
1374
        upgrade_main_savepoint(true, 2025012400.01);
1375
    }
1376
 
1377
    if ($oldversion < 2025013100.01) {
1378
        // Remove imageauthorname, imageauthoremail and imageauthorurl fields for badges.
1379
        $table = new xmldb_table('badge');
1380
        $fields = [
1381
            'imageauthorname',
1382
            'imageauthoremail',
1383
            'imageauthorurl',
1384
        ];
1385
 
1386
        foreach ($fields as $field) {
1387
            $field = new xmldb_field($field);
1388
            if ($dbman->field_exists($table, $field)) {
1389
                $dbman->drop_field($table, $field);
1390
            }
1391
        }
1392
 
1393
        // Main savepoint reached.
1394
        upgrade_main_savepoint(true, 2025013100.01);
1395
    }
1396
 
1397
    if ($oldversion < 2025022100.01) {
1398
        // Define table ai_action_explain_text to be created.
1399
        $table = new xmldb_table('ai_action_explain_text');
1400
 
1401
        // Adding fields to table ai_action_explain_text.
1402
        $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
1403
        $table->add_field('prompt', XMLDB_TYPE_TEXT, null, null, null, null, null);
1404
        $table->add_field('responseid', XMLDB_TYPE_CHAR, '128', null, null, null, null);
1405
        $table->add_field('fingerprint', XMLDB_TYPE_CHAR, '128', null, null, null, null);
1406
        $table->add_field('generatedcontent', XMLDB_TYPE_TEXT, null, null, null, null, null);
1407
        $table->add_field('finishreason', XMLDB_TYPE_CHAR, '128', null, null, null, null);
1408
        $table->add_field('prompttokens', XMLDB_TYPE_INTEGER, '10', null, null, null, null);
1409
        $table->add_field('completiontoken', XMLDB_TYPE_INTEGER, '10', null, null, null, null);
1410
 
1411
        // Adding keys to table ai_action_explain_text.
1412
        $table->add_key('primary', XMLDB_KEY_PRIMARY, ['id']);
1413
 
1414
        // Conditionally launch create table for ai_action_explain_text.
1415
        if (!$dbman->table_exists($table)) {
1416
            $dbman->create_table($table);
1417
        }
1418
 
1419
        // Add explain action config to the AI providers.
1420
        upgrade_add_explain_action_to_ai_providers();
1421
 
1422
        // Main savepoint reached.
1423
        upgrade_main_savepoint(true, 2025022100.01);
1424
    }
1425
 
1426
    if ($oldversion < 2025022100.02) {
1427
        // Due to a code restriction on the upgrade, invoking any core functions is not permitted.
1428
        // Thus, to acquire the list of provider plugins,
1429
        // we should extract them from the `config_plugins` database table.
1430
        $condition = $DB->sql_like('plugin', ':pattern');
1431
        $params = ['pattern' => 'aiprovider_%', 'name' => 'version'];
1432
        $sql = "SELECT plugin FROM {config_plugins} WHERE {$condition} AND name = :name";
1433
        $providers = $DB->get_fieldset_sql($sql, $params);
1434
        foreach ($providers as $provider) {
1435
            // Replace the provider's language string with the provider component's name.
1436
            if (get_string_manager()->string_exists('pluginname', $provider)) {
1437
                $providername = get_string('pluginname', $provider);
1438
                $sql = 'UPDATE {ai_action_register}
1439
                        SET provider = :provider
1440
                        WHERE LOWER(provider) = :providername';
1441
                $DB->execute($sql, ['provider' => $provider, 'providername' => strtolower($providername)]);
1442
            }
1443
        }
1444
 
1445
        // Main savepoint reached.
1446
        upgrade_main_savepoint(true, 2025022100.02);
1447
    }
1448
 
1449
    // Uninstall auth_cas and remove dependencies.
1450
    if ($oldversion < 2025030500.00) {
1451
        if (!file_exists($CFG->dirroot . "/auth/cas/version.php")) {
1452
            uninstall_plugin('auth', 'cas');
1453
 
1454
            // Remove the sensiblesettings config for auth_cas.
1455
            $sensiblesettingsraw = explode(',', get_config('adminpresets', 'sensiblesettings'));
1456
            $sensiblesettings = array_map('trim', $sensiblesettingsraw);
1457
 
1458
            if (($key = array_search('bind_pw@@auth_cas', $sensiblesettings)) !== false) {
1459
                unset($sensiblesettings[$key]);
1460
            }
1461
            $sensiblesettings = implode(', ', $sensiblesettings);
1462
            set_config('sensiblesettings', $sensiblesettings, 'adminpresets');
1463
        }
1464
 
1465
        // Main savepoint reached.
1466
        upgrade_main_savepoint(true, 2025030500.00);
1467
    }
1468
 
1469
    if ($oldversion < 2025030500.01) {
1470
        // If atto is no longer present, remove it.
1471
        if (!file_exists("{$CFG->dirroot}/lib/editor/atto/version.php")) {
1472
            // Remove each of the subplugins first. These are no longer on disk so the standard `uninstall_plugin` approach
1473
            // on atto itself will not remove them.
1474
            $plugins = array_keys(core_plugin_manager::instance()->get_plugins_of_type('atto'));
1475
 
1476
            // Now remove each.
1477
            foreach ($plugins as $pluginname) {
1478
                uninstall_plugin('atto', $pluginname);
1479
            }
1480
 
1481
            // Finally uninstall the actual plugin.
1482
            uninstall_plugin('editor', 'atto');
1483
        }
1484
 
1485
        upgrade_main_savepoint(true, 2025030500.01);
1486
    }
1487
 
1488
    // Remove portfolio_mahara.
1489
    if ($oldversion < 2025030600.02) {
1490
        if (!file_exists($CFG->dirroot . "/portfolio/mahara/version.php")) {
1491
            uninstall_plugin('portfolio', 'mahara');
1492
        }
1493
        // Main savepoint reached.
1494
        upgrade_main_savepoint(true, 2025030600.02);
1495
    }
1496
 
1497
    // Remove enrol_mnet.
1498
    if ($oldversion < 2025030600.03) {
1499
        if (!file_exists($CFG->dirroot . "/enrol/mnet/version.php")) {
1500
            uninstall_plugin('enrol', 'mnet');
1501
        }
1502
        // Main savepoint reached.
1503
        upgrade_main_savepoint(true, 2025030600.03);
1504
    }
1505
 
1506
    // Remove block_mnet_hosts.
1507
    if ($oldversion < 2025030600.04) {
1508
        if (!file_exists($CFG->dirroot . "/blocks/mnet_hosts/version.php")) {
1509
            uninstall_plugin('block', 'mnet_hosts');
1510
 
1511
            // Delete all the admin preset plugin states concerning mnet_hosts in adminpresets_plug table.
1512
            $DB->delete_records('adminpresets_plug', ['name' => 'mnet_hosts']);
1513
        }
1514
 
1515
        // Main savepoint reached.
1516
        upgrade_main_savepoint(true, 2025030600.04);
1517
    }
1518
 
1519
    // Remove auth_mnet.
1520
    if ($oldversion < 2025030600.05) {
1521
        if (!file_exists($CFG->dirroot . "/auth/mnet/version.php")) {
1522
            uninstall_plugin('auth', 'mnet');
1523
        }
1524
        // Main savepoint reached.
1525
        upgrade_main_savepoint(true, 2025030600.05);
1526
    }
1527
 
1528
    if ($oldversion < 2025030600.06) {
1529
        // If mlbackend_php is no longer present, remove it.
1530
        if (!file_exists($CFG->dirroot . '/lib/mlbackend/php/version.php')) {
1531
            // Clean config.
1532
            uninstall_plugin('mlbackend', 'php');
1533
 
1534
            // Change the processor if mlbackend_php is set.
1535
            if (get_config('analytics', 'predictionsprocessor') === '\mlbackend_php\processor') {
1536
                set_config('predictionsprocessor', '\mlbackend_python\processor', 'analytics');
1537
                // We can't be sure mlbackend_python is set up correctly, so we disable analytics.
1538
                set_config('enableanalytics', false);
1539
            }
1540
 
1541
            // Cleanup any references to mlbackend_php.
1542
            $select = $DB->sql_like('predictionsprocessor', ':predictionsprocessor', false);
1543
            $params = ['predictionsprocessor' => '%' . $DB->sql_like_escape('mlbackend_php') . '%'];
1544
            $DB->set_field_select(
1545
                table: 'analytics_models',
1546
                newfield: 'predictionsprocessor',
1547
                newvalue: null,
1548
                select: $select,
1549
                params: $params,
1550
            );
1551
        }
1552
 
1553
        // Main savepoint reached.
1554
        upgrade_main_savepoint(true, 2025030600.06);
1555
    }
1556
 
1557
    if ($oldversion < 2025030600.07) {
1558
        $providers = $DB->get_records('ai_providers', ['enabled' => 1]);
1559
        // Formatting the value.
1560
        $value = ','. implode(',', array_column($providers, 'id'));
1561
        // Create the order config setting.
1562
        set_config('provider_order', $value, 'core_ai');
1563
 
1564
        // Main savepoint reached.
1565
        upgrade_main_savepoint(true, 2025030600.07);
1566
    }
1567
 
1568
    // Remove mnetservice_enrol.
1569
    if ($oldversion < 2025030600.08) {
1570
        if (!file_exists($CFG->dirroot . "/mnet/service/enrol/version.php")) {
1571
            uninstall_plugin('mnetservice', 'enrol');
1572
        }
1573
        // Main savepoint reached.
1574
        upgrade_main_savepoint(true, 2025030600.08);
1575
    }
1576
 
1577
    if ($oldversion < 2025031800.00) {
1578
        // Add index for querying delegated sections.
1579
        $table = new xmldb_table('course_sections');
1580
        $index = new xmldb_index('component_itemid', XMLDB_INDEX_NOTUNIQUE, ['component', 'itemid']);
1581
 
1582
        if (!$dbman->index_exists($table, $index)) {
1583
            $dbman->add_index($table, $index);
1584
        }
1585
        // Main savepoint reached.
1586
        upgrade_main_savepoint(true, 2025031800.00);
1587
    }
1588
 
1589
    if ($oldversion < 2025031800.03) {
1590
 
1591
        // Define field penalty to be added to grade_grades.
1592
        $table = new xmldb_table('grade_grades');
1593
        $field = new xmldb_field('deductedmark', XMLDB_TYPE_NUMBER, '10, 5', null,
1594
            XMLDB_NOTNULL, null, '0', 'aggregationweight');
1595
 
1596
        // Conditionally launch add field penalty.
1597
        if (!$dbman->field_exists($table, $field)) {
1598
            $dbman->add_field($table, $field);
1599
        }
1600
 
1601
        // Main savepoint reached.
1602
        upgrade_main_savepoint(true, 2025031800.03);
1603
    }
1604
 
1605
    if ($oldversion < 2025031800.04) {
1606
 
1607
        // Define field overriddenmark to be added to grade_grades.
1608
        $table = new xmldb_table('grade_grades');
1609
        $field = new xmldb_field('overriddenmark', XMLDB_TYPE_NUMBER, '10, 5', null,
1610
            XMLDB_NOTNULL, null, '0', 'deductedmark');
1611
 
1612
        // Conditionally launch add field penalty.
1613
        if (!$dbman->field_exists($table, $field)) {
1614
            $dbman->add_field($table, $field);
1615
        }
1616
 
1617
        // Main savepoint reached.
1618
        upgrade_main_savepoint(true, 2025031800.04);
1619
    }
1620
 
1621
    if ($oldversion < 2025032800.01) {
1622
        // Upgrade webp mime type for existing webp files.
1623
        upgrade_create_async_mimetype_upgrade_task('image/webp', ['webp']);
1624
 
1625
        // Main savepoint reached.
1626
        upgrade_main_savepoint(true, 2025032800.01);
1627
    }
1628
 
1629
    // Remove chat and survey and respective analytics indicators.
1630
    if ($oldversion < 2025040100.01) {
1631
        $indicatorstoremove = [];
1632
        $sqllikes = [];
1633
        $sqlparams = [];
1634
 
1635
        if (!file_exists($CFG->dirroot . "/mod/survey/version.php")) {
1636
            uninstall_plugin('mod', 'survey');
1637
            $DB->delete_records('adminpresets_plug', ['plugin' => 'mod', 'name' => 'survey']);
1638
            $indicatorstoremove['survey'] = [
1639
                '\mod_survey\analytics\indicator\cognitive_depth',
1640
                '\mod_survey\analytics\indicator\social_breadth',
1641
            ];
1642
            $sqlparams['surveypluginname'] = '%' . $DB->sql_like_escape('mod_survey') . '%';
1643
            $sqllikes['survey'] = $DB->sql_like('indicators', ':surveypluginname');
1644
        }
1645
        if (!file_exists($CFG->dirroot . "/mod/chat/version.php")) {
1646
            uninstall_plugin('mod', 'chat');
1647
            $DB->delete_records('adminpresets_plug', ['plugin' => 'mod', 'name' => 'chat']);
1648
            $indicatorstoremove['chat'] = [
1649
                '\mod_chat\analytics\indicator\cognitive_depth',
1650
                '\mod_chat\analytics\indicator\social_breadth',
1651
            ];
1652
            $sqlparams['chatpluginname'] = '%' . $DB->sql_like_escape('mod_chat') . '%';
1653
            $sqllikes['chat'] = $DB->sql_like('indicators', ':chatpluginname');
1654
        }
1655
 
1656
        foreach ($indicatorstoremove as $module => $indicators) {
1657
            $models = $DB->get_recordset_select('analytics_models', $sqllikes[$module], $sqlparams);
1658
            foreach ($models as $model) {
1659
                $currentindicators = json_decode($model->indicators, true);
1660
                if (!empty($indicators) && !empty($currentindicators)) {
1661
                    $newindicators = array_values(array_diff($currentindicators, $indicators));
1662
                    $model->indicators = json_encode($newindicators);
1663
                    $DB->update_record('analytics_models', $model);
1664
                }
1665
            }
1666
            $models->close();
1667
        }
1668
        // Main savepoint reached.
1669
        upgrade_main_savepoint(true, 2025040100.01);
1670
    }
1671
 
1672
    // Remove overriddenmark field from grade_grades.
1673
    if ($oldversion < 2025040700.00) {
1674
        $table = new xmldb_table('grade_grades');
1675
        $field = new xmldb_field('overriddenmark');
1676
        if ($dbman->field_exists($table, $field)) {
1677
            $dbman->drop_field($table, $field);
1678
        }
1679
 
1680
        // Main savepoint reached.
1681
        upgrade_main_savepoint(true, 2025040700.00);
1682
    }
1683
 
1684
    // Automatically generated Moodle v5.0.0 release upgrade line.
1685
    // Put any upgrade step following this.
1686
 
1687
    if ($oldversion < 2025041400.09) {
1688
 
1689
        // Define field systememail to be added to oauth2_issuer.
1690
        $table = new xmldb_table('oauth2_issuer');
1691
        $field = new xmldb_field('systememail', XMLDB_TYPE_CHAR, '100', null, null, null, null, 'loginpagename');
1692
 
1693
        // Conditionally launch add field systememail.
1694
        if (!$dbman->field_exists($table, $field)) {
1695
            $dbman->add_field($table, $field);
1696
        }
1697
 
1698
        // Main savepoint reached.
1699
        upgrade_main_savepoint(true, 2025041400.09);
1700
    }
1701
 
1702
    if ($oldversion < 2025041401.08) {
1703
        // Get all OpenAI providers.
1704
        $records = $DB->get_records('ai_providers', ['provider' => 'aiprovider_openai\provider']);
1705
 
1706
        foreach ($records as $record) {
1707
            $actionconfig = json_decode($record->actionconfig, true, 512);
1708
            $originalactionconfig = $actionconfig;
1709
 
1710
            foreach ($actionconfig as $actionkey => $action) {
1711
                $model = $action['settings']['model'];
1712
                if ($model === 'gpt-4o' || $model === 'o1') {
1713
                    // Rename setting max_tokens to max_completion_tokens.
1714
                    if (isset($action['settings']['max_tokens'])) {
1715
                        $actionconfig[$actionkey]['settings']['max_completion_tokens'] = intval($action['settings']['max_tokens']);
1716
                        unset($actionconfig[$actionkey]['settings']['max_tokens']);
1717
                    }
1718
                }
1719
                // Cast settings for 'gpt-4o' model.
1720
                if ($model === 'gpt-4o') {
1721
                    if (isset($action['settings']['top_p'])) {
1722
                        $actionconfig[$actionkey]['settings']['top_p'] = floatval($action['settings']['top_p']);
1723
                    }
1724
                    if (isset($action['settings']['presence_penalty'])) {
1725
                        $actionconfig[$actionkey]['settings']['presence_penalty'] =
1726
                            floatval($action['settings']['presence_penalty']);
1727
                    }
1728
                    if (isset($action['settings']['frequency_penalty'])) {
1729
                        $actionconfig[$actionkey]['settings']['frequency_penalty'] =
1730
                            floatval($action['settings']['frequency_penalty']);
1731
                    }
1732
                }
1733
                // Remove settings from 'o1' model.
1734
                if ($model === 'o1') {
1735
                    if (isset($action['settings']['top_p'])) {
1736
                        unset($actionconfig[$actionkey]['settings']['top_p']);
1737
                    }
1738
                    if (isset($action['settings']['presence_penalty'])) {
1739
                        unset($actionconfig[$actionkey]['settings']['presence_penalty']);
1740
                    }
1741
                    if (isset($action['settings']['frequency_penalty'])) {
1742
                        unset($actionconfig[$actionkey]['settings']['frequency_penalty']);
1743
                    }
1744
                }
1745
            }
1746
 
1747
            if ($originalactionconfig !== $actionconfig) {
1748
                $updatedrecord = new stdClass();
1749
                $updatedrecord->id = $record->id;
1750
                $updatedrecord->actionconfig = json_encode($actionconfig);
1751
                $DB->update_record('ai_providers', $updatedrecord);
1752
            }
1753
        }
1754
 
1755
        // Main savepoint reached.
1756
        upgrade_main_savepoint(true, 2025041401.08);
1757
    }
1758
 
1759
    if ($oldversion < 2025041401.10) {
1760
        // A [name => url] map of new OIDC endpoints to be updated/created.
1761
        $endpointuris = [
1762
            'discovery_endpoint' => 'https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration',
1763
            'token_endpoint' => 'https://login.microsoftonline.com/common/oauth2/v2.0/token',
1764
            'userinfo_endpoint' => 'https://graph.microsoft.com/oidc/userinfo',
1765
            'authorization_endpoint' => 'https://login.microsoftonline.com/common/oauth2/v2.0/authorize',
1766
            'device_authorization_endpoint' => 'https://login.microsoftonline.com/common/oauth2/v2.0/devicecode',
1767
            'end_session_endpoint' => 'https://login.microsoftonline.com/common/oauth2/v2.0/logout',
1768
            'kerberos_endpoint' => 'https://login.microsoftonline.com/common/kerberos',
1769
        ];
1770
        // A [name] map of endpoints to be deleted.
1771
        $deletedendpointuris = [
1772
            'userpicture_endpoint',
1773
        ];
1774
        // A [internalfield => externalfield] map of new OIDC-based user field mappings to be updated/created.
1775
        $userfieldmappings = [
1776
            'idnumber' => 'sub',
1777
            'firstname' => 'givenname',
1778
            'lastname' => 'familyname',
1779
            'email' => 'email',
1780
            'lang' => 'locale',
1781
        ];
1782
        $admin = get_admin();
1783
        $adminid = $admin ? $admin->id : '0';
1784
        $microsoftservices = $DB->get_records('oauth2_issuer', ['servicetype' => 'microsoft']);
1785
        foreach ($microsoftservices as $microsoftservice) {
1786
            $time = time();
1787
            if (strpos($microsoftservice->baseurl, 'common') !== false) {
1788
                // Multi-tenant endpoint, proceed with upgrade.
1789
                // Insert/update the new endpoints.
1790
                foreach ($endpointuris as $endpointname => $endpointuri) {
1791
                    $endpoint = ['issuerid' => $microsoftservice->id, 'name' => $endpointname];
1792
                    $endpointid = $DB->get_field('oauth2_endpoint', 'id', $endpoint);
1793
                    if ($endpointid) {
1794
                        $endpoint = array_merge($endpoint, [
1795
                            'id' => $endpointid,
1796
                            'url' => $endpointuri,
1797
                            'timemodified' => $time,
1798
                            'usermodified' => $adminid,
1799
                        ]);
1800
                        $DB->update_record('oauth2_endpoint', $endpoint);
1801
                    } else {
1802
                        $endpoint = array_merge($endpoint, [
1803
                            'url' => $endpointuri,
1804
                            'timecreated' => $time,
1805
                            'timemodified' => $time,
1806
                            'usermodified' => $adminid,
1807
                        ]);
1808
                        $DB->insert_record('oauth2_endpoint', $endpoint);
1809
                    }
1810
                }
1811
                // Delete the old endpoints.
1812
                foreach ($deletedendpointuris as $endpointname) {
1813
                    $endpoint = ['issuerid' => $microsoftservice->id, 'name' => $endpointname];
1814
                    $DB->delete_records('oauth2_endpoint', $endpoint);
1815
                }
1816
                // Insert/update new user field mappings.
1817
                foreach ($userfieldmappings as $internalfieldname => $externalfieldname) {
1818
                    $fieldmap = ['issuerid' => $microsoftservice->id, 'internalfield' => $internalfieldname];
1819
                    $fieldmapid = $DB->get_field('oauth2_user_field_mapping', 'id', $fieldmap);
1820
                    if ($fieldmapid) {
1821
                        $fieldmap = array_merge($fieldmap, [
1822
                            'id' => $fieldmapid,
1823
                            'externalfield' => $externalfieldname,
1824
                            'timemodified' => $time,
1825
                            'usermodified' => $adminid,
1826
                        ]);
1827
                        $DB->update_record('oauth2_user_field_mapping', $fieldmap);
1828
                    } else {
1829
                        $fieldmap = array_merge($fieldmap, [
1830
                            'externalfield' => $externalfieldname,
1831
                            'timecreated' => $time,
1832
                            'timemodified' => $time,
1833
                            'usermodified' => $adminid,
1834
                        ]);
1835
                        $DB->insert_record('oauth2_user_field_mapping', $fieldmap);
1836
                    }
1837
                }
1838
                // Update the baseurl for the issuer.
1839
                $microsoftservice->baseurl = 'https://login.microsoftonline.com/common/v2.0';
1840
                $microsoftservice->timemodified = $time;
1841
                $microsoftservice->usermodified = $adminid;
1842
                $DB->update_record('oauth2_issuer', $microsoftservice);
1843
            } else {
1844
                // Single-tenant endpoint, add discovery_endpoint if it doesn't exist.
1845
                $url = $microsoftservice->baseurl;
1846
                $url .= (substr($url, -1) === '/') ? '' : '/';
1847
                $url .= '.well-known/openid-configuration';
1848
                $endpoint = ['issuerid' => $microsoftservice->id, 'name' => 'discovery_endpoint'];
1849
                $endpointid = $DB->get_field('oauth2_endpoint', 'id', $endpoint);
1850
                if (!$endpointid) {
1851
                    $endpoint = array_merge($endpoint, [
1852
                        'url' => $url,
1853
                        'timecreated' => $time,
1854
                        'timemodified' => $time,
1855
                        'usermodified' => $adminid,
1856
                    ]);
1857
                    $DB->insert_record('oauth2_endpoint', $endpoint);
1858
                }
1859
            }
1860
        }
1861
        // Main savepoint reached.
1862
        upgrade_main_savepoint(true, 2025041401.10);
1863
    }
1864
 
1 efrain 1865
    return true;
1866
}