Merge branch 'wip-mdl-52007' of https://github.com/rajeshtaneja/moodle
[moodle.git] / lib / upgradelib.php
blob7832ce18123d84f5dd9407e2be9989e6a9d82497
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);
1554 * Upgrade moodle core
1555 * @param float $version target version
1556 * @param bool $verbose
1557 * @return void, may throw exception
1559 function upgrade_core($version, $verbose) {
1560 global $CFG, $SITE, $DB, $COURSE;
1562 raise_memory_limit(MEMORY_EXTRA);
1564 require_once($CFG->libdir.'/db/upgrade.php'); // Defines upgrades
1566 try {
1567 // Reset caches before any output.
1568 cache_helper::purge_all(true);
1569 purge_all_caches();
1571 // Upgrade current language pack if we can
1572 upgrade_language_pack();
1574 print_upgrade_part_start('moodle', false, $verbose);
1576 // Pre-upgrade scripts for local hack workarounds.
1577 $preupgradefile = "$CFG->dirroot/local/preupgrade.php";
1578 if (file_exists($preupgradefile)) {
1579 core_php_time_limit::raise();
1580 require($preupgradefile);
1581 // Reset upgrade timeout to default.
1582 upgrade_set_timeout();
1585 $result = xmldb_main_upgrade($CFG->version);
1586 if ($version > $CFG->version) {
1587 // store version if not already there
1588 upgrade_main_savepoint($result, $version, false);
1591 // In case structure of 'course' table has been changed and we forgot to update $SITE, re-read it from db.
1592 $SITE = $DB->get_record('course', array('id' => $SITE->id));
1593 $COURSE = clone($SITE);
1595 // perform all other component upgrade routines
1596 update_capabilities('moodle');
1597 log_update_descriptions('moodle');
1598 external_update_descriptions('moodle');
1599 events_update_definition('moodle');
1600 \core\task\manager::reset_scheduled_tasks_for_component('moodle');
1601 message_update_providers('moodle');
1602 \core\message\inbound\manager::update_handlers_for_component('moodle');
1603 // Update core definitions.
1604 cache_helper::update_definitions(true);
1606 // Purge caches again, just to be sure we arn't holding onto old stuff now.
1607 cache_helper::purge_all(true);
1608 purge_all_caches();
1610 // Clean up contexts - more and more stuff depends on existence of paths and contexts
1611 context_helper::cleanup_instances();
1612 context_helper::create_instances(null, false);
1613 context_helper::build_all_paths(false);
1614 $syscontext = context_system::instance();
1615 $syscontext->mark_dirty();
1617 print_upgrade_part_end('moodle', false, $verbose);
1618 } catch (Exception $ex) {
1619 upgrade_handle_exception($ex);
1624 * Upgrade/install other parts of moodle
1625 * @param bool $verbose
1626 * @return void, may throw exception
1628 function upgrade_noncore($verbose) {
1629 global $CFG;
1631 raise_memory_limit(MEMORY_EXTRA);
1633 // upgrade all plugins types
1634 try {
1635 // Reset caches before any output.
1636 cache_helper::purge_all(true);
1637 purge_all_caches();
1639 $plugintypes = core_component::get_plugin_types();
1640 foreach ($plugintypes as $type=>$location) {
1641 upgrade_plugins($type, 'print_upgrade_part_start', 'print_upgrade_part_end', $verbose);
1643 // Update cache definitions. Involves scanning each plugin for any changes.
1644 cache_helper::update_definitions();
1645 // Mark the site as upgraded.
1646 set_config('allversionshash', core_component::get_all_versions_hash());
1648 // Purge caches again, just to be sure we arn't holding onto old stuff now.
1649 cache_helper::purge_all(true);
1650 purge_all_caches();
1652 } catch (Exception $ex) {
1653 upgrade_handle_exception($ex);
1658 * Checks if the main tables have been installed yet or not.
1660 * Note: we can not use caches here because they might be stale,
1661 * use with care!
1663 * @return bool
1665 function core_tables_exist() {
1666 global $DB;
1668 if (!$tables = $DB->get_tables(false) ) { // No tables yet at all.
1669 return false;
1671 } else { // Check for missing main tables
1672 $mtables = array('config', 'course', 'groupings'); // some tables used in 1.9 and 2.0, preferable something from the start and end of install.xml
1673 foreach ($mtables as $mtable) {
1674 if (!in_array($mtable, $tables)) {
1675 return false;
1678 return true;
1683 * upgrades the mnet rpc definitions for the given component.
1684 * this method doesn't return status, an exception will be thrown in the case of an error
1686 * @param string $component the plugin to upgrade, eg auth_mnet
1688 function upgrade_plugin_mnet_functions($component) {
1689 global $DB, $CFG;
1691 list($type, $plugin) = core_component::normalize_component($component);
1692 $path = core_component::get_plugin_directory($type, $plugin);
1694 $publishes = array();
1695 $subscribes = array();
1696 if (file_exists($path . '/db/mnet.php')) {
1697 require_once($path . '/db/mnet.php'); // $publishes comes from this file
1699 if (empty($publishes)) {
1700 $publishes = array(); // still need this to be able to disable stuff later
1702 if (empty($subscribes)) {
1703 $subscribes = array(); // still need this to be able to disable stuff later
1706 static $servicecache = array();
1708 // rekey an array based on the rpc method for easy lookups later
1709 $publishmethodservices = array();
1710 $subscribemethodservices = array();
1711 foreach($publishes as $servicename => $service) {
1712 if (is_array($service['methods'])) {
1713 foreach($service['methods'] as $methodname) {
1714 $service['servicename'] = $servicename;
1715 $publishmethodservices[$methodname][] = $service;
1720 // Disable functions that don't exist (any more) in the source
1721 // Should these be deleted? What about their permissions records?
1722 foreach ($DB->get_records('mnet_rpc', array('pluginname'=>$plugin, 'plugintype'=>$type), 'functionname ASC ') as $rpc) {
1723 if (!array_key_exists($rpc->functionname, $publishmethodservices) && $rpc->enabled) {
1724 $DB->set_field('mnet_rpc', 'enabled', 0, array('id' => $rpc->id));
1725 } else if (array_key_exists($rpc->functionname, $publishmethodservices) && !$rpc->enabled) {
1726 $DB->set_field('mnet_rpc', 'enabled', 1, array('id' => $rpc->id));
1730 // reflect all the services we're publishing and save them
1731 require_once($CFG->dirroot . '/lib/zend/Zend/Server/Reflection.php');
1732 static $cachedclasses = array(); // to store reflection information in
1733 foreach ($publishes as $service => $data) {
1734 $f = $data['filename'];
1735 $c = $data['classname'];
1736 foreach ($data['methods'] as $method) {
1737 $dataobject = new stdClass();
1738 $dataobject->plugintype = $type;
1739 $dataobject->pluginname = $plugin;
1740 $dataobject->enabled = 1;
1741 $dataobject->classname = $c;
1742 $dataobject->filename = $f;
1744 if (is_string($method)) {
1745 $dataobject->functionname = $method;
1747 } else if (is_array($method)) { // wants to override file or class
1748 $dataobject->functionname = $method['method'];
1749 $dataobject->classname = $method['classname'];
1750 $dataobject->filename = $method['filename'];
1752 $dataobject->xmlrpcpath = $type.'/'.$plugin.'/'.$dataobject->filename.'/'.$method;
1753 $dataobject->static = false;
1755 require_once($path . '/' . $dataobject->filename);
1756 $functionreflect = null; // slightly different ways to get this depending on whether it's a class method or a function
1757 if (!empty($dataobject->classname)) {
1758 if (!class_exists($dataobject->classname)) {
1759 throw new moodle_exception('installnosuchmethod', 'mnet', '', (object)array('method' => $dataobject->functionname, 'class' => $dataobject->classname));
1761 $key = $dataobject->filename . '|' . $dataobject->classname;
1762 if (!array_key_exists($key, $cachedclasses)) { // look to see if we've already got a reflection object
1763 try {
1764 $cachedclasses[$key] = Zend_Server_Reflection::reflectClass($dataobject->classname);
1765 } catch (Zend_Server_Reflection_Exception $e) { // catch these and rethrow them to something more helpful
1766 throw new moodle_exception('installreflectionclasserror', 'mnet', '', (object)array('method' => $dataobject->functionname, 'class' => $dataobject->classname, 'error' => $e->getMessage()));
1769 $r =& $cachedclasses[$key];
1770 if (!$r->hasMethod($dataobject->functionname)) {
1771 throw new moodle_exception('installnosuchmethod', 'mnet', '', (object)array('method' => $dataobject->functionname, 'class' => $dataobject->classname));
1773 // stupid workaround for zend not having a getMethod($name) function
1774 $ms = $r->getMethods();
1775 foreach ($ms as $m) {
1776 if ($m->getName() == $dataobject->functionname) {
1777 $functionreflect = $m;
1778 break;
1781 $dataobject->static = (int)$functionreflect->isStatic();
1782 } else {
1783 if (!function_exists($dataobject->functionname)) {
1784 throw new moodle_exception('installnosuchfunction', 'mnet', '', (object)array('method' => $dataobject->functionname, 'file' => $dataobject->filename));
1786 try {
1787 $functionreflect = Zend_Server_Reflection::reflectFunction($dataobject->functionname);
1788 } catch (Zend_Server_Reflection_Exception $e) { // catch these and rethrow them to something more helpful
1789 throw new moodle_exception('installreflectionfunctionerror', 'mnet', '', (object)array('method' => $dataobject->functionname, '' => $dataobject->filename, 'error' => $e->getMessage()));
1792 $dataobject->profile = serialize(admin_mnet_method_profile($functionreflect));
1793 $dataobject->help = $functionreflect->getDescription();
1795 if ($record_exists = $DB->get_record('mnet_rpc', array('xmlrpcpath'=>$dataobject->xmlrpcpath))) {
1796 $dataobject->id = $record_exists->id;
1797 $dataobject->enabled = $record_exists->enabled;
1798 $DB->update_record('mnet_rpc', $dataobject);
1799 } else {
1800 $dataobject->id = $DB->insert_record('mnet_rpc', $dataobject, true);
1803 // TODO this API versioning must be reworked, here the recently processed method
1804 // sets the service API which may not be correct
1805 foreach ($publishmethodservices[$dataobject->functionname] as $service) {
1806 if ($serviceobj = $DB->get_record('mnet_service', array('name'=>$service['servicename']))) {
1807 $serviceobj->apiversion = $service['apiversion'];
1808 $DB->update_record('mnet_service', $serviceobj);
1809 } else {
1810 $serviceobj = new stdClass();
1811 $serviceobj->name = $service['servicename'];
1812 $serviceobj->description = empty($service['description']) ? '' : $service['description'];
1813 $serviceobj->apiversion = $service['apiversion'];
1814 $serviceobj->offer = 1;
1815 $serviceobj->id = $DB->insert_record('mnet_service', $serviceobj);
1817 $servicecache[$service['servicename']] = $serviceobj;
1818 if (!$DB->record_exists('mnet_service2rpc', array('rpcid'=>$dataobject->id, 'serviceid'=>$serviceobj->id))) {
1819 $obj = new stdClass();
1820 $obj->rpcid = $dataobject->id;
1821 $obj->serviceid = $serviceobj->id;
1822 $DB->insert_record('mnet_service2rpc', $obj, true);
1827 // finished with methods we publish, now do subscribable methods
1828 foreach($subscribes as $service => $methods) {
1829 if (!array_key_exists($service, $servicecache)) {
1830 if (!$serviceobj = $DB->get_record('mnet_service', array('name' => $service))) {
1831 debugging("TODO: skipping unknown service $service - somebody needs to fix MDL-21993");
1832 continue;
1834 $servicecache[$service] = $serviceobj;
1835 } else {
1836 $serviceobj = $servicecache[$service];
1838 foreach ($methods as $method => $xmlrpcpath) {
1839 if (!$rpcid = $DB->get_field('mnet_remote_rpc', 'id', array('xmlrpcpath'=>$xmlrpcpath))) {
1840 $remoterpc = (object)array(
1841 'functionname' => $method,
1842 'xmlrpcpath' => $xmlrpcpath,
1843 'plugintype' => $type,
1844 'pluginname' => $plugin,
1845 'enabled' => 1,
1847 $rpcid = $remoterpc->id = $DB->insert_record('mnet_remote_rpc', $remoterpc, true);
1849 if (!$DB->record_exists('mnet_remote_service2rpc', array('rpcid'=>$rpcid, 'serviceid'=>$serviceobj->id))) {
1850 $obj = new stdClass();
1851 $obj->rpcid = $rpcid;
1852 $obj->serviceid = $serviceobj->id;
1853 $DB->insert_record('mnet_remote_service2rpc', $obj, true);
1855 $subscribemethodservices[$method][] = $service;
1859 foreach ($DB->get_records('mnet_remote_rpc', array('pluginname'=>$plugin, 'plugintype'=>$type), 'functionname ASC ') as $rpc) {
1860 if (!array_key_exists($rpc->functionname, $subscribemethodservices) && $rpc->enabled) {
1861 $DB->set_field('mnet_remote_rpc', 'enabled', 0, array('id' => $rpc->id));
1862 } else if (array_key_exists($rpc->functionname, $subscribemethodservices) && !$rpc->enabled) {
1863 $DB->set_field('mnet_remote_rpc', 'enabled', 1, array('id' => $rpc->id));
1867 return true;
1871 * Given some sort of Zend Reflection function/method object, return a profile array, ready to be serialized and stored
1873 * @param Zend_Server_Reflection_Function_Abstract $function can be any subclass of this object type
1875 * @return array
1877 function admin_mnet_method_profile(Zend_Server_Reflection_Function_Abstract $function) {
1878 $protos = $function->getPrototypes();
1879 $proto = array_pop($protos);
1880 $ret = $proto->getReturnValue();
1881 $profile = array(
1882 'parameters' => array(),
1883 'return' => array(
1884 'type' => $ret->getType(),
1885 'description' => $ret->getDescription(),
1888 foreach ($proto->getParameters() as $p) {
1889 $profile['parameters'][] = array(
1890 'name' => $p->getName(),
1891 'type' => $p->getType(),
1892 'description' => $p->getDescription(),
1895 return $profile;
1900 * This function finds duplicate records (based on combinations of fields that should be unique)
1901 * and then progamatically generated a "most correct" version of the data, update and removing
1902 * records as appropriate
1904 * Thanks to Dan Marsden for help
1906 * @param string $table Table name
1907 * @param array $uniques Array of field names that should be unique
1908 * @param array $fieldstocheck Array of fields to generate "correct" data from (optional)
1909 * @return void
1911 function upgrade_course_completion_remove_duplicates($table, $uniques, $fieldstocheck = array()) {
1912 global $DB;
1914 // Find duplicates
1915 $sql_cols = implode(', ', $uniques);
1917 $sql = "SELECT {$sql_cols} FROM {{$table}} GROUP BY {$sql_cols} HAVING (count(id) > 1)";
1918 $duplicates = $DB->get_recordset_sql($sql, array());
1920 // Loop through duplicates
1921 foreach ($duplicates as $duplicate) {
1922 $pointer = 0;
1924 // Generate SQL for finding records with these duplicate uniques
1925 $sql_select = implode(' = ? AND ', $uniques).' = ?'; // builds "fieldname = ? AND fieldname = ?"
1926 $uniq_values = array();
1927 foreach ($uniques as $u) {
1928 $uniq_values[] = $duplicate->$u;
1931 $sql_order = implode(' DESC, ', $uniques).' DESC'; // builds "fieldname DESC, fieldname DESC"
1933 // Get records with these duplicate uniques
1934 $records = $DB->get_records_select(
1935 $table,
1936 $sql_select,
1937 $uniq_values,
1938 $sql_order
1941 // Loop through and build a "correct" record, deleting the others
1942 $needsupdate = false;
1943 $origrecord = null;
1944 foreach ($records as $record) {
1945 $pointer++;
1946 if ($pointer === 1) { // keep 1st record but delete all others.
1947 $origrecord = $record;
1948 } else {
1949 // If we have fields to check, update original record
1950 if ($fieldstocheck) {
1951 // we need to keep the "oldest" of all these fields as the valid completion record.
1952 // but we want to ignore null values
1953 foreach ($fieldstocheck as $f) {
1954 if ($record->$f && (($origrecord->$f > $record->$f) || !$origrecord->$f)) {
1955 $origrecord->$f = $record->$f;
1956 $needsupdate = true;
1960 $DB->delete_records($table, array('id' => $record->id));
1963 if ($needsupdate || isset($origrecord->reaggregate)) {
1964 // If this table has a reaggregate field, update to force recheck on next cron run
1965 if (isset($origrecord->reaggregate)) {
1966 $origrecord->reaggregate = time();
1968 $DB->update_record($table, $origrecord);
1974 * Find questions missing an existing category and associate them with
1975 * a category which purpose is to gather them.
1977 * @return void
1979 function upgrade_save_orphaned_questions() {
1980 global $DB;
1982 // Looking for orphaned questions
1983 $orphans = $DB->record_exists_select('question',
1984 'NOT EXISTS (SELECT 1 FROM {question_categories} WHERE {question_categories}.id = {question}.category)');
1985 if (!$orphans) {
1986 return;
1989 // Generate a unique stamp for the orphaned questions category, easier to identify it later on
1990 $uniquestamp = "unknownhost+120719170400+orphan";
1991 $systemcontext = context_system::instance();
1993 // Create the orphaned category at system level
1994 $cat = $DB->get_record('question_categories', array('stamp' => $uniquestamp,
1995 'contextid' => $systemcontext->id));
1996 if (!$cat) {
1997 $cat = new stdClass();
1998 $cat->parent = 0;
1999 $cat->contextid = $systemcontext->id;
2000 $cat->name = get_string('orphanedquestionscategory', 'question');
2001 $cat->info = get_string('orphanedquestionscategoryinfo', 'question');
2002 $cat->sortorder = 999;
2003 $cat->stamp = $uniquestamp;
2004 $cat->id = $DB->insert_record("question_categories", $cat);
2007 // Set a category to those orphans
2008 $params = array('catid' => $cat->id);
2009 $DB->execute('UPDATE {question} SET category = :catid WHERE NOT EXISTS
2010 (SELECT 1 FROM {question_categories} WHERE {question_categories}.id = {question}.category)', $params);
2014 * Rename old backup files to current backup files.
2016 * When added the setting 'backup_shortname' (MDL-28657) the backup file names did not contain the id of the course.
2017 * Further we fixed that behaviour by forcing the id to be always present in the file name (MDL-33812).
2018 * This function will explore the backup directory and attempt to rename the previously created files to include
2019 * the id in the name. Doing this will put them back in the process of deleting the excess backups for each course.
2021 * This function manually recreates the file name, instead of using
2022 * {@link backup_plan_dbops::get_default_backup_filename()}, use it carefully if you're using it outside of the
2023 * usual upgrade process.
2025 * @see backup_cron_automated_helper::remove_excess_backups()
2026 * @link http://tracker.moodle.org/browse/MDL-35116
2027 * @return void
2028 * @since Moodle 2.4
2030 function upgrade_rename_old_backup_files_using_shortname() {
2031 global $CFG;
2032 $dir = get_config('backup', 'backup_auto_destination');
2033 $useshortname = get_config('backup', 'backup_shortname');
2034 if (empty($dir) || !is_dir($dir) || !is_writable($dir)) {
2035 return;
2038 require_once($CFG->dirroot.'/backup/util/includes/backup_includes.php');
2039 $backupword = str_replace(' ', '_', core_text::strtolower(get_string('backupfilename')));
2040 $backupword = trim(clean_filename($backupword), '_');
2041 $filename = $backupword . '-' . backup::FORMAT_MOODLE . '-' . backup::TYPE_1COURSE . '-';
2042 $regex = '#^'.preg_quote($filename, '#').'.*\.mbz$#';
2043 $thirtyapril = strtotime('30 April 2012 00:00');
2045 // Reading the directory.
2046 if (!$files = scandir($dir)) {
2047 return;
2049 foreach ($files as $file) {
2050 // Skip directories and files which do not start with the common prefix.
2051 // This avoids working on files which are not related to this issue.
2052 if (!is_file($dir . '/' . $file) || !preg_match($regex, $file)) {
2053 continue;
2056 // Extract the information from the XML file.
2057 try {
2058 $bcinfo = backup_general_helper::get_backup_information_from_mbz($dir . '/' . $file);
2059 } catch (backup_helper_exception $e) {
2060 // Some error while retrieving the backup informations, skipping...
2061 continue;
2064 // Make sure this a course backup.
2065 if ($bcinfo->format !== backup::FORMAT_MOODLE || $bcinfo->type !== backup::TYPE_1COURSE) {
2066 continue;
2069 // Skip the backups created before the short name option was initially introduced (MDL-28657).
2070 // This was integrated on the 2nd of May 2012. Let's play safe with timezone and use the 30th of April.
2071 if ($bcinfo->backup_date < $thirtyapril) {
2072 continue;
2075 // Let's check if the file name contains the ID where it is supposed to be, if it is the case then
2076 // we will skip the file. Of course it could happen that the course ID is identical to the course short name
2077 // even though really unlikely, but then renaming this file is not necessary. If the ID is not found in the
2078 // file name then it was probably the short name which was used.
2079 $idfilename = $filename . $bcinfo->original_course_id . '-';
2080 $idregex = '#^'.preg_quote($idfilename, '#').'.*\.mbz$#';
2081 if (preg_match($idregex, $file)) {
2082 continue;
2085 // Generating the file name manually. We do not use backup_plan_dbops::get_default_backup_filename() because
2086 // it will query the database to get some course information, and the course could not exist any more.
2087 $newname = $filename . $bcinfo->original_course_id . '-';
2088 if ($useshortname) {
2089 $shortname = str_replace(' ', '_', $bcinfo->original_course_shortname);
2090 $shortname = core_text::strtolower(trim(clean_filename($shortname), '_'));
2091 $newname .= $shortname . '-';
2094 $backupdateformat = str_replace(' ', '_', get_string('backupnameformat', 'langconfig'));
2095 $date = userdate($bcinfo->backup_date, $backupdateformat, 99, false);
2096 $date = core_text::strtolower(trim(clean_filename($date), '_'));
2097 $newname .= $date;
2099 if (isset($bcinfo->root_settings['users']) && !$bcinfo->root_settings['users']) {
2100 $newname .= '-nu';
2101 } else if (isset($bcinfo->root_settings['anonymize']) && $bcinfo->root_settings['anonymize']) {
2102 $newname .= '-an';
2104 $newname .= '.mbz';
2106 // Final check before attempting the renaming.
2107 if ($newname == $file || file_exists($dir . '/' . $newname)) {
2108 continue;
2110 @rename($dir . '/' . $file, $dir . '/' . $newname);
2115 * Detect duplicate grade item sortorders and resort the
2116 * items to remove them.
2118 function upgrade_grade_item_fix_sortorder() {
2119 global $DB;
2121 // The simple way to fix these sortorder duplicates would be simply to resort each
2122 // affected course. But in order to reduce the impact of this upgrade step we're trying
2123 // to do it more efficiently by doing a series of update statements rather than updating
2124 // every single grade item in affected courses.
2126 $sql = "SELECT DISTINCT g1.courseid
2127 FROM {grade_items} g1
2128 JOIN {grade_items} g2 ON g1.courseid = g2.courseid
2129 WHERE g1.sortorder = g2.sortorder AND g1.id != g2.id
2130 ORDER BY g1.courseid ASC";
2131 foreach ($DB->get_fieldset_sql($sql) as $courseid) {
2132 $transaction = $DB->start_delegated_transaction();
2133 $items = $DB->get_records('grade_items', array('courseid' => $courseid), '', 'id, sortorder, sortorder AS oldsort');
2135 // Get all duplicates in course order, highest sort order, and higest id first so that we can make space at the
2136 // bottom higher end of the sort orders and work down by id.
2137 $sql = "SELECT DISTINCT g1.id, g1.sortorder
2138 FROM {grade_items} g1
2139 JOIN {grade_items} g2 ON g1.courseid = g2.courseid
2140 WHERE g1.sortorder = g2.sortorder AND g1.id != g2.id AND g1.courseid = :courseid
2141 ORDER BY g1.sortorder DESC, g1.id DESC";
2143 // This is the O(N*N) like the database version we're replacing, but at least the constants are a billion times smaller...
2144 foreach ($DB->get_records_sql($sql, array('courseid' => $courseid)) as $duplicate) {
2145 foreach ($items as $item) {
2146 if ($item->sortorder > $duplicate->sortorder || ($item->sortorder == $duplicate->sortorder && $item->id > $duplicate->id)) {
2147 $item->sortorder += 1;
2151 foreach ($items as $item) {
2152 if ($item->sortorder != $item->oldsort) {
2153 $DB->update_record('grade_items', array('id' => $item->id, 'sortorder' => $item->sortorder));
2157 $transaction->allow_commit();
2162 * Detect file areas with missing root directory records and add them.
2164 function upgrade_fix_missing_root_folders() {
2165 global $DB, $USER;
2167 $transaction = $DB->start_delegated_transaction();
2169 $sql = "SELECT contextid, component, filearea, itemid
2170 FROM {files}
2171 WHERE (component <> 'user' OR filearea <> 'draft')
2172 GROUP BY contextid, component, filearea, itemid
2173 HAVING MAX(CASE WHEN filename = '.' AND filepath = '/' THEN 1 ELSE 0 END) = 0";
2175 $rs = $DB->get_recordset_sql($sql);
2176 $defaults = array('filepath' => '/',
2177 'filename' => '.',
2178 'userid' => 0, // Don't rely on any particular user for these system records.
2179 'filesize' => 0,
2180 'timecreated' => time(),
2181 'timemodified' => time(),
2182 'contenthash' => sha1(''));
2183 foreach ($rs as $r) {
2184 $pathhash = sha1("/$r->contextid/$r->component/$r->filearea/$r->itemid/.");
2185 $DB->insert_record('files', (array)$r + $defaults +
2186 array('pathnamehash' => $pathhash));
2188 $rs->close();
2189 $transaction->allow_commit();
2193 * Detect draft file areas with missing root directory records and add them.
2195 function upgrade_fix_missing_root_folders_draft() {
2196 global $DB;
2198 $transaction = $DB->start_delegated_transaction();
2200 $sql = "SELECT contextid, itemid, MAX(timecreated) AS timecreated, MAX(timemodified) AS timemodified
2201 FROM {files}
2202 WHERE (component = 'user' AND filearea = 'draft')
2203 GROUP BY contextid, itemid
2204 HAVING MAX(CASE WHEN filename = '.' AND filepath = '/' THEN 1 ELSE 0 END) = 0";
2206 $rs = $DB->get_recordset_sql($sql);
2207 $defaults = array('component' => 'user',
2208 'filearea' => 'draft',
2209 'filepath' => '/',
2210 'filename' => '.',
2211 'userid' => 0, // Don't rely on any particular user for these system records.
2212 'filesize' => 0,
2213 'contenthash' => sha1(''));
2214 foreach ($rs as $r) {
2215 $r->pathnamehash = sha1("/$r->contextid/user/draft/$r->itemid/.");
2216 $DB->insert_record('files', (array)$r + $defaults);
2218 $rs->close();
2219 $transaction->allow_commit();
2223 * This function verifies that the database is not using an unsupported storage engine.
2225 * @param environment_results $result object to update, if relevant
2226 * @return environment_results|null updated results object, or null if the storage engine is supported
2228 function check_database_storage_engine(environment_results $result) {
2229 global $DB;
2231 // Check if MySQL is the DB family (this will also be the same for MariaDB).
2232 if ($DB->get_dbfamily() == 'mysql') {
2233 // Get the database engine we will either be using to install the tables, or what we are currently using.
2234 $engine = $DB->get_dbengine();
2235 // Check if MyISAM is the storage engine that will be used, if so, do not proceed and display an error.
2236 if ($engine == 'MyISAM') {
2237 $result->setInfo('unsupported_db_storage_engine');
2238 $result->setStatus(false);
2239 return $result;
2243 return null;
2247 * Method used to check the usage of slasharguments config and display a warning message.
2249 * @param environment_results $result object to update, if relevant.
2250 * @return environment_results|null updated results or null if slasharguments is disabled.
2252 function check_slasharguments(environment_results $result){
2253 global $CFG;
2255 if (!during_initial_install() && empty($CFG->slasharguments)) {
2256 $result->setInfo('slasharguments');
2257 $result->setStatus(false);
2258 return $result;
2261 return null;
2265 * This function verifies if the database has tables using innoDB Antelope row format.
2267 * @param environment_results $result
2268 * @return environment_results|null updated results object, or null if no Antelope table has been found.
2270 function check_database_tables_row_format(environment_results $result) {
2271 global $DB;
2273 if ($DB->get_dbfamily() == 'mysql') {
2274 $generator = $DB->get_manager()->generator;
2276 foreach ($DB->get_tables(false) as $table) {
2277 $columns = $DB->get_columns($table, false);
2278 $size = $generator->guess_antelope_row_size($columns);
2279 $format = $DB->get_row_format($table);
2281 if ($size <= $generator::ANTELOPE_MAX_ROW_SIZE) {
2282 continue;
2285 if ($format === 'Compact' or $format === 'Redundant') {
2286 $result->setInfo('unsupported_db_table_row_format');
2287 $result->setStatus(false);
2288 return $result;
2293 return null;
2297 * Upgrade the minmaxgrade setting.
2299 * This step should only be run for sites running 2.8 or later. Sites using 2.7 will be fine
2300 * using the new default system setting $CFG->grade_minmaxtouse.
2302 * @return void
2304 function upgrade_minmaxgrade() {
2305 global $CFG, $DB;
2307 // 2 is a copy of GRADE_MIN_MAX_FROM_GRADE_GRADE.
2308 $settingvalue = 2;
2310 // Set the course setting when:
2311 // - The system setting does not exist yet.
2312 // - The system seeting is not set to what we'd set the course setting.
2313 $setcoursesetting = !isset($CFG->grade_minmaxtouse) || $CFG->grade_minmaxtouse != $settingvalue;
2315 // Identify the courses that have inconsistencies grade_item vs grade_grade.
2316 $sql = "SELECT DISTINCT(gi.courseid)
2317 FROM {grade_grades} gg
2318 JOIN {grade_items} gi
2319 ON gg.itemid = gi.id
2320 WHERE gi.itemtype NOT IN (?, ?)
2321 AND (gg.rawgrademax != gi.grademax OR gg.rawgrademin != gi.grademin)";
2323 $rs = $DB->get_recordset_sql($sql, array('course', 'category'));
2324 foreach ($rs as $record) {
2325 // Flag the course to show a notice in the gradebook.
2326 set_config('show_min_max_grades_changed_' . $record->courseid, 1);
2328 // Set the appropriate course setting so that grades displayed are not changed.
2329 $configname = 'minmaxtouse';
2330 if ($setcoursesetting &&
2331 !$DB->record_exists('grade_settings', array('courseid' => $record->courseid, 'name' => $configname))) {
2332 // Do not set the setting when the course already defines it.
2333 $data = new stdClass();
2334 $data->courseid = $record->courseid;
2335 $data->name = $configname;
2336 $data->value = $settingvalue;
2337 $DB->insert_record('grade_settings', $data);
2340 // Mark the grades to be regraded.
2341 $DB->set_field('grade_items', 'needsupdate', 1, array('courseid' => $record->courseid));
2343 $rs->close();
2348 * Assert the upgrade key is provided, if it is defined.
2350 * The upgrade key can be defined in the main config.php as $CFG->upgradekey. If
2351 * it is defined there, then its value must be provided every time the site is
2352 * being upgraded, regardless the administrator is logged in or not.
2354 * This is supposed to be used at certain places in /admin/index.php only.
2356 * @param string|null $upgradekeyhash the SHA-1 of the value provided by the user
2358 function check_upgrade_key($upgradekeyhash) {
2359 global $CFG, $PAGE;
2361 if (isset($CFG->config_php_settings['upgradekey'])) {
2362 if ($upgradekeyhash === null or $upgradekeyhash !== sha1($CFG->config_php_settings['upgradekey'])) {
2363 if (!$PAGE->headerprinted) {
2364 $output = $PAGE->get_renderer('core', 'admin');
2365 echo $output->upgradekey_form_page(new moodle_url('/admin/index.php', array('cache' => 0)));
2366 die();
2367 } else {
2368 // This should not happen.
2369 die('Upgrade locked');
2376 * Helper procedure/macro for installing remote plugins at admin/index.php
2378 * Does not return, always redirects or exits.
2380 * @param array $installable list of \core\update\remote_info
2381 * @param bool $confirmed false: display the validation screen, true: proceed installation
2382 * @param string $heading validation screen heading
2383 * @param moodle_url|string|null $continue URL to proceed with installation at the validation screen
2384 * @param moodle_url|string|null $return URL to go back on cancelling at the validation screen
2386 function upgrade_install_plugins(array $installable, $confirmed, $heading='', $continue=null, $return=null) {
2387 global $CFG, $PAGE;
2389 if (empty($return)) {
2390 $return = $PAGE->url;
2393 if (!empty($CFG->disableupdateautodeploy)) {
2394 redirect($return);
2397 if (empty($installable)) {
2398 redirect($return);
2401 $pluginman = core_plugin_manager::instance();
2403 if ($confirmed) {
2404 // Installation confirmed at the validation results page.
2405 if (!$pluginman->install_plugins($installable, true, true)) {
2406 throw new moodle_exception('install_plugins_failed', 'core_plugin', $return);
2409 // Always redirect to admin/index.php to perform the database upgrade.
2410 // Do not throw away the existing $PAGE->url parameters such as
2411 // confirmupgrade or confirmrelease if $PAGE->url is a superset of the
2412 // URL we must go to.
2413 $mustgoto = new moodle_url('/admin/index.php', array('cache' => 0, 'confirmplugincheck' => 0));
2414 if ($mustgoto->compare($PAGE->url, URL_MATCH_PARAMS)) {
2415 redirect($PAGE->url);
2416 } else {
2417 redirect($mustgoto);
2420 } else {
2421 $output = $PAGE->get_renderer('core', 'admin');
2422 echo $output->header();
2423 if ($heading) {
2424 echo $output->heading($heading, 3);
2426 echo html_writer::start_tag('pre', array('class' => 'plugin-install-console'));
2427 $validated = $pluginman->install_plugins($installable, false, false);
2428 echo html_writer::end_tag('pre');
2429 if ($validated) {
2430 echo $output->plugins_management_confirm_buttons($continue, $return);
2431 } else {
2432 echo $output->plugins_management_confirm_buttons(null, $return);
2434 echo $output->footer();
2435 die();