MDL-64790 upgrade: parameter API doc regression fix
[moodle.git] / lib / upgradelib.php
CommitLineData
96db14f9 1<?php
2
3// This file is part of Moodle - http://moodle.org/
4//
5// Moodle is free software: you can redistribute it and/or modify
6// it under the terms of the GNU General Public License as published by
7// the Free Software Foundation, either version 3 of the License, or
8// (at your option) any later version.
9//
10// Moodle is distributed in the hope that it will be useful,
11// but WITHOUT ANY WARRANTY; without even the implied warranty of
12// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13// GNU General Public License for more details.
14//
15// You should have received a copy of the GNU General Public License
16// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
db9d4a3d 17
18/**
8580535b 19 * Various upgrade/install related functions and classes.
db9d4a3d 20 *
78bfb562 21 * @package core
96db14f9 22 * @subpackage upgrade
23 * @copyright 1999 onwards Martin Dougiamas (http://dougiamas.com)
24 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
db9d4a3d 25 */
26
78bfb562
PS
27defined('MOODLE_INTERNAL') || die();
28
72fb21b6 29/** UPGRADE_LOG_NORMAL = 0 */
db9d4a3d 30define('UPGRADE_LOG_NORMAL', 0);
72fb21b6 31/** UPGRADE_LOG_NOTICE = 1 */
db9d4a3d 32define('UPGRADE_LOG_NOTICE', 1);
72fb21b6 33/** UPGRADE_LOG_ERROR = 2 */
795a08ad 34define('UPGRADE_LOG_ERROR', 2);
35
36/**
37 * Exception indicating unknown error during upgrade.
72fb21b6 38 *
d32fb550 39 * @package core
72fb21b6 40 * @subpackage upgrade
d32fb550 41 * @copyright 2009 Petr Skoda {@link http://skodak.org}
72fb21b6 42 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
795a08ad 43 */
44class upgrade_exception extends moodle_exception {
4f0c2d00 45 function __construct($plugin, $version, $debuginfo=NULL) {
795a08ad 46 global $CFG;
47 $a = (object)array('plugin'=>$plugin, 'version'=>$version);
4f0c2d00 48 parent::__construct('upgradeerror', 'admin', "$CFG->wwwroot/$CFG->admin/index.php", $a, $debuginfo);
795a08ad 49 }
50}
51
52/**
53 * Exception indicating downgrade error during upgrade.
72fb21b6 54 *
d32fb550 55 * @package core
72fb21b6 56 * @subpackage upgrade
d32fb550 57 * @copyright 2009 Petr Skoda {@link http://skodak.org}
72fb21b6 58 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
795a08ad 59 */
60class downgrade_exception extends moodle_exception {
61 function __construct($plugin, $oldversion, $newversion) {
62 global $CFG;
63 $plugin = is_null($plugin) ? 'moodle' : $plugin;
64 $a = (object)array('plugin'=>$plugin, 'oldversion'=>$oldversion, 'newversion'=>$newversion);
65 parent::__construct('cannotdowngrade', 'debug', "$CFG->wwwroot/$CFG->admin/index.php", $a);
66 }
67}
68
72fb21b6 69/**
d32fb550 70 * @package core
72fb21b6 71 * @subpackage upgrade
d32fb550 72 * @copyright 2009 Petr Skoda {@link http://skodak.org}
72fb21b6 73 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
74 */
795a08ad 75class upgrade_requires_exception extends moodle_exception {
76 function __construct($plugin, $pluginversion, $currentmoodle, $requiremoodle) {
77 global $CFG;
365a5941 78 $a = new stdClass();
795a08ad 79 $a->pluginname = $plugin;
80 $a->pluginversion = $pluginversion;
81 $a->currentmoodle = $currentmoodle;
17da2e6f 82 $a->requiremoodle = $requiremoodle;
795a08ad 83 parent::__construct('pluginrequirementsnotmet', 'error', "$CFG->wwwroot/$CFG->admin/index.php", $a);
84 }
85}
86
72fb21b6 87/**
d32fb550 88 * @package core
72fb21b6 89 * @subpackage upgrade
d32fb550 90 * @copyright 2009 Petr Skoda {@link http://skodak.org}
72fb21b6 91 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
92 */
795a08ad 93class plugin_defective_exception extends moodle_exception {
94 function __construct($plugin, $details) {
95 global $CFG;
96 parent::__construct('detectedbrokenplugin', 'error', "$CFG->wwwroot/$CFG->admin/index.php", $plugin, $details);
97 }
98}
db9d4a3d 99
bdbcb6d7 100/**
b3d5bd33
101 * Misplaced plugin exception.
102 *
103 * Note: this should be used only from the upgrade/admin code.
104 *
bdbcb6d7
PS
105 * @package core
106 * @subpackage upgrade
107 * @copyright 2009 Petr Skoda {@link http://skodak.org}
108 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
109 */
110class plugin_misplaced_exception extends moodle_exception {
b3d5bd33
111 /**
112 * Constructor.
113 * @param string $component the component from version.php
114 * @param string $expected expected directory, null means calculate
115 * @param string $current plugin directory path
116 */
117 public function __construct($component, $expected, $current) {
bdbcb6d7 118 global $CFG;
b3d5bd33
119 if (empty($expected)) {
120 list($type, $plugin) = core_component::normalize_component($component);
121 $plugintypes = core_component::get_plugin_types();
122 if (isset($plugintypes[$type])) {
123 $expected = $plugintypes[$type] . '/' . $plugin;
124 }
125 }
126 if (strpos($expected, '$CFG->dirroot') !== 0) {
127 $expected = str_replace($CFG->dirroot, '$CFG->dirroot', $expected);
128 }
129 if (strpos($current, '$CFG->dirroot') !== 0) {
130 $current = str_replace($CFG->dirroot, '$CFG->dirroot', $current);
131 }
bdbcb6d7
PS
132 $a = new stdClass();
133 $a->component = $component;
134 $a->expected = $expected;
135 $a->current = $current;
136 parent::__construct('detectedmisplacedplugin', 'core_plugin', "$CFG->wwwroot/$CFG->admin/index.php", $a);
137 }
138}
139
03440bcb 140/**
141 * Static class monitors performance of upgrade steps.
142 */
143class core_upgrade_time {
144 /** @var float Time at start of current upgrade (plugin/system) */
145 protected static $before;
146 /** @var float Time at end of last savepoint */
147 protected static $lastsavepoint;
83740b9f
JP
148 /** @var bool Flag to indicate whether we are recording timestamps or not. */
149 protected static $isrecording = false;
03440bcb 150
151 /**
152 * Records current time at the start of the current upgrade item, e.g. plugin.
153 */
154 public static function record_start() {
155 self::$before = microtime(true);
156 self::$lastsavepoint = self::$before;
83740b9f 157 self::$isrecording = true;
03440bcb 158 }
159
160 /**
161 * Records current time at the end of a given numbered step.
162 *
163 * @param float $version Version number (may have decimals, or not)
164 */
165 public static function record_savepoint($version) {
166 global $CFG, $OUTPUT;
167
168 // In developer debug mode we show a notification after each individual save point.
83740b9f 169 if ($CFG->debugdeveloper && self::$isrecording) {
03440bcb 170 $time = microtime(true);
171
172 $notification = new \core\output\notification($version . ': ' .
173 get_string('successduration', '', format_float($time - self::$lastsavepoint, 2)),
174 \core\output\notification::NOTIFY_SUCCESS);
175 $notification->set_show_closebutton(false);
176 echo $OUTPUT->render($notification);
177 self::$lastsavepoint = $time;
178 }
179 }
180
181 /**
182 * Gets the time since the record_start function was called, rounded to 2 digits.
183 *
184 * @return float Elapsed time
185 */
186 public static function get_elapsed() {
187 return microtime(true) - self::$before;
188 }
189}
190
0c5406ca
PS
191/**
192 * Sets maximum expected time needed for upgrade task.
193 * Please always make sure that upgrade will not run longer!
194 *
195 * The script may be automatically aborted if upgrade times out.
196 *
197 * @category upgrade
198 * @param int $max_execution_time in seconds (can not be less than 60 s)
199 */
200function upgrade_set_timeout($max_execution_time=300) {
201 global $CFG;
202
203 if (!isset($CFG->upgraderunning) or $CFG->upgraderunning < time()) {
204 $upgraderunning = get_config(null, 'upgraderunning');
205 } else {
206 $upgraderunning = $CFG->upgraderunning;
207 }
208
209 if (!$upgraderunning) {
b814d1b4
PS
210 if (CLI_SCRIPT) {
211 // never stop CLI upgrades
212 $upgraderunning = 0;
213 } else {
214 // web upgrade not running or aborted
215 print_error('upgradetimedout', 'admin', "$CFG->wwwroot/$CFG->admin/");
216 }
0c5406ca
PS
217 }
218
219 if ($max_execution_time < 60) {
220 // protection against 0 here
221 $max_execution_time = 60;
222 }
223
224 $expected_end = time() + $max_execution_time;
225
226 if ($expected_end < $upgraderunning + 10 and $expected_end > $upgraderunning - 10) {
227 // no need to store new end, it is nearly the same ;-)
228 return;
229 }
230
5563f5fb
PS
231 if (CLI_SCRIPT) {
232 // there is no point in timing out of CLI scripts, admins can stop them if necessary
3ef7279f 233 core_php_time_limit::raise();
5563f5fb 234 } else {
3ef7279f 235 core_php_time_limit::raise($max_execution_time);
5563f5fb 236 }
0c5406ca
PS
237 set_config('upgraderunning', $expected_end); // keep upgrade locked until this time
238}
239
db9d4a3d 240/**
241 * Upgrade savepoint, marks end of each upgrade block.
242 * It stores new main version, resets upgrade timeout
243 * and abort upgrade if user cancels page loading.
244 *
245 * Please do not make large upgrade blocks with lots of operations,
246 * for example when adding tables keep only one table operation per block.
247 *
39b90b51 248 * @category upgrade
db9d4a3d 249 * @param bool $result false if upgrade step failed, true if completed
250 * @param string or float $version main version
251 * @param bool $allowabort allow user to abort script execution here
252 * @return void
253 */
254function upgrade_main_savepoint($result, $version, $allowabort=true) {
255 global $CFG;
256
bb44ef99
RT
257 //sanity check to avoid confusion with upgrade_mod_savepoint usage.
258 if (!is_bool($allowabort)) {
259 $errormessage = 'Parameter type mismatch. Are you mixing up upgrade_main_savepoint() and upgrade_mod_savepoint()?';
260 throw new coding_exception($errormessage);
261 }
262
795a08ad 263 if (!$result) {
520cea92 264 throw new upgrade_exception(null, $version);
795a08ad 265 }
266
267 if ($CFG->version >= $version) {
268 // something really wrong is going on in main upgrade script
269 throw new downgrade_exception(null, $CFG->version, $version);
db9d4a3d 270 }
271
795a08ad 272 set_config('version', $version);
273 upgrade_log(UPGRADE_LOG_NORMAL, null, 'Upgrade savepoint reached');
274
db9d4a3d 275 // reset upgrade timeout to default
276 upgrade_set_timeout();
277
03440bcb 278 core_upgrade_time::record_savepoint($version);
279
db9d4a3d 280 // this is a safe place to stop upgrades if user aborts page loading
281 if ($allowabort and connection_aborted()) {
282 die;
283 }
284}
285
286/**
287 * Module upgrade savepoint, marks end of module upgrade blocks
288 * It stores module version, resets upgrade timeout
289 * and abort upgrade if user cancels page loading.
290 *
39b90b51 291 * @category upgrade
db9d4a3d 292 * @param bool $result false if upgrade step failed, true if completed
293 * @param string or float $version main version
294 * @param string $modname name of module
295 * @param bool $allowabort allow user to abort script execution here
296 * @return void
297 */
298function upgrade_mod_savepoint($result, $version, $modname, $allowabort=true) {
299 global $DB;
300
bde002b8
PS
301 $component = 'mod_'.$modname;
302
795a08ad 303 if (!$result) {
bde002b8 304 throw new upgrade_exception($component, $version);
795a08ad 305 }
306
bde002b8
PS
307 $dbversion = $DB->get_field('config_plugins', 'value', array('plugin'=>$component, 'name'=>'version'));
308
db9d4a3d 309 if (!$module = $DB->get_record('modules', array('name'=>$modname))) {
310 print_error('modulenotexist', 'debug', '', $modname);
311 }
312
bde002b8 313 if ($dbversion >= $version) {
795a08ad 314 // something really wrong is going on in upgrade script
bde002b8 315 throw new downgrade_exception($component, $dbversion, $version);
db9d4a3d 316 }
bde002b8
PS
317 set_config('version', $version, $component);
318
319 upgrade_log(UPGRADE_LOG_NORMAL, $component, 'Upgrade savepoint reached');
db9d4a3d 320
321 // reset upgrade timeout to default
322 upgrade_set_timeout();
323
03440bcb 324 core_upgrade_time::record_savepoint($version);
325
db9d4a3d 326 // this is a safe place to stop upgrades if user aborts page loading
327 if ($allowabort and connection_aborted()) {
328 die;
329 }
330}
331
332/**
333 * Blocks upgrade savepoint, marks end of blocks upgrade blocks
334 * It stores block version, resets upgrade timeout
335 * and abort upgrade if user cancels page loading.
336 *
39b90b51 337 * @category upgrade
db9d4a3d 338 * @param bool $result false if upgrade step failed, true if completed
339 * @param string or float $version main version
340 * @param string $blockname name of block
341 * @param bool $allowabort allow user to abort script execution here
342 * @return void
343 */
795a08ad 344function upgrade_block_savepoint($result, $version, $blockname, $allowabort=true) {
db9d4a3d 345 global $DB;
346
bde002b8
PS
347 $component = 'block_'.$blockname;
348
795a08ad 349 if (!$result) {
bde002b8 350 throw new upgrade_exception($component, $version);
795a08ad 351 }
352
bde002b8
PS
353 $dbversion = $DB->get_field('config_plugins', 'value', array('plugin'=>$component, 'name'=>'version'));
354
db9d4a3d 355 if (!$block = $DB->get_record('block', array('name'=>$blockname))) {
356 print_error('blocknotexist', 'debug', '', $blockname);
357 }
358
bde002b8 359 if ($dbversion >= $version) {
795a08ad 360 // something really wrong is going on in upgrade script
bde002b8 361 throw new downgrade_exception($component, $dbversion, $version);
db9d4a3d 362 }
bde002b8
PS
363 set_config('version', $version, $component);
364
365 upgrade_log(UPGRADE_LOG_NORMAL, $component, 'Upgrade savepoint reached');
db9d4a3d 366
367 // reset upgrade timeout to default
368 upgrade_set_timeout();
369
03440bcb 370 core_upgrade_time::record_savepoint($version);
371
db9d4a3d 372 // this is a safe place to stop upgrades if user aborts page loading
373 if ($allowabort and connection_aborted()) {
374 die;
375 }
376}
377
378/**
379 * Plugins upgrade savepoint, marks end of blocks upgrade blocks
380 * It stores plugin version, resets upgrade timeout
381 * and abort upgrade if user cancels page loading.
382 *
39b90b51 383 * @category upgrade
db9d4a3d 384 * @param bool $result false if upgrade step failed, true if completed
385 * @param string or float $version main version
88d0f635
NR
386 * @param string $type The type of the plugin.
387 * @param string $plugin The name of the plugin.
db9d4a3d 388 * @param bool $allowabort allow user to abort script execution here
389 * @return void
390 */
17da2e6f 391function upgrade_plugin_savepoint($result, $version, $type, $plugin, $allowabort=true) {
bde002b8
PS
392 global $DB;
393
17da2e6f 394 $component = $type.'_'.$plugin;
395
795a08ad 396 if (!$result) {
17da2e6f 397 throw new upgrade_exception($component, $version);
db9d4a3d 398 }
399
bde002b8
PS
400 $dbversion = $DB->get_field('config_plugins', 'value', array('plugin'=>$component, 'name'=>'version'));
401
402 if ($dbversion >= $version) {
795a08ad 403 // Something really wrong is going on in the upgrade script
bde002b8 404 throw new downgrade_exception($component, $dbversion, $version);
795a08ad 405 }
17da2e6f 406 set_config('version', $version, $component);
795a08ad 407 upgrade_log(UPGRADE_LOG_NORMAL, $component, 'Upgrade savepoint reached');
408
db9d4a3d 409 // Reset upgrade timeout to default
410 upgrade_set_timeout();
411
03440bcb 412 core_upgrade_time::record_savepoint($version);
413
db9d4a3d 414 // This is a safe place to stop upgrades if user aborts page loading
415 if ($allowabort and connection_aborted()) {
416 die;
417 }
418}
419
9008ec16
PS
420/**
421 * Detect if there are leftovers in PHP source files.
422 *
423 * During main version upgrades administrators MUST move away
424 * old PHP source files and start from scratch (or better
425 * use git).
426 *
427 * @return bool true means borked upgrade, false means previous PHP files were properly removed
428 */
429function upgrade_stale_php_files_present() {
430 global $CFG;
431
432 $someexamplesofremovedfiles = array(
512a1d31 433 // Removed in 3.6.
b08cdad2
EL
434 '/lib/classes/session/memcache.php',
435 '/lib/eventslib.php',
436 '/lib/form/submitlink.php',
d77b5db5 437 '/lib/medialib.php',
512a1d31 438 '/lib/password_compat/lib/password.php',
970df71d
EL
439 // Removed in 3.5.
440 '/lib/dml/mssql_native_moodle_database.php',
441 '/lib/dml/mssql_native_moodle_recordset.php',
442 '/lib/dml/mssql_native_moodle_temptables.php',
1ae99ec3
EL
443 // Removed in 3.4.
444 '/auth/README.txt',
445 '/calendar/set.php',
446 '/enrol/users.php',
447 '/enrol/yui/rolemanager/assets/skins/sam/rolemanager.css',
fea4557c
EL
448 // Removed in 3.3.
449 '/badges/backpackconnect.php',
450 '/calendar/yui/src/info/assets/skins/sam/moodle-calendar-info.css',
451 '/competency/classes/external/exporter.php',
452 '/mod/forum/forum.js',
453 '/user/pixgroup.php',
85ef6fe2
EL
454 // Removed in 3.2.
455 '/calendar/preferences.php',
456 '/lib/alfresco/',
457 '/lib/jquery/jquery-1.12.1.min.js',
458 '/lib/password_compat/tests/',
459 '/lib/phpunit/classes/unittestcase.php',
bbd7f7f7 460 // Removed in 3.1.
f8b059f2
EL
461 '/lib/classes/log/sql_internal_reader.php',
462 '/lib/zend/',
463 '/mod/forum/pix/icon.gif',
464 '/tag/templates/tagname.mustache',
5222ab7f
SC
465 // Removed in 3.0.
466 '/mod/lti/grade.php',
0d1e5456 467 '/tag/coursetagslib.php',
aac67170
AG
468 // Removed in 2.9.
469 '/lib/timezone.txt',
470 // Removed in 2.8.
471 '/course/delete_category_form.php',
4e8a07d2
TH
472 // Removed in 2.7.
473 '/admin/tool/qeupgradehelper/version.php',
474 // Removed in 2.6.
bde002b8 475 '/admin/block.php',
72e3a3c9 476 '/admin/oacleanup.php',
4e8a07d2 477 // Removed in 2.5.
c1782ec6
EL
478 '/backup/lib.php',
479 '/backup/bb/README.txt',
301ebbe5 480 '/lib/excel/test.php',
4e8a07d2 481 // Removed in 2.4.
c8b3346c 482 '/admin/tool/unittest/simpletestlib.php',
4e8a07d2 483 // Removed in 2.3.
37d72977 484 '/lib/minify/builder/',
4e8a07d2 485 // Removed in 2.2.
9008ec16 486 '/lib/yui/3.4.1pr1/',
4e8a07d2 487 // Removed in 2.2.
9008ec16
PS
488 '/search/cron_php5.php',
489 '/course/report/log/indexlive.php',
490 '/admin/report/backups/index.php',
491 '/admin/generator.php',
4e8a07d2 492 // Removed in 2.1.
9008ec16 493 '/lib/yui/2.8.0r4/',
4e8a07d2 494 // Removed in 2.0.
9008ec16
PS
495 '/blocks/admin/block_admin.php',
496 '/blocks/admin_tree/block_admin_tree.php',
497 );
498
499 foreach ($someexamplesofremovedfiles as $file) {
500 if (file_exists($CFG->dirroot.$file)) {
501 return true;
502 }
503 }
504
505 return false;
506}
db9d4a3d 507
508/**
509 * Upgrade plugins
db9d4a3d 510 * @param string $type The type of plugins that should be updated (e.g. 'enrol', 'qtype')
17da2e6f 511 * return void
db9d4a3d 512 */
17da2e6f 513function upgrade_plugins($type, $startcallback, $endcallback, $verbose) {
db9d4a3d 514 global $CFG, $DB;
515
516/// special cases
517 if ($type === 'mod') {
194cdca8 518 return upgrade_plugins_modules($startcallback, $endcallback, $verbose);
795a08ad 519 } else if ($type === 'block') {
194cdca8 520 return upgrade_plugins_blocks($startcallback, $endcallback, $verbose);
db9d4a3d 521 }
522
bd3b3bba 523 $plugs = core_component::get_plugin_list($type);
db9d4a3d 524
17da2e6f 525 foreach ($plugs as $plug=>$fullplug) {
ebb98bf5 526 // Reset time so that it works when installing a large number of plugins
3ef7279f 527 core_php_time_limit::raise(600);
aff24313 528 $component = clean_param($type.'_'.$plug, PARAM_COMPONENT); // standardised plugin name
db9d4a3d 529
3e858ea7 530 // check plugin dir is valid name
aff24313
PS
531 if (empty($component)) {
532 throw new plugin_defective_exception($type.'_'.$plug, 'Invalid plugin directory name.');
3e858ea7
PS
533 }
534
795a08ad 535 if (!is_readable($fullplug.'/version.php')) {
536 continue;
db9d4a3d 537 }
538
365a5941 539 $plugin = new stdClass();
bde002b8
PS
540 $plugin->version = null;
541 $module = $plugin; // Prevent some notices when plugin placed in wrong directory.
795a08ad 542 require($fullplug.'/version.php'); // defines $plugin with version etc
bde002b8 543 unset($module);
bdbcb6d7 544
98ea6973
DM
545 if (empty($plugin->version)) {
546 throw new plugin_defective_exception($component, 'Missing $plugin->version number in version.php.');
3e858ea7
PS
547 }
548
98ea6973
DM
549 if (empty($plugin->component)) {
550 throw new plugin_defective_exception($component, 'Missing $plugin->component declaration in version.php.');
551 }
552
553 if ($plugin->component !== $component) {
554 throw new plugin_misplaced_exception($plugin->component, null, $fullplug);
db9d4a3d 555 }
556
17da2e6f 557 $plugin->name = $plug;
558 $plugin->fullname = $component;
795a08ad 559
db9d4a3d 560 if (!empty($plugin->requires)) {
561 if ($plugin->requires > $CFG->version) {
795a08ad 562 throw new upgrade_requires_exception($component, $plugin->version, $CFG->version, $plugin->requires);
ef14c1e7
PS
563 } else if ($plugin->requires < 2010000000) {
564 throw new plugin_defective_exception($component, 'Plugin is not compatible with Moodle 2.x or later.');
db9d4a3d 565 }
566 }
567
9b683d13 568 // try to recover from interrupted install.php if needed
569 if (file_exists($fullplug.'/db/install.php')) {
570 if (get_config($plugin->fullname, 'installrunning')) {
571 require_once($fullplug.'/db/install.php');
572 $recover_install_function = 'xmldb_'.$plugin->fullname.'_install_recovery';
573 if (function_exists($recover_install_function)) {
574 $startcallback($component, true, $verbose);
575 $recover_install_function();
f6f06d69 576 unset_config('installrunning', $plugin->fullname);
9b683d13 577 update_capabilities($component);
c6d75bff 578 log_update_descriptions($component);
c976e271 579 external_update_descriptions($component);
309ae892 580 \core\task\manager::reset_scheduled_tasks_for_component($component);
9b683d13 581 message_update_providers($component);
6c0bfb14 582 \core\message\inbound\manager::update_handlers_for_component($component);
afed8d0f
RK
583 if ($type === 'message') {
584 message_update_processors($plug);
585 }
de260e0f 586 upgrade_plugin_mnet_functions($component);
c026a28d 587 core_tag_area::reset_definitions_for_component($component);
9b683d13 588 $endcallback($component, true, $verbose);
589 }
590 }
591 }
db9d4a3d 592
bde002b8 593 $installedversion = $DB->get_field('config_plugins', 'value', array('name'=>'version', 'plugin'=>$component)); // No caching!
795a08ad 594 if (empty($installedversion)) { // new installation
194cdca8 595 $startcallback($component, true, $verbose);
db9d4a3d 596
795a08ad 597 /// Install tables if defined
598 if (file_exists($fullplug.'/db/install.xml')) {
599 $DB->get_manager()->install_from_xmldb_file($fullplug.'/db/install.xml');
db9d4a3d 600 }
9b683d13 601
602 /// store version
603 upgrade_plugin_savepoint(true, $plugin->version, $type, $plug, false);
604
795a08ad 605 /// execute post install file
606 if (file_exists($fullplug.'/db/install.php')) {
607 require_once($fullplug.'/db/install.php');
f6f06d69
PS
608 set_config('installrunning', 1, $plugin->fullname);
609 $post_install_function = 'xmldb_'.$plugin->fullname.'_install';
795a08ad 610 $post_install_function();
f6f06d69 611 unset_config('installrunning', $plugin->fullname);
795a08ad 612 }
613
795a08ad 614 /// Install various components
615 update_capabilities($component);
c6d75bff 616 log_update_descriptions($component);
c976e271 617 external_update_descriptions($component);
309ae892 618 \core\task\manager::reset_scheduled_tasks_for_component($component);
795a08ad 619 message_update_providers($component);
6c0bfb14 620 \core\message\inbound\manager::update_handlers_for_component($component);
afed8d0f
RK
621 if ($type === 'message') {
622 message_update_processors($plug);
623 }
de260e0f 624 upgrade_plugin_mnet_functions($component);
c026a28d 625 core_tag_area::reset_definitions_for_component($component);
194cdca8 626 $endcallback($component, true, $verbose);
795a08ad 627
628 } else if ($installedversion < $plugin->version) { // upgrade
629 /// Run the upgrade function for the plugin.
194cdca8 630 $startcallback($component, false, $verbose);
795a08ad 631
632 if (is_readable($fullplug.'/db/upgrade.php')) {
633 require_once($fullplug.'/db/upgrade.php'); // defines upgrading function
634
635 $newupgrade_function = 'xmldb_'.$plugin->fullname.'_upgrade';
636 $result = $newupgrade_function($installedversion);
637 } else {
638 $result = true;
639 }
640
bde002b8 641 $installedversion = $DB->get_field('config_plugins', 'value', array('name'=>'version', 'plugin'=>$component)); // No caching!
795a08ad 642 if ($installedversion < $plugin->version) {
643 // store version if not already there
644 upgrade_plugin_savepoint($result, $plugin->version, $type, $plug, false);
645 }
646
647 /// Upgrade various components
648 update_capabilities($component);
c6d75bff 649 log_update_descriptions($component);
c976e271 650 external_update_descriptions($component);
309ae892 651 \core\task\manager::reset_scheduled_tasks_for_component($component);
795a08ad 652 message_update_providers($component);
6c0bfb14 653 \core\message\inbound\manager::update_handlers_for_component($component);
afed8d0f 654 if ($type === 'message') {
bde002b8 655 // Ugly hack!
afed8d0f
RK
656 message_update_processors($plug);
657 }
de260e0f 658 upgrade_plugin_mnet_functions($component);
c026a28d 659 core_tag_area::reset_definitions_for_component($component);
194cdca8 660 $endcallback($component, false, $verbose);
795a08ad 661
662 } else if ($installedversion > $plugin->version) {
663 throw new downgrade_exception($component, $installedversion, $plugin->version);
db9d4a3d 664 }
665 }
db9d4a3d 666}
667
668/**
669 * Find and check all modules and load them up or upgrade them if necessary
72fb21b6 670 *
671 * @global object
672 * @global object
db9d4a3d 673 */
194cdca8 674function upgrade_plugins_modules($startcallback, $endcallback, $verbose) {
db9d4a3d 675 global $CFG, $DB;
676
bd3b3bba 677 $mods = core_component::get_plugin_list('mod');
db9d4a3d 678
17da2e6f 679 foreach ($mods as $mod=>$fullmod) {
db9d4a3d 680
3e858ea7 681 if ($mod === 'NEWMODULE') { // Someone has unzipped the template, ignore it
db9d4a3d 682 continue;
683 }
684
aff24313 685 $component = clean_param('mod_'.$mod, PARAM_COMPONENT);
db9d4a3d 686
3e858ea7 687 // check module dir is valid name
aff24313
PS
688 if (empty($component)) {
689 throw new plugin_defective_exception('mod_'.$mod, 'Invalid plugin directory name.');
3e858ea7
PS
690 }
691
795a08ad 692 if (!is_readable($fullmod.'/version.php')) {
693 throw new plugin_defective_exception($component, 'Missing version.php');
db9d4a3d 694 }
695
01889f01 696 $module = new stdClass();
bde002b8
PS
697 $plugin = new stdClass();
698 $plugin->version = null;
994e5662 699 require($fullmod .'/version.php'); // Defines $plugin with version etc.
01889f01
DM
700
701 // Check if the legacy $module syntax is still used.
17d2a336 702 if (!is_object($module) or (count((array)$module) > 0)) {
01889f01
DM
703 throw new plugin_defective_exception($component, 'Unsupported $module syntax detected in version.php');
704 }
705
706 // Prepare the record for the {modules} table.
707 $module = clone($plugin);
bde002b8
PS
708 unset($module->version);
709 unset($module->component);
710 unset($module->dependencies);
711 unset($module->release);
bdbcb6d7 712
98ea6973
DM
713 if (empty($plugin->version)) {
714 throw new plugin_defective_exception($component, 'Missing $plugin->version number in version.php.');
3e858ea7
PS
715 }
716
98ea6973
DM
717 if (empty($plugin->component)) {
718 throw new plugin_defective_exception($component, 'Missing $plugin->component declaration in version.php.');
719 }
720
721 if ($plugin->component !== $component) {
722 throw new plugin_misplaced_exception($plugin->component, null, $fullmod);
db9d4a3d 723 }
724
bde002b8
PS
725 if (!empty($plugin->requires)) {
726 if ($plugin->requires > $CFG->version) {
727 throw new upgrade_requires_exception($component, $plugin->version, $CFG->version, $plugin->requires);
728 } else if ($plugin->requires < 2010000000) {
ef14c1e7 729 throw new plugin_defective_exception($component, 'Plugin is not compatible with Moodle 2.x or later.');
db9d4a3d 730 }
731 }
732
ff05bb31
TH
733 if (empty($module->cron)) {
734 $module->cron = 0;
735 }
736
3e858ea7
PS
737 // all modules must have en lang pack
738 if (!is_readable("$fullmod/lang/en/$mod.php")) {
739 throw new plugin_defective_exception($component, 'Missing mandatory en language pack.');
740 }
741
db9d4a3d 742 $module->name = $mod; // The name MUST match the directory
743
bde002b8 744 $installedversion = $DB->get_field('config_plugins', 'value', array('name'=>'version', 'plugin'=>$component)); // No caching!
db9d4a3d 745
9b683d13 746 if (file_exists($fullmod.'/db/install.php')) {
747 if (get_config($module->name, 'installrunning')) {
748 require_once($fullmod.'/db/install.php');
749 $recover_install_function = 'xmldb_'.$module->name.'_install_recovery';
750 if (function_exists($recover_install_function)) {
751 $startcallback($component, true, $verbose);
752 $recover_install_function();
753 unset_config('installrunning', $module->name);
754 // Install various components too
755 update_capabilities($component);
c6d75bff 756 log_update_descriptions($component);
c976e271 757 external_update_descriptions($component);
309ae892 758 \core\task\manager::reset_scheduled_tasks_for_component($component);
9b683d13 759 message_update_providers($component);
6c0bfb14 760 \core\message\inbound\manager::update_handlers_for_component($component);
de260e0f 761 upgrade_plugin_mnet_functions($component);
c026a28d 762 core_tag_area::reset_definitions_for_component($component);
9b683d13 763 $endcallback($component, true, $verbose);
764 }
765 }
766 }
767
bde002b8 768 if (empty($installedversion)) {
194cdca8 769 $startcallback($component, true, $verbose);
db9d4a3d 770
795a08ad 771 /// Execute install.xml (XMLDB) - must be present in all modules
772 $DB->get_manager()->install_from_xmldb_file($fullmod.'/db/install.xml');
db9d4a3d 773
2e3da297 774 /// Add record into modules table - may be needed in install.php already
775 $module->id = $DB->insert_record('modules', $module);
bde002b8 776 upgrade_mod_savepoint(true, $plugin->version, $module->name, false);
2e3da297 777
db9d4a3d 778 /// Post installation hook - optional
779 if (file_exists("$fullmod/db/install.php")) {
780 require_once("$fullmod/db/install.php");
9b683d13 781 // Set installation running flag, we need to recover after exception or error
782 set_config('installrunning', 1, $module->name);
3412cb43 783 $post_install_function = 'xmldb_'.$module->name.'_install';
db9d4a3d 784 $post_install_function();
9b683d13 785 unset_config('installrunning', $module->name);
db9d4a3d 786 }
787
795a08ad 788 /// Install various components
789 update_capabilities($component);
c6d75bff 790 log_update_descriptions($component);
c976e271 791 external_update_descriptions($component);
309ae892 792 \core\task\manager::reset_scheduled_tasks_for_component($component);
795a08ad 793 message_update_providers($component);
6c0bfb14 794 \core\message\inbound\manager::update_handlers_for_component($component);
de260e0f 795 upgrade_plugin_mnet_functions($component);
c026a28d 796 core_tag_area::reset_definitions_for_component($component);
795a08ad 797
194cdca8 798 $endcallback($component, true, $verbose);
db9d4a3d 799
bde002b8 800 } else if ($installedversion < $plugin->version) {
795a08ad 801 /// If versions say that we need to upgrade but no upgrade files are available, notify and continue
194cdca8 802 $startcallback($component, false, $verbose);
795a08ad 803
804 if (is_readable($fullmod.'/db/upgrade.php')) {
805 require_once($fullmod.'/db/upgrade.php'); // defines new upgrading function
806 $newupgrade_function = 'xmldb_'.$module->name.'_upgrade';
bde002b8 807 $result = $newupgrade_function($installedversion, $module);
795a08ad 808 } else {
809 $result = true;
810 }
811
bde002b8 812 $installedversion = $DB->get_field('config_plugins', 'value', array('name'=>'version', 'plugin'=>$component)); // No caching!
795a08ad 813 $currmodule = $DB->get_record('modules', array('name'=>$module->name));
bde002b8 814 if ($installedversion < $plugin->version) {
795a08ad 815 // store version if not already there
bde002b8 816 upgrade_mod_savepoint($result, $plugin->version, $mod, false);
795a08ad 817 }
818
3412cb43
TH
819 // update cron flag if needed
820 if ($currmodule->cron != $module->cron) {
821 $DB->set_field('modules', 'cron', $module->cron, array('name' => $module->name));
822 }
823
824 // Upgrade various components
795a08ad 825 update_capabilities($component);
c6d75bff 826 log_update_descriptions($component);
c976e271 827 external_update_descriptions($component);
309ae892 828 \core\task\manager::reset_scheduled_tasks_for_component($component);
795a08ad 829 message_update_providers($component);
6c0bfb14 830 \core\message\inbound\manager::update_handlers_for_component($component);
de260e0f 831 upgrade_plugin_mnet_functions($component);
c026a28d 832 core_tag_area::reset_definitions_for_component($component);
795a08ad 833
194cdca8 834 $endcallback($component, false, $verbose);
795a08ad 835
bde002b8
PS
836 } else if ($installedversion > $plugin->version) {
837 throw new downgrade_exception($component, $installedversion, $plugin->version);
795a08ad 838 }
839 }
840}
db9d4a3d 841
db9d4a3d 842
795a08ad 843/**
844 * This function finds all available blocks and install them
845 * into blocks table or do all the upgrade process if newer.
72fb21b6 846 *
847 * @global object
848 * @global object
795a08ad 849 */
194cdca8 850function upgrade_plugins_blocks($startcallback, $endcallback, $verbose) {
795a08ad 851 global $CFG, $DB;
852
795a08ad 853 require_once($CFG->dirroot.'/blocks/moodleblock.class.php');
854
855 $blocktitles = array(); // we do not want duplicate titles
856
857 //Is this a first install
858 $first_install = null;
859
bd3b3bba 860 $blocks = core_component::get_plugin_list('block');
795a08ad 861
17da2e6f 862 foreach ($blocks as $blockname=>$fullblock) {
795a08ad 863
864 if (is_null($first_install)) {
f46eba7e 865 $first_install = ($DB->count_records('block_instances') == 0);
795a08ad 866 }
867
aff24313 868 if ($blockname === 'NEWBLOCK') { // Someone has unzipped the template, ignore it
795a08ad 869 continue;
db9d4a3d 870 }
871
aff24313 872 $component = clean_param('block_'.$blockname, PARAM_COMPONENT);
db9d4a3d 873
3e858ea7 874 // check block dir is valid name
aff24313
PS
875 if (empty($component)) {
876 throw new plugin_defective_exception('block_'.$blockname, 'Invalid plugin directory name.');
3e858ea7
PS
877 }
878
8571833f
PS
879 if (!is_readable($fullblock.'/version.php')) {
880 throw new plugin_defective_exception('block/'.$blockname, 'Missing version.php file.');
881 }
365a5941 882 $plugin = new stdClass();
bde002b8 883 $plugin->version = null;
8571833f 884 $plugin->cron = 0;
bde002b8 885 $module = $plugin; // Prevent some notices when module placed in wrong directory.
8571833f 886 include($fullblock.'/version.php');
bde002b8
PS
887 unset($module);
888 $block = clone($plugin);
889 unset($block->version);
890 unset($block->component);
891 unset($block->dependencies);
892 unset($block->release);
8571833f 893
98ea6973
DM
894 if (empty($plugin->version)) {
895 throw new plugin_defective_exception($component, 'Missing block version number in version.php.');
3e858ea7
PS
896 }
897
98ea6973
DM
898 if (empty($plugin->component)) {
899 throw new plugin_defective_exception($component, 'Missing $plugin->component declaration in version.php.');
900 }
901
902 if ($plugin->component !== $component) {
903 throw new plugin_misplaced_exception($plugin->component, null, $fullblock);
bde002b8
PS
904 }
905
ef14c1e7
PS
906 if (!empty($plugin->requires)) {
907 if ($plugin->requires > $CFG->version) {
908 throw new upgrade_requires_exception($component, $plugin->version, $CFG->version, $plugin->requires);
909 } else if ($plugin->requires < 2010000000) {
910 throw new plugin_defective_exception($component, 'Plugin is not compatible with Moodle 2.x or later.');
911 }
912 }
913
795a08ad 914 if (!is_readable($fullblock.'/block_'.$blockname.'.php')) {
915 throw new plugin_defective_exception('block/'.$blockname, 'Missing main block class file.');
db9d4a3d 916 }
8571833f 917 include_once($fullblock.'/block_'.$blockname.'.php');
db9d4a3d 918
795a08ad 919 $classname = 'block_'.$blockname;
920
921 if (!class_exists($classname)) {
922 throw new plugin_defective_exception($component, 'Can not load main class.');
923 }
924
b921b6ee 925 $blockobj = new $classname; // This is what we'll be testing
795a08ad 926 $blocktitle = $blockobj->get_title();
927
928 // OK, it's as we all hoped. For further tests, the object will do them itself.
929 if (!$blockobj->_self_test()) {
930 throw new plugin_defective_exception($component, 'Self test failed.');
931 }
932
795a08ad 933 $block->name = $blockname; // The name MUST match the directory
795a08ad 934
bde002b8 935 $installedversion = $DB->get_field('config_plugins', 'value', array('name'=>'version', 'plugin'=>$component)); // No caching!
795a08ad 936
9b683d13 937 if (file_exists($fullblock.'/db/install.php')) {
938 if (get_config('block_'.$blockname, 'installrunning')) {
939 require_once($fullblock.'/db/install.php');
940 $recover_install_function = 'xmldb_block_'.$blockname.'_install_recovery';
941 if (function_exists($recover_install_function)) {
942 $startcallback($component, true, $verbose);
943 $recover_install_function();
944 unset_config('installrunning', 'block_'.$blockname);
945 // Install various components
946 update_capabilities($component);
c6d75bff 947 log_update_descriptions($component);
c976e271 948 external_update_descriptions($component);
309ae892 949 \core\task\manager::reset_scheduled_tasks_for_component($component);
9b683d13 950 message_update_providers($component);
6c0bfb14 951 \core\message\inbound\manager::update_handlers_for_component($component);
de260e0f 952 upgrade_plugin_mnet_functions($component);
c026a28d 953 core_tag_area::reset_definitions_for_component($component);
9b683d13 954 $endcallback($component, true, $verbose);
955 }
956 }
957 }
958
bde002b8 959 if (empty($installedversion)) { // block not installed yet, so install it
795a08ad 960 $conflictblock = array_search($blocktitle, $blocktitles);
961 if ($conflictblock !== false) {
962 // Duplicate block titles are not allowed, they confuse people
963 // AND PHP's associative arrays ;)
c1ddac83 964 throw new plugin_defective_exception($component, get_string('blocknameconflict', 'error', (object)array('name'=>$block->name, 'conflict'=>$conflictblock)));
795a08ad 965 }
194cdca8 966 $startcallback($component, true, $verbose);
795a08ad 967
968 if (file_exists($fullblock.'/db/install.xml')) {
969 $DB->get_manager()->install_from_xmldb_file($fullblock.'/db/install.xml');
970 }
971 $block->id = $DB->insert_record('block', $block);
bde002b8 972 upgrade_block_savepoint(true, $plugin->version, $block->name, false);
795a08ad 973
974 if (file_exists($fullblock.'/db/install.php')) {
975 require_once($fullblock.'/db/install.php');
9b683d13 976 // Set installation running flag, we need to recover after exception or error
977 set_config('installrunning', 1, 'block_'.$blockname);
0e35ba6f 978 $post_install_function = 'xmldb_block_'.$blockname.'_install';
795a08ad 979 $post_install_function();
9b683d13 980 unset_config('installrunning', 'block_'.$blockname);
795a08ad 981 }
982
983 $blocktitles[$block->name] = $blocktitle;
984
985 // Install various components
986 update_capabilities($component);
c6d75bff 987 log_update_descriptions($component);
c976e271 988 external_update_descriptions($component);
309ae892 989 \core\task\manager::reset_scheduled_tasks_for_component($component);
795a08ad 990 message_update_providers($component);
6c0bfb14 991 \core\message\inbound\manager::update_handlers_for_component($component);
c026a28d 992 core_tag_area::reset_definitions_for_component($component);
de260e0f 993 upgrade_plugin_mnet_functions($component);
795a08ad 994
194cdca8 995 $endcallback($component, true, $verbose);
795a08ad 996
bde002b8 997 } else if ($installedversion < $plugin->version) {
194cdca8 998 $startcallback($component, false, $verbose);
795a08ad 999
1000 if (is_readable($fullblock.'/db/upgrade.php')) {
1001 require_once($fullblock.'/db/upgrade.php'); // defines new upgrading function
1002 $newupgrade_function = 'xmldb_block_'.$blockname.'_upgrade';
bde002b8 1003 $result = $newupgrade_function($installedversion, $block);
795a08ad 1004 } else {
1005 $result = true;
1006 }
1007
bde002b8 1008 $installedversion = $DB->get_field('config_plugins', 'value', array('name'=>'version', 'plugin'=>$component)); // No caching!
795a08ad 1009 $currblock = $DB->get_record('block', array('name'=>$block->name));
bde002b8 1010 if ($installedversion < $plugin->version) {
795a08ad 1011 // store version if not already there
bde002b8 1012 upgrade_block_savepoint($result, $plugin->version, $block->name, false);
795a08ad 1013 }
1014
1015 if ($currblock->cron != $block->cron) {
1016 // update cron flag if needed
1fa84543 1017 $DB->set_field('block', 'cron', $block->cron, array('id' => $currblock->id));
795a08ad 1018 }
1019
b921b6ee 1020 // Upgrade various components
795a08ad 1021 update_capabilities($component);
c6d75bff 1022 log_update_descriptions($component);
c976e271 1023 external_update_descriptions($component);
309ae892 1024 \core\task\manager::reset_scheduled_tasks_for_component($component);
795a08ad 1025 message_update_providers($component);
6c0bfb14 1026 \core\message\inbound\manager::update_handlers_for_component($component);
de260e0f 1027 upgrade_plugin_mnet_functions($component);
c026a28d 1028 core_tag_area::reset_definitions_for_component($component);
795a08ad 1029
194cdca8 1030 $endcallback($component, false, $verbose);
795a08ad 1031
bde002b8
PS
1032 } else if ($installedversion > $plugin->version) {
1033 throw new downgrade_exception($component, $installedversion, $plugin->version);
795a08ad 1034 }
1035 }
1036
1037
1038 // Finally, if we are in the first_install of BLOCKS setup frontpage and admin page blocks
1039 if ($first_install) {
795a08ad 1040 //Iterate over each course - there should be only site course here now
1041 if ($courses = $DB->get_records('course')) {
1042 foreach ($courses as $course) {
9d1d606e 1043 blocks_add_default_course_blocks($course);
db9d4a3d 1044 }
1045 }
795a08ad 1046
9d1d606e 1047 blocks_add_default_system_blocks();
795a08ad 1048 }
1049}
1050
c6d75bff
PS
1051
1052/**
1053 * Log_display description function used during install and upgrade.
1054 *
1055 * @param string $component name of component (moodle, mod_assignment, etc.)
1056 * @return void
1057 */
1058function log_update_descriptions($component) {
1059 global $DB;
1060
b0d1d941 1061 $defpath = core_component::get_component_directory($component).'/db/log.php';
c6d75bff
PS
1062
1063 if (!file_exists($defpath)) {
1064 $DB->delete_records('log_display', array('component'=>$component));
1065 return;
1066 }
1067
1068 // load new info
1069 $logs = array();
1070 include($defpath);
1071 $newlogs = array();
1072 foreach ($logs as $log) {
1073 $newlogs[$log['module'].'-'.$log['action']] = $log; // kind of unique name
1074 }
1075 unset($logs);
1076 $logs = $newlogs;
1077
1078 $fields = array('module', 'action', 'mtable', 'field');
1079 // update all log fist
1080 $dblogs = $DB->get_records('log_display', array('component'=>$component));
1081 foreach ($dblogs as $dblog) {
1082 $name = $dblog->module.'-'.$dblog->action;
1083
1084 if (empty($logs[$name])) {
1085 $DB->delete_records('log_display', array('id'=>$dblog->id));
1086 continue;
1087 }
1088
1089 $log = $logs[$name];
1090 unset($logs[$name]);
1091
1092 $update = false;
1093 foreach ($fields as $field) {
1094 if ($dblog->$field != $log[$field]) {
1095 $dblog->$field = $log[$field];
1096 $update = true;
1097 }
1098 }
1099 if ($update) {
1100 $DB->update_record('log_display', $dblog);
1101 }
1102 }
1103 foreach ($logs as $log) {
1104 $dblog = (object)$log;
1105 $dblog->component = $component;
1106 $DB->insert_record('log_display', $dblog);
1107 }
1108}
1109
c976e271 1110/**
1111 * Web service discovery function used during install and upgrade.
1112 * @param string $component name of component (moodle, mod_assignment, etc.)
1113 * @return void
1114 */
1115function external_update_descriptions($component) {
bc81eadb 1116 global $DB, $CFG;
c976e271 1117
b0d1d941 1118 $defpath = core_component::get_component_directory($component).'/db/services.php';
c976e271 1119
1120 if (!file_exists($defpath)) {
bc81eadb 1121 require_once($CFG->dirroot.'/lib/externallib.php');
c976e271 1122 external_delete_descriptions($component);
1123 return;
1124 }
1125
1126 // load new info
1127 $functions = array();
1128 $services = array();
1129 include($defpath);
1130
1131 // update all function fist
1132 $dbfunctions = $DB->get_records('external_functions', array('component'=>$component));
1133 foreach ($dbfunctions as $dbfunction) {
1134 if (empty($functions[$dbfunction->name])) {
1135 $DB->delete_records('external_functions', array('id'=>$dbfunction->id));
1136 // do not delete functions from external_services_functions, beacuse
1137 // we want to notify admins when functions used in custom services disappear
c6d75bff
PS
1138
1139 //TODO: this looks wrong, we have to delete it eventually (skodak)
c976e271 1140 continue;
1141 }
1142
1143 $function = $functions[$dbfunction->name];
1144 unset($functions[$dbfunction->name]);
1145 $function['classpath'] = empty($function['classpath']) ? null : $function['classpath'];
1146
1147 $update = false;
1148 if ($dbfunction->classname != $function['classname']) {
1149 $dbfunction->classname = $function['classname'];
1150 $update = true;
1151 }
1152 if ($dbfunction->methodname != $function['methodname']) {
1153 $dbfunction->methodname = $function['methodname'];
1154 $update = true;
1155 }
1156 if ($dbfunction->classpath != $function['classpath']) {
1157 $dbfunction->classpath = $function['classpath'];
1158 $update = true;
1159 }
12fc8acf 1160 $functioncapabilities = array_key_exists('capabilities', $function)?$function['capabilities']:'';
72f68b51 1161 if ($dbfunction->capabilities != $functioncapabilities) {
1162 $dbfunction->capabilities = $functioncapabilities;
1163 $update = true;
1164 }
186eba1b
JL
1165
1166 if (isset($function['services']) and is_array($function['services'])) {
1167 sort($function['services']);
1168 $functionservices = implode(',', $function['services']);
1169 } else {
1170 // Force null values in the DB.
1171 $functionservices = null;
1172 }
1173
1174 if ($dbfunction->services != $functionservices) {
1175 // Now, we need to check if services were removed, in that case we need to remove the function from them.
1176 $servicesremoved = array_diff(explode(",", $dbfunction->services), explode(",", $functionservices));
1177 foreach ($servicesremoved as $removedshortname) {
1178 if ($externalserviceid = $DB->get_field('external_services', 'id', array("shortname" => $removedshortname))) {
1179 $DB->delete_records('external_services_functions', array('functionname' => $dbfunction->name,
1180 'externalserviceid' => $externalserviceid));
1181 }
1182 }
1183
1184 $dbfunction->services = $functionservices;
1185 $update = true;
1186 }
c976e271 1187 if ($update) {
1188 $DB->update_record('external_functions', $dbfunction);
1189 }
1190 }
1191 foreach ($functions as $fname => $function) {
365a5941 1192 $dbfunction = new stdClass();
c976e271 1193 $dbfunction->name = $fname;
1194 $dbfunction->classname = $function['classname'];
1195 $dbfunction->methodname = $function['methodname'];
1196 $dbfunction->classpath = empty($function['classpath']) ? null : $function['classpath'];
1197 $dbfunction->component = $component;
12fc8acf 1198 $dbfunction->capabilities = array_key_exists('capabilities', $function)?$function['capabilities']:'';
186eba1b
JL
1199
1200 if (isset($function['services']) and is_array($function['services'])) {
1201 sort($function['services']);
1202 $dbfunction->services = implode(',', $function['services']);
1203 } else {
1204 // Force null values in the DB.
1205 $dbfunction->services = null;
1206 }
1207
c976e271 1208 $dbfunction->id = $DB->insert_record('external_functions', $dbfunction);
1209 }
1210 unset($functions);
1211
1212 // now deal with services
1213 $dbservices = $DB->get_records('external_services', array('component'=>$component));
1214 foreach ($dbservices as $dbservice) {
1215 if (empty($services[$dbservice->name])) {
bc81eadb 1216 $DB->delete_records('external_tokens', array('externalserviceid'=>$dbservice->id));
c976e271 1217 $DB->delete_records('external_services_functions', array('externalserviceid'=>$dbservice->id));
1218 $DB->delete_records('external_services_users', array('externalserviceid'=>$dbservice->id));
1219 $DB->delete_records('external_services', array('id'=>$dbservice->id));
1220 continue;
1221 }
1222 $service = $services[$dbservice->name];
1223 unset($services[$dbservice->name]);
1224 $service['enabled'] = empty($service['enabled']) ? 0 : $service['enabled'];
1225 $service['requiredcapability'] = empty($service['requiredcapability']) ? null : $service['requiredcapability'];
1226 $service['restrictedusers'] = !isset($service['restrictedusers']) ? 1 : $service['restrictedusers'];
af03513f 1227 $service['downloadfiles'] = !isset($service['downloadfiles']) ? 0 : $service['downloadfiles'];
106c55fb 1228 $service['uploadfiles'] = !isset($service['uploadfiles']) ? 0 : $service['uploadfiles'];
c1b65883 1229 $service['shortname'] = !isset($service['shortname']) ? null : $service['shortname'];
c976e271 1230
1231 $update = false;
c976e271 1232 if ($dbservice->requiredcapability != $service['requiredcapability']) {
1233 $dbservice->requiredcapability = $service['requiredcapability'];
1234 $update = true;
1235 }
1236 if ($dbservice->restrictedusers != $service['restrictedusers']) {
1237 $dbservice->restrictedusers = $service['restrictedusers'];
1238 $update = true;
1239 }
af03513f
JM
1240 if ($dbservice->downloadfiles != $service['downloadfiles']) {
1241 $dbservice->downloadfiles = $service['downloadfiles'];
1242 $update = true;
1243 }
106c55fb
DW
1244 if ($dbservice->uploadfiles != $service['uploadfiles']) {
1245 $dbservice->uploadfiles = $service['uploadfiles'];
1246 $update = true;
1247 }
c1b65883
JM
1248 //if shortname is not a PARAM_ALPHANUMEXT, fail (tested here for service update and creation)
1249 if (isset($service['shortname']) and
1250 (clean_param($service['shortname'], PARAM_ALPHANUMEXT) != $service['shortname'])) {
1251 throw new moodle_exception('installserviceshortnameerror', 'webservice', '', $service['shortname']);
1252 }
1253 if ($dbservice->shortname != $service['shortname']) {
1254 //check that shortname is unique
1255 if (isset($service['shortname'])) { //we currently accepts multiple shortname == null
1256 $existingservice = $DB->get_record('external_services',
1257 array('shortname' => $service['shortname']));
1258 if (!empty($existingservice)) {
1259 throw new moodle_exception('installexistingserviceshortnameerror', 'webservice', '', $service['shortname']);
1260 }
1261 }
1262 $dbservice->shortname = $service['shortname'];
1263 $update = true;
1264 }
c976e271 1265 if ($update) {
1266 $DB->update_record('external_services', $dbservice);
1267 }
1268
1269 $functions = $DB->get_records('external_services_functions', array('externalserviceid'=>$dbservice->id));
1270 foreach ($functions as $function) {
1271 $key = array_search($function->functionname, $service['functions']);
1272 if ($key === false) {
1273 $DB->delete_records('external_services_functions', array('id'=>$function->id));
1274 } else {
1275 unset($service['functions'][$key]);
1276 }
1277 }
1278 foreach ($service['functions'] as $fname) {
365a5941 1279 $newf = new stdClass();
c976e271 1280 $newf->externalserviceid = $dbservice->id;
1281 $newf->functionname = $fname;
1282 $DB->insert_record('external_services_functions', $newf);
1283 }
1284 unset($functions);
1285 }
1286 foreach ($services as $name => $service) {
c1b65883
JM
1287 //check that shortname is unique
1288 if (isset($service['shortname'])) { //we currently accepts multiple shortname == null
1289 $existingservice = $DB->get_record('external_services',
1290 array('shortname' => $service['shortname']));
1291 if (!empty($existingservice)) {
1292 throw new moodle_exception('installserviceshortnameerror', 'webservice');
1293 }
1294 }
1295
365a5941 1296 $dbservice = new stdClass();
c976e271 1297 $dbservice->name = $name;
1298 $dbservice->enabled = empty($service['enabled']) ? 0 : $service['enabled'];
1299 $dbservice->requiredcapability = empty($service['requiredcapability']) ? null : $service['requiredcapability'];
1300 $dbservice->restrictedusers = !isset($service['restrictedusers']) ? 1 : $service['restrictedusers'];
af03513f 1301 $dbservice->downloadfiles = !isset($service['downloadfiles']) ? 0 : $service['downloadfiles'];
106c55fb 1302 $dbservice->uploadfiles = !isset($service['uploadfiles']) ? 0 : $service['uploadfiles'];
c1b65883 1303 $dbservice->shortname = !isset($service['shortname']) ? null : $service['shortname'];
c976e271 1304 $dbservice->component = $component;
e5180580 1305 $dbservice->timecreated = time();
c976e271 1306 $dbservice->id = $DB->insert_record('external_services', $dbservice);
1307 foreach ($service['functions'] as $fname) {
365a5941 1308 $newf = new stdClass();
c976e271 1309 $newf->externalserviceid = $dbservice->id;
1310 $newf->functionname = $fname;
1311 $DB->insert_record('external_services_functions', $newf);
1312 }
1313 }
1314}
1315
186eba1b 1316/**
ee7295ee 1317 * Allow plugins and subsystems to add external functions to other plugins or built-in services.
186eba1b
JL
1318 * This function is executed just after all the plugins have been updated.
1319 */
1320function external_update_services() {
1321 global $DB;
1322
1323 // Look for external functions that want to be added in existing services.
1324 $functions = $DB->get_records_select('external_functions', 'services IS NOT NULL');
1325
1326 $servicescache = array();
1327 foreach ($functions as $function) {
1328 // Prevent edge cases.
1329 if (empty($function->services)) {
1330 continue;
1331 }
1332 $services = explode(',', $function->services);
1333
1334 foreach ($services as $serviceshortname) {
1335 // Get the service id by shortname.
1336 if (!empty($servicescache[$serviceshortname])) {
1337 $serviceid = $servicescache[$serviceshortname];
1338 } else if ($service = $DB->get_record('external_services', array('shortname' => $serviceshortname))) {
1339 // If the component is empty, it means that is not a built-in service.
1340 // We don't allow functions to inject themselves in services created by an user in Moodle.
1341 if (empty($service->component)) {
1342 continue;
1343 }
1344 $serviceid = $service->id;
1345 $servicescache[$serviceshortname] = $serviceid;
1346 } else {
1347 // Service not found.
1348 continue;
1349 }
1350 // Finally add the function to the service.
1351 $newf = new stdClass();
1352 $newf->externalserviceid = $serviceid;
1353 $newf->functionname = $function->name;
1354
1355 if (!$DB->record_exists('external_services_functions', (array)$newf)) {
1356 $DB->insert_record('external_services_functions', $newf);
1357 }
1358 }
1359 }
1360}
1361
72fb21b6 1362/**
1363 * upgrade logging functions
72fb21b6 1364 */
fd1a792e 1365function upgrade_handle_exception($ex, $plugin = null) {
96e1fdf4
PS
1366 global $CFG;
1367
a56c457e
PS
1368 // rollback everything, we need to log all upgrade problems
1369 abort_all_db_transactions();
1370
c19bc39c
PS
1371 $info = get_exception_info($ex);
1372
1373 // First log upgrade error
1374 upgrade_log(UPGRADE_LOG_ERROR, $plugin, 'Exception: ' . get_class($ex), $info->message, $info->backtrace);
1375
1376 // Always turn on debugging - admins need to know what is going on
96f81ea3 1377 set_debugging(DEBUG_DEVELOPER, true);
c19bc39c 1378
fd1a792e 1379 default_exception_handler($ex, true, $plugin);
db9d4a3d 1380}
1381
1382/**
1383 * Adds log entry into upgrade_log table
1384 *
1385 * @param int $type UPGRADE_LOG_NORMAL, UPGRADE_LOG_NOTICE or UPGRADE_LOG_ERROR
bb8b2971 1386 * @param string $plugin frankenstyle component name
db9d4a3d 1387 * @param string $info short description text of log entry
1388 * @param string $details long problem description
1389 * @param string $backtrace string used for errors only
1390 * @return void
1391 */
1392function upgrade_log($type, $plugin, $info, $details=null, $backtrace=null) {
1393 global $DB, $USER, $CFG;
1394
bb8b2971
PS
1395 if (empty($plugin)) {
1396 $plugin = 'core';
1397 }
1398
56da374e 1399 list($plugintype, $pluginname) = core_component::normalize_component($plugin);
bb8b2971 1400 $component = is_null($pluginname) ? $plugintype : $plugintype . '_' . $pluginname;
795a08ad 1401
34a2777c 1402 $backtrace = format_backtrace($backtrace, true);
db9d4a3d 1403
bb8b2971
PS
1404 $currentversion = null;
1405 $targetversion = null;
db9d4a3d 1406
1407 //first try to find out current version number
bb8b2971 1408 if ($plugintype === 'core') {
db9d4a3d 1409 //main
bb8b2971 1410 $currentversion = $CFG->version;
db9d4a3d 1411
bb8b2971
PS
1412 $version = null;
1413 include("$CFG->dirroot/version.php");
1414 $targetversion = $version;
795a08ad 1415
795a08ad 1416 } else {
bb8b2971 1417 $pluginversion = get_config($component, 'version');
795a08ad 1418 if (!empty($pluginversion)) {
bb8b2971
PS
1419 $currentversion = $pluginversion;
1420 }
b0d1d941 1421 $cd = core_component::get_component_directory($component);
bb8b2971
PS
1422 if (file_exists("$cd/version.php")) {
1423 $plugin = new stdClass();
1424 $plugin->version = null;
bde002b8 1425 $module = $plugin;
bb8b2971
PS
1426 include("$cd/version.php");
1427 $targetversion = $plugin->version;
795a08ad 1428 }
db9d4a3d 1429 }
1430
365a5941 1431 $log = new stdClass();
bb8b2971
PS
1432 $log->type = $type;
1433 $log->plugin = $component;
1434 $log->version = $currentversion;
1435 $log->targetversion = $targetversion;
1436 $log->info = $info;
1437 $log->details = $details;
1438 $log->backtrace = $backtrace;
1439 $log->userid = $USER->id;
1440 $log->timemodified = time();
db9d4a3d 1441 try {
1442 $DB->insert_record('upgrade_log', $log);
1443 } catch (Exception $ignored) {
795a08ad 1444 // possible during install or 2.0 upgrade
db9d4a3d 1445 }
1446}
1447
1448/**
1449 * Marks start of upgrade, blocks any other access to site.
1450 * The upgrade is finished at the end of script or after timeout.
72fb21b6 1451 *
1452 * @global object
1453 * @global object
1454 * @global object
db9d4a3d 1455 */
1456function upgrade_started($preinstall=false) {
de6d81e6 1457 global $CFG, $DB, $PAGE, $OUTPUT;
db9d4a3d 1458
1459 static $started = false;
1460
1461 if ($preinstall) {
1462 ignore_user_abort(true);
1463 upgrade_setup_debug(true);
1464
1465 } else if ($started) {
1466 upgrade_set_timeout(120);
1467
1468 } else {
c13a5e71 1469 if (!CLI_SCRIPT and !$PAGE->headerprinted) {
db9d4a3d 1470 $strupgrade = get_string('upgradingversion', 'admin');
78946b9b 1471 $PAGE->set_pagelayout('maintenance');
543f54d3 1472 upgrade_init_javascript();
de6d81e6 1473 $PAGE->set_title($strupgrade.' - Moodle '.$CFG->target_release);
1474 $PAGE->set_heading($strupgrade);
1475 $PAGE->navbar->add($strupgrade);
1476 $PAGE->set_cacheable(false);
1477 echo $OUTPUT->header();
db9d4a3d 1478 }
1479
1480 ignore_user_abort(true);
38fc0130 1481 core_shutdown_manager::register_function('upgrade_finished_handler');
db9d4a3d 1482 upgrade_setup_debug(true);
1483 set_config('upgraderunning', time()+300);
1484 $started = true;
1485 }
1486}
1487
1488/**
b921b6ee 1489 * Internal function - executed if upgrade interrupted.
db9d4a3d 1490 */
1491function upgrade_finished_handler() {
1492 upgrade_finished();
1493}
1494
1495/**
1496 * Indicates upgrade is finished.
1497 *
1498 * This function may be called repeatedly.
72fb21b6 1499 *
1500 * @global object
1501 * @global object
db9d4a3d 1502 */
1503function upgrade_finished($continueurl=null) {
7e0d6675 1504 global $CFG, $DB, $OUTPUT;
db9d4a3d 1505
1506 if (!empty($CFG->upgraderunning)) {
1507 unset_config('upgraderunning');
24dedb96
SH
1508 // We have to forcefully purge the caches using the writer here.
1509 // This has to be done after we unset the config var. If someone hits the site while this is set they will
1510 // cause the config values to propogate to the caches.
1511 // Caches are purged after the last step in an upgrade but there is several code routines that exceute between
1512 // then and now that leaving a window for things to fall out of sync.
1513 cache_helper::purge_all(true);
db9d4a3d 1514 upgrade_setup_debug(false);
1515 ignore_user_abort(false);
1516 if ($continueurl) {
aa9a6867 1517 echo $OUTPUT->continue_button($continueurl);
7e0d6675 1518 echo $OUTPUT->footer();
db9d4a3d 1519 die;
1520 }
1521 }
1522}
1523
72fb21b6 1524/**
1525 * @global object
1526 * @global object
1527 */
db9d4a3d 1528function upgrade_setup_debug($starting) {
1529 global $CFG, $DB;
1530
1531 static $originaldebug = null;
1532
1533 if ($starting) {
1534 if ($originaldebug === null) {
1535 $originaldebug = $DB->get_debug();
1536 }
1537 if (!empty($CFG->upgradeshowsql)) {
1538 $DB->set_debug(true);
1539 }
1540 } else {
1541 $DB->set_debug($originaldebug);
1542 }
1543}
1544
1545function print_upgrade_separator() {
1546 if (!CLI_SCRIPT) {
1547 echo '<hr />';
1548 }
1549}
1550
795a08ad 1551/**
1552 * Default start upgrade callback
1553 * @param string $plugin
b921b6ee 1554 * @param bool $installation true if installation, false means upgrade
795a08ad 1555 */
194cdca8 1556function print_upgrade_part_start($plugin, $installation, $verbose) {
3c159385 1557 global $OUTPUT;
795a08ad 1558 if (empty($plugin) or $plugin == 'moodle') {
1559 upgrade_started($installation); // does not store upgrade running flag yet
194cdca8 1560 if ($verbose) {
3c159385 1561 echo $OUTPUT->heading(get_string('coresystem'));
194cdca8 1562 }
795a08ad 1563 } else {
1564 upgrade_started();
194cdca8 1565 if ($verbose) {
3c159385 1566 echo $OUTPUT->heading($plugin);
194cdca8 1567 }
795a08ad 1568 }
1569 if ($installation) {
1570 if (empty($plugin) or $plugin == 'moodle') {
1571 // no need to log - log table not yet there ;-)
1572 } else {
1573 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Starting plugin installation');
1574 }
1575 } else {
83740b9f 1576 core_upgrade_time::record_start();
795a08ad 1577 if (empty($plugin) or $plugin == 'moodle') {
1578 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Starting core upgrade');
1579 } else {
1580 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Starting plugin upgrade');
1581 }
1582 }
1583}
1584
1585/**
1586 * Default end upgrade callback
1587 * @param string $plugin
b921b6ee 1588 * @param bool $installation true if installation, false means upgrade
795a08ad 1589 */
194cdca8 1590function print_upgrade_part_end($plugin, $installation, $verbose) {
aa9a6867 1591 global $OUTPUT;
795a08ad 1592 upgrade_started();
1593 if ($installation) {
1594 if (empty($plugin) or $plugin == 'moodle') {
1595 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Core installed');
1596 } else {
1597 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Plugin installed');
1598 }
1599 } else {
1600 if (empty($plugin) or $plugin == 'moodle') {
1601 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Core upgraded');
1602 } else {
1603 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Plugin upgraded');
1604 }
1605 }
194cdca8 1606 if ($verbose) {
83740b9f
JP
1607 if ($installation) {
1608 $message = get_string('success');
1609 } else {
1610 $duration = core_upgrade_time::get_elapsed();
1611 $message = get_string('successduration', '', format_float($duration, 2));
1612 }
1613 $notification = new \core\output\notification($message, \core\output\notification::NOTIFY_SUCCESS);
2059d6ed
RW
1614 $notification->set_show_closebutton(false);
1615 echo $OUTPUT->render($notification);
194cdca8 1616 print_upgrade_separator();
96db14f9 1617 }
1618}
1619
72fb21b6 1620/**
b921b6ee 1621 * Sets up JS code required for all upgrade scripts.
72fb21b6 1622 * @global object
1623 */
543f54d3 1624function upgrade_init_javascript() {
e29380f3 1625 global $PAGE;
543f54d3
PS
1626 // scroll to the end of each upgrade page so that ppl see either error or continue button,
1627 // no need to scroll continuously any more, it is enough to jump to end once the footer is printed ;-)
1628 $js = "window.scrollTo(0, 5000000);";
1629 $PAGE->requires->js_init_code($js);
db9d4a3d 1630}
1631
db9d4a3d 1632/**
1633 * Try to upgrade the given language pack (or current language)
af8d4d91 1634 *
74a4c9a9 1635 * @param string $lang the code of the language to update, defaults to the current language
db9d4a3d 1636 */
bd41bdd9
PS
1637function upgrade_language_pack($lang = null) {
1638 global $CFG;
db9d4a3d 1639
bd41bdd9
PS
1640 if (!empty($CFG->skiplangupgrade)) {
1641 return;
1642 }
af8d4d91 1643
bd41bdd9
PS
1644 if (!file_exists("$CFG->dirroot/$CFG->admin/tool/langimport/lib.php")) {
1645 // weird, somebody uninstalled the import utility
1646 return;
1647 }
1648
1649 if (!$lang) {
db9d4a3d 1650 $lang = current_language();
1651 }
1652
bd41bdd9
PS
1653 if (!get_string_manager()->translation_exists($lang)) {
1654 return;
db9d4a3d 1655 }
1656
bd41bdd9
PS
1657 get_string_manager()->reset_caches();
1658
1659 if ($lang === 'en') {
1660 return; // Nothing to do
db9d4a3d 1661 }
af8d4d91 1662
bd41bdd9
PS
1663 upgrade_started(false);
1664
1665 require_once("$CFG->dirroot/$CFG->admin/tool/langimport/lib.php");
1666 tool_langimport_preupgrade_update($lang);
1667
af8d4d91
DM
1668 get_string_manager()->reset_caches();
1669
551fe0e5 1670 print_upgrade_separator();
db9d4a3d 1671}
8580535b 1672
0f268f5d
RW
1673/**
1674 * Build the current theme so that the user doesn't have to wait for it
1675 * to build on the first page load after the install / upgrade.
1676 */
1677function upgrade_themes() {
1678 global $CFG;
1679
1680 require_once("{$CFG->libdir}/outputlib.php");
1681
1682 // Build the current theme so that the user can immediately
1683 // browse the site without having to wait for the theme to build.
1684 $themeconfig = theme_config::load($CFG->theme);
1685 $direction = right_to_left() ? 'rtl' : 'ltr';
1686 theme_build_css_for_themes([$themeconfig], [$direction]);
1687
1688 // Only queue the task if there isn't already one queued.
1689 if (empty(\core\task\manager::get_adhoc_tasks('\\core\\task\\build_installed_themes_task'))) {
1690 // Queue a task to build all of the site themes at some point
1691 // later. These can happen offline because it doesn't block the
1692 // user unless they quickly change theme.
1693 $adhoctask = new \core\task\build_installed_themes_task();
1694 \core\task\manager::queue_adhoc_task($adhoctask);
1695 }
1696}
1697
8580535b 1698/**
1699 * Install core moodle tables and initialize
1700 * @param float $version target version
1701 * @param bool $verbose
1702 * @return void, may throw exception
1703 */
1704function install_core($version, $verbose) {
1705 global $CFG, $DB;
1706
e2e35e71 1707 // We can not call purge_all_caches() yet, make sure the temp and cache dirs exist and are empty.
e2e35e71 1708 remove_dir($CFG->cachedir.'', true);
85b38061
PS
1709 make_cache_directory('', true);
1710
1711 remove_dir($CFG->localcachedir.'', true);
1712 make_localcache_directory('', true);
1713
e2e35e71 1714 remove_dir($CFG->tempdir.'', true);
85b38061
PS
1715 make_temp_directory('', true);
1716
ef844148
MS
1717 remove_dir($CFG->backuptempdir.'', true);
1718 make_backup_temp_directory('', true);
1719
e2e35e71 1720 remove_dir($CFG->dataroot.'/muc', true);
85b38061 1721 make_writable_directory($CFG->dataroot.'/muc', true);
e2e35e71 1722
8580535b 1723 try {
3ef7279f 1724 core_php_time_limit::raise(600);
194cdca8 1725 print_upgrade_part_start('moodle', true, $verbose); // does not store upgrade running flag
8580535b 1726
1727 $DB->get_manager()->install_from_xmldb_file("$CFG->libdir/db/install.xml");
1728 upgrade_started(); // we want the flag to be stored in config table ;-)
1729
1730 // set all core default records and default settings
1731 require_once("$CFG->libdir/db/install.php");
c6d75bff 1732 xmldb_main_install(); // installs the capabilities too
8580535b 1733
1734 // store version
1735 upgrade_main_savepoint(true, $version, false);
1736
df997f84 1737 // Continue with the installation
c6d75bff
PS
1738 log_update_descriptions('moodle');
1739 external_update_descriptions('moodle');
309ae892 1740 \core\task\manager::reset_scheduled_tasks_for_component('moodle');
8580535b 1741 message_update_providers('moodle');
6c0bfb14 1742 \core\message\inbound\manager::update_handlers_for_component('moodle');
c026a28d 1743 core_tag_area::reset_definitions_for_component('moodle');
8580535b 1744
df997f84 1745 // Write default settings unconditionally
8580535b 1746 admin_apply_default_settings(NULL, true);
1747
194cdca8 1748 print_upgrade_part_end(null, true, $verbose);
94ef67cf 1749
e0d9b7c0
SH
1750 // Purge all caches. They're disabled but this ensures that we don't have any persistent data just in case something
1751 // during installation didn't use APIs.
1752 cache_helper::purge_all();
8580535b 1753 } catch (exception $ex) {
1754 upgrade_handle_exception($ex);
1766e6a1
MG
1755 } catch (Throwable $ex) {
1756 // Engine errors in PHP7 throw exceptions of type Throwable (this "catch" will be ignored in PHP5).
1757 upgrade_handle_exception($ex);
8580535b 1758 }
1759}
1760
1761/**
1762 * Upgrade moodle core
1763 * @param float $version target version
1764 * @param bool $verbose
1765 * @return void, may throw exception
1766 */
1767function upgrade_core($version, $verbose) {
e2049782 1768 global $CFG, $SITE, $DB, $COURSE;
8580535b 1769
41209c1e
PS
1770 raise_memory_limit(MEMORY_EXTRA);
1771
3316fe24 1772 require_once($CFG->libdir.'/db/upgrade.php'); // Defines upgrades
3316fe24 1773
8580535b 1774 try {
7b4d5af7 1775 // Reset caches before any output.
b0dd08dd 1776 cache_helper::purge_all(true);
7b4d5af7 1777 purge_all_caches();
dcf9be7f 1778
8580535b 1779 // Upgrade current language pack if we can
bd41bdd9 1780 upgrade_language_pack();
8580535b 1781
194cdca8 1782 print_upgrade_part_start('moodle', false, $verbose);
8580535b 1783
6b4b7490
PS
1784 // Pre-upgrade scripts for local hack workarounds.
1785 $preupgradefile = "$CFG->dirroot/local/preupgrade.php";
1786 if (file_exists($preupgradefile)) {
3ef7279f 1787 core_php_time_limit::raise();
6b4b7490
PS
1788 require($preupgradefile);
1789 // Reset upgrade timeout to default.
1790 upgrade_set_timeout();
17da2e6f 1791 }
1792
8580535b 1793 $result = xmldb_main_upgrade($CFG->version);
1794 if ($version > $CFG->version) {
1795 // store version if not already there
1796 upgrade_main_savepoint($result, $version, false);
1797 }
1798
e2049782
MG
1799 // In case structure of 'course' table has been changed and we forgot to update $SITE, re-read it from db.
1800 $SITE = $DB->get_record('course', array('id' => $SITE->id));
1801 $COURSE = clone($SITE);
1802
8580535b 1803 // perform all other component upgrade routines
1804 update_capabilities('moodle');
c6d75bff 1805 log_update_descriptions('moodle');
c976e271 1806 external_update_descriptions('moodle');
309ae892 1807 \core\task\manager::reset_scheduled_tasks_for_component('moodle');
8580535b 1808 message_update_providers('moodle');
6c0bfb14 1809 \core\message\inbound\manager::update_handlers_for_component('moodle');
c026a28d 1810 core_tag_area::reset_definitions_for_component('moodle');
75af47ee
SH
1811 // Update core definitions.
1812 cache_helper::update_definitions(true);
8580535b 1813
94ef67cf 1814 // Purge caches again, just to be sure we arn't holding onto old stuff now.
a5a6e93f 1815 cache_helper::purge_all(true);
7b4d5af7 1816 purge_all_caches();
2e5eba85
PS
1817
1818 // Clean up contexts - more and more stuff depends on existence of paths and contexts
e922fe23
PS
1819 context_helper::cleanup_instances();
1820 context_helper::create_instances(null, false);
1821 context_helper::build_all_paths(false);
1822 $syscontext = context_system::instance();
1823 $syscontext->mark_dirty();
8580535b 1824
194cdca8 1825 print_upgrade_part_end('moodle', false, $verbose);
8580535b 1826 } catch (Exception $ex) {
1827 upgrade_handle_exception($ex);
1766e6a1
MG
1828 } catch (Throwable $ex) {
1829 // Engine errors in PHP7 throw exceptions of type Throwable (this "catch" will be ignored in PHP5).
1830 upgrade_handle_exception($ex);
8580535b 1831 }
1832}
1833
1834/**
1835 * Upgrade/install other parts of moodle
1836 * @param bool $verbose
1837 * @return void, may throw exception
1838 */
1839function upgrade_noncore($verbose) {
1840 global $CFG;
1841
41209c1e
PS
1842 raise_memory_limit(MEMORY_EXTRA);
1843
8580535b 1844 // upgrade all plugins types
1845 try {
7b4d5af7
PS
1846 // Reset caches before any output.
1847 cache_helper::purge_all(true);
1848 purge_all_caches();
1849
46f6f7f2 1850 $plugintypes = core_component::get_plugin_types();
8580535b 1851 foreach ($plugintypes as $type=>$location) {
17da2e6f 1852 upgrade_plugins($type, 'print_upgrade_part_start', 'print_upgrade_part_end', $verbose);
8580535b 1853 }
ee7295ee
JL
1854 // Upgrade services.
1855 // This function gives plugins and subsystems a chance to add functions to existing built-in services.
186eba1b
JL
1856 external_update_services();
1857
94ef67cf 1858 // Update cache definitions. Involves scanning each plugin for any changes.
75af47ee 1859 cache_helper::update_definitions();
c5701ce7
PS
1860 // Mark the site as upgraded.
1861 set_config('allversionshash', core_component::get_all_versions_hash());
7b4d5af7
PS
1862
1863 // Purge caches again, just to be sure we arn't holding onto old stuff now.
1864 cache_helper::purge_all(true);
1865 purge_all_caches();
1866
8580535b 1867 } catch (Exception $ex) {
1868 upgrade_handle_exception($ex);
1766e6a1
MG
1869 } catch (Throwable $ex) {
1870 // Engine errors in PHP7 throw exceptions of type Throwable (this "catch" will be ignored in PHP5).
1871 upgrade_handle_exception($ex);
8580535b 1872 }
8580535b 1873}
3316fe24 1874
1875/**
1876 * Checks if the main tables have been installed yet or not.
e2e35e71
PS
1877 *
1878 * Note: we can not use caches here because they might be stale,
1879 * use with care!
1880 *
3316fe24 1881 * @return bool
1882 */
1883function core_tables_exist() {
1884 global $DB;
1885
e2e35e71 1886 if (!$tables = $DB->get_tables(false) ) { // No tables yet at all.
3316fe24 1887 return false;
9b683d13 1888
3316fe24 1889 } else { // Check for missing main tables
1890 $mtables = array('config', 'course', 'groupings'); // some tables used in 1.9 and 2.0, preferable something from the start and end of install.xml
1891 foreach ($mtables as $mtable) {
1892 if (!in_array($mtable, $tables)) {
1893 return false;
1894 }
1895 }
1896 return true;
9b683d13 1897 }
ba04999c 1898}
c71ade2f
PL
1899
1900/**
1901 * upgrades the mnet rpc definitions for the given component.
1902 * this method doesn't return status, an exception will be thrown in the case of an error
1903 *
1904 * @param string $component the plugin to upgrade, eg auth_mnet
1905 */
1906function upgrade_plugin_mnet_functions($component) {
1907 global $DB, $CFG;
1908
8c59114f 1909 list($type, $plugin) = core_component::normalize_component($component);
1c74b260 1910 $path = core_component::get_plugin_directory($type, $plugin);
c71ade2f 1911
17b71716
PS
1912 $publishes = array();
1913 $subscribes = array();
c71ade2f
PL
1914 if (file_exists($path . '/db/mnet.php')) {
1915 require_once($path . '/db/mnet.php'); // $publishes comes from this file
1916 }
1917 if (empty($publishes)) {
1918 $publishes = array(); // still need this to be able to disable stuff later
1919 }
1920 if (empty($subscribes)) {
1921 $subscribes = array(); // still need this to be able to disable stuff later
1922 }
1923
1924 static $servicecache = array();
1925
1926 // rekey an array based on the rpc method for easy lookups later
1927 $publishmethodservices = array();
1928 $subscribemethodservices = array();
1929 foreach($publishes as $servicename => $service) {
1930 if (is_array($service['methods'])) {
1931 foreach($service['methods'] as $methodname) {
1932 $service['servicename'] = $servicename;
1933 $publishmethodservices[$methodname][] = $service;
1934 }
1935 }
1936 }
1937
1938 // Disable functions that don't exist (any more) in the source
1939 // Should these be deleted? What about their permissions records?
1940 foreach ($DB->get_records('mnet_rpc', array('pluginname'=>$plugin, 'plugintype'=>$type), 'functionname ASC ') as $rpc) {
1941 if (!array_key_exists($rpc->functionname, $publishmethodservices) && $rpc->enabled) {
1942 $DB->set_field('mnet_rpc', 'enabled', 0, array('id' => $rpc->id));
1943 } else if (array_key_exists($rpc->functionname, $publishmethodservices) && !$rpc->enabled) {
1944 $DB->set_field('mnet_rpc', 'enabled', 1, array('id' => $rpc->id));
1945 }
1946 }
1947
1948 // reflect all the services we're publishing and save them
c71ade2f
PL
1949 static $cachedclasses = array(); // to store reflection information in
1950 foreach ($publishes as $service => $data) {
1951 $f = $data['filename'];
1952 $c = $data['classname'];
1953 foreach ($data['methods'] as $method) {
6bdfef5d 1954 $dataobject = new stdClass();
c71ade2f
PL
1955 $dataobject->plugintype = $type;
1956 $dataobject->pluginname = $plugin;
1957 $dataobject->enabled = 1;
1958 $dataobject->classname = $c;
1959 $dataobject->filename = $f;
1960
1961 if (is_string($method)) {
1962 $dataobject->functionname = $method;
1963
1964 } else if (is_array($method)) { // wants to override file or class
1965 $dataobject->functionname = $method['method'];
1966 $dataobject->classname = $method['classname'];
1967 $dataobject->filename = $method['filename'];
1968 }
1969 $dataobject->xmlrpcpath = $type.'/'.$plugin.'/'.$dataobject->filename.'/'.$method;
1970 $dataobject->static = false;
1971
1972 require_once($path . '/' . $dataobject->filename);
1973 $functionreflect = null; // slightly different ways to get this depending on whether it's a class method or a function
1974 if (!empty($dataobject->classname)) {
1975 if (!class_exists($dataobject->classname)) {
1976 throw new moodle_exception('installnosuchmethod', 'mnet', '', (object)array('method' => $dataobject->functionname, 'class' => $dataobject->classname));
1977 }
1978 $key = $dataobject->filename . '|' . $dataobject->classname;
1979 if (!array_key_exists($key, $cachedclasses)) { // look to see if we've already got a reflection object
1980 try {
052141ab
CB
1981 $cachedclasses[$key] = new ReflectionClass($dataobject->classname);
1982 } catch (ReflectionException $e) { // catch these and rethrow them to something more helpful
c71ade2f
PL
1983 throw new moodle_exception('installreflectionclasserror', 'mnet', '', (object)array('method' => $dataobject->functionname, 'class' => $dataobject->classname, 'error' => $e->getMessage()));
1984 }
1985 }
1986 $r =& $cachedclasses[$key];
1987 if (!$r->hasMethod($dataobject->functionname)) {
1988 throw new moodle_exception('installnosuchmethod', 'mnet', '', (object)array('method' => $dataobject->functionname, 'class' => $dataobject->classname));
1989 }
052141ab 1990 $functionreflect = $r->getMethod($dataobject->functionname);
c71ade2f
PL
1991 $dataobject->static = (int)$functionreflect->isStatic();
1992 } else {
1993 if (!function_exists($dataobject->functionname)) {
1994 throw new moodle_exception('installnosuchfunction', 'mnet', '', (object)array('method' => $dataobject->functionname, 'file' => $dataobject->filename));
1995 }
1996 try {
052141ab
CB
1997 $functionreflect = new ReflectionFunction($dataobject->functionname);
1998 } catch (ReflectionException $e) { // catch these and rethrow them to something more helpful
c71ade2f
PL
1999 throw new moodle_exception('installreflectionfunctionerror', 'mnet', '', (object)array('method' => $dataobject->functionname, '' => $dataobject->filename, 'error' => $e->getMessage()));
2000 }
2001 }
2002 $dataobject->profile = serialize(admin_mnet_method_profile($functionreflect));
052141ab 2003 $dataobject->help = admin_mnet_method_get_help($functionreflect);
c71ade2f
PL
2004
2005 if ($record_exists = $DB->get_record('mnet_rpc', array('xmlrpcpath'=>$dataobject->xmlrpcpath))) {
2006 $dataobject->id = $record_exists->id;
2007 $dataobject->enabled = $record_exists->enabled;
2008 $DB->update_record('mnet_rpc', $dataobject);
2009 } else {
2010 $dataobject->id = $DB->insert_record('mnet_rpc', $dataobject, true);
2011 }
c71ade2f 2012
d5bd0b01
DM
2013 // TODO this API versioning must be reworked, here the recently processed method
2014 // sets the service API which may not be correct
677b6321
PL
2015 foreach ($publishmethodservices[$dataobject->functionname] as $service) {
2016 if ($serviceobj = $DB->get_record('mnet_service', array('name'=>$service['servicename']))) {
2017 $serviceobj->apiversion = $service['apiversion'];
2018 $DB->update_record('mnet_service', $serviceobj);
2019 } else {
2020 $serviceobj = new stdClass();
2021 $serviceobj->name = $service['servicename'];
f4a2817a 2022 $serviceobj->description = empty($service['description']) ? '' : $service['description'];
677b6321
PL
2023 $serviceobj->apiversion = $service['apiversion'];
2024 $serviceobj->offer = 1;
2025 $serviceobj->id = $DB->insert_record('mnet_service', $serviceobj);
2026 }
2027 $servicecache[$service['servicename']] = $serviceobj;
2028 if (!$DB->record_exists('mnet_service2rpc', array('rpcid'=>$dataobject->id, 'serviceid'=>$serviceobj->id))) {
2029 $obj = new stdClass();
2030 $obj->rpcid = $dataobject->id;
2031 $obj->serviceid = $serviceobj->id;
2032 $DB->insert_record('mnet_service2rpc', $obj, true);
2033 }
c71ade2f
PL
2034 }
2035 }
2036 }
c71ade2f
PL
2037 // finished with methods we publish, now do subscribable methods
2038 foreach($subscribes as $service => $methods) {
2039 if (!array_key_exists($service, $servicecache)) {
2040 if (!$serviceobj = $DB->get_record('mnet_service', array('name' => $service))) {
81634f03 2041 debugging("TODO: skipping unknown service $service - somebody needs to fix MDL-21993");
c71ade2f
PL
2042 continue;
2043 }
2044 $servicecache[$service] = $serviceobj;
2045 } else {
2046 $serviceobj = $servicecache[$service];
2047 }
2048 foreach ($methods as $method => $xmlrpcpath) {
2049 if (!$rpcid = $DB->get_field('mnet_remote_rpc', 'id', array('xmlrpcpath'=>$xmlrpcpath))) {
2050 $remoterpc = (object)array(
2051 'functionname' => $method,
2052 'xmlrpcpath' => $xmlrpcpath,
2053 'plugintype' => $type,
2054 'pluginname' => $plugin,
2055 'enabled' => 1,
2056 );
2057 $rpcid = $remoterpc->id = $DB->insert_record('mnet_remote_rpc', $remoterpc, true);
2058 }
2059 if (!$DB->record_exists('mnet_remote_service2rpc', array('rpcid'=>$rpcid, 'serviceid'=>$serviceobj->id))) {
2060 $obj = new stdClass();
2061 $obj->rpcid = $rpcid;
2062 $obj->serviceid = $serviceobj->id;
2063 $DB->insert_record('mnet_remote_service2rpc', $obj, true);
2064 }
677b6321 2065 $subscribemethodservices[$method][] = $service;
c71ade2f
PL
2066 }
2067 }
2068
2069 foreach ($DB->get_records('mnet_remote_rpc', array('pluginname'=>$plugin, 'plugintype'=>$type), 'functionname ASC ') as $rpc) {
2070 if (!array_key_exists($rpc->functionname, $subscribemethodservices) && $rpc->enabled) {
2071 $DB->set_field('mnet_remote_rpc', 'enabled', 0, array('id' => $rpc->id));
2072 } else if (array_key_exists($rpc->functionname, $subscribemethodservices) && !$rpc->enabled) {
2073 $DB->set_field('mnet_remote_rpc', 'enabled', 1, array('id' => $rpc->id));
2074 }
2075 }
2076
2077 return true;
2078}
2079
2080/**
052141ab 2081 * Given some sort of reflection function/method object, return a profile array, ready to be serialized and stored
c71ade2f 2082 *
052141ab 2083 * @param ReflectionFunctionAbstract $function reflection function/method object from which to extract information
c71ade2f 2084 *
052141ab 2085 * @return array associative array with function/method information
c71ade2f 2086 */
052141ab
CB
2087function admin_mnet_method_profile(ReflectionFunctionAbstract $function) {
2088 $commentlines = admin_mnet_method_get_docblock($function);
2089 $getkey = function($key) use ($commentlines) {
2090 return array_values(array_filter($commentlines, function($line) use ($key) {
2091 return $line[0] == $key;
2092 }));
2093 };
2094 $returnline = $getkey('@return');
2095 return array (
2096 'parameters' => array_map(function($line) {
2097 return array(
2098 'name' => trim($line[2], " \t\n\r\0\x0B$"),
2099 'type' => $line[1],
2100 'description' => $line[3]
2101 );
2102 }, $getkey('@param')),
2103
2104 'return' => array(
2105 'type' => !empty($returnline[0][1]) ? $returnline[0][1] : 'void',
2106 'description' => !empty($returnline[0][2]) ? $returnline[0][2] : ''
2107 )
c71ade2f 2108 );
052141ab
CB
2109}
2110
2111/**
2112 * Given some sort of reflection function/method object, return an array of docblock lines, where each line is an array of
2113 * keywords/descriptions
2114 *
2115 * @param ReflectionFunctionAbstract $function reflection function/method object from which to extract information
2116 *
2117 * @return array docblock converted in to an array
2118 */
2119function admin_mnet_method_get_docblock(ReflectionFunctionAbstract $function) {
2120 return array_map(function($line) {
2121 $text = trim($line, " \t\n\r\0\x0B*/");
2122 if (strpos($text, '@param') === 0) {
2123 return preg_split('/\s+/', $text, 4);
2124 }
2125
2126 if (strpos($text, '@return') === 0) {
2127 return preg_split('/\s+/', $text, 3);
2128 }
2129
2130 return array($text);
2131 }, explode("\n", $function->getDocComment()));
2132}
2133
2134/**
2135 * Given some sort of reflection function/method object, return just the help text
2136 *
2137 * @param ReflectionFunctionAbstract $function reflection function/method object from which to extract information
2138 *
2139 * @return string docblock help text
2140 */
2141function admin_mnet_method_get_help(ReflectionFunctionAbstract $function) {
2142 $helplines = array_map(function($line) {
2143 return implode(' ', $line);
2144 }, array_values(array_filter(admin_mnet_method_get_docblock($function), function($line) {
2145 return strpos($line[0], '@') !== 0 && !empty($line[0]);
2146 })));
2147
2148 return implode("\n", $helplines);
c71ade2f 2149}
424a19b1 2150
71611510
MN
2151/**
2152 * This function verifies that the database is not using an unsupported storage engine.
2153 *
2154 * @param environment_results $result object to update, if relevant
2155 * @return environment_results|null updated results object, or null if the storage engine is supported
2156 */
2157function check_database_storage_engine(environment_results $result) {
2158 global $DB;
2159
2160 // Check if MySQL is the DB family (this will also be the same for MariaDB).
2161 if ($DB->get_dbfamily() == 'mysql') {
2162 // Get the database engine we will either be using to install the tables, or what we are currently using.
2163 $engine = $DB->get_dbengine();
2164 // Check if MyISAM is the storage engine that will be used, if so, do not proceed and display an error.
2165 if ($engine == 'MyISAM') {
2166 $result->setInfo('unsupported_db_storage_engine');
2167 $result->setStatus(false);
2168 return $result;
2169 }
2170 }
2171
2172 return null;
2173}
1bd4b9fc
SL
2174
2175/**
2176 * Method used to check the usage of slasharguments config and display a warning message.
2177 *
2178 * @param environment_results $result object to update, if relevant.
2179 * @return environment_results|null updated results or null if slasharguments is disabled.
2180 */
2181function check_slasharguments(environment_results $result){
2182 global $CFG;
2183
e284ac02 2184 if (!during_initial_install() && empty($CFG->slasharguments)) {
1bd4b9fc
SL
2185 $result->setInfo('slasharguments');
2186 $result->setStatus(false);
2187 return $result;
2188 }
2189
2190 return null;
2191}
9b8104ce
SL
2192
2193/**
2194 * This function verifies if the database has tables using innoDB Antelope row format.
2195 *
2196 * @param environment_results $result
2197 * @return environment_results|null updated results object, or null if no Antelope table has been found.
2198 */
2199function check_database_tables_row_format(environment_results $result) {
2200 global $DB;
2201
2202 if ($DB->get_dbfamily() == 'mysql') {
2203 $generator = $DB->get_manager()->generator;
2204
2205 foreach ($DB->get_tables(false) as $table) {
2206 $columns = $DB->get_columns($table, false);
c7ccb543 2207 $size = $generator->guess_antelope_row_size($columns);
9b8104ce
SL
2208 $format = $DB->get_row_format($table);
2209
2210 if ($size <= $generator::ANTELOPE_MAX_ROW_SIZE) {
2211 continue;
2212 }
2213
2214 if ($format === 'Compact' or $format === 'Redundant') {
2215 $result->setInfo('unsupported_db_table_row_format');
2216 $result->setStatus(false);
2217 return $result;
2218 }
2219 }
2220 }
2221
2222 return null;
2223}
ebea19cb 2224
0bbefd81
AG
2225/**
2226 * This function verfies that the database has tables using InnoDB Antelope row format.
2227 *
2228 * @param environment_results $result
2229 * @return environment_results|null updated results object, or null if no Antelope table has been found.
2230 */
2231function check_mysql_file_format(environment_results $result) {
2232 global $DB;
2233
2234 if ($DB->get_dbfamily() == 'mysql') {
2235 $collation = $DB->get_dbcollation();
2236 $collationinfo = explode('_', $collation);
2237 $charset = reset($collationinfo);
2238
2239 if ($charset == 'utf8mb4') {
2240 if ($DB->get_row_format() !== "Barracuda") {
2241 $result->setInfo('mysql_full_unicode_support#File_format');
2242 $result->setStatus(false);
2243 return $result;
2244 }
2245 }
2246 }
2247 return null;
2248}
2249
2250/**
2251 * This function verfies that the database has a setting of one file per table. This is required for 'utf8mb4'.
2252 *
2253 * @param environment_results $result
2254 * @return environment_results|null updated results object, or null if innodb_file_per_table = 1.
2255 */
2256function check_mysql_file_per_table(environment_results $result) {
2257 global $DB;
2258
2259 if ($DB->get_dbfamily() == 'mysql') {
2260 $collation = $DB->get_dbcollation();
2261 $collationinfo = explode('_', $collation);
2262 $charset = reset($collationinfo);
2263
2264 if ($charset == 'utf8mb4') {
2265 if (!$DB->is_file_per_table_enabled()) {
2266 $result->setInfo('mysql_full_unicode_support#File_per_table');
2267 $result->setStatus(false);
2268 return $result;
2269 }
2270 }
2271 }
2272 return null;
2273}
2274
2275/**
2276 * This function verfies that the database has the setting of large prefix enabled. This is required for 'utf8mb4'.
2277 *
2278 * @param environment_results $result
2279 * @return environment_results|null updated results object, or null if innodb_large_prefix = 1.
2280 */
2281function check_mysql_large_prefix(environment_results $result) {
2282 global $DB;
2283
2284 if ($DB->get_dbfamily() == 'mysql') {
2285 $collation = $DB->get_dbcollation();
2286 $collationinfo = explode('_', $collation);
2287 $charset = reset($collationinfo);
2288
2289 if ($charset == 'utf8mb4') {
2290 if (!$DB->is_large_prefix_enabled()) {
2291 $result->setInfo('mysql_full_unicode_support#Large_prefix');
2292 $result->setStatus(false);
2293 return $result;
2294 }
2295 }
2296 }
2297 return null;
2298}
2299
2300/**
2301 * This function checks the database to see if it is using incomplete unicode support.
2302 *
2303 * @param environment_results $result $result
2304 * @return environment_results|null updated results object, or null if unicode is fully supported.
2305 */
2306function check_mysql_incomplete_unicode_support(environment_results $result) {
2307 global $DB;
2308
2309 if ($DB->get_dbfamily() == 'mysql') {
2310 $collation = $DB->get_dbcollation();
2311 $collationinfo = explode('_', $collation);
2312 $charset = reset($collationinfo);
2313
2314 if ($charset == 'utf8') {
2315 $result->setInfo('mysql_full_unicode_support');
2316 $result->setStatus(false);
2317 return $result;
2318 }
2319 }
2320 return null;
2321}
2322
9d2112e8
EL
2323/**
2324 * Check if the site is being served using an ssl url.
2325 *
2326 * Note this does not really perform any request neither looks for proxies or
2327 * other situations. Just looks to wwwroot and warn if it's not using https.
2328 *
2329 * @param environment_results $result $result
2330 * @return environment_results|null updated results object, or null if the site is https.
2331 */
2332function check_is_https(environment_results $result) {
2333 global $CFG;
2334
2335 // Only if is defined, non-empty and whatever core tell us.
2336 if (!empty($CFG->wwwroot) && !is_https()) {
2337 $result->setInfo('site not https');
2338 $result->setStatus(false);
2339 return $result;
2340 }
2341 return null;
2342}
2343
9b92642c
EL
2344/**
2345 * Check if the site is using 64 bits PHP.
2346 *
2347 * @param environment_results $result
2348 * @return environment_results|null updated results object, or null if the site is using 64 bits PHP.
2349 */
2350function check_sixtyfour_bits(environment_results $result) {
2351
2352 if (PHP_INT_SIZE === 4) {
2353 $result->setInfo('php not 64 bits');
2354 $result->setStatus(false);
2355 return $result;
2356 }
2357 return null;
2358}
2359
98b32c9e
DM
2360/**
2361 * Assert the upgrade key is provided, if it is defined.
2362 *
2363 * The upgrade key can be defined in the main config.php as $CFG->upgradekey. If
2364 * it is defined there, then its value must be provided every time the site is
2365 * being upgraded, regardless the administrator is logged in or not.
2366 *
2367 * This is supposed to be used at certain places in /admin/index.php only.
2368 *
2369 * @param string|null $upgradekeyhash the SHA-1 of the value provided by the user
2370 */
2371function check_upgrade_key($upgradekeyhash) {
2372 global $CFG, $PAGE;
2373
2374 if (isset($CFG->config_php_settings['upgradekey'])) {
2375 if ($upgradekeyhash === null or $upgradekeyhash !== sha1($CFG->config_php_settings['upgradekey'])) {
2376 if (!$PAGE->headerprinted) {
2377 $output = $PAGE->get_renderer('core', 'admin');
2378 echo $output->upgradekey_form_page(new moodle_url('/admin/index.php', array('cache' => 0)));
2379 die();
2380 } else {
2381 // This should not happen.
2382 die('Upgrade locked');
2383 }
2384 }
2385 }
2386}
531381f9
DM
2387
2388/**
2389 * Helper procedure/macro for installing remote plugins at admin/index.php
2390 *
2391 * Does not return, always redirects or exits.
2392 *
2393 * @param array $installable list of \core\update\remote_info
2394 * @param bool $confirmed false: display the validation screen, true: proceed installation
2395 * @param string $heading validation screen heading
2396 * @param moodle_url|string|null $continue URL to proceed with installation at the validation screen
8726c07c 2397 * @param moodle_url|string|null $return URL to go back on cancelling at the validation screen
531381f9 2398 */
2d00be61 2399function upgrade_install_plugins(array $installable, $confirmed, $heading='', $continue=null, $return=null) {
b0fc7898 2400 global $CFG, $PAGE;
531381f9
DM
2401
2402 if (empty($return)) {
2403 $return = $PAGE->url;
2404 }
2405
b0fc7898
DM
2406 if (!empty($CFG->disableupdateautodeploy)) {
2407 redirect($return);
2408 }
2409
531381f9
DM
2410 if (empty($installable)) {
2411 redirect($return);
2412 }
2413
2414 $pluginman = core_plugin_manager::instance();
2415
2416 if ($confirmed) {
2417 // Installation confirmed at the validation results page.
2d00be61
DM
2418 if (!$pluginman->install_plugins($installable, true, true)) {
2419 throw new moodle_exception('install_plugins_failed', 'core_plugin', $return);
531381f9 2420 }
d9a5b810 2421
8726c07c 2422 // Always redirect to admin/index.php to perform the database upgrade.
d9a5b810
DM
2423 // Do not throw away the existing $PAGE->url parameters such as
2424 // confirmupgrade or confirmrelease if $PAGE->url is a superset of the
2425 // URL we must go to.
2426 $mustgoto = new moodle_url('/admin/index.php', array('cache' => 0, 'confirmplugincheck' => 0));
2427 if ($mustgoto->compare($PAGE->url, URL_MATCH_PARAMS)) {
2428 redirect($PAGE->url);
2429 } else {
2430 redirect($mustgoto);
2431 }
531381f9
DM
2432
2433 } else {
2434 $output = $PAGE->get_renderer('core', 'admin');
2435 echo $output->header();
2436 if ($heading) {
2437 echo $output->heading($heading, 3);
2438 }
2439 echo html_writer::start_tag('pre', array('class' => 'plugin-install-console'));
2d00be61 2440 $validated = $pluginman->install_plugins($installable, false, false);
531381f9
DM
2441 echo html_writer::end_tag('pre');
2442 if ($validated) {
4d7528f9 2443 echo $output->plugins_management_confirm_buttons($continue, $return);
531381f9 2444 } else {
4d7528f9 2445 echo $output->plugins_management_confirm_buttons(null, $return);
531381f9
DM
2446 }
2447 echo $output->footer();
2448 die();
2449 }
2450}
c4d69228
SL
2451/**
2452 * Method used to check the installed unoconv version.
2453 *
2454 * @param environment_results $result object to update, if relevant.
2455 * @return environment_results|null updated results or null if unoconv path is not executable.
2456 */
0eecf876 2457function check_unoconv_version(environment_results $result) {
c4d69228
SL
2458 global $CFG;
2459
0eecf876 2460 if (!during_initial_install() && !empty($CFG->pathtounoconv) && file_is_executable(trim($CFG->pathtounoconv))) {
84440fe3
SL
2461 $currentversion = 0;
2462 $supportedversion = 0.7;
0eecf876
AG
2463 $unoconvbin = \escapeshellarg($CFG->pathtounoconv);
2464 $command = "$unoconvbin --version";
2465 exec($command, $output);
84440fe3
SL
2466
2467 // If the command execution returned some output, then get the unoconv version.
6937d89b 2468 if ($output) {
6937d89b
SL
2469 foreach ($output as $response) {
2470 if (preg_match('/unoconv (\\d+\\.\\d+)/', $response, $matches)) {
2471 $currentversion = (float)$matches[1];
2472 }
2473 }
84440fe3
SL
2474 }
2475
2476 if ($currentversion < $supportedversion) {
2477 $result->setInfo('unoconv version not supported');
2478 $result->setStatus(false);
2479 return $result;
c4d69228
SL
2480 }
2481 }
2482 return null;
2483}
ab3759ff
CB
2484
2485/**
89556019 2486 * Checks for up-to-date TLS libraries. NOTE: this is not currently used, see MDL-57262.
ab3759ff
CB
2487 *
2488 * @param environment_results $result object to update, if relevant.
2489 * @return environment_results|null updated results or null if unoconv path is not executable.
2490 */
2491function check_tls_libraries(environment_results $result) {
2492 global $CFG;
2493
4a1165ba
DM
2494 if (!function_exists('curl_version')) {
2495 $result->setInfo('cURL PHP extension is not installed');
2496 $result->setStatus(false);
2497 return $result;
2498 }
2499
ab3759ff
CB
2500 if (!\core\upgrade\util::validate_php_curl_tls(curl_version(), PHP_ZTS)) {
2501 $result->setInfo('invalid ssl/tls configuration');
2502 $result->setStatus(false);
2503 return $result;
2504 }
2505
2506 if (!\core\upgrade\util::can_use_tls12(curl_version(), php_uname('r'))) {
2507 $result->setInfo('ssl/tls configuration not supported');
2508 $result->setStatus(false);
2509 return $result;
2510 }
2511
2512 return null;
2513}
f2330472
AA
2514
2515/**
2516 * Check if recommended version of libcurl is installed or not.
2517 *
2518 * @param environment_results $result object to update, if relevant.
2519 * @return environment_results|null updated results or null.
2520 */
2521function check_libcurl_version(environment_results $result) {
2522
acefc7d9
VZ
2523 if (!function_exists('curl_version')) {
2524 $result->setInfo('cURL PHP extension is not installed');
2525 $result->setStatus(false);
2526 return $result;
2527 }
2528
f2330472
AA
2529 // Supported version and version number.
2530 $supportedversion = 0x071304;
2531 $supportedversionstring = "7.19.4";
2532
2533 // Installed version.
2534 $curlinfo = curl_version();
2535 $currentversion = $curlinfo['version_number'];
2536
2537 if ($currentversion < $supportedversion) {
2538 // Test fail.
2539 // Set info, we want to let user know how to resolve the problem.
2540 $result->setInfo('Libcurl version check');
2541 $result->setNeededVersion($supportedversionstring);
2542 $result->setCurrentVersion($curlinfo['version']);
2543 $result->setStatus(false);
2544 return $result;
2545 }
2546
2547 return null;
2548}
31bd1023
DM
2549
2550/**
2551 * Fix how auth plugins are called in the 'config_plugins' table.
2552 *
2553 * For legacy reasons, the auth plugins did not always use their frankenstyle
2554 * component name in the 'plugin' column of the 'config_plugins' table. This is
2555 * a helper function to correctly migrate the legacy settings into the expected
2556 * and consistent way.
2557 *
2558 * @param string $plugin the auth plugin name such as 'cas', 'manual' or 'mnet'
2559 */
2560function upgrade_fix_config_auth_plugin_names($plugin) {
2561 global $CFG, $DB, $OUTPUT;
2562
2563 $legacy = (array) get_config('auth/'.$plugin);
2564 $current = (array) get_config('auth_'.$plugin);
2565
2566 // I don't want to rely on array_merge() and friends here just in case
2567 // there was some crazy setting with a numerical name.
2568
2569 if ($legacy) {
2570 $new = $legacy;
2571 } else {
2572 $new = [];
2573 }
2574
2575 if ($current) {
2576 foreach ($current as $name => $value) {
2577 if (isset($legacy[$name]) && ($legacy[$name] !== $value)) {
2578 // No need to pollute the output during unit tests.
2579 if (!empty($CFG->upgraderunning)) {
2580 $message = get_string('settingmigrationmismatch', 'core_auth', [
2581 'plugin' => 'auth_'.$plugin,
2582 'setting' => s($name),
2583 'legacy' => s($legacy[$name]),
2584 'current' => s($value),
2585 ]);
2586 echo $OUTPUT->notification($message, \core\output\notification::NOTIFY_ERROR);
2587
2588 upgrade_log(UPGRADE_LOG_NOTICE, 'auth_'.$plugin, 'Setting values mismatch detected',
2589 'SETTING: '.$name. ' LEGACY: '.$legacy[$name].' CURRENT: '.$value);
2590 }
2591 }
2592
2593 $new[$name] = $value;
2594 }
2595 }
2596
2597 foreach ($new as $name => $value) {
2598 set_config($name, $value, 'auth_'.$plugin);
2599 unset_config($name, 'auth/'.$plugin);
2600 }
2601}
2b948c20
DM
2602
2603/**
2604 * Populate the auth plugin settings with defaults if needed.
2605 *
2606 * As a result of fixing the auth plugins config storage, many settings would
2607 * be falsely reported as new ones by admin/upgradesettings.php. We do not want
2608 * to confuse admins so we try to reduce the bewilderment by pre-populating the
2609 * config_plugins table with default values. This should be done only for
2610 * disabled auth methods. The enabled methods have their settings already
2611 * stored, so reporting actual new settings for them is valid.
2612 *
2613 * @param string $plugin the auth plugin name such as 'cas', 'manual' or 'mnet'
2614 */
2615function upgrade_fix_config_auth_plugin_defaults($plugin) {
2616 global $CFG;
2617
2618 $pluginman = core_plugin_manager::instance();
2619 $enabled = $pluginman->get_enabled_plugins('auth');
2620
2621 if (isset($enabled[$plugin])) {
2622 // Do not touch settings of enabled auth methods.
2623 return;
2624 }
2625
2626 // We can't directly use {@link core\plugininfo\auth::load_settings()} here
2627 // because the plugins are not fully upgraded yet. Instead, we emulate what
2628 // that method does. We fetch a temporary instance of the plugin's settings
2629 // page to get access to the settings and their defaults. Note we are not
2630 // adding that temporary instance into the admin tree. Yes, this is a hack.
2631
2632 $plugininfo = $pluginman->get_plugin_info('auth_'.$plugin);
2633 $adminroot = admin_get_root();
2634 $ADMIN = $adminroot;
2635 $auth = $plugininfo;
2636
2637 $section = $plugininfo->get_settings_section_name();
2638 $settingspath = $plugininfo->full_path('settings.php');
2639
2640 if (file_exists($settingspath)) {
2641 $settings = new admin_settingpage($section, 'Emulated settings page for auth_'.$plugin, 'moodle/site:config');
2642 include($settingspath);
2643
2644 if ($settings) {
2b948c20
DM
2645 admin_apply_default_settings($settings, false);
2646 }
2647 }
2648}
e46fde42
JO
2649
2650/**
2651 * Search for a given theme in any of the parent themes of a given theme.
2652 *
2653 * @param string $needle The name of the theme you want to search for
2654 * @param string $themename The name of the theme you want to search for
2655 * @param string $checkedthemeforparents The name of all the themes already checked
2656 * @return bool True if found, false if not.
2657 */
2658function upgrade_theme_is_from_family($needle, $themename, $checkedthemeforparents = []) {
2659 global $CFG;
2660
2661 // Once we've started checking a theme, don't start checking it again. Prevent recursion.
2662 if (!empty($checkedthemeforparents[$themename])) {
2663 return false;
2664 }
2665 $checkedthemeforparents[$themename] = true;
2666
2667 if ($themename == $needle) {
2668 return true;
2669 }
2670
2671 if ($themedir = upgrade_find_theme_location($themename)) {
2672 $THEME = new stdClass();
2673 require($themedir . '/config.php');
2674 $theme = $THEME;
2675 } else {
2676 return false;
2677 }
2678
2679 if (empty($theme->parents)) {
2680 return false;
2681 }
2682
2683 // Recursively search through each parent theme.
2684 foreach ($theme->parents as $parent) {
2685 if (upgrade_theme_is_from_family($needle, $parent, $checkedthemeforparents)) {
2686 return true;
2687 }
2688 }
2689 return false;
2690}
2691
2692/**
2693 * Finds the theme location and verifies the theme has all needed files.
2694 *
2695 * @param string $themename The name of the theme you want to search for
2696 * @return string full dir path or null if not found
2697 * @see \theme_config::find_theme_location()
2698 */
2699function upgrade_find_theme_location($themename) {
2700 global $CFG;
2701
2702 if (file_exists("$CFG->dirroot/theme/$themename/config.php")) {
2703 $dir = "$CFG->dirroot/theme/$themename";
2704 } else if (!empty($CFG->themedir) and file_exists("$CFG->themedir/$themename/config.php")) {
2705 $dir = "$CFG->themedir/$themename";
2706 } else {
2707 return null;
2708 }
2709
2710 return $dir;
2711}