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);
90 * @copyright 2009 Petr Skoda {@link http://skodak.org}
91 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
93 class plugin_defective_exception
extends moodle_exception
{
94 function __construct($plugin, $details) {
96 parent
::__construct('detectedbrokenplugin', 'error', "$CFG->wwwroot/$CFG->admin/index.php", $plugin, $details);
101 * Misplaced plugin exception.
103 * Note: this should be used only from the upgrade/admin code.
106 * @subpackage upgrade
107 * @copyright 2009 Petr Skoda {@link http://skodak.org}
108 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
110 class plugin_misplaced_exception
extends moodle_exception
{
113 * @param string $component the component from version.php
114 * @param string $expected expected directory, null means calculate
115 * @param string $current plugin directory path
117 public function __construct($component, $expected, $current) {
119 if (empty($expected)) {
120 list($type, $plugin) = core_component
::normalize_component($component);
121 $plugintypes = core_component
::get_plugin_types();
122 if (isset($plugintypes[$type])) {
123 $expected = $plugintypes[$type] . '/' . $plugin;
126 if (strpos($expected, '$CFG->dirroot') !== 0) {
127 $expected = str_replace($CFG->dirroot
, '$CFG->dirroot', $expected);
129 if (strpos($current, '$CFG->dirroot') !== 0) {
130 $current = str_replace($CFG->dirroot
, '$CFG->dirroot', $current);
133 $a->component
= $component;
134 $a->expected
= $expected;
135 $a->current
= $current;
136 parent
::__construct('detectedmisplacedplugin', 'core_plugin', "$CFG->wwwroot/$CFG->admin/index.php", $a);
141 * Sets maximum expected time needed for upgrade task.
142 * Please always make sure that upgrade will not run longer!
144 * The script may be automatically aborted if upgrade times out.
147 * @param int $max_execution_time in seconds (can not be less than 60 s)
149 function upgrade_set_timeout($max_execution_time=300) {
152 if (!isset($CFG->upgraderunning
) or $CFG->upgraderunning
< time()) {
153 $upgraderunning = get_config(null, 'upgraderunning');
155 $upgraderunning = $CFG->upgraderunning
;
158 if (!$upgraderunning) {
160 // never stop CLI upgrades
163 // web upgrade not running or aborted
164 print_error('upgradetimedout', 'admin', "$CFG->wwwroot/$CFG->admin/");
168 if ($max_execution_time < 60) {
169 // protection against 0 here
170 $max_execution_time = 60;
173 $expected_end = time() +
$max_execution_time;
175 if ($expected_end < $upgraderunning +
10 and $expected_end > $upgraderunning - 10) {
176 // no need to store new end, it is nearly the same ;-)
181 // there is no point in timing out of CLI scripts, admins can stop them if necessary
182 core_php_time_limit
::raise();
184 core_php_time_limit
::raise($max_execution_time);
186 set_config('upgraderunning', $expected_end); // keep upgrade locked until this time
190 * Upgrade savepoint, marks end of each upgrade block.
191 * It stores new main version, resets upgrade timeout
192 * and abort upgrade if user cancels page loading.
194 * Please do not make large upgrade blocks with lots of operations,
195 * for example when adding tables keep only one table operation per block.
198 * @param bool $result false if upgrade step failed, true if completed
199 * @param string or float $version main version
200 * @param bool $allowabort allow user to abort script execution here
203 function upgrade_main_savepoint($result, $version, $allowabort=true) {
206 //sanity check to avoid confusion with upgrade_mod_savepoint usage.
207 if (!is_bool($allowabort)) {
208 $errormessage = 'Parameter type mismatch. Are you mixing up upgrade_main_savepoint() and upgrade_mod_savepoint()?';
209 throw new coding_exception($errormessage);
213 throw new upgrade_exception(null, $version);
216 if ($CFG->version
>= $version) {
217 // something really wrong is going on in main upgrade script
218 throw new downgrade_exception(null, $CFG->version
, $version);
221 set_config('version', $version);
222 upgrade_log(UPGRADE_LOG_NORMAL
, null, 'Upgrade savepoint reached');
224 // reset upgrade timeout to default
225 upgrade_set_timeout();
227 // this is a safe place to stop upgrades if user aborts page loading
228 if ($allowabort and connection_aborted()) {
234 * Module upgrade savepoint, marks end of module upgrade blocks
235 * It stores module version, resets upgrade timeout
236 * and abort upgrade if user cancels page loading.
239 * @param bool $result false if upgrade step failed, true if completed
240 * @param string or float $version main version
241 * @param string $modname name of module
242 * @param bool $allowabort allow user to abort script execution here
245 function upgrade_mod_savepoint($result, $version, $modname, $allowabort=true) {
248 $component = 'mod_'.$modname;
251 throw new upgrade_exception($component, $version);
254 $dbversion = $DB->get_field('config_plugins', 'value', array('plugin'=>$component, 'name'=>'version'));
256 if (!$module = $DB->get_record('modules', array('name'=>$modname))) {
257 print_error('modulenotexist', 'debug', '', $modname);
260 if ($dbversion >= $version) {
261 // something really wrong is going on in upgrade script
262 throw new downgrade_exception($component, $dbversion, $version);
264 set_config('version', $version, $component);
266 upgrade_log(UPGRADE_LOG_NORMAL
, $component, 'Upgrade savepoint reached');
268 // reset upgrade timeout to default
269 upgrade_set_timeout();
271 // this is a safe place to stop upgrades if user aborts page loading
272 if ($allowabort and connection_aborted()) {
278 * Blocks upgrade savepoint, marks end of blocks upgrade blocks
279 * It stores block version, resets upgrade timeout
280 * and abort upgrade if user cancels page loading.
283 * @param bool $result false if upgrade step failed, true if completed
284 * @param string or float $version main version
285 * @param string $blockname name of block
286 * @param bool $allowabort allow user to abort script execution here
289 function upgrade_block_savepoint($result, $version, $blockname, $allowabort=true) {
292 $component = 'block_'.$blockname;
295 throw new upgrade_exception($component, $version);
298 $dbversion = $DB->get_field('config_plugins', 'value', array('plugin'=>$component, 'name'=>'version'));
300 if (!$block = $DB->get_record('block', array('name'=>$blockname))) {
301 print_error('blocknotexist', 'debug', '', $blockname);
304 if ($dbversion >= $version) {
305 // something really wrong is going on in upgrade script
306 throw new downgrade_exception($component, $dbversion, $version);
308 set_config('version', $version, $component);
310 upgrade_log(UPGRADE_LOG_NORMAL
, $component, 'Upgrade savepoint reached');
312 // reset upgrade timeout to default
313 upgrade_set_timeout();
315 // this is a safe place to stop upgrades if user aborts page loading
316 if ($allowabort and connection_aborted()) {
322 * Plugins upgrade savepoint, marks end of blocks upgrade blocks
323 * It stores plugin version, resets upgrade timeout
324 * and abort upgrade if user cancels page loading.
327 * @param bool $result false if upgrade step failed, true if completed
328 * @param string or float $version main version
329 * @param string $type name of plugin
330 * @param string $dir location of plugin
331 * @param bool $allowabort allow user to abort script execution here
334 function upgrade_plugin_savepoint($result, $version, $type, $plugin, $allowabort=true) {
337 $component = $type.'_'.$plugin;
340 throw new upgrade_exception($component, $version);
343 $dbversion = $DB->get_field('config_plugins', 'value', array('plugin'=>$component, 'name'=>'version'));
345 if ($dbversion >= $version) {
346 // Something really wrong is going on in the upgrade script
347 throw new downgrade_exception($component, $dbversion, $version);
349 set_config('version', $version, $component);
350 upgrade_log(UPGRADE_LOG_NORMAL
, $component, 'Upgrade savepoint reached');
352 // Reset upgrade timeout to default
353 upgrade_set_timeout();
355 // This is a safe place to stop upgrades if user aborts page loading
356 if ($allowabort and connection_aborted()) {
362 * Detect if there are leftovers in PHP source files.
364 * During main version upgrades administrators MUST move away
365 * old PHP source files and start from scratch (or better
368 * @return bool true means borked upgrade, false means previous PHP files were properly removed
370 function upgrade_stale_php_files_present() {
373 $someexamplesofremovedfiles = array(
375 '/course/delete_category_form.php',
377 '/admin/tool/qeupgradehelper/version.php',
380 '/admin/oacleanup.php',
383 '/backup/bb/README.txt',
384 '/lib/excel/test.php',
386 '/admin/tool/unittest/simpletestlib.php',
388 '/lib/minify/builder/',
390 '/lib/yui/3.4.1pr1/',
392 '/search/cron_php5.php',
393 '/course/report/log/indexlive.php',
394 '/admin/report/backups/index.php',
395 '/admin/generator.php',
399 '/blocks/admin/block_admin.php',
400 '/blocks/admin_tree/block_admin_tree.php',
403 foreach ($someexamplesofremovedfiles as $file) {
404 if (file_exists($CFG->dirroot
.$file)) {
414 * @param string $type The type of plugins that should be updated (e.g. 'enrol', 'qtype')
417 function upgrade_plugins($type, $startcallback, $endcallback, $verbose) {
421 if ($type === 'mod') {
422 return upgrade_plugins_modules($startcallback, $endcallback, $verbose);
423 } else if ($type === 'block') {
424 return upgrade_plugins_blocks($startcallback, $endcallback, $verbose);
427 $plugs = core_component
::get_plugin_list($type);
429 foreach ($plugs as $plug=>$fullplug) {
430 // Reset time so that it works when installing a large number of plugins
431 core_php_time_limit
::raise(600);
432 $component = clean_param($type.'_'.$plug, PARAM_COMPONENT
); // standardised plugin name
434 // check plugin dir is valid name
435 if (empty($component)) {
436 throw new plugin_defective_exception($type.'_'.$plug, 'Invalid plugin directory name.');
439 if (!is_readable($fullplug.'/version.php')) {
443 $plugin = new stdClass();
444 $plugin->version
= null;
445 $module = $plugin; // Prevent some notices when plugin placed in wrong directory.
446 require($fullplug.'/version.php'); // defines $plugin with version etc
449 // if plugin tells us it's full name we may check the location
450 if (isset($plugin->component
)) {
451 if ($plugin->component
!== $component) {
452 throw new plugin_misplaced_exception($plugin->component
, null, $fullplug);
456 if (empty($plugin->version
)) {
457 throw new plugin_defective_exception($component, 'Missing version value in version.php');
460 $plugin->name
= $plug;
461 $plugin->fullname
= $component;
463 if (!empty($plugin->requires
)) {
464 if ($plugin->requires
> $CFG->version
) {
465 throw new upgrade_requires_exception($component, $plugin->version
, $CFG->version
, $plugin->requires
);
466 } else if ($plugin->requires
< 2010000000) {
467 throw new plugin_defective_exception($component, 'Plugin is not compatible with Moodle 2.x or later.');
471 // try to recover from interrupted install.php if needed
472 if (file_exists($fullplug.'/db/install.php')) {
473 if (get_config($plugin->fullname
, 'installrunning')) {
474 require_once($fullplug.'/db/install.php');
475 $recover_install_function = 'xmldb_'.$plugin->fullname
.'_install_recovery';
476 if (function_exists($recover_install_function)) {
477 $startcallback($component, true, $verbose);
478 $recover_install_function();
479 unset_config('installrunning', $plugin->fullname
);
480 update_capabilities($component);
481 log_update_descriptions($component);
482 external_update_descriptions($component);
483 events_update_definition($component);
484 \core\task\manager
::reset_scheduled_tasks_for_component($component);
485 message_update_providers($component);
486 \core\message\inbound\manager
::update_handlers_for_component($component);
487 if ($type === 'message') {
488 message_update_processors($plug);
490 upgrade_plugin_mnet_functions($component);
491 $endcallback($component, true, $verbose);
496 $installedversion = $DB->get_field('config_plugins', 'value', array('name'=>'version', 'plugin'=>$component)); // No caching!
497 if (empty($installedversion)) { // new installation
498 $startcallback($component, true, $verbose);
500 /// Install tables if defined
501 if (file_exists($fullplug.'/db/install.xml')) {
502 $DB->get_manager()->install_from_xmldb_file($fullplug.'/db/install.xml');
506 upgrade_plugin_savepoint(true, $plugin->version
, $type, $plug, false);
508 /// execute post install file
509 if (file_exists($fullplug.'/db/install.php')) {
510 require_once($fullplug.'/db/install.php');
511 set_config('installrunning', 1, $plugin->fullname
);
512 $post_install_function = 'xmldb_'.$plugin->fullname
.'_install';
513 $post_install_function();
514 unset_config('installrunning', $plugin->fullname
);
517 /// Install various components
518 update_capabilities($component);
519 log_update_descriptions($component);
520 external_update_descriptions($component);
521 events_update_definition($component);
522 \core\task\manager
::reset_scheduled_tasks_for_component($component);
523 message_update_providers($component);
524 \core\message\inbound\manager
::update_handlers_for_component($component);
525 if ($type === 'message') {
526 message_update_processors($plug);
528 upgrade_plugin_mnet_functions($component);
529 $endcallback($component, true, $verbose);
531 } else if ($installedversion < $plugin->version
) { // upgrade
532 /// Run the upgrade function for the plugin.
533 $startcallback($component, false, $verbose);
535 if (is_readable($fullplug.'/db/upgrade.php')) {
536 require_once($fullplug.'/db/upgrade.php'); // defines upgrading function
538 $newupgrade_function = 'xmldb_'.$plugin->fullname
.'_upgrade';
539 $result = $newupgrade_function($installedversion);
544 $installedversion = $DB->get_field('config_plugins', 'value', array('name'=>'version', 'plugin'=>$component)); // No caching!
545 if ($installedversion < $plugin->version
) {
546 // store version if not already there
547 upgrade_plugin_savepoint($result, $plugin->version
, $type, $plug, false);
550 /// Upgrade various components
551 update_capabilities($component);
552 log_update_descriptions($component);
553 external_update_descriptions($component);
554 events_update_definition($component);
555 \core\task\manager
::reset_scheduled_tasks_for_component($component);
556 message_update_providers($component);
557 \core\message\inbound\manager
::update_handlers_for_component($component);
558 if ($type === 'message') {
560 message_update_processors($plug);
562 upgrade_plugin_mnet_functions($component);
563 $endcallback($component, false, $verbose);
565 } else if ($installedversion > $plugin->version
) {
566 throw new downgrade_exception($component, $installedversion, $plugin->version
);
572 * Find and check all modules and load them up or upgrade them if necessary
577 function upgrade_plugins_modules($startcallback, $endcallback, $verbose) {
580 $mods = core_component
::get_plugin_list('mod');
582 foreach ($mods as $mod=>$fullmod) {
584 if ($mod === 'NEWMODULE') { // Someone has unzipped the template, ignore it
588 $component = clean_param('mod_'.$mod, PARAM_COMPONENT
);
590 // check module dir is valid name
591 if (empty($component)) {
592 throw new plugin_defective_exception('mod_'.$mod, 'Invalid plugin directory name.');
595 if (!is_readable($fullmod.'/version.php')) {
596 throw new plugin_defective_exception($component, 'Missing version.php');
599 // TODO: Support for $module will end with Moodle 2.10 by MDL-43896. Was deprecated for Moodle 2.7 by MDL-43040.
600 $plugin = new stdClass();
601 $plugin->version
= null;
603 require($fullmod .'/version.php'); // Defines $plugin with version etc.
604 $plugin = clone($module);
605 unset($module->version
);
606 unset($module->component
);
607 unset($module->dependencies
);
608 unset($module->release
);
610 // if plugin tells us it's full name we may check the location
611 if (isset($plugin->component
)) {
612 if ($plugin->component
!== $component) {
613 throw new plugin_misplaced_exception($plugin->component
, null, $fullmod);
617 if (empty($plugin->version
)) {
618 // Version must be always set now!
619 throw new plugin_defective_exception($component, 'Missing version value in version.php');
622 if (!empty($plugin->requires
)) {
623 if ($plugin->requires
> $CFG->version
) {
624 throw new upgrade_requires_exception($component, $plugin->version
, $CFG->version
, $plugin->requires
);
625 } else if ($plugin->requires
< 2010000000) {
626 throw new plugin_defective_exception($component, 'Plugin is not compatible with Moodle 2.x or later.');
630 if (empty($module->cron
)) {
634 // all modules must have en lang pack
635 if (!is_readable("$fullmod/lang/en/$mod.php")) {
636 throw new plugin_defective_exception($component, 'Missing mandatory en language pack.');
639 $module->name
= $mod; // The name MUST match the directory
641 $installedversion = $DB->get_field('config_plugins', 'value', array('name'=>'version', 'plugin'=>$component)); // No caching!
643 if (file_exists($fullmod.'/db/install.php')) {
644 if (get_config($module->name
, 'installrunning')) {
645 require_once($fullmod.'/db/install.php');
646 $recover_install_function = 'xmldb_'.$module->name
.'_install_recovery';
647 if (function_exists($recover_install_function)) {
648 $startcallback($component, true, $verbose);
649 $recover_install_function();
650 unset_config('installrunning', $module->name
);
651 // Install various components too
652 update_capabilities($component);
653 log_update_descriptions($component);
654 external_update_descriptions($component);
655 events_update_definition($component);
656 \core\task\manager
::reset_scheduled_tasks_for_component($component);
657 message_update_providers($component);
658 \core\message\inbound\manager
::update_handlers_for_component($component);
659 upgrade_plugin_mnet_functions($component);
660 $endcallback($component, true, $verbose);
665 if (empty($installedversion)) {
666 $startcallback($component, true, $verbose);
668 /// Execute install.xml (XMLDB) - must be present in all modules
669 $DB->get_manager()->install_from_xmldb_file($fullmod.'/db/install.xml');
671 /// Add record into modules table - may be needed in install.php already
672 $module->id
= $DB->insert_record('modules', $module);
673 upgrade_mod_savepoint(true, $plugin->version
, $module->name
, false);
675 /// Post installation hook - optional
676 if (file_exists("$fullmod/db/install.php")) {
677 require_once("$fullmod/db/install.php");
678 // Set installation running flag, we need to recover after exception or error
679 set_config('installrunning', 1, $module->name
);
680 $post_install_function = 'xmldb_'.$module->name
.'_install';
681 $post_install_function();
682 unset_config('installrunning', $module->name
);
685 /// Install various components
686 update_capabilities($component);
687 log_update_descriptions($component);
688 external_update_descriptions($component);
689 events_update_definition($component);
690 \core\task\manager
::reset_scheduled_tasks_for_component($component);
691 message_update_providers($component);
692 \core\message\inbound\manager
::update_handlers_for_component($component);
693 upgrade_plugin_mnet_functions($component);
695 $endcallback($component, true, $verbose);
697 } else if ($installedversion < $plugin->version
) {
698 /// If versions say that we need to upgrade but no upgrade files are available, notify and continue
699 $startcallback($component, false, $verbose);
701 if (is_readable($fullmod.'/db/upgrade.php')) {
702 require_once($fullmod.'/db/upgrade.php'); // defines new upgrading function
703 $newupgrade_function = 'xmldb_'.$module->name
.'_upgrade';
704 $result = $newupgrade_function($installedversion, $module);
709 $installedversion = $DB->get_field('config_plugins', 'value', array('name'=>'version', 'plugin'=>$component)); // No caching!
710 $currmodule = $DB->get_record('modules', array('name'=>$module->name
));
711 if ($installedversion < $plugin->version
) {
712 // store version if not already there
713 upgrade_mod_savepoint($result, $plugin->version
, $mod, false);
716 // update cron flag if needed
717 if ($currmodule->cron
!= $module->cron
) {
718 $DB->set_field('modules', 'cron', $module->cron
, array('name' => $module->name
));
721 // Upgrade various components
722 update_capabilities($component);
723 log_update_descriptions($component);
724 external_update_descriptions($component);
725 events_update_definition($component);
726 \core\task\manager
::reset_scheduled_tasks_for_component($component);
727 message_update_providers($component);
728 \core\message\inbound\manager
::update_handlers_for_component($component);
729 upgrade_plugin_mnet_functions($component);
731 $endcallback($component, false, $verbose);
733 } else if ($installedversion > $plugin->version
) {
734 throw new downgrade_exception($component, $installedversion, $plugin->version
);
741 * This function finds all available blocks and install them
742 * into blocks table or do all the upgrade process if newer.
747 function upgrade_plugins_blocks($startcallback, $endcallback, $verbose) {
750 require_once($CFG->dirroot
.'/blocks/moodleblock.class.php');
752 $blocktitles = array(); // we do not want duplicate titles
754 //Is this a first install
755 $first_install = null;
757 $blocks = core_component
::get_plugin_list('block');
759 foreach ($blocks as $blockname=>$fullblock) {
761 if (is_null($first_install)) {
762 $first_install = ($DB->count_records('block_instances') == 0);
765 if ($blockname === 'NEWBLOCK') { // Someone has unzipped the template, ignore it
769 $component = clean_param('block_'.$blockname, PARAM_COMPONENT
);
771 // check block dir is valid name
772 if (empty($component)) {
773 throw new plugin_defective_exception('block_'.$blockname, 'Invalid plugin directory name.');
776 if (!is_readable($fullblock.'/version.php')) {
777 throw new plugin_defective_exception('block/'.$blockname, 'Missing version.php file.');
779 $plugin = new stdClass();
780 $plugin->version
= null;
782 $module = $plugin; // Prevent some notices when module placed in wrong directory.
783 include($fullblock.'/version.php');
785 $block = clone($plugin);
786 unset($block->version
);
787 unset($block->component
);
788 unset($block->dependencies
);
789 unset($block->release
);
791 // if plugin tells us it's full name we may check the location
792 if (isset($plugin->component
)) {
793 if ($plugin->component
!== $component) {
794 throw new plugin_misplaced_exception($plugin->component
, null, $fullblock);
798 if (empty($plugin->version
)) {
799 throw new plugin_defective_exception($component, 'Missing block version.');
802 if (!empty($plugin->requires
)) {
803 if ($plugin->requires
> $CFG->version
) {
804 throw new upgrade_requires_exception($component, $plugin->version
, $CFG->version
, $plugin->requires
);
805 } else if ($plugin->requires
< 2010000000) {
806 throw new plugin_defective_exception($component, 'Plugin is not compatible with Moodle 2.x or later.');
810 if (!is_readable($fullblock.'/block_'.$blockname.'.php')) {
811 throw new plugin_defective_exception('block/'.$blockname, 'Missing main block class file.');
813 include_once($fullblock.'/block_'.$blockname.'.php');
815 $classname = 'block_'.$blockname;
817 if (!class_exists($classname)) {
818 throw new plugin_defective_exception($component, 'Can not load main class.');
821 $blockobj = new $classname; // This is what we'll be testing
822 $blocktitle = $blockobj->get_title();
824 // OK, it's as we all hoped. For further tests, the object will do them itself.
825 if (!$blockobj->_self_test()) {
826 throw new plugin_defective_exception($component, 'Self test failed.');
829 $block->name
= $blockname; // The name MUST match the directory
831 $installedversion = $DB->get_field('config_plugins', 'value', array('name'=>'version', 'plugin'=>$component)); // No caching!
833 if (file_exists($fullblock.'/db/install.php')) {
834 if (get_config('block_'.$blockname, 'installrunning')) {
835 require_once($fullblock.'/db/install.php');
836 $recover_install_function = 'xmldb_block_'.$blockname.'_install_recovery';
837 if (function_exists($recover_install_function)) {
838 $startcallback($component, true, $verbose);
839 $recover_install_function();
840 unset_config('installrunning', 'block_'.$blockname);
841 // Install various components
842 update_capabilities($component);
843 log_update_descriptions($component);
844 external_update_descriptions($component);
845 events_update_definition($component);
846 \core\task\manager
::reset_scheduled_tasks_for_component($component);
847 message_update_providers($component);
848 \core\message\inbound\manager
::update_handlers_for_component($component);
849 upgrade_plugin_mnet_functions($component);
850 $endcallback($component, true, $verbose);
855 if (empty($installedversion)) { // block not installed yet, so install it
856 $conflictblock = array_search($blocktitle, $blocktitles);
857 if ($conflictblock !== false) {
858 // Duplicate block titles are not allowed, they confuse people
859 // AND PHP's associative arrays ;)
860 throw new plugin_defective_exception($component, get_string('blocknameconflict', 'error', (object)array('name'=>$block->name
, 'conflict'=>$conflictblock)));
862 $startcallback($component, true, $verbose);
864 if (file_exists($fullblock.'/db/install.xml')) {
865 $DB->get_manager()->install_from_xmldb_file($fullblock.'/db/install.xml');
867 $block->id
= $DB->insert_record('block', $block);
868 upgrade_block_savepoint(true, $plugin->version
, $block->name
, false);
870 if (file_exists($fullblock.'/db/install.php')) {
871 require_once($fullblock.'/db/install.php');
872 // Set installation running flag, we need to recover after exception or error
873 set_config('installrunning', 1, 'block_'.$blockname);
874 $post_install_function = 'xmldb_block_'.$blockname.'_install';
875 $post_install_function();
876 unset_config('installrunning', 'block_'.$blockname);
879 $blocktitles[$block->name
] = $blocktitle;
881 // Install various components
882 update_capabilities($component);
883 log_update_descriptions($component);
884 external_update_descriptions($component);
885 events_update_definition($component);
886 \core\task\manager
::reset_scheduled_tasks_for_component($component);
887 message_update_providers($component);
888 \core\message\inbound\manager
::update_handlers_for_component($component);
889 upgrade_plugin_mnet_functions($component);
891 $endcallback($component, true, $verbose);
893 } else if ($installedversion < $plugin->version
) {
894 $startcallback($component, false, $verbose);
896 if (is_readable($fullblock.'/db/upgrade.php')) {
897 require_once($fullblock.'/db/upgrade.php'); // defines new upgrading function
898 $newupgrade_function = 'xmldb_block_'.$blockname.'_upgrade';
899 $result = $newupgrade_function($installedversion, $block);
904 $installedversion = $DB->get_field('config_plugins', 'value', array('name'=>'version', 'plugin'=>$component)); // No caching!
905 $currblock = $DB->get_record('block', array('name'=>$block->name
));
906 if ($installedversion < $plugin->version
) {
907 // store version if not already there
908 upgrade_block_savepoint($result, $plugin->version
, $block->name
, false);
911 if ($currblock->cron
!= $block->cron
) {
912 // update cron flag if needed
913 $DB->set_field('block', 'cron', $block->cron
, array('id' => $currblock->id
));
916 // Upgrade various components
917 update_capabilities($component);
918 log_update_descriptions($component);
919 external_update_descriptions($component);
920 events_update_definition($component);
921 \core\task\manager
::reset_scheduled_tasks_for_component($component);
922 message_update_providers($component);
923 \core\message\inbound\manager
::update_handlers_for_component($component);
924 upgrade_plugin_mnet_functions($component);
926 $endcallback($component, false, $verbose);
928 } else if ($installedversion > $plugin->version
) {
929 throw new downgrade_exception($component, $installedversion, $plugin->version
);
934 // Finally, if we are in the first_install of BLOCKS setup frontpage and admin page blocks
935 if ($first_install) {
936 //Iterate over each course - there should be only site course here now
937 if ($courses = $DB->get_records('course')) {
938 foreach ($courses as $course) {
939 blocks_add_default_course_blocks($course);
943 blocks_add_default_system_blocks();
949 * Log_display description function used during install and upgrade.
951 * @param string $component name of component (moodle, mod_assignment, etc.)
954 function log_update_descriptions($component) {
957 $defpath = core_component
::get_component_directory($component).'/db/log.php';
959 if (!file_exists($defpath)) {
960 $DB->delete_records('log_display', array('component'=>$component));
968 foreach ($logs as $log) {
969 $newlogs[$log['module'].'-'.$log['action']] = $log; // kind of unique name
974 $fields = array('module', 'action', 'mtable', 'field');
975 // update all log fist
976 $dblogs = $DB->get_records('log_display', array('component'=>$component));
977 foreach ($dblogs as $dblog) {
978 $name = $dblog->module
.'-'.$dblog->action
;
980 if (empty($logs[$name])) {
981 $DB->delete_records('log_display', array('id'=>$dblog->id
));
989 foreach ($fields as $field) {
990 if ($dblog->$field != $log[$field]) {
991 $dblog->$field = $log[$field];
996 $DB->update_record('log_display', $dblog);
999 foreach ($logs as $log) {
1000 $dblog = (object)$log;
1001 $dblog->component
= $component;
1002 $DB->insert_record('log_display', $dblog);
1007 * Web service discovery function used during install and upgrade.
1008 * @param string $component name of component (moodle, mod_assignment, etc.)
1011 function external_update_descriptions($component) {
1014 $defpath = core_component
::get_component_directory($component).'/db/services.php';
1016 if (!file_exists($defpath)) {
1017 require_once($CFG->dirroot
.'/lib/externallib.php');
1018 external_delete_descriptions($component);
1023 $functions = array();
1024 $services = array();
1027 // update all function fist
1028 $dbfunctions = $DB->get_records('external_functions', array('component'=>$component));
1029 foreach ($dbfunctions as $dbfunction) {
1030 if (empty($functions[$dbfunction->name
])) {
1031 $DB->delete_records('external_functions', array('id'=>$dbfunction->id
));
1032 // do not delete functions from external_services_functions, beacuse
1033 // we want to notify admins when functions used in custom services disappear
1035 //TODO: this looks wrong, we have to delete it eventually (skodak)
1039 $function = $functions[$dbfunction->name
];
1040 unset($functions[$dbfunction->name
]);
1041 $function['classpath'] = empty($function['classpath']) ?
null : $function['classpath'];
1044 if ($dbfunction->classname
!= $function['classname']) {
1045 $dbfunction->classname
= $function['classname'];
1048 if ($dbfunction->methodname
!= $function['methodname']) {
1049 $dbfunction->methodname
= $function['methodname'];
1052 if ($dbfunction->classpath
!= $function['classpath']) {
1053 $dbfunction->classpath
= $function['classpath'];
1056 $functioncapabilities = array_key_exists('capabilities', $function)?
$function['capabilities']:'';
1057 if ($dbfunction->capabilities
!= $functioncapabilities) {
1058 $dbfunction->capabilities
= $functioncapabilities;
1062 $DB->update_record('external_functions', $dbfunction);
1065 foreach ($functions as $fname => $function) {
1066 $dbfunction = new stdClass();
1067 $dbfunction->name
= $fname;
1068 $dbfunction->classname
= $function['classname'];
1069 $dbfunction->methodname
= $function['methodname'];
1070 $dbfunction->classpath
= empty($function['classpath']) ?
null : $function['classpath'];
1071 $dbfunction->component
= $component;
1072 $dbfunction->capabilities
= array_key_exists('capabilities', $function)?
$function['capabilities']:'';
1073 $dbfunction->id
= $DB->insert_record('external_functions', $dbfunction);
1077 // now deal with services
1078 $dbservices = $DB->get_records('external_services', array('component'=>$component));
1079 foreach ($dbservices as $dbservice) {
1080 if (empty($services[$dbservice->name
])) {
1081 $DB->delete_records('external_tokens', array('externalserviceid'=>$dbservice->id
));
1082 $DB->delete_records('external_services_functions', array('externalserviceid'=>$dbservice->id
));
1083 $DB->delete_records('external_services_users', array('externalserviceid'=>$dbservice->id
));
1084 $DB->delete_records('external_services', array('id'=>$dbservice->id
));
1087 $service = $services[$dbservice->name
];
1088 unset($services[$dbservice->name
]);
1089 $service['enabled'] = empty($service['enabled']) ?
0 : $service['enabled'];
1090 $service['requiredcapability'] = empty($service['requiredcapability']) ?
null : $service['requiredcapability'];
1091 $service['restrictedusers'] = !isset($service['restrictedusers']) ?
1 : $service['restrictedusers'];
1092 $service['downloadfiles'] = !isset($service['downloadfiles']) ?
0 : $service['downloadfiles'];
1093 $service['uploadfiles'] = !isset($service['uploadfiles']) ?
0 : $service['uploadfiles'];
1094 $service['shortname'] = !isset($service['shortname']) ?
null : $service['shortname'];
1097 if ($dbservice->requiredcapability
!= $service['requiredcapability']) {
1098 $dbservice->requiredcapability
= $service['requiredcapability'];
1101 if ($dbservice->restrictedusers
!= $service['restrictedusers']) {
1102 $dbservice->restrictedusers
= $service['restrictedusers'];
1105 if ($dbservice->downloadfiles
!= $service['downloadfiles']) {
1106 $dbservice->downloadfiles
= $service['downloadfiles'];
1109 if ($dbservice->uploadfiles
!= $service['uploadfiles']) {
1110 $dbservice->uploadfiles
= $service['uploadfiles'];
1113 //if shortname is not a PARAM_ALPHANUMEXT, fail (tested here for service update and creation)
1114 if (isset($service['shortname']) and
1115 (clean_param($service['shortname'], PARAM_ALPHANUMEXT
) != $service['shortname'])) {
1116 throw new moodle_exception('installserviceshortnameerror', 'webservice', '', $service['shortname']);
1118 if ($dbservice->shortname
!= $service['shortname']) {
1119 //check that shortname is unique
1120 if (isset($service['shortname'])) { //we currently accepts multiple shortname == null
1121 $existingservice = $DB->get_record('external_services',
1122 array('shortname' => $service['shortname']));
1123 if (!empty($existingservice)) {
1124 throw new moodle_exception('installexistingserviceshortnameerror', 'webservice', '', $service['shortname']);
1127 $dbservice->shortname
= $service['shortname'];
1131 $DB->update_record('external_services', $dbservice);
1134 $functions = $DB->get_records('external_services_functions', array('externalserviceid'=>$dbservice->id
));
1135 foreach ($functions as $function) {
1136 $key = array_search($function->functionname
, $service['functions']);
1137 if ($key === false) {
1138 $DB->delete_records('external_services_functions', array('id'=>$function->id
));
1140 unset($service['functions'][$key]);
1143 foreach ($service['functions'] as $fname) {
1144 $newf = new stdClass();
1145 $newf->externalserviceid
= $dbservice->id
;
1146 $newf->functionname
= $fname;
1147 $DB->insert_record('external_services_functions', $newf);
1151 foreach ($services as $name => $service) {
1152 //check that shortname is unique
1153 if (isset($service['shortname'])) { //we currently accepts multiple shortname == null
1154 $existingservice = $DB->get_record('external_services',
1155 array('shortname' => $service['shortname']));
1156 if (!empty($existingservice)) {
1157 throw new moodle_exception('installserviceshortnameerror', 'webservice');
1161 $dbservice = new stdClass();
1162 $dbservice->name
= $name;
1163 $dbservice->enabled
= empty($service['enabled']) ?
0 : $service['enabled'];
1164 $dbservice->requiredcapability
= empty($service['requiredcapability']) ?
null : $service['requiredcapability'];
1165 $dbservice->restrictedusers
= !isset($service['restrictedusers']) ?
1 : $service['restrictedusers'];
1166 $dbservice->downloadfiles
= !isset($service['downloadfiles']) ?
0 : $service['downloadfiles'];
1167 $dbservice->uploadfiles
= !isset($service['uploadfiles']) ?
0 : $service['uploadfiles'];
1168 $dbservice->shortname
= !isset($service['shortname']) ?
null : $service['shortname'];
1169 $dbservice->component
= $component;
1170 $dbservice->timecreated
= time();
1171 $dbservice->id
= $DB->insert_record('external_services', $dbservice);
1172 foreach ($service['functions'] as $fname) {
1173 $newf = new stdClass();
1174 $newf->externalserviceid
= $dbservice->id
;
1175 $newf->functionname
= $fname;
1176 $DB->insert_record('external_services_functions', $newf);
1182 * upgrade logging functions
1184 function upgrade_handle_exception($ex, $plugin = null) {
1187 // rollback everything, we need to log all upgrade problems
1188 abort_all_db_transactions();
1190 $info = get_exception_info($ex);
1192 // First log upgrade error
1193 upgrade_log(UPGRADE_LOG_ERROR
, $plugin, 'Exception: ' . get_class($ex), $info->message
, $info->backtrace
);
1195 // Always turn on debugging - admins need to know what is going on
1196 set_debugging(DEBUG_DEVELOPER
, true);
1198 default_exception_handler($ex, true, $plugin);
1202 * Adds log entry into upgrade_log table
1204 * @param int $type UPGRADE_LOG_NORMAL, UPGRADE_LOG_NOTICE or UPGRADE_LOG_ERROR
1205 * @param string $plugin frankenstyle component name
1206 * @param string $info short description text of log entry
1207 * @param string $details long problem description
1208 * @param string $backtrace string used for errors only
1211 function upgrade_log($type, $plugin, $info, $details=null, $backtrace=null) {
1212 global $DB, $USER, $CFG;
1214 if (empty($plugin)) {
1218 list($plugintype, $pluginname) = core_component
::normalize_component($plugin);
1219 $component = is_null($pluginname) ?
$plugintype : $plugintype . '_' . $pluginname;
1221 $backtrace = format_backtrace($backtrace, true);
1223 $currentversion = null;
1224 $targetversion = null;
1226 //first try to find out current version number
1227 if ($plugintype === 'core') {
1229 $currentversion = $CFG->version
;
1232 include("$CFG->dirroot/version.php");
1233 $targetversion = $version;
1236 $pluginversion = get_config($component, 'version');
1237 if (!empty($pluginversion)) {
1238 $currentversion = $pluginversion;
1240 $cd = core_component
::get_component_directory($component);
1241 if (file_exists("$cd/version.php")) {
1242 $plugin = new stdClass();
1243 $plugin->version
= null;
1245 include("$cd/version.php");
1246 $targetversion = $plugin->version
;
1250 $log = new stdClass();
1252 $log->plugin
= $component;
1253 $log->version
= $currentversion;
1254 $log->targetversion
= $targetversion;
1256 $log->details
= $details;
1257 $log->backtrace
= $backtrace;
1258 $log->userid
= $USER->id
;
1259 $log->timemodified
= time();
1261 $DB->insert_record('upgrade_log', $log);
1262 } catch (Exception
$ignored) {
1263 // possible during install or 2.0 upgrade
1268 * Marks start of upgrade, blocks any other access to site.
1269 * The upgrade is finished at the end of script or after timeout.
1275 function upgrade_started($preinstall=false) {
1276 global $CFG, $DB, $PAGE, $OUTPUT;
1278 static $started = false;
1281 ignore_user_abort(true);
1282 upgrade_setup_debug(true);
1284 } else if ($started) {
1285 upgrade_set_timeout(120);
1288 if (!CLI_SCRIPT
and !$PAGE->headerprinted
) {
1289 $strupgrade = get_string('upgradingversion', 'admin');
1290 $PAGE->set_pagelayout('maintenance');
1291 upgrade_init_javascript();
1292 $PAGE->set_title($strupgrade.' - Moodle '.$CFG->target_release
);
1293 $PAGE->set_heading($strupgrade);
1294 $PAGE->navbar
->add($strupgrade);
1295 $PAGE->set_cacheable(false);
1296 echo $OUTPUT->header();
1299 ignore_user_abort(true);
1300 core_shutdown_manager
::register_function('upgrade_finished_handler');
1301 upgrade_setup_debug(true);
1302 set_config('upgraderunning', time()+
300);
1308 * Internal function - executed if upgrade interrupted.
1310 function upgrade_finished_handler() {
1315 * Indicates upgrade is finished.
1317 * This function may be called repeatedly.
1322 function upgrade_finished($continueurl=null) {
1323 global $CFG, $DB, $OUTPUT;
1325 if (!empty($CFG->upgraderunning
)) {
1326 unset_config('upgraderunning');
1327 // We have to forcefully purge the caches using the writer here.
1328 // This has to be done after we unset the config var. If someone hits the site while this is set they will
1329 // cause the config values to propogate to the caches.
1330 // Caches are purged after the last step in an upgrade but there is several code routines that exceute between
1331 // then and now that leaving a window for things to fall out of sync.
1332 cache_helper
::purge_all(true);
1333 upgrade_setup_debug(false);
1334 ignore_user_abort(false);
1336 echo $OUTPUT->continue_button($continueurl);
1337 echo $OUTPUT->footer();
1347 function upgrade_setup_debug($starting) {
1350 static $originaldebug = null;
1353 if ($originaldebug === null) {
1354 $originaldebug = $DB->get_debug();
1356 if (!empty($CFG->upgradeshowsql
)) {
1357 $DB->set_debug(true);
1360 $DB->set_debug($originaldebug);
1364 function print_upgrade_separator() {
1371 * Default start upgrade callback
1372 * @param string $plugin
1373 * @param bool $installation true if installation, false means upgrade
1375 function print_upgrade_part_start($plugin, $installation, $verbose) {
1377 if (empty($plugin) or $plugin == 'moodle') {
1378 upgrade_started($installation); // does not store upgrade running flag yet
1380 echo $OUTPUT->heading(get_string('coresystem'));
1385 echo $OUTPUT->heading($plugin);
1388 if ($installation) {
1389 if (empty($plugin) or $plugin == 'moodle') {
1390 // no need to log - log table not yet there ;-)
1392 upgrade_log(UPGRADE_LOG_NORMAL
, $plugin, 'Starting plugin installation');
1395 if (empty($plugin) or $plugin == 'moodle') {
1396 upgrade_log(UPGRADE_LOG_NORMAL
, $plugin, 'Starting core upgrade');
1398 upgrade_log(UPGRADE_LOG_NORMAL
, $plugin, 'Starting plugin upgrade');
1404 * Default end upgrade callback
1405 * @param string $plugin
1406 * @param bool $installation true if installation, false means upgrade
1408 function print_upgrade_part_end($plugin, $installation, $verbose) {
1411 if ($installation) {
1412 if (empty($plugin) or $plugin == 'moodle') {
1413 upgrade_log(UPGRADE_LOG_NORMAL
, $plugin, 'Core installed');
1415 upgrade_log(UPGRADE_LOG_NORMAL
, $plugin, 'Plugin installed');
1418 if (empty($plugin) or $plugin == 'moodle') {
1419 upgrade_log(UPGRADE_LOG_NORMAL
, $plugin, 'Core upgraded');
1421 upgrade_log(UPGRADE_LOG_NORMAL
, $plugin, 'Plugin upgraded');
1425 echo $OUTPUT->notification(get_string('success'), 'notifysuccess');
1426 print_upgrade_separator();
1431 * Sets up JS code required for all upgrade scripts.
1434 function upgrade_init_javascript() {
1436 // scroll to the end of each upgrade page so that ppl see either error or continue button,
1437 // no need to scroll continuously any more, it is enough to jump to end once the footer is printed ;-)
1438 $js = "window.scrollTo(0, 5000000);";
1439 $PAGE->requires
->js_init_code($js);
1443 * Try to upgrade the given language pack (or current language)
1445 * @param string $lang the code of the language to update, defaults to the current language
1447 function upgrade_language_pack($lang = null) {
1450 if (!empty($CFG->skiplangupgrade
)) {
1454 if (!file_exists("$CFG->dirroot/$CFG->admin/tool/langimport/lib.php")) {
1455 // weird, somebody uninstalled the import utility
1460 $lang = current_language();
1463 if (!get_string_manager()->translation_exists($lang)) {
1467 get_string_manager()->reset_caches();
1469 if ($lang === 'en') {
1470 return; // Nothing to do
1473 upgrade_started(false);
1475 require_once("$CFG->dirroot/$CFG->admin/tool/langimport/lib.php");
1476 tool_langimport_preupgrade_update($lang);
1478 get_string_manager()->reset_caches();
1480 print_upgrade_separator();
1484 * Install core moodle tables and initialize
1485 * @param float $version target version
1486 * @param bool $verbose
1487 * @return void, may throw exception
1489 function install_core($version, $verbose) {
1492 // We can not call purge_all_caches() yet, make sure the temp and cache dirs exist and are empty.
1493 remove_dir($CFG->cachedir
.'', true);
1494 make_cache_directory('', true);
1496 remove_dir($CFG->localcachedir
.'', true);
1497 make_localcache_directory('', true);
1499 remove_dir($CFG->tempdir
.'', true);
1500 make_temp_directory('', true);
1502 remove_dir($CFG->dataroot
.'/muc', true);
1503 make_writable_directory($CFG->dataroot
.'/muc', true);
1506 core_php_time_limit
::raise(600);
1507 print_upgrade_part_start('moodle', true, $verbose); // does not store upgrade running flag
1509 $DB->get_manager()->install_from_xmldb_file("$CFG->libdir/db/install.xml");
1510 upgrade_started(); // we want the flag to be stored in config table ;-)
1512 // set all core default records and default settings
1513 require_once("$CFG->libdir/db/install.php");
1514 xmldb_main_install(); // installs the capabilities too
1517 upgrade_main_savepoint(true, $version, false);
1519 // Continue with the installation
1520 log_update_descriptions('moodle');
1521 external_update_descriptions('moodle');
1522 events_update_definition('moodle');
1523 \core\task\manager
::reset_scheduled_tasks_for_component('moodle');
1524 message_update_providers('moodle');
1525 \core\message\inbound\manager
::update_handlers_for_component('moodle');
1527 // Write default settings unconditionally
1528 admin_apply_default_settings(NULL, true);
1530 print_upgrade_part_end(null, true, $verbose);
1532 // Purge all caches. They're disabled but this ensures that we don't have any persistent data just in case something
1533 // during installation didn't use APIs.
1534 cache_helper
::purge_all();
1535 } catch (exception
$ex) {
1536 upgrade_handle_exception($ex);
1541 * Upgrade moodle core
1542 * @param float $version target version
1543 * @param bool $verbose
1544 * @return void, may throw exception
1546 function upgrade_core($version, $verbose) {
1547 global $CFG, $SITE, $DB, $COURSE;
1549 raise_memory_limit(MEMORY_EXTRA
);
1551 require_once($CFG->libdir
.'/db/upgrade.php'); // Defines upgrades
1554 // Reset caches before any output.
1555 cache_helper
::purge_all(true);
1558 // Upgrade current language pack if we can
1559 upgrade_language_pack();
1561 print_upgrade_part_start('moodle', false, $verbose);
1563 // Pre-upgrade scripts for local hack workarounds.
1564 $preupgradefile = "$CFG->dirroot/local/preupgrade.php";
1565 if (file_exists($preupgradefile)) {
1566 core_php_time_limit
::raise();
1567 require($preupgradefile);
1568 // Reset upgrade timeout to default.
1569 upgrade_set_timeout();
1572 $result = xmldb_main_upgrade($CFG->version
);
1573 if ($version > $CFG->version
) {
1574 // store version if not already there
1575 upgrade_main_savepoint($result, $version, false);
1578 // In case structure of 'course' table has been changed and we forgot to update $SITE, re-read it from db.
1579 $SITE = $DB->get_record('course', array('id' => $SITE->id
));
1580 $COURSE = clone($SITE);
1582 // perform all other component upgrade routines
1583 update_capabilities('moodle');
1584 log_update_descriptions('moodle');
1585 external_update_descriptions('moodle');
1586 events_update_definition('moodle');
1587 \core\task\manager
::reset_scheduled_tasks_for_component('moodle');
1588 message_update_providers('moodle');
1589 \core\message\inbound\manager
::update_handlers_for_component('moodle');
1590 // Update core definitions.
1591 cache_helper
::update_definitions(true);
1593 // Purge caches again, just to be sure we arn't holding onto old stuff now.
1594 cache_helper
::purge_all(true);
1597 // Clean up contexts - more and more stuff depends on existence of paths and contexts
1598 context_helper
::cleanup_instances();
1599 context_helper
::create_instances(null, false);
1600 context_helper
::build_all_paths(false);
1601 $syscontext = context_system
::instance();
1602 $syscontext->mark_dirty();
1604 print_upgrade_part_end('moodle', false, $verbose);
1605 } catch (Exception
$ex) {
1606 upgrade_handle_exception($ex);
1611 * Upgrade/install other parts of moodle
1612 * @param bool $verbose
1613 * @return void, may throw exception
1615 function upgrade_noncore($verbose) {
1618 raise_memory_limit(MEMORY_EXTRA
);
1620 // upgrade all plugins types
1622 // Reset caches before any output.
1623 cache_helper
::purge_all(true);
1626 $plugintypes = core_component
::get_plugin_types();
1627 foreach ($plugintypes as $type=>$location) {
1628 upgrade_plugins($type, 'print_upgrade_part_start', 'print_upgrade_part_end', $verbose);
1630 // Update cache definitions. Involves scanning each plugin for any changes.
1631 cache_helper
::update_definitions();
1632 // Mark the site as upgraded.
1633 set_config('allversionshash', core_component
::get_all_versions_hash());
1635 // Purge caches again, just to be sure we arn't holding onto old stuff now.
1636 cache_helper
::purge_all(true);
1639 } catch (Exception
$ex) {
1640 upgrade_handle_exception($ex);
1645 * Checks if the main tables have been installed yet or not.
1647 * Note: we can not use caches here because they might be stale,
1652 function core_tables_exist() {
1655 if (!$tables = $DB->get_tables(false) ) { // No tables yet at all.
1658 } else { // Check for missing main tables
1659 $mtables = array('config', 'course', 'groupings'); // some tables used in 1.9 and 2.0, preferable something from the start and end of install.xml
1660 foreach ($mtables as $mtable) {
1661 if (!in_array($mtable, $tables)) {
1670 * upgrades the mnet rpc definitions for the given component.
1671 * this method doesn't return status, an exception will be thrown in the case of an error
1673 * @param string $component the plugin to upgrade, eg auth_mnet
1675 function upgrade_plugin_mnet_functions($component) {
1678 list($type, $plugin) = core_component
::normalize_component($component);
1679 $path = core_component
::get_plugin_directory($type, $plugin);
1681 $publishes = array();
1682 $subscribes = array();
1683 if (file_exists($path . '/db/mnet.php')) {
1684 require_once($path . '/db/mnet.php'); // $publishes comes from this file
1686 if (empty($publishes)) {
1687 $publishes = array(); // still need this to be able to disable stuff later
1689 if (empty($subscribes)) {
1690 $subscribes = array(); // still need this to be able to disable stuff later
1693 static $servicecache = array();
1695 // rekey an array based on the rpc method for easy lookups later
1696 $publishmethodservices = array();
1697 $subscribemethodservices = array();
1698 foreach($publishes as $servicename => $service) {
1699 if (is_array($service['methods'])) {
1700 foreach($service['methods'] as $methodname) {
1701 $service['servicename'] = $servicename;
1702 $publishmethodservices[$methodname][] = $service;
1707 // Disable functions that don't exist (any more) in the source
1708 // Should these be deleted? What about their permissions records?
1709 foreach ($DB->get_records('mnet_rpc', array('pluginname'=>$plugin, 'plugintype'=>$type), 'functionname ASC ') as $rpc) {
1710 if (!array_key_exists($rpc->functionname
, $publishmethodservices) && $rpc->enabled
) {
1711 $DB->set_field('mnet_rpc', 'enabled', 0, array('id' => $rpc->id
));
1712 } else if (array_key_exists($rpc->functionname
, $publishmethodservices) && !$rpc->enabled
) {
1713 $DB->set_field('mnet_rpc', 'enabled', 1, array('id' => $rpc->id
));
1717 // reflect all the services we're publishing and save them
1718 require_once($CFG->dirroot
. '/lib/zend/Zend/Server/Reflection.php');
1719 static $cachedclasses = array(); // to store reflection information in
1720 foreach ($publishes as $service => $data) {
1721 $f = $data['filename'];
1722 $c = $data['classname'];
1723 foreach ($data['methods'] as $method) {
1724 $dataobject = new stdClass();
1725 $dataobject->plugintype
= $type;
1726 $dataobject->pluginname
= $plugin;
1727 $dataobject->enabled
= 1;
1728 $dataobject->classname
= $c;
1729 $dataobject->filename
= $f;
1731 if (is_string($method)) {
1732 $dataobject->functionname
= $method;
1734 } else if (is_array($method)) { // wants to override file or class
1735 $dataobject->functionname
= $method['method'];
1736 $dataobject->classname
= $method['classname'];
1737 $dataobject->filename
= $method['filename'];
1739 $dataobject->xmlrpcpath
= $type.'/'.$plugin.'/'.$dataobject->filename
.'/'.$method;
1740 $dataobject->static = false;
1742 require_once($path . '/' . $dataobject->filename
);
1743 $functionreflect = null; // slightly different ways to get this depending on whether it's a class method or a function
1744 if (!empty($dataobject->classname
)) {
1745 if (!class_exists($dataobject->classname
)) {
1746 throw new moodle_exception('installnosuchmethod', 'mnet', '', (object)array('method' => $dataobject->functionname
, 'class' => $dataobject->classname
));
1748 $key = $dataobject->filename
. '|' . $dataobject->classname
;
1749 if (!array_key_exists($key, $cachedclasses)) { // look to see if we've already got a reflection object
1751 $cachedclasses[$key] = Zend_Server_Reflection
::reflectClass($dataobject->classname
);
1752 } catch (Zend_Server_Reflection_Exception
$e) { // catch these and rethrow them to something more helpful
1753 throw new moodle_exception('installreflectionclasserror', 'mnet', '', (object)array('method' => $dataobject->functionname
, 'class' => $dataobject->classname
, 'error' => $e->getMessage()));
1756 $r =& $cachedclasses[$key];
1757 if (!$r->hasMethod($dataobject->functionname
)) {
1758 throw new moodle_exception('installnosuchmethod', 'mnet', '', (object)array('method' => $dataobject->functionname
, 'class' => $dataobject->classname
));
1760 // stupid workaround for zend not having a getMethod($name) function
1761 $ms = $r->getMethods();
1762 foreach ($ms as $m) {
1763 if ($m->getName() == $dataobject->functionname
) {
1764 $functionreflect = $m;
1768 $dataobject->static = (int)$functionreflect->isStatic();
1770 if (!function_exists($dataobject->functionname
)) {
1771 throw new moodle_exception('installnosuchfunction', 'mnet', '', (object)array('method' => $dataobject->functionname
, 'file' => $dataobject->filename
));
1774 $functionreflect = Zend_Server_Reflection
::reflectFunction($dataobject->functionname
);
1775 } catch (Zend_Server_Reflection_Exception
$e) { // catch these and rethrow them to something more helpful
1776 throw new moodle_exception('installreflectionfunctionerror', 'mnet', '', (object)array('method' => $dataobject->functionname
, '' => $dataobject->filename
, 'error' => $e->getMessage()));
1779 $dataobject->profile
= serialize(admin_mnet_method_profile($functionreflect));
1780 $dataobject->help
= $functionreflect->getDescription();
1782 if ($record_exists = $DB->get_record('mnet_rpc', array('xmlrpcpath'=>$dataobject->xmlrpcpath
))) {
1783 $dataobject->id
= $record_exists->id
;
1784 $dataobject->enabled
= $record_exists->enabled
;
1785 $DB->update_record('mnet_rpc', $dataobject);
1787 $dataobject->id
= $DB->insert_record('mnet_rpc', $dataobject, true);
1790 // TODO this API versioning must be reworked, here the recently processed method
1791 // sets the service API which may not be correct
1792 foreach ($publishmethodservices[$dataobject->functionname
] as $service) {
1793 if ($serviceobj = $DB->get_record('mnet_service', array('name'=>$service['servicename']))) {
1794 $serviceobj->apiversion
= $service['apiversion'];
1795 $DB->update_record('mnet_service', $serviceobj);
1797 $serviceobj = new stdClass();
1798 $serviceobj->name
= $service['servicename'];
1799 $serviceobj->description
= empty($service['description']) ?
'' : $service['description'];
1800 $serviceobj->apiversion
= $service['apiversion'];
1801 $serviceobj->offer
= 1;
1802 $serviceobj->id
= $DB->insert_record('mnet_service', $serviceobj);
1804 $servicecache[$service['servicename']] = $serviceobj;
1805 if (!$DB->record_exists('mnet_service2rpc', array('rpcid'=>$dataobject->id
, 'serviceid'=>$serviceobj->id
))) {
1806 $obj = new stdClass();
1807 $obj->rpcid
= $dataobject->id
;
1808 $obj->serviceid
= $serviceobj->id
;
1809 $DB->insert_record('mnet_service2rpc', $obj, true);
1814 // finished with methods we publish, now do subscribable methods
1815 foreach($subscribes as $service => $methods) {
1816 if (!array_key_exists($service, $servicecache)) {
1817 if (!$serviceobj = $DB->get_record('mnet_service', array('name' => $service))) {
1818 debugging("TODO: skipping unknown service $service - somebody needs to fix MDL-21993");
1821 $servicecache[$service] = $serviceobj;
1823 $serviceobj = $servicecache[$service];
1825 foreach ($methods as $method => $xmlrpcpath) {
1826 if (!$rpcid = $DB->get_field('mnet_remote_rpc', 'id', array('xmlrpcpath'=>$xmlrpcpath))) {
1827 $remoterpc = (object)array(
1828 'functionname' => $method,
1829 'xmlrpcpath' => $xmlrpcpath,
1830 'plugintype' => $type,
1831 'pluginname' => $plugin,
1834 $rpcid = $remoterpc->id
= $DB->insert_record('mnet_remote_rpc', $remoterpc, true);
1836 if (!$DB->record_exists('mnet_remote_service2rpc', array('rpcid'=>$rpcid, 'serviceid'=>$serviceobj->id
))) {
1837 $obj = new stdClass();
1838 $obj->rpcid
= $rpcid;
1839 $obj->serviceid
= $serviceobj->id
;
1840 $DB->insert_record('mnet_remote_service2rpc', $obj, true);
1842 $subscribemethodservices[$method][] = $service;
1846 foreach ($DB->get_records('mnet_remote_rpc', array('pluginname'=>$plugin, 'plugintype'=>$type), 'functionname ASC ') as $rpc) {
1847 if (!array_key_exists($rpc->functionname
, $subscribemethodservices) && $rpc->enabled
) {
1848 $DB->set_field('mnet_remote_rpc', 'enabled', 0, array('id' => $rpc->id
));
1849 } else if (array_key_exists($rpc->functionname
, $subscribemethodservices) && !$rpc->enabled
) {
1850 $DB->set_field('mnet_remote_rpc', 'enabled', 1, array('id' => $rpc->id
));
1858 * Given some sort of Zend Reflection function/method object, return a profile array, ready to be serialized and stored
1860 * @param Zend_Server_Reflection_Function_Abstract $function can be any subclass of this object type
1864 function admin_mnet_method_profile(Zend_Server_Reflection_Function_Abstract
$function) {
1865 $protos = $function->getPrototypes();
1866 $proto = array_pop($protos);
1867 $ret = $proto->getReturnValue();
1869 'parameters' => array(),
1871 'type' => $ret->getType(),
1872 'description' => $ret->getDescription(),
1875 foreach ($proto->getParameters() as $p) {
1876 $profile['parameters'][] = array(
1877 'name' => $p->getName(),
1878 'type' => $p->getType(),
1879 'description' => $p->getDescription(),
1887 * This function finds duplicate records (based on combinations of fields that should be unique)
1888 * and then progamatically generated a "most correct" version of the data, update and removing
1889 * records as appropriate
1891 * Thanks to Dan Marsden for help
1893 * @param string $table Table name
1894 * @param array $uniques Array of field names that should be unique
1895 * @param array $fieldstocheck Array of fields to generate "correct" data from (optional)
1898 function upgrade_course_completion_remove_duplicates($table, $uniques, $fieldstocheck = array()) {
1902 $sql_cols = implode(', ', $uniques);
1904 $sql = "SELECT {$sql_cols} FROM {{$table}} GROUP BY {$sql_cols} HAVING (count(id) > 1)";
1905 $duplicates = $DB->get_recordset_sql($sql, array());
1907 // Loop through duplicates
1908 foreach ($duplicates as $duplicate) {
1911 // Generate SQL for finding records with these duplicate uniques
1912 $sql_select = implode(' = ? AND ', $uniques).' = ?'; // builds "fieldname = ? AND fieldname = ?"
1913 $uniq_values = array();
1914 foreach ($uniques as $u) {
1915 $uniq_values[] = $duplicate->$u;
1918 $sql_order = implode(' DESC, ', $uniques).' DESC'; // builds "fieldname DESC, fieldname DESC"
1920 // Get records with these duplicate uniques
1921 $records = $DB->get_records_select(
1928 // Loop through and build a "correct" record, deleting the others
1929 $needsupdate = false;
1931 foreach ($records as $record) {
1933 if ($pointer === 1) { // keep 1st record but delete all others.
1934 $origrecord = $record;
1936 // If we have fields to check, update original record
1937 if ($fieldstocheck) {
1938 // we need to keep the "oldest" of all these fields as the valid completion record.
1939 // but we want to ignore null values
1940 foreach ($fieldstocheck as $f) {
1941 if ($record->$f && (($origrecord->$f > $record->$f) ||
!$origrecord->$f)) {
1942 $origrecord->$f = $record->$f;
1943 $needsupdate = true;
1947 $DB->delete_records($table, array('id' => $record->id
));
1950 if ($needsupdate ||
isset($origrecord->reaggregate
)) {
1951 // If this table has a reaggregate field, update to force recheck on next cron run
1952 if (isset($origrecord->reaggregate
)) {
1953 $origrecord->reaggregate
= time();
1955 $DB->update_record($table, $origrecord);
1961 * Find questions missing an existing category and associate them with
1962 * a category which purpose is to gather them.
1966 function upgrade_save_orphaned_questions() {
1969 // Looking for orphaned questions
1970 $orphans = $DB->record_exists_select('question',
1971 'NOT EXISTS (SELECT 1 FROM {question_categories} WHERE {question_categories}.id = {question}.category)');
1976 // Generate a unique stamp for the orphaned questions category, easier to identify it later on
1977 $uniquestamp = "unknownhost+120719170400+orphan";
1978 $systemcontext = context_system
::instance();
1980 // Create the orphaned category at system level
1981 $cat = $DB->get_record('question_categories', array('stamp' => $uniquestamp,
1982 'contextid' => $systemcontext->id
));
1984 $cat = new stdClass();
1986 $cat->contextid
= $systemcontext->id
;
1987 $cat->name
= get_string('orphanedquestionscategory', 'question');
1988 $cat->info
= get_string('orphanedquestionscategoryinfo', 'question');
1989 $cat->sortorder
= 999;
1990 $cat->stamp
= $uniquestamp;
1991 $cat->id
= $DB->insert_record("question_categories", $cat);
1994 // Set a category to those orphans
1995 $params = array('catid' => $cat->id
);
1996 $DB->execute('UPDATE {question} SET category = :catid WHERE NOT EXISTS
1997 (SELECT 1 FROM {question_categories} WHERE {question_categories}.id = {question}.category)', $params);
2001 * Rename old backup files to current backup files.
2003 * When added the setting 'backup_shortname' (MDL-28657) the backup file names did not contain the id of the course.
2004 * Further we fixed that behaviour by forcing the id to be always present in the file name (MDL-33812).
2005 * This function will explore the backup directory and attempt to rename the previously created files to include
2006 * the id in the name. Doing this will put them back in the process of deleting the excess backups for each course.
2008 * This function manually recreates the file name, instead of using
2009 * {@link backup_plan_dbops::get_default_backup_filename()}, use it carefully if you're using it outside of the
2010 * usual upgrade process.
2012 * @see backup_cron_automated_helper::remove_excess_backups()
2013 * @link http://tracker.moodle.org/browse/MDL-35116
2017 function upgrade_rename_old_backup_files_using_shortname() {
2019 $dir = get_config('backup', 'backup_auto_destination');
2020 $useshortname = get_config('backup', 'backup_shortname');
2021 if (empty($dir) ||
!is_dir($dir) ||
!is_writable($dir)) {
2025 require_once($CFG->dirroot
.'/backup/util/includes/backup_includes.php');
2026 $backupword = str_replace(' ', '_', core_text
::strtolower(get_string('backupfilename')));
2027 $backupword = trim(clean_filename($backupword), '_');
2028 $filename = $backupword . '-' . backup
::FORMAT_MOODLE
. '-' . backup
::TYPE_1COURSE
. '-';
2029 $regex = '#^'.preg_quote($filename, '#').'.*\.mbz$#';
2030 $thirtyapril = strtotime('30 April 2012 00:00');
2032 // Reading the directory.
2033 if (!$files = scandir($dir)) {
2036 foreach ($files as $file) {
2037 // Skip directories and files which do not start with the common prefix.
2038 // This avoids working on files which are not related to this issue.
2039 if (!is_file($dir . '/' . $file) ||
!preg_match($regex, $file)) {
2043 // Extract the information from the XML file.
2045 $bcinfo = backup_general_helper
::get_backup_information_from_mbz($dir . '/' . $file);
2046 } catch (backup_helper_exception
$e) {
2047 // Some error while retrieving the backup informations, skipping...
2051 // Make sure this a course backup.
2052 if ($bcinfo->format
!== backup
::FORMAT_MOODLE ||
$bcinfo->type
!== backup
::TYPE_1COURSE
) {
2056 // Skip the backups created before the short name option was initially introduced (MDL-28657).
2057 // This was integrated on the 2nd of May 2012. Let's play safe with timezone and use the 30th of April.
2058 if ($bcinfo->backup_date
< $thirtyapril) {
2062 // Let's check if the file name contains the ID where it is supposed to be, if it is the case then
2063 // we will skip the file. Of course it could happen that the course ID is identical to the course short name
2064 // even though really unlikely, but then renaming this file is not necessary. If the ID is not found in the
2065 // file name then it was probably the short name which was used.
2066 $idfilename = $filename . $bcinfo->original_course_id
. '-';
2067 $idregex = '#^'.preg_quote($idfilename, '#').'.*\.mbz$#';
2068 if (preg_match($idregex, $file)) {
2072 // Generating the file name manually. We do not use backup_plan_dbops::get_default_backup_filename() because
2073 // it will query the database to get some course information, and the course could not exist any more.
2074 $newname = $filename . $bcinfo->original_course_id
. '-';
2075 if ($useshortname) {
2076 $shortname = str_replace(' ', '_', $bcinfo->original_course_shortname
);
2077 $shortname = core_text
::strtolower(trim(clean_filename($shortname), '_'));
2078 $newname .= $shortname . '-';
2081 $backupdateformat = str_replace(' ', '_', get_string('backupnameformat', 'langconfig'));
2082 $date = userdate($bcinfo->backup_date
, $backupdateformat, 99, false);
2083 $date = core_text
::strtolower(trim(clean_filename($date), '_'));
2086 if (isset($bcinfo->root_settings
['users']) && !$bcinfo->root_settings
['users']) {
2088 } else if (isset($bcinfo->root_settings
['anonymize']) && $bcinfo->root_settings
['anonymize']) {
2093 // Final check before attempting the renaming.
2094 if ($newname == $file ||
file_exists($dir . '/' . $newname)) {
2097 @rename
($dir . '/' . $file, $dir . '/' . $newname);
2102 * Detect duplicate grade item sortorders and resort the
2103 * items to remove them.
2105 function upgrade_grade_item_fix_sortorder() {
2108 // The simple way to fix these sortorder duplicates would be simply to resort each
2109 // affected course. But in order to reduce the impact of this upgrade step we're trying
2110 // to do it more efficiently by doing a series of update statements rather than updating
2111 // every single grade item in affected courses.
2113 $sql = "SELECT DISTINCT g1.courseid
2114 FROM {grade_items} g1
2115 JOIN {grade_items} g2 ON g1.courseid = g2.courseid
2116 WHERE g1.sortorder = g2.sortorder AND g1.id != g2.id
2117 ORDER BY g1.courseid ASC";
2118 foreach ($DB->get_fieldset_sql($sql) as $courseid) {
2119 $transaction = $DB->start_delegated_transaction();
2120 $items = $DB->get_records('grade_items', array('courseid' => $courseid), '', 'id, sortorder, sortorder AS oldsort');
2122 // Get all duplicates in course order, highest sort order, and higest id first so that we can make space at the
2123 // bottom higher end of the sort orders and work down by id.
2124 $sql = "SELECT DISTINCT g1.id, g1.sortorder
2125 FROM {grade_items} g1
2126 JOIN {grade_items} g2 ON g1.courseid = g2.courseid
2127 WHERE g1.sortorder = g2.sortorder AND g1.id != g2.id AND g1.courseid = :courseid
2128 ORDER BY g1.sortorder DESC, g1.id DESC";
2130 // This is the O(N*N) like the database version we're replacing, but at least the constants are a billion times smaller...
2131 foreach ($DB->get_records_sql($sql, array('courseid' => $courseid)) as $duplicate) {
2132 foreach ($items as $item) {
2133 if ($item->sortorder
> $duplicate->sortorder ||
($item->sortorder
== $duplicate->sortorder
&& $item->id
> $duplicate->id
)) {
2134 $item->sortorder +
= 1;
2138 foreach ($items as $item) {
2139 if ($item->sortorder
!= $item->oldsort
) {
2140 $DB->update_record('grade_items', array('id' => $item->id
, 'sortorder' => $item->sortorder
));
2144 $transaction->allow_commit();
2149 * Detect file areas with missing root directory records and add them.
2151 function upgrade_fix_missing_root_folders() {
2154 $transaction = $DB->start_delegated_transaction();
2156 $sql = "SELECT contextid, component, filearea, itemid
2158 WHERE (component <> 'user' OR filearea <> 'draft')
2159 GROUP BY contextid, component, filearea, itemid
2160 HAVING MAX(CASE WHEN filename = '.' AND filepath = '/' THEN 1 ELSE 0 END) = 0";
2162 $rs = $DB->get_recordset_sql($sql);
2163 $defaults = array('filepath' => '/',
2165 'userid' => 0, // Don't rely on any particular user for these system records.
2167 'timecreated' => time(),
2168 'timemodified' => time(),
2169 'contenthash' => sha1(''));
2170 foreach ($rs as $r) {
2171 $pathhash = sha1("/$r->contextid/$r->component/$r->filearea/$r->itemid/.");
2172 $DB->insert_record('files', (array)$r +
$defaults +
2173 array('pathnamehash' => $pathhash));
2176 $transaction->allow_commit();
2180 * Detect draft file areas with missing root directory records and add them.
2182 function upgrade_fix_missing_root_folders_draft() {
2185 $transaction = $DB->start_delegated_transaction();
2187 $sql = "SELECT contextid, itemid, MAX(timecreated) AS timecreated, MAX(timemodified) AS timemodified
2189 WHERE (component = 'user' AND filearea = 'draft')
2190 GROUP BY contextid, itemid
2191 HAVING MAX(CASE WHEN filename = '.' AND filepath = '/' THEN 1 ELSE 0 END) = 0";
2193 $rs = $DB->get_recordset_sql($sql);
2194 $defaults = array('component' => 'user',
2195 'filearea' => 'draft',
2198 'userid' => 0, // Don't rely on any particular user for these system records.
2200 'contenthash' => sha1(''));
2201 foreach ($rs as $r) {
2202 $r->pathnamehash
= sha1("/$r->contextid/user/draft/$r->itemid/.");
2203 $DB->insert_record('files', (array)$r +
$defaults);
2206 $transaction->allow_commit();
2210 * This function verifies that the database is not using an unsupported storage engine.
2212 * @param environment_results $result object to update, if relevant
2213 * @return environment_results|null updated results object, or null if the storage engine is supported
2215 function check_database_storage_engine(environment_results
$result) {
2218 // Check if MySQL is the DB family (this will also be the same for MariaDB).
2219 if ($DB->get_dbfamily() == 'mysql') {
2220 // Get the database engine we will either be using to install the tables, or what we are currently using.
2221 $engine = $DB->get_dbengine();
2222 // Check if MyISAM is the storage engine that will be used, if so, do not proceed and display an error.
2223 if ($engine == 'MyISAM') {
2224 $result->setInfo('unsupported_db_storage_engine');
2225 $result->setStatus(false);
2234 * Method used to check the usage of slasharguments config and display a warning message.
2236 * @param environment_results $result object to update, if relevant.
2237 * @return environment_results|null updated results or null if slasharguments is disabled.
2239 function check_slasharguments(environment_results
$result){
2242 if (!during_initial_install() && empty($CFG->slasharguments
)) {
2243 $result->setInfo('slasharguments');
2244 $result->setStatus(false);
2252 * This function verifies if the database has tables using innoDB Antelope row format.
2254 * @param environment_results $result
2255 * @return environment_results|null updated results object, or null if no Antelope table has been found.
2257 function check_database_tables_row_format(environment_results
$result) {
2260 if ($DB->get_dbfamily() == 'mysql') {
2261 $generator = $DB->get_manager()->generator
;
2263 foreach ($DB->get_tables(false) as $table) {
2264 $columns = $DB->get_columns($table, false);
2265 $size = $generator->guess_antolope_row_size($columns);
2266 $format = $DB->get_row_format($table);
2268 if ($size <= $generator::ANTELOPE_MAX_ROW_SIZE
) {
2272 if ($format === 'Compact' or $format === 'Redundant') {
2273 $result->setInfo('unsupported_db_table_row_format');
2274 $result->setStatus(false);
2284 * Upgrade the minmaxgrade setting.
2286 * This step should only be run for sites running 2.8 or later. Sites using 2.7 will be fine
2287 * using the new default system setting $CFG->grade_minmaxtouse.
2291 function upgrade_minmaxgrade() {
2294 // 2 is a copy of GRADE_MIN_MAX_FROM_GRADE_GRADE.
2297 // Set the course setting when:
2298 // - The system setting does not exist yet.
2299 // - The system seeting is not set to what we'd set the course setting.
2300 $setcoursesetting = !isset($CFG->grade_minmaxtouse
) ||
$CFG->grade_minmaxtouse
!= $settingvalue;
2302 // Identify the courses that have inconsistencies grade_item vs grade_grade.
2303 $sql = "SELECT DISTINCT(gi.courseid)
2304 FROM {grade_grades} gg
2305 JOIN {grade_items} gi
2306 ON gg.itemid = gi.id
2307 WHERE gi.itemtype NOT IN (?, ?)
2308 AND (gg.rawgrademax != gi.grademax OR gg.rawgrademin != gi.grademin)";
2310 $rs = $DB->get_recordset_sql($sql, array('course', 'category'));
2311 foreach ($rs as $record) {
2312 // Flag the course to show a notice in the gradebook.
2313 set_config('show_min_max_grades_changed_' . $record->courseid
, 1);
2315 // Set the appropriate course setting so that grades displayed are not changed.
2316 $configname = 'minmaxtouse';
2317 if ($setcoursesetting &&
2318 !$DB->record_exists('grade_settings', array('courseid' => $record->courseid
, 'name' => $configname))) {
2319 // Do not set the setting when the course already defines it.
2320 $data = new stdClass();
2321 $data->courseid
= $record->courseid
;
2322 $data->name
= $configname;
2323 $data->value
= $settingvalue;
2324 $DB->insert_record('grade_settings', $data);
2327 // Mark the grades to be regraded.
2328 $DB->set_field('grade_items', 'needsupdate', 1, array('courseid' => $record->courseid
));