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