3 // This file is part of Moodle - http://moodle.org/
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.
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/>.
19 * Various upgrade/install related functions and classes.
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);
37 * Exception indicating unknown error during 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) {
47 $a = (object)array('plugin'=>$plugin, 'version'=>$version);
48 parent
::__construct('upgradeerror', 'admin', "$CFG->wwwroot/$CFG->admin/index.php", $a, $debuginfo);
53 * Exception indicating downgrade error during 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) {
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);
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) {
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);
88 * Exception thrown when attempting to install a plugin that declares incompatibility with moodle version
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
{
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) {
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);
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) {
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.
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
{
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) {
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);
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
{
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
221 if (self
::$installation) {
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);
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.
276 * @param int $max_execution_time in seconds (can not be less than 60 s)
278 function upgrade_set_timeout($max_execution_time=300) {
281 if (!isset($CFG->upgraderunning
) or $CFG->upgraderunning
< time()) {
282 $upgraderunning = get_config(null, 'upgraderunning');
284 $upgraderunning = $CFG->upgraderunning
;
287 if (!$upgraderunning) {
289 // never stop CLI upgrades
292 // web upgrade not running or aborted
293 throw new \
moodle_exception('upgradetimedout', 'admin', "$CFG->wwwroot/$CFG->admin/");
297 if ($max_execution_time < 60) {
298 // protection against 0 here
299 $max_execution_time = 60;
302 $expected_end = time() +
$max_execution_time;
304 if ($expected_end < $upgraderunning +
10 and $expected_end > $upgraderunning - 10) {
305 // no need to store new end, it is nearly the same ;-)
310 // there is no point in timing out of CLI scripts, admins can stop them if necessary
311 core_php_time_limit
::raise();
313 core_php_time_limit
::raise($max_execution_time);
315 set_config('upgraderunning', $expected_end); // keep upgrade locked until this time
319 * Upgrade savepoint, marks end of each upgrade block.
320 * It stores new main version, resets upgrade timeout
321 * and abort upgrade if user cancels page loading.
323 * Please do not make large upgrade blocks with lots of operations,
324 * for example when adding tables keep only one table operation per block.
327 * @param bool $result false if upgrade step failed, true if completed
328 * @param string or float $version main version
329 * @param bool $allowabort allow user to abort script execution here
332 function upgrade_main_savepoint($result, $version, $allowabort=true) {
335 //sanity check to avoid confusion with upgrade_mod_savepoint usage.
336 if (!is_bool($allowabort)) {
337 $errormessage = 'Parameter type mismatch. Are you mixing up upgrade_main_savepoint() and upgrade_mod_savepoint()?';
338 throw new coding_exception($errormessage);
342 throw new upgrade_exception(null, $version);
345 if ($CFG->version
>= $version) {
346 // something really wrong is going on in main upgrade script
347 throw new downgrade_exception(null, $CFG->version
, $version);
350 set_config('version', $version);
351 upgrade_log(UPGRADE_LOG_NORMAL
, null, 'Upgrade savepoint reached');
353 // reset upgrade timeout to default
354 upgrade_set_timeout();
356 core_upgrade_time
::record_savepoint($version);
358 // this is a safe place to stop upgrades if user aborts page loading
359 if ($allowabort and connection_aborted()) {
365 * Module upgrade savepoint, marks end of module upgrade blocks
366 * It stores module version, resets upgrade timeout
367 * and abort upgrade if user cancels page loading.
370 * @param bool $result false if upgrade step failed, true if completed
371 * @param string or float $version main version
372 * @param string $modname name of module
373 * @param bool $allowabort allow user to abort script execution here
376 function upgrade_mod_savepoint($result, $version, $modname, $allowabort=true) {
379 $component = 'mod_'.$modname;
382 throw new upgrade_exception($component, $version);
385 $dbversion = $DB->get_field('config_plugins', 'value', array('plugin'=>$component, 'name'=>'version'));
387 if (!$module = $DB->get_record('modules', array('name'=>$modname))) {
388 throw new \
moodle_exception('modulenotexist', 'debug', '', $modname);
391 if ($dbversion >= $version) {
392 // something really wrong is going on in upgrade script
393 throw new downgrade_exception($component, $dbversion, $version);
395 set_config('version', $version, $component);
397 upgrade_log(UPGRADE_LOG_NORMAL
, $component, 'Upgrade savepoint reached');
399 // reset upgrade timeout to default
400 upgrade_set_timeout();
402 core_upgrade_time
::record_savepoint($version);
404 // this is a safe place to stop upgrades if user aborts page loading
405 if ($allowabort and connection_aborted()) {
411 * Blocks upgrade savepoint, marks end of blocks upgrade blocks
412 * It stores block version, resets upgrade timeout
413 * and abort upgrade if user cancels page loading.
416 * @param bool $result false if upgrade step failed, true if completed
417 * @param string or float $version main version
418 * @param string $blockname name of block
419 * @param bool $allowabort allow user to abort script execution here
422 function upgrade_block_savepoint($result, $version, $blockname, $allowabort=true) {
425 $component = 'block_'.$blockname;
428 throw new upgrade_exception($component, $version);
431 $dbversion = $DB->get_field('config_plugins', 'value', array('plugin'=>$component, 'name'=>'version'));
433 if (!$block = $DB->get_record('block', array('name'=>$blockname))) {
434 throw new \
moodle_exception('blocknotexist', 'debug', '', $blockname);
437 if ($dbversion >= $version) {
438 // something really wrong is going on in upgrade script
439 throw new downgrade_exception($component, $dbversion, $version);
441 set_config('version', $version, $component);
443 upgrade_log(UPGRADE_LOG_NORMAL
, $component, 'Upgrade savepoint reached');
445 // reset upgrade timeout to default
446 upgrade_set_timeout();
448 core_upgrade_time
::record_savepoint($version);
450 // this is a safe place to stop upgrades if user aborts page loading
451 if ($allowabort and connection_aborted()) {
457 * Plugins upgrade savepoint, marks end of blocks upgrade blocks
458 * It stores plugin version, resets upgrade timeout
459 * and abort upgrade if user cancels page loading.
462 * @param bool $result false if upgrade step failed, true if completed
463 * @param string or float $version main version
464 * @param string $type The type of the plugin.
465 * @param string $plugin The name of the plugin.
466 * @param bool $allowabort allow user to abort script execution here
469 function upgrade_plugin_savepoint($result, $version, $type, $plugin, $allowabort=true) {
472 $component = $type.'_'.$plugin;
475 throw new upgrade_exception($component, $version);
478 $dbversion = $DB->get_field('config_plugins', 'value', array('plugin'=>$component, 'name'=>'version'));
480 if ($dbversion >= $version) {
481 // Something really wrong is going on in the upgrade script
482 throw new downgrade_exception($component, $dbversion, $version);
484 set_config('version', $version, $component);
485 upgrade_log(UPGRADE_LOG_NORMAL
, $component, 'Upgrade savepoint reached');
487 // Reset upgrade timeout to default
488 upgrade_set_timeout();
490 core_upgrade_time
::record_savepoint($version);
492 // This is a safe place to stop upgrades if user aborts page loading
493 if ($allowabort and connection_aborted()) {
499 * Detect if there are leftovers in PHP source files.
501 * During main version upgrades administrators MUST move away
502 * old PHP source files and start from scratch (or better
505 * @return bool true means borked upgrade, false means previous PHP files were properly removed
507 function upgrade_stale_php_files_present(): bool {
510 $someexamplesofremovedfiles = [
512 '/admin/auth_config.php',
513 '/auth/yui/passwordunmask/passwordunmask.js',
514 '/lib/spout/readme_moodle.txt',
515 '/lib/yui/src/tooltip/js/tooltip.js',
517 '/mod/forum/classes/task/refresh_forum_post_counts.php',
518 '/user/amd/build/participantsfilter.min.js',
519 '/user/amd/src/participantsfilter.js',
521 '/admin/classes/task_log_table.php',
522 '/admin/cli/mysql_engine.php',
523 '/lib/babel-polyfill/polyfill.js',
524 '/lib/typo3/class.t3lib_cs.php',
525 '/question/tests/category_class_test.php',
527 '/customfield/edit.php',
528 '/lib/phpunit/classes/autoloader.php',
529 '/lib/xhprof/README',
530 '/message/defaultoutputs.php',
531 '/user/files_form.php',
533 '/grade/grading/classes/privacy/gradingform_provider.php',
534 '/lib/coursecatlib.php',
535 '/lib/form/htmleditor.php',
536 '/message/classes/output/messagearea/contact.php',
538 '/course/classes/output/modchooser_item.php',
539 '/course/yui/build/moodle-course-modchooser/moodle-course-modchooser-min.js',
540 '/course/yui/src/modchooser/js/modchooser.js',
541 '/h5p/classes/autoloader.php',
542 '/lib/adodb/readme.txt',
543 '/lib/maxmind/GeoIp2/Compat/JsonSerializable.php',
545 '/lib/amd/src/modal_confirm.js',
546 '/lib/fonts/font-awesome-4.7.0/css/font-awesome.css',
547 '/lib/jquery/jquery-3.2.1.min.js',
548 '/lib/recaptchalib.php',
549 '/lib/sessionkeepalive_ajax.php',
550 '/lib/yui/src/checknet/js/checknet.js',
551 '/question/amd/src/qbankmanager.js',
553 '/lib/form/yui/src/showadvanced/js/showadvanced.js',
554 '/lib/tests/output_external_test.php',
555 '/message/amd/src/message_area.js',
556 '/message/templates/message_area.mustache',
557 '/question/yui/src/qbankmanager/build.json',
559 '/lib/classes/session/memcache.php',
560 '/lib/eventslib.php',
561 '/lib/form/submitlink.php',
563 '/lib/password_compat/lib/password.php',
565 '/lib/dml/mssql_native_moodle_database.php',
566 '/lib/dml/mssql_native_moodle_recordset.php',
567 '/lib/dml/mssql_native_moodle_temptables.php',
572 '/enrol/yui/rolemanager/assets/skins/sam/rolemanager.css',
574 '/badges/backpackconnect.php',
575 '/calendar/yui/src/info/assets/skins/sam/moodle-calendar-info.css',
576 '/competency/classes/external/exporter.php',
577 '/mod/forum/forum.js',
578 '/user/pixgroup.php',
580 '/calendar/preferences.php',
582 '/lib/jquery/jquery-1.12.1.min.js',
583 '/lib/password_compat/tests/',
584 '/lib/phpunit/classes/unittestcase.php',
586 '/lib/classes/log/sql_internal_reader.php',
588 '/mod/forum/pix/icon.gif',
589 '/tag/templates/tagname.mustache',
591 '/tag/coursetagslib.php',
595 '/course/delete_category_form.php',
597 '/admin/tool/qeupgradehelper/version.php',
600 '/admin/oacleanup.php',
603 '/backup/bb/README.txt',
604 '/lib/excel/test.php',
606 '/admin/tool/unittest/simpletestlib.php',
608 '/lib/minify/builder/',
610 '/lib/yui/3.4.1pr1/',
612 '/search/cron_php5.php',
613 '/course/report/log/indexlive.php',
614 '/admin/report/backups/index.php',
615 '/admin/generator.php',
619 '/blocks/admin/block_admin.php',
620 '/blocks/admin_tree/block_admin_tree.php',
623 foreach ($someexamplesofremovedfiles as $file) {
624 if (file_exists($CFG->dirroot
.$file)) {
633 * After upgrading a module, block, or generic plugin, various parts of the system need to be
636 * @param string $component Frankenstyle component or 'moodle' for core
637 * @param string $messageplug Set to the name of a message plugin if this is one
638 * @param bool $coreinstall Set to true if this is the core install
640 function upgrade_component_updated(string $component, string $messageplug = '',
641 bool $coreinstall = false): void
{
643 update_capabilities($component);
644 core_upgrade_time
::record_detail('update_capabilities');
646 log_update_descriptions($component);
647 core_upgrade_time
::record_detail('log_update_descriptions');
648 external_update_descriptions($component);
649 core_upgrade_time
::record_detail('external_update_descriptions');
650 \core\task\manager
::reset_scheduled_tasks_for_component($component);
651 core_upgrade_time
::record_detail('\core\task\manager::reset_scheduled_tasks_for_component');
652 \core_analytics\manager
::update_default_models_for_component($component);
653 core_upgrade_time
::record_detail('\core_analytics\manager::update_default_models_for_component');
654 message_update_providers($component);
655 core_upgrade_time
::record_detail('message_update_providers');
656 \core\message\inbound\manager
::update_handlers_for_component($component);
657 core_upgrade_time
::record_detail('\core\message\inbound\manager::update_handlers_for_component');
658 if ($messageplug !== '') {
660 message_update_processors($messageplug);
661 core_upgrade_time
::record_detail('message_update_processors');
663 if ($component !== 'moodle') {
664 // This one is not run for core upgrades.
665 upgrade_plugin_mnet_functions($component);
666 core_upgrade_time
::record_detail('upgrade_plugin_mnet_functions');
668 core_tag_area
::reset_definitions_for_component($component);
669 core_upgrade_time
::record_detail('core_tag_area::reset_definitions_for_component');
674 * @param string $type The type of plugins that should be updated (e.g. 'enrol', 'qtype')
677 function upgrade_plugins($type, $startcallback, $endcallback, $verbose) {
681 if ($type === 'mod') {
682 return upgrade_plugins_modules($startcallback, $endcallback, $verbose);
683 } else if ($type === 'block') {
684 return upgrade_plugins_blocks($startcallback, $endcallback, $verbose);
687 $plugs = core_component
::get_plugin_list($type);
689 foreach ($plugs as $plug=>$fullplug) {
690 // Reset time so that it works when installing a large number of plugins
691 core_php_time_limit
::raise(600);
692 $component = clean_param($type.'_'.$plug, PARAM_COMPONENT
); // standardised plugin name
694 // check plugin dir is valid name
695 if (empty($component)) {
696 throw new plugin_defective_exception($type.'_'.$plug, 'Invalid plugin directory name.');
699 if (!is_readable($fullplug.'/version.php')) {
703 $plugin = new stdClass();
704 $plugin->version
= null;
705 $module = $plugin; // Prevent some notices when plugin placed in wrong directory.
706 require($fullplug.'/version.php'); // defines $plugin with version etc
709 if (empty($plugin->version
)) {
710 throw new plugin_defective_exception($component, 'Missing $plugin->version number in version.php.');
713 if (empty($plugin->component
)) {
714 throw new plugin_defective_exception($component, 'Missing $plugin->component declaration in version.php.');
717 if ($plugin->component
!== $component) {
718 throw new plugin_misplaced_exception($plugin->component
, null, $fullplug);
721 $plugin->name
= $plug;
722 $plugin->fullname
= $component;
724 if (!empty($plugin->requires
)) {
725 if ($plugin->requires
> $CFG->version
) {
726 throw new upgrade_requires_exception($component, $plugin->version
, $CFG->version
, $plugin->requires
);
727 } else if ($plugin->requires
< 2010000000) {
728 throw new plugin_defective_exception($component, 'Plugin is not compatible with Moodle 2.x or later.');
732 // Throw exception if plugin is incompatible with moodle version.
733 if (!empty($plugin->incompatible
)) {
734 if ($CFG->branch
>= $plugin->incompatible
) {
735 throw new plugin_incompatible_exception($component, $plugin->version
);
739 // try to recover from interrupted install.php if needed
740 if (file_exists($fullplug.'/db/install.php')) {
741 if (get_config($plugin->fullname
, 'installrunning')) {
742 require_once($fullplug.'/db/install.php');
743 $recover_install_function = 'xmldb_'.$plugin->fullname
.'_install_recovery';
744 if (function_exists($recover_install_function)) {
745 $startcallback($component, true, $verbose);
746 $recover_install_function();
747 unset_config('installrunning', $plugin->fullname
);
748 upgrade_component_updated($component, $type === 'message' ?
$plug : '');
749 $endcallback($component, true, $verbose);
754 $installedversion = $DB->get_field('config_plugins', 'value', array('name'=>'version', 'plugin'=>$component)); // No caching!
755 if (empty($installedversion)) { // new installation
756 $startcallback($component, true, $verbose);
758 /// Install tables if defined
759 if (file_exists($fullplug.'/db/install.xml')) {
760 $DB->get_manager()->install_from_xmldb_file($fullplug.'/db/install.xml');
761 core_upgrade_time
::record_detail('install.xml');
765 upgrade_plugin_savepoint(true, $plugin->version
, $type, $plug, false);
767 /// execute post install file
768 if (file_exists($fullplug.'/db/install.php')) {
769 require_once($fullplug.'/db/install.php');
770 set_config('installrunning', 1, $plugin->fullname
);
771 $post_install_function = 'xmldb_'.$plugin->fullname
.'_install';
772 $post_install_function();
773 unset_config('installrunning', $plugin->fullname
);
774 core_upgrade_time
::record_detail('install.php');
777 /// Install various components
778 upgrade_component_updated($component, $type === 'message' ?
$plug : '');
779 $endcallback($component, true, $verbose);
781 } else if ($installedversion < $plugin->version
) { // upgrade
782 /// Run the upgrade function for the plugin.
783 $startcallback($component, false, $verbose);
785 if (is_readable($fullplug.'/db/upgrade.php')) {
786 require_once($fullplug.'/db/upgrade.php'); // defines upgrading function
788 $newupgrade_function = 'xmldb_'.$plugin->fullname
.'_upgrade';
789 $result = $newupgrade_function($installedversion);
790 core_upgrade_time
::record_detail('upgrade.php');
795 $installedversion = $DB->get_field('config_plugins', 'value', array('name'=>'version', 'plugin'=>$component)); // No caching!
796 if ($installedversion < $plugin->version
) {
797 // store version if not already there
798 upgrade_plugin_savepoint($result, $plugin->version
, $type, $plug, false);
801 /// Upgrade various components
802 upgrade_component_updated($component, $type === 'message' ?
$plug : '');
803 $endcallback($component, false, $verbose);
805 } else if ($installedversion > $plugin->version
) {
806 throw new downgrade_exception($component, $installedversion, $plugin->version
);
812 * Find and check all modules and load them up or upgrade them if necessary
817 function upgrade_plugins_modules($startcallback, $endcallback, $verbose) {
820 $mods = core_component
::get_plugin_list('mod');
822 foreach ($mods as $mod=>$fullmod) {
824 if ($mod === 'NEWMODULE') { // Someone has unzipped the template, ignore it
828 $component = clean_param('mod_'.$mod, PARAM_COMPONENT
);
830 // check module dir is valid name
831 if (empty($component)) {
832 throw new plugin_defective_exception('mod_'.$mod, 'Invalid plugin directory name.');
835 if (!is_readable($fullmod.'/version.php')) {
836 throw new plugin_defective_exception($component, 'Missing version.php');
839 $module = new stdClass();
840 $plugin = new stdClass();
841 $plugin->version
= null;
842 require($fullmod .'/version.php'); // Defines $plugin with version etc.
844 // Check if the legacy $module syntax is still used.
845 if (!is_object($module) or (count((array)$module) > 0)) {
846 throw new plugin_defective_exception($component, 'Unsupported $module syntax detected in version.php');
849 // Prepare the record for the {modules} table.
850 $module = clone($plugin);
851 unset($module->version
);
852 unset($module->component
);
853 unset($module->dependencies
);
854 unset($module->release
);
856 if (empty($plugin->version
)) {
857 throw new plugin_defective_exception($component, 'Missing $plugin->version number in version.php.');
860 if (empty($plugin->component
)) {
861 throw new plugin_defective_exception($component, 'Missing $plugin->component declaration in version.php.');
864 if ($plugin->component
!== $component) {
865 throw new plugin_misplaced_exception($plugin->component
, null, $fullmod);
868 if (!empty($plugin->requires
)) {
869 if ($plugin->requires
> $CFG->version
) {
870 throw new upgrade_requires_exception($component, $plugin->version
, $CFG->version
, $plugin->requires
);
871 } else if ($plugin->requires
< 2010000000) {
872 throw new plugin_defective_exception($component, 'Plugin is not compatible with Moodle 2.x or later.');
876 if (empty($module->cron
)) {
880 // all modules must have en lang pack
881 if (!is_readable("$fullmod/lang/en/$mod.php")) {
882 throw new plugin_defective_exception($component, 'Missing mandatory en language pack.');
885 $module->name
= $mod; // The name MUST match the directory
887 $installedversion = $DB->get_field('config_plugins', 'value', array('name'=>'version', 'plugin'=>$component)); // No caching!
889 if (file_exists($fullmod.'/db/install.php')) {
890 if (get_config($module->name
, 'installrunning')) {
891 require_once($fullmod.'/db/install.php');
892 $recover_install_function = 'xmldb_'.$module->name
.'_install_recovery';
893 if (function_exists($recover_install_function)) {
894 $startcallback($component, true, $verbose);
895 $recover_install_function();
896 unset_config('installrunning', $module->name
);
897 // Install various components too
898 upgrade_component_updated($component);
899 $endcallback($component, true, $verbose);
904 if (empty($installedversion)) {
905 $startcallback($component, true, $verbose);
907 /// Execute install.xml (XMLDB) - must be present in all modules
908 $DB->get_manager()->install_from_xmldb_file($fullmod.'/db/install.xml');
909 core_upgrade_time
::record_detail('install.xml');
911 /// Add record into modules table - may be needed in install.php already
912 $module->id
= $DB->insert_record('modules', $module);
913 core_upgrade_time
::record_detail('insert_record');
914 upgrade_mod_savepoint(true, $plugin->version
, $module->name
, false);
916 /// Post installation hook - optional
917 if (file_exists("$fullmod/db/install.php")) {
918 require_once("$fullmod/db/install.php");
919 // Set installation running flag, we need to recover after exception or error
920 set_config('installrunning', 1, $module->name
);
921 $post_install_function = 'xmldb_'.$module->name
.'_install';
922 $post_install_function();
923 unset_config('installrunning', $module->name
);
924 core_upgrade_time
::record_detail('install.php');
927 /// Install various components
928 upgrade_component_updated($component);
930 $endcallback($component, true, $verbose);
932 } else if ($installedversion < $plugin->version
) {
933 /// If versions say that we need to upgrade but no upgrade files are available, notify and continue
934 $startcallback($component, false, $verbose);
936 if (is_readable($fullmod.'/db/upgrade.php')) {
937 require_once($fullmod.'/db/upgrade.php'); // defines new upgrading function
938 $newupgrade_function = 'xmldb_'.$module->name
.'_upgrade';
939 $result = $newupgrade_function($installedversion, $module);
940 core_upgrade_time
::record_detail('upgrade.php');
945 $installedversion = $DB->get_field('config_plugins', 'value', array('name'=>'version', 'plugin'=>$component)); // No caching!
946 $currmodule = $DB->get_record('modules', array('name'=>$module->name
));
947 if ($installedversion < $plugin->version
) {
948 // store version if not already there
949 upgrade_mod_savepoint($result, $plugin->version
, $mod, false);
952 // update cron flag if needed
953 if ($currmodule->cron
!= $module->cron
) {
954 $DB->set_field('modules', 'cron', $module->cron
, array('name' => $module->name
));
957 // Upgrade various components
958 upgrade_component_updated($component);
960 $endcallback($component, false, $verbose);
962 } else if ($installedversion > $plugin->version
) {
963 throw new downgrade_exception($component, $installedversion, $plugin->version
);
970 * This function finds all available blocks and install them
971 * into blocks table or do all the upgrade process if newer.
976 function upgrade_plugins_blocks($startcallback, $endcallback, $verbose) {
979 require_once($CFG->dirroot
.'/blocks/moodleblock.class.php');
981 $blocktitles = array(); // we do not want duplicate titles
983 //Is this a first install
984 $first_install = null;
986 $blocks = core_component
::get_plugin_list('block');
988 foreach ($blocks as $blockname=>$fullblock) {
990 if (is_null($first_install)) {
991 $first_install = ($DB->count_records('block_instances') == 0);
994 if ($blockname === 'NEWBLOCK') { // Someone has unzipped the template, ignore it
998 $component = clean_param('block_'.$blockname, PARAM_COMPONENT
);
1000 // check block dir is valid name
1001 if (empty($component)) {
1002 throw new plugin_defective_exception('block_'.$blockname, 'Invalid plugin directory name.');
1005 if (!is_readable($fullblock.'/version.php')) {
1006 throw new plugin_defective_exception('block/'.$blockname, 'Missing version.php file.');
1008 $plugin = new stdClass();
1009 $plugin->version
= null;
1011 $module = $plugin; // Prevent some notices when module placed in wrong directory.
1012 include($fullblock.'/version.php');
1014 $block = clone($plugin);
1015 unset($block->version
);
1016 unset($block->component
);
1017 unset($block->dependencies
);
1018 unset($block->release
);
1020 if (empty($plugin->version
)) {
1021 throw new plugin_defective_exception($component, 'Missing block version number in version.php.');
1024 if (empty($plugin->component
)) {
1025 throw new plugin_defective_exception($component, 'Missing $plugin->component declaration in version.php.');
1028 if ($plugin->component
!== $component) {
1029 throw new plugin_misplaced_exception($plugin->component
, null, $fullblock);
1032 if (!empty($plugin->requires
)) {
1033 if ($plugin->requires
> $CFG->version
) {
1034 throw new upgrade_requires_exception($component, $plugin->version
, $CFG->version
, $plugin->requires
);
1035 } else if ($plugin->requires
< 2010000000) {
1036 throw new plugin_defective_exception($component, 'Plugin is not compatible with Moodle 2.x or later.');
1040 if (!is_readable($fullblock.'/block_'.$blockname.'.php')) {
1041 throw new plugin_defective_exception('block/'.$blockname, 'Missing main block class file.');
1043 include_once($fullblock.'/block_'.$blockname.'.php');
1045 $classname = 'block_'.$blockname;
1047 if (!class_exists($classname)) {
1048 throw new plugin_defective_exception($component, 'Can not load main class.');
1051 $blockobj = new $classname; // This is what we'll be testing
1052 $blocktitle = $blockobj->get_title();
1054 // OK, it's as we all hoped. For further tests, the object will do them itself.
1055 if (!$blockobj->_self_test()) {
1056 throw new plugin_defective_exception($component, 'Self test failed.');
1059 $block->name
= $blockname; // The name MUST match the directory
1061 $installedversion = $DB->get_field('config_plugins', 'value', array('name'=>'version', 'plugin'=>$component)); // No caching!
1063 if (file_exists($fullblock.'/db/install.php')) {
1064 if (get_config('block_'.$blockname, 'installrunning')) {
1065 require_once($fullblock.'/db/install.php');
1066 $recover_install_function = 'xmldb_block_'.$blockname.'_install_recovery';
1067 if (function_exists($recover_install_function)) {
1068 $startcallback($component, true, $verbose);
1069 $recover_install_function();
1070 unset_config('installrunning', 'block_'.$blockname);
1071 // Install various components
1072 upgrade_component_updated($component);
1073 $endcallback($component, true, $verbose);
1078 if (empty($installedversion)) { // block not installed yet, so install it
1079 $conflictblock = array_search($blocktitle, $blocktitles);
1080 if ($conflictblock !== false) {
1081 // Duplicate block titles are not allowed, they confuse people
1082 // AND PHP's associative arrays ;)
1083 throw new plugin_defective_exception($component, get_string('blocknameconflict', 'error', (object)array('name'=>$block->name
, 'conflict'=>$conflictblock)));
1085 $startcallback($component, true, $verbose);
1087 if (file_exists($fullblock.'/db/install.xml')) {
1088 $DB->get_manager()->install_from_xmldb_file($fullblock.'/db/install.xml');
1089 core_upgrade_time
::record_detail('install.xml');
1091 $block->id
= $DB->insert_record('block', $block);
1092 core_upgrade_time
::record_detail('insert_record');
1093 upgrade_block_savepoint(true, $plugin->version
, $block->name
, false);
1095 if (file_exists($fullblock.'/db/install.php')) {
1096 require_once($fullblock.'/db/install.php');
1097 // Set installation running flag, we need to recover after exception or error
1098 set_config('installrunning', 1, 'block_'.$blockname);
1099 $post_install_function = 'xmldb_block_'.$blockname.'_install';
1100 $post_install_function();
1101 unset_config('installrunning', 'block_'.$blockname);
1102 core_upgrade_time
::record_detail('install.php');
1105 $blocktitles[$block->name
] = $blocktitle;
1107 // Install various components
1108 upgrade_component_updated($component);
1110 $endcallback($component, true, $verbose);
1112 } else if ($installedversion < $plugin->version
) {
1113 $startcallback($component, false, $verbose);
1115 if (is_readable($fullblock.'/db/upgrade.php')) {
1116 require_once($fullblock.'/db/upgrade.php'); // defines new upgrading function
1117 $newupgrade_function = 'xmldb_block_'.$blockname.'_upgrade';
1118 $result = $newupgrade_function($installedversion, $block);
1119 core_upgrade_time
::record_detail('upgrade.php');
1124 $installedversion = $DB->get_field('config_plugins', 'value', array('name'=>'version', 'plugin'=>$component)); // No caching!
1125 $currblock = $DB->get_record('block', array('name'=>$block->name
));
1126 if ($installedversion < $plugin->version
) {
1127 // store version if not already there
1128 upgrade_block_savepoint($result, $plugin->version
, $block->name
, false);
1131 if ($currblock->cron
!= $block->cron
) {
1132 // update cron flag if needed
1133 $DB->set_field('block', 'cron', $block->cron
, array('id' => $currblock->id
));
1136 // Upgrade various components
1137 upgrade_component_updated($component);
1139 $endcallback($component, false, $verbose);
1141 } else if ($installedversion > $plugin->version
) {
1142 throw new downgrade_exception($component, $installedversion, $plugin->version
);
1147 // Finally, if we are in the first_install of BLOCKS setup frontpage and admin page blocks
1148 if ($first_install) {
1149 //Iterate over each course - there should be only site course here now
1150 if ($courses = $DB->get_records('course')) {
1151 foreach ($courses as $course) {
1152 blocks_add_default_course_blocks($course);
1156 blocks_add_default_system_blocks();
1162 * Log_display description function used during install and upgrade.
1164 * @param string $component name of component (moodle, mod_assignment, etc.)
1167 function log_update_descriptions($component) {
1170 $defpath = core_component
::get_component_directory($component).'/db/log.php';
1172 if (!file_exists($defpath)) {
1173 $DB->delete_records('log_display', array('component'=>$component));
1181 foreach ($logs as $log) {
1182 $newlogs[$log['module'].'-'.$log['action']] = $log; // kind of unique name
1187 $fields = array('module', 'action', 'mtable', 'field');
1188 // update all log fist
1189 $dblogs = $DB->get_records('log_display', array('component'=>$component));
1190 foreach ($dblogs as $dblog) {
1191 $name = $dblog->module
.'-'.$dblog->action
;
1193 if (empty($logs[$name])) {
1194 $DB->delete_records('log_display', array('id'=>$dblog->id
));
1198 $log = $logs[$name];
1199 unset($logs[$name]);
1202 foreach ($fields as $field) {
1203 if ($dblog->$field != $log[$field]) {
1204 $dblog->$field = $log[$field];
1209 $DB->update_record('log_display', $dblog);
1212 foreach ($logs as $log) {
1213 $dblog = (object)$log;
1214 $dblog->component
= $component;
1215 $DB->insert_record('log_display', $dblog);
1220 * Web service discovery function used during install and upgrade.
1221 * @param string $component name of component (moodle, mod_assignment, etc.)
1224 function external_update_descriptions($component) {
1227 $defpath = core_component
::get_component_directory($component).'/db/services.php';
1229 if (!file_exists($defpath)) {
1230 \core_external\util
::delete_service_descriptions($component);
1235 $functions = array();
1236 $services = array();
1239 // update all function fist
1240 $dbfunctions = $DB->get_records('external_functions', array('component'=>$component));
1241 foreach ($dbfunctions as $dbfunction) {
1242 if (empty($functions[$dbfunction->name
])) {
1243 $DB->delete_records('external_functions', array('id'=>$dbfunction->id
));
1244 // do not delete functions from external_services_functions, beacuse
1245 // we want to notify admins when functions used in custom services disappear
1247 //TODO: this looks wrong, we have to delete it eventually (skodak)
1251 $function = $functions[$dbfunction->name
];
1252 unset($functions[$dbfunction->name
]);
1253 $function['classpath'] = empty($function['classpath']) ?
null : $function['classpath'];
1254 $function['methodname'] = $function['methodname'] ??
'execute';
1257 if ($dbfunction->classname
!= $function['classname']) {
1258 $dbfunction->classname
= $function['classname'];
1261 if ($dbfunction->methodname
!= $function['methodname']) {
1262 $dbfunction->methodname
= $function['methodname'];
1265 if ($dbfunction->classpath
!= $function['classpath']) {
1266 $dbfunction->classpath
= $function['classpath'];
1269 $functioncapabilities = array_key_exists('capabilities', $function)?
$function['capabilities']:'';
1270 if ($dbfunction->capabilities
!= $functioncapabilities) {
1271 $dbfunction->capabilities
= $functioncapabilities;
1275 if (isset($function['services']) and is_array($function['services'])) {
1276 sort($function['services']);
1277 $functionservices = implode(',', $function['services']);
1279 // Force null values in the DB.
1280 $functionservices = null;
1283 if ($dbfunction->services
!= $functionservices) {
1284 // Now, we need to check if services were removed, in that case we need to remove the function from them.
1285 $servicesremoved = array_diff(explode(",", $dbfunction->services
), explode(",", $functionservices));
1286 foreach ($servicesremoved as $removedshortname) {
1287 if ($externalserviceid = $DB->get_field('external_services', 'id', array("shortname" => $removedshortname))) {
1288 $DB->delete_records('external_services_functions', array('functionname' => $dbfunction->name
,
1289 'externalserviceid' => $externalserviceid));
1293 $dbfunction->services
= $functionservices;
1297 $DB->update_record('external_functions', $dbfunction);
1300 foreach ($functions as $fname => $function) {
1301 $dbfunction = new stdClass();
1302 $dbfunction->name
= $fname;
1303 $dbfunction->classname
= $function['classname'];
1304 $dbfunction->methodname
= $function['methodname'] ??
'execute';
1305 $dbfunction->classpath
= empty($function['classpath']) ?
null : $function['classpath'];
1306 $dbfunction->component
= $component;
1307 $dbfunction->capabilities
= array_key_exists('capabilities', $function)?
$function['capabilities']:'';
1309 if (isset($function['services']) and is_array($function['services'])) {
1310 sort($function['services']);
1311 $dbfunction->services
= implode(',', $function['services']);
1313 // Force null values in the DB.
1314 $dbfunction->services
= null;
1317 $dbfunction->id
= $DB->insert_record('external_functions', $dbfunction);
1321 // now deal with services
1322 $dbservices = $DB->get_records('external_services', array('component'=>$component));
1323 foreach ($dbservices as $dbservice) {
1324 if (empty($services[$dbservice->name
])) {
1325 $DB->delete_records('external_tokens', array('externalserviceid'=>$dbservice->id
));
1326 $DB->delete_records('external_services_functions', array('externalserviceid'=>$dbservice->id
));
1327 $DB->delete_records('external_services_users', array('externalserviceid'=>$dbservice->id
));
1328 $DB->delete_records('external_services', array('id'=>$dbservice->id
));
1331 $service = $services[$dbservice->name
];
1332 unset($services[$dbservice->name
]);
1333 $service['enabled'] = empty($service['enabled']) ?
0 : $service['enabled'];
1334 $service['requiredcapability'] = empty($service['requiredcapability']) ?
null : $service['requiredcapability'];
1335 $service['restrictedusers'] = !isset($service['restrictedusers']) ?
1 : $service['restrictedusers'];
1336 $service['downloadfiles'] = !isset($service['downloadfiles']) ?
0 : $service['downloadfiles'];
1337 $service['uploadfiles'] = !isset($service['uploadfiles']) ?
0 : $service['uploadfiles'];
1338 $service['shortname'] = !isset($service['shortname']) ?
null : $service['shortname'];
1341 if ($dbservice->requiredcapability
!= $service['requiredcapability']) {
1342 $dbservice->requiredcapability
= $service['requiredcapability'];
1345 if ($dbservice->restrictedusers
!= $service['restrictedusers']) {
1346 $dbservice->restrictedusers
= $service['restrictedusers'];
1349 if ($dbservice->downloadfiles
!= $service['downloadfiles']) {
1350 $dbservice->downloadfiles
= $service['downloadfiles'];
1353 if ($dbservice->uploadfiles
!= $service['uploadfiles']) {
1354 $dbservice->uploadfiles
= $service['uploadfiles'];
1357 //if shortname is not a PARAM_ALPHANUMEXT, fail (tested here for service update and creation)
1358 if (isset($service['shortname']) and
1359 (clean_param($service['shortname'], PARAM_ALPHANUMEXT
) != $service['shortname'])) {
1360 throw new moodle_exception('installserviceshortnameerror', 'webservice', '', $service['shortname']);
1362 if ($dbservice->shortname
!= $service['shortname']) {
1363 //check that shortname is unique
1364 if (isset($service['shortname'])) { //we currently accepts multiple shortname == null
1365 $existingservice = $DB->get_record('external_services',
1366 array('shortname' => $service['shortname']));
1367 if (!empty($existingservice)) {
1368 throw new moodle_exception('installexistingserviceshortnameerror', 'webservice', '', $service['shortname']);
1371 $dbservice->shortname
= $service['shortname'];
1375 $DB->update_record('external_services', $dbservice);
1378 $functions = $DB->get_records('external_services_functions', array('externalserviceid'=>$dbservice->id
));
1379 foreach ($functions as $function) {
1380 $key = array_search($function->functionname
, $service['functions']);
1381 if ($key === false) {
1382 $DB->delete_records('external_services_functions', array('id'=>$function->id
));
1384 unset($service['functions'][$key]);
1387 foreach ($service['functions'] as $fname) {
1388 $newf = new stdClass();
1389 $newf->externalserviceid
= $dbservice->id
;
1390 $newf->functionname
= $fname;
1391 $DB->insert_record('external_services_functions', $newf);
1395 foreach ($services as $name => $service) {
1396 //check that shortname is unique
1397 if (isset($service['shortname'])) { //we currently accepts multiple shortname == null
1398 $existingservice = $DB->get_record('external_services',
1399 array('shortname' => $service['shortname']));
1400 if (!empty($existingservice)) {
1401 throw new moodle_exception('installserviceshortnameerror', 'webservice');
1405 $dbservice = new stdClass();
1406 $dbservice->name
= $name;
1407 $dbservice->enabled
= empty($service['enabled']) ?
0 : $service['enabled'];
1408 $dbservice->requiredcapability
= empty($service['requiredcapability']) ?
null : $service['requiredcapability'];
1409 $dbservice->restrictedusers
= !isset($service['restrictedusers']) ?
1 : $service['restrictedusers'];
1410 $dbservice->downloadfiles
= !isset($service['downloadfiles']) ?
0 : $service['downloadfiles'];
1411 $dbservice->uploadfiles
= !isset($service['uploadfiles']) ?
0 : $service['uploadfiles'];
1412 $dbservice->shortname
= !isset($service['shortname']) ?
null : $service['shortname'];
1413 $dbservice->component
= $component;
1414 $dbservice->timecreated
= time();
1415 $dbservice->id
= $DB->insert_record('external_services', $dbservice);
1416 foreach ($service['functions'] as $fname) {
1417 $newf = new stdClass();
1418 $newf->externalserviceid
= $dbservice->id
;
1419 $newf->functionname
= $fname;
1420 $DB->insert_record('external_services_functions', $newf);
1426 * Allow plugins and subsystems to add external functions to other plugins or built-in services.
1427 * This function is executed just after all the plugins have been updated.
1429 function external_update_services() {
1432 // Look for external functions that want to be added in existing services.
1433 $functions = $DB->get_records_select('external_functions', 'services IS NOT NULL');
1435 $servicescache = array();
1436 foreach ($functions as $function) {
1437 // Prevent edge cases.
1438 if (empty($function->services
)) {
1441 $services = explode(',', $function->services
);
1443 foreach ($services as $serviceshortname) {
1444 // Get the service id by shortname.
1445 if (!empty($servicescache[$serviceshortname])) {
1446 $serviceid = $servicescache[$serviceshortname];
1447 } else if ($service = $DB->get_record('external_services', array('shortname' => $serviceshortname))) {
1448 // If the component is empty, it means that is not a built-in service.
1449 // We don't allow functions to inject themselves in services created by an user in Moodle.
1450 if (empty($service->component
)) {
1453 $serviceid = $service->id
;
1454 $servicescache[$serviceshortname] = $serviceid;
1456 // Service not found.
1459 // Finally add the function to the service.
1460 $newf = new stdClass();
1461 $newf->externalserviceid
= $serviceid;
1462 $newf->functionname
= $function->name
;
1464 if (!$DB->record_exists('external_services_functions', (array)$newf)) {
1465 $DB->insert_record('external_services_functions', $newf);
1472 * upgrade logging functions
1474 function upgrade_handle_exception($ex, $plugin = null) {
1477 // rollback everything, we need to log all upgrade problems
1478 abort_all_db_transactions();
1480 $info = get_exception_info($ex);
1482 // First log upgrade error
1483 upgrade_log(UPGRADE_LOG_ERROR
, $plugin, 'Exception: ' . get_class($ex), $info->message
, $info->backtrace
);
1485 // Always turn on debugging - admins need to know what is going on
1486 set_debugging(DEBUG_DEVELOPER
, true);
1488 default_exception_handler($ex, true, $plugin);
1492 * Adds log entry into upgrade_log table
1494 * @param int $type UPGRADE_LOG_NORMAL, UPGRADE_LOG_NOTICE or UPGRADE_LOG_ERROR
1495 * @param string $plugin frankenstyle component name
1496 * @param string $info short description text of log entry
1497 * @param string $details long problem description
1498 * @param string $backtrace string used for errors only
1501 function upgrade_log($type, $plugin, $info, $details=null, $backtrace=null) {
1502 global $DB, $USER, $CFG;
1504 if (empty($plugin)) {
1508 list($plugintype, $pluginname) = core_component
::normalize_component($plugin);
1509 $component = is_null($pluginname) ?
$plugintype : $plugintype . '_' . $pluginname;
1511 $backtrace = format_backtrace($backtrace, true);
1513 $currentversion = null;
1514 $targetversion = null;
1516 //first try to find out current version number
1517 if ($plugintype === 'core') {
1519 $currentversion = $CFG->version
;
1522 include("$CFG->dirroot/version.php");
1523 $targetversion = $version;
1526 $pluginversion = get_config($component, 'version');
1527 if (!empty($pluginversion)) {
1528 $currentversion = $pluginversion;
1530 $cd = core_component
::get_component_directory($component);
1531 if (file_exists("$cd/version.php")) {
1532 $plugin = new stdClass();
1533 $plugin->version
= null;
1535 include("$cd/version.php");
1536 $targetversion = $plugin->version
;
1540 $log = new stdClass();
1542 $log->plugin
= $component;
1543 $log->version
= $currentversion;
1544 $log->targetversion
= $targetversion;
1546 $log->details
= $details;
1547 $log->backtrace
= $backtrace;
1548 $log->userid
= $USER->id
;
1549 $log->timemodified
= time();
1551 $DB->insert_record('upgrade_log', $log);
1552 } catch (Exception
$ignored) {
1553 // possible during install or 2.0 upgrade
1558 * Marks start of upgrade, blocks any other access to site.
1559 * The upgrade is finished at the end of script or after timeout.
1565 function upgrade_started($preinstall=false) {
1566 global $CFG, $DB, $PAGE, $OUTPUT;
1568 static $started = false;
1571 ignore_user_abort(true);
1572 upgrade_setup_debug(true);
1574 } else if ($started) {
1575 upgrade_set_timeout(120);
1578 if (!CLI_SCRIPT
and !$PAGE->headerprinted
) {
1579 $strupgrade = get_string('upgradingversion', 'admin');
1580 $PAGE->set_pagelayout('maintenance');
1581 upgrade_init_javascript();
1582 $PAGE->set_title($strupgrade.' - Moodle '.$CFG->target_release
);
1583 $PAGE->set_heading($strupgrade);
1584 $PAGE->navbar
->add($strupgrade);
1585 $PAGE->set_cacheable(false);
1586 echo $OUTPUT->header();
1589 ignore_user_abort(true);
1590 core_shutdown_manager
::register_function('upgrade_finished_handler');
1591 upgrade_setup_debug(true);
1592 set_config('upgraderunning', time()+
300);
1598 * Internal function - executed if upgrade interrupted.
1600 function upgrade_finished_handler() {
1605 * Indicates upgrade is finished.
1607 * This function may be called repeatedly.
1612 function upgrade_finished($continueurl=null) {
1613 global $CFG, $DB, $OUTPUT;
1615 if (!empty($CFG->upgraderunning
)) {
1616 unset_config('upgraderunning');
1617 // We have to forcefully purge the caches using the writer here.
1618 // This has to be done after we unset the config var. If someone hits the site while this is set they will
1619 // cause the config values to propogate to the caches.
1620 // Caches are purged after the last step in an upgrade but there is several code routines that exceute between
1621 // then and now that leaving a window for things to fall out of sync.
1622 cache_helper
::purge_all(true);
1623 upgrade_setup_debug(false);
1624 ignore_user_abort(false);
1626 echo $OUTPUT->continue_button($continueurl);
1627 echo $OUTPUT->footer();
1637 function upgrade_setup_debug($starting) {
1640 static $originaldebug = null;
1643 if ($originaldebug === null) {
1644 $originaldebug = $DB->get_debug();
1646 if (!empty($CFG->upgradeshowsql
)) {
1647 $DB->set_debug(true);
1650 $DB->set_debug($originaldebug);
1654 function print_upgrade_separator() {
1661 * Default start upgrade callback
1662 * @param string $plugin
1663 * @param bool $installation true if installation, false means upgrade
1665 function print_upgrade_part_start($plugin, $installation, $verbose) {
1667 if (empty($plugin) or $plugin == 'moodle') {
1668 upgrade_started($installation); // does not store upgrade running flag yet
1670 echo $OUTPUT->heading(get_string('coresystem'));
1675 echo $OUTPUT->heading($plugin);
1678 core_upgrade_time
::record_start($installation);
1679 if ($installation) {
1680 if (empty($plugin) or $plugin == 'moodle') {
1681 // no need to log - log table not yet there ;-)
1683 upgrade_log(UPGRADE_LOG_NORMAL
, $plugin, 'Starting plugin installation');
1686 if (empty($plugin) or $plugin == 'moodle') {
1687 upgrade_log(UPGRADE_LOG_NORMAL
, $plugin, 'Starting core upgrade');
1689 upgrade_log(UPGRADE_LOG_NORMAL
, $plugin, 'Starting plugin upgrade');
1695 * Default end upgrade callback
1696 * @param string $plugin
1697 * @param bool $installation true if installation, false means upgrade
1699 function print_upgrade_part_end($plugin, $installation, $verbose) {
1702 if ($installation) {
1703 if (empty($plugin) or $plugin == 'moodle') {
1704 upgrade_log(UPGRADE_LOG_NORMAL
, $plugin, 'Core installed');
1706 upgrade_log(UPGRADE_LOG_NORMAL
, $plugin, 'Plugin installed');
1709 if (empty($plugin) or $plugin == 'moodle') {
1710 upgrade_log(UPGRADE_LOG_NORMAL
, $plugin, 'Core upgraded');
1712 upgrade_log(UPGRADE_LOG_NORMAL
, $plugin, 'Plugin upgraded');
1716 core_upgrade_time
::record_end();
1717 print_upgrade_separator();
1722 * Sets up JS code required for all upgrade scripts.
1725 function upgrade_init_javascript() {
1727 // scroll to the end of each upgrade page so that ppl see either error or continue button,
1728 // no need to scroll continuously any more, it is enough to jump to end once the footer is printed ;-)
1729 $js = "window.scrollTo(0, 5000000);";
1730 $PAGE->requires
->js_init_code($js);
1734 * Try to upgrade the given language pack (or current language)
1736 * @param string $lang the code of the language to update, defaults to the current language
1738 function upgrade_language_pack($lang = null) {
1741 if (!empty($CFG->skiplangupgrade
)) {
1745 if (!file_exists("$CFG->dirroot/$CFG->admin/tool/langimport/lib.php")) {
1746 // weird, somebody uninstalled the import utility
1751 $lang = current_language();
1754 if (!get_string_manager()->translation_exists($lang)) {
1758 get_string_manager()->reset_caches();
1760 if ($lang === 'en') {
1761 return; // Nothing to do
1764 upgrade_started(false);
1766 require_once("$CFG->dirroot/$CFG->admin/tool/langimport/lib.php");
1767 tool_langimport_preupgrade_update($lang);
1769 get_string_manager()->reset_caches();
1771 print_upgrade_separator();
1775 * Build the current theme so that the user doesn't have to wait for it
1776 * to build on the first page load after the install / upgrade.
1778 function upgrade_themes() {
1781 require_once("{$CFG->libdir}/outputlib.php");
1783 // Build the current theme so that the user can immediately
1784 // browse the site without having to wait for the theme to build.
1785 $themeconfig = theme_config
::load($CFG->theme
);
1786 $direction = right_to_left() ?
'rtl' : 'ltr';
1787 theme_build_css_for_themes([$themeconfig], [$direction]);
1789 // Only queue the task if there isn't already one queued.
1790 if (empty(\core\task\manager
::get_adhoc_tasks('\\core\\task\\build_installed_themes_task'))) {
1791 // Queue a task to build all of the site themes at some point
1792 // later. These can happen offline because it doesn't block the
1793 // user unless they quickly change theme.
1794 $adhoctask = new \core\task\build_installed_themes_task
();
1795 \core\task\manager
::queue_adhoc_task($adhoctask);
1800 * Install core moodle tables and initialize
1801 * @param float $version target version
1802 * @param bool $verbose
1803 * @return void, may throw exception
1805 function install_core($version, $verbose) {
1808 // We can not call purge_all_caches() yet, make sure the temp and cache dirs exist and are empty.
1809 remove_dir($CFG->cachedir
.'', true);
1810 make_cache_directory('', true);
1812 remove_dir($CFG->localcachedir
.'', true);
1813 make_localcache_directory('', true);
1815 remove_dir($CFG->tempdir
.'', true);
1816 make_temp_directory('', true);
1818 remove_dir($CFG->backuptempdir
.'', true);
1819 make_backup_temp_directory('', true);
1821 remove_dir($CFG->dataroot
.'/muc', true);
1822 make_writable_directory($CFG->dataroot
.'/muc', true);
1825 core_php_time_limit
::raise(600);
1826 print_upgrade_part_start('moodle', true, $verbose); // does not store upgrade running flag
1828 $DB->get_manager()->install_from_xmldb_file("$CFG->libdir/db/install.xml");
1829 core_upgrade_time
::record_detail('install.xml');
1830 upgrade_started(); // we want the flag to be stored in config table ;-)
1831 core_upgrade_time
::record_detail('upgrade_started');
1833 // set all core default records and default settings
1834 require_once("$CFG->libdir/db/install.php");
1835 core_upgrade_time
::record_detail('install.php');
1836 xmldb_main_install(); // installs the capabilities too
1837 core_upgrade_time
::record_detail('xmldb_main_install');
1840 upgrade_main_savepoint(true, $version, false);
1842 // Continue with the installation
1843 upgrade_component_updated('moodle', '', true);
1845 // Write default settings unconditionally
1846 admin_apply_default_settings(NULL, true);
1847 core_upgrade_time
::record_detail('admin_apply_default_settings');
1849 print_upgrade_part_end(null, true, $verbose);
1851 // Purge all caches. They're disabled but this ensures that we don't have any persistent data just in case something
1852 // during installation didn't use APIs.
1853 cache_helper
::purge_all();
1854 } catch (exception
$ex) {
1855 upgrade_handle_exception($ex);
1856 } catch (Throwable
$ex) {
1857 // Engine errors in PHP7 throw exceptions of type Throwable (this "catch" will be ignored in PHP5).
1858 upgrade_handle_exception($ex);
1863 * Upgrade moodle core
1864 * @param float $version target version
1865 * @param bool $verbose
1866 * @return void, may throw exception
1868 function upgrade_core($version, $verbose) {
1869 global $CFG, $SITE, $DB, $COURSE;
1871 raise_memory_limit(MEMORY_EXTRA
);
1873 require_once($CFG->libdir
.'/db/upgrade.php'); // Defines upgrades
1876 // Reset caches before any output.
1877 cache_helper
::purge_all(true);
1880 // Upgrade current language pack if we can
1881 upgrade_language_pack();
1883 print_upgrade_part_start('moodle', false, $verbose);
1885 // Pre-upgrade scripts for local hack workarounds.
1886 $preupgradefile = "$CFG->dirroot/local/preupgrade.php";
1887 if (file_exists($preupgradefile)) {
1888 core_php_time_limit
::raise();
1889 require($preupgradefile);
1890 // Reset upgrade timeout to default.
1891 upgrade_set_timeout();
1892 core_upgrade_time
::record_detail('local/preupgrade.php');
1895 $result = xmldb_main_upgrade($CFG->version
);
1896 core_upgrade_time
::record_detail('xmldb_main_upgrade');
1897 if ($version > $CFG->version
) {
1898 // store version if not already there
1899 upgrade_main_savepoint($result, $version, false);
1902 // In case structure of 'course' table has been changed and we forgot to update $SITE, re-read it from db.
1903 $SITE = $DB->get_record('course', array('id' => $SITE->id
));
1904 $COURSE = clone($SITE);
1906 // perform all other component upgrade routines
1907 upgrade_component_updated('moodle');
1908 // Update core definitions.
1909 cache_helper
::update_definitions(true);
1910 core_upgrade_time
::record_detail('cache_helper::update_definitions');
1912 // Purge caches again, just to be sure we arn't holding onto old stuff now.
1913 cache_helper
::purge_all(true);
1914 core_upgrade_time
::record_detail('cache_helper::purge_all');
1916 core_upgrade_time
::record_detail('purge_all_caches');
1918 // Clean up contexts - more and more stuff depends on existence of paths and contexts
1919 context_helper
::cleanup_instances();
1920 core_upgrade_time
::record_detail('context_helper::cleanup_instance');
1921 context_helper
::create_instances(null, false);
1922 core_upgrade_time
::record_detail('context_helper::create_instances');
1923 context_helper
::build_all_paths(false);
1924 core_upgrade_time
::record_detail('context_helper::build_all_paths');
1925 $syscontext = context_system
::instance();
1926 $syscontext->mark_dirty();
1927 core_upgrade_time
::record_detail('context_system::mark_dirty');
1929 // Prompt admin to register site. Reminder flow handles sites already registered, so admin won't be prompted if registered.
1930 set_config('registrationpending', true);
1932 print_upgrade_part_end('moodle', false, $verbose);
1933 } catch (Exception
$ex) {
1934 upgrade_handle_exception($ex);
1935 } catch (Throwable
$ex) {
1936 // Engine errors in PHP7 throw exceptions of type Throwable (this "catch" will be ignored in PHP5).
1937 upgrade_handle_exception($ex);
1942 * Upgrade/install other parts of moodle
1943 * @param bool $verbose
1944 * @return void, may throw exception
1946 function upgrade_noncore($verbose) {
1947 global $CFG, $OUTPUT;
1949 raise_memory_limit(MEMORY_EXTRA
);
1951 // upgrade all plugins types
1953 // Reset caches before any output.
1954 cache_helper
::purge_all(true);
1957 $plugintypes = core_component
::get_plugin_types();
1959 foreach ($plugintypes as $type=>$location) {
1960 upgrade_plugins($type, 'print_upgrade_part_start', 'print_upgrade_part_end', $verbose);
1962 if ($CFG->debugdeveloper
) {
1963 // Only show this heading in developer mode to go with the times below.
1964 echo $OUTPUT->heading('upgrade_noncore()');
1966 core_upgrade_time
::record_start();
1967 // Upgrade services.
1968 // This function gives plugins and subsystems a chance to add functions to existing built-in services.
1969 external_update_services();
1970 core_upgrade_time
::record_detail('external_update_services');
1972 // Update cache definitions. Involves scanning each plugin for any changes.
1973 cache_helper
::update_definitions();
1974 core_upgrade_time
::record_detail('cache_helper::update_definitions');
1976 // Mark the site as upgraded.
1977 set_config('allversionshash', core_component
::get_all_versions_hash());
1978 core_upgrade_time
::record_detail('core_component::get_all_versions_hash');
1980 // Purge caches again, just to be sure we arn't holding onto old stuff now.
1981 cache_helper
::purge_all(true);
1982 core_upgrade_time
::record_detail('cache_helper::purge_all');
1984 core_upgrade_time
::record_detail('purge_all_caches');
1986 // Only display the final 'Success' if we also showed the heading.
1987 core_upgrade_time
::record_end($CFG->debugdeveloper
);
1988 } catch (Exception
$ex) {
1989 upgrade_handle_exception($ex);
1990 } catch (Throwable
$ex) {
1991 // Engine errors in PHP7 throw exceptions of type Throwable (this "catch" will be ignored in PHP5).
1992 upgrade_handle_exception($ex);
1997 * Checks if the main tables have been installed yet or not.
1999 * Note: we can not use caches here because they might be stale,
2004 function core_tables_exist() {
2007 if (!$tables = $DB->get_tables(false) ) { // No tables yet at all.
2010 } else { // Check for missing main tables
2011 $mtables = array('config', 'course', 'groupings'); // some tables used in 1.9 and 2.0, preferable something from the start and end of install.xml
2012 foreach ($mtables as $mtable) {
2013 if (!in_array($mtable, $tables)) {
2022 * upgrades the mnet rpc definitions for the given component.
2023 * this method doesn't return status, an exception will be thrown in the case of an error
2025 * @param string $component the plugin to upgrade, eg auth_mnet
2027 function upgrade_plugin_mnet_functions($component) {
2030 list($type, $plugin) = core_component
::normalize_component($component);
2031 $path = core_component
::get_plugin_directory($type, $plugin);
2033 $publishes = array();
2034 $subscribes = array();
2035 if (file_exists($path . '/db/mnet.php')) {
2036 require_once($path . '/db/mnet.php'); // $publishes comes from this file
2038 if (empty($publishes)) {
2039 $publishes = array(); // still need this to be able to disable stuff later
2041 if (empty($subscribes)) {
2042 $subscribes = array(); // still need this to be able to disable stuff later
2045 static $servicecache = array();
2047 // rekey an array based on the rpc method for easy lookups later
2048 $publishmethodservices = array();
2049 $subscribemethodservices = array();
2050 foreach($publishes as $servicename => $service) {
2051 if (is_array($service['methods'])) {
2052 foreach($service['methods'] as $methodname) {
2053 $service['servicename'] = $servicename;
2054 $publishmethodservices[$methodname][] = $service;
2059 // Disable functions that don't exist (any more) in the source
2060 // Should these be deleted? What about their permissions records?
2061 foreach ($DB->get_records('mnet_rpc', array('pluginname'=>$plugin, 'plugintype'=>$type), 'functionname ASC ') as $rpc) {
2062 if (!array_key_exists($rpc->functionname
, $publishmethodservices) && $rpc->enabled
) {
2063 $DB->set_field('mnet_rpc', 'enabled', 0, array('id' => $rpc->id
));
2064 } else if (array_key_exists($rpc->functionname
, $publishmethodservices) && !$rpc->enabled
) {
2065 $DB->set_field('mnet_rpc', 'enabled', 1, array('id' => $rpc->id
));
2069 // reflect all the services we're publishing and save them
2070 static $cachedclasses = array(); // to store reflection information in
2071 foreach ($publishes as $service => $data) {
2072 $f = $data['filename'];
2073 $c = $data['classname'];
2074 foreach ($data['methods'] as $method) {
2075 $dataobject = new stdClass();
2076 $dataobject->plugintype
= $type;
2077 $dataobject->pluginname
= $plugin;
2078 $dataobject->enabled
= 1;
2079 $dataobject->classname
= $c;
2080 $dataobject->filename
= $f;
2082 if (is_string($method)) {
2083 $dataobject->functionname
= $method;
2085 } else if (is_array($method)) { // wants to override file or class
2086 $dataobject->functionname
= $method['method'];
2087 $dataobject->classname
= $method['classname'];
2088 $dataobject->filename
= $method['filename'];
2090 $dataobject->xmlrpcpath
= $type.'/'.$plugin.'/'.$dataobject->filename
.'/'.$method;
2091 $dataobject->static = false;
2093 require_once($path . '/' . $dataobject->filename
);
2094 $functionreflect = null; // slightly different ways to get this depending on whether it's a class method or a function
2095 if (!empty($dataobject->classname
)) {
2096 if (!class_exists($dataobject->classname
)) {
2097 throw new moodle_exception('installnosuchmethod', 'mnet', '', (object)array('method' => $dataobject->functionname
, 'class' => $dataobject->classname
));
2099 $key = $dataobject->filename
. '|' . $dataobject->classname
;
2100 if (!array_key_exists($key, $cachedclasses)) { // look to see if we've already got a reflection object
2102 $cachedclasses[$key] = new ReflectionClass($dataobject->classname
);
2103 } catch (ReflectionException
$e) { // catch these and rethrow them to something more helpful
2104 throw new moodle_exception('installreflectionclasserror', 'mnet', '', (object)array('method' => $dataobject->functionname
, 'class' => $dataobject->classname
, 'error' => $e->getMessage()));
2107 $r =& $cachedclasses[$key];
2108 if (!$r->hasMethod($dataobject->functionname
)) {
2109 throw new moodle_exception('installnosuchmethod', 'mnet', '', (object)array('method' => $dataobject->functionname
, 'class' => $dataobject->classname
));
2111 $functionreflect = $r->getMethod($dataobject->functionname
);
2112 $dataobject->static = (int)$functionreflect->isStatic();
2114 if (!function_exists($dataobject->functionname
)) {
2115 throw new moodle_exception('installnosuchfunction', 'mnet', '', (object)array('method' => $dataobject->functionname
, 'file' => $dataobject->filename
));
2118 $functionreflect = new ReflectionFunction($dataobject->functionname
);
2119 } catch (ReflectionException
$e) { // catch these and rethrow them to something more helpful
2120 throw new moodle_exception('installreflectionfunctionerror', 'mnet', '', (object)array('method' => $dataobject->functionname
, '' => $dataobject->filename
, 'error' => $e->getMessage()));
2123 $dataobject->profile
= serialize(admin_mnet_method_profile($functionreflect));
2124 $dataobject->help
= admin_mnet_method_get_help($functionreflect);
2126 if ($record_exists = $DB->get_record('mnet_rpc', array('xmlrpcpath'=>$dataobject->xmlrpcpath
))) {
2127 $dataobject->id
= $record_exists->id
;
2128 $dataobject->enabled
= $record_exists->enabled
;
2129 $DB->update_record('mnet_rpc', $dataobject);
2131 $dataobject->id
= $DB->insert_record('mnet_rpc', $dataobject, true);
2134 // TODO this API versioning must be reworked, here the recently processed method
2135 // sets the service API which may not be correct
2136 foreach ($publishmethodservices[$dataobject->functionname
] as $service) {
2137 if ($serviceobj = $DB->get_record('mnet_service', array('name'=>$service['servicename']))) {
2138 $serviceobj->apiversion
= $service['apiversion'];
2139 $DB->update_record('mnet_service', $serviceobj);
2141 $serviceobj = new stdClass();
2142 $serviceobj->name
= $service['servicename'];
2143 $serviceobj->description
= empty($service['description']) ?
'' : $service['description'];
2144 $serviceobj->apiversion
= $service['apiversion'];
2145 $serviceobj->offer
= 1;
2146 $serviceobj->id
= $DB->insert_record('mnet_service', $serviceobj);
2148 $servicecache[$service['servicename']] = $serviceobj;
2149 if (!$DB->record_exists('mnet_service2rpc', array('rpcid'=>$dataobject->id
, 'serviceid'=>$serviceobj->id
))) {
2150 $obj = new stdClass();
2151 $obj->rpcid
= $dataobject->id
;
2152 $obj->serviceid
= $serviceobj->id
;
2153 $DB->insert_record('mnet_service2rpc', $obj, true);
2158 // finished with methods we publish, now do subscribable methods
2159 foreach($subscribes as $service => $methods) {
2160 if (!array_key_exists($service, $servicecache)) {
2161 if (!$serviceobj = $DB->get_record('mnet_service', array('name' => $service))) {
2162 debugging("TODO: skipping unknown service $service - somebody needs to fix MDL-21993");
2165 $servicecache[$service] = $serviceobj;
2167 $serviceobj = $servicecache[$service];
2169 foreach ($methods as $method => $xmlrpcpath) {
2170 if (!$rpcid = $DB->get_field('mnet_remote_rpc', 'id', array('xmlrpcpath'=>$xmlrpcpath))) {
2171 $remoterpc = (object)array(
2172 'functionname' => $method,
2173 'xmlrpcpath' => $xmlrpcpath,
2174 'plugintype' => $type,
2175 'pluginname' => $plugin,
2178 $rpcid = $remoterpc->id
= $DB->insert_record('mnet_remote_rpc', $remoterpc, true);
2180 if (!$DB->record_exists('mnet_remote_service2rpc', array('rpcid'=>$rpcid, 'serviceid'=>$serviceobj->id
))) {
2181 $obj = new stdClass();
2182 $obj->rpcid
= $rpcid;
2183 $obj->serviceid
= $serviceobj->id
;
2184 $DB->insert_record('mnet_remote_service2rpc', $obj, true);
2186 $subscribemethodservices[$method][] = $service;
2190 foreach ($DB->get_records('mnet_remote_rpc', array('pluginname'=>$plugin, 'plugintype'=>$type), 'functionname ASC ') as $rpc) {
2191 if (!array_key_exists($rpc->functionname
, $subscribemethodservices) && $rpc->enabled
) {
2192 $DB->set_field('mnet_remote_rpc', 'enabled', 0, array('id' => $rpc->id
));
2193 } else if (array_key_exists($rpc->functionname
, $subscribemethodservices) && !$rpc->enabled
) {
2194 $DB->set_field('mnet_remote_rpc', 'enabled', 1, array('id' => $rpc->id
));
2202 * Given some sort of reflection function/method object, return a profile array, ready to be serialized and stored
2204 * @param ReflectionFunctionAbstract $function reflection function/method object from which to extract information
2206 * @return array associative array with function/method information
2208 function admin_mnet_method_profile(ReflectionFunctionAbstract
$function) {
2209 $commentlines = admin_mnet_method_get_docblock($function);
2210 $getkey = function($key) use ($commentlines) {
2211 return array_values(array_filter($commentlines, function($line) use ($key) {
2212 return $line[0] == $key;
2215 $returnline = $getkey('@return');
2217 'parameters' => array_map(function($line) {
2219 'name' => trim($line[2], " \t\n\r\0\x0B$"),
2221 'description' => $line[3]
2223 }, $getkey('@param')),
2226 'type' => !empty($returnline[0][1]) ?
$returnline[0][1] : 'void',
2227 'description' => !empty($returnline[0][2]) ?
$returnline[0][2] : ''
2233 * Given some sort of reflection function/method object, return an array of docblock lines, where each line is an array of
2234 * keywords/descriptions
2236 * @param ReflectionFunctionAbstract $function reflection function/method object from which to extract information
2238 * @return array docblock converted in to an array
2240 function admin_mnet_method_get_docblock(ReflectionFunctionAbstract
$function) {
2241 return array_map(function($line) {
2242 $text = trim($line, " \t\n\r\0\x0B*/");
2243 if (strpos($text, '@param') === 0) {
2244 return preg_split('/\s+/', $text, 4);
2247 if (strpos($text, '@return') === 0) {
2248 return preg_split('/\s+/', $text, 3);
2251 return array($text);
2252 }, explode("\n", $function->getDocComment()));
2256 * Given some sort of reflection function/method object, return just the help text
2258 * @param ReflectionFunctionAbstract $function reflection function/method object from which to extract information
2260 * @return string docblock help text
2262 function admin_mnet_method_get_help(ReflectionFunctionAbstract
$function) {
2263 $helplines = array_map(function($line) {
2264 return implode(' ', $line);
2265 }, array_values(array_filter(admin_mnet_method_get_docblock($function), function($line) {
2266 return strpos($line[0], '@') !== 0 && !empty($line[0]);
2269 return implode("\n", $helplines);
2273 * This function verifies that the database is not using an unsupported storage engine.
2275 * @param environment_results $result object to update, if relevant
2276 * @return environment_results|null updated results object, or null if the storage engine is supported
2278 function check_database_storage_engine(environment_results
$result) {
2281 // Check if MySQL is the DB family (this will also be the same for MariaDB).
2282 if ($DB->get_dbfamily() == 'mysql') {
2283 // Get the database engine we will either be using to install the tables, or what we are currently using.
2284 $engine = $DB->get_dbengine();
2285 // Check if MyISAM is the storage engine that will be used, if so, do not proceed and display an error.
2286 if ($engine == 'MyISAM') {
2287 $result->setInfo('unsupported_db_storage_engine');
2288 $result->setStatus(false);
2297 * Method used to check the usage of slasharguments config and display a warning message.
2299 * @param environment_results $result object to update, if relevant.
2300 * @return environment_results|null updated results or null if slasharguments is disabled.
2302 function check_slasharguments(environment_results
$result){
2305 if (!during_initial_install() && empty($CFG->slasharguments
)) {
2306 $result->setInfo('slasharguments');
2307 $result->setStatus(false);
2315 * This function verifies if the database has tables using innoDB Antelope row format.
2317 * @param environment_results $result
2318 * @return environment_results|null updated results object, or null if no Antelope table has been found.
2320 function check_database_tables_row_format(environment_results
$result) {
2323 if ($DB->get_dbfamily() == 'mysql') {
2324 $generator = $DB->get_manager()->generator
;
2326 foreach ($DB->get_tables(false) as $table) {
2327 $columns = $DB->get_columns($table, false);
2328 $size = $generator->guess_antelope_row_size($columns);
2329 $format = $DB->get_row_format($table);
2331 if ($size <= $generator::ANTELOPE_MAX_ROW_SIZE
) {
2335 if ($format === 'Compact' or $format === 'Redundant') {
2336 $result->setInfo('unsupported_db_table_row_format');
2337 $result->setStatus(false);
2347 * This function verfies that the database has tables using InnoDB Antelope row format.
2349 * @param environment_results $result
2350 * @return environment_results|null updated results object, or null if no Antelope table has been found.
2352 function check_mysql_file_format(environment_results
$result) {
2355 if ($DB->get_dbfamily() == 'mysql') {
2356 $collation = $DB->get_dbcollation();
2357 $collationinfo = explode('_', $collation);
2358 $charset = reset($collationinfo);
2360 if ($charset == 'utf8mb4') {
2361 if ($DB->get_row_format() !== "Barracuda") {
2362 $result->setInfo('mysql_full_unicode_support#File_format');
2363 $result->setStatus(false);
2372 * This function verfies that the database has a setting of one file per table. This is required for 'utf8mb4'.
2374 * @param environment_results $result
2375 * @return environment_results|null updated results object, or null if innodb_file_per_table = 1.
2377 function check_mysql_file_per_table(environment_results
$result) {
2380 if ($DB->get_dbfamily() == 'mysql') {
2381 $collation = $DB->get_dbcollation();
2382 $collationinfo = explode('_', $collation);
2383 $charset = reset($collationinfo);
2385 if ($charset == 'utf8mb4') {
2386 if (!$DB->is_file_per_table_enabled()) {
2387 $result->setInfo('mysql_full_unicode_support#File_per_table');
2388 $result->setStatus(false);
2397 * This function verfies that the database has the setting of large prefix enabled. This is required for 'utf8mb4'.
2399 * @param environment_results $result
2400 * @return environment_results|null updated results object, or null if innodb_large_prefix = 1.
2402 function check_mysql_large_prefix(environment_results
$result) {
2405 if ($DB->get_dbfamily() == 'mysql') {
2406 $collation = $DB->get_dbcollation();
2407 $collationinfo = explode('_', $collation);
2408 $charset = reset($collationinfo);
2410 if ($charset == 'utf8mb4') {
2411 if (!$DB->is_large_prefix_enabled()) {
2412 $result->setInfo('mysql_full_unicode_support#Large_prefix');
2413 $result->setStatus(false);
2422 * This function checks the database to see if it is using incomplete unicode support.
2424 * @param environment_results $result $result
2425 * @return environment_results|null updated results object, or null if unicode is fully supported.
2427 function check_mysql_incomplete_unicode_support(environment_results
$result) {
2430 if ($DB->get_dbfamily() == 'mysql') {
2431 $collation = $DB->get_dbcollation();
2432 $collationinfo = explode('_', $collation);
2433 $charset = reset($collationinfo);
2435 if ($charset == 'utf8') {
2436 $result->setInfo('mysql_full_unicode_support');
2437 $result->setStatus(false);
2445 * Check if the site is being served using an ssl url.
2447 * Note this does not really perform any request neither looks for proxies or
2448 * other situations. Just looks to wwwroot and warn if it's not using https.
2450 * @param environment_results $result $result
2451 * @return environment_results|null updated results object, or null if the site is https.
2453 function check_is_https(environment_results
$result) {
2456 // Only if is defined, non-empty and whatever core tell us.
2457 if (!empty($CFG->wwwroot
) && !is_https()) {
2458 $result->setInfo('site not https');
2459 $result->setStatus(false);
2466 * Check if the site is using 64 bits PHP.
2468 * @param environment_results $result
2469 * @return environment_results|null updated results object, or null if the site is using 64 bits PHP.
2471 function check_sixtyfour_bits(environment_results
$result) {
2473 if (PHP_INT_SIZE
=== 4) {
2474 $result->setInfo('php not 64 bits');
2475 $result->setStatus(false);
2482 * Check if the igbinary extension installed is buggy one
2484 * There are a few php-igbinary versions that are buggy and
2485 * return any unserialised array with wrong index. This defeats
2486 * key() and next() operations on them.
2488 * This library is used by MUC and also by memcached and redis
2491 * Let's inform if there is some problem when:
2492 * - php 7.2 is being used (php 7.3 and up are immune).
2493 * - the igbinary extension is installed.
2494 * - the version of the extension is between 3.2.2 and 3.2.4.
2495 * - the buggy behaviour is reproduced.
2497 * @param environment_results $result object to update, if relevant.
2498 * @return environment_results|null updated results or null.
2500 function check_igbinary322_version(environment_results
$result) {
2502 // No problem if using PHP version 7.3 and up.
2503 $phpversion = normalize_version(phpversion());
2504 if (version_compare($phpversion, '7.3', '>=')) {
2508 // No problem if igbinary is not installed..
2509 if (!function_exists('igbinary_serialize')) {
2513 // No problem if using igbinary < 3.2.2 or > 3.2.4.
2514 $igbinaryversion = normalize_version(phpversion('igbinary'));
2515 if (version_compare($igbinaryversion, '3.2.2', '<') or version_compare($igbinaryversion, '3.2.4', '>')) {
2519 // Let's verify the real behaviour to see if the bug is around.
2520 // Note that we need this extra check because they released 3.2.5 with 3.2.4 version number, so
2521 // over the paper, there are 3.2.4 working versions (3.2.5 ones with messed reflection version).
2523 $data = igbinary_unserialize(igbinary_serialize($data));
2524 if (key($data) === 0) {
2528 // Arrived here, we are using PHP 7.2 and a buggy verified igbinary version, let's inform and don't allow to continue.
2529 $result->setInfo('igbinary version problem');
2530 $result->setStatus(false);
2535 * Assert the upgrade key is provided, if it is defined.
2537 * The upgrade key can be defined in the main config.php as $CFG->upgradekey. If
2538 * it is defined there, then its value must be provided every time the site is
2539 * being upgraded, regardless the administrator is logged in or not.
2541 * This is supposed to be used at certain places in /admin/index.php only.
2543 * @param string|null $upgradekeyhash the SHA-1 of the value provided by the user
2545 function check_upgrade_key($upgradekeyhash) {
2548 if (isset($CFG->config_php_settings
['upgradekey'])) {
2549 if ($upgradekeyhash === null or $upgradekeyhash !== sha1($CFG->config_php_settings
['upgradekey'])) {
2550 if (!$PAGE->headerprinted
) {
2551 $PAGE->set_title(get_string('upgradekeyreq', 'admin'));
2552 $output = $PAGE->get_renderer('core', 'admin');
2553 echo $output->upgradekey_form_page(new moodle_url('/admin/index.php', array('cache' => 0)));
2556 // This should not happen.
2557 die('Upgrade locked');
2564 * Helper procedure/macro for installing remote plugins at admin/index.php
2566 * Does not return, always redirects or exits.
2568 * @param array $installable list of \core\update\remote_info
2569 * @param bool $confirmed false: display the validation screen, true: proceed installation
2570 * @param string $heading validation screen heading
2571 * @param moodle_url|string|null $continue URL to proceed with installation at the validation screen
2572 * @param moodle_url|string|null $return URL to go back on cancelling at the validation screen
2574 function upgrade_install_plugins(array $installable, $confirmed, $heading='', $continue=null, $return=null) {
2577 if (empty($return)) {
2578 $return = $PAGE->url
;
2581 if (!empty($CFG->disableupdateautodeploy
)) {
2585 if (empty($installable)) {
2589 $pluginman = core_plugin_manager
::instance();
2592 // Installation confirmed at the validation results page.
2593 if (!$pluginman->install_plugins($installable, true, true)) {
2594 throw new moodle_exception('install_plugins_failed', 'core_plugin', $return);
2597 // Always redirect to admin/index.php to perform the database upgrade.
2598 // Do not throw away the existing $PAGE->url parameters such as
2599 // confirmupgrade or confirmrelease if $PAGE->url is a superset of the
2600 // URL we must go to.
2601 $mustgoto = new moodle_url('/admin/index.php', array('cache' => 0, 'confirmplugincheck' => 0));
2602 if ($mustgoto->compare($PAGE->url
, URL_MATCH_PARAMS
)) {
2603 redirect($PAGE->url
);
2605 redirect($mustgoto);
2609 $output = $PAGE->get_renderer('core', 'admin');
2610 echo $output->header();
2612 echo $output->heading($heading, 3);
2614 echo html_writer
::start_tag('pre', array('class' => 'plugin-install-console'));
2615 $validated = $pluginman->install_plugins($installable, false, false);
2616 echo html_writer
::end_tag('pre');
2618 echo $output->plugins_management_confirm_buttons($continue, $return);
2620 echo $output->plugins_management_confirm_buttons(null, $return);
2622 echo $output->footer();
2627 * Method used to check the installed unoconv version.
2629 * @param environment_results $result object to update, if relevant.
2630 * @return environment_results|null updated results or null if unoconv path is not executable.
2632 function check_unoconv_version(environment_results
$result) {
2635 if (!during_initial_install() && !empty($CFG->pathtounoconv
) && file_is_executable(trim($CFG->pathtounoconv
))) {
2636 $currentversion = 0;
2637 $supportedversion = 0.7;
2638 $unoconvbin = \
escapeshellarg($CFG->pathtounoconv
);
2639 $command = "$unoconvbin --version";
2640 exec($command, $output);
2642 // If the command execution returned some output, then get the unoconv version.
2644 foreach ($output as $response) {
2645 if (preg_match('/unoconv (\\d+\\.\\d+)/', $response, $matches)) {
2646 $currentversion = (float)$matches[1];
2651 if ($currentversion < $supportedversion) {
2652 $result->setInfo('unoconv version not supported');
2653 $result->setStatus(false);
2661 * Checks for up-to-date TLS libraries. NOTE: this is not currently used, see MDL-57262.
2663 * @param environment_results $result object to update, if relevant.
2664 * @return environment_results|null updated results or null if unoconv path is not executable.
2666 function check_tls_libraries(environment_results
$result) {
2669 if (!function_exists('curl_version')) {
2670 $result->setInfo('cURL PHP extension is not installed');
2671 $result->setStatus(false);
2675 if (!\core\upgrade\util
::validate_php_curl_tls(curl_version(), PHP_ZTS
)) {
2676 $result->setInfo('invalid ssl/tls configuration');
2677 $result->setStatus(false);
2681 if (!\core\upgrade\util
::can_use_tls12(curl_version(), php_uname('r'))) {
2682 $result->setInfo('ssl/tls configuration not supported');
2683 $result->setStatus(false);
2691 * Check if recommended version of libcurl is installed or not.
2693 * @param environment_results $result object to update, if relevant.
2694 * @return environment_results|null updated results or null.
2696 function check_libcurl_version(environment_results
$result) {
2698 if (!function_exists('curl_version')) {
2699 $result->setInfo('cURL PHP extension is not installed');
2700 $result->setStatus(false);
2704 // Supported version and version number.
2705 $supportedversion = 0x071304;
2706 $supportedversionstring = "7.19.4";
2708 // Installed version.
2709 $curlinfo = curl_version();
2710 $currentversion = $curlinfo['version_number'];
2712 if ($currentversion < $supportedversion) {
2714 // Set info, we want to let user know how to resolve the problem.
2715 $result->setInfo('Libcurl version check');
2716 $result->setNeededVersion($supportedversionstring);
2717 $result->setCurrentVersion($curlinfo['version']);
2718 $result->setStatus(false);
2726 * Environment check for the php setting max_input_vars
2728 * @param environment_results $result
2729 * @return environment_results|null
2731 function check_max_input_vars(environment_results
$result) {
2732 $max = (int)ini_get('max_input_vars');
2734 $result->setInfo('max_input_vars');
2735 $result->setStatus(false);
2736 if (PHP_VERSION_ID
>= 80000) {
2737 // For PHP8 this check is required.
2738 $result->setLevel('required');
2739 $result->setFeedbackStr('settingmaxinputvarsrequired');
2741 // For PHP7 this check is optional (recommended).
2742 $result->setFeedbackStr('settingmaxinputvars');
2750 * Check whether the admin directory has been configured and warn if so.
2752 * The admin directory has been deprecated since Moodle 4.0.
2754 * @param environment_results $result
2755 * @return null|environment_results
2757 function check_admin_dir_usage(environment_results
$result): ?environment_results
{
2760 if (empty($CFG->admin
)) {
2764 if ($CFG->admin
=== 'admin') {
2768 $result->setInfo('admin_dir_usage');
2769 $result->setStatus(false);
2775 * Check whether the XML-RPC protocol is enabled and warn if so.
2777 * The XML-RPC protocol will be removed in a future version (4.1) as it is no longer supported by PHP.
2779 * See MDL-70889 for further information.
2781 * @param environment_results $result
2782 * @return null|environment_results
2784 function check_xmlrpc_usage(environment_results
$result): ?environment_results
{
2787 // Checking Web Service protocols.
2788 if (!empty($CFG->webserviceprotocols
)) {
2789 $plugins = array_flip(explode(',', $CFG->webserviceprotocols
));
2790 if (array_key_exists('xmlrpc', $plugins)) {
2791 $result->setInfo('xmlrpc_webservice_usage');
2792 $result->setFeedbackStr('xmlrpcwebserviceenabled');