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