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