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