Merge branch 'MDL-62388_master' of git://github.com/dmonllao/moodle
[moodle.git] / lib / upgradelib.php
blob13ab17aa7919cb4b6c7aac231198daff1d0e6f8c
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 * Static class monitors performance of upgrade steps.
143 class core_upgrade_time {
144 /** @var float Time at start of current upgrade (plugin/system) */
145 protected static $before;
146 /** @var float Time at end of last savepoint */
147 protected static $lastsavepoint;
148 /** @var bool Flag to indicate whether we are recording timestamps or not. */
149 protected static $isrecording = false;
152 * Records current time at the start of the current upgrade item, e.g. plugin.
154 public static function record_start() {
155 self::$before = microtime(true);
156 self::$lastsavepoint = self::$before;
157 self::$isrecording = true;
161 * Records current time at the end of a given numbered step.
163 * @param float $version Version number (may have decimals, or not)
165 public static function record_savepoint($version) {
166 global $CFG, $OUTPUT;
168 // In developer debug mode we show a notification after each individual save point.
169 if ($CFG->debugdeveloper && self::$isrecording) {
170 $time = microtime(true);
172 $notification = new \core\output\notification($version . ': ' .
173 get_string('successduration', '', format_float($time - self::$lastsavepoint, 2)),
174 \core\output\notification::NOTIFY_SUCCESS);
175 $notification->set_show_closebutton(false);
176 echo $OUTPUT->render($notification);
177 self::$lastsavepoint = $time;
182 * Gets the time since the record_start function was called, rounded to 2 digits.
184 * @return float Elapsed time
186 public static function get_elapsed() {
187 return microtime(true) - self::$before;
192 * Sets maximum expected time needed for upgrade task.
193 * Please always make sure that upgrade will not run longer!
195 * The script may be automatically aborted if upgrade times out.
197 * @category upgrade
198 * @param int $max_execution_time in seconds (can not be less than 60 s)
200 function upgrade_set_timeout($max_execution_time=300) {
201 global $CFG;
203 if (!isset($CFG->upgraderunning) or $CFG->upgraderunning < time()) {
204 $upgraderunning = get_config(null, 'upgraderunning');
205 } else {
206 $upgraderunning = $CFG->upgraderunning;
209 if (!$upgraderunning) {
210 if (CLI_SCRIPT) {
211 // never stop CLI upgrades
212 $upgraderunning = 0;
213 } else {
214 // web upgrade not running or aborted
215 print_error('upgradetimedout', 'admin', "$CFG->wwwroot/$CFG->admin/");
219 if ($max_execution_time < 60) {
220 // protection against 0 here
221 $max_execution_time = 60;
224 $expected_end = time() + $max_execution_time;
226 if ($expected_end < $upgraderunning + 10 and $expected_end > $upgraderunning - 10) {
227 // no need to store new end, it is nearly the same ;-)
228 return;
231 if (CLI_SCRIPT) {
232 // there is no point in timing out of CLI scripts, admins can stop them if necessary
233 core_php_time_limit::raise();
234 } else {
235 core_php_time_limit::raise($max_execution_time);
237 set_config('upgraderunning', $expected_end); // keep upgrade locked until this time
241 * Upgrade savepoint, marks end of each upgrade block.
242 * It stores new main version, resets upgrade timeout
243 * and abort upgrade if user cancels page loading.
245 * Please do not make large upgrade blocks with lots of operations,
246 * for example when adding tables keep only one table operation per block.
248 * @category upgrade
249 * @param bool $result false if upgrade step failed, true if completed
250 * @param string or float $version main version
251 * @param bool $allowabort allow user to abort script execution here
252 * @return void
254 function upgrade_main_savepoint($result, $version, $allowabort=true) {
255 global $CFG;
257 //sanity check to avoid confusion with upgrade_mod_savepoint usage.
258 if (!is_bool($allowabort)) {
259 $errormessage = 'Parameter type mismatch. Are you mixing up upgrade_main_savepoint() and upgrade_mod_savepoint()?';
260 throw new coding_exception($errormessage);
263 if (!$result) {
264 throw new upgrade_exception(null, $version);
267 if ($CFG->version >= $version) {
268 // something really wrong is going on in main upgrade script
269 throw new downgrade_exception(null, $CFG->version, $version);
272 set_config('version', $version);
273 upgrade_log(UPGRADE_LOG_NORMAL, null, 'Upgrade savepoint reached');
275 // reset upgrade timeout to default
276 upgrade_set_timeout();
278 core_upgrade_time::record_savepoint($version);
280 // this is a safe place to stop upgrades if user aborts page loading
281 if ($allowabort and connection_aborted()) {
282 die;
287 * Module upgrade savepoint, marks end of module upgrade blocks
288 * It stores module version, resets upgrade timeout
289 * and abort upgrade if user cancels page loading.
291 * @category upgrade
292 * @param bool $result false if upgrade step failed, true if completed
293 * @param string or float $version main version
294 * @param string $modname name of module
295 * @param bool $allowabort allow user to abort script execution here
296 * @return void
298 function upgrade_mod_savepoint($result, $version, $modname, $allowabort=true) {
299 global $DB;
301 $component = 'mod_'.$modname;
303 if (!$result) {
304 throw new upgrade_exception($component, $version);
307 $dbversion = $DB->get_field('config_plugins', 'value', array('plugin'=>$component, 'name'=>'version'));
309 if (!$module = $DB->get_record('modules', array('name'=>$modname))) {
310 print_error('modulenotexist', 'debug', '', $modname);
313 if ($dbversion >= $version) {
314 // something really wrong is going on in upgrade script
315 throw new downgrade_exception($component, $dbversion, $version);
317 set_config('version', $version, $component);
319 upgrade_log(UPGRADE_LOG_NORMAL, $component, 'Upgrade savepoint reached');
321 // reset upgrade timeout to default
322 upgrade_set_timeout();
324 core_upgrade_time::record_savepoint($version);
326 // this is a safe place to stop upgrades if user aborts page loading
327 if ($allowabort and connection_aborted()) {
328 die;
333 * Blocks upgrade savepoint, marks end of blocks upgrade blocks
334 * It stores block version, resets upgrade timeout
335 * and abort upgrade if user cancels page loading.
337 * @category upgrade
338 * @param bool $result false if upgrade step failed, true if completed
339 * @param string or float $version main version
340 * @param string $blockname name of block
341 * @param bool $allowabort allow user to abort script execution here
342 * @return void
344 function upgrade_block_savepoint($result, $version, $blockname, $allowabort=true) {
345 global $DB;
347 $component = 'block_'.$blockname;
349 if (!$result) {
350 throw new upgrade_exception($component, $version);
353 $dbversion = $DB->get_field('config_plugins', 'value', array('plugin'=>$component, 'name'=>'version'));
355 if (!$block = $DB->get_record('block', array('name'=>$blockname))) {
356 print_error('blocknotexist', 'debug', '', $blockname);
359 if ($dbversion >= $version) {
360 // something really wrong is going on in upgrade script
361 throw new downgrade_exception($component, $dbversion, $version);
363 set_config('version', $version, $component);
365 upgrade_log(UPGRADE_LOG_NORMAL, $component, 'Upgrade savepoint reached');
367 // reset upgrade timeout to default
368 upgrade_set_timeout();
370 core_upgrade_time::record_savepoint($version);
372 // this is a safe place to stop upgrades if user aborts page loading
373 if ($allowabort and connection_aborted()) {
374 die;
379 * Plugins upgrade savepoint, marks end of blocks upgrade blocks
380 * It stores plugin version, resets upgrade timeout
381 * and abort upgrade if user cancels page loading.
383 * @category upgrade
384 * @param bool $result false if upgrade step failed, true if completed
385 * @param string or float $version main version
386 * @param string $type name of plugin
387 * @param string $dir location of plugin
388 * @param bool $allowabort allow user to abort script execution here
389 * @return void
391 function upgrade_plugin_savepoint($result, $version, $type, $plugin, $allowabort=true) {
392 global $DB;
394 $component = $type.'_'.$plugin;
396 if (!$result) {
397 throw new upgrade_exception($component, $version);
400 $dbversion = $DB->get_field('config_plugins', 'value', array('plugin'=>$component, 'name'=>'version'));
402 if ($dbversion >= $version) {
403 // Something really wrong is going on in the upgrade script
404 throw new downgrade_exception($component, $dbversion, $version);
406 set_config('version', $version, $component);
407 upgrade_log(UPGRADE_LOG_NORMAL, $component, 'Upgrade savepoint reached');
409 // Reset upgrade timeout to default
410 upgrade_set_timeout();
412 core_upgrade_time::record_savepoint($version);
414 // This is a safe place to stop upgrades if user aborts page loading
415 if ($allowabort and connection_aborted()) {
416 die;
421 * Detect if there are leftovers in PHP source files.
423 * During main version upgrades administrators MUST move away
424 * old PHP source files and start from scratch (or better
425 * use git).
427 * @return bool true means borked upgrade, false means previous PHP files were properly removed
429 function upgrade_stale_php_files_present() {
430 global $CFG;
432 $someexamplesofremovedfiles = array(
433 // Removed in 3.5.
434 '/lib/dml/mssql_native_moodle_database.php',
435 '/lib/dml/mssql_native_moodle_recordset.php',
436 '/lib/dml/mssql_native_moodle_temptables.php',
437 // Removed in 3.4.
438 '/auth/README.txt',
439 '/calendar/set.php',
440 '/enrol/users.php',
441 '/enrol/yui/rolemanager/assets/skins/sam/rolemanager.css',
442 // Removed in 3.3.
443 '/badges/backpackconnect.php',
444 '/calendar/yui/src/info/assets/skins/sam/moodle-calendar-info.css',
445 '/competency/classes/external/exporter.php',
446 '/mod/forum/forum.js',
447 '/user/pixgroup.php',
448 // Removed in 3.2.
449 '/calendar/preferences.php',
450 '/lib/alfresco/',
451 '/lib/jquery/jquery-1.12.1.min.js',
452 '/lib/password_compat/tests/',
453 '/lib/phpunit/classes/unittestcase.php',
454 // Removed in 3.1.
455 '/lib/classes/log/sql_internal_reader.php',
456 '/lib/zend/',
457 '/mod/forum/pix/icon.gif',
458 '/tag/templates/tagname.mustache',
459 // Removed in 3.0.
460 '/mod/lti/grade.php',
461 '/tag/coursetagslib.php',
462 // Removed in 2.9.
463 '/lib/timezone.txt',
464 // Removed in 2.8.
465 '/course/delete_category_form.php',
466 // Removed in 2.7.
467 '/admin/tool/qeupgradehelper/version.php',
468 // Removed in 2.6.
469 '/admin/block.php',
470 '/admin/oacleanup.php',
471 // Removed in 2.5.
472 '/backup/lib.php',
473 '/backup/bb/README.txt',
474 '/lib/excel/test.php',
475 // Removed in 2.4.
476 '/admin/tool/unittest/simpletestlib.php',
477 // Removed in 2.3.
478 '/lib/minify/builder/',
479 // Removed in 2.2.
480 '/lib/yui/3.4.1pr1/',
481 // Removed in 2.2.
482 '/search/cron_php5.php',
483 '/course/report/log/indexlive.php',
484 '/admin/report/backups/index.php',
485 '/admin/generator.php',
486 // Removed in 2.1.
487 '/lib/yui/2.8.0r4/',
488 // Removed in 2.0.
489 '/blocks/admin/block_admin.php',
490 '/blocks/admin_tree/block_admin_tree.php',
493 foreach ($someexamplesofremovedfiles as $file) {
494 if (file_exists($CFG->dirroot.$file)) {
495 return true;
499 return false;
503 * Upgrade plugins
504 * @param string $type The type of plugins that should be updated (e.g. 'enrol', 'qtype')
505 * return void
507 function upgrade_plugins($type, $startcallback, $endcallback, $verbose) {
508 global $CFG, $DB;
510 /// special cases
511 if ($type === 'mod') {
512 return upgrade_plugins_modules($startcallback, $endcallback, $verbose);
513 } else if ($type === 'block') {
514 return upgrade_plugins_blocks($startcallback, $endcallback, $verbose);
517 $plugs = core_component::get_plugin_list($type);
519 foreach ($plugs as $plug=>$fullplug) {
520 // Reset time so that it works when installing a large number of plugins
521 core_php_time_limit::raise(600);
522 $component = clean_param($type.'_'.$plug, PARAM_COMPONENT); // standardised plugin name
524 // check plugin dir is valid name
525 if (empty($component)) {
526 throw new plugin_defective_exception($type.'_'.$plug, 'Invalid plugin directory name.');
529 if (!is_readable($fullplug.'/version.php')) {
530 continue;
533 $plugin = new stdClass();
534 $plugin->version = null;
535 $module = $plugin; // Prevent some notices when plugin placed in wrong directory.
536 require($fullplug.'/version.php'); // defines $plugin with version etc
537 unset($module);
539 if (empty($plugin->version)) {
540 throw new plugin_defective_exception($component, 'Missing $plugin->version number in version.php.');
543 if (empty($plugin->component)) {
544 throw new plugin_defective_exception($component, 'Missing $plugin->component declaration in version.php.');
547 if ($plugin->component !== $component) {
548 throw new plugin_misplaced_exception($plugin->component, null, $fullplug);
551 $plugin->name = $plug;
552 $plugin->fullname = $component;
554 if (!empty($plugin->requires)) {
555 if ($plugin->requires > $CFG->version) {
556 throw new upgrade_requires_exception($component, $plugin->version, $CFG->version, $plugin->requires);
557 } else if ($plugin->requires < 2010000000) {
558 throw new plugin_defective_exception($component, 'Plugin is not compatible with Moodle 2.x or later.');
562 // try to recover from interrupted install.php if needed
563 if (file_exists($fullplug.'/db/install.php')) {
564 if (get_config($plugin->fullname, 'installrunning')) {
565 require_once($fullplug.'/db/install.php');
566 $recover_install_function = 'xmldb_'.$plugin->fullname.'_install_recovery';
567 if (function_exists($recover_install_function)) {
568 $startcallback($component, true, $verbose);
569 $recover_install_function();
570 unset_config('installrunning', $plugin->fullname);
571 update_capabilities($component);
572 log_update_descriptions($component);
573 external_update_descriptions($component);
574 events_update_definition($component);
575 \core\task\manager::reset_scheduled_tasks_for_component($component);
576 message_update_providers($component);
577 \core\message\inbound\manager::update_handlers_for_component($component);
578 if ($type === 'message') {
579 message_update_processors($plug);
581 upgrade_plugin_mnet_functions($component);
582 core_tag_area::reset_definitions_for_component($component);
583 $endcallback($component, true, $verbose);
588 $installedversion = $DB->get_field('config_plugins', 'value', array('name'=>'version', 'plugin'=>$component)); // No caching!
589 if (empty($installedversion)) { // new installation
590 $startcallback($component, true, $verbose);
592 /// Install tables if defined
593 if (file_exists($fullplug.'/db/install.xml')) {
594 $DB->get_manager()->install_from_xmldb_file($fullplug.'/db/install.xml');
597 /// store version
598 upgrade_plugin_savepoint(true, $plugin->version, $type, $plug, false);
600 /// execute post install file
601 if (file_exists($fullplug.'/db/install.php')) {
602 require_once($fullplug.'/db/install.php');
603 set_config('installrunning', 1, $plugin->fullname);
604 $post_install_function = 'xmldb_'.$plugin->fullname.'_install';
605 $post_install_function();
606 unset_config('installrunning', $plugin->fullname);
609 /// Install various components
610 update_capabilities($component);
611 log_update_descriptions($component);
612 external_update_descriptions($component);
613 events_update_definition($component);
614 \core\task\manager::reset_scheduled_tasks_for_component($component);
615 message_update_providers($component);
616 \core\message\inbound\manager::update_handlers_for_component($component);
617 if ($type === 'message') {
618 message_update_processors($plug);
620 upgrade_plugin_mnet_functions($component);
621 core_tag_area::reset_definitions_for_component($component);
622 $endcallback($component, true, $verbose);
624 } else if ($installedversion < $plugin->version) { // upgrade
625 /// Run the upgrade function for the plugin.
626 $startcallback($component, false, $verbose);
628 if (is_readable($fullplug.'/db/upgrade.php')) {
629 require_once($fullplug.'/db/upgrade.php'); // defines upgrading function
631 $newupgrade_function = 'xmldb_'.$plugin->fullname.'_upgrade';
632 $result = $newupgrade_function($installedversion);
633 } else {
634 $result = true;
637 $installedversion = $DB->get_field('config_plugins', 'value', array('name'=>'version', 'plugin'=>$component)); // No caching!
638 if ($installedversion < $plugin->version) {
639 // store version if not already there
640 upgrade_plugin_savepoint($result, $plugin->version, $type, $plug, false);
643 /// Upgrade various components
644 update_capabilities($component);
645 log_update_descriptions($component);
646 external_update_descriptions($component);
647 events_update_definition($component);
648 \core\task\manager::reset_scheduled_tasks_for_component($component);
649 message_update_providers($component);
650 \core\message\inbound\manager::update_handlers_for_component($component);
651 if ($type === 'message') {
652 // Ugly hack!
653 message_update_processors($plug);
655 upgrade_plugin_mnet_functions($component);
656 core_tag_area::reset_definitions_for_component($component);
657 $endcallback($component, false, $verbose);
659 } else if ($installedversion > $plugin->version) {
660 throw new downgrade_exception($component, $installedversion, $plugin->version);
666 * Find and check all modules and load them up or upgrade them if necessary
668 * @global object
669 * @global object
671 function upgrade_plugins_modules($startcallback, $endcallback, $verbose) {
672 global $CFG, $DB;
674 $mods = core_component::get_plugin_list('mod');
676 foreach ($mods as $mod=>$fullmod) {
678 if ($mod === 'NEWMODULE') { // Someone has unzipped the template, ignore it
679 continue;
682 $component = clean_param('mod_'.$mod, PARAM_COMPONENT);
684 // check module dir is valid name
685 if (empty($component)) {
686 throw new plugin_defective_exception('mod_'.$mod, 'Invalid plugin directory name.');
689 if (!is_readable($fullmod.'/version.php')) {
690 throw new plugin_defective_exception($component, 'Missing version.php');
693 $module = new stdClass();
694 $plugin = new stdClass();
695 $plugin->version = null;
696 require($fullmod .'/version.php'); // Defines $plugin with version etc.
698 // Check if the legacy $module syntax is still used.
699 if (!is_object($module) or (count((array)$module) > 0)) {
700 throw new plugin_defective_exception($component, 'Unsupported $module syntax detected in version.php');
703 // Prepare the record for the {modules} table.
704 $module = clone($plugin);
705 unset($module->version);
706 unset($module->component);
707 unset($module->dependencies);
708 unset($module->release);
710 if (empty($plugin->version)) {
711 throw new plugin_defective_exception($component, 'Missing $plugin->version number in version.php.');
714 if (empty($plugin->component)) {
715 throw new plugin_defective_exception($component, 'Missing $plugin->component declaration in version.php.');
718 if ($plugin->component !== $component) {
719 throw new plugin_misplaced_exception($plugin->component, null, $fullmod);
722 if (!empty($plugin->requires)) {
723 if ($plugin->requires > $CFG->version) {
724 throw new upgrade_requires_exception($component, $plugin->version, $CFG->version, $plugin->requires);
725 } else if ($plugin->requires < 2010000000) {
726 throw new plugin_defective_exception($component, 'Plugin is not compatible with Moodle 2.x or later.');
730 if (empty($module->cron)) {
731 $module->cron = 0;
734 // all modules must have en lang pack
735 if (!is_readable("$fullmod/lang/en/$mod.php")) {
736 throw new plugin_defective_exception($component, 'Missing mandatory en language pack.');
739 $module->name = $mod; // The name MUST match the directory
741 $installedversion = $DB->get_field('config_plugins', 'value', array('name'=>'version', 'plugin'=>$component)); // No caching!
743 if (file_exists($fullmod.'/db/install.php')) {
744 if (get_config($module->name, 'installrunning')) {
745 require_once($fullmod.'/db/install.php');
746 $recover_install_function = 'xmldb_'.$module->name.'_install_recovery';
747 if (function_exists($recover_install_function)) {
748 $startcallback($component, true, $verbose);
749 $recover_install_function();
750 unset_config('installrunning', $module->name);
751 // Install various components too
752 update_capabilities($component);
753 log_update_descriptions($component);
754 external_update_descriptions($component);
755 events_update_definition($component);
756 \core\task\manager::reset_scheduled_tasks_for_component($component);
757 message_update_providers($component);
758 \core\message\inbound\manager::update_handlers_for_component($component);
759 upgrade_plugin_mnet_functions($component);
760 core_tag_area::reset_definitions_for_component($component);
761 $endcallback($component, true, $verbose);
766 if (empty($installedversion)) {
767 $startcallback($component, true, $verbose);
769 /// Execute install.xml (XMLDB) - must be present in all modules
770 $DB->get_manager()->install_from_xmldb_file($fullmod.'/db/install.xml');
772 /// Add record into modules table - may be needed in install.php already
773 $module->id = $DB->insert_record('modules', $module);
774 upgrade_mod_savepoint(true, $plugin->version, $module->name, false);
776 /// Post installation hook - optional
777 if (file_exists("$fullmod/db/install.php")) {
778 require_once("$fullmod/db/install.php");
779 // Set installation running flag, we need to recover after exception or error
780 set_config('installrunning', 1, $module->name);
781 $post_install_function = 'xmldb_'.$module->name.'_install';
782 $post_install_function();
783 unset_config('installrunning', $module->name);
786 /// Install various components
787 update_capabilities($component);
788 log_update_descriptions($component);
789 external_update_descriptions($component);
790 events_update_definition($component);
791 \core\task\manager::reset_scheduled_tasks_for_component($component);
792 message_update_providers($component);
793 \core\message\inbound\manager::update_handlers_for_component($component);
794 upgrade_plugin_mnet_functions($component);
795 core_tag_area::reset_definitions_for_component($component);
797 $endcallback($component, true, $verbose);
799 } else if ($installedversion < $plugin->version) {
800 /// If versions say that we need to upgrade but no upgrade files are available, notify and continue
801 $startcallback($component, false, $verbose);
803 if (is_readable($fullmod.'/db/upgrade.php')) {
804 require_once($fullmod.'/db/upgrade.php'); // defines new upgrading function
805 $newupgrade_function = 'xmldb_'.$module->name.'_upgrade';
806 $result = $newupgrade_function($installedversion, $module);
807 } else {
808 $result = true;
811 $installedversion = $DB->get_field('config_plugins', 'value', array('name'=>'version', 'plugin'=>$component)); // No caching!
812 $currmodule = $DB->get_record('modules', array('name'=>$module->name));
813 if ($installedversion < $plugin->version) {
814 // store version if not already there
815 upgrade_mod_savepoint($result, $plugin->version, $mod, false);
818 // update cron flag if needed
819 if ($currmodule->cron != $module->cron) {
820 $DB->set_field('modules', 'cron', $module->cron, array('name' => $module->name));
823 // Upgrade various components
824 update_capabilities($component);
825 log_update_descriptions($component);
826 external_update_descriptions($component);
827 events_update_definition($component);
828 \core\task\manager::reset_scheduled_tasks_for_component($component);
829 message_update_providers($component);
830 \core\message\inbound\manager::update_handlers_for_component($component);
831 upgrade_plugin_mnet_functions($component);
832 core_tag_area::reset_definitions_for_component($component);
834 $endcallback($component, false, $verbose);
836 } else if ($installedversion > $plugin->version) {
837 throw new downgrade_exception($component, $installedversion, $plugin->version);
844 * This function finds all available blocks and install them
845 * into blocks table or do all the upgrade process if newer.
847 * @global object
848 * @global object
850 function upgrade_plugins_blocks($startcallback, $endcallback, $verbose) {
851 global $CFG, $DB;
853 require_once($CFG->dirroot.'/blocks/moodleblock.class.php');
855 $blocktitles = array(); // we do not want duplicate titles
857 //Is this a first install
858 $first_install = null;
860 $blocks = core_component::get_plugin_list('block');
862 foreach ($blocks as $blockname=>$fullblock) {
864 if (is_null($first_install)) {
865 $first_install = ($DB->count_records('block_instances') == 0);
868 if ($blockname === 'NEWBLOCK') { // Someone has unzipped the template, ignore it
869 continue;
872 $component = clean_param('block_'.$blockname, PARAM_COMPONENT);
874 // check block dir is valid name
875 if (empty($component)) {
876 throw new plugin_defective_exception('block_'.$blockname, 'Invalid plugin directory name.');
879 if (!is_readable($fullblock.'/version.php')) {
880 throw new plugin_defective_exception('block/'.$blockname, 'Missing version.php file.');
882 $plugin = new stdClass();
883 $plugin->version = null;
884 $plugin->cron = 0;
885 $module = $plugin; // Prevent some notices when module placed in wrong directory.
886 include($fullblock.'/version.php');
887 unset($module);
888 $block = clone($plugin);
889 unset($block->version);
890 unset($block->component);
891 unset($block->dependencies);
892 unset($block->release);
894 if (empty($plugin->version)) {
895 throw new plugin_defective_exception($component, 'Missing block version number in version.php.');
898 if (empty($plugin->component)) {
899 throw new plugin_defective_exception($component, 'Missing $plugin->component declaration in version.php.');
902 if ($plugin->component !== $component) {
903 throw new plugin_misplaced_exception($plugin->component, null, $fullblock);
906 if (!empty($plugin->requires)) {
907 if ($plugin->requires > $CFG->version) {
908 throw new upgrade_requires_exception($component, $plugin->version, $CFG->version, $plugin->requires);
909 } else if ($plugin->requires < 2010000000) {
910 throw new plugin_defective_exception($component, 'Plugin is not compatible with Moodle 2.x or later.');
914 if (!is_readable($fullblock.'/block_'.$blockname.'.php')) {
915 throw new plugin_defective_exception('block/'.$blockname, 'Missing main block class file.');
917 include_once($fullblock.'/block_'.$blockname.'.php');
919 $classname = 'block_'.$blockname;
921 if (!class_exists($classname)) {
922 throw new plugin_defective_exception($component, 'Can not load main class.');
925 $blockobj = new $classname; // This is what we'll be testing
926 $blocktitle = $blockobj->get_title();
928 // OK, it's as we all hoped. For further tests, the object will do them itself.
929 if (!$blockobj->_self_test()) {
930 throw new plugin_defective_exception($component, 'Self test failed.');
933 $block->name = $blockname; // The name MUST match the directory
935 $installedversion = $DB->get_field('config_plugins', 'value', array('name'=>'version', 'plugin'=>$component)); // No caching!
937 if (file_exists($fullblock.'/db/install.php')) {
938 if (get_config('block_'.$blockname, 'installrunning')) {
939 require_once($fullblock.'/db/install.php');
940 $recover_install_function = 'xmldb_block_'.$blockname.'_install_recovery';
941 if (function_exists($recover_install_function)) {
942 $startcallback($component, true, $verbose);
943 $recover_install_function();
944 unset_config('installrunning', 'block_'.$blockname);
945 // Install various components
946 update_capabilities($component);
947 log_update_descriptions($component);
948 external_update_descriptions($component);
949 events_update_definition($component);
950 \core\task\manager::reset_scheduled_tasks_for_component($component);
951 message_update_providers($component);
952 \core\message\inbound\manager::update_handlers_for_component($component);
953 upgrade_plugin_mnet_functions($component);
954 core_tag_area::reset_definitions_for_component($component);
955 $endcallback($component, true, $verbose);
960 if (empty($installedversion)) { // block not installed yet, so install it
961 $conflictblock = array_search($blocktitle, $blocktitles);
962 if ($conflictblock !== false) {
963 // Duplicate block titles are not allowed, they confuse people
964 // AND PHP's associative arrays ;)
965 throw new plugin_defective_exception($component, get_string('blocknameconflict', 'error', (object)array('name'=>$block->name, 'conflict'=>$conflictblock)));
967 $startcallback($component, true, $verbose);
969 if (file_exists($fullblock.'/db/install.xml')) {
970 $DB->get_manager()->install_from_xmldb_file($fullblock.'/db/install.xml');
972 $block->id = $DB->insert_record('block', $block);
973 upgrade_block_savepoint(true, $plugin->version, $block->name, false);
975 if (file_exists($fullblock.'/db/install.php')) {
976 require_once($fullblock.'/db/install.php');
977 // Set installation running flag, we need to recover after exception or error
978 set_config('installrunning', 1, 'block_'.$blockname);
979 $post_install_function = 'xmldb_block_'.$blockname.'_install';
980 $post_install_function();
981 unset_config('installrunning', 'block_'.$blockname);
984 $blocktitles[$block->name] = $blocktitle;
986 // Install various components
987 update_capabilities($component);
988 log_update_descriptions($component);
989 external_update_descriptions($component);
990 events_update_definition($component);
991 \core\task\manager::reset_scheduled_tasks_for_component($component);
992 message_update_providers($component);
993 \core\message\inbound\manager::update_handlers_for_component($component);
994 core_tag_area::reset_definitions_for_component($component);
995 upgrade_plugin_mnet_functions($component);
997 $endcallback($component, true, $verbose);
999 } else if ($installedversion < $plugin->version) {
1000 $startcallback($component, false, $verbose);
1002 if (is_readable($fullblock.'/db/upgrade.php')) {
1003 require_once($fullblock.'/db/upgrade.php'); // defines new upgrading function
1004 $newupgrade_function = 'xmldb_block_'.$blockname.'_upgrade';
1005 $result = $newupgrade_function($installedversion, $block);
1006 } else {
1007 $result = true;
1010 $installedversion = $DB->get_field('config_plugins', 'value', array('name'=>'version', 'plugin'=>$component)); // No caching!
1011 $currblock = $DB->get_record('block', array('name'=>$block->name));
1012 if ($installedversion < $plugin->version) {
1013 // store version if not already there
1014 upgrade_block_savepoint($result, $plugin->version, $block->name, false);
1017 if ($currblock->cron != $block->cron) {
1018 // update cron flag if needed
1019 $DB->set_field('block', 'cron', $block->cron, array('id' => $currblock->id));
1022 // Upgrade various components
1023 update_capabilities($component);
1024 log_update_descriptions($component);
1025 external_update_descriptions($component);
1026 events_update_definition($component);
1027 \core\task\manager::reset_scheduled_tasks_for_component($component);
1028 message_update_providers($component);
1029 \core\message\inbound\manager::update_handlers_for_component($component);
1030 upgrade_plugin_mnet_functions($component);
1031 core_tag_area::reset_definitions_for_component($component);
1033 $endcallback($component, false, $verbose);
1035 } else if ($installedversion > $plugin->version) {
1036 throw new downgrade_exception($component, $installedversion, $plugin->version);
1041 // Finally, if we are in the first_install of BLOCKS setup frontpage and admin page blocks
1042 if ($first_install) {
1043 //Iterate over each course - there should be only site course here now
1044 if ($courses = $DB->get_records('course')) {
1045 foreach ($courses as $course) {
1046 blocks_add_default_course_blocks($course);
1050 blocks_add_default_system_blocks();
1056 * Log_display description function used during install and upgrade.
1058 * @param string $component name of component (moodle, mod_assignment, etc.)
1059 * @return void
1061 function log_update_descriptions($component) {
1062 global $DB;
1064 $defpath = core_component::get_component_directory($component).'/db/log.php';
1066 if (!file_exists($defpath)) {
1067 $DB->delete_records('log_display', array('component'=>$component));
1068 return;
1071 // load new info
1072 $logs = array();
1073 include($defpath);
1074 $newlogs = array();
1075 foreach ($logs as $log) {
1076 $newlogs[$log['module'].'-'.$log['action']] = $log; // kind of unique name
1078 unset($logs);
1079 $logs = $newlogs;
1081 $fields = array('module', 'action', 'mtable', 'field');
1082 // update all log fist
1083 $dblogs = $DB->get_records('log_display', array('component'=>$component));
1084 foreach ($dblogs as $dblog) {
1085 $name = $dblog->module.'-'.$dblog->action;
1087 if (empty($logs[$name])) {
1088 $DB->delete_records('log_display', array('id'=>$dblog->id));
1089 continue;
1092 $log = $logs[$name];
1093 unset($logs[$name]);
1095 $update = false;
1096 foreach ($fields as $field) {
1097 if ($dblog->$field != $log[$field]) {
1098 $dblog->$field = $log[$field];
1099 $update = true;
1102 if ($update) {
1103 $DB->update_record('log_display', $dblog);
1106 foreach ($logs as $log) {
1107 $dblog = (object)$log;
1108 $dblog->component = $component;
1109 $DB->insert_record('log_display', $dblog);
1114 * Web service discovery function used during install and upgrade.
1115 * @param string $component name of component (moodle, mod_assignment, etc.)
1116 * @return void
1118 function external_update_descriptions($component) {
1119 global $DB, $CFG;
1121 $defpath = core_component::get_component_directory($component).'/db/services.php';
1123 if (!file_exists($defpath)) {
1124 require_once($CFG->dirroot.'/lib/externallib.php');
1125 external_delete_descriptions($component);
1126 return;
1129 // load new info
1130 $functions = array();
1131 $services = array();
1132 include($defpath);
1134 // update all function fist
1135 $dbfunctions = $DB->get_records('external_functions', array('component'=>$component));
1136 foreach ($dbfunctions as $dbfunction) {
1137 if (empty($functions[$dbfunction->name])) {
1138 $DB->delete_records('external_functions', array('id'=>$dbfunction->id));
1139 // do not delete functions from external_services_functions, beacuse
1140 // we want to notify admins when functions used in custom services disappear
1142 //TODO: this looks wrong, we have to delete it eventually (skodak)
1143 continue;
1146 $function = $functions[$dbfunction->name];
1147 unset($functions[$dbfunction->name]);
1148 $function['classpath'] = empty($function['classpath']) ? null : $function['classpath'];
1150 $update = false;
1151 if ($dbfunction->classname != $function['classname']) {
1152 $dbfunction->classname = $function['classname'];
1153 $update = true;
1155 if ($dbfunction->methodname != $function['methodname']) {
1156 $dbfunction->methodname = $function['methodname'];
1157 $update = true;
1159 if ($dbfunction->classpath != $function['classpath']) {
1160 $dbfunction->classpath = $function['classpath'];
1161 $update = true;
1163 $functioncapabilities = array_key_exists('capabilities', $function)?$function['capabilities']:'';
1164 if ($dbfunction->capabilities != $functioncapabilities) {
1165 $dbfunction->capabilities = $functioncapabilities;
1166 $update = true;
1169 if (isset($function['services']) and is_array($function['services'])) {
1170 sort($function['services']);
1171 $functionservices = implode(',', $function['services']);
1172 } else {
1173 // Force null values in the DB.
1174 $functionservices = null;
1177 if ($dbfunction->services != $functionservices) {
1178 // Now, we need to check if services were removed, in that case we need to remove the function from them.
1179 $servicesremoved = array_diff(explode(",", $dbfunction->services), explode(",", $functionservices));
1180 foreach ($servicesremoved as $removedshortname) {
1181 if ($externalserviceid = $DB->get_field('external_services', 'id', array("shortname" => $removedshortname))) {
1182 $DB->delete_records('external_services_functions', array('functionname' => $dbfunction->name,
1183 'externalserviceid' => $externalserviceid));
1187 $dbfunction->services = $functionservices;
1188 $update = true;
1190 if ($update) {
1191 $DB->update_record('external_functions', $dbfunction);
1194 foreach ($functions as $fname => $function) {
1195 $dbfunction = new stdClass();
1196 $dbfunction->name = $fname;
1197 $dbfunction->classname = $function['classname'];
1198 $dbfunction->methodname = $function['methodname'];
1199 $dbfunction->classpath = empty($function['classpath']) ? null : $function['classpath'];
1200 $dbfunction->component = $component;
1201 $dbfunction->capabilities = array_key_exists('capabilities', $function)?$function['capabilities']:'';
1203 if (isset($function['services']) and is_array($function['services'])) {
1204 sort($function['services']);
1205 $dbfunction->services = implode(',', $function['services']);
1206 } else {
1207 // Force null values in the DB.
1208 $dbfunction->services = null;
1211 $dbfunction->id = $DB->insert_record('external_functions', $dbfunction);
1213 unset($functions);
1215 // now deal with services
1216 $dbservices = $DB->get_records('external_services', array('component'=>$component));
1217 foreach ($dbservices as $dbservice) {
1218 if (empty($services[$dbservice->name])) {
1219 $DB->delete_records('external_tokens', array('externalserviceid'=>$dbservice->id));
1220 $DB->delete_records('external_services_functions', array('externalserviceid'=>$dbservice->id));
1221 $DB->delete_records('external_services_users', array('externalserviceid'=>$dbservice->id));
1222 $DB->delete_records('external_services', array('id'=>$dbservice->id));
1223 continue;
1225 $service = $services[$dbservice->name];
1226 unset($services[$dbservice->name]);
1227 $service['enabled'] = empty($service['enabled']) ? 0 : $service['enabled'];
1228 $service['requiredcapability'] = empty($service['requiredcapability']) ? null : $service['requiredcapability'];
1229 $service['restrictedusers'] = !isset($service['restrictedusers']) ? 1 : $service['restrictedusers'];
1230 $service['downloadfiles'] = !isset($service['downloadfiles']) ? 0 : $service['downloadfiles'];
1231 $service['uploadfiles'] = !isset($service['uploadfiles']) ? 0 : $service['uploadfiles'];
1232 $service['shortname'] = !isset($service['shortname']) ? null : $service['shortname'];
1234 $update = false;
1235 if ($dbservice->requiredcapability != $service['requiredcapability']) {
1236 $dbservice->requiredcapability = $service['requiredcapability'];
1237 $update = true;
1239 if ($dbservice->restrictedusers != $service['restrictedusers']) {
1240 $dbservice->restrictedusers = $service['restrictedusers'];
1241 $update = true;
1243 if ($dbservice->downloadfiles != $service['downloadfiles']) {
1244 $dbservice->downloadfiles = $service['downloadfiles'];
1245 $update = true;
1247 if ($dbservice->uploadfiles != $service['uploadfiles']) {
1248 $dbservice->uploadfiles = $service['uploadfiles'];
1249 $update = true;
1251 //if shortname is not a PARAM_ALPHANUMEXT, fail (tested here for service update and creation)
1252 if (isset($service['shortname']) and
1253 (clean_param($service['shortname'], PARAM_ALPHANUMEXT) != $service['shortname'])) {
1254 throw new moodle_exception('installserviceshortnameerror', 'webservice', '', $service['shortname']);
1256 if ($dbservice->shortname != $service['shortname']) {
1257 //check that shortname is unique
1258 if (isset($service['shortname'])) { //we currently accepts multiple shortname == null
1259 $existingservice = $DB->get_record('external_services',
1260 array('shortname' => $service['shortname']));
1261 if (!empty($existingservice)) {
1262 throw new moodle_exception('installexistingserviceshortnameerror', 'webservice', '', $service['shortname']);
1265 $dbservice->shortname = $service['shortname'];
1266 $update = true;
1268 if ($update) {
1269 $DB->update_record('external_services', $dbservice);
1272 $functions = $DB->get_records('external_services_functions', array('externalserviceid'=>$dbservice->id));
1273 foreach ($functions as $function) {
1274 $key = array_search($function->functionname, $service['functions']);
1275 if ($key === false) {
1276 $DB->delete_records('external_services_functions', array('id'=>$function->id));
1277 } else {
1278 unset($service['functions'][$key]);
1281 foreach ($service['functions'] as $fname) {
1282 $newf = new stdClass();
1283 $newf->externalserviceid = $dbservice->id;
1284 $newf->functionname = $fname;
1285 $DB->insert_record('external_services_functions', $newf);
1287 unset($functions);
1289 foreach ($services as $name => $service) {
1290 //check that shortname is unique
1291 if (isset($service['shortname'])) { //we currently accepts multiple shortname == null
1292 $existingservice = $DB->get_record('external_services',
1293 array('shortname' => $service['shortname']));
1294 if (!empty($existingservice)) {
1295 throw new moodle_exception('installserviceshortnameerror', 'webservice');
1299 $dbservice = new stdClass();
1300 $dbservice->name = $name;
1301 $dbservice->enabled = empty($service['enabled']) ? 0 : $service['enabled'];
1302 $dbservice->requiredcapability = empty($service['requiredcapability']) ? null : $service['requiredcapability'];
1303 $dbservice->restrictedusers = !isset($service['restrictedusers']) ? 1 : $service['restrictedusers'];
1304 $dbservice->downloadfiles = !isset($service['downloadfiles']) ? 0 : $service['downloadfiles'];
1305 $dbservice->uploadfiles = !isset($service['uploadfiles']) ? 0 : $service['uploadfiles'];
1306 $dbservice->shortname = !isset($service['shortname']) ? null : $service['shortname'];
1307 $dbservice->component = $component;
1308 $dbservice->timecreated = time();
1309 $dbservice->id = $DB->insert_record('external_services', $dbservice);
1310 foreach ($service['functions'] as $fname) {
1311 $newf = new stdClass();
1312 $newf->externalserviceid = $dbservice->id;
1313 $newf->functionname = $fname;
1314 $DB->insert_record('external_services_functions', $newf);
1320 * Allow plugins and subsystems to add external functions to other plugins or built-in services.
1321 * This function is executed just after all the plugins have been updated.
1323 function external_update_services() {
1324 global $DB;
1326 // Look for external functions that want to be added in existing services.
1327 $functions = $DB->get_records_select('external_functions', 'services IS NOT NULL');
1329 $servicescache = array();
1330 foreach ($functions as $function) {
1331 // Prevent edge cases.
1332 if (empty($function->services)) {
1333 continue;
1335 $services = explode(',', $function->services);
1337 foreach ($services as $serviceshortname) {
1338 // Get the service id by shortname.
1339 if (!empty($servicescache[$serviceshortname])) {
1340 $serviceid = $servicescache[$serviceshortname];
1341 } else if ($service = $DB->get_record('external_services', array('shortname' => $serviceshortname))) {
1342 // If the component is empty, it means that is not a built-in service.
1343 // We don't allow functions to inject themselves in services created by an user in Moodle.
1344 if (empty($service->component)) {
1345 continue;
1347 $serviceid = $service->id;
1348 $servicescache[$serviceshortname] = $serviceid;
1349 } else {
1350 // Service not found.
1351 continue;
1353 // Finally add the function to the service.
1354 $newf = new stdClass();
1355 $newf->externalserviceid = $serviceid;
1356 $newf->functionname = $function->name;
1358 if (!$DB->record_exists('external_services_functions', (array)$newf)) {
1359 $DB->insert_record('external_services_functions', $newf);
1366 * upgrade logging functions
1368 function upgrade_handle_exception($ex, $plugin = null) {
1369 global $CFG;
1371 // rollback everything, we need to log all upgrade problems
1372 abort_all_db_transactions();
1374 $info = get_exception_info($ex);
1376 // First log upgrade error
1377 upgrade_log(UPGRADE_LOG_ERROR, $plugin, 'Exception: ' . get_class($ex), $info->message, $info->backtrace);
1379 // Always turn on debugging - admins need to know what is going on
1380 set_debugging(DEBUG_DEVELOPER, true);
1382 default_exception_handler($ex, true, $plugin);
1386 * Adds log entry into upgrade_log table
1388 * @param int $type UPGRADE_LOG_NORMAL, UPGRADE_LOG_NOTICE or UPGRADE_LOG_ERROR
1389 * @param string $plugin frankenstyle component name
1390 * @param string $info short description text of log entry
1391 * @param string $details long problem description
1392 * @param string $backtrace string used for errors only
1393 * @return void
1395 function upgrade_log($type, $plugin, $info, $details=null, $backtrace=null) {
1396 global $DB, $USER, $CFG;
1398 if (empty($plugin)) {
1399 $plugin = 'core';
1402 list($plugintype, $pluginname) = core_component::normalize_component($plugin);
1403 $component = is_null($pluginname) ? $plugintype : $plugintype . '_' . $pluginname;
1405 $backtrace = format_backtrace($backtrace, true);
1407 $currentversion = null;
1408 $targetversion = null;
1410 //first try to find out current version number
1411 if ($plugintype === 'core') {
1412 //main
1413 $currentversion = $CFG->version;
1415 $version = null;
1416 include("$CFG->dirroot/version.php");
1417 $targetversion = $version;
1419 } else {
1420 $pluginversion = get_config($component, 'version');
1421 if (!empty($pluginversion)) {
1422 $currentversion = $pluginversion;
1424 $cd = core_component::get_component_directory($component);
1425 if (file_exists("$cd/version.php")) {
1426 $plugin = new stdClass();
1427 $plugin->version = null;
1428 $module = $plugin;
1429 include("$cd/version.php");
1430 $targetversion = $plugin->version;
1434 $log = new stdClass();
1435 $log->type = $type;
1436 $log->plugin = $component;
1437 $log->version = $currentversion;
1438 $log->targetversion = $targetversion;
1439 $log->info = $info;
1440 $log->details = $details;
1441 $log->backtrace = $backtrace;
1442 $log->userid = $USER->id;
1443 $log->timemodified = time();
1444 try {
1445 $DB->insert_record('upgrade_log', $log);
1446 } catch (Exception $ignored) {
1447 // possible during install or 2.0 upgrade
1452 * Marks start of upgrade, blocks any other access to site.
1453 * The upgrade is finished at the end of script or after timeout.
1455 * @global object
1456 * @global object
1457 * @global object
1459 function upgrade_started($preinstall=false) {
1460 global $CFG, $DB, $PAGE, $OUTPUT;
1462 static $started = false;
1464 if ($preinstall) {
1465 ignore_user_abort(true);
1466 upgrade_setup_debug(true);
1468 } else if ($started) {
1469 upgrade_set_timeout(120);
1471 } else {
1472 if (!CLI_SCRIPT and !$PAGE->headerprinted) {
1473 $strupgrade = get_string('upgradingversion', 'admin');
1474 $PAGE->set_pagelayout('maintenance');
1475 upgrade_init_javascript();
1476 $PAGE->set_title($strupgrade.' - Moodle '.$CFG->target_release);
1477 $PAGE->set_heading($strupgrade);
1478 $PAGE->navbar->add($strupgrade);
1479 $PAGE->set_cacheable(false);
1480 echo $OUTPUT->header();
1483 ignore_user_abort(true);
1484 core_shutdown_manager::register_function('upgrade_finished_handler');
1485 upgrade_setup_debug(true);
1486 set_config('upgraderunning', time()+300);
1487 $started = true;
1492 * Internal function - executed if upgrade interrupted.
1494 function upgrade_finished_handler() {
1495 upgrade_finished();
1499 * Indicates upgrade is finished.
1501 * This function may be called repeatedly.
1503 * @global object
1504 * @global object
1506 function upgrade_finished($continueurl=null) {
1507 global $CFG, $DB, $OUTPUT;
1509 if (!empty($CFG->upgraderunning)) {
1510 unset_config('upgraderunning');
1511 // We have to forcefully purge the caches using the writer here.
1512 // This has to be done after we unset the config var. If someone hits the site while this is set they will
1513 // cause the config values to propogate to the caches.
1514 // Caches are purged after the last step in an upgrade but there is several code routines that exceute between
1515 // then and now that leaving a window for things to fall out of sync.
1516 cache_helper::purge_all(true);
1517 upgrade_setup_debug(false);
1518 ignore_user_abort(false);
1519 if ($continueurl) {
1520 echo $OUTPUT->continue_button($continueurl);
1521 echo $OUTPUT->footer();
1522 die;
1528 * @global object
1529 * @global object
1531 function upgrade_setup_debug($starting) {
1532 global $CFG, $DB;
1534 static $originaldebug = null;
1536 if ($starting) {
1537 if ($originaldebug === null) {
1538 $originaldebug = $DB->get_debug();
1540 if (!empty($CFG->upgradeshowsql)) {
1541 $DB->set_debug(true);
1543 } else {
1544 $DB->set_debug($originaldebug);
1548 function print_upgrade_separator() {
1549 if (!CLI_SCRIPT) {
1550 echo '<hr />';
1555 * Default start upgrade callback
1556 * @param string $plugin
1557 * @param bool $installation true if installation, false means upgrade
1559 function print_upgrade_part_start($plugin, $installation, $verbose) {
1560 global $OUTPUT;
1561 if (empty($plugin) or $plugin == 'moodle') {
1562 upgrade_started($installation); // does not store upgrade running flag yet
1563 if ($verbose) {
1564 echo $OUTPUT->heading(get_string('coresystem'));
1566 } else {
1567 upgrade_started();
1568 if ($verbose) {
1569 echo $OUTPUT->heading($plugin);
1572 if ($installation) {
1573 if (empty($plugin) or $plugin == 'moodle') {
1574 // no need to log - log table not yet there ;-)
1575 } else {
1576 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Starting plugin installation');
1578 } else {
1579 core_upgrade_time::record_start();
1580 if (empty($plugin) or $plugin == 'moodle') {
1581 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Starting core upgrade');
1582 } else {
1583 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Starting plugin upgrade');
1589 * Default end upgrade callback
1590 * @param string $plugin
1591 * @param bool $installation true if installation, false means upgrade
1593 function print_upgrade_part_end($plugin, $installation, $verbose) {
1594 global $OUTPUT;
1595 upgrade_started();
1596 if ($installation) {
1597 if (empty($plugin) or $plugin == 'moodle') {
1598 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Core installed');
1599 } else {
1600 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Plugin installed');
1602 } else {
1603 if (empty($plugin) or $plugin == 'moodle') {
1604 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Core upgraded');
1605 } else {
1606 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Plugin upgraded');
1609 if ($verbose) {
1610 if ($installation) {
1611 $message = get_string('success');
1612 } else {
1613 $duration = core_upgrade_time::get_elapsed();
1614 $message = get_string('successduration', '', format_float($duration, 2));
1616 $notification = new \core\output\notification($message, \core\output\notification::NOTIFY_SUCCESS);
1617 $notification->set_show_closebutton(false);
1618 echo $OUTPUT->render($notification);
1619 print_upgrade_separator();
1624 * Sets up JS code required for all upgrade scripts.
1625 * @global object
1627 function upgrade_init_javascript() {
1628 global $PAGE;
1629 // scroll to the end of each upgrade page so that ppl see either error or continue button,
1630 // no need to scroll continuously any more, it is enough to jump to end once the footer is printed ;-)
1631 $js = "window.scrollTo(0, 5000000);";
1632 $PAGE->requires->js_init_code($js);
1636 * Try to upgrade the given language pack (or current language)
1638 * @param string $lang the code of the language to update, defaults to the current language
1640 function upgrade_language_pack($lang = null) {
1641 global $CFG;
1643 if (!empty($CFG->skiplangupgrade)) {
1644 return;
1647 if (!file_exists("$CFG->dirroot/$CFG->admin/tool/langimport/lib.php")) {
1648 // weird, somebody uninstalled the import utility
1649 return;
1652 if (!$lang) {
1653 $lang = current_language();
1656 if (!get_string_manager()->translation_exists($lang)) {
1657 return;
1660 get_string_manager()->reset_caches();
1662 if ($lang === 'en') {
1663 return; // Nothing to do
1666 upgrade_started(false);
1668 require_once("$CFG->dirroot/$CFG->admin/tool/langimport/lib.php");
1669 tool_langimport_preupgrade_update($lang);
1671 get_string_manager()->reset_caches();
1673 print_upgrade_separator();
1677 * Build the current theme so that the user doesn't have to wait for it
1678 * to build on the first page load after the install / upgrade.
1680 function upgrade_themes() {
1681 global $CFG;
1683 require_once("{$CFG->libdir}/outputlib.php");
1685 // Build the current theme so that the user can immediately
1686 // browse the site without having to wait for the theme to build.
1687 $themeconfig = theme_config::load($CFG->theme);
1688 $direction = right_to_left() ? 'rtl' : 'ltr';
1689 theme_build_css_for_themes([$themeconfig], [$direction]);
1691 // Only queue the task if there isn't already one queued.
1692 if (empty(\core\task\manager::get_adhoc_tasks('\\core\\task\\build_installed_themes_task'))) {
1693 // Queue a task to build all of the site themes at some point
1694 // later. These can happen offline because it doesn't block the
1695 // user unless they quickly change theme.
1696 $adhoctask = new \core\task\build_installed_themes_task();
1697 \core\task\manager::queue_adhoc_task($adhoctask);
1702 * Install core moodle tables and initialize
1703 * @param float $version target version
1704 * @param bool $verbose
1705 * @return void, may throw exception
1707 function install_core($version, $verbose) {
1708 global $CFG, $DB;
1710 // We can not call purge_all_caches() yet, make sure the temp and cache dirs exist and are empty.
1711 remove_dir($CFG->cachedir.'', true);
1712 make_cache_directory('', true);
1714 remove_dir($CFG->localcachedir.'', true);
1715 make_localcache_directory('', true);
1717 remove_dir($CFG->tempdir.'', true);
1718 make_temp_directory('', true);
1720 remove_dir($CFG->backuptempdir.'', true);
1721 make_backup_temp_directory('', true);
1723 remove_dir($CFG->dataroot.'/muc', true);
1724 make_writable_directory($CFG->dataroot.'/muc', true);
1726 try {
1727 core_php_time_limit::raise(600);
1728 print_upgrade_part_start('moodle', true, $verbose); // does not store upgrade running flag
1730 $DB->get_manager()->install_from_xmldb_file("$CFG->libdir/db/install.xml");
1731 upgrade_started(); // we want the flag to be stored in config table ;-)
1733 // set all core default records and default settings
1734 require_once("$CFG->libdir/db/install.php");
1735 xmldb_main_install(); // installs the capabilities too
1737 // store version
1738 upgrade_main_savepoint(true, $version, false);
1740 // Continue with the installation
1741 log_update_descriptions('moodle');
1742 external_update_descriptions('moodle');
1743 events_update_definition('moodle');
1744 \core\task\manager::reset_scheduled_tasks_for_component('moodle');
1745 message_update_providers('moodle');
1746 \core\message\inbound\manager::update_handlers_for_component('moodle');
1747 core_tag_area::reset_definitions_for_component('moodle');
1749 // Write default settings unconditionally
1750 admin_apply_default_settings(NULL, true);
1752 print_upgrade_part_end(null, true, $verbose);
1754 // Purge all caches. They're disabled but this ensures that we don't have any persistent data just in case something
1755 // during installation didn't use APIs.
1756 cache_helper::purge_all();
1757 } catch (exception $ex) {
1758 upgrade_handle_exception($ex);
1759 } catch (Throwable $ex) {
1760 // Engine errors in PHP7 throw exceptions of type Throwable (this "catch" will be ignored in PHP5).
1761 upgrade_handle_exception($ex);
1766 * Upgrade moodle core
1767 * @param float $version target version
1768 * @param bool $verbose
1769 * @return void, may throw exception
1771 function upgrade_core($version, $verbose) {
1772 global $CFG, $SITE, $DB, $COURSE;
1774 raise_memory_limit(MEMORY_EXTRA);
1776 require_once($CFG->libdir.'/db/upgrade.php'); // Defines upgrades
1778 try {
1779 // Reset caches before any output.
1780 cache_helper::purge_all(true);
1781 purge_all_caches();
1783 // Upgrade current language pack if we can
1784 upgrade_language_pack();
1786 print_upgrade_part_start('moodle', false, $verbose);
1788 // Pre-upgrade scripts for local hack workarounds.
1789 $preupgradefile = "$CFG->dirroot/local/preupgrade.php";
1790 if (file_exists($preupgradefile)) {
1791 core_php_time_limit::raise();
1792 require($preupgradefile);
1793 // Reset upgrade timeout to default.
1794 upgrade_set_timeout();
1797 $result = xmldb_main_upgrade($CFG->version);
1798 if ($version > $CFG->version) {
1799 // store version if not already there
1800 upgrade_main_savepoint($result, $version, false);
1803 // In case structure of 'course' table has been changed and we forgot to update $SITE, re-read it from db.
1804 $SITE = $DB->get_record('course', array('id' => $SITE->id));
1805 $COURSE = clone($SITE);
1807 // perform all other component upgrade routines
1808 update_capabilities('moodle');
1809 log_update_descriptions('moodle');
1810 external_update_descriptions('moodle');
1811 events_update_definition('moodle');
1812 \core\task\manager::reset_scheduled_tasks_for_component('moodle');
1813 message_update_providers('moodle');
1814 \core\message\inbound\manager::update_handlers_for_component('moodle');
1815 core_tag_area::reset_definitions_for_component('moodle');
1816 // Update core definitions.
1817 cache_helper::update_definitions(true);
1819 // Purge caches again, just to be sure we arn't holding onto old stuff now.
1820 cache_helper::purge_all(true);
1821 purge_all_caches();
1823 // Clean up contexts - more and more stuff depends on existence of paths and contexts
1824 context_helper::cleanup_instances();
1825 context_helper::create_instances(null, false);
1826 context_helper::build_all_paths(false);
1827 $syscontext = context_system::instance();
1828 $syscontext->mark_dirty();
1830 print_upgrade_part_end('moodle', false, $verbose);
1831 } catch (Exception $ex) {
1832 upgrade_handle_exception($ex);
1833 } catch (Throwable $ex) {
1834 // Engine errors in PHP7 throw exceptions of type Throwable (this "catch" will be ignored in PHP5).
1835 upgrade_handle_exception($ex);
1840 * Upgrade/install other parts of moodle
1841 * @param bool $verbose
1842 * @return void, may throw exception
1844 function upgrade_noncore($verbose) {
1845 global $CFG;
1847 raise_memory_limit(MEMORY_EXTRA);
1849 // upgrade all plugins types
1850 try {
1851 // Reset caches before any output.
1852 cache_helper::purge_all(true);
1853 purge_all_caches();
1855 $plugintypes = core_component::get_plugin_types();
1856 foreach ($plugintypes as $type=>$location) {
1857 upgrade_plugins($type, 'print_upgrade_part_start', 'print_upgrade_part_end', $verbose);
1859 // Upgrade services.
1860 // This function gives plugins and subsystems a chance to add functions to existing built-in services.
1861 external_update_services();
1863 // Update cache definitions. Involves scanning each plugin for any changes.
1864 cache_helper::update_definitions();
1865 // Mark the site as upgraded.
1866 set_config('allversionshash', core_component::get_all_versions_hash());
1868 // Purge caches again, just to be sure we arn't holding onto old stuff now.
1869 cache_helper::purge_all(true);
1870 purge_all_caches();
1872 } catch (Exception $ex) {
1873 upgrade_handle_exception($ex);
1874 } catch (Throwable $ex) {
1875 // Engine errors in PHP7 throw exceptions of type Throwable (this "catch" will be ignored in PHP5).
1876 upgrade_handle_exception($ex);
1881 * Checks if the main tables have been installed yet or not.
1883 * Note: we can not use caches here because they might be stale,
1884 * use with care!
1886 * @return bool
1888 function core_tables_exist() {
1889 global $DB;
1891 if (!$tables = $DB->get_tables(false) ) { // No tables yet at all.
1892 return false;
1894 } else { // Check for missing main tables
1895 $mtables = array('config', 'course', 'groupings'); // some tables used in 1.9 and 2.0, preferable something from the start and end of install.xml
1896 foreach ($mtables as $mtable) {
1897 if (!in_array($mtable, $tables)) {
1898 return false;
1901 return true;
1906 * upgrades the mnet rpc definitions for the given component.
1907 * this method doesn't return status, an exception will be thrown in the case of an error
1909 * @param string $component the plugin to upgrade, eg auth_mnet
1911 function upgrade_plugin_mnet_functions($component) {
1912 global $DB, $CFG;
1914 list($type, $plugin) = core_component::normalize_component($component);
1915 $path = core_component::get_plugin_directory($type, $plugin);
1917 $publishes = array();
1918 $subscribes = array();
1919 if (file_exists($path . '/db/mnet.php')) {
1920 require_once($path . '/db/mnet.php'); // $publishes comes from this file
1922 if (empty($publishes)) {
1923 $publishes = array(); // still need this to be able to disable stuff later
1925 if (empty($subscribes)) {
1926 $subscribes = array(); // still need this to be able to disable stuff later
1929 static $servicecache = array();
1931 // rekey an array based on the rpc method for easy lookups later
1932 $publishmethodservices = array();
1933 $subscribemethodservices = array();
1934 foreach($publishes as $servicename => $service) {
1935 if (is_array($service['methods'])) {
1936 foreach($service['methods'] as $methodname) {
1937 $service['servicename'] = $servicename;
1938 $publishmethodservices[$methodname][] = $service;
1943 // Disable functions that don't exist (any more) in the source
1944 // Should these be deleted? What about their permissions records?
1945 foreach ($DB->get_records('mnet_rpc', array('pluginname'=>$plugin, 'plugintype'=>$type), 'functionname ASC ') as $rpc) {
1946 if (!array_key_exists($rpc->functionname, $publishmethodservices) && $rpc->enabled) {
1947 $DB->set_field('mnet_rpc', 'enabled', 0, array('id' => $rpc->id));
1948 } else if (array_key_exists($rpc->functionname, $publishmethodservices) && !$rpc->enabled) {
1949 $DB->set_field('mnet_rpc', 'enabled', 1, array('id' => $rpc->id));
1953 // reflect all the services we're publishing and save them
1954 static $cachedclasses = array(); // to store reflection information in
1955 foreach ($publishes as $service => $data) {
1956 $f = $data['filename'];
1957 $c = $data['classname'];
1958 foreach ($data['methods'] as $method) {
1959 $dataobject = new stdClass();
1960 $dataobject->plugintype = $type;
1961 $dataobject->pluginname = $plugin;
1962 $dataobject->enabled = 1;
1963 $dataobject->classname = $c;
1964 $dataobject->filename = $f;
1966 if (is_string($method)) {
1967 $dataobject->functionname = $method;
1969 } else if (is_array($method)) { // wants to override file or class
1970 $dataobject->functionname = $method['method'];
1971 $dataobject->classname = $method['classname'];
1972 $dataobject->filename = $method['filename'];
1974 $dataobject->xmlrpcpath = $type.'/'.$plugin.'/'.$dataobject->filename.'/'.$method;
1975 $dataobject->static = false;
1977 require_once($path . '/' . $dataobject->filename);
1978 $functionreflect = null; // slightly different ways to get this depending on whether it's a class method or a function
1979 if (!empty($dataobject->classname)) {
1980 if (!class_exists($dataobject->classname)) {
1981 throw new moodle_exception('installnosuchmethod', 'mnet', '', (object)array('method' => $dataobject->functionname, 'class' => $dataobject->classname));
1983 $key = $dataobject->filename . '|' . $dataobject->classname;
1984 if (!array_key_exists($key, $cachedclasses)) { // look to see if we've already got a reflection object
1985 try {
1986 $cachedclasses[$key] = new ReflectionClass($dataobject->classname);
1987 } catch (ReflectionException $e) { // catch these and rethrow them to something more helpful
1988 throw new moodle_exception('installreflectionclasserror', 'mnet', '', (object)array('method' => $dataobject->functionname, 'class' => $dataobject->classname, 'error' => $e->getMessage()));
1991 $r =& $cachedclasses[$key];
1992 if (!$r->hasMethod($dataobject->functionname)) {
1993 throw new moodle_exception('installnosuchmethod', 'mnet', '', (object)array('method' => $dataobject->functionname, 'class' => $dataobject->classname));
1995 $functionreflect = $r->getMethod($dataobject->functionname);
1996 $dataobject->static = (int)$functionreflect->isStatic();
1997 } else {
1998 if (!function_exists($dataobject->functionname)) {
1999 throw new moodle_exception('installnosuchfunction', 'mnet', '', (object)array('method' => $dataobject->functionname, 'file' => $dataobject->filename));
2001 try {
2002 $functionreflect = new ReflectionFunction($dataobject->functionname);
2003 } catch (ReflectionException $e) { // catch these and rethrow them to something more helpful
2004 throw new moodle_exception('installreflectionfunctionerror', 'mnet', '', (object)array('method' => $dataobject->functionname, '' => $dataobject->filename, 'error' => $e->getMessage()));
2007 $dataobject->profile = serialize(admin_mnet_method_profile($functionreflect));
2008 $dataobject->help = admin_mnet_method_get_help($functionreflect);
2010 if ($record_exists = $DB->get_record('mnet_rpc', array('xmlrpcpath'=>$dataobject->xmlrpcpath))) {
2011 $dataobject->id = $record_exists->id;
2012 $dataobject->enabled = $record_exists->enabled;
2013 $DB->update_record('mnet_rpc', $dataobject);
2014 } else {
2015 $dataobject->id = $DB->insert_record('mnet_rpc', $dataobject, true);
2018 // TODO this API versioning must be reworked, here the recently processed method
2019 // sets the service API which may not be correct
2020 foreach ($publishmethodservices[$dataobject->functionname] as $service) {
2021 if ($serviceobj = $DB->get_record('mnet_service', array('name'=>$service['servicename']))) {
2022 $serviceobj->apiversion = $service['apiversion'];
2023 $DB->update_record('mnet_service', $serviceobj);
2024 } else {
2025 $serviceobj = new stdClass();
2026 $serviceobj->name = $service['servicename'];
2027 $serviceobj->description = empty($service['description']) ? '' : $service['description'];
2028 $serviceobj->apiversion = $service['apiversion'];
2029 $serviceobj->offer = 1;
2030 $serviceobj->id = $DB->insert_record('mnet_service', $serviceobj);
2032 $servicecache[$service['servicename']] = $serviceobj;
2033 if (!$DB->record_exists('mnet_service2rpc', array('rpcid'=>$dataobject->id, 'serviceid'=>$serviceobj->id))) {
2034 $obj = new stdClass();
2035 $obj->rpcid = $dataobject->id;
2036 $obj->serviceid = $serviceobj->id;
2037 $DB->insert_record('mnet_service2rpc', $obj, true);
2042 // finished with methods we publish, now do subscribable methods
2043 foreach($subscribes as $service => $methods) {
2044 if (!array_key_exists($service, $servicecache)) {
2045 if (!$serviceobj = $DB->get_record('mnet_service', array('name' => $service))) {
2046 debugging("TODO: skipping unknown service $service - somebody needs to fix MDL-21993");
2047 continue;
2049 $servicecache[$service] = $serviceobj;
2050 } else {
2051 $serviceobj = $servicecache[$service];
2053 foreach ($methods as $method => $xmlrpcpath) {
2054 if (!$rpcid = $DB->get_field('mnet_remote_rpc', 'id', array('xmlrpcpath'=>$xmlrpcpath))) {
2055 $remoterpc = (object)array(
2056 'functionname' => $method,
2057 'xmlrpcpath' => $xmlrpcpath,
2058 'plugintype' => $type,
2059 'pluginname' => $plugin,
2060 'enabled' => 1,
2062 $rpcid = $remoterpc->id = $DB->insert_record('mnet_remote_rpc', $remoterpc, true);
2064 if (!$DB->record_exists('mnet_remote_service2rpc', array('rpcid'=>$rpcid, 'serviceid'=>$serviceobj->id))) {
2065 $obj = new stdClass();
2066 $obj->rpcid = $rpcid;
2067 $obj->serviceid = $serviceobj->id;
2068 $DB->insert_record('mnet_remote_service2rpc', $obj, true);
2070 $subscribemethodservices[$method][] = $service;
2074 foreach ($DB->get_records('mnet_remote_rpc', array('pluginname'=>$plugin, 'plugintype'=>$type), 'functionname ASC ') as $rpc) {
2075 if (!array_key_exists($rpc->functionname, $subscribemethodservices) && $rpc->enabled) {
2076 $DB->set_field('mnet_remote_rpc', 'enabled', 0, array('id' => $rpc->id));
2077 } else if (array_key_exists($rpc->functionname, $subscribemethodservices) && !$rpc->enabled) {
2078 $DB->set_field('mnet_remote_rpc', 'enabled', 1, array('id' => $rpc->id));
2082 return true;
2086 * Given some sort of reflection function/method object, return a profile array, ready to be serialized and stored
2088 * @param ReflectionFunctionAbstract $function reflection function/method object from which to extract information
2090 * @return array associative array with function/method information
2092 function admin_mnet_method_profile(ReflectionFunctionAbstract $function) {
2093 $commentlines = admin_mnet_method_get_docblock($function);
2094 $getkey = function($key) use ($commentlines) {
2095 return array_values(array_filter($commentlines, function($line) use ($key) {
2096 return $line[0] == $key;
2097 }));
2099 $returnline = $getkey('@return');
2100 return array (
2101 'parameters' => array_map(function($line) {
2102 return array(
2103 'name' => trim($line[2], " \t\n\r\0\x0B$"),
2104 'type' => $line[1],
2105 'description' => $line[3]
2107 }, $getkey('@param')),
2109 'return' => array(
2110 'type' => !empty($returnline[0][1]) ? $returnline[0][1] : 'void',
2111 'description' => !empty($returnline[0][2]) ? $returnline[0][2] : ''
2117 * Given some sort of reflection function/method object, return an array of docblock lines, where each line is an array of
2118 * keywords/descriptions
2120 * @param ReflectionFunctionAbstract $function reflection function/method object from which to extract information
2122 * @return array docblock converted in to an array
2124 function admin_mnet_method_get_docblock(ReflectionFunctionAbstract $function) {
2125 return array_map(function($line) {
2126 $text = trim($line, " \t\n\r\0\x0B*/");
2127 if (strpos($text, '@param') === 0) {
2128 return preg_split('/\s+/', $text, 4);
2131 if (strpos($text, '@return') === 0) {
2132 return preg_split('/\s+/', $text, 3);
2135 return array($text);
2136 }, explode("\n", $function->getDocComment()));
2140 * Given some sort of reflection function/method object, return just the help text
2142 * @param ReflectionFunctionAbstract $function reflection function/method object from which to extract information
2144 * @return string docblock help text
2146 function admin_mnet_method_get_help(ReflectionFunctionAbstract $function) {
2147 $helplines = array_map(function($line) {
2148 return implode(' ', $line);
2149 }, array_values(array_filter(admin_mnet_method_get_docblock($function), function($line) {
2150 return strpos($line[0], '@') !== 0 && !empty($line[0]);
2151 })));
2153 return implode("\n", $helplines);
2157 * This function verifies that the database is not using an unsupported storage engine.
2159 * @param environment_results $result object to update, if relevant
2160 * @return environment_results|null updated results object, or null if the storage engine is supported
2162 function check_database_storage_engine(environment_results $result) {
2163 global $DB;
2165 // Check if MySQL is the DB family (this will also be the same for MariaDB).
2166 if ($DB->get_dbfamily() == 'mysql') {
2167 // Get the database engine we will either be using to install the tables, or what we are currently using.
2168 $engine = $DB->get_dbengine();
2169 // Check if MyISAM is the storage engine that will be used, if so, do not proceed and display an error.
2170 if ($engine == 'MyISAM') {
2171 $result->setInfo('unsupported_db_storage_engine');
2172 $result->setStatus(false);
2173 return $result;
2177 return null;
2181 * Method used to check the usage of slasharguments config and display a warning message.
2183 * @param environment_results $result object to update, if relevant.
2184 * @return environment_results|null updated results or null if slasharguments is disabled.
2186 function check_slasharguments(environment_results $result){
2187 global $CFG;
2189 if (!during_initial_install() && empty($CFG->slasharguments)) {
2190 $result->setInfo('slasharguments');
2191 $result->setStatus(false);
2192 return $result;
2195 return null;
2199 * This function verifies if the database has tables using innoDB Antelope row format.
2201 * @param environment_results $result
2202 * @return environment_results|null updated results object, or null if no Antelope table has been found.
2204 function check_database_tables_row_format(environment_results $result) {
2205 global $DB;
2207 if ($DB->get_dbfamily() == 'mysql') {
2208 $generator = $DB->get_manager()->generator;
2210 foreach ($DB->get_tables(false) as $table) {
2211 $columns = $DB->get_columns($table, false);
2212 $size = $generator->guess_antelope_row_size($columns);
2213 $format = $DB->get_row_format($table);
2215 if ($size <= $generator::ANTELOPE_MAX_ROW_SIZE) {
2216 continue;
2219 if ($format === 'Compact' or $format === 'Redundant') {
2220 $result->setInfo('unsupported_db_table_row_format');
2221 $result->setStatus(false);
2222 return $result;
2227 return null;
2231 * This function verfies that the database has tables using InnoDB Antelope row format.
2233 * @param environment_results $result
2234 * @return environment_results|null updated results object, or null if no Antelope table has been found.
2236 function check_mysql_file_format(environment_results $result) {
2237 global $DB;
2239 if ($DB->get_dbfamily() == 'mysql') {
2240 $collation = $DB->get_dbcollation();
2241 $collationinfo = explode('_', $collation);
2242 $charset = reset($collationinfo);
2244 if ($charset == 'utf8mb4') {
2245 if ($DB->get_row_format() !== "Barracuda") {
2246 $result->setInfo('mysql_full_unicode_support#File_format');
2247 $result->setStatus(false);
2248 return $result;
2252 return null;
2256 * This function verfies that the database has a setting of one file per table. This is required for 'utf8mb4'.
2258 * @param environment_results $result
2259 * @return environment_results|null updated results object, or null if innodb_file_per_table = 1.
2261 function check_mysql_file_per_table(environment_results $result) {
2262 global $DB;
2264 if ($DB->get_dbfamily() == 'mysql') {
2265 $collation = $DB->get_dbcollation();
2266 $collationinfo = explode('_', $collation);
2267 $charset = reset($collationinfo);
2269 if ($charset == 'utf8mb4') {
2270 if (!$DB->is_file_per_table_enabled()) {
2271 $result->setInfo('mysql_full_unicode_support#File_per_table');
2272 $result->setStatus(false);
2273 return $result;
2277 return null;
2281 * This function verfies that the database has the setting of large prefix enabled. This is required for 'utf8mb4'.
2283 * @param environment_results $result
2284 * @return environment_results|null updated results object, or null if innodb_large_prefix = 1.
2286 function check_mysql_large_prefix(environment_results $result) {
2287 global $DB;
2289 if ($DB->get_dbfamily() == 'mysql') {
2290 $collation = $DB->get_dbcollation();
2291 $collationinfo = explode('_', $collation);
2292 $charset = reset($collationinfo);
2294 if ($charset == 'utf8mb4') {
2295 if (!$DB->is_large_prefix_enabled()) {
2296 $result->setInfo('mysql_full_unicode_support#Large_prefix');
2297 $result->setStatus(false);
2298 return $result;
2302 return null;
2306 * This function checks the database to see if it is using incomplete unicode support.
2308 * @param environment_results $result $result
2309 * @return environment_results|null updated results object, or null if unicode is fully supported.
2311 function check_mysql_incomplete_unicode_support(environment_results $result) {
2312 global $DB;
2314 if ($DB->get_dbfamily() == 'mysql') {
2315 $collation = $DB->get_dbcollation();
2316 $collationinfo = explode('_', $collation);
2317 $charset = reset($collationinfo);
2319 if ($charset == 'utf8') {
2320 $result->setInfo('mysql_full_unicode_support');
2321 $result->setStatus(false);
2322 return $result;
2325 return null;
2329 * Check if the site is being served using an ssl url.
2331 * Note this does not really perform any request neither looks for proxies or
2332 * other situations. Just looks to wwwroot and warn if it's not using https.
2334 * @param environment_results $result $result
2335 * @return environment_results|null updated results object, or null if the site is https.
2337 function check_is_https(environment_results $result) {
2338 global $CFG;
2340 // Only if is defined, non-empty and whatever core tell us.
2341 if (!empty($CFG->wwwroot) && !is_https()) {
2342 $result->setInfo('site not https');
2343 $result->setStatus(false);
2344 return $result;
2346 return null;
2350 * Assert the upgrade key is provided, if it is defined.
2352 * The upgrade key can be defined in the main config.php as $CFG->upgradekey. If
2353 * it is defined there, then its value must be provided every time the site is
2354 * being upgraded, regardless the administrator is logged in or not.
2356 * This is supposed to be used at certain places in /admin/index.php only.
2358 * @param string|null $upgradekeyhash the SHA-1 of the value provided by the user
2360 function check_upgrade_key($upgradekeyhash) {
2361 global $CFG, $PAGE;
2363 if (isset($CFG->config_php_settings['upgradekey'])) {
2364 if ($upgradekeyhash === null or $upgradekeyhash !== sha1($CFG->config_php_settings['upgradekey'])) {
2365 if (!$PAGE->headerprinted) {
2366 $output = $PAGE->get_renderer('core', 'admin');
2367 echo $output->upgradekey_form_page(new moodle_url('/admin/index.php', array('cache' => 0)));
2368 die();
2369 } else {
2370 // This should not happen.
2371 die('Upgrade locked');
2378 * Helper procedure/macro for installing remote plugins at admin/index.php
2380 * Does not return, always redirects or exits.
2382 * @param array $installable list of \core\update\remote_info
2383 * @param bool $confirmed false: display the validation screen, true: proceed installation
2384 * @param string $heading validation screen heading
2385 * @param moodle_url|string|null $continue URL to proceed with installation at the validation screen
2386 * @param moodle_url|string|null $return URL to go back on cancelling at the validation screen
2388 function upgrade_install_plugins(array $installable, $confirmed, $heading='', $continue=null, $return=null) {
2389 global $CFG, $PAGE;
2391 if (empty($return)) {
2392 $return = $PAGE->url;
2395 if (!empty($CFG->disableupdateautodeploy)) {
2396 redirect($return);
2399 if (empty($installable)) {
2400 redirect($return);
2403 $pluginman = core_plugin_manager::instance();
2405 if ($confirmed) {
2406 // Installation confirmed at the validation results page.
2407 if (!$pluginman->install_plugins($installable, true, true)) {
2408 throw new moodle_exception('install_plugins_failed', 'core_plugin', $return);
2411 // Always redirect to admin/index.php to perform the database upgrade.
2412 // Do not throw away the existing $PAGE->url parameters such as
2413 // confirmupgrade or confirmrelease if $PAGE->url is a superset of the
2414 // URL we must go to.
2415 $mustgoto = new moodle_url('/admin/index.php', array('cache' => 0, 'confirmplugincheck' => 0));
2416 if ($mustgoto->compare($PAGE->url, URL_MATCH_PARAMS)) {
2417 redirect($PAGE->url);
2418 } else {
2419 redirect($mustgoto);
2422 } else {
2423 $output = $PAGE->get_renderer('core', 'admin');
2424 echo $output->header();
2425 if ($heading) {
2426 echo $output->heading($heading, 3);
2428 echo html_writer::start_tag('pre', array('class' => 'plugin-install-console'));
2429 $validated = $pluginman->install_plugins($installable, false, false);
2430 echo html_writer::end_tag('pre');
2431 if ($validated) {
2432 echo $output->plugins_management_confirm_buttons($continue, $return);
2433 } else {
2434 echo $output->plugins_management_confirm_buttons(null, $return);
2436 echo $output->footer();
2437 die();
2441 * Method used to check the installed unoconv version.
2443 * @param environment_results $result object to update, if relevant.
2444 * @return environment_results|null updated results or null if unoconv path is not executable.
2446 function check_unoconv_version(environment_results $result) {
2447 global $CFG;
2449 if (!during_initial_install() && !empty($CFG->pathtounoconv) && file_is_executable(trim($CFG->pathtounoconv))) {
2450 $currentversion = 0;
2451 $supportedversion = 0.7;
2452 $unoconvbin = \escapeshellarg($CFG->pathtounoconv);
2453 $command = "$unoconvbin --version";
2454 exec($command, $output);
2456 // If the command execution returned some output, then get the unoconv version.
2457 if ($output) {
2458 foreach ($output as $response) {
2459 if (preg_match('/unoconv (\\d+\\.\\d+)/', $response, $matches)) {
2460 $currentversion = (float)$matches[1];
2465 if ($currentversion < $supportedversion) {
2466 $result->setInfo('unoconv version not supported');
2467 $result->setStatus(false);
2468 return $result;
2471 return null;
2475 * Checks for up-to-date TLS libraries. NOTE: this is not currently used, see MDL-57262.
2477 * @param environment_results $result object to update, if relevant.
2478 * @return environment_results|null updated results or null if unoconv path is not executable.
2480 function check_tls_libraries(environment_results $result) {
2481 global $CFG;
2483 if (!function_exists('curl_version')) {
2484 $result->setInfo('cURL PHP extension is not installed');
2485 $result->setStatus(false);
2486 return $result;
2489 if (!\core\upgrade\util::validate_php_curl_tls(curl_version(), PHP_ZTS)) {
2490 $result->setInfo('invalid ssl/tls configuration');
2491 $result->setStatus(false);
2492 return $result;
2495 if (!\core\upgrade\util::can_use_tls12(curl_version(), php_uname('r'))) {
2496 $result->setInfo('ssl/tls configuration not supported');
2497 $result->setStatus(false);
2498 return $result;
2501 return null;
2505 * Check if recommended version of libcurl is installed or not.
2507 * @param environment_results $result object to update, if relevant.
2508 * @return environment_results|null updated results or null.
2510 function check_libcurl_version(environment_results $result) {
2512 if (!function_exists('curl_version')) {
2513 $result->setInfo('cURL PHP extension is not installed');
2514 $result->setStatus(false);
2515 return $result;
2518 // Supported version and version number.
2519 $supportedversion = 0x071304;
2520 $supportedversionstring = "7.19.4";
2522 // Installed version.
2523 $curlinfo = curl_version();
2524 $currentversion = $curlinfo['version_number'];
2526 if ($currentversion < $supportedversion) {
2527 // Test fail.
2528 // Set info, we want to let user know how to resolve the problem.
2529 $result->setInfo('Libcurl version check');
2530 $result->setNeededVersion($supportedversionstring);
2531 $result->setCurrentVersion($curlinfo['version']);
2532 $result->setStatus(false);
2533 return $result;
2536 return null;
2540 * Fix how auth plugins are called in the 'config_plugins' table.
2542 * For legacy reasons, the auth plugins did not always use their frankenstyle
2543 * component name in the 'plugin' column of the 'config_plugins' table. This is
2544 * a helper function to correctly migrate the legacy settings into the expected
2545 * and consistent way.
2547 * @param string $plugin the auth plugin name such as 'cas', 'manual' or 'mnet'
2549 function upgrade_fix_config_auth_plugin_names($plugin) {
2550 global $CFG, $DB, $OUTPUT;
2552 $legacy = (array) get_config('auth/'.$plugin);
2553 $current = (array) get_config('auth_'.$plugin);
2555 // I don't want to rely on array_merge() and friends here just in case
2556 // there was some crazy setting with a numerical name.
2558 if ($legacy) {
2559 $new = $legacy;
2560 } else {
2561 $new = [];
2564 if ($current) {
2565 foreach ($current as $name => $value) {
2566 if (isset($legacy[$name]) && ($legacy[$name] !== $value)) {
2567 // No need to pollute the output during unit tests.
2568 if (!empty($CFG->upgraderunning)) {
2569 $message = get_string('settingmigrationmismatch', 'core_auth', [
2570 'plugin' => 'auth_'.$plugin,
2571 'setting' => s($name),
2572 'legacy' => s($legacy[$name]),
2573 'current' => s($value),
2575 echo $OUTPUT->notification($message, \core\output\notification::NOTIFY_ERROR);
2577 upgrade_log(UPGRADE_LOG_NOTICE, 'auth_'.$plugin, 'Setting values mismatch detected',
2578 'SETTING: '.$name. ' LEGACY: '.$legacy[$name].' CURRENT: '.$value);
2582 $new[$name] = $value;
2586 foreach ($new as $name => $value) {
2587 set_config($name, $value, 'auth_'.$plugin);
2588 unset_config($name, 'auth/'.$plugin);
2593 * Populate the auth plugin settings with defaults if needed.
2595 * As a result of fixing the auth plugins config storage, many settings would
2596 * be falsely reported as new ones by admin/upgradesettings.php. We do not want
2597 * to confuse admins so we try to reduce the bewilderment by pre-populating the
2598 * config_plugins table with default values. This should be done only for
2599 * disabled auth methods. The enabled methods have their settings already
2600 * stored, so reporting actual new settings for them is valid.
2602 * @param string $plugin the auth plugin name such as 'cas', 'manual' or 'mnet'
2604 function upgrade_fix_config_auth_plugin_defaults($plugin) {
2605 global $CFG;
2607 $pluginman = core_plugin_manager::instance();
2608 $enabled = $pluginman->get_enabled_plugins('auth');
2610 if (isset($enabled[$plugin])) {
2611 // Do not touch settings of enabled auth methods.
2612 return;
2615 // We can't directly use {@link core\plugininfo\auth::load_settings()} here
2616 // because the plugins are not fully upgraded yet. Instead, we emulate what
2617 // that method does. We fetch a temporary instance of the plugin's settings
2618 // page to get access to the settings and their defaults. Note we are not
2619 // adding that temporary instance into the admin tree. Yes, this is a hack.
2621 $plugininfo = $pluginman->get_plugin_info('auth_'.$plugin);
2622 $adminroot = admin_get_root();
2623 $ADMIN = $adminroot;
2624 $auth = $plugininfo;
2626 $section = $plugininfo->get_settings_section_name();
2627 $settingspath = $plugininfo->full_path('settings.php');
2629 if (file_exists($settingspath)) {
2630 $settings = new admin_settingpage($section, 'Emulated settings page for auth_'.$plugin, 'moodle/site:config');
2631 include($settingspath);
2633 if ($settings) {
2634 // Consistently with what admin/cli/upgrade.php does, apply the default settings twice.
2635 // I assume this is done for theoretical cases when a default value depends on an other.
2636 admin_apply_default_settings($settings, false);
2637 admin_apply_default_settings($settings, false);
2643 * Search for a given theme in any of the parent themes of a given theme.
2645 * @param string $needle The name of the theme you want to search for
2646 * @param string $themename The name of the theme you want to search for
2647 * @param string $checkedthemeforparents The name of all the themes already checked
2648 * @return bool True if found, false if not.
2650 function upgrade_theme_is_from_family($needle, $themename, $checkedthemeforparents = []) {
2651 global $CFG;
2653 // Once we've started checking a theme, don't start checking it again. Prevent recursion.
2654 if (!empty($checkedthemeforparents[$themename])) {
2655 return false;
2657 $checkedthemeforparents[$themename] = true;
2659 if ($themename == $needle) {
2660 return true;
2663 if ($themedir = upgrade_find_theme_location($themename)) {
2664 $THEME = new stdClass();
2665 require($themedir . '/config.php');
2666 $theme = $THEME;
2667 } else {
2668 return false;
2671 if (empty($theme->parents)) {
2672 return false;
2675 // Recursively search through each parent theme.
2676 foreach ($theme->parents as $parent) {
2677 if (upgrade_theme_is_from_family($needle, $parent, $checkedthemeforparents)) {
2678 return true;
2681 return false;
2685 * Finds the theme location and verifies the theme has all needed files.
2687 * @param string $themename The name of the theme you want to search for
2688 * @return string full dir path or null if not found
2689 * @see \theme_config::find_theme_location()
2691 function upgrade_find_theme_location($themename) {
2692 global $CFG;
2694 if (file_exists("$CFG->dirroot/theme/$themename/config.php")) {
2695 $dir = "$CFG->dirroot/theme/$themename";
2696 } else if (!empty($CFG->themedir) and file_exists("$CFG->themedir/$themename/config.php")) {
2697 $dir = "$CFG->themedir/$themename";
2698 } else {
2699 return null;
2702 return $dir;