resetting more filters in each upgrade
[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 {
4f0c2d00 43 function __construct($plugin, $version, $debuginfo=NULL) {
795a08ad 44 global $CFG;
45 $a = (object)array('plugin'=>$plugin, 'version'=>$version);
4f0c2d00 46 parent::__construct('upgradeerror', 'admin', "$CFG->wwwroot/$CFG->admin/index.php", $a, $debuginfo);
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);
de260e0f 338 upgrade_plugin_mnet_functions($component);
9b683d13 339 $endcallback($component, true, $verbose);
340 }
341 }
342 }
db9d4a3d 343
9b683d13 344 $installedversion = get_config($plugin->fullname, 'version');
795a08ad 345 if (empty($installedversion)) { // new installation
194cdca8 346 $startcallback($component, true, $verbose);
db9d4a3d 347
795a08ad 348 /// Install tables if defined
349 if (file_exists($fullplug.'/db/install.xml')) {
350 $DB->get_manager()->install_from_xmldb_file($fullplug.'/db/install.xml');
db9d4a3d 351 }
9b683d13 352
353 /// store version
354 upgrade_plugin_savepoint(true, $plugin->version, $type, $plug, false);
355
795a08ad 356 /// execute post install file
357 if (file_exists($fullplug.'/db/install.php')) {
358 require_once($fullplug.'/db/install.php');
9b683d13 359 set_config('installrunning', 1, 'block_'.$plugin->fullname);
795a08ad 360 $post_install_function = 'xmldb_'.$plugin->fullname.'_install';;
361 $post_install_function();
9b683d13 362 unset_config('installrunning', 'block_'.$plugin->fullname);
795a08ad 363 }
364
795a08ad 365 /// Install various components
366 update_capabilities($component);
c976e271 367 external_update_descriptions($component);
795a08ad 368 events_update_definition($component);
369 message_update_providers($component);
de260e0f 370 upgrade_plugin_mnet_functions($component);
795a08ad 371
0139ec3f 372 upgrade_reset_caches();
194cdca8 373 $endcallback($component, true, $verbose);
795a08ad 374
375 } else if ($installedversion < $plugin->version) { // upgrade
376 /// Run the upgrade function for the plugin.
194cdca8 377 $startcallback($component, false, $verbose);
795a08ad 378
379 if (is_readable($fullplug.'/db/upgrade.php')) {
380 require_once($fullplug.'/db/upgrade.php'); // defines upgrading function
381
382 $newupgrade_function = 'xmldb_'.$plugin->fullname.'_upgrade';
383 $result = $newupgrade_function($installedversion);
384 } else {
385 $result = true;
386 }
387
388 $installedversion = get_config($plugin->fullname, 'version');
389 if ($installedversion < $plugin->version) {
390 // store version if not already there
391 upgrade_plugin_savepoint($result, $plugin->version, $type, $plug, false);
392 }
393
394 /// Upgrade various components
395 update_capabilities($component);
c976e271 396 external_update_descriptions($component);
795a08ad 397 events_update_definition($component);
398 message_update_providers($component);
de260e0f 399 upgrade_plugin_mnet_functions($component);
795a08ad 400
0139ec3f 401 upgrade_reset_caches();
194cdca8 402 $endcallback($component, false, $verbose);
795a08ad 403
404 } else if ($installedversion > $plugin->version) {
405 throw new downgrade_exception($component, $installedversion, $plugin->version);
db9d4a3d 406 }
407 }
db9d4a3d 408}
409
410/**
411 * Find and check all modules and load them up or upgrade them if necessary
72fb21b6 412 *
413 * @global object
414 * @global object
db9d4a3d 415 */
194cdca8 416function upgrade_plugins_modules($startcallback, $endcallback, $verbose) {
db9d4a3d 417 global $CFG, $DB;
418
17da2e6f 419 $mods = get_plugin_list('mod');
db9d4a3d 420
17da2e6f 421 foreach ($mods as $mod=>$fullmod) {
db9d4a3d 422
423 if ($mod == 'NEWMODULE') { // Someone has unzipped the template, ignore it
424 continue;
425 }
426
17da2e6f 427 $component = 'mod_'.$mod;
db9d4a3d 428
795a08ad 429 if (!is_readable($fullmod.'/version.php')) {
430 throw new plugin_defective_exception($component, 'Missing version.php');
db9d4a3d 431 }
432
795a08ad 433 $module = new object();
434 require($fullmod .'/version.php'); // defines $module with version etc
db9d4a3d 435
795a08ad 436 if (empty($module->version)) {
c1fe2368 437 if (isset($module->version)) {
438 // Version is empty but is set - it means its value is 0 or ''. Let us skip such module.
b921b6ee 439 // This is intended for developers so they can work on the early stages of the module.
c1fe2368 440 continue;
441 }
795a08ad 442 throw new plugin_defective_exception($component, 'Missing version value in version.php');
db9d4a3d 443 }
444
445 if (!empty($module->requires)) {
446 if ($module->requires > $CFG->version) {
795a08ad 447 throw new upgrade_requires_exception($component, $module->version, $CFG->version, $module->requires);
db9d4a3d 448 }
449 }
450
451 $module->name = $mod; // The name MUST match the directory
452
795a08ad 453 $currmodule = $DB->get_record('modules', array('name'=>$module->name));
db9d4a3d 454
9b683d13 455 if (file_exists($fullmod.'/db/install.php')) {
456 if (get_config($module->name, 'installrunning')) {
457 require_once($fullmod.'/db/install.php');
458 $recover_install_function = 'xmldb_'.$module->name.'_install_recovery';
459 if (function_exists($recover_install_function)) {
460 $startcallback($component, true, $verbose);
461 $recover_install_function();
462 unset_config('installrunning', $module->name);
463 // Install various components too
464 update_capabilities($component);
c976e271 465 external_update_descriptions($component);
9b683d13 466 events_update_definition($component);
467 message_update_providers($component);
de260e0f 468 upgrade_plugin_mnet_functions($component);
9b683d13 469 $endcallback($component, true, $verbose);
470 }
471 }
472 }
473
795a08ad 474 if (empty($currmodule->version)) {
194cdca8 475 $startcallback($component, true, $verbose);
db9d4a3d 476
795a08ad 477 /// Execute install.xml (XMLDB) - must be present in all modules
478 $DB->get_manager()->install_from_xmldb_file($fullmod.'/db/install.xml');
db9d4a3d 479
2e3da297 480 /// Add record into modules table - may be needed in install.php already
481 $module->id = $DB->insert_record('modules', $module);
482
db9d4a3d 483 /// Post installation hook - optional
484 if (file_exists("$fullmod/db/install.php")) {
485 require_once("$fullmod/db/install.php");
9b683d13 486 // Set installation running flag, we need to recover after exception or error
487 set_config('installrunning', 1, $module->name);
db9d4a3d 488 $post_install_function = 'xmldb_'.$module->name.'_install';;
489 $post_install_function();
9b683d13 490 unset_config('installrunning', $module->name);
db9d4a3d 491 }
492
795a08ad 493 /// Install various components
494 update_capabilities($component);
c976e271 495 external_update_descriptions($component);
795a08ad 496 events_update_definition($component);
497 message_update_providers($component);
de260e0f 498 upgrade_plugin_mnet_functions($component);
795a08ad 499
0139ec3f 500 upgrade_reset_caches();
194cdca8 501 $endcallback($component, true, $verbose);
db9d4a3d 502
795a08ad 503 } else if ($currmodule->version < $module->version) {
504 /// If versions say that we need to upgrade but no upgrade files are available, notify and continue
194cdca8 505 $startcallback($component, false, $verbose);
795a08ad 506
507 if (is_readable($fullmod.'/db/upgrade.php')) {
508 require_once($fullmod.'/db/upgrade.php'); // defines new upgrading function
509 $newupgrade_function = 'xmldb_'.$module->name.'_upgrade';
510 $result = $newupgrade_function($currmodule->version, $module);
511 } else {
512 $result = true;
513 }
514
515 $currmodule = $DB->get_record('modules', array('name'=>$module->name));
516 if ($currmodule->version < $module->version) {
517 // store version if not already there
518 upgrade_mod_savepoint($result, $module->version, $mod, false);
519 }
520
521 /// Upgrade various components
522 update_capabilities($component);
c976e271 523 external_update_descriptions($component);
795a08ad 524 events_update_definition($component);
525 message_update_providers($component);
de260e0f 526 upgrade_plugin_mnet_functions($component);
795a08ad 527
0139ec3f 528 upgrade_reset_caches();
795a08ad 529 remove_dir($CFG->dataroot.'/cache', true); // flush cache
530
194cdca8 531 $endcallback($component, false, $verbose);
795a08ad 532
533 } else if ($currmodule->version > $module->version) {
534 throw new downgrade_exception($component, $currmodule->version, $module->version);
535 }
536 }
537}
db9d4a3d 538
db9d4a3d 539
795a08ad 540/**
541 * This function finds all available blocks and install them
542 * into blocks table or do all the upgrade process if newer.
72fb21b6 543 *
544 * @global object
545 * @global object
795a08ad 546 */
194cdca8 547function upgrade_plugins_blocks($startcallback, $endcallback, $verbose) {
795a08ad 548 global $CFG, $DB;
549
795a08ad 550 require_once($CFG->dirroot.'/blocks/moodleblock.class.php');
551
552 $blocktitles = array(); // we do not want duplicate titles
553
554 //Is this a first install
555 $first_install = null;
556
17da2e6f 557 $blocks = get_plugin_list('block');
795a08ad 558
17da2e6f 559 foreach ($blocks as $blockname=>$fullblock) {
795a08ad 560
561 if (is_null($first_install)) {
f46eba7e 562 $first_install = ($DB->count_records('block_instances') == 0);
795a08ad 563 }
564
565 if ($blockname == 'NEWBLOCK') { // Someone has unzipped the template, ignore it
566 continue;
db9d4a3d 567 }
568
17da2e6f 569 $component = 'block_'.$blockname;
db9d4a3d 570
8571833f
PS
571 if (!is_readable($fullblock.'/version.php')) {
572 throw new plugin_defective_exception('block/'.$blockname, 'Missing version.php file.');
573 }
574 $plugin = new object();
575 $plugin->version = NULL;
576 $plugin->cron = 0;
577 include($fullblock.'/version.php');
578 $block = $plugin;
579
795a08ad 580 if (!is_readable($fullblock.'/block_'.$blockname.'.php')) {
581 throw new plugin_defective_exception('block/'.$blockname, 'Missing main block class file.');
db9d4a3d 582 }
8571833f 583 include_once($fullblock.'/block_'.$blockname.'.php');
db9d4a3d 584
795a08ad 585 $classname = 'block_'.$blockname;
586
587 if (!class_exists($classname)) {
588 throw new plugin_defective_exception($component, 'Can not load main class.');
589 }
590
b921b6ee 591 $blockobj = new $classname; // This is what we'll be testing
795a08ad 592 $blocktitle = $blockobj->get_title();
593
594 // OK, it's as we all hoped. For further tests, the object will do them itself.
595 if (!$blockobj->_self_test()) {
596 throw new plugin_defective_exception($component, 'Self test failed.');
597 }
598
795a08ad 599 $block->name = $blockname; // The name MUST match the directory
795a08ad 600 $block->multiple = $blockobj->instance_allow_multiple() ? 1 : 0;
601
602 if (empty($block->version)) {
603 throw new plugin_defective_exception($component, 'Missing block version.');
604 }
605
606 $currblock = $DB->get_record('block', array('name'=>$block->name));
607
9b683d13 608 if (file_exists($fullblock.'/db/install.php')) {
609 if (get_config('block_'.$blockname, 'installrunning')) {
610 require_once($fullblock.'/db/install.php');
611 $recover_install_function = 'xmldb_block_'.$blockname.'_install_recovery';
612 if (function_exists($recover_install_function)) {
613 $startcallback($component, true, $verbose);
614 $recover_install_function();
615 unset_config('installrunning', 'block_'.$blockname);
616 // Install various components
617 update_capabilities($component);
c976e271 618 external_update_descriptions($component);
9b683d13 619 events_update_definition($component);
620 message_update_providers($component);
de260e0f 621 upgrade_plugin_mnet_functions($component);
9b683d13 622 $endcallback($component, true, $verbose);
623 }
624 }
625 }
626
795a08ad 627 if (empty($currblock->version)) { // block not installed yet, so install it
628 // If it allows multiples, start with it enabled
629
630 $conflictblock = array_search($blocktitle, $blocktitles);
631 if ($conflictblock !== false) {
632 // Duplicate block titles are not allowed, they confuse people
633 // AND PHP's associative arrays ;)
634 throw new plugin_defective_exception($component, get_string('blocknameconflict', '', (object)array('name'=>$block->name, 'conflict'=>$conflictblock)));
635 }
194cdca8 636 $startcallback($component, true, $verbose);
795a08ad 637
638 if (file_exists($fullblock.'/db/install.xml')) {
639 $DB->get_manager()->install_from_xmldb_file($fullblock.'/db/install.xml');
640 }
641 $block->id = $DB->insert_record('block', $block);
642
643 if (file_exists($fullblock.'/db/install.php')) {
644 require_once($fullblock.'/db/install.php');
9b683d13 645 // Set installation running flag, we need to recover after exception or error
646 set_config('installrunning', 1, 'block_'.$blockname);
795a08ad 647 $post_install_function = 'xmldb_block_'.$blockname.'_install';;
648 $post_install_function();
9b683d13 649 unset_config('installrunning', 'block_'.$blockname);
795a08ad 650 }
651
652 $blocktitles[$block->name] = $blocktitle;
653
654 // Install various components
655 update_capabilities($component);
c976e271 656 external_update_descriptions($component);
795a08ad 657 events_update_definition($component);
658 message_update_providers($component);
de260e0f 659 upgrade_plugin_mnet_functions($component);
795a08ad 660
0139ec3f 661 upgrade_reset_caches();
194cdca8 662 $endcallback($component, true, $verbose);
795a08ad 663
664 } else if ($currblock->version < $block->version) {
194cdca8 665 $startcallback($component, false, $verbose);
795a08ad 666
667 if (is_readable($fullblock.'/db/upgrade.php')) {
668 require_once($fullblock.'/db/upgrade.php'); // defines new upgrading function
669 $newupgrade_function = 'xmldb_block_'.$blockname.'_upgrade';
670 $result = $newupgrade_function($currblock->version, $block);
671 } else {
672 $result = true;
673 }
674
675 $currblock = $DB->get_record('block', array('name'=>$block->name));
676 if ($currblock->version < $block->version) {
677 // store version if not already there
678 upgrade_block_savepoint($result, $block->version, $block->name, false);
679 }
680
681 if ($currblock->cron != $block->cron) {
682 // update cron flag if needed
683 $currblock->cron = $block->cron;
684 $DB->update_record('block', $currblock);
685 }
686
b921b6ee 687 // Upgrade various components
795a08ad 688 update_capabilities($component);
c976e271 689 external_update_descriptions($component);
17da2e6f 690 events_update_definition($component);
795a08ad 691 message_update_providers($component);
de260e0f 692 upgrade_plugin_mnet_functions($component);
795a08ad 693
0139ec3f 694 upgrade_reset_caches();
194cdca8 695 $endcallback($component, false, $verbose);
795a08ad 696
697 } else if ($currblock->version > $block->version) {
698 throw new downgrade_exception($component, $currblock->version, $block->version);
699 }
700 }
701
702
703 // Finally, if we are in the first_install of BLOCKS setup frontpage and admin page blocks
704 if ($first_install) {
795a08ad 705 //Iterate over each course - there should be only site course here now
706 if ($courses = $DB->get_records('course')) {
707 foreach ($courses as $course) {
9d1d606e 708 blocks_add_default_course_blocks($course);
db9d4a3d 709 }
710 }
795a08ad 711
9d1d606e 712 blocks_add_default_system_blocks();
795a08ad 713 }
714}
715
c976e271 716/**
717 * Web service discovery function used during install and upgrade.
718 * @param string $component name of component (moodle, mod_assignment, etc.)
719 * @return void
720 */
721function external_update_descriptions($component) {
722 global $DB;
723
724 $defpath = get_component_directory($component).'/db/services.php';
725
726 if (!file_exists($defpath)) {
727 external_delete_descriptions($component);
728 return;
729 }
730
731 // load new info
732 $functions = array();
733 $services = array();
734 include($defpath);
735
736 // update all function fist
737 $dbfunctions = $DB->get_records('external_functions', array('component'=>$component));
738 foreach ($dbfunctions as $dbfunction) {
739 if (empty($functions[$dbfunction->name])) {
740 $DB->delete_records('external_functions', array('id'=>$dbfunction->id));
741 // do not delete functions from external_services_functions, beacuse
742 // we want to notify admins when functions used in custom services disappear
743 continue;
744 }
745
746 $function = $functions[$dbfunction->name];
747 unset($functions[$dbfunction->name]);
748 $function['classpath'] = empty($function['classpath']) ? null : $function['classpath'];
749
750 $update = false;
751 if ($dbfunction->classname != $function['classname']) {
752 $dbfunction->classname = $function['classname'];
753 $update = true;
754 }
755 if ($dbfunction->methodname != $function['methodname']) {
756 $dbfunction->methodname = $function['methodname'];
757 $update = true;
758 }
759 if ($dbfunction->classpath != $function['classpath']) {
760 $dbfunction->classpath = $function['classpath'];
761 $update = true;
762 }
763 if ($update) {
764 $DB->update_record('external_functions', $dbfunction);
765 }
766 }
767 foreach ($functions as $fname => $function) {
768 $dbfunction = new object();
769 $dbfunction->name = $fname;
770 $dbfunction->classname = $function['classname'];
771 $dbfunction->methodname = $function['methodname'];
772 $dbfunction->classpath = empty($function['classpath']) ? null : $function['classpath'];
773 $dbfunction->component = $component;
774 $dbfunction->id = $DB->insert_record('external_functions', $dbfunction);
775 }
776 unset($functions);
777
778 // now deal with services
779 $dbservices = $DB->get_records('external_services', array('component'=>$component));
780 foreach ($dbservices as $dbservice) {
781 if (empty($services[$dbservice->name])) {
782 $DB->delete_records('external_services_functions', array('externalserviceid'=>$dbservice->id));
783 $DB->delete_records('external_services_users', array('externalserviceid'=>$dbservice->id));
784 $DB->delete_records('external_services', array('id'=>$dbservice->id));
785 continue;
786 }
787 $service = $services[$dbservice->name];
788 unset($services[$dbservice->name]);
789 $service['enabled'] = empty($service['enabled']) ? 0 : $service['enabled'];
790 $service['requiredcapability'] = empty($service['requiredcapability']) ? null : $service['requiredcapability'];
791 $service['restrictedusers'] = !isset($service['restrictedusers']) ? 1 : $service['restrictedusers'];
792
793 $update = false;
794 if ($dbservice->enabled != $service['enabled']) {
795 $dbservice->enabled = $service['enabled'];
796 $update = true;
797 }
798 if ($dbservice->requiredcapability != $service['requiredcapability']) {
799 $dbservice->requiredcapability = $service['requiredcapability'];
800 $update = true;
801 }
802 if ($dbservice->restrictedusers != $service['restrictedusers']) {
803 $dbservice->restrictedusers = $service['restrictedusers'];
804 $update = true;
805 }
806 if ($update) {
807 $DB->update_record('external_services', $dbservice);
808 }
809
810 $functions = $DB->get_records('external_services_functions', array('externalserviceid'=>$dbservice->id));
811 foreach ($functions as $function) {
812 $key = array_search($function->functionname, $service['functions']);
813 if ($key === false) {
814 $DB->delete_records('external_services_functions', array('id'=>$function->id));
815 } else {
816 unset($service['functions'][$key]);
817 }
818 }
819 foreach ($service['functions'] as $fname) {
820 $newf = new object();
821 $newf->externalserviceid = $dbservice->id;
822 $newf->functionname = $fname;
823 $DB->insert_record('external_services_functions', $newf);
824 }
825 unset($functions);
826 }
827 foreach ($services as $name => $service) {
828 $dbservice = new object();
829 $dbservice->name = $name;
830 $dbservice->enabled = empty($service['enabled']) ? 0 : $service['enabled'];
831 $dbservice->requiredcapability = empty($service['requiredcapability']) ? null : $service['requiredcapability'];
832 $dbservice->restrictedusers = !isset($service['restrictedusers']) ? 1 : $service['restrictedusers'];
833 $dbservice->component = $component;
e5180580 834 $dbservice->timecreated = time();
c976e271 835 $dbservice->id = $DB->insert_record('external_services', $dbservice);
836 foreach ($service['functions'] as $fname) {
837 $newf = new object();
838 $newf->externalserviceid = $dbservice->id;
839 $newf->functionname = $fname;
840 $DB->insert_record('external_services_functions', $newf);
841 }
842 }
843}
844
845/**
b921b6ee 846 * Delete all service and external functions information defined in the specified component.
c976e271 847 * @param string $component name of component (moodle, mod_assignment, etc.)
848 * @return void
849 */
850function external_delete_descriptions($component) {
851 global $DB;
852
853 $params = array($component);
854
855 $DB->delete_records_select('external_services_users', "externalserviceid IN (SELECT id FROM {external_services} WHERE component = ?)", $params);
856 $DB->delete_records_select('external_services_functions', "externalserviceid IN (SELECT id FROM {external_services} WHERE component = ?)", $params);
857 $DB->delete_records('external_services', array('component'=>$component));
858 $DB->delete_records('external_functions', array('component'=>$component));
859}
860
72fb21b6 861/**
862 * upgrade logging functions
72fb21b6 863 */
fd1a792e 864function upgrade_handle_exception($ex, $plugin = null) {
a56c457e
PS
865 // rollback everything, we need to log all upgrade problems
866 abort_all_db_transactions();
867
c19bc39c
PS
868 $info = get_exception_info($ex);
869
870 // First log upgrade error
871 upgrade_log(UPGRADE_LOG_ERROR, $plugin, 'Exception: ' . get_class($ex), $info->message, $info->backtrace);
872
873 // Always turn on debugging - admins need to know what is going on
874 $CFG->debug = DEBUG_DEVELOPER;
875
fd1a792e 876 default_exception_handler($ex, true, $plugin);
db9d4a3d 877}
878
879/**
880 * Adds log entry into upgrade_log table
881 *
72fb21b6 882 * @global object
883 * @global object
884 * @global object
db9d4a3d 885 * @param int $type UPGRADE_LOG_NORMAL, UPGRADE_LOG_NOTICE or UPGRADE_LOG_ERROR
886 * @param string $plugin plugin or null if main
887 * @param string $info short description text of log entry
888 * @param string $details long problem description
889 * @param string $backtrace string used for errors only
890 * @return void
891 */
892function upgrade_log($type, $plugin, $info, $details=null, $backtrace=null) {
893 global $DB, $USER, $CFG;
894
795a08ad 895 $plugin = ($plugin==='moodle') ? null : $plugin;
896
34a2777c 897 $backtrace = format_backtrace($backtrace, true);
db9d4a3d 898
899 $version = null;
900
901 //first try to find out current version number
795a08ad 902 if (empty($plugin) or $plugin === 'moodle') {
db9d4a3d 903 //main
904 $version = $CFG->version;
905
795a08ad 906 } else if ($plugin === 'local') {
907 //customisation
908 $version = $CFG->local_version;
909
910 } else if (strpos($plugin, 'mod/') === 0) {
db9d4a3d 911 try {
912 $modname = substr($plugin, strlen('mod/'));
913 $version = $DB->get_field('modules', 'version', array('name'=>$modname));
795a08ad 914 $version = ($version === false) ? null : $version;
db9d4a3d 915 } catch (Exception $ignored) {
916 }
917
795a08ad 918 } else if (strpos($plugin, 'block/') === 0) {
db9d4a3d 919 try {
795a08ad 920 $blockname = substr($plugin, strlen('block/'));
db9d4a3d 921 if ($block = $DB->get_record('block', array('name'=>$blockname))) {
922 $version = $block->version;
923 }
924 } catch (Exception $ignored) {
925 }
795a08ad 926
927 } else {
928 $pluginversion = get_config(str_replace('/', '_', $plugin), 'version');
929 if (!empty($pluginversion)) {
930 $version = $pluginversion;
931 }
db9d4a3d 932 }
933
934 $log = new object();
935 $log->type = $type;
936 $log->plugin = $plugin;
937 $log->version = $version;
938 $log->info = $info;
939 $log->details = $details;
940 $log->backtrace = $backtrace;
941 $log->userid = $USER->id;
942 $log->timemodified = time();
db9d4a3d 943 try {
944 $DB->insert_record('upgrade_log', $log);
945 } catch (Exception $ignored) {
795a08ad 946 // possible during install or 2.0 upgrade
db9d4a3d 947 }
948}
949
950/**
951 * Marks start of upgrade, blocks any other access to site.
952 * The upgrade is finished at the end of script or after timeout.
72fb21b6 953 *
954 * @global object
955 * @global object
956 * @global object
db9d4a3d 957 */
958function upgrade_started($preinstall=false) {
de6d81e6 959 global $CFG, $DB, $PAGE, $OUTPUT;
db9d4a3d 960
961 static $started = false;
962
963 if ($preinstall) {
964 ignore_user_abort(true);
965 upgrade_setup_debug(true);
966
967 } else if ($started) {
968 upgrade_set_timeout(120);
969
970 } else {
c13a5e71 971 if (!CLI_SCRIPT and !$PAGE->headerprinted) {
db9d4a3d 972 $strupgrade = get_string('upgradingversion', 'admin');
78946b9b 973 $PAGE->set_pagelayout('maintenance');
543f54d3 974 upgrade_init_javascript();
de6d81e6 975 $PAGE->set_title($strupgrade.' - Moodle '.$CFG->target_release);
976 $PAGE->set_heading($strupgrade);
977 $PAGE->navbar->add($strupgrade);
978 $PAGE->set_cacheable(false);
979 echo $OUTPUT->header();
db9d4a3d 980 }
981
982 ignore_user_abort(true);
983 register_shutdown_function('upgrade_finished_handler');
984 upgrade_setup_debug(true);
985 set_config('upgraderunning', time()+300);
986 $started = true;
987 }
988}
989
990/**
b921b6ee 991 * Internal function - executed if upgrade interrupted.
db9d4a3d 992 */
993function upgrade_finished_handler() {
994 upgrade_finished();
995}
996
997/**
998 * Indicates upgrade is finished.
999 *
1000 * This function may be called repeatedly.
72fb21b6 1001 *
1002 * @global object
1003 * @global object
db9d4a3d 1004 */
1005function upgrade_finished($continueurl=null) {
7e0d6675 1006 global $CFG, $DB, $OUTPUT;
db9d4a3d 1007
1008 if (!empty($CFG->upgraderunning)) {
1009 unset_config('upgraderunning');
1010 upgrade_setup_debug(false);
1011 ignore_user_abort(false);
1012 if ($continueurl) {
aa9a6867 1013 echo $OUTPUT->continue_button($continueurl);
7e0d6675 1014 echo $OUTPUT->footer();
db9d4a3d 1015 die;
1016 }
1017 }
1018}
1019
72fb21b6 1020/**
1021 * @global object
1022 * @global object
1023 */
db9d4a3d 1024function upgrade_setup_debug($starting) {
1025 global $CFG, $DB;
1026
1027 static $originaldebug = null;
1028
1029 if ($starting) {
1030 if ($originaldebug === null) {
1031 $originaldebug = $DB->get_debug();
1032 }
1033 if (!empty($CFG->upgradeshowsql)) {
1034 $DB->set_debug(true);
1035 }
1036 } else {
1037 $DB->set_debug($originaldebug);
1038 }
1039}
1040
72fb21b6 1041/**
1042 * @global object
1043 */
90509582 1044function print_upgrade_reload($url) {
f2a1963c 1045 global $OUTPUT;
90509582 1046
1047 echo "<br />";
1048 echo '<div class="continuebutton">';
b5d0cafc 1049 echo '<a href="'.$url.'" title="'.get_string('reload').'" ><img src="'.$OUTPUT->pix_url('i/reload') . '" alt="" /> '.get_string('reload').'</a>';
90509582 1050 echo '</div><br />';
1051}
1052
db9d4a3d 1053function print_upgrade_separator() {
1054 if (!CLI_SCRIPT) {
1055 echo '<hr />';
1056 }
1057}
1058
795a08ad 1059/**
1060 * Default start upgrade callback
1061 * @param string $plugin
b921b6ee 1062 * @param bool $installation true if installation, false means upgrade
795a08ad 1063 */
194cdca8 1064function print_upgrade_part_start($plugin, $installation, $verbose) {
3c159385 1065 global $OUTPUT;
795a08ad 1066 if (empty($plugin) or $plugin == 'moodle') {
1067 upgrade_started($installation); // does not store upgrade running flag yet
194cdca8 1068 if ($verbose) {
3c159385 1069 echo $OUTPUT->heading(get_string('coresystem'));
194cdca8 1070 }
795a08ad 1071 } else {
1072 upgrade_started();
194cdca8 1073 if ($verbose) {
3c159385 1074 echo $OUTPUT->heading($plugin);
194cdca8 1075 }
795a08ad 1076 }
1077 if ($installation) {
1078 if (empty($plugin) or $plugin == 'moodle') {
1079 // no need to log - log table not yet there ;-)
1080 } else {
1081 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Starting plugin installation');
1082 }
1083 } else {
1084 if (empty($plugin) or $plugin == 'moodle') {
1085 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Starting core upgrade');
1086 } else {
1087 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Starting plugin upgrade');
1088 }
1089 }
1090}
1091
1092/**
1093 * Default end upgrade callback
1094 * @param string $plugin
b921b6ee 1095 * @param bool $installation true if installation, false means upgrade
795a08ad 1096 */
194cdca8 1097function print_upgrade_part_end($plugin, $installation, $verbose) {
aa9a6867 1098 global $OUTPUT;
795a08ad 1099 upgrade_started();
1100 if ($installation) {
1101 if (empty($plugin) or $plugin == 'moodle') {
1102 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Core installed');
1103 } else {
1104 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Plugin installed');
1105 }
1106 } else {
1107 if (empty($plugin) or $plugin == 'moodle') {
1108 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Core upgraded');
1109 } else {
1110 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Plugin upgraded');
1111 }
1112 }
194cdca8 1113 if ($verbose) {
aa9a6867 1114 echo $OUTPUT->notification(get_string('success'), 'notifysuccess');
194cdca8 1115 print_upgrade_separator();
96db14f9 1116 }
1117}
1118
72fb21b6 1119/**
b921b6ee 1120 * Sets up JS code required for all upgrade scripts.
72fb21b6 1121 * @global object
1122 */
543f54d3 1123function upgrade_init_javascript() {
e29380f3 1124 global $PAGE;
543f54d3
PS
1125 // scroll to the end of each upgrade page so that ppl see either error or continue button,
1126 // no need to scroll continuously any more, it is enough to jump to end once the footer is printed ;-)
1127 $js = "window.scrollTo(0, 5000000);";
1128 $PAGE->requires->js_init_code($js);
db9d4a3d 1129}
1130
1131
1132/**
1133 * Try to upgrade the given language pack (or current language)
af8d4d91
DM
1134 *
1135 * @todo hardcoded Moodle version here - shall be provided by version.php or similar script
db9d4a3d 1136 */
1137function upgrade_language_pack($lang='') {
3c159385 1138 global $CFG, $OUTPUT;
db9d4a3d 1139
af8d4d91
DM
1140 get_string_manager()->reset_caches();
1141
db9d4a3d 1142 if (empty($lang)) {
1143 $lang = current_language();
1144 }
1145
3a915b06 1146 if ($lang == 'en') {
db9d4a3d 1147 return true; // Nothing to do
1148 }
1149
551fe0e5 1150 upgrade_started(false);
3c159385 1151 echo $OUTPUT->heading(get_string('langimport', 'admin').': '.$lang);
db9d4a3d 1152
1153 @mkdir ($CFG->dataroot.'/temp/'); //make it in case it's a fresh install, it might not be there
1154 @mkdir ($CFG->dataroot.'/lang/');
1155
1156 require_once($CFG->libdir.'/componentlib.class.php');
af8d4d91
DM
1157
1158 if ($cd = new component_installer('http://download.moodle.org', 'langpack/2.0', $lang.'.zip', 'languages.md5', 'lang')) {
db9d4a3d 1159 $status = $cd->install(); //returns COMPONENT_(ERROR | UPTODATE | INSTALLED)
1160
1161 if ($status == COMPONENT_INSTALLED) {
af8d4d91 1162 remove_dir($CFG->dataroot.'/cache/languages');
551fe0e5 1163 if ($parentlang = get_parent_language($lang)) {
af8d4d91 1164 if ($cd = new component_installer('http://download.moodle.org', 'langpack/2.0', $parentlang.'.zip', 'languages.md5', 'lang')) {
551fe0e5 1165 $cd->install();
1166 }
1167 }
aa9a6867 1168 echo $OUTPUT->notification(get_string('success'), 'notifysuccess');
db9d4a3d 1169 }
1170 }
af8d4d91
DM
1171
1172 get_string_manager()->reset_caches();
1173
551fe0e5 1174 print_upgrade_separator();
db9d4a3d 1175}
8580535b 1176
1177/**
1178 * Install core moodle tables and initialize
1179 * @param float $version target version
1180 * @param bool $verbose
1181 * @return void, may throw exception
1182 */
1183function install_core($version, $verbose) {
1184 global $CFG, $DB;
1185
1186 try {
c3d0e149 1187 set_time_limit(600);
194cdca8 1188 print_upgrade_part_start('moodle', true, $verbose); // does not store upgrade running flag
8580535b 1189
1190 $DB->get_manager()->install_from_xmldb_file("$CFG->libdir/db/install.xml");
1191 upgrade_started(); // we want the flag to be stored in config table ;-)
1192
1193 // set all core default records and default settings
1194 require_once("$CFG->libdir/db/install.php");
1195 xmldb_main_install();
1196
1197 // store version
1198 upgrade_main_savepoint(true, $version, false);
1199
df997f84 1200 // Continue with the installation
8580535b 1201 events_update_definition('moodle');
1202 message_update_providers('moodle');
8580535b 1203
df997f84 1204 // Write default settings unconditionally
8580535b 1205 admin_apply_default_settings(NULL, true);
1206
194cdca8 1207 print_upgrade_part_end(null, true, $verbose);
8580535b 1208 } catch (exception $ex) {
1209 upgrade_handle_exception($ex);
1210 }
1211}
1212
1213/**
1214 * Upgrade moodle core
1215 * @param float $version target version
1216 * @param bool $verbose
1217 * @return void, may throw exception
1218 */
1219function upgrade_core($version, $verbose) {
1220 global $CFG;
1221
3316fe24 1222 require_once($CFG->libdir.'/db/upgrade.php'); // Defines upgrades
3316fe24 1223
8580535b 1224 try {
dcf9be7f
MD
1225 // Reset caches before any output
1226 upgrade_reset_caches();
1227 remove_dir($CFG->dataroot . '/cache', true); // flush cache
1228
8580535b 1229 // Upgrade current language pack if we can
1230 if (empty($CFG->skiplangupgrade)) {
1231 upgrade_language_pack(false);
1232 }
1233
194cdca8 1234 print_upgrade_part_start('moodle', false, $verbose);
8580535b 1235
17da2e6f 1236 // one time special local migration pre 2.0 upgrade script
1237 if ($version < 2007101600) {
1238 $pre20upgradefile = "$CFG->dirrot/local/upgrade_pre20.php";
1239 if (file_exists($pre20upgradefile)) {
1240 set_time_limit(0);
1241 require($pre20upgradefile);
1242 // reset upgrade timeout to default
1243 upgrade_set_timeout();
1244 }
1245 }
1246
8580535b 1247 $result = xmldb_main_upgrade($CFG->version);
1248 if ($version > $CFG->version) {
1249 // store version if not already there
1250 upgrade_main_savepoint($result, $version, false);
1251 }
1252
1253 // perform all other component upgrade routines
1254 update_capabilities('moodle');
c976e271 1255 external_update_descriptions('moodle');
8580535b 1256 events_update_definition('moodle');
1257 message_update_providers('moodle');
8580535b 1258
dcf9be7f 1259 // Reset caches again, just to be sure
0139ec3f 1260 upgrade_reset_caches();
8580535b 1261 remove_dir($CFG->dataroot . '/cache', true); // flush cache
2e5eba85
PS
1262
1263 // Clean up contexts - more and more stuff depends on existence of paths and contexts
1264 cleanup_contexts();
1265 create_contexts();
1266 build_context_path();
df997f84
PS
1267 $syscontext = get_context_instance(CONTEXT_SYSTEM);
1268 mark_context_dirty($syscontext->path);
8580535b 1269
194cdca8 1270 print_upgrade_part_end('moodle', false, $verbose);
8580535b 1271 } catch (Exception $ex) {
1272 upgrade_handle_exception($ex);
1273 }
1274}
1275
1276/**
1277 * Upgrade/install other parts of moodle
1278 * @param bool $verbose
1279 * @return void, may throw exception
1280 */
1281function upgrade_noncore($verbose) {
1282 global $CFG;
1283
8580535b 1284 // upgrade all plugins types
1285 try {
1286 $plugintypes = get_plugin_types();
1287 foreach ($plugintypes as $type=>$location) {
17da2e6f 1288 upgrade_plugins($type, 'print_upgrade_part_start', 'print_upgrade_part_end', $verbose);
8580535b 1289 }
1290 } catch (Exception $ex) {
1291 upgrade_handle_exception($ex);
1292 }
8580535b 1293}
3316fe24 1294
1295/**
1296 * Checks if the main tables have been installed yet or not.
1297 * @return bool
1298 */
1299function core_tables_exist() {
1300 global $DB;
1301
1302 if (!$tables = $DB->get_tables() ) { // No tables yet at all.
1303 return false;
9b683d13 1304
3316fe24 1305 } else { // Check for missing main tables
1306 $mtables = array('config', 'course', 'groupings'); // some tables used in 1.9 and 2.0, preferable something from the start and end of install.xml
1307 foreach ($mtables as $mtable) {
1308 if (!in_array($mtable, $tables)) {
1309 return false;
1310 }
1311 }
1312 return true;
9b683d13 1313 }
ba04999c 1314}
c71ade2f 1315
0139ec3f
PS
1316/**
1317 * Invalidates browser caches and cached data in temp
1318 * @return void
1319 */
1320function upgrade_reset_caches() {
63bfc7d6 1321 reset_text_filters_cache();
0139ec3f
PS
1322 js_reset_all_caches();
1323 theme_reset_all_caches();
9b3af74c 1324 get_string_manager()->reset_caches();
0139ec3f
PS
1325}
1326
c71ade2f
PL
1327/**
1328 * upgrades the mnet rpc definitions for the given component.
1329 * this method doesn't return status, an exception will be thrown in the case of an error
1330 *
1331 * @param string $component the plugin to upgrade, eg auth_mnet
1332 */
1333function upgrade_plugin_mnet_functions($component) {
1334 global $DB, $CFG;
1335
1336 list($type, $plugin) = explode('_', $component);
1337 $path = get_plugin_directory($type, $plugin);
1338
1339 if (file_exists($path . '/db/mnet.php')) {
1340 require_once($path . '/db/mnet.php'); // $publishes comes from this file
1341 }
1342 if (empty($publishes)) {
1343 $publishes = array(); // still need this to be able to disable stuff later
1344 }
1345 if (empty($subscribes)) {
1346 $subscribes = array(); // still need this to be able to disable stuff later
1347 }
1348
1349 static $servicecache = array();
1350
1351 // rekey an array based on the rpc method for easy lookups later
1352 $publishmethodservices = array();
1353 $subscribemethodservices = array();
1354 foreach($publishes as $servicename => $service) {
1355 if (is_array($service['methods'])) {
1356 foreach($service['methods'] as $methodname) {
1357 $service['servicename'] = $servicename;
1358 $publishmethodservices[$methodname][] = $service;
1359 }
1360 }
1361 }
1362
1363 // Disable functions that don't exist (any more) in the source
1364 // Should these be deleted? What about their permissions records?
1365 foreach ($DB->get_records('mnet_rpc', array('pluginname'=>$plugin, 'plugintype'=>$type), 'functionname ASC ') as $rpc) {
1366 if (!array_key_exists($rpc->functionname, $publishmethodservices) && $rpc->enabled) {
1367 $DB->set_field('mnet_rpc', 'enabled', 0, array('id' => $rpc->id));
1368 } else if (array_key_exists($rpc->functionname, $publishmethodservices) && !$rpc->enabled) {
1369 $DB->set_field('mnet_rpc', 'enabled', 1, array('id' => $rpc->id));
1370 }
1371 }
1372
1373 // reflect all the services we're publishing and save them
1374 require_once($CFG->dirroot . '/lib/zend/Zend/Server/Reflection.php');
1375 static $cachedclasses = array(); // to store reflection information in
1376 foreach ($publishes as $service => $data) {
1377 $f = $data['filename'];
1378 $c = $data['classname'];
1379 foreach ($data['methods'] as $method) {
1380 $dataobject = new stdclass;
1381 $dataobject->plugintype = $type;
1382 $dataobject->pluginname = $plugin;
1383 $dataobject->enabled = 1;
1384 $dataobject->classname = $c;
1385 $dataobject->filename = $f;
1386
1387 if (is_string($method)) {
1388 $dataobject->functionname = $method;
1389
1390 } else if (is_array($method)) { // wants to override file or class
1391 $dataobject->functionname = $method['method'];
1392 $dataobject->classname = $method['classname'];
1393 $dataobject->filename = $method['filename'];
1394 }
1395 $dataobject->xmlrpcpath = $type.'/'.$plugin.'/'.$dataobject->filename.'/'.$method;
1396 $dataobject->static = false;
1397
1398 require_once($path . '/' . $dataobject->filename);
1399 $functionreflect = null; // slightly different ways to get this depending on whether it's a class method or a function
1400 if (!empty($dataobject->classname)) {
1401 if (!class_exists($dataobject->classname)) {
1402 throw new moodle_exception('installnosuchmethod', 'mnet', '', (object)array('method' => $dataobject->functionname, 'class' => $dataobject->classname));
1403 }
1404 $key = $dataobject->filename . '|' . $dataobject->classname;
1405 if (!array_key_exists($key, $cachedclasses)) { // look to see if we've already got a reflection object
1406 try {
1407 $cachedclasses[$key] = Zend_Server_Reflection::reflectClass($dataobject->classname);
1408 } catch (Zend_Server_Reflection_Exception $e) { // catch these and rethrow them to something more helpful
1409 throw new moodle_exception('installreflectionclasserror', 'mnet', '', (object)array('method' => $dataobject->functionname, 'class' => $dataobject->classname, 'error' => $e->getMessage()));
1410 }
1411 }
1412 $r =& $cachedclasses[$key];
1413 if (!$r->hasMethod($dataobject->functionname)) {
1414 throw new moodle_exception('installnosuchmethod', 'mnet', '', (object)array('method' => $dataobject->functionname, 'class' => $dataobject->classname));
1415 }
1416 // stupid workaround for zend not having a getMethod($name) function
1417 $ms = $r->getMethods();
1418 foreach ($ms as $m) {
1419 if ($m->getName() == $dataobject->functionname) {
1420 $functionreflect = $m;
1421 break;
1422 }
1423 }
1424 $dataobject->static = (int)$functionreflect->isStatic();
1425 } else {
1426 if (!function_exists($dataobject->functionname)) {
1427 throw new moodle_exception('installnosuchfunction', 'mnet', '', (object)array('method' => $dataobject->functionname, 'file' => $dataobject->filename));
1428 }
1429 try {
1430 $functionreflect = Zend_Server_Reflection::reflectFunction($dataobject->functionname);
1431 } catch (Zend_Server_Reflection_Exception $e) { // catch these and rethrow them to something more helpful
1432 throw new moodle_exception('installreflectionfunctionerror', 'mnet', '', (object)array('method' => $dataobject->functionname, '' => $dataobject->filename, 'error' => $e->getMessage()));
1433 }
1434 }
1435 $dataobject->profile = serialize(admin_mnet_method_profile($functionreflect));
1436 $dataobject->help = $functionreflect->getDescription();
1437
1438 if ($record_exists = $DB->get_record('mnet_rpc', array('xmlrpcpath'=>$dataobject->xmlrpcpath))) {
1439 $dataobject->id = $record_exists->id;
1440 $dataobject->enabled = $record_exists->enabled;
1441 $DB->update_record('mnet_rpc', $dataobject);
1442 } else {
1443 $dataobject->id = $DB->insert_record('mnet_rpc', $dataobject, true);
1444 }
c71ade2f 1445
677b6321
PL
1446 foreach ($publishmethodservices[$dataobject->functionname] as $service) {
1447 if ($serviceobj = $DB->get_record('mnet_service', array('name'=>$service['servicename']))) {
1448 $serviceobj->apiversion = $service['apiversion'];
1449 $DB->update_record('mnet_service', $serviceobj);
1450 } else {
1451 $serviceobj = new stdClass();
1452 $serviceobj->name = $service['servicename'];
1453 $serviceobj->apiversion = $service['apiversion'];
1454 $serviceobj->offer = 1;
1455 $serviceobj->id = $DB->insert_record('mnet_service', $serviceobj);
1456 }
1457 $servicecache[$service['servicename']] = $serviceobj;
1458 if (!$DB->record_exists('mnet_service2rpc', array('rpcid'=>$dataobject->id, 'serviceid'=>$serviceobj->id))) {
1459 $obj = new stdClass();
1460 $obj->rpcid = $dataobject->id;
1461 $obj->serviceid = $serviceobj->id;
1462 $DB->insert_record('mnet_service2rpc', $obj, true);
1463 }
c71ade2f
PL
1464 }
1465 }
1466 }
c71ade2f
PL
1467 // finished with methods we publish, now do subscribable methods
1468 foreach($subscribes as $service => $methods) {
1469 if (!array_key_exists($service, $servicecache)) {
1470 if (!$serviceobj = $DB->get_record('mnet_service', array('name' => $service))) {
81634f03 1471 debugging("TODO: skipping unknown service $service - somebody needs to fix MDL-21993");
c71ade2f
PL
1472 continue;
1473 }
1474 $servicecache[$service] = $serviceobj;
1475 } else {
1476 $serviceobj = $servicecache[$service];
1477 }
1478 foreach ($methods as $method => $xmlrpcpath) {
1479 if (!$rpcid = $DB->get_field('mnet_remote_rpc', 'id', array('xmlrpcpath'=>$xmlrpcpath))) {
1480 $remoterpc = (object)array(
1481 'functionname' => $method,
1482 'xmlrpcpath' => $xmlrpcpath,
1483 'plugintype' => $type,
1484 'pluginname' => $plugin,
1485 'enabled' => 1,
1486 );
1487 $rpcid = $remoterpc->id = $DB->insert_record('mnet_remote_rpc', $remoterpc, true);
1488 }
1489 if (!$DB->record_exists('mnet_remote_service2rpc', array('rpcid'=>$rpcid, 'serviceid'=>$serviceobj->id))) {
1490 $obj = new stdClass();
1491 $obj->rpcid = $rpcid;
1492 $obj->serviceid = $serviceobj->id;
1493 $DB->insert_record('mnet_remote_service2rpc', $obj, true);
1494 }
677b6321 1495 $subscribemethodservices[$method][] = $service;
c71ade2f
PL
1496 }
1497 }
1498
1499 foreach ($DB->get_records('mnet_remote_rpc', array('pluginname'=>$plugin, 'plugintype'=>$type), 'functionname ASC ') as $rpc) {
1500 if (!array_key_exists($rpc->functionname, $subscribemethodservices) && $rpc->enabled) {
1501 $DB->set_field('mnet_remote_rpc', 'enabled', 0, array('id' => $rpc->id));
1502 } else if (array_key_exists($rpc->functionname, $subscribemethodservices) && !$rpc->enabled) {
1503 $DB->set_field('mnet_remote_rpc', 'enabled', 1, array('id' => $rpc->id));
1504 }
1505 }
1506
1507 return true;
1508}
1509
1510/**
1511 * Given some sort of Zend Reflection function/method object, return a profile array, ready to be serialized and stored
1512 *
1513 * @param Zend_Server_Reflection_Function_Abstract $function can be any subclass of this object type
1514 *
1515 * @return array
1516 */
1517function admin_mnet_method_profile(Zend_Server_Reflection_Function_Abstract $function) {
1518 $proto = array_pop($function->getPrototypes());
1519 $ret = $proto->getReturnValue();
1520 $profile = array(
1521 'parameters' => array(),
1522 'return' => array(
1523 'type' => $ret->getType(),
1524 'description' => $ret->getDescription(),
1525 ),
1526 );
1527 foreach ($proto->getParameters() as $p) {
1528 $profile['parameters'][] = array(
1529 'name' => $p->getName(),
1530 'type' => $p->getType(),
1531 'description' => $p->getDescription(),
1532 );
1533 }
1534 return $profile;
1535}