Moodle release 3.0.3
[moodle.git] / lib / upgradelib.php
blobc44cee9bd6fe3534651178eb4106cea05191f1af
1 <?php
3 // This file is part of Moodle - http://moodle.org/
4 //
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
9 //
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 /**
19 * Various upgrade/install related functions and classes.
21 * @package core
22 * @subpackage upgrade
23 * @copyright 1999 onwards Martin Dougiamas (http://dougiamas.com)
24 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
27 defined('MOODLE_INTERNAL') || die();
29 /** UPGRADE_LOG_NORMAL = 0 */
30 define('UPGRADE_LOG_NORMAL', 0);
31 /** UPGRADE_LOG_NOTICE = 1 */
32 define('UPGRADE_LOG_NOTICE', 1);
33 /** UPGRADE_LOG_ERROR = 2 */
34 define('UPGRADE_LOG_ERROR', 2);
36 /**
37 * Exception indicating unknown error during upgrade.
39 * @package core
40 * @subpackage upgrade
41 * @copyright 2009 Petr Skoda {@link http://skodak.org}
42 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
44 class upgrade_exception extends moodle_exception {
45 function __construct($plugin, $version, $debuginfo=NULL) {
46 global $CFG;
47 $a = (object)array('plugin'=>$plugin, 'version'=>$version);
48 parent::__construct('upgradeerror', 'admin', "$CFG->wwwroot/$CFG->admin/index.php", $a, $debuginfo);
52 /**
53 * Exception indicating downgrade error during upgrade.
55 * @package core
56 * @subpackage upgrade
57 * @copyright 2009 Petr Skoda {@link http://skodak.org}
58 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
60 class downgrade_exception extends moodle_exception {
61 function __construct($plugin, $oldversion, $newversion) {
62 global $CFG;
63 $plugin = is_null($plugin) ? 'moodle' : $plugin;
64 $a = (object)array('plugin'=>$plugin, 'oldversion'=>$oldversion, 'newversion'=>$newversion);
65 parent::__construct('cannotdowngrade', 'debug', "$CFG->wwwroot/$CFG->admin/index.php", $a);
69 /**
70 * @package core
71 * @subpackage upgrade
72 * @copyright 2009 Petr Skoda {@link http://skodak.org}
73 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
75 class upgrade_requires_exception extends moodle_exception {
76 function __construct($plugin, $pluginversion, $currentmoodle, $requiremoodle) {
77 global $CFG;
78 $a = new stdClass();
79 $a->pluginname = $plugin;
80 $a->pluginversion = $pluginversion;
81 $a->currentmoodle = $currentmoodle;
82 $a->requiremoodle = $requiremoodle;
83 parent::__construct('pluginrequirementsnotmet', 'error', "$CFG->wwwroot/$CFG->admin/index.php", $a);
87 /**
88 * @package core
89 * @subpackage upgrade
90 * @copyright 2009 Petr Skoda {@link http://skodak.org}
91 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
93 class plugin_defective_exception extends moodle_exception {
94 function __construct($plugin, $details) {
95 global $CFG;
96 parent::__construct('detectedbrokenplugin', 'error', "$CFG->wwwroot/$CFG->admin/index.php", $plugin, $details);
101 * Misplaced plugin exception.
103 * Note: this should be used only from the upgrade/admin code.
105 * @package core
106 * @subpackage upgrade
107 * @copyright 2009 Petr Skoda {@link http://skodak.org}
108 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
110 class plugin_misplaced_exception extends moodle_exception {
112 * Constructor.
113 * @param string $component the component from version.php
114 * @param string $expected expected directory, null means calculate
115 * @param string $current plugin directory path
117 public function __construct($component, $expected, $current) {
118 global $CFG;
119 if (empty($expected)) {
120 list($type, $plugin) = core_component::normalize_component($component);
121 $plugintypes = core_component::get_plugin_types();
122 if (isset($plugintypes[$type])) {
123 $expected = $plugintypes[$type] . '/' . $plugin;
126 if (strpos($expected, '$CFG->dirroot') !== 0) {
127 $expected = str_replace($CFG->dirroot, '$CFG->dirroot', $expected);
129 if (strpos($current, '$CFG->dirroot') !== 0) {
130 $current = str_replace($CFG->dirroot, '$CFG->dirroot', $current);
132 $a = new stdClass();
133 $a->component = $component;
134 $a->expected = $expected;
135 $a->current = $current;
136 parent::__construct('detectedmisplacedplugin', 'core_plugin', "$CFG->wwwroot/$CFG->admin/index.php", $a);
141 * 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.
146 * @category upgrade
147 * @param int $max_execution_time in seconds (can not be less than 60 s)
149 function upgrade_set_timeout($max_execution_time=300) {
150 global $CFG;
152 if (!isset($CFG->upgraderunning) or $CFG->upgraderunning < time()) {
153 $upgraderunning = get_config(null, 'upgraderunning');
154 } else {
155 $upgraderunning = $CFG->upgraderunning;
158 if (!$upgraderunning) {
159 if (CLI_SCRIPT) {
160 // never stop CLI upgrades
161 $upgraderunning = 0;
162 } else {
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 ;-)
177 return;
180 if (CLI_SCRIPT) {
181 // there is no point in timing out of CLI scripts, admins can stop them if necessary
182 core_php_time_limit::raise();
183 } else {
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.
197 * @category upgrade
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
201 * @return void
203 function upgrade_main_savepoint($result, $version, $allowabort=true) {
204 global $CFG;
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);
212 if (!$result) {
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()) {
229 die;
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.
238 * @category upgrade
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
243 * @return void
245 function upgrade_mod_savepoint($result, $version, $modname, $allowabort=true) {
246 global $DB;
248 $component = 'mod_'.$modname;
250 if (!$result) {
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()) {
273 die;
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.
282 * @category upgrade
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
287 * @return void
289 function upgrade_block_savepoint($result, $version, $blockname, $allowabort=true) {
290 global $DB;
292 $component = 'block_'.$blockname;
294 if (!$result) {
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()) {
317 die;
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.
326 * @category upgrade
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
332 * @return void
334 function upgrade_plugin_savepoint($result, $version, $type, $plugin, $allowabort=true) {
335 global $DB;
337 $component = $type.'_'.$plugin;
339 if (!$result) {
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()) {
357 die;
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
366 * use git).
368 * @return bool true means borked upgrade, false means previous PHP files were properly removed
370 function upgrade_stale_php_files_present() {
371 global $CFG;
373 $someexamplesofremovedfiles = array(
374 // Removed in 3.0.
375 '/mod/lti/grade.php',
376 '/tag/coursetagslib.php',
377 // Removed in 2.9.
378 '/lib/timezone.txt',
379 // Removed in 2.8.
380 '/course/delete_category_form.php',
381 // Removed in 2.7.
382 '/admin/tool/qeupgradehelper/version.php',
383 // Removed in 2.6.
384 '/admin/block.php',
385 '/admin/oacleanup.php',
386 // Removed in 2.5.
387 '/backup/lib.php',
388 '/backup/bb/README.txt',
389 '/lib/excel/test.php',
390 // Removed in 2.4.
391 '/admin/tool/unittest/simpletestlib.php',
392 // Removed in 2.3.
393 '/lib/minify/builder/',
394 // Removed in 2.2.
395 '/lib/yui/3.4.1pr1/',
396 // Removed in 2.2.
397 '/search/cron_php5.php',
398 '/course/report/log/indexlive.php',
399 '/admin/report/backups/index.php',
400 '/admin/generator.php',
401 // Removed in 2.1.
402 '/lib/yui/2.8.0r4/',
403 // Removed in 2.0.
404 '/blocks/admin/block_admin.php',
405 '/blocks/admin_tree/block_admin_tree.php',
408 foreach ($someexamplesofremovedfiles as $file) {
409 if (file_exists($CFG->dirroot.$file)) {
410 return true;
414 return false;
418 * Upgrade plugins
419 * @param string $type The type of plugins that should be updated (e.g. 'enrol', 'qtype')
420 * return void
422 function upgrade_plugins($type, $startcallback, $endcallback, $verbose) {
423 global $CFG, $DB;
425 /// special cases
426 if ($type === 'mod') {
427 return upgrade_plugins_modules($startcallback, $endcallback, $verbose);
428 } else if ($type === 'block') {
429 return upgrade_plugins_blocks($startcallback, $endcallback, $verbose);
432 $plugs = core_component::get_plugin_list($type);
434 foreach ($plugs as $plug=>$fullplug) {
435 // Reset time so that it works when installing a large number of plugins
436 core_php_time_limit::raise(600);
437 $component = clean_param($type.'_'.$plug, PARAM_COMPONENT); // standardised plugin name
439 // check plugin dir is valid name
440 if (empty($component)) {
441 throw new plugin_defective_exception($type.'_'.$plug, 'Invalid plugin directory name.');
444 if (!is_readable($fullplug.'/version.php')) {
445 continue;
448 $plugin = new stdClass();
449 $plugin->version = null;
450 $module = $plugin; // Prevent some notices when plugin placed in wrong directory.
451 require($fullplug.'/version.php'); // defines $plugin with version etc
452 unset($module);
454 if (empty($plugin->version)) {
455 throw new plugin_defective_exception($component, 'Missing $plugin->version number in version.php.');
458 if (empty($plugin->component)) {
459 throw new plugin_defective_exception($component, 'Missing $plugin->component declaration in version.php.');
462 if ($plugin->component !== $component) {
463 throw new plugin_misplaced_exception($plugin->component, null, $fullplug);
466 $plugin->name = $plug;
467 $plugin->fullname = $component;
469 if (!empty($plugin->requires)) {
470 if ($plugin->requires > $CFG->version) {
471 throw new upgrade_requires_exception($component, $plugin->version, $CFG->version, $plugin->requires);
472 } else if ($plugin->requires < 2010000000) {
473 throw new plugin_defective_exception($component, 'Plugin is not compatible with Moodle 2.x or later.');
477 // try to recover from interrupted install.php if needed
478 if (file_exists($fullplug.'/db/install.php')) {
479 if (get_config($plugin->fullname, 'installrunning')) {
480 require_once($fullplug.'/db/install.php');
481 $recover_install_function = 'xmldb_'.$plugin->fullname.'_install_recovery';
482 if (function_exists($recover_install_function)) {
483 $startcallback($component, true, $verbose);
484 $recover_install_function();
485 unset_config('installrunning', $plugin->fullname);
486 update_capabilities($component);
487 log_update_descriptions($component);
488 external_update_descriptions($component);
489 events_update_definition($component);
490 \core\task\manager::reset_scheduled_tasks_for_component($component);
491 message_update_providers($component);
492 \core\message\inbound\manager::update_handlers_for_component($component);
493 if ($type === 'message') {
494 message_update_processors($plug);
496 upgrade_plugin_mnet_functions($component);
497 $endcallback($component, true, $verbose);
502 $installedversion = $DB->get_field('config_plugins', 'value', array('name'=>'version', 'plugin'=>$component)); // No caching!
503 if (empty($installedversion)) { // new installation
504 $startcallback($component, true, $verbose);
506 /// Install tables if defined
507 if (file_exists($fullplug.'/db/install.xml')) {
508 $DB->get_manager()->install_from_xmldb_file($fullplug.'/db/install.xml');
511 /// store version
512 upgrade_plugin_savepoint(true, $plugin->version, $type, $plug, false);
514 /// execute post install file
515 if (file_exists($fullplug.'/db/install.php')) {
516 require_once($fullplug.'/db/install.php');
517 set_config('installrunning', 1, $plugin->fullname);
518 $post_install_function = 'xmldb_'.$plugin->fullname.'_install';
519 $post_install_function();
520 unset_config('installrunning', $plugin->fullname);
523 /// Install various components
524 update_capabilities($component);
525 log_update_descriptions($component);
526 external_update_descriptions($component);
527 events_update_definition($component);
528 \core\task\manager::reset_scheduled_tasks_for_component($component);
529 message_update_providers($component);
530 \core\message\inbound\manager::update_handlers_for_component($component);
531 if ($type === 'message') {
532 message_update_processors($plug);
534 upgrade_plugin_mnet_functions($component);
535 $endcallback($component, true, $verbose);
537 } else if ($installedversion < $plugin->version) { // upgrade
538 /// Run the upgrade function for the plugin.
539 $startcallback($component, false, $verbose);
541 if (is_readable($fullplug.'/db/upgrade.php')) {
542 require_once($fullplug.'/db/upgrade.php'); // defines upgrading function
544 $newupgrade_function = 'xmldb_'.$plugin->fullname.'_upgrade';
545 $result = $newupgrade_function($installedversion);
546 } else {
547 $result = true;
550 $installedversion = $DB->get_field('config_plugins', 'value', array('name'=>'version', 'plugin'=>$component)); // No caching!
551 if ($installedversion < $plugin->version) {
552 // store version if not already there
553 upgrade_plugin_savepoint($result, $plugin->version, $type, $plug, false);
556 /// Upgrade various components
557 update_capabilities($component);
558 log_update_descriptions($component);
559 external_update_descriptions($component);
560 events_update_definition($component);
561 \core\task\manager::reset_scheduled_tasks_for_component($component);
562 message_update_providers($component);
563 \core\message\inbound\manager::update_handlers_for_component($component);
564 if ($type === 'message') {
565 // Ugly hack!
566 message_update_processors($plug);
568 upgrade_plugin_mnet_functions($component);
569 $endcallback($component, false, $verbose);
571 } else if ($installedversion > $plugin->version) {
572 throw new downgrade_exception($component, $installedversion, $plugin->version);
578 * Find and check all modules and load them up or upgrade them if necessary
580 * @global object
581 * @global object
583 function upgrade_plugins_modules($startcallback, $endcallback, $verbose) {
584 global $CFG, $DB;
586 $mods = core_component::get_plugin_list('mod');
588 foreach ($mods as $mod=>$fullmod) {
590 if ($mod === 'NEWMODULE') { // Someone has unzipped the template, ignore it
591 continue;
594 $component = clean_param('mod_'.$mod, PARAM_COMPONENT);
596 // check module dir is valid name
597 if (empty($component)) {
598 throw new plugin_defective_exception('mod_'.$mod, 'Invalid plugin directory name.');
601 if (!is_readable($fullmod.'/version.php')) {
602 throw new plugin_defective_exception($component, 'Missing version.php');
605 $module = new stdClass();
606 $plugin = new stdClass();
607 $plugin->version = null;
608 require($fullmod .'/version.php'); // Defines $plugin with version etc.
610 // Check if the legacy $module syntax is still used.
611 if (!is_object($module) or (count((array)$module) > 0)) {
612 throw new plugin_defective_exception($component, 'Unsupported $module syntax detected in version.php');
615 // Prepare the record for the {modules} table.
616 $module = clone($plugin);
617 unset($module->version);
618 unset($module->component);
619 unset($module->dependencies);
620 unset($module->release);
622 if (empty($plugin->version)) {
623 throw new plugin_defective_exception($component, 'Missing $plugin->version number in version.php.');
626 if (empty($plugin->component)) {
627 throw new plugin_defective_exception($component, 'Missing $plugin->component declaration in version.php.');
630 if ($plugin->component !== $component) {
631 throw new plugin_misplaced_exception($plugin->component, null, $fullmod);
634 if (!empty($plugin->requires)) {
635 if ($plugin->requires > $CFG->version) {
636 throw new upgrade_requires_exception($component, $plugin->version, $CFG->version, $plugin->requires);
637 } else if ($plugin->requires < 2010000000) {
638 throw new plugin_defective_exception($component, 'Plugin is not compatible with Moodle 2.x or later.');
642 if (empty($module->cron)) {
643 $module->cron = 0;
646 // all modules must have en lang pack
647 if (!is_readable("$fullmod/lang/en/$mod.php")) {
648 throw new plugin_defective_exception($component, 'Missing mandatory en language pack.');
651 $module->name = $mod; // The name MUST match the directory
653 $installedversion = $DB->get_field('config_plugins', 'value', array('name'=>'version', 'plugin'=>$component)); // No caching!
655 if (file_exists($fullmod.'/db/install.php')) {
656 if (get_config($module->name, 'installrunning')) {
657 require_once($fullmod.'/db/install.php');
658 $recover_install_function = 'xmldb_'.$module->name.'_install_recovery';
659 if (function_exists($recover_install_function)) {
660 $startcallback($component, true, $verbose);
661 $recover_install_function();
662 unset_config('installrunning', $module->name);
663 // Install various components too
664 update_capabilities($component);
665 log_update_descriptions($component);
666 external_update_descriptions($component);
667 events_update_definition($component);
668 \core\task\manager::reset_scheduled_tasks_for_component($component);
669 message_update_providers($component);
670 \core\message\inbound\manager::update_handlers_for_component($component);
671 upgrade_plugin_mnet_functions($component);
672 $endcallback($component, true, $verbose);
677 if (empty($installedversion)) {
678 $startcallback($component, true, $verbose);
680 /// Execute install.xml (XMLDB) - must be present in all modules
681 $DB->get_manager()->install_from_xmldb_file($fullmod.'/db/install.xml');
683 /// Add record into modules table - may be needed in install.php already
684 $module->id = $DB->insert_record('modules', $module);
685 upgrade_mod_savepoint(true, $plugin->version, $module->name, false);
687 /// Post installation hook - optional
688 if (file_exists("$fullmod/db/install.php")) {
689 require_once("$fullmod/db/install.php");
690 // Set installation running flag, we need to recover after exception or error
691 set_config('installrunning', 1, $module->name);
692 $post_install_function = 'xmldb_'.$module->name.'_install';
693 $post_install_function();
694 unset_config('installrunning', $module->name);
697 /// Install various components
698 update_capabilities($component);
699 log_update_descriptions($component);
700 external_update_descriptions($component);
701 events_update_definition($component);
702 \core\task\manager::reset_scheduled_tasks_for_component($component);
703 message_update_providers($component);
704 \core\message\inbound\manager::update_handlers_for_component($component);
705 upgrade_plugin_mnet_functions($component);
707 $endcallback($component, true, $verbose);
709 } else if ($installedversion < $plugin->version) {
710 /// If versions say that we need to upgrade but no upgrade files are available, notify and continue
711 $startcallback($component, false, $verbose);
713 if (is_readable($fullmod.'/db/upgrade.php')) {
714 require_once($fullmod.'/db/upgrade.php'); // defines new upgrading function
715 $newupgrade_function = 'xmldb_'.$module->name.'_upgrade';
716 $result = $newupgrade_function($installedversion, $module);
717 } else {
718 $result = true;
721 $installedversion = $DB->get_field('config_plugins', 'value', array('name'=>'version', 'plugin'=>$component)); // No caching!
722 $currmodule = $DB->get_record('modules', array('name'=>$module->name));
723 if ($installedversion < $plugin->version) {
724 // store version if not already there
725 upgrade_mod_savepoint($result, $plugin->version, $mod, false);
728 // update cron flag if needed
729 if ($currmodule->cron != $module->cron) {
730 $DB->set_field('modules', 'cron', $module->cron, array('name' => $module->name));
733 // Upgrade various components
734 update_capabilities($component);
735 log_update_descriptions($component);
736 external_update_descriptions($component);
737 events_update_definition($component);
738 \core\task\manager::reset_scheduled_tasks_for_component($component);
739 message_update_providers($component);
740 \core\message\inbound\manager::update_handlers_for_component($component);
741 upgrade_plugin_mnet_functions($component);
743 $endcallback($component, false, $verbose);
745 } else if ($installedversion > $plugin->version) {
746 throw new downgrade_exception($component, $installedversion, $plugin->version);
753 * This function finds all available blocks and install them
754 * into blocks table or do all the upgrade process if newer.
756 * @global object
757 * @global object
759 function upgrade_plugins_blocks($startcallback, $endcallback, $verbose) {
760 global $CFG, $DB;
762 require_once($CFG->dirroot.'/blocks/moodleblock.class.php');
764 $blocktitles = array(); // we do not want duplicate titles
766 //Is this a first install
767 $first_install = null;
769 $blocks = core_component::get_plugin_list('block');
771 foreach ($blocks as $blockname=>$fullblock) {
773 if (is_null($first_install)) {
774 $first_install = ($DB->count_records('block_instances') == 0);
777 if ($blockname === 'NEWBLOCK') { // Someone has unzipped the template, ignore it
778 continue;
781 $component = clean_param('block_'.$blockname, PARAM_COMPONENT);
783 // check block dir is valid name
784 if (empty($component)) {
785 throw new plugin_defective_exception('block_'.$blockname, 'Invalid plugin directory name.');
788 if (!is_readable($fullblock.'/version.php')) {
789 throw new plugin_defective_exception('block/'.$blockname, 'Missing version.php file.');
791 $plugin = new stdClass();
792 $plugin->version = null;
793 $plugin->cron = 0;
794 $module = $plugin; // Prevent some notices when module placed in wrong directory.
795 include($fullblock.'/version.php');
796 unset($module);
797 $block = clone($plugin);
798 unset($block->version);
799 unset($block->component);
800 unset($block->dependencies);
801 unset($block->release);
803 if (empty($plugin->version)) {
804 throw new plugin_defective_exception($component, 'Missing block version number in version.php.');
807 if (empty($plugin->component)) {
808 throw new plugin_defective_exception($component, 'Missing $plugin->component declaration in version.php.');
811 if ($plugin->component !== $component) {
812 throw new plugin_misplaced_exception($plugin->component, null, $fullblock);
815 if (!empty($plugin->requires)) {
816 if ($plugin->requires > $CFG->version) {
817 throw new upgrade_requires_exception($component, $plugin->version, $CFG->version, $plugin->requires);
818 } else if ($plugin->requires < 2010000000) {
819 throw new plugin_defective_exception($component, 'Plugin is not compatible with Moodle 2.x or later.');
823 if (!is_readable($fullblock.'/block_'.$blockname.'.php')) {
824 throw new plugin_defective_exception('block/'.$blockname, 'Missing main block class file.');
826 include_once($fullblock.'/block_'.$blockname.'.php');
828 $classname = 'block_'.$blockname;
830 if (!class_exists($classname)) {
831 throw new plugin_defective_exception($component, 'Can not load main class.');
834 $blockobj = new $classname; // This is what we'll be testing
835 $blocktitle = $blockobj->get_title();
837 // OK, it's as we all hoped. For further tests, the object will do them itself.
838 if (!$blockobj->_self_test()) {
839 throw new plugin_defective_exception($component, 'Self test failed.');
842 $block->name = $blockname; // The name MUST match the directory
844 $installedversion = $DB->get_field('config_plugins', 'value', array('name'=>'version', 'plugin'=>$component)); // No caching!
846 if (file_exists($fullblock.'/db/install.php')) {
847 if (get_config('block_'.$blockname, 'installrunning')) {
848 require_once($fullblock.'/db/install.php');
849 $recover_install_function = 'xmldb_block_'.$blockname.'_install_recovery';
850 if (function_exists($recover_install_function)) {
851 $startcallback($component, true, $verbose);
852 $recover_install_function();
853 unset_config('installrunning', 'block_'.$blockname);
854 // Install various components
855 update_capabilities($component);
856 log_update_descriptions($component);
857 external_update_descriptions($component);
858 events_update_definition($component);
859 \core\task\manager::reset_scheduled_tasks_for_component($component);
860 message_update_providers($component);
861 \core\message\inbound\manager::update_handlers_for_component($component);
862 upgrade_plugin_mnet_functions($component);
863 $endcallback($component, true, $verbose);
868 if (empty($installedversion)) { // block not installed yet, so install it
869 $conflictblock = array_search($blocktitle, $blocktitles);
870 if ($conflictblock !== false) {
871 // Duplicate block titles are not allowed, they confuse people
872 // AND PHP's associative arrays ;)
873 throw new plugin_defective_exception($component, get_string('blocknameconflict', 'error', (object)array('name'=>$block->name, 'conflict'=>$conflictblock)));
875 $startcallback($component, true, $verbose);
877 if (file_exists($fullblock.'/db/install.xml')) {
878 $DB->get_manager()->install_from_xmldb_file($fullblock.'/db/install.xml');
880 $block->id = $DB->insert_record('block', $block);
881 upgrade_block_savepoint(true, $plugin->version, $block->name, false);
883 if (file_exists($fullblock.'/db/install.php')) {
884 require_once($fullblock.'/db/install.php');
885 // Set installation running flag, we need to recover after exception or error
886 set_config('installrunning', 1, 'block_'.$blockname);
887 $post_install_function = 'xmldb_block_'.$blockname.'_install';
888 $post_install_function();
889 unset_config('installrunning', 'block_'.$blockname);
892 $blocktitles[$block->name] = $blocktitle;
894 // Install various components
895 update_capabilities($component);
896 log_update_descriptions($component);
897 external_update_descriptions($component);
898 events_update_definition($component);
899 \core\task\manager::reset_scheduled_tasks_for_component($component);
900 message_update_providers($component);
901 \core\message\inbound\manager::update_handlers_for_component($component);
902 upgrade_plugin_mnet_functions($component);
904 $endcallback($component, true, $verbose);
906 } else if ($installedversion < $plugin->version) {
907 $startcallback($component, false, $verbose);
909 if (is_readable($fullblock.'/db/upgrade.php')) {
910 require_once($fullblock.'/db/upgrade.php'); // defines new upgrading function
911 $newupgrade_function = 'xmldb_block_'.$blockname.'_upgrade';
912 $result = $newupgrade_function($installedversion, $block);
913 } else {
914 $result = true;
917 $installedversion = $DB->get_field('config_plugins', 'value', array('name'=>'version', 'plugin'=>$component)); // No caching!
918 $currblock = $DB->get_record('block', array('name'=>$block->name));
919 if ($installedversion < $plugin->version) {
920 // store version if not already there
921 upgrade_block_savepoint($result, $plugin->version, $block->name, false);
924 if ($currblock->cron != $block->cron) {
925 // update cron flag if needed
926 $DB->set_field('block', 'cron', $block->cron, array('id' => $currblock->id));
929 // Upgrade various components
930 update_capabilities($component);
931 log_update_descriptions($component);
932 external_update_descriptions($component);
933 events_update_definition($component);
934 \core\task\manager::reset_scheduled_tasks_for_component($component);
935 message_update_providers($component);
936 \core\message\inbound\manager::update_handlers_for_component($component);
937 upgrade_plugin_mnet_functions($component);
939 $endcallback($component, false, $verbose);
941 } else if ($installedversion > $plugin->version) {
942 throw new downgrade_exception($component, $installedversion, $plugin->version);
947 // Finally, if we are in the first_install of BLOCKS setup frontpage and admin page blocks
948 if ($first_install) {
949 //Iterate over each course - there should be only site course here now
950 if ($courses = $DB->get_records('course')) {
951 foreach ($courses as $course) {
952 blocks_add_default_course_blocks($course);
956 blocks_add_default_system_blocks();
962 * Log_display description function used during install and upgrade.
964 * @param string $component name of component (moodle, mod_assignment, etc.)
965 * @return void
967 function log_update_descriptions($component) {
968 global $DB;
970 $defpath = core_component::get_component_directory($component).'/db/log.php';
972 if (!file_exists($defpath)) {
973 $DB->delete_records('log_display', array('component'=>$component));
974 return;
977 // load new info
978 $logs = array();
979 include($defpath);
980 $newlogs = array();
981 foreach ($logs as $log) {
982 $newlogs[$log['module'].'-'.$log['action']] = $log; // kind of unique name
984 unset($logs);
985 $logs = $newlogs;
987 $fields = array('module', 'action', 'mtable', 'field');
988 // update all log fist
989 $dblogs = $DB->get_records('log_display', array('component'=>$component));
990 foreach ($dblogs as $dblog) {
991 $name = $dblog->module.'-'.$dblog->action;
993 if (empty($logs[$name])) {
994 $DB->delete_records('log_display', array('id'=>$dblog->id));
995 continue;
998 $log = $logs[$name];
999 unset($logs[$name]);
1001 $update = false;
1002 foreach ($fields as $field) {
1003 if ($dblog->$field != $log[$field]) {
1004 $dblog->$field = $log[$field];
1005 $update = true;
1008 if ($update) {
1009 $DB->update_record('log_display', $dblog);
1012 foreach ($logs as $log) {
1013 $dblog = (object)$log;
1014 $dblog->component = $component;
1015 $DB->insert_record('log_display', $dblog);
1020 * Web service discovery function used during install and upgrade.
1021 * @param string $component name of component (moodle, mod_assignment, etc.)
1022 * @return void
1024 function external_update_descriptions($component) {
1025 global $DB, $CFG;
1027 $defpath = core_component::get_component_directory($component).'/db/services.php';
1029 if (!file_exists($defpath)) {
1030 require_once($CFG->dirroot.'/lib/externallib.php');
1031 external_delete_descriptions($component);
1032 return;
1035 // load new info
1036 $functions = array();
1037 $services = array();
1038 include($defpath);
1040 // update all function fist
1041 $dbfunctions = $DB->get_records('external_functions', array('component'=>$component));
1042 foreach ($dbfunctions as $dbfunction) {
1043 if (empty($functions[$dbfunction->name])) {
1044 $DB->delete_records('external_functions', array('id'=>$dbfunction->id));
1045 // do not delete functions from external_services_functions, beacuse
1046 // we want to notify admins when functions used in custom services disappear
1048 //TODO: this looks wrong, we have to delete it eventually (skodak)
1049 continue;
1052 $function = $functions[$dbfunction->name];
1053 unset($functions[$dbfunction->name]);
1054 $function['classpath'] = empty($function['classpath']) ? null : $function['classpath'];
1056 $update = false;
1057 if ($dbfunction->classname != $function['classname']) {
1058 $dbfunction->classname = $function['classname'];
1059 $update = true;
1061 if ($dbfunction->methodname != $function['methodname']) {
1062 $dbfunction->methodname = $function['methodname'];
1063 $update = true;
1065 if ($dbfunction->classpath != $function['classpath']) {
1066 $dbfunction->classpath = $function['classpath'];
1067 $update = true;
1069 $functioncapabilities = array_key_exists('capabilities', $function)?$function['capabilities']:'';
1070 if ($dbfunction->capabilities != $functioncapabilities) {
1071 $dbfunction->capabilities = $functioncapabilities;
1072 $update = true;
1074 if ($update) {
1075 $DB->update_record('external_functions', $dbfunction);
1078 foreach ($functions as $fname => $function) {
1079 $dbfunction = new stdClass();
1080 $dbfunction->name = $fname;
1081 $dbfunction->classname = $function['classname'];
1082 $dbfunction->methodname = $function['methodname'];
1083 $dbfunction->classpath = empty($function['classpath']) ? null : $function['classpath'];
1084 $dbfunction->component = $component;
1085 $dbfunction->capabilities = array_key_exists('capabilities', $function)?$function['capabilities']:'';
1086 $dbfunction->id = $DB->insert_record('external_functions', $dbfunction);
1088 unset($functions);
1090 // now deal with services
1091 $dbservices = $DB->get_records('external_services', array('component'=>$component));
1092 foreach ($dbservices as $dbservice) {
1093 if (empty($services[$dbservice->name])) {
1094 $DB->delete_records('external_tokens', array('externalserviceid'=>$dbservice->id));
1095 $DB->delete_records('external_services_functions', array('externalserviceid'=>$dbservice->id));
1096 $DB->delete_records('external_services_users', array('externalserviceid'=>$dbservice->id));
1097 $DB->delete_records('external_services', array('id'=>$dbservice->id));
1098 continue;
1100 $service = $services[$dbservice->name];
1101 unset($services[$dbservice->name]);
1102 $service['enabled'] = empty($service['enabled']) ? 0 : $service['enabled'];
1103 $service['requiredcapability'] = empty($service['requiredcapability']) ? null : $service['requiredcapability'];
1104 $service['restrictedusers'] = !isset($service['restrictedusers']) ? 1 : $service['restrictedusers'];
1105 $service['downloadfiles'] = !isset($service['downloadfiles']) ? 0 : $service['downloadfiles'];
1106 $service['uploadfiles'] = !isset($service['uploadfiles']) ? 0 : $service['uploadfiles'];
1107 $service['shortname'] = !isset($service['shortname']) ? null : $service['shortname'];
1109 $update = false;
1110 if ($dbservice->requiredcapability != $service['requiredcapability']) {
1111 $dbservice->requiredcapability = $service['requiredcapability'];
1112 $update = true;
1114 if ($dbservice->restrictedusers != $service['restrictedusers']) {
1115 $dbservice->restrictedusers = $service['restrictedusers'];
1116 $update = true;
1118 if ($dbservice->downloadfiles != $service['downloadfiles']) {
1119 $dbservice->downloadfiles = $service['downloadfiles'];
1120 $update = true;
1122 if ($dbservice->uploadfiles != $service['uploadfiles']) {
1123 $dbservice->uploadfiles = $service['uploadfiles'];
1124 $update = true;
1126 //if shortname is not a PARAM_ALPHANUMEXT, fail (tested here for service update and creation)
1127 if (isset($service['shortname']) and
1128 (clean_param($service['shortname'], PARAM_ALPHANUMEXT) != $service['shortname'])) {
1129 throw new moodle_exception('installserviceshortnameerror', 'webservice', '', $service['shortname']);
1131 if ($dbservice->shortname != $service['shortname']) {
1132 //check that shortname is unique
1133 if (isset($service['shortname'])) { //we currently accepts multiple shortname == null
1134 $existingservice = $DB->get_record('external_services',
1135 array('shortname' => $service['shortname']));
1136 if (!empty($existingservice)) {
1137 throw new moodle_exception('installexistingserviceshortnameerror', 'webservice', '', $service['shortname']);
1140 $dbservice->shortname = $service['shortname'];
1141 $update = true;
1143 if ($update) {
1144 $DB->update_record('external_services', $dbservice);
1147 $functions = $DB->get_records('external_services_functions', array('externalserviceid'=>$dbservice->id));
1148 foreach ($functions as $function) {
1149 $key = array_search($function->functionname, $service['functions']);
1150 if ($key === false) {
1151 $DB->delete_records('external_services_functions', array('id'=>$function->id));
1152 } else {
1153 unset($service['functions'][$key]);
1156 foreach ($service['functions'] as $fname) {
1157 $newf = new stdClass();
1158 $newf->externalserviceid = $dbservice->id;
1159 $newf->functionname = $fname;
1160 $DB->insert_record('external_services_functions', $newf);
1162 unset($functions);
1164 foreach ($services as $name => $service) {
1165 //check that shortname is unique
1166 if (isset($service['shortname'])) { //we currently accepts multiple shortname == null
1167 $existingservice = $DB->get_record('external_services',
1168 array('shortname' => $service['shortname']));
1169 if (!empty($existingservice)) {
1170 throw new moodle_exception('installserviceshortnameerror', 'webservice');
1174 $dbservice = new stdClass();
1175 $dbservice->name = $name;
1176 $dbservice->enabled = empty($service['enabled']) ? 0 : $service['enabled'];
1177 $dbservice->requiredcapability = empty($service['requiredcapability']) ? null : $service['requiredcapability'];
1178 $dbservice->restrictedusers = !isset($service['restrictedusers']) ? 1 : $service['restrictedusers'];
1179 $dbservice->downloadfiles = !isset($service['downloadfiles']) ? 0 : $service['downloadfiles'];
1180 $dbservice->uploadfiles = !isset($service['uploadfiles']) ? 0 : $service['uploadfiles'];
1181 $dbservice->shortname = !isset($service['shortname']) ? null : $service['shortname'];
1182 $dbservice->component = $component;
1183 $dbservice->timecreated = time();
1184 $dbservice->id = $DB->insert_record('external_services', $dbservice);
1185 foreach ($service['functions'] as $fname) {
1186 $newf = new stdClass();
1187 $newf->externalserviceid = $dbservice->id;
1188 $newf->functionname = $fname;
1189 $DB->insert_record('external_services_functions', $newf);
1195 * upgrade logging functions
1197 function upgrade_handle_exception($ex, $plugin = null) {
1198 global $CFG;
1200 // rollback everything, we need to log all upgrade problems
1201 abort_all_db_transactions();
1203 $info = get_exception_info($ex);
1205 // First log upgrade error
1206 upgrade_log(UPGRADE_LOG_ERROR, $plugin, 'Exception: ' . get_class($ex), $info->message, $info->backtrace);
1208 // Always turn on debugging - admins need to know what is going on
1209 set_debugging(DEBUG_DEVELOPER, true);
1211 default_exception_handler($ex, true, $plugin);
1215 * Adds log entry into upgrade_log table
1217 * @param int $type UPGRADE_LOG_NORMAL, UPGRADE_LOG_NOTICE or UPGRADE_LOG_ERROR
1218 * @param string $plugin frankenstyle component name
1219 * @param string $info short description text of log entry
1220 * @param string $details long problem description
1221 * @param string $backtrace string used for errors only
1222 * @return void
1224 function upgrade_log($type, $plugin, $info, $details=null, $backtrace=null) {
1225 global $DB, $USER, $CFG;
1227 if (empty($plugin)) {
1228 $plugin = 'core';
1231 list($plugintype, $pluginname) = core_component::normalize_component($plugin);
1232 $component = is_null($pluginname) ? $plugintype : $plugintype . '_' . $pluginname;
1234 $backtrace = format_backtrace($backtrace, true);
1236 $currentversion = null;
1237 $targetversion = null;
1239 //first try to find out current version number
1240 if ($plugintype === 'core') {
1241 //main
1242 $currentversion = $CFG->version;
1244 $version = null;
1245 include("$CFG->dirroot/version.php");
1246 $targetversion = $version;
1248 } else {
1249 $pluginversion = get_config($component, 'version');
1250 if (!empty($pluginversion)) {
1251 $currentversion = $pluginversion;
1253 $cd = core_component::get_component_directory($component);
1254 if (file_exists("$cd/version.php")) {
1255 $plugin = new stdClass();
1256 $plugin->version = null;
1257 $module = $plugin;
1258 include("$cd/version.php");
1259 $targetversion = $plugin->version;
1263 $log = new stdClass();
1264 $log->type = $type;
1265 $log->plugin = $component;
1266 $log->version = $currentversion;
1267 $log->targetversion = $targetversion;
1268 $log->info = $info;
1269 $log->details = $details;
1270 $log->backtrace = $backtrace;
1271 $log->userid = $USER->id;
1272 $log->timemodified = time();
1273 try {
1274 $DB->insert_record('upgrade_log', $log);
1275 } catch (Exception $ignored) {
1276 // possible during install or 2.0 upgrade
1281 * Marks start of upgrade, blocks any other access to site.
1282 * The upgrade is finished at the end of script or after timeout.
1284 * @global object
1285 * @global object
1286 * @global object
1288 function upgrade_started($preinstall=false) {
1289 global $CFG, $DB, $PAGE, $OUTPUT;
1291 static $started = false;
1293 if ($preinstall) {
1294 ignore_user_abort(true);
1295 upgrade_setup_debug(true);
1297 } else if ($started) {
1298 upgrade_set_timeout(120);
1300 } else {
1301 if (!CLI_SCRIPT and !$PAGE->headerprinted) {
1302 $strupgrade = get_string('upgradingversion', 'admin');
1303 $PAGE->set_pagelayout('maintenance');
1304 upgrade_init_javascript();
1305 $PAGE->set_title($strupgrade.' - Moodle '.$CFG->target_release);
1306 $PAGE->set_heading($strupgrade);
1307 $PAGE->navbar->add($strupgrade);
1308 $PAGE->set_cacheable(false);
1309 echo $OUTPUT->header();
1312 ignore_user_abort(true);
1313 core_shutdown_manager::register_function('upgrade_finished_handler');
1314 upgrade_setup_debug(true);
1315 set_config('upgraderunning', time()+300);
1316 $started = true;
1321 * Internal function - executed if upgrade interrupted.
1323 function upgrade_finished_handler() {
1324 upgrade_finished();
1328 * Indicates upgrade is finished.
1330 * This function may be called repeatedly.
1332 * @global object
1333 * @global object
1335 function upgrade_finished($continueurl=null) {
1336 global $CFG, $DB, $OUTPUT;
1338 if (!empty($CFG->upgraderunning)) {
1339 unset_config('upgraderunning');
1340 // We have to forcefully purge the caches using the writer here.
1341 // This has to be done after we unset the config var. If someone hits the site while this is set they will
1342 // cause the config values to propogate to the caches.
1343 // Caches are purged after the last step in an upgrade but there is several code routines that exceute between
1344 // then and now that leaving a window for things to fall out of sync.
1345 cache_helper::purge_all(true);
1346 upgrade_setup_debug(false);
1347 ignore_user_abort(false);
1348 if ($continueurl) {
1349 echo $OUTPUT->continue_button($continueurl);
1350 echo $OUTPUT->footer();
1351 die;
1357 * @global object
1358 * @global object
1360 function upgrade_setup_debug($starting) {
1361 global $CFG, $DB;
1363 static $originaldebug = null;
1365 if ($starting) {
1366 if ($originaldebug === null) {
1367 $originaldebug = $DB->get_debug();
1369 if (!empty($CFG->upgradeshowsql)) {
1370 $DB->set_debug(true);
1372 } else {
1373 $DB->set_debug($originaldebug);
1377 function print_upgrade_separator() {
1378 if (!CLI_SCRIPT) {
1379 echo '<hr />';
1384 * Default start upgrade callback
1385 * @param string $plugin
1386 * @param bool $installation true if installation, false means upgrade
1388 function print_upgrade_part_start($plugin, $installation, $verbose) {
1389 global $OUTPUT;
1390 if (empty($plugin) or $plugin == 'moodle') {
1391 upgrade_started($installation); // does not store upgrade running flag yet
1392 if ($verbose) {
1393 echo $OUTPUT->heading(get_string('coresystem'));
1395 } else {
1396 upgrade_started();
1397 if ($verbose) {
1398 echo $OUTPUT->heading($plugin);
1401 if ($installation) {
1402 if (empty($plugin) or $plugin == 'moodle') {
1403 // no need to log - log table not yet there ;-)
1404 } else {
1405 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Starting plugin installation');
1407 } else {
1408 if (empty($plugin) or $plugin == 'moodle') {
1409 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Starting core upgrade');
1410 } else {
1411 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Starting plugin upgrade');
1417 * Default end upgrade callback
1418 * @param string $plugin
1419 * @param bool $installation true if installation, false means upgrade
1421 function print_upgrade_part_end($plugin, $installation, $verbose) {
1422 global $OUTPUT;
1423 upgrade_started();
1424 if ($installation) {
1425 if (empty($plugin) or $plugin == 'moodle') {
1426 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Core installed');
1427 } else {
1428 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Plugin installed');
1430 } else {
1431 if (empty($plugin) or $plugin == 'moodle') {
1432 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Core upgraded');
1433 } else {
1434 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Plugin upgraded');
1437 if ($verbose) {
1438 echo $OUTPUT->notification(get_string('success'), 'notifysuccess');
1439 print_upgrade_separator();
1444 * Sets up JS code required for all upgrade scripts.
1445 * @global object
1447 function upgrade_init_javascript() {
1448 global $PAGE;
1449 // scroll to the end of each upgrade page so that ppl see either error or continue button,
1450 // no need to scroll continuously any more, it is enough to jump to end once the footer is printed ;-)
1451 $js = "window.scrollTo(0, 5000000);";
1452 $PAGE->requires->js_init_code($js);
1456 * Try to upgrade the given language pack (or current language)
1458 * @param string $lang the code of the language to update, defaults to the current language
1460 function upgrade_language_pack($lang = null) {
1461 global $CFG;
1463 if (!empty($CFG->skiplangupgrade)) {
1464 return;
1467 if (!file_exists("$CFG->dirroot/$CFG->admin/tool/langimport/lib.php")) {
1468 // weird, somebody uninstalled the import utility
1469 return;
1472 if (!$lang) {
1473 $lang = current_language();
1476 if (!get_string_manager()->translation_exists($lang)) {
1477 return;
1480 get_string_manager()->reset_caches();
1482 if ($lang === 'en') {
1483 return; // Nothing to do
1486 upgrade_started(false);
1488 require_once("$CFG->dirroot/$CFG->admin/tool/langimport/lib.php");
1489 tool_langimport_preupgrade_update($lang);
1491 get_string_manager()->reset_caches();
1493 print_upgrade_separator();
1497 * Install core moodle tables and initialize
1498 * @param float $version target version
1499 * @param bool $verbose
1500 * @return void, may throw exception
1502 function install_core($version, $verbose) {
1503 global $CFG, $DB;
1505 // We can not call purge_all_caches() yet, make sure the temp and cache dirs exist and are empty.
1506 remove_dir($CFG->cachedir.'', true);
1507 make_cache_directory('', true);
1509 remove_dir($CFG->localcachedir.'', true);
1510 make_localcache_directory('', true);
1512 remove_dir($CFG->tempdir.'', true);
1513 make_temp_directory('', true);
1515 remove_dir($CFG->dataroot.'/muc', true);
1516 make_writable_directory($CFG->dataroot.'/muc', true);
1518 try {
1519 core_php_time_limit::raise(600);
1520 print_upgrade_part_start('moodle', true, $verbose); // does not store upgrade running flag
1522 $DB->get_manager()->install_from_xmldb_file("$CFG->libdir/db/install.xml");
1523 upgrade_started(); // we want the flag to be stored in config table ;-)
1525 // set all core default records and default settings
1526 require_once("$CFG->libdir/db/install.php");
1527 xmldb_main_install(); // installs the capabilities too
1529 // store version
1530 upgrade_main_savepoint(true, $version, false);
1532 // Continue with the installation
1533 log_update_descriptions('moodle');
1534 external_update_descriptions('moodle');
1535 events_update_definition('moodle');
1536 \core\task\manager::reset_scheduled_tasks_for_component('moodle');
1537 message_update_providers('moodle');
1538 \core\message\inbound\manager::update_handlers_for_component('moodle');
1540 // Write default settings unconditionally
1541 admin_apply_default_settings(NULL, true);
1543 print_upgrade_part_end(null, true, $verbose);
1545 // Purge all caches. They're disabled but this ensures that we don't have any persistent data just in case something
1546 // during installation didn't use APIs.
1547 cache_helper::purge_all();
1548 } catch (exception $ex) {
1549 upgrade_handle_exception($ex);
1550 } catch (Throwable $ex) {
1551 // Engine errors in PHP7 throw exceptions of type Throwable (this "catch" will be ignored in PHP5).
1552 upgrade_handle_exception($ex);
1557 * Upgrade moodle core
1558 * @param float $version target version
1559 * @param bool $verbose
1560 * @return void, may throw exception
1562 function upgrade_core($version, $verbose) {
1563 global $CFG, $SITE, $DB, $COURSE;
1565 raise_memory_limit(MEMORY_EXTRA);
1567 require_once($CFG->libdir.'/db/upgrade.php'); // Defines upgrades
1569 try {
1570 // Reset caches before any output.
1571 cache_helper::purge_all(true);
1572 purge_all_caches();
1574 // Upgrade current language pack if we can
1575 upgrade_language_pack();
1577 print_upgrade_part_start('moodle', false, $verbose);
1579 // Pre-upgrade scripts for local hack workarounds.
1580 $preupgradefile = "$CFG->dirroot/local/preupgrade.php";
1581 if (file_exists($preupgradefile)) {
1582 core_php_time_limit::raise();
1583 require($preupgradefile);
1584 // Reset upgrade timeout to default.
1585 upgrade_set_timeout();
1588 $result = xmldb_main_upgrade($CFG->version);
1589 if ($version > $CFG->version) {
1590 // store version if not already there
1591 upgrade_main_savepoint($result, $version, false);
1594 // In case structure of 'course' table has been changed and we forgot to update $SITE, re-read it from db.
1595 $SITE = $DB->get_record('course', array('id' => $SITE->id));
1596 $COURSE = clone($SITE);
1598 // perform all other component upgrade routines
1599 update_capabilities('moodle');
1600 log_update_descriptions('moodle');
1601 external_update_descriptions('moodle');
1602 events_update_definition('moodle');
1603 \core\task\manager::reset_scheduled_tasks_for_component('moodle');
1604 message_update_providers('moodle');
1605 \core\message\inbound\manager::update_handlers_for_component('moodle');
1606 // Update core definitions.
1607 cache_helper::update_definitions(true);
1609 // Purge caches again, just to be sure we arn't holding onto old stuff now.
1610 cache_helper::purge_all(true);
1611 purge_all_caches();
1613 // Clean up contexts - more and more stuff depends on existence of paths and contexts
1614 context_helper::cleanup_instances();
1615 context_helper::create_instances(null, false);
1616 context_helper::build_all_paths(false);
1617 $syscontext = context_system::instance();
1618 $syscontext->mark_dirty();
1620 print_upgrade_part_end('moodle', false, $verbose);
1621 } catch (Exception $ex) {
1622 upgrade_handle_exception($ex);
1623 } catch (Throwable $ex) {
1624 // Engine errors in PHP7 throw exceptions of type Throwable (this "catch" will be ignored in PHP5).
1625 upgrade_handle_exception($ex);
1630 * Upgrade/install other parts of moodle
1631 * @param bool $verbose
1632 * @return void, may throw exception
1634 function upgrade_noncore($verbose) {
1635 global $CFG;
1637 raise_memory_limit(MEMORY_EXTRA);
1639 // upgrade all plugins types
1640 try {
1641 // Reset caches before any output.
1642 cache_helper::purge_all(true);
1643 purge_all_caches();
1645 $plugintypes = core_component::get_plugin_types();
1646 foreach ($plugintypes as $type=>$location) {
1647 upgrade_plugins($type, 'print_upgrade_part_start', 'print_upgrade_part_end', $verbose);
1649 // Update cache definitions. Involves scanning each plugin for any changes.
1650 cache_helper::update_definitions();
1651 // Mark the site as upgraded.
1652 set_config('allversionshash', core_component::get_all_versions_hash());
1654 // Purge caches again, just to be sure we arn't holding onto old stuff now.
1655 cache_helper::purge_all(true);
1656 purge_all_caches();
1658 } catch (Exception $ex) {
1659 upgrade_handle_exception($ex);
1660 } catch (Throwable $ex) {
1661 // Engine errors in PHP7 throw exceptions of type Throwable (this "catch" will be ignored in PHP5).
1662 upgrade_handle_exception($ex);
1667 * Checks if the main tables have been installed yet or not.
1669 * Note: we can not use caches here because they might be stale,
1670 * use with care!
1672 * @return bool
1674 function core_tables_exist() {
1675 global $DB;
1677 if (!$tables = $DB->get_tables(false) ) { // No tables yet at all.
1678 return false;
1680 } else { // Check for missing main tables
1681 $mtables = array('config', 'course', 'groupings'); // some tables used in 1.9 and 2.0, preferable something from the start and end of install.xml
1682 foreach ($mtables as $mtable) {
1683 if (!in_array($mtable, $tables)) {
1684 return false;
1687 return true;
1692 * upgrades the mnet rpc definitions for the given component.
1693 * this method doesn't return status, an exception will be thrown in the case of an error
1695 * @param string $component the plugin to upgrade, eg auth_mnet
1697 function upgrade_plugin_mnet_functions($component) {
1698 global $DB, $CFG;
1700 list($type, $plugin) = core_component::normalize_component($component);
1701 $path = core_component::get_plugin_directory($type, $plugin);
1703 $publishes = array();
1704 $subscribes = array();
1705 if (file_exists($path . '/db/mnet.php')) {
1706 require_once($path . '/db/mnet.php'); // $publishes comes from this file
1708 if (empty($publishes)) {
1709 $publishes = array(); // still need this to be able to disable stuff later
1711 if (empty($subscribes)) {
1712 $subscribes = array(); // still need this to be able to disable stuff later
1715 static $servicecache = array();
1717 // rekey an array based on the rpc method for easy lookups later
1718 $publishmethodservices = array();
1719 $subscribemethodservices = array();
1720 foreach($publishes as $servicename => $service) {
1721 if (is_array($service['methods'])) {
1722 foreach($service['methods'] as $methodname) {
1723 $service['servicename'] = $servicename;
1724 $publishmethodservices[$methodname][] = $service;
1729 // Disable functions that don't exist (any more) in the source
1730 // Should these be deleted? What about their permissions records?
1731 foreach ($DB->get_records('mnet_rpc', array('pluginname'=>$plugin, 'plugintype'=>$type), 'functionname ASC ') as $rpc) {
1732 if (!array_key_exists($rpc->functionname, $publishmethodservices) && $rpc->enabled) {
1733 $DB->set_field('mnet_rpc', 'enabled', 0, array('id' => $rpc->id));
1734 } else if (array_key_exists($rpc->functionname, $publishmethodservices) && !$rpc->enabled) {
1735 $DB->set_field('mnet_rpc', 'enabled', 1, array('id' => $rpc->id));
1739 // reflect all the services we're publishing and save them
1740 require_once($CFG->dirroot . '/lib/zend/Zend/Server/Reflection.php');
1741 static $cachedclasses = array(); // to store reflection information in
1742 foreach ($publishes as $service => $data) {
1743 $f = $data['filename'];
1744 $c = $data['classname'];
1745 foreach ($data['methods'] as $method) {
1746 $dataobject = new stdClass();
1747 $dataobject->plugintype = $type;
1748 $dataobject->pluginname = $plugin;
1749 $dataobject->enabled = 1;
1750 $dataobject->classname = $c;
1751 $dataobject->filename = $f;
1753 if (is_string($method)) {
1754 $dataobject->functionname = $method;
1756 } else if (is_array($method)) { // wants to override file or class
1757 $dataobject->functionname = $method['method'];
1758 $dataobject->classname = $method['classname'];
1759 $dataobject->filename = $method['filename'];
1761 $dataobject->xmlrpcpath = $type.'/'.$plugin.'/'.$dataobject->filename.'/'.$method;
1762 $dataobject->static = false;
1764 require_once($path . '/' . $dataobject->filename);
1765 $functionreflect = null; // slightly different ways to get this depending on whether it's a class method or a function
1766 if (!empty($dataobject->classname)) {
1767 if (!class_exists($dataobject->classname)) {
1768 throw new moodle_exception('installnosuchmethod', 'mnet', '', (object)array('method' => $dataobject->functionname, 'class' => $dataobject->classname));
1770 $key = $dataobject->filename . '|' . $dataobject->classname;
1771 if (!array_key_exists($key, $cachedclasses)) { // look to see if we've already got a reflection object
1772 try {
1773 $cachedclasses[$key] = Zend_Server_Reflection::reflectClass($dataobject->classname);
1774 } catch (Zend_Server_Reflection_Exception $e) { // catch these and rethrow them to something more helpful
1775 throw new moodle_exception('installreflectionclasserror', 'mnet', '', (object)array('method' => $dataobject->functionname, 'class' => $dataobject->classname, 'error' => $e->getMessage()));
1778 $r =& $cachedclasses[$key];
1779 if (!$r->hasMethod($dataobject->functionname)) {
1780 throw new moodle_exception('installnosuchmethod', 'mnet', '', (object)array('method' => $dataobject->functionname, 'class' => $dataobject->classname));
1782 // stupid workaround for zend not having a getMethod($name) function
1783 $ms = $r->getMethods();
1784 foreach ($ms as $m) {
1785 if ($m->getName() == $dataobject->functionname) {
1786 $functionreflect = $m;
1787 break;
1790 $dataobject->static = (int)$functionreflect->isStatic();
1791 } else {
1792 if (!function_exists($dataobject->functionname)) {
1793 throw new moodle_exception('installnosuchfunction', 'mnet', '', (object)array('method' => $dataobject->functionname, 'file' => $dataobject->filename));
1795 try {
1796 $functionreflect = Zend_Server_Reflection::reflectFunction($dataobject->functionname);
1797 } catch (Zend_Server_Reflection_Exception $e) { // catch these and rethrow them to something more helpful
1798 throw new moodle_exception('installreflectionfunctionerror', 'mnet', '', (object)array('method' => $dataobject->functionname, '' => $dataobject->filename, 'error' => $e->getMessage()));
1801 $dataobject->profile = serialize(admin_mnet_method_profile($functionreflect));
1802 $dataobject->help = $functionreflect->getDescription();
1804 if ($record_exists = $DB->get_record('mnet_rpc', array('xmlrpcpath'=>$dataobject->xmlrpcpath))) {
1805 $dataobject->id = $record_exists->id;
1806 $dataobject->enabled = $record_exists->enabled;
1807 $DB->update_record('mnet_rpc', $dataobject);
1808 } else {
1809 $dataobject->id = $DB->insert_record('mnet_rpc', $dataobject, true);
1812 // TODO this API versioning must be reworked, here the recently processed method
1813 // sets the service API which may not be correct
1814 foreach ($publishmethodservices[$dataobject->functionname] as $service) {
1815 if ($serviceobj = $DB->get_record('mnet_service', array('name'=>$service['servicename']))) {
1816 $serviceobj->apiversion = $service['apiversion'];
1817 $DB->update_record('mnet_service', $serviceobj);
1818 } else {
1819 $serviceobj = new stdClass();
1820 $serviceobj->name = $service['servicename'];
1821 $serviceobj->description = empty($service['description']) ? '' : $service['description'];
1822 $serviceobj->apiversion = $service['apiversion'];
1823 $serviceobj->offer = 1;
1824 $serviceobj->id = $DB->insert_record('mnet_service', $serviceobj);
1826 $servicecache[$service['servicename']] = $serviceobj;
1827 if (!$DB->record_exists('mnet_service2rpc', array('rpcid'=>$dataobject->id, 'serviceid'=>$serviceobj->id))) {
1828 $obj = new stdClass();
1829 $obj->rpcid = $dataobject->id;
1830 $obj->serviceid = $serviceobj->id;
1831 $DB->insert_record('mnet_service2rpc', $obj, true);
1836 // finished with methods we publish, now do subscribable methods
1837 foreach($subscribes as $service => $methods) {
1838 if (!array_key_exists($service, $servicecache)) {
1839 if (!$serviceobj = $DB->get_record('mnet_service', array('name' => $service))) {
1840 debugging("TODO: skipping unknown service $service - somebody needs to fix MDL-21993");
1841 continue;
1843 $servicecache[$service] = $serviceobj;
1844 } else {
1845 $serviceobj = $servicecache[$service];
1847 foreach ($methods as $method => $xmlrpcpath) {
1848 if (!$rpcid = $DB->get_field('mnet_remote_rpc', 'id', array('xmlrpcpath'=>$xmlrpcpath))) {
1849 $remoterpc = (object)array(
1850 'functionname' => $method,
1851 'xmlrpcpath' => $xmlrpcpath,
1852 'plugintype' => $type,
1853 'pluginname' => $plugin,
1854 'enabled' => 1,
1856 $rpcid = $remoterpc->id = $DB->insert_record('mnet_remote_rpc', $remoterpc, true);
1858 if (!$DB->record_exists('mnet_remote_service2rpc', array('rpcid'=>$rpcid, 'serviceid'=>$serviceobj->id))) {
1859 $obj = new stdClass();
1860 $obj->rpcid = $rpcid;
1861 $obj->serviceid = $serviceobj->id;
1862 $DB->insert_record('mnet_remote_service2rpc', $obj, true);
1864 $subscribemethodservices[$method][] = $service;
1868 foreach ($DB->get_records('mnet_remote_rpc', array('pluginname'=>$plugin, 'plugintype'=>$type), 'functionname ASC ') as $rpc) {
1869 if (!array_key_exists($rpc->functionname, $subscribemethodservices) && $rpc->enabled) {
1870 $DB->set_field('mnet_remote_rpc', 'enabled', 0, array('id' => $rpc->id));
1871 } else if (array_key_exists($rpc->functionname, $subscribemethodservices) && !$rpc->enabled) {
1872 $DB->set_field('mnet_remote_rpc', 'enabled', 1, array('id' => $rpc->id));
1876 return true;
1880 * Given some sort of Zend Reflection function/method object, return a profile array, ready to be serialized and stored
1882 * @param Zend_Server_Reflection_Function_Abstract $function can be any subclass of this object type
1884 * @return array
1886 function admin_mnet_method_profile(Zend_Server_Reflection_Function_Abstract $function) {
1887 $protos = $function->getPrototypes();
1888 $proto = array_pop($protos);
1889 $ret = $proto->getReturnValue();
1890 $profile = array(
1891 'parameters' => array(),
1892 'return' => array(
1893 'type' => $ret->getType(),
1894 'description' => $ret->getDescription(),
1897 foreach ($proto->getParameters() as $p) {
1898 $profile['parameters'][] = array(
1899 'name' => $p->getName(),
1900 'type' => $p->getType(),
1901 'description' => $p->getDescription(),
1904 return $profile;
1909 * This function finds duplicate records (based on combinations of fields that should be unique)
1910 * and then progamatically generated a "most correct" version of the data, update and removing
1911 * records as appropriate
1913 * Thanks to Dan Marsden for help
1915 * @param string $table Table name
1916 * @param array $uniques Array of field names that should be unique
1917 * @param array $fieldstocheck Array of fields to generate "correct" data from (optional)
1918 * @return void
1920 function upgrade_course_completion_remove_duplicates($table, $uniques, $fieldstocheck = array()) {
1921 global $DB;
1923 // Find duplicates
1924 $sql_cols = implode(', ', $uniques);
1926 $sql = "SELECT {$sql_cols} FROM {{$table}} GROUP BY {$sql_cols} HAVING (count(id) > 1)";
1927 $duplicates = $DB->get_recordset_sql($sql, array());
1929 // Loop through duplicates
1930 foreach ($duplicates as $duplicate) {
1931 $pointer = 0;
1933 // Generate SQL for finding records with these duplicate uniques
1934 $sql_select = implode(' = ? AND ', $uniques).' = ?'; // builds "fieldname = ? AND fieldname = ?"
1935 $uniq_values = array();
1936 foreach ($uniques as $u) {
1937 $uniq_values[] = $duplicate->$u;
1940 $sql_order = implode(' DESC, ', $uniques).' DESC'; // builds "fieldname DESC, fieldname DESC"
1942 // Get records with these duplicate uniques
1943 $records = $DB->get_records_select(
1944 $table,
1945 $sql_select,
1946 $uniq_values,
1947 $sql_order
1950 // Loop through and build a "correct" record, deleting the others
1951 $needsupdate = false;
1952 $origrecord = null;
1953 foreach ($records as $record) {
1954 $pointer++;
1955 if ($pointer === 1) { // keep 1st record but delete all others.
1956 $origrecord = $record;
1957 } else {
1958 // If we have fields to check, update original record
1959 if ($fieldstocheck) {
1960 // we need to keep the "oldest" of all these fields as the valid completion record.
1961 // but we want to ignore null values
1962 foreach ($fieldstocheck as $f) {
1963 if ($record->$f && (($origrecord->$f > $record->$f) || !$origrecord->$f)) {
1964 $origrecord->$f = $record->$f;
1965 $needsupdate = true;
1969 $DB->delete_records($table, array('id' => $record->id));
1972 if ($needsupdate || isset($origrecord->reaggregate)) {
1973 // If this table has a reaggregate field, update to force recheck on next cron run
1974 if (isset($origrecord->reaggregate)) {
1975 $origrecord->reaggregate = time();
1977 $DB->update_record($table, $origrecord);
1983 * Find questions missing an existing category and associate them with
1984 * a category which purpose is to gather them.
1986 * @return void
1988 function upgrade_save_orphaned_questions() {
1989 global $DB;
1991 // Looking for orphaned questions
1992 $orphans = $DB->record_exists_select('question',
1993 'NOT EXISTS (SELECT 1 FROM {question_categories} WHERE {question_categories}.id = {question}.category)');
1994 if (!$orphans) {
1995 return;
1998 // Generate a unique stamp for the orphaned questions category, easier to identify it later on
1999 $uniquestamp = "unknownhost+120719170400+orphan";
2000 $systemcontext = context_system::instance();
2002 // Create the orphaned category at system level
2003 $cat = $DB->get_record('question_categories', array('stamp' => $uniquestamp,
2004 'contextid' => $systemcontext->id));
2005 if (!$cat) {
2006 $cat = new stdClass();
2007 $cat->parent = 0;
2008 $cat->contextid = $systemcontext->id;
2009 $cat->name = get_string('orphanedquestionscategory', 'question');
2010 $cat->info = get_string('orphanedquestionscategoryinfo', 'question');
2011 $cat->sortorder = 999;
2012 $cat->stamp = $uniquestamp;
2013 $cat->id = $DB->insert_record("question_categories", $cat);
2016 // Set a category to those orphans
2017 $params = array('catid' => $cat->id);
2018 $DB->execute('UPDATE {question} SET category = :catid WHERE NOT EXISTS
2019 (SELECT 1 FROM {question_categories} WHERE {question_categories}.id = {question}.category)', $params);
2023 * Rename old backup files to current backup files.
2025 * When added the setting 'backup_shortname' (MDL-28657) the backup file names did not contain the id of the course.
2026 * Further we fixed that behaviour by forcing the id to be always present in the file name (MDL-33812).
2027 * This function will explore the backup directory and attempt to rename the previously created files to include
2028 * the id in the name. Doing this will put them back in the process of deleting the excess backups for each course.
2030 * This function manually recreates the file name, instead of using
2031 * {@link backup_plan_dbops::get_default_backup_filename()}, use it carefully if you're using it outside of the
2032 * usual upgrade process.
2034 * @see backup_cron_automated_helper::remove_excess_backups()
2035 * @link http://tracker.moodle.org/browse/MDL-35116
2036 * @return void
2037 * @since Moodle 2.4
2039 function upgrade_rename_old_backup_files_using_shortname() {
2040 global $CFG;
2041 $dir = get_config('backup', 'backup_auto_destination');
2042 $useshortname = get_config('backup', 'backup_shortname');
2043 if (empty($dir) || !is_dir($dir) || !is_writable($dir)) {
2044 return;
2047 require_once($CFG->dirroot.'/backup/util/includes/backup_includes.php');
2048 $backupword = str_replace(' ', '_', core_text::strtolower(get_string('backupfilename')));
2049 $backupword = trim(clean_filename($backupword), '_');
2050 $filename = $backupword . '-' . backup::FORMAT_MOODLE . '-' . backup::TYPE_1COURSE . '-';
2051 $regex = '#^'.preg_quote($filename, '#').'.*\.mbz$#';
2052 $thirtyapril = strtotime('30 April 2012 00:00');
2054 // Reading the directory.
2055 if (!$files = scandir($dir)) {
2056 return;
2058 foreach ($files as $file) {
2059 // Skip directories and files which do not start with the common prefix.
2060 // This avoids working on files which are not related to this issue.
2061 if (!is_file($dir . '/' . $file) || !preg_match($regex, $file)) {
2062 continue;
2065 // Extract the information from the XML file.
2066 try {
2067 $bcinfo = backup_general_helper::get_backup_information_from_mbz($dir . '/' . $file);
2068 } catch (backup_helper_exception $e) {
2069 // Some error while retrieving the backup informations, skipping...
2070 continue;
2073 // Make sure this a course backup.
2074 if ($bcinfo->format !== backup::FORMAT_MOODLE || $bcinfo->type !== backup::TYPE_1COURSE) {
2075 continue;
2078 // Skip the backups created before the short name option was initially introduced (MDL-28657).
2079 // This was integrated on the 2nd of May 2012. Let's play safe with timezone and use the 30th of April.
2080 if ($bcinfo->backup_date < $thirtyapril) {
2081 continue;
2084 // Let's check if the file name contains the ID where it is supposed to be, if it is the case then
2085 // we will skip the file. Of course it could happen that the course ID is identical to the course short name
2086 // even though really unlikely, but then renaming this file is not necessary. If the ID is not found in the
2087 // file name then it was probably the short name which was used.
2088 $idfilename = $filename . $bcinfo->original_course_id . '-';
2089 $idregex = '#^'.preg_quote($idfilename, '#').'.*\.mbz$#';
2090 if (preg_match($idregex, $file)) {
2091 continue;
2094 // Generating the file name manually. We do not use backup_plan_dbops::get_default_backup_filename() because
2095 // it will query the database to get some course information, and the course could not exist any more.
2096 $newname = $filename . $bcinfo->original_course_id . '-';
2097 if ($useshortname) {
2098 $shortname = str_replace(' ', '_', $bcinfo->original_course_shortname);
2099 $shortname = core_text::strtolower(trim(clean_filename($shortname), '_'));
2100 $newname .= $shortname . '-';
2103 $backupdateformat = str_replace(' ', '_', get_string('backupnameformat', 'langconfig'));
2104 $date = userdate($bcinfo->backup_date, $backupdateformat, 99, false);
2105 $date = core_text::strtolower(trim(clean_filename($date), '_'));
2106 $newname .= $date;
2108 if (isset($bcinfo->root_settings['users']) && !$bcinfo->root_settings['users']) {
2109 $newname .= '-nu';
2110 } else if (isset($bcinfo->root_settings['anonymize']) && $bcinfo->root_settings['anonymize']) {
2111 $newname .= '-an';
2113 $newname .= '.mbz';
2115 // Final check before attempting the renaming.
2116 if ($newname == $file || file_exists($dir . '/' . $newname)) {
2117 continue;
2119 @rename($dir . '/' . $file, $dir . '/' . $newname);
2124 * Detect duplicate grade item sortorders and resort the
2125 * items to remove them.
2127 function upgrade_grade_item_fix_sortorder() {
2128 global $DB;
2130 // The simple way to fix these sortorder duplicates would be simply to resort each
2131 // affected course. But in order to reduce the impact of this upgrade step we're trying
2132 // to do it more efficiently by doing a series of update statements rather than updating
2133 // every single grade item in affected courses.
2135 $sql = "SELECT DISTINCT g1.courseid
2136 FROM {grade_items} g1
2137 JOIN {grade_items} g2 ON g1.courseid = g2.courseid
2138 WHERE g1.sortorder = g2.sortorder AND g1.id != g2.id
2139 ORDER BY g1.courseid ASC";
2140 foreach ($DB->get_fieldset_sql($sql) as $courseid) {
2141 $transaction = $DB->start_delegated_transaction();
2142 $items = $DB->get_records('grade_items', array('courseid' => $courseid), '', 'id, sortorder, sortorder AS oldsort');
2144 // Get all duplicates in course order, highest sort order, and higest id first so that we can make space at the
2145 // bottom higher end of the sort orders and work down by id.
2146 $sql = "SELECT DISTINCT g1.id, g1.sortorder
2147 FROM {grade_items} g1
2148 JOIN {grade_items} g2 ON g1.courseid = g2.courseid
2149 WHERE g1.sortorder = g2.sortorder AND g1.id != g2.id AND g1.courseid = :courseid
2150 ORDER BY g1.sortorder DESC, g1.id DESC";
2152 // This is the O(N*N) like the database version we're replacing, but at least the constants are a billion times smaller...
2153 foreach ($DB->get_records_sql($sql, array('courseid' => $courseid)) as $duplicate) {
2154 foreach ($items as $item) {
2155 if ($item->sortorder > $duplicate->sortorder || ($item->sortorder == $duplicate->sortorder && $item->id > $duplicate->id)) {
2156 $item->sortorder += 1;
2160 foreach ($items as $item) {
2161 if ($item->sortorder != $item->oldsort) {
2162 $DB->update_record('grade_items', array('id' => $item->id, 'sortorder' => $item->sortorder));
2166 $transaction->allow_commit();
2171 * Detect file areas with missing root directory records and add them.
2173 function upgrade_fix_missing_root_folders() {
2174 global $DB, $USER;
2176 $transaction = $DB->start_delegated_transaction();
2178 $sql = "SELECT contextid, component, filearea, itemid
2179 FROM {files}
2180 WHERE (component <> 'user' OR filearea <> 'draft')
2181 GROUP BY contextid, component, filearea, itemid
2182 HAVING MAX(CASE WHEN filename = '.' AND filepath = '/' THEN 1 ELSE 0 END) = 0";
2184 $rs = $DB->get_recordset_sql($sql);
2185 $defaults = array('filepath' => '/',
2186 'filename' => '.',
2187 'userid' => 0, // Don't rely on any particular user for these system records.
2188 'filesize' => 0,
2189 'timecreated' => time(),
2190 'timemodified' => time(),
2191 'contenthash' => sha1(''));
2192 foreach ($rs as $r) {
2193 $pathhash = sha1("/$r->contextid/$r->component/$r->filearea/$r->itemid/.");
2194 $DB->insert_record('files', (array)$r + $defaults +
2195 array('pathnamehash' => $pathhash));
2197 $rs->close();
2198 $transaction->allow_commit();
2202 * Detect draft file areas with missing root directory records and add them.
2204 function upgrade_fix_missing_root_folders_draft() {
2205 global $DB;
2207 $transaction = $DB->start_delegated_transaction();
2209 $sql = "SELECT contextid, itemid, MAX(timecreated) AS timecreated, MAX(timemodified) AS timemodified
2210 FROM {files}
2211 WHERE (component = 'user' AND filearea = 'draft')
2212 GROUP BY contextid, itemid
2213 HAVING MAX(CASE WHEN filename = '.' AND filepath = '/' THEN 1 ELSE 0 END) = 0";
2215 $rs = $DB->get_recordset_sql($sql);
2216 $defaults = array('component' => 'user',
2217 'filearea' => 'draft',
2218 'filepath' => '/',
2219 'filename' => '.',
2220 'userid' => 0, // Don't rely on any particular user for these system records.
2221 'filesize' => 0,
2222 'contenthash' => sha1(''));
2223 foreach ($rs as $r) {
2224 $r->pathnamehash = sha1("/$r->contextid/user/draft/$r->itemid/.");
2225 $DB->insert_record('files', (array)$r + $defaults);
2227 $rs->close();
2228 $transaction->allow_commit();
2232 * This function verifies that the database is not using an unsupported storage engine.
2234 * @param environment_results $result object to update, if relevant
2235 * @return environment_results|null updated results object, or null if the storage engine is supported
2237 function check_database_storage_engine(environment_results $result) {
2238 global $DB;
2240 // Check if MySQL is the DB family (this will also be the same for MariaDB).
2241 if ($DB->get_dbfamily() == 'mysql') {
2242 // Get the database engine we will either be using to install the tables, or what we are currently using.
2243 $engine = $DB->get_dbengine();
2244 // Check if MyISAM is the storage engine that will be used, if so, do not proceed and display an error.
2245 if ($engine == 'MyISAM') {
2246 $result->setInfo('unsupported_db_storage_engine');
2247 $result->setStatus(false);
2248 return $result;
2252 return null;
2256 * Method used to check the usage of slasharguments config and display a warning message.
2258 * @param environment_results $result object to update, if relevant.
2259 * @return environment_results|null updated results or null if slasharguments is disabled.
2261 function check_slasharguments(environment_results $result){
2262 global $CFG;
2264 if (!during_initial_install() && empty($CFG->slasharguments)) {
2265 $result->setInfo('slasharguments');
2266 $result->setStatus(false);
2267 return $result;
2270 return null;
2274 * This function verifies if the database has tables using innoDB Antelope row format.
2276 * @param environment_results $result
2277 * @return environment_results|null updated results object, or null if no Antelope table has been found.
2279 function check_database_tables_row_format(environment_results $result) {
2280 global $DB;
2282 if ($DB->get_dbfamily() == 'mysql') {
2283 $generator = $DB->get_manager()->generator;
2285 foreach ($DB->get_tables(false) as $table) {
2286 $columns = $DB->get_columns($table, false);
2287 $size = $generator->guess_antelope_row_size($columns);
2288 $format = $DB->get_row_format($table);
2290 if ($size <= $generator::ANTELOPE_MAX_ROW_SIZE) {
2291 continue;
2294 if ($format === 'Compact' or $format === 'Redundant') {
2295 $result->setInfo('unsupported_db_table_row_format');
2296 $result->setStatus(false);
2297 return $result;
2302 return null;
2306 * Upgrade the minmaxgrade setting.
2308 * This step should only be run for sites running 2.8 or later. Sites using 2.7 will be fine
2309 * using the new default system setting $CFG->grade_minmaxtouse.
2311 * @return void
2313 function upgrade_minmaxgrade() {
2314 global $CFG, $DB;
2316 // 2 is a copy of GRADE_MIN_MAX_FROM_GRADE_GRADE.
2317 $settingvalue = 2;
2319 // Set the course setting when:
2320 // - The system setting does not exist yet.
2321 // - The system seeting is not set to what we'd set the course setting.
2322 $setcoursesetting = !isset($CFG->grade_minmaxtouse) || $CFG->grade_minmaxtouse != $settingvalue;
2324 // Identify the courses that have inconsistencies grade_item vs grade_grade.
2325 $sql = "SELECT DISTINCT(gi.courseid)
2326 FROM {grade_grades} gg
2327 JOIN {grade_items} gi
2328 ON gg.itemid = gi.id
2329 WHERE gi.itemtype NOT IN (?, ?)
2330 AND (gg.rawgrademax != gi.grademax OR gg.rawgrademin != gi.grademin)";
2332 $rs = $DB->get_recordset_sql($sql, array('course', 'category'));
2333 foreach ($rs as $record) {
2334 // Flag the course to show a notice in the gradebook.
2335 set_config('show_min_max_grades_changed_' . $record->courseid, 1);
2337 // Set the appropriate course setting so that grades displayed are not changed.
2338 $configname = 'minmaxtouse';
2339 if ($setcoursesetting &&
2340 !$DB->record_exists('grade_settings', array('courseid' => $record->courseid, 'name' => $configname))) {
2341 // Do not set the setting when the course already defines it.
2342 $data = new stdClass();
2343 $data->courseid = $record->courseid;
2344 $data->name = $configname;
2345 $data->value = $settingvalue;
2346 $DB->insert_record('grade_settings', $data);
2349 // Mark the grades to be regraded.
2350 $DB->set_field('grade_items', 'needsupdate', 1, array('courseid' => $record->courseid));
2352 $rs->close();
2357 * Assert the upgrade key is provided, if it is defined.
2359 * The upgrade key can be defined in the main config.php as $CFG->upgradekey. If
2360 * it is defined there, then its value must be provided every time the site is
2361 * being upgraded, regardless the administrator is logged in or not.
2363 * This is supposed to be used at certain places in /admin/index.php only.
2365 * @param string|null $upgradekeyhash the SHA-1 of the value provided by the user
2367 function check_upgrade_key($upgradekeyhash) {
2368 global $CFG, $PAGE;
2370 if (isset($CFG->config_php_settings['upgradekey'])) {
2371 if ($upgradekeyhash === null or $upgradekeyhash !== sha1($CFG->config_php_settings['upgradekey'])) {
2372 if (!$PAGE->headerprinted) {
2373 $output = $PAGE->get_renderer('core', 'admin');
2374 echo $output->upgradekey_form_page(new moodle_url('/admin/index.php', array('cache' => 0)));
2375 die();
2376 } else {
2377 // This should not happen.
2378 die('Upgrade locked');
2385 * Helper procedure/macro for installing remote plugins at admin/index.php
2387 * Does not return, always redirects or exits.
2389 * @param array $installable list of \core\update\remote_info
2390 * @param bool $confirmed false: display the validation screen, true: proceed installation
2391 * @param string $heading validation screen heading
2392 * @param moodle_url|string|null $continue URL to proceed with installation at the validation screen
2393 * @param moodle_url|string|null $return URL to go back on cancelling at the validation screen
2395 function upgrade_install_plugins(array $installable, $confirmed, $heading='', $continue=null, $return=null) {
2396 global $CFG, $PAGE;
2398 if (empty($return)) {
2399 $return = $PAGE->url;
2402 if (!empty($CFG->disableupdateautodeploy)) {
2403 redirect($return);
2406 if (empty($installable)) {
2407 redirect($return);
2410 $pluginman = core_plugin_manager::instance();
2412 if ($confirmed) {
2413 // Installation confirmed at the validation results page.
2414 if (!$pluginman->install_plugins($installable, true, true)) {
2415 throw new moodle_exception('install_plugins_failed', 'core_plugin', $return);
2418 // Always redirect to admin/index.php to perform the database upgrade.
2419 // Do not throw away the existing $PAGE->url parameters such as
2420 // confirmupgrade or confirmrelease if $PAGE->url is a superset of the
2421 // URL we must go to.
2422 $mustgoto = new moodle_url('/admin/index.php', array('cache' => 0, 'confirmplugincheck' => 0));
2423 if ($mustgoto->compare($PAGE->url, URL_MATCH_PARAMS)) {
2424 redirect($PAGE->url);
2425 } else {
2426 redirect($mustgoto);
2429 } else {
2430 $output = $PAGE->get_renderer('core', 'admin');
2431 echo $output->header();
2432 if ($heading) {
2433 echo $output->heading($heading, 3);
2435 echo html_writer::start_tag('pre', array('class' => 'plugin-install-console'));
2436 $validated = $pluginman->install_plugins($installable, false, false);
2437 echo html_writer::end_tag('pre');
2438 if ($validated) {
2439 echo $output->plugins_management_confirm_buttons($continue, $return);
2440 } else {
2441 echo $output->plugins_management_confirm_buttons(null, $return);
2443 echo $output->footer();
2444 die();