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