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