Merge branch 'wip-mdl-52020-m29' of https://github.com/rajeshtaneja/moodle into MOODL...
[moodle.git] / lib / upgradelib.php
blob8cc30c3de82a04ccbc65ddc946670a69468eb409
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 2.9.
375 '/lib/timezone.txt',
376 // Removed in 2.8.
377 '/course/delete_category_form.php',
378 // Removed in 2.7.
379 '/admin/tool/qeupgradehelper/version.php',
380 // Removed in 2.6.
381 '/admin/block.php',
382 '/admin/oacleanup.php',
383 // Removed in 2.5.
384 '/backup/lib.php',
385 '/backup/bb/README.txt',
386 '/lib/excel/test.php',
387 // Removed in 2.4.
388 '/admin/tool/unittest/simpletestlib.php',
389 // Removed in 2.3.
390 '/lib/minify/builder/',
391 // Removed in 2.2.
392 '/lib/yui/3.4.1pr1/',
393 // Removed in 2.2.
394 '/search/cron_php5.php',
395 '/course/report/log/indexlive.php',
396 '/admin/report/backups/index.php',
397 '/admin/generator.php',
398 // Removed in 2.1.
399 '/lib/yui/2.8.0r4/',
400 // Removed in 2.0.
401 '/blocks/admin/block_admin.php',
402 '/blocks/admin_tree/block_admin_tree.php',
405 foreach ($someexamplesofremovedfiles as $file) {
406 if (file_exists($CFG->dirroot.$file)) {
407 return true;
411 return false;
415 * Upgrade plugins
416 * @param string $type The type of plugins that should be updated (e.g. 'enrol', 'qtype')
417 * return void
419 function upgrade_plugins($type, $startcallback, $endcallback, $verbose) {
420 global $CFG, $DB;
422 /// special cases
423 if ($type === 'mod') {
424 return upgrade_plugins_modules($startcallback, $endcallback, $verbose);
425 } else if ($type === 'block') {
426 return upgrade_plugins_blocks($startcallback, $endcallback, $verbose);
429 $plugs = core_component::get_plugin_list($type);
431 foreach ($plugs as $plug=>$fullplug) {
432 // Reset time so that it works when installing a large number of plugins
433 core_php_time_limit::raise(600);
434 $component = clean_param($type.'_'.$plug, PARAM_COMPONENT); // standardised plugin name
436 // check plugin dir is valid name
437 if (empty($component)) {
438 throw new plugin_defective_exception($type.'_'.$plug, 'Invalid plugin directory name.');
441 if (!is_readable($fullplug.'/version.php')) {
442 continue;
445 $plugin = new stdClass();
446 $plugin->version = null;
447 $module = $plugin; // Prevent some notices when plugin placed in wrong directory.
448 require($fullplug.'/version.php'); // defines $plugin with version etc
449 unset($module);
451 // if plugin tells us it's full name we may check the location
452 if (isset($plugin->component)) {
453 if ($plugin->component !== $component) {
454 throw new plugin_misplaced_exception($plugin->component, null, $fullplug);
458 if (empty($plugin->version)) {
459 throw new plugin_defective_exception($component, 'Missing version value in version.php');
462 $plugin->name = $plug;
463 $plugin->fullname = $component;
465 if (!empty($plugin->requires)) {
466 if ($plugin->requires > $CFG->version) {
467 throw new upgrade_requires_exception($component, $plugin->version, $CFG->version, $plugin->requires);
468 } else if ($plugin->requires < 2010000000) {
469 throw new plugin_defective_exception($component, 'Plugin is not compatible with Moodle 2.x or later.');
473 // try to recover from interrupted install.php if needed
474 if (file_exists($fullplug.'/db/install.php')) {
475 if (get_config($plugin->fullname, 'installrunning')) {
476 require_once($fullplug.'/db/install.php');
477 $recover_install_function = 'xmldb_'.$plugin->fullname.'_install_recovery';
478 if (function_exists($recover_install_function)) {
479 $startcallback($component, true, $verbose);
480 $recover_install_function();
481 unset_config('installrunning', $plugin->fullname);
482 update_capabilities($component);
483 log_update_descriptions($component);
484 external_update_descriptions($component);
485 events_update_definition($component);
486 \core\task\manager::reset_scheduled_tasks_for_component($component);
487 message_update_providers($component);
488 \core\message\inbound\manager::update_handlers_for_component($component);
489 if ($type === 'message') {
490 message_update_processors($plug);
492 upgrade_plugin_mnet_functions($component);
493 $endcallback($component, true, $verbose);
498 $installedversion = $DB->get_field('config_plugins', 'value', array('name'=>'version', 'plugin'=>$component)); // No caching!
499 if (empty($installedversion)) { // new installation
500 $startcallback($component, true, $verbose);
502 /// Install tables if defined
503 if (file_exists($fullplug.'/db/install.xml')) {
504 $DB->get_manager()->install_from_xmldb_file($fullplug.'/db/install.xml');
507 /// store version
508 upgrade_plugin_savepoint(true, $plugin->version, $type, $plug, false);
510 /// execute post install file
511 if (file_exists($fullplug.'/db/install.php')) {
512 require_once($fullplug.'/db/install.php');
513 set_config('installrunning', 1, $plugin->fullname);
514 $post_install_function = 'xmldb_'.$plugin->fullname.'_install';
515 $post_install_function();
516 unset_config('installrunning', $plugin->fullname);
519 /// Install various components
520 update_capabilities($component);
521 log_update_descriptions($component);
522 external_update_descriptions($component);
523 events_update_definition($component);
524 \core\task\manager::reset_scheduled_tasks_for_component($component);
525 message_update_providers($component);
526 \core\message\inbound\manager::update_handlers_for_component($component);
527 if ($type === 'message') {
528 message_update_processors($plug);
530 upgrade_plugin_mnet_functions($component);
531 $endcallback($component, true, $verbose);
533 } else if ($installedversion < $plugin->version) { // upgrade
534 /// Run the upgrade function for the plugin.
535 $startcallback($component, false, $verbose);
537 if (is_readable($fullplug.'/db/upgrade.php')) {
538 require_once($fullplug.'/db/upgrade.php'); // defines upgrading function
540 $newupgrade_function = 'xmldb_'.$plugin->fullname.'_upgrade';
541 $result = $newupgrade_function($installedversion);
542 } else {
543 $result = true;
546 $installedversion = $DB->get_field('config_plugins', 'value', array('name'=>'version', 'plugin'=>$component)); // No caching!
547 if ($installedversion < $plugin->version) {
548 // store version if not already there
549 upgrade_plugin_savepoint($result, $plugin->version, $type, $plug, false);
552 /// Upgrade various components
553 update_capabilities($component);
554 log_update_descriptions($component);
555 external_update_descriptions($component);
556 events_update_definition($component);
557 \core\task\manager::reset_scheduled_tasks_for_component($component);
558 message_update_providers($component);
559 \core\message\inbound\manager::update_handlers_for_component($component);
560 if ($type === 'message') {
561 // Ugly hack!
562 message_update_processors($plug);
564 upgrade_plugin_mnet_functions($component);
565 $endcallback($component, false, $verbose);
567 } else if ($installedversion > $plugin->version) {
568 throw new downgrade_exception($component, $installedversion, $plugin->version);
574 * Find and check all modules and load them up or upgrade them if necessary
576 * @global object
577 * @global object
579 function upgrade_plugins_modules($startcallback, $endcallback, $verbose) {
580 global $CFG, $DB;
582 $mods = core_component::get_plugin_list('mod');
584 foreach ($mods as $mod=>$fullmod) {
586 if ($mod === 'NEWMODULE') { // Someone has unzipped the template, ignore it
587 continue;
590 $component = clean_param('mod_'.$mod, PARAM_COMPONENT);
592 // check module dir is valid name
593 if (empty($component)) {
594 throw new plugin_defective_exception('mod_'.$mod, 'Invalid plugin directory name.');
597 if (!is_readable($fullmod.'/version.php')) {
598 throw new plugin_defective_exception($component, 'Missing version.php');
601 // TODO: Support for $module will end with Moodle 2.10 by MDL-43896. Was deprecated for Moodle 2.7 by MDL-43040.
602 $plugin = new stdClass();
603 $plugin->version = null;
604 $module = $plugin;
605 require($fullmod .'/version.php'); // Defines $plugin with version etc.
606 $plugin = clone($module);
607 unset($module->version);
608 unset($module->component);
609 unset($module->dependencies);
610 unset($module->release);
612 // if plugin tells us it's full name we may check the location
613 if (isset($plugin->component)) {
614 if ($plugin->component !== $component) {
615 throw new plugin_misplaced_exception($plugin->component, null, $fullmod);
619 if (empty($plugin->version)) {
620 // Version must be always set now!
621 throw new plugin_defective_exception($component, 'Missing version value in version.php');
624 if (!empty($plugin->requires)) {
625 if ($plugin->requires > $CFG->version) {
626 throw new upgrade_requires_exception($component, $plugin->version, $CFG->version, $plugin->requires);
627 } else if ($plugin->requires < 2010000000) {
628 throw new plugin_defective_exception($component, 'Plugin is not compatible with Moodle 2.x or later.');
632 if (empty($module->cron)) {
633 $module->cron = 0;
636 // all modules must have en lang pack
637 if (!is_readable("$fullmod/lang/en/$mod.php")) {
638 throw new plugin_defective_exception($component, 'Missing mandatory en language pack.');
641 $module->name = $mod; // The name MUST match the directory
643 $installedversion = $DB->get_field('config_plugins', 'value', array('name'=>'version', 'plugin'=>$component)); // No caching!
645 if (file_exists($fullmod.'/db/install.php')) {
646 if (get_config($module->name, 'installrunning')) {
647 require_once($fullmod.'/db/install.php');
648 $recover_install_function = 'xmldb_'.$module->name.'_install_recovery';
649 if (function_exists($recover_install_function)) {
650 $startcallback($component, true, $verbose);
651 $recover_install_function();
652 unset_config('installrunning', $module->name);
653 // Install various components too
654 update_capabilities($component);
655 log_update_descriptions($component);
656 external_update_descriptions($component);
657 events_update_definition($component);
658 \core\task\manager::reset_scheduled_tasks_for_component($component);
659 message_update_providers($component);
660 \core\message\inbound\manager::update_handlers_for_component($component);
661 upgrade_plugin_mnet_functions($component);
662 $endcallback($component, true, $verbose);
667 if (empty($installedversion)) {
668 $startcallback($component, true, $verbose);
670 /// Execute install.xml (XMLDB) - must be present in all modules
671 $DB->get_manager()->install_from_xmldb_file($fullmod.'/db/install.xml');
673 /// Add record into modules table - may be needed in install.php already
674 $module->id = $DB->insert_record('modules', $module);
675 upgrade_mod_savepoint(true, $plugin->version, $module->name, false);
677 /// Post installation hook - optional
678 if (file_exists("$fullmod/db/install.php")) {
679 require_once("$fullmod/db/install.php");
680 // Set installation running flag, we need to recover after exception or error
681 set_config('installrunning', 1, $module->name);
682 $post_install_function = 'xmldb_'.$module->name.'_install';
683 $post_install_function();
684 unset_config('installrunning', $module->name);
687 /// Install various components
688 update_capabilities($component);
689 log_update_descriptions($component);
690 external_update_descriptions($component);
691 events_update_definition($component);
692 \core\task\manager::reset_scheduled_tasks_for_component($component);
693 message_update_providers($component);
694 \core\message\inbound\manager::update_handlers_for_component($component);
695 upgrade_plugin_mnet_functions($component);
697 $endcallback($component, true, $verbose);
699 } else if ($installedversion < $plugin->version) {
700 /// If versions say that we need to upgrade but no upgrade files are available, notify and continue
701 $startcallback($component, false, $verbose);
703 if (is_readable($fullmod.'/db/upgrade.php')) {
704 require_once($fullmod.'/db/upgrade.php'); // defines new upgrading function
705 $newupgrade_function = 'xmldb_'.$module->name.'_upgrade';
706 $result = $newupgrade_function($installedversion, $module);
707 } else {
708 $result = true;
711 $installedversion = $DB->get_field('config_plugins', 'value', array('name'=>'version', 'plugin'=>$component)); // No caching!
712 $currmodule = $DB->get_record('modules', array('name'=>$module->name));
713 if ($installedversion < $plugin->version) {
714 // store version if not already there
715 upgrade_mod_savepoint($result, $plugin->version, $mod, false);
718 // update cron flag if needed
719 if ($currmodule->cron != $module->cron) {
720 $DB->set_field('modules', 'cron', $module->cron, array('name' => $module->name));
723 // Upgrade various components
724 update_capabilities($component);
725 log_update_descriptions($component);
726 external_update_descriptions($component);
727 events_update_definition($component);
728 \core\task\manager::reset_scheduled_tasks_for_component($component);
729 message_update_providers($component);
730 \core\message\inbound\manager::update_handlers_for_component($component);
731 upgrade_plugin_mnet_functions($component);
733 $endcallback($component, false, $verbose);
735 } else if ($installedversion > $plugin->version) {
736 throw new downgrade_exception($component, $installedversion, $plugin->version);
743 * This function finds all available blocks and install them
744 * into blocks table or do all the upgrade process if newer.
746 * @global object
747 * @global object
749 function upgrade_plugins_blocks($startcallback, $endcallback, $verbose) {
750 global $CFG, $DB;
752 require_once($CFG->dirroot.'/blocks/moodleblock.class.php');
754 $blocktitles = array(); // we do not want duplicate titles
756 //Is this a first install
757 $first_install = null;
759 $blocks = core_component::get_plugin_list('block');
761 foreach ($blocks as $blockname=>$fullblock) {
763 if (is_null($first_install)) {
764 $first_install = ($DB->count_records('block_instances') == 0);
767 if ($blockname === 'NEWBLOCK') { // Someone has unzipped the template, ignore it
768 continue;
771 $component = clean_param('block_'.$blockname, PARAM_COMPONENT);
773 // check block dir is valid name
774 if (empty($component)) {
775 throw new plugin_defective_exception('block_'.$blockname, 'Invalid plugin directory name.');
778 if (!is_readable($fullblock.'/version.php')) {
779 throw new plugin_defective_exception('block/'.$blockname, 'Missing version.php file.');
781 $plugin = new stdClass();
782 $plugin->version = null;
783 $plugin->cron = 0;
784 $module = $plugin; // Prevent some notices when module placed in wrong directory.
785 include($fullblock.'/version.php');
786 unset($module);
787 $block = clone($plugin);
788 unset($block->version);
789 unset($block->component);
790 unset($block->dependencies);
791 unset($block->release);
793 // if plugin tells us it's full name we may check the location
794 if (isset($plugin->component)) {
795 if ($plugin->component !== $component) {
796 throw new plugin_misplaced_exception($plugin->component, null, $fullblock);
800 if (empty($plugin->version)) {
801 throw new plugin_defective_exception($component, 'Missing block version.');
804 if (!empty($plugin->requires)) {
805 if ($plugin->requires > $CFG->version) {
806 throw new upgrade_requires_exception($component, $plugin->version, $CFG->version, $plugin->requires);
807 } else if ($plugin->requires < 2010000000) {
808 throw new plugin_defective_exception($component, 'Plugin is not compatible with Moodle 2.x or later.');
812 if (!is_readable($fullblock.'/block_'.$blockname.'.php')) {
813 throw new plugin_defective_exception('block/'.$blockname, 'Missing main block class file.');
815 include_once($fullblock.'/block_'.$blockname.'.php');
817 $classname = 'block_'.$blockname;
819 if (!class_exists($classname)) {
820 throw new plugin_defective_exception($component, 'Can not load main class.');
823 $blockobj = new $classname; // This is what we'll be testing
824 $blocktitle = $blockobj->get_title();
826 // OK, it's as we all hoped. For further tests, the object will do them itself.
827 if (!$blockobj->_self_test()) {
828 throw new plugin_defective_exception($component, 'Self test failed.');
831 $block->name = $blockname; // The name MUST match the directory
833 $installedversion = $DB->get_field('config_plugins', 'value', array('name'=>'version', 'plugin'=>$component)); // No caching!
835 if (file_exists($fullblock.'/db/install.php')) {
836 if (get_config('block_'.$blockname, 'installrunning')) {
837 require_once($fullblock.'/db/install.php');
838 $recover_install_function = 'xmldb_block_'.$blockname.'_install_recovery';
839 if (function_exists($recover_install_function)) {
840 $startcallback($component, true, $verbose);
841 $recover_install_function();
842 unset_config('installrunning', 'block_'.$blockname);
843 // Install various components
844 update_capabilities($component);
845 log_update_descriptions($component);
846 external_update_descriptions($component);
847 events_update_definition($component);
848 \core\task\manager::reset_scheduled_tasks_for_component($component);
849 message_update_providers($component);
850 \core\message\inbound\manager::update_handlers_for_component($component);
851 upgrade_plugin_mnet_functions($component);
852 $endcallback($component, true, $verbose);
857 if (empty($installedversion)) { // block not installed yet, so install it
858 $conflictblock = array_search($blocktitle, $blocktitles);
859 if ($conflictblock !== false) {
860 // Duplicate block titles are not allowed, they confuse people
861 // AND PHP's associative arrays ;)
862 throw new plugin_defective_exception($component, get_string('blocknameconflict', 'error', (object)array('name'=>$block->name, 'conflict'=>$conflictblock)));
864 $startcallback($component, true, $verbose);
866 if (file_exists($fullblock.'/db/install.xml')) {
867 $DB->get_manager()->install_from_xmldb_file($fullblock.'/db/install.xml');
869 $block->id = $DB->insert_record('block', $block);
870 upgrade_block_savepoint(true, $plugin->version, $block->name, false);
872 if (file_exists($fullblock.'/db/install.php')) {
873 require_once($fullblock.'/db/install.php');
874 // Set installation running flag, we need to recover after exception or error
875 set_config('installrunning', 1, 'block_'.$blockname);
876 $post_install_function = 'xmldb_block_'.$blockname.'_install';
877 $post_install_function();
878 unset_config('installrunning', 'block_'.$blockname);
881 $blocktitles[$block->name] = $blocktitle;
883 // Install various components
884 update_capabilities($component);
885 log_update_descriptions($component);
886 external_update_descriptions($component);
887 events_update_definition($component);
888 \core\task\manager::reset_scheduled_tasks_for_component($component);
889 message_update_providers($component);
890 \core\message\inbound\manager::update_handlers_for_component($component);
891 upgrade_plugin_mnet_functions($component);
893 $endcallback($component, true, $verbose);
895 } else if ($installedversion < $plugin->version) {
896 $startcallback($component, false, $verbose);
898 if (is_readable($fullblock.'/db/upgrade.php')) {
899 require_once($fullblock.'/db/upgrade.php'); // defines new upgrading function
900 $newupgrade_function = 'xmldb_block_'.$blockname.'_upgrade';
901 $result = $newupgrade_function($installedversion, $block);
902 } else {
903 $result = true;
906 $installedversion = $DB->get_field('config_plugins', 'value', array('name'=>'version', 'plugin'=>$component)); // No caching!
907 $currblock = $DB->get_record('block', array('name'=>$block->name));
908 if ($installedversion < $plugin->version) {
909 // store version if not already there
910 upgrade_block_savepoint($result, $plugin->version, $block->name, false);
913 if ($currblock->cron != $block->cron) {
914 // update cron flag if needed
915 $DB->set_field('block', 'cron', $block->cron, array('id' => $currblock->id));
918 // Upgrade various components
919 update_capabilities($component);
920 log_update_descriptions($component);
921 external_update_descriptions($component);
922 events_update_definition($component);
923 \core\task\manager::reset_scheduled_tasks_for_component($component);
924 message_update_providers($component);
925 \core\message\inbound\manager::update_handlers_for_component($component);
926 upgrade_plugin_mnet_functions($component);
928 $endcallback($component, false, $verbose);
930 } else if ($installedversion > $plugin->version) {
931 throw new downgrade_exception($component, $installedversion, $plugin->version);
936 // Finally, if we are in the first_install of BLOCKS setup frontpage and admin page blocks
937 if ($first_install) {
938 //Iterate over each course - there should be only site course here now
939 if ($courses = $DB->get_records('course')) {
940 foreach ($courses as $course) {
941 blocks_add_default_course_blocks($course);
945 blocks_add_default_system_blocks();
951 * Log_display description function used during install and upgrade.
953 * @param string $component name of component (moodle, mod_assignment, etc.)
954 * @return void
956 function log_update_descriptions($component) {
957 global $DB;
959 $defpath = core_component::get_component_directory($component).'/db/log.php';
961 if (!file_exists($defpath)) {
962 $DB->delete_records('log_display', array('component'=>$component));
963 return;
966 // load new info
967 $logs = array();
968 include($defpath);
969 $newlogs = array();
970 foreach ($logs as $log) {
971 $newlogs[$log['module'].'-'.$log['action']] = $log; // kind of unique name
973 unset($logs);
974 $logs = $newlogs;
976 $fields = array('module', 'action', 'mtable', 'field');
977 // update all log fist
978 $dblogs = $DB->get_records('log_display', array('component'=>$component));
979 foreach ($dblogs as $dblog) {
980 $name = $dblog->module.'-'.$dblog->action;
982 if (empty($logs[$name])) {
983 $DB->delete_records('log_display', array('id'=>$dblog->id));
984 continue;
987 $log = $logs[$name];
988 unset($logs[$name]);
990 $update = false;
991 foreach ($fields as $field) {
992 if ($dblog->$field != $log[$field]) {
993 $dblog->$field = $log[$field];
994 $update = true;
997 if ($update) {
998 $DB->update_record('log_display', $dblog);
1001 foreach ($logs as $log) {
1002 $dblog = (object)$log;
1003 $dblog->component = $component;
1004 $DB->insert_record('log_display', $dblog);
1009 * Web service discovery function used during install and upgrade.
1010 * @param string $component name of component (moodle, mod_assignment, etc.)
1011 * @return void
1013 function external_update_descriptions($component) {
1014 global $DB, $CFG;
1016 $defpath = core_component::get_component_directory($component).'/db/services.php';
1018 if (!file_exists($defpath)) {
1019 require_once($CFG->dirroot.'/lib/externallib.php');
1020 external_delete_descriptions($component);
1021 return;
1024 // load new info
1025 $functions = array();
1026 $services = array();
1027 include($defpath);
1029 // update all function fist
1030 $dbfunctions = $DB->get_records('external_functions', array('component'=>$component));
1031 foreach ($dbfunctions as $dbfunction) {
1032 if (empty($functions[$dbfunction->name])) {
1033 $DB->delete_records('external_functions', array('id'=>$dbfunction->id));
1034 // do not delete functions from external_services_functions, beacuse
1035 // we want to notify admins when functions used in custom services disappear
1037 //TODO: this looks wrong, we have to delete it eventually (skodak)
1038 continue;
1041 $function = $functions[$dbfunction->name];
1042 unset($functions[$dbfunction->name]);
1043 $function['classpath'] = empty($function['classpath']) ? null : $function['classpath'];
1045 $update = false;
1046 if ($dbfunction->classname != $function['classname']) {
1047 $dbfunction->classname = $function['classname'];
1048 $update = true;
1050 if ($dbfunction->methodname != $function['methodname']) {
1051 $dbfunction->methodname = $function['methodname'];
1052 $update = true;
1054 if ($dbfunction->classpath != $function['classpath']) {
1055 $dbfunction->classpath = $function['classpath'];
1056 $update = true;
1058 $functioncapabilities = array_key_exists('capabilities', $function)?$function['capabilities']:'';
1059 if ($dbfunction->capabilities != $functioncapabilities) {
1060 $dbfunction->capabilities = $functioncapabilities;
1061 $update = true;
1063 if ($update) {
1064 $DB->update_record('external_functions', $dbfunction);
1067 foreach ($functions as $fname => $function) {
1068 $dbfunction = new stdClass();
1069 $dbfunction->name = $fname;
1070 $dbfunction->classname = $function['classname'];
1071 $dbfunction->methodname = $function['methodname'];
1072 $dbfunction->classpath = empty($function['classpath']) ? null : $function['classpath'];
1073 $dbfunction->component = $component;
1074 $dbfunction->capabilities = array_key_exists('capabilities', $function)?$function['capabilities']:'';
1075 $dbfunction->id = $DB->insert_record('external_functions', $dbfunction);
1077 unset($functions);
1079 // now deal with services
1080 $dbservices = $DB->get_records('external_services', array('component'=>$component));
1081 foreach ($dbservices as $dbservice) {
1082 if (empty($services[$dbservice->name])) {
1083 $DB->delete_records('external_tokens', array('externalserviceid'=>$dbservice->id));
1084 $DB->delete_records('external_services_functions', array('externalserviceid'=>$dbservice->id));
1085 $DB->delete_records('external_services_users', array('externalserviceid'=>$dbservice->id));
1086 $DB->delete_records('external_services', array('id'=>$dbservice->id));
1087 continue;
1089 $service = $services[$dbservice->name];
1090 unset($services[$dbservice->name]);
1091 $service['enabled'] = empty($service['enabled']) ? 0 : $service['enabled'];
1092 $service['requiredcapability'] = empty($service['requiredcapability']) ? null : $service['requiredcapability'];
1093 $service['restrictedusers'] = !isset($service['restrictedusers']) ? 1 : $service['restrictedusers'];
1094 $service['downloadfiles'] = !isset($service['downloadfiles']) ? 0 : $service['downloadfiles'];
1095 $service['uploadfiles'] = !isset($service['uploadfiles']) ? 0 : $service['uploadfiles'];
1096 $service['shortname'] = !isset($service['shortname']) ? null : $service['shortname'];
1098 $update = false;
1099 if ($dbservice->requiredcapability != $service['requiredcapability']) {
1100 $dbservice->requiredcapability = $service['requiredcapability'];
1101 $update = true;
1103 if ($dbservice->restrictedusers != $service['restrictedusers']) {
1104 $dbservice->restrictedusers = $service['restrictedusers'];
1105 $update = true;
1107 if ($dbservice->downloadfiles != $service['downloadfiles']) {
1108 $dbservice->downloadfiles = $service['downloadfiles'];
1109 $update = true;
1111 if ($dbservice->uploadfiles != $service['uploadfiles']) {
1112 $dbservice->uploadfiles = $service['uploadfiles'];
1113 $update = true;
1115 //if shortname is not a PARAM_ALPHANUMEXT, fail (tested here for service update and creation)
1116 if (isset($service['shortname']) and
1117 (clean_param($service['shortname'], PARAM_ALPHANUMEXT) != $service['shortname'])) {
1118 throw new moodle_exception('installserviceshortnameerror', 'webservice', '', $service['shortname']);
1120 if ($dbservice->shortname != $service['shortname']) {
1121 //check that shortname is unique
1122 if (isset($service['shortname'])) { //we currently accepts multiple shortname == null
1123 $existingservice = $DB->get_record('external_services',
1124 array('shortname' => $service['shortname']));
1125 if (!empty($existingservice)) {
1126 throw new moodle_exception('installexistingserviceshortnameerror', 'webservice', '', $service['shortname']);
1129 $dbservice->shortname = $service['shortname'];
1130 $update = true;
1132 if ($update) {
1133 $DB->update_record('external_services', $dbservice);
1136 $functions = $DB->get_records('external_services_functions', array('externalserviceid'=>$dbservice->id));
1137 foreach ($functions as $function) {
1138 $key = array_search($function->functionname, $service['functions']);
1139 if ($key === false) {
1140 $DB->delete_records('external_services_functions', array('id'=>$function->id));
1141 } else {
1142 unset($service['functions'][$key]);
1145 foreach ($service['functions'] as $fname) {
1146 $newf = new stdClass();
1147 $newf->externalserviceid = $dbservice->id;
1148 $newf->functionname = $fname;
1149 $DB->insert_record('external_services_functions', $newf);
1151 unset($functions);
1153 foreach ($services as $name => $service) {
1154 //check that shortname is unique
1155 if (isset($service['shortname'])) { //we currently accepts multiple shortname == null
1156 $existingservice = $DB->get_record('external_services',
1157 array('shortname' => $service['shortname']));
1158 if (!empty($existingservice)) {
1159 throw new moodle_exception('installserviceshortnameerror', 'webservice');
1163 $dbservice = new stdClass();
1164 $dbservice->name = $name;
1165 $dbservice->enabled = empty($service['enabled']) ? 0 : $service['enabled'];
1166 $dbservice->requiredcapability = empty($service['requiredcapability']) ? null : $service['requiredcapability'];
1167 $dbservice->restrictedusers = !isset($service['restrictedusers']) ? 1 : $service['restrictedusers'];
1168 $dbservice->downloadfiles = !isset($service['downloadfiles']) ? 0 : $service['downloadfiles'];
1169 $dbservice->uploadfiles = !isset($service['uploadfiles']) ? 0 : $service['uploadfiles'];
1170 $dbservice->shortname = !isset($service['shortname']) ? null : $service['shortname'];
1171 $dbservice->component = $component;
1172 $dbservice->timecreated = time();
1173 $dbservice->id = $DB->insert_record('external_services', $dbservice);
1174 foreach ($service['functions'] as $fname) {
1175 $newf = new stdClass();
1176 $newf->externalserviceid = $dbservice->id;
1177 $newf->functionname = $fname;
1178 $DB->insert_record('external_services_functions', $newf);
1184 * upgrade logging functions
1186 function upgrade_handle_exception($ex, $plugin = null) {
1187 global $CFG;
1189 // rollback everything, we need to log all upgrade problems
1190 abort_all_db_transactions();
1192 $info = get_exception_info($ex);
1194 // First log upgrade error
1195 upgrade_log(UPGRADE_LOG_ERROR, $plugin, 'Exception: ' . get_class($ex), $info->message, $info->backtrace);
1197 // Always turn on debugging - admins need to know what is going on
1198 set_debugging(DEBUG_DEVELOPER, true);
1200 default_exception_handler($ex, true, $plugin);
1204 * Adds log entry into upgrade_log table
1206 * @param int $type UPGRADE_LOG_NORMAL, UPGRADE_LOG_NOTICE or UPGRADE_LOG_ERROR
1207 * @param string $plugin frankenstyle component name
1208 * @param string $info short description text of log entry
1209 * @param string $details long problem description
1210 * @param string $backtrace string used for errors only
1211 * @return void
1213 function upgrade_log($type, $plugin, $info, $details=null, $backtrace=null) {
1214 global $DB, $USER, $CFG;
1216 if (empty($plugin)) {
1217 $plugin = 'core';
1220 list($plugintype, $pluginname) = core_component::normalize_component($plugin);
1221 $component = is_null($pluginname) ? $plugintype : $plugintype . '_' . $pluginname;
1223 $backtrace = format_backtrace($backtrace, true);
1225 $currentversion = null;
1226 $targetversion = null;
1228 //first try to find out current version number
1229 if ($plugintype === 'core') {
1230 //main
1231 $currentversion = $CFG->version;
1233 $version = null;
1234 include("$CFG->dirroot/version.php");
1235 $targetversion = $version;
1237 } else {
1238 $pluginversion = get_config($component, 'version');
1239 if (!empty($pluginversion)) {
1240 $currentversion = $pluginversion;
1242 $cd = core_component::get_component_directory($component);
1243 if (file_exists("$cd/version.php")) {
1244 $plugin = new stdClass();
1245 $plugin->version = null;
1246 $module = $plugin;
1247 include("$cd/version.php");
1248 $targetversion = $plugin->version;
1252 $log = new stdClass();
1253 $log->type = $type;
1254 $log->plugin = $component;
1255 $log->version = $currentversion;
1256 $log->targetversion = $targetversion;
1257 $log->info = $info;
1258 $log->details = $details;
1259 $log->backtrace = $backtrace;
1260 $log->userid = $USER->id;
1261 $log->timemodified = time();
1262 try {
1263 $DB->insert_record('upgrade_log', $log);
1264 } catch (Exception $ignored) {
1265 // possible during install or 2.0 upgrade
1270 * Marks start of upgrade, blocks any other access to site.
1271 * The upgrade is finished at the end of script or after timeout.
1273 * @global object
1274 * @global object
1275 * @global object
1277 function upgrade_started($preinstall=false) {
1278 global $CFG, $DB, $PAGE, $OUTPUT;
1280 static $started = false;
1282 if ($preinstall) {
1283 ignore_user_abort(true);
1284 upgrade_setup_debug(true);
1286 } else if ($started) {
1287 upgrade_set_timeout(120);
1289 } else {
1290 if (!CLI_SCRIPT and !$PAGE->headerprinted) {
1291 $strupgrade = get_string('upgradingversion', 'admin');
1292 $PAGE->set_pagelayout('maintenance');
1293 upgrade_init_javascript();
1294 $PAGE->set_title($strupgrade.' - Moodle '.$CFG->target_release);
1295 $PAGE->set_heading($strupgrade);
1296 $PAGE->navbar->add($strupgrade);
1297 $PAGE->set_cacheable(false);
1298 echo $OUTPUT->header();
1301 ignore_user_abort(true);
1302 core_shutdown_manager::register_function('upgrade_finished_handler');
1303 upgrade_setup_debug(true);
1304 set_config('upgraderunning', time()+300);
1305 $started = true;
1310 * Internal function - executed if upgrade interrupted.
1312 function upgrade_finished_handler() {
1313 upgrade_finished();
1317 * Indicates upgrade is finished.
1319 * This function may be called repeatedly.
1321 * @global object
1322 * @global object
1324 function upgrade_finished($continueurl=null) {
1325 global $CFG, $DB, $OUTPUT;
1327 if (!empty($CFG->upgraderunning)) {
1328 unset_config('upgraderunning');
1329 // We have to forcefully purge the caches using the writer here.
1330 // This has to be done after we unset the config var. If someone hits the site while this is set they will
1331 // cause the config values to propogate to the caches.
1332 // Caches are purged after the last step in an upgrade but there is several code routines that exceute between
1333 // then and now that leaving a window for things to fall out of sync.
1334 cache_helper::purge_all(true);
1335 upgrade_setup_debug(false);
1336 ignore_user_abort(false);
1337 if ($continueurl) {
1338 echo $OUTPUT->continue_button($continueurl);
1339 echo $OUTPUT->footer();
1340 die;
1346 * @global object
1347 * @global object
1349 function upgrade_setup_debug($starting) {
1350 global $CFG, $DB;
1352 static $originaldebug = null;
1354 if ($starting) {
1355 if ($originaldebug === null) {
1356 $originaldebug = $DB->get_debug();
1358 if (!empty($CFG->upgradeshowsql)) {
1359 $DB->set_debug(true);
1361 } else {
1362 $DB->set_debug($originaldebug);
1366 function print_upgrade_separator() {
1367 if (!CLI_SCRIPT) {
1368 echo '<hr />';
1373 * Default start upgrade callback
1374 * @param string $plugin
1375 * @param bool $installation true if installation, false means upgrade
1377 function print_upgrade_part_start($plugin, $installation, $verbose) {
1378 global $OUTPUT;
1379 if (empty($plugin) or $plugin == 'moodle') {
1380 upgrade_started($installation); // does not store upgrade running flag yet
1381 if ($verbose) {
1382 echo $OUTPUT->heading(get_string('coresystem'));
1384 } else {
1385 upgrade_started();
1386 if ($verbose) {
1387 echo $OUTPUT->heading($plugin);
1390 if ($installation) {
1391 if (empty($plugin) or $plugin == 'moodle') {
1392 // no need to log - log table not yet there ;-)
1393 } else {
1394 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Starting plugin installation');
1396 } else {
1397 if (empty($plugin) or $plugin == 'moodle') {
1398 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Starting core upgrade');
1399 } else {
1400 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Starting plugin upgrade');
1406 * Default end upgrade callback
1407 * @param string $plugin
1408 * @param bool $installation true if installation, false means upgrade
1410 function print_upgrade_part_end($plugin, $installation, $verbose) {
1411 global $OUTPUT;
1412 upgrade_started();
1413 if ($installation) {
1414 if (empty($plugin) or $plugin == 'moodle') {
1415 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Core installed');
1416 } else {
1417 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Plugin installed');
1419 } else {
1420 if (empty($plugin) or $plugin == 'moodle') {
1421 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Core upgraded');
1422 } else {
1423 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Plugin upgraded');
1426 if ($verbose) {
1427 echo $OUTPUT->notification(get_string('success'), 'notifysuccess');
1428 print_upgrade_separator();
1433 * Sets up JS code required for all upgrade scripts.
1434 * @global object
1436 function upgrade_init_javascript() {
1437 global $PAGE;
1438 // scroll to the end of each upgrade page so that ppl see either error or continue button,
1439 // no need to scroll continuously any more, it is enough to jump to end once the footer is printed ;-)
1440 $js = "window.scrollTo(0, 5000000);";
1441 $PAGE->requires->js_init_code($js);
1445 * Try to upgrade the given language pack (or current language)
1447 * @param string $lang the code of the language to update, defaults to the current language
1449 function upgrade_language_pack($lang = null) {
1450 global $CFG;
1452 if (!empty($CFG->skiplangupgrade)) {
1453 return;
1456 if (!file_exists("$CFG->dirroot/$CFG->admin/tool/langimport/lib.php")) {
1457 // weird, somebody uninstalled the import utility
1458 return;
1461 if (!$lang) {
1462 $lang = current_language();
1465 if (!get_string_manager()->translation_exists($lang)) {
1466 return;
1469 get_string_manager()->reset_caches();
1471 if ($lang === 'en') {
1472 return; // Nothing to do
1475 upgrade_started(false);
1477 require_once("$CFG->dirroot/$CFG->admin/tool/langimport/lib.php");
1478 tool_langimport_preupgrade_update($lang);
1480 get_string_manager()->reset_caches();
1482 print_upgrade_separator();
1486 * Install core moodle tables and initialize
1487 * @param float $version target version
1488 * @param bool $verbose
1489 * @return void, may throw exception
1491 function install_core($version, $verbose) {
1492 global $CFG, $DB;
1494 // We can not call purge_all_caches() yet, make sure the temp and cache dirs exist and are empty.
1495 remove_dir($CFG->cachedir.'', true);
1496 make_cache_directory('', true);
1498 remove_dir($CFG->localcachedir.'', true);
1499 make_localcache_directory('', true);
1501 remove_dir($CFG->tempdir.'', true);
1502 make_temp_directory('', true);
1504 remove_dir($CFG->dataroot.'/muc', true);
1505 make_writable_directory($CFG->dataroot.'/muc', true);
1507 try {
1508 core_php_time_limit::raise(600);
1509 print_upgrade_part_start('moodle', true, $verbose); // does not store upgrade running flag
1511 $DB->get_manager()->install_from_xmldb_file("$CFG->libdir/db/install.xml");
1512 upgrade_started(); // we want the flag to be stored in config table ;-)
1514 // set all core default records and default settings
1515 require_once("$CFG->libdir/db/install.php");
1516 xmldb_main_install(); // installs the capabilities too
1518 // store version
1519 upgrade_main_savepoint(true, $version, false);
1521 // Continue with the installation
1522 log_update_descriptions('moodle');
1523 external_update_descriptions('moodle');
1524 events_update_definition('moodle');
1525 \core\task\manager::reset_scheduled_tasks_for_component('moodle');
1526 message_update_providers('moodle');
1527 \core\message\inbound\manager::update_handlers_for_component('moodle');
1529 // Write default settings unconditionally
1530 admin_apply_default_settings(NULL, true);
1532 print_upgrade_part_end(null, true, $verbose);
1534 // Purge all caches. They're disabled but this ensures that we don't have any persistent data just in case something
1535 // during installation didn't use APIs.
1536 cache_helper::purge_all();
1537 } catch (exception $ex) {
1538 upgrade_handle_exception($ex);
1543 * Upgrade moodle core
1544 * @param float $version target version
1545 * @param bool $verbose
1546 * @return void, may throw exception
1548 function upgrade_core($version, $verbose) {
1549 global $CFG, $SITE, $DB, $COURSE;
1551 raise_memory_limit(MEMORY_EXTRA);
1553 require_once($CFG->libdir.'/db/upgrade.php'); // Defines upgrades
1555 try {
1556 // Reset caches before any output.
1557 cache_helper::purge_all(true);
1558 purge_all_caches();
1560 // Upgrade current language pack if we can
1561 upgrade_language_pack();
1563 print_upgrade_part_start('moodle', false, $verbose);
1565 // Pre-upgrade scripts for local hack workarounds.
1566 $preupgradefile = "$CFG->dirroot/local/preupgrade.php";
1567 if (file_exists($preupgradefile)) {
1568 core_php_time_limit::raise();
1569 require($preupgradefile);
1570 // Reset upgrade timeout to default.
1571 upgrade_set_timeout();
1574 $result = xmldb_main_upgrade($CFG->version);
1575 if ($version > $CFG->version) {
1576 // store version if not already there
1577 upgrade_main_savepoint($result, $version, false);
1580 // In case structure of 'course' table has been changed and we forgot to update $SITE, re-read it from db.
1581 $SITE = $DB->get_record('course', array('id' => $SITE->id));
1582 $COURSE = clone($SITE);
1584 // perform all other component upgrade routines
1585 update_capabilities('moodle');
1586 log_update_descriptions('moodle');
1587 external_update_descriptions('moodle');
1588 events_update_definition('moodle');
1589 \core\task\manager::reset_scheduled_tasks_for_component('moodle');
1590 message_update_providers('moodle');
1591 \core\message\inbound\manager::update_handlers_for_component('moodle');
1592 // Update core definitions.
1593 cache_helper::update_definitions(true);
1595 // Purge caches again, just to be sure we arn't holding onto old stuff now.
1596 cache_helper::purge_all(true);
1597 purge_all_caches();
1599 // Clean up contexts - more and more stuff depends on existence of paths and contexts
1600 context_helper::cleanup_instances();
1601 context_helper::create_instances(null, false);
1602 context_helper::build_all_paths(false);
1603 $syscontext = context_system::instance();
1604 $syscontext->mark_dirty();
1606 print_upgrade_part_end('moodle', false, $verbose);
1607 } catch (Exception $ex) {
1608 upgrade_handle_exception($ex);
1613 * Upgrade/install other parts of moodle
1614 * @param bool $verbose
1615 * @return void, may throw exception
1617 function upgrade_noncore($verbose) {
1618 global $CFG;
1620 raise_memory_limit(MEMORY_EXTRA);
1622 // upgrade all plugins types
1623 try {
1624 // Reset caches before any output.
1625 cache_helper::purge_all(true);
1626 purge_all_caches();
1628 $plugintypes = core_component::get_plugin_types();
1629 foreach ($plugintypes as $type=>$location) {
1630 upgrade_plugins($type, 'print_upgrade_part_start', 'print_upgrade_part_end', $verbose);
1632 // Update cache definitions. Involves scanning each plugin for any changes.
1633 cache_helper::update_definitions();
1634 // Mark the site as upgraded.
1635 set_config('allversionshash', core_component::get_all_versions_hash());
1637 // Purge caches again, just to be sure we arn't holding onto old stuff now.
1638 cache_helper::purge_all(true);
1639 purge_all_caches();
1641 } catch (Exception $ex) {
1642 upgrade_handle_exception($ex);
1647 * Checks if the main tables have been installed yet or not.
1649 * Note: we can not use caches here because they might be stale,
1650 * use with care!
1652 * @return bool
1654 function core_tables_exist() {
1655 global $DB;
1657 if (!$tables = $DB->get_tables(false) ) { // No tables yet at all.
1658 return false;
1660 } else { // Check for missing main tables
1661 $mtables = array('config', 'course', 'groupings'); // some tables used in 1.9 and 2.0, preferable something from the start and end of install.xml
1662 foreach ($mtables as $mtable) {
1663 if (!in_array($mtable, $tables)) {
1664 return false;
1667 return true;
1672 * upgrades the mnet rpc definitions for the given component.
1673 * this method doesn't return status, an exception will be thrown in the case of an error
1675 * @param string $component the plugin to upgrade, eg auth_mnet
1677 function upgrade_plugin_mnet_functions($component) {
1678 global $DB, $CFG;
1680 list($type, $plugin) = core_component::normalize_component($component);
1681 $path = core_component::get_plugin_directory($type, $plugin);
1683 $publishes = array();
1684 $subscribes = array();
1685 if (file_exists($path . '/db/mnet.php')) {
1686 require_once($path . '/db/mnet.php'); // $publishes comes from this file
1688 if (empty($publishes)) {
1689 $publishes = array(); // still need this to be able to disable stuff later
1691 if (empty($subscribes)) {
1692 $subscribes = array(); // still need this to be able to disable stuff later
1695 static $servicecache = array();
1697 // rekey an array based on the rpc method for easy lookups later
1698 $publishmethodservices = array();
1699 $subscribemethodservices = array();
1700 foreach($publishes as $servicename => $service) {
1701 if (is_array($service['methods'])) {
1702 foreach($service['methods'] as $methodname) {
1703 $service['servicename'] = $servicename;
1704 $publishmethodservices[$methodname][] = $service;
1709 // Disable functions that don't exist (any more) in the source
1710 // Should these be deleted? What about their permissions records?
1711 foreach ($DB->get_records('mnet_rpc', array('pluginname'=>$plugin, 'plugintype'=>$type), 'functionname ASC ') as $rpc) {
1712 if (!array_key_exists($rpc->functionname, $publishmethodservices) && $rpc->enabled) {
1713 $DB->set_field('mnet_rpc', 'enabled', 0, array('id' => $rpc->id));
1714 } else if (array_key_exists($rpc->functionname, $publishmethodservices) && !$rpc->enabled) {
1715 $DB->set_field('mnet_rpc', 'enabled', 1, array('id' => $rpc->id));
1719 // reflect all the services we're publishing and save them
1720 require_once($CFG->dirroot . '/lib/zend/Zend/Server/Reflection.php');
1721 static $cachedclasses = array(); // to store reflection information in
1722 foreach ($publishes as $service => $data) {
1723 $f = $data['filename'];
1724 $c = $data['classname'];
1725 foreach ($data['methods'] as $method) {
1726 $dataobject = new stdClass();
1727 $dataobject->plugintype = $type;
1728 $dataobject->pluginname = $plugin;
1729 $dataobject->enabled = 1;
1730 $dataobject->classname = $c;
1731 $dataobject->filename = $f;
1733 if (is_string($method)) {
1734 $dataobject->functionname = $method;
1736 } else if (is_array($method)) { // wants to override file or class
1737 $dataobject->functionname = $method['method'];
1738 $dataobject->classname = $method['classname'];
1739 $dataobject->filename = $method['filename'];
1741 $dataobject->xmlrpcpath = $type.'/'.$plugin.'/'.$dataobject->filename.'/'.$method;
1742 $dataobject->static = false;
1744 require_once($path . '/' . $dataobject->filename);
1745 $functionreflect = null; // slightly different ways to get this depending on whether it's a class method or a function
1746 if (!empty($dataobject->classname)) {
1747 if (!class_exists($dataobject->classname)) {
1748 throw new moodle_exception('installnosuchmethod', 'mnet', '', (object)array('method' => $dataobject->functionname, 'class' => $dataobject->classname));
1750 $key = $dataobject->filename . '|' . $dataobject->classname;
1751 if (!array_key_exists($key, $cachedclasses)) { // look to see if we've already got a reflection object
1752 try {
1753 $cachedclasses[$key] = Zend_Server_Reflection::reflectClass($dataobject->classname);
1754 } catch (Zend_Server_Reflection_Exception $e) { // catch these and rethrow them to something more helpful
1755 throw new moodle_exception('installreflectionclasserror', 'mnet', '', (object)array('method' => $dataobject->functionname, 'class' => $dataobject->classname, 'error' => $e->getMessage()));
1758 $r =& $cachedclasses[$key];
1759 if (!$r->hasMethod($dataobject->functionname)) {
1760 throw new moodle_exception('installnosuchmethod', 'mnet', '', (object)array('method' => $dataobject->functionname, 'class' => $dataobject->classname));
1762 // stupid workaround for zend not having a getMethod($name) function
1763 $ms = $r->getMethods();
1764 foreach ($ms as $m) {
1765 if ($m->getName() == $dataobject->functionname) {
1766 $functionreflect = $m;
1767 break;
1770 $dataobject->static = (int)$functionreflect->isStatic();
1771 } else {
1772 if (!function_exists($dataobject->functionname)) {
1773 throw new moodle_exception('installnosuchfunction', 'mnet', '', (object)array('method' => $dataobject->functionname, 'file' => $dataobject->filename));
1775 try {
1776 $functionreflect = Zend_Server_Reflection::reflectFunction($dataobject->functionname);
1777 } catch (Zend_Server_Reflection_Exception $e) { // catch these and rethrow them to something more helpful
1778 throw new moodle_exception('installreflectionfunctionerror', 'mnet', '', (object)array('method' => $dataobject->functionname, '' => $dataobject->filename, 'error' => $e->getMessage()));
1781 $dataobject->profile = serialize(admin_mnet_method_profile($functionreflect));
1782 $dataobject->help = $functionreflect->getDescription();
1784 if ($record_exists = $DB->get_record('mnet_rpc', array('xmlrpcpath'=>$dataobject->xmlrpcpath))) {
1785 $dataobject->id = $record_exists->id;
1786 $dataobject->enabled = $record_exists->enabled;
1787 $DB->update_record('mnet_rpc', $dataobject);
1788 } else {
1789 $dataobject->id = $DB->insert_record('mnet_rpc', $dataobject, true);
1792 // TODO this API versioning must be reworked, here the recently processed method
1793 // sets the service API which may not be correct
1794 foreach ($publishmethodservices[$dataobject->functionname] as $service) {
1795 if ($serviceobj = $DB->get_record('mnet_service', array('name'=>$service['servicename']))) {
1796 $serviceobj->apiversion = $service['apiversion'];
1797 $DB->update_record('mnet_service', $serviceobj);
1798 } else {
1799 $serviceobj = new stdClass();
1800 $serviceobj->name = $service['servicename'];
1801 $serviceobj->description = empty($service['description']) ? '' : $service['description'];
1802 $serviceobj->apiversion = $service['apiversion'];
1803 $serviceobj->offer = 1;
1804 $serviceobj->id = $DB->insert_record('mnet_service', $serviceobj);
1806 $servicecache[$service['servicename']] = $serviceobj;
1807 if (!$DB->record_exists('mnet_service2rpc', array('rpcid'=>$dataobject->id, 'serviceid'=>$serviceobj->id))) {
1808 $obj = new stdClass();
1809 $obj->rpcid = $dataobject->id;
1810 $obj->serviceid = $serviceobj->id;
1811 $DB->insert_record('mnet_service2rpc', $obj, true);
1816 // finished with methods we publish, now do subscribable methods
1817 foreach($subscribes as $service => $methods) {
1818 if (!array_key_exists($service, $servicecache)) {
1819 if (!$serviceobj = $DB->get_record('mnet_service', array('name' => $service))) {
1820 debugging("TODO: skipping unknown service $service - somebody needs to fix MDL-21993");
1821 continue;
1823 $servicecache[$service] = $serviceobj;
1824 } else {
1825 $serviceobj = $servicecache[$service];
1827 foreach ($methods as $method => $xmlrpcpath) {
1828 if (!$rpcid = $DB->get_field('mnet_remote_rpc', 'id', array('xmlrpcpath'=>$xmlrpcpath))) {
1829 $remoterpc = (object)array(
1830 'functionname' => $method,
1831 'xmlrpcpath' => $xmlrpcpath,
1832 'plugintype' => $type,
1833 'pluginname' => $plugin,
1834 'enabled' => 1,
1836 $rpcid = $remoterpc->id = $DB->insert_record('mnet_remote_rpc', $remoterpc, true);
1838 if (!$DB->record_exists('mnet_remote_service2rpc', array('rpcid'=>$rpcid, 'serviceid'=>$serviceobj->id))) {
1839 $obj = new stdClass();
1840 $obj->rpcid = $rpcid;
1841 $obj->serviceid = $serviceobj->id;
1842 $DB->insert_record('mnet_remote_service2rpc', $obj, true);
1844 $subscribemethodservices[$method][] = $service;
1848 foreach ($DB->get_records('mnet_remote_rpc', array('pluginname'=>$plugin, 'plugintype'=>$type), 'functionname ASC ') as $rpc) {
1849 if (!array_key_exists($rpc->functionname, $subscribemethodservices) && $rpc->enabled) {
1850 $DB->set_field('mnet_remote_rpc', 'enabled', 0, array('id' => $rpc->id));
1851 } else if (array_key_exists($rpc->functionname, $subscribemethodservices) && !$rpc->enabled) {
1852 $DB->set_field('mnet_remote_rpc', 'enabled', 1, array('id' => $rpc->id));
1856 return true;
1860 * Given some sort of Zend Reflection function/method object, return a profile array, ready to be serialized and stored
1862 * @param Zend_Server_Reflection_Function_Abstract $function can be any subclass of this object type
1864 * @return array
1866 function admin_mnet_method_profile(Zend_Server_Reflection_Function_Abstract $function) {
1867 $protos = $function->getPrototypes();
1868 $proto = array_pop($protos);
1869 $ret = $proto->getReturnValue();
1870 $profile = array(
1871 'parameters' => array(),
1872 'return' => array(
1873 'type' => $ret->getType(),
1874 'description' => $ret->getDescription(),
1877 foreach ($proto->getParameters() as $p) {
1878 $profile['parameters'][] = array(
1879 'name' => $p->getName(),
1880 'type' => $p->getType(),
1881 'description' => $p->getDescription(),
1884 return $profile;
1889 * This function finds duplicate records (based on combinations of fields that should be unique)
1890 * and then progamatically generated a "most correct" version of the data, update and removing
1891 * records as appropriate
1893 * Thanks to Dan Marsden for help
1895 * @param string $table Table name
1896 * @param array $uniques Array of field names that should be unique
1897 * @param array $fieldstocheck Array of fields to generate "correct" data from (optional)
1898 * @return void
1900 function upgrade_course_completion_remove_duplicates($table, $uniques, $fieldstocheck = array()) {
1901 global $DB;
1903 // Find duplicates
1904 $sql_cols = implode(', ', $uniques);
1906 $sql = "SELECT {$sql_cols} FROM {{$table}} GROUP BY {$sql_cols} HAVING (count(id) > 1)";
1907 $duplicates = $DB->get_recordset_sql($sql, array());
1909 // Loop through duplicates
1910 foreach ($duplicates as $duplicate) {
1911 $pointer = 0;
1913 // Generate SQL for finding records with these duplicate uniques
1914 $sql_select = implode(' = ? AND ', $uniques).' = ?'; // builds "fieldname = ? AND fieldname = ?"
1915 $uniq_values = array();
1916 foreach ($uniques as $u) {
1917 $uniq_values[] = $duplicate->$u;
1920 $sql_order = implode(' DESC, ', $uniques).' DESC'; // builds "fieldname DESC, fieldname DESC"
1922 // Get records with these duplicate uniques
1923 $records = $DB->get_records_select(
1924 $table,
1925 $sql_select,
1926 $uniq_values,
1927 $sql_order
1930 // Loop through and build a "correct" record, deleting the others
1931 $needsupdate = false;
1932 $origrecord = null;
1933 foreach ($records as $record) {
1934 $pointer++;
1935 if ($pointer === 1) { // keep 1st record but delete all others.
1936 $origrecord = $record;
1937 } else {
1938 // If we have fields to check, update original record
1939 if ($fieldstocheck) {
1940 // we need to keep the "oldest" of all these fields as the valid completion record.
1941 // but we want to ignore null values
1942 foreach ($fieldstocheck as $f) {
1943 if ($record->$f && (($origrecord->$f > $record->$f) || !$origrecord->$f)) {
1944 $origrecord->$f = $record->$f;
1945 $needsupdate = true;
1949 $DB->delete_records($table, array('id' => $record->id));
1952 if ($needsupdate || isset($origrecord->reaggregate)) {
1953 // If this table has a reaggregate field, update to force recheck on next cron run
1954 if (isset($origrecord->reaggregate)) {
1955 $origrecord->reaggregate = time();
1957 $DB->update_record($table, $origrecord);
1963 * Find questions missing an existing category and associate them with
1964 * a category which purpose is to gather them.
1966 * @return void
1968 function upgrade_save_orphaned_questions() {
1969 global $DB;
1971 // Looking for orphaned questions
1972 $orphans = $DB->record_exists_select('question',
1973 'NOT EXISTS (SELECT 1 FROM {question_categories} WHERE {question_categories}.id = {question}.category)');
1974 if (!$orphans) {
1975 return;
1978 // Generate a unique stamp for the orphaned questions category, easier to identify it later on
1979 $uniquestamp = "unknownhost+120719170400+orphan";
1980 $systemcontext = context_system::instance();
1982 // Create the orphaned category at system level
1983 $cat = $DB->get_record('question_categories', array('stamp' => $uniquestamp,
1984 'contextid' => $systemcontext->id));
1985 if (!$cat) {
1986 $cat = new stdClass();
1987 $cat->parent = 0;
1988 $cat->contextid = $systemcontext->id;
1989 $cat->name = get_string('orphanedquestionscategory', 'question');
1990 $cat->info = get_string('orphanedquestionscategoryinfo', 'question');
1991 $cat->sortorder = 999;
1992 $cat->stamp = $uniquestamp;
1993 $cat->id = $DB->insert_record("question_categories", $cat);
1996 // Set a category to those orphans
1997 $params = array('catid' => $cat->id);
1998 $DB->execute('UPDATE {question} SET category = :catid WHERE NOT EXISTS
1999 (SELECT 1 FROM {question_categories} WHERE {question_categories}.id = {question}.category)', $params);
2003 * Rename old backup files to current backup files.
2005 * When added the setting 'backup_shortname' (MDL-28657) the backup file names did not contain the id of the course.
2006 * Further we fixed that behaviour by forcing the id to be always present in the file name (MDL-33812).
2007 * This function will explore the backup directory and attempt to rename the previously created files to include
2008 * the id in the name. Doing this will put them back in the process of deleting the excess backups for each course.
2010 * This function manually recreates the file name, instead of using
2011 * {@link backup_plan_dbops::get_default_backup_filename()}, use it carefully if you're using it outside of the
2012 * usual upgrade process.
2014 * @see backup_cron_automated_helper::remove_excess_backups()
2015 * @link http://tracker.moodle.org/browse/MDL-35116
2016 * @return void
2017 * @since Moodle 2.4
2019 function upgrade_rename_old_backup_files_using_shortname() {
2020 global $CFG;
2021 $dir = get_config('backup', 'backup_auto_destination');
2022 $useshortname = get_config('backup', 'backup_shortname');
2023 if (empty($dir) || !is_dir($dir) || !is_writable($dir)) {
2024 return;
2027 require_once($CFG->dirroot.'/backup/util/includes/backup_includes.php');
2028 $backupword = str_replace(' ', '_', core_text::strtolower(get_string('backupfilename')));
2029 $backupword = trim(clean_filename($backupword), '_');
2030 $filename = $backupword . '-' . backup::FORMAT_MOODLE . '-' . backup::TYPE_1COURSE . '-';
2031 $regex = '#^'.preg_quote($filename, '#').'.*\.mbz$#';
2032 $thirtyapril = strtotime('30 April 2012 00:00');
2034 // Reading the directory.
2035 if (!$files = scandir($dir)) {
2036 return;
2038 foreach ($files as $file) {
2039 // Skip directories and files which do not start with the common prefix.
2040 // This avoids working on files which are not related to this issue.
2041 if (!is_file($dir . '/' . $file) || !preg_match($regex, $file)) {
2042 continue;
2045 // Extract the information from the XML file.
2046 try {
2047 $bcinfo = backup_general_helper::get_backup_information_from_mbz($dir . '/' . $file);
2048 } catch (backup_helper_exception $e) {
2049 // Some error while retrieving the backup informations, skipping...
2050 continue;
2053 // Make sure this a course backup.
2054 if ($bcinfo->format !== backup::FORMAT_MOODLE || $bcinfo->type !== backup::TYPE_1COURSE) {
2055 continue;
2058 // Skip the backups created before the short name option was initially introduced (MDL-28657).
2059 // This was integrated on the 2nd of May 2012. Let's play safe with timezone and use the 30th of April.
2060 if ($bcinfo->backup_date < $thirtyapril) {
2061 continue;
2064 // Let's check if the file name contains the ID where it is supposed to be, if it is the case then
2065 // we will skip the file. Of course it could happen that the course ID is identical to the course short name
2066 // even though really unlikely, but then renaming this file is not necessary. If the ID is not found in the
2067 // file name then it was probably the short name which was used.
2068 $idfilename = $filename . $bcinfo->original_course_id . '-';
2069 $idregex = '#^'.preg_quote($idfilename, '#').'.*\.mbz$#';
2070 if (preg_match($idregex, $file)) {
2071 continue;
2074 // Generating the file name manually. We do not use backup_plan_dbops::get_default_backup_filename() because
2075 // it will query the database to get some course information, and the course could not exist any more.
2076 $newname = $filename . $bcinfo->original_course_id . '-';
2077 if ($useshortname) {
2078 $shortname = str_replace(' ', '_', $bcinfo->original_course_shortname);
2079 $shortname = core_text::strtolower(trim(clean_filename($shortname), '_'));
2080 $newname .= $shortname . '-';
2083 $backupdateformat = str_replace(' ', '_', get_string('backupnameformat', 'langconfig'));
2084 $date = userdate($bcinfo->backup_date, $backupdateformat, 99, false);
2085 $date = core_text::strtolower(trim(clean_filename($date), '_'));
2086 $newname .= $date;
2088 if (isset($bcinfo->root_settings['users']) && !$bcinfo->root_settings['users']) {
2089 $newname .= '-nu';
2090 } else if (isset($bcinfo->root_settings['anonymize']) && $bcinfo->root_settings['anonymize']) {
2091 $newname .= '-an';
2093 $newname .= '.mbz';
2095 // Final check before attempting the renaming.
2096 if ($newname == $file || file_exists($dir . '/' . $newname)) {
2097 continue;
2099 @rename($dir . '/' . $file, $dir . '/' . $newname);
2104 * Detect duplicate grade item sortorders and resort the
2105 * items to remove them.
2107 function upgrade_grade_item_fix_sortorder() {
2108 global $DB;
2110 // The simple way to fix these sortorder duplicates would be simply to resort each
2111 // affected course. But in order to reduce the impact of this upgrade step we're trying
2112 // to do it more efficiently by doing a series of update statements rather than updating
2113 // every single grade item in affected courses.
2115 $sql = "SELECT DISTINCT g1.courseid
2116 FROM {grade_items} g1
2117 JOIN {grade_items} g2 ON g1.courseid = g2.courseid
2118 WHERE g1.sortorder = g2.sortorder AND g1.id != g2.id
2119 ORDER BY g1.courseid ASC";
2120 foreach ($DB->get_fieldset_sql($sql) as $courseid) {
2121 $transaction = $DB->start_delegated_transaction();
2122 $items = $DB->get_records('grade_items', array('courseid' => $courseid), '', 'id, sortorder, sortorder AS oldsort');
2124 // Get all duplicates in course order, highest sort order, and higest id first so that we can make space at the
2125 // bottom higher end of the sort orders and work down by id.
2126 $sql = "SELECT DISTINCT g1.id, g1.sortorder
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 AND g1.courseid = :courseid
2130 ORDER BY g1.sortorder DESC, g1.id DESC";
2132 // This is the O(N*N) like the database version we're replacing, but at least the constants are a billion times smaller...
2133 foreach ($DB->get_records_sql($sql, array('courseid' => $courseid)) as $duplicate) {
2134 foreach ($items as $item) {
2135 if ($item->sortorder > $duplicate->sortorder || ($item->sortorder == $duplicate->sortorder && $item->id > $duplicate->id)) {
2136 $item->sortorder += 1;
2140 foreach ($items as $item) {
2141 if ($item->sortorder != $item->oldsort) {
2142 $DB->update_record('grade_items', array('id' => $item->id, 'sortorder' => $item->sortorder));
2146 $transaction->allow_commit();
2151 * Detect file areas with missing root directory records and add them.
2153 function upgrade_fix_missing_root_folders() {
2154 global $DB, $USER;
2156 $transaction = $DB->start_delegated_transaction();
2158 $sql = "SELECT contextid, component, filearea, itemid
2159 FROM {files}
2160 WHERE (component <> 'user' OR filearea <> 'draft')
2161 GROUP BY contextid, component, filearea, itemid
2162 HAVING MAX(CASE WHEN filename = '.' AND filepath = '/' THEN 1 ELSE 0 END) = 0";
2164 $rs = $DB->get_recordset_sql($sql);
2165 $defaults = array('filepath' => '/',
2166 'filename' => '.',
2167 'userid' => 0, // Don't rely on any particular user for these system records.
2168 'filesize' => 0,
2169 'timecreated' => time(),
2170 'timemodified' => time(),
2171 'contenthash' => sha1(''));
2172 foreach ($rs as $r) {
2173 $pathhash = sha1("/$r->contextid/$r->component/$r->filearea/$r->itemid/.");
2174 $DB->insert_record('files', (array)$r + $defaults +
2175 array('pathnamehash' => $pathhash));
2177 $rs->close();
2178 $transaction->allow_commit();
2182 * Detect draft file areas with missing root directory records and add them.
2184 function upgrade_fix_missing_root_folders_draft() {
2185 global $DB;
2187 $transaction = $DB->start_delegated_transaction();
2189 $sql = "SELECT contextid, itemid, MAX(timecreated) AS timecreated, MAX(timemodified) AS timemodified
2190 FROM {files}
2191 WHERE (component = 'user' AND filearea = 'draft')
2192 GROUP BY contextid, itemid
2193 HAVING MAX(CASE WHEN filename = '.' AND filepath = '/' THEN 1 ELSE 0 END) = 0";
2195 $rs = $DB->get_recordset_sql($sql);
2196 $defaults = array('component' => 'user',
2197 'filearea' => 'draft',
2198 'filepath' => '/',
2199 'filename' => '.',
2200 'userid' => 0, // Don't rely on any particular user for these system records.
2201 'filesize' => 0,
2202 'contenthash' => sha1(''));
2203 foreach ($rs as $r) {
2204 $r->pathnamehash = sha1("/$r->contextid/user/draft/$r->itemid/.");
2205 $DB->insert_record('files', (array)$r + $defaults);
2207 $rs->close();
2208 $transaction->allow_commit();
2212 * This function verifies that the database is not using an unsupported storage engine.
2214 * @param environment_results $result object to update, if relevant
2215 * @return environment_results|null updated results object, or null if the storage engine is supported
2217 function check_database_storage_engine(environment_results $result) {
2218 global $DB;
2220 // Check if MySQL is the DB family (this will also be the same for MariaDB).
2221 if ($DB->get_dbfamily() == 'mysql') {
2222 // Get the database engine we will either be using to install the tables, or what we are currently using.
2223 $engine = $DB->get_dbengine();
2224 // Check if MyISAM is the storage engine that will be used, if so, do not proceed and display an error.
2225 if ($engine == 'MyISAM') {
2226 $result->setInfo('unsupported_db_storage_engine');
2227 $result->setStatus(false);
2228 return $result;
2232 return null;
2236 * Method used to check the usage of slasharguments config and display a warning message.
2238 * @param environment_results $result object to update, if relevant.
2239 * @return environment_results|null updated results or null if slasharguments is disabled.
2241 function check_slasharguments(environment_results $result){
2242 global $CFG;
2244 if (!during_initial_install() && empty($CFG->slasharguments)) {
2245 $result->setInfo('slasharguments');
2246 $result->setStatus(false);
2247 return $result;
2250 return null;
2254 * This function verifies if the database has tables using innoDB Antelope row format.
2256 * @param environment_results $result
2257 * @return environment_results|null updated results object, or null if no Antelope table has been found.
2259 function check_database_tables_row_format(environment_results $result) {
2260 global $DB;
2262 if ($DB->get_dbfamily() == 'mysql') {
2263 $generator = $DB->get_manager()->generator;
2265 foreach ($DB->get_tables(false) as $table) {
2266 $columns = $DB->get_columns($table, false);
2267 $size = $generator->guess_antelope_row_size($columns);
2268 $format = $DB->get_row_format($table);
2270 if ($size <= $generator::ANTELOPE_MAX_ROW_SIZE) {
2271 continue;
2274 if ($format === 'Compact' or $format === 'Redundant') {
2275 $result->setInfo('unsupported_db_table_row_format');
2276 $result->setStatus(false);
2277 return $result;
2282 return null;
2286 * Upgrade the minmaxgrade setting.
2288 * This step should only be run for sites running 2.8 or later. Sites using 2.7 will be fine
2289 * using the new default system setting $CFG->grade_minmaxtouse.
2291 * @return void
2293 function upgrade_minmaxgrade() {
2294 global $CFG, $DB;
2296 // 2 is a copy of GRADE_MIN_MAX_FROM_GRADE_GRADE.
2297 $settingvalue = 2;
2299 // Set the course setting when:
2300 // - The system setting does not exist yet.
2301 // - The system seeting is not set to what we'd set the course setting.
2302 $setcoursesetting = !isset($CFG->grade_minmaxtouse) || $CFG->grade_minmaxtouse != $settingvalue;
2304 // Identify the courses that have inconsistencies grade_item vs grade_grade.
2305 $sql = "SELECT DISTINCT(gi.courseid)
2306 FROM {grade_grades} gg
2307 JOIN {grade_items} gi
2308 ON gg.itemid = gi.id
2309 WHERE gi.itemtype NOT IN (?, ?)
2310 AND (gg.rawgrademax != gi.grademax OR gg.rawgrademin != gi.grademin)";
2312 $rs = $DB->get_recordset_sql($sql, array('course', 'category'));
2313 foreach ($rs as $record) {
2314 // Flag the course to show a notice in the gradebook.
2315 set_config('show_min_max_grades_changed_' . $record->courseid, 1);
2317 // Set the appropriate course setting so that grades displayed are not changed.
2318 $configname = 'minmaxtouse';
2319 if ($setcoursesetting &&
2320 !$DB->record_exists('grade_settings', array('courseid' => $record->courseid, 'name' => $configname))) {
2321 // Do not set the setting when the course already defines it.
2322 $data = new stdClass();
2323 $data->courseid = $record->courseid;
2324 $data->name = $configname;
2325 $data->value = $settingvalue;
2326 $DB->insert_record('grade_settings', $data);
2329 // Mark the grades to be regraded.
2330 $DB->set_field('grade_items', 'needsupdate', 1, array('courseid' => $record->courseid));
2332 $rs->close();