Merge branch 'wip-mdl-48190-m27' of https://github.com/rajeshtaneja/moodle into MOODL...
[moodle.git] / lib / upgradelib.php
blob88b8c1a4c2dd2ebfe5c18fd9f7be767f0550e492
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.7.
375 '/admin/tool/qeupgradehelper/version.php',
376 // Removed in 2.6.
377 '/admin/block.php',
378 '/admin/oacleanup.php',
379 // Removed in 2.5.
380 '/backup/lib.php',
381 '/backup/bb/README.txt',
382 '/lib/excel/test.php',
383 // Removed in 2.4.
384 '/admin/tool/unittest/simpletestlib.php',
385 // Removed in 2.3.
386 '/lib/minify/builder/',
387 // Removed in 2.2.
388 '/lib/yui/3.4.1pr1/',
389 // Removed in 2.2.
390 '/search/cron_php5.php',
391 '/course/report/log/indexlive.php',
392 '/admin/report/backups/index.php',
393 '/admin/generator.php',
394 // Removed in 2.1.
395 '/lib/yui/2.8.0r4/',
396 // Removed in 2.0.
397 '/blocks/admin/block_admin.php',
398 '/blocks/admin_tree/block_admin_tree.php',
401 foreach ($someexamplesofremovedfiles as $file) {
402 if (file_exists($CFG->dirroot.$file)) {
403 return true;
407 return false;
411 * Upgrade plugins
412 * @param string $type The type of plugins that should be updated (e.g. 'enrol', 'qtype')
413 * return void
415 function upgrade_plugins($type, $startcallback, $endcallback, $verbose) {
416 global $CFG, $DB;
418 /// special cases
419 if ($type === 'mod') {
420 return upgrade_plugins_modules($startcallback, $endcallback, $verbose);
421 } else if ($type === 'block') {
422 return upgrade_plugins_blocks($startcallback, $endcallback, $verbose);
425 $plugs = core_component::get_plugin_list($type);
427 foreach ($plugs as $plug=>$fullplug) {
428 // Reset time so that it works when installing a large number of plugins
429 core_php_time_limit::raise(600);
430 $component = clean_param($type.'_'.$plug, PARAM_COMPONENT); // standardised plugin name
432 // check plugin dir is valid name
433 if (empty($component)) {
434 throw new plugin_defective_exception($type.'_'.$plug, 'Invalid plugin directory name.');
437 if (!is_readable($fullplug.'/version.php')) {
438 continue;
441 $plugin = new stdClass();
442 $plugin->version = null;
443 $module = $plugin; // Prevent some notices when plugin placed in wrong directory.
444 require($fullplug.'/version.php'); // defines $plugin with version etc
445 unset($module);
447 // if plugin tells us it's full name we may check the location
448 if (isset($plugin->component)) {
449 if ($plugin->component !== $component) {
450 throw new plugin_misplaced_exception($plugin->component, null, $fullplug);
454 if (empty($plugin->version)) {
455 throw new plugin_defective_exception($component, 'Missing version value in version.php');
458 $plugin->name = $plug;
459 $plugin->fullname = $component;
461 if (!empty($plugin->requires)) {
462 if ($plugin->requires > $CFG->version) {
463 throw new upgrade_requires_exception($component, $plugin->version, $CFG->version, $plugin->requires);
464 } else if ($plugin->requires < 2010000000) {
465 throw new plugin_defective_exception($component, 'Plugin is not compatible with Moodle 2.x or later.');
469 // try to recover from interrupted install.php if needed
470 if (file_exists($fullplug.'/db/install.php')) {
471 if (get_config($plugin->fullname, 'installrunning')) {
472 require_once($fullplug.'/db/install.php');
473 $recover_install_function = 'xmldb_'.$plugin->fullname.'_install_recovery';
474 if (function_exists($recover_install_function)) {
475 $startcallback($component, true, $verbose);
476 $recover_install_function();
477 unset_config('installrunning', $plugin->fullname);
478 update_capabilities($component);
479 log_update_descriptions($component);
480 external_update_descriptions($component);
481 events_update_definition($component);
482 \core\task\manager::reset_scheduled_tasks_for_component($component);
483 message_update_providers($component);
484 if ($type === 'message') {
485 message_update_processors($plug);
487 upgrade_plugin_mnet_functions($component);
488 $endcallback($component, true, $verbose);
493 $installedversion = $DB->get_field('config_plugins', 'value', array('name'=>'version', 'plugin'=>$component)); // No caching!
494 if (empty($installedversion)) { // new installation
495 $startcallback($component, true, $verbose);
497 /// Install tables if defined
498 if (file_exists($fullplug.'/db/install.xml')) {
499 $DB->get_manager()->install_from_xmldb_file($fullplug.'/db/install.xml');
502 /// store version
503 upgrade_plugin_savepoint(true, $plugin->version, $type, $plug, false);
505 /// execute post install file
506 if (file_exists($fullplug.'/db/install.php')) {
507 require_once($fullplug.'/db/install.php');
508 set_config('installrunning', 1, $plugin->fullname);
509 $post_install_function = 'xmldb_'.$plugin->fullname.'_install';
510 $post_install_function();
511 unset_config('installrunning', $plugin->fullname);
514 /// Install various components
515 update_capabilities($component);
516 log_update_descriptions($component);
517 external_update_descriptions($component);
518 events_update_definition($component);
519 \core\task\manager::reset_scheduled_tasks_for_component($component);
520 message_update_providers($component);
521 if ($type === 'message') {
522 message_update_processors($plug);
524 upgrade_plugin_mnet_functions($component);
525 $endcallback($component, true, $verbose);
527 } else if ($installedversion < $plugin->version) { // upgrade
528 /// Run the upgrade function for the plugin.
529 $startcallback($component, false, $verbose);
531 if (is_readable($fullplug.'/db/upgrade.php')) {
532 require_once($fullplug.'/db/upgrade.php'); // defines upgrading function
534 $newupgrade_function = 'xmldb_'.$plugin->fullname.'_upgrade';
535 $result = $newupgrade_function($installedversion);
536 } else {
537 $result = true;
540 $installedversion = $DB->get_field('config_plugins', 'value', array('name'=>'version', 'plugin'=>$component)); // No caching!
541 if ($installedversion < $plugin->version) {
542 // store version if not already there
543 upgrade_plugin_savepoint($result, $plugin->version, $type, $plug, false);
546 /// Upgrade various components
547 update_capabilities($component);
548 log_update_descriptions($component);
549 external_update_descriptions($component);
550 events_update_definition($component);
551 \core\task\manager::reset_scheduled_tasks_for_component($component);
552 message_update_providers($component);
553 if ($type === 'message') {
554 // Ugly hack!
555 message_update_processors($plug);
557 upgrade_plugin_mnet_functions($component);
558 $endcallback($component, false, $verbose);
560 } else if ($installedversion > $plugin->version) {
561 throw new downgrade_exception($component, $installedversion, $plugin->version);
567 * Find and check all modules and load them up or upgrade them if necessary
569 * @global object
570 * @global object
572 function upgrade_plugins_modules($startcallback, $endcallback, $verbose) {
573 global $CFG, $DB;
575 $mods = core_component::get_plugin_list('mod');
577 foreach ($mods as $mod=>$fullmod) {
579 if ($mod === 'NEWMODULE') { // Someone has unzipped the template, ignore it
580 continue;
583 $component = clean_param('mod_'.$mod, PARAM_COMPONENT);
585 // check module dir is valid name
586 if (empty($component)) {
587 throw new plugin_defective_exception('mod_'.$mod, 'Invalid plugin directory name.');
590 if (!is_readable($fullmod.'/version.php')) {
591 throw new plugin_defective_exception($component, 'Missing version.php');
594 // TODO: Support for $module will end with Moodle 2.10 by MDL-43896. Was deprecated for Moodle 2.7 by MDL-43040.
595 $plugin = new stdClass();
596 $plugin->version = null;
597 $module = $plugin;
598 require($fullmod .'/version.php'); // Defines $plugin with version etc.
599 $plugin = clone($module);
600 unset($module->version);
601 unset($module->component);
602 unset($module->dependencies);
603 unset($module->release);
605 // if plugin tells us it's full name we may check the location
606 if (isset($plugin->component)) {
607 if ($plugin->component !== $component) {
608 throw new plugin_misplaced_exception($plugin->component, null, $fullmod);
612 if (empty($plugin->version)) {
613 // Version must be always set now!
614 throw new plugin_defective_exception($component, 'Missing version value in version.php');
617 if (!empty($plugin->requires)) {
618 if ($plugin->requires > $CFG->version) {
619 throw new upgrade_requires_exception($component, $plugin->version, $CFG->version, $plugin->requires);
620 } else if ($plugin->requires < 2010000000) {
621 throw new plugin_defective_exception($component, 'Plugin is not compatible with Moodle 2.x or later.');
625 if (empty($module->cron)) {
626 $module->cron = 0;
629 // all modules must have en lang pack
630 if (!is_readable("$fullmod/lang/en/$mod.php")) {
631 throw new plugin_defective_exception($component, 'Missing mandatory en language pack.');
634 $module->name = $mod; // The name MUST match the directory
636 $installedversion = $DB->get_field('config_plugins', 'value', array('name'=>'version', 'plugin'=>$component)); // No caching!
638 if (file_exists($fullmod.'/db/install.php')) {
639 if (get_config($module->name, 'installrunning')) {
640 require_once($fullmod.'/db/install.php');
641 $recover_install_function = 'xmldb_'.$module->name.'_install_recovery';
642 if (function_exists($recover_install_function)) {
643 $startcallback($component, true, $verbose);
644 $recover_install_function();
645 unset_config('installrunning', $module->name);
646 // Install various components too
647 update_capabilities($component);
648 log_update_descriptions($component);
649 external_update_descriptions($component);
650 events_update_definition($component);
651 \core\task\manager::reset_scheduled_tasks_for_component($component);
652 message_update_providers($component);
653 upgrade_plugin_mnet_functions($component);
654 $endcallback($component, true, $verbose);
659 if (empty($installedversion)) {
660 $startcallback($component, true, $verbose);
662 /// Execute install.xml (XMLDB) - must be present in all modules
663 $DB->get_manager()->install_from_xmldb_file($fullmod.'/db/install.xml');
665 /// Add record into modules table - may be needed in install.php already
666 $module->id = $DB->insert_record('modules', $module);
667 upgrade_mod_savepoint(true, $plugin->version, $module->name, false);
669 /// Post installation hook - optional
670 if (file_exists("$fullmod/db/install.php")) {
671 require_once("$fullmod/db/install.php");
672 // Set installation running flag, we need to recover after exception or error
673 set_config('installrunning', 1, $module->name);
674 $post_install_function = 'xmldb_'.$module->name.'_install';
675 $post_install_function();
676 unset_config('installrunning', $module->name);
679 /// Install various components
680 update_capabilities($component);
681 log_update_descriptions($component);
682 external_update_descriptions($component);
683 events_update_definition($component);
684 \core\task\manager::reset_scheduled_tasks_for_component($component);
685 message_update_providers($component);
686 upgrade_plugin_mnet_functions($component);
688 $endcallback($component, true, $verbose);
690 } else if ($installedversion < $plugin->version) {
691 /// If versions say that we need to upgrade but no upgrade files are available, notify and continue
692 $startcallback($component, false, $verbose);
694 if (is_readable($fullmod.'/db/upgrade.php')) {
695 require_once($fullmod.'/db/upgrade.php'); // defines new upgrading function
696 $newupgrade_function = 'xmldb_'.$module->name.'_upgrade';
697 $result = $newupgrade_function($installedversion, $module);
698 } else {
699 $result = true;
702 $installedversion = $DB->get_field('config_plugins', 'value', array('name'=>'version', 'plugin'=>$component)); // No caching!
703 $currmodule = $DB->get_record('modules', array('name'=>$module->name));
704 if ($installedversion < $plugin->version) {
705 // store version if not already there
706 upgrade_mod_savepoint($result, $plugin->version, $mod, false);
709 // update cron flag if needed
710 if ($currmodule->cron != $module->cron) {
711 $DB->set_field('modules', 'cron', $module->cron, array('name' => $module->name));
714 // Upgrade various components
715 update_capabilities($component);
716 log_update_descriptions($component);
717 external_update_descriptions($component);
718 events_update_definition($component);
719 \core\task\manager::reset_scheduled_tasks_for_component($component);
720 message_update_providers($component);
721 upgrade_plugin_mnet_functions($component);
723 $endcallback($component, false, $verbose);
725 } else if ($installedversion > $plugin->version) {
726 throw new downgrade_exception($component, $installedversion, $plugin->version);
733 * This function finds all available blocks and install them
734 * into blocks table or do all the upgrade process if newer.
736 * @global object
737 * @global object
739 function upgrade_plugins_blocks($startcallback, $endcallback, $verbose) {
740 global $CFG, $DB;
742 require_once($CFG->dirroot.'/blocks/moodleblock.class.php');
744 $blocktitles = array(); // we do not want duplicate titles
746 //Is this a first install
747 $first_install = null;
749 $blocks = core_component::get_plugin_list('block');
751 foreach ($blocks as $blockname=>$fullblock) {
753 if (is_null($first_install)) {
754 $first_install = ($DB->count_records('block_instances') == 0);
757 if ($blockname === 'NEWBLOCK') { // Someone has unzipped the template, ignore it
758 continue;
761 $component = clean_param('block_'.$blockname, PARAM_COMPONENT);
763 // check block dir is valid name
764 if (empty($component)) {
765 throw new plugin_defective_exception('block_'.$blockname, 'Invalid plugin directory name.');
768 if (!is_readable($fullblock.'/version.php')) {
769 throw new plugin_defective_exception('block/'.$blockname, 'Missing version.php file.');
771 $plugin = new stdClass();
772 $plugin->version = null;
773 $plugin->cron = 0;
774 $module = $plugin; // Prevent some notices when module placed in wrong directory.
775 include($fullblock.'/version.php');
776 unset($module);
777 $block = clone($plugin);
778 unset($block->version);
779 unset($block->component);
780 unset($block->dependencies);
781 unset($block->release);
783 // if plugin tells us it's full name we may check the location
784 if (isset($plugin->component)) {
785 if ($plugin->component !== $component) {
786 throw new plugin_misplaced_exception($plugin->component, null, $fullblock);
790 if (empty($plugin->version)) {
791 throw new plugin_defective_exception($component, 'Missing block version.');
794 if (!empty($plugin->requires)) {
795 if ($plugin->requires > $CFG->version) {
796 throw new upgrade_requires_exception($component, $plugin->version, $CFG->version, $plugin->requires);
797 } else if ($plugin->requires < 2010000000) {
798 throw new plugin_defective_exception($component, 'Plugin is not compatible with Moodle 2.x or later.');
802 if (!is_readable($fullblock.'/block_'.$blockname.'.php')) {
803 throw new plugin_defective_exception('block/'.$blockname, 'Missing main block class file.');
805 include_once($fullblock.'/block_'.$blockname.'.php');
807 $classname = 'block_'.$blockname;
809 if (!class_exists($classname)) {
810 throw new plugin_defective_exception($component, 'Can not load main class.');
813 $blockobj = new $classname; // This is what we'll be testing
814 $blocktitle = $blockobj->get_title();
816 // OK, it's as we all hoped. For further tests, the object will do them itself.
817 if (!$blockobj->_self_test()) {
818 throw new plugin_defective_exception($component, 'Self test failed.');
821 $block->name = $blockname; // The name MUST match the directory
823 $installedversion = $DB->get_field('config_plugins', 'value', array('name'=>'version', 'plugin'=>$component)); // No caching!
825 if (file_exists($fullblock.'/db/install.php')) {
826 if (get_config('block_'.$blockname, 'installrunning')) {
827 require_once($fullblock.'/db/install.php');
828 $recover_install_function = 'xmldb_block_'.$blockname.'_install_recovery';
829 if (function_exists($recover_install_function)) {
830 $startcallback($component, true, $verbose);
831 $recover_install_function();
832 unset_config('installrunning', 'block_'.$blockname);
833 // Install various components
834 update_capabilities($component);
835 log_update_descriptions($component);
836 external_update_descriptions($component);
837 events_update_definition($component);
838 \core\task\manager::reset_scheduled_tasks_for_component($component);
839 message_update_providers($component);
840 upgrade_plugin_mnet_functions($component);
841 $endcallback($component, true, $verbose);
846 if (empty($installedversion)) { // block not installed yet, so install it
847 $conflictblock = array_search($blocktitle, $blocktitles);
848 if ($conflictblock !== false) {
849 // Duplicate block titles are not allowed, they confuse people
850 // AND PHP's associative arrays ;)
851 throw new plugin_defective_exception($component, get_string('blocknameconflict', 'error', (object)array('name'=>$block->name, 'conflict'=>$conflictblock)));
853 $startcallback($component, true, $verbose);
855 if (file_exists($fullblock.'/db/install.xml')) {
856 $DB->get_manager()->install_from_xmldb_file($fullblock.'/db/install.xml');
858 $block->id = $DB->insert_record('block', $block);
859 upgrade_block_savepoint(true, $plugin->version, $block->name, false);
861 if (file_exists($fullblock.'/db/install.php')) {
862 require_once($fullblock.'/db/install.php');
863 // Set installation running flag, we need to recover after exception or error
864 set_config('installrunning', 1, 'block_'.$blockname);
865 $post_install_function = 'xmldb_block_'.$blockname.'_install';
866 $post_install_function();
867 unset_config('installrunning', 'block_'.$blockname);
870 $blocktitles[$block->name] = $blocktitle;
872 // Install various components
873 update_capabilities($component);
874 log_update_descriptions($component);
875 external_update_descriptions($component);
876 events_update_definition($component);
877 \core\task\manager::reset_scheduled_tasks_for_component($component);
878 message_update_providers($component);
879 upgrade_plugin_mnet_functions($component);
881 $endcallback($component, true, $verbose);
883 } else if ($installedversion < $plugin->version) {
884 $startcallback($component, false, $verbose);
886 if (is_readable($fullblock.'/db/upgrade.php')) {
887 require_once($fullblock.'/db/upgrade.php'); // defines new upgrading function
888 $newupgrade_function = 'xmldb_block_'.$blockname.'_upgrade';
889 $result = $newupgrade_function($installedversion, $block);
890 } else {
891 $result = true;
894 $installedversion = $DB->get_field('config_plugins', 'value', array('name'=>'version', 'plugin'=>$component)); // No caching!
895 $currblock = $DB->get_record('block', array('name'=>$block->name));
896 if ($installedversion < $plugin->version) {
897 // store version if not already there
898 upgrade_block_savepoint($result, $plugin->version, $block->name, false);
901 if ($currblock->cron != $block->cron) {
902 // update cron flag if needed
903 $DB->set_field('block', 'cron', $block->cron, array('id' => $currblock->id));
906 // Upgrade various components
907 update_capabilities($component);
908 log_update_descriptions($component);
909 external_update_descriptions($component);
910 events_update_definition($component);
911 \core\task\manager::reset_scheduled_tasks_for_component($component);
912 message_update_providers($component);
913 upgrade_plugin_mnet_functions($component);
915 $endcallback($component, false, $verbose);
917 } else if ($installedversion > $plugin->version) {
918 throw new downgrade_exception($component, $installedversion, $plugin->version);
923 // Finally, if we are in the first_install of BLOCKS setup frontpage and admin page blocks
924 if ($first_install) {
925 //Iterate over each course - there should be only site course here now
926 if ($courses = $DB->get_records('course')) {
927 foreach ($courses as $course) {
928 blocks_add_default_course_blocks($course);
932 blocks_add_default_system_blocks();
938 * Log_display description function used during install and upgrade.
940 * @param string $component name of component (moodle, mod_assignment, etc.)
941 * @return void
943 function log_update_descriptions($component) {
944 global $DB;
946 $defpath = core_component::get_component_directory($component).'/db/log.php';
948 if (!file_exists($defpath)) {
949 $DB->delete_records('log_display', array('component'=>$component));
950 return;
953 // load new info
954 $logs = array();
955 include($defpath);
956 $newlogs = array();
957 foreach ($logs as $log) {
958 $newlogs[$log['module'].'-'.$log['action']] = $log; // kind of unique name
960 unset($logs);
961 $logs = $newlogs;
963 $fields = array('module', 'action', 'mtable', 'field');
964 // update all log fist
965 $dblogs = $DB->get_records('log_display', array('component'=>$component));
966 foreach ($dblogs as $dblog) {
967 $name = $dblog->module.'-'.$dblog->action;
969 if (empty($logs[$name])) {
970 $DB->delete_records('log_display', array('id'=>$dblog->id));
971 continue;
974 $log = $logs[$name];
975 unset($logs[$name]);
977 $update = false;
978 foreach ($fields as $field) {
979 if ($dblog->$field != $log[$field]) {
980 $dblog->$field = $log[$field];
981 $update = true;
984 if ($update) {
985 $DB->update_record('log_display', $dblog);
988 foreach ($logs as $log) {
989 $dblog = (object)$log;
990 $dblog->component = $component;
991 $DB->insert_record('log_display', $dblog);
996 * Web service discovery function used during install and upgrade.
997 * @param string $component name of component (moodle, mod_assignment, etc.)
998 * @return void
1000 function external_update_descriptions($component) {
1001 global $DB, $CFG;
1003 $defpath = core_component::get_component_directory($component).'/db/services.php';
1005 if (!file_exists($defpath)) {
1006 require_once($CFG->dirroot.'/lib/externallib.php');
1007 external_delete_descriptions($component);
1008 return;
1011 // load new info
1012 $functions = array();
1013 $services = array();
1014 include($defpath);
1016 // update all function fist
1017 $dbfunctions = $DB->get_records('external_functions', array('component'=>$component));
1018 foreach ($dbfunctions as $dbfunction) {
1019 if (empty($functions[$dbfunction->name])) {
1020 $DB->delete_records('external_functions', array('id'=>$dbfunction->id));
1021 // do not delete functions from external_services_functions, beacuse
1022 // we want to notify admins when functions used in custom services disappear
1024 //TODO: this looks wrong, we have to delete it eventually (skodak)
1025 continue;
1028 $function = $functions[$dbfunction->name];
1029 unset($functions[$dbfunction->name]);
1030 $function['classpath'] = empty($function['classpath']) ? null : $function['classpath'];
1032 $update = false;
1033 if ($dbfunction->classname != $function['classname']) {
1034 $dbfunction->classname = $function['classname'];
1035 $update = true;
1037 if ($dbfunction->methodname != $function['methodname']) {
1038 $dbfunction->methodname = $function['methodname'];
1039 $update = true;
1041 if ($dbfunction->classpath != $function['classpath']) {
1042 $dbfunction->classpath = $function['classpath'];
1043 $update = true;
1045 $functioncapabilities = array_key_exists('capabilities', $function)?$function['capabilities']:'';
1046 if ($dbfunction->capabilities != $functioncapabilities) {
1047 $dbfunction->capabilities = $functioncapabilities;
1048 $update = true;
1050 if ($update) {
1051 $DB->update_record('external_functions', $dbfunction);
1054 foreach ($functions as $fname => $function) {
1055 $dbfunction = new stdClass();
1056 $dbfunction->name = $fname;
1057 $dbfunction->classname = $function['classname'];
1058 $dbfunction->methodname = $function['methodname'];
1059 $dbfunction->classpath = empty($function['classpath']) ? null : $function['classpath'];
1060 $dbfunction->component = $component;
1061 $dbfunction->capabilities = array_key_exists('capabilities', $function)?$function['capabilities']:'';
1062 $dbfunction->id = $DB->insert_record('external_functions', $dbfunction);
1064 unset($functions);
1066 // now deal with services
1067 $dbservices = $DB->get_records('external_services', array('component'=>$component));
1068 foreach ($dbservices as $dbservice) {
1069 if (empty($services[$dbservice->name])) {
1070 $DB->delete_records('external_tokens', array('externalserviceid'=>$dbservice->id));
1071 $DB->delete_records('external_services_functions', array('externalserviceid'=>$dbservice->id));
1072 $DB->delete_records('external_services_users', array('externalserviceid'=>$dbservice->id));
1073 $DB->delete_records('external_services', array('id'=>$dbservice->id));
1074 continue;
1076 $service = $services[$dbservice->name];
1077 unset($services[$dbservice->name]);
1078 $service['enabled'] = empty($service['enabled']) ? 0 : $service['enabled'];
1079 $service['requiredcapability'] = empty($service['requiredcapability']) ? null : $service['requiredcapability'];
1080 $service['restrictedusers'] = !isset($service['restrictedusers']) ? 1 : $service['restrictedusers'];
1081 $service['downloadfiles'] = !isset($service['downloadfiles']) ? 0 : $service['downloadfiles'];
1082 $service['uploadfiles'] = !isset($service['uploadfiles']) ? 0 : $service['uploadfiles'];
1083 $service['shortname'] = !isset($service['shortname']) ? null : $service['shortname'];
1085 $update = false;
1086 if ($dbservice->requiredcapability != $service['requiredcapability']) {
1087 $dbservice->requiredcapability = $service['requiredcapability'];
1088 $update = true;
1090 if ($dbservice->restrictedusers != $service['restrictedusers']) {
1091 $dbservice->restrictedusers = $service['restrictedusers'];
1092 $update = true;
1094 if ($dbservice->downloadfiles != $service['downloadfiles']) {
1095 $dbservice->downloadfiles = $service['downloadfiles'];
1096 $update = true;
1098 if ($dbservice->uploadfiles != $service['uploadfiles']) {
1099 $dbservice->uploadfiles = $service['uploadfiles'];
1100 $update = true;
1102 //if shortname is not a PARAM_ALPHANUMEXT, fail (tested here for service update and creation)
1103 if (isset($service['shortname']) and
1104 (clean_param($service['shortname'], PARAM_ALPHANUMEXT) != $service['shortname'])) {
1105 throw new moodle_exception('installserviceshortnameerror', 'webservice', '', $service['shortname']);
1107 if ($dbservice->shortname != $service['shortname']) {
1108 //check that shortname is unique
1109 if (isset($service['shortname'])) { //we currently accepts multiple shortname == null
1110 $existingservice = $DB->get_record('external_services',
1111 array('shortname' => $service['shortname']));
1112 if (!empty($existingservice)) {
1113 throw new moodle_exception('installexistingserviceshortnameerror', 'webservice', '', $service['shortname']);
1116 $dbservice->shortname = $service['shortname'];
1117 $update = true;
1119 if ($update) {
1120 $DB->update_record('external_services', $dbservice);
1123 $functions = $DB->get_records('external_services_functions', array('externalserviceid'=>$dbservice->id));
1124 foreach ($functions as $function) {
1125 $key = array_search($function->functionname, $service['functions']);
1126 if ($key === false) {
1127 $DB->delete_records('external_services_functions', array('id'=>$function->id));
1128 } else {
1129 unset($service['functions'][$key]);
1132 foreach ($service['functions'] as $fname) {
1133 $newf = new stdClass();
1134 $newf->externalserviceid = $dbservice->id;
1135 $newf->functionname = $fname;
1136 $DB->insert_record('external_services_functions', $newf);
1138 unset($functions);
1140 foreach ($services as $name => $service) {
1141 //check that shortname is unique
1142 if (isset($service['shortname'])) { //we currently accepts multiple shortname == null
1143 $existingservice = $DB->get_record('external_services',
1144 array('shortname' => $service['shortname']));
1145 if (!empty($existingservice)) {
1146 throw new moodle_exception('installserviceshortnameerror', 'webservice');
1150 $dbservice = new stdClass();
1151 $dbservice->name = $name;
1152 $dbservice->enabled = empty($service['enabled']) ? 0 : $service['enabled'];
1153 $dbservice->requiredcapability = empty($service['requiredcapability']) ? null : $service['requiredcapability'];
1154 $dbservice->restrictedusers = !isset($service['restrictedusers']) ? 1 : $service['restrictedusers'];
1155 $dbservice->downloadfiles = !isset($service['downloadfiles']) ? 0 : $service['downloadfiles'];
1156 $dbservice->uploadfiles = !isset($service['uploadfiles']) ? 0 : $service['uploadfiles'];
1157 $dbservice->shortname = !isset($service['shortname']) ? null : $service['shortname'];
1158 $dbservice->component = $component;
1159 $dbservice->timecreated = time();
1160 $dbservice->id = $DB->insert_record('external_services', $dbservice);
1161 foreach ($service['functions'] as $fname) {
1162 $newf = new stdClass();
1163 $newf->externalserviceid = $dbservice->id;
1164 $newf->functionname = $fname;
1165 $DB->insert_record('external_services_functions', $newf);
1171 * upgrade logging functions
1173 function upgrade_handle_exception($ex, $plugin = null) {
1174 global $CFG;
1176 // rollback everything, we need to log all upgrade problems
1177 abort_all_db_transactions();
1179 $info = get_exception_info($ex);
1181 // First log upgrade error
1182 upgrade_log(UPGRADE_LOG_ERROR, $plugin, 'Exception: ' . get_class($ex), $info->message, $info->backtrace);
1184 // Always turn on debugging - admins need to know what is going on
1185 set_debugging(DEBUG_DEVELOPER, true);
1187 default_exception_handler($ex, true, $plugin);
1191 * Adds log entry into upgrade_log table
1193 * @param int $type UPGRADE_LOG_NORMAL, UPGRADE_LOG_NOTICE or UPGRADE_LOG_ERROR
1194 * @param string $plugin frankenstyle component name
1195 * @param string $info short description text of log entry
1196 * @param string $details long problem description
1197 * @param string $backtrace string used for errors only
1198 * @return void
1200 function upgrade_log($type, $plugin, $info, $details=null, $backtrace=null) {
1201 global $DB, $USER, $CFG;
1203 if (empty($plugin)) {
1204 $plugin = 'core';
1207 list($plugintype, $pluginname) = core_component::normalize_component($plugin);
1208 $component = is_null($pluginname) ? $plugintype : $plugintype . '_' . $pluginname;
1210 $backtrace = format_backtrace($backtrace, true);
1212 $currentversion = null;
1213 $targetversion = null;
1215 //first try to find out current version number
1216 if ($plugintype === 'core') {
1217 //main
1218 $currentversion = $CFG->version;
1220 $version = null;
1221 include("$CFG->dirroot/version.php");
1222 $targetversion = $version;
1224 } else {
1225 $pluginversion = get_config($component, 'version');
1226 if (!empty($pluginversion)) {
1227 $currentversion = $pluginversion;
1229 $cd = core_component::get_component_directory($component);
1230 if (file_exists("$cd/version.php")) {
1231 $plugin = new stdClass();
1232 $plugin->version = null;
1233 $module = $plugin;
1234 include("$cd/version.php");
1235 $targetversion = $plugin->version;
1239 $log = new stdClass();
1240 $log->type = $type;
1241 $log->plugin = $component;
1242 $log->version = $currentversion;
1243 $log->targetversion = $targetversion;
1244 $log->info = $info;
1245 $log->details = $details;
1246 $log->backtrace = $backtrace;
1247 $log->userid = $USER->id;
1248 $log->timemodified = time();
1249 try {
1250 $DB->insert_record('upgrade_log', $log);
1251 } catch (Exception $ignored) {
1252 // possible during install or 2.0 upgrade
1257 * Marks start of upgrade, blocks any other access to site.
1258 * The upgrade is finished at the end of script or after timeout.
1260 * @global object
1261 * @global object
1262 * @global object
1264 function upgrade_started($preinstall=false) {
1265 global $CFG, $DB, $PAGE, $OUTPUT;
1267 static $started = false;
1269 if ($preinstall) {
1270 ignore_user_abort(true);
1271 upgrade_setup_debug(true);
1273 } else if ($started) {
1274 upgrade_set_timeout(120);
1276 } else {
1277 if (!CLI_SCRIPT and !$PAGE->headerprinted) {
1278 $strupgrade = get_string('upgradingversion', 'admin');
1279 $PAGE->set_pagelayout('maintenance');
1280 upgrade_init_javascript();
1281 $PAGE->set_title($strupgrade.' - Moodle '.$CFG->target_release);
1282 $PAGE->set_heading($strupgrade);
1283 $PAGE->navbar->add($strupgrade);
1284 $PAGE->set_cacheable(false);
1285 echo $OUTPUT->header();
1288 ignore_user_abort(true);
1289 core_shutdown_manager::register_function('upgrade_finished_handler');
1290 upgrade_setup_debug(true);
1291 set_config('upgraderunning', time()+300);
1292 $started = true;
1297 * Internal function - executed if upgrade interrupted.
1299 function upgrade_finished_handler() {
1300 upgrade_finished();
1304 * Indicates upgrade is finished.
1306 * This function may be called repeatedly.
1308 * @global object
1309 * @global object
1311 function upgrade_finished($continueurl=null) {
1312 global $CFG, $DB, $OUTPUT;
1314 if (!empty($CFG->upgraderunning)) {
1315 unset_config('upgraderunning');
1316 // We have to forcefully purge the caches using the writer here.
1317 // This has to be done after we unset the config var. If someone hits the site while this is set they will
1318 // cause the config values to propogate to the caches.
1319 // Caches are purged after the last step in an upgrade but there is several code routines that exceute between
1320 // then and now that leaving a window for things to fall out of sync.
1321 cache_helper::purge_all(true);
1322 upgrade_setup_debug(false);
1323 ignore_user_abort(false);
1324 if ($continueurl) {
1325 echo $OUTPUT->continue_button($continueurl);
1326 echo $OUTPUT->footer();
1327 die;
1333 * @global object
1334 * @global object
1336 function upgrade_setup_debug($starting) {
1337 global $CFG, $DB;
1339 static $originaldebug = null;
1341 if ($starting) {
1342 if ($originaldebug === null) {
1343 $originaldebug = $DB->get_debug();
1345 if (!empty($CFG->upgradeshowsql)) {
1346 $DB->set_debug(true);
1348 } else {
1349 $DB->set_debug($originaldebug);
1353 function print_upgrade_separator() {
1354 if (!CLI_SCRIPT) {
1355 echo '<hr />';
1360 * Default start upgrade callback
1361 * @param string $plugin
1362 * @param bool $installation true if installation, false means upgrade
1364 function print_upgrade_part_start($plugin, $installation, $verbose) {
1365 global $OUTPUT;
1366 if (empty($plugin) or $plugin == 'moodle') {
1367 upgrade_started($installation); // does not store upgrade running flag yet
1368 if ($verbose) {
1369 echo $OUTPUT->heading(get_string('coresystem'));
1371 } else {
1372 upgrade_started();
1373 if ($verbose) {
1374 echo $OUTPUT->heading($plugin);
1377 if ($installation) {
1378 if (empty($plugin) or $plugin == 'moodle') {
1379 // no need to log - log table not yet there ;-)
1380 } else {
1381 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Starting plugin installation');
1383 } else {
1384 if (empty($plugin) or $plugin == 'moodle') {
1385 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Starting core upgrade');
1386 } else {
1387 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Starting plugin upgrade');
1393 * Default end upgrade callback
1394 * @param string $plugin
1395 * @param bool $installation true if installation, false means upgrade
1397 function print_upgrade_part_end($plugin, $installation, $verbose) {
1398 global $OUTPUT;
1399 upgrade_started();
1400 if ($installation) {
1401 if (empty($plugin) or $plugin == 'moodle') {
1402 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Core installed');
1403 } else {
1404 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Plugin installed');
1406 } else {
1407 if (empty($plugin) or $plugin == 'moodle') {
1408 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Core upgraded');
1409 } else {
1410 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Plugin upgraded');
1413 if ($verbose) {
1414 echo $OUTPUT->notification(get_string('success'), 'notifysuccess');
1415 print_upgrade_separator();
1420 * Sets up JS code required for all upgrade scripts.
1421 * @global object
1423 function upgrade_init_javascript() {
1424 global $PAGE;
1425 // scroll to the end of each upgrade page so that ppl see either error or continue button,
1426 // no need to scroll continuously any more, it is enough to jump to end once the footer is printed ;-)
1427 $js = "window.scrollTo(0, 5000000);";
1428 $PAGE->requires->js_init_code($js);
1432 * Try to upgrade the given language pack (or current language)
1434 * @param string $lang the code of the language to update, defaults to the current language
1436 function upgrade_language_pack($lang = null) {
1437 global $CFG;
1439 if (!empty($CFG->skiplangupgrade)) {
1440 return;
1443 if (!file_exists("$CFG->dirroot/$CFG->admin/tool/langimport/lib.php")) {
1444 // weird, somebody uninstalled the import utility
1445 return;
1448 if (!$lang) {
1449 $lang = current_language();
1452 if (!get_string_manager()->translation_exists($lang)) {
1453 return;
1456 get_string_manager()->reset_caches();
1458 if ($lang === 'en') {
1459 return; // Nothing to do
1462 upgrade_started(false);
1464 require_once("$CFG->dirroot/$CFG->admin/tool/langimport/lib.php");
1465 tool_langimport_preupgrade_update($lang);
1467 get_string_manager()->reset_caches();
1469 print_upgrade_separator();
1473 * Install core moodle tables and initialize
1474 * @param float $version target version
1475 * @param bool $verbose
1476 * @return void, may throw exception
1478 function install_core($version, $verbose) {
1479 global $CFG, $DB;
1481 // We can not call purge_all_caches() yet, make sure the temp and cache dirs exist and are empty.
1482 remove_dir($CFG->cachedir.'', true);
1483 make_cache_directory('', true);
1485 remove_dir($CFG->localcachedir.'', true);
1486 make_localcache_directory('', true);
1488 remove_dir($CFG->tempdir.'', true);
1489 make_temp_directory('', true);
1491 remove_dir($CFG->dataroot.'/muc', true);
1492 make_writable_directory($CFG->dataroot.'/muc', true);
1494 try {
1495 core_php_time_limit::raise(600);
1496 print_upgrade_part_start('moodle', true, $verbose); // does not store upgrade running flag
1498 $DB->get_manager()->install_from_xmldb_file("$CFG->libdir/db/install.xml");
1499 upgrade_started(); // we want the flag to be stored in config table ;-)
1501 // set all core default records and default settings
1502 require_once("$CFG->libdir/db/install.php");
1503 xmldb_main_install(); // installs the capabilities too
1505 // store version
1506 upgrade_main_savepoint(true, $version, false);
1508 // Continue with the installation
1509 log_update_descriptions('moodle');
1510 external_update_descriptions('moodle');
1511 events_update_definition('moodle');
1512 \core\task\manager::reset_scheduled_tasks_for_component('moodle');
1513 message_update_providers('moodle');
1515 // Write default settings unconditionally
1516 admin_apply_default_settings(NULL, true);
1518 print_upgrade_part_end(null, true, $verbose);
1520 // Purge all caches. They're disabled but this ensures that we don't have any persistent data just in case something
1521 // during installation didn't use APIs.
1522 cache_helper::purge_all();
1523 } catch (exception $ex) {
1524 upgrade_handle_exception($ex);
1529 * Upgrade moodle core
1530 * @param float $version target version
1531 * @param bool $verbose
1532 * @return void, may throw exception
1534 function upgrade_core($version, $verbose) {
1535 global $CFG, $SITE, $DB, $COURSE;
1537 raise_memory_limit(MEMORY_EXTRA);
1539 require_once($CFG->libdir.'/db/upgrade.php'); // Defines upgrades
1541 try {
1542 // Reset caches before any output.
1543 cache_helper::purge_all(true);
1544 purge_all_caches();
1546 // Upgrade current language pack if we can
1547 upgrade_language_pack();
1549 print_upgrade_part_start('moodle', false, $verbose);
1551 // Pre-upgrade scripts for local hack workarounds.
1552 $preupgradefile = "$CFG->dirroot/local/preupgrade.php";
1553 if (file_exists($preupgradefile)) {
1554 core_php_time_limit::raise();
1555 require($preupgradefile);
1556 // Reset upgrade timeout to default.
1557 upgrade_set_timeout();
1560 $result = xmldb_main_upgrade($CFG->version);
1561 if ($version > $CFG->version) {
1562 // store version if not already there
1563 upgrade_main_savepoint($result, $version, false);
1566 // In case structure of 'course' table has been changed and we forgot to update $SITE, re-read it from db.
1567 $SITE = $DB->get_record('course', array('id' => $SITE->id));
1568 $COURSE = clone($SITE);
1570 // perform all other component upgrade routines
1571 update_capabilities('moodle');
1572 log_update_descriptions('moodle');
1573 external_update_descriptions('moodle');
1574 events_update_definition('moodle');
1575 \core\task\manager::reset_scheduled_tasks_for_component('moodle');
1576 message_update_providers('moodle');
1577 // Update core definitions.
1578 cache_helper::update_definitions(true);
1580 // Purge caches again, just to be sure we arn't holding onto old stuff now.
1581 cache_helper::purge_all(true);
1582 purge_all_caches();
1584 // Clean up contexts - more and more stuff depends on existence of paths and contexts
1585 context_helper::cleanup_instances();
1586 context_helper::create_instances(null, false);
1587 context_helper::build_all_paths(false);
1588 $syscontext = context_system::instance();
1589 $syscontext->mark_dirty();
1591 print_upgrade_part_end('moodle', false, $verbose);
1592 } catch (Exception $ex) {
1593 upgrade_handle_exception($ex);
1598 * Upgrade/install other parts of moodle
1599 * @param bool $verbose
1600 * @return void, may throw exception
1602 function upgrade_noncore($verbose) {
1603 global $CFG;
1605 raise_memory_limit(MEMORY_EXTRA);
1607 // upgrade all plugins types
1608 try {
1609 // Reset caches before any output.
1610 cache_helper::purge_all(true);
1611 purge_all_caches();
1613 $plugintypes = core_component::get_plugin_types();
1614 foreach ($plugintypes as $type=>$location) {
1615 upgrade_plugins($type, 'print_upgrade_part_start', 'print_upgrade_part_end', $verbose);
1617 // Update cache definitions. Involves scanning each plugin for any changes.
1618 cache_helper::update_definitions();
1619 // Mark the site as upgraded.
1620 set_config('allversionshash', core_component::get_all_versions_hash());
1622 // Purge caches again, just to be sure we arn't holding onto old stuff now.
1623 cache_helper::purge_all(true);
1624 purge_all_caches();
1626 } catch (Exception $ex) {
1627 upgrade_handle_exception($ex);
1632 * Checks if the main tables have been installed yet or not.
1634 * Note: we can not use caches here because they might be stale,
1635 * use with care!
1637 * @return bool
1639 function core_tables_exist() {
1640 global $DB;
1642 if (!$tables = $DB->get_tables(false) ) { // No tables yet at all.
1643 return false;
1645 } else { // Check for missing main tables
1646 $mtables = array('config', 'course', 'groupings'); // some tables used in 1.9 and 2.0, preferable something from the start and end of install.xml
1647 foreach ($mtables as $mtable) {
1648 if (!in_array($mtable, $tables)) {
1649 return false;
1652 return true;
1657 * upgrades the mnet rpc definitions for the given component.
1658 * this method doesn't return status, an exception will be thrown in the case of an error
1660 * @param string $component the plugin to upgrade, eg auth_mnet
1662 function upgrade_plugin_mnet_functions($component) {
1663 global $DB, $CFG;
1665 list($type, $plugin) = core_component::normalize_component($component);
1666 $path = core_component::get_plugin_directory($type, $plugin);
1668 $publishes = array();
1669 $subscribes = array();
1670 if (file_exists($path . '/db/mnet.php')) {
1671 require_once($path . '/db/mnet.php'); // $publishes comes from this file
1673 if (empty($publishes)) {
1674 $publishes = array(); // still need this to be able to disable stuff later
1676 if (empty($subscribes)) {
1677 $subscribes = array(); // still need this to be able to disable stuff later
1680 static $servicecache = array();
1682 // rekey an array based on the rpc method for easy lookups later
1683 $publishmethodservices = array();
1684 $subscribemethodservices = array();
1685 foreach($publishes as $servicename => $service) {
1686 if (is_array($service['methods'])) {
1687 foreach($service['methods'] as $methodname) {
1688 $service['servicename'] = $servicename;
1689 $publishmethodservices[$methodname][] = $service;
1694 // Disable functions that don't exist (any more) in the source
1695 // Should these be deleted? What about their permissions records?
1696 foreach ($DB->get_records('mnet_rpc', array('pluginname'=>$plugin, 'plugintype'=>$type), 'functionname ASC ') as $rpc) {
1697 if (!array_key_exists($rpc->functionname, $publishmethodservices) && $rpc->enabled) {
1698 $DB->set_field('mnet_rpc', 'enabled', 0, array('id' => $rpc->id));
1699 } else if (array_key_exists($rpc->functionname, $publishmethodservices) && !$rpc->enabled) {
1700 $DB->set_field('mnet_rpc', 'enabled', 1, array('id' => $rpc->id));
1704 // reflect all the services we're publishing and save them
1705 require_once($CFG->dirroot . '/lib/zend/Zend/Server/Reflection.php');
1706 static $cachedclasses = array(); // to store reflection information in
1707 foreach ($publishes as $service => $data) {
1708 $f = $data['filename'];
1709 $c = $data['classname'];
1710 foreach ($data['methods'] as $method) {
1711 $dataobject = new stdClass();
1712 $dataobject->plugintype = $type;
1713 $dataobject->pluginname = $plugin;
1714 $dataobject->enabled = 1;
1715 $dataobject->classname = $c;
1716 $dataobject->filename = $f;
1718 if (is_string($method)) {
1719 $dataobject->functionname = $method;
1721 } else if (is_array($method)) { // wants to override file or class
1722 $dataobject->functionname = $method['method'];
1723 $dataobject->classname = $method['classname'];
1724 $dataobject->filename = $method['filename'];
1726 $dataobject->xmlrpcpath = $type.'/'.$plugin.'/'.$dataobject->filename.'/'.$method;
1727 $dataobject->static = false;
1729 require_once($path . '/' . $dataobject->filename);
1730 $functionreflect = null; // slightly different ways to get this depending on whether it's a class method or a function
1731 if (!empty($dataobject->classname)) {
1732 if (!class_exists($dataobject->classname)) {
1733 throw new moodle_exception('installnosuchmethod', 'mnet', '', (object)array('method' => $dataobject->functionname, 'class' => $dataobject->classname));
1735 $key = $dataobject->filename . '|' . $dataobject->classname;
1736 if (!array_key_exists($key, $cachedclasses)) { // look to see if we've already got a reflection object
1737 try {
1738 $cachedclasses[$key] = Zend_Server_Reflection::reflectClass($dataobject->classname);
1739 } catch (Zend_Server_Reflection_Exception $e) { // catch these and rethrow them to something more helpful
1740 throw new moodle_exception('installreflectionclasserror', 'mnet', '', (object)array('method' => $dataobject->functionname, 'class' => $dataobject->classname, 'error' => $e->getMessage()));
1743 $r =& $cachedclasses[$key];
1744 if (!$r->hasMethod($dataobject->functionname)) {
1745 throw new moodle_exception('installnosuchmethod', 'mnet', '', (object)array('method' => $dataobject->functionname, 'class' => $dataobject->classname));
1747 // stupid workaround for zend not having a getMethod($name) function
1748 $ms = $r->getMethods();
1749 foreach ($ms as $m) {
1750 if ($m->getName() == $dataobject->functionname) {
1751 $functionreflect = $m;
1752 break;
1755 $dataobject->static = (int)$functionreflect->isStatic();
1756 } else {
1757 if (!function_exists($dataobject->functionname)) {
1758 throw new moodle_exception('installnosuchfunction', 'mnet', '', (object)array('method' => $dataobject->functionname, 'file' => $dataobject->filename));
1760 try {
1761 $functionreflect = Zend_Server_Reflection::reflectFunction($dataobject->functionname);
1762 } catch (Zend_Server_Reflection_Exception $e) { // catch these and rethrow them to something more helpful
1763 throw new moodle_exception('installreflectionfunctionerror', 'mnet', '', (object)array('method' => $dataobject->functionname, '' => $dataobject->filename, 'error' => $e->getMessage()));
1766 $dataobject->profile = serialize(admin_mnet_method_profile($functionreflect));
1767 $dataobject->help = $functionreflect->getDescription();
1769 if ($record_exists = $DB->get_record('mnet_rpc', array('xmlrpcpath'=>$dataobject->xmlrpcpath))) {
1770 $dataobject->id = $record_exists->id;
1771 $dataobject->enabled = $record_exists->enabled;
1772 $DB->update_record('mnet_rpc', $dataobject);
1773 } else {
1774 $dataobject->id = $DB->insert_record('mnet_rpc', $dataobject, true);
1777 // TODO this API versioning must be reworked, here the recently processed method
1778 // sets the service API which may not be correct
1779 foreach ($publishmethodservices[$dataobject->functionname] as $service) {
1780 if ($serviceobj = $DB->get_record('mnet_service', array('name'=>$service['servicename']))) {
1781 $serviceobj->apiversion = $service['apiversion'];
1782 $DB->update_record('mnet_service', $serviceobj);
1783 } else {
1784 $serviceobj = new stdClass();
1785 $serviceobj->name = $service['servicename'];
1786 $serviceobj->description = empty($service['description']) ? '' : $service['description'];
1787 $serviceobj->apiversion = $service['apiversion'];
1788 $serviceobj->offer = 1;
1789 $serviceobj->id = $DB->insert_record('mnet_service', $serviceobj);
1791 $servicecache[$service['servicename']] = $serviceobj;
1792 if (!$DB->record_exists('mnet_service2rpc', array('rpcid'=>$dataobject->id, 'serviceid'=>$serviceobj->id))) {
1793 $obj = new stdClass();
1794 $obj->rpcid = $dataobject->id;
1795 $obj->serviceid = $serviceobj->id;
1796 $DB->insert_record('mnet_service2rpc', $obj, true);
1801 // finished with methods we publish, now do subscribable methods
1802 foreach($subscribes as $service => $methods) {
1803 if (!array_key_exists($service, $servicecache)) {
1804 if (!$serviceobj = $DB->get_record('mnet_service', array('name' => $service))) {
1805 debugging("TODO: skipping unknown service $service - somebody needs to fix MDL-21993");
1806 continue;
1808 $servicecache[$service] = $serviceobj;
1809 } else {
1810 $serviceobj = $servicecache[$service];
1812 foreach ($methods as $method => $xmlrpcpath) {
1813 if (!$rpcid = $DB->get_field('mnet_remote_rpc', 'id', array('xmlrpcpath'=>$xmlrpcpath))) {
1814 $remoterpc = (object)array(
1815 'functionname' => $method,
1816 'xmlrpcpath' => $xmlrpcpath,
1817 'plugintype' => $type,
1818 'pluginname' => $plugin,
1819 'enabled' => 1,
1821 $rpcid = $remoterpc->id = $DB->insert_record('mnet_remote_rpc', $remoterpc, true);
1823 if (!$DB->record_exists('mnet_remote_service2rpc', array('rpcid'=>$rpcid, 'serviceid'=>$serviceobj->id))) {
1824 $obj = new stdClass();
1825 $obj->rpcid = $rpcid;
1826 $obj->serviceid = $serviceobj->id;
1827 $DB->insert_record('mnet_remote_service2rpc', $obj, true);
1829 $subscribemethodservices[$method][] = $service;
1833 foreach ($DB->get_records('mnet_remote_rpc', array('pluginname'=>$plugin, 'plugintype'=>$type), 'functionname ASC ') as $rpc) {
1834 if (!array_key_exists($rpc->functionname, $subscribemethodservices) && $rpc->enabled) {
1835 $DB->set_field('mnet_remote_rpc', 'enabled', 0, array('id' => $rpc->id));
1836 } else if (array_key_exists($rpc->functionname, $subscribemethodservices) && !$rpc->enabled) {
1837 $DB->set_field('mnet_remote_rpc', 'enabled', 1, array('id' => $rpc->id));
1841 return true;
1845 * Given some sort of Zend Reflection function/method object, return a profile array, ready to be serialized and stored
1847 * @param Zend_Server_Reflection_Function_Abstract $function can be any subclass of this object type
1849 * @return array
1851 function admin_mnet_method_profile(Zend_Server_Reflection_Function_Abstract $function) {
1852 $protos = $function->getPrototypes();
1853 $proto = array_pop($protos);
1854 $ret = $proto->getReturnValue();
1855 $profile = array(
1856 'parameters' => array(),
1857 'return' => array(
1858 'type' => $ret->getType(),
1859 'description' => $ret->getDescription(),
1862 foreach ($proto->getParameters() as $p) {
1863 $profile['parameters'][] = array(
1864 'name' => $p->getName(),
1865 'type' => $p->getType(),
1866 'description' => $p->getDescription(),
1869 return $profile;
1874 * This function finds duplicate records (based on combinations of fields that should be unique)
1875 * and then progamatically generated a "most correct" version of the data, update and removing
1876 * records as appropriate
1878 * Thanks to Dan Marsden for help
1880 * @param string $table Table name
1881 * @param array $uniques Array of field names that should be unique
1882 * @param array $fieldstocheck Array of fields to generate "correct" data from (optional)
1883 * @return void
1885 function upgrade_course_completion_remove_duplicates($table, $uniques, $fieldstocheck = array()) {
1886 global $DB;
1888 // Find duplicates
1889 $sql_cols = implode(', ', $uniques);
1891 $sql = "SELECT {$sql_cols} FROM {{$table}} GROUP BY {$sql_cols} HAVING (count(id) > 1)";
1892 $duplicates = $DB->get_recordset_sql($sql, array());
1894 // Loop through duplicates
1895 foreach ($duplicates as $duplicate) {
1896 $pointer = 0;
1898 // Generate SQL for finding records with these duplicate uniques
1899 $sql_select = implode(' = ? AND ', $uniques).' = ?'; // builds "fieldname = ? AND fieldname = ?"
1900 $uniq_values = array();
1901 foreach ($uniques as $u) {
1902 $uniq_values[] = $duplicate->$u;
1905 $sql_order = implode(' DESC, ', $uniques).' DESC'; // builds "fieldname DESC, fieldname DESC"
1907 // Get records with these duplicate uniques
1908 $records = $DB->get_records_select(
1909 $table,
1910 $sql_select,
1911 $uniq_values,
1912 $sql_order
1915 // Loop through and build a "correct" record, deleting the others
1916 $needsupdate = false;
1917 $origrecord = null;
1918 foreach ($records as $record) {
1919 $pointer++;
1920 if ($pointer === 1) { // keep 1st record but delete all others.
1921 $origrecord = $record;
1922 } else {
1923 // If we have fields to check, update original record
1924 if ($fieldstocheck) {
1925 // we need to keep the "oldest" of all these fields as the valid completion record.
1926 // but we want to ignore null values
1927 foreach ($fieldstocheck as $f) {
1928 if ($record->$f && (($origrecord->$f > $record->$f) || !$origrecord->$f)) {
1929 $origrecord->$f = $record->$f;
1930 $needsupdate = true;
1934 $DB->delete_records($table, array('id' => $record->id));
1937 if ($needsupdate || isset($origrecord->reaggregate)) {
1938 // If this table has a reaggregate field, update to force recheck on next cron run
1939 if (isset($origrecord->reaggregate)) {
1940 $origrecord->reaggregate = time();
1942 $DB->update_record($table, $origrecord);
1948 * Find questions missing an existing category and associate them with
1949 * a category which purpose is to gather them.
1951 * @return void
1953 function upgrade_save_orphaned_questions() {
1954 global $DB;
1956 // Looking for orphaned questions
1957 $orphans = $DB->record_exists_select('question',
1958 'NOT EXISTS (SELECT 1 FROM {question_categories} WHERE {question_categories}.id = {question}.category)');
1959 if (!$orphans) {
1960 return;
1963 // Generate a unique stamp for the orphaned questions category, easier to identify it later on
1964 $uniquestamp = "unknownhost+120719170400+orphan";
1965 $systemcontext = context_system::instance();
1967 // Create the orphaned category at system level
1968 $cat = $DB->get_record('question_categories', array('stamp' => $uniquestamp,
1969 'contextid' => $systemcontext->id));
1970 if (!$cat) {
1971 $cat = new stdClass();
1972 $cat->parent = 0;
1973 $cat->contextid = $systemcontext->id;
1974 $cat->name = get_string('orphanedquestionscategory', 'question');
1975 $cat->info = get_string('orphanedquestionscategoryinfo', 'question');
1976 $cat->sortorder = 999;
1977 $cat->stamp = $uniquestamp;
1978 $cat->id = $DB->insert_record("question_categories", $cat);
1981 // Set a category to those orphans
1982 $params = array('catid' => $cat->id);
1983 $DB->execute('UPDATE {question} SET category = :catid WHERE NOT EXISTS
1984 (SELECT 1 FROM {question_categories} WHERE {question_categories}.id = {question}.category)', $params);
1988 * Rename old backup files to current backup files.
1990 * When added the setting 'backup_shortname' (MDL-28657) the backup file names did not contain the id of the course.
1991 * Further we fixed that behaviour by forcing the id to be always present in the file name (MDL-33812).
1992 * This function will explore the backup directory and attempt to rename the previously created files to include
1993 * the id in the name. Doing this will put them back in the process of deleting the excess backups for each course.
1995 * This function manually recreates the file name, instead of using
1996 * {@link backup_plan_dbops::get_default_backup_filename()}, use it carefully if you're using it outside of the
1997 * usual upgrade process.
1999 * @see backup_cron_automated_helper::remove_excess_backups()
2000 * @link http://tracker.moodle.org/browse/MDL-35116
2001 * @return void
2002 * @since Moodle 2.4
2004 function upgrade_rename_old_backup_files_using_shortname() {
2005 global $CFG;
2006 $dir = get_config('backup', 'backup_auto_destination');
2007 $useshortname = get_config('backup', 'backup_shortname');
2008 if (empty($dir) || !is_dir($dir) || !is_writable($dir)) {
2009 return;
2012 require_once($CFG->dirroot.'/backup/util/includes/backup_includes.php');
2013 $backupword = str_replace(' ', '_', core_text::strtolower(get_string('backupfilename')));
2014 $backupword = trim(clean_filename($backupword), '_');
2015 $filename = $backupword . '-' . backup::FORMAT_MOODLE . '-' . backup::TYPE_1COURSE . '-';
2016 $regex = '#^'.preg_quote($filename, '#').'.*\.mbz$#';
2017 $thirtyapril = strtotime('30 April 2012 00:00');
2019 // Reading the directory.
2020 if (!$files = scandir($dir)) {
2021 return;
2023 foreach ($files as $file) {
2024 // Skip directories and files which do not start with the common prefix.
2025 // This avoids working on files which are not related to this issue.
2026 if (!is_file($dir . '/' . $file) || !preg_match($regex, $file)) {
2027 continue;
2030 // Extract the information from the XML file.
2031 try {
2032 $bcinfo = backup_general_helper::get_backup_information_from_mbz($dir . '/' . $file);
2033 } catch (backup_helper_exception $e) {
2034 // Some error while retrieving the backup informations, skipping...
2035 continue;
2038 // Make sure this a course backup.
2039 if ($bcinfo->format !== backup::FORMAT_MOODLE || $bcinfo->type !== backup::TYPE_1COURSE) {
2040 continue;
2043 // Skip the backups created before the short name option was initially introduced (MDL-28657).
2044 // This was integrated on the 2nd of May 2012. Let's play safe with timezone and use the 30th of April.
2045 if ($bcinfo->backup_date < $thirtyapril) {
2046 continue;
2049 // Let's check if the file name contains the ID where it is supposed to be, if it is the case then
2050 // we will skip the file. Of course it could happen that the course ID is identical to the course short name
2051 // even though really unlikely, but then renaming this file is not necessary. If the ID is not found in the
2052 // file name then it was probably the short name which was used.
2053 $idfilename = $filename . $bcinfo->original_course_id . '-';
2054 $idregex = '#^'.preg_quote($idfilename, '#').'.*\.mbz$#';
2055 if (preg_match($idregex, $file)) {
2056 continue;
2059 // Generating the file name manually. We do not use backup_plan_dbops::get_default_backup_filename() because
2060 // it will query the database to get some course information, and the course could not exist any more.
2061 $newname = $filename . $bcinfo->original_course_id . '-';
2062 if ($useshortname) {
2063 $shortname = str_replace(' ', '_', $bcinfo->original_course_shortname);
2064 $shortname = core_text::strtolower(trim(clean_filename($shortname), '_'));
2065 $newname .= $shortname . '-';
2068 $backupdateformat = str_replace(' ', '_', get_string('backupnameformat', 'langconfig'));
2069 $date = userdate($bcinfo->backup_date, $backupdateformat, 99, false);
2070 $date = core_text::strtolower(trim(clean_filename($date), '_'));
2071 $newname .= $date;
2073 if (isset($bcinfo->root_settings['users']) && !$bcinfo->root_settings['users']) {
2074 $newname .= '-nu';
2075 } else if (isset($bcinfo->root_settings['anonymize']) && $bcinfo->root_settings['anonymize']) {
2076 $newname .= '-an';
2078 $newname .= '.mbz';
2080 // Final check before attempting the renaming.
2081 if ($newname == $file || file_exists($dir . '/' . $newname)) {
2082 continue;
2084 @rename($dir . '/' . $file, $dir . '/' . $newname);
2089 * Detect duplicate grade item sortorders and resort the
2090 * items to remove them.
2092 function upgrade_grade_item_fix_sortorder() {
2093 global $DB;
2095 // The simple way to fix these sortorder duplicates would be simply to resort each
2096 // affected course. But in order to reduce the impact of this upgrade step we're trying
2097 // to do it more efficiently by doing a series of update statements rather than updating
2098 // every single grade item in affected courses.
2100 $sql = "SELECT DISTINCT g1.courseid
2101 FROM {grade_items} g1
2102 JOIN {grade_items} g2 ON g1.courseid = g2.courseid
2103 WHERE g1.sortorder = g2.sortorder AND g1.id != g2.id
2104 ORDER BY g1.courseid ASC";
2105 foreach ($DB->get_fieldset_sql($sql) as $courseid) {
2106 $transaction = $DB->start_delegated_transaction();
2107 $items = $DB->get_records('grade_items', array('courseid' => $courseid), '', 'id, sortorder, sortorder AS oldsort');
2109 // Get all duplicates in course order, highest sort order, and higest id first so that we can make space at the
2110 // bottom higher end of the sort orders and work down by id.
2111 $sql = "SELECT DISTINCT g1.id, g1.sortorder
2112 FROM {grade_items} g1
2113 JOIN {grade_items} g2 ON g1.courseid = g2.courseid
2114 WHERE g1.sortorder = g2.sortorder AND g1.id != g2.id AND g1.courseid = :courseid
2115 ORDER BY g1.sortorder DESC, g1.id DESC";
2117 // This is the O(N*N) like the database version we're replacing, but at least the constants are a billion times smaller...
2118 foreach ($DB->get_records_sql($sql, array('courseid' => $courseid)) as $duplicate) {
2119 foreach ($items as $item) {
2120 if ($item->sortorder > $duplicate->sortorder || ($item->sortorder == $duplicate->sortorder && $item->id > $duplicate->id)) {
2121 $item->sortorder += 1;
2125 foreach ($items as $item) {
2126 if ($item->sortorder != $item->oldsort) {
2127 $DB->update_record('grade_items', array('id' => $item->id, 'sortorder' => $item->sortorder));
2131 $transaction->allow_commit();
2136 * Detect file areas with missing root directory records and add them.
2138 function upgrade_fix_missing_root_folders() {
2139 global $DB, $USER;
2141 $transaction = $DB->start_delegated_transaction();
2143 $sql = "SELECT contextid, component, filearea, itemid
2144 FROM {files}
2145 WHERE (component <> 'user' OR filearea <> 'draft')
2146 GROUP BY contextid, component, filearea, itemid
2147 HAVING MAX(CASE WHEN filename = '.' AND filepath = '/' THEN 1 ELSE 0 END) = 0";
2149 $rs = $DB->get_recordset_sql($sql);
2150 $defaults = array('filepath' => '/',
2151 'filename' => '.',
2152 'userid' => 0, // Don't rely on any particular user for these system records.
2153 'filesize' => 0,
2154 'timecreated' => time(),
2155 'timemodified' => time(),
2156 'contenthash' => sha1(''));
2157 foreach ($rs as $r) {
2158 $pathhash = sha1("/$r->contextid/$r->component/$r->filearea/$r->itemid/.");
2159 $DB->insert_record('files', (array)$r + $defaults +
2160 array('pathnamehash' => $pathhash));
2162 $rs->close();
2163 $transaction->allow_commit();
2167 * Detect draft file areas with missing root directory records and add them.
2169 function upgrade_fix_missing_root_folders_draft() {
2170 global $DB;
2172 $transaction = $DB->start_delegated_transaction();
2174 $sql = "SELECT contextid, itemid, MAX(timecreated) AS timecreated, MAX(timemodified) AS timemodified
2175 FROM {files}
2176 WHERE (component = 'user' AND filearea = 'draft')
2177 GROUP BY contextid, itemid
2178 HAVING MAX(CASE WHEN filename = '.' AND filepath = '/' THEN 1 ELSE 0 END) = 0";
2180 $rs = $DB->get_recordset_sql($sql);
2181 $defaults = array('component' => 'user',
2182 'filearea' => 'draft',
2183 'filepath' => '/',
2184 'filename' => '.',
2185 'userid' => 0, // Don't rely on any particular user for these system records.
2186 'filesize' => 0,
2187 'contenthash' => sha1(''));
2188 foreach ($rs as $r) {
2189 $r->pathnamehash = sha1("/$r->contextid/user/draft/$r->itemid/.");
2190 $DB->insert_record('files', (array)$r + $defaults);
2192 $rs->close();
2193 $transaction->allow_commit();