Merge branch 'MDL-66614_36' of https://github.com/timhunt/moodle into MOODLE_36_STABLE
[moodle.git] / lib / upgradelib.php
blobb02579f536364b2641e6778c9a5334140a306b43
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 The type of the plugin.
387 * @param string $plugin The name of the 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.6.
434 '/lib/classes/session/memcache.php',
435 '/lib/eventslib.php',
436 '/lib/form/submitlink.php',
437 '/lib/medialib.php',
438 '/lib/password_compat/lib/password.php',
439 // Removed in 3.5.
440 '/lib/dml/mssql_native_moodle_database.php',
441 '/lib/dml/mssql_native_moodle_recordset.php',
442 '/lib/dml/mssql_native_moodle_temptables.php',
443 // Removed in 3.4.
444 '/auth/README.txt',
445 '/calendar/set.php',
446 '/enrol/users.php',
447 '/enrol/yui/rolemanager/assets/skins/sam/rolemanager.css',
448 // Removed in 3.3.
449 '/badges/backpackconnect.php',
450 '/calendar/yui/src/info/assets/skins/sam/moodle-calendar-info.css',
451 '/competency/classes/external/exporter.php',
452 '/mod/forum/forum.js',
453 '/user/pixgroup.php',
454 // Removed in 3.2.
455 '/calendar/preferences.php',
456 '/lib/alfresco/',
457 '/lib/jquery/jquery-1.12.1.min.js',
458 '/lib/password_compat/tests/',
459 '/lib/phpunit/classes/unittestcase.php',
460 // Removed in 3.1.
461 '/lib/classes/log/sql_internal_reader.php',
462 '/lib/zend/',
463 '/mod/forum/pix/icon.gif',
464 '/tag/templates/tagname.mustache',
465 // Removed in 3.0.
466 '/mod/lti/grade.php',
467 '/tag/coursetagslib.php',
468 // Removed in 2.9.
469 '/lib/timezone.txt',
470 // Removed in 2.8.
471 '/course/delete_category_form.php',
472 // Removed in 2.7.
473 '/admin/tool/qeupgradehelper/version.php',
474 // Removed in 2.6.
475 '/admin/block.php',
476 '/admin/oacleanup.php',
477 // Removed in 2.5.
478 '/backup/lib.php',
479 '/backup/bb/README.txt',
480 '/lib/excel/test.php',
481 // Removed in 2.4.
482 '/admin/tool/unittest/simpletestlib.php',
483 // Removed in 2.3.
484 '/lib/minify/builder/',
485 // Removed in 2.2.
486 '/lib/yui/3.4.1pr1/',
487 // Removed in 2.2.
488 '/search/cron_php5.php',
489 '/course/report/log/indexlive.php',
490 '/admin/report/backups/index.php',
491 '/admin/generator.php',
492 // Removed in 2.1.
493 '/lib/yui/2.8.0r4/',
494 // Removed in 2.0.
495 '/blocks/admin/block_admin.php',
496 '/blocks/admin_tree/block_admin_tree.php',
499 foreach ($someexamplesofremovedfiles as $file) {
500 if (file_exists($CFG->dirroot.$file)) {
501 return true;
505 return false;
509 * Upgrade plugins
510 * @param string $type The type of plugins that should be updated (e.g. 'enrol', 'qtype')
511 * return void
513 function upgrade_plugins($type, $startcallback, $endcallback, $verbose) {
514 global $CFG, $DB;
516 /// special cases
517 if ($type === 'mod') {
518 return upgrade_plugins_modules($startcallback, $endcallback, $verbose);
519 } else if ($type === 'block') {
520 return upgrade_plugins_blocks($startcallback, $endcallback, $verbose);
523 $plugs = core_component::get_plugin_list($type);
525 foreach ($plugs as $plug=>$fullplug) {
526 // Reset time so that it works when installing a large number of plugins
527 core_php_time_limit::raise(600);
528 $component = clean_param($type.'_'.$plug, PARAM_COMPONENT); // standardised plugin name
530 // check plugin dir is valid name
531 if (empty($component)) {
532 throw new plugin_defective_exception($type.'_'.$plug, 'Invalid plugin directory name.');
535 if (!is_readable($fullplug.'/version.php')) {
536 continue;
539 $plugin = new stdClass();
540 $plugin->version = null;
541 $module = $plugin; // Prevent some notices when plugin placed in wrong directory.
542 require($fullplug.'/version.php'); // defines $plugin with version etc
543 unset($module);
545 if (empty($plugin->version)) {
546 throw new plugin_defective_exception($component, 'Missing $plugin->version number in version.php.');
549 if (empty($plugin->component)) {
550 throw new plugin_defective_exception($component, 'Missing $plugin->component declaration in version.php.');
553 if ($plugin->component !== $component) {
554 throw new plugin_misplaced_exception($plugin->component, null, $fullplug);
557 $plugin->name = $plug;
558 $plugin->fullname = $component;
560 if (!empty($plugin->requires)) {
561 if ($plugin->requires > $CFG->version) {
562 throw new upgrade_requires_exception($component, $plugin->version, $CFG->version, $plugin->requires);
563 } else if ($plugin->requires < 2010000000) {
564 throw new plugin_defective_exception($component, 'Plugin is not compatible with Moodle 2.x or later.');
568 // try to recover from interrupted install.php if needed
569 if (file_exists($fullplug.'/db/install.php')) {
570 if (get_config($plugin->fullname, 'installrunning')) {
571 require_once($fullplug.'/db/install.php');
572 $recover_install_function = 'xmldb_'.$plugin->fullname.'_install_recovery';
573 if (function_exists($recover_install_function)) {
574 $startcallback($component, true, $verbose);
575 $recover_install_function();
576 unset_config('installrunning', $plugin->fullname);
577 update_capabilities($component);
578 log_update_descriptions($component);
579 external_update_descriptions($component);
580 \core\task\manager::reset_scheduled_tasks_for_component($component);
581 message_update_providers($component);
582 \core\message\inbound\manager::update_handlers_for_component($component);
583 if ($type === 'message') {
584 message_update_processors($plug);
586 upgrade_plugin_mnet_functions($component);
587 core_tag_area::reset_definitions_for_component($component);
588 $endcallback($component, true, $verbose);
593 $installedversion = $DB->get_field('config_plugins', 'value', array('name'=>'version', 'plugin'=>$component)); // No caching!
594 if (empty($installedversion)) { // new installation
595 $startcallback($component, true, $verbose);
597 /// Install tables if defined
598 if (file_exists($fullplug.'/db/install.xml')) {
599 $DB->get_manager()->install_from_xmldb_file($fullplug.'/db/install.xml');
602 /// store version
603 upgrade_plugin_savepoint(true, $plugin->version, $type, $plug, false);
605 /// execute post install file
606 if (file_exists($fullplug.'/db/install.php')) {
607 require_once($fullplug.'/db/install.php');
608 set_config('installrunning', 1, $plugin->fullname);
609 $post_install_function = 'xmldb_'.$plugin->fullname.'_install';
610 $post_install_function();
611 unset_config('installrunning', $plugin->fullname);
614 /// Install various components
615 update_capabilities($component);
616 log_update_descriptions($component);
617 external_update_descriptions($component);
618 \core\task\manager::reset_scheduled_tasks_for_component($component);
619 message_update_providers($component);
620 \core\message\inbound\manager::update_handlers_for_component($component);
621 if ($type === 'message') {
622 message_update_processors($plug);
624 upgrade_plugin_mnet_functions($component);
625 core_tag_area::reset_definitions_for_component($component);
626 $endcallback($component, true, $verbose);
628 } else if ($installedversion < $plugin->version) { // upgrade
629 /// Run the upgrade function for the plugin.
630 $startcallback($component, false, $verbose);
632 if (is_readable($fullplug.'/db/upgrade.php')) {
633 require_once($fullplug.'/db/upgrade.php'); // defines upgrading function
635 $newupgrade_function = 'xmldb_'.$plugin->fullname.'_upgrade';
636 $result = $newupgrade_function($installedversion);
637 } else {
638 $result = true;
641 $installedversion = $DB->get_field('config_plugins', 'value', array('name'=>'version', 'plugin'=>$component)); // No caching!
642 if ($installedversion < $plugin->version) {
643 // store version if not already there
644 upgrade_plugin_savepoint($result, $plugin->version, $type, $plug, false);
647 /// Upgrade various components
648 update_capabilities($component);
649 log_update_descriptions($component);
650 external_update_descriptions($component);
651 \core\task\manager::reset_scheduled_tasks_for_component($component);
652 message_update_providers($component);
653 \core\message\inbound\manager::update_handlers_for_component($component);
654 if ($type === 'message') {
655 // Ugly hack!
656 message_update_processors($plug);
658 upgrade_plugin_mnet_functions($component);
659 core_tag_area::reset_definitions_for_component($component);
660 $endcallback($component, false, $verbose);
662 } else if ($installedversion > $plugin->version) {
663 throw new downgrade_exception($component, $installedversion, $plugin->version);
669 * Find and check all modules and load them up or upgrade them if necessary
671 * @global object
672 * @global object
674 function upgrade_plugins_modules($startcallback, $endcallback, $verbose) {
675 global $CFG, $DB;
677 $mods = core_component::get_plugin_list('mod');
679 foreach ($mods as $mod=>$fullmod) {
681 if ($mod === 'NEWMODULE') { // Someone has unzipped the template, ignore it
682 continue;
685 $component = clean_param('mod_'.$mod, PARAM_COMPONENT);
687 // check module dir is valid name
688 if (empty($component)) {
689 throw new plugin_defective_exception('mod_'.$mod, 'Invalid plugin directory name.');
692 if (!is_readable($fullmod.'/version.php')) {
693 throw new plugin_defective_exception($component, 'Missing version.php');
696 $module = new stdClass();
697 $plugin = new stdClass();
698 $plugin->version = null;
699 require($fullmod .'/version.php'); // Defines $plugin with version etc.
701 // Check if the legacy $module syntax is still used.
702 if (!is_object($module) or (count((array)$module) > 0)) {
703 throw new plugin_defective_exception($component, 'Unsupported $module syntax detected in version.php');
706 // Prepare the record for the {modules} table.
707 $module = clone($plugin);
708 unset($module->version);
709 unset($module->component);
710 unset($module->dependencies);
711 unset($module->release);
713 if (empty($plugin->version)) {
714 throw new plugin_defective_exception($component, 'Missing $plugin->version number in version.php.');
717 if (empty($plugin->component)) {
718 throw new plugin_defective_exception($component, 'Missing $plugin->component declaration in version.php.');
721 if ($plugin->component !== $component) {
722 throw new plugin_misplaced_exception($plugin->component, null, $fullmod);
725 if (!empty($plugin->requires)) {
726 if ($plugin->requires > $CFG->version) {
727 throw new upgrade_requires_exception($component, $plugin->version, $CFG->version, $plugin->requires);
728 } else if ($plugin->requires < 2010000000) {
729 throw new plugin_defective_exception($component, 'Plugin is not compatible with Moodle 2.x or later.');
733 if (empty($module->cron)) {
734 $module->cron = 0;
737 // all modules must have en lang pack
738 if (!is_readable("$fullmod/lang/en/$mod.php")) {
739 throw new plugin_defective_exception($component, 'Missing mandatory en language pack.');
742 $module->name = $mod; // The name MUST match the directory
744 $installedversion = $DB->get_field('config_plugins', 'value', array('name'=>'version', 'plugin'=>$component)); // No caching!
746 if (file_exists($fullmod.'/db/install.php')) {
747 if (get_config($module->name, 'installrunning')) {
748 require_once($fullmod.'/db/install.php');
749 $recover_install_function = 'xmldb_'.$module->name.'_install_recovery';
750 if (function_exists($recover_install_function)) {
751 $startcallback($component, true, $verbose);
752 $recover_install_function();
753 unset_config('installrunning', $module->name);
754 // Install various components too
755 update_capabilities($component);
756 log_update_descriptions($component);
757 external_update_descriptions($component);
758 \core\task\manager::reset_scheduled_tasks_for_component($component);
759 message_update_providers($component);
760 \core\message\inbound\manager::update_handlers_for_component($component);
761 upgrade_plugin_mnet_functions($component);
762 core_tag_area::reset_definitions_for_component($component);
763 $endcallback($component, true, $verbose);
768 if (empty($installedversion)) {
769 $startcallback($component, true, $verbose);
771 /// Execute install.xml (XMLDB) - must be present in all modules
772 $DB->get_manager()->install_from_xmldb_file($fullmod.'/db/install.xml');
774 /// Add record into modules table - may be needed in install.php already
775 $module->id = $DB->insert_record('modules', $module);
776 upgrade_mod_savepoint(true, $plugin->version, $module->name, false);
778 /// Post installation hook - optional
779 if (file_exists("$fullmod/db/install.php")) {
780 require_once("$fullmod/db/install.php");
781 // Set installation running flag, we need to recover after exception or error
782 set_config('installrunning', 1, $module->name);
783 $post_install_function = 'xmldb_'.$module->name.'_install';
784 $post_install_function();
785 unset_config('installrunning', $module->name);
788 /// Install various components
789 update_capabilities($component);
790 log_update_descriptions($component);
791 external_update_descriptions($component);
792 \core\task\manager::reset_scheduled_tasks_for_component($component);
793 message_update_providers($component);
794 \core\message\inbound\manager::update_handlers_for_component($component);
795 upgrade_plugin_mnet_functions($component);
796 core_tag_area::reset_definitions_for_component($component);
798 $endcallback($component, true, $verbose);
800 } else if ($installedversion < $plugin->version) {
801 /// If versions say that we need to upgrade but no upgrade files are available, notify and continue
802 $startcallback($component, false, $verbose);
804 if (is_readable($fullmod.'/db/upgrade.php')) {
805 require_once($fullmod.'/db/upgrade.php'); // defines new upgrading function
806 $newupgrade_function = 'xmldb_'.$module->name.'_upgrade';
807 $result = $newupgrade_function($installedversion, $module);
808 } else {
809 $result = true;
812 $installedversion = $DB->get_field('config_plugins', 'value', array('name'=>'version', 'plugin'=>$component)); // No caching!
813 $currmodule = $DB->get_record('modules', array('name'=>$module->name));
814 if ($installedversion < $plugin->version) {
815 // store version if not already there
816 upgrade_mod_savepoint($result, $plugin->version, $mod, false);
819 // update cron flag if needed
820 if ($currmodule->cron != $module->cron) {
821 $DB->set_field('modules', 'cron', $module->cron, array('name' => $module->name));
824 // Upgrade various components
825 update_capabilities($component);
826 log_update_descriptions($component);
827 external_update_descriptions($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 \core\task\manager::reset_scheduled_tasks_for_component($component);
950 message_update_providers($component);
951 \core\message\inbound\manager::update_handlers_for_component($component);
952 upgrade_plugin_mnet_functions($component);
953 core_tag_area::reset_definitions_for_component($component);
954 $endcallback($component, true, $verbose);
959 if (empty($installedversion)) { // block not installed yet, so install it
960 $conflictblock = array_search($blocktitle, $blocktitles);
961 if ($conflictblock !== false) {
962 // Duplicate block titles are not allowed, they confuse people
963 // AND PHP's associative arrays ;)
964 throw new plugin_defective_exception($component, get_string('blocknameconflict', 'error', (object)array('name'=>$block->name, 'conflict'=>$conflictblock)));
966 $startcallback($component, true, $verbose);
968 if (file_exists($fullblock.'/db/install.xml')) {
969 $DB->get_manager()->install_from_xmldb_file($fullblock.'/db/install.xml');
971 $block->id = $DB->insert_record('block', $block);
972 upgrade_block_savepoint(true, $plugin->version, $block->name, false);
974 if (file_exists($fullblock.'/db/install.php')) {
975 require_once($fullblock.'/db/install.php');
976 // Set installation running flag, we need to recover after exception or error
977 set_config('installrunning', 1, 'block_'.$blockname);
978 $post_install_function = 'xmldb_block_'.$blockname.'_install';
979 $post_install_function();
980 unset_config('installrunning', 'block_'.$blockname);
983 $blocktitles[$block->name] = $blocktitle;
985 // Install various components
986 update_capabilities($component);
987 log_update_descriptions($component);
988 external_update_descriptions($component);
989 \core\task\manager::reset_scheduled_tasks_for_component($component);
990 message_update_providers($component);
991 \core\message\inbound\manager::update_handlers_for_component($component);
992 core_tag_area::reset_definitions_for_component($component);
993 upgrade_plugin_mnet_functions($component);
995 $endcallback($component, true, $verbose);
997 } else if ($installedversion < $plugin->version) {
998 $startcallback($component, false, $verbose);
1000 if (is_readable($fullblock.'/db/upgrade.php')) {
1001 require_once($fullblock.'/db/upgrade.php'); // defines new upgrading function
1002 $newupgrade_function = 'xmldb_block_'.$blockname.'_upgrade';
1003 $result = $newupgrade_function($installedversion, $block);
1004 } else {
1005 $result = true;
1008 $installedversion = $DB->get_field('config_plugins', 'value', array('name'=>'version', 'plugin'=>$component)); // No caching!
1009 $currblock = $DB->get_record('block', array('name'=>$block->name));
1010 if ($installedversion < $plugin->version) {
1011 // store version if not already there
1012 upgrade_block_savepoint($result, $plugin->version, $block->name, false);
1015 if ($currblock->cron != $block->cron) {
1016 // update cron flag if needed
1017 $DB->set_field('block', 'cron', $block->cron, array('id' => $currblock->id));
1020 // Upgrade various components
1021 update_capabilities($component);
1022 log_update_descriptions($component);
1023 external_update_descriptions($component);
1024 \core\task\manager::reset_scheduled_tasks_for_component($component);
1025 message_update_providers($component);
1026 \core\message\inbound\manager::update_handlers_for_component($component);
1027 upgrade_plugin_mnet_functions($component);
1028 core_tag_area::reset_definitions_for_component($component);
1030 $endcallback($component, false, $verbose);
1032 } else if ($installedversion > $plugin->version) {
1033 throw new downgrade_exception($component, $installedversion, $plugin->version);
1038 // Finally, if we are in the first_install of BLOCKS setup frontpage and admin page blocks
1039 if ($first_install) {
1040 //Iterate over each course - there should be only site course here now
1041 if ($courses = $DB->get_records('course')) {
1042 foreach ($courses as $course) {
1043 blocks_add_default_course_blocks($course);
1047 blocks_add_default_system_blocks();
1053 * Log_display description function used during install and upgrade.
1055 * @param string $component name of component (moodle, mod_assignment, etc.)
1056 * @return void
1058 function log_update_descriptions($component) {
1059 global $DB;
1061 $defpath = core_component::get_component_directory($component).'/db/log.php';
1063 if (!file_exists($defpath)) {
1064 $DB->delete_records('log_display', array('component'=>$component));
1065 return;
1068 // load new info
1069 $logs = array();
1070 include($defpath);
1071 $newlogs = array();
1072 foreach ($logs as $log) {
1073 $newlogs[$log['module'].'-'.$log['action']] = $log; // kind of unique name
1075 unset($logs);
1076 $logs = $newlogs;
1078 $fields = array('module', 'action', 'mtable', 'field');
1079 // update all log fist
1080 $dblogs = $DB->get_records('log_display', array('component'=>$component));
1081 foreach ($dblogs as $dblog) {
1082 $name = $dblog->module.'-'.$dblog->action;
1084 if (empty($logs[$name])) {
1085 $DB->delete_records('log_display', array('id'=>$dblog->id));
1086 continue;
1089 $log = $logs[$name];
1090 unset($logs[$name]);
1092 $update = false;
1093 foreach ($fields as $field) {
1094 if ($dblog->$field != $log[$field]) {
1095 $dblog->$field = $log[$field];
1096 $update = true;
1099 if ($update) {
1100 $DB->update_record('log_display', $dblog);
1103 foreach ($logs as $log) {
1104 $dblog = (object)$log;
1105 $dblog->component = $component;
1106 $DB->insert_record('log_display', $dblog);
1111 * Web service discovery function used during install and upgrade.
1112 * @param string $component name of component (moodle, mod_assignment, etc.)
1113 * @return void
1115 function external_update_descriptions($component) {
1116 global $DB, $CFG;
1118 $defpath = core_component::get_component_directory($component).'/db/services.php';
1120 if (!file_exists($defpath)) {
1121 require_once($CFG->dirroot.'/lib/externallib.php');
1122 external_delete_descriptions($component);
1123 return;
1126 // load new info
1127 $functions = array();
1128 $services = array();
1129 include($defpath);
1131 // update all function fist
1132 $dbfunctions = $DB->get_records('external_functions', array('component'=>$component));
1133 foreach ($dbfunctions as $dbfunction) {
1134 if (empty($functions[$dbfunction->name])) {
1135 $DB->delete_records('external_functions', array('id'=>$dbfunction->id));
1136 // do not delete functions from external_services_functions, beacuse
1137 // we want to notify admins when functions used in custom services disappear
1139 //TODO: this looks wrong, we have to delete it eventually (skodak)
1140 continue;
1143 $function = $functions[$dbfunction->name];
1144 unset($functions[$dbfunction->name]);
1145 $function['classpath'] = empty($function['classpath']) ? null : $function['classpath'];
1147 $update = false;
1148 if ($dbfunction->classname != $function['classname']) {
1149 $dbfunction->classname = $function['classname'];
1150 $update = true;
1152 if ($dbfunction->methodname != $function['methodname']) {
1153 $dbfunction->methodname = $function['methodname'];
1154 $update = true;
1156 if ($dbfunction->classpath != $function['classpath']) {
1157 $dbfunction->classpath = $function['classpath'];
1158 $update = true;
1160 $functioncapabilities = array_key_exists('capabilities', $function)?$function['capabilities']:'';
1161 if ($dbfunction->capabilities != $functioncapabilities) {
1162 $dbfunction->capabilities = $functioncapabilities;
1163 $update = true;
1166 if (isset($function['services']) and is_array($function['services'])) {
1167 sort($function['services']);
1168 $functionservices = implode(',', $function['services']);
1169 } else {
1170 // Force null values in the DB.
1171 $functionservices = null;
1174 if ($dbfunction->services != $functionservices) {
1175 // Now, we need to check if services were removed, in that case we need to remove the function from them.
1176 $servicesremoved = array_diff(explode(",", $dbfunction->services), explode(",", $functionservices));
1177 foreach ($servicesremoved as $removedshortname) {
1178 if ($externalserviceid = $DB->get_field('external_services', 'id', array("shortname" => $removedshortname))) {
1179 $DB->delete_records('external_services_functions', array('functionname' => $dbfunction->name,
1180 'externalserviceid' => $externalserviceid));
1184 $dbfunction->services = $functionservices;
1185 $update = true;
1187 if ($update) {
1188 $DB->update_record('external_functions', $dbfunction);
1191 foreach ($functions as $fname => $function) {
1192 $dbfunction = new stdClass();
1193 $dbfunction->name = $fname;
1194 $dbfunction->classname = $function['classname'];
1195 $dbfunction->methodname = $function['methodname'];
1196 $dbfunction->classpath = empty($function['classpath']) ? null : $function['classpath'];
1197 $dbfunction->component = $component;
1198 $dbfunction->capabilities = array_key_exists('capabilities', $function)?$function['capabilities']:'';
1200 if (isset($function['services']) and is_array($function['services'])) {
1201 sort($function['services']);
1202 $dbfunction->services = implode(',', $function['services']);
1203 } else {
1204 // Force null values in the DB.
1205 $dbfunction->services = null;
1208 $dbfunction->id = $DB->insert_record('external_functions', $dbfunction);
1210 unset($functions);
1212 // now deal with services
1213 $dbservices = $DB->get_records('external_services', array('component'=>$component));
1214 foreach ($dbservices as $dbservice) {
1215 if (empty($services[$dbservice->name])) {
1216 $DB->delete_records('external_tokens', array('externalserviceid'=>$dbservice->id));
1217 $DB->delete_records('external_services_functions', array('externalserviceid'=>$dbservice->id));
1218 $DB->delete_records('external_services_users', array('externalserviceid'=>$dbservice->id));
1219 $DB->delete_records('external_services', array('id'=>$dbservice->id));
1220 continue;
1222 $service = $services[$dbservice->name];
1223 unset($services[$dbservice->name]);
1224 $service['enabled'] = empty($service['enabled']) ? 0 : $service['enabled'];
1225 $service['requiredcapability'] = empty($service['requiredcapability']) ? null : $service['requiredcapability'];
1226 $service['restrictedusers'] = !isset($service['restrictedusers']) ? 1 : $service['restrictedusers'];
1227 $service['downloadfiles'] = !isset($service['downloadfiles']) ? 0 : $service['downloadfiles'];
1228 $service['uploadfiles'] = !isset($service['uploadfiles']) ? 0 : $service['uploadfiles'];
1229 $service['shortname'] = !isset($service['shortname']) ? null : $service['shortname'];
1231 $update = false;
1232 if ($dbservice->requiredcapability != $service['requiredcapability']) {
1233 $dbservice->requiredcapability = $service['requiredcapability'];
1234 $update = true;
1236 if ($dbservice->restrictedusers != $service['restrictedusers']) {
1237 $dbservice->restrictedusers = $service['restrictedusers'];
1238 $update = true;
1240 if ($dbservice->downloadfiles != $service['downloadfiles']) {
1241 $dbservice->downloadfiles = $service['downloadfiles'];
1242 $update = true;
1244 if ($dbservice->uploadfiles != $service['uploadfiles']) {
1245 $dbservice->uploadfiles = $service['uploadfiles'];
1246 $update = true;
1248 //if shortname is not a PARAM_ALPHANUMEXT, fail (tested here for service update and creation)
1249 if (isset($service['shortname']) and
1250 (clean_param($service['shortname'], PARAM_ALPHANUMEXT) != $service['shortname'])) {
1251 throw new moodle_exception('installserviceshortnameerror', 'webservice', '', $service['shortname']);
1253 if ($dbservice->shortname != $service['shortname']) {
1254 //check that shortname is unique
1255 if (isset($service['shortname'])) { //we currently accepts multiple shortname == null
1256 $existingservice = $DB->get_record('external_services',
1257 array('shortname' => $service['shortname']));
1258 if (!empty($existingservice)) {
1259 throw new moodle_exception('installexistingserviceshortnameerror', 'webservice', '', $service['shortname']);
1262 $dbservice->shortname = $service['shortname'];
1263 $update = true;
1265 if ($update) {
1266 $DB->update_record('external_services', $dbservice);
1269 $functions = $DB->get_records('external_services_functions', array('externalserviceid'=>$dbservice->id));
1270 foreach ($functions as $function) {
1271 $key = array_search($function->functionname, $service['functions']);
1272 if ($key === false) {
1273 $DB->delete_records('external_services_functions', array('id'=>$function->id));
1274 } else {
1275 unset($service['functions'][$key]);
1278 foreach ($service['functions'] as $fname) {
1279 $newf = new stdClass();
1280 $newf->externalserviceid = $dbservice->id;
1281 $newf->functionname = $fname;
1282 $DB->insert_record('external_services_functions', $newf);
1284 unset($functions);
1286 foreach ($services as $name => $service) {
1287 //check that shortname is unique
1288 if (isset($service['shortname'])) { //we currently accepts multiple shortname == null
1289 $existingservice = $DB->get_record('external_services',
1290 array('shortname' => $service['shortname']));
1291 if (!empty($existingservice)) {
1292 throw new moodle_exception('installserviceshortnameerror', 'webservice');
1296 $dbservice = new stdClass();
1297 $dbservice->name = $name;
1298 $dbservice->enabled = empty($service['enabled']) ? 0 : $service['enabled'];
1299 $dbservice->requiredcapability = empty($service['requiredcapability']) ? null : $service['requiredcapability'];
1300 $dbservice->restrictedusers = !isset($service['restrictedusers']) ? 1 : $service['restrictedusers'];
1301 $dbservice->downloadfiles = !isset($service['downloadfiles']) ? 0 : $service['downloadfiles'];
1302 $dbservice->uploadfiles = !isset($service['uploadfiles']) ? 0 : $service['uploadfiles'];
1303 $dbservice->shortname = !isset($service['shortname']) ? null : $service['shortname'];
1304 $dbservice->component = $component;
1305 $dbservice->timecreated = time();
1306 $dbservice->id = $DB->insert_record('external_services', $dbservice);
1307 foreach ($service['functions'] as $fname) {
1308 $newf = new stdClass();
1309 $newf->externalserviceid = $dbservice->id;
1310 $newf->functionname = $fname;
1311 $DB->insert_record('external_services_functions', $newf);
1317 * Allow plugins and subsystems to add external functions to other plugins or built-in services.
1318 * This function is executed just after all the plugins have been updated.
1320 function external_update_services() {
1321 global $DB;
1323 // Look for external functions that want to be added in existing services.
1324 $functions = $DB->get_records_select('external_functions', 'services IS NOT NULL');
1326 $servicescache = array();
1327 foreach ($functions as $function) {
1328 // Prevent edge cases.
1329 if (empty($function->services)) {
1330 continue;
1332 $services = explode(',', $function->services);
1334 foreach ($services as $serviceshortname) {
1335 // Get the service id by shortname.
1336 if (!empty($servicescache[$serviceshortname])) {
1337 $serviceid = $servicescache[$serviceshortname];
1338 } else if ($service = $DB->get_record('external_services', array('shortname' => $serviceshortname))) {
1339 // If the component is empty, it means that is not a built-in service.
1340 // We don't allow functions to inject themselves in services created by an user in Moodle.
1341 if (empty($service->component)) {
1342 continue;
1344 $serviceid = $service->id;
1345 $servicescache[$serviceshortname] = $serviceid;
1346 } else {
1347 // Service not found.
1348 continue;
1350 // Finally add the function to the service.
1351 $newf = new stdClass();
1352 $newf->externalserviceid = $serviceid;
1353 $newf->functionname = $function->name;
1355 if (!$DB->record_exists('external_services_functions', (array)$newf)) {
1356 $DB->insert_record('external_services_functions', $newf);
1363 * upgrade logging functions
1365 function upgrade_handle_exception($ex, $plugin = null) {
1366 global $CFG;
1368 // rollback everything, we need to log all upgrade problems
1369 abort_all_db_transactions();
1371 $info = get_exception_info($ex);
1373 // First log upgrade error
1374 upgrade_log(UPGRADE_LOG_ERROR, $plugin, 'Exception: ' . get_class($ex), $info->message, $info->backtrace);
1376 // Always turn on debugging - admins need to know what is going on
1377 set_debugging(DEBUG_DEVELOPER, true);
1379 default_exception_handler($ex, true, $plugin);
1383 * Adds log entry into upgrade_log table
1385 * @param int $type UPGRADE_LOG_NORMAL, UPGRADE_LOG_NOTICE or UPGRADE_LOG_ERROR
1386 * @param string $plugin frankenstyle component name
1387 * @param string $info short description text of log entry
1388 * @param string $details long problem description
1389 * @param string $backtrace string used for errors only
1390 * @return void
1392 function upgrade_log($type, $plugin, $info, $details=null, $backtrace=null) {
1393 global $DB, $USER, $CFG;
1395 if (empty($plugin)) {
1396 $plugin = 'core';
1399 list($plugintype, $pluginname) = core_component::normalize_component($plugin);
1400 $component = is_null($pluginname) ? $plugintype : $plugintype . '_' . $pluginname;
1402 $backtrace = format_backtrace($backtrace, true);
1404 $currentversion = null;
1405 $targetversion = null;
1407 //first try to find out current version number
1408 if ($plugintype === 'core') {
1409 //main
1410 $currentversion = $CFG->version;
1412 $version = null;
1413 include("$CFG->dirroot/version.php");
1414 $targetversion = $version;
1416 } else {
1417 $pluginversion = get_config($component, 'version');
1418 if (!empty($pluginversion)) {
1419 $currentversion = $pluginversion;
1421 $cd = core_component::get_component_directory($component);
1422 if (file_exists("$cd/version.php")) {
1423 $plugin = new stdClass();
1424 $plugin->version = null;
1425 $module = $plugin;
1426 include("$cd/version.php");
1427 $targetversion = $plugin->version;
1431 $log = new stdClass();
1432 $log->type = $type;
1433 $log->plugin = $component;
1434 $log->version = $currentversion;
1435 $log->targetversion = $targetversion;
1436 $log->info = $info;
1437 $log->details = $details;
1438 $log->backtrace = $backtrace;
1439 $log->userid = $USER->id;
1440 $log->timemodified = time();
1441 try {
1442 $DB->insert_record('upgrade_log', $log);
1443 } catch (Exception $ignored) {
1444 // possible during install or 2.0 upgrade
1449 * Marks start of upgrade, blocks any other access to site.
1450 * The upgrade is finished at the end of script or after timeout.
1452 * @global object
1453 * @global object
1454 * @global object
1456 function upgrade_started($preinstall=false) {
1457 global $CFG, $DB, $PAGE, $OUTPUT;
1459 static $started = false;
1461 if ($preinstall) {
1462 ignore_user_abort(true);
1463 upgrade_setup_debug(true);
1465 } else if ($started) {
1466 upgrade_set_timeout(120);
1468 } else {
1469 if (!CLI_SCRIPT and !$PAGE->headerprinted) {
1470 $strupgrade = get_string('upgradingversion', 'admin');
1471 $PAGE->set_pagelayout('maintenance');
1472 upgrade_init_javascript();
1473 $PAGE->set_title($strupgrade.' - Moodle '.$CFG->target_release);
1474 $PAGE->set_heading($strupgrade);
1475 $PAGE->navbar->add($strupgrade);
1476 $PAGE->set_cacheable(false);
1477 echo $OUTPUT->header();
1480 ignore_user_abort(true);
1481 core_shutdown_manager::register_function('upgrade_finished_handler');
1482 upgrade_setup_debug(true);
1483 set_config('upgraderunning', time()+300);
1484 $started = true;
1489 * Internal function - executed if upgrade interrupted.
1491 function upgrade_finished_handler() {
1492 upgrade_finished();
1496 * Indicates upgrade is finished.
1498 * This function may be called repeatedly.
1500 * @global object
1501 * @global object
1503 function upgrade_finished($continueurl=null) {
1504 global $CFG, $DB, $OUTPUT;
1506 if (!empty($CFG->upgraderunning)) {
1507 unset_config('upgraderunning');
1508 // We have to forcefully purge the caches using the writer here.
1509 // This has to be done after we unset the config var. If someone hits the site while this is set they will
1510 // cause the config values to propogate to the caches.
1511 // Caches are purged after the last step in an upgrade but there is several code routines that exceute between
1512 // then and now that leaving a window for things to fall out of sync.
1513 cache_helper::purge_all(true);
1514 upgrade_setup_debug(false);
1515 ignore_user_abort(false);
1516 if ($continueurl) {
1517 echo $OUTPUT->continue_button($continueurl);
1518 echo $OUTPUT->footer();
1519 die;
1525 * @global object
1526 * @global object
1528 function upgrade_setup_debug($starting) {
1529 global $CFG, $DB;
1531 static $originaldebug = null;
1533 if ($starting) {
1534 if ($originaldebug === null) {
1535 $originaldebug = $DB->get_debug();
1537 if (!empty($CFG->upgradeshowsql)) {
1538 $DB->set_debug(true);
1540 } else {
1541 $DB->set_debug($originaldebug);
1545 function print_upgrade_separator() {
1546 if (!CLI_SCRIPT) {
1547 echo '<hr />';
1552 * Default start upgrade callback
1553 * @param string $plugin
1554 * @param bool $installation true if installation, false means upgrade
1556 function print_upgrade_part_start($plugin, $installation, $verbose) {
1557 global $OUTPUT;
1558 if (empty($plugin) or $plugin == 'moodle') {
1559 upgrade_started($installation); // does not store upgrade running flag yet
1560 if ($verbose) {
1561 echo $OUTPUT->heading(get_string('coresystem'));
1563 } else {
1564 upgrade_started();
1565 if ($verbose) {
1566 echo $OUTPUT->heading($plugin);
1569 if ($installation) {
1570 if (empty($plugin) or $plugin == 'moodle') {
1571 // no need to log - log table not yet there ;-)
1572 } else {
1573 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Starting plugin installation');
1575 } else {
1576 core_upgrade_time::record_start();
1577 if (empty($plugin) or $plugin == 'moodle') {
1578 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Starting core upgrade');
1579 } else {
1580 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Starting plugin upgrade');
1586 * Default end upgrade callback
1587 * @param string $plugin
1588 * @param bool $installation true if installation, false means upgrade
1590 function print_upgrade_part_end($plugin, $installation, $verbose) {
1591 global $OUTPUT;
1592 upgrade_started();
1593 if ($installation) {
1594 if (empty($plugin) or $plugin == 'moodle') {
1595 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Core installed');
1596 } else {
1597 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Plugin installed');
1599 } else {
1600 if (empty($plugin) or $plugin == 'moodle') {
1601 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Core upgraded');
1602 } else {
1603 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Plugin upgraded');
1606 if ($verbose) {
1607 if ($installation) {
1608 $message = get_string('success');
1609 } else {
1610 $duration = core_upgrade_time::get_elapsed();
1611 $message = get_string('successduration', '', format_float($duration, 2));
1613 $notification = new \core\output\notification($message, \core\output\notification::NOTIFY_SUCCESS);
1614 $notification->set_show_closebutton(false);
1615 echo $OUTPUT->render($notification);
1616 print_upgrade_separator();
1621 * Sets up JS code required for all upgrade scripts.
1622 * @global object
1624 function upgrade_init_javascript() {
1625 global $PAGE;
1626 // scroll to the end of each upgrade page so that ppl see either error or continue button,
1627 // no need to scroll continuously any more, it is enough to jump to end once the footer is printed ;-)
1628 $js = "window.scrollTo(0, 5000000);";
1629 $PAGE->requires->js_init_code($js);
1633 * Try to upgrade the given language pack (or current language)
1635 * @param string $lang the code of the language to update, defaults to the current language
1637 function upgrade_language_pack($lang = null) {
1638 global $CFG;
1640 if (!empty($CFG->skiplangupgrade)) {
1641 return;
1644 if (!file_exists("$CFG->dirroot/$CFG->admin/tool/langimport/lib.php")) {
1645 // weird, somebody uninstalled the import utility
1646 return;
1649 if (!$lang) {
1650 $lang = current_language();
1653 if (!get_string_manager()->translation_exists($lang)) {
1654 return;
1657 get_string_manager()->reset_caches();
1659 if ($lang === 'en') {
1660 return; // Nothing to do
1663 upgrade_started(false);
1665 require_once("$CFG->dirroot/$CFG->admin/tool/langimport/lib.php");
1666 tool_langimport_preupgrade_update($lang);
1668 get_string_manager()->reset_caches();
1670 print_upgrade_separator();
1674 * Build the current theme so that the user doesn't have to wait for it
1675 * to build on the first page load after the install / upgrade.
1677 function upgrade_themes() {
1678 global $CFG;
1680 require_once("{$CFG->libdir}/outputlib.php");
1682 // Build the current theme so that the user can immediately
1683 // browse the site without having to wait for the theme to build.
1684 $themeconfig = theme_config::load($CFG->theme);
1685 $direction = right_to_left() ? 'rtl' : 'ltr';
1686 theme_build_css_for_themes([$themeconfig], [$direction]);
1688 // Only queue the task if there isn't already one queued.
1689 if (empty(\core\task\manager::get_adhoc_tasks('\\core\\task\\build_installed_themes_task'))) {
1690 // Queue a task to build all of the site themes at some point
1691 // later. These can happen offline because it doesn't block the
1692 // user unless they quickly change theme.
1693 $adhoctask = new \core\task\build_installed_themes_task();
1694 \core\task\manager::queue_adhoc_task($adhoctask);
1699 * Install core moodle tables and initialize
1700 * @param float $version target version
1701 * @param bool $verbose
1702 * @return void, may throw exception
1704 function install_core($version, $verbose) {
1705 global $CFG, $DB;
1707 // We can not call purge_all_caches() yet, make sure the temp and cache dirs exist and are empty.
1708 remove_dir($CFG->cachedir.'', true);
1709 make_cache_directory('', true);
1711 remove_dir($CFG->localcachedir.'', true);
1712 make_localcache_directory('', true);
1714 remove_dir($CFG->tempdir.'', true);
1715 make_temp_directory('', true);
1717 remove_dir($CFG->backuptempdir.'', true);
1718 make_backup_temp_directory('', true);
1720 remove_dir($CFG->dataroot.'/muc', true);
1721 make_writable_directory($CFG->dataroot.'/muc', true);
1723 try {
1724 core_php_time_limit::raise(600);
1725 print_upgrade_part_start('moodle', true, $verbose); // does not store upgrade running flag
1727 $DB->get_manager()->install_from_xmldb_file("$CFG->libdir/db/install.xml");
1728 upgrade_started(); // we want the flag to be stored in config table ;-)
1730 // set all core default records and default settings
1731 require_once("$CFG->libdir/db/install.php");
1732 xmldb_main_install(); // installs the capabilities too
1734 // store version
1735 upgrade_main_savepoint(true, $version, false);
1737 // Continue with the installation
1738 log_update_descriptions('moodle');
1739 external_update_descriptions('moodle');
1740 \core\task\manager::reset_scheduled_tasks_for_component('moodle');
1741 message_update_providers('moodle');
1742 \core\message\inbound\manager::update_handlers_for_component('moodle');
1743 core_tag_area::reset_definitions_for_component('moodle');
1745 // Write default settings unconditionally
1746 admin_apply_default_settings(NULL, true);
1748 print_upgrade_part_end(null, true, $verbose);
1750 // Purge all caches. They're disabled but this ensures that we don't have any persistent data just in case something
1751 // during installation didn't use APIs.
1752 cache_helper::purge_all();
1753 } catch (exception $ex) {
1754 upgrade_handle_exception($ex);
1755 } catch (Throwable $ex) {
1756 // Engine errors in PHP7 throw exceptions of type Throwable (this "catch" will be ignored in PHP5).
1757 upgrade_handle_exception($ex);
1762 * Upgrade moodle core
1763 * @param float $version target version
1764 * @param bool $verbose
1765 * @return void, may throw exception
1767 function upgrade_core($version, $verbose) {
1768 global $CFG, $SITE, $DB, $COURSE;
1770 raise_memory_limit(MEMORY_EXTRA);
1772 require_once($CFG->libdir.'/db/upgrade.php'); // Defines upgrades
1774 try {
1775 // Reset caches before any output.
1776 cache_helper::purge_all(true);
1777 purge_all_caches();
1779 // Upgrade current language pack if we can
1780 upgrade_language_pack();
1782 print_upgrade_part_start('moodle', false, $verbose);
1784 // Pre-upgrade scripts for local hack workarounds.
1785 $preupgradefile = "$CFG->dirroot/local/preupgrade.php";
1786 if (file_exists($preupgradefile)) {
1787 core_php_time_limit::raise();
1788 require($preupgradefile);
1789 // Reset upgrade timeout to default.
1790 upgrade_set_timeout();
1793 $result = xmldb_main_upgrade($CFG->version);
1794 if ($version > $CFG->version) {
1795 // store version if not already there
1796 upgrade_main_savepoint($result, $version, false);
1799 // In case structure of 'course' table has been changed and we forgot to update $SITE, re-read it from db.
1800 $SITE = $DB->get_record('course', array('id' => $SITE->id));
1801 $COURSE = clone($SITE);
1803 // perform all other component upgrade routines
1804 update_capabilities('moodle');
1805 log_update_descriptions('moodle');
1806 external_update_descriptions('moodle');
1807 \core\task\manager::reset_scheduled_tasks_for_component('moodle');
1808 message_update_providers('moodle');
1809 \core\message\inbound\manager::update_handlers_for_component('moodle');
1810 core_tag_area::reset_definitions_for_component('moodle');
1811 // Update core definitions.
1812 cache_helper::update_definitions(true);
1814 // Purge caches again, just to be sure we arn't holding onto old stuff now.
1815 cache_helper::purge_all(true);
1816 purge_all_caches();
1818 // Clean up contexts - more and more stuff depends on existence of paths and contexts
1819 context_helper::cleanup_instances();
1820 context_helper::create_instances(null, false);
1821 context_helper::build_all_paths(false);
1822 $syscontext = context_system::instance();
1823 $syscontext->mark_dirty();
1825 print_upgrade_part_end('moodle', false, $verbose);
1826 } catch (Exception $ex) {
1827 upgrade_handle_exception($ex);
1828 } catch (Throwable $ex) {
1829 // Engine errors in PHP7 throw exceptions of type Throwable (this "catch" will be ignored in PHP5).
1830 upgrade_handle_exception($ex);
1835 * Upgrade/install other parts of moodle
1836 * @param bool $verbose
1837 * @return void, may throw exception
1839 function upgrade_noncore($verbose) {
1840 global $CFG;
1842 raise_memory_limit(MEMORY_EXTRA);
1844 // upgrade all plugins types
1845 try {
1846 // Reset caches before any output.
1847 cache_helper::purge_all(true);
1848 purge_all_caches();
1850 $plugintypes = core_component::get_plugin_types();
1851 foreach ($plugintypes as $type=>$location) {
1852 upgrade_plugins($type, 'print_upgrade_part_start', 'print_upgrade_part_end', $verbose);
1854 // Upgrade services.
1855 // This function gives plugins and subsystems a chance to add functions to existing built-in services.
1856 external_update_services();
1858 // Update cache definitions. Involves scanning each plugin for any changes.
1859 cache_helper::update_definitions();
1860 // Mark the site as upgraded.
1861 set_config('allversionshash', core_component::get_all_versions_hash());
1863 // Purge caches again, just to be sure we arn't holding onto old stuff now.
1864 cache_helper::purge_all(true);
1865 purge_all_caches();
1867 } catch (Exception $ex) {
1868 upgrade_handle_exception($ex);
1869 } catch (Throwable $ex) {
1870 // Engine errors in PHP7 throw exceptions of type Throwable (this "catch" will be ignored in PHP5).
1871 upgrade_handle_exception($ex);
1876 * Checks if the main tables have been installed yet or not.
1878 * Note: we can not use caches here because they might be stale,
1879 * use with care!
1881 * @return bool
1883 function core_tables_exist() {
1884 global $DB;
1886 if (!$tables = $DB->get_tables(false) ) { // No tables yet at all.
1887 return false;
1889 } else { // Check for missing main tables
1890 $mtables = array('config', 'course', 'groupings'); // some tables used in 1.9 and 2.0, preferable something from the start and end of install.xml
1891 foreach ($mtables as $mtable) {
1892 if (!in_array($mtable, $tables)) {
1893 return false;
1896 return true;
1901 * upgrades the mnet rpc definitions for the given component.
1902 * this method doesn't return status, an exception will be thrown in the case of an error
1904 * @param string $component the plugin to upgrade, eg auth_mnet
1906 function upgrade_plugin_mnet_functions($component) {
1907 global $DB, $CFG;
1909 list($type, $plugin) = core_component::normalize_component($component);
1910 $path = core_component::get_plugin_directory($type, $plugin);
1912 $publishes = array();
1913 $subscribes = array();
1914 if (file_exists($path . '/db/mnet.php')) {
1915 require_once($path . '/db/mnet.php'); // $publishes comes from this file
1917 if (empty($publishes)) {
1918 $publishes = array(); // still need this to be able to disable stuff later
1920 if (empty($subscribes)) {
1921 $subscribes = array(); // still need this to be able to disable stuff later
1924 static $servicecache = array();
1926 // rekey an array based on the rpc method for easy lookups later
1927 $publishmethodservices = array();
1928 $subscribemethodservices = array();
1929 foreach($publishes as $servicename => $service) {
1930 if (is_array($service['methods'])) {
1931 foreach($service['methods'] as $methodname) {
1932 $service['servicename'] = $servicename;
1933 $publishmethodservices[$methodname][] = $service;
1938 // Disable functions that don't exist (any more) in the source
1939 // Should these be deleted? What about their permissions records?
1940 foreach ($DB->get_records('mnet_rpc', array('pluginname'=>$plugin, 'plugintype'=>$type), 'functionname ASC ') as $rpc) {
1941 if (!array_key_exists($rpc->functionname, $publishmethodservices) && $rpc->enabled) {
1942 $DB->set_field('mnet_rpc', 'enabled', 0, array('id' => $rpc->id));
1943 } else if (array_key_exists($rpc->functionname, $publishmethodservices) && !$rpc->enabled) {
1944 $DB->set_field('mnet_rpc', 'enabled', 1, array('id' => $rpc->id));
1948 // reflect all the services we're publishing and save them
1949 static $cachedclasses = array(); // to store reflection information in
1950 foreach ($publishes as $service => $data) {
1951 $f = $data['filename'];
1952 $c = $data['classname'];
1953 foreach ($data['methods'] as $method) {
1954 $dataobject = new stdClass();
1955 $dataobject->plugintype = $type;
1956 $dataobject->pluginname = $plugin;
1957 $dataobject->enabled = 1;
1958 $dataobject->classname = $c;
1959 $dataobject->filename = $f;
1961 if (is_string($method)) {
1962 $dataobject->functionname = $method;
1964 } else if (is_array($method)) { // wants to override file or class
1965 $dataobject->functionname = $method['method'];
1966 $dataobject->classname = $method['classname'];
1967 $dataobject->filename = $method['filename'];
1969 $dataobject->xmlrpcpath = $type.'/'.$plugin.'/'.$dataobject->filename.'/'.$method;
1970 $dataobject->static = false;
1972 require_once($path . '/' . $dataobject->filename);
1973 $functionreflect = null; // slightly different ways to get this depending on whether it's a class method or a function
1974 if (!empty($dataobject->classname)) {
1975 if (!class_exists($dataobject->classname)) {
1976 throw new moodle_exception('installnosuchmethod', 'mnet', '', (object)array('method' => $dataobject->functionname, 'class' => $dataobject->classname));
1978 $key = $dataobject->filename . '|' . $dataobject->classname;
1979 if (!array_key_exists($key, $cachedclasses)) { // look to see if we've already got a reflection object
1980 try {
1981 $cachedclasses[$key] = new ReflectionClass($dataobject->classname);
1982 } catch (ReflectionException $e) { // catch these and rethrow them to something more helpful
1983 throw new moodle_exception('installreflectionclasserror', 'mnet', '', (object)array('method' => $dataobject->functionname, 'class' => $dataobject->classname, 'error' => $e->getMessage()));
1986 $r =& $cachedclasses[$key];
1987 if (!$r->hasMethod($dataobject->functionname)) {
1988 throw new moodle_exception('installnosuchmethod', 'mnet', '', (object)array('method' => $dataobject->functionname, 'class' => $dataobject->classname));
1990 $functionreflect = $r->getMethod($dataobject->functionname);
1991 $dataobject->static = (int)$functionreflect->isStatic();
1992 } else {
1993 if (!function_exists($dataobject->functionname)) {
1994 throw new moodle_exception('installnosuchfunction', 'mnet', '', (object)array('method' => $dataobject->functionname, 'file' => $dataobject->filename));
1996 try {
1997 $functionreflect = new ReflectionFunction($dataobject->functionname);
1998 } catch (ReflectionException $e) { // catch these and rethrow them to something more helpful
1999 throw new moodle_exception('installreflectionfunctionerror', 'mnet', '', (object)array('method' => $dataobject->functionname, '' => $dataobject->filename, 'error' => $e->getMessage()));
2002 $dataobject->profile = serialize(admin_mnet_method_profile($functionreflect));
2003 $dataobject->help = admin_mnet_method_get_help($functionreflect);
2005 if ($record_exists = $DB->get_record('mnet_rpc', array('xmlrpcpath'=>$dataobject->xmlrpcpath))) {
2006 $dataobject->id = $record_exists->id;
2007 $dataobject->enabled = $record_exists->enabled;
2008 $DB->update_record('mnet_rpc', $dataobject);
2009 } else {
2010 $dataobject->id = $DB->insert_record('mnet_rpc', $dataobject, true);
2013 // TODO this API versioning must be reworked, here the recently processed method
2014 // sets the service API which may not be correct
2015 foreach ($publishmethodservices[$dataobject->functionname] as $service) {
2016 if ($serviceobj = $DB->get_record('mnet_service', array('name'=>$service['servicename']))) {
2017 $serviceobj->apiversion = $service['apiversion'];
2018 $DB->update_record('mnet_service', $serviceobj);
2019 } else {
2020 $serviceobj = new stdClass();
2021 $serviceobj->name = $service['servicename'];
2022 $serviceobj->description = empty($service['description']) ? '' : $service['description'];
2023 $serviceobj->apiversion = $service['apiversion'];
2024 $serviceobj->offer = 1;
2025 $serviceobj->id = $DB->insert_record('mnet_service', $serviceobj);
2027 $servicecache[$service['servicename']] = $serviceobj;
2028 if (!$DB->record_exists('mnet_service2rpc', array('rpcid'=>$dataobject->id, 'serviceid'=>$serviceobj->id))) {
2029 $obj = new stdClass();
2030 $obj->rpcid = $dataobject->id;
2031 $obj->serviceid = $serviceobj->id;
2032 $DB->insert_record('mnet_service2rpc', $obj, true);
2037 // finished with methods we publish, now do subscribable methods
2038 foreach($subscribes as $service => $methods) {
2039 if (!array_key_exists($service, $servicecache)) {
2040 if (!$serviceobj = $DB->get_record('mnet_service', array('name' => $service))) {
2041 debugging("TODO: skipping unknown service $service - somebody needs to fix MDL-21993");
2042 continue;
2044 $servicecache[$service] = $serviceobj;
2045 } else {
2046 $serviceobj = $servicecache[$service];
2048 foreach ($methods as $method => $xmlrpcpath) {
2049 if (!$rpcid = $DB->get_field('mnet_remote_rpc', 'id', array('xmlrpcpath'=>$xmlrpcpath))) {
2050 $remoterpc = (object)array(
2051 'functionname' => $method,
2052 'xmlrpcpath' => $xmlrpcpath,
2053 'plugintype' => $type,
2054 'pluginname' => $plugin,
2055 'enabled' => 1,
2057 $rpcid = $remoterpc->id = $DB->insert_record('mnet_remote_rpc', $remoterpc, true);
2059 if (!$DB->record_exists('mnet_remote_service2rpc', array('rpcid'=>$rpcid, 'serviceid'=>$serviceobj->id))) {
2060 $obj = new stdClass();
2061 $obj->rpcid = $rpcid;
2062 $obj->serviceid = $serviceobj->id;
2063 $DB->insert_record('mnet_remote_service2rpc', $obj, true);
2065 $subscribemethodservices[$method][] = $service;
2069 foreach ($DB->get_records('mnet_remote_rpc', array('pluginname'=>$plugin, 'plugintype'=>$type), 'functionname ASC ') as $rpc) {
2070 if (!array_key_exists($rpc->functionname, $subscribemethodservices) && $rpc->enabled) {
2071 $DB->set_field('mnet_remote_rpc', 'enabled', 0, array('id' => $rpc->id));
2072 } else if (array_key_exists($rpc->functionname, $subscribemethodservices) && !$rpc->enabled) {
2073 $DB->set_field('mnet_remote_rpc', 'enabled', 1, array('id' => $rpc->id));
2077 return true;
2081 * Given some sort of reflection function/method object, return a profile array, ready to be serialized and stored
2083 * @param ReflectionFunctionAbstract $function reflection function/method object from which to extract information
2085 * @return array associative array with function/method information
2087 function admin_mnet_method_profile(ReflectionFunctionAbstract $function) {
2088 $commentlines = admin_mnet_method_get_docblock($function);
2089 $getkey = function($key) use ($commentlines) {
2090 return array_values(array_filter($commentlines, function($line) use ($key) {
2091 return $line[0] == $key;
2092 }));
2094 $returnline = $getkey('@return');
2095 return array (
2096 'parameters' => array_map(function($line) {
2097 return array(
2098 'name' => trim($line[2], " \t\n\r\0\x0B$"),
2099 'type' => $line[1],
2100 'description' => $line[3]
2102 }, $getkey('@param')),
2104 'return' => array(
2105 'type' => !empty($returnline[0][1]) ? $returnline[0][1] : 'void',
2106 'description' => !empty($returnline[0][2]) ? $returnline[0][2] : ''
2112 * Given some sort of reflection function/method object, return an array of docblock lines, where each line is an array of
2113 * keywords/descriptions
2115 * @param ReflectionFunctionAbstract $function reflection function/method object from which to extract information
2117 * @return array docblock converted in to an array
2119 function admin_mnet_method_get_docblock(ReflectionFunctionAbstract $function) {
2120 return array_map(function($line) {
2121 $text = trim($line, " \t\n\r\0\x0B*/");
2122 if (strpos($text, '@param') === 0) {
2123 return preg_split('/\s+/', $text, 4);
2126 if (strpos($text, '@return') === 0) {
2127 return preg_split('/\s+/', $text, 3);
2130 return array($text);
2131 }, explode("\n", $function->getDocComment()));
2135 * Given some sort of reflection function/method object, return just the help text
2137 * @param ReflectionFunctionAbstract $function reflection function/method object from which to extract information
2139 * @return string docblock help text
2141 function admin_mnet_method_get_help(ReflectionFunctionAbstract $function) {
2142 $helplines = array_map(function($line) {
2143 return implode(' ', $line);
2144 }, array_values(array_filter(admin_mnet_method_get_docblock($function), function($line) {
2145 return strpos($line[0], '@') !== 0 && !empty($line[0]);
2146 })));
2148 return implode("\n", $helplines);
2152 * This function verifies that the database is not using an unsupported storage engine.
2154 * @param environment_results $result object to update, if relevant
2155 * @return environment_results|null updated results object, or null if the storage engine is supported
2157 function check_database_storage_engine(environment_results $result) {
2158 global $DB;
2160 // Check if MySQL is the DB family (this will also be the same for MariaDB).
2161 if ($DB->get_dbfamily() == 'mysql') {
2162 // Get the database engine we will either be using to install the tables, or what we are currently using.
2163 $engine = $DB->get_dbengine();
2164 // Check if MyISAM is the storage engine that will be used, if so, do not proceed and display an error.
2165 if ($engine == 'MyISAM') {
2166 $result->setInfo('unsupported_db_storage_engine');
2167 $result->setStatus(false);
2168 return $result;
2172 return null;
2176 * Method used to check the usage of slasharguments config and display a warning message.
2178 * @param environment_results $result object to update, if relevant.
2179 * @return environment_results|null updated results or null if slasharguments is disabled.
2181 function check_slasharguments(environment_results $result){
2182 global $CFG;
2184 if (!during_initial_install() && empty($CFG->slasharguments)) {
2185 $result->setInfo('slasharguments');
2186 $result->setStatus(false);
2187 return $result;
2190 return null;
2194 * This function verifies if the database has tables using innoDB Antelope row format.
2196 * @param environment_results $result
2197 * @return environment_results|null updated results object, or null if no Antelope table has been found.
2199 function check_database_tables_row_format(environment_results $result) {
2200 global $DB;
2202 if ($DB->get_dbfamily() == 'mysql') {
2203 $generator = $DB->get_manager()->generator;
2205 foreach ($DB->get_tables(false) as $table) {
2206 $columns = $DB->get_columns($table, false);
2207 $size = $generator->guess_antelope_row_size($columns);
2208 $format = $DB->get_row_format($table);
2210 if ($size <= $generator::ANTELOPE_MAX_ROW_SIZE) {
2211 continue;
2214 if ($format === 'Compact' or $format === 'Redundant') {
2215 $result->setInfo('unsupported_db_table_row_format');
2216 $result->setStatus(false);
2217 return $result;
2222 return null;
2226 * This function verfies that the database has tables using InnoDB Antelope row format.
2228 * @param environment_results $result
2229 * @return environment_results|null updated results object, or null if no Antelope table has been found.
2231 function check_mysql_file_format(environment_results $result) {
2232 global $DB;
2234 if ($DB->get_dbfamily() == 'mysql') {
2235 $collation = $DB->get_dbcollation();
2236 $collationinfo = explode('_', $collation);
2237 $charset = reset($collationinfo);
2239 if ($charset == 'utf8mb4') {
2240 if ($DB->get_row_format() !== "Barracuda") {
2241 $result->setInfo('mysql_full_unicode_support#File_format');
2242 $result->setStatus(false);
2243 return $result;
2247 return null;
2251 * This function verfies that the database has a setting of one file per table. This is required for 'utf8mb4'.
2253 * @param environment_results $result
2254 * @return environment_results|null updated results object, or null if innodb_file_per_table = 1.
2256 function check_mysql_file_per_table(environment_results $result) {
2257 global $DB;
2259 if ($DB->get_dbfamily() == 'mysql') {
2260 $collation = $DB->get_dbcollation();
2261 $collationinfo = explode('_', $collation);
2262 $charset = reset($collationinfo);
2264 if ($charset == 'utf8mb4') {
2265 if (!$DB->is_file_per_table_enabled()) {
2266 $result->setInfo('mysql_full_unicode_support#File_per_table');
2267 $result->setStatus(false);
2268 return $result;
2272 return null;
2276 * This function verfies that the database has the setting of large prefix enabled. This is required for 'utf8mb4'.
2278 * @param environment_results $result
2279 * @return environment_results|null updated results object, or null if innodb_large_prefix = 1.
2281 function check_mysql_large_prefix(environment_results $result) {
2282 global $DB;
2284 if ($DB->get_dbfamily() == 'mysql') {
2285 $collation = $DB->get_dbcollation();
2286 $collationinfo = explode('_', $collation);
2287 $charset = reset($collationinfo);
2289 if ($charset == 'utf8mb4') {
2290 if (!$DB->is_large_prefix_enabled()) {
2291 $result->setInfo('mysql_full_unicode_support#Large_prefix');
2292 $result->setStatus(false);
2293 return $result;
2297 return null;
2301 * This function checks the database to see if it is using incomplete unicode support.
2303 * @param environment_results $result $result
2304 * @return environment_results|null updated results object, or null if unicode is fully supported.
2306 function check_mysql_incomplete_unicode_support(environment_results $result) {
2307 global $DB;
2309 if ($DB->get_dbfamily() == 'mysql') {
2310 $collation = $DB->get_dbcollation();
2311 $collationinfo = explode('_', $collation);
2312 $charset = reset($collationinfo);
2314 if ($charset == 'utf8') {
2315 $result->setInfo('mysql_full_unicode_support');
2316 $result->setStatus(false);
2317 return $result;
2320 return null;
2324 * Check if the site is being served using an ssl url.
2326 * Note this does not really perform any request neither looks for proxies or
2327 * other situations. Just looks to wwwroot and warn if it's not using https.
2329 * @param environment_results $result $result
2330 * @return environment_results|null updated results object, or null if the site is https.
2332 function check_is_https(environment_results $result) {
2333 global $CFG;
2335 // Only if is defined, non-empty and whatever core tell us.
2336 if (!empty($CFG->wwwroot) && !is_https()) {
2337 $result->setInfo('site not https');
2338 $result->setStatus(false);
2339 return $result;
2341 return null;
2345 * Check if the site is using 64 bits PHP.
2347 * @param environment_results $result
2348 * @return environment_results|null updated results object, or null if the site is using 64 bits PHP.
2350 function check_sixtyfour_bits(environment_results $result) {
2352 if (PHP_INT_SIZE === 4) {
2353 $result->setInfo('php not 64 bits');
2354 $result->setStatus(false);
2355 return $result;
2357 return null;
2361 * Assert the upgrade key is provided, if it is defined.
2363 * The upgrade key can be defined in the main config.php as $CFG->upgradekey. If
2364 * it is defined there, then its value must be provided every time the site is
2365 * being upgraded, regardless the administrator is logged in or not.
2367 * This is supposed to be used at certain places in /admin/index.php only.
2369 * @param string|null $upgradekeyhash the SHA-1 of the value provided by the user
2371 function check_upgrade_key($upgradekeyhash) {
2372 global $CFG, $PAGE;
2374 if (isset($CFG->config_php_settings['upgradekey'])) {
2375 if ($upgradekeyhash === null or $upgradekeyhash !== sha1($CFG->config_php_settings['upgradekey'])) {
2376 if (!$PAGE->headerprinted) {
2377 $output = $PAGE->get_renderer('core', 'admin');
2378 echo $output->upgradekey_form_page(new moodle_url('/admin/index.php', array('cache' => 0)));
2379 die();
2380 } else {
2381 // This should not happen.
2382 die('Upgrade locked');
2389 * Helper procedure/macro for installing remote plugins at admin/index.php
2391 * Does not return, always redirects or exits.
2393 * @param array $installable list of \core\update\remote_info
2394 * @param bool $confirmed false: display the validation screen, true: proceed installation
2395 * @param string $heading validation screen heading
2396 * @param moodle_url|string|null $continue URL to proceed with installation at the validation screen
2397 * @param moodle_url|string|null $return URL to go back on cancelling at the validation screen
2399 function upgrade_install_plugins(array $installable, $confirmed, $heading='', $continue=null, $return=null) {
2400 global $CFG, $PAGE;
2402 if (empty($return)) {
2403 $return = $PAGE->url;
2406 if (!empty($CFG->disableupdateautodeploy)) {
2407 redirect($return);
2410 if (empty($installable)) {
2411 redirect($return);
2414 $pluginman = core_plugin_manager::instance();
2416 if ($confirmed) {
2417 // Installation confirmed at the validation results page.
2418 if (!$pluginman->install_plugins($installable, true, true)) {
2419 throw new moodle_exception('install_plugins_failed', 'core_plugin', $return);
2422 // Always redirect to admin/index.php to perform the database upgrade.
2423 // Do not throw away the existing $PAGE->url parameters such as
2424 // confirmupgrade or confirmrelease if $PAGE->url is a superset of the
2425 // URL we must go to.
2426 $mustgoto = new moodle_url('/admin/index.php', array('cache' => 0, 'confirmplugincheck' => 0));
2427 if ($mustgoto->compare($PAGE->url, URL_MATCH_PARAMS)) {
2428 redirect($PAGE->url);
2429 } else {
2430 redirect($mustgoto);
2433 } else {
2434 $output = $PAGE->get_renderer('core', 'admin');
2435 echo $output->header();
2436 if ($heading) {
2437 echo $output->heading($heading, 3);
2439 echo html_writer::start_tag('pre', array('class' => 'plugin-install-console'));
2440 $validated = $pluginman->install_plugins($installable, false, false);
2441 echo html_writer::end_tag('pre');
2442 if ($validated) {
2443 echo $output->plugins_management_confirm_buttons($continue, $return);
2444 } else {
2445 echo $output->plugins_management_confirm_buttons(null, $return);
2447 echo $output->footer();
2448 die();
2452 * Method used to check the installed unoconv version.
2454 * @param environment_results $result object to update, if relevant.
2455 * @return environment_results|null updated results or null if unoconv path is not executable.
2457 function check_unoconv_version(environment_results $result) {
2458 global $CFG;
2460 if (!during_initial_install() && !empty($CFG->pathtounoconv) && file_is_executable(trim($CFG->pathtounoconv))) {
2461 $currentversion = 0;
2462 $supportedversion = 0.7;
2463 $unoconvbin = \escapeshellarg($CFG->pathtounoconv);
2464 $command = "$unoconvbin --version";
2465 exec($command, $output);
2467 // If the command execution returned some output, then get the unoconv version.
2468 if ($output) {
2469 foreach ($output as $response) {
2470 if (preg_match('/unoconv (\\d+\\.\\d+)/', $response, $matches)) {
2471 $currentversion = (float)$matches[1];
2476 if ($currentversion < $supportedversion) {
2477 $result->setInfo('unoconv version not supported');
2478 $result->setStatus(false);
2479 return $result;
2482 return null;
2486 * Checks for up-to-date TLS libraries. NOTE: this is not currently used, see MDL-57262.
2488 * @param environment_results $result object to update, if relevant.
2489 * @return environment_results|null updated results or null if unoconv path is not executable.
2491 function check_tls_libraries(environment_results $result) {
2492 global $CFG;
2494 if (!function_exists('curl_version')) {
2495 $result->setInfo('cURL PHP extension is not installed');
2496 $result->setStatus(false);
2497 return $result;
2500 if (!\core\upgrade\util::validate_php_curl_tls(curl_version(), PHP_ZTS)) {
2501 $result->setInfo('invalid ssl/tls configuration');
2502 $result->setStatus(false);
2503 return $result;
2506 if (!\core\upgrade\util::can_use_tls12(curl_version(), php_uname('r'))) {
2507 $result->setInfo('ssl/tls configuration not supported');
2508 $result->setStatus(false);
2509 return $result;
2512 return null;
2516 * Check if recommended version of libcurl is installed or not.
2518 * @param environment_results $result object to update, if relevant.
2519 * @return environment_results|null updated results or null.
2521 function check_libcurl_version(environment_results $result) {
2523 if (!function_exists('curl_version')) {
2524 $result->setInfo('cURL PHP extension is not installed');
2525 $result->setStatus(false);
2526 return $result;
2529 // Supported version and version number.
2530 $supportedversion = 0x071304;
2531 $supportedversionstring = "7.19.4";
2533 // Installed version.
2534 $curlinfo = curl_version();
2535 $currentversion = $curlinfo['version_number'];
2537 if ($currentversion < $supportedversion) {
2538 // Test fail.
2539 // Set info, we want to let user know how to resolve the problem.
2540 $result->setInfo('Libcurl version check');
2541 $result->setNeededVersion($supportedversionstring);
2542 $result->setCurrentVersion($curlinfo['version']);
2543 $result->setStatus(false);
2544 return $result;
2547 return null;
2551 * Fix how auth plugins are called in the 'config_plugins' table.
2553 * For legacy reasons, the auth plugins did not always use their frankenstyle
2554 * component name in the 'plugin' column of the 'config_plugins' table. This is
2555 * a helper function to correctly migrate the legacy settings into the expected
2556 * and consistent way.
2558 * @param string $plugin the auth plugin name such as 'cas', 'manual' or 'mnet'
2560 function upgrade_fix_config_auth_plugin_names($plugin) {
2561 global $CFG, $DB, $OUTPUT;
2563 $legacy = (array) get_config('auth/'.$plugin);
2564 $current = (array) get_config('auth_'.$plugin);
2566 // I don't want to rely on array_merge() and friends here just in case
2567 // there was some crazy setting with a numerical name.
2569 if ($legacy) {
2570 $new = $legacy;
2571 } else {
2572 $new = [];
2575 if ($current) {
2576 foreach ($current as $name => $value) {
2577 if (isset($legacy[$name]) && ($legacy[$name] !== $value)) {
2578 // No need to pollute the output during unit tests.
2579 if (!empty($CFG->upgraderunning)) {
2580 $message = get_string('settingmigrationmismatch', 'core_auth', [
2581 'plugin' => 'auth_'.$plugin,
2582 'setting' => s($name),
2583 'legacy' => s($legacy[$name]),
2584 'current' => s($value),
2586 echo $OUTPUT->notification($message, \core\output\notification::NOTIFY_ERROR);
2588 upgrade_log(UPGRADE_LOG_NOTICE, 'auth_'.$plugin, 'Setting values mismatch detected',
2589 'SETTING: '.$name. ' LEGACY: '.$legacy[$name].' CURRENT: '.$value);
2593 $new[$name] = $value;
2597 foreach ($new as $name => $value) {
2598 set_config($name, $value, 'auth_'.$plugin);
2599 unset_config($name, 'auth/'.$plugin);
2604 * Populate the auth plugin settings with defaults if needed.
2606 * As a result of fixing the auth plugins config storage, many settings would
2607 * be falsely reported as new ones by admin/upgradesettings.php. We do not want
2608 * to confuse admins so we try to reduce the bewilderment by pre-populating the
2609 * config_plugins table with default values. This should be done only for
2610 * disabled auth methods. The enabled methods have their settings already
2611 * stored, so reporting actual new settings for them is valid.
2613 * @param string $plugin the auth plugin name such as 'cas', 'manual' or 'mnet'
2615 function upgrade_fix_config_auth_plugin_defaults($plugin) {
2616 global $CFG;
2618 $pluginman = core_plugin_manager::instance();
2619 $enabled = $pluginman->get_enabled_plugins('auth');
2621 if (isset($enabled[$plugin])) {
2622 // Do not touch settings of enabled auth methods.
2623 return;
2626 // We can't directly use {@link core\plugininfo\auth::load_settings()} here
2627 // because the plugins are not fully upgraded yet. Instead, we emulate what
2628 // that method does. We fetch a temporary instance of the plugin's settings
2629 // page to get access to the settings and their defaults. Note we are not
2630 // adding that temporary instance into the admin tree. Yes, this is a hack.
2632 $plugininfo = $pluginman->get_plugin_info('auth_'.$plugin);
2633 $adminroot = admin_get_root();
2634 $ADMIN = $adminroot;
2635 $auth = $plugininfo;
2637 $section = $plugininfo->get_settings_section_name();
2638 $settingspath = $plugininfo->full_path('settings.php');
2640 if (file_exists($settingspath)) {
2641 $settings = new admin_settingpage($section, 'Emulated settings page for auth_'.$plugin, 'moodle/site:config');
2642 include($settingspath);
2644 if ($settings) {
2645 admin_apply_default_settings($settings, false);
2651 * Search for a given theme in any of the parent themes of a given theme.
2653 * @param string $needle The name of the theme you want to search for
2654 * @param string $themename The name of the theme you want to search for
2655 * @param string $checkedthemeforparents The name of all the themes already checked
2656 * @return bool True if found, false if not.
2658 function upgrade_theme_is_from_family($needle, $themename, $checkedthemeforparents = []) {
2659 global $CFG;
2661 // Once we've started checking a theme, don't start checking it again. Prevent recursion.
2662 if (!empty($checkedthemeforparents[$themename])) {
2663 return false;
2665 $checkedthemeforparents[$themename] = true;
2667 if ($themename == $needle) {
2668 return true;
2671 if ($themedir = upgrade_find_theme_location($themename)) {
2672 $THEME = new stdClass();
2673 require($themedir . '/config.php');
2674 $theme = $THEME;
2675 } else {
2676 return false;
2679 if (empty($theme->parents)) {
2680 return false;
2683 // Recursively search through each parent theme.
2684 foreach ($theme->parents as $parent) {
2685 if (upgrade_theme_is_from_family($needle, $parent, $checkedthemeforparents)) {
2686 return true;
2689 return false;
2693 * Finds the theme location and verifies the theme has all needed files.
2695 * @param string $themename The name of the theme you want to search for
2696 * @return string full dir path or null if not found
2697 * @see \theme_config::find_theme_location()
2699 function upgrade_find_theme_location($themename) {
2700 global $CFG;
2702 if (file_exists("$CFG->dirroot/theme/$themename/config.php")) {
2703 $dir = "$CFG->dirroot/theme/$themename";
2704 } else if (!empty($CFG->themedir) and file_exists("$CFG->themedir/$themename/config.php")) {
2705 $dir = "$CFG->themedir/$themename";
2706 } else {
2707 return null;
2710 return $dir;