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 savepoint */
173 protected static $lastsavepoint;
174 /** @var bool Flag to indicate whether we are recording timestamps or not. */
175 protected static $isrecording = false;
178 * Records current time at the start of the current upgrade item, e.g. plugin.
180 public static function record_start() {
181 self
::$before = microtime(true);
182 self
::$lastsavepoint = self
::$before;
183 self
::$isrecording = true;
187 * Records current time at the end of a given numbered step.
189 * @param float $version Version number (may have decimals, or not)
191 public static function record_savepoint($version) {
192 global $CFG, $OUTPUT;
194 // In developer debug mode we show a notification after each individual save point.
195 if ($CFG->debugdeveloper
&& self
::$isrecording) {
196 $time = microtime(true);
198 $notification = new \core\output\notification
($version . ': ' .
199 get_string('successduration', '', format_float($time - self
::$lastsavepoint, 2)),
200 \core\output\notification
::NOTIFY_SUCCESS
);
201 $notification->set_show_closebutton(false);
202 echo $OUTPUT->render($notification);
203 self
::$lastsavepoint = $time;
208 * Gets the time since the record_start function was called, rounded to 2 digits.
210 * @return float Elapsed time
212 public static function get_elapsed() {
213 return microtime(true) - self
::$before;
218 * Sets maximum expected time needed for upgrade task.
219 * Please always make sure that upgrade will not run longer!
221 * The script may be automatically aborted if upgrade times out.
224 * @param int $max_execution_time in seconds (can not be less than 60 s)
226 function upgrade_set_timeout($max_execution_time=300) {
229 if (!isset($CFG->upgraderunning
) or $CFG->upgraderunning
< time()) {
230 $upgraderunning = get_config(null, 'upgraderunning');
232 $upgraderunning = $CFG->upgraderunning
;
235 if (!$upgraderunning) {
237 // never stop CLI upgrades
240 // web upgrade not running or aborted
241 print_error('upgradetimedout', 'admin', "$CFG->wwwroot/$CFG->admin/");
245 if ($max_execution_time < 60) {
246 // protection against 0 here
247 $max_execution_time = 60;
250 $expected_end = time() +
$max_execution_time;
252 if ($expected_end < $upgraderunning +
10 and $expected_end > $upgraderunning - 10) {
253 // no need to store new end, it is nearly the same ;-)
258 // there is no point in timing out of CLI scripts, admins can stop them if necessary
259 core_php_time_limit
::raise();
261 core_php_time_limit
::raise($max_execution_time);
263 set_config('upgraderunning', $expected_end); // keep upgrade locked until this time
267 * Upgrade savepoint, marks end of each upgrade block.
268 * It stores new main version, resets upgrade timeout
269 * and abort upgrade if user cancels page loading.
271 * Please do not make large upgrade blocks with lots of operations,
272 * for example when adding tables keep only one table operation per block.
275 * @param bool $result false if upgrade step failed, true if completed
276 * @param string or float $version main version
277 * @param bool $allowabort allow user to abort script execution here
280 function upgrade_main_savepoint($result, $version, $allowabort=true) {
283 //sanity check to avoid confusion with upgrade_mod_savepoint usage.
284 if (!is_bool($allowabort)) {
285 $errormessage = 'Parameter type mismatch. Are you mixing up upgrade_main_savepoint() and upgrade_mod_savepoint()?';
286 throw new coding_exception($errormessage);
290 throw new upgrade_exception(null, $version);
293 if ($CFG->version
>= $version) {
294 // something really wrong is going on in main upgrade script
295 throw new downgrade_exception(null, $CFG->version
, $version);
298 set_config('version', $version);
299 upgrade_log(UPGRADE_LOG_NORMAL
, null, 'Upgrade savepoint reached');
301 // reset upgrade timeout to default
302 upgrade_set_timeout();
304 core_upgrade_time
::record_savepoint($version);
306 // this is a safe place to stop upgrades if user aborts page loading
307 if ($allowabort and connection_aborted()) {
313 * Module upgrade savepoint, marks end of module upgrade blocks
314 * It stores module version, resets upgrade timeout
315 * and abort upgrade if user cancels page loading.
318 * @param bool $result false if upgrade step failed, true if completed
319 * @param string or float $version main version
320 * @param string $modname name of module
321 * @param bool $allowabort allow user to abort script execution here
324 function upgrade_mod_savepoint($result, $version, $modname, $allowabort=true) {
327 $component = 'mod_'.$modname;
330 throw new upgrade_exception($component, $version);
333 $dbversion = $DB->get_field('config_plugins', 'value', array('plugin'=>$component, 'name'=>'version'));
335 if (!$module = $DB->get_record('modules', array('name'=>$modname))) {
336 print_error('modulenotexist', 'debug', '', $modname);
339 if ($dbversion >= $version) {
340 // something really wrong is going on in upgrade script
341 throw new downgrade_exception($component, $dbversion, $version);
343 set_config('version', $version, $component);
345 upgrade_log(UPGRADE_LOG_NORMAL
, $component, 'Upgrade savepoint reached');
347 // reset upgrade timeout to default
348 upgrade_set_timeout();
350 core_upgrade_time
::record_savepoint($version);
352 // this is a safe place to stop upgrades if user aborts page loading
353 if ($allowabort and connection_aborted()) {
359 * Blocks upgrade savepoint, marks end of blocks upgrade blocks
360 * It stores block version, resets upgrade timeout
361 * and abort upgrade if user cancels page loading.
364 * @param bool $result false if upgrade step failed, true if completed
365 * @param string or float $version main version
366 * @param string $blockname name of block
367 * @param bool $allowabort allow user to abort script execution here
370 function upgrade_block_savepoint($result, $version, $blockname, $allowabort=true) {
373 $component = 'block_'.$blockname;
376 throw new upgrade_exception($component, $version);
379 $dbversion = $DB->get_field('config_plugins', 'value', array('plugin'=>$component, 'name'=>'version'));
381 if (!$block = $DB->get_record('block', array('name'=>$blockname))) {
382 print_error('blocknotexist', 'debug', '', $blockname);
385 if ($dbversion >= $version) {
386 // something really wrong is going on in upgrade script
387 throw new downgrade_exception($component, $dbversion, $version);
389 set_config('version', $version, $component);
391 upgrade_log(UPGRADE_LOG_NORMAL
, $component, 'Upgrade savepoint reached');
393 // reset upgrade timeout to default
394 upgrade_set_timeout();
396 core_upgrade_time
::record_savepoint($version);
398 // this is a safe place to stop upgrades if user aborts page loading
399 if ($allowabort and connection_aborted()) {
405 * Plugins upgrade savepoint, marks end of blocks upgrade blocks
406 * It stores plugin version, resets upgrade timeout
407 * and abort upgrade if user cancels page loading.
410 * @param bool $result false if upgrade step failed, true if completed
411 * @param string or float $version main version
412 * @param string $type The type of the plugin.
413 * @param string $plugin The name of the plugin.
414 * @param bool $allowabort allow user to abort script execution here
417 function upgrade_plugin_savepoint($result, $version, $type, $plugin, $allowabort=true) {
420 $component = $type.'_'.$plugin;
423 throw new upgrade_exception($component, $version);
426 $dbversion = $DB->get_field('config_plugins', 'value', array('plugin'=>$component, 'name'=>'version'));
428 if ($dbversion >= $version) {
429 // Something really wrong is going on in the upgrade script
430 throw new downgrade_exception($component, $dbversion, $version);
432 set_config('version', $version, $component);
433 upgrade_log(UPGRADE_LOG_NORMAL
, $component, 'Upgrade savepoint reached');
435 // Reset upgrade timeout to default
436 upgrade_set_timeout();
438 core_upgrade_time
::record_savepoint($version);
440 // This is a safe place to stop upgrades if user aborts page loading
441 if ($allowabort and connection_aborted()) {
447 * Detect if there are leftovers in PHP source files.
449 * During main version upgrades administrators MUST move away
450 * old PHP source files and start from scratch (or better
453 * @return bool true means borked upgrade, false means previous PHP files were properly removed
455 function upgrade_stale_php_files_present() {
458 $someexamplesofremovedfiles = array(
460 '/course/classes/output/modchooser_item.php',
461 '/course/yui/build/moodle-course-modchooser/moodle-course-modchooser-min.js',
462 '/course/yui/src/modchooser/js/modchooser.js',
463 '/h5p/classes/autoloader.php',
464 '/lib/adodb/readme.txt',
465 '/lib/maxmind/GeoIp2/Compat/JsonSerializable.php',
467 '/lib/amd/src/modal_confirm.js',
468 '/lib/fonts/font-awesome-4.7.0/css/font-awesome.css',
469 '/lib/jquery/jquery-3.2.1.min.js',
470 '/lib/recaptchalib.php',
471 '/lib/sessionkeepalive_ajax.php',
472 '/lib/yui/src/checknet/js/checknet.js',
473 '/question/amd/src/qbankmanager.js',
475 '/lib/form/yui/src/showadvanced/js/showadvanced.js',
476 '/lib/tests/output_external_test.php',
477 '/message/amd/src/message_area.js',
478 '/message/templates/message_area.mustache',
479 '/question/yui/src/qbankmanager/build.json',
481 '/lib/classes/session/memcache.php',
482 '/lib/eventslib.php',
483 '/lib/form/submitlink.php',
485 '/lib/password_compat/lib/password.php',
487 '/lib/dml/mssql_native_moodle_database.php',
488 '/lib/dml/mssql_native_moodle_recordset.php',
489 '/lib/dml/mssql_native_moodle_temptables.php',
494 '/enrol/yui/rolemanager/assets/skins/sam/rolemanager.css',
496 '/badges/backpackconnect.php',
497 '/calendar/yui/src/info/assets/skins/sam/moodle-calendar-info.css',
498 '/competency/classes/external/exporter.php',
499 '/mod/forum/forum.js',
500 '/user/pixgroup.php',
502 '/calendar/preferences.php',
504 '/lib/jquery/jquery-1.12.1.min.js',
505 '/lib/password_compat/tests/',
506 '/lib/phpunit/classes/unittestcase.php',
508 '/lib/classes/log/sql_internal_reader.php',
510 '/mod/forum/pix/icon.gif',
511 '/tag/templates/tagname.mustache',
513 '/mod/lti/grade.php',
514 '/tag/coursetagslib.php',
518 '/course/delete_category_form.php',
520 '/admin/tool/qeupgradehelper/version.php',
523 '/admin/oacleanup.php',
526 '/backup/bb/README.txt',
527 '/lib/excel/test.php',
529 '/admin/tool/unittest/simpletestlib.php',
531 '/lib/minify/builder/',
533 '/lib/yui/3.4.1pr1/',
535 '/search/cron_php5.php',
536 '/course/report/log/indexlive.php',
537 '/admin/report/backups/index.php',
538 '/admin/generator.php',
542 '/blocks/admin/block_admin.php',
543 '/blocks/admin_tree/block_admin_tree.php',
546 foreach ($someexamplesofremovedfiles as $file) {
547 if (file_exists($CFG->dirroot
.$file)) {
557 * @param string $type The type of plugins that should be updated (e.g. 'enrol', 'qtype')
560 function upgrade_plugins($type, $startcallback, $endcallback, $verbose) {
564 if ($type === 'mod') {
565 return upgrade_plugins_modules($startcallback, $endcallback, $verbose);
566 } else if ($type === 'block') {
567 return upgrade_plugins_blocks($startcallback, $endcallback, $verbose);
570 $plugs = core_component
::get_plugin_list($type);
572 foreach ($plugs as $plug=>$fullplug) {
573 // Reset time so that it works when installing a large number of plugins
574 core_php_time_limit
::raise(600);
575 $component = clean_param($type.'_'.$plug, PARAM_COMPONENT
); // standardised plugin name
577 // check plugin dir is valid name
578 if (empty($component)) {
579 throw new plugin_defective_exception($type.'_'.$plug, 'Invalid plugin directory name.');
582 if (!is_readable($fullplug.'/version.php')) {
586 $plugin = new stdClass();
587 $plugin->version
= null;
588 $module = $plugin; // Prevent some notices when plugin placed in wrong directory.
589 require($fullplug.'/version.php'); // defines $plugin with version etc
592 if (empty($plugin->version
)) {
593 throw new plugin_defective_exception($component, 'Missing $plugin->version number in version.php.');
596 if (empty($plugin->component
)) {
597 throw new plugin_defective_exception($component, 'Missing $plugin->component declaration in version.php.');
600 if ($plugin->component
!== $component) {
601 throw new plugin_misplaced_exception($plugin->component
, null, $fullplug);
604 $plugin->name
= $plug;
605 $plugin->fullname
= $component;
607 if (!empty($plugin->requires
)) {
608 if ($plugin->requires
> $CFG->version
) {
609 throw new upgrade_requires_exception($component, $plugin->version
, $CFG->version
, $plugin->requires
);
610 } else if ($plugin->requires
< 2010000000) {
611 throw new plugin_defective_exception($component, 'Plugin is not compatible with Moodle 2.x or later.');
615 // Throw exception if plugin is incompatible with moodle version.
616 if (!empty($plugin->incompatible
)) {
617 if ($CFG->branch
<= $plugin->incompatible
) {
618 throw new plugin_incompatible_exception($component, $plugin->version
);
622 // try to recover from interrupted install.php if needed
623 if (file_exists($fullplug.'/db/install.php')) {
624 if (get_config($plugin->fullname
, 'installrunning')) {
625 require_once($fullplug.'/db/install.php');
626 $recover_install_function = 'xmldb_'.$plugin->fullname
.'_install_recovery';
627 if (function_exists($recover_install_function)) {
628 $startcallback($component, true, $verbose);
629 $recover_install_function();
630 unset_config('installrunning', $plugin->fullname
);
631 update_capabilities($component);
632 log_update_descriptions($component);
633 external_update_descriptions($component);
634 \core\task\manager
::reset_scheduled_tasks_for_component($component);
635 \core_analytics\manager
::update_default_models_for_component($component);
636 message_update_providers($component);
637 \core\message\inbound\manager
::update_handlers_for_component($component);
638 if ($type === 'message') {
639 message_update_processors($plug);
641 upgrade_plugin_mnet_functions($component);
642 core_tag_area
::reset_definitions_for_component($component);
643 $endcallback($component, true, $verbose);
648 $installedversion = $DB->get_field('config_plugins', 'value', array('name'=>'version', 'plugin'=>$component)); // No caching!
649 if (empty($installedversion)) { // new installation
650 $startcallback($component, true, $verbose);
652 /// Install tables if defined
653 if (file_exists($fullplug.'/db/install.xml')) {
654 $DB->get_manager()->install_from_xmldb_file($fullplug.'/db/install.xml');
658 upgrade_plugin_savepoint(true, $plugin->version
, $type, $plug, false);
660 /// execute post install file
661 if (file_exists($fullplug.'/db/install.php')) {
662 require_once($fullplug.'/db/install.php');
663 set_config('installrunning', 1, $plugin->fullname
);
664 $post_install_function = 'xmldb_'.$plugin->fullname
.'_install';
665 $post_install_function();
666 unset_config('installrunning', $plugin->fullname
);
669 /// Install various components
670 update_capabilities($component);
671 log_update_descriptions($component);
672 external_update_descriptions($component);
673 \core\task\manager
::reset_scheduled_tasks_for_component($component);
674 \core_analytics\manager
::update_default_models_for_component($component);
675 message_update_providers($component);
676 \core\message\inbound\manager
::update_handlers_for_component($component);
677 if ($type === 'message') {
678 message_update_processors($plug);
680 upgrade_plugin_mnet_functions($component);
681 core_tag_area
::reset_definitions_for_component($component);
682 $endcallback($component, true, $verbose);
684 } else if ($installedversion < $plugin->version
) { // upgrade
685 /// Run the upgrade function for the plugin.
686 $startcallback($component, false, $verbose);
688 if (is_readable($fullplug.'/db/upgrade.php')) {
689 require_once($fullplug.'/db/upgrade.php'); // defines upgrading function
691 $newupgrade_function = 'xmldb_'.$plugin->fullname
.'_upgrade';
692 $result = $newupgrade_function($installedversion);
697 $installedversion = $DB->get_field('config_plugins', 'value', array('name'=>'version', 'plugin'=>$component)); // No caching!
698 if ($installedversion < $plugin->version
) {
699 // store version if not already there
700 upgrade_plugin_savepoint($result, $plugin->version
, $type, $plug, false);
703 /// Upgrade various components
704 update_capabilities($component);
705 log_update_descriptions($component);
706 external_update_descriptions($component);
707 \core\task\manager
::reset_scheduled_tasks_for_component($component);
708 \core_analytics\manager
::update_default_models_for_component($component);
709 message_update_providers($component);
710 \core\message\inbound\manager
::update_handlers_for_component($component);
711 if ($type === 'message') {
713 message_update_processors($plug);
715 upgrade_plugin_mnet_functions($component);
716 core_tag_area
::reset_definitions_for_component($component);
717 $endcallback($component, false, $verbose);
719 } else if ($installedversion > $plugin->version
) {
720 throw new downgrade_exception($component, $installedversion, $plugin->version
);
726 * Find and check all modules and load them up or upgrade them if necessary
731 function upgrade_plugins_modules($startcallback, $endcallback, $verbose) {
734 $mods = core_component
::get_plugin_list('mod');
736 foreach ($mods as $mod=>$fullmod) {
738 if ($mod === 'NEWMODULE') { // Someone has unzipped the template, ignore it
742 $component = clean_param('mod_'.$mod, PARAM_COMPONENT
);
744 // check module dir is valid name
745 if (empty($component)) {
746 throw new plugin_defective_exception('mod_'.$mod, 'Invalid plugin directory name.');
749 if (!is_readable($fullmod.'/version.php')) {
750 throw new plugin_defective_exception($component, 'Missing version.php');
753 $module = new stdClass();
754 $plugin = new stdClass();
755 $plugin->version
= null;
756 require($fullmod .'/version.php'); // Defines $plugin with version etc.
758 // Check if the legacy $module syntax is still used.
759 if (!is_object($module) or (count((array)$module) > 0)) {
760 throw new plugin_defective_exception($component, 'Unsupported $module syntax detected in version.php');
763 // Prepare the record for the {modules} table.
764 $module = clone($plugin);
765 unset($module->version
);
766 unset($module->component
);
767 unset($module->dependencies
);
768 unset($module->release
);
770 if (empty($plugin->version
)) {
771 throw new plugin_defective_exception($component, 'Missing $plugin->version number in version.php.');
774 if (empty($plugin->component
)) {
775 throw new plugin_defective_exception($component, 'Missing $plugin->component declaration in version.php.');
778 if ($plugin->component
!== $component) {
779 throw new plugin_misplaced_exception($plugin->component
, null, $fullmod);
782 if (!empty($plugin->requires
)) {
783 if ($plugin->requires
> $CFG->version
) {
784 throw new upgrade_requires_exception($component, $plugin->version
, $CFG->version
, $plugin->requires
);
785 } else if ($plugin->requires
< 2010000000) {
786 throw new plugin_defective_exception($component, 'Plugin is not compatible with Moodle 2.x or later.');
790 if (empty($module->cron
)) {
794 // all modules must have en lang pack
795 if (!is_readable("$fullmod/lang/en/$mod.php")) {
796 throw new plugin_defective_exception($component, 'Missing mandatory en language pack.');
799 $module->name
= $mod; // The name MUST match the directory
801 $installedversion = $DB->get_field('config_plugins', 'value', array('name'=>'version', 'plugin'=>$component)); // No caching!
803 if (file_exists($fullmod.'/db/install.php')) {
804 if (get_config($module->name
, 'installrunning')) {
805 require_once($fullmod.'/db/install.php');
806 $recover_install_function = 'xmldb_'.$module->name
.'_install_recovery';
807 if (function_exists($recover_install_function)) {
808 $startcallback($component, true, $verbose);
809 $recover_install_function();
810 unset_config('installrunning', $module->name
);
811 // Install various components too
812 update_capabilities($component);
813 log_update_descriptions($component);
814 external_update_descriptions($component);
815 \core\task\manager
::reset_scheduled_tasks_for_component($component);
816 \core_analytics\manager
::update_default_models_for_component($component);
817 message_update_providers($component);
818 \core\message\inbound\manager
::update_handlers_for_component($component);
819 upgrade_plugin_mnet_functions($component);
820 core_tag_area
::reset_definitions_for_component($component);
821 $endcallback($component, true, $verbose);
826 if (empty($installedversion)) {
827 $startcallback($component, true, $verbose);
829 /// Execute install.xml (XMLDB) - must be present in all modules
830 $DB->get_manager()->install_from_xmldb_file($fullmod.'/db/install.xml');
832 /// Add record into modules table - may be needed in install.php already
833 $module->id
= $DB->insert_record('modules', $module);
834 upgrade_mod_savepoint(true, $plugin->version
, $module->name
, false);
836 /// Post installation hook - optional
837 if (file_exists("$fullmod/db/install.php")) {
838 require_once("$fullmod/db/install.php");
839 // Set installation running flag, we need to recover after exception or error
840 set_config('installrunning', 1, $module->name
);
841 $post_install_function = 'xmldb_'.$module->name
.'_install';
842 $post_install_function();
843 unset_config('installrunning', $module->name
);
846 /// Install various components
847 update_capabilities($component);
848 log_update_descriptions($component);
849 external_update_descriptions($component);
850 \core\task\manager
::reset_scheduled_tasks_for_component($component);
851 \core_analytics\manager
::update_default_models_for_component($component);
852 message_update_providers($component);
853 \core\message\inbound\manager
::update_handlers_for_component($component);
854 upgrade_plugin_mnet_functions($component);
855 core_tag_area
::reset_definitions_for_component($component);
857 $endcallback($component, true, $verbose);
859 } else if ($installedversion < $plugin->version
) {
860 /// If versions say that we need to upgrade but no upgrade files are available, notify and continue
861 $startcallback($component, false, $verbose);
863 if (is_readable($fullmod.'/db/upgrade.php')) {
864 require_once($fullmod.'/db/upgrade.php'); // defines new upgrading function
865 $newupgrade_function = 'xmldb_'.$module->name
.'_upgrade';
866 $result = $newupgrade_function($installedversion, $module);
871 $installedversion = $DB->get_field('config_plugins', 'value', array('name'=>'version', 'plugin'=>$component)); // No caching!
872 $currmodule = $DB->get_record('modules', array('name'=>$module->name
));
873 if ($installedversion < $plugin->version
) {
874 // store version if not already there
875 upgrade_mod_savepoint($result, $plugin->version
, $mod, false);
878 // update cron flag if needed
879 if ($currmodule->cron
!= $module->cron
) {
880 $DB->set_field('modules', 'cron', $module->cron
, array('name' => $module->name
));
883 // Upgrade various components
884 update_capabilities($component);
885 log_update_descriptions($component);
886 external_update_descriptions($component);
887 \core\task\manager
::reset_scheduled_tasks_for_component($component);
888 \core_analytics\manager
::update_default_models_for_component($component);
889 message_update_providers($component);
890 \core\message\inbound\manager
::update_handlers_for_component($component);
891 upgrade_plugin_mnet_functions($component);
892 core_tag_area
::reset_definitions_for_component($component);
894 $endcallback($component, false, $verbose);
896 } else if ($installedversion > $plugin->version
) {
897 throw new downgrade_exception($component, $installedversion, $plugin->version
);
904 * This function finds all available blocks and install them
905 * into blocks table or do all the upgrade process if newer.
910 function upgrade_plugins_blocks($startcallback, $endcallback, $verbose) {
913 require_once($CFG->dirroot
.'/blocks/moodleblock.class.php');
915 $blocktitles = array(); // we do not want duplicate titles
917 //Is this a first install
918 $first_install = null;
920 $blocks = core_component
::get_plugin_list('block');
922 foreach ($blocks as $blockname=>$fullblock) {
924 if (is_null($first_install)) {
925 $first_install = ($DB->count_records('block_instances') == 0);
928 if ($blockname === 'NEWBLOCK') { // Someone has unzipped the template, ignore it
932 $component = clean_param('block_'.$blockname, PARAM_COMPONENT
);
934 // check block dir is valid name
935 if (empty($component)) {
936 throw new plugin_defective_exception('block_'.$blockname, 'Invalid plugin directory name.');
939 if (!is_readable($fullblock.'/version.php')) {
940 throw new plugin_defective_exception('block/'.$blockname, 'Missing version.php file.');
942 $plugin = new stdClass();
943 $plugin->version
= null;
945 $module = $plugin; // Prevent some notices when module placed in wrong directory.
946 include($fullblock.'/version.php');
948 $block = clone($plugin);
949 unset($block->version
);
950 unset($block->component
);
951 unset($block->dependencies
);
952 unset($block->release
);
954 if (empty($plugin->version
)) {
955 throw new plugin_defective_exception($component, 'Missing block version number in version.php.');
958 if (empty($plugin->component
)) {
959 throw new plugin_defective_exception($component, 'Missing $plugin->component declaration in version.php.');
962 if ($plugin->component
!== $component) {
963 throw new plugin_misplaced_exception($plugin->component
, null, $fullblock);
966 if (!empty($plugin->requires
)) {
967 if ($plugin->requires
> $CFG->version
) {
968 throw new upgrade_requires_exception($component, $plugin->version
, $CFG->version
, $plugin->requires
);
969 } else if ($plugin->requires
< 2010000000) {
970 throw new plugin_defective_exception($component, 'Plugin is not compatible with Moodle 2.x or later.');
974 if (!is_readable($fullblock.'/block_'.$blockname.'.php')) {
975 throw new plugin_defective_exception('block/'.$blockname, 'Missing main block class file.');
977 include_once($fullblock.'/block_'.$blockname.'.php');
979 $classname = 'block_'.$blockname;
981 if (!class_exists($classname)) {
982 throw new plugin_defective_exception($component, 'Can not load main class.');
985 $blockobj = new $classname; // This is what we'll be testing
986 $blocktitle = $blockobj->get_title();
988 // OK, it's as we all hoped. For further tests, the object will do them itself.
989 if (!$blockobj->_self_test()) {
990 throw new plugin_defective_exception($component, 'Self test failed.');
993 $block->name
= $blockname; // The name MUST match the directory
995 $installedversion = $DB->get_field('config_plugins', 'value', array('name'=>'version', 'plugin'=>$component)); // No caching!
997 if (file_exists($fullblock.'/db/install.php')) {
998 if (get_config('block_'.$blockname, 'installrunning')) {
999 require_once($fullblock.'/db/install.php');
1000 $recover_install_function = 'xmldb_block_'.$blockname.'_install_recovery';
1001 if (function_exists($recover_install_function)) {
1002 $startcallback($component, true, $verbose);
1003 $recover_install_function();
1004 unset_config('installrunning', 'block_'.$blockname);
1005 // Install various components
1006 update_capabilities($component);
1007 log_update_descriptions($component);
1008 external_update_descriptions($component);
1009 \core\task\manager
::reset_scheduled_tasks_for_component($component);
1010 \core_analytics\manager
::update_default_models_for_component($component);
1011 message_update_providers($component);
1012 \core\message\inbound\manager
::update_handlers_for_component($component);
1013 upgrade_plugin_mnet_functions($component);
1014 core_tag_area
::reset_definitions_for_component($component);
1015 $endcallback($component, true, $verbose);
1020 if (empty($installedversion)) { // block not installed yet, so install it
1021 $conflictblock = array_search($blocktitle, $blocktitles);
1022 if ($conflictblock !== false) {
1023 // Duplicate block titles are not allowed, they confuse people
1024 // AND PHP's associative arrays ;)
1025 throw new plugin_defective_exception($component, get_string('blocknameconflict', 'error', (object)array('name'=>$block->name
, 'conflict'=>$conflictblock)));
1027 $startcallback($component, true, $verbose);
1029 if (file_exists($fullblock.'/db/install.xml')) {
1030 $DB->get_manager()->install_from_xmldb_file($fullblock.'/db/install.xml');
1032 $block->id
= $DB->insert_record('block', $block);
1033 upgrade_block_savepoint(true, $plugin->version
, $block->name
, false);
1035 if (file_exists($fullblock.'/db/install.php')) {
1036 require_once($fullblock.'/db/install.php');
1037 // Set installation running flag, we need to recover after exception or error
1038 set_config('installrunning', 1, 'block_'.$blockname);
1039 $post_install_function = 'xmldb_block_'.$blockname.'_install';
1040 $post_install_function();
1041 unset_config('installrunning', 'block_'.$blockname);
1044 $blocktitles[$block->name
] = $blocktitle;
1046 // Install various components
1047 update_capabilities($component);
1048 log_update_descriptions($component);
1049 external_update_descriptions($component);
1050 \core\task\manager
::reset_scheduled_tasks_for_component($component);
1051 \core_analytics\manager
::update_default_models_for_component($component);
1052 message_update_providers($component);
1053 \core\message\inbound\manager
::update_handlers_for_component($component);
1054 core_tag_area
::reset_definitions_for_component($component);
1055 upgrade_plugin_mnet_functions($component);
1057 $endcallback($component, true, $verbose);
1059 } else if ($installedversion < $plugin->version
) {
1060 $startcallback($component, false, $verbose);
1062 if (is_readable($fullblock.'/db/upgrade.php')) {
1063 require_once($fullblock.'/db/upgrade.php'); // defines new upgrading function
1064 $newupgrade_function = 'xmldb_block_'.$blockname.'_upgrade';
1065 $result = $newupgrade_function($installedversion, $block);
1070 $installedversion = $DB->get_field('config_plugins', 'value', array('name'=>'version', 'plugin'=>$component)); // No caching!
1071 $currblock = $DB->get_record('block', array('name'=>$block->name
));
1072 if ($installedversion < $plugin->version
) {
1073 // store version if not already there
1074 upgrade_block_savepoint($result, $plugin->version
, $block->name
, false);
1077 if ($currblock->cron
!= $block->cron
) {
1078 // update cron flag if needed
1079 $DB->set_field('block', 'cron', $block->cron
, array('id' => $currblock->id
));
1082 // Upgrade various components
1083 update_capabilities($component);
1084 log_update_descriptions($component);
1085 external_update_descriptions($component);
1086 \core\task\manager
::reset_scheduled_tasks_for_component($component);
1087 \core_analytics\manager
::update_default_models_for_component($component);
1088 message_update_providers($component);
1089 \core\message\inbound\manager
::update_handlers_for_component($component);
1090 upgrade_plugin_mnet_functions($component);
1091 core_tag_area
::reset_definitions_for_component($component);
1093 $endcallback($component, false, $verbose);
1095 } else if ($installedversion > $plugin->version
) {
1096 throw new downgrade_exception($component, $installedversion, $plugin->version
);
1101 // Finally, if we are in the first_install of BLOCKS setup frontpage and admin page blocks
1102 if ($first_install) {
1103 //Iterate over each course - there should be only site course here now
1104 if ($courses = $DB->get_records('course')) {
1105 foreach ($courses as $course) {
1106 blocks_add_default_course_blocks($course);
1110 blocks_add_default_system_blocks();
1116 * Log_display description function used during install and upgrade.
1118 * @param string $component name of component (moodle, mod_assignment, etc.)
1121 function log_update_descriptions($component) {
1124 $defpath = core_component
::get_component_directory($component).'/db/log.php';
1126 if (!file_exists($defpath)) {
1127 $DB->delete_records('log_display', array('component'=>$component));
1135 foreach ($logs as $log) {
1136 $newlogs[$log['module'].'-'.$log['action']] = $log; // kind of unique name
1141 $fields = array('module', 'action', 'mtable', 'field');
1142 // update all log fist
1143 $dblogs = $DB->get_records('log_display', array('component'=>$component));
1144 foreach ($dblogs as $dblog) {
1145 $name = $dblog->module
.'-'.$dblog->action
;
1147 if (empty($logs[$name])) {
1148 $DB->delete_records('log_display', array('id'=>$dblog->id
));
1152 $log = $logs[$name];
1153 unset($logs[$name]);
1156 foreach ($fields as $field) {
1157 if ($dblog->$field != $log[$field]) {
1158 $dblog->$field = $log[$field];
1163 $DB->update_record('log_display', $dblog);
1166 foreach ($logs as $log) {
1167 $dblog = (object)$log;
1168 $dblog->component
= $component;
1169 $DB->insert_record('log_display', $dblog);
1174 * Web service discovery function used during install and upgrade.
1175 * @param string $component name of component (moodle, mod_assignment, etc.)
1178 function external_update_descriptions($component) {
1181 $defpath = core_component
::get_component_directory($component).'/db/services.php';
1183 if (!file_exists($defpath)) {
1184 require_once($CFG->dirroot
.'/lib/externallib.php');
1185 external_delete_descriptions($component);
1190 $functions = array();
1191 $services = array();
1194 // update all function fist
1195 $dbfunctions = $DB->get_records('external_functions', array('component'=>$component));
1196 foreach ($dbfunctions as $dbfunction) {
1197 if (empty($functions[$dbfunction->name
])) {
1198 $DB->delete_records('external_functions', array('id'=>$dbfunction->id
));
1199 // do not delete functions from external_services_functions, beacuse
1200 // we want to notify admins when functions used in custom services disappear
1202 //TODO: this looks wrong, we have to delete it eventually (skodak)
1206 $function = $functions[$dbfunction->name
];
1207 unset($functions[$dbfunction->name
]);
1208 $function['classpath'] = empty($function['classpath']) ?
null : $function['classpath'];
1211 if ($dbfunction->classname
!= $function['classname']) {
1212 $dbfunction->classname
= $function['classname'];
1215 if ($dbfunction->methodname
!= $function['methodname']) {
1216 $dbfunction->methodname
= $function['methodname'];
1219 if ($dbfunction->classpath
!= $function['classpath']) {
1220 $dbfunction->classpath
= $function['classpath'];
1223 $functioncapabilities = array_key_exists('capabilities', $function)?
$function['capabilities']:'';
1224 if ($dbfunction->capabilities
!= $functioncapabilities) {
1225 $dbfunction->capabilities
= $functioncapabilities;
1229 if (isset($function['services']) and is_array($function['services'])) {
1230 sort($function['services']);
1231 $functionservices = implode(',', $function['services']);
1233 // Force null values in the DB.
1234 $functionservices = null;
1237 if ($dbfunction->services
!= $functionservices) {
1238 // Now, we need to check if services were removed, in that case we need to remove the function from them.
1239 $servicesremoved = array_diff(explode(",", $dbfunction->services
), explode(",", $functionservices));
1240 foreach ($servicesremoved as $removedshortname) {
1241 if ($externalserviceid = $DB->get_field('external_services', 'id', array("shortname" => $removedshortname))) {
1242 $DB->delete_records('external_services_functions', array('functionname' => $dbfunction->name
,
1243 'externalserviceid' => $externalserviceid));
1247 $dbfunction->services
= $functionservices;
1251 $DB->update_record('external_functions', $dbfunction);
1254 foreach ($functions as $fname => $function) {
1255 $dbfunction = new stdClass();
1256 $dbfunction->name
= $fname;
1257 $dbfunction->classname
= $function['classname'];
1258 $dbfunction->methodname
= $function['methodname'];
1259 $dbfunction->classpath
= empty($function['classpath']) ?
null : $function['classpath'];
1260 $dbfunction->component
= $component;
1261 $dbfunction->capabilities
= array_key_exists('capabilities', $function)?
$function['capabilities']:'';
1263 if (isset($function['services']) and is_array($function['services'])) {
1264 sort($function['services']);
1265 $dbfunction->services
= implode(',', $function['services']);
1267 // Force null values in the DB.
1268 $dbfunction->services
= null;
1271 $dbfunction->id
= $DB->insert_record('external_functions', $dbfunction);
1275 // now deal with services
1276 $dbservices = $DB->get_records('external_services', array('component'=>$component));
1277 foreach ($dbservices as $dbservice) {
1278 if (empty($services[$dbservice->name
])) {
1279 $DB->delete_records('external_tokens', array('externalserviceid'=>$dbservice->id
));
1280 $DB->delete_records('external_services_functions', array('externalserviceid'=>$dbservice->id
));
1281 $DB->delete_records('external_services_users', array('externalserviceid'=>$dbservice->id
));
1282 $DB->delete_records('external_services', array('id'=>$dbservice->id
));
1285 $service = $services[$dbservice->name
];
1286 unset($services[$dbservice->name
]);
1287 $service['enabled'] = empty($service['enabled']) ?
0 : $service['enabled'];
1288 $service['requiredcapability'] = empty($service['requiredcapability']) ?
null : $service['requiredcapability'];
1289 $service['restrictedusers'] = !isset($service['restrictedusers']) ?
1 : $service['restrictedusers'];
1290 $service['downloadfiles'] = !isset($service['downloadfiles']) ?
0 : $service['downloadfiles'];
1291 $service['uploadfiles'] = !isset($service['uploadfiles']) ?
0 : $service['uploadfiles'];
1292 $service['shortname'] = !isset($service['shortname']) ?
null : $service['shortname'];
1295 if ($dbservice->requiredcapability
!= $service['requiredcapability']) {
1296 $dbservice->requiredcapability
= $service['requiredcapability'];
1299 if ($dbservice->restrictedusers
!= $service['restrictedusers']) {
1300 $dbservice->restrictedusers
= $service['restrictedusers'];
1303 if ($dbservice->downloadfiles
!= $service['downloadfiles']) {
1304 $dbservice->downloadfiles
= $service['downloadfiles'];
1307 if ($dbservice->uploadfiles
!= $service['uploadfiles']) {
1308 $dbservice->uploadfiles
= $service['uploadfiles'];
1311 //if shortname is not a PARAM_ALPHANUMEXT, fail (tested here for service update and creation)
1312 if (isset($service['shortname']) and
1313 (clean_param($service['shortname'], PARAM_ALPHANUMEXT
) != $service['shortname'])) {
1314 throw new moodle_exception('installserviceshortnameerror', 'webservice', '', $service['shortname']);
1316 if ($dbservice->shortname
!= $service['shortname']) {
1317 //check that shortname is unique
1318 if (isset($service['shortname'])) { //we currently accepts multiple shortname == null
1319 $existingservice = $DB->get_record('external_services',
1320 array('shortname' => $service['shortname']));
1321 if (!empty($existingservice)) {
1322 throw new moodle_exception('installexistingserviceshortnameerror', 'webservice', '', $service['shortname']);
1325 $dbservice->shortname
= $service['shortname'];
1329 $DB->update_record('external_services', $dbservice);
1332 $functions = $DB->get_records('external_services_functions', array('externalserviceid'=>$dbservice->id
));
1333 foreach ($functions as $function) {
1334 $key = array_search($function->functionname
, $service['functions']);
1335 if ($key === false) {
1336 $DB->delete_records('external_services_functions', array('id'=>$function->id
));
1338 unset($service['functions'][$key]);
1341 foreach ($service['functions'] as $fname) {
1342 $newf = new stdClass();
1343 $newf->externalserviceid
= $dbservice->id
;
1344 $newf->functionname
= $fname;
1345 $DB->insert_record('external_services_functions', $newf);
1349 foreach ($services as $name => $service) {
1350 //check that shortname is unique
1351 if (isset($service['shortname'])) { //we currently accepts multiple shortname == null
1352 $existingservice = $DB->get_record('external_services',
1353 array('shortname' => $service['shortname']));
1354 if (!empty($existingservice)) {
1355 throw new moodle_exception('installserviceshortnameerror', 'webservice');
1359 $dbservice = new stdClass();
1360 $dbservice->name
= $name;
1361 $dbservice->enabled
= empty($service['enabled']) ?
0 : $service['enabled'];
1362 $dbservice->requiredcapability
= empty($service['requiredcapability']) ?
null : $service['requiredcapability'];
1363 $dbservice->restrictedusers
= !isset($service['restrictedusers']) ?
1 : $service['restrictedusers'];
1364 $dbservice->downloadfiles
= !isset($service['downloadfiles']) ?
0 : $service['downloadfiles'];
1365 $dbservice->uploadfiles
= !isset($service['uploadfiles']) ?
0 : $service['uploadfiles'];
1366 $dbservice->shortname
= !isset($service['shortname']) ?
null : $service['shortname'];
1367 $dbservice->component
= $component;
1368 $dbservice->timecreated
= time();
1369 $dbservice->id
= $DB->insert_record('external_services', $dbservice);
1370 foreach ($service['functions'] as $fname) {
1371 $newf = new stdClass();
1372 $newf->externalserviceid
= $dbservice->id
;
1373 $newf->functionname
= $fname;
1374 $DB->insert_record('external_services_functions', $newf);
1380 * Allow plugins and subsystems to add external functions to other plugins or built-in services.
1381 * This function is executed just after all the plugins have been updated.
1383 function external_update_services() {
1386 // Look for external functions that want to be added in existing services.
1387 $functions = $DB->get_records_select('external_functions', 'services IS NOT NULL');
1389 $servicescache = array();
1390 foreach ($functions as $function) {
1391 // Prevent edge cases.
1392 if (empty($function->services
)) {
1395 $services = explode(',', $function->services
);
1397 foreach ($services as $serviceshortname) {
1398 // Get the service id by shortname.
1399 if (!empty($servicescache[$serviceshortname])) {
1400 $serviceid = $servicescache[$serviceshortname];
1401 } else if ($service = $DB->get_record('external_services', array('shortname' => $serviceshortname))) {
1402 // If the component is empty, it means that is not a built-in service.
1403 // We don't allow functions to inject themselves in services created by an user in Moodle.
1404 if (empty($service->component
)) {
1407 $serviceid = $service->id
;
1408 $servicescache[$serviceshortname] = $serviceid;
1410 // Service not found.
1413 // Finally add the function to the service.
1414 $newf = new stdClass();
1415 $newf->externalserviceid
= $serviceid;
1416 $newf->functionname
= $function->name
;
1418 if (!$DB->record_exists('external_services_functions', (array)$newf)) {
1419 $DB->insert_record('external_services_functions', $newf);
1426 * upgrade logging functions
1428 function upgrade_handle_exception($ex, $plugin = null) {
1431 // rollback everything, we need to log all upgrade problems
1432 abort_all_db_transactions();
1434 $info = get_exception_info($ex);
1436 // First log upgrade error
1437 upgrade_log(UPGRADE_LOG_ERROR
, $plugin, 'Exception: ' . get_class($ex), $info->message
, $info->backtrace
);
1439 // Always turn on debugging - admins need to know what is going on
1440 set_debugging(DEBUG_DEVELOPER
, true);
1442 default_exception_handler($ex, true, $plugin);
1446 * Adds log entry into upgrade_log table
1448 * @param int $type UPGRADE_LOG_NORMAL, UPGRADE_LOG_NOTICE or UPGRADE_LOG_ERROR
1449 * @param string $plugin frankenstyle component name
1450 * @param string $info short description text of log entry
1451 * @param string $details long problem description
1452 * @param string $backtrace string used for errors only
1455 function upgrade_log($type, $plugin, $info, $details=null, $backtrace=null) {
1456 global $DB, $USER, $CFG;
1458 if (empty($plugin)) {
1462 list($plugintype, $pluginname) = core_component
::normalize_component($plugin);
1463 $component = is_null($pluginname) ?
$plugintype : $plugintype . '_' . $pluginname;
1465 $backtrace = format_backtrace($backtrace, true);
1467 $currentversion = null;
1468 $targetversion = null;
1470 //first try to find out current version number
1471 if ($plugintype === 'core') {
1473 $currentversion = $CFG->version
;
1476 include("$CFG->dirroot/version.php");
1477 $targetversion = $version;
1480 $pluginversion = get_config($component, 'version');
1481 if (!empty($pluginversion)) {
1482 $currentversion = $pluginversion;
1484 $cd = core_component
::get_component_directory($component);
1485 if (file_exists("$cd/version.php")) {
1486 $plugin = new stdClass();
1487 $plugin->version
= null;
1489 include("$cd/version.php");
1490 $targetversion = $plugin->version
;
1494 $log = new stdClass();
1496 $log->plugin
= $component;
1497 $log->version
= $currentversion;
1498 $log->targetversion
= $targetversion;
1500 $log->details
= $details;
1501 $log->backtrace
= $backtrace;
1502 $log->userid
= $USER->id
;
1503 $log->timemodified
= time();
1505 $DB->insert_record('upgrade_log', $log);
1506 } catch (Exception
$ignored) {
1507 // possible during install or 2.0 upgrade
1512 * Marks start of upgrade, blocks any other access to site.
1513 * The upgrade is finished at the end of script or after timeout.
1519 function upgrade_started($preinstall=false) {
1520 global $CFG, $DB, $PAGE, $OUTPUT;
1522 static $started = false;
1525 ignore_user_abort(true);
1526 upgrade_setup_debug(true);
1528 } else if ($started) {
1529 upgrade_set_timeout(120);
1532 if (!CLI_SCRIPT
and !$PAGE->headerprinted
) {
1533 $strupgrade = get_string('upgradingversion', 'admin');
1534 $PAGE->set_pagelayout('maintenance');
1535 upgrade_init_javascript();
1536 $PAGE->set_title($strupgrade.' - Moodle '.$CFG->target_release
);
1537 $PAGE->set_heading($strupgrade);
1538 $PAGE->navbar
->add($strupgrade);
1539 $PAGE->set_cacheable(false);
1540 echo $OUTPUT->header();
1543 ignore_user_abort(true);
1544 core_shutdown_manager
::register_function('upgrade_finished_handler');
1545 upgrade_setup_debug(true);
1546 set_config('upgraderunning', time()+
300);
1552 * Internal function - executed if upgrade interrupted.
1554 function upgrade_finished_handler() {
1559 * Indicates upgrade is finished.
1561 * This function may be called repeatedly.
1566 function upgrade_finished($continueurl=null) {
1567 global $CFG, $DB, $OUTPUT;
1569 if (!empty($CFG->upgraderunning
)) {
1570 unset_config('upgraderunning');
1571 // We have to forcefully purge the caches using the writer here.
1572 // This has to be done after we unset the config var. If someone hits the site while this is set they will
1573 // cause the config values to propogate to the caches.
1574 // Caches are purged after the last step in an upgrade but there is several code routines that exceute between
1575 // then and now that leaving a window for things to fall out of sync.
1576 cache_helper
::purge_all(true);
1577 upgrade_setup_debug(false);
1578 ignore_user_abort(false);
1580 echo $OUTPUT->continue_button($continueurl);
1581 echo $OUTPUT->footer();
1591 function upgrade_setup_debug($starting) {
1594 static $originaldebug = null;
1597 if ($originaldebug === null) {
1598 $originaldebug = $DB->get_debug();
1600 if (!empty($CFG->upgradeshowsql
)) {
1601 $DB->set_debug(true);
1604 $DB->set_debug($originaldebug);
1608 function print_upgrade_separator() {
1615 * Default start upgrade callback
1616 * @param string $plugin
1617 * @param bool $installation true if installation, false means upgrade
1619 function print_upgrade_part_start($plugin, $installation, $verbose) {
1621 if (empty($plugin) or $plugin == 'moodle') {
1622 upgrade_started($installation); // does not store upgrade running flag yet
1624 echo $OUTPUT->heading(get_string('coresystem'));
1629 echo $OUTPUT->heading($plugin);
1632 if ($installation) {
1633 if (empty($plugin) or $plugin == 'moodle') {
1634 // no need to log - log table not yet there ;-)
1636 upgrade_log(UPGRADE_LOG_NORMAL
, $plugin, 'Starting plugin installation');
1639 core_upgrade_time
::record_start();
1640 if (empty($plugin) or $plugin == 'moodle') {
1641 upgrade_log(UPGRADE_LOG_NORMAL
, $plugin, 'Starting core upgrade');
1643 upgrade_log(UPGRADE_LOG_NORMAL
, $plugin, 'Starting plugin upgrade');
1649 * Default end upgrade callback
1650 * @param string $plugin
1651 * @param bool $installation true if installation, false means upgrade
1653 function print_upgrade_part_end($plugin, $installation, $verbose) {
1656 if ($installation) {
1657 if (empty($plugin) or $plugin == 'moodle') {
1658 upgrade_log(UPGRADE_LOG_NORMAL
, $plugin, 'Core installed');
1660 upgrade_log(UPGRADE_LOG_NORMAL
, $plugin, 'Plugin installed');
1663 if (empty($plugin) or $plugin == 'moodle') {
1664 upgrade_log(UPGRADE_LOG_NORMAL
, $plugin, 'Core upgraded');
1666 upgrade_log(UPGRADE_LOG_NORMAL
, $plugin, 'Plugin upgraded');
1670 if ($installation) {
1671 $message = get_string('success');
1673 $duration = core_upgrade_time
::get_elapsed();
1674 $message = get_string('successduration', '', format_float($duration, 2));
1676 $notification = new \core\output\notification
($message, \core\output\notification
::NOTIFY_SUCCESS
);
1677 $notification->set_show_closebutton(false);
1678 echo $OUTPUT->render($notification);
1679 print_upgrade_separator();
1684 * Sets up JS code required for all upgrade scripts.
1687 function upgrade_init_javascript() {
1689 // scroll to the end of each upgrade page so that ppl see either error or continue button,
1690 // no need to scroll continuously any more, it is enough to jump to end once the footer is printed ;-)
1691 $js = "window.scrollTo(0, 5000000);";
1692 $PAGE->requires
->js_init_code($js);
1696 * Try to upgrade the given language pack (or current language)
1698 * @param string $lang the code of the language to update, defaults to the current language
1700 function upgrade_language_pack($lang = null) {
1703 if (!empty($CFG->skiplangupgrade
)) {
1707 if (!file_exists("$CFG->dirroot/$CFG->admin/tool/langimport/lib.php")) {
1708 // weird, somebody uninstalled the import utility
1713 $lang = current_language();
1716 if (!get_string_manager()->translation_exists($lang)) {
1720 get_string_manager()->reset_caches();
1722 if ($lang === 'en') {
1723 return; // Nothing to do
1726 upgrade_started(false);
1728 require_once("$CFG->dirroot/$CFG->admin/tool/langimport/lib.php");
1729 tool_langimport_preupgrade_update($lang);
1731 get_string_manager()->reset_caches();
1733 print_upgrade_separator();
1737 * Build the current theme so that the user doesn't have to wait for it
1738 * to build on the first page load after the install / upgrade.
1740 function upgrade_themes() {
1743 require_once("{$CFG->libdir}/outputlib.php");
1745 // Build the current theme so that the user can immediately
1746 // browse the site without having to wait for the theme to build.
1747 $themeconfig = theme_config
::load($CFG->theme
);
1748 $direction = right_to_left() ?
'rtl' : 'ltr';
1749 theme_build_css_for_themes([$themeconfig], [$direction]);
1751 // Only queue the task if there isn't already one queued.
1752 if (empty(\core\task\manager
::get_adhoc_tasks('\\core\\task\\build_installed_themes_task'))) {
1753 // Queue a task to build all of the site themes at some point
1754 // later. These can happen offline because it doesn't block the
1755 // user unless they quickly change theme.
1756 $adhoctask = new \core\task\build_installed_themes_task
();
1757 \core\task\manager
::queue_adhoc_task($adhoctask);
1762 * Install core moodle tables and initialize
1763 * @param float $version target version
1764 * @param bool $verbose
1765 * @return void, may throw exception
1767 function install_core($version, $verbose) {
1770 // We can not call purge_all_caches() yet, make sure the temp and cache dirs exist and are empty.
1771 remove_dir($CFG->cachedir
.'', true);
1772 make_cache_directory('', true);
1774 remove_dir($CFG->localcachedir
.'', true);
1775 make_localcache_directory('', true);
1777 remove_dir($CFG->tempdir
.'', true);
1778 make_temp_directory('', true);
1780 remove_dir($CFG->backuptempdir
.'', true);
1781 make_backup_temp_directory('', true);
1783 remove_dir($CFG->dataroot
.'/muc', true);
1784 make_writable_directory($CFG->dataroot
.'/muc', true);
1787 core_php_time_limit
::raise(600);
1788 print_upgrade_part_start('moodle', true, $verbose); // does not store upgrade running flag
1790 $DB->get_manager()->install_from_xmldb_file("$CFG->libdir/db/install.xml");
1791 upgrade_started(); // we want the flag to be stored in config table ;-)
1793 // set all core default records and default settings
1794 require_once("$CFG->libdir/db/install.php");
1795 xmldb_main_install(); // installs the capabilities too
1798 upgrade_main_savepoint(true, $version, false);
1800 // Continue with the installation
1801 log_update_descriptions('moodle');
1802 external_update_descriptions('moodle');
1803 \core\task\manager
::reset_scheduled_tasks_for_component('moodle');
1804 \core_analytics\manager
::update_default_models_for_component('moodle');
1805 message_update_providers('moodle');
1806 \core\message\inbound\manager
::update_handlers_for_component('moodle');
1807 core_tag_area
::reset_definitions_for_component('moodle');
1809 // Write default settings unconditionally
1810 admin_apply_default_settings(NULL, true);
1812 print_upgrade_part_end(null, true, $verbose);
1814 // Purge all caches. They're disabled but this ensures that we don't have any persistent data just in case something
1815 // during installation didn't use APIs.
1816 cache_helper
::purge_all();
1817 } catch (exception
$ex) {
1818 upgrade_handle_exception($ex);
1819 } catch (Throwable
$ex) {
1820 // Engine errors in PHP7 throw exceptions of type Throwable (this "catch" will be ignored in PHP5).
1821 upgrade_handle_exception($ex);
1826 * Upgrade moodle core
1827 * @param float $version target version
1828 * @param bool $verbose
1829 * @return void, may throw exception
1831 function upgrade_core($version, $verbose) {
1832 global $CFG, $SITE, $DB, $COURSE;
1834 raise_memory_limit(MEMORY_EXTRA
);
1836 require_once($CFG->libdir
.'/db/upgrade.php'); // Defines upgrades
1839 // Reset caches before any output.
1840 cache_helper
::purge_all(true);
1843 // Upgrade current language pack if we can
1844 upgrade_language_pack();
1846 print_upgrade_part_start('moodle', false, $verbose);
1848 // Pre-upgrade scripts for local hack workarounds.
1849 $preupgradefile = "$CFG->dirroot/local/preupgrade.php";
1850 if (file_exists($preupgradefile)) {
1851 core_php_time_limit
::raise();
1852 require($preupgradefile);
1853 // Reset upgrade timeout to default.
1854 upgrade_set_timeout();
1857 $result = xmldb_main_upgrade($CFG->version
);
1858 if ($version > $CFG->version
) {
1859 // store version if not already there
1860 upgrade_main_savepoint($result, $version, false);
1863 // In case structure of 'course' table has been changed and we forgot to update $SITE, re-read it from db.
1864 $SITE = $DB->get_record('course', array('id' => $SITE->id
));
1865 $COURSE = clone($SITE);
1867 // perform all other component upgrade routines
1868 update_capabilities('moodle');
1869 log_update_descriptions('moodle');
1870 external_update_descriptions('moodle');
1871 \core\task\manager
::reset_scheduled_tasks_for_component('moodle');
1872 \core_analytics\manager
::update_default_models_for_component('moodle');
1873 message_update_providers('moodle');
1874 \core\message\inbound\manager
::update_handlers_for_component('moodle');
1875 core_tag_area
::reset_definitions_for_component('moodle');
1876 // Update core definitions.
1877 cache_helper
::update_definitions(true);
1879 // Purge caches again, just to be sure we arn't holding onto old stuff now.
1880 cache_helper
::purge_all(true);
1883 // Clean up contexts - more and more stuff depends on existence of paths and contexts
1884 context_helper
::cleanup_instances();
1885 context_helper
::create_instances(null, false);
1886 context_helper
::build_all_paths(false);
1887 $syscontext = context_system
::instance();
1888 $syscontext->mark_dirty();
1890 print_upgrade_part_end('moodle', false, $verbose);
1891 } catch (Exception
$ex) {
1892 upgrade_handle_exception($ex);
1893 } catch (Throwable
$ex) {
1894 // Engine errors in PHP7 throw exceptions of type Throwable (this "catch" will be ignored in PHP5).
1895 upgrade_handle_exception($ex);
1900 * Upgrade/install other parts of moodle
1901 * @param bool $verbose
1902 * @return void, may throw exception
1904 function upgrade_noncore($verbose) {
1907 raise_memory_limit(MEMORY_EXTRA
);
1909 // upgrade all plugins types
1911 // Reset caches before any output.
1912 cache_helper
::purge_all(true);
1915 $plugintypes = core_component
::get_plugin_types();
1916 foreach ($plugintypes as $type=>$location) {
1917 upgrade_plugins($type, 'print_upgrade_part_start', 'print_upgrade_part_end', $verbose);
1919 // Upgrade services.
1920 // This function gives plugins and subsystems a chance to add functions to existing built-in services.
1921 external_update_services();
1923 // Update cache definitions. Involves scanning each plugin for any changes.
1924 cache_helper
::update_definitions();
1925 // Mark the site as upgraded.
1926 set_config('allversionshash', core_component
::get_all_versions_hash());
1928 // Purge caches again, just to be sure we arn't holding onto old stuff now.
1929 cache_helper
::purge_all(true);
1932 } catch (Exception
$ex) {
1933 upgrade_handle_exception($ex);
1934 } catch (Throwable
$ex) {
1935 // Engine errors in PHP7 throw exceptions of type Throwable (this "catch" will be ignored in PHP5).
1936 upgrade_handle_exception($ex);
1941 * Checks if the main tables have been installed yet or not.
1943 * Note: we can not use caches here because they might be stale,
1948 function core_tables_exist() {
1951 if (!$tables = $DB->get_tables(false) ) { // No tables yet at all.
1954 } else { // Check for missing main tables
1955 $mtables = array('config', 'course', 'groupings'); // some tables used in 1.9 and 2.0, preferable something from the start and end of install.xml
1956 foreach ($mtables as $mtable) {
1957 if (!in_array($mtable, $tables)) {
1966 * upgrades the mnet rpc definitions for the given component.
1967 * this method doesn't return status, an exception will be thrown in the case of an error
1969 * @param string $component the plugin to upgrade, eg auth_mnet
1971 function upgrade_plugin_mnet_functions($component) {
1974 list($type, $plugin) = core_component
::normalize_component($component);
1975 $path = core_component
::get_plugin_directory($type, $plugin);
1977 $publishes = array();
1978 $subscribes = array();
1979 if (file_exists($path . '/db/mnet.php')) {
1980 require_once($path . '/db/mnet.php'); // $publishes comes from this file
1982 if (empty($publishes)) {
1983 $publishes = array(); // still need this to be able to disable stuff later
1985 if (empty($subscribes)) {
1986 $subscribes = array(); // still need this to be able to disable stuff later
1989 static $servicecache = array();
1991 // rekey an array based on the rpc method for easy lookups later
1992 $publishmethodservices = array();
1993 $subscribemethodservices = array();
1994 foreach($publishes as $servicename => $service) {
1995 if (is_array($service['methods'])) {
1996 foreach($service['methods'] as $methodname) {
1997 $service['servicename'] = $servicename;
1998 $publishmethodservices[$methodname][] = $service;
2003 // Disable functions that don't exist (any more) in the source
2004 // Should these be deleted? What about their permissions records?
2005 foreach ($DB->get_records('mnet_rpc', array('pluginname'=>$plugin, 'plugintype'=>$type), 'functionname ASC ') as $rpc) {
2006 if (!array_key_exists($rpc->functionname
, $publishmethodservices) && $rpc->enabled
) {
2007 $DB->set_field('mnet_rpc', 'enabled', 0, array('id' => $rpc->id
));
2008 } else if (array_key_exists($rpc->functionname
, $publishmethodservices) && !$rpc->enabled
) {
2009 $DB->set_field('mnet_rpc', 'enabled', 1, array('id' => $rpc->id
));
2013 // reflect all the services we're publishing and save them
2014 static $cachedclasses = array(); // to store reflection information in
2015 foreach ($publishes as $service => $data) {
2016 $f = $data['filename'];
2017 $c = $data['classname'];
2018 foreach ($data['methods'] as $method) {
2019 $dataobject = new stdClass();
2020 $dataobject->plugintype
= $type;
2021 $dataobject->pluginname
= $plugin;
2022 $dataobject->enabled
= 1;
2023 $dataobject->classname
= $c;
2024 $dataobject->filename
= $f;
2026 if (is_string($method)) {
2027 $dataobject->functionname
= $method;
2029 } else if (is_array($method)) { // wants to override file or class
2030 $dataobject->functionname
= $method['method'];
2031 $dataobject->classname
= $method['classname'];
2032 $dataobject->filename
= $method['filename'];
2034 $dataobject->xmlrpcpath
= $type.'/'.$plugin.'/'.$dataobject->filename
.'/'.$method;
2035 $dataobject->static = false;
2037 require_once($path . '/' . $dataobject->filename
);
2038 $functionreflect = null; // slightly different ways to get this depending on whether it's a class method or a function
2039 if (!empty($dataobject->classname
)) {
2040 if (!class_exists($dataobject->classname
)) {
2041 throw new moodle_exception('installnosuchmethod', 'mnet', '', (object)array('method' => $dataobject->functionname
, 'class' => $dataobject->classname
));
2043 $key = $dataobject->filename
. '|' . $dataobject->classname
;
2044 if (!array_key_exists($key, $cachedclasses)) { // look to see if we've already got a reflection object
2046 $cachedclasses[$key] = new ReflectionClass($dataobject->classname
);
2047 } catch (ReflectionException
$e) { // catch these and rethrow them to something more helpful
2048 throw new moodle_exception('installreflectionclasserror', 'mnet', '', (object)array('method' => $dataobject->functionname
, 'class' => $dataobject->classname
, 'error' => $e->getMessage()));
2051 $r =& $cachedclasses[$key];
2052 if (!$r->hasMethod($dataobject->functionname
)) {
2053 throw new moodle_exception('installnosuchmethod', 'mnet', '', (object)array('method' => $dataobject->functionname
, 'class' => $dataobject->classname
));
2055 $functionreflect = $r->getMethod($dataobject->functionname
);
2056 $dataobject->static = (int)$functionreflect->isStatic();
2058 if (!function_exists($dataobject->functionname
)) {
2059 throw new moodle_exception('installnosuchfunction', 'mnet', '', (object)array('method' => $dataobject->functionname
, 'file' => $dataobject->filename
));
2062 $functionreflect = new ReflectionFunction($dataobject->functionname
);
2063 } catch (ReflectionException
$e) { // catch these and rethrow them to something more helpful
2064 throw new moodle_exception('installreflectionfunctionerror', 'mnet', '', (object)array('method' => $dataobject->functionname
, '' => $dataobject->filename
, 'error' => $e->getMessage()));
2067 $dataobject->profile
= serialize(admin_mnet_method_profile($functionreflect));
2068 $dataobject->help
= admin_mnet_method_get_help($functionreflect);
2070 if ($record_exists = $DB->get_record('mnet_rpc', array('xmlrpcpath'=>$dataobject->xmlrpcpath
))) {
2071 $dataobject->id
= $record_exists->id
;
2072 $dataobject->enabled
= $record_exists->enabled
;
2073 $DB->update_record('mnet_rpc', $dataobject);
2075 $dataobject->id
= $DB->insert_record('mnet_rpc', $dataobject, true);
2078 // TODO this API versioning must be reworked, here the recently processed method
2079 // sets the service API which may not be correct
2080 foreach ($publishmethodservices[$dataobject->functionname
] as $service) {
2081 if ($serviceobj = $DB->get_record('mnet_service', array('name'=>$service['servicename']))) {
2082 $serviceobj->apiversion
= $service['apiversion'];
2083 $DB->update_record('mnet_service', $serviceobj);
2085 $serviceobj = new stdClass();
2086 $serviceobj->name
= $service['servicename'];
2087 $serviceobj->description
= empty($service['description']) ?
'' : $service['description'];
2088 $serviceobj->apiversion
= $service['apiversion'];
2089 $serviceobj->offer
= 1;
2090 $serviceobj->id
= $DB->insert_record('mnet_service', $serviceobj);
2092 $servicecache[$service['servicename']] = $serviceobj;
2093 if (!$DB->record_exists('mnet_service2rpc', array('rpcid'=>$dataobject->id
, 'serviceid'=>$serviceobj->id
))) {
2094 $obj = new stdClass();
2095 $obj->rpcid
= $dataobject->id
;
2096 $obj->serviceid
= $serviceobj->id
;
2097 $DB->insert_record('mnet_service2rpc', $obj, true);
2102 // finished with methods we publish, now do subscribable methods
2103 foreach($subscribes as $service => $methods) {
2104 if (!array_key_exists($service, $servicecache)) {
2105 if (!$serviceobj = $DB->get_record('mnet_service', array('name' => $service))) {
2106 debugging("TODO: skipping unknown service $service - somebody needs to fix MDL-21993");
2109 $servicecache[$service] = $serviceobj;
2111 $serviceobj = $servicecache[$service];
2113 foreach ($methods as $method => $xmlrpcpath) {
2114 if (!$rpcid = $DB->get_field('mnet_remote_rpc', 'id', array('xmlrpcpath'=>$xmlrpcpath))) {
2115 $remoterpc = (object)array(
2116 'functionname' => $method,
2117 'xmlrpcpath' => $xmlrpcpath,
2118 'plugintype' => $type,
2119 'pluginname' => $plugin,
2122 $rpcid = $remoterpc->id
= $DB->insert_record('mnet_remote_rpc', $remoterpc, true);
2124 if (!$DB->record_exists('mnet_remote_service2rpc', array('rpcid'=>$rpcid, 'serviceid'=>$serviceobj->id
))) {
2125 $obj = new stdClass();
2126 $obj->rpcid
= $rpcid;
2127 $obj->serviceid
= $serviceobj->id
;
2128 $DB->insert_record('mnet_remote_service2rpc', $obj, true);
2130 $subscribemethodservices[$method][] = $service;
2134 foreach ($DB->get_records('mnet_remote_rpc', array('pluginname'=>$plugin, 'plugintype'=>$type), 'functionname ASC ') as $rpc) {
2135 if (!array_key_exists($rpc->functionname
, $subscribemethodservices) && $rpc->enabled
) {
2136 $DB->set_field('mnet_remote_rpc', 'enabled', 0, array('id' => $rpc->id
));
2137 } else if (array_key_exists($rpc->functionname
, $subscribemethodservices) && !$rpc->enabled
) {
2138 $DB->set_field('mnet_remote_rpc', 'enabled', 1, array('id' => $rpc->id
));
2146 * Given some sort of reflection function/method object, return a profile array, ready to be serialized and stored
2148 * @param ReflectionFunctionAbstract $function reflection function/method object from which to extract information
2150 * @return array associative array with function/method information
2152 function admin_mnet_method_profile(ReflectionFunctionAbstract
$function) {
2153 $commentlines = admin_mnet_method_get_docblock($function);
2154 $getkey = function($key) use ($commentlines) {
2155 return array_values(array_filter($commentlines, function($line) use ($key) {
2156 return $line[0] == $key;
2159 $returnline = $getkey('@return');
2161 'parameters' => array_map(function($line) {
2163 'name' => trim($line[2], " \t\n\r\0\x0B$"),
2165 'description' => $line[3]
2167 }, $getkey('@param')),
2170 'type' => !empty($returnline[0][1]) ?
$returnline[0][1] : 'void',
2171 'description' => !empty($returnline[0][2]) ?
$returnline[0][2] : ''
2177 * Given some sort of reflection function/method object, return an array of docblock lines, where each line is an array of
2178 * keywords/descriptions
2180 * @param ReflectionFunctionAbstract $function reflection function/method object from which to extract information
2182 * @return array docblock converted in to an array
2184 function admin_mnet_method_get_docblock(ReflectionFunctionAbstract
$function) {
2185 return array_map(function($line) {
2186 $text = trim($line, " \t\n\r\0\x0B*/");
2187 if (strpos($text, '@param') === 0) {
2188 return preg_split('/\s+/', $text, 4);
2191 if (strpos($text, '@return') === 0) {
2192 return preg_split('/\s+/', $text, 3);
2195 return array($text);
2196 }, explode("\n", $function->getDocComment()));
2200 * Given some sort of reflection function/method object, return just the help text
2202 * @param ReflectionFunctionAbstract $function reflection function/method object from which to extract information
2204 * @return string docblock help text
2206 function admin_mnet_method_get_help(ReflectionFunctionAbstract
$function) {
2207 $helplines = array_map(function($line) {
2208 return implode(' ', $line);
2209 }, array_values(array_filter(admin_mnet_method_get_docblock($function), function($line) {
2210 return strpos($line[0], '@') !== 0 && !empty($line[0]);
2213 return implode("\n", $helplines);
2217 * This function verifies that the database is not using an unsupported storage engine.
2219 * @param environment_results $result object to update, if relevant
2220 * @return environment_results|null updated results object, or null if the storage engine is supported
2222 function check_database_storage_engine(environment_results
$result) {
2225 // Check if MySQL is the DB family (this will also be the same for MariaDB).
2226 if ($DB->get_dbfamily() == 'mysql') {
2227 // Get the database engine we will either be using to install the tables, or what we are currently using.
2228 $engine = $DB->get_dbengine();
2229 // Check if MyISAM is the storage engine that will be used, if so, do not proceed and display an error.
2230 if ($engine == 'MyISAM') {
2231 $result->setInfo('unsupported_db_storage_engine');
2232 $result->setStatus(false);
2241 * Method used to check the usage of slasharguments config and display a warning message.
2243 * @param environment_results $result object to update, if relevant.
2244 * @return environment_results|null updated results or null if slasharguments is disabled.
2246 function check_slasharguments(environment_results
$result){
2249 if (!during_initial_install() && empty($CFG->slasharguments
)) {
2250 $result->setInfo('slasharguments');
2251 $result->setStatus(false);
2259 * This function verifies if the database has tables using innoDB Antelope row format.
2261 * @param environment_results $result
2262 * @return environment_results|null updated results object, or null if no Antelope table has been found.
2264 function check_database_tables_row_format(environment_results
$result) {
2267 if ($DB->get_dbfamily() == 'mysql') {
2268 $generator = $DB->get_manager()->generator
;
2270 foreach ($DB->get_tables(false) as $table) {
2271 $columns = $DB->get_columns($table, false);
2272 $size = $generator->guess_antelope_row_size($columns);
2273 $format = $DB->get_row_format($table);
2275 if ($size <= $generator::ANTELOPE_MAX_ROW_SIZE
) {
2279 if ($format === 'Compact' or $format === 'Redundant') {
2280 $result->setInfo('unsupported_db_table_row_format');
2281 $result->setStatus(false);
2291 * This function verfies that the database has tables using InnoDB Antelope row format.
2293 * @param environment_results $result
2294 * @return environment_results|null updated results object, or null if no Antelope table has been found.
2296 function check_mysql_file_format(environment_results
$result) {
2299 if ($DB->get_dbfamily() == 'mysql') {
2300 $collation = $DB->get_dbcollation();
2301 $collationinfo = explode('_', $collation);
2302 $charset = reset($collationinfo);
2304 if ($charset == 'utf8mb4') {
2305 if ($DB->get_row_format() !== "Barracuda") {
2306 $result->setInfo('mysql_full_unicode_support#File_format');
2307 $result->setStatus(false);
2316 * This function verfies that the database has a setting of one file per table. This is required for 'utf8mb4'.
2318 * @param environment_results $result
2319 * @return environment_results|null updated results object, or null if innodb_file_per_table = 1.
2321 function check_mysql_file_per_table(environment_results
$result) {
2324 if ($DB->get_dbfamily() == 'mysql') {
2325 $collation = $DB->get_dbcollation();
2326 $collationinfo = explode('_', $collation);
2327 $charset = reset($collationinfo);
2329 if ($charset == 'utf8mb4') {
2330 if (!$DB->is_file_per_table_enabled()) {
2331 $result->setInfo('mysql_full_unicode_support#File_per_table');
2332 $result->setStatus(false);
2341 * This function verfies that the database has the setting of large prefix enabled. This is required for 'utf8mb4'.
2343 * @param environment_results $result
2344 * @return environment_results|null updated results object, or null if innodb_large_prefix = 1.
2346 function check_mysql_large_prefix(environment_results
$result) {
2349 if ($DB->get_dbfamily() == 'mysql') {
2350 $collation = $DB->get_dbcollation();
2351 $collationinfo = explode('_', $collation);
2352 $charset = reset($collationinfo);
2354 if ($charset == 'utf8mb4') {
2355 if (!$DB->is_large_prefix_enabled()) {
2356 $result->setInfo('mysql_full_unicode_support#Large_prefix');
2357 $result->setStatus(false);
2366 * This function checks the database to see if it is using incomplete unicode support.
2368 * @param environment_results $result $result
2369 * @return environment_results|null updated results object, or null if unicode is fully supported.
2371 function check_mysql_incomplete_unicode_support(environment_results
$result) {
2374 if ($DB->get_dbfamily() == 'mysql') {
2375 $collation = $DB->get_dbcollation();
2376 $collationinfo = explode('_', $collation);
2377 $charset = reset($collationinfo);
2379 if ($charset == 'utf8') {
2380 $result->setInfo('mysql_full_unicode_support');
2381 $result->setStatus(false);
2389 * Check if the site is being served using an ssl url.
2391 * Note this does not really perform any request neither looks for proxies or
2392 * other situations. Just looks to wwwroot and warn if it's not using https.
2394 * @param environment_results $result $result
2395 * @return environment_results|null updated results object, or null if the site is https.
2397 function check_is_https(environment_results
$result) {
2400 // Only if is defined, non-empty and whatever core tell us.
2401 if (!empty($CFG->wwwroot
) && !is_https()) {
2402 $result->setInfo('site not https');
2403 $result->setStatus(false);
2410 * Check if the site is using 64 bits PHP.
2412 * @param environment_results $result
2413 * @return environment_results|null updated results object, or null if the site is using 64 bits PHP.
2415 function check_sixtyfour_bits(environment_results
$result) {
2417 if (PHP_INT_SIZE
=== 4) {
2418 $result->setInfo('php not 64 bits');
2419 $result->setStatus(false);
2426 * Assert the upgrade key is provided, if it is defined.
2428 * The upgrade key can be defined in the main config.php as $CFG->upgradekey. If
2429 * it is defined there, then its value must be provided every time the site is
2430 * being upgraded, regardless the administrator is logged in or not.
2432 * This is supposed to be used at certain places in /admin/index.php only.
2434 * @param string|null $upgradekeyhash the SHA-1 of the value provided by the user
2436 function check_upgrade_key($upgradekeyhash) {
2439 if (isset($CFG->config_php_settings
['upgradekey'])) {
2440 if ($upgradekeyhash === null or $upgradekeyhash !== sha1($CFG->config_php_settings
['upgradekey'])) {
2441 if (!$PAGE->headerprinted
) {
2442 $output = $PAGE->get_renderer('core', 'admin');
2443 echo $output->upgradekey_form_page(new moodle_url('/admin/index.php', array('cache' => 0)));
2446 // This should not happen.
2447 die('Upgrade locked');
2454 * Helper procedure/macro for installing remote plugins at admin/index.php
2456 * Does not return, always redirects or exits.
2458 * @param array $installable list of \core\update\remote_info
2459 * @param bool $confirmed false: display the validation screen, true: proceed installation
2460 * @param string $heading validation screen heading
2461 * @param moodle_url|string|null $continue URL to proceed with installation at the validation screen
2462 * @param moodle_url|string|null $return URL to go back on cancelling at the validation screen
2464 function upgrade_install_plugins(array $installable, $confirmed, $heading='', $continue=null, $return=null) {
2467 if (empty($return)) {
2468 $return = $PAGE->url
;
2471 if (!empty($CFG->disableupdateautodeploy
)) {
2475 if (empty($installable)) {
2479 $pluginman = core_plugin_manager
::instance();
2482 // Installation confirmed at the validation results page.
2483 if (!$pluginman->install_plugins($installable, true, true)) {
2484 throw new moodle_exception('install_plugins_failed', 'core_plugin', $return);
2487 // Always redirect to admin/index.php to perform the database upgrade.
2488 // Do not throw away the existing $PAGE->url parameters such as
2489 // confirmupgrade or confirmrelease if $PAGE->url is a superset of the
2490 // URL we must go to.
2491 $mustgoto = new moodle_url('/admin/index.php', array('cache' => 0, 'confirmplugincheck' => 0));
2492 if ($mustgoto->compare($PAGE->url
, URL_MATCH_PARAMS
)) {
2493 redirect($PAGE->url
);
2495 redirect($mustgoto);
2499 $output = $PAGE->get_renderer('core', 'admin');
2500 echo $output->header();
2502 echo $output->heading($heading, 3);
2504 echo html_writer
::start_tag('pre', array('class' => 'plugin-install-console'));
2505 $validated = $pluginman->install_plugins($installable, false, false);
2506 echo html_writer
::end_tag('pre');
2508 echo $output->plugins_management_confirm_buttons($continue, $return);
2510 echo $output->plugins_management_confirm_buttons(null, $return);
2512 echo $output->footer();
2517 * Method used to check the installed unoconv version.
2519 * @param environment_results $result object to update, if relevant.
2520 * @return environment_results|null updated results or null if unoconv path is not executable.
2522 function check_unoconv_version(environment_results
$result) {
2525 if (!during_initial_install() && !empty($CFG->pathtounoconv
) && file_is_executable(trim($CFG->pathtounoconv
))) {
2526 $currentversion = 0;
2527 $supportedversion = 0.7;
2528 $unoconvbin = \
escapeshellarg($CFG->pathtounoconv
);
2529 $command = "$unoconvbin --version";
2530 exec($command, $output);
2532 // If the command execution returned some output, then get the unoconv version.
2534 foreach ($output as $response) {
2535 if (preg_match('/unoconv (\\d+\\.\\d+)/', $response, $matches)) {
2536 $currentversion = (float)$matches[1];
2541 if ($currentversion < $supportedversion) {
2542 $result->setInfo('unoconv version not supported');
2543 $result->setStatus(false);
2551 * Checks for up-to-date TLS libraries. NOTE: this is not currently used, see MDL-57262.
2553 * @param environment_results $result object to update, if relevant.
2554 * @return environment_results|null updated results or null if unoconv path is not executable.
2556 function check_tls_libraries(environment_results
$result) {
2559 if (!function_exists('curl_version')) {
2560 $result->setInfo('cURL PHP extension is not installed');
2561 $result->setStatus(false);
2565 if (!\core\upgrade\util
::validate_php_curl_tls(curl_version(), PHP_ZTS
)) {
2566 $result->setInfo('invalid ssl/tls configuration');
2567 $result->setStatus(false);
2571 if (!\core\upgrade\util
::can_use_tls12(curl_version(), php_uname('r'))) {
2572 $result->setInfo('ssl/tls configuration not supported');
2573 $result->setStatus(false);
2581 * Check if recommended version of libcurl is installed or not.
2583 * @param environment_results $result object to update, if relevant.
2584 * @return environment_results|null updated results or null.
2586 function check_libcurl_version(environment_results
$result) {
2588 if (!function_exists('curl_version')) {
2589 $result->setInfo('cURL PHP extension is not installed');
2590 $result->setStatus(false);
2594 // Supported version and version number.
2595 $supportedversion = 0x071304;
2596 $supportedversionstring = "7.19.4";
2598 // Installed version.
2599 $curlinfo = curl_version();
2600 $currentversion = $curlinfo['version_number'];
2602 if ($currentversion < $supportedversion) {
2604 // Set info, we want to let user know how to resolve the problem.
2605 $result->setInfo('Libcurl version check');
2606 $result->setNeededVersion($supportedversionstring);
2607 $result->setCurrentVersion($curlinfo['version']);
2608 $result->setStatus(false);