weekly release 3.1dev
[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
bdbcb6d7 100/**
b3d5bd33
101 * Misplaced plugin exception.
102 *
103 * Note: this should be used only from the upgrade/admin code.
104 *
bdbcb6d7
PS
105 * @package core
106 * @subpackage upgrade
107 * @copyright 2009 Petr Skoda {@link http://skodak.org}
108 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
109 */
110class plugin_misplaced_exception extends moodle_exception {
b3d5bd33
111 /**
112 * Constructor.
113 * @param string $component the component from version.php
114 * @param string $expected expected directory, null means calculate
115 * @param string $current plugin directory path
116 */
117 public function __construct($component, $expected, $current) {
bdbcb6d7 118 global $CFG;
b3d5bd33
119 if (empty($expected)) {
120 list($type, $plugin) = core_component::normalize_component($component);
121 $plugintypes = core_component::get_plugin_types();
122 if (isset($plugintypes[$type])) {
123 $expected = $plugintypes[$type] . '/' . $plugin;
124 }
125 }
126 if (strpos($expected, '$CFG->dirroot') !== 0) {
127 $expected = str_replace($CFG->dirroot, '$CFG->dirroot', $expected);
128 }
129 if (strpos($current, '$CFG->dirroot') !== 0) {
130 $current = str_replace($CFG->dirroot, '$CFG->dirroot', $current);
131 }
bdbcb6d7
PS
132 $a = new stdClass();
133 $a->component = $component;
134 $a->expected = $expected;
135 $a->current = $current;
136 parent::__construct('detectedmisplacedplugin', 'core_plugin', "$CFG->wwwroot/$CFG->admin/index.php", $a);
137 }
138}
139
0c5406ca
PS
140/**
141 * Sets maximum expected time needed for upgrade task.
142 * Please always make sure that upgrade will not run longer!
143 *
144 * The script may be automatically aborted if upgrade times out.
145 *
146 * @category upgrade
147 * @param int $max_execution_time in seconds (can not be less than 60 s)
148 */
149function upgrade_set_timeout($max_execution_time=300) {
150 global $CFG;
151
152 if (!isset($CFG->upgraderunning) or $CFG->upgraderunning < time()) {
153 $upgraderunning = get_config(null, 'upgraderunning');
154 } else {
155 $upgraderunning = $CFG->upgraderunning;
156 }
157
158 if (!$upgraderunning) {
b814d1b4
PS
159 if (CLI_SCRIPT) {
160 // never stop CLI upgrades
161 $upgraderunning = 0;
162 } else {
163 // web upgrade not running or aborted
164 print_error('upgradetimedout', 'admin', "$CFG->wwwroot/$CFG->admin/");
165 }
0c5406ca
PS
166 }
167
168 if ($max_execution_time < 60) {
169 // protection against 0 here
170 $max_execution_time = 60;
171 }
172
173 $expected_end = time() + $max_execution_time;
174
175 if ($expected_end < $upgraderunning + 10 and $expected_end > $upgraderunning - 10) {
176 // no need to store new end, it is nearly the same ;-)
177 return;
178 }
179
5563f5fb
PS
180 if (CLI_SCRIPT) {
181 // there is no point in timing out of CLI scripts, admins can stop them if necessary
3ef7279f 182 core_php_time_limit::raise();
5563f5fb 183 } else {
3ef7279f 184 core_php_time_limit::raise($max_execution_time);
5563f5fb 185 }
0c5406ca
PS
186 set_config('upgraderunning', $expected_end); // keep upgrade locked until this time
187}
188
db9d4a3d 189/**
190 * Upgrade savepoint, marks end of each upgrade block.
191 * It stores new main version, resets upgrade timeout
192 * and abort upgrade if user cancels page loading.
193 *
194 * Please do not make large upgrade blocks with lots of operations,
195 * for example when adding tables keep only one table operation per block.
196 *
39b90b51 197 * @category upgrade
db9d4a3d 198 * @param bool $result false if upgrade step failed, true if completed
199 * @param string or float $version main version
200 * @param bool $allowabort allow user to abort script execution here
201 * @return void
202 */
203function upgrade_main_savepoint($result, $version, $allowabort=true) {
204 global $CFG;
205
bb44ef99
RT
206 //sanity check to avoid confusion with upgrade_mod_savepoint usage.
207 if (!is_bool($allowabort)) {
208 $errormessage = 'Parameter type mismatch. Are you mixing up upgrade_main_savepoint() and upgrade_mod_savepoint()?';
209 throw new coding_exception($errormessage);
210 }
211
795a08ad 212 if (!$result) {
520cea92 213 throw new upgrade_exception(null, $version);
795a08ad 214 }
215
216 if ($CFG->version >= $version) {
217 // something really wrong is going on in main upgrade script
218 throw new downgrade_exception(null, $CFG->version, $version);
db9d4a3d 219 }
220
795a08ad 221 set_config('version', $version);
222 upgrade_log(UPGRADE_LOG_NORMAL, null, 'Upgrade savepoint reached');
223
db9d4a3d 224 // reset upgrade timeout to default
225 upgrade_set_timeout();
226
227 // this is a safe place to stop upgrades if user aborts page loading
228 if ($allowabort and connection_aborted()) {
229 die;
230 }
231}
232
233/**
234 * Module upgrade savepoint, marks end of module upgrade blocks
235 * It stores module version, resets upgrade timeout
236 * and abort upgrade if user cancels page loading.
237 *
39b90b51 238 * @category upgrade
db9d4a3d 239 * @param bool $result false if upgrade step failed, true if completed
240 * @param string or float $version main version
241 * @param string $modname name of module
242 * @param bool $allowabort allow user to abort script execution here
243 * @return void
244 */
245function upgrade_mod_savepoint($result, $version, $modname, $allowabort=true) {
246 global $DB;
247
bde002b8
PS
248 $component = 'mod_'.$modname;
249
795a08ad 250 if (!$result) {
bde002b8 251 throw new upgrade_exception($component, $version);
795a08ad 252 }
253
bde002b8
PS
254 $dbversion = $DB->get_field('config_plugins', 'value', array('plugin'=>$component, 'name'=>'version'));
255
db9d4a3d 256 if (!$module = $DB->get_record('modules', array('name'=>$modname))) {
257 print_error('modulenotexist', 'debug', '', $modname);
258 }
259
bde002b8 260 if ($dbversion >= $version) {
795a08ad 261 // something really wrong is going on in upgrade script
bde002b8 262 throw new downgrade_exception($component, $dbversion, $version);
db9d4a3d 263 }
bde002b8
PS
264 set_config('version', $version, $component);
265
266 upgrade_log(UPGRADE_LOG_NORMAL, $component, 'Upgrade savepoint reached');
db9d4a3d 267
268 // reset upgrade timeout to default
269 upgrade_set_timeout();
270
271 // this is a safe place to stop upgrades if user aborts page loading
272 if ($allowabort and connection_aborted()) {
273 die;
274 }
275}
276
277/**
278 * Blocks upgrade savepoint, marks end of blocks upgrade blocks
279 * It stores block version, resets upgrade timeout
280 * and abort upgrade if user cancels page loading.
281 *
39b90b51 282 * @category upgrade
db9d4a3d 283 * @param bool $result false if upgrade step failed, true if completed
284 * @param string or float $version main version
285 * @param string $blockname name of block
286 * @param bool $allowabort allow user to abort script execution here
287 * @return void
288 */
795a08ad 289function upgrade_block_savepoint($result, $version, $blockname, $allowabort=true) {
db9d4a3d 290 global $DB;
291
bde002b8
PS
292 $component = 'block_'.$blockname;
293
795a08ad 294 if (!$result) {
bde002b8 295 throw new upgrade_exception($component, $version);
795a08ad 296 }
297
bde002b8
PS
298 $dbversion = $DB->get_field('config_plugins', 'value', array('plugin'=>$component, 'name'=>'version'));
299
db9d4a3d 300 if (!$block = $DB->get_record('block', array('name'=>$blockname))) {
301 print_error('blocknotexist', 'debug', '', $blockname);
302 }
303
bde002b8 304 if ($dbversion >= $version) {
795a08ad 305 // something really wrong is going on in upgrade script
bde002b8 306 throw new downgrade_exception($component, $dbversion, $version);
db9d4a3d 307 }
bde002b8
PS
308 set_config('version', $version, $component);
309
310 upgrade_log(UPGRADE_LOG_NORMAL, $component, 'Upgrade savepoint reached');
db9d4a3d 311
312 // reset upgrade timeout to default
313 upgrade_set_timeout();
314
315 // this is a safe place to stop upgrades if user aborts page loading
316 if ($allowabort and connection_aborted()) {
317 die;
318 }
319}
320
321/**
322 * Plugins upgrade savepoint, marks end of blocks upgrade blocks
323 * It stores plugin version, resets upgrade timeout
324 * and abort upgrade if user cancels page loading.
325 *
39b90b51 326 * @category upgrade
db9d4a3d 327 * @param bool $result false if upgrade step failed, true if completed
328 * @param string or float $version main version
329 * @param string $type name of plugin
330 * @param string $dir location of plugin
331 * @param bool $allowabort allow user to abort script execution here
332 * @return void
333 */
17da2e6f 334function upgrade_plugin_savepoint($result, $version, $type, $plugin, $allowabort=true) {
bde002b8
PS
335 global $DB;
336
17da2e6f 337 $component = $type.'_'.$plugin;
338
795a08ad 339 if (!$result) {
17da2e6f 340 throw new upgrade_exception($component, $version);
db9d4a3d 341 }
342
bde002b8
PS
343 $dbversion = $DB->get_field('config_plugins', 'value', array('plugin'=>$component, 'name'=>'version'));
344
345 if ($dbversion >= $version) {
795a08ad 346 // Something really wrong is going on in the upgrade script
bde002b8 347 throw new downgrade_exception($component, $dbversion, $version);
795a08ad 348 }
17da2e6f 349 set_config('version', $version, $component);
795a08ad 350 upgrade_log(UPGRADE_LOG_NORMAL, $component, 'Upgrade savepoint reached');
351
db9d4a3d 352 // Reset upgrade timeout to default
353 upgrade_set_timeout();
354
355 // This is a safe place to stop upgrades if user aborts page loading
356 if ($allowabort and connection_aborted()) {
357 die;
358 }
359}
360
9008ec16
PS
361/**
362 * Detect if there are leftovers in PHP source files.
363 *
364 * During main version upgrades administrators MUST move away
365 * old PHP source files and start from scratch (or better
366 * use git).
367 *
368 * @return bool true means borked upgrade, false means previous PHP files were properly removed
369 */
370function upgrade_stale_php_files_present() {
371 global $CFG;
372
373 $someexamplesofremovedfiles = array(
5222ab7f
SC
374 // Removed in 3.0.
375 '/mod/lti/grade.php',
0d1e5456 376 '/tag/coursetagslib.php',
aac67170
AG
377 // Removed in 2.9.
378 '/lib/timezone.txt',
379 // Removed in 2.8.
380 '/course/delete_category_form.php',
4e8a07d2
TH
381 // Removed in 2.7.
382 '/admin/tool/qeupgradehelper/version.php',
383 // Removed in 2.6.
bde002b8 384 '/admin/block.php',
72e3a3c9 385 '/admin/oacleanup.php',
4e8a07d2 386 // Removed in 2.5.
c1782ec6
EL
387 '/backup/lib.php',
388 '/backup/bb/README.txt',
301ebbe5 389 '/lib/excel/test.php',
4e8a07d2 390 // Removed in 2.4.
c8b3346c 391 '/admin/tool/unittest/simpletestlib.php',
4e8a07d2 392 // Removed in 2.3.
37d72977 393 '/lib/minify/builder/',
4e8a07d2 394 // Removed in 2.2.
9008ec16 395 '/lib/yui/3.4.1pr1/',
4e8a07d2 396 // Removed in 2.2.
9008ec16
PS
397 '/search/cron_php5.php',
398 '/course/report/log/indexlive.php',
399 '/admin/report/backups/index.php',
400 '/admin/generator.php',
4e8a07d2 401 // Removed in 2.1.
9008ec16 402 '/lib/yui/2.8.0r4/',
4e8a07d2 403 // Removed in 2.0.
9008ec16
PS
404 '/blocks/admin/block_admin.php',
405 '/blocks/admin_tree/block_admin_tree.php',
406 );
407
408 foreach ($someexamplesofremovedfiles as $file) {
409 if (file_exists($CFG->dirroot.$file)) {
410 return true;
411 }
412 }
413
414 return false;
415}
db9d4a3d 416
417/**
418 * Upgrade plugins
db9d4a3d 419 * @param string $type The type of plugins that should be updated (e.g. 'enrol', 'qtype')
17da2e6f 420 * return void
db9d4a3d 421 */
17da2e6f 422function upgrade_plugins($type, $startcallback, $endcallback, $verbose) {
db9d4a3d 423 global $CFG, $DB;
424
425/// special cases
426 if ($type === 'mod') {
194cdca8 427 return upgrade_plugins_modules($startcallback, $endcallback, $verbose);
795a08ad 428 } else if ($type === 'block') {
194cdca8 429 return upgrade_plugins_blocks($startcallback, $endcallback, $verbose);
db9d4a3d 430 }
431
bd3b3bba 432 $plugs = core_component::get_plugin_list($type);
db9d4a3d 433
17da2e6f 434 foreach ($plugs as $plug=>$fullplug) {
ebb98bf5 435 // Reset time so that it works when installing a large number of plugins
3ef7279f 436 core_php_time_limit::raise(600);
aff24313 437 $component = clean_param($type.'_'.$plug, PARAM_COMPONENT); // standardised plugin name
db9d4a3d 438
3e858ea7 439 // check plugin dir is valid name
aff24313
PS
440 if (empty($component)) {
441 throw new plugin_defective_exception($type.'_'.$plug, 'Invalid plugin directory name.');
3e858ea7
PS
442 }
443
795a08ad 444 if (!is_readable($fullplug.'/version.php')) {
445 continue;
db9d4a3d 446 }
447
365a5941 448 $plugin = new stdClass();
bde002b8
PS
449 $plugin->version = null;
450 $module = $plugin; // Prevent some notices when plugin placed in wrong directory.
795a08ad 451 require($fullplug.'/version.php'); // defines $plugin with version etc
bde002b8 452 unset($module);
bdbcb6d7 453
98ea6973
DM
454 if (empty($plugin->version)) {
455 throw new plugin_defective_exception($component, 'Missing $plugin->version number in version.php.');
3e858ea7
PS
456 }
457
98ea6973
DM
458 if (empty($plugin->component)) {
459 throw new plugin_defective_exception($component, 'Missing $plugin->component declaration in version.php.');
460 }
461
462 if ($plugin->component !== $component) {
463 throw new plugin_misplaced_exception($plugin->component, null, $fullplug);
db9d4a3d 464 }
465
17da2e6f 466 $plugin->name = $plug;
467 $plugin->fullname = $component;
795a08ad 468
db9d4a3d 469 if (!empty($plugin->requires)) {
470 if ($plugin->requires > $CFG->version) {
795a08ad 471 throw new upgrade_requires_exception($component, $plugin->version, $CFG->version, $plugin->requires);
ef14c1e7
PS
472 } else if ($plugin->requires < 2010000000) {
473 throw new plugin_defective_exception($component, 'Plugin is not compatible with Moodle 2.x or later.');
db9d4a3d 474 }
475 }
476
9b683d13 477 // try to recover from interrupted install.php if needed
478 if (file_exists($fullplug.'/db/install.php')) {
479 if (get_config($plugin->fullname, 'installrunning')) {
480 require_once($fullplug.'/db/install.php');
481 $recover_install_function = 'xmldb_'.$plugin->fullname.'_install_recovery';
482 if (function_exists($recover_install_function)) {
483 $startcallback($component, true, $verbose);
484 $recover_install_function();
f6f06d69 485 unset_config('installrunning', $plugin->fullname);
9b683d13 486 update_capabilities($component);
c6d75bff 487 log_update_descriptions($component);
c976e271 488 external_update_descriptions($component);
9b683d13 489 events_update_definition($component);
309ae892 490 \core\task\manager::reset_scheduled_tasks_for_component($component);
9b683d13 491 message_update_providers($component);
6c0bfb14 492 \core\message\inbound\manager::update_handlers_for_component($component);
afed8d0f
RK
493 if ($type === 'message') {
494 message_update_processors($plug);
495 }
de260e0f 496 upgrade_plugin_mnet_functions($component);
c026a28d 497 core_tag_area::reset_definitions_for_component($component);
9b683d13 498 $endcallback($component, true, $verbose);
499 }
500 }
501 }
db9d4a3d 502
bde002b8 503 $installedversion = $DB->get_field('config_plugins', 'value', array('name'=>'version', 'plugin'=>$component)); // No caching!
795a08ad 504 if (empty($installedversion)) { // new installation
194cdca8 505 $startcallback($component, true, $verbose);
db9d4a3d 506
795a08ad 507 /// Install tables if defined
508 if (file_exists($fullplug.'/db/install.xml')) {
509 $DB->get_manager()->install_from_xmldb_file($fullplug.'/db/install.xml');
db9d4a3d 510 }
9b683d13 511
512 /// store version
513 upgrade_plugin_savepoint(true, $plugin->version, $type, $plug, false);
514
795a08ad 515 /// execute post install file
516 if (file_exists($fullplug.'/db/install.php')) {
517 require_once($fullplug.'/db/install.php');
f6f06d69
PS
518 set_config('installrunning', 1, $plugin->fullname);
519 $post_install_function = 'xmldb_'.$plugin->fullname.'_install';
795a08ad 520 $post_install_function();
f6f06d69 521 unset_config('installrunning', $plugin->fullname);
795a08ad 522 }
523
795a08ad 524 /// Install various components
525 update_capabilities($component);
c6d75bff 526 log_update_descriptions($component);
c976e271 527 external_update_descriptions($component);
795a08ad 528 events_update_definition($component);
309ae892 529 \core\task\manager::reset_scheduled_tasks_for_component($component);
795a08ad 530 message_update_providers($component);
6c0bfb14 531 \core\message\inbound\manager::update_handlers_for_component($component);
afed8d0f
RK
532 if ($type === 'message') {
533 message_update_processors($plug);
534 }
de260e0f 535 upgrade_plugin_mnet_functions($component);
c026a28d 536 core_tag_area::reset_definitions_for_component($component);
194cdca8 537 $endcallback($component, true, $verbose);
795a08ad 538
539 } else if ($installedversion < $plugin->version) { // upgrade
540 /// Run the upgrade function for the plugin.
194cdca8 541 $startcallback($component, false, $verbose);
795a08ad 542
543 if (is_readable($fullplug.'/db/upgrade.php')) {
544 require_once($fullplug.'/db/upgrade.php'); // defines upgrading function
545
546 $newupgrade_function = 'xmldb_'.$plugin->fullname.'_upgrade';
547 $result = $newupgrade_function($installedversion);
548 } else {
549 $result = true;
550 }
551
bde002b8 552 $installedversion = $DB->get_field('config_plugins', 'value', array('name'=>'version', 'plugin'=>$component)); // No caching!
795a08ad 553 if ($installedversion < $plugin->version) {
554 // store version if not already there
555 upgrade_plugin_savepoint($result, $plugin->version, $type, $plug, false);
556 }
557
558 /// Upgrade various components
559 update_capabilities($component);
c6d75bff 560 log_update_descriptions($component);
c976e271 561 external_update_descriptions($component);
795a08ad 562 events_update_definition($component);
309ae892 563 \core\task\manager::reset_scheduled_tasks_for_component($component);
795a08ad 564 message_update_providers($component);
6c0bfb14 565 \core\message\inbound\manager::update_handlers_for_component($component);
afed8d0f 566 if ($type === 'message') {
bde002b8 567 // Ugly hack!
afed8d0f
RK
568 message_update_processors($plug);
569 }
de260e0f 570 upgrade_plugin_mnet_functions($component);
c026a28d 571 core_tag_area::reset_definitions_for_component($component);
194cdca8 572 $endcallback($component, false, $verbose);
795a08ad 573
574 } else if ($installedversion > $plugin->version) {
575 throw new downgrade_exception($component, $installedversion, $plugin->version);
db9d4a3d 576 }
577 }
db9d4a3d 578}
579
580/**
581 * Find and check all modules and load them up or upgrade them if necessary
72fb21b6 582 *
583 * @global object
584 * @global object
db9d4a3d 585 */
194cdca8 586function upgrade_plugins_modules($startcallback, $endcallback, $verbose) {
db9d4a3d 587 global $CFG, $DB;
588
bd3b3bba 589 $mods = core_component::get_plugin_list('mod');
db9d4a3d 590
17da2e6f 591 foreach ($mods as $mod=>$fullmod) {
db9d4a3d 592
3e858ea7 593 if ($mod === 'NEWMODULE') { // Someone has unzipped the template, ignore it
db9d4a3d 594 continue;
595 }
596
aff24313 597 $component = clean_param('mod_'.$mod, PARAM_COMPONENT);
db9d4a3d 598
3e858ea7 599 // check module dir is valid name
aff24313
PS
600 if (empty($component)) {
601 throw new plugin_defective_exception('mod_'.$mod, 'Invalid plugin directory name.');
3e858ea7
PS
602 }
603
795a08ad 604 if (!is_readable($fullmod.'/version.php')) {
605 throw new plugin_defective_exception($component, 'Missing version.php');
db9d4a3d 606 }
607
01889f01 608 $module = new stdClass();
bde002b8
PS
609 $plugin = new stdClass();
610 $plugin->version = null;
994e5662 611 require($fullmod .'/version.php'); // Defines $plugin with version etc.
01889f01
DM
612
613 // Check if the legacy $module syntax is still used.
17d2a336 614 if (!is_object($module) or (count((array)$module) > 0)) {
01889f01
DM
615 throw new plugin_defective_exception($component, 'Unsupported $module syntax detected in version.php');
616 }
617
618 // Prepare the record for the {modules} table.
619 $module = clone($plugin);
bde002b8
PS
620 unset($module->version);
621 unset($module->component);
622 unset($module->dependencies);
623 unset($module->release);
bdbcb6d7 624
98ea6973
DM
625 if (empty($plugin->version)) {
626 throw new plugin_defective_exception($component, 'Missing $plugin->version number in version.php.');
3e858ea7
PS
627 }
628
98ea6973
DM
629 if (empty($plugin->component)) {
630 throw new plugin_defective_exception($component, 'Missing $plugin->component declaration in version.php.');
631 }
632
633 if ($plugin->component !== $component) {
634 throw new plugin_misplaced_exception($plugin->component, null, $fullmod);
db9d4a3d 635 }
636
bde002b8
PS
637 if (!empty($plugin->requires)) {
638 if ($plugin->requires > $CFG->version) {
639 throw new upgrade_requires_exception($component, $plugin->version, $CFG->version, $plugin->requires);
640 } else if ($plugin->requires < 2010000000) {
ef14c1e7 641 throw new plugin_defective_exception($component, 'Plugin is not compatible with Moodle 2.x or later.');
db9d4a3d 642 }
643 }
644
ff05bb31
TH
645 if (empty($module->cron)) {
646 $module->cron = 0;
647 }
648
3e858ea7
PS
649 // all modules must have en lang pack
650 if (!is_readable("$fullmod/lang/en/$mod.php")) {
651 throw new plugin_defective_exception($component, 'Missing mandatory en language pack.');
652 }
653
db9d4a3d 654 $module->name = $mod; // The name MUST match the directory
655
bde002b8 656 $installedversion = $DB->get_field('config_plugins', 'value', array('name'=>'version', 'plugin'=>$component)); // No caching!
db9d4a3d 657
9b683d13 658 if (file_exists($fullmod.'/db/install.php')) {
659 if (get_config($module->name, 'installrunning')) {
660 require_once($fullmod.'/db/install.php');
661 $recover_install_function = 'xmldb_'.$module->name.'_install_recovery';
662 if (function_exists($recover_install_function)) {
663 $startcallback($component, true, $verbose);
664 $recover_install_function();
665 unset_config('installrunning', $module->name);
666 // Install various components too
667 update_capabilities($component);
c6d75bff 668 log_update_descriptions($component);
c976e271 669 external_update_descriptions($component);
9b683d13 670 events_update_definition($component);
309ae892 671 \core\task\manager::reset_scheduled_tasks_for_component($component);
9b683d13 672 message_update_providers($component);
6c0bfb14 673 \core\message\inbound\manager::update_handlers_for_component($component);
de260e0f 674 upgrade_plugin_mnet_functions($component);
c026a28d 675 core_tag_area::reset_definitions_for_component($component);
9b683d13 676 $endcallback($component, true, $verbose);
677 }
678 }
679 }
680
bde002b8 681 if (empty($installedversion)) {
194cdca8 682 $startcallback($component, true, $verbose);
db9d4a3d 683
795a08ad 684 /// Execute install.xml (XMLDB) - must be present in all modules
685 $DB->get_manager()->install_from_xmldb_file($fullmod.'/db/install.xml');
db9d4a3d 686
2e3da297 687 /// Add record into modules table - may be needed in install.php already
688 $module->id = $DB->insert_record('modules', $module);
bde002b8 689 upgrade_mod_savepoint(true, $plugin->version, $module->name, false);
2e3da297 690
db9d4a3d 691 /// Post installation hook - optional
692 if (file_exists("$fullmod/db/install.php")) {
693 require_once("$fullmod/db/install.php");
9b683d13 694 // Set installation running flag, we need to recover after exception or error
695 set_config('installrunning', 1, $module->name);
3412cb43 696 $post_install_function = 'xmldb_'.$module->name.'_install';
db9d4a3d 697 $post_install_function();
9b683d13 698 unset_config('installrunning', $module->name);
db9d4a3d 699 }
700
795a08ad 701 /// Install various components
702 update_capabilities($component);
c6d75bff 703 log_update_descriptions($component);
c976e271 704 external_update_descriptions($component);
795a08ad 705 events_update_definition($component);
309ae892 706 \core\task\manager::reset_scheduled_tasks_for_component($component);
795a08ad 707 message_update_providers($component);
6c0bfb14 708 \core\message\inbound\manager::update_handlers_for_component($component);
de260e0f 709 upgrade_plugin_mnet_functions($component);
c026a28d 710 core_tag_area::reset_definitions_for_component($component);
795a08ad 711
194cdca8 712 $endcallback($component, true, $verbose);
db9d4a3d 713
bde002b8 714 } else if ($installedversion < $plugin->version) {
795a08ad 715 /// If versions say that we need to upgrade but no upgrade files are available, notify and continue
194cdca8 716 $startcallback($component, false, $verbose);
795a08ad 717
718 if (is_readable($fullmod.'/db/upgrade.php')) {
719 require_once($fullmod.'/db/upgrade.php'); // defines new upgrading function
720 $newupgrade_function = 'xmldb_'.$module->name.'_upgrade';
bde002b8 721 $result = $newupgrade_function($installedversion, $module);
795a08ad 722 } else {
723 $result = true;
724 }
725
bde002b8 726 $installedversion = $DB->get_field('config_plugins', 'value', array('name'=>'version', 'plugin'=>$component)); // No caching!
795a08ad 727 $currmodule = $DB->get_record('modules', array('name'=>$module->name));
bde002b8 728 if ($installedversion < $plugin->version) {
795a08ad 729 // store version if not already there
bde002b8 730 upgrade_mod_savepoint($result, $plugin->version, $mod, false);
795a08ad 731 }
732
3412cb43
TH
733 // update cron flag if needed
734 if ($currmodule->cron != $module->cron) {
735 $DB->set_field('modules', 'cron', $module->cron, array('name' => $module->name));
736 }
737
738 // Upgrade various components
795a08ad 739 update_capabilities($component);
c6d75bff 740 log_update_descriptions($component);
c976e271 741 external_update_descriptions($component);
795a08ad 742 events_update_definition($component);
309ae892 743 \core\task\manager::reset_scheduled_tasks_for_component($component);
795a08ad 744 message_update_providers($component);
6c0bfb14 745 \core\message\inbound\manager::update_handlers_for_component($component);
de260e0f 746 upgrade_plugin_mnet_functions($component);
c026a28d 747 core_tag_area::reset_definitions_for_component($component);
795a08ad 748
194cdca8 749 $endcallback($component, false, $verbose);
795a08ad 750
bde002b8
PS
751 } else if ($installedversion > $plugin->version) {
752 throw new downgrade_exception($component, $installedversion, $plugin->version);
795a08ad 753 }
754 }
755}
db9d4a3d 756
db9d4a3d 757
795a08ad 758/**
759 * This function finds all available blocks and install them
760 * into blocks table or do all the upgrade process if newer.
72fb21b6 761 *
762 * @global object
763 * @global object
795a08ad 764 */
194cdca8 765function upgrade_plugins_blocks($startcallback, $endcallback, $verbose) {
795a08ad 766 global $CFG, $DB;
767
795a08ad 768 require_once($CFG->dirroot.'/blocks/moodleblock.class.php');
769
770 $blocktitles = array(); // we do not want duplicate titles
771
772 //Is this a first install
773 $first_install = null;
774
bd3b3bba 775 $blocks = core_component::get_plugin_list('block');
795a08ad 776
17da2e6f 777 foreach ($blocks as $blockname=>$fullblock) {
795a08ad 778
779 if (is_null($first_install)) {
f46eba7e 780 $first_install = ($DB->count_records('block_instances') == 0);
795a08ad 781 }
782
aff24313 783 if ($blockname === 'NEWBLOCK') { // Someone has unzipped the template, ignore it
795a08ad 784 continue;
db9d4a3d 785 }
786
aff24313 787 $component = clean_param('block_'.$blockname, PARAM_COMPONENT);
db9d4a3d 788
3e858ea7 789 // check block dir is valid name
aff24313
PS
790 if (empty($component)) {
791 throw new plugin_defective_exception('block_'.$blockname, 'Invalid plugin directory name.');
3e858ea7
PS
792 }
793
8571833f
PS
794 if (!is_readable($fullblock.'/version.php')) {
795 throw new plugin_defective_exception('block/'.$blockname, 'Missing version.php file.');
796 }
365a5941 797 $plugin = new stdClass();
bde002b8 798 $plugin->version = null;
8571833f 799 $plugin->cron = 0;
bde002b8 800 $module = $plugin; // Prevent some notices when module placed in wrong directory.
8571833f 801 include($fullblock.'/version.php');
bde002b8
PS
802 unset($module);
803 $block = clone($plugin);
804 unset($block->version);
805 unset($block->component);
806 unset($block->dependencies);
807 unset($block->release);
8571833f 808
98ea6973
DM
809 if (empty($plugin->version)) {
810 throw new plugin_defective_exception($component, 'Missing block version number in version.php.');
3e858ea7
PS
811 }
812
98ea6973
DM
813 if (empty($plugin->component)) {
814 throw new plugin_defective_exception($component, 'Missing $plugin->component declaration in version.php.');
815 }
816
817 if ($plugin->component !== $component) {
818 throw new plugin_misplaced_exception($plugin->component, null, $fullblock);
bde002b8
PS
819 }
820
ef14c1e7
PS
821 if (!empty($plugin->requires)) {
822 if ($plugin->requires > $CFG->version) {
823 throw new upgrade_requires_exception($component, $plugin->version, $CFG->version, $plugin->requires);
824 } else if ($plugin->requires < 2010000000) {
825 throw new plugin_defective_exception($component, 'Plugin is not compatible with Moodle 2.x or later.');
826 }
827 }
828
795a08ad 829 if (!is_readable($fullblock.'/block_'.$blockname.'.php')) {
830 throw new plugin_defective_exception('block/'.$blockname, 'Missing main block class file.');
db9d4a3d 831 }
8571833f 832 include_once($fullblock.'/block_'.$blockname.'.php');
db9d4a3d 833
795a08ad 834 $classname = 'block_'.$blockname;
835
836 if (!class_exists($classname)) {
837 throw new plugin_defective_exception($component, 'Can not load main class.');
838 }
839
b921b6ee 840 $blockobj = new $classname; // This is what we'll be testing
795a08ad 841 $blocktitle = $blockobj->get_title();
842
843 // OK, it's as we all hoped. For further tests, the object will do them itself.
844 if (!$blockobj->_self_test()) {
845 throw new plugin_defective_exception($component, 'Self test failed.');
846 }
847
795a08ad 848 $block->name = $blockname; // The name MUST match the directory
795a08ad 849
bde002b8 850 $installedversion = $DB->get_field('config_plugins', 'value', array('name'=>'version', 'plugin'=>$component)); // No caching!
795a08ad 851
9b683d13 852 if (file_exists($fullblock.'/db/install.php')) {
853 if (get_config('block_'.$blockname, 'installrunning')) {
854 require_once($fullblock.'/db/install.php');
855 $recover_install_function = 'xmldb_block_'.$blockname.'_install_recovery';
856 if (function_exists($recover_install_function)) {
857 $startcallback($component, true, $verbose);
858 $recover_install_function();
859 unset_config('installrunning', 'block_'.$blockname);
860 // Install various components
861 update_capabilities($component);
c6d75bff 862 log_update_descriptions($component);
c976e271 863 external_update_descriptions($component);
9b683d13 864 events_update_definition($component);
309ae892 865 \core\task\manager::reset_scheduled_tasks_for_component($component);
9b683d13 866 message_update_providers($component);
6c0bfb14 867 \core\message\inbound\manager::update_handlers_for_component($component);
de260e0f 868 upgrade_plugin_mnet_functions($component);
c026a28d 869 core_tag_area::reset_definitions_for_component($component);
9b683d13 870 $endcallback($component, true, $verbose);
871 }
872 }
873 }
874
bde002b8 875 if (empty($installedversion)) { // block not installed yet, so install it
795a08ad 876 $conflictblock = array_search($blocktitle, $blocktitles);
877 if ($conflictblock !== false) {
878 // Duplicate block titles are not allowed, they confuse people
879 // AND PHP's associative arrays ;)
c1ddac83 880 throw new plugin_defective_exception($component, get_string('blocknameconflict', 'error', (object)array('name'=>$block->name, 'conflict'=>$conflictblock)));
795a08ad 881 }
194cdca8 882 $startcallback($component, true, $verbose);
795a08ad 883
884 if (file_exists($fullblock.'/db/install.xml')) {
885 $DB->get_manager()->install_from_xmldb_file($fullblock.'/db/install.xml');
886 }
887 $block->id = $DB->insert_record('block', $block);
bde002b8 888 upgrade_block_savepoint(true, $plugin->version, $block->name, false);
795a08ad 889
890 if (file_exists($fullblock.'/db/install.php')) {
891 require_once($fullblock.'/db/install.php');
9b683d13 892 // Set installation running flag, we need to recover after exception or error
893 set_config('installrunning', 1, 'block_'.$blockname);
0e35ba6f 894 $post_install_function = 'xmldb_block_'.$blockname.'_install';
795a08ad 895 $post_install_function();
9b683d13 896 unset_config('installrunning', 'block_'.$blockname);
795a08ad 897 }
898
899 $blocktitles[$block->name] = $blocktitle;
900
901 // Install various components
902 update_capabilities($component);
c6d75bff 903 log_update_descriptions($component);
c976e271 904 external_update_descriptions($component);
795a08ad 905 events_update_definition($component);
309ae892 906 \core\task\manager::reset_scheduled_tasks_for_component($component);
795a08ad 907 message_update_providers($component);
6c0bfb14 908 \core\message\inbound\manager::update_handlers_for_component($component);
c026a28d 909 core_tag_area::reset_definitions_for_component($component);
de260e0f 910 upgrade_plugin_mnet_functions($component);
795a08ad 911
194cdca8 912 $endcallback($component, true, $verbose);
795a08ad 913
bde002b8 914 } else if ($installedversion < $plugin->version) {
194cdca8 915 $startcallback($component, false, $verbose);
795a08ad 916
917 if (is_readable($fullblock.'/db/upgrade.php')) {
918 require_once($fullblock.'/db/upgrade.php'); // defines new upgrading function
919 $newupgrade_function = 'xmldb_block_'.$blockname.'_upgrade';
bde002b8 920 $result = $newupgrade_function($installedversion, $block);
795a08ad 921 } else {
922 $result = true;
923 }
924
bde002b8 925 $installedversion = $DB->get_field('config_plugins', 'value', array('name'=>'version', 'plugin'=>$component)); // No caching!
795a08ad 926 $currblock = $DB->get_record('block', array('name'=>$block->name));
bde002b8 927 if ($installedversion < $plugin->version) {
795a08ad 928 // store version if not already there
bde002b8 929 upgrade_block_savepoint($result, $plugin->version, $block->name, false);
795a08ad 930 }
931
932 if ($currblock->cron != $block->cron) {
933 // update cron flag if needed
1fa84543 934 $DB->set_field('block', 'cron', $block->cron, array('id' => $currblock->id));
795a08ad 935 }
936
b921b6ee 937 // Upgrade various components
795a08ad 938 update_capabilities($component);
c6d75bff 939 log_update_descriptions($component);
c976e271 940 external_update_descriptions($component);
17da2e6f 941 events_update_definition($component);
309ae892 942 \core\task\manager::reset_scheduled_tasks_for_component($component);
795a08ad 943 message_update_providers($component);
6c0bfb14 944 \core\message\inbound\manager::update_handlers_for_component($component);
de260e0f 945 upgrade_plugin_mnet_functions($component);
c026a28d 946 core_tag_area::reset_definitions_for_component($component);
795a08ad 947
194cdca8 948 $endcallback($component, false, $verbose);
795a08ad 949
bde002b8
PS
950 } else if ($installedversion > $plugin->version) {
951 throw new downgrade_exception($component, $installedversion, $plugin->version);
795a08ad 952 }
953 }
954
955
956 // Finally, if we are in the first_install of BLOCKS setup frontpage and admin page blocks
957 if ($first_install) {
795a08ad 958 //Iterate over each course - there should be only site course here now
959 if ($courses = $DB->get_records('course')) {
960 foreach ($courses as $course) {
9d1d606e 961 blocks_add_default_course_blocks($course);
db9d4a3d 962 }
963 }
795a08ad 964
9d1d606e 965 blocks_add_default_system_blocks();
795a08ad 966 }
967}
968
c6d75bff
PS
969
970/**
971 * Log_display description function used during install and upgrade.
972 *
973 * @param string $component name of component (moodle, mod_assignment, etc.)
974 * @return void
975 */
976function log_update_descriptions($component) {
977 global $DB;
978
b0d1d941 979 $defpath = core_component::get_component_directory($component).'/db/log.php';
c6d75bff
PS
980
981 if (!file_exists($defpath)) {
982 $DB->delete_records('log_display', array('component'=>$component));
983 return;
984 }
985
986 // load new info
987 $logs = array();
988 include($defpath);
989 $newlogs = array();
990 foreach ($logs as $log) {
991 $newlogs[$log['module'].'-'.$log['action']] = $log; // kind of unique name
992 }
993 unset($logs);
994 $logs = $newlogs;
995
996 $fields = array('module', 'action', 'mtable', 'field');
997 // update all log fist
998 $dblogs = $DB->get_records('log_display', array('component'=>$component));
999 foreach ($dblogs as $dblog) {
1000 $name = $dblog->module.'-'.$dblog->action;
1001
1002 if (empty($logs[$name])) {
1003 $DB->delete_records('log_display', array('id'=>$dblog->id));
1004 continue;
1005 }
1006
1007 $log = $logs[$name];
1008 unset($logs[$name]);
1009
1010 $update = false;
1011 foreach ($fields as $field) {
1012 if ($dblog->$field != $log[$field]) {
1013 $dblog->$field = $log[$field];
1014 $update = true;
1015 }
1016 }
1017 if ($update) {
1018 $DB->update_record('log_display', $dblog);
1019 }
1020 }
1021 foreach ($logs as $log) {
1022 $dblog = (object)$log;
1023 $dblog->component = $component;
1024 $DB->insert_record('log_display', $dblog);
1025 }
1026}
1027
c976e271 1028/**
1029 * Web service discovery function used during install and upgrade.
1030 * @param string $component name of component (moodle, mod_assignment, etc.)
1031 * @return void
1032 */
1033function external_update_descriptions($component) {
bc81eadb 1034 global $DB, $CFG;
c976e271 1035
b0d1d941 1036 $defpath = core_component::get_component_directory($component).'/db/services.php';
c976e271 1037
1038 if (!file_exists($defpath)) {
bc81eadb 1039 require_once($CFG->dirroot.'/lib/externallib.php');
c976e271 1040 external_delete_descriptions($component);
1041 return;
1042 }
1043
1044 // load new info
1045 $functions = array();
1046 $services = array();
1047 include($defpath);
1048
1049 // update all function fist
1050 $dbfunctions = $DB->get_records('external_functions', array('component'=>$component));
1051 foreach ($dbfunctions as $dbfunction) {
1052 if (empty($functions[$dbfunction->name])) {
1053 $DB->delete_records('external_functions', array('id'=>$dbfunction->id));
1054 // do not delete functions from external_services_functions, beacuse
1055 // we want to notify admins when functions used in custom services disappear
c6d75bff
PS
1056
1057 //TODO: this looks wrong, we have to delete it eventually (skodak)
c976e271 1058 continue;
1059 }
1060
1061 $function = $functions[$dbfunction->name];
1062 unset($functions[$dbfunction->name]);
1063 $function['classpath'] = empty($function['classpath']) ? null : $function['classpath'];
1064
1065 $update = false;
1066 if ($dbfunction->classname != $function['classname']) {
1067 $dbfunction->classname = $function['classname'];
1068 $update = true;
1069 }
1070 if ($dbfunction->methodname != $function['methodname']) {
1071 $dbfunction->methodname = $function['methodname'];
1072 $update = true;
1073 }
1074 if ($dbfunction->classpath != $function['classpath']) {
1075 $dbfunction->classpath = $function['classpath'];
1076 $update = true;
1077 }
12fc8acf 1078 $functioncapabilities = array_key_exists('capabilities', $function)?$function['capabilities']:'';
72f68b51 1079 if ($dbfunction->capabilities != $functioncapabilities) {
1080 $dbfunction->capabilities = $functioncapabilities;
1081 $update = true;
1082 }
c976e271 1083 if ($update) {
1084 $DB->update_record('external_functions', $dbfunction);
1085 }
1086 }
1087 foreach ($functions as $fname => $function) {
365a5941 1088 $dbfunction = new stdClass();
c976e271 1089 $dbfunction->name = $fname;
1090 $dbfunction->classname = $function['classname'];
1091 $dbfunction->methodname = $function['methodname'];
1092 $dbfunction->classpath = empty($function['classpath']) ? null : $function['classpath'];
1093 $dbfunction->component = $component;
12fc8acf 1094 $dbfunction->capabilities = array_key_exists('capabilities', $function)?$function['capabilities']:'';
c976e271 1095 $dbfunction->id = $DB->insert_record('external_functions', $dbfunction);
1096 }
1097 unset($functions);
1098
1099 // now deal with services
1100 $dbservices = $DB->get_records('external_services', array('component'=>$component));
1101 foreach ($dbservices as $dbservice) {
1102 if (empty($services[$dbservice->name])) {
bc81eadb 1103 $DB->delete_records('external_tokens', array('externalserviceid'=>$dbservice->id));
c976e271 1104 $DB->delete_records('external_services_functions', array('externalserviceid'=>$dbservice->id));
1105 $DB->delete_records('external_services_users', array('externalserviceid'=>$dbservice->id));
1106 $DB->delete_records('external_services', array('id'=>$dbservice->id));
1107 continue;
1108 }
1109 $service = $services[$dbservice->name];
1110 unset($services[$dbservice->name]);
1111 $service['enabled'] = empty($service['enabled']) ? 0 : $service['enabled'];
1112 $service['requiredcapability'] = empty($service['requiredcapability']) ? null : $service['requiredcapability'];
1113 $service['restrictedusers'] = !isset($service['restrictedusers']) ? 1 : $service['restrictedusers'];
af03513f 1114 $service['downloadfiles'] = !isset($service['downloadfiles']) ? 0 : $service['downloadfiles'];
106c55fb 1115 $service['uploadfiles'] = !isset($service['uploadfiles']) ? 0 : $service['uploadfiles'];
c1b65883 1116 $service['shortname'] = !isset($service['shortname']) ? null : $service['shortname'];
c976e271 1117
1118 $update = false;
c976e271 1119 if ($dbservice->requiredcapability != $service['requiredcapability']) {
1120 $dbservice->requiredcapability = $service['requiredcapability'];
1121 $update = true;
1122 }
1123 if ($dbservice->restrictedusers != $service['restrictedusers']) {
1124 $dbservice->restrictedusers = $service['restrictedusers'];
1125 $update = true;
1126 }
af03513f
JM
1127 if ($dbservice->downloadfiles != $service['downloadfiles']) {
1128 $dbservice->downloadfiles = $service['downloadfiles'];
1129 $update = true;
1130 }
106c55fb
DW
1131 if ($dbservice->uploadfiles != $service['uploadfiles']) {
1132 $dbservice->uploadfiles = $service['uploadfiles'];
1133 $update = true;
1134 }
c1b65883
JM
1135 //if shortname is not a PARAM_ALPHANUMEXT, fail (tested here for service update and creation)
1136 if (isset($service['shortname']) and
1137 (clean_param($service['shortname'], PARAM_ALPHANUMEXT) != $service['shortname'])) {
1138 throw new moodle_exception('installserviceshortnameerror', 'webservice', '', $service['shortname']);
1139 }
1140 if ($dbservice->shortname != $service['shortname']) {
1141 //check that shortname is unique
1142 if (isset($service['shortname'])) { //we currently accepts multiple shortname == null
1143 $existingservice = $DB->get_record('external_services',
1144 array('shortname' => $service['shortname']));
1145 if (!empty($existingservice)) {
1146 throw new moodle_exception('installexistingserviceshortnameerror', 'webservice', '', $service['shortname']);
1147 }
1148 }
1149 $dbservice->shortname = $service['shortname'];
1150 $update = true;
1151 }
c976e271 1152 if ($update) {
1153 $DB->update_record('external_services', $dbservice);
1154 }
1155
1156 $functions = $DB->get_records('external_services_functions', array('externalserviceid'=>$dbservice->id));
1157 foreach ($functions as $function) {
1158 $key = array_search($function->functionname, $service['functions']);
1159 if ($key === false) {
1160 $DB->delete_records('external_services_functions', array('id'=>$function->id));
1161 } else {
1162 unset($service['functions'][$key]);
1163 }
1164 }
1165 foreach ($service['functions'] as $fname) {
365a5941 1166 $newf = new stdClass();
c976e271 1167 $newf->externalserviceid = $dbservice->id;
1168 $newf->functionname = $fname;
1169 $DB->insert_record('external_services_functions', $newf);
1170 }
1171 unset($functions);
1172 }
1173 foreach ($services as $name => $service) {
c1b65883
JM
1174 //check that shortname is unique
1175 if (isset($service['shortname'])) { //we currently accepts multiple shortname == null
1176 $existingservice = $DB->get_record('external_services',
1177 array('shortname' => $service['shortname']));
1178 if (!empty($existingservice)) {
1179 throw new moodle_exception('installserviceshortnameerror', 'webservice');
1180 }
1181 }
1182
365a5941 1183 $dbservice = new stdClass();
c976e271 1184 $dbservice->name = $name;
1185 $dbservice->enabled = empty($service['enabled']) ? 0 : $service['enabled'];
1186 $dbservice->requiredcapability = empty($service['requiredcapability']) ? null : $service['requiredcapability'];
1187 $dbservice->restrictedusers = !isset($service['restrictedusers']) ? 1 : $service['restrictedusers'];
af03513f 1188 $dbservice->downloadfiles = !isset($service['downloadfiles']) ? 0 : $service['downloadfiles'];
106c55fb 1189 $dbservice->uploadfiles = !isset($service['uploadfiles']) ? 0 : $service['uploadfiles'];
c1b65883 1190 $dbservice->shortname = !isset($service['shortname']) ? null : $service['shortname'];
c976e271 1191 $dbservice->component = $component;
e5180580 1192 $dbservice->timecreated = time();
c976e271 1193 $dbservice->id = $DB->insert_record('external_services', $dbservice);
1194 foreach ($service['functions'] as $fname) {
365a5941 1195 $newf = new stdClass();
c976e271 1196 $newf->externalserviceid = $dbservice->id;
1197 $newf->functionname = $fname;
1198 $DB->insert_record('external_services_functions', $newf);
1199 }
1200 }
1201}
1202
72fb21b6 1203/**
1204 * upgrade logging functions
72fb21b6 1205 */
fd1a792e 1206function upgrade_handle_exception($ex, $plugin = null) {
96e1fdf4
PS
1207 global $CFG;
1208
a56c457e
PS
1209 // rollback everything, we need to log all upgrade problems
1210 abort_all_db_transactions();
1211
c19bc39c
PS
1212 $info = get_exception_info($ex);
1213
1214 // First log upgrade error
1215 upgrade_log(UPGRADE_LOG_ERROR, $plugin, 'Exception: ' . get_class($ex), $info->message, $info->backtrace);
1216
1217 // Always turn on debugging - admins need to know what is going on
96f81ea3 1218 set_debugging(DEBUG_DEVELOPER, true);
c19bc39c 1219
fd1a792e 1220 default_exception_handler($ex, true, $plugin);
db9d4a3d 1221}
1222
1223/**
1224 * Adds log entry into upgrade_log table
1225 *
1226 * @param int $type UPGRADE_LOG_NORMAL, UPGRADE_LOG_NOTICE or UPGRADE_LOG_ERROR
bb8b2971 1227 * @param string $plugin frankenstyle component name
db9d4a3d 1228 * @param string $info short description text of log entry
1229 * @param string $details long problem description
1230 * @param string $backtrace string used for errors only
1231 * @return void
1232 */
1233function upgrade_log($type, $plugin, $info, $details=null, $backtrace=null) {
1234 global $DB, $USER, $CFG;
1235
bb8b2971
PS
1236 if (empty($plugin)) {
1237 $plugin = 'core';
1238 }
1239
56da374e 1240 list($plugintype, $pluginname) = core_component::normalize_component($plugin);
bb8b2971 1241 $component = is_null($pluginname) ? $plugintype : $plugintype . '_' . $pluginname;
795a08ad 1242
34a2777c 1243 $backtrace = format_backtrace($backtrace, true);
db9d4a3d 1244
bb8b2971
PS
1245 $currentversion = null;
1246 $targetversion = null;
db9d4a3d 1247
1248 //first try to find out current version number
bb8b2971 1249 if ($plugintype === 'core') {
db9d4a3d 1250 //main
bb8b2971 1251 $currentversion = $CFG->version;
db9d4a3d 1252
bb8b2971
PS
1253 $version = null;
1254 include("$CFG->dirroot/version.php");
1255 $targetversion = $version;
795a08ad 1256
795a08ad 1257 } else {
bb8b2971 1258 $pluginversion = get_config($component, 'version');
795a08ad 1259 if (!empty($pluginversion)) {
bb8b2971
PS
1260 $currentversion = $pluginversion;
1261 }
b0d1d941 1262 $cd = core_component::get_component_directory($component);
bb8b2971
PS
1263 if (file_exists("$cd/version.php")) {
1264 $plugin = new stdClass();
1265 $plugin->version = null;
bde002b8 1266 $module = $plugin;
bb8b2971
PS
1267 include("$cd/version.php");
1268 $targetversion = $plugin->version;
795a08ad 1269 }
db9d4a3d 1270 }
1271
365a5941 1272 $log = new stdClass();
bb8b2971
PS
1273 $log->type = $type;
1274 $log->plugin = $component;
1275 $log->version = $currentversion;
1276 $log->targetversion = $targetversion;
1277 $log->info = $info;
1278 $log->details = $details;
1279 $log->backtrace = $backtrace;
1280 $log->userid = $USER->id;
1281 $log->timemodified = time();
db9d4a3d 1282 try {
1283 $DB->insert_record('upgrade_log', $log);
1284 } catch (Exception $ignored) {
795a08ad 1285 // possible during install or 2.0 upgrade
db9d4a3d 1286 }
1287}
1288
1289/**
1290 * Marks start of upgrade, blocks any other access to site.
1291 * The upgrade is finished at the end of script or after timeout.
72fb21b6 1292 *
1293 * @global object
1294 * @global object
1295 * @global object
db9d4a3d 1296 */
1297function upgrade_started($preinstall=false) {
de6d81e6 1298 global $CFG, $DB, $PAGE, $OUTPUT;
db9d4a3d 1299
1300 static $started = false;
1301
1302 if ($preinstall) {
1303 ignore_user_abort(true);
1304 upgrade_setup_debug(true);
1305
1306 } else if ($started) {
1307 upgrade_set_timeout(120);
1308
1309 } else {
c13a5e71 1310 if (!CLI_SCRIPT and !$PAGE->headerprinted) {
db9d4a3d 1311 $strupgrade = get_string('upgradingversion', 'admin');
78946b9b 1312 $PAGE->set_pagelayout('maintenance');
543f54d3 1313 upgrade_init_javascript();
de6d81e6 1314 $PAGE->set_title($strupgrade.' - Moodle '.$CFG->target_release);
1315 $PAGE->set_heading($strupgrade);
1316 $PAGE->navbar->add($strupgrade);
1317 $PAGE->set_cacheable(false);
1318 echo $OUTPUT->header();
db9d4a3d 1319 }
1320
1321 ignore_user_abort(true);
38fc0130 1322 core_shutdown_manager::register_function('upgrade_finished_handler');
db9d4a3d 1323 upgrade_setup_debug(true);
1324 set_config('upgraderunning', time()+300);
1325 $started = true;
1326 }
1327}
1328
1329/**
b921b6ee 1330 * Internal function - executed if upgrade interrupted.
db9d4a3d 1331 */
1332function upgrade_finished_handler() {
1333 upgrade_finished();
1334}
1335
1336/**
1337 * Indicates upgrade is finished.
1338 *
1339 * This function may be called repeatedly.
72fb21b6 1340 *
1341 * @global object
1342 * @global object
db9d4a3d 1343 */
1344function upgrade_finished($continueurl=null) {
7e0d6675 1345 global $CFG, $DB, $OUTPUT;
db9d4a3d 1346
1347 if (!empty($CFG->upgraderunning)) {
1348 unset_config('upgraderunning');
24dedb96
SH
1349 // We have to forcefully purge the caches using the writer here.
1350 // This has to be done after we unset the config var. If someone hits the site while this is set they will
1351 // cause the config values to propogate to the caches.
1352 // Caches are purged after the last step in an upgrade but there is several code routines that exceute between
1353 // then and now that leaving a window for things to fall out of sync.
1354 cache_helper::purge_all(true);
db9d4a3d 1355 upgrade_setup_debug(false);
1356 ignore_user_abort(false);
1357 if ($continueurl) {
aa9a6867 1358 echo $OUTPUT->continue_button($continueurl);
7e0d6675 1359 echo $OUTPUT->footer();
db9d4a3d 1360 die;
1361 }
1362 }
1363}
1364
72fb21b6 1365/**
1366 * @global object
1367 * @global object
1368 */
db9d4a3d 1369function upgrade_setup_debug($starting) {
1370 global $CFG, $DB;
1371
1372 static $originaldebug = null;
1373
1374 if ($starting) {
1375 if ($originaldebug === null) {
1376 $originaldebug = $DB->get_debug();
1377 }
1378 if (!empty($CFG->upgradeshowsql)) {
1379 $DB->set_debug(true);
1380 }
1381 } else {
1382 $DB->set_debug($originaldebug);
1383 }
1384}
1385
1386function print_upgrade_separator() {
1387 if (!CLI_SCRIPT) {
1388 echo '<hr />';
1389 }
1390}
1391
795a08ad 1392/**
1393 * Default start upgrade callback
1394 * @param string $plugin
b921b6ee 1395 * @param bool $installation true if installation, false means upgrade
795a08ad 1396 */
194cdca8 1397function print_upgrade_part_start($plugin, $installation, $verbose) {
3c159385 1398 global $OUTPUT;
795a08ad 1399 if (empty($plugin) or $plugin == 'moodle') {
1400 upgrade_started($installation); // does not store upgrade running flag yet
194cdca8 1401 if ($verbose) {
3c159385 1402 echo $OUTPUT->heading(get_string('coresystem'));
194cdca8 1403 }
795a08ad 1404 } else {
1405 upgrade_started();
194cdca8 1406 if ($verbose) {
3c159385 1407 echo $OUTPUT->heading($plugin);
194cdca8 1408 }
795a08ad 1409 }
1410 if ($installation) {
1411 if (empty($plugin) or $plugin == 'moodle') {
1412 // no need to log - log table not yet there ;-)
1413 } else {
1414 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Starting plugin installation');
1415 }
1416 } else {
1417 if (empty($plugin) or $plugin == 'moodle') {
1418 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Starting core upgrade');
1419 } else {
1420 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Starting plugin upgrade');
1421 }
1422 }
1423}
1424
1425/**
1426 * Default end upgrade callback
1427 * @param string $plugin
b921b6ee 1428 * @param bool $installation true if installation, false means upgrade
795a08ad 1429 */
194cdca8 1430function print_upgrade_part_end($plugin, $installation, $verbose) {
aa9a6867 1431 global $OUTPUT;
795a08ad 1432 upgrade_started();
1433 if ($installation) {
1434 if (empty($plugin) or $plugin == 'moodle') {
1435 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Core installed');
1436 } else {
1437 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Plugin installed');
1438 }
1439 } else {
1440 if (empty($plugin) or $plugin == 'moodle') {
1441 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Core upgraded');
1442 } else {
1443 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Plugin upgraded');
1444 }
1445 }
194cdca8 1446 if ($verbose) {
aa9a6867 1447 echo $OUTPUT->notification(get_string('success'), 'notifysuccess');
194cdca8 1448 print_upgrade_separator();
96db14f9 1449 }
1450}
1451
72fb21b6 1452/**
b921b6ee 1453 * Sets up JS code required for all upgrade scripts.
72fb21b6 1454 * @global object
1455 */
543f54d3 1456function upgrade_init_javascript() {
e29380f3 1457 global $PAGE;
543f54d3
PS
1458 // scroll to the end of each upgrade page so that ppl see either error or continue button,
1459 // no need to scroll continuously any more, it is enough to jump to end once the footer is printed ;-)
1460 $js = "window.scrollTo(0, 5000000);";
1461 $PAGE->requires->js_init_code($js);
db9d4a3d 1462}
1463
db9d4a3d 1464/**
1465 * Try to upgrade the given language pack (or current language)
af8d4d91 1466 *
74a4c9a9 1467 * @param string $lang the code of the language to update, defaults to the current language
db9d4a3d 1468 */
bd41bdd9
PS
1469function upgrade_language_pack($lang = null) {
1470 global $CFG;
db9d4a3d 1471
bd41bdd9
PS
1472 if (!empty($CFG->skiplangupgrade)) {
1473 return;
1474 }
af8d4d91 1475
bd41bdd9
PS
1476 if (!file_exists("$CFG->dirroot/$CFG->admin/tool/langimport/lib.php")) {
1477 // weird, somebody uninstalled the import utility
1478 return;
1479 }
1480
1481 if (!$lang) {
db9d4a3d 1482 $lang = current_language();
1483 }
1484
bd41bdd9
PS
1485 if (!get_string_manager()->translation_exists($lang)) {
1486 return;
db9d4a3d 1487 }
1488
bd41bdd9
PS
1489 get_string_manager()->reset_caches();
1490
1491 if ($lang === 'en') {
1492 return; // Nothing to do
db9d4a3d 1493 }
af8d4d91 1494
bd41bdd9
PS
1495 upgrade_started(false);
1496
1497 require_once("$CFG->dirroot/$CFG->admin/tool/langimport/lib.php");
1498 tool_langimport_preupgrade_update($lang);
1499
af8d4d91
DM
1500 get_string_manager()->reset_caches();
1501
551fe0e5 1502 print_upgrade_separator();
db9d4a3d 1503}
8580535b 1504
1505/**
1506 * Install core moodle tables and initialize
1507 * @param float $version target version
1508 * @param bool $verbose
1509 * @return void, may throw exception
1510 */
1511function install_core($version, $verbose) {
1512 global $CFG, $DB;
1513
e2e35e71 1514 // We can not call purge_all_caches() yet, make sure the temp and cache dirs exist and are empty.
e2e35e71 1515 remove_dir($CFG->cachedir.'', true);
85b38061
PS
1516 make_cache_directory('', true);
1517
1518 remove_dir($CFG->localcachedir.'', true);
1519 make_localcache_directory('', true);
1520
e2e35e71 1521 remove_dir($CFG->tempdir.'', true);
85b38061
PS
1522 make_temp_directory('', true);
1523
e2e35e71 1524 remove_dir($CFG->dataroot.'/muc', true);
85b38061 1525 make_writable_directory($CFG->dataroot.'/muc', true);
e2e35e71 1526
8580535b 1527 try {
3ef7279f 1528 core_php_time_limit::raise(600);
194cdca8 1529 print_upgrade_part_start('moodle', true, $verbose); // does not store upgrade running flag
8580535b 1530
1531 $DB->get_manager()->install_from_xmldb_file("$CFG->libdir/db/install.xml");
1532 upgrade_started(); // we want the flag to be stored in config table ;-)
1533
1534 // set all core default records and default settings
1535 require_once("$CFG->libdir/db/install.php");
c6d75bff 1536 xmldb_main_install(); // installs the capabilities too
8580535b 1537
1538 // store version
1539 upgrade_main_savepoint(true, $version, false);
1540
df997f84 1541 // Continue with the installation
c6d75bff
PS
1542 log_update_descriptions('moodle');
1543 external_update_descriptions('moodle');
8580535b 1544 events_update_definition('moodle');
309ae892 1545 \core\task\manager::reset_scheduled_tasks_for_component('moodle');
8580535b 1546 message_update_providers('moodle');
6c0bfb14 1547 \core\message\inbound\manager::update_handlers_for_component('moodle');
c026a28d 1548 core_tag_area::reset_definitions_for_component('moodle');
8580535b 1549
df997f84 1550 // Write default settings unconditionally
8580535b 1551 admin_apply_default_settings(NULL, true);
1552
194cdca8 1553 print_upgrade_part_end(null, true, $verbose);
94ef67cf 1554
e0d9b7c0
SH
1555 // Purge all caches. They're disabled but this ensures that we don't have any persistent data just in case something
1556 // during installation didn't use APIs.
1557 cache_helper::purge_all();
8580535b 1558 } catch (exception $ex) {
1559 upgrade_handle_exception($ex);
1766e6a1
MG
1560 } catch (Throwable $ex) {
1561 // Engine errors in PHP7 throw exceptions of type Throwable (this "catch" will be ignored in PHP5).
1562 upgrade_handle_exception($ex);
8580535b 1563 }
1564}
1565
1566/**
1567 * Upgrade moodle core
1568 * @param float $version target version
1569 * @param bool $verbose
1570 * @return void, may throw exception
1571 */
1572function upgrade_core($version, $verbose) {
e2049782 1573 global $CFG, $SITE, $DB, $COURSE;
8580535b 1574
41209c1e
PS
1575 raise_memory_limit(MEMORY_EXTRA);
1576
3316fe24 1577 require_once($CFG->libdir.'/db/upgrade.php'); // Defines upgrades
3316fe24 1578
8580535b 1579 try {
7b4d5af7 1580 // Reset caches before any output.
b0dd08dd 1581 cache_helper::purge_all(true);
7b4d5af7 1582 purge_all_caches();
dcf9be7f 1583
8580535b 1584 // Upgrade current language pack if we can
bd41bdd9 1585 upgrade_language_pack();
8580535b 1586
194cdca8 1587 print_upgrade_part_start('moodle', false, $verbose);
8580535b 1588
6b4b7490
PS
1589 // Pre-upgrade scripts for local hack workarounds.
1590 $preupgradefile = "$CFG->dirroot/local/preupgrade.php";
1591 if (file_exists($preupgradefile)) {
3ef7279f 1592 core_php_time_limit::raise();
6b4b7490
PS
1593 require($preupgradefile);
1594 // Reset upgrade timeout to default.
1595 upgrade_set_timeout();
17da2e6f 1596 }
1597
8580535b 1598 $result = xmldb_main_upgrade($CFG->version);
1599 if ($version > $CFG->version) {
1600 // store version if not already there
1601 upgrade_main_savepoint($result, $version, false);
1602 }
1603
e2049782
MG
1604 // In case structure of 'course' table has been changed and we forgot to update $SITE, re-read it from db.
1605 $SITE = $DB->get_record('course', array('id' => $SITE->id));
1606 $COURSE = clone($SITE);
1607
8580535b 1608 // perform all other component upgrade routines
1609 update_capabilities('moodle');
c6d75bff 1610 log_update_descriptions('moodle');
c976e271 1611 external_update_descriptions('moodle');
8580535b 1612 events_update_definition('moodle');
309ae892 1613 \core\task\manager::reset_scheduled_tasks_for_component('moodle');
8580535b 1614 message_update_providers('moodle');
6c0bfb14 1615 \core\message\inbound\manager::update_handlers_for_component('moodle');
c026a28d 1616 core_tag_area::reset_definitions_for_component('moodle');
75af47ee
SH
1617 // Update core definitions.
1618 cache_helper::update_definitions(true);
8580535b 1619
94ef67cf 1620 // Purge caches again, just to be sure we arn't holding onto old stuff now.
a5a6e93f 1621 cache_helper::purge_all(true);
7b4d5af7 1622 purge_all_caches();
2e5eba85
PS
1623
1624 // Clean up contexts - more and more stuff depends on existence of paths and contexts
e922fe23
PS
1625 context_helper::cleanup_instances();
1626 context_helper::create_instances(null, false);
1627 context_helper::build_all_paths(false);
1628 $syscontext = context_system::instance();
1629 $syscontext->mark_dirty();
8580535b 1630
194cdca8 1631 print_upgrade_part_end('moodle', false, $verbose);
8580535b 1632 } catch (Exception $ex) {
1633 upgrade_handle_exception($ex);
1766e6a1
MG
1634 } catch (Throwable $ex) {
1635 // Engine errors in PHP7 throw exceptions of type Throwable (this "catch" will be ignored in PHP5).
1636 upgrade_handle_exception($ex);
8580535b 1637 }
1638}
1639
1640/**
1641 * Upgrade/install other parts of moodle
1642 * @param bool $verbose
1643 * @return void, may throw exception
1644 */
1645function upgrade_noncore($verbose) {
1646 global $CFG;
1647
41209c1e
PS
1648 raise_memory_limit(MEMORY_EXTRA);
1649
8580535b 1650 // upgrade all plugins types
1651 try {
7b4d5af7
PS
1652 // Reset caches before any output.
1653 cache_helper::purge_all(true);
1654 purge_all_caches();
1655
46f6f7f2 1656 $plugintypes = core_component::get_plugin_types();
8580535b 1657 foreach ($plugintypes as $type=>$location) {
17da2e6f 1658 upgrade_plugins($type, 'print_upgrade_part_start', 'print_upgrade_part_end', $verbose);
8580535b 1659 }
94ef67cf 1660 // Update cache definitions. Involves scanning each plugin for any changes.
75af47ee 1661 cache_helper::update_definitions();
c5701ce7
PS
1662 // Mark the site as upgraded.
1663 set_config('allversionshash', core_component::get_all_versions_hash());
7b4d5af7
PS
1664
1665 // Purge caches again, just to be sure we arn't holding onto old stuff now.
1666 cache_helper::purge_all(true);
1667 purge_all_caches();
1668
8580535b 1669 } catch (Exception $ex) {
1670 upgrade_handle_exception($ex);
1766e6a1
MG
1671 } catch (Throwable $ex) {
1672 // Engine errors in PHP7 throw exceptions of type Throwable (this "catch" will be ignored in PHP5).
1673 upgrade_handle_exception($ex);
8580535b 1674 }
8580535b 1675}
3316fe24 1676
1677/**
1678 * Checks if the main tables have been installed yet or not.
e2e35e71
PS
1679 *
1680 * Note: we can not use caches here because they might be stale,
1681 * use with care!
1682 *
3316fe24 1683 * @return bool
1684 */
1685function core_tables_exist() {
1686 global $DB;
1687
e2e35e71 1688 if (!$tables = $DB->get_tables(false) ) { // No tables yet at all.
3316fe24 1689 return false;
9b683d13 1690
3316fe24 1691 } else { // Check for missing main tables
1692 $mtables = array('config', 'course', 'groupings'); // some tables used in 1.9 and 2.0, preferable something from the start and end of install.xml
1693 foreach ($mtables as $mtable) {
1694 if (!in_array($mtable, $tables)) {
1695 return false;
1696 }
1697 }
1698 return true;
9b683d13 1699 }
ba04999c 1700}
c71ade2f
PL
1701
1702/**
1703 * upgrades the mnet rpc definitions for the given component.
1704 * this method doesn't return status, an exception will be thrown in the case of an error
1705 *
1706 * @param string $component the plugin to upgrade, eg auth_mnet
1707 */
1708function upgrade_plugin_mnet_functions($component) {
1709 global $DB, $CFG;
1710
8c59114f 1711 list($type, $plugin) = core_component::normalize_component($component);
1c74b260 1712 $path = core_component::get_plugin_directory($type, $plugin);
c71ade2f 1713
17b71716
PS
1714 $publishes = array();
1715 $subscribes = array();
c71ade2f
PL
1716 if (file_exists($path . '/db/mnet.php')) {
1717 require_once($path . '/db/mnet.php'); // $publishes comes from this file
1718 }
1719 if (empty($publishes)) {
1720 $publishes = array(); // still need this to be able to disable stuff later
1721 }
1722 if (empty($subscribes)) {
1723 $subscribes = array(); // still need this to be able to disable stuff later
1724 }
1725
1726 static $servicecache = array();
1727
1728 // rekey an array based on the rpc method for easy lookups later
1729 $publishmethodservices = array();
1730 $subscribemethodservices = array();
1731 foreach($publishes as $servicename => $service) {
1732 if (is_array($service['methods'])) {
1733 foreach($service['methods'] as $methodname) {
1734 $service['servicename'] = $servicename;
1735 $publishmethodservices[$methodname][] = $service;
1736 }
1737 }
1738 }
1739
1740 // Disable functions that don't exist (any more) in the source
1741 // Should these be deleted? What about their permissions records?
1742 foreach ($DB->get_records('mnet_rpc', array('pluginname'=>$plugin, 'plugintype'=>$type), 'functionname ASC ') as $rpc) {
1743 if (!array_key_exists($rpc->functionname, $publishmethodservices) && $rpc->enabled) {
1744 $DB->set_field('mnet_rpc', 'enabled', 0, array('id' => $rpc->id));
1745 } else if (array_key_exists($rpc->functionname, $publishmethodservices) && !$rpc->enabled) {
1746 $DB->set_field('mnet_rpc', 'enabled', 1, array('id' => $rpc->id));
1747 }
1748 }
1749
1750 // reflect all the services we're publishing and save them
1751 require_once($CFG->dirroot . '/lib/zend/Zend/Server/Reflection.php');
1752 static $cachedclasses = array(); // to store reflection information in
1753 foreach ($publishes as $service => $data) {
1754 $f = $data['filename'];
1755 $c = $data['classname'];
1756 foreach ($data['methods'] as $method) {
6bdfef5d 1757 $dataobject = new stdClass();
c71ade2f
PL
1758 $dataobject->plugintype = $type;
1759 $dataobject->pluginname = $plugin;
1760 $dataobject->enabled = 1;
1761 $dataobject->classname = $c;
1762 $dataobject->filename = $f;
1763
1764 if (is_string($method)) {
1765 $dataobject->functionname = $method;
1766
1767 } else if (is_array($method)) { // wants to override file or class
1768 $dataobject->functionname = $method['method'];
1769 $dataobject->classname = $method['classname'];
1770 $dataobject->filename = $method['filename'];
1771 }
1772 $dataobject->xmlrpcpath = $type.'/'.$plugin.'/'.$dataobject->filename.'/'.$method;
1773 $dataobject->static = false;
1774
1775 require_once($path . '/' . $dataobject->filename);
1776 $functionreflect = null; // slightly different ways to get this depending on whether it's a class method or a function
1777 if (!empty($dataobject->classname)) {
1778 if (!class_exists($dataobject->classname)) {
1779 throw new moodle_exception('installnosuchmethod', 'mnet', '', (object)array('method' => $dataobject->functionname, 'class' => $dataobject->classname));
1780 }
1781 $key = $dataobject->filename . '|' . $dataobject->classname;
1782 if (!array_key_exists($key, $cachedclasses)) { // look to see if we've already got a reflection object
1783 try {
1784 $cachedclasses[$key] = Zend_Server_Reflection::reflectClass($dataobject->classname);
1785 } catch (Zend_Server_Reflection_Exception $e) { // catch these and rethrow them to something more helpful
1786 throw new moodle_exception('installreflectionclasserror', 'mnet', '', (object)array('method' => $dataobject->functionname, 'class' => $dataobject->classname, 'error' => $e->getMessage()));
1787 }
1788 }
1789 $r =& $cachedclasses[$key];
1790 if (!$r->hasMethod($dataobject->functionname)) {
1791 throw new moodle_exception('installnosuchmethod', 'mnet', '', (object)array('method' => $dataobject->functionname, 'class' => $dataobject->classname));
1792 }
1793 // stupid workaround for zend not having a getMethod($name) function
1794 $ms = $r->getMethods();
1795 foreach ($ms as $m) {
1796 if ($m->getName() == $dataobject->functionname) {
1797 $functionreflect = $m;
1798 break;
1799 }
1800 }
1801 $dataobject->static = (int)$functionreflect->isStatic();
1802 } else {
1803 if (!function_exists($dataobject->functionname)) {
1804 throw new moodle_exception('installnosuchfunction', 'mnet', '', (object)array('method' => $dataobject->functionname, 'file' => $dataobject->filename));
1805 }
1806 try {
1807 $functionreflect = Zend_Server_Reflection::reflectFunction($dataobject->functionname);
1808 } catch (Zend_Server_Reflection_Exception $e) { // catch these and rethrow them to something more helpful
1809 throw new moodle_exception('installreflectionfunctionerror', 'mnet', '', (object)array('method' => $dataobject->functionname, '' => $dataobject->filename, 'error' => $e->getMessage()));
1810 }
1811 }
1812 $dataobject->profile = serialize(admin_mnet_method_profile($functionreflect));
1813 $dataobject->help = $functionreflect->getDescription();
1814
1815 if ($record_exists = $DB->get_record('mnet_rpc', array('xmlrpcpath'=>$dataobject->xmlrpcpath))) {
1816 $dataobject->id = $record_exists->id;
1817 $dataobject->enabled = $record_exists->enabled;
1818 $DB->update_record('mnet_rpc', $dataobject);
1819 } else {
1820 $dataobject->id = $DB->insert_record('mnet_rpc', $dataobject, true);
1821 }
c71ade2f 1822
d5bd0b01
DM
1823 // TODO this API versioning must be reworked, here the recently processed method
1824 // sets the service API which may not be correct
677b6321
PL
1825 foreach ($publishmethodservices[$dataobject->functionname] as $service) {
1826 if ($serviceobj = $DB->get_record('mnet_service', array('name'=>$service['servicename']))) {
1827 $serviceobj->apiversion = $service['apiversion'];
1828 $DB->update_record('mnet_service', $serviceobj);
1829 } else {
1830 $serviceobj = new stdClass();
1831 $serviceobj->name = $service['servicename'];
f4a2817a 1832 $serviceobj->description = empty($service['description']) ? '' : $service['description'];
677b6321
PL
1833 $serviceobj->apiversion = $service['apiversion'];
1834 $serviceobj->offer = 1;
1835 $serviceobj->id = $DB->insert_record('mnet_service', $serviceobj);
1836 }
1837 $servicecache[$service['servicename']] = $serviceobj;
1838 if (!$DB->record_exists('mnet_service2rpc', array('rpcid'=>$dataobject->id, 'serviceid'=>$serviceobj->id))) {
1839 $obj = new stdClass();
1840 $obj->rpcid = $dataobject->id;
1841 $obj->serviceid = $serviceobj->id;
1842 $DB->insert_record('mnet_service2rpc', $obj, true);
1843 }
c71ade2f
PL
1844 }
1845 }
1846 }
c71ade2f
PL
1847 // finished with methods we publish, now do subscribable methods
1848 foreach($subscribes as $service => $methods) {
1849 if (!array_key_exists($service, $servicecache)) {
1850 if (!$serviceobj = $DB->get_record('mnet_service', array('name' => $service))) {
81634f03 1851 debugging("TODO: skipping unknown service $service - somebody needs to fix MDL-21993");
c71ade2f
PL
1852 continue;
1853 }
1854 $servicecache[$service] = $serviceobj;
1855 } else {
1856 $serviceobj = $servicecache[$service];
1857 }
1858 foreach ($methods as $method => $xmlrpcpath) {
1859 if (!$rpcid = $DB->get_field('mnet_remote_rpc', 'id', array('xmlrpcpath'=>$xmlrpcpath))) {
1860 $remoterpc = (object)array(
1861 'functionname' => $method,
1862 'xmlrpcpath' => $xmlrpcpath,
1863 'plugintype' => $type,
1864 'pluginname' => $plugin,
1865 'enabled' => 1,
1866 );
1867 $rpcid = $remoterpc->id = $DB->insert_record('mnet_remote_rpc', $remoterpc, true);
1868 }
1869 if (!$DB->record_exists('mnet_remote_service2rpc', array('rpcid'=>$rpcid, 'serviceid'=>$serviceobj->id))) {
1870 $obj = new stdClass();
1871 $obj->rpcid = $rpcid;
1872 $obj->serviceid = $serviceobj->id;
1873 $DB->insert_record('mnet_remote_service2rpc', $obj, true);
1874 }
677b6321 1875 $subscribemethodservices[$method][] = $service;
c71ade2f
PL
1876 }
1877 }
1878
1879 foreach ($DB->get_records('mnet_remote_rpc', array('pluginname'=>$plugin, 'plugintype'=>$type), 'functionname ASC ') as $rpc) {
1880 if (!array_key_exists($rpc->functionname, $subscribemethodservices) && $rpc->enabled) {
1881 $DB->set_field('mnet_remote_rpc', 'enabled', 0, array('id' => $rpc->id));
1882 } else if (array_key_exists($rpc->functionname, $subscribemethodservices) && !$rpc->enabled) {
1883 $DB->set_field('mnet_remote_rpc', 'enabled', 1, array('id' => $rpc->id));
1884 }
1885 }
1886
1887 return true;
1888}
1889
1890/**
1891 * Given some sort of Zend Reflection function/method object, return a profile array, ready to be serialized and stored
1892 *
1893 * @param Zend_Server_Reflection_Function_Abstract $function can be any subclass of this object type
1894 *
1895 * @return array
1896 */
1897function admin_mnet_method_profile(Zend_Server_Reflection_Function_Abstract $function) {
f20edd52
PS
1898 $protos = $function->getPrototypes();
1899 $proto = array_pop($protos);
c71ade2f
PL
1900 $ret = $proto->getReturnValue();
1901 $profile = array(
1902 'parameters' => array(),
1903 'return' => array(
1904 'type' => $ret->getType(),
1905 'description' => $ret->getDescription(),
1906 ),
1907 );
1908 foreach ($proto->getParameters() as $p) {
1909 $profile['parameters'][] = array(
1910 'name' => $p->getName(),
1911 'type' => $p->getType(),
1912 'description' => $p->getDescription(),
1913 );
1914 }
1915 return $profile;
1916}
424a19b1 1917
941de296
MG
1918/**
1919 * Detect draft file areas with missing root directory records and add them.
1920 */
1921function upgrade_fix_missing_root_folders_draft() {
1922 global $DB;
1923
1924 $transaction = $DB->start_delegated_transaction();
1925
1926 $sql = "SELECT contextid, itemid, MAX(timecreated) AS timecreated, MAX(timemodified) AS timemodified
1927 FROM {files}
1928 WHERE (component = 'user' AND filearea = 'draft')
1929 GROUP BY contextid, itemid
1930 HAVING MAX(CASE WHEN filename = '.' AND filepath = '/' THEN 1 ELSE 0 END) = 0";
1931
1932 $rs = $DB->get_recordset_sql($sql);
1933 $defaults = array('component' => 'user',
1934 'filearea' => 'draft',
1935 'filepath' => '/',
1936 'filename' => '.',
1937 'userid' => 0, // Don't rely on any particular user for these system records.
1938 'filesize' => 0,
1939 'contenthash' => sha1(''));
1940 foreach ($rs as $r) {
1941 $r->pathnamehash = sha1("/$r->contextid/user/draft/$r->itemid/.");
1942 $DB->insert_record('files', (array)$r + $defaults);
1943 }
1944 $rs->close();
1945 $transaction->allow_commit();
1946}
71611510
MN
1947
1948/**
1949 * This function verifies that the database is not using an unsupported storage engine.
1950 *
1951 * @param environment_results $result object to update, if relevant
1952 * @return environment_results|null updated results object, or null if the storage engine is supported
1953 */
1954function check_database_storage_engine(environment_results $result) {
1955 global $DB;
1956
1957 // Check if MySQL is the DB family (this will also be the same for MariaDB).
1958 if ($DB->get_dbfamily() == 'mysql') {
1959 // Get the database engine we will either be using to install the tables, or what we are currently using.
1960 $engine = $DB->get_dbengine();
1961 // Check if MyISAM is the storage engine that will be used, if so, do not proceed and display an error.
1962 if ($engine == 'MyISAM') {
1963 $result->setInfo('unsupported_db_storage_engine');
1964 $result->setStatus(false);
1965 return $result;
1966 }
1967 }
1968
1969 return null;
1970}
1bd4b9fc
SL
1971
1972/**
1973 * Method used to check the usage of slasharguments config and display a warning message.
1974 *
1975 * @param environment_results $result object to update, if relevant.
1976 * @return environment_results|null updated results or null if slasharguments is disabled.
1977 */
1978function check_slasharguments(environment_results $result){
1979 global $CFG;
1980
e284ac02 1981 if (!during_initial_install() && empty($CFG->slasharguments)) {
1bd4b9fc
SL
1982 $result->setInfo('slasharguments');
1983 $result->setStatus(false);
1984 return $result;
1985 }
1986
1987 return null;
1988}
9b8104ce
SL
1989
1990/**
1991 * This function verifies if the database has tables using innoDB Antelope row format.
1992 *
1993 * @param environment_results $result
1994 * @return environment_results|null updated results object, or null if no Antelope table has been found.
1995 */
1996function check_database_tables_row_format(environment_results $result) {
1997 global $DB;
1998
1999 if ($DB->get_dbfamily() == 'mysql') {
2000 $generator = $DB->get_manager()->generator;
2001
2002 foreach ($DB->get_tables(false) as $table) {
2003 $columns = $DB->get_columns($table, false);
c7ccb543 2004 $size = $generator->guess_antelope_row_size($columns);
9b8104ce
SL
2005 $format = $DB->get_row_format($table);
2006
2007 if ($size <= $generator::ANTELOPE_MAX_ROW_SIZE) {
2008 continue;
2009 }
2010
2011 if ($format === 'Compact' or $format === 'Redundant') {
2012 $result->setInfo('unsupported_db_table_row_format');
2013 $result->setStatus(false);
2014 return $result;
2015 }
2016 }
2017 }
2018
2019 return null;
2020}
ebea19cb
FM
2021
2022/**
2023 * Upgrade the minmaxgrade setting.
2024 *
2025 * This step should only be run for sites running 2.8 or later. Sites using 2.7 will be fine
2026 * using the new default system setting $CFG->grade_minmaxtouse.
2027 *
2028 * @return void
2029 */
2030function upgrade_minmaxgrade() {
2031 global $CFG, $DB;
2032
2033 // 2 is a copy of GRADE_MIN_MAX_FROM_GRADE_GRADE.
2034 $settingvalue = 2;
2035
2036 // Set the course setting when:
2037 // - The system setting does not exist yet.
2038 // - The system seeting is not set to what we'd set the course setting.
2039 $setcoursesetting = !isset($CFG->grade_minmaxtouse) || $CFG->grade_minmaxtouse != $settingvalue;
2040
2041 // Identify the courses that have inconsistencies grade_item vs grade_grade.
2042 $sql = "SELECT DISTINCT(gi.courseid)
82cca1ab
G
2043 FROM {grade_grades} gg
2044 JOIN {grade_items} gi
ebea19cb 2045 ON gg.itemid = gi.id
82cca1ab 2046 WHERE gi.itemtype NOT IN (?, ?)
ebea19cb
FM
2047 AND (gg.rawgrademax != gi.grademax OR gg.rawgrademin != gi.grademin)";
2048
2049 $rs = $DB->get_recordset_sql($sql, array('course', 'category'));
2050 foreach ($rs as $record) {
2051 // Flag the course to show a notice in the gradebook.
2052 set_config('show_min_max_grades_changed_' . $record->courseid, 1);
2053
2054 // Set the appropriate course setting so that grades displayed are not changed.
2055 $configname = 'minmaxtouse';
2056 if ($setcoursesetting &&
2057 !$DB->record_exists('grade_settings', array('courseid' => $record->courseid, 'name' => $configname))) {
2058 // Do not set the setting when the course already defines it.
2059 $data = new stdClass();
2060 $data->courseid = $record->courseid;
2061 $data->name = $configname;
2062 $data->value = $settingvalue;
2063 $DB->insert_record('grade_settings', $data);
2064 }
2065
2066 // Mark the grades to be regraded.
2067 $DB->set_field('grade_items', 'needsupdate', 1, array('courseid' => $record->courseid));
2068 }
2069 $rs->close();
2070}
98b32c9e
DM
2071
2072
2073/**
2074 * Assert the upgrade key is provided, if it is defined.
2075 *
2076 * The upgrade key can be defined in the main config.php as $CFG->upgradekey. If
2077 * it is defined there, then its value must be provided every time the site is
2078 * being upgraded, regardless the administrator is logged in or not.
2079 *
2080 * This is supposed to be used at certain places in /admin/index.php only.
2081 *
2082 * @param string|null $upgradekeyhash the SHA-1 of the value provided by the user
2083 */
2084function check_upgrade_key($upgradekeyhash) {
2085 global $CFG, $PAGE;
2086
2087 if (isset($CFG->config_php_settings['upgradekey'])) {
2088 if ($upgradekeyhash === null or $upgradekeyhash !== sha1($CFG->config_php_settings['upgradekey'])) {
2089 if (!$PAGE->headerprinted) {
2090 $output = $PAGE->get_renderer('core', 'admin');
2091 echo $output->upgradekey_form_page(new moodle_url('/admin/index.php', array('cache' => 0)));
2092 die();
2093 } else {
2094 // This should not happen.
2095 die('Upgrade locked');
2096 }
2097 }
2098 }
2099}
531381f9
DM
2100
2101/**
2102 * Helper procedure/macro for installing remote plugins at admin/index.php
2103 *
2104 * Does not return, always redirects or exits.
2105 *
2106 * @param array $installable list of \core\update\remote_info
2107 * @param bool $confirmed false: display the validation screen, true: proceed installation
2108 * @param string $heading validation screen heading
2109 * @param moodle_url|string|null $continue URL to proceed with installation at the validation screen
8726c07c 2110 * @param moodle_url|string|null $return URL to go back on cancelling at the validation screen
531381f9 2111 */
2d00be61 2112function upgrade_install_plugins(array $installable, $confirmed, $heading='', $continue=null, $return=null) {
b0fc7898 2113 global $CFG, $PAGE;
531381f9
DM
2114
2115 if (empty($return)) {
2116 $return = $PAGE->url;
2117 }
2118
b0fc7898
DM
2119 if (!empty($CFG->disableupdateautodeploy)) {
2120 redirect($return);
2121 }
2122
531381f9
DM
2123 if (empty($installable)) {
2124 redirect($return);
2125 }
2126
2127 $pluginman = core_plugin_manager::instance();
2128
2129 if ($confirmed) {
2130 // Installation confirmed at the validation results page.
2d00be61
DM
2131 if (!$pluginman->install_plugins($installable, true, true)) {
2132 throw new moodle_exception('install_plugins_failed', 'core_plugin', $return);
531381f9 2133 }
d9a5b810 2134
8726c07c 2135 // Always redirect to admin/index.php to perform the database upgrade.
d9a5b810
DM
2136 // Do not throw away the existing $PAGE->url parameters such as
2137 // confirmupgrade or confirmrelease if $PAGE->url is a superset of the
2138 // URL we must go to.
2139 $mustgoto = new moodle_url('/admin/index.php', array('cache' => 0, 'confirmplugincheck' => 0));
2140 if ($mustgoto->compare($PAGE->url, URL_MATCH_PARAMS)) {
2141 redirect($PAGE->url);
2142 } else {
2143 redirect($mustgoto);
2144 }
531381f9
DM
2145
2146 } else {
2147 $output = $PAGE->get_renderer('core', 'admin');
2148 echo $output->header();
2149 if ($heading) {
2150 echo $output->heading($heading, 3);
2151 }
2152 echo html_writer::start_tag('pre', array('class' => 'plugin-install-console'));
2d00be61 2153 $validated = $pluginman->install_plugins($installable, false, false);
531381f9
DM
2154 echo html_writer::end_tag('pre');
2155 if ($validated) {
4d7528f9 2156 echo $output->plugins_management_confirm_buttons($continue, $return);
531381f9 2157 } else {
4d7528f9 2158 echo $output->plugins_management_confirm_buttons(null, $return);
531381f9
DM
2159 }
2160 echo $output->footer();
2161 die();
2162 }
2163}