MDL-20274 upgrade and install support for db/services.php
[moodle.git] / lib / upgradelib.php
CommitLineData
96db14f9 1<?php
2
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.
14//
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/>.
db9d4a3d 17
18/**
8580535b 19 * Various upgrade/install related functions and classes.
db9d4a3d 20 *
96db14f9 21 * @package moodlecore
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
db9d4a3d 25 */
26
72fb21b6 27/** UPGRADE_LOG_NORMAL = 0 */
db9d4a3d 28define('UPGRADE_LOG_NORMAL', 0);
72fb21b6 29/** UPGRADE_LOG_NOTICE = 1 */
db9d4a3d 30define('UPGRADE_LOG_NOTICE', 1);
72fb21b6 31/** UPGRADE_LOG_ERROR = 2 */
795a08ad 32define('UPGRADE_LOG_ERROR', 2);
33
34/**
35 * Exception indicating unknown error during upgrade.
72fb21b6 36 *
37 * @package moodlecore
38 * @subpackage upgrade
39 * @copyright 1999 onwards Martin Dougiamas (http://dougiamas.com)
40 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
795a08ad 41 */
42class upgrade_exception extends moodle_exception {
43 function __construct($plugin, $version) {
44 global $CFG;
45 $a = (object)array('plugin'=>$plugin, 'version'=>$version);
45440ceb 46 parent::__construct('upgradeerror', 'admin', "$CFG->wwwroot/$CFG->admin/index.php", $a);
795a08ad 47 }
48}
49
50/**
51 * Exception indicating downgrade error during upgrade.
72fb21b6 52 *
53 * @package moodlecore
54 * @subpackage upgrade
55 * @copyright 1999 onwards Martin Dougiamas (http://dougiamas.com)
56 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
795a08ad 57 */
58class downgrade_exception extends moodle_exception {
59 function __construct($plugin, $oldversion, $newversion) {
60 global $CFG;
61 $plugin = is_null($plugin) ? 'moodle' : $plugin;
62 $a = (object)array('plugin'=>$plugin, 'oldversion'=>$oldversion, 'newversion'=>$newversion);
63 parent::__construct('cannotdowngrade', 'debug', "$CFG->wwwroot/$CFG->admin/index.php", $a);
64 }
65}
66
72fb21b6 67/**
68 * @package moodlecore
69 * @subpackage upgrade
70 * @copyright 1999 onwards Martin Dougiamas (http://dougiamas.com)
71 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
72 */
795a08ad 73class upgrade_requires_exception extends moodle_exception {
74 function __construct($plugin, $pluginversion, $currentmoodle, $requiremoodle) {
75 global $CFG;
76 $a = new object();
77 $a->pluginname = $plugin;
78 $a->pluginversion = $pluginversion;
79 $a->currentmoodle = $currentmoodle;
17da2e6f 80 $a->requiremoodle = $requiremoodle;
795a08ad 81 parent::__construct('pluginrequirementsnotmet', 'error', "$CFG->wwwroot/$CFG->admin/index.php", $a);
82 }
83}
84
72fb21b6 85/**
86 * @package moodlecore
87 * @subpackage upgrade
88 * @copyright 1999 onwards Martin Dougiamas (http://dougiamas.com)
89 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
90 */
795a08ad 91class plugin_defective_exception extends moodle_exception {
92 function __construct($plugin, $details) {
93 global $CFG;
94 parent::__construct('detectedbrokenplugin', 'error', "$CFG->wwwroot/$CFG->admin/index.php", $plugin, $details);
95 }
96}
db9d4a3d 97
98/**
99 * Insert or update log display entry. Entry may already exist.
100 * $module, $action must be unique
101 *
72fb21b6 102 * @global object
db9d4a3d 103 * @param string $module
104 * @param string $action
105 * @param string $mtable
106 * @param string $field
107 * @return void
108 *
109 */
110function update_log_display_entry($module, $action, $mtable, $field) {
111 global $DB;
112
113 if ($type = $DB->get_record('log_display', array('module'=>$module, 'action'=>$action))) {
114 $type->mtable = $mtable;
115 $type->field = $field;
116 $DB->update_record('log_display', $type);
117
118 } else {
119 $type = new object();
120 $type->module = $module;
121 $type->action = $action;
122 $type->mtable = $mtable;
123 $type->field = $field;
124
125 $DB->insert_record('log_display', $type, false);
126 }
127}
128
129/**
130 * Upgrade savepoint, marks end of each upgrade block.
131 * It stores new main version, resets upgrade timeout
132 * and abort upgrade if user cancels page loading.
133 *
134 * Please do not make large upgrade blocks with lots of operations,
135 * for example when adding tables keep only one table operation per block.
136 *
72fb21b6 137 * @global object
db9d4a3d 138 * @param bool $result false if upgrade step failed, true if completed
139 * @param string or float $version main version
140 * @param bool $allowabort allow user to abort script execution here
141 * @return void
142 */
143function upgrade_main_savepoint($result, $version, $allowabort=true) {
144 global $CFG;
145
795a08ad 146 if (!$result) {
520cea92 147 throw new upgrade_exception(null, $version);
795a08ad 148 }
149
150 if ($CFG->version >= $version) {
151 // something really wrong is going on in main upgrade script
152 throw new downgrade_exception(null, $CFG->version, $version);
db9d4a3d 153 }
154
795a08ad 155 set_config('version', $version);
156 upgrade_log(UPGRADE_LOG_NORMAL, null, 'Upgrade savepoint reached');
157
db9d4a3d 158 // reset upgrade timeout to default
159 upgrade_set_timeout();
160
161 // this is a safe place to stop upgrades if user aborts page loading
162 if ($allowabort and connection_aborted()) {
163 die;
164 }
165}
166
167/**
168 * Module upgrade savepoint, marks end of module upgrade blocks
169 * It stores module version, resets upgrade timeout
170 * and abort upgrade if user cancels page loading.
171 *
72fb21b6 172 * @global object
db9d4a3d 173 * @param bool $result false if upgrade step failed, true if completed
174 * @param string or float $version main version
175 * @param string $modname name of module
176 * @param bool $allowabort allow user to abort script execution here
177 * @return void
178 */
179function upgrade_mod_savepoint($result, $version, $modname, $allowabort=true) {
180 global $DB;
181
795a08ad 182 if (!$result) {
520cea92 183 throw new upgrade_exception("mod_$modname", $version);
795a08ad 184 }
185
db9d4a3d 186 if (!$module = $DB->get_record('modules', array('name'=>$modname))) {
187 print_error('modulenotexist', 'debug', '', $modname);
188 }
189
795a08ad 190 if ($module->version >= $version) {
191 // something really wrong is going on in upgrade script
520cea92 192 throw new downgrade_exception("mod_$modname", $module->version, $version);
db9d4a3d 193 }
795a08ad 194 $module->version = $version;
195 $DB->update_record('modules', $module);
520cea92 196 upgrade_log(UPGRADE_LOG_NORMAL, "mod_$modname", 'Upgrade savepoint reached');
db9d4a3d 197
198 // reset upgrade timeout to default
199 upgrade_set_timeout();
200
201 // this is a safe place to stop upgrades if user aborts page loading
202 if ($allowabort and connection_aborted()) {
203 die;
204 }
205}
206
207/**
208 * Blocks upgrade savepoint, marks end of blocks upgrade blocks
209 * It stores block version, resets upgrade timeout
210 * and abort upgrade if user cancels page loading.
211 *
72fb21b6 212 * @global object
db9d4a3d 213 * @param bool $result false if upgrade step failed, true if completed
214 * @param string or float $version main version
215 * @param string $blockname name of block
216 * @param bool $allowabort allow user to abort script execution here
217 * @return void
218 */
795a08ad 219function upgrade_block_savepoint($result, $version, $blockname, $allowabort=true) {
db9d4a3d 220 global $DB;
221
795a08ad 222 if (!$result) {
520cea92 223 throw new upgrade_exception("block_$blockname", $version);
795a08ad 224 }
225
db9d4a3d 226 if (!$block = $DB->get_record('block', array('name'=>$blockname))) {
227 print_error('blocknotexist', 'debug', '', $blockname);
228 }
229
795a08ad 230 if ($block->version >= $version) {
231 // something really wrong is going on in upgrade script
520cea92 232 throw new downgrade_exception("block_$blockname", $block->version, $version);
db9d4a3d 233 }
795a08ad 234 $block->version = $version;
235 $DB->update_record('block', $block);
520cea92 236 upgrade_log(UPGRADE_LOG_NORMAL, "block_$blockname", 'Upgrade savepoint reached');
db9d4a3d 237
238 // reset upgrade timeout to default
239 upgrade_set_timeout();
240
241 // this is a safe place to stop upgrades if user aborts page loading
242 if ($allowabort and connection_aborted()) {
243 die;
244 }
245}
246
247/**
248 * Plugins upgrade savepoint, marks end of blocks upgrade blocks
249 * It stores plugin version, resets upgrade timeout
250 * and abort upgrade if user cancels page loading.
251 *
252 * @param bool $result false if upgrade step failed, true if completed
253 * @param string or float $version main version
254 * @param string $type name of plugin
255 * @param string $dir location of plugin
256 * @param bool $allowabort allow user to abort script execution here
257 * @return void
258 */
17da2e6f 259function upgrade_plugin_savepoint($result, $version, $type, $plugin, $allowabort=true) {
260 $component = $type.'_'.$plugin;
261
795a08ad 262 if (!$result) {
17da2e6f 263 throw new upgrade_exception($component, $version);
db9d4a3d 264 }
265
17da2e6f 266 $installedversion = get_config($component, 'version');
795a08ad 267 if ($installedversion >= $version) {
268 // Something really wrong is going on in the upgrade script
269 throw new downgrade_exception($component, $installedversion, $version);
270 }
17da2e6f 271 set_config('version', $version, $component);
795a08ad 272 upgrade_log(UPGRADE_LOG_NORMAL, $component, 'Upgrade savepoint reached');
273
db9d4a3d 274 // Reset upgrade timeout to default
275 upgrade_set_timeout();
276
277 // This is a safe place to stop upgrades if user aborts page loading
278 if ($allowabort and connection_aborted()) {
279 die;
280 }
281}
282
283
284/**
285 * Upgrade plugins
db9d4a3d 286 * @param string $type The type of plugins that should be updated (e.g. 'enrol', 'qtype')
17da2e6f 287 * return void
db9d4a3d 288 */
17da2e6f 289function upgrade_plugins($type, $startcallback, $endcallback, $verbose) {
db9d4a3d 290 global $CFG, $DB;
291
292/// special cases
293 if ($type === 'mod') {
194cdca8 294 return upgrade_plugins_modules($startcallback, $endcallback, $verbose);
795a08ad 295 } else if ($type === 'block') {
194cdca8 296 return upgrade_plugins_blocks($startcallback, $endcallback, $verbose);
db9d4a3d 297 }
298
17da2e6f 299 $plugs = get_plugin_list($type);
db9d4a3d 300
17da2e6f 301 foreach ($plugs as $plug=>$fullplug) {
302 $component = $type.'_'.$plug; // standardised plugin name
db9d4a3d 303
795a08ad 304 if (!is_readable($fullplug.'/version.php')) {
305 continue;
db9d4a3d 306 }
307
795a08ad 308 $plugin = new object();
309 require($fullplug.'/version.php'); // defines $plugin with version etc
db9d4a3d 310
795a08ad 311 if (empty($plugin->version)) {
312 throw new plugin_defective_exception($component, 'Missing version value in version.php');
db9d4a3d 313 }
314
17da2e6f 315 $plugin->name = $plug;
316 $plugin->fullname = $component;
795a08ad 317
318
db9d4a3d 319 if (!empty($plugin->requires)) {
320 if ($plugin->requires > $CFG->version) {
795a08ad 321 throw new upgrade_requires_exception($component, $plugin->version, $CFG->version, $plugin->requires);
db9d4a3d 322 }
323 }
324
9b683d13 325 // try to recover from interrupted install.php if needed
326 if (file_exists($fullplug.'/db/install.php')) {
327 if (get_config($plugin->fullname, 'installrunning')) {
328 require_once($fullplug.'/db/install.php');
329 $recover_install_function = 'xmldb_'.$plugin->fullname.'_install_recovery';
330 if (function_exists($recover_install_function)) {
331 $startcallback($component, true, $verbose);
332 $recover_install_function();
333 unset_config('installrunning', 'block_'.$plugin->fullname);
334 update_capabilities($component);
c976e271 335 external_update_descriptions($component);
9b683d13 336 events_update_definition($component);
337 message_update_providers($component);
338 $endcallback($component, true, $verbose);
339 }
340 }
341 }
db9d4a3d 342
9b683d13 343 $installedversion = get_config($plugin->fullname, 'version');
795a08ad 344 if (empty($installedversion)) { // new installation
194cdca8 345 $startcallback($component, true, $verbose);
db9d4a3d 346
795a08ad 347 /// Install tables if defined
348 if (file_exists($fullplug.'/db/install.xml')) {
349 $DB->get_manager()->install_from_xmldb_file($fullplug.'/db/install.xml');
db9d4a3d 350 }
9b683d13 351
352 /// store version
353 upgrade_plugin_savepoint(true, $plugin->version, $type, $plug, false);
354
795a08ad 355 /// execute post install file
356 if (file_exists($fullplug.'/db/install.php')) {
357 require_once($fullplug.'/db/install.php');
9b683d13 358 set_config('installrunning', 1, 'block_'.$plugin->fullname);
795a08ad 359 $post_install_function = 'xmldb_'.$plugin->fullname.'_install';;
360 $post_install_function();
9b683d13 361 unset_config('installrunning', 'block_'.$plugin->fullname);
795a08ad 362 }
363
795a08ad 364 /// Install various components
365 update_capabilities($component);
c976e271 366 external_update_descriptions($component);
795a08ad 367 events_update_definition($component);
368 message_update_providers($component);
369
194cdca8 370 $endcallback($component, true, $verbose);
795a08ad 371
372 } else if ($installedversion < $plugin->version) { // upgrade
373 /// Run the upgrade function for the plugin.
194cdca8 374 $startcallback($component, false, $verbose);
795a08ad 375
376 if (is_readable($fullplug.'/db/upgrade.php')) {
377 require_once($fullplug.'/db/upgrade.php'); // defines upgrading function
378
379 $newupgrade_function = 'xmldb_'.$plugin->fullname.'_upgrade';
380 $result = $newupgrade_function($installedversion);
381 } else {
382 $result = true;
383 }
384
385 $installedversion = get_config($plugin->fullname, 'version');
386 if ($installedversion < $plugin->version) {
387 // store version if not already there
388 upgrade_plugin_savepoint($result, $plugin->version, $type, $plug, false);
389 }
390
391 /// Upgrade various components
392 update_capabilities($component);
c976e271 393 external_update_descriptions($component);
795a08ad 394 events_update_definition($component);
395 message_update_providers($component);
396
194cdca8 397 $endcallback($component, false, $verbose);
795a08ad 398
399 } else if ($installedversion > $plugin->version) {
400 throw new downgrade_exception($component, $installedversion, $plugin->version);
db9d4a3d 401 }
402 }
db9d4a3d 403}
404
405/**
406 * Find and check all modules and load them up or upgrade them if necessary
72fb21b6 407 *
408 * @global object
409 * @global object
db9d4a3d 410 */
194cdca8 411function upgrade_plugins_modules($startcallback, $endcallback, $verbose) {
db9d4a3d 412 global $CFG, $DB;
413
17da2e6f 414 $mods = get_plugin_list('mod');
db9d4a3d 415
17da2e6f 416 foreach ($mods as $mod=>$fullmod) {
db9d4a3d 417
418 if ($mod == 'NEWMODULE') { // Someone has unzipped the template, ignore it
419 continue;
420 }
421
17da2e6f 422 $component = 'mod_'.$mod;
db9d4a3d 423
795a08ad 424 if (!is_readable($fullmod.'/version.php')) {
425 throw new plugin_defective_exception($component, 'Missing version.php');
db9d4a3d 426 }
427
795a08ad 428 $module = new object();
429 require($fullmod .'/version.php'); // defines $module with version etc
db9d4a3d 430
795a08ad 431 if (empty($module->version)) {
c1fe2368 432 if (isset($module->version)) {
433 // Version is empty but is set - it means its value is 0 or ''. Let us skip such module.
434 // This is inteded for developers so they can work on the early stages of the module.
435 continue;
436 }
795a08ad 437 throw new plugin_defective_exception($component, 'Missing version value in version.php');
db9d4a3d 438 }
439
440 if (!empty($module->requires)) {
441 if ($module->requires > $CFG->version) {
795a08ad 442 throw new upgrade_requires_exception($component, $module->version, $CFG->version, $module->requires);
db9d4a3d 443 }
444 }
445
446 $module->name = $mod; // The name MUST match the directory
447
795a08ad 448 $currmodule = $DB->get_record('modules', array('name'=>$module->name));
db9d4a3d 449
9b683d13 450 if (file_exists($fullmod.'/db/install.php')) {
451 if (get_config($module->name, 'installrunning')) {
452 require_once($fullmod.'/db/install.php');
453 $recover_install_function = 'xmldb_'.$module->name.'_install_recovery';
454 if (function_exists($recover_install_function)) {
455 $startcallback($component, true, $verbose);
456 $recover_install_function();
457 unset_config('installrunning', $module->name);
458 // Install various components too
459 update_capabilities($component);
c976e271 460 external_update_descriptions($component);
9b683d13 461 events_update_definition($component);
462 message_update_providers($component);
463 $endcallback($component, true, $verbose);
464 }
465 }
466 }
467
795a08ad 468 if (empty($currmodule->version)) {
194cdca8 469 $startcallback($component, true, $verbose);
db9d4a3d 470
795a08ad 471 /// Execute install.xml (XMLDB) - must be present in all modules
472 $DB->get_manager()->install_from_xmldb_file($fullmod.'/db/install.xml');
db9d4a3d 473
2e3da297 474 /// Add record into modules table - may be needed in install.php already
475 $module->id = $DB->insert_record('modules', $module);
476
db9d4a3d 477 /// Post installation hook - optional
478 if (file_exists("$fullmod/db/install.php")) {
479 require_once("$fullmod/db/install.php");
9b683d13 480 // Set installation running flag, we need to recover after exception or error
481 set_config('installrunning', 1, $module->name);
db9d4a3d 482 $post_install_function = 'xmldb_'.$module->name.'_install';;
483 $post_install_function();
9b683d13 484 unset_config('installrunning', $module->name);
db9d4a3d 485 }
486
795a08ad 487 /// Install various components
488 update_capabilities($component);
c976e271 489 external_update_descriptions($component);
795a08ad 490 events_update_definition($component);
491 message_update_providers($component);
492
194cdca8 493 $endcallback($component, true, $verbose);
db9d4a3d 494
795a08ad 495 } else if ($currmodule->version < $module->version) {
496 /// If versions say that we need to upgrade but no upgrade files are available, notify and continue
194cdca8 497 $startcallback($component, false, $verbose);
795a08ad 498
499 if (is_readable($fullmod.'/db/upgrade.php')) {
500 require_once($fullmod.'/db/upgrade.php'); // defines new upgrading function
501 $newupgrade_function = 'xmldb_'.$module->name.'_upgrade';
502 $result = $newupgrade_function($currmodule->version, $module);
503 } else {
504 $result = true;
505 }
506
507 $currmodule = $DB->get_record('modules', array('name'=>$module->name));
508 if ($currmodule->version < $module->version) {
509 // store version if not already there
510 upgrade_mod_savepoint($result, $module->version, $mod, false);
511 }
512
513 /// Upgrade various components
514 update_capabilities($component);
c976e271 515 external_update_descriptions($component);
795a08ad 516 events_update_definition($component);
517 message_update_providers($component);
518
519 remove_dir($CFG->dataroot.'/cache', true); // flush cache
520
194cdca8 521 $endcallback($component, false, $verbose);
795a08ad 522
523 } else if ($currmodule->version > $module->version) {
524 throw new downgrade_exception($component, $currmodule->version, $module->version);
525 }
526 }
527}
db9d4a3d 528
db9d4a3d 529
795a08ad 530/**
531 * This function finds all available blocks and install them
532 * into blocks table or do all the upgrade process if newer.
72fb21b6 533 *
534 * @global object
535 * @global object
795a08ad 536 */
194cdca8 537function upgrade_plugins_blocks($startcallback, $endcallback, $verbose) {
795a08ad 538 global $CFG, $DB;
539
795a08ad 540 require_once($CFG->dirroot.'/blocks/moodleblock.class.php');
541
542 $blocktitles = array(); // we do not want duplicate titles
543
544 //Is this a first install
545 $first_install = null;
546
17da2e6f 547 $blocks = get_plugin_list('block');
795a08ad 548
17da2e6f 549 foreach ($blocks as $blockname=>$fullblock) {
795a08ad 550
551 if (is_null($first_install)) {
552 $first_install = ($DB->count_records('block') == 0);
553 }
554
555 if ($blockname == 'NEWBLOCK') { // Someone has unzipped the template, ignore it
556 continue;
db9d4a3d 557 }
558
17da2e6f 559 $component = 'block_'.$blockname;
db9d4a3d 560
795a08ad 561 if (!is_readable($fullblock.'/block_'.$blockname.'.php')) {
562 throw new plugin_defective_exception('block/'.$blockname, 'Missing main block class file.');
db9d4a3d 563 }
795a08ad 564 require_once($fullblock.'/block_'.$blockname.'.php');
db9d4a3d 565
795a08ad 566 $classname = 'block_'.$blockname;
567
568 if (!class_exists($classname)) {
569 throw new plugin_defective_exception($component, 'Can not load main class.');
570 }
571
572 $blockobj = new $classname; // This is what we 'll be testing
573 $blocktitle = $blockobj->get_title();
574
575 // OK, it's as we all hoped. For further tests, the object will do them itself.
576 if (!$blockobj->_self_test()) {
577 throw new plugin_defective_exception($component, 'Self test failed.');
578 }
579
580 $block = new object(); // This may be used to update the db below
581 $block->name = $blockname; // The name MUST match the directory
582 $block->version = $blockobj->get_version();
583 $block->cron = !empty($blockobj->cron) ? $blockobj->cron : 0;
584 $block->multiple = $blockobj->instance_allow_multiple() ? 1 : 0;
585
586 if (empty($block->version)) {
587 throw new plugin_defective_exception($component, 'Missing block version.');
588 }
589
590 $currblock = $DB->get_record('block', array('name'=>$block->name));
591
9b683d13 592 if (file_exists($fullblock.'/db/install.php')) {
593 if (get_config('block_'.$blockname, 'installrunning')) {
594 require_once($fullblock.'/db/install.php');
595 $recover_install_function = 'xmldb_block_'.$blockname.'_install_recovery';
596 if (function_exists($recover_install_function)) {
597 $startcallback($component, true, $verbose);
598 $recover_install_function();
599 unset_config('installrunning', 'block_'.$blockname);
600 // Install various components
601 update_capabilities($component);
c976e271 602 external_update_descriptions($component);
9b683d13 603 events_update_definition($component);
604 message_update_providers($component);
605 $endcallback($component, true, $verbose);
606 }
607 }
608 }
609
795a08ad 610 if (empty($currblock->version)) { // block not installed yet, so install it
611 // If it allows multiples, start with it enabled
612
613 $conflictblock = array_search($blocktitle, $blocktitles);
614 if ($conflictblock !== false) {
615 // Duplicate block titles are not allowed, they confuse people
616 // AND PHP's associative arrays ;)
617 throw new plugin_defective_exception($component, get_string('blocknameconflict', '', (object)array('name'=>$block->name, 'conflict'=>$conflictblock)));
618 }
194cdca8 619 $startcallback($component, true, $verbose);
795a08ad 620
621 if (file_exists($fullblock.'/db/install.xml')) {
622 $DB->get_manager()->install_from_xmldb_file($fullblock.'/db/install.xml');
623 }
624 $block->id = $DB->insert_record('block', $block);
625
626 if (file_exists($fullblock.'/db/install.php')) {
627 require_once($fullblock.'/db/install.php');
9b683d13 628 // Set installation running flag, we need to recover after exception or error
629 set_config('installrunning', 1, 'block_'.$blockname);
795a08ad 630 $post_install_function = 'xmldb_block_'.$blockname.'_install';;
631 $post_install_function();
9b683d13 632 unset_config('installrunning', 'block_'.$blockname);
795a08ad 633 }
634
635 $blocktitles[$block->name] = $blocktitle;
636
637 // Install various components
638 update_capabilities($component);
c976e271 639 external_update_descriptions($component);
795a08ad 640 events_update_definition($component);
641 message_update_providers($component);
642
194cdca8 643 $endcallback($component, true, $verbose);
795a08ad 644
645 } else if ($currblock->version < $block->version) {
194cdca8 646 $startcallback($component, false, $verbose);
795a08ad 647
648 if (is_readable($fullblock.'/db/upgrade.php')) {
649 require_once($fullblock.'/db/upgrade.php'); // defines new upgrading function
650 $newupgrade_function = 'xmldb_block_'.$blockname.'_upgrade';
651 $result = $newupgrade_function($currblock->version, $block);
652 } else {
653 $result = true;
654 }
655
656 $currblock = $DB->get_record('block', array('name'=>$block->name));
657 if ($currblock->version < $block->version) {
658 // store version if not already there
659 upgrade_block_savepoint($result, $block->version, $block->name, false);
660 }
661
662 if ($currblock->cron != $block->cron) {
663 // update cron flag if needed
664 $currblock->cron = $block->cron;
665 $DB->update_record('block', $currblock);
666 }
667
668 // Upgrade various componebts
795a08ad 669 update_capabilities($component);
c976e271 670 external_update_descriptions($component);
17da2e6f 671 events_update_definition($component);
795a08ad 672 message_update_providers($component);
673
194cdca8 674 $endcallback($component, false, $verbose);
795a08ad 675
676 } else if ($currblock->version > $block->version) {
677 throw new downgrade_exception($component, $currblock->version, $block->version);
678 }
679 }
680
681
682 // Finally, if we are in the first_install of BLOCKS setup frontpage and admin page blocks
683 if ($first_install) {
795a08ad 684 //Iterate over each course - there should be only site course here now
685 if ($courses = $DB->get_records('course')) {
686 foreach ($courses as $course) {
9d1d606e 687 blocks_add_default_course_blocks($course);
db9d4a3d 688 }
689 }
795a08ad 690
9d1d606e 691 blocks_add_default_system_blocks();
795a08ad 692 }
693}
694
c976e271 695/**
696 * Web service discovery function used during install and upgrade.
697 * @param string $component name of component (moodle, mod_assignment, etc.)
698 * @return void
699 */
700function external_update_descriptions($component) {
701 global $DB;
702
703 $defpath = get_component_directory($component).'/db/services.php';
704
705 if (!file_exists($defpath)) {
706 external_delete_descriptions($component);
707 return;
708 }
709
710 // load new info
711 $functions = array();
712 $services = array();
713 include($defpath);
714
715 // update all function fist
716 $dbfunctions = $DB->get_records('external_functions', array('component'=>$component));
717 foreach ($dbfunctions as $dbfunction) {
718 if (empty($functions[$dbfunction->name])) {
719 $DB->delete_records('external_functions', array('id'=>$dbfunction->id));
720 // do not delete functions from external_services_functions, beacuse
721 // we want to notify admins when functions used in custom services disappear
722 continue;
723 }
724
725 $function = $functions[$dbfunction->name];
726 unset($functions[$dbfunction->name]);
727 $function['classpath'] = empty($function['classpath']) ? null : $function['classpath'];
728
729 $update = false;
730 if ($dbfunction->classname != $function['classname']) {
731 $dbfunction->classname = $function['classname'];
732 $update = true;
733 }
734 if ($dbfunction->methodname != $function['methodname']) {
735 $dbfunction->methodname = $function['methodname'];
736 $update = true;
737 }
738 if ($dbfunction->classpath != $function['classpath']) {
739 $dbfunction->classpath = $function['classpath'];
740 $update = true;
741 }
742 if ($update) {
743 $DB->update_record('external_functions', $dbfunction);
744 }
745 }
746 foreach ($functions as $fname => $function) {
747 $dbfunction = new object();
748 $dbfunction->name = $fname;
749 $dbfunction->classname = $function['classname'];
750 $dbfunction->methodname = $function['methodname'];
751 $dbfunction->classpath = empty($function['classpath']) ? null : $function['classpath'];
752 $dbfunction->component = $component;
753 $dbfunction->id = $DB->insert_record('external_functions', $dbfunction);
754 }
755 unset($functions);
756
757 // now deal with services
758 $dbservices = $DB->get_records('external_services', array('component'=>$component));
759 foreach ($dbservices as $dbservice) {
760 if (empty($services[$dbservice->name])) {
761 $DB->delete_records('external_services_functions', array('externalserviceid'=>$dbservice->id));
762 $DB->delete_records('external_services_users', array('externalserviceid'=>$dbservice->id));
763 $DB->delete_records('external_services', array('id'=>$dbservice->id));
764 continue;
765 }
766 $service = $services[$dbservice->name];
767 unset($services[$dbservice->name]);
768 $service['enabled'] = empty($service['enabled']) ? 0 : $service['enabled'];
769 $service['requiredcapability'] = empty($service['requiredcapability']) ? null : $service['requiredcapability'];
770 $service['restrictedusers'] = !isset($service['restrictedusers']) ? 1 : $service['restrictedusers'];
771
772 $update = false;
773 if ($dbservice->enabled != $service['enabled']) {
774 $dbservice->enabled = $service['enabled'];
775 $update = true;
776 }
777 if ($dbservice->requiredcapability != $service['requiredcapability']) {
778 $dbservice->requiredcapability = $service['requiredcapability'];
779 $update = true;
780 }
781 if ($dbservice->restrictedusers != $service['restrictedusers']) {
782 $dbservice->restrictedusers = $service['restrictedusers'];
783 $update = true;
784 }
785 if ($update) {
786 $DB->update_record('external_services', $dbservice);
787 }
788
789 $functions = $DB->get_records('external_services_functions', array('externalserviceid'=>$dbservice->id));
790 foreach ($functions as $function) {
791 $key = array_search($function->functionname, $service['functions']);
792 if ($key === false) {
793 $DB->delete_records('external_services_functions', array('id'=>$function->id));
794 } else {
795 unset($service['functions'][$key]);
796 }
797 }
798 foreach ($service['functions'] as $fname) {
799 $newf = new object();
800 $newf->externalserviceid = $dbservice->id;
801 $newf->functionname = $fname;
802 $DB->insert_record('external_services_functions', $newf);
803 }
804 unset($functions);
805 }
806 foreach ($services as $name => $service) {
807 $dbservice = new object();
808 $dbservice->name = $name;
809 $dbservice->enabled = empty($service['enabled']) ? 0 : $service['enabled'];
810 $dbservice->requiredcapability = empty($service['requiredcapability']) ? null : $service['requiredcapability'];
811 $dbservice->restrictedusers = !isset($service['restrictedusers']) ? 1 : $service['restrictedusers'];
812 $dbservice->component = $component;
813 $dbservice->id = $DB->insert_record('external_services', $dbservice);
814 foreach ($service['functions'] as $fname) {
815 $newf = new object();
816 $newf->externalserviceid = $dbservice->id;
817 $newf->functionname = $fname;
818 $DB->insert_record('external_services_functions', $newf);
819 }
820 }
821}
822
823/**
824 * Delete all service and external functions information defined in the specified compoment.
825 * @param string $component name of component (moodle, mod_assignment, etc.)
826 * @return void
827 */
828function external_delete_descriptions($component) {
829 global $DB;
830
831 $params = array($component);
832
833 $DB->delete_records_select('external_services_users', "externalserviceid IN (SELECT id FROM {external_services} WHERE component = ?)", $params);
834 $DB->delete_records_select('external_services_functions', "externalserviceid IN (SELECT id FROM {external_services} WHERE component = ?)", $params);
835 $DB->delete_records('external_services', array('component'=>$component));
836 $DB->delete_records('external_functions', array('component'=>$component));
837}
838
72fb21b6 839/**
840 * upgrade logging functions
72fb21b6 841 */
fd1a792e 842function upgrade_handle_exception($ex, $plugin = null) {
843 default_exception_handler($ex, true, $plugin);
db9d4a3d 844}
845
846/**
847 * Adds log entry into upgrade_log table
848 *
72fb21b6 849 * @global object
850 * @global object
851 * @global object
db9d4a3d 852 * @param int $type UPGRADE_LOG_NORMAL, UPGRADE_LOG_NOTICE or UPGRADE_LOG_ERROR
853 * @param string $plugin plugin or null if main
854 * @param string $info short description text of log entry
855 * @param string $details long problem description
856 * @param string $backtrace string used for errors only
857 * @return void
858 */
859function upgrade_log($type, $plugin, $info, $details=null, $backtrace=null) {
860 global $DB, $USER, $CFG;
861
795a08ad 862 $plugin = ($plugin==='moodle') ? null : $plugin;
863
34a2777c 864 $backtrace = format_backtrace($backtrace, true);
db9d4a3d 865
866 $version = null;
867
868 //first try to find out current version number
795a08ad 869 if (empty($plugin) or $plugin === 'moodle') {
db9d4a3d 870 //main
871 $version = $CFG->version;
872
795a08ad 873 } else if ($plugin === 'local') {
874 //customisation
875 $version = $CFG->local_version;
876
877 } else if (strpos($plugin, 'mod/') === 0) {
db9d4a3d 878 try {
879 $modname = substr($plugin, strlen('mod/'));
880 $version = $DB->get_field('modules', 'version', array('name'=>$modname));
795a08ad 881 $version = ($version === false) ? null : $version;
db9d4a3d 882 } catch (Exception $ignored) {
883 }
884
795a08ad 885 } else if (strpos($plugin, 'block/') === 0) {
db9d4a3d 886 try {
795a08ad 887 $blockname = substr($plugin, strlen('block/'));
db9d4a3d 888 if ($block = $DB->get_record('block', array('name'=>$blockname))) {
889 $version = $block->version;
890 }
891 } catch (Exception $ignored) {
892 }
795a08ad 893
894 } else {
895 $pluginversion = get_config(str_replace('/', '_', $plugin), 'version');
896 if (!empty($pluginversion)) {
897 $version = $pluginversion;
898 }
db9d4a3d 899 }
900
901 $log = new object();
902 $log->type = $type;
903 $log->plugin = $plugin;
904 $log->version = $version;
905 $log->info = $info;
906 $log->details = $details;
907 $log->backtrace = $backtrace;
908 $log->userid = $USER->id;
909 $log->timemodified = time();
db9d4a3d 910 try {
911 $DB->insert_record('upgrade_log', $log);
912 } catch (Exception $ignored) {
795a08ad 913 // possible during install or 2.0 upgrade
db9d4a3d 914 }
915}
916
917/**
918 * Marks start of upgrade, blocks any other access to site.
919 * The upgrade is finished at the end of script or after timeout.
72fb21b6 920 *
921 * @global object
922 * @global object
923 * @global object
db9d4a3d 924 */
925function upgrade_started($preinstall=false) {
de6d81e6 926 global $CFG, $DB, $PAGE, $OUTPUT;
db9d4a3d 927
928 static $started = false;
929
930 if ($preinstall) {
931 ignore_user_abort(true);
932 upgrade_setup_debug(true);
933
934 } else if ($started) {
935 upgrade_set_timeout(120);
936
937 } else {
c13a5e71 938 if (!CLI_SCRIPT and !$PAGE->headerprinted) {
db9d4a3d 939 $strupgrade = get_string('upgradingversion', 'admin');
d4a03c00 940 $PAGE->set_generaltype('maintenance');
e29380f3 941 upgrade_get_javascript();
de6d81e6 942 $PAGE->set_title($strupgrade.' - Moodle '.$CFG->target_release);
943 $PAGE->set_heading($strupgrade);
944 $PAGE->navbar->add($strupgrade);
945 $PAGE->set_cacheable(false);
946 echo $OUTPUT->header();
db9d4a3d 947 }
948
949 ignore_user_abort(true);
950 register_shutdown_function('upgrade_finished_handler');
951 upgrade_setup_debug(true);
952 set_config('upgraderunning', time()+300);
953 $started = true;
954 }
955}
956
957/**
958 * Internal function - executed if upgrade interruped.
959 */
960function upgrade_finished_handler() {
961 upgrade_finished();
962}
963
964/**
965 * Indicates upgrade is finished.
966 *
967 * This function may be called repeatedly.
72fb21b6 968 *
969 * @global object
970 * @global object
db9d4a3d 971 */
972function upgrade_finished($continueurl=null) {
7e0d6675 973 global $CFG, $DB, $OUTPUT;
db9d4a3d 974
975 if (!empty($CFG->upgraderunning)) {
976 unset_config('upgraderunning');
977 upgrade_setup_debug(false);
978 ignore_user_abort(false);
979 if ($continueurl) {
aa9a6867 980 echo $OUTPUT->continue_button($continueurl);
7e0d6675 981 echo $OUTPUT->footer();
db9d4a3d 982 die;
983 }
984 }
985}
986
72fb21b6 987/**
988 * @global object
989 * @global object
990 */
db9d4a3d 991function upgrade_setup_debug($starting) {
992 global $CFG, $DB;
993
994 static $originaldebug = null;
995
996 if ($starting) {
997 if ($originaldebug === null) {
998 $originaldebug = $DB->get_debug();
999 }
1000 if (!empty($CFG->upgradeshowsql)) {
1001 $DB->set_debug(true);
1002 }
1003 } else {
1004 $DB->set_debug($originaldebug);
1005 }
1006}
1007
72fb21b6 1008/**
1009 * @global object
1010 */
90509582 1011function print_upgrade_reload($url) {
f2a1963c 1012 global $OUTPUT;
90509582 1013
1014 echo "<br />";
1015 echo '<div class="continuebutton">';
f2a1963c 1016 echo '<a href="'.$url.'" title="'.get_string('reload').'" ><img src="'.$OUTPUT->old_icon_url('i/reload') . '" alt="" /> '.get_string('reload').'</a>';
90509582 1017 echo '</div><br />';
1018}
1019
db9d4a3d 1020function print_upgrade_separator() {
1021 if (!CLI_SCRIPT) {
1022 echo '<hr />';
1023 }
1024}
1025
795a08ad 1026/**
1027 * Default start upgrade callback
1028 * @param string $plugin
1029 * @param bool $installation true if installation, false menas upgrade
1030 */
194cdca8 1031function print_upgrade_part_start($plugin, $installation, $verbose) {
3c159385 1032 global $OUTPUT;
795a08ad 1033 if (empty($plugin) or $plugin == 'moodle') {
1034 upgrade_started($installation); // does not store upgrade running flag yet
194cdca8 1035 if ($verbose) {
3c159385 1036 echo $OUTPUT->heading(get_string('coresystem'));
194cdca8 1037 }
795a08ad 1038 } else {
1039 upgrade_started();
194cdca8 1040 if ($verbose) {
3c159385 1041 echo $OUTPUT->heading($plugin);
194cdca8 1042 }
795a08ad 1043 }
1044 if ($installation) {
1045 if (empty($plugin) or $plugin == 'moodle') {
1046 // no need to log - log table not yet there ;-)
1047 } else {
1048 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Starting plugin installation');
1049 }
1050 } else {
1051 if (empty($plugin) or $plugin == 'moodle') {
1052 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Starting core upgrade');
1053 } else {
1054 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Starting plugin upgrade');
1055 }
1056 }
1057}
1058
1059/**
1060 * Default end upgrade callback
1061 * @param string $plugin
1062 * @param bool $installation true if installation, false menas upgrade
1063 */
194cdca8 1064function print_upgrade_part_end($plugin, $installation, $verbose) {
aa9a6867 1065 global $OUTPUT;
795a08ad 1066 upgrade_started();
1067 if ($installation) {
1068 if (empty($plugin) or $plugin == 'moodle') {
1069 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Core installed');
1070 } else {
1071 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Plugin installed');
1072 }
1073 } else {
1074 if (empty($plugin) or $plugin == 'moodle') {
1075 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Core upgraded');
1076 } else {
1077 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Plugin upgraded');
1078 }
1079 }
194cdca8 1080 if ($verbose) {
aa9a6867 1081 echo $OUTPUT->notification(get_string('success'), 'notifysuccess');
194cdca8 1082 print_upgrade_separator();
96db14f9 1083 }
1084}
1085
72fb21b6 1086/**
1087 * @global object
1088 */
db9d4a3d 1089function upgrade_get_javascript() {
e29380f3 1090 global $PAGE;
1091 $PAGE->requires->js('lib/javascript-static.js')->at_top_of_body();
1092 $PAGE->requires->js_function_call('repeatedly_scroll_to_end')->at_top_of_body();
1093 $PAGE->requires->js_function_call('cancel_scroll_to_end')->after_delay(1);
db9d4a3d 1094}
1095
1096
1097/**
1098 * Try to upgrade the given language pack (or current language)
72fb21b6 1099 * @global object
db9d4a3d 1100 */
1101function upgrade_language_pack($lang='') {
3c159385 1102 global $CFG, $OUTPUT;
db9d4a3d 1103
1104 if (empty($lang)) {
1105 $lang = current_language();
1106 }
1107
1108 if ($lang == 'en_utf8') {
1109 return true; // Nothing to do
1110 }
1111
551fe0e5 1112 upgrade_started(false);
3c159385 1113 echo $OUTPUT->heading(get_string('langimport', 'admin').': '.$lang);
db9d4a3d 1114
1115 @mkdir ($CFG->dataroot.'/temp/'); //make it in case it's a fresh install, it might not be there
1116 @mkdir ($CFG->dataroot.'/lang/');
1117
1118 require_once($CFG->libdir.'/componentlib.class.php');
1119
1120 if ($cd = new component_installer('http://download.moodle.org', 'lang16', $lang.'.zip', 'languages.md5', 'lang')) {
1121 $status = $cd->install(); //returns COMPONENT_(ERROR | UPTODATE | INSTALLED)
1122
1123 if ($status == COMPONENT_INSTALLED) {
db9d4a3d 1124 @unlink($CFG->dataroot.'/cache/languages');
551fe0e5 1125 if ($parentlang = get_parent_language($lang)) {
1126 if ($cd = new component_installer('http://download.moodle.org', 'lang16', $parentlang.'.zip', 'languages.md5', 'lang')) {
1127 $cd->install();
1128 }
1129 }
aa9a6867 1130 echo $OUTPUT->notification(get_string('success'), 'notifysuccess');
db9d4a3d 1131 }
1132 }
1133
551fe0e5 1134 print_upgrade_separator();
db9d4a3d 1135}
8580535b 1136
1137/**
1138 * Install core moodle tables and initialize
1139 * @param float $version target version
1140 * @param bool $verbose
1141 * @return void, may throw exception
1142 */
1143function install_core($version, $verbose) {
1144 global $CFG, $DB;
1145
1146 try {
c3d0e149 1147 set_time_limit(600);
194cdca8 1148 print_upgrade_part_start('moodle', true, $verbose); // does not store upgrade running flag
8580535b 1149
1150 $DB->get_manager()->install_from_xmldb_file("$CFG->libdir/db/install.xml");
1151 upgrade_started(); // we want the flag to be stored in config table ;-)
1152
1153 // set all core default records and default settings
1154 require_once("$CFG->libdir/db/install.php");
1155 xmldb_main_install();
1156
1157 // store version
1158 upgrade_main_savepoint(true, $version, false);
1159
1160 // Continue with the instalation
1161 events_update_definition('moodle');
1162 message_update_providers('moodle');
8580535b 1163
1164 // Write default settings unconditionlly
1165 admin_apply_default_settings(NULL, true);
1166
194cdca8 1167 print_upgrade_part_end(null, true, $verbose);
8580535b 1168 } catch (exception $ex) {
1169 upgrade_handle_exception($ex);
1170 }
1171}
1172
1173/**
1174 * Upgrade moodle core
1175 * @param float $version target version
1176 * @param bool $verbose
1177 * @return void, may throw exception
1178 */
1179function upgrade_core($version, $verbose) {
1180 global $CFG;
1181
3316fe24 1182 require_once($CFG->libdir.'/db/upgrade.php'); // Defines upgrades
3316fe24 1183
8580535b 1184 try {
1185 // Upgrade current language pack if we can
1186 if (empty($CFG->skiplangupgrade)) {
1187 upgrade_language_pack(false);
1188 }
1189
194cdca8 1190 print_upgrade_part_start('moodle', false, $verbose);
8580535b 1191
17da2e6f 1192 // one time special local migration pre 2.0 upgrade script
1193 if ($version < 2007101600) {
1194 $pre20upgradefile = "$CFG->dirrot/local/upgrade_pre20.php";
1195 if (file_exists($pre20upgradefile)) {
1196 set_time_limit(0);
1197 require($pre20upgradefile);
1198 // reset upgrade timeout to default
1199 upgrade_set_timeout();
1200 }
1201 }
1202
8580535b 1203 $result = xmldb_main_upgrade($CFG->version);
1204 if ($version > $CFG->version) {
1205 // store version if not already there
1206 upgrade_main_savepoint($result, $version, false);
1207 }
1208
1209 // perform all other component upgrade routines
1210 update_capabilities('moodle');
c976e271 1211 external_update_descriptions('moodle');
8580535b 1212 events_update_definition('moodle');
1213 message_update_providers('moodle');
8580535b 1214
1215 remove_dir($CFG->dataroot . '/cache', true); // flush cache
1216
194cdca8 1217 print_upgrade_part_end('moodle', false, $verbose);
8580535b 1218 } catch (Exception $ex) {
1219 upgrade_handle_exception($ex);
1220 }
1221}
1222
1223/**
1224 * Upgrade/install other parts of moodle
1225 * @param bool $verbose
1226 * @return void, may throw exception
1227 */
1228function upgrade_noncore($verbose) {
1229 global $CFG;
1230
8580535b 1231 // upgrade all plugins types
1232 try {
1233 $plugintypes = get_plugin_types();
1234 foreach ($plugintypes as $type=>$location) {
17da2e6f 1235 upgrade_plugins($type, 'print_upgrade_part_start', 'print_upgrade_part_end', $verbose);
8580535b 1236 }
1237 } catch (Exception $ex) {
1238 upgrade_handle_exception($ex);
1239 }
1240
1241 // Check for changes to RPC functions
1242 if ($CFG->mnet_dispatcher_mode != 'off') {
1243 try {
1244 // this needs a full rewrite, sorry to mention that :-(
1245 // we have to make it part of standard WS framework
1246 require_once("$CFG->dirroot/$CFG->admin/mnet/adminlib.php");
1247 upgrade_RPC_functions(); // Return here afterwards
1248 } catch (Exception $ex) {
1249 upgrade_handle_exception($ex);
1250 }
1251 }
8580535b 1252}
3316fe24 1253
1254/**
1255 * Checks if the main tables have been installed yet or not.
1256 * @return bool
1257 */
1258function core_tables_exist() {
1259 global $DB;
1260
1261 if (!$tables = $DB->get_tables() ) { // No tables yet at all.
1262 return false;
9b683d13 1263
3316fe24 1264 } else { // Check for missing main tables
1265 $mtables = array('config', 'course', 'groupings'); // some tables used in 1.9 and 2.0, preferable something from the start and end of install.xml
1266 foreach ($mtables as $mtable) {
1267 if (!in_array($mtable, $tables)) {
1268 return false;
1269 }
1270 }
1271 return true;
9b683d13 1272 }
ba04999c 1273}