Merge branch 'MDL-62181-33-enfix' of git://github.com/mudrd8mz/moodle into MOODLE_33_...
[moodle.git] / lib / upgradelib.php
blobd4db126446f9381ead10de9b5cd6a08ed8ddb754
1 <?php
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.
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/>.
18 /**
19 * Various upgrade/install related functions and classes.
21 * @package core
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
27 defined('MOODLE_INTERNAL') || die();
29 /** UPGRADE_LOG_NORMAL = 0 */
30 define('UPGRADE_LOG_NORMAL', 0);
31 /** UPGRADE_LOG_NOTICE = 1 */
32 define('UPGRADE_LOG_NOTICE', 1);
33 /** UPGRADE_LOG_ERROR = 2 */
34 define('UPGRADE_LOG_ERROR', 2);
36 /**
37 * Exception indicating unknown error during upgrade.
39 * @package core
40 * @subpackage upgrade
41 * @copyright 2009 Petr Skoda {@link http://skodak.org}
42 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
44 class upgrade_exception extends moodle_exception {
45 function __construct($plugin, $version, $debuginfo=NULL) {
46 global $CFG;
47 $a = (object)array('plugin'=>$plugin, 'version'=>$version);
48 parent::__construct('upgradeerror', 'admin', "$CFG->wwwroot/$CFG->admin/index.php", $a, $debuginfo);
52 /**
53 * Exception indicating downgrade error during upgrade.
55 * @package core
56 * @subpackage upgrade
57 * @copyright 2009 Petr Skoda {@link http://skodak.org}
58 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
60 class 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);
69 /**
70 * @package core
71 * @subpackage upgrade
72 * @copyright 2009 Petr Skoda {@link http://skodak.org}
73 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
75 class upgrade_requires_exception extends moodle_exception {
76 function __construct($plugin, $pluginversion, $currentmoodle, $requiremoodle) {
77 global $CFG;
78 $a = new stdClass();
79 $a->pluginname = $plugin;
80 $a->pluginversion = $pluginversion;
81 $a->currentmoodle = $currentmoodle;
82 $a->requiremoodle = $requiremoodle;
83 parent::__construct('pluginrequirementsnotmet', 'error', "$CFG->wwwroot/$CFG->admin/index.php", $a);
87 /**
88 * @package core
89 * @subpackage upgrade
90 * @copyright 2009 Petr Skoda {@link http://skodak.org}
91 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
93 class 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);
101 * Misplaced plugin exception.
103 * Note: this should be used only from the upgrade/admin code.
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
110 class plugin_misplaced_exception extends moodle_exception {
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
117 public function __construct($component, $expected, $current) {
118 global $CFG;
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;
126 if (strpos($expected, '$CFG->dirroot') !== 0) {
127 $expected = str_replace($CFG->dirroot, '$CFG->dirroot', $expected);
129 if (strpos($current, '$CFG->dirroot') !== 0) {
130 $current = str_replace($CFG->dirroot, '$CFG->dirroot', $current);
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);
141 * Sets maximum expected time needed for upgrade task.
142 * Please always make sure that upgrade will not run longer!
144 * The script may be automatically aborted if upgrade times out.
146 * @category upgrade
147 * @param int $max_execution_time in seconds (can not be less than 60 s)
149 function upgrade_set_timeout($max_execution_time=300) {
150 global $CFG;
152 if (!isset($CFG->upgraderunning) or $CFG->upgraderunning < time()) {
153 $upgraderunning = get_config(null, 'upgraderunning');
154 } else {
155 $upgraderunning = $CFG->upgraderunning;
158 if (!$upgraderunning) {
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/");
168 if ($max_execution_time < 60) {
169 // protection against 0 here
170 $max_execution_time = 60;
173 $expected_end = time() + $max_execution_time;
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;
180 if (CLI_SCRIPT) {
181 // there is no point in timing out of CLI scripts, admins can stop them if necessary
182 core_php_time_limit::raise();
183 } else {
184 core_php_time_limit::raise($max_execution_time);
186 set_config('upgraderunning', $expected_end); // keep upgrade locked until this time
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.
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.
197 * @category upgrade
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
203 function upgrade_main_savepoint($result, $version, $allowabort=true) {
204 global $CFG;
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);
212 if (!$result) {
213 throw new upgrade_exception(null, $version);
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);
221 set_config('version', $version);
222 upgrade_log(UPGRADE_LOG_NORMAL, null, 'Upgrade savepoint reached');
224 // reset upgrade timeout to default
225 upgrade_set_timeout();
227 // this is a safe place to stop upgrades if user aborts page loading
228 if ($allowabort and connection_aborted()) {
229 die;
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.
238 * @category upgrade
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
245 function upgrade_mod_savepoint($result, $version, $modname, $allowabort=true) {
246 global $DB;
248 $component = 'mod_'.$modname;
250 if (!$result) {
251 throw new upgrade_exception($component, $version);
254 $dbversion = $DB->get_field('config_plugins', 'value', array('plugin'=>$component, 'name'=>'version'));
256 if (!$module = $DB->get_record('modules', array('name'=>$modname))) {
257 print_error('modulenotexist', 'debug', '', $modname);
260 if ($dbversion >= $version) {
261 // something really wrong is going on in upgrade script
262 throw new downgrade_exception($component, $dbversion, $version);
264 set_config('version', $version, $component);
266 upgrade_log(UPGRADE_LOG_NORMAL, $component, 'Upgrade savepoint reached');
268 // reset upgrade timeout to default
269 upgrade_set_timeout();
271 // this is a safe place to stop upgrades if user aborts page loading
272 if ($allowabort and connection_aborted()) {
273 die;
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.
282 * @category upgrade
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
289 function upgrade_block_savepoint($result, $version, $blockname, $allowabort=true) {
290 global $DB;
292 $component = 'block_'.$blockname;
294 if (!$result) {
295 throw new upgrade_exception($component, $version);
298 $dbversion = $DB->get_field('config_plugins', 'value', array('plugin'=>$component, 'name'=>'version'));
300 if (!$block = $DB->get_record('block', array('name'=>$blockname))) {
301 print_error('blocknotexist', 'debug', '', $blockname);
304 if ($dbversion >= $version) {
305 // something really wrong is going on in upgrade script
306 throw new downgrade_exception($component, $dbversion, $version);
308 set_config('version', $version, $component);
310 upgrade_log(UPGRADE_LOG_NORMAL, $component, 'Upgrade savepoint reached');
312 // reset upgrade timeout to default
313 upgrade_set_timeout();
315 // this is a safe place to stop upgrades if user aborts page loading
316 if ($allowabort and connection_aborted()) {
317 die;
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.
326 * @category upgrade
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
334 function upgrade_plugin_savepoint($result, $version, $type, $plugin, $allowabort=true) {
335 global $DB;
337 $component = $type.'_'.$plugin;
339 if (!$result) {
340 throw new upgrade_exception($component, $version);
343 $dbversion = $DB->get_field('config_plugins', 'value', array('plugin'=>$component, 'name'=>'version'));
345 if ($dbversion >= $version) {
346 // Something really wrong is going on in the upgrade script
347 throw new downgrade_exception($component, $dbversion, $version);
349 set_config('version', $version, $component);
350 upgrade_log(UPGRADE_LOG_NORMAL, $component, 'Upgrade savepoint reached');
352 // Reset upgrade timeout to default
353 upgrade_set_timeout();
355 // This is a safe place to stop upgrades if user aborts page loading
356 if ($allowabort and connection_aborted()) {
357 die;
362 * Detect if there are leftovers in PHP source files.
364 * During main version upgrades administrators MUST move away
365 * old PHP source files and start from scratch (or better
366 * use git).
368 * @return bool true means borked upgrade, false means previous PHP files were properly removed
370 function upgrade_stale_php_files_present() {
371 global $CFG;
373 $someexamplesofremovedfiles = array(
374 // Removed in 3.3.
375 '/badges/backpackconnect.php',
376 '/calendar/yui/src/info/assets/skins/sam/moodle-calendar-info.css',
377 '/competency/classes/external/exporter.php',
378 '/mod/forum/forum.js',
379 '/user/pixgroup.php',
380 // Removed in 3.2.
381 '/calendar/preferences.php',
382 '/lib/alfresco/',
383 '/lib/jquery/jquery-1.12.1.min.js',
384 '/lib/password_compat/tests/',
385 '/lib/phpunit/classes/unittestcase.php',
386 // Removed in 3.1.
387 '/lib/classes/log/sql_internal_reader.php',
388 '/lib/zend/',
389 '/mod/forum/pix/icon.gif',
390 '/tag/templates/tagname.mustache',
391 // Removed in 3.0.
392 '/mod/lti/grade.php',
393 '/tag/coursetagslib.php',
394 // Removed in 2.9.
395 '/lib/timezone.txt',
396 // Removed in 2.8.
397 '/course/delete_category_form.php',
398 // Removed in 2.7.
399 '/admin/tool/qeupgradehelper/version.php',
400 // Removed in 2.6.
401 '/admin/block.php',
402 '/admin/oacleanup.php',
403 // Removed in 2.5.
404 '/backup/lib.php',
405 '/backup/bb/README.txt',
406 '/lib/excel/test.php',
407 // Removed in 2.4.
408 '/admin/tool/unittest/simpletestlib.php',
409 // Removed in 2.3.
410 '/lib/minify/builder/',
411 // Removed in 2.2.
412 '/lib/yui/3.4.1pr1/',
413 // Removed in 2.2.
414 '/search/cron_php5.php',
415 '/course/report/log/indexlive.php',
416 '/admin/report/backups/index.php',
417 '/admin/generator.php',
418 // Removed in 2.1.
419 '/lib/yui/2.8.0r4/',
420 // Removed in 2.0.
421 '/blocks/admin/block_admin.php',
422 '/blocks/admin_tree/block_admin_tree.php',
425 foreach ($someexamplesofremovedfiles as $file) {
426 if (file_exists($CFG->dirroot.$file)) {
427 return true;
431 return false;
435 * Upgrade plugins
436 * @param string $type The type of plugins that should be updated (e.g. 'enrol', 'qtype')
437 * return void
439 function upgrade_plugins($type, $startcallback, $endcallback, $verbose) {
440 global $CFG, $DB;
442 /// special cases
443 if ($type === 'mod') {
444 return upgrade_plugins_modules($startcallback, $endcallback, $verbose);
445 } else if ($type === 'block') {
446 return upgrade_plugins_blocks($startcallback, $endcallback, $verbose);
449 $plugs = core_component::get_plugin_list($type);
451 foreach ($plugs as $plug=>$fullplug) {
452 // Reset time so that it works when installing a large number of plugins
453 core_php_time_limit::raise(600);
454 $component = clean_param($type.'_'.$plug, PARAM_COMPONENT); // standardised plugin name
456 // check plugin dir is valid name
457 if (empty($component)) {
458 throw new plugin_defective_exception($type.'_'.$plug, 'Invalid plugin directory name.');
461 if (!is_readable($fullplug.'/version.php')) {
462 continue;
465 $plugin = new stdClass();
466 $plugin->version = null;
467 $module = $plugin; // Prevent some notices when plugin placed in wrong directory.
468 require($fullplug.'/version.php'); // defines $plugin with version etc
469 unset($module);
471 if (empty($plugin->version)) {
472 throw new plugin_defective_exception($component, 'Missing $plugin->version number in version.php.');
475 if (empty($plugin->component)) {
476 throw new plugin_defective_exception($component, 'Missing $plugin->component declaration in version.php.');
479 if ($plugin->component !== $component) {
480 throw new plugin_misplaced_exception($plugin->component, null, $fullplug);
483 $plugin->name = $plug;
484 $plugin->fullname = $component;
486 if (!empty($plugin->requires)) {
487 if ($plugin->requires > $CFG->version) {
488 throw new upgrade_requires_exception($component, $plugin->version, $CFG->version, $plugin->requires);
489 } else if ($plugin->requires < 2010000000) {
490 throw new plugin_defective_exception($component, 'Plugin is not compatible with Moodle 2.x or later.');
494 // try to recover from interrupted install.php if needed
495 if (file_exists($fullplug.'/db/install.php')) {
496 if (get_config($plugin->fullname, 'installrunning')) {
497 require_once($fullplug.'/db/install.php');
498 $recover_install_function = 'xmldb_'.$plugin->fullname.'_install_recovery';
499 if (function_exists($recover_install_function)) {
500 $startcallback($component, true, $verbose);
501 $recover_install_function();
502 unset_config('installrunning', $plugin->fullname);
503 update_capabilities($component);
504 log_update_descriptions($component);
505 external_update_descriptions($component);
506 events_update_definition($component);
507 \core\task\manager::reset_scheduled_tasks_for_component($component);
508 message_update_providers($component);
509 \core\message\inbound\manager::update_handlers_for_component($component);
510 if ($type === 'message') {
511 message_update_processors($plug);
513 upgrade_plugin_mnet_functions($component);
514 core_tag_area::reset_definitions_for_component($component);
515 $endcallback($component, true, $verbose);
520 $installedversion = $DB->get_field('config_plugins', 'value', array('name'=>'version', 'plugin'=>$component)); // No caching!
521 if (empty($installedversion)) { // new installation
522 $startcallback($component, true, $verbose);
524 /// Install tables if defined
525 if (file_exists($fullplug.'/db/install.xml')) {
526 $DB->get_manager()->install_from_xmldb_file($fullplug.'/db/install.xml');
529 /// store version
530 upgrade_plugin_savepoint(true, $plugin->version, $type, $plug, false);
532 /// execute post install file
533 if (file_exists($fullplug.'/db/install.php')) {
534 require_once($fullplug.'/db/install.php');
535 set_config('installrunning', 1, $plugin->fullname);
536 $post_install_function = 'xmldb_'.$plugin->fullname.'_install';
537 $post_install_function();
538 unset_config('installrunning', $plugin->fullname);
541 /// Install various components
542 update_capabilities($component);
543 log_update_descriptions($component);
544 external_update_descriptions($component);
545 events_update_definition($component);
546 \core\task\manager::reset_scheduled_tasks_for_component($component);
547 message_update_providers($component);
548 \core\message\inbound\manager::update_handlers_for_component($component);
549 if ($type === 'message') {
550 message_update_processors($plug);
552 upgrade_plugin_mnet_functions($component);
553 core_tag_area::reset_definitions_for_component($component);
554 $endcallback($component, true, $verbose);
556 } else if ($installedversion < $plugin->version) { // upgrade
557 /// Run the upgrade function for the plugin.
558 $startcallback($component, false, $verbose);
560 if (is_readable($fullplug.'/db/upgrade.php')) {
561 require_once($fullplug.'/db/upgrade.php'); // defines upgrading function
563 $newupgrade_function = 'xmldb_'.$plugin->fullname.'_upgrade';
564 $result = $newupgrade_function($installedversion);
565 } else {
566 $result = true;
569 $installedversion = $DB->get_field('config_plugins', 'value', array('name'=>'version', 'plugin'=>$component)); // No caching!
570 if ($installedversion < $plugin->version) {
571 // store version if not already there
572 upgrade_plugin_savepoint($result, $plugin->version, $type, $plug, false);
575 /// Upgrade various components
576 update_capabilities($component);
577 log_update_descriptions($component);
578 external_update_descriptions($component);
579 events_update_definition($component);
580 \core\task\manager::reset_scheduled_tasks_for_component($component);
581 message_update_providers($component);
582 \core\message\inbound\manager::update_handlers_for_component($component);
583 if ($type === 'message') {
584 // Ugly hack!
585 message_update_processors($plug);
587 upgrade_plugin_mnet_functions($component);
588 core_tag_area::reset_definitions_for_component($component);
589 $endcallback($component, false, $verbose);
591 } else if ($installedversion > $plugin->version) {
592 throw new downgrade_exception($component, $installedversion, $plugin->version);
598 * Find and check all modules and load them up or upgrade them if necessary
600 * @global object
601 * @global object
603 function upgrade_plugins_modules($startcallback, $endcallback, $verbose) {
604 global $CFG, $DB;
606 $mods = core_component::get_plugin_list('mod');
608 foreach ($mods as $mod=>$fullmod) {
610 if ($mod === 'NEWMODULE') { // Someone has unzipped the template, ignore it
611 continue;
614 $component = clean_param('mod_'.$mod, PARAM_COMPONENT);
616 // check module dir is valid name
617 if (empty($component)) {
618 throw new plugin_defective_exception('mod_'.$mod, 'Invalid plugin directory name.');
621 if (!is_readable($fullmod.'/version.php')) {
622 throw new plugin_defective_exception($component, 'Missing version.php');
625 $module = new stdClass();
626 $plugin = new stdClass();
627 $plugin->version = null;
628 require($fullmod .'/version.php'); // Defines $plugin with version etc.
630 // Check if the legacy $module syntax is still used.
631 if (!is_object($module) or (count((array)$module) > 0)) {
632 throw new plugin_defective_exception($component, 'Unsupported $module syntax detected in version.php');
635 // Prepare the record for the {modules} table.
636 $module = clone($plugin);
637 unset($module->version);
638 unset($module->component);
639 unset($module->dependencies);
640 unset($module->release);
642 if (empty($plugin->version)) {
643 throw new plugin_defective_exception($component, 'Missing $plugin->version number in version.php.');
646 if (empty($plugin->component)) {
647 throw new plugin_defective_exception($component, 'Missing $plugin->component declaration in version.php.');
650 if ($plugin->component !== $component) {
651 throw new plugin_misplaced_exception($plugin->component, null, $fullmod);
654 if (!empty($plugin->requires)) {
655 if ($plugin->requires > $CFG->version) {
656 throw new upgrade_requires_exception($component, $plugin->version, $CFG->version, $plugin->requires);
657 } else if ($plugin->requires < 2010000000) {
658 throw new plugin_defective_exception($component, 'Plugin is not compatible with Moodle 2.x or later.');
662 if (empty($module->cron)) {
663 $module->cron = 0;
666 // all modules must have en lang pack
667 if (!is_readable("$fullmod/lang/en/$mod.php")) {
668 throw new plugin_defective_exception($component, 'Missing mandatory en language pack.');
671 $module->name = $mod; // The name MUST match the directory
673 $installedversion = $DB->get_field('config_plugins', 'value', array('name'=>'version', 'plugin'=>$component)); // No caching!
675 if (file_exists($fullmod.'/db/install.php')) {
676 if (get_config($module->name, 'installrunning')) {
677 require_once($fullmod.'/db/install.php');
678 $recover_install_function = 'xmldb_'.$module->name.'_install_recovery';
679 if (function_exists($recover_install_function)) {
680 $startcallback($component, true, $verbose);
681 $recover_install_function();
682 unset_config('installrunning', $module->name);
683 // Install various components too
684 update_capabilities($component);
685 log_update_descriptions($component);
686 external_update_descriptions($component);
687 events_update_definition($component);
688 \core\task\manager::reset_scheduled_tasks_for_component($component);
689 message_update_providers($component);
690 \core\message\inbound\manager::update_handlers_for_component($component);
691 upgrade_plugin_mnet_functions($component);
692 core_tag_area::reset_definitions_for_component($component);
693 $endcallback($component, true, $verbose);
698 if (empty($installedversion)) {
699 $startcallback($component, true, $verbose);
701 /// Execute install.xml (XMLDB) - must be present in all modules
702 $DB->get_manager()->install_from_xmldb_file($fullmod.'/db/install.xml');
704 /// Add record into modules table - may be needed in install.php already
705 $module->id = $DB->insert_record('modules', $module);
706 upgrade_mod_savepoint(true, $plugin->version, $module->name, false);
708 /// Post installation hook - optional
709 if (file_exists("$fullmod/db/install.php")) {
710 require_once("$fullmod/db/install.php");
711 // Set installation running flag, we need to recover after exception or error
712 set_config('installrunning', 1, $module->name);
713 $post_install_function = 'xmldb_'.$module->name.'_install';
714 $post_install_function();
715 unset_config('installrunning', $module->name);
718 /// Install various components
719 update_capabilities($component);
720 log_update_descriptions($component);
721 external_update_descriptions($component);
722 events_update_definition($component);
723 \core\task\manager::reset_scheduled_tasks_for_component($component);
724 message_update_providers($component);
725 \core\message\inbound\manager::update_handlers_for_component($component);
726 upgrade_plugin_mnet_functions($component);
727 core_tag_area::reset_definitions_for_component($component);
729 $endcallback($component, true, $verbose);
731 } else if ($installedversion < $plugin->version) {
732 /// If versions say that we need to upgrade but no upgrade files are available, notify and continue
733 $startcallback($component, false, $verbose);
735 if (is_readable($fullmod.'/db/upgrade.php')) {
736 require_once($fullmod.'/db/upgrade.php'); // defines new upgrading function
737 $newupgrade_function = 'xmldb_'.$module->name.'_upgrade';
738 $result = $newupgrade_function($installedversion, $module);
739 } else {
740 $result = true;
743 $installedversion = $DB->get_field('config_plugins', 'value', array('name'=>'version', 'plugin'=>$component)); // No caching!
744 $currmodule = $DB->get_record('modules', array('name'=>$module->name));
745 if ($installedversion < $plugin->version) {
746 // store version if not already there
747 upgrade_mod_savepoint($result, $plugin->version, $mod, false);
750 // update cron flag if needed
751 if ($currmodule->cron != $module->cron) {
752 $DB->set_field('modules', 'cron', $module->cron, array('name' => $module->name));
755 // Upgrade various components
756 update_capabilities($component);
757 log_update_descriptions($component);
758 external_update_descriptions($component);
759 events_update_definition($component);
760 \core\task\manager::reset_scheduled_tasks_for_component($component);
761 message_update_providers($component);
762 \core\message\inbound\manager::update_handlers_for_component($component);
763 upgrade_plugin_mnet_functions($component);
764 core_tag_area::reset_definitions_for_component($component);
766 $endcallback($component, false, $verbose);
768 } else if ($installedversion > $plugin->version) {
769 throw new downgrade_exception($component, $installedversion, $plugin->version);
776 * This function finds all available blocks and install them
777 * into blocks table or do all the upgrade process if newer.
779 * @global object
780 * @global object
782 function upgrade_plugins_blocks($startcallback, $endcallback, $verbose) {
783 global $CFG, $DB;
785 require_once($CFG->dirroot.'/blocks/moodleblock.class.php');
787 $blocktitles = array(); // we do not want duplicate titles
789 //Is this a first install
790 $first_install = null;
792 $blocks = core_component::get_plugin_list('block');
794 foreach ($blocks as $blockname=>$fullblock) {
796 if (is_null($first_install)) {
797 $first_install = ($DB->count_records('block_instances') == 0);
800 if ($blockname === 'NEWBLOCK') { // Someone has unzipped the template, ignore it
801 continue;
804 $component = clean_param('block_'.$blockname, PARAM_COMPONENT);
806 // check block dir is valid name
807 if (empty($component)) {
808 throw new plugin_defective_exception('block_'.$blockname, 'Invalid plugin directory name.');
811 if (!is_readable($fullblock.'/version.php')) {
812 throw new plugin_defective_exception('block/'.$blockname, 'Missing version.php file.');
814 $plugin = new stdClass();
815 $plugin->version = null;
816 $plugin->cron = 0;
817 $module = $plugin; // Prevent some notices when module placed in wrong directory.
818 include($fullblock.'/version.php');
819 unset($module);
820 $block = clone($plugin);
821 unset($block->version);
822 unset($block->component);
823 unset($block->dependencies);
824 unset($block->release);
826 if (empty($plugin->version)) {
827 throw new plugin_defective_exception($component, 'Missing block version number in version.php.');
830 if (empty($plugin->component)) {
831 throw new plugin_defective_exception($component, 'Missing $plugin->component declaration in version.php.');
834 if ($plugin->component !== $component) {
835 throw new plugin_misplaced_exception($plugin->component, null, $fullblock);
838 if (!empty($plugin->requires)) {
839 if ($plugin->requires > $CFG->version) {
840 throw new upgrade_requires_exception($component, $plugin->version, $CFG->version, $plugin->requires);
841 } else if ($plugin->requires < 2010000000) {
842 throw new plugin_defective_exception($component, 'Plugin is not compatible with Moodle 2.x or later.');
846 if (!is_readable($fullblock.'/block_'.$blockname.'.php')) {
847 throw new plugin_defective_exception('block/'.$blockname, 'Missing main block class file.');
849 include_once($fullblock.'/block_'.$blockname.'.php');
851 $classname = 'block_'.$blockname;
853 if (!class_exists($classname)) {
854 throw new plugin_defective_exception($component, 'Can not load main class.');
857 $blockobj = new $classname; // This is what we'll be testing
858 $blocktitle = $blockobj->get_title();
860 // OK, it's as we all hoped. For further tests, the object will do them itself.
861 if (!$blockobj->_self_test()) {
862 throw new plugin_defective_exception($component, 'Self test failed.');
865 $block->name = $blockname; // The name MUST match the directory
867 $installedversion = $DB->get_field('config_plugins', 'value', array('name'=>'version', 'plugin'=>$component)); // No caching!
869 if (file_exists($fullblock.'/db/install.php')) {
870 if (get_config('block_'.$blockname, 'installrunning')) {
871 require_once($fullblock.'/db/install.php');
872 $recover_install_function = 'xmldb_block_'.$blockname.'_install_recovery';
873 if (function_exists($recover_install_function)) {
874 $startcallback($component, true, $verbose);
875 $recover_install_function();
876 unset_config('installrunning', 'block_'.$blockname);
877 // Install various components
878 update_capabilities($component);
879 log_update_descriptions($component);
880 external_update_descriptions($component);
881 events_update_definition($component);
882 \core\task\manager::reset_scheduled_tasks_for_component($component);
883 message_update_providers($component);
884 \core\message\inbound\manager::update_handlers_for_component($component);
885 upgrade_plugin_mnet_functions($component);
886 core_tag_area::reset_definitions_for_component($component);
887 $endcallback($component, true, $verbose);
892 if (empty($installedversion)) { // block not installed yet, so install it
893 $conflictblock = array_search($blocktitle, $blocktitles);
894 if ($conflictblock !== false) {
895 // Duplicate block titles are not allowed, they confuse people
896 // AND PHP's associative arrays ;)
897 throw new plugin_defective_exception($component, get_string('blocknameconflict', 'error', (object)array('name'=>$block->name, 'conflict'=>$conflictblock)));
899 $startcallback($component, true, $verbose);
901 if (file_exists($fullblock.'/db/install.xml')) {
902 $DB->get_manager()->install_from_xmldb_file($fullblock.'/db/install.xml');
904 $block->id = $DB->insert_record('block', $block);
905 upgrade_block_savepoint(true, $plugin->version, $block->name, false);
907 if (file_exists($fullblock.'/db/install.php')) {
908 require_once($fullblock.'/db/install.php');
909 // Set installation running flag, we need to recover after exception or error
910 set_config('installrunning', 1, 'block_'.$blockname);
911 $post_install_function = 'xmldb_block_'.$blockname.'_install';
912 $post_install_function();
913 unset_config('installrunning', 'block_'.$blockname);
916 $blocktitles[$block->name] = $blocktitle;
918 // Install various components
919 update_capabilities($component);
920 log_update_descriptions($component);
921 external_update_descriptions($component);
922 events_update_definition($component);
923 \core\task\manager::reset_scheduled_tasks_for_component($component);
924 message_update_providers($component);
925 \core\message\inbound\manager::update_handlers_for_component($component);
926 core_tag_area::reset_definitions_for_component($component);
927 upgrade_plugin_mnet_functions($component);
929 $endcallback($component, true, $verbose);
931 } else if ($installedversion < $plugin->version) {
932 $startcallback($component, false, $verbose);
934 if (is_readable($fullblock.'/db/upgrade.php')) {
935 require_once($fullblock.'/db/upgrade.php'); // defines new upgrading function
936 $newupgrade_function = 'xmldb_block_'.$blockname.'_upgrade';
937 $result = $newupgrade_function($installedversion, $block);
938 } else {
939 $result = true;
942 $installedversion = $DB->get_field('config_plugins', 'value', array('name'=>'version', 'plugin'=>$component)); // No caching!
943 $currblock = $DB->get_record('block', array('name'=>$block->name));
944 if ($installedversion < $plugin->version) {
945 // store version if not already there
946 upgrade_block_savepoint($result, $plugin->version, $block->name, false);
949 if ($currblock->cron != $block->cron) {
950 // update cron flag if needed
951 $DB->set_field('block', 'cron', $block->cron, array('id' => $currblock->id));
954 // Upgrade various components
955 update_capabilities($component);
956 log_update_descriptions($component);
957 external_update_descriptions($component);
958 events_update_definition($component);
959 \core\task\manager::reset_scheduled_tasks_for_component($component);
960 message_update_providers($component);
961 \core\message\inbound\manager::update_handlers_for_component($component);
962 upgrade_plugin_mnet_functions($component);
963 core_tag_area::reset_definitions_for_component($component);
965 $endcallback($component, false, $verbose);
967 } else if ($installedversion > $plugin->version) {
968 throw new downgrade_exception($component, $installedversion, $plugin->version);
973 // Finally, if we are in the first_install of BLOCKS setup frontpage and admin page blocks
974 if ($first_install) {
975 //Iterate over each course - there should be only site course here now
976 if ($courses = $DB->get_records('course')) {
977 foreach ($courses as $course) {
978 blocks_add_default_course_blocks($course);
982 blocks_add_default_system_blocks();
988 * Log_display description function used during install and upgrade.
990 * @param string $component name of component (moodle, mod_assignment, etc.)
991 * @return void
993 function log_update_descriptions($component) {
994 global $DB;
996 $defpath = core_component::get_component_directory($component).'/db/log.php';
998 if (!file_exists($defpath)) {
999 $DB->delete_records('log_display', array('component'=>$component));
1000 return;
1003 // load new info
1004 $logs = array();
1005 include($defpath);
1006 $newlogs = array();
1007 foreach ($logs as $log) {
1008 $newlogs[$log['module'].'-'.$log['action']] = $log; // kind of unique name
1010 unset($logs);
1011 $logs = $newlogs;
1013 $fields = array('module', 'action', 'mtable', 'field');
1014 // update all log fist
1015 $dblogs = $DB->get_records('log_display', array('component'=>$component));
1016 foreach ($dblogs as $dblog) {
1017 $name = $dblog->module.'-'.$dblog->action;
1019 if (empty($logs[$name])) {
1020 $DB->delete_records('log_display', array('id'=>$dblog->id));
1021 continue;
1024 $log = $logs[$name];
1025 unset($logs[$name]);
1027 $update = false;
1028 foreach ($fields as $field) {
1029 if ($dblog->$field != $log[$field]) {
1030 $dblog->$field = $log[$field];
1031 $update = true;
1034 if ($update) {
1035 $DB->update_record('log_display', $dblog);
1038 foreach ($logs as $log) {
1039 $dblog = (object)$log;
1040 $dblog->component = $component;
1041 $DB->insert_record('log_display', $dblog);
1046 * Web service discovery function used during install and upgrade.
1047 * @param string $component name of component (moodle, mod_assignment, etc.)
1048 * @return void
1050 function external_update_descriptions($component) {
1051 global $DB, $CFG;
1053 $defpath = core_component::get_component_directory($component).'/db/services.php';
1055 if (!file_exists($defpath)) {
1056 require_once($CFG->dirroot.'/lib/externallib.php');
1057 external_delete_descriptions($component);
1058 return;
1061 // load new info
1062 $functions = array();
1063 $services = array();
1064 include($defpath);
1066 // update all function fist
1067 $dbfunctions = $DB->get_records('external_functions', array('component'=>$component));
1068 foreach ($dbfunctions as $dbfunction) {
1069 if (empty($functions[$dbfunction->name])) {
1070 $DB->delete_records('external_functions', array('id'=>$dbfunction->id));
1071 // do not delete functions from external_services_functions, beacuse
1072 // we want to notify admins when functions used in custom services disappear
1074 //TODO: this looks wrong, we have to delete it eventually (skodak)
1075 continue;
1078 $function = $functions[$dbfunction->name];
1079 unset($functions[$dbfunction->name]);
1080 $function['classpath'] = empty($function['classpath']) ? null : $function['classpath'];
1082 $update = false;
1083 if ($dbfunction->classname != $function['classname']) {
1084 $dbfunction->classname = $function['classname'];
1085 $update = true;
1087 if ($dbfunction->methodname != $function['methodname']) {
1088 $dbfunction->methodname = $function['methodname'];
1089 $update = true;
1091 if ($dbfunction->classpath != $function['classpath']) {
1092 $dbfunction->classpath = $function['classpath'];
1093 $update = true;
1095 $functioncapabilities = array_key_exists('capabilities', $function)?$function['capabilities']:'';
1096 if ($dbfunction->capabilities != $functioncapabilities) {
1097 $dbfunction->capabilities = $functioncapabilities;
1098 $update = true;
1101 if (isset($function['services']) and is_array($function['services'])) {
1102 sort($function['services']);
1103 $functionservices = implode(',', $function['services']);
1104 } else {
1105 // Force null values in the DB.
1106 $functionservices = null;
1109 if ($dbfunction->services != $functionservices) {
1110 // Now, we need to check if services were removed, in that case we need to remove the function from them.
1111 $servicesremoved = array_diff(explode(",", $dbfunction->services), explode(",", $functionservices));
1112 foreach ($servicesremoved as $removedshortname) {
1113 if ($externalserviceid = $DB->get_field('external_services', 'id', array("shortname" => $removedshortname))) {
1114 $DB->delete_records('external_services_functions', array('functionname' => $dbfunction->name,
1115 'externalserviceid' => $externalserviceid));
1119 $dbfunction->services = $functionservices;
1120 $update = true;
1122 if ($update) {
1123 $DB->update_record('external_functions', $dbfunction);
1126 foreach ($functions as $fname => $function) {
1127 $dbfunction = new stdClass();
1128 $dbfunction->name = $fname;
1129 $dbfunction->classname = $function['classname'];
1130 $dbfunction->methodname = $function['methodname'];
1131 $dbfunction->classpath = empty($function['classpath']) ? null : $function['classpath'];
1132 $dbfunction->component = $component;
1133 $dbfunction->capabilities = array_key_exists('capabilities', $function)?$function['capabilities']:'';
1135 if (isset($function['services']) and is_array($function['services'])) {
1136 sort($function['services']);
1137 $dbfunction->services = implode(',', $function['services']);
1138 } else {
1139 // Force null values in the DB.
1140 $dbfunction->services = null;
1143 $dbfunction->id = $DB->insert_record('external_functions', $dbfunction);
1145 unset($functions);
1147 // now deal with services
1148 $dbservices = $DB->get_records('external_services', array('component'=>$component));
1149 foreach ($dbservices as $dbservice) {
1150 if (empty($services[$dbservice->name])) {
1151 $DB->delete_records('external_tokens', array('externalserviceid'=>$dbservice->id));
1152 $DB->delete_records('external_services_functions', array('externalserviceid'=>$dbservice->id));
1153 $DB->delete_records('external_services_users', array('externalserviceid'=>$dbservice->id));
1154 $DB->delete_records('external_services', array('id'=>$dbservice->id));
1155 continue;
1157 $service = $services[$dbservice->name];
1158 unset($services[$dbservice->name]);
1159 $service['enabled'] = empty($service['enabled']) ? 0 : $service['enabled'];
1160 $service['requiredcapability'] = empty($service['requiredcapability']) ? null : $service['requiredcapability'];
1161 $service['restrictedusers'] = !isset($service['restrictedusers']) ? 1 : $service['restrictedusers'];
1162 $service['downloadfiles'] = !isset($service['downloadfiles']) ? 0 : $service['downloadfiles'];
1163 $service['uploadfiles'] = !isset($service['uploadfiles']) ? 0 : $service['uploadfiles'];
1164 $service['shortname'] = !isset($service['shortname']) ? null : $service['shortname'];
1166 $update = false;
1167 if ($dbservice->requiredcapability != $service['requiredcapability']) {
1168 $dbservice->requiredcapability = $service['requiredcapability'];
1169 $update = true;
1171 if ($dbservice->restrictedusers != $service['restrictedusers']) {
1172 $dbservice->restrictedusers = $service['restrictedusers'];
1173 $update = true;
1175 if ($dbservice->downloadfiles != $service['downloadfiles']) {
1176 $dbservice->downloadfiles = $service['downloadfiles'];
1177 $update = true;
1179 if ($dbservice->uploadfiles != $service['uploadfiles']) {
1180 $dbservice->uploadfiles = $service['uploadfiles'];
1181 $update = true;
1183 //if shortname is not a PARAM_ALPHANUMEXT, fail (tested here for service update and creation)
1184 if (isset($service['shortname']) and
1185 (clean_param($service['shortname'], PARAM_ALPHANUMEXT) != $service['shortname'])) {
1186 throw new moodle_exception('installserviceshortnameerror', 'webservice', '', $service['shortname']);
1188 if ($dbservice->shortname != $service['shortname']) {
1189 //check that shortname is unique
1190 if (isset($service['shortname'])) { //we currently accepts multiple shortname == null
1191 $existingservice = $DB->get_record('external_services',
1192 array('shortname' => $service['shortname']));
1193 if (!empty($existingservice)) {
1194 throw new moodle_exception('installexistingserviceshortnameerror', 'webservice', '', $service['shortname']);
1197 $dbservice->shortname = $service['shortname'];
1198 $update = true;
1200 if ($update) {
1201 $DB->update_record('external_services', $dbservice);
1204 $functions = $DB->get_records('external_services_functions', array('externalserviceid'=>$dbservice->id));
1205 foreach ($functions as $function) {
1206 $key = array_search($function->functionname, $service['functions']);
1207 if ($key === false) {
1208 $DB->delete_records('external_services_functions', array('id'=>$function->id));
1209 } else {
1210 unset($service['functions'][$key]);
1213 foreach ($service['functions'] as $fname) {
1214 $newf = new stdClass();
1215 $newf->externalserviceid = $dbservice->id;
1216 $newf->functionname = $fname;
1217 $DB->insert_record('external_services_functions', $newf);
1219 unset($functions);
1221 foreach ($services as $name => $service) {
1222 //check that shortname is unique
1223 if (isset($service['shortname'])) { //we currently accepts multiple shortname == null
1224 $existingservice = $DB->get_record('external_services',
1225 array('shortname' => $service['shortname']));
1226 if (!empty($existingservice)) {
1227 throw new moodle_exception('installserviceshortnameerror', 'webservice');
1231 $dbservice = new stdClass();
1232 $dbservice->name = $name;
1233 $dbservice->enabled = empty($service['enabled']) ? 0 : $service['enabled'];
1234 $dbservice->requiredcapability = empty($service['requiredcapability']) ? null : $service['requiredcapability'];
1235 $dbservice->restrictedusers = !isset($service['restrictedusers']) ? 1 : $service['restrictedusers'];
1236 $dbservice->downloadfiles = !isset($service['downloadfiles']) ? 0 : $service['downloadfiles'];
1237 $dbservice->uploadfiles = !isset($service['uploadfiles']) ? 0 : $service['uploadfiles'];
1238 $dbservice->shortname = !isset($service['shortname']) ? null : $service['shortname'];
1239 $dbservice->component = $component;
1240 $dbservice->timecreated = time();
1241 $dbservice->id = $DB->insert_record('external_services', $dbservice);
1242 foreach ($service['functions'] as $fname) {
1243 $newf = new stdClass();
1244 $newf->externalserviceid = $dbservice->id;
1245 $newf->functionname = $fname;
1246 $DB->insert_record('external_services_functions', $newf);
1252 * Allow plugins and subsystems to add external functions to other plugins or built-in services.
1253 * This function is executed just after all the plugins have been updated.
1255 function external_update_services() {
1256 global $DB;
1258 // Look for external functions that want to be added in existing services.
1259 $functions = $DB->get_records_select('external_functions', 'services IS NOT NULL');
1261 $servicescache = array();
1262 foreach ($functions as $function) {
1263 // Prevent edge cases.
1264 if (empty($function->services)) {
1265 continue;
1267 $services = explode(',', $function->services);
1269 foreach ($services as $serviceshortname) {
1270 // Get the service id by shortname.
1271 if (!empty($servicescache[$serviceshortname])) {
1272 $serviceid = $servicescache[$serviceshortname];
1273 } else if ($service = $DB->get_record('external_services', array('shortname' => $serviceshortname))) {
1274 // If the component is empty, it means that is not a built-in service.
1275 // We don't allow functions to inject themselves in services created by an user in Moodle.
1276 if (empty($service->component)) {
1277 continue;
1279 $serviceid = $service->id;
1280 $servicescache[$serviceshortname] = $serviceid;
1281 } else {
1282 // Service not found.
1283 continue;
1285 // Finally add the function to the service.
1286 $newf = new stdClass();
1287 $newf->externalserviceid = $serviceid;
1288 $newf->functionname = $function->name;
1290 if (!$DB->record_exists('external_services_functions', (array)$newf)) {
1291 $DB->insert_record('external_services_functions', $newf);
1298 * upgrade logging functions
1300 function upgrade_handle_exception($ex, $plugin = null) {
1301 global $CFG;
1303 // rollback everything, we need to log all upgrade problems
1304 abort_all_db_transactions();
1306 $info = get_exception_info($ex);
1308 // First log upgrade error
1309 upgrade_log(UPGRADE_LOG_ERROR, $plugin, 'Exception: ' . get_class($ex), $info->message, $info->backtrace);
1311 // Always turn on debugging - admins need to know what is going on
1312 set_debugging(DEBUG_DEVELOPER, true);
1314 default_exception_handler($ex, true, $plugin);
1318 * Adds log entry into upgrade_log table
1320 * @param int $type UPGRADE_LOG_NORMAL, UPGRADE_LOG_NOTICE or UPGRADE_LOG_ERROR
1321 * @param string $plugin frankenstyle component name
1322 * @param string $info short description text of log entry
1323 * @param string $details long problem description
1324 * @param string $backtrace string used for errors only
1325 * @return void
1327 function upgrade_log($type, $plugin, $info, $details=null, $backtrace=null) {
1328 global $DB, $USER, $CFG;
1330 if (empty($plugin)) {
1331 $plugin = 'core';
1334 list($plugintype, $pluginname) = core_component::normalize_component($plugin);
1335 $component = is_null($pluginname) ? $plugintype : $plugintype . '_' . $pluginname;
1337 $backtrace = format_backtrace($backtrace, true);
1339 $currentversion = null;
1340 $targetversion = null;
1342 //first try to find out current version number
1343 if ($plugintype === 'core') {
1344 //main
1345 $currentversion = $CFG->version;
1347 $version = null;
1348 include("$CFG->dirroot/version.php");
1349 $targetversion = $version;
1351 } else {
1352 $pluginversion = get_config($component, 'version');
1353 if (!empty($pluginversion)) {
1354 $currentversion = $pluginversion;
1356 $cd = core_component::get_component_directory($component);
1357 if (file_exists("$cd/version.php")) {
1358 $plugin = new stdClass();
1359 $plugin->version = null;
1360 $module = $plugin;
1361 include("$cd/version.php");
1362 $targetversion = $plugin->version;
1366 $log = new stdClass();
1367 $log->type = $type;
1368 $log->plugin = $component;
1369 $log->version = $currentversion;
1370 $log->targetversion = $targetversion;
1371 $log->info = $info;
1372 $log->details = $details;
1373 $log->backtrace = $backtrace;
1374 $log->userid = $USER->id;
1375 $log->timemodified = time();
1376 try {
1377 $DB->insert_record('upgrade_log', $log);
1378 } catch (Exception $ignored) {
1379 // possible during install or 2.0 upgrade
1384 * Marks start of upgrade, blocks any other access to site.
1385 * The upgrade is finished at the end of script or after timeout.
1387 * @global object
1388 * @global object
1389 * @global object
1391 function upgrade_started($preinstall=false) {
1392 global $CFG, $DB, $PAGE, $OUTPUT;
1394 static $started = false;
1396 if ($preinstall) {
1397 ignore_user_abort(true);
1398 upgrade_setup_debug(true);
1400 } else if ($started) {
1401 upgrade_set_timeout(120);
1403 } else {
1404 if (!CLI_SCRIPT and !$PAGE->headerprinted) {
1405 $strupgrade = get_string('upgradingversion', 'admin');
1406 $PAGE->set_pagelayout('maintenance');
1407 upgrade_init_javascript();
1408 $PAGE->set_title($strupgrade.' - Moodle '.$CFG->target_release);
1409 $PAGE->set_heading($strupgrade);
1410 $PAGE->navbar->add($strupgrade);
1411 $PAGE->set_cacheable(false);
1412 echo $OUTPUT->header();
1415 ignore_user_abort(true);
1416 core_shutdown_manager::register_function('upgrade_finished_handler');
1417 upgrade_setup_debug(true);
1418 set_config('upgraderunning', time()+300);
1419 $started = true;
1424 * Internal function - executed if upgrade interrupted.
1426 function upgrade_finished_handler() {
1427 upgrade_finished();
1431 * Indicates upgrade is finished.
1433 * This function may be called repeatedly.
1435 * @global object
1436 * @global object
1438 function upgrade_finished($continueurl=null) {
1439 global $CFG, $DB, $OUTPUT;
1441 if (!empty($CFG->upgraderunning)) {
1442 unset_config('upgraderunning');
1443 // We have to forcefully purge the caches using the writer here.
1444 // This has to be done after we unset the config var. If someone hits the site while this is set they will
1445 // cause the config values to propogate to the caches.
1446 // Caches are purged after the last step in an upgrade but there is several code routines that exceute between
1447 // then and now that leaving a window for things to fall out of sync.
1448 cache_helper::purge_all(true);
1449 upgrade_setup_debug(false);
1450 ignore_user_abort(false);
1451 if ($continueurl) {
1452 echo $OUTPUT->continue_button($continueurl);
1453 echo $OUTPUT->footer();
1454 die;
1460 * @global object
1461 * @global object
1463 function upgrade_setup_debug($starting) {
1464 global $CFG, $DB;
1466 static $originaldebug = null;
1468 if ($starting) {
1469 if ($originaldebug === null) {
1470 $originaldebug = $DB->get_debug();
1472 if (!empty($CFG->upgradeshowsql)) {
1473 $DB->set_debug(true);
1475 } else {
1476 $DB->set_debug($originaldebug);
1480 function print_upgrade_separator() {
1481 if (!CLI_SCRIPT) {
1482 echo '<hr />';
1487 * Default start upgrade callback
1488 * @param string $plugin
1489 * @param bool $installation true if installation, false means upgrade
1491 function print_upgrade_part_start($plugin, $installation, $verbose) {
1492 global $OUTPUT;
1493 if (empty($plugin) or $plugin == 'moodle') {
1494 upgrade_started($installation); // does not store upgrade running flag yet
1495 if ($verbose) {
1496 echo $OUTPUT->heading(get_string('coresystem'));
1498 } else {
1499 upgrade_started();
1500 if ($verbose) {
1501 echo $OUTPUT->heading($plugin);
1504 if ($installation) {
1505 if (empty($plugin) or $plugin == 'moodle') {
1506 // no need to log - log table not yet there ;-)
1507 } else {
1508 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Starting plugin installation');
1510 } else {
1511 if (empty($plugin) or $plugin == 'moodle') {
1512 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Starting core upgrade');
1513 } else {
1514 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Starting plugin upgrade');
1520 * Default end upgrade callback
1521 * @param string $plugin
1522 * @param bool $installation true if installation, false means upgrade
1524 function print_upgrade_part_end($plugin, $installation, $verbose) {
1525 global $OUTPUT;
1526 upgrade_started();
1527 if ($installation) {
1528 if (empty($plugin) or $plugin == 'moodle') {
1529 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Core installed');
1530 } else {
1531 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Plugin installed');
1533 } else {
1534 if (empty($plugin) or $plugin == 'moodle') {
1535 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Core upgraded');
1536 } else {
1537 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Plugin upgraded');
1540 if ($verbose) {
1541 $notification = new \core\output\notification(get_string('success'), \core\output\notification::NOTIFY_SUCCESS);
1542 $notification->set_show_closebutton(false);
1543 echo $OUTPUT->render($notification);
1544 print_upgrade_separator();
1549 * Sets up JS code required for all upgrade scripts.
1550 * @global object
1552 function upgrade_init_javascript() {
1553 global $PAGE;
1554 // scroll to the end of each upgrade page so that ppl see either error or continue button,
1555 // no need to scroll continuously any more, it is enough to jump to end once the footer is printed ;-)
1556 $js = "window.scrollTo(0, 5000000);";
1557 $PAGE->requires->js_init_code($js);
1561 * Try to upgrade the given language pack (or current language)
1563 * @param string $lang the code of the language to update, defaults to the current language
1565 function upgrade_language_pack($lang = null) {
1566 global $CFG;
1568 if (!empty($CFG->skiplangupgrade)) {
1569 return;
1572 if (!file_exists("$CFG->dirroot/$CFG->admin/tool/langimport/lib.php")) {
1573 // weird, somebody uninstalled the import utility
1574 return;
1577 if (!$lang) {
1578 $lang = current_language();
1581 if (!get_string_manager()->translation_exists($lang)) {
1582 return;
1585 get_string_manager()->reset_caches();
1587 if ($lang === 'en') {
1588 return; // Nothing to do
1591 upgrade_started(false);
1593 require_once("$CFG->dirroot/$CFG->admin/tool/langimport/lib.php");
1594 tool_langimport_preupgrade_update($lang);
1596 get_string_manager()->reset_caches();
1598 print_upgrade_separator();
1602 * Install core moodle tables and initialize
1603 * @param float $version target version
1604 * @param bool $verbose
1605 * @return void, may throw exception
1607 function install_core($version, $verbose) {
1608 global $CFG, $DB;
1610 // We can not call purge_all_caches() yet, make sure the temp and cache dirs exist and are empty.
1611 remove_dir($CFG->cachedir.'', true);
1612 make_cache_directory('', true);
1614 remove_dir($CFG->localcachedir.'', true);
1615 make_localcache_directory('', true);
1617 remove_dir($CFG->tempdir.'', true);
1618 make_temp_directory('', true);
1620 remove_dir($CFG->dataroot.'/muc', true);
1621 make_writable_directory($CFG->dataroot.'/muc', true);
1623 try {
1624 core_php_time_limit::raise(600);
1625 print_upgrade_part_start('moodle', true, $verbose); // does not store upgrade running flag
1627 $DB->get_manager()->install_from_xmldb_file("$CFG->libdir/db/install.xml");
1628 upgrade_started(); // we want the flag to be stored in config table ;-)
1630 // set all core default records and default settings
1631 require_once("$CFG->libdir/db/install.php");
1632 xmldb_main_install(); // installs the capabilities too
1634 // store version
1635 upgrade_main_savepoint(true, $version, false);
1637 // Continue with the installation
1638 log_update_descriptions('moodle');
1639 external_update_descriptions('moodle');
1640 events_update_definition('moodle');
1641 \core\task\manager::reset_scheduled_tasks_for_component('moodle');
1642 message_update_providers('moodle');
1643 \core\message\inbound\manager::update_handlers_for_component('moodle');
1644 core_tag_area::reset_definitions_for_component('moodle');
1646 // Write default settings unconditionally
1647 admin_apply_default_settings(NULL, true);
1649 print_upgrade_part_end(null, true, $verbose);
1651 // Purge all caches. They're disabled but this ensures that we don't have any persistent data just in case something
1652 // during installation didn't use APIs.
1653 cache_helper::purge_all();
1654 } catch (exception $ex) {
1655 upgrade_handle_exception($ex);
1656 } catch (Throwable $ex) {
1657 // Engine errors in PHP7 throw exceptions of type Throwable (this "catch" will be ignored in PHP5).
1658 upgrade_handle_exception($ex);
1663 * Upgrade moodle core
1664 * @param float $version target version
1665 * @param bool $verbose
1666 * @return void, may throw exception
1668 function upgrade_core($version, $verbose) {
1669 global $CFG, $SITE, $DB, $COURSE;
1671 raise_memory_limit(MEMORY_EXTRA);
1673 require_once($CFG->libdir.'/db/upgrade.php'); // Defines upgrades
1675 try {
1676 // Reset caches before any output.
1677 cache_helper::purge_all(true);
1678 purge_all_caches();
1680 // Upgrade current language pack if we can
1681 upgrade_language_pack();
1683 print_upgrade_part_start('moodle', false, $verbose);
1685 // Pre-upgrade scripts for local hack workarounds.
1686 $preupgradefile = "$CFG->dirroot/local/preupgrade.php";
1687 if (file_exists($preupgradefile)) {
1688 core_php_time_limit::raise();
1689 require($preupgradefile);
1690 // Reset upgrade timeout to default.
1691 upgrade_set_timeout();
1694 $result = xmldb_main_upgrade($CFG->version);
1695 if ($version > $CFG->version) {
1696 // store version if not already there
1697 upgrade_main_savepoint($result, $version, false);
1700 // In case structure of 'course' table has been changed and we forgot to update $SITE, re-read it from db.
1701 $SITE = $DB->get_record('course', array('id' => $SITE->id));
1702 $COURSE = clone($SITE);
1704 // perform all other component upgrade routines
1705 update_capabilities('moodle');
1706 log_update_descriptions('moodle');
1707 external_update_descriptions('moodle');
1708 events_update_definition('moodle');
1709 \core\task\manager::reset_scheduled_tasks_for_component('moodle');
1710 message_update_providers('moodle');
1711 \core\message\inbound\manager::update_handlers_for_component('moodle');
1712 core_tag_area::reset_definitions_for_component('moodle');
1713 // Update core definitions.
1714 cache_helper::update_definitions(true);
1716 // Purge caches again, just to be sure we arn't holding onto old stuff now.
1717 cache_helper::purge_all(true);
1718 purge_all_caches();
1720 // Clean up contexts - more and more stuff depends on existence of paths and contexts
1721 context_helper::cleanup_instances();
1722 context_helper::create_instances(null, false);
1723 context_helper::build_all_paths(false);
1724 $syscontext = context_system::instance();
1725 $syscontext->mark_dirty();
1727 print_upgrade_part_end('moodle', false, $verbose);
1728 } catch (Exception $ex) {
1729 upgrade_handle_exception($ex);
1730 } catch (Throwable $ex) {
1731 // Engine errors in PHP7 throw exceptions of type Throwable (this "catch" will be ignored in PHP5).
1732 upgrade_handle_exception($ex);
1737 * Upgrade/install other parts of moodle
1738 * @param bool $verbose
1739 * @return void, may throw exception
1741 function upgrade_noncore($verbose) {
1742 global $CFG;
1744 raise_memory_limit(MEMORY_EXTRA);
1746 // upgrade all plugins types
1747 try {
1748 // Reset caches before any output.
1749 cache_helper::purge_all(true);
1750 purge_all_caches();
1752 $plugintypes = core_component::get_plugin_types();
1753 foreach ($plugintypes as $type=>$location) {
1754 upgrade_plugins($type, 'print_upgrade_part_start', 'print_upgrade_part_end', $verbose);
1756 // Upgrade services.
1757 // This function gives plugins and subsystems a chance to add functions to existing built-in services.
1758 external_update_services();
1760 // Update cache definitions. Involves scanning each plugin for any changes.
1761 cache_helper::update_definitions();
1762 // Mark the site as upgraded.
1763 set_config('allversionshash', core_component::get_all_versions_hash());
1765 // Purge caches again, just to be sure we arn't holding onto old stuff now.
1766 cache_helper::purge_all(true);
1767 purge_all_caches();
1769 } catch (Exception $ex) {
1770 upgrade_handle_exception($ex);
1771 } catch (Throwable $ex) {
1772 // Engine errors in PHP7 throw exceptions of type Throwable (this "catch" will be ignored in PHP5).
1773 upgrade_handle_exception($ex);
1778 * Checks if the main tables have been installed yet or not.
1780 * Note: we can not use caches here because they might be stale,
1781 * use with care!
1783 * @return bool
1785 function core_tables_exist() {
1786 global $DB;
1788 if (!$tables = $DB->get_tables(false) ) { // No tables yet at all.
1789 return false;
1791 } else { // Check for missing main tables
1792 $mtables = array('config', 'course', 'groupings'); // some tables used in 1.9 and 2.0, preferable something from the start and end of install.xml
1793 foreach ($mtables as $mtable) {
1794 if (!in_array($mtable, $tables)) {
1795 return false;
1798 return true;
1803 * upgrades the mnet rpc definitions for the given component.
1804 * this method doesn't return status, an exception will be thrown in the case of an error
1806 * @param string $component the plugin to upgrade, eg auth_mnet
1808 function upgrade_plugin_mnet_functions($component) {
1809 global $DB, $CFG;
1811 list($type, $plugin) = core_component::normalize_component($component);
1812 $path = core_component::get_plugin_directory($type, $plugin);
1814 $publishes = array();
1815 $subscribes = array();
1816 if (file_exists($path . '/db/mnet.php')) {
1817 require_once($path . '/db/mnet.php'); // $publishes comes from this file
1819 if (empty($publishes)) {
1820 $publishes = array(); // still need this to be able to disable stuff later
1822 if (empty($subscribes)) {
1823 $subscribes = array(); // still need this to be able to disable stuff later
1826 static $servicecache = array();
1828 // rekey an array based on the rpc method for easy lookups later
1829 $publishmethodservices = array();
1830 $subscribemethodservices = array();
1831 foreach($publishes as $servicename => $service) {
1832 if (is_array($service['methods'])) {
1833 foreach($service['methods'] as $methodname) {
1834 $service['servicename'] = $servicename;
1835 $publishmethodservices[$methodname][] = $service;
1840 // Disable functions that don't exist (any more) in the source
1841 // Should these be deleted? What about their permissions records?
1842 foreach ($DB->get_records('mnet_rpc', array('pluginname'=>$plugin, 'plugintype'=>$type), 'functionname ASC ') as $rpc) {
1843 if (!array_key_exists($rpc->functionname, $publishmethodservices) && $rpc->enabled) {
1844 $DB->set_field('mnet_rpc', 'enabled', 0, array('id' => $rpc->id));
1845 } else if (array_key_exists($rpc->functionname, $publishmethodservices) && !$rpc->enabled) {
1846 $DB->set_field('mnet_rpc', 'enabled', 1, array('id' => $rpc->id));
1850 // reflect all the services we're publishing and save them
1851 static $cachedclasses = array(); // to store reflection information in
1852 foreach ($publishes as $service => $data) {
1853 $f = $data['filename'];
1854 $c = $data['classname'];
1855 foreach ($data['methods'] as $method) {
1856 $dataobject = new stdClass();
1857 $dataobject->plugintype = $type;
1858 $dataobject->pluginname = $plugin;
1859 $dataobject->enabled = 1;
1860 $dataobject->classname = $c;
1861 $dataobject->filename = $f;
1863 if (is_string($method)) {
1864 $dataobject->functionname = $method;
1866 } else if (is_array($method)) { // wants to override file or class
1867 $dataobject->functionname = $method['method'];
1868 $dataobject->classname = $method['classname'];
1869 $dataobject->filename = $method['filename'];
1871 $dataobject->xmlrpcpath = $type.'/'.$plugin.'/'.$dataobject->filename.'/'.$method;
1872 $dataobject->static = false;
1874 require_once($path . '/' . $dataobject->filename);
1875 $functionreflect = null; // slightly different ways to get this depending on whether it's a class method or a function
1876 if (!empty($dataobject->classname)) {
1877 if (!class_exists($dataobject->classname)) {
1878 throw new moodle_exception('installnosuchmethod', 'mnet', '', (object)array('method' => $dataobject->functionname, 'class' => $dataobject->classname));
1880 $key = $dataobject->filename . '|' . $dataobject->classname;
1881 if (!array_key_exists($key, $cachedclasses)) { // look to see if we've already got a reflection object
1882 try {
1883 $cachedclasses[$key] = new ReflectionClass($dataobject->classname);
1884 } catch (ReflectionException $e) { // catch these and rethrow them to something more helpful
1885 throw new moodle_exception('installreflectionclasserror', 'mnet', '', (object)array('method' => $dataobject->functionname, 'class' => $dataobject->classname, 'error' => $e->getMessage()));
1888 $r =& $cachedclasses[$key];
1889 if (!$r->hasMethod($dataobject->functionname)) {
1890 throw new moodle_exception('installnosuchmethod', 'mnet', '', (object)array('method' => $dataobject->functionname, 'class' => $dataobject->classname));
1892 $functionreflect = $r->getMethod($dataobject->functionname);
1893 $dataobject->static = (int)$functionreflect->isStatic();
1894 } else {
1895 if (!function_exists($dataobject->functionname)) {
1896 throw new moodle_exception('installnosuchfunction', 'mnet', '', (object)array('method' => $dataobject->functionname, 'file' => $dataobject->filename));
1898 try {
1899 $functionreflect = new ReflectionFunction($dataobject->functionname);
1900 } catch (ReflectionException $e) { // catch these and rethrow them to something more helpful
1901 throw new moodle_exception('installreflectionfunctionerror', 'mnet', '', (object)array('method' => $dataobject->functionname, '' => $dataobject->filename, 'error' => $e->getMessage()));
1904 $dataobject->profile = serialize(admin_mnet_method_profile($functionreflect));
1905 $dataobject->help = admin_mnet_method_get_help($functionreflect);
1907 if ($record_exists = $DB->get_record('mnet_rpc', array('xmlrpcpath'=>$dataobject->xmlrpcpath))) {
1908 $dataobject->id = $record_exists->id;
1909 $dataobject->enabled = $record_exists->enabled;
1910 $DB->update_record('mnet_rpc', $dataobject);
1911 } else {
1912 $dataobject->id = $DB->insert_record('mnet_rpc', $dataobject, true);
1915 // TODO this API versioning must be reworked, here the recently processed method
1916 // sets the service API which may not be correct
1917 foreach ($publishmethodservices[$dataobject->functionname] as $service) {
1918 if ($serviceobj = $DB->get_record('mnet_service', array('name'=>$service['servicename']))) {
1919 $serviceobj->apiversion = $service['apiversion'];
1920 $DB->update_record('mnet_service', $serviceobj);
1921 } else {
1922 $serviceobj = new stdClass();
1923 $serviceobj->name = $service['servicename'];
1924 $serviceobj->description = empty($service['description']) ? '' : $service['description'];
1925 $serviceobj->apiversion = $service['apiversion'];
1926 $serviceobj->offer = 1;
1927 $serviceobj->id = $DB->insert_record('mnet_service', $serviceobj);
1929 $servicecache[$service['servicename']] = $serviceobj;
1930 if (!$DB->record_exists('mnet_service2rpc', array('rpcid'=>$dataobject->id, 'serviceid'=>$serviceobj->id))) {
1931 $obj = new stdClass();
1932 $obj->rpcid = $dataobject->id;
1933 $obj->serviceid = $serviceobj->id;
1934 $DB->insert_record('mnet_service2rpc', $obj, true);
1939 // finished with methods we publish, now do subscribable methods
1940 foreach($subscribes as $service => $methods) {
1941 if (!array_key_exists($service, $servicecache)) {
1942 if (!$serviceobj = $DB->get_record('mnet_service', array('name' => $service))) {
1943 debugging("TODO: skipping unknown service $service - somebody needs to fix MDL-21993");
1944 continue;
1946 $servicecache[$service] = $serviceobj;
1947 } else {
1948 $serviceobj = $servicecache[$service];
1950 foreach ($methods as $method => $xmlrpcpath) {
1951 if (!$rpcid = $DB->get_field('mnet_remote_rpc', 'id', array('xmlrpcpath'=>$xmlrpcpath))) {
1952 $remoterpc = (object)array(
1953 'functionname' => $method,
1954 'xmlrpcpath' => $xmlrpcpath,
1955 'plugintype' => $type,
1956 'pluginname' => $plugin,
1957 'enabled' => 1,
1959 $rpcid = $remoterpc->id = $DB->insert_record('mnet_remote_rpc', $remoterpc, true);
1961 if (!$DB->record_exists('mnet_remote_service2rpc', array('rpcid'=>$rpcid, 'serviceid'=>$serviceobj->id))) {
1962 $obj = new stdClass();
1963 $obj->rpcid = $rpcid;
1964 $obj->serviceid = $serviceobj->id;
1965 $DB->insert_record('mnet_remote_service2rpc', $obj, true);
1967 $subscribemethodservices[$method][] = $service;
1971 foreach ($DB->get_records('mnet_remote_rpc', array('pluginname'=>$plugin, 'plugintype'=>$type), 'functionname ASC ') as $rpc) {
1972 if (!array_key_exists($rpc->functionname, $subscribemethodservices) && $rpc->enabled) {
1973 $DB->set_field('mnet_remote_rpc', 'enabled', 0, array('id' => $rpc->id));
1974 } else if (array_key_exists($rpc->functionname, $subscribemethodservices) && !$rpc->enabled) {
1975 $DB->set_field('mnet_remote_rpc', 'enabled', 1, array('id' => $rpc->id));
1979 return true;
1983 * Given some sort of reflection function/method object, return a profile array, ready to be serialized and stored
1985 * @param ReflectionFunctionAbstract $function reflection function/method object from which to extract information
1987 * @return array associative array with function/method information
1989 function admin_mnet_method_profile(ReflectionFunctionAbstract $function) {
1990 $commentlines = admin_mnet_method_get_docblock($function);
1991 $getkey = function($key) use ($commentlines) {
1992 return array_values(array_filter($commentlines, function($line) use ($key) {
1993 return $line[0] == $key;
1994 }));
1996 $returnline = $getkey('@return');
1997 return array (
1998 'parameters' => array_map(function($line) {
1999 return array(
2000 'name' => trim($line[2], " \t\n\r\0\x0B$"),
2001 'type' => $line[1],
2002 'description' => $line[3]
2004 }, $getkey('@param')),
2006 'return' => array(
2007 'type' => !empty($returnline[0][1]) ? $returnline[0][1] : 'void',
2008 'description' => !empty($returnline[0][2]) ? $returnline[0][2] : ''
2014 * Given some sort of reflection function/method object, return an array of docblock lines, where each line is an array of
2015 * keywords/descriptions
2017 * @param ReflectionFunctionAbstract $function reflection function/method object from which to extract information
2019 * @return array docblock converted in to an array
2021 function admin_mnet_method_get_docblock(ReflectionFunctionAbstract $function) {
2022 return array_map(function($line) {
2023 $text = trim($line, " \t\n\r\0\x0B*/");
2024 if (strpos($text, '@param') === 0) {
2025 return preg_split('/\s+/', $text, 4);
2028 if (strpos($text, '@return') === 0) {
2029 return preg_split('/\s+/', $text, 3);
2032 return array($text);
2033 }, explode("\n", $function->getDocComment()));
2037 * Given some sort of reflection function/method object, return just the help text
2039 * @param ReflectionFunctionAbstract $function reflection function/method object from which to extract information
2041 * @return string docblock help text
2043 function admin_mnet_method_get_help(ReflectionFunctionAbstract $function) {
2044 $helplines = array_map(function($line) {
2045 return implode(' ', $line);
2046 }, array_values(array_filter(admin_mnet_method_get_docblock($function), function($line) {
2047 return strpos($line[0], '@') !== 0 && !empty($line[0]);
2048 })));
2050 return implode("\n", $helplines);
2054 * Detect draft file areas with missing root directory records and add them.
2056 function upgrade_fix_missing_root_folders_draft() {
2057 global $DB;
2059 $transaction = $DB->start_delegated_transaction();
2061 $sql = "SELECT contextid, itemid, MAX(timecreated) AS timecreated, MAX(timemodified) AS timemodified
2062 FROM {files}
2063 WHERE (component = 'user' AND filearea = 'draft')
2064 GROUP BY contextid, itemid
2065 HAVING MAX(CASE WHEN filename = '.' AND filepath = '/' THEN 1 ELSE 0 END) = 0";
2067 $rs = $DB->get_recordset_sql($sql);
2068 $defaults = array('component' => 'user',
2069 'filearea' => 'draft',
2070 'filepath' => '/',
2071 'filename' => '.',
2072 'userid' => 0, // Don't rely on any particular user for these system records.
2073 'filesize' => 0,
2074 // Note: This does not use the file_storage API's hash calculator
2075 // because access to core APIs is not allowed during upgrade.
2076 'contenthash' => sha1(''),
2078 foreach ($rs as $r) {
2079 $r->pathnamehash = sha1("/$r->contextid/user/draft/$r->itemid/.");
2080 $DB->insert_record('files', (array)$r + $defaults);
2082 $rs->close();
2083 $transaction->allow_commit();
2087 * This function verifies that the database is not using an unsupported storage engine.
2089 * @param environment_results $result object to update, if relevant
2090 * @return environment_results|null updated results object, or null if the storage engine is supported
2092 function check_database_storage_engine(environment_results $result) {
2093 global $DB;
2095 // Check if MySQL is the DB family (this will also be the same for MariaDB).
2096 if ($DB->get_dbfamily() == 'mysql') {
2097 // Get the database engine we will either be using to install the tables, or what we are currently using.
2098 $engine = $DB->get_dbengine();
2099 // Check if MyISAM is the storage engine that will be used, if so, do not proceed and display an error.
2100 if ($engine == 'MyISAM') {
2101 $result->setInfo('unsupported_db_storage_engine');
2102 $result->setStatus(false);
2103 return $result;
2107 return null;
2111 * Method used to check the usage of slasharguments config and display a warning message.
2113 * @param environment_results $result object to update, if relevant.
2114 * @return environment_results|null updated results or null if slasharguments is disabled.
2116 function check_slasharguments(environment_results $result){
2117 global $CFG;
2119 if (!during_initial_install() && empty($CFG->slasharguments)) {
2120 $result->setInfo('slasharguments');
2121 $result->setStatus(false);
2122 return $result;
2125 return null;
2129 * This function verifies if the database has tables using innoDB Antelope row format.
2131 * @param environment_results $result
2132 * @return environment_results|null updated results object, or null if no Antelope table has been found.
2134 function check_database_tables_row_format(environment_results $result) {
2135 global $DB;
2137 if ($DB->get_dbfamily() == 'mysql') {
2138 $generator = $DB->get_manager()->generator;
2140 foreach ($DB->get_tables(false) as $table) {
2141 $columns = $DB->get_columns($table, false);
2142 $size = $generator->guess_antelope_row_size($columns);
2143 $format = $DB->get_row_format($table);
2145 if ($size <= $generator::ANTELOPE_MAX_ROW_SIZE) {
2146 continue;
2149 if ($format === 'Compact' or $format === 'Redundant') {
2150 $result->setInfo('unsupported_db_table_row_format');
2151 $result->setStatus(false);
2152 return $result;
2157 return null;
2161 * This function verfies that the database has tables using InnoDB Antelope row format.
2163 * @param environment_results $result
2164 * @return environment_results|null updated results object, or null if no Antelope table has been found.
2166 function check_mysql_file_format(environment_results $result) {
2167 global $DB;
2169 if ($DB->get_dbfamily() == 'mysql') {
2170 $collation = $DB->get_dbcollation();
2171 $collationinfo = explode('_', $collation);
2172 $charset = reset($collationinfo);
2174 if ($charset == 'utf8mb4') {
2175 if ($DB->get_row_format() !== "Barracuda") {
2176 $result->setInfo('mysql_full_unicode_support#File_format');
2177 $result->setStatus(false);
2178 return $result;
2182 return null;
2186 * This function verfies that the database has a setting of one file per table. This is required for 'utf8mb4'.
2188 * @param environment_results $result
2189 * @return environment_results|null updated results object, or null if innodb_file_per_table = 1.
2191 function check_mysql_file_per_table(environment_results $result) {
2192 global $DB;
2194 if ($DB->get_dbfamily() == 'mysql') {
2195 $collation = $DB->get_dbcollation();
2196 $collationinfo = explode('_', $collation);
2197 $charset = reset($collationinfo);
2199 if ($charset == 'utf8mb4') {
2200 if (!$DB->is_file_per_table_enabled()) {
2201 $result->setInfo('mysql_full_unicode_support#File_per_table');
2202 $result->setStatus(false);
2203 return $result;
2207 return null;
2211 * This function verfies that the database has the setting of large prefix enabled. This is required for 'utf8mb4'.
2213 * @param environment_results $result
2214 * @return environment_results|null updated results object, or null if innodb_large_prefix = 1.
2216 function check_mysql_large_prefix(environment_results $result) {
2217 global $DB;
2219 if ($DB->get_dbfamily() == 'mysql') {
2220 $collation = $DB->get_dbcollation();
2221 $collationinfo = explode('_', $collation);
2222 $charset = reset($collationinfo);
2224 if ($charset == 'utf8mb4') {
2225 if (!$DB->is_large_prefix_enabled()) {
2226 $result->setInfo('mysql_full_unicode_support#Large_prefix');
2227 $result->setStatus(false);
2228 return $result;
2232 return null;
2236 * This function checks the database to see if it is using incomplete unicode support.
2238 * @param environment_results $result $result
2239 * @return environment_results|null updated results object, or null if unicode is fully supported.
2241 function check_mysql_incomplete_unicode_support(environment_results $result) {
2242 global $DB;
2244 if ($DB->get_dbfamily() == 'mysql') {
2245 $collation = $DB->get_dbcollation();
2246 $collationinfo = explode('_', $collation);
2247 $charset = reset($collationinfo);
2249 if ($charset == 'utf8') {
2250 $result->setInfo('mysql_full_unicode_support');
2251 $result->setStatus(false);
2252 return $result;
2255 return null;
2259 * Check if the site is being served using an ssl url.
2261 * Note this does not really perform any request neither looks for proxies or
2262 * other situations. Just looks to wwwroot and warn if it's not using https.
2264 * @param environment_results $result $result
2265 * @return environment_results|null updated results object, or null if the site is https.
2267 function check_is_https(environment_results $result) {
2268 global $CFG;
2270 // Only if is defined, non-empty and whatever core tell us.
2271 if (!empty($CFG->wwwroot) && !is_https()) {
2272 $result->setInfo('site not https');
2273 $result->setStatus(false);
2274 return $result;
2276 return null;
2280 * Upgrade the minmaxgrade setting.
2282 * This step should only be run for sites running 2.8 or later. Sites using 2.7 will be fine
2283 * using the new default system setting $CFG->grade_minmaxtouse.
2285 * @return void
2287 function upgrade_minmaxgrade() {
2288 global $CFG, $DB;
2290 // 2 is a copy of GRADE_MIN_MAX_FROM_GRADE_GRADE.
2291 $settingvalue = 2;
2293 // Set the course setting when:
2294 // - The system setting does not exist yet.
2295 // - The system seeting is not set to what we'd set the course setting.
2296 $setcoursesetting = !isset($CFG->grade_minmaxtouse) || $CFG->grade_minmaxtouse != $settingvalue;
2298 // Identify the courses that have inconsistencies grade_item vs grade_grade.
2299 $sql = "SELECT DISTINCT(gi.courseid)
2300 FROM {grade_grades} gg
2301 JOIN {grade_items} gi
2302 ON gg.itemid = gi.id
2303 WHERE gi.itemtype NOT IN (?, ?)
2304 AND (gg.rawgrademax != gi.grademax OR gg.rawgrademin != gi.grademin)";
2306 $rs = $DB->get_recordset_sql($sql, array('course', 'category'));
2307 foreach ($rs as $record) {
2308 // Flag the course to show a notice in the gradebook.
2309 set_config('show_min_max_grades_changed_' . $record->courseid, 1);
2311 // Set the appropriate course setting so that grades displayed are not changed.
2312 $configname = 'minmaxtouse';
2313 if ($setcoursesetting &&
2314 !$DB->record_exists('grade_settings', array('courseid' => $record->courseid, 'name' => $configname))) {
2315 // Do not set the setting when the course already defines it.
2316 $data = new stdClass();
2317 $data->courseid = $record->courseid;
2318 $data->name = $configname;
2319 $data->value = $settingvalue;
2320 $DB->insert_record('grade_settings', $data);
2323 // Mark the grades to be regraded.
2324 $DB->set_field('grade_items', 'needsupdate', 1, array('courseid' => $record->courseid));
2326 $rs->close();
2331 * Assert the upgrade key is provided, if it is defined.
2333 * The upgrade key can be defined in the main config.php as $CFG->upgradekey. If
2334 * it is defined there, then its value must be provided every time the site is
2335 * being upgraded, regardless the administrator is logged in or not.
2337 * This is supposed to be used at certain places in /admin/index.php only.
2339 * @param string|null $upgradekeyhash the SHA-1 of the value provided by the user
2341 function check_upgrade_key($upgradekeyhash) {
2342 global $CFG, $PAGE;
2344 if (isset($CFG->config_php_settings['upgradekey'])) {
2345 if ($upgradekeyhash === null or $upgradekeyhash !== sha1($CFG->config_php_settings['upgradekey'])) {
2346 if (!$PAGE->headerprinted) {
2347 $output = $PAGE->get_renderer('core', 'admin');
2348 echo $output->upgradekey_form_page(new moodle_url('/admin/index.php', array('cache' => 0)));
2349 die();
2350 } else {
2351 // This should not happen.
2352 die('Upgrade locked');
2359 * Helper procedure/macro for installing remote plugins at admin/index.php
2361 * Does not return, always redirects or exits.
2363 * @param array $installable list of \core\update\remote_info
2364 * @param bool $confirmed false: display the validation screen, true: proceed installation
2365 * @param string $heading validation screen heading
2366 * @param moodle_url|string|null $continue URL to proceed with installation at the validation screen
2367 * @param moodle_url|string|null $return URL to go back on cancelling at the validation screen
2369 function upgrade_install_plugins(array $installable, $confirmed, $heading='', $continue=null, $return=null) {
2370 global $CFG, $PAGE;
2372 if (empty($return)) {
2373 $return = $PAGE->url;
2376 if (!empty($CFG->disableupdateautodeploy)) {
2377 redirect($return);
2380 if (empty($installable)) {
2381 redirect($return);
2384 $pluginman = core_plugin_manager::instance();
2386 if ($confirmed) {
2387 // Installation confirmed at the validation results page.
2388 if (!$pluginman->install_plugins($installable, true, true)) {
2389 throw new moodle_exception('install_plugins_failed', 'core_plugin', $return);
2392 // Always redirect to admin/index.php to perform the database upgrade.
2393 // Do not throw away the existing $PAGE->url parameters such as
2394 // confirmupgrade or confirmrelease if $PAGE->url is a superset of the
2395 // URL we must go to.
2396 $mustgoto = new moodle_url('/admin/index.php', array('cache' => 0, 'confirmplugincheck' => 0));
2397 if ($mustgoto->compare($PAGE->url, URL_MATCH_PARAMS)) {
2398 redirect($PAGE->url);
2399 } else {
2400 redirect($mustgoto);
2403 } else {
2404 $output = $PAGE->get_renderer('core', 'admin');
2405 echo $output->header();
2406 if ($heading) {
2407 echo $output->heading($heading, 3);
2409 echo html_writer::start_tag('pre', array('class' => 'plugin-install-console'));
2410 $validated = $pluginman->install_plugins($installable, false, false);
2411 echo html_writer::end_tag('pre');
2412 if ($validated) {
2413 echo $output->plugins_management_confirm_buttons($continue, $return);
2414 } else {
2415 echo $output->plugins_management_confirm_buttons(null, $return);
2417 echo $output->footer();
2418 die();
2422 * Method used to check the installed unoconv version.
2424 * @param environment_results $result object to update, if relevant.
2425 * @return environment_results|null updated results or null if unoconv path is not executable.
2427 function check_unoconv_version(environment_results $result) {
2428 global $CFG;
2430 if (!during_initial_install() && !empty($CFG->pathtounoconv) && file_is_executable(trim($CFG->pathtounoconv))) {
2431 $currentversion = 0;
2432 $supportedversion = 0.7;
2433 $unoconvbin = \escapeshellarg($CFG->pathtounoconv);
2434 $command = "$unoconvbin --version";
2435 exec($command, $output);
2437 // If the command execution returned some output, then get the unoconv version.
2438 if ($output) {
2439 foreach ($output as $response) {
2440 if (preg_match('/unoconv (\\d+\\.\\d+)/', $response, $matches)) {
2441 $currentversion = (float)$matches[1];
2446 if ($currentversion < $supportedversion) {
2447 $result->setInfo('unoconv version not supported');
2448 $result->setStatus(false);
2449 return $result;
2452 return null;
2456 * Checks for up-to-date TLS libraries. NOTE: this is not currently used, see MDL-57262.
2458 * @param environment_results $result object to update, if relevant.
2459 * @return environment_results|null updated results or null if unoconv path is not executable.
2461 function check_tls_libraries(environment_results $result) {
2462 global $CFG;
2464 if (!function_exists('curl_version')) {
2465 $result->setInfo('cURL PHP extension is not installed');
2466 $result->setStatus(false);
2467 return $result;
2470 if (!\core\upgrade\util::validate_php_curl_tls(curl_version(), PHP_ZTS)) {
2471 $result->setInfo('invalid ssl/tls configuration');
2472 $result->setStatus(false);
2473 return $result;
2476 if (!\core\upgrade\util::can_use_tls12(curl_version(), php_uname('r'))) {
2477 $result->setInfo('ssl/tls configuration not supported');
2478 $result->setStatus(false);
2479 return $result;
2482 return null;
2486 * Check if recommended version of libcurl is installed or not.
2488 * @param environment_results $result object to update, if relevant.
2489 * @return environment_results|null updated results or null.
2491 function check_libcurl_version(environment_results $result) {
2493 if (!function_exists('curl_version')) {
2494 $result->setInfo('cURL PHP extension is not installed');
2495 $result->setStatus(false);
2496 return $result;
2499 // Supported version and version number.
2500 $supportedversion = 0x071304;
2501 $supportedversionstring = "7.19.4";
2503 // Installed version.
2504 $curlinfo = curl_version();
2505 $currentversion = $curlinfo['version_number'];
2507 if ($currentversion < $supportedversion) {
2508 // Test fail.
2509 // Set info, we want to let user know how to resolve the problem.
2510 $result->setInfo('Libcurl version check');
2511 $result->setNeededVersion($supportedversionstring);
2512 $result->setCurrentVersion($curlinfo['version']);
2513 $result->setStatus(false);
2514 return $result;
2517 return null;
2521 * Fix how auth plugins are called in the 'config_plugins' table.
2523 * For legacy reasons, the auth plugins did not always use their frankenstyle
2524 * component name in the 'plugin' column of the 'config_plugins' table. This is
2525 * a helper function to correctly migrate the legacy settings into the expected
2526 * and consistent way.
2528 * @param string $plugin the auth plugin name such as 'cas', 'manual' or 'mnet'
2530 function upgrade_fix_config_auth_plugin_names($plugin) {
2531 global $CFG, $DB, $OUTPUT;
2533 $legacy = (array) get_config('auth/'.$plugin);
2534 $current = (array) get_config('auth_'.$plugin);
2536 // I don't want to rely on array_merge() and friends here just in case
2537 // there was some crazy setting with a numerical name.
2539 if ($legacy) {
2540 $new = $legacy;
2541 } else {
2542 $new = [];
2545 if ($current) {
2546 foreach ($current as $name => $value) {
2547 if (isset($legacy[$name]) && ($legacy[$name] !== $value)) {
2548 // No need to pollute the output during unit tests.
2549 if (!empty($CFG->upgraderunning)) {
2550 $message = get_string('settingmigrationmismatch', 'core_auth', [
2551 'plugin' => 'auth_'.$plugin,
2552 'setting' => s($name),
2553 'legacy' => s($legacy[$name]),
2554 'current' => s($value),
2556 echo $OUTPUT->notification($message, \core\output\notification::NOTIFY_ERROR);
2558 upgrade_log(UPGRADE_LOG_NOTICE, 'auth_'.$plugin, 'Setting values mismatch detected',
2559 'SETTING: '.$name. ' LEGACY: '.$legacy[$name].' CURRENT: '.$value);
2563 $new[$name] = $value;
2567 foreach ($new as $name => $value) {
2568 set_config($name, $value, 'auth_'.$plugin);
2569 unset_config($name, 'auth/'.$plugin);
2574 * Populate the auth plugin settings with defaults if needed.
2576 * As a result of fixing the auth plugins config storage, many settings would
2577 * be falsely reported as new ones by admin/upgradesettings.php. We do not want
2578 * to confuse admins so we try to reduce the bewilderment by pre-populating the
2579 * config_plugins table with default values. This should be done only for
2580 * disabled auth methods. The enabled methods have their settings already
2581 * stored, so reporting actual new settings for them is valid.
2583 * @param string $plugin the auth plugin name such as 'cas', 'manual' or 'mnet'
2585 function upgrade_fix_config_auth_plugin_defaults($plugin) {
2586 global $CFG;
2588 $pluginman = core_plugin_manager::instance();
2589 $enabled = $pluginman->get_enabled_plugins('auth');
2591 if (isset($enabled[$plugin])) {
2592 // Do not touch settings of enabled auth methods.
2593 return;
2596 // We can't directly use {@link core\plugininfo\auth::load_settings()} here
2597 // because the plugins are not fully upgraded yet. Instead, we emulate what
2598 // that method does. We fetch a temporary instance of the plugin's settings
2599 // page to get access to the settings and their defaults. Note we are not
2600 // adding that temporary instance into the admin tree. Yes, this is a hack.
2602 $plugininfo = $pluginman->get_plugin_info('auth_'.$plugin);
2603 $adminroot = admin_get_root();
2604 $ADMIN = $adminroot;
2605 $auth = $plugininfo;
2607 $section = $plugininfo->get_settings_section_name();
2608 $settingspath = $plugininfo->full_path('settings.php');
2610 if (file_exists($settingspath)) {
2611 $settings = new admin_settingpage($section, 'Emulated settings page for auth_'.$plugin, 'moodle/site:config');
2612 include($settingspath);
2614 if ($settings) {
2615 // Consistently with what admin/cli/upgrade.php does, apply the default settings twice.
2616 // I assume this is done for theoretical cases when a default value depends on an other.
2617 admin_apply_default_settings($settings, false);
2618 admin_apply_default_settings($settings, false);
2624 * Search for a given theme in any of the parent themes of a given theme.
2626 * @param string $needle The name of the theme you want to search for
2627 * @param string $themename The name of the theme you want to search for
2628 * @param string $checkedthemeforparents The name of all the themes already checked
2629 * @return bool True if found, false if not.
2631 function upgrade_theme_is_from_family($needle, $themename, $checkedthemeforparents = []) {
2632 global $CFG;
2634 // Once we've started checking a theme, don't start checking it again. Prevent recursion.
2635 if (!empty($checkedthemeforparents[$themename])) {
2636 return false;
2638 $checkedthemeforparents[$themename] = true;
2640 if ($themename == $needle) {
2641 return true;
2644 if ($themedir = upgrade_find_theme_location($themename)) {
2645 $THEME = new stdClass();
2646 require($themedir . '/config.php');
2647 $theme = $THEME;
2648 } else {
2649 return false;
2652 if (empty($theme->parents)) {
2653 return false;
2656 // Recursively search through each parent theme.
2657 foreach ($theme->parents as $parent) {
2658 if (upgrade_theme_is_from_family($needle, $parent, $checkedthemeforparents)) {
2659 return true;
2662 return false;
2666 * Finds the theme location and verifies the theme has all needed files.
2668 * @param string $themename The name of the theme you want to search for
2669 * @return string full dir path or null if not found
2670 * @see \theme_config::find_theme_location()
2672 function upgrade_find_theme_location($themename) {
2673 global $CFG;
2675 if (file_exists("$CFG->dirroot/theme/$themename/config.php")) {
2676 $dir = "$CFG->dirroot/theme/$themename";
2677 } else if (!empty($CFG->themedir) and file_exists("$CFG->themedir/$themename/config.php")) {
2678 $dir = "$CFG->themedir/$themename";
2679 } else {
2680 return null;
2683 return $dir;