MDL-49329 admin: Do not force admin to reconfirm the core upgrade
[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);
9b683d13 497 $endcallback($component, true, $verbose);
498 }
499 }
500 }
db9d4a3d 501
bde002b8 502 $installedversion = $DB->get_field('config_plugins', 'value', array('name'=>'version', 'plugin'=>$component)); // No caching!
795a08ad 503 if (empty($installedversion)) { // new installation
194cdca8 504 $startcallback($component, true, $verbose);
db9d4a3d 505
795a08ad 506 /// Install tables if defined
507 if (file_exists($fullplug.'/db/install.xml')) {
508 $DB->get_manager()->install_from_xmldb_file($fullplug.'/db/install.xml');
db9d4a3d 509 }
9b683d13 510
511 /// store version
512 upgrade_plugin_savepoint(true, $plugin->version, $type, $plug, false);
513
795a08ad 514 /// execute post install file
515 if (file_exists($fullplug.'/db/install.php')) {
516 require_once($fullplug.'/db/install.php');
f6f06d69
PS
517 set_config('installrunning', 1, $plugin->fullname);
518 $post_install_function = 'xmldb_'.$plugin->fullname.'_install';
795a08ad 519 $post_install_function();
f6f06d69 520 unset_config('installrunning', $plugin->fullname);
795a08ad 521 }
522
795a08ad 523 /// Install various components
524 update_capabilities($component);
c6d75bff 525 log_update_descriptions($component);
c976e271 526 external_update_descriptions($component);
795a08ad 527 events_update_definition($component);
309ae892 528 \core\task\manager::reset_scheduled_tasks_for_component($component);
795a08ad 529 message_update_providers($component);
6c0bfb14 530 \core\message\inbound\manager::update_handlers_for_component($component);
afed8d0f
RK
531 if ($type === 'message') {
532 message_update_processors($plug);
533 }
de260e0f 534 upgrade_plugin_mnet_functions($component);
194cdca8 535 $endcallback($component, true, $verbose);
795a08ad 536
537 } else if ($installedversion < $plugin->version) { // upgrade
538 /// Run the upgrade function for the plugin.
194cdca8 539 $startcallback($component, false, $verbose);
795a08ad 540
541 if (is_readable($fullplug.'/db/upgrade.php')) {
542 require_once($fullplug.'/db/upgrade.php'); // defines upgrading function
543
544 $newupgrade_function = 'xmldb_'.$plugin->fullname.'_upgrade';
545 $result = $newupgrade_function($installedversion);
546 } else {
547 $result = true;
548 }
549
bde002b8 550 $installedversion = $DB->get_field('config_plugins', 'value', array('name'=>'version', 'plugin'=>$component)); // No caching!
795a08ad 551 if ($installedversion < $plugin->version) {
552 // store version if not already there
553 upgrade_plugin_savepoint($result, $plugin->version, $type, $plug, false);
554 }
555
556 /// Upgrade various components
557 update_capabilities($component);
c6d75bff 558 log_update_descriptions($component);
c976e271 559 external_update_descriptions($component);
795a08ad 560 events_update_definition($component);
309ae892 561 \core\task\manager::reset_scheduled_tasks_for_component($component);
795a08ad 562 message_update_providers($component);
6c0bfb14 563 \core\message\inbound\manager::update_handlers_for_component($component);
afed8d0f 564 if ($type === 'message') {
bde002b8 565 // Ugly hack!
afed8d0f
RK
566 message_update_processors($plug);
567 }
de260e0f 568 upgrade_plugin_mnet_functions($component);
194cdca8 569 $endcallback($component, false, $verbose);
795a08ad 570
571 } else if ($installedversion > $plugin->version) {
572 throw new downgrade_exception($component, $installedversion, $plugin->version);
db9d4a3d 573 }
574 }
db9d4a3d 575}
576
577/**
578 * Find and check all modules and load them up or upgrade them if necessary
72fb21b6 579 *
580 * @global object
581 * @global object
db9d4a3d 582 */
194cdca8 583function upgrade_plugins_modules($startcallback, $endcallback, $verbose) {
db9d4a3d 584 global $CFG, $DB;
585
bd3b3bba 586 $mods = core_component::get_plugin_list('mod');
db9d4a3d 587
17da2e6f 588 foreach ($mods as $mod=>$fullmod) {
db9d4a3d 589
3e858ea7 590 if ($mod === 'NEWMODULE') { // Someone has unzipped the template, ignore it
db9d4a3d 591 continue;
592 }
593
aff24313 594 $component = clean_param('mod_'.$mod, PARAM_COMPONENT);
db9d4a3d 595
3e858ea7 596 // check module dir is valid name
aff24313
PS
597 if (empty($component)) {
598 throw new plugin_defective_exception('mod_'.$mod, 'Invalid plugin directory name.');
3e858ea7
PS
599 }
600
795a08ad 601 if (!is_readable($fullmod.'/version.php')) {
602 throw new plugin_defective_exception($component, 'Missing version.php');
db9d4a3d 603 }
604
01889f01 605 $module = new stdClass();
bde002b8
PS
606 $plugin = new stdClass();
607 $plugin->version = null;
994e5662 608 require($fullmod .'/version.php'); // Defines $plugin with version etc.
01889f01
DM
609
610 // Check if the legacy $module syntax is still used.
17d2a336 611 if (!is_object($module) or (count((array)$module) > 0)) {
01889f01
DM
612 throw new plugin_defective_exception($component, 'Unsupported $module syntax detected in version.php');
613 }
614
615 // Prepare the record for the {modules} table.
616 $module = clone($plugin);
bde002b8
PS
617 unset($module->version);
618 unset($module->component);
619 unset($module->dependencies);
620 unset($module->release);
bdbcb6d7 621
98ea6973
DM
622 if (empty($plugin->version)) {
623 throw new plugin_defective_exception($component, 'Missing $plugin->version number in version.php.');
3e858ea7
PS
624 }
625
98ea6973
DM
626 if (empty($plugin->component)) {
627 throw new plugin_defective_exception($component, 'Missing $plugin->component declaration in version.php.');
628 }
629
630 if ($plugin->component !== $component) {
631 throw new plugin_misplaced_exception($plugin->component, null, $fullmod);
db9d4a3d 632 }
633
bde002b8
PS
634 if (!empty($plugin->requires)) {
635 if ($plugin->requires > $CFG->version) {
636 throw new upgrade_requires_exception($component, $plugin->version, $CFG->version, $plugin->requires);
637 } else if ($plugin->requires < 2010000000) {
ef14c1e7 638 throw new plugin_defective_exception($component, 'Plugin is not compatible with Moodle 2.x or later.');
db9d4a3d 639 }
640 }
641
ff05bb31
TH
642 if (empty($module->cron)) {
643 $module->cron = 0;
644 }
645
3e858ea7
PS
646 // all modules must have en lang pack
647 if (!is_readable("$fullmod/lang/en/$mod.php")) {
648 throw new plugin_defective_exception($component, 'Missing mandatory en language pack.');
649 }
650
db9d4a3d 651 $module->name = $mod; // The name MUST match the directory
652
bde002b8 653 $installedversion = $DB->get_field('config_plugins', 'value', array('name'=>'version', 'plugin'=>$component)); // No caching!
db9d4a3d 654
9b683d13 655 if (file_exists($fullmod.'/db/install.php')) {
656 if (get_config($module->name, 'installrunning')) {
657 require_once($fullmod.'/db/install.php');
658 $recover_install_function = 'xmldb_'.$module->name.'_install_recovery';
659 if (function_exists($recover_install_function)) {
660 $startcallback($component, true, $verbose);
661 $recover_install_function();
662 unset_config('installrunning', $module->name);
663 // Install various components too
664 update_capabilities($component);
c6d75bff 665 log_update_descriptions($component);
c976e271 666 external_update_descriptions($component);
9b683d13 667 events_update_definition($component);
309ae892 668 \core\task\manager::reset_scheduled_tasks_for_component($component);
9b683d13 669 message_update_providers($component);
6c0bfb14 670 \core\message\inbound\manager::update_handlers_for_component($component);
de260e0f 671 upgrade_plugin_mnet_functions($component);
9b683d13 672 $endcallback($component, true, $verbose);
673 }
674 }
675 }
676
bde002b8 677 if (empty($installedversion)) {
194cdca8 678 $startcallback($component, true, $verbose);
db9d4a3d 679
795a08ad 680 /// Execute install.xml (XMLDB) - must be present in all modules
681 $DB->get_manager()->install_from_xmldb_file($fullmod.'/db/install.xml');
db9d4a3d 682
2e3da297 683 /// Add record into modules table - may be needed in install.php already
684 $module->id = $DB->insert_record('modules', $module);
bde002b8 685 upgrade_mod_savepoint(true, $plugin->version, $module->name, false);
2e3da297 686
db9d4a3d 687 /// Post installation hook - optional
688 if (file_exists("$fullmod/db/install.php")) {
689 require_once("$fullmod/db/install.php");
9b683d13 690 // Set installation running flag, we need to recover after exception or error
691 set_config('installrunning', 1, $module->name);
3412cb43 692 $post_install_function = 'xmldb_'.$module->name.'_install';
db9d4a3d 693 $post_install_function();
9b683d13 694 unset_config('installrunning', $module->name);
db9d4a3d 695 }
696
795a08ad 697 /// Install various components
698 update_capabilities($component);
c6d75bff 699 log_update_descriptions($component);
c976e271 700 external_update_descriptions($component);
795a08ad 701 events_update_definition($component);
309ae892 702 \core\task\manager::reset_scheduled_tasks_for_component($component);
795a08ad 703 message_update_providers($component);
6c0bfb14 704 \core\message\inbound\manager::update_handlers_for_component($component);
de260e0f 705 upgrade_plugin_mnet_functions($component);
795a08ad 706
194cdca8 707 $endcallback($component, true, $verbose);
db9d4a3d 708
bde002b8 709 } else if ($installedversion < $plugin->version) {
795a08ad 710 /// If versions say that we need to upgrade but no upgrade files are available, notify and continue
194cdca8 711 $startcallback($component, false, $verbose);
795a08ad 712
713 if (is_readable($fullmod.'/db/upgrade.php')) {
714 require_once($fullmod.'/db/upgrade.php'); // defines new upgrading function
715 $newupgrade_function = 'xmldb_'.$module->name.'_upgrade';
bde002b8 716 $result = $newupgrade_function($installedversion, $module);
795a08ad 717 } else {
718 $result = true;
719 }
720
bde002b8 721 $installedversion = $DB->get_field('config_plugins', 'value', array('name'=>'version', 'plugin'=>$component)); // No caching!
795a08ad 722 $currmodule = $DB->get_record('modules', array('name'=>$module->name));
bde002b8 723 if ($installedversion < $plugin->version) {
795a08ad 724 // store version if not already there
bde002b8 725 upgrade_mod_savepoint($result, $plugin->version, $mod, false);
795a08ad 726 }
727
3412cb43
TH
728 // update cron flag if needed
729 if ($currmodule->cron != $module->cron) {
730 $DB->set_field('modules', 'cron', $module->cron, array('name' => $module->name));
731 }
732
733 // Upgrade various components
795a08ad 734 update_capabilities($component);
c6d75bff 735 log_update_descriptions($component);
c976e271 736 external_update_descriptions($component);
795a08ad 737 events_update_definition($component);
309ae892 738 \core\task\manager::reset_scheduled_tasks_for_component($component);
795a08ad 739 message_update_providers($component);
6c0bfb14 740 \core\message\inbound\manager::update_handlers_for_component($component);
de260e0f 741 upgrade_plugin_mnet_functions($component);
795a08ad 742
194cdca8 743 $endcallback($component, false, $verbose);
795a08ad 744
bde002b8
PS
745 } else if ($installedversion > $plugin->version) {
746 throw new downgrade_exception($component, $installedversion, $plugin->version);
795a08ad 747 }
748 }
749}
db9d4a3d 750
db9d4a3d 751
795a08ad 752/**
753 * This function finds all available blocks and install them
754 * into blocks table or do all the upgrade process if newer.
72fb21b6 755 *
756 * @global object
757 * @global object
795a08ad 758 */
194cdca8 759function upgrade_plugins_blocks($startcallback, $endcallback, $verbose) {
795a08ad 760 global $CFG, $DB;
761
795a08ad 762 require_once($CFG->dirroot.'/blocks/moodleblock.class.php');
763
764 $blocktitles = array(); // we do not want duplicate titles
765
766 //Is this a first install
767 $first_install = null;
768
bd3b3bba 769 $blocks = core_component::get_plugin_list('block');
795a08ad 770
17da2e6f 771 foreach ($blocks as $blockname=>$fullblock) {
795a08ad 772
773 if (is_null($first_install)) {
f46eba7e 774 $first_install = ($DB->count_records('block_instances') == 0);
795a08ad 775 }
776
aff24313 777 if ($blockname === 'NEWBLOCK') { // Someone has unzipped the template, ignore it
795a08ad 778 continue;
db9d4a3d 779 }
780
aff24313 781 $component = clean_param('block_'.$blockname, PARAM_COMPONENT);
db9d4a3d 782
3e858ea7 783 // check block dir is valid name
aff24313
PS
784 if (empty($component)) {
785 throw new plugin_defective_exception('block_'.$blockname, 'Invalid plugin directory name.');
3e858ea7
PS
786 }
787
8571833f
PS
788 if (!is_readable($fullblock.'/version.php')) {
789 throw new plugin_defective_exception('block/'.$blockname, 'Missing version.php file.');
790 }
365a5941 791 $plugin = new stdClass();
bde002b8 792 $plugin->version = null;
8571833f 793 $plugin->cron = 0;
bde002b8 794 $module = $plugin; // Prevent some notices when module placed in wrong directory.
8571833f 795 include($fullblock.'/version.php');
bde002b8
PS
796 unset($module);
797 $block = clone($plugin);
798 unset($block->version);
799 unset($block->component);
800 unset($block->dependencies);
801 unset($block->release);
8571833f 802
98ea6973
DM
803 if (empty($plugin->version)) {
804 throw new plugin_defective_exception($component, 'Missing block version number in version.php.');
3e858ea7
PS
805 }
806
98ea6973
DM
807 if (empty($plugin->component)) {
808 throw new plugin_defective_exception($component, 'Missing $plugin->component declaration in version.php.');
809 }
810
811 if ($plugin->component !== $component) {
812 throw new plugin_misplaced_exception($plugin->component, null, $fullblock);
bde002b8
PS
813 }
814
ef14c1e7
PS
815 if (!empty($plugin->requires)) {
816 if ($plugin->requires > $CFG->version) {
817 throw new upgrade_requires_exception($component, $plugin->version, $CFG->version, $plugin->requires);
818 } else if ($plugin->requires < 2010000000) {
819 throw new plugin_defective_exception($component, 'Plugin is not compatible with Moodle 2.x or later.');
820 }
821 }
822
795a08ad 823 if (!is_readable($fullblock.'/block_'.$blockname.'.php')) {
824 throw new plugin_defective_exception('block/'.$blockname, 'Missing main block class file.');
db9d4a3d 825 }
8571833f 826 include_once($fullblock.'/block_'.$blockname.'.php');
db9d4a3d 827
795a08ad 828 $classname = 'block_'.$blockname;
829
830 if (!class_exists($classname)) {
831 throw new plugin_defective_exception($component, 'Can not load main class.');
832 }
833
b921b6ee 834 $blockobj = new $classname; // This is what we'll be testing
795a08ad 835 $blocktitle = $blockobj->get_title();
836
837 // OK, it's as we all hoped. For further tests, the object will do them itself.
838 if (!$blockobj->_self_test()) {
839 throw new plugin_defective_exception($component, 'Self test failed.');
840 }
841
795a08ad 842 $block->name = $blockname; // The name MUST match the directory
795a08ad 843
bde002b8 844 $installedversion = $DB->get_field('config_plugins', 'value', array('name'=>'version', 'plugin'=>$component)); // No caching!
795a08ad 845
9b683d13 846 if (file_exists($fullblock.'/db/install.php')) {
847 if (get_config('block_'.$blockname, 'installrunning')) {
848 require_once($fullblock.'/db/install.php');
849 $recover_install_function = 'xmldb_block_'.$blockname.'_install_recovery';
850 if (function_exists($recover_install_function)) {
851 $startcallback($component, true, $verbose);
852 $recover_install_function();
853 unset_config('installrunning', 'block_'.$blockname);
854 // Install various components
855 update_capabilities($component);
c6d75bff 856 log_update_descriptions($component);
c976e271 857 external_update_descriptions($component);
9b683d13 858 events_update_definition($component);
309ae892 859 \core\task\manager::reset_scheduled_tasks_for_component($component);
9b683d13 860 message_update_providers($component);
6c0bfb14 861 \core\message\inbound\manager::update_handlers_for_component($component);
de260e0f 862 upgrade_plugin_mnet_functions($component);
9b683d13 863 $endcallback($component, true, $verbose);
864 }
865 }
866 }
867
bde002b8 868 if (empty($installedversion)) { // block not installed yet, so install it
795a08ad 869 $conflictblock = array_search($blocktitle, $blocktitles);
870 if ($conflictblock !== false) {
871 // Duplicate block titles are not allowed, they confuse people
872 // AND PHP's associative arrays ;)
c1ddac83 873 throw new plugin_defective_exception($component, get_string('blocknameconflict', 'error', (object)array('name'=>$block->name, 'conflict'=>$conflictblock)));
795a08ad 874 }
194cdca8 875 $startcallback($component, true, $verbose);
795a08ad 876
877 if (file_exists($fullblock.'/db/install.xml')) {
878 $DB->get_manager()->install_from_xmldb_file($fullblock.'/db/install.xml');
879 }
880 $block->id = $DB->insert_record('block', $block);
bde002b8 881 upgrade_block_savepoint(true, $plugin->version, $block->name, false);
795a08ad 882
883 if (file_exists($fullblock.'/db/install.php')) {
884 require_once($fullblock.'/db/install.php');
9b683d13 885 // Set installation running flag, we need to recover after exception or error
886 set_config('installrunning', 1, 'block_'.$blockname);
0e35ba6f 887 $post_install_function = 'xmldb_block_'.$blockname.'_install';
795a08ad 888 $post_install_function();
9b683d13 889 unset_config('installrunning', 'block_'.$blockname);
795a08ad 890 }
891
892 $blocktitles[$block->name] = $blocktitle;
893
894 // Install various components
895 update_capabilities($component);
c6d75bff 896 log_update_descriptions($component);
c976e271 897 external_update_descriptions($component);
795a08ad 898 events_update_definition($component);
309ae892 899 \core\task\manager::reset_scheduled_tasks_for_component($component);
795a08ad 900 message_update_providers($component);
6c0bfb14 901 \core\message\inbound\manager::update_handlers_for_component($component);
de260e0f 902 upgrade_plugin_mnet_functions($component);
795a08ad 903
194cdca8 904 $endcallback($component, true, $verbose);
795a08ad 905
bde002b8 906 } else if ($installedversion < $plugin->version) {
194cdca8 907 $startcallback($component, false, $verbose);
795a08ad 908
909 if (is_readable($fullblock.'/db/upgrade.php')) {
910 require_once($fullblock.'/db/upgrade.php'); // defines new upgrading function
911 $newupgrade_function = 'xmldb_block_'.$blockname.'_upgrade';
bde002b8 912 $result = $newupgrade_function($installedversion, $block);
795a08ad 913 } else {
914 $result = true;
915 }
916
bde002b8 917 $installedversion = $DB->get_field('config_plugins', 'value', array('name'=>'version', 'plugin'=>$component)); // No caching!
795a08ad 918 $currblock = $DB->get_record('block', array('name'=>$block->name));
bde002b8 919 if ($installedversion < $plugin->version) {
795a08ad 920 // store version if not already there
bde002b8 921 upgrade_block_savepoint($result, $plugin->version, $block->name, false);
795a08ad 922 }
923
924 if ($currblock->cron != $block->cron) {
925 // update cron flag if needed
1fa84543 926 $DB->set_field('block', 'cron', $block->cron, array('id' => $currblock->id));
795a08ad 927 }
928
b921b6ee 929 // Upgrade various components
795a08ad 930 update_capabilities($component);
c6d75bff 931 log_update_descriptions($component);
c976e271 932 external_update_descriptions($component);
17da2e6f 933 events_update_definition($component);
309ae892 934 \core\task\manager::reset_scheduled_tasks_for_component($component);
795a08ad 935 message_update_providers($component);
6c0bfb14 936 \core\message\inbound\manager::update_handlers_for_component($component);
de260e0f 937 upgrade_plugin_mnet_functions($component);
795a08ad 938
194cdca8 939 $endcallback($component, false, $verbose);
795a08ad 940
bde002b8
PS
941 } else if ($installedversion > $plugin->version) {
942 throw new downgrade_exception($component, $installedversion, $plugin->version);
795a08ad 943 }
944 }
945
946
947 // Finally, if we are in the first_install of BLOCKS setup frontpage and admin page blocks
948 if ($first_install) {
795a08ad 949 //Iterate over each course - there should be only site course here now
950 if ($courses = $DB->get_records('course')) {
951 foreach ($courses as $course) {
9d1d606e 952 blocks_add_default_course_blocks($course);
db9d4a3d 953 }
954 }
795a08ad 955
9d1d606e 956 blocks_add_default_system_blocks();
795a08ad 957 }
958}
959
c6d75bff
PS
960
961/**
962 * Log_display description function used during install and upgrade.
963 *
964 * @param string $component name of component (moodle, mod_assignment, etc.)
965 * @return void
966 */
967function log_update_descriptions($component) {
968 global $DB;
969
b0d1d941 970 $defpath = core_component::get_component_directory($component).'/db/log.php';
c6d75bff
PS
971
972 if (!file_exists($defpath)) {
973 $DB->delete_records('log_display', array('component'=>$component));
974 return;
975 }
976
977 // load new info
978 $logs = array();
979 include($defpath);
980 $newlogs = array();
981 foreach ($logs as $log) {
982 $newlogs[$log['module'].'-'.$log['action']] = $log; // kind of unique name
983 }
984 unset($logs);
985 $logs = $newlogs;
986
987 $fields = array('module', 'action', 'mtable', 'field');
988 // update all log fist
989 $dblogs = $DB->get_records('log_display', array('component'=>$component));
990 foreach ($dblogs as $dblog) {
991 $name = $dblog->module.'-'.$dblog->action;
992
993 if (empty($logs[$name])) {
994 $DB->delete_records('log_display', array('id'=>$dblog->id));
995 continue;
996 }
997
998 $log = $logs[$name];
999 unset($logs[$name]);
1000
1001 $update = false;
1002 foreach ($fields as $field) {
1003 if ($dblog->$field != $log[$field]) {
1004 $dblog->$field = $log[$field];
1005 $update = true;
1006 }
1007 }
1008 if ($update) {
1009 $DB->update_record('log_display', $dblog);
1010 }
1011 }
1012 foreach ($logs as $log) {
1013 $dblog = (object)$log;
1014 $dblog->component = $component;
1015 $DB->insert_record('log_display', $dblog);
1016 }
1017}
1018
c976e271 1019/**
1020 * Web service discovery function used during install and upgrade.
1021 * @param string $component name of component (moodle, mod_assignment, etc.)
1022 * @return void
1023 */
1024function external_update_descriptions($component) {
bc81eadb 1025 global $DB, $CFG;
c976e271 1026
b0d1d941 1027 $defpath = core_component::get_component_directory($component).'/db/services.php';
c976e271 1028
1029 if (!file_exists($defpath)) {
bc81eadb 1030 require_once($CFG->dirroot.'/lib/externallib.php');
c976e271 1031 external_delete_descriptions($component);
1032 return;
1033 }
1034
1035 // load new info
1036 $functions = array();
1037 $services = array();
1038 include($defpath);
1039
1040 // update all function fist
1041 $dbfunctions = $DB->get_records('external_functions', array('component'=>$component));
1042 foreach ($dbfunctions as $dbfunction) {
1043 if (empty($functions[$dbfunction->name])) {
1044 $DB->delete_records('external_functions', array('id'=>$dbfunction->id));
1045 // do not delete functions from external_services_functions, beacuse
1046 // we want to notify admins when functions used in custom services disappear
c6d75bff
PS
1047
1048 //TODO: this looks wrong, we have to delete it eventually (skodak)
c976e271 1049 continue;
1050 }
1051
1052 $function = $functions[$dbfunction->name];
1053 unset($functions[$dbfunction->name]);
1054 $function['classpath'] = empty($function['classpath']) ? null : $function['classpath'];
1055
1056 $update = false;
1057 if ($dbfunction->classname != $function['classname']) {
1058 $dbfunction->classname = $function['classname'];
1059 $update = true;
1060 }
1061 if ($dbfunction->methodname != $function['methodname']) {
1062 $dbfunction->methodname = $function['methodname'];
1063 $update = true;
1064 }
1065 if ($dbfunction->classpath != $function['classpath']) {
1066 $dbfunction->classpath = $function['classpath'];
1067 $update = true;
1068 }
12fc8acf 1069 $functioncapabilities = array_key_exists('capabilities', $function)?$function['capabilities']:'';
72f68b51 1070 if ($dbfunction->capabilities != $functioncapabilities) {
1071 $dbfunction->capabilities = $functioncapabilities;
1072 $update = true;
1073 }
c976e271 1074 if ($update) {
1075 $DB->update_record('external_functions', $dbfunction);
1076 }
1077 }
1078 foreach ($functions as $fname => $function) {
365a5941 1079 $dbfunction = new stdClass();
c976e271 1080 $dbfunction->name = $fname;
1081 $dbfunction->classname = $function['classname'];
1082 $dbfunction->methodname = $function['methodname'];
1083 $dbfunction->classpath = empty($function['classpath']) ? null : $function['classpath'];
1084 $dbfunction->component = $component;
12fc8acf 1085 $dbfunction->capabilities = array_key_exists('capabilities', $function)?$function['capabilities']:'';
c976e271 1086 $dbfunction->id = $DB->insert_record('external_functions', $dbfunction);
1087 }
1088 unset($functions);
1089
1090 // now deal with services
1091 $dbservices = $DB->get_records('external_services', array('component'=>$component));
1092 foreach ($dbservices as $dbservice) {
1093 if (empty($services[$dbservice->name])) {
bc81eadb 1094 $DB->delete_records('external_tokens', array('externalserviceid'=>$dbservice->id));
c976e271 1095 $DB->delete_records('external_services_functions', array('externalserviceid'=>$dbservice->id));
1096 $DB->delete_records('external_services_users', array('externalserviceid'=>$dbservice->id));
1097 $DB->delete_records('external_services', array('id'=>$dbservice->id));
1098 continue;
1099 }
1100 $service = $services[$dbservice->name];
1101 unset($services[$dbservice->name]);
1102 $service['enabled'] = empty($service['enabled']) ? 0 : $service['enabled'];
1103 $service['requiredcapability'] = empty($service['requiredcapability']) ? null : $service['requiredcapability'];
1104 $service['restrictedusers'] = !isset($service['restrictedusers']) ? 1 : $service['restrictedusers'];
af03513f 1105 $service['downloadfiles'] = !isset($service['downloadfiles']) ? 0 : $service['downloadfiles'];
106c55fb 1106 $service['uploadfiles'] = !isset($service['uploadfiles']) ? 0 : $service['uploadfiles'];
c1b65883 1107 $service['shortname'] = !isset($service['shortname']) ? null : $service['shortname'];
c976e271 1108
1109 $update = false;
c976e271 1110 if ($dbservice->requiredcapability != $service['requiredcapability']) {
1111 $dbservice->requiredcapability = $service['requiredcapability'];
1112 $update = true;
1113 }
1114 if ($dbservice->restrictedusers != $service['restrictedusers']) {
1115 $dbservice->restrictedusers = $service['restrictedusers'];
1116 $update = true;
1117 }
af03513f
JM
1118 if ($dbservice->downloadfiles != $service['downloadfiles']) {
1119 $dbservice->downloadfiles = $service['downloadfiles'];
1120 $update = true;
1121 }
106c55fb
DW
1122 if ($dbservice->uploadfiles != $service['uploadfiles']) {
1123 $dbservice->uploadfiles = $service['uploadfiles'];
1124 $update = true;
1125 }
c1b65883
JM
1126 //if shortname is not a PARAM_ALPHANUMEXT, fail (tested here for service update and creation)
1127 if (isset($service['shortname']) and
1128 (clean_param($service['shortname'], PARAM_ALPHANUMEXT) != $service['shortname'])) {
1129 throw new moodle_exception('installserviceshortnameerror', 'webservice', '', $service['shortname']);
1130 }
1131 if ($dbservice->shortname != $service['shortname']) {
1132 //check that shortname is unique
1133 if (isset($service['shortname'])) { //we currently accepts multiple shortname == null
1134 $existingservice = $DB->get_record('external_services',
1135 array('shortname' => $service['shortname']));
1136 if (!empty($existingservice)) {
1137 throw new moodle_exception('installexistingserviceshortnameerror', 'webservice', '', $service['shortname']);
1138 }
1139 }
1140 $dbservice->shortname = $service['shortname'];
1141 $update = true;
1142 }
c976e271 1143 if ($update) {
1144 $DB->update_record('external_services', $dbservice);
1145 }
1146
1147 $functions = $DB->get_records('external_services_functions', array('externalserviceid'=>$dbservice->id));
1148 foreach ($functions as $function) {
1149 $key = array_search($function->functionname, $service['functions']);
1150 if ($key === false) {
1151 $DB->delete_records('external_services_functions', array('id'=>$function->id));
1152 } else {
1153 unset($service['functions'][$key]);
1154 }
1155 }
1156 foreach ($service['functions'] as $fname) {
365a5941 1157 $newf = new stdClass();
c976e271 1158 $newf->externalserviceid = $dbservice->id;
1159 $newf->functionname = $fname;
1160 $DB->insert_record('external_services_functions', $newf);
1161 }
1162 unset($functions);
1163 }
1164 foreach ($services as $name => $service) {
c1b65883
JM
1165 //check that shortname is unique
1166 if (isset($service['shortname'])) { //we currently accepts multiple shortname == null
1167 $existingservice = $DB->get_record('external_services',
1168 array('shortname' => $service['shortname']));
1169 if (!empty($existingservice)) {
1170 throw new moodle_exception('installserviceshortnameerror', 'webservice');
1171 }
1172 }
1173
365a5941 1174 $dbservice = new stdClass();
c976e271 1175 $dbservice->name = $name;
1176 $dbservice->enabled = empty($service['enabled']) ? 0 : $service['enabled'];
1177 $dbservice->requiredcapability = empty($service['requiredcapability']) ? null : $service['requiredcapability'];
1178 $dbservice->restrictedusers = !isset($service['restrictedusers']) ? 1 : $service['restrictedusers'];
af03513f 1179 $dbservice->downloadfiles = !isset($service['downloadfiles']) ? 0 : $service['downloadfiles'];
106c55fb 1180 $dbservice->uploadfiles = !isset($service['uploadfiles']) ? 0 : $service['uploadfiles'];
c1b65883 1181 $dbservice->shortname = !isset($service['shortname']) ? null : $service['shortname'];
c976e271 1182 $dbservice->component = $component;
e5180580 1183 $dbservice->timecreated = time();
c976e271 1184 $dbservice->id = $DB->insert_record('external_services', $dbservice);
1185 foreach ($service['functions'] as $fname) {
365a5941 1186 $newf = new stdClass();
c976e271 1187 $newf->externalserviceid = $dbservice->id;
1188 $newf->functionname = $fname;
1189 $DB->insert_record('external_services_functions', $newf);
1190 }
1191 }
1192}
1193
72fb21b6 1194/**
1195 * upgrade logging functions
72fb21b6 1196 */
fd1a792e 1197function upgrade_handle_exception($ex, $plugin = null) {
96e1fdf4
PS
1198 global $CFG;
1199
a56c457e
PS
1200 // rollback everything, we need to log all upgrade problems
1201 abort_all_db_transactions();
1202
c19bc39c
PS
1203 $info = get_exception_info($ex);
1204
1205 // First log upgrade error
1206 upgrade_log(UPGRADE_LOG_ERROR, $plugin, 'Exception: ' . get_class($ex), $info->message, $info->backtrace);
1207
1208 // Always turn on debugging - admins need to know what is going on
96f81ea3 1209 set_debugging(DEBUG_DEVELOPER, true);
c19bc39c 1210
fd1a792e 1211 default_exception_handler($ex, true, $plugin);
db9d4a3d 1212}
1213
1214/**
1215 * Adds log entry into upgrade_log table
1216 *
1217 * @param int $type UPGRADE_LOG_NORMAL, UPGRADE_LOG_NOTICE or UPGRADE_LOG_ERROR
bb8b2971 1218 * @param string $plugin frankenstyle component name
db9d4a3d 1219 * @param string $info short description text of log entry
1220 * @param string $details long problem description
1221 * @param string $backtrace string used for errors only
1222 * @return void
1223 */
1224function upgrade_log($type, $plugin, $info, $details=null, $backtrace=null) {
1225 global $DB, $USER, $CFG;
1226
bb8b2971
PS
1227 if (empty($plugin)) {
1228 $plugin = 'core';
1229 }
1230
56da374e 1231 list($plugintype, $pluginname) = core_component::normalize_component($plugin);
bb8b2971 1232 $component = is_null($pluginname) ? $plugintype : $plugintype . '_' . $pluginname;
795a08ad 1233
34a2777c 1234 $backtrace = format_backtrace($backtrace, true);
db9d4a3d 1235
bb8b2971
PS
1236 $currentversion = null;
1237 $targetversion = null;
db9d4a3d 1238
1239 //first try to find out current version number
bb8b2971 1240 if ($plugintype === 'core') {
db9d4a3d 1241 //main
bb8b2971 1242 $currentversion = $CFG->version;
db9d4a3d 1243
bb8b2971
PS
1244 $version = null;
1245 include("$CFG->dirroot/version.php");
1246 $targetversion = $version;
795a08ad 1247
795a08ad 1248 } else {
bb8b2971 1249 $pluginversion = get_config($component, 'version');
795a08ad 1250 if (!empty($pluginversion)) {
bb8b2971
PS
1251 $currentversion = $pluginversion;
1252 }
b0d1d941 1253 $cd = core_component::get_component_directory($component);
bb8b2971
PS
1254 if (file_exists("$cd/version.php")) {
1255 $plugin = new stdClass();
1256 $plugin->version = null;
bde002b8 1257 $module = $plugin;
bb8b2971
PS
1258 include("$cd/version.php");
1259 $targetversion = $plugin->version;
795a08ad 1260 }
db9d4a3d 1261 }
1262
365a5941 1263 $log = new stdClass();
bb8b2971
PS
1264 $log->type = $type;
1265 $log->plugin = $component;
1266 $log->version = $currentversion;
1267 $log->targetversion = $targetversion;
1268 $log->info = $info;
1269 $log->details = $details;
1270 $log->backtrace = $backtrace;
1271 $log->userid = $USER->id;
1272 $log->timemodified = time();
db9d4a3d 1273 try {
1274 $DB->insert_record('upgrade_log', $log);
1275 } catch (Exception $ignored) {
795a08ad 1276 // possible during install or 2.0 upgrade
db9d4a3d 1277 }
1278}
1279
1280/**
1281 * Marks start of upgrade, blocks any other access to site.
1282 * The upgrade is finished at the end of script or after timeout.
72fb21b6 1283 *
1284 * @global object
1285 * @global object
1286 * @global object
db9d4a3d 1287 */
1288function upgrade_started($preinstall=false) {
de6d81e6 1289 global $CFG, $DB, $PAGE, $OUTPUT;
db9d4a3d 1290
1291 static $started = false;
1292
1293 if ($preinstall) {
1294 ignore_user_abort(true);
1295 upgrade_setup_debug(true);
1296
1297 } else if ($started) {
1298 upgrade_set_timeout(120);
1299
1300 } else {
c13a5e71 1301 if (!CLI_SCRIPT and !$PAGE->headerprinted) {
db9d4a3d 1302 $strupgrade = get_string('upgradingversion', 'admin');
78946b9b 1303 $PAGE->set_pagelayout('maintenance');
543f54d3 1304 upgrade_init_javascript();
de6d81e6 1305 $PAGE->set_title($strupgrade.' - Moodle '.$CFG->target_release);
1306 $PAGE->set_heading($strupgrade);
1307 $PAGE->navbar->add($strupgrade);
1308 $PAGE->set_cacheable(false);
1309 echo $OUTPUT->header();
db9d4a3d 1310 }
1311
1312 ignore_user_abort(true);
38fc0130 1313 core_shutdown_manager::register_function('upgrade_finished_handler');
db9d4a3d 1314 upgrade_setup_debug(true);
1315 set_config('upgraderunning', time()+300);
1316 $started = true;
1317 }
1318}
1319
1320/**
b921b6ee 1321 * Internal function - executed if upgrade interrupted.
db9d4a3d 1322 */
1323function upgrade_finished_handler() {
1324 upgrade_finished();
1325}
1326
1327/**
1328 * Indicates upgrade is finished.
1329 *
1330 * This function may be called repeatedly.
72fb21b6 1331 *
1332 * @global object
1333 * @global object
db9d4a3d 1334 */
1335function upgrade_finished($continueurl=null) {
7e0d6675 1336 global $CFG, $DB, $OUTPUT;
db9d4a3d 1337
1338 if (!empty($CFG->upgraderunning)) {
1339 unset_config('upgraderunning');
24dedb96
SH
1340 // We have to forcefully purge the caches using the writer here.
1341 // This has to be done after we unset the config var. If someone hits the site while this is set they will
1342 // cause the config values to propogate to the caches.
1343 // Caches are purged after the last step in an upgrade but there is several code routines that exceute between
1344 // then and now that leaving a window for things to fall out of sync.
1345 cache_helper::purge_all(true);
db9d4a3d 1346 upgrade_setup_debug(false);
1347 ignore_user_abort(false);
1348 if ($continueurl) {
aa9a6867 1349 echo $OUTPUT->continue_button($continueurl);
7e0d6675 1350 echo $OUTPUT->footer();
db9d4a3d 1351 die;
1352 }
1353 }
1354}
1355
72fb21b6 1356/**
1357 * @global object
1358 * @global object
1359 */
db9d4a3d 1360function upgrade_setup_debug($starting) {
1361 global $CFG, $DB;
1362
1363 static $originaldebug = null;
1364
1365 if ($starting) {
1366 if ($originaldebug === null) {
1367 $originaldebug = $DB->get_debug();
1368 }
1369 if (!empty($CFG->upgradeshowsql)) {
1370 $DB->set_debug(true);
1371 }
1372 } else {
1373 $DB->set_debug($originaldebug);
1374 }
1375}
1376
1377function print_upgrade_separator() {
1378 if (!CLI_SCRIPT) {
1379 echo '<hr />';
1380 }
1381}
1382
795a08ad 1383/**
1384 * Default start upgrade callback
1385 * @param string $plugin
b921b6ee 1386 * @param bool $installation true if installation, false means upgrade
795a08ad 1387 */
194cdca8 1388function print_upgrade_part_start($plugin, $installation, $verbose) {
3c159385 1389 global $OUTPUT;
795a08ad 1390 if (empty($plugin) or $plugin == 'moodle') {
1391 upgrade_started($installation); // does not store upgrade running flag yet
194cdca8 1392 if ($verbose) {
3c159385 1393 echo $OUTPUT->heading(get_string('coresystem'));
194cdca8 1394 }
795a08ad 1395 } else {
1396 upgrade_started();
194cdca8 1397 if ($verbose) {
3c159385 1398 echo $OUTPUT->heading($plugin);
194cdca8 1399 }
795a08ad 1400 }
1401 if ($installation) {
1402 if (empty($plugin) or $plugin == 'moodle') {
1403 // no need to log - log table not yet there ;-)
1404 } else {
1405 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Starting plugin installation');
1406 }
1407 } else {
1408 if (empty($plugin) or $plugin == 'moodle') {
1409 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Starting core upgrade');
1410 } else {
1411 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Starting plugin upgrade');
1412 }
1413 }
1414}
1415
1416/**
1417 * Default end upgrade callback
1418 * @param string $plugin
b921b6ee 1419 * @param bool $installation true if installation, false means upgrade
795a08ad 1420 */
194cdca8 1421function print_upgrade_part_end($plugin, $installation, $verbose) {
aa9a6867 1422 global $OUTPUT;
795a08ad 1423 upgrade_started();
1424 if ($installation) {
1425 if (empty($plugin) or $plugin == 'moodle') {
1426 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Core installed');
1427 } else {
1428 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Plugin installed');
1429 }
1430 } else {
1431 if (empty($plugin) or $plugin == 'moodle') {
1432 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Core upgraded');
1433 } else {
1434 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Plugin upgraded');
1435 }
1436 }
194cdca8 1437 if ($verbose) {
aa9a6867 1438 echo $OUTPUT->notification(get_string('success'), 'notifysuccess');
194cdca8 1439 print_upgrade_separator();
96db14f9 1440 }
1441}
1442
72fb21b6 1443/**
b921b6ee 1444 * Sets up JS code required for all upgrade scripts.
72fb21b6 1445 * @global object
1446 */
543f54d3 1447function upgrade_init_javascript() {
e29380f3 1448 global $PAGE;
543f54d3
PS
1449 // scroll to the end of each upgrade page so that ppl see either error or continue button,
1450 // no need to scroll continuously any more, it is enough to jump to end once the footer is printed ;-)
1451 $js = "window.scrollTo(0, 5000000);";
1452 $PAGE->requires->js_init_code($js);
db9d4a3d 1453}
1454
db9d4a3d 1455/**
1456 * Try to upgrade the given language pack (or current language)
af8d4d91 1457 *
74a4c9a9 1458 * @param string $lang the code of the language to update, defaults to the current language
db9d4a3d 1459 */
bd41bdd9
PS
1460function upgrade_language_pack($lang = null) {
1461 global $CFG;
db9d4a3d 1462
bd41bdd9
PS
1463 if (!empty($CFG->skiplangupgrade)) {
1464 return;
1465 }
af8d4d91 1466
bd41bdd9
PS
1467 if (!file_exists("$CFG->dirroot/$CFG->admin/tool/langimport/lib.php")) {
1468 // weird, somebody uninstalled the import utility
1469 return;
1470 }
1471
1472 if (!$lang) {
db9d4a3d 1473 $lang = current_language();
1474 }
1475
bd41bdd9
PS
1476 if (!get_string_manager()->translation_exists($lang)) {
1477 return;
db9d4a3d 1478 }
1479
bd41bdd9
PS
1480 get_string_manager()->reset_caches();
1481
1482 if ($lang === 'en') {
1483 return; // Nothing to do
db9d4a3d 1484 }
af8d4d91 1485
bd41bdd9
PS
1486 upgrade_started(false);
1487
1488 require_once("$CFG->dirroot/$CFG->admin/tool/langimport/lib.php");
1489 tool_langimport_preupgrade_update($lang);
1490
af8d4d91
DM
1491 get_string_manager()->reset_caches();
1492
551fe0e5 1493 print_upgrade_separator();
db9d4a3d 1494}
8580535b 1495
1496/**
1497 * Install core moodle tables and initialize
1498 * @param float $version target version
1499 * @param bool $verbose
1500 * @return void, may throw exception
1501 */
1502function install_core($version, $verbose) {
1503 global $CFG, $DB;
1504
e2e35e71 1505 // We can not call purge_all_caches() yet, make sure the temp and cache dirs exist and are empty.
e2e35e71 1506 remove_dir($CFG->cachedir.'', true);
85b38061
PS
1507 make_cache_directory('', true);
1508
1509 remove_dir($CFG->localcachedir.'', true);
1510 make_localcache_directory('', true);
1511
e2e35e71 1512 remove_dir($CFG->tempdir.'', true);
85b38061
PS
1513 make_temp_directory('', true);
1514
e2e35e71 1515 remove_dir($CFG->dataroot.'/muc', true);
85b38061 1516 make_writable_directory($CFG->dataroot.'/muc', true);
e2e35e71 1517
8580535b 1518 try {
3ef7279f 1519 core_php_time_limit::raise(600);
194cdca8 1520 print_upgrade_part_start('moodle', true, $verbose); // does not store upgrade running flag
8580535b 1521
1522 $DB->get_manager()->install_from_xmldb_file("$CFG->libdir/db/install.xml");
1523 upgrade_started(); // we want the flag to be stored in config table ;-)
1524
1525 // set all core default records and default settings
1526 require_once("$CFG->libdir/db/install.php");
c6d75bff 1527 xmldb_main_install(); // installs the capabilities too
8580535b 1528
1529 // store version
1530 upgrade_main_savepoint(true, $version, false);
1531
df997f84 1532 // Continue with the installation
c6d75bff
PS
1533 log_update_descriptions('moodle');
1534 external_update_descriptions('moodle');
8580535b 1535 events_update_definition('moodle');
309ae892 1536 \core\task\manager::reset_scheduled_tasks_for_component('moodle');
8580535b 1537 message_update_providers('moodle');
6c0bfb14 1538 \core\message\inbound\manager::update_handlers_for_component('moodle');
8580535b 1539
df997f84 1540 // Write default settings unconditionally
8580535b 1541 admin_apply_default_settings(NULL, true);
1542
194cdca8 1543 print_upgrade_part_end(null, true, $verbose);
94ef67cf 1544
e0d9b7c0
SH
1545 // Purge all caches. They're disabled but this ensures that we don't have any persistent data just in case something
1546 // during installation didn't use APIs.
1547 cache_helper::purge_all();
8580535b 1548 } catch (exception $ex) {
1549 upgrade_handle_exception($ex);
1550 }
1551}
1552
1553/**
1554 * Upgrade moodle core
1555 * @param float $version target version
1556 * @param bool $verbose
1557 * @return void, may throw exception
1558 */
1559function upgrade_core($version, $verbose) {
e2049782 1560 global $CFG, $SITE, $DB, $COURSE;
8580535b 1561
41209c1e
PS
1562 raise_memory_limit(MEMORY_EXTRA);
1563
3316fe24 1564 require_once($CFG->libdir.'/db/upgrade.php'); // Defines upgrades
3316fe24 1565
8580535b 1566 try {
7b4d5af7 1567 // Reset caches before any output.
b0dd08dd 1568 cache_helper::purge_all(true);
7b4d5af7 1569 purge_all_caches();
dcf9be7f 1570
8580535b 1571 // Upgrade current language pack if we can
bd41bdd9 1572 upgrade_language_pack();
8580535b 1573
194cdca8 1574 print_upgrade_part_start('moodle', false, $verbose);
8580535b 1575
6b4b7490
PS
1576 // Pre-upgrade scripts for local hack workarounds.
1577 $preupgradefile = "$CFG->dirroot/local/preupgrade.php";
1578 if (file_exists($preupgradefile)) {
3ef7279f 1579 core_php_time_limit::raise();
6b4b7490
PS
1580 require($preupgradefile);
1581 // Reset upgrade timeout to default.
1582 upgrade_set_timeout();
17da2e6f 1583 }
1584
8580535b 1585 $result = xmldb_main_upgrade($CFG->version);
1586 if ($version > $CFG->version) {
1587 // store version if not already there
1588 upgrade_main_savepoint($result, $version, false);
1589 }
1590
e2049782
MG
1591 // In case structure of 'course' table has been changed and we forgot to update $SITE, re-read it from db.
1592 $SITE = $DB->get_record('course', array('id' => $SITE->id));
1593 $COURSE = clone($SITE);
1594
8580535b 1595 // perform all other component upgrade routines
1596 update_capabilities('moodle');
c6d75bff 1597 log_update_descriptions('moodle');
c976e271 1598 external_update_descriptions('moodle');
8580535b 1599 events_update_definition('moodle');
309ae892 1600 \core\task\manager::reset_scheduled_tasks_for_component('moodle');
8580535b 1601 message_update_providers('moodle');
6c0bfb14 1602 \core\message\inbound\manager::update_handlers_for_component('moodle');
75af47ee
SH
1603 // Update core definitions.
1604 cache_helper::update_definitions(true);
8580535b 1605
94ef67cf 1606 // Purge caches again, just to be sure we arn't holding onto old stuff now.
a5a6e93f 1607 cache_helper::purge_all(true);
7b4d5af7 1608 purge_all_caches();
2e5eba85
PS
1609
1610 // Clean up contexts - more and more stuff depends on existence of paths and contexts
e922fe23
PS
1611 context_helper::cleanup_instances();
1612 context_helper::create_instances(null, false);
1613 context_helper::build_all_paths(false);
1614 $syscontext = context_system::instance();
1615 $syscontext->mark_dirty();
8580535b 1616
194cdca8 1617 print_upgrade_part_end('moodle', false, $verbose);
8580535b 1618 } catch (Exception $ex) {
1619 upgrade_handle_exception($ex);
1620 }
1621}
1622
1623/**
1624 * Upgrade/install other parts of moodle
1625 * @param bool $verbose
1626 * @return void, may throw exception
1627 */
1628function upgrade_noncore($verbose) {
1629 global $CFG;
1630
41209c1e
PS
1631 raise_memory_limit(MEMORY_EXTRA);
1632
8580535b 1633 // upgrade all plugins types
1634 try {
7b4d5af7
PS
1635 // Reset caches before any output.
1636 cache_helper::purge_all(true);
1637 purge_all_caches();
1638
46f6f7f2 1639 $plugintypes = core_component::get_plugin_types();
8580535b 1640 foreach ($plugintypes as $type=>$location) {
17da2e6f 1641 upgrade_plugins($type, 'print_upgrade_part_start', 'print_upgrade_part_end', $verbose);
8580535b 1642 }
94ef67cf 1643 // Update cache definitions. Involves scanning each plugin for any changes.
75af47ee 1644 cache_helper::update_definitions();
c5701ce7
PS
1645 // Mark the site as upgraded.
1646 set_config('allversionshash', core_component::get_all_versions_hash());
7b4d5af7
PS
1647
1648 // Purge caches again, just to be sure we arn't holding onto old stuff now.
1649 cache_helper::purge_all(true);
1650 purge_all_caches();
1651
8580535b 1652 } catch (Exception $ex) {
1653 upgrade_handle_exception($ex);
1654 }
8580535b 1655}
3316fe24 1656
1657/**
1658 * Checks if the main tables have been installed yet or not.
e2e35e71
PS
1659 *
1660 * Note: we can not use caches here because they might be stale,
1661 * use with care!
1662 *
3316fe24 1663 * @return bool
1664 */
1665function core_tables_exist() {
1666 global $DB;
1667
e2e35e71 1668 if (!$tables = $DB->get_tables(false) ) { // No tables yet at all.
3316fe24 1669 return false;
9b683d13 1670
3316fe24 1671 } else { // Check for missing main tables
1672 $mtables = array('config', 'course', 'groupings'); // some tables used in 1.9 and 2.0, preferable something from the start and end of install.xml
1673 foreach ($mtables as $mtable) {
1674 if (!in_array($mtable, $tables)) {
1675 return false;
1676 }
1677 }
1678 return true;
9b683d13 1679 }
ba04999c 1680}
c71ade2f
PL
1681
1682/**
1683 * upgrades the mnet rpc definitions for the given component.
1684 * this method doesn't return status, an exception will be thrown in the case of an error
1685 *
1686 * @param string $component the plugin to upgrade, eg auth_mnet
1687 */
1688function upgrade_plugin_mnet_functions($component) {
1689 global $DB, $CFG;
1690
8c59114f 1691 list($type, $plugin) = core_component::normalize_component($component);
1c74b260 1692 $path = core_component::get_plugin_directory($type, $plugin);
c71ade2f 1693
17b71716
PS
1694 $publishes = array();
1695 $subscribes = array();
c71ade2f
PL
1696 if (file_exists($path . '/db/mnet.php')) {
1697 require_once($path . '/db/mnet.php'); // $publishes comes from this file
1698 }
1699 if (empty($publishes)) {
1700 $publishes = array(); // still need this to be able to disable stuff later
1701 }
1702 if (empty($subscribes)) {
1703 $subscribes = array(); // still need this to be able to disable stuff later
1704 }
1705
1706 static $servicecache = array();
1707
1708 // rekey an array based on the rpc method for easy lookups later
1709 $publishmethodservices = array();
1710 $subscribemethodservices = array();
1711 foreach($publishes as $servicename => $service) {
1712 if (is_array($service['methods'])) {
1713 foreach($service['methods'] as $methodname) {
1714 $service['servicename'] = $servicename;
1715 $publishmethodservices[$methodname][] = $service;
1716 }
1717 }
1718 }
1719
1720 // Disable functions that don't exist (any more) in the source
1721 // Should these be deleted? What about their permissions records?
1722 foreach ($DB->get_records('mnet_rpc', array('pluginname'=>$plugin, 'plugintype'=>$type), 'functionname ASC ') as $rpc) {
1723 if (!array_key_exists($rpc->functionname, $publishmethodservices) && $rpc->enabled) {
1724 $DB->set_field('mnet_rpc', 'enabled', 0, array('id' => $rpc->id));
1725 } else if (array_key_exists($rpc->functionname, $publishmethodservices) && !$rpc->enabled) {
1726 $DB->set_field('mnet_rpc', 'enabled', 1, array('id' => $rpc->id));
1727 }
1728 }
1729
1730 // reflect all the services we're publishing and save them
1731 require_once($CFG->dirroot . '/lib/zend/Zend/Server/Reflection.php');
1732 static $cachedclasses = array(); // to store reflection information in
1733 foreach ($publishes as $service => $data) {
1734 $f = $data['filename'];
1735 $c = $data['classname'];
1736 foreach ($data['methods'] as $method) {
6bdfef5d 1737 $dataobject = new stdClass();
c71ade2f
PL
1738 $dataobject->plugintype = $type;
1739 $dataobject->pluginname = $plugin;
1740 $dataobject->enabled = 1;
1741 $dataobject->classname = $c;
1742 $dataobject->filename = $f;
1743
1744 if (is_string($method)) {
1745 $dataobject->functionname = $method;
1746
1747 } else if (is_array($method)) { // wants to override file or class
1748 $dataobject->functionname = $method['method'];
1749 $dataobject->classname = $method['classname'];
1750 $dataobject->filename = $method['filename'];
1751 }
1752 $dataobject->xmlrpcpath = $type.'/'.$plugin.'/'.$dataobject->filename.'/'.$method;
1753 $dataobject->static = false;
1754
1755 require_once($path . '/' . $dataobject->filename);
1756 $functionreflect = null; // slightly different ways to get this depending on whether it's a class method or a function
1757 if (!empty($dataobject->classname)) {
1758 if (!class_exists($dataobject->classname)) {
1759 throw new moodle_exception('installnosuchmethod', 'mnet', '', (object)array('method' => $dataobject->functionname, 'class' => $dataobject->classname));
1760 }
1761 $key = $dataobject->filename . '|' . $dataobject->classname;
1762 if (!array_key_exists($key, $cachedclasses)) { // look to see if we've already got a reflection object
1763 try {
1764 $cachedclasses[$key] = Zend_Server_Reflection::reflectClass($dataobject->classname);
1765 } catch (Zend_Server_Reflection_Exception $e) { // catch these and rethrow them to something more helpful
1766 throw new moodle_exception('installreflectionclasserror', 'mnet', '', (object)array('method' => $dataobject->functionname, 'class' => $dataobject->classname, 'error' => $e->getMessage()));
1767 }
1768 }
1769 $r =& $cachedclasses[$key];
1770 if (!$r->hasMethod($dataobject->functionname)) {
1771 throw new moodle_exception('installnosuchmethod', 'mnet', '', (object)array('method' => $dataobject->functionname, 'class' => $dataobject->classname));
1772 }
1773 // stupid workaround for zend not having a getMethod($name) function
1774 $ms = $r->getMethods();
1775 foreach ($ms as $m) {
1776 if ($m->getName() == $dataobject->functionname) {
1777 $functionreflect = $m;
1778 break;
1779 }
1780 }
1781 $dataobject->static = (int)$functionreflect->isStatic();
1782 } else {
1783 if (!function_exists($dataobject->functionname)) {
1784 throw new moodle_exception('installnosuchfunction', 'mnet', '', (object)array('method' => $dataobject->functionname, 'file' => $dataobject->filename));
1785 }
1786 try {
1787 $functionreflect = Zend_Server_Reflection::reflectFunction($dataobject->functionname);
1788 } catch (Zend_Server_Reflection_Exception $e) { // catch these and rethrow them to something more helpful
1789 throw new moodle_exception('installreflectionfunctionerror', 'mnet', '', (object)array('method' => $dataobject->functionname, '' => $dataobject->filename, 'error' => $e->getMessage()));
1790 }
1791 }
1792 $dataobject->profile = serialize(admin_mnet_method_profile($functionreflect));
1793 $dataobject->help = $functionreflect->getDescription();
1794
1795 if ($record_exists = $DB->get_record('mnet_rpc', array('xmlrpcpath'=>$dataobject->xmlrpcpath))) {
1796 $dataobject->id = $record_exists->id;
1797 $dataobject->enabled = $record_exists->enabled;
1798 $DB->update_record('mnet_rpc', $dataobject);
1799 } else {
1800 $dataobject->id = $DB->insert_record('mnet_rpc', $dataobject, true);
1801 }
c71ade2f 1802
d5bd0b01
DM
1803 // TODO this API versioning must be reworked, here the recently processed method
1804 // sets the service API which may not be correct
677b6321
PL
1805 foreach ($publishmethodservices[$dataobject->functionname] as $service) {
1806 if ($serviceobj = $DB->get_record('mnet_service', array('name'=>$service['servicename']))) {
1807 $serviceobj->apiversion = $service['apiversion'];
1808 $DB->update_record('mnet_service', $serviceobj);
1809 } else {
1810 $serviceobj = new stdClass();
1811 $serviceobj->name = $service['servicename'];
f4a2817a 1812 $serviceobj->description = empty($service['description']) ? '' : $service['description'];
677b6321
PL
1813 $serviceobj->apiversion = $service['apiversion'];
1814 $serviceobj->offer = 1;
1815 $serviceobj->id = $DB->insert_record('mnet_service', $serviceobj);
1816 }
1817 $servicecache[$service['servicename']] = $serviceobj;
1818 if (!$DB->record_exists('mnet_service2rpc', array('rpcid'=>$dataobject->id, 'serviceid'=>$serviceobj->id))) {
1819 $obj = new stdClass();
1820 $obj->rpcid = $dataobject->id;
1821 $obj->serviceid = $serviceobj->id;
1822 $DB->insert_record('mnet_service2rpc', $obj, true);
1823 }
c71ade2f
PL
1824 }
1825 }
1826 }
c71ade2f
PL
1827 // finished with methods we publish, now do subscribable methods
1828 foreach($subscribes as $service => $methods) {
1829 if (!array_key_exists($service, $servicecache)) {
1830 if (!$serviceobj = $DB->get_record('mnet_service', array('name' => $service))) {
81634f03 1831 debugging("TODO: skipping unknown service $service - somebody needs to fix MDL-21993");
c71ade2f
PL
1832 continue;
1833 }
1834 $servicecache[$service] = $serviceobj;
1835 } else {
1836 $serviceobj = $servicecache[$service];
1837 }
1838 foreach ($methods as $method => $xmlrpcpath) {
1839 if (!$rpcid = $DB->get_field('mnet_remote_rpc', 'id', array('xmlrpcpath'=>$xmlrpcpath))) {
1840 $remoterpc = (object)array(
1841 'functionname' => $method,
1842 'xmlrpcpath' => $xmlrpcpath,
1843 'plugintype' => $type,
1844 'pluginname' => $plugin,
1845 'enabled' => 1,
1846 );
1847 $rpcid = $remoterpc->id = $DB->insert_record('mnet_remote_rpc', $remoterpc, true);
1848 }
1849 if (!$DB->record_exists('mnet_remote_service2rpc', array('rpcid'=>$rpcid, 'serviceid'=>$serviceobj->id))) {
1850 $obj = new stdClass();
1851 $obj->rpcid = $rpcid;
1852 $obj->serviceid = $serviceobj->id;
1853 $DB->insert_record('mnet_remote_service2rpc', $obj, true);
1854 }
677b6321 1855 $subscribemethodservices[$method][] = $service;
c71ade2f
PL
1856 }
1857 }
1858
1859 foreach ($DB->get_records('mnet_remote_rpc', array('pluginname'=>$plugin, 'plugintype'=>$type), 'functionname ASC ') as $rpc) {
1860 if (!array_key_exists($rpc->functionname, $subscribemethodservices) && $rpc->enabled) {
1861 $DB->set_field('mnet_remote_rpc', 'enabled', 0, array('id' => $rpc->id));
1862 } else if (array_key_exists($rpc->functionname, $subscribemethodservices) && !$rpc->enabled) {
1863 $DB->set_field('mnet_remote_rpc', 'enabled', 1, array('id' => $rpc->id));
1864 }
1865 }
1866
1867 return true;
1868}
1869
1870/**
1871 * Given some sort of Zend Reflection function/method object, return a profile array, ready to be serialized and stored
1872 *
1873 * @param Zend_Server_Reflection_Function_Abstract $function can be any subclass of this object type
1874 *
1875 * @return array
1876 */
1877function admin_mnet_method_profile(Zend_Server_Reflection_Function_Abstract $function) {
f20edd52
PS
1878 $protos = $function->getPrototypes();
1879 $proto = array_pop($protos);
c71ade2f
PL
1880 $ret = $proto->getReturnValue();
1881 $profile = array(
1882 'parameters' => array(),
1883 'return' => array(
1884 'type' => $ret->getType(),
1885 'description' => $ret->getDescription(),
1886 ),
1887 );
1888 foreach ($proto->getParameters() as $p) {
1889 $profile['parameters'][] = array(
1890 'name' => $p->getName(),
1891 'type' => $p->getType(),
1892 'description' => $p->getDescription(),
1893 );
1894 }
1895 return $profile;
1896}
424a19b1
AB
1897
1898
1899/**
1900 * This function finds duplicate records (based on combinations of fields that should be unique)
1901 * and then progamatically generated a "most correct" version of the data, update and removing
1902 * records as appropriate
1903 *
1904 * Thanks to Dan Marsden for help
1905 *
1906 * @param string $table Table name
1907 * @param array $uniques Array of field names that should be unique
e6f55285 1908 * @param array $fieldstocheck Array of fields to generate "correct" data from (optional)
424a19b1
AB
1909 * @return void
1910 */
1911function upgrade_course_completion_remove_duplicates($table, $uniques, $fieldstocheck = array()) {
1912 global $DB;
1913
1914 // Find duplicates
1915 $sql_cols = implode(', ', $uniques);
1916
1917 $sql = "SELECT {$sql_cols} FROM {{$table}} GROUP BY {$sql_cols} HAVING (count(id) > 1)";
1918 $duplicates = $DB->get_recordset_sql($sql, array());
1919
1920 // Loop through duplicates
1921 foreach ($duplicates as $duplicate) {
1922 $pointer = 0;
1923
1924 // Generate SQL for finding records with these duplicate uniques
e6f55285 1925 $sql_select = implode(' = ? AND ', $uniques).' = ?'; // builds "fieldname = ? AND fieldname = ?"
424a19b1
AB
1926 $uniq_values = array();
1927 foreach ($uniques as $u) {
1928 $uniq_values[] = $duplicate->$u;
1929 }
1930
1931 $sql_order = implode(' DESC, ', $uniques).' DESC'; // builds "fieldname DESC, fieldname DESC"
1932
1933 // Get records with these duplicate uniques
1934 $records = $DB->get_records_select(
1935 $table,
1936 $sql_select,
1937 $uniq_values,
1938 $sql_order
1939 );
1940
1941 // Loop through and build a "correct" record, deleting the others
1942 $needsupdate = false;
1943 $origrecord = null;
1944 foreach ($records as $record) {
1945 $pointer++;
1946 if ($pointer === 1) { // keep 1st record but delete all others.
1947 $origrecord = $record;
1948 } else {
1949 // If we have fields to check, update original record
1950 if ($fieldstocheck) {
1951 // we need to keep the "oldest" of all these fields as the valid completion record.
1952 // but we want to ignore null values
1953 foreach ($fieldstocheck as $f) {
1954 if ($record->$f && (($origrecord->$f > $record->$f) || !$origrecord->$f)) {
1955 $origrecord->$f = $record->$f;
1956 $needsupdate = true;
1957 }
1958 }
1959 }
1960 $DB->delete_records($table, array('id' => $record->id));
1961 }
1962 }
1963 if ($needsupdate || isset($origrecord->reaggregate)) {
e6f55285 1964 // If this table has a reaggregate field, update to force recheck on next cron run
424a19b1
AB
1965 if (isset($origrecord->reaggregate)) {
1966 $origrecord->reaggregate = time();
1967 }
1968 $DB->update_record($table, $origrecord);
1969 }
1970 }
1971}
67e3dd2c
FM
1972
1973/**
1974 * Find questions missing an existing category and associate them with
1975 * a category which purpose is to gather them.
1976 *
1977 * @return void
1978 */
1979function upgrade_save_orphaned_questions() {
1980 global $DB;
1981
1982 // Looking for orphaned questions
1983 $orphans = $DB->record_exists_select('question',
1984 'NOT EXISTS (SELECT 1 FROM {question_categories} WHERE {question_categories}.id = {question}.category)');
1985 if (!$orphans) {
1986 return;
1987 }
1988
1989 // Generate a unique stamp for the orphaned questions category, easier to identify it later on
1990 $uniquestamp = "unknownhost+120719170400+orphan";
1991 $systemcontext = context_system::instance();
1992
1993 // Create the orphaned category at system level
1994 $cat = $DB->get_record('question_categories', array('stamp' => $uniquestamp,
1995 'contextid' => $systemcontext->id));
1996 if (!$cat) {
1997 $cat = new stdClass();
1998 $cat->parent = 0;
1999 $cat->contextid = $systemcontext->id;
2000 $cat->name = get_string('orphanedquestionscategory', 'question');
2001 $cat->info = get_string('orphanedquestionscategoryinfo', 'question');
2002 $cat->sortorder = 999;
2003 $cat->stamp = $uniquestamp;
2004 $cat->id = $DB->insert_record("question_categories", $cat);
2005 }
2006
2007 // Set a category to those orphans
2008 $params = array('catid' => $cat->id);
2009 $DB->execute('UPDATE {question} SET category = :catid WHERE NOT EXISTS
2010 (SELECT 1 FROM {question_categories} WHERE {question_categories}.id = {question}.category)', $params);
2011}
2012
d8271e39
FM
2013/**
2014 * Rename old backup files to current backup files.
2015 *
2016 * When added the setting 'backup_shortname' (MDL-28657) the backup file names did not contain the id of the course.
2017 * Further we fixed that behaviour by forcing the id to be always present in the file name (MDL-33812).
2018 * This function will explore the backup directory and attempt to rename the previously created files to include
2019 * the id in the name. Doing this will put them back in the process of deleting the excess backups for each course.
2020 *
2021 * This function manually recreates the file name, instead of using
2022 * {@link backup_plan_dbops::get_default_backup_filename()}, use it carefully if you're using it outside of the
2023 * usual upgrade process.
2024 *
2025 * @see backup_cron_automated_helper::remove_excess_backups()
2026 * @link http://tracker.moodle.org/browse/MDL-35116
2027 * @return void
5bcfd504 2028 * @since Moodle 2.4
d8271e39
FM
2029 */
2030function upgrade_rename_old_backup_files_using_shortname() {
2031 global $CFG;
2032 $dir = get_config('backup', 'backup_auto_destination');
2033 $useshortname = get_config('backup', 'backup_shortname');
2034 if (empty($dir) || !is_dir($dir) || !is_writable($dir)) {
2035 return;
2036 }
2037
d8271e39 2038 require_once($CFG->dirroot.'/backup/util/includes/backup_includes.php');
2f1e464a 2039 $backupword = str_replace(' ', '_', core_text::strtolower(get_string('backupfilename')));
d8271e39
FM
2040 $backupword = trim(clean_filename($backupword), '_');
2041 $filename = $backupword . '-' . backup::FORMAT_MOODLE . '-' . backup::TYPE_1COURSE . '-';
2042 $regex = '#^'.preg_quote($filename, '#').'.*\.mbz$#';
2043 $thirtyapril = strtotime('30 April 2012 00:00');
2044
2045 // Reading the directory.
2046 if (!$files = scandir($dir)) {
2047 return;
2048 }
2049 foreach ($files as $file) {
2050 // Skip directories and files which do not start with the common prefix.
2051 // This avoids working on files which are not related to this issue.
2052 if (!is_file($dir . '/' . $file) || !preg_match($regex, $file)) {
2053 continue;
2054 }
2055
2056 // Extract the information from the XML file.
2057 try {
2058 $bcinfo = backup_general_helper::get_backup_information_from_mbz($dir . '/' . $file);
2059 } catch (backup_helper_exception $e) {
2060 // Some error while retrieving the backup informations, skipping...
2061 continue;
2062 }
2063
2064 // Make sure this a course backup.
2065 if ($bcinfo->format !== backup::FORMAT_MOODLE || $bcinfo->type !== backup::TYPE_1COURSE) {
2066 continue;
2067 }
2068
2069 // Skip the backups created before the short name option was initially introduced (MDL-28657).
2070 // This was integrated on the 2nd of May 2012. Let's play safe with timezone and use the 30th of April.
2071 if ($bcinfo->backup_date < $thirtyapril) {
2072 continue;
2073 }
2074
2075 // Let's check if the file name contains the ID where it is supposed to be, if it is the case then
2076 // we will skip the file. Of course it could happen that the course ID is identical to the course short name
2077 // even though really unlikely, but then renaming this file is not necessary. If the ID is not found in the
2078 // file name then it was probably the short name which was used.
2079 $idfilename = $filename . $bcinfo->original_course_id . '-';
2080 $idregex = '#^'.preg_quote($idfilename, '#').'.*\.mbz$#';
2081 if (preg_match($idregex, $file)) {
2082 continue;
2083 }
2084
2085 // Generating the file name manually. We do not use backup_plan_dbops::get_default_backup_filename() because
2086 // it will query the database to get some course information, and the course could not exist any more.
2087 $newname = $filename . $bcinfo->original_course_id . '-';
2088 if ($useshortname) {
2089 $shortname = str_replace(' ', '_', $bcinfo->original_course_shortname);
2f1e464a 2090 $shortname = core_text::strtolower(trim(clean_filename($shortname), '_'));
d8271e39
FM
2091 $newname .= $shortname . '-';
2092 }
2093
2094 $backupdateformat = str_replace(' ', '_', get_string('backupnameformat', 'langconfig'));
2095 $date = userdate($bcinfo->backup_date, $backupdateformat, 99, false);
2f1e464a 2096 $date = core_text::strtolower(trim(clean_filename($date), '_'));
d8271e39
FM
2097 $newname .= $date;
2098
2099 if (isset($bcinfo->root_settings['users']) && !$bcinfo->root_settings['users']) {
2100 $newname .= '-nu';
2101 } else if (isset($bcinfo->root_settings['anonymize']) && $bcinfo->root_settings['anonymize']) {
2102 $newname .= '-an';
2103 }
2104 $newname .= '.mbz';
2105
2106 // Final check before attempting the renaming.
2107 if ($newname == $file || file_exists($dir . '/' . $newname)) {
2108 continue;
2109 }
2110 @rename($dir . '/' . $file, $dir . '/' . $newname);
2111 }
2112}
2a9d7a42
DP
2113
2114/**
2115 * Detect duplicate grade item sortorders and resort the
2116 * items to remove them.
2117 */
2118function upgrade_grade_item_fix_sortorder() {
2119 global $DB;
2120
2121 // The simple way to fix these sortorder duplicates would be simply to resort each
2122 // affected course. But in order to reduce the impact of this upgrade step we're trying
2123 // to do it more efficiently by doing a series of update statements rather than updating
2124 // every single grade item in affected courses.
2125
800e9028 2126 $sql = "SELECT DISTINCT g1.courseid
2a9d7a42
DP
2127 FROM {grade_items} g1
2128 JOIN {grade_items} g2 ON g1.courseid = g2.courseid
2129 WHERE g1.sortorder = g2.sortorder AND g1.id != g2.id
800e9028
TL
2130 ORDER BY g1.courseid ASC";
2131 foreach ($DB->get_fieldset_sql($sql) as $courseid) {
2132 $transaction = $DB->start_delegated_transaction();
2133 $items = $DB->get_records('grade_items', array('courseid' => $courseid), '', 'id, sortorder, sortorder AS oldsort');
2134
2135 // Get all duplicates in course order, highest sort order, and higest id first so that we can make space at the
2136 // bottom higher end of the sort orders and work down by id.
2137 $sql = "SELECT DISTINCT g1.id, g1.sortorder
2138 FROM {grade_items} g1
2139 JOIN {grade_items} g2 ON g1.courseid = g2.courseid
2140 WHERE g1.sortorder = g2.sortorder AND g1.id != g2.id AND g1.courseid = :courseid
2141 ORDER BY g1.sortorder DESC, g1.id DESC";
2142
2143 // This is the O(N*N) like the database version we're replacing, but at least the constants are a billion times smaller...
2144 foreach ($DB->get_records_sql($sql, array('courseid' => $courseid)) as $duplicate) {
2145 foreach ($items as $item) {
2146 if ($item->sortorder > $duplicate->sortorder || ($item->sortorder == $duplicate->sortorder && $item->id > $duplicate->id)) {
2147 $item->sortorder += 1;
2148 }
2149 }
2150 }
2151 foreach ($items as $item) {
2152 if ($item->sortorder != $item->oldsort) {
2153 $DB->update_record('grade_items', array('id' => $item->id, 'sortorder' => $item->sortorder));
2154 }
2155 }
2a9d7a42 2156
800e9028 2157 $transaction->allow_commit();
2a9d7a42 2158 }
2a9d7a42 2159}
119cf17e
DP
2160
2161/**
2162 * Detect file areas with missing root directory records and add them.
2163 */
2164function upgrade_fix_missing_root_folders() {
2165 global $DB, $USER;
2166
2167 $transaction = $DB->start_delegated_transaction();
40c761e0
DP
2168
2169 $sql = "SELECT contextid, component, filearea, itemid
2170 FROM {files}
2171 WHERE (component <> 'user' OR filearea <> 'draft')
2172 GROUP BY contextid, component, filearea, itemid
2173 HAVING MAX(CASE WHEN filename = '.' AND filepath = '/' THEN 1 ELSE 0 END) = 0";
2174
119cf17e
DP
2175 $rs = $DB->get_recordset_sql($sql);
2176 $defaults = array('filepath' => '/',
2177 'filename' => '.',
6c704b15 2178 'userid' => 0, // Don't rely on any particular user for these system records.
119cf17e
DP
2179 'filesize' => 0,
2180 'timecreated' => time(),
2181 'timemodified' => time(),
2182 'contenthash' => sha1(''));
2183 foreach ($rs as $r) {
6c704b15 2184 $pathhash = sha1("/$r->contextid/$r->component/$r->filearea/$r->itemid/.");
119cf17e
DP
2185 $DB->insert_record('files', (array)$r + $defaults +
2186 array('pathnamehash' => $pathhash));
2187 }
2188 $rs->close();
2189 $transaction->allow_commit();
2190}
941de296
MG
2191
2192/**
2193 * Detect draft file areas with missing root directory records and add them.
2194 */
2195function upgrade_fix_missing_root_folders_draft() {
2196 global $DB;
2197
2198 $transaction = $DB->start_delegated_transaction();
2199
2200 $sql = "SELECT contextid, itemid, MAX(timecreated) AS timecreated, MAX(timemodified) AS timemodified
2201 FROM {files}
2202 WHERE (component = 'user' AND filearea = 'draft')
2203 GROUP BY contextid, itemid
2204 HAVING MAX(CASE WHEN filename = '.' AND filepath = '/' THEN 1 ELSE 0 END) = 0";
2205
2206 $rs = $DB->get_recordset_sql($sql);
2207 $defaults = array('component' => 'user',
2208 'filearea' => 'draft',
2209 'filepath' => '/',
2210 'filename' => '.',
2211 'userid' => 0, // Don't rely on any particular user for these system records.
2212 'filesize' => 0,
2213 'contenthash' => sha1(''));
2214 foreach ($rs as $r) {
2215 $r->pathnamehash = sha1("/$r->contextid/user/draft/$r->itemid/.");
2216 $DB->insert_record('files', (array)$r + $defaults);
2217 }
2218 $rs->close();
2219 $transaction->allow_commit();
2220}
71611510
MN
2221
2222/**
2223 * This function verifies that the database is not using an unsupported storage engine.
2224 *
2225 * @param environment_results $result object to update, if relevant
2226 * @return environment_results|null updated results object, or null if the storage engine is supported
2227 */
2228function check_database_storage_engine(environment_results $result) {
2229 global $DB;
2230
2231 // Check if MySQL is the DB family (this will also be the same for MariaDB).
2232 if ($DB->get_dbfamily() == 'mysql') {
2233 // Get the database engine we will either be using to install the tables, or what we are currently using.
2234 $engine = $DB->get_dbengine();
2235 // Check if MyISAM is the storage engine that will be used, if so, do not proceed and display an error.
2236 if ($engine == 'MyISAM') {
2237 $result->setInfo('unsupported_db_storage_engine');
2238 $result->setStatus(false);
2239 return $result;
2240 }
2241 }
2242
2243 return null;
2244}
1bd4b9fc
SL
2245
2246/**
2247 * Method used to check the usage of slasharguments config and display a warning message.
2248 *
2249 * @param environment_results $result object to update, if relevant.
2250 * @return environment_results|null updated results or null if slasharguments is disabled.
2251 */
2252function check_slasharguments(environment_results $result){
2253 global $CFG;
2254
e284ac02 2255 if (!during_initial_install() && empty($CFG->slasharguments)) {
1bd4b9fc
SL
2256 $result->setInfo('slasharguments');
2257 $result->setStatus(false);
2258 return $result;
2259 }
2260
2261 return null;
2262}
9b8104ce
SL
2263
2264/**
2265 * This function verifies if the database has tables using innoDB Antelope row format.
2266 *
2267 * @param environment_results $result
2268 * @return environment_results|null updated results object, or null if no Antelope table has been found.
2269 */
2270function check_database_tables_row_format(environment_results $result) {
2271 global $DB;
2272
2273 if ($DB->get_dbfamily() == 'mysql') {
2274 $generator = $DB->get_manager()->generator;
2275
2276 foreach ($DB->get_tables(false) as $table) {
2277 $columns = $DB->get_columns($table, false);
c7ccb543 2278 $size = $generator->guess_antelope_row_size($columns);
9b8104ce
SL
2279 $format = $DB->get_row_format($table);
2280
2281 if ($size <= $generator::ANTELOPE_MAX_ROW_SIZE) {
2282 continue;
2283 }
2284
2285 if ($format === 'Compact' or $format === 'Redundant') {
2286 $result->setInfo('unsupported_db_table_row_format');
2287 $result->setStatus(false);
2288 return $result;
2289 }
2290 }
2291 }
2292
2293 return null;
2294}
ebea19cb
FM
2295
2296/**
2297 * Upgrade the minmaxgrade setting.
2298 *
2299 * This step should only be run for sites running 2.8 or later. Sites using 2.7 will be fine
2300 * using the new default system setting $CFG->grade_minmaxtouse.
2301 *
2302 * @return void
2303 */
2304function upgrade_minmaxgrade() {
2305 global $CFG, $DB;
2306
2307 // 2 is a copy of GRADE_MIN_MAX_FROM_GRADE_GRADE.
2308 $settingvalue = 2;
2309
2310 // Set the course setting when:
2311 // - The system setting does not exist yet.
2312 // - The system seeting is not set to what we'd set the course setting.
2313 $setcoursesetting = !isset($CFG->grade_minmaxtouse) || $CFG->grade_minmaxtouse != $settingvalue;
2314
2315 // Identify the courses that have inconsistencies grade_item vs grade_grade.
2316 $sql = "SELECT DISTINCT(gi.courseid)
82cca1ab
G
2317 FROM {grade_grades} gg
2318 JOIN {grade_items} gi
ebea19cb 2319 ON gg.itemid = gi.id
82cca1ab 2320 WHERE gi.itemtype NOT IN (?, ?)
ebea19cb
FM
2321 AND (gg.rawgrademax != gi.grademax OR gg.rawgrademin != gi.grademin)";
2322
2323 $rs = $DB->get_recordset_sql($sql, array('course', 'category'));
2324 foreach ($rs as $record) {
2325 // Flag the course to show a notice in the gradebook.
2326 set_config('show_min_max_grades_changed_' . $record->courseid, 1);
2327
2328 // Set the appropriate course setting so that grades displayed are not changed.
2329 $configname = 'minmaxtouse';
2330 if ($setcoursesetting &&
2331 !$DB->record_exists('grade_settings', array('courseid' => $record->courseid, 'name' => $configname))) {
2332 // Do not set the setting when the course already defines it.
2333 $data = new stdClass();
2334 $data->courseid = $record->courseid;
2335 $data->name = $configname;
2336 $data->value = $settingvalue;
2337 $DB->insert_record('grade_settings', $data);
2338 }
2339
2340 // Mark the grades to be regraded.
2341 $DB->set_field('grade_items', 'needsupdate', 1, array('courseid' => $record->courseid));
2342 }
2343 $rs->close();
2344}
98b32c9e
DM
2345
2346
2347/**
2348 * Assert the upgrade key is provided, if it is defined.
2349 *
2350 * The upgrade key can be defined in the main config.php as $CFG->upgradekey. If
2351 * it is defined there, then its value must be provided every time the site is
2352 * being upgraded, regardless the administrator is logged in or not.
2353 *
2354 * This is supposed to be used at certain places in /admin/index.php only.
2355 *
2356 * @param string|null $upgradekeyhash the SHA-1 of the value provided by the user
2357 */
2358function check_upgrade_key($upgradekeyhash) {
2359 global $CFG, $PAGE;
2360
2361 if (isset($CFG->config_php_settings['upgradekey'])) {
2362 if ($upgradekeyhash === null or $upgradekeyhash !== sha1($CFG->config_php_settings['upgradekey'])) {
2363 if (!$PAGE->headerprinted) {
2364 $output = $PAGE->get_renderer('core', 'admin');
2365 echo $output->upgradekey_form_page(new moodle_url('/admin/index.php', array('cache' => 0)));
2366 die();
2367 } else {
2368 // This should not happen.
2369 die('Upgrade locked');
2370 }
2371 }
2372 }
2373}
531381f9
DM
2374
2375/**
2376 * Helper procedure/macro for installing remote plugins at admin/index.php
2377 *
2378 * Does not return, always redirects or exits.
2379 *
2380 * @param array $installable list of \core\update\remote_info
2381 * @param bool $confirmed false: display the validation screen, true: proceed installation
2382 * @param string $heading validation screen heading
2383 * @param moodle_url|string|null $continue URL to proceed with installation at the validation screen
8726c07c 2384 * @param moodle_url|string|null $return URL to go back on cancelling at the validation screen
531381f9 2385 */
2d00be61 2386function upgrade_install_plugins(array $installable, $confirmed, $heading='', $continue=null, $return=null) {
531381f9
DM
2387 global $PAGE;
2388
2389 if (empty($return)) {
2390 $return = $PAGE->url;
2391 }
2392
2393 if (empty($installable)) {
2394 redirect($return);
2395 }
2396
2397 $pluginman = core_plugin_manager::instance();
2398
2399 if ($confirmed) {
2400 // Installation confirmed at the validation results page.
2d00be61
DM
2401 if (!$pluginman->install_plugins($installable, true, true)) {
2402 throw new moodle_exception('install_plugins_failed', 'core_plugin', $return);
531381f9 2403 }
d9a5b810 2404
8726c07c 2405 // Always redirect to admin/index.php to perform the database upgrade.
d9a5b810
DM
2406 // Do not throw away the existing $PAGE->url parameters such as
2407 // confirmupgrade or confirmrelease if $PAGE->url is a superset of the
2408 // URL we must go to.
2409 $mustgoto = new moodle_url('/admin/index.php', array('cache' => 0, 'confirmplugincheck' => 0));
2410 if ($mustgoto->compare($PAGE->url, URL_MATCH_PARAMS)) {
2411 redirect($PAGE->url);
2412 } else {
2413 redirect($mustgoto);
2414 }
531381f9
DM
2415
2416 } else {
2417 $output = $PAGE->get_renderer('core', 'admin');
2418 echo $output->header();
2419 if ($heading) {
2420 echo $output->heading($heading, 3);
2421 }
2422 echo html_writer::start_tag('pre', array('class' => 'plugin-install-console'));
2d00be61 2423 $validated = $pluginman->install_plugins($installable, false, false);
531381f9
DM
2424 echo html_writer::end_tag('pre');
2425 if ($validated) {
4d7528f9 2426 echo $output->plugins_management_confirm_buttons($continue, $return);
531381f9 2427 } else {
4d7528f9 2428 echo $output->plugins_management_confirm_buttons(null, $return);
531381f9
DM
2429 }
2430 echo $output->footer();
2431 die();
2432 }
2433}