Merge branch 'MDL-81457-main' of https://github.com/andrewnicols/moodle
[moodle.git] / lib / upgradelib.php
blobf0ca4bb42ce19fd66ea003af197d2151aa287220
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 * Exception thrown when attempting to install a plugin that declares incompatibility with moodle version
90 * @package core
91 * @subpackage upgrade
92 * @copyright 2019 Peter Burnett <peterburnett@catalyst-au.net>
93 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
95 class plugin_incompatible_exception extends moodle_exception {
96 /**
97 * Constructor function for exception
99 * @param \core\plugininfo\base $plugin The plugin causing the exception
100 * @param int $pluginversion The version of the plugin causing the exception
102 public function __construct($plugin, $pluginversion) {
103 global $CFG;
104 $a = new stdClass();
105 $a->pluginname = $plugin;
106 $a->pluginversion = $pluginversion;
107 $a->moodleversion = $CFG->branch;
109 parent::__construct('pluginunsupported', 'error', "$CFG->wwwroot/$CFG->admin/index.php", $a);
114 * @package core
115 * @subpackage upgrade
116 * @copyright 2009 Petr Skoda {@link http://skodak.org}
117 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
119 class plugin_defective_exception extends moodle_exception {
120 function __construct($plugin, $details) {
121 global $CFG;
122 parent::__construct('detectedbrokenplugin', 'error', "$CFG->wwwroot/$CFG->admin/index.php", $plugin, $details);
127 * Misplaced plugin exception.
129 * Note: this should be used only from the upgrade/admin code.
131 * @package core
132 * @subpackage upgrade
133 * @copyright 2009 Petr Skoda {@link http://skodak.org}
134 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
136 class plugin_misplaced_exception extends moodle_exception {
138 * Constructor.
139 * @param string $component the component from version.php
140 * @param string $expected expected directory, null means calculate
141 * @param string $current plugin directory path
143 public function __construct($component, $expected, $current) {
144 global $CFG;
145 if (empty($expected)) {
146 list($type, $plugin) = core_component::normalize_component($component);
147 $plugintypes = core_component::get_plugin_types();
148 if (isset($plugintypes[$type])) {
149 $expected = $plugintypes[$type] . '/' . $plugin;
152 if (strpos($expected, '$CFG->dirroot') !== 0) {
153 $expected = str_replace($CFG->dirroot, '$CFG->dirroot', $expected);
155 if (strpos($current, '$CFG->dirroot') !== 0) {
156 $current = str_replace($CFG->dirroot, '$CFG->dirroot', $current);
158 $a = new stdClass();
159 $a->component = $component;
160 $a->expected = $expected;
161 $a->current = $current;
162 parent::__construct('detectedmisplacedplugin', 'core_plugin', "$CFG->wwwroot/$CFG->admin/index.php", $a);
167 * Static class monitors performance of upgrade steps.
169 class core_upgrade_time {
170 /** @var float Time at start of current upgrade (plugin/system) */
171 protected static $before;
172 /** @var float Time at end of last recorded savepoint or detail */
173 protected static $lastdetail;
174 /** @var bool Flag to indicate whether we are recording timestamps or not. */
175 protected static $isrecording = false;
176 /** @var bool Flag indicates whether this is an installation (=no savepoints) */
177 protected static $installation = false;
179 /** @var float For details, only show if they take longer than a second. */
180 const THRESHOLD = 1.0;
183 * Records current time at the start of the current upgrade item, e.g. plugin.
185 * @param bool $installation True if this is an installation (of this item) not upgrade
187 public static function record_start(bool $installation = false): void {
188 self::$before = microtime(true);
189 self::$lastdetail = self::$before;
190 self::$isrecording = true;
191 self::$installation = $installation;
195 * Records the end of the current upgrade item.
197 * @param bool $verbose If true, displays output
199 public static function record_end(bool $verbose = true): void {
200 global $OUTPUT;
202 if ($verbose) {
203 $duration = self::get_elapsed();
204 $message = get_string('successduration', '', format_float($duration, 2));
205 $notification = new \core\output\notification($message, \core\output\notification::NOTIFY_SUCCESS);
206 $notification->set_show_closebutton(false);
207 echo $OUTPUT->render($notification);
210 self::$isrecording = false;
214 * Records current time at the end of a given numbered step.
216 * @param float $version Version number (may have decimals, or not)
218 public static function record_savepoint($version) {
219 // Skip savepoints during installation because there is always exactly one and it's not
220 // interesting.
221 if (self::$installation) {
222 return;
224 // We show the time taken by each savepoint even if it's quick, because it could be useful
225 // just to see the list of upgrade steps completed, so pass $showalways = true.
226 self::record_detail($version, true);
230 * Records time taken by a detail of the install process. Time is only displayed if longer than
231 * threshold, and if in developer debug mode.
233 * @param string $detail Text e.g. file or function name
234 * @param bool $showalways If true, shows time even if quick
236 public static function record_detail(string $detail, bool $showalways = false): void {
237 global $CFG, $OUTPUT;
239 // In developer debug mode we show a notification after each detail.
240 if ($CFG->debugdeveloper && self::$isrecording) {
241 // Calculate time taken since previous detail.
242 $time = microtime(true);
243 $duration = $time - self::$lastdetail;
245 // Display the time if significant, and always for savepoints.
246 if ($duration > self::THRESHOLD || $showalways) {
247 $notification = new \core\output\notification($detail . ': ' .
248 get_string('successduration', '', format_float($duration, 2)),
249 \core\output\notification::NOTIFY_SUCCESS);
250 $notification->set_show_closebutton(false);
251 echo $OUTPUT->render($notification);
254 // Record the time.
255 self::$lastdetail = $time;
260 * Gets the time since the record_start function was called, rounded to 2 digits.
262 * @return float Elapsed time
264 public static function get_elapsed() {
265 return microtime(true) - self::$before;
270 * Sets maximum expected time needed for upgrade task.
271 * Please always make sure that upgrade will not run longer!
273 * The script may be automatically aborted if upgrade times out.
275 * @category upgrade
276 * @param int $max_execution_time in seconds (can not be less than 60 s)
278 function upgrade_set_timeout($max_execution_time=300) {
279 global $CFG;
281 // Support outageless upgrades.
282 if (defined('CLI_UPGRADE_RUNNING') && CLI_UPGRADE_RUNNING) {
283 return;
286 if (!isset($CFG->upgraderunning) or $CFG->upgraderunning < time()) {
287 $upgraderunning = get_config(null, 'upgraderunning');
288 } else {
289 $upgraderunning = $CFG->upgraderunning;
292 if (!$upgraderunning) {
293 if (CLI_SCRIPT) {
294 // never stop CLI upgrades
295 $upgraderunning = 0;
296 } else {
297 // web upgrade not running or aborted
298 throw new \moodle_exception('upgradetimedout', 'admin', "$CFG->wwwroot/$CFG->admin/");
302 if ($max_execution_time < 60) {
303 // protection against 0 here
304 $max_execution_time = 60;
307 $expected_end = time() + $max_execution_time;
309 if ($expected_end < $upgraderunning + 10 and $expected_end > $upgraderunning - 10) {
310 // no need to store new end, it is nearly the same ;-)
311 return;
314 if (CLI_SCRIPT) {
315 // there is no point in timing out of CLI scripts, admins can stop them if necessary
316 core_php_time_limit::raise();
317 } else {
318 core_php_time_limit::raise($max_execution_time);
320 set_config('upgraderunning', $expected_end); // keep upgrade locked until this time
324 * Upgrade savepoint, marks end of each upgrade block.
325 * It stores new main version, resets upgrade timeout
326 * and abort upgrade if user cancels page loading.
328 * Please do not make large upgrade blocks with lots of operations,
329 * for example when adding tables keep only one table operation per block.
331 * @category upgrade
332 * @param bool $result false if upgrade step failed, true if completed
333 * @param string or float $version main version
334 * @param bool $allowabort allow user to abort script execution here
335 * @return void
337 function upgrade_main_savepoint($result, $version, $allowabort=true) {
338 global $CFG;
340 //sanity check to avoid confusion with upgrade_mod_savepoint usage.
341 if (!is_bool($allowabort)) {
342 $errormessage = 'Parameter type mismatch. Are you mixing up upgrade_main_savepoint() and upgrade_mod_savepoint()?';
343 throw new coding_exception($errormessage);
346 if (!$result) {
347 throw new upgrade_exception(null, $version);
350 if ($CFG->version >= $version) {
351 // something really wrong is going on in main upgrade script
352 throw new downgrade_exception(null, $CFG->version, $version);
355 set_config('version', $version);
356 upgrade_log(UPGRADE_LOG_NORMAL, null, 'Upgrade savepoint reached');
358 // reset upgrade timeout to default
359 upgrade_set_timeout();
361 core_upgrade_time::record_savepoint($version);
363 // this is a safe place to stop upgrades if user aborts page loading
364 if ($allowabort and connection_aborted()) {
365 die;
370 * Module upgrade savepoint, marks end of module upgrade blocks
371 * It stores module version, resets upgrade timeout
372 * and abort upgrade if user cancels page loading.
374 * @category upgrade
375 * @param bool $result false if upgrade step failed, true if completed
376 * @param string or float $version main version
377 * @param string $modname name of module
378 * @param bool $allowabort allow user to abort script execution here
379 * @return void
381 function upgrade_mod_savepoint($result, $version, $modname, $allowabort=true) {
382 global $DB;
384 $component = 'mod_'.$modname;
386 if (!$result) {
387 throw new upgrade_exception($component, $version);
390 $dbversion = $DB->get_field('config_plugins', 'value', array('plugin'=>$component, 'name'=>'version'));
392 if (!$module = $DB->get_record('modules', array('name'=>$modname))) {
393 throw new \moodle_exception('modulenotexist', 'debug', '', $modname);
396 if ($dbversion >= $version) {
397 // something really wrong is going on in upgrade script
398 throw new downgrade_exception($component, $dbversion, $version);
400 set_config('version', $version, $component);
402 upgrade_log(UPGRADE_LOG_NORMAL, $component, 'Upgrade savepoint reached');
404 // reset upgrade timeout to default
405 upgrade_set_timeout();
407 core_upgrade_time::record_savepoint($version);
409 // this is a safe place to stop upgrades if user aborts page loading
410 if ($allowabort and connection_aborted()) {
411 die;
416 * Blocks upgrade savepoint, marks end of blocks upgrade blocks
417 * It stores block version, resets upgrade timeout
418 * and abort upgrade if user cancels page loading.
420 * @category upgrade
421 * @param bool $result false if upgrade step failed, true if completed
422 * @param string or float $version main version
423 * @param string $blockname name of block
424 * @param bool $allowabort allow user to abort script execution here
425 * @return void
427 function upgrade_block_savepoint($result, $version, $blockname, $allowabort=true) {
428 global $DB;
430 $component = 'block_'.$blockname;
432 if (!$result) {
433 throw new upgrade_exception($component, $version);
436 $dbversion = $DB->get_field('config_plugins', 'value', array('plugin'=>$component, 'name'=>'version'));
438 if (!$block = $DB->get_record('block', array('name'=>$blockname))) {
439 throw new \moodle_exception('blocknotexist', 'debug', '', $blockname);
442 if ($dbversion >= $version) {
443 // something really wrong is going on in upgrade script
444 throw new downgrade_exception($component, $dbversion, $version);
446 set_config('version', $version, $component);
448 upgrade_log(UPGRADE_LOG_NORMAL, $component, 'Upgrade savepoint reached');
450 // reset upgrade timeout to default
451 upgrade_set_timeout();
453 core_upgrade_time::record_savepoint($version);
455 // this is a safe place to stop upgrades if user aborts page loading
456 if ($allowabort and connection_aborted()) {
457 die;
462 * Plugins upgrade savepoint, marks end of blocks upgrade blocks
463 * It stores plugin version, resets upgrade timeout
464 * and abort upgrade if user cancels page loading.
466 * @category upgrade
467 * @param bool $result false if upgrade step failed, true if completed
468 * @param string or float $version main version
469 * @param string $type The type of the plugin.
470 * @param string $plugin The name of the plugin.
471 * @param bool $allowabort allow user to abort script execution here
472 * @return void
474 function upgrade_plugin_savepoint($result, $version, $type, $plugin, $allowabort=true) {
475 global $DB;
477 $component = $type.'_'.$plugin;
479 if (!$result) {
480 throw new upgrade_exception($component, $version);
483 $dbversion = $DB->get_field('config_plugins', 'value', array('plugin'=>$component, 'name'=>'version'));
485 if ($dbversion >= $version) {
486 // Something really wrong is going on in the upgrade script
487 throw new downgrade_exception($component, $dbversion, $version);
489 set_config('version', $version, $component);
490 upgrade_log(UPGRADE_LOG_NORMAL, $component, 'Upgrade savepoint reached');
492 // Reset upgrade timeout to default
493 upgrade_set_timeout();
495 core_upgrade_time::record_savepoint($version);
497 // This is a safe place to stop upgrades if user aborts page loading
498 if ($allowabort and connection_aborted()) {
499 die;
504 * Detect if there are leftovers in PHP source files.
506 * During main version upgrades administrators MUST move away
507 * old PHP source files and start from scratch (or better
508 * use git).
510 * @return bool true means borked upgrade, false means previous PHP files were properly removed
512 function upgrade_stale_php_files_present(): bool {
513 global $CFG;
515 $someexamplesofremovedfiles = [
516 // Removed in 4.4.
517 '/README.txt',
518 '/lib/dataformatlib.php',
519 '/lib/horde/readme_moodle.txt',
520 '/lib/yui/src/formchangechecker/js/formchangechecker.js',
521 '/mod/forum/pix/monologo.png',
522 '/question/tests/behat/behat_question.php',
523 // Removed in 4.3.
524 '/badges/ajax.php',
525 '/course/editdefaultcompletion.php',
526 '/grade/amd/src/searchwidget/group.js',
527 '/lib/behat/extension/Moodle/BehatExtension/Locator/FilesystemSkipPassedListLocator.php',
528 '/lib/classes/task/legacy_plugin_cron_task.php',
529 '/mod/lti/ajax.php',
530 '/pix/f/archive.png',
531 '/user/repository.php',
532 // Removed in 4.2.
533 '/admin/auth_config.php',
534 '/auth/yui/passwordunmask/passwordunmask.js',
535 '/lib/spout/readme_moodle.txt',
536 '/lib/yui/src/tooltip/js/tooltip.js',
537 // Removed in 4.1.
538 '/mod/forum/classes/task/refresh_forum_post_counts.php',
539 '/user/amd/build/participantsfilter.min.js',
540 '/user/amd/src/participantsfilter.js',
541 // Removed in 4.0.
542 '/admin/classes/task_log_table.php',
543 '/admin/cli/mysql_engine.php',
544 '/lib/babel-polyfill/polyfill.js',
545 '/lib/typo3/class.t3lib_cs.php',
546 '/question/tests/category_class_test.php',
547 // Removed in 3.11.
548 '/customfield/edit.php',
549 '/lib/phpunit/classes/autoloader.php',
550 '/lib/xhprof/README',
551 '/message/defaultoutputs.php',
552 '/user/files_form.php',
553 // Removed in 3.10.
554 '/grade/grading/classes/privacy/gradingform_provider.php',
555 '/lib/coursecatlib.php',
556 '/lib/form/htmleditor.php',
557 '/message/classes/output/messagearea/contact.php',
558 // Removed in 3.9.
559 '/course/classes/output/modchooser_item.php',
560 '/course/yui/build/moodle-course-modchooser/moodle-course-modchooser-min.js',
561 '/course/yui/src/modchooser/js/modchooser.js',
562 '/h5p/classes/autoloader.php',
563 '/lib/adodb/readme.txt',
564 '/lib/maxmind/GeoIp2/Compat/JsonSerializable.php',
565 // Removed in 3.8.
566 '/lib/amd/src/modal_confirm.js',
567 '/lib/fonts/font-awesome-4.7.0/css/font-awesome.css',
568 '/lib/jquery/jquery-3.2.1.min.js',
569 '/lib/recaptchalib.php',
570 '/lib/sessionkeepalive_ajax.php',
571 '/lib/yui/src/checknet/js/checknet.js',
572 '/question/amd/src/qbankmanager.js',
573 // Removed in 3.7.
574 '/lib/form/yui/src/showadvanced/js/showadvanced.js',
575 '/lib/tests/output_external_test.php',
576 '/message/amd/src/message_area.js',
577 '/message/templates/message_area.mustache',
578 '/question/yui/src/qbankmanager/build.json',
579 // Removed in 3.6.
580 '/lib/classes/session/memcache.php',
581 '/lib/eventslib.php',
582 '/lib/form/submitlink.php',
583 '/lib/medialib.php',
584 '/lib/password_compat/lib/password.php',
585 // Removed in 3.5.
586 '/lib/dml/mssql_native_moodle_database.php',
587 '/lib/dml/mssql_native_moodle_recordset.php',
588 '/lib/dml/mssql_native_moodle_temptables.php',
589 // Removed in 3.4.
590 '/auth/README.txt',
591 '/calendar/set.php',
592 '/enrol/users.php',
593 '/enrol/yui/rolemanager/assets/skins/sam/rolemanager.css',
594 // Removed in 3.3.
595 '/badges/backpackconnect.php',
596 '/calendar/yui/src/info/assets/skins/sam/moodle-calendar-info.css',
597 '/competency/classes/external/exporter.php',
598 '/mod/forum/forum.js',
599 '/user/pixgroup.php',
600 // Removed in 3.2.
601 '/calendar/preferences.php',
602 '/lib/alfresco/',
603 '/lib/jquery/jquery-1.12.1.min.js',
604 '/lib/password_compat/tests/',
605 '/lib/phpunit/classes/unittestcase.php',
606 // Removed in 3.1.
607 '/lib/classes/log/sql_internal_reader.php',
608 '/lib/zend/',
609 '/mod/forum/pix/icon.gif',
610 '/tag/templates/tagname.mustache',
611 // Removed in 3.0.
612 '/tag/coursetagslib.php',
613 // Removed in 2.9.
614 '/lib/timezone.txt',
615 // Removed in 2.8.
616 '/course/delete_category_form.php',
617 // Removed in 2.7.
618 '/admin/tool/qeupgradehelper/version.php',
619 // Removed in 2.6.
620 '/admin/block.php',
621 '/admin/oacleanup.php',
622 // Removed in 2.5.
623 '/backup/lib.php',
624 '/backup/bb/README.txt',
625 '/lib/excel/test.php',
626 // Removed in 2.4.
627 '/admin/tool/unittest/simpletestlib.php',
628 // Removed in 2.3.
629 '/lib/minify/builder/',
630 // Removed in 2.2.
631 '/lib/yui/3.4.1pr1/',
632 // Removed in 2.2.
633 '/search/cron_php5.php',
634 '/course/report/log/indexlive.php',
635 '/admin/report/backups/index.php',
636 '/admin/generator.php',
637 // Removed in 2.1.
638 '/lib/yui/2.8.0r4/',
639 // Removed in 2.0.
640 '/blocks/admin/block_admin.php',
641 '/blocks/admin_tree/block_admin_tree.php',
644 foreach ($someexamplesofremovedfiles as $file) {
645 if (file_exists($CFG->dirroot.$file)) {
646 return true;
650 return false;
654 * After upgrading a module, block, or generic plugin, various parts of the system need to be
655 * informed.
657 * @param string $component Frankenstyle component or 'moodle' for core
658 * @param string $messageplug Set to the name of a message plugin if this is one
659 * @param bool $coreinstall Set to true if this is the core install
661 function upgrade_component_updated(string $component, string $messageplug = '',
662 bool $coreinstall = false): void {
663 if (!$coreinstall) {
664 update_capabilities($component);
665 core_upgrade_time::record_detail('update_capabilities');
667 log_update_descriptions($component);
668 core_upgrade_time::record_detail('log_update_descriptions');
669 external_update_descriptions($component);
670 core_upgrade_time::record_detail('external_update_descriptions');
671 \core\task\manager::reset_scheduled_tasks_for_component($component);
672 core_upgrade_time::record_detail('\core\task\manager::reset_scheduled_tasks_for_component');
673 \core_analytics\manager::update_default_models_for_component($component);
674 core_upgrade_time::record_detail('\core_analytics\manager::update_default_models_for_component');
675 message_update_providers($component);
676 core_upgrade_time::record_detail('message_update_providers');
677 \core\message\inbound\manager::update_handlers_for_component($component);
678 core_upgrade_time::record_detail('\core\message\inbound\manager::update_handlers_for_component');
679 if ($messageplug !== '') {
680 // Ugly hack!
681 message_update_processors($messageplug);
682 core_upgrade_time::record_detail('message_update_processors');
684 if ($component !== 'moodle') {
685 // This one is not run for core upgrades.
686 upgrade_plugin_mnet_functions($component);
687 core_upgrade_time::record_detail('upgrade_plugin_mnet_functions');
689 core_tag_area::reset_definitions_for_component($component);
690 core_upgrade_time::record_detail('core_tag_area::reset_definitions_for_component');
694 * Upgrade plugins
695 * @param string $type The type of plugins that should be updated (e.g. 'enrol', 'qtype')
696 * return void
698 function upgrade_plugins($type, $startcallback, $endcallback, $verbose) {
699 global $CFG, $DB;
701 /// special cases
702 if ($type === 'mod') {
703 return upgrade_plugins_modules($startcallback, $endcallback, $verbose);
704 } else if ($type === 'block') {
705 return upgrade_plugins_blocks($startcallback, $endcallback, $verbose);
708 $plugs = core_component::get_plugin_list($type);
710 foreach ($plugs as $plug=>$fullplug) {
711 // Reset time so that it works when installing a large number of plugins
712 core_php_time_limit::raise(600);
713 $component = clean_param($type.'_'.$plug, PARAM_COMPONENT); // standardised plugin name
715 // check plugin dir is valid name
716 if (empty($component)) {
717 throw new plugin_defective_exception($type.'_'.$plug, 'Invalid plugin directory name.');
720 if (!is_readable($fullplug.'/version.php')) {
721 continue;
724 $plugin = new stdClass();
725 $plugin->version = null;
726 $module = $plugin; // Prevent some notices when plugin placed in wrong directory.
727 require($fullplug.'/version.php'); // defines $plugin with version etc
728 unset($module);
730 if (empty($plugin->version)) {
731 throw new plugin_defective_exception($component, 'Missing $plugin->version number in version.php.');
734 if (empty($plugin->component)) {
735 throw new plugin_defective_exception($component, 'Missing $plugin->component declaration in version.php.');
738 if ($plugin->component !== $component) {
739 throw new plugin_misplaced_exception($plugin->component, null, $fullplug);
742 $plugin->name = $plug;
743 $plugin->fullname = $component;
745 if (!empty($plugin->requires)) {
746 if ($plugin->requires > $CFG->version) {
747 throw new upgrade_requires_exception($component, $plugin->version, $CFG->version, $plugin->requires);
748 } else if ($plugin->requires < 2010000000) {
749 throw new plugin_defective_exception($component, 'Plugin is not compatible with Moodle 2.x or later.');
753 // Throw exception if plugin is incompatible with moodle version.
754 if (!empty($plugin->incompatible)) {
755 if ($CFG->branch >= $plugin->incompatible) {
756 throw new plugin_incompatible_exception($component, $plugin->version);
760 // try to recover from interrupted install.php if needed
761 if (file_exists($fullplug.'/db/install.php')) {
762 if (get_config($plugin->fullname, 'installrunning')) {
763 require_once($fullplug.'/db/install.php');
764 $recover_install_function = 'xmldb_'.$plugin->fullname.'_install_recovery';
765 if (function_exists($recover_install_function)) {
766 $startcallback($component, true, $verbose);
767 $recover_install_function();
768 unset_config('installrunning', $plugin->fullname);
769 upgrade_component_updated($component, $type === 'message' ? $plug : '');
770 $endcallback($component, true, $verbose);
775 $installedversion = $DB->get_field('config_plugins', 'value', array('name'=>'version', 'plugin'=>$component)); // No caching!
776 if (empty($installedversion)) { // new installation
777 $startcallback($component, true, $verbose);
779 /// Install tables if defined
780 if (file_exists($fullplug.'/db/install.xml')) {
781 $DB->get_manager()->install_from_xmldb_file($fullplug.'/db/install.xml');
782 core_upgrade_time::record_detail('install.xml');
785 /// store version
786 upgrade_plugin_savepoint(true, $plugin->version, $type, $plug, false);
788 /// execute post install file
789 if (file_exists($fullplug.'/db/install.php')) {
790 require_once($fullplug.'/db/install.php');
791 set_config('installrunning', 1, $plugin->fullname);
792 $post_install_function = 'xmldb_'.$plugin->fullname.'_install';
793 $post_install_function();
794 unset_config('installrunning', $plugin->fullname);
795 core_upgrade_time::record_detail('install.php');
798 /// Install various components
799 upgrade_component_updated($component, $type === 'message' ? $plug : '');
800 $endcallback($component, true, $verbose);
802 } else if ($installedversion < $plugin->version) { // upgrade
803 /// Run the upgrade function for the plugin.
804 $startcallback($component, false, $verbose);
806 if (is_readable($fullplug.'/db/upgrade.php')) {
807 require_once($fullplug.'/db/upgrade.php'); // defines upgrading function
809 $newupgrade_function = 'xmldb_'.$plugin->fullname.'_upgrade';
810 $result = $newupgrade_function($installedversion);
811 core_upgrade_time::record_detail('upgrade.php');
812 } else {
813 $result = true;
816 $installedversion = $DB->get_field('config_plugins', 'value', array('name'=>'version', 'plugin'=>$component)); // No caching!
817 if ($installedversion < $plugin->version) {
818 // store version if not already there
819 upgrade_plugin_savepoint($result, $plugin->version, $type, $plug, false);
822 /// Upgrade various components
823 upgrade_component_updated($component, $type === 'message' ? $plug : '');
824 $endcallback($component, false, $verbose);
826 } else if ($installedversion > $plugin->version) {
827 throw new downgrade_exception($component, $installedversion, $plugin->version);
833 * Find and check all modules and load them up or upgrade them if necessary
835 * @global object
836 * @global object
838 function upgrade_plugins_modules($startcallback, $endcallback, $verbose) {
839 global $CFG, $DB;
841 $mods = core_component::get_plugin_list('mod');
843 foreach ($mods as $mod=>$fullmod) {
845 if ($mod === 'NEWMODULE') { // Someone has unzipped the template, ignore it
846 continue;
849 $component = clean_param('mod_'.$mod, PARAM_COMPONENT);
851 // check module dir is valid name
852 if (empty($component)) {
853 throw new plugin_defective_exception('mod_'.$mod, 'Invalid plugin directory name.');
856 if (!is_readable($fullmod.'/version.php')) {
857 throw new plugin_defective_exception($component, 'Missing version.php');
860 $module = new stdClass();
861 $plugin = new stdClass();
862 $plugin->version = null;
863 require($fullmod .'/version.php'); // Defines $plugin with version etc.
865 // Check if the legacy $module syntax is still used.
866 if (!is_object($module) or (count((array)$module) > 0)) {
867 throw new plugin_defective_exception($component, 'Unsupported $module syntax detected in version.php');
870 // Prepare the record for the {modules} table.
871 $module = clone($plugin);
872 unset($module->version);
873 unset($module->component);
874 unset($module->dependencies);
875 unset($module->release);
877 if (empty($plugin->version)) {
878 throw new plugin_defective_exception($component, 'Missing $plugin->version number in version.php.');
881 if (empty($plugin->component)) {
882 throw new plugin_defective_exception($component, 'Missing $plugin->component declaration in version.php.');
885 if ($plugin->component !== $component) {
886 throw new plugin_misplaced_exception($plugin->component, null, $fullmod);
889 if (!empty($plugin->requires)) {
890 if ($plugin->requires > $CFG->version) {
891 throw new upgrade_requires_exception($component, $plugin->version, $CFG->version, $plugin->requires);
892 } else if ($plugin->requires < 2010000000) {
893 throw new plugin_defective_exception($component, 'Plugin is not compatible with Moodle 2.x or later.');
897 if (empty($module->cron)) {
898 $module->cron = 0;
901 // all modules must have en lang pack
902 if (!is_readable("$fullmod/lang/en/$mod.php")) {
903 throw new plugin_defective_exception($component, 'Missing mandatory en language pack.');
906 $module->name = $mod; // The name MUST match the directory
908 $installedversion = $DB->get_field('config_plugins', 'value', array('name'=>'version', 'plugin'=>$component)); // No caching!
910 if (file_exists($fullmod.'/db/install.php')) {
911 if (get_config($module->name, 'installrunning')) {
912 require_once($fullmod.'/db/install.php');
913 $recover_install_function = 'xmldb_'.$module->name.'_install_recovery';
914 if (function_exists($recover_install_function)) {
915 $startcallback($component, true, $verbose);
916 $recover_install_function();
917 unset_config('installrunning', $module->name);
918 // Install various components too
919 upgrade_component_updated($component);
920 $endcallback($component, true, $verbose);
925 if (empty($installedversion)) {
926 $startcallback($component, true, $verbose);
928 /// Execute install.xml (XMLDB) - must be present in all modules
929 $DB->get_manager()->install_from_xmldb_file($fullmod.'/db/install.xml');
930 core_upgrade_time::record_detail('install.xml');
932 /// Add record into modules table - may be needed in install.php already
933 $module->id = $DB->insert_record('modules', $module);
934 core_upgrade_time::record_detail('insert_record');
935 upgrade_mod_savepoint(true, $plugin->version, $module->name, false);
937 /// Post installation hook - optional
938 if (file_exists("$fullmod/db/install.php")) {
939 require_once("$fullmod/db/install.php");
940 // Set installation running flag, we need to recover after exception or error
941 set_config('installrunning', 1, $module->name);
942 $post_install_function = 'xmldb_'.$module->name.'_install';
943 $post_install_function();
944 unset_config('installrunning', $module->name);
945 core_upgrade_time::record_detail('install.php');
948 /// Install various components
949 upgrade_component_updated($component);
951 $endcallback($component, true, $verbose);
953 } else if ($installedversion < $plugin->version) {
954 /// If versions say that we need to upgrade but no upgrade files are available, notify and continue
955 $startcallback($component, false, $verbose);
957 if (is_readable($fullmod.'/db/upgrade.php')) {
958 require_once($fullmod.'/db/upgrade.php'); // defines new upgrading function
959 $newupgrade_function = 'xmldb_'.$module->name.'_upgrade';
960 $result = $newupgrade_function($installedversion, $module);
961 core_upgrade_time::record_detail('upgrade.php');
962 } else {
963 $result = true;
966 $installedversion = $DB->get_field('config_plugins', 'value', array('name'=>'version', 'plugin'=>$component)); // No caching!
967 $currmodule = $DB->get_record('modules', array('name'=>$module->name));
968 if ($installedversion < $plugin->version) {
969 // store version if not already there
970 upgrade_mod_savepoint($result, $plugin->version, $mod, false);
973 // update cron flag if needed
974 if ($currmodule->cron != $module->cron) {
975 $DB->set_field('modules', 'cron', $module->cron, array('name' => $module->name));
978 // Upgrade various components
979 upgrade_component_updated($component);
981 $endcallback($component, false, $verbose);
983 } else if ($installedversion > $plugin->version) {
984 throw new downgrade_exception($component, $installedversion, $plugin->version);
991 * This function finds all available blocks and install them
992 * into blocks table or do all the upgrade process if newer.
994 * @global object
995 * @global object
997 function upgrade_plugins_blocks($startcallback, $endcallback, $verbose) {
998 global $CFG, $DB;
1000 require_once($CFG->dirroot.'/blocks/moodleblock.class.php');
1002 $blocktitles = array(); // we do not want duplicate titles
1004 //Is this a first install
1005 $first_install = null;
1007 $blocks = core_component::get_plugin_list('block');
1009 foreach ($blocks as $blockname=>$fullblock) {
1011 if (is_null($first_install)) {
1012 $first_install = ($DB->count_records('block_instances') == 0);
1015 if ($blockname === 'NEWBLOCK') { // Someone has unzipped the template, ignore it
1016 continue;
1019 $component = clean_param('block_'.$blockname, PARAM_COMPONENT);
1021 // check block dir is valid name
1022 if (empty($component)) {
1023 throw new plugin_defective_exception('block_'.$blockname, 'Invalid plugin directory name.');
1026 if (!is_readable($fullblock.'/version.php')) {
1027 throw new plugin_defective_exception('block/'.$blockname, 'Missing version.php file.');
1029 $plugin = new stdClass();
1030 $plugin->version = null;
1031 $plugin->cron = 0;
1032 $module = $plugin; // Prevent some notices when module placed in wrong directory.
1033 include($fullblock.'/version.php');
1034 unset($module);
1035 $block = clone($plugin);
1036 unset($block->version);
1037 unset($block->component);
1038 unset($block->dependencies);
1039 unset($block->release);
1041 if (empty($plugin->version)) {
1042 throw new plugin_defective_exception($component, 'Missing block version number in version.php.');
1045 if (empty($plugin->component)) {
1046 throw new plugin_defective_exception($component, 'Missing $plugin->component declaration in version.php.');
1049 if ($plugin->component !== $component) {
1050 throw new plugin_misplaced_exception($plugin->component, null, $fullblock);
1053 if (!empty($plugin->requires)) {
1054 if ($plugin->requires > $CFG->version) {
1055 throw new upgrade_requires_exception($component, $plugin->version, $CFG->version, $plugin->requires);
1056 } else if ($plugin->requires < 2010000000) {
1057 throw new plugin_defective_exception($component, 'Plugin is not compatible with Moodle 2.x or later.');
1061 if (!is_readable($fullblock.'/block_'.$blockname.'.php')) {
1062 throw new plugin_defective_exception('block/'.$blockname, 'Missing main block class file.');
1064 include_once($fullblock.'/block_'.$blockname.'.php');
1066 $classname = 'block_'.$blockname;
1068 if (!class_exists($classname)) {
1069 throw new plugin_defective_exception($component, 'Can not load main class.');
1072 $blockobj = new $classname; // This is what we'll be testing
1073 $blocktitle = $blockobj->get_title();
1075 // OK, it's as we all hoped. For further tests, the object will do them itself.
1076 if (!$blockobj->_self_test()) {
1077 throw new plugin_defective_exception($component, 'Self test failed.');
1080 $block->name = $blockname; // The name MUST match the directory
1082 $installedversion = $DB->get_field('config_plugins', 'value', array('name'=>'version', 'plugin'=>$component)); // No caching!
1084 if (file_exists($fullblock.'/db/install.php')) {
1085 if (get_config('block_'.$blockname, 'installrunning')) {
1086 require_once($fullblock.'/db/install.php');
1087 $recover_install_function = 'xmldb_block_'.$blockname.'_install_recovery';
1088 if (function_exists($recover_install_function)) {
1089 $startcallback($component, true, $verbose);
1090 $recover_install_function();
1091 unset_config('installrunning', 'block_'.$blockname);
1092 // Install various components
1093 upgrade_component_updated($component);
1094 $endcallback($component, true, $verbose);
1099 if (empty($installedversion)) { // block not installed yet, so install it
1100 $conflictblock = array_search($blocktitle, $blocktitles);
1101 if ($conflictblock !== false) {
1102 // Duplicate block titles are not allowed, they confuse people
1103 // AND PHP's associative arrays ;)
1104 throw new plugin_defective_exception($component, get_string('blocknameconflict', 'error', (object)array('name'=>$block->name, 'conflict'=>$conflictblock)));
1106 $startcallback($component, true, $verbose);
1108 if (file_exists($fullblock.'/db/install.xml')) {
1109 $DB->get_manager()->install_from_xmldb_file($fullblock.'/db/install.xml');
1110 core_upgrade_time::record_detail('install.xml');
1112 $block->id = $DB->insert_record('block', $block);
1113 core_upgrade_time::record_detail('insert_record');
1114 upgrade_block_savepoint(true, $plugin->version, $block->name, false);
1116 if (file_exists($fullblock.'/db/install.php')) {
1117 require_once($fullblock.'/db/install.php');
1118 // Set installation running flag, we need to recover after exception or error
1119 set_config('installrunning', 1, 'block_'.$blockname);
1120 $post_install_function = 'xmldb_block_'.$blockname.'_install';
1121 $post_install_function();
1122 unset_config('installrunning', 'block_'.$blockname);
1123 core_upgrade_time::record_detail('install.php');
1126 $blocktitles[$block->name] = $blocktitle;
1128 // Install various components
1129 upgrade_component_updated($component);
1131 $endcallback($component, true, $verbose);
1133 } else if ($installedversion < $plugin->version) {
1134 $startcallback($component, false, $verbose);
1136 if (is_readable($fullblock.'/db/upgrade.php')) {
1137 require_once($fullblock.'/db/upgrade.php'); // defines new upgrading function
1138 $newupgrade_function = 'xmldb_block_'.$blockname.'_upgrade';
1139 $result = $newupgrade_function($installedversion, $block);
1140 core_upgrade_time::record_detail('upgrade.php');
1141 } else {
1142 $result = true;
1145 $installedversion = $DB->get_field('config_plugins', 'value', array('name'=>'version', 'plugin'=>$component)); // No caching!
1146 $currblock = $DB->get_record('block', array('name'=>$block->name));
1147 if ($installedversion < $plugin->version) {
1148 // store version if not already there
1149 upgrade_block_savepoint($result, $plugin->version, $block->name, false);
1152 if ($currblock->cron != $block->cron) {
1153 // update cron flag if needed
1154 $DB->set_field('block', 'cron', $block->cron, array('id' => $currblock->id));
1157 // Upgrade various components
1158 upgrade_component_updated($component);
1160 $endcallback($component, false, $verbose);
1162 } else if ($installedversion > $plugin->version) {
1163 throw new downgrade_exception($component, $installedversion, $plugin->version);
1168 // Finally, if we are in the first_install of BLOCKS setup frontpage and admin page blocks
1169 if ($first_install) {
1170 //Iterate over each course - there should be only site course here now
1171 if ($courses = $DB->get_records('course')) {
1172 foreach ($courses as $course) {
1173 blocks_add_default_course_blocks($course);
1177 blocks_add_default_system_blocks();
1183 * Log_display description function used during install and upgrade.
1185 * @param string $component name of component (moodle, etc.)
1186 * @return void
1188 function log_update_descriptions($component) {
1189 global $DB;
1191 $defpath = core_component::get_component_directory($component).'/db/log.php';
1193 if (!file_exists($defpath)) {
1194 $DB->delete_records('log_display', array('component'=>$component));
1195 return;
1198 // load new info
1199 $logs = array();
1200 include($defpath);
1201 $newlogs = array();
1202 foreach ($logs as $log) {
1203 $newlogs[$log['module'].'-'.$log['action']] = $log; // kind of unique name
1205 unset($logs);
1206 $logs = $newlogs;
1208 $fields = array('module', 'action', 'mtable', 'field');
1209 // update all log fist
1210 $dblogs = $DB->get_records('log_display', array('component'=>$component));
1211 foreach ($dblogs as $dblog) {
1212 $name = $dblog->module.'-'.$dblog->action;
1214 if (empty($logs[$name])) {
1215 $DB->delete_records('log_display', array('id'=>$dblog->id));
1216 continue;
1219 $log = $logs[$name];
1220 unset($logs[$name]);
1222 $update = false;
1223 foreach ($fields as $field) {
1224 if ($dblog->$field != $log[$field]) {
1225 $dblog->$field = $log[$field];
1226 $update = true;
1229 if ($update) {
1230 $DB->update_record('log_display', $dblog);
1233 foreach ($logs as $log) {
1234 $dblog = (object)$log;
1235 $dblog->component = $component;
1236 $DB->insert_record('log_display', $dblog);
1241 * Web service discovery function used during install and upgrade.
1242 * @param string $component name of component (moodle, etc.)
1243 * @return void
1245 function external_update_descriptions($component) {
1246 global $DB, $CFG;
1248 $defpath = core_component::get_component_directory($component).'/db/services.php';
1250 if (!file_exists($defpath)) {
1251 \core_external\util::delete_service_descriptions($component);
1252 return;
1255 // load new info
1256 $functions = array();
1257 $services = array();
1258 include($defpath);
1260 // update all function fist
1261 $dbfunctions = $DB->get_records('external_functions', array('component'=>$component));
1262 foreach ($dbfunctions as $dbfunction) {
1263 if (empty($functions[$dbfunction->name])) {
1264 $DB->delete_records('external_functions', array('id'=>$dbfunction->id));
1265 // do not delete functions from external_services_functions, beacuse
1266 // we want to notify admins when functions used in custom services disappear
1268 //TODO: this looks wrong, we have to delete it eventually (skodak)
1269 continue;
1272 $function = $functions[$dbfunction->name];
1273 unset($functions[$dbfunction->name]);
1274 $function['classpath'] = empty($function['classpath']) ? null : $function['classpath'];
1275 $function['methodname'] = $function['methodname'] ?? 'execute';
1277 $update = false;
1278 if ($dbfunction->classname != $function['classname']) {
1279 $dbfunction->classname = $function['classname'];
1280 $update = true;
1282 if ($dbfunction->methodname != $function['methodname']) {
1283 $dbfunction->methodname = $function['methodname'];
1284 $update = true;
1286 if ($dbfunction->classpath != $function['classpath']) {
1287 $dbfunction->classpath = $function['classpath'];
1288 $update = true;
1290 $functioncapabilities = array_key_exists('capabilities', $function)?$function['capabilities']:'';
1291 if ($dbfunction->capabilities != $functioncapabilities) {
1292 $dbfunction->capabilities = $functioncapabilities;
1293 $update = true;
1296 if (isset($function['services']) and is_array($function['services'])) {
1297 sort($function['services']);
1298 $functionservices = implode(',', $function['services']);
1299 } else {
1300 // Force null values in the DB.
1301 $functionservices = null;
1304 if ($dbfunction->services != $functionservices) {
1305 // Now, we need to check if services were removed, in that case we need to remove the function from them.
1306 $oldservices = $dbfunction->services ? explode(',', $dbfunction->services) : [];
1307 $newservices = $functionservices ? explode(',', $functionservices) : [];
1308 $servicesremoved = array_diff($oldservices, $newservices);
1309 foreach ($servicesremoved as $removedshortname) {
1310 if ($externalserviceid = $DB->get_field('external_services', 'id', array("shortname" => $removedshortname))) {
1311 $DB->delete_records('external_services_functions', array('functionname' => $dbfunction->name,
1312 'externalserviceid' => $externalserviceid));
1316 $dbfunction->services = $functionservices;
1317 $update = true;
1319 if ($update) {
1320 $DB->update_record('external_functions', $dbfunction);
1323 foreach ($functions as $fname => $function) {
1324 $dbfunction = new stdClass();
1325 $dbfunction->name = $fname;
1326 $dbfunction->classname = $function['classname'];
1327 $dbfunction->methodname = $function['methodname'] ?? 'execute';
1328 $dbfunction->classpath = empty($function['classpath']) ? null : $function['classpath'];
1329 $dbfunction->component = $component;
1330 $dbfunction->capabilities = array_key_exists('capabilities', $function)?$function['capabilities']:'';
1332 if (isset($function['services']) and is_array($function['services'])) {
1333 sort($function['services']);
1334 $dbfunction->services = implode(',', $function['services']);
1335 } else {
1336 // Force null values in the DB.
1337 $dbfunction->services = null;
1340 $dbfunction->id = $DB->insert_record('external_functions', $dbfunction);
1342 unset($functions);
1344 // now deal with services
1345 $dbservices = $DB->get_records('external_services', array('component'=>$component));
1346 foreach ($dbservices as $dbservice) {
1347 if (empty($services[$dbservice->name])) {
1348 $DB->delete_records('external_tokens', array('externalserviceid'=>$dbservice->id));
1349 $DB->delete_records('external_services_functions', array('externalserviceid'=>$dbservice->id));
1350 $DB->delete_records('external_services_users', array('externalserviceid'=>$dbservice->id));
1351 $DB->delete_records('external_services', array('id'=>$dbservice->id));
1352 continue;
1354 $service = $services[$dbservice->name];
1355 unset($services[$dbservice->name]);
1356 $service['enabled'] = empty($service['enabled']) ? 0 : $service['enabled'];
1357 $service['requiredcapability'] = empty($service['requiredcapability']) ? null : $service['requiredcapability'];
1358 $service['restrictedusers'] = !isset($service['restrictedusers']) ? 1 : $service['restrictedusers'];
1359 $service['downloadfiles'] = !isset($service['downloadfiles']) ? 0 : $service['downloadfiles'];
1360 $service['uploadfiles'] = !isset($service['uploadfiles']) ? 0 : $service['uploadfiles'];
1361 $service['shortname'] = !isset($service['shortname']) ? null : $service['shortname'];
1363 $update = false;
1364 if ($dbservice->requiredcapability != $service['requiredcapability']) {
1365 $dbservice->requiredcapability = $service['requiredcapability'];
1366 $update = true;
1368 if ($dbservice->restrictedusers != $service['restrictedusers']) {
1369 $dbservice->restrictedusers = $service['restrictedusers'];
1370 $update = true;
1372 if ($dbservice->downloadfiles != $service['downloadfiles']) {
1373 $dbservice->downloadfiles = $service['downloadfiles'];
1374 $update = true;
1376 if ($dbservice->uploadfiles != $service['uploadfiles']) {
1377 $dbservice->uploadfiles = $service['uploadfiles'];
1378 $update = true;
1380 //if shortname is not a PARAM_ALPHANUMEXT, fail (tested here for service update and creation)
1381 if (isset($service['shortname']) and
1382 (clean_param($service['shortname'], PARAM_ALPHANUMEXT) != $service['shortname'])) {
1383 throw new moodle_exception('installserviceshortnameerror', 'webservice', '', $service['shortname']);
1385 if ($dbservice->shortname != $service['shortname']) {
1386 //check that shortname is unique
1387 if (isset($service['shortname'])) { //we currently accepts multiple shortname == null
1388 $existingservice = $DB->get_record('external_services',
1389 array('shortname' => $service['shortname']));
1390 if (!empty($existingservice)) {
1391 throw new moodle_exception('installexistingserviceshortnameerror', 'webservice', '', $service['shortname']);
1394 $dbservice->shortname = $service['shortname'];
1395 $update = true;
1397 if ($update) {
1398 $DB->update_record('external_services', $dbservice);
1401 $functions = $DB->get_records('external_services_functions', array('externalserviceid'=>$dbservice->id));
1402 foreach ($functions as $function) {
1403 $key = array_search($function->functionname, $service['functions']);
1404 if ($key === false) {
1405 $DB->delete_records('external_services_functions', array('id'=>$function->id));
1406 } else {
1407 unset($service['functions'][$key]);
1410 foreach ($service['functions'] as $fname) {
1411 $newf = new stdClass();
1412 $newf->externalserviceid = $dbservice->id;
1413 $newf->functionname = $fname;
1414 $DB->insert_record('external_services_functions', $newf);
1416 unset($functions);
1418 foreach ($services as $name => $service) {
1419 //check that shortname is unique
1420 if (isset($service['shortname'])) { //we currently accepts multiple shortname == null
1421 $existingservice = $DB->get_record('external_services',
1422 array('shortname' => $service['shortname']));
1423 if (!empty($existingservice)) {
1424 throw new moodle_exception('installserviceshortnameerror', 'webservice');
1428 $dbservice = new stdClass();
1429 $dbservice->name = $name;
1430 $dbservice->enabled = empty($service['enabled']) ? 0 : $service['enabled'];
1431 $dbservice->requiredcapability = empty($service['requiredcapability']) ? null : $service['requiredcapability'];
1432 $dbservice->restrictedusers = !isset($service['restrictedusers']) ? 1 : $service['restrictedusers'];
1433 $dbservice->downloadfiles = !isset($service['downloadfiles']) ? 0 : $service['downloadfiles'];
1434 $dbservice->uploadfiles = !isset($service['uploadfiles']) ? 0 : $service['uploadfiles'];
1435 $dbservice->shortname = !isset($service['shortname']) ? null : $service['shortname'];
1436 $dbservice->component = $component;
1437 $dbservice->timecreated = time();
1438 $dbservice->id = $DB->insert_record('external_services', $dbservice);
1439 foreach ($service['functions'] as $fname) {
1440 $newf = new stdClass();
1441 $newf->externalserviceid = $dbservice->id;
1442 $newf->functionname = $fname;
1443 $DB->insert_record('external_services_functions', $newf);
1449 * Allow plugins and subsystems to add external functions to other plugins or built-in services.
1450 * This function is executed just after all the plugins have been updated.
1452 function external_update_services() {
1453 global $DB;
1455 // Look for external functions that want to be added in existing services.
1456 $functions = $DB->get_records_select('external_functions', 'services IS NOT NULL');
1458 $servicescache = array();
1459 foreach ($functions as $function) {
1460 // Prevent edge cases.
1461 if (empty($function->services)) {
1462 continue;
1464 $services = explode(',', $function->services);
1466 foreach ($services as $serviceshortname) {
1467 // Get the service id by shortname.
1468 if (!empty($servicescache[$serviceshortname])) {
1469 $serviceid = $servicescache[$serviceshortname];
1470 } else if ($service = $DB->get_record('external_services', array('shortname' => $serviceshortname))) {
1471 // If the component is empty, it means that is not a built-in service.
1472 // We don't allow functions to inject themselves in services created by an user in Moodle.
1473 if (empty($service->component)) {
1474 continue;
1476 $serviceid = $service->id;
1477 $servicescache[$serviceshortname] = $serviceid;
1478 } else {
1479 // Service not found.
1480 continue;
1482 // Finally add the function to the service.
1483 $newf = new stdClass();
1484 $newf->externalserviceid = $serviceid;
1485 $newf->functionname = $function->name;
1487 if (!$DB->record_exists('external_services_functions', (array)$newf)) {
1488 $DB->insert_record('external_services_functions', $newf);
1495 * upgrade logging functions
1497 function upgrade_handle_exception($ex, $plugin = null) {
1498 global $CFG;
1500 // rollback everything, we need to log all upgrade problems
1501 abort_all_db_transactions();
1503 $info = get_exception_info($ex);
1505 // First log upgrade error
1506 upgrade_log(UPGRADE_LOG_ERROR, $plugin, 'Exception: ' . get_class($ex), $info->message, $info->backtrace);
1508 // Always turn on debugging - admins need to know what is going on
1509 set_debugging(DEBUG_DEVELOPER, true);
1511 default_exception_handler($ex, true, $plugin);
1515 * Adds log entry into upgrade_log table
1517 * @param int $type UPGRADE_LOG_NORMAL, UPGRADE_LOG_NOTICE or UPGRADE_LOG_ERROR
1518 * @param string $plugin frankenstyle component name
1519 * @param string $info short description text of log entry
1520 * @param string $details long problem description
1521 * @param string $backtrace string used for errors only
1522 * @return void
1524 function upgrade_log($type, $plugin, $info, $details=null, $backtrace=null) {
1525 global $DB, $USER, $CFG;
1527 if (empty($plugin)) {
1528 $plugin = 'core';
1531 list($plugintype, $pluginname) = core_component::normalize_component($plugin);
1532 $component = is_null($pluginname) ? $plugintype : $plugintype . '_' . $pluginname;
1534 $backtrace = format_backtrace($backtrace, true);
1536 $currentversion = null;
1537 $targetversion = null;
1539 //first try to find out current version number
1540 if ($plugintype === 'core') {
1541 //main
1542 $currentversion = $CFG->version;
1544 $version = null;
1545 include("$CFG->dirroot/version.php");
1546 $targetversion = $version;
1548 } else {
1549 $pluginversion = get_config($component, 'version');
1550 if (!empty($pluginversion)) {
1551 $currentversion = $pluginversion;
1553 $cd = core_component::get_component_directory($component);
1554 if (file_exists("$cd/version.php")) {
1555 $plugin = new stdClass();
1556 $plugin->version = null;
1557 $module = $plugin;
1558 include("$cd/version.php");
1559 $targetversion = $plugin->version;
1563 $log = new stdClass();
1564 $log->type = $type;
1565 $log->plugin = $component;
1566 $log->version = $currentversion;
1567 $log->targetversion = $targetversion;
1568 $log->info = $info;
1569 $log->details = $details;
1570 $log->backtrace = $backtrace;
1571 $log->userid = $USER->id;
1572 $log->timemodified = time();
1573 try {
1574 $DB->insert_record('upgrade_log', $log);
1575 } catch (Exception $ignored) {
1576 // possible during install or 2.0 upgrade
1581 * Marks start of upgrade, blocks any other access to site.
1582 * The upgrade is finished at the end of script or after timeout.
1584 * @global object
1585 * @global object
1586 * @global object
1588 function upgrade_started($preinstall=false) {
1589 global $CFG, $DB, $PAGE, $OUTPUT;
1591 static $started = false;
1593 if ($preinstall) {
1594 ignore_user_abort(true);
1595 upgrade_setup_debug(true);
1597 } else if ($started) {
1598 upgrade_set_timeout(120);
1600 } else {
1601 if (!CLI_SCRIPT and !$PAGE->headerprinted) {
1602 $strupgrade = get_string('upgradingversion', 'admin');
1603 $PAGE->set_pagelayout('maintenance');
1604 upgrade_init_javascript();
1605 $PAGE->set_title($strupgrade . moodle_page::TITLE_SEPARATOR . 'Moodle ' . $CFG->target_release);
1606 $PAGE->set_heading($strupgrade);
1607 $PAGE->navbar->add($strupgrade);
1608 $PAGE->set_cacheable(false);
1609 echo $OUTPUT->header();
1612 ignore_user_abort(true);
1613 core_shutdown_manager::register_function('upgrade_finished_handler');
1614 upgrade_setup_debug(true);
1615 // Support no-maintenance upgrades.
1616 if (!defined('CLI_UPGRADE_RUNNING') || !CLI_UPGRADE_RUNNING) {
1617 set_config('upgraderunning', time() + 300);
1619 $started = true;
1624 * Internal function - executed if upgrade interrupted.
1626 function upgrade_finished_handler() {
1627 upgrade_finished();
1631 * Indicates upgrade is finished.
1633 * This function may be called repeatedly.
1635 * @global object
1636 * @global object
1638 function upgrade_finished($continueurl=null) {
1639 global $CFG, $DB, $OUTPUT;
1641 if (!empty($CFG->upgraderunning)) {
1642 unset_config('upgraderunning');
1643 // We have to forcefully purge the caches using the writer here.
1644 // This has to be done after we unset the config var. If someone hits the site while this is set they will
1645 // cause the config values to propogate to the caches.
1646 // Caches are purged after the last step in an upgrade but there is several code routines that exceute between
1647 // then and now that leaving a window for things to fall out of sync.
1648 cache_helper::purge_all(true);
1649 upgrade_setup_debug(false);
1650 ignore_user_abort(false);
1651 if ($continueurl) {
1652 echo $OUTPUT->continue_button($continueurl);
1653 echo $OUTPUT->footer();
1654 die;
1660 * @global object
1661 * @global object
1663 function upgrade_setup_debug($starting) {
1664 global $CFG, $DB;
1666 static $originaldebug = null;
1668 if ($starting) {
1669 if ($originaldebug === null) {
1670 $originaldebug = $DB->get_debug();
1672 if (!empty($CFG->upgradeshowsql)) {
1673 $DB->set_debug(true);
1675 } else {
1676 $DB->set_debug($originaldebug);
1680 function print_upgrade_separator() {
1681 if (!CLI_SCRIPT) {
1682 echo '<hr />';
1687 * Default start upgrade callback
1688 * @param string $plugin
1689 * @param bool $installation true if installation, false means upgrade
1691 function print_upgrade_part_start($plugin, $installation, $verbose) {
1692 global $OUTPUT;
1693 if (empty($plugin) or $plugin == 'moodle') {
1694 upgrade_started($installation); // does not store upgrade running flag yet
1695 if ($verbose) {
1696 echo $OUTPUT->heading(get_string('coresystem'));
1698 } else {
1699 upgrade_started();
1700 if ($verbose) {
1701 echo $OUTPUT->heading($plugin);
1704 core_upgrade_time::record_start($installation);
1705 if ($installation) {
1706 if (empty($plugin) or $plugin == 'moodle') {
1707 // no need to log - log table not yet there ;-)
1708 } else {
1709 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Starting plugin installation');
1711 } else {
1712 if (empty($plugin) or $plugin == 'moodle') {
1713 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Starting core upgrade');
1714 } else {
1715 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Starting plugin upgrade');
1721 * Default end upgrade callback
1722 * @param string $plugin
1723 * @param bool $installation true if installation, false means upgrade
1725 function print_upgrade_part_end($plugin, $installation, $verbose) {
1726 global $OUTPUT;
1727 upgrade_started();
1728 if ($installation) {
1729 if (empty($plugin) or $plugin == 'moodle') {
1730 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Core installed');
1731 } else {
1732 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Plugin installed');
1734 } else {
1735 if (empty($plugin) or $plugin == 'moodle') {
1736 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Core upgraded');
1737 } else {
1738 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Plugin upgraded');
1741 if ($verbose) {
1742 core_upgrade_time::record_end();
1743 print_upgrade_separator();
1748 * Sets up JS code required for all upgrade scripts.
1749 * @global object
1751 function upgrade_init_javascript() {
1752 global $PAGE;
1753 // scroll to the end of each upgrade page so that ppl see either error or continue button,
1754 // no need to scroll continuously any more, it is enough to jump to end once the footer is printed ;-)
1755 $js = "window.scrollTo(0, 5000000);";
1756 $PAGE->requires->js_init_code($js);
1760 * Try to upgrade the given language pack (or current language)
1762 * @param string $lang the code of the language to update, defaults to the current language
1764 function upgrade_language_pack($lang = null) {
1765 global $CFG;
1767 if (!empty($CFG->skiplangupgrade)) {
1768 return;
1771 if (!file_exists("$CFG->dirroot/$CFG->admin/tool/langimport/lib.php")) {
1772 // weird, somebody uninstalled the import utility
1773 return;
1776 if (!$lang) {
1777 $lang = current_language();
1780 if (!get_string_manager()->translation_exists($lang)) {
1781 return;
1784 get_string_manager()->reset_caches();
1786 if ($lang === 'en') {
1787 return; // Nothing to do
1790 upgrade_started(false);
1792 require_once("$CFG->dirroot/$CFG->admin/tool/langimport/lib.php");
1793 tool_langimport_preupgrade_update($lang);
1795 get_string_manager()->reset_caches();
1797 print_upgrade_separator();
1801 * Build the current theme so that the user doesn't have to wait for it
1802 * to build on the first page load after the install / upgrade.
1804 function upgrade_themes() {
1805 global $CFG;
1807 require_once("{$CFG->libdir}/outputlib.php");
1809 // Build the current theme so that the user can immediately
1810 // browse the site without having to wait for the theme to build.
1811 $themeconfig = theme_config::load($CFG->theme);
1812 $direction = right_to_left() ? 'rtl' : 'ltr';
1813 theme_build_css_for_themes([$themeconfig], [$direction]);
1815 // Only queue the task if there isn't already one queued.
1816 if (empty(\core\task\manager::get_adhoc_tasks('\\core\\task\\build_installed_themes_task'))) {
1817 // Queue a task to build all of the site themes at some point
1818 // later. These can happen offline because it doesn't block the
1819 // user unless they quickly change theme.
1820 $adhoctask = new \core\task\build_installed_themes_task();
1821 \core\task\manager::queue_adhoc_task($adhoctask);
1826 * Install core moodle tables and initialize
1827 * @param float $version target version
1828 * @param bool $verbose
1829 * @return void, may throw exception
1831 function install_core($version, $verbose) {
1832 global $CFG, $DB;
1834 // We can not call purge_all_caches() yet, make sure the temp and cache dirs exist and are empty.
1835 remove_dir($CFG->cachedir.'', true);
1836 make_cache_directory('', true);
1838 remove_dir($CFG->localcachedir.'', true);
1839 make_localcache_directory('', true);
1841 remove_dir($CFG->tempdir.'', true);
1842 make_temp_directory('', true);
1844 remove_dir($CFG->backuptempdir.'', true);
1845 make_backup_temp_directory('', true);
1847 remove_dir($CFG->dataroot.'/muc', true);
1848 make_writable_directory($CFG->dataroot.'/muc', true);
1850 try {
1851 core_php_time_limit::raise(600);
1852 print_upgrade_part_start('moodle', true, $verbose); // does not store upgrade running flag
1854 $DB->get_manager()->install_from_xmldb_file("$CFG->libdir/db/install.xml");
1855 core_upgrade_time::record_detail('install.xml');
1856 upgrade_started(); // we want the flag to be stored in config table ;-)
1857 core_upgrade_time::record_detail('upgrade_started');
1859 // set all core default records and default settings
1860 require_once("$CFG->libdir/db/install.php");
1861 core_upgrade_time::record_detail('install.php');
1862 xmldb_main_install(); // installs the capabilities too
1863 core_upgrade_time::record_detail('xmldb_main_install');
1865 // store version
1866 upgrade_main_savepoint(true, $version, false);
1868 // Continue with the installation
1869 upgrade_component_updated('moodle', '', true);
1871 // Write default settings unconditionally
1872 admin_apply_default_settings(NULL, true);
1873 core_upgrade_time::record_detail('admin_apply_default_settings');
1875 print_upgrade_part_end(null, true, $verbose);
1877 // Purge all caches. They're disabled but this ensures that we don't have any persistent data just in case something
1878 // during installation didn't use APIs.
1879 cache_helper::purge_all();
1880 } catch (exception $ex) {
1881 upgrade_handle_exception($ex);
1882 } catch (Throwable $ex) {
1883 // Engine errors in PHP7 throw exceptions of type Throwable (this "catch" will be ignored in PHP5).
1884 upgrade_handle_exception($ex);
1889 * Upgrade moodle core
1890 * @param float $version target version
1891 * @param bool $verbose
1892 * @return void, may throw exception
1894 function upgrade_core($version, $verbose) {
1895 global $CFG, $SITE, $DB, $COURSE;
1897 raise_memory_limit(MEMORY_EXTRA);
1899 require_once($CFG->libdir.'/db/upgrade.php'); // Defines upgrades
1901 try {
1902 // If we are in maintenance, we can purge all our caches here.
1903 if (!defined('CLI_UPGRADE_RUNNING') || !CLI_UPGRADE_RUNNING) {
1904 cache_helper::purge_all(true);
1905 purge_all_caches();
1908 // Upgrade current language pack if we can
1909 upgrade_language_pack();
1911 print_upgrade_part_start('moodle', false, $verbose);
1913 // Pre-upgrade scripts for local hack workarounds.
1914 $preupgradefile = "$CFG->dirroot/local/preupgrade.php";
1915 if (file_exists($preupgradefile)) {
1916 core_php_time_limit::raise();
1917 require($preupgradefile);
1918 // Reset upgrade timeout to default.
1919 upgrade_set_timeout();
1920 core_upgrade_time::record_detail('local/preupgrade.php');
1923 $result = xmldb_main_upgrade($CFG->version);
1924 core_upgrade_time::record_detail('xmldb_main_upgrade');
1925 if ($version > $CFG->version) {
1926 // store version if not already there
1927 upgrade_main_savepoint($result, $version, false);
1930 // In case structure of 'course' table has been changed and we forgot to update $SITE, re-read it from db.
1931 $SITE = $DB->get_record('course', array('id' => $SITE->id));
1932 $COURSE = clone($SITE);
1934 // perform all other component upgrade routines
1935 upgrade_component_updated('moodle');
1936 // Update core definitions.
1937 cache_helper::update_definitions(true);
1938 core_upgrade_time::record_detail('cache_helper::update_definitions');
1940 // Purge caches again, just to be sure we arn't holding onto old stuff now.
1941 if (!defined('CLI_UPGRADE_RUNNING') || !CLI_UPGRADE_RUNNING) {
1942 cache_helper::purge_all(true);
1943 core_upgrade_time::record_detail('cache_helper::purge_all');
1944 purge_all_caches();
1945 core_upgrade_time::record_detail('purge_all_caches');
1948 // Clean up contexts - more and more stuff depends on existence of paths and contexts
1949 context_helper::cleanup_instances();
1950 core_upgrade_time::record_detail('context_helper::cleanup_instance');
1951 context_helper::create_instances(null, false);
1952 core_upgrade_time::record_detail('context_helper::create_instances');
1953 context_helper::build_all_paths(false);
1954 core_upgrade_time::record_detail('context_helper::build_all_paths');
1955 $syscontext = context_system::instance();
1956 $syscontext->mark_dirty();
1957 core_upgrade_time::record_detail('context_system::mark_dirty');
1959 print_upgrade_part_end('moodle', false, $verbose);
1960 } catch (Exception $ex) {
1961 upgrade_handle_exception($ex);
1962 } catch (Throwable $ex) {
1963 // Engine errors in PHP7 throw exceptions of type Throwable (this "catch" will be ignored in PHP5).
1964 upgrade_handle_exception($ex);
1969 * Upgrade/install other parts of moodle
1970 * @param bool $verbose
1971 * @return void, may throw exception
1973 function upgrade_noncore($verbose) {
1974 global $CFG, $OUTPUT;
1976 raise_memory_limit(MEMORY_EXTRA);
1978 // upgrade all plugins types
1979 try {
1980 // Reset caches before any output, unless we are not in maintenance.
1981 if (!defined('CLI_UPGRADE_RUNNING') || !CLI_UPGRADE_RUNNING) {
1982 cache_helper::purge_all(true);
1983 purge_all_caches();
1986 $plugintypes = core_component::get_plugin_types();
1987 upgrade_started();
1988 foreach ($plugintypes as $type=>$location) {
1989 upgrade_plugins($type, 'print_upgrade_part_start', 'print_upgrade_part_end', $verbose);
1991 if ($CFG->debugdeveloper) {
1992 // Only show this heading in developer mode to go with the times below.
1993 echo $OUTPUT->heading('upgrade_noncore()');
1995 core_upgrade_time::record_start();
1996 // Upgrade services.
1997 // This function gives plugins and subsystems a chance to add functions to existing built-in services.
1998 external_update_services();
1999 core_upgrade_time::record_detail('external_update_services');
2001 // Update cache definitions. Involves scanning each plugin for any changes.
2002 cache_helper::update_definitions();
2003 core_upgrade_time::record_detail('cache_helper::update_definitions');
2005 // Mark the site as upgraded.
2006 set_config('allversionshash', core_component::get_all_versions_hash());
2007 core_upgrade_time::record_detail('core_component::get_all_versions_hash');
2008 set_config('allcomponenthash', core_component::get_all_component_hash());
2009 core_upgrade_time::record_detail('core_component::get_all_component_hash');
2011 // Prompt admin to register site. Reminder flow handles sites already registered, so admin won't be prompted if registered.
2012 // Defining for non-core upgrades also covers core upgrades.
2013 set_config('registrationpending', true);
2015 // Purge caches again, just to be sure we arn't holding onto old stuff now.
2016 if (!defined('CLI_UPGRADE_RUNNING') || !CLI_UPGRADE_RUNNING) {
2017 cache_helper::purge_all(true);
2018 core_upgrade_time::record_detail('cache_helper::purge_all');
2019 purge_all_caches();
2020 core_upgrade_time::record_detail('purge_all_caches');
2023 // Only display the final 'Success' if we also showed the heading.
2024 core_upgrade_time::record_end($CFG->debugdeveloper);
2025 } catch (Exception $ex) {
2026 upgrade_handle_exception($ex);
2027 } catch (Throwable $ex) {
2028 // Engine errors in PHP7 throw exceptions of type Throwable (this "catch" will be ignored in PHP5).
2029 upgrade_handle_exception($ex);
2034 * Checks if the main tables have been installed yet or not.
2036 * Note: we can not use caches here because they might be stale,
2037 * use with care!
2039 * @return bool
2041 function core_tables_exist() {
2042 global $DB;
2044 if (!$tables = $DB->get_tables(false) ) { // No tables yet at all.
2045 return false;
2047 } else { // Check for missing main tables
2048 $mtables = array('config', 'course', 'groupings'); // some tables used in 1.9 and 2.0, preferable something from the start and end of install.xml
2049 foreach ($mtables as $mtable) {
2050 if (!in_array($mtable, $tables)) {
2051 return false;
2054 return true;
2059 * upgrades the mnet rpc definitions for the given component.
2060 * this method doesn't return status, an exception will be thrown in the case of an error
2062 * @param string $component the plugin to upgrade, eg auth_mnet
2064 function upgrade_plugin_mnet_functions($component) {
2065 global $DB, $CFG;
2067 list($type, $plugin) = core_component::normalize_component($component);
2068 $path = core_component::get_plugin_directory($type, $plugin);
2070 $publishes = array();
2071 $subscribes = array();
2072 if (file_exists($path . '/db/mnet.php')) {
2073 require_once($path . '/db/mnet.php'); // $publishes comes from this file
2075 if (empty($publishes)) {
2076 $publishes = array(); // still need this to be able to disable stuff later
2078 if (empty($subscribes)) {
2079 $subscribes = array(); // still need this to be able to disable stuff later
2082 static $servicecache = array();
2084 // rekey an array based on the rpc method for easy lookups later
2085 $publishmethodservices = array();
2086 $subscribemethodservices = array();
2087 foreach($publishes as $servicename => $service) {
2088 if (is_array($service['methods'])) {
2089 foreach($service['methods'] as $methodname) {
2090 $service['servicename'] = $servicename;
2091 $publishmethodservices[$methodname][] = $service;
2096 // Disable functions that don't exist (any more) in the source
2097 // Should these be deleted? What about their permissions records?
2098 foreach ($DB->get_records('mnet_rpc', array('pluginname'=>$plugin, 'plugintype'=>$type), 'functionname ASC ') as $rpc) {
2099 if (!array_key_exists($rpc->functionname, $publishmethodservices) && $rpc->enabled) {
2100 $DB->set_field('mnet_rpc', 'enabled', 0, array('id' => $rpc->id));
2101 } else if (array_key_exists($rpc->functionname, $publishmethodservices) && !$rpc->enabled) {
2102 $DB->set_field('mnet_rpc', 'enabled', 1, array('id' => $rpc->id));
2106 // reflect all the services we're publishing and save them
2107 static $cachedclasses = array(); // to store reflection information in
2108 foreach ($publishes as $service => $data) {
2109 $f = $data['filename'];
2110 $c = $data['classname'];
2111 foreach ($data['methods'] as $method) {
2112 $dataobject = new stdClass();
2113 $dataobject->plugintype = $type;
2114 $dataobject->pluginname = $plugin;
2115 $dataobject->enabled = 1;
2116 $dataobject->classname = $c;
2117 $dataobject->filename = $f;
2119 if (is_string($method)) {
2120 $dataobject->functionname = $method;
2122 } else if (is_array($method)) { // wants to override file or class
2123 $dataobject->functionname = $method['method'];
2124 $dataobject->classname = $method['classname'];
2125 $dataobject->filename = $method['filename'];
2127 $dataobject->xmlrpcpath = $type.'/'.$plugin.'/'.$dataobject->filename.'/'.$method;
2128 $dataobject->static = false;
2130 require_once($path . '/' . $dataobject->filename);
2131 $functionreflect = null; // slightly different ways to get this depending on whether it's a class method or a function
2132 if (!empty($dataobject->classname)) {
2133 if (!class_exists($dataobject->classname)) {
2134 throw new moodle_exception('installnosuchmethod', 'mnet', '', (object)array('method' => $dataobject->functionname, 'class' => $dataobject->classname));
2136 $key = $dataobject->filename . '|' . $dataobject->classname;
2137 if (!array_key_exists($key, $cachedclasses)) { // look to see if we've already got a reflection object
2138 try {
2139 $cachedclasses[$key] = new ReflectionClass($dataobject->classname);
2140 } catch (ReflectionException $e) { // catch these and rethrow them to something more helpful
2141 throw new moodle_exception('installreflectionclasserror', 'mnet', '', (object)array('method' => $dataobject->functionname, 'class' => $dataobject->classname, 'error' => $e->getMessage()));
2144 $r =& $cachedclasses[$key];
2145 if (!$r->hasMethod($dataobject->functionname)) {
2146 throw new moodle_exception('installnosuchmethod', 'mnet', '', (object)array('method' => $dataobject->functionname, 'class' => $dataobject->classname));
2148 $functionreflect = $r->getMethod($dataobject->functionname);
2149 $dataobject->static = (int)$functionreflect->isStatic();
2150 } else {
2151 if (!function_exists($dataobject->functionname)) {
2152 throw new moodle_exception('installnosuchfunction', 'mnet', '', (object)array('method' => $dataobject->functionname, 'file' => $dataobject->filename));
2154 try {
2155 $functionreflect = new ReflectionFunction($dataobject->functionname);
2156 } catch (ReflectionException $e) { // catch these and rethrow them to something more helpful
2157 throw new moodle_exception('installreflectionfunctionerror', 'mnet', '', (object)array('method' => $dataobject->functionname, '' => $dataobject->filename, 'error' => $e->getMessage()));
2160 $dataobject->profile = serialize(admin_mnet_method_profile($functionreflect));
2161 $dataobject->help = admin_mnet_method_get_help($functionreflect);
2163 if ($record_exists = $DB->get_record('mnet_rpc', array('xmlrpcpath'=>$dataobject->xmlrpcpath))) {
2164 $dataobject->id = $record_exists->id;
2165 $dataobject->enabled = $record_exists->enabled;
2166 $DB->update_record('mnet_rpc', $dataobject);
2167 } else {
2168 $dataobject->id = $DB->insert_record('mnet_rpc', $dataobject, true);
2171 // TODO this API versioning must be reworked, here the recently processed method
2172 // sets the service API which may not be correct
2173 foreach ($publishmethodservices[$dataobject->functionname] as $service) {
2174 if ($serviceobj = $DB->get_record('mnet_service', array('name'=>$service['servicename']))) {
2175 $serviceobj->apiversion = $service['apiversion'];
2176 $DB->update_record('mnet_service', $serviceobj);
2177 } else {
2178 $serviceobj = new stdClass();
2179 $serviceobj->name = $service['servicename'];
2180 $serviceobj->description = empty($service['description']) ? '' : $service['description'];
2181 $serviceobj->apiversion = $service['apiversion'];
2182 $serviceobj->offer = 1;
2183 $serviceobj->id = $DB->insert_record('mnet_service', $serviceobj);
2185 $servicecache[$service['servicename']] = $serviceobj;
2186 if (!$DB->record_exists('mnet_service2rpc', array('rpcid'=>$dataobject->id, 'serviceid'=>$serviceobj->id))) {
2187 $obj = new stdClass();
2188 $obj->rpcid = $dataobject->id;
2189 $obj->serviceid = $serviceobj->id;
2190 $DB->insert_record('mnet_service2rpc', $obj, true);
2195 // finished with methods we publish, now do subscribable methods
2196 foreach($subscribes as $service => $methods) {
2197 if (!array_key_exists($service, $servicecache)) {
2198 if (!$serviceobj = $DB->get_record('mnet_service', array('name' => $service))) {
2199 debugging("TODO: skipping unknown service $service - somebody needs to fix MDL-21993");
2200 continue;
2202 $servicecache[$service] = $serviceobj;
2203 } else {
2204 $serviceobj = $servicecache[$service];
2206 foreach ($methods as $method => $xmlrpcpath) {
2207 if (!$rpcid = $DB->get_field('mnet_remote_rpc', 'id', array('xmlrpcpath'=>$xmlrpcpath))) {
2208 $remoterpc = (object)array(
2209 'functionname' => $method,
2210 'xmlrpcpath' => $xmlrpcpath,
2211 'plugintype' => $type,
2212 'pluginname' => $plugin,
2213 'enabled' => 1,
2215 $rpcid = $remoterpc->id = $DB->insert_record('mnet_remote_rpc', $remoterpc, true);
2217 if (!$DB->record_exists('mnet_remote_service2rpc', array('rpcid'=>$rpcid, 'serviceid'=>$serviceobj->id))) {
2218 $obj = new stdClass();
2219 $obj->rpcid = $rpcid;
2220 $obj->serviceid = $serviceobj->id;
2221 $DB->insert_record('mnet_remote_service2rpc', $obj, true);
2223 $subscribemethodservices[$method][] = $service;
2227 foreach ($DB->get_records('mnet_remote_rpc', array('pluginname'=>$plugin, 'plugintype'=>$type), 'functionname ASC ') as $rpc) {
2228 if (!array_key_exists($rpc->functionname, $subscribemethodservices) && $rpc->enabled) {
2229 $DB->set_field('mnet_remote_rpc', 'enabled', 0, array('id' => $rpc->id));
2230 } else if (array_key_exists($rpc->functionname, $subscribemethodservices) && !$rpc->enabled) {
2231 $DB->set_field('mnet_remote_rpc', 'enabled', 1, array('id' => $rpc->id));
2235 return true;
2239 * Given some sort of reflection function/method object, return a profile array, ready to be serialized and stored
2241 * @param ReflectionFunctionAbstract $function reflection function/method object from which to extract information
2243 * @return array associative array with function/method information
2245 function admin_mnet_method_profile(ReflectionFunctionAbstract $function) {
2246 $commentlines = admin_mnet_method_get_docblock($function);
2247 $getkey = function($key) use ($commentlines) {
2248 return array_values(array_filter($commentlines, function($line) use ($key) {
2249 return $line[0] == $key;
2250 }));
2252 $returnline = $getkey('@return');
2253 return array (
2254 'parameters' => array_map(function($line) {
2255 return array(
2256 'name' => trim($line[2], " \t\n\r\0\x0B$"),
2257 'type' => $line[1],
2258 'description' => $line[3]
2260 }, $getkey('@param')),
2262 'return' => array(
2263 'type' => !empty($returnline[0][1]) ? $returnline[0][1] : 'void',
2264 'description' => !empty($returnline[0][2]) ? $returnline[0][2] : ''
2270 * Given some sort of reflection function/method object, return an array of docblock lines, where each line is an array of
2271 * keywords/descriptions
2273 * @param ReflectionFunctionAbstract $function reflection function/method object from which to extract information
2275 * @return array docblock converted in to an array
2277 function admin_mnet_method_get_docblock(ReflectionFunctionAbstract $function) {
2278 return array_map(function($line) {
2279 $text = trim($line, " \t\n\r\0\x0B*/");
2280 if (strpos($text, '@param') === 0) {
2281 return preg_split('/\s+/', $text, 4);
2284 if (strpos($text, '@return') === 0) {
2285 return preg_split('/\s+/', $text, 3);
2288 return array($text);
2289 }, explode("\n", $function->getDocComment()));
2293 * Given some sort of reflection function/method object, return just the help text
2295 * @param ReflectionFunctionAbstract $function reflection function/method object from which to extract information
2297 * @return string docblock help text
2299 function admin_mnet_method_get_help(ReflectionFunctionAbstract $function) {
2300 $helplines = array_map(function($line) {
2301 return implode(' ', $line);
2302 }, array_values(array_filter(admin_mnet_method_get_docblock($function), function($line) {
2303 return strpos($line[0], '@') !== 0 && !empty($line[0]);
2304 })));
2306 return implode("\n", $helplines);
2310 * This function verifies that the database is not using an unsupported storage engine.
2312 * @param environment_results $result object to update, if relevant
2313 * @return environment_results|null updated results object, or null if the storage engine is supported
2315 function check_database_storage_engine(environment_results $result) {
2316 global $DB;
2318 // Check if MySQL is the DB family (this will also be the same for MariaDB).
2319 if ($DB->get_dbfamily() == 'mysql') {
2320 // Get the database engine we will either be using to install the tables, or what we are currently using.
2321 $engine = $DB->get_dbengine();
2322 // Check if MyISAM is the storage engine that will be used, if so, do not proceed and display an error.
2323 if ($engine == 'MyISAM') {
2324 $result->setInfo('unsupported_db_storage_engine');
2325 $result->setStatus(false);
2326 return $result;
2330 return null;
2334 * Method used to check the usage of slasharguments config and display a warning message.
2336 * @param environment_results $result object to update, if relevant.
2337 * @return environment_results|null updated results or null if slasharguments is disabled.
2339 function check_slasharguments(environment_results $result){
2340 global $CFG;
2342 if (!during_initial_install() && empty($CFG->slasharguments)) {
2343 $result->setInfo('slasharguments');
2344 $result->setStatus(false);
2345 return $result;
2348 return null;
2352 * This function verifies if the database has tables using innoDB Antelope row format.
2354 * @param environment_results $result
2355 * @return environment_results|null updated results object, or null if no Antelope table has been found.
2357 function check_database_tables_row_format(environment_results $result) {
2358 global $DB;
2360 if ($DB->get_dbfamily() == 'mysql') {
2361 $generator = $DB->get_manager()->generator;
2363 foreach ($DB->get_tables(false) as $table) {
2364 $columns = $DB->get_columns($table, false);
2365 $size = $generator->guess_antelope_row_size($columns);
2366 $format = $DB->get_row_format($table);
2368 if ($size <= $generator::ANTELOPE_MAX_ROW_SIZE) {
2369 continue;
2372 if ($format === 'Compact' or $format === 'Redundant') {
2373 $result->setInfo('unsupported_db_table_row_format');
2374 $result->setStatus(false);
2375 return $result;
2380 return null;
2384 * This function verfies that the database has tables using InnoDB Antelope row format.
2386 * @param environment_results $result
2387 * @return environment_results|null updated results object, or null if no Antelope table has been found.
2389 function check_mysql_file_format(environment_results $result) {
2390 global $DB;
2392 if ($DB->get_dbfamily() == 'mysql') {
2393 $collation = $DB->get_dbcollation();
2394 $collationinfo = explode('_', $collation);
2395 $charset = reset($collationinfo);
2397 if ($charset == 'utf8mb4') {
2398 if ($DB->get_row_format() !== "Barracuda") {
2399 $result->setInfo('mysql_full_unicode_support#File_format');
2400 $result->setStatus(false);
2401 return $result;
2405 return null;
2409 * This function verfies that the database has a setting of one file per table. This is required for 'utf8mb4'.
2411 * @param environment_results $result
2412 * @return environment_results|null updated results object, or null if innodb_file_per_table = 1.
2414 function check_mysql_file_per_table(environment_results $result) {
2415 global $DB;
2417 if ($DB->get_dbfamily() == 'mysql') {
2418 $collation = $DB->get_dbcollation();
2419 $collationinfo = explode('_', $collation);
2420 $charset = reset($collationinfo);
2422 if ($charset == 'utf8mb4') {
2423 if (!$DB->is_file_per_table_enabled()) {
2424 $result->setInfo('mysql_full_unicode_support#File_per_table');
2425 $result->setStatus(false);
2426 return $result;
2430 return null;
2434 * This function verfies that the database has the setting of large prefix enabled. This is required for 'utf8mb4'.
2436 * @param environment_results $result
2437 * @return environment_results|null updated results object, or null if innodb_large_prefix = 1.
2439 function check_mysql_large_prefix(environment_results $result) {
2440 global $DB;
2442 if ($DB->get_dbfamily() == 'mysql') {
2443 $collation = $DB->get_dbcollation();
2444 $collationinfo = explode('_', $collation);
2445 $charset = reset($collationinfo);
2447 if ($charset == 'utf8mb4') {
2448 if (!$DB->is_large_prefix_enabled()) {
2449 $result->setInfo('mysql_full_unicode_support#Large_prefix');
2450 $result->setStatus(false);
2451 return $result;
2455 return null;
2459 * This function checks the database to see if it is using incomplete unicode support.
2461 * @param environment_results $result $result
2462 * @return environment_results|null updated results object, or null if unicode is fully supported.
2464 function check_mysql_incomplete_unicode_support(environment_results $result) {
2465 global $DB;
2467 if ($DB->get_dbfamily() == 'mysql') {
2468 $collation = $DB->get_dbcollation();
2469 $collationinfo = explode('_', $collation);
2470 $charset = reset($collationinfo);
2472 if ($charset == 'utf8') {
2473 $result->setInfo('mysql_full_unicode_support');
2474 $result->setStatus(false);
2475 return $result;
2478 return null;
2482 * Check if the site is being served using an ssl url.
2484 * Note this does not really perform any request neither looks for proxies or
2485 * other situations. Just looks to wwwroot and warn if it's not using https.
2487 * @param environment_results $result $result
2488 * @return environment_results|null updated results object, or null if the site is https.
2490 function check_is_https(environment_results $result) {
2491 global $CFG;
2493 // Only if is defined, non-empty and whatever core tell us.
2494 if (!empty($CFG->wwwroot) && !is_https()) {
2495 $result->setInfo('site not https');
2496 $result->setStatus(false);
2497 return $result;
2499 return null;
2503 * Check if the site is using 64 bits PHP.
2505 * @param environment_results $result
2506 * @return environment_results|null updated results object, or null if the site is using 64 bits PHP.
2508 function check_sixtyfour_bits(environment_results $result) {
2510 if (PHP_INT_SIZE === 4) {
2511 $result->setInfo('php not 64 bits');
2512 $result->setStatus(false);
2513 return $result;
2515 return null;
2519 * Check if the igbinary extension installed is buggy one
2521 * There are a few php-igbinary versions that are buggy and
2522 * return any unserialised array with wrong index. This defeats
2523 * key() and next() operations on them.
2525 * This library is used by MUC and also by memcached and redis
2526 * when available.
2528 * Let's inform if there is some problem when:
2529 * - php 7.2 is being used (php 7.3 and up are immune).
2530 * - the igbinary extension is installed.
2531 * - the version of the extension is between 3.2.2 and 3.2.4.
2532 * - the buggy behaviour is reproduced.
2534 * @param environment_results $result object to update, if relevant.
2535 * @return environment_results|null updated results or null.
2537 function check_igbinary322_version(environment_results $result) {
2539 // No problem if using PHP version 7.3 and up.
2540 $phpversion = normalize_version(phpversion());
2541 if (version_compare($phpversion, '7.3', '>=')) {
2542 return null;
2545 // No problem if igbinary is not installed..
2546 if (!function_exists('igbinary_serialize')) {
2547 return null;
2550 // No problem if using igbinary < 3.2.2 or > 3.2.4.
2551 $igbinaryversion = normalize_version(phpversion('igbinary'));
2552 if (version_compare($igbinaryversion, '3.2.2', '<') or version_compare($igbinaryversion, '3.2.4', '>')) {
2553 return null;
2556 // Let's verify the real behaviour to see if the bug is around.
2557 // Note that we need this extra check because they released 3.2.5 with 3.2.4 version number, so
2558 // over the paper, there are 3.2.4 working versions (3.2.5 ones with messed reflection version).
2559 $data = [1, 2, 3];
2560 $data = igbinary_unserialize(igbinary_serialize($data));
2561 if (key($data) === 0) {
2562 return null;
2565 // Arrived here, we are using PHP 7.2 and a buggy verified igbinary version, let's inform and don't allow to continue.
2566 $result->setInfo('igbinary version problem');
2567 $result->setStatus(false);
2568 return $result;
2572 * This function checks that the database prefix ($CFG->prefix) is <= xmldb_table::PREFIX_MAX_LENGTH
2574 * @param environment_results $result
2575 * @return environment_results|null updated results object, or null if the prefix check is passing ok.
2577 function check_db_prefix_length(environment_results $result) {
2578 global $CFG;
2580 require_once($CFG->libdir.'/ddllib.php');
2581 $prefixlen = strlen($CFG->prefix) ?? 0;
2582 if ($prefixlen > xmldb_table::PREFIX_MAX_LENGTH) {
2583 $parameters = (object)['current' => $prefixlen, 'maximum' => xmldb_table::PREFIX_MAX_LENGTH];
2584 $result->setFeedbackStr(['dbprefixtoolong', 'admin', $parameters]);
2585 $result->setInfo('db prefix too long');
2586 $result->setStatus(false);
2587 return $result;
2589 return null; // All, good. By returning null we hide the check.
2593 * Assert the upgrade key is provided, if it is defined.
2595 * The upgrade key can be defined in the main config.php as $CFG->upgradekey. If
2596 * it is defined there, then its value must be provided every time the site is
2597 * being upgraded, regardless the administrator is logged in or not.
2599 * This is supposed to be used at certain places in /admin/index.php only.
2601 * @param string|null $upgradekeyhash the SHA-1 of the value provided by the user
2603 function check_upgrade_key($upgradekeyhash) {
2604 global $CFG, $PAGE;
2606 if (isset($CFG->config_php_settings['upgradekey'])) {
2607 if ($upgradekeyhash === null or $upgradekeyhash !== sha1($CFG->config_php_settings['upgradekey'])) {
2608 if (!$PAGE->headerprinted) {
2609 $PAGE->set_title(get_string('upgradekeyreq', 'admin'));
2610 $output = $PAGE->get_renderer('core', 'admin');
2611 echo $output->upgradekey_form_page(new moodle_url('/admin/index.php', array('cache' => 0)));
2612 die();
2613 } else {
2614 // This should not happen.
2615 die('Upgrade locked');
2622 * Helper procedure/macro for installing remote plugins at admin/index.php
2624 * Does not return, always redirects or exits.
2626 * @param array $installable list of \core\update\remote_info
2627 * @param bool $confirmed false: display the validation screen, true: proceed installation
2628 * @param string $heading validation screen heading
2629 * @param moodle_url|string|null $continue URL to proceed with installation at the validation screen
2630 * @param moodle_url|string|null $return URL to go back on cancelling at the validation screen
2632 function upgrade_install_plugins(array $installable, $confirmed, $heading='', $continue=null, $return=null) {
2633 global $CFG, $PAGE;
2635 if (empty($return)) {
2636 $return = $PAGE->url;
2639 if (!empty($CFG->disableupdateautodeploy)) {
2640 redirect($return);
2643 if (empty($installable)) {
2644 redirect($return);
2647 $pluginman = core_plugin_manager::instance();
2649 if ($confirmed) {
2650 // Installation confirmed at the validation results page.
2651 if (!$pluginman->install_plugins($installable, true, true)) {
2652 throw new moodle_exception('install_plugins_failed', 'core_plugin', $return);
2655 // Always redirect to admin/index.php to perform the database upgrade.
2656 // Do not throw away the existing $PAGE->url parameters such as
2657 // confirmupgrade or confirmrelease if $PAGE->url is a superset of the
2658 // URL we must go to.
2659 $mustgoto = new moodle_url('/admin/index.php', array('cache' => 0, 'confirmplugincheck' => 0));
2660 if ($mustgoto->compare($PAGE->url, URL_MATCH_PARAMS)) {
2661 redirect($PAGE->url);
2662 } else {
2663 redirect($mustgoto);
2666 } else {
2667 $output = $PAGE->get_renderer('core', 'admin');
2668 echo $output->header();
2669 if ($heading) {
2670 echo $output->heading($heading, 3);
2672 echo html_writer::start_tag('pre', array('class' => 'plugin-install-console'));
2673 $validated = $pluginman->install_plugins($installable, false, false);
2674 echo html_writer::end_tag('pre');
2675 if ($validated) {
2676 echo $output->plugins_management_confirm_buttons($continue, $return);
2677 } else {
2678 echo $output->plugins_management_confirm_buttons(null, $return);
2680 echo $output->footer();
2681 die();
2685 * Method used to check the installed unoconv version.
2687 * @param environment_results $result object to update, if relevant.
2688 * @return environment_results|null updated results or null if unoconv path is not executable.
2690 function check_unoconv_version(environment_results $result) {
2691 global $CFG;
2693 if (!during_initial_install() && !empty($CFG->pathtounoconv) && file_is_executable(trim($CFG->pathtounoconv))) {
2694 $currentversion = 0;
2695 $supportedversion = 0.7;
2696 $unoconvbin = \escapeshellarg($CFG->pathtounoconv);
2697 $command = "$unoconvbin --version";
2698 exec($command, $output);
2700 // If the command execution returned some output, then get the unoconv version.
2701 if ($output) {
2702 foreach ($output as $response) {
2703 if (preg_match('/unoconv (\\d+\\.\\d+)/', $response, $matches)) {
2704 $currentversion = (float)$matches[1];
2709 if ($currentversion < $supportedversion) {
2710 $result->setInfo('unoconv version not supported');
2711 $result->setStatus(false);
2712 return $result;
2715 return null;
2719 * Checks for up-to-date TLS libraries. NOTE: this is not currently used, see MDL-57262.
2721 * @param environment_results $result object to update, if relevant.
2722 * @return environment_results|null updated results or null if unoconv path is not executable.
2724 function check_tls_libraries(environment_results $result) {
2725 global $CFG;
2727 if (!function_exists('curl_version')) {
2728 $result->setInfo('cURL PHP extension is not installed');
2729 $result->setStatus(false);
2730 return $result;
2733 if (!\core\upgrade\util::validate_php_curl_tls(curl_version(), PHP_ZTS)) {
2734 $result->setInfo('invalid ssl/tls configuration');
2735 $result->setStatus(false);
2736 return $result;
2739 if (!\core\upgrade\util::can_use_tls12(curl_version(), php_uname('r'))) {
2740 $result->setInfo('ssl/tls configuration not supported');
2741 $result->setStatus(false);
2742 return $result;
2745 return null;
2749 * Check if recommended version of libcurl is installed or not.
2751 * @param environment_results $result object to update, if relevant.
2752 * @return environment_results|null updated results or null.
2754 function check_libcurl_version(environment_results $result) {
2756 if (!function_exists('curl_version')) {
2757 $result->setInfo('cURL PHP extension is not installed');
2758 $result->setStatus(false);
2759 return $result;
2762 // Supported version and version number.
2763 $supportedversion = 0x071304;
2764 $supportedversionstring = "7.19.4";
2766 // Installed version.
2767 $curlinfo = curl_version();
2768 $currentversion = $curlinfo['version_number'];
2770 if ($currentversion < $supportedversion) {
2771 // Test fail.
2772 // Set info, we want to let user know how to resolve the problem.
2773 $result->setInfo('Libcurl version check');
2774 $result->setNeededVersion($supportedversionstring);
2775 $result->setCurrentVersion($curlinfo['version']);
2776 $result->setStatus(false);
2777 return $result;
2780 return null;
2784 * Environment check for the php setting max_input_vars
2786 * @param environment_results $result
2787 * @return environment_results|null
2789 function check_max_input_vars(environment_results $result) {
2790 $max = (int)ini_get('max_input_vars');
2791 if ($max < 5000) {
2792 $result->setInfo('max_input_vars');
2793 $result->setStatus(false);
2794 if (PHP_VERSION_ID >= 80000) {
2795 // For PHP8 this check is required.
2796 $result->setLevel('required');
2797 $result->setFeedbackStr('settingmaxinputvarsrequired');
2798 } else {
2799 // For PHP7 this check is optional (recommended).
2800 $result->setFeedbackStr('settingmaxinputvars');
2802 return $result;
2804 return null;
2808 * Check whether the admin directory has been configured and warn if so.
2810 * The admin directory has been deprecated since Moodle 4.0.
2812 * @param environment_results $result
2813 * @return null|environment_results
2815 function check_admin_dir_usage(environment_results $result): ?environment_results {
2816 global $CFG;
2818 if (empty($CFG->admin)) {
2819 return null;
2822 if ($CFG->admin === 'admin') {
2823 return null;
2826 $result->setInfo('admin_dir_usage');
2827 $result->setStatus(false);
2829 return $result;
2833 * Check whether the XML-RPC protocol is enabled and warn if so.
2835 * The XML-RPC protocol will be removed in a future version (4.1) as it is no longer supported by PHP.
2837 * See MDL-70889 for further information.
2839 * @param environment_results $result
2840 * @return null|environment_results
2842 function check_xmlrpc_usage(environment_results $result): ?environment_results {
2843 global $CFG;
2845 // Checking Web Service protocols.
2846 if (!empty($CFG->webserviceprotocols)) {
2847 $plugins = array_flip(explode(',', $CFG->webserviceprotocols));
2848 if (array_key_exists('xmlrpc', $plugins)) {
2849 $result->setInfo('xmlrpc_webservice_usage');
2850 $result->setFeedbackStr('xmlrpcwebserviceenabled');
2851 return $result;
2855 return null;
2859 * Check whether the mod_assignment is currently being used.
2861 * @param environment_results $result
2862 * @return environment_results|null
2864 function check_mod_assignment(environment_results $result): ?environment_results {
2865 global $CFG, $DB;
2867 if (!file_exists("{$CFG->dirroot}/mod/assignment/version.php")) {
2868 // Check for mod_assignment instances.
2869 if ($DB->get_manager()->table_exists('assignment') && $DB->count_records('assignment') > 0) {
2870 $result->setInfo('Assignment 2.2 is in use');
2871 $result->setFeedbackStr('modassignmentinuse');
2872 return $result;
2875 // Check for mod_assignment subplugins.
2876 if (is_dir($CFG->dirroot . '/mod/assignment/type')) {
2877 $result->setInfo('Assignment 2.2 subplugins present');
2878 $result->setFeedbackStr('modassignmentsubpluginsexist');
2879 return $result;
2883 return null;
2887 * Check whether the Oracle database is currently being used and warn if so.
2889 * The Oracle database support will be removed in a future version (4.5) as it is no longer supported by PHP.
2891 * @param environment_results $result object to update, if relevant
2892 * @return environment_results|null updated results or null if the current database is not Oracle.
2894 * @see https://tracker.moodle.org/browse/MDL-80166 for further information.
2896 function check_oracle_usage(environment_results $result): ?environment_results {
2897 global $CFG;
2899 // Checking database type.
2900 if ($CFG->dbtype === 'oci') {
2901 $result->setInfo('oracle_database_usage');
2902 $result->setFeedbackStr('oracledatabaseinuse');
2903 return $result;
2906 return null;
2910 * Check if asynchronous backups are enabled.
2912 * @param environment_results $result
2913 * @return environment_results|null
2915 function check_async_backup(environment_results $result): ?environment_results {
2916 global $CFG;
2918 if (!during_initial_install() && empty($CFG->enableasyncbackup)) { // Have to use $CFG as config table may not be available.
2919 $result->setInfo('Asynchronous backups disabled');
2920 $result->setFeedbackStr('asyncbackupdisabled');
2921 return $result;
2924 return null;