Merge branch 'MDL-52284-master' of git://github.com/marinaglancy/moodle
[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);
1766e6a1
MG
1550 } catch (Throwable $ex) {
1551 // Engine errors in PHP7 throw exceptions of type Throwable (this "catch" will be ignored in PHP5).
1552 upgrade_handle_exception($ex);
8580535b 1553 }
1554}
1555
1556/**
1557 * Upgrade moodle core
1558 * @param float $version target version
1559 * @param bool $verbose
1560 * @return void, may throw exception
1561 */
1562function upgrade_core($version, $verbose) {
e2049782 1563 global $CFG, $SITE, $DB, $COURSE;
8580535b 1564
41209c1e
PS
1565 raise_memory_limit(MEMORY_EXTRA);
1566
3316fe24 1567 require_once($CFG->libdir.'/db/upgrade.php'); // Defines upgrades
3316fe24 1568
8580535b 1569 try {
7b4d5af7 1570 // Reset caches before any output.
b0dd08dd 1571 cache_helper::purge_all(true);
7b4d5af7 1572 purge_all_caches();
dcf9be7f 1573
8580535b 1574 // Upgrade current language pack if we can
bd41bdd9 1575 upgrade_language_pack();
8580535b 1576
194cdca8 1577 print_upgrade_part_start('moodle', false, $verbose);
8580535b 1578
6b4b7490
PS
1579 // Pre-upgrade scripts for local hack workarounds.
1580 $preupgradefile = "$CFG->dirroot/local/preupgrade.php";
1581 if (file_exists($preupgradefile)) {
3ef7279f 1582 core_php_time_limit::raise();
6b4b7490
PS
1583 require($preupgradefile);
1584 // Reset upgrade timeout to default.
1585 upgrade_set_timeout();
17da2e6f 1586 }
1587
8580535b 1588 $result = xmldb_main_upgrade($CFG->version);
1589 if ($version > $CFG->version) {
1590 // store version if not already there
1591 upgrade_main_savepoint($result, $version, false);
1592 }
1593
e2049782
MG
1594 // In case structure of 'course' table has been changed and we forgot to update $SITE, re-read it from db.
1595 $SITE = $DB->get_record('course', array('id' => $SITE->id));
1596 $COURSE = clone($SITE);
1597
8580535b 1598 // perform all other component upgrade routines
1599 update_capabilities('moodle');
c6d75bff 1600 log_update_descriptions('moodle');
c976e271 1601 external_update_descriptions('moodle');
8580535b 1602 events_update_definition('moodle');
309ae892 1603 \core\task\manager::reset_scheduled_tasks_for_component('moodle');
8580535b 1604 message_update_providers('moodle');
6c0bfb14 1605 \core\message\inbound\manager::update_handlers_for_component('moodle');
75af47ee
SH
1606 // Update core definitions.
1607 cache_helper::update_definitions(true);
8580535b 1608
94ef67cf 1609 // Purge caches again, just to be sure we arn't holding onto old stuff now.
a5a6e93f 1610 cache_helper::purge_all(true);
7b4d5af7 1611 purge_all_caches();
2e5eba85
PS
1612
1613 // Clean up contexts - more and more stuff depends on existence of paths and contexts
e922fe23
PS
1614 context_helper::cleanup_instances();
1615 context_helper::create_instances(null, false);
1616 context_helper::build_all_paths(false);
1617 $syscontext = context_system::instance();
1618 $syscontext->mark_dirty();
8580535b 1619
194cdca8 1620 print_upgrade_part_end('moodle', false, $verbose);
8580535b 1621 } catch (Exception $ex) {
1622 upgrade_handle_exception($ex);
1766e6a1
MG
1623 } catch (Throwable $ex) {
1624 // Engine errors in PHP7 throw exceptions of type Throwable (this "catch" will be ignored in PHP5).
1625 upgrade_handle_exception($ex);
8580535b 1626 }
1627}
1628
1629/**
1630 * Upgrade/install other parts of moodle
1631 * @param bool $verbose
1632 * @return void, may throw exception
1633 */
1634function upgrade_noncore($verbose) {
1635 global $CFG;
1636
41209c1e
PS
1637 raise_memory_limit(MEMORY_EXTRA);
1638
8580535b 1639 // upgrade all plugins types
1640 try {
7b4d5af7
PS
1641 // Reset caches before any output.
1642 cache_helper::purge_all(true);
1643 purge_all_caches();
1644
46f6f7f2 1645 $plugintypes = core_component::get_plugin_types();
8580535b 1646 foreach ($plugintypes as $type=>$location) {
17da2e6f 1647 upgrade_plugins($type, 'print_upgrade_part_start', 'print_upgrade_part_end', $verbose);
8580535b 1648 }
94ef67cf 1649 // Update cache definitions. Involves scanning each plugin for any changes.
75af47ee 1650 cache_helper::update_definitions();
c5701ce7
PS
1651 // Mark the site as upgraded.
1652 set_config('allversionshash', core_component::get_all_versions_hash());
7b4d5af7
PS
1653
1654 // Purge caches again, just to be sure we arn't holding onto old stuff now.
1655 cache_helper::purge_all(true);
1656 purge_all_caches();
1657
8580535b 1658 } catch (Exception $ex) {
1659 upgrade_handle_exception($ex);
1766e6a1
MG
1660 } catch (Throwable $ex) {
1661 // Engine errors in PHP7 throw exceptions of type Throwable (this "catch" will be ignored in PHP5).
1662 upgrade_handle_exception($ex);
8580535b 1663 }
8580535b 1664}
3316fe24 1665
1666/**
1667 * Checks if the main tables have been installed yet or not.
e2e35e71
PS
1668 *
1669 * Note: we can not use caches here because they might be stale,
1670 * use with care!
1671 *
3316fe24 1672 * @return bool
1673 */
1674function core_tables_exist() {
1675 global $DB;
1676
e2e35e71 1677 if (!$tables = $DB->get_tables(false) ) { // No tables yet at all.
3316fe24 1678 return false;
9b683d13 1679
3316fe24 1680 } else { // Check for missing main tables
1681 $mtables = array('config', 'course', 'groupings'); // some tables used in 1.9 and 2.0, preferable something from the start and end of install.xml
1682 foreach ($mtables as $mtable) {
1683 if (!in_array($mtable, $tables)) {
1684 return false;
1685 }
1686 }
1687 return true;
9b683d13 1688 }
ba04999c 1689}
c71ade2f
PL
1690
1691/**
1692 * upgrades the mnet rpc definitions for the given component.
1693 * this method doesn't return status, an exception will be thrown in the case of an error
1694 *
1695 * @param string $component the plugin to upgrade, eg auth_mnet
1696 */
1697function upgrade_plugin_mnet_functions($component) {
1698 global $DB, $CFG;
1699
8c59114f 1700 list($type, $plugin) = core_component::normalize_component($component);
1c74b260 1701 $path = core_component::get_plugin_directory($type, $plugin);
c71ade2f 1702
17b71716
PS
1703 $publishes = array();
1704 $subscribes = array();
c71ade2f
PL
1705 if (file_exists($path . '/db/mnet.php')) {
1706 require_once($path . '/db/mnet.php'); // $publishes comes from this file
1707 }
1708 if (empty($publishes)) {
1709 $publishes = array(); // still need this to be able to disable stuff later
1710 }
1711 if (empty($subscribes)) {
1712 $subscribes = array(); // still need this to be able to disable stuff later
1713 }
1714
1715 static $servicecache = array();
1716
1717 // rekey an array based on the rpc method for easy lookups later
1718 $publishmethodservices = array();
1719 $subscribemethodservices = array();
1720 foreach($publishes as $servicename => $service) {
1721 if (is_array($service['methods'])) {
1722 foreach($service['methods'] as $methodname) {
1723 $service['servicename'] = $servicename;
1724 $publishmethodservices[$methodname][] = $service;
1725 }
1726 }
1727 }
1728
1729 // Disable functions that don't exist (any more) in the source
1730 // Should these be deleted? What about their permissions records?
1731 foreach ($DB->get_records('mnet_rpc', array('pluginname'=>$plugin, 'plugintype'=>$type), 'functionname ASC ') as $rpc) {
1732 if (!array_key_exists($rpc->functionname, $publishmethodservices) && $rpc->enabled) {
1733 $DB->set_field('mnet_rpc', 'enabled', 0, array('id' => $rpc->id));
1734 } else if (array_key_exists($rpc->functionname, $publishmethodservices) && !$rpc->enabled) {
1735 $DB->set_field('mnet_rpc', 'enabled', 1, array('id' => $rpc->id));
1736 }
1737 }
1738
1739 // reflect all the services we're publishing and save them
1740 require_once($CFG->dirroot . '/lib/zend/Zend/Server/Reflection.php');
1741 static $cachedclasses = array(); // to store reflection information in
1742 foreach ($publishes as $service => $data) {
1743 $f = $data['filename'];
1744 $c = $data['classname'];
1745 foreach ($data['methods'] as $method) {
6bdfef5d 1746 $dataobject = new stdClass();
c71ade2f
PL
1747 $dataobject->plugintype = $type;
1748 $dataobject->pluginname = $plugin;
1749 $dataobject->enabled = 1;
1750 $dataobject->classname = $c;
1751 $dataobject->filename = $f;
1752
1753 if (is_string($method)) {
1754 $dataobject->functionname = $method;
1755
1756 } else if (is_array($method)) { // wants to override file or class
1757 $dataobject->functionname = $method['method'];
1758 $dataobject->classname = $method['classname'];
1759 $dataobject->filename = $method['filename'];
1760 }
1761 $dataobject->xmlrpcpath = $type.'/'.$plugin.'/'.$dataobject->filename.'/'.$method;
1762 $dataobject->static = false;
1763
1764 require_once($path . '/' . $dataobject->filename);
1765 $functionreflect = null; // slightly different ways to get this depending on whether it's a class method or a function
1766 if (!empty($dataobject->classname)) {
1767 if (!class_exists($dataobject->classname)) {
1768 throw new moodle_exception('installnosuchmethod', 'mnet', '', (object)array('method' => $dataobject->functionname, 'class' => $dataobject->classname));
1769 }
1770 $key = $dataobject->filename . '|' . $dataobject->classname;
1771 if (!array_key_exists($key, $cachedclasses)) { // look to see if we've already got a reflection object
1772 try {
1773 $cachedclasses[$key] = Zend_Server_Reflection::reflectClass($dataobject->classname);
1774 } catch (Zend_Server_Reflection_Exception $e) { // catch these and rethrow them to something more helpful
1775 throw new moodle_exception('installreflectionclasserror', 'mnet', '', (object)array('method' => $dataobject->functionname, 'class' => $dataobject->classname, 'error' => $e->getMessage()));
1776 }
1777 }
1778 $r =& $cachedclasses[$key];
1779 if (!$r->hasMethod($dataobject->functionname)) {
1780 throw new moodle_exception('installnosuchmethod', 'mnet', '', (object)array('method' => $dataobject->functionname, 'class' => $dataobject->classname));
1781 }
1782 // stupid workaround for zend not having a getMethod($name) function
1783 $ms = $r->getMethods();
1784 foreach ($ms as $m) {
1785 if ($m->getName() == $dataobject->functionname) {
1786 $functionreflect = $m;
1787 break;
1788 }
1789 }
1790 $dataobject->static = (int)$functionreflect->isStatic();
1791 } else {
1792 if (!function_exists($dataobject->functionname)) {
1793 throw new moodle_exception('installnosuchfunction', 'mnet', '', (object)array('method' => $dataobject->functionname, 'file' => $dataobject->filename));
1794 }
1795 try {
1796 $functionreflect = Zend_Server_Reflection::reflectFunction($dataobject->functionname);
1797 } catch (Zend_Server_Reflection_Exception $e) { // catch these and rethrow them to something more helpful
1798 throw new moodle_exception('installreflectionfunctionerror', 'mnet', '', (object)array('method' => $dataobject->functionname, '' => $dataobject->filename, 'error' => $e->getMessage()));
1799 }
1800 }
1801 $dataobject->profile = serialize(admin_mnet_method_profile($functionreflect));
1802 $dataobject->help = $functionreflect->getDescription();
1803
1804 if ($record_exists = $DB->get_record('mnet_rpc', array('xmlrpcpath'=>$dataobject->xmlrpcpath))) {
1805 $dataobject->id = $record_exists->id;
1806 $dataobject->enabled = $record_exists->enabled;
1807 $DB->update_record('mnet_rpc', $dataobject);
1808 } else {
1809 $dataobject->id = $DB->insert_record('mnet_rpc', $dataobject, true);
1810 }
c71ade2f 1811
d5bd0b01
DM
1812 // TODO this API versioning must be reworked, here the recently processed method
1813 // sets the service API which may not be correct
677b6321
PL
1814 foreach ($publishmethodservices[$dataobject->functionname] as $service) {
1815 if ($serviceobj = $DB->get_record('mnet_service', array('name'=>$service['servicename']))) {
1816 $serviceobj->apiversion = $service['apiversion'];
1817 $DB->update_record('mnet_service', $serviceobj);
1818 } else {
1819 $serviceobj = new stdClass();
1820 $serviceobj->name = $service['servicename'];
f4a2817a 1821 $serviceobj->description = empty($service['description']) ? '' : $service['description'];
677b6321
PL
1822 $serviceobj->apiversion = $service['apiversion'];
1823 $serviceobj->offer = 1;
1824 $serviceobj->id = $DB->insert_record('mnet_service', $serviceobj);
1825 }
1826 $servicecache[$service['servicename']] = $serviceobj;
1827 if (!$DB->record_exists('mnet_service2rpc', array('rpcid'=>$dataobject->id, 'serviceid'=>$serviceobj->id))) {
1828 $obj = new stdClass();
1829 $obj->rpcid = $dataobject->id;
1830 $obj->serviceid = $serviceobj->id;
1831 $DB->insert_record('mnet_service2rpc', $obj, true);
1832 }
c71ade2f
PL
1833 }
1834 }
1835 }
c71ade2f
PL
1836 // finished with methods we publish, now do subscribable methods
1837 foreach($subscribes as $service => $methods) {
1838 if (!array_key_exists($service, $servicecache)) {
1839 if (!$serviceobj = $DB->get_record('mnet_service', array('name' => $service))) {
81634f03 1840 debugging("TODO: skipping unknown service $service - somebody needs to fix MDL-21993");
c71ade2f
PL
1841 continue;
1842 }
1843 $servicecache[$service] = $serviceobj;
1844 } else {
1845 $serviceobj = $servicecache[$service];
1846 }
1847 foreach ($methods as $method => $xmlrpcpath) {
1848 if (!$rpcid = $DB->get_field('mnet_remote_rpc', 'id', array('xmlrpcpath'=>$xmlrpcpath))) {
1849 $remoterpc = (object)array(
1850 'functionname' => $method,
1851 'xmlrpcpath' => $xmlrpcpath,
1852 'plugintype' => $type,
1853 'pluginname' => $plugin,
1854 'enabled' => 1,
1855 );
1856 $rpcid = $remoterpc->id = $DB->insert_record('mnet_remote_rpc', $remoterpc, true);
1857 }
1858 if (!$DB->record_exists('mnet_remote_service2rpc', array('rpcid'=>$rpcid, 'serviceid'=>$serviceobj->id))) {
1859 $obj = new stdClass();
1860 $obj->rpcid = $rpcid;
1861 $obj->serviceid = $serviceobj->id;
1862 $DB->insert_record('mnet_remote_service2rpc', $obj, true);
1863 }
677b6321 1864 $subscribemethodservices[$method][] = $service;
c71ade2f
PL
1865 }
1866 }
1867
1868 foreach ($DB->get_records('mnet_remote_rpc', array('pluginname'=>$plugin, 'plugintype'=>$type), 'functionname ASC ') as $rpc) {
1869 if (!array_key_exists($rpc->functionname, $subscribemethodservices) && $rpc->enabled) {
1870 $DB->set_field('mnet_remote_rpc', 'enabled', 0, array('id' => $rpc->id));
1871 } else if (array_key_exists($rpc->functionname, $subscribemethodservices) && !$rpc->enabled) {
1872 $DB->set_field('mnet_remote_rpc', 'enabled', 1, array('id' => $rpc->id));
1873 }
1874 }
1875
1876 return true;
1877}
1878
1879/**
1880 * Given some sort of Zend Reflection function/method object, return a profile array, ready to be serialized and stored
1881 *
1882 * @param Zend_Server_Reflection_Function_Abstract $function can be any subclass of this object type
1883 *
1884 * @return array
1885 */
1886function admin_mnet_method_profile(Zend_Server_Reflection_Function_Abstract $function) {
f20edd52
PS
1887 $protos = $function->getPrototypes();
1888 $proto = array_pop($protos);
c71ade2f
PL
1889 $ret = $proto->getReturnValue();
1890 $profile = array(
1891 'parameters' => array(),
1892 'return' => array(
1893 'type' => $ret->getType(),
1894 'description' => $ret->getDescription(),
1895 ),
1896 );
1897 foreach ($proto->getParameters() as $p) {
1898 $profile['parameters'][] = array(
1899 'name' => $p->getName(),
1900 'type' => $p->getType(),
1901 'description' => $p->getDescription(),
1902 );
1903 }
1904 return $profile;
1905}
424a19b1
AB
1906
1907
1908/**
1909 * This function finds duplicate records (based on combinations of fields that should be unique)
1910 * and then progamatically generated a "most correct" version of the data, update and removing
1911 * records as appropriate
1912 *
1913 * Thanks to Dan Marsden for help
1914 *
1915 * @param string $table Table name
1916 * @param array $uniques Array of field names that should be unique
e6f55285 1917 * @param array $fieldstocheck Array of fields to generate "correct" data from (optional)
424a19b1
AB
1918 * @return void
1919 */
1920function upgrade_course_completion_remove_duplicates($table, $uniques, $fieldstocheck = array()) {
1921 global $DB;
1922
1923 // Find duplicates
1924 $sql_cols = implode(', ', $uniques);
1925
1926 $sql = "SELECT {$sql_cols} FROM {{$table}} GROUP BY {$sql_cols} HAVING (count(id) > 1)";
1927 $duplicates = $DB->get_recordset_sql($sql, array());
1928
1929 // Loop through duplicates
1930 foreach ($duplicates as $duplicate) {
1931 $pointer = 0;
1932
1933 // Generate SQL for finding records with these duplicate uniques
e6f55285 1934 $sql_select = implode(' = ? AND ', $uniques).' = ?'; // builds "fieldname = ? AND fieldname = ?"
424a19b1
AB
1935 $uniq_values = array();
1936 foreach ($uniques as $u) {
1937 $uniq_values[] = $duplicate->$u;
1938 }
1939
1940 $sql_order = implode(' DESC, ', $uniques).' DESC'; // builds "fieldname DESC, fieldname DESC"
1941
1942 // Get records with these duplicate uniques
1943 $records = $DB->get_records_select(
1944 $table,
1945 $sql_select,
1946 $uniq_values,
1947 $sql_order
1948 );
1949
1950 // Loop through and build a "correct" record, deleting the others
1951 $needsupdate = false;
1952 $origrecord = null;
1953 foreach ($records as $record) {
1954 $pointer++;
1955 if ($pointer === 1) { // keep 1st record but delete all others.
1956 $origrecord = $record;
1957 } else {
1958 // If we have fields to check, update original record
1959 if ($fieldstocheck) {
1960 // we need to keep the "oldest" of all these fields as the valid completion record.
1961 // but we want to ignore null values
1962 foreach ($fieldstocheck as $f) {
1963 if ($record->$f && (($origrecord->$f > $record->$f) || !$origrecord->$f)) {
1964 $origrecord->$f = $record->$f;
1965 $needsupdate = true;
1966 }
1967 }
1968 }
1969 $DB->delete_records($table, array('id' => $record->id));
1970 }
1971 }
1972 if ($needsupdate || isset($origrecord->reaggregate)) {
e6f55285 1973 // If this table has a reaggregate field, update to force recheck on next cron run
424a19b1
AB
1974 if (isset($origrecord->reaggregate)) {
1975 $origrecord->reaggregate = time();
1976 }
1977 $DB->update_record($table, $origrecord);
1978 }
1979 }
1980}
67e3dd2c
FM
1981
1982/**
1983 * Find questions missing an existing category and associate them with
1984 * a category which purpose is to gather them.
1985 *
1986 * @return void
1987 */
1988function upgrade_save_orphaned_questions() {
1989 global $DB;
1990
1991 // Looking for orphaned questions
1992 $orphans = $DB->record_exists_select('question',
1993 'NOT EXISTS (SELECT 1 FROM {question_categories} WHERE {question_categories}.id = {question}.category)');
1994 if (!$orphans) {
1995 return;
1996 }
1997
1998 // Generate a unique stamp for the orphaned questions category, easier to identify it later on
1999 $uniquestamp = "unknownhost+120719170400+orphan";
2000 $systemcontext = context_system::instance();
2001
2002 // Create the orphaned category at system level
2003 $cat = $DB->get_record('question_categories', array('stamp' => $uniquestamp,
2004 'contextid' => $systemcontext->id));
2005 if (!$cat) {
2006 $cat = new stdClass();
2007 $cat->parent = 0;
2008 $cat->contextid = $systemcontext->id;
2009 $cat->name = get_string('orphanedquestionscategory', 'question');
2010 $cat->info = get_string('orphanedquestionscategoryinfo', 'question');
2011 $cat->sortorder = 999;
2012 $cat->stamp = $uniquestamp;
2013 $cat->id = $DB->insert_record("question_categories", $cat);
2014 }
2015
2016 // Set a category to those orphans
2017 $params = array('catid' => $cat->id);
2018 $DB->execute('UPDATE {question} SET category = :catid WHERE NOT EXISTS
2019 (SELECT 1 FROM {question_categories} WHERE {question_categories}.id = {question}.category)', $params);
2020}
2021
d8271e39
FM
2022/**
2023 * Rename old backup files to current backup files.
2024 *
2025 * When added the setting 'backup_shortname' (MDL-28657) the backup file names did not contain the id of the course.
2026 * Further we fixed that behaviour by forcing the id to be always present in the file name (MDL-33812).
2027 * This function will explore the backup directory and attempt to rename the previously created files to include
2028 * the id in the name. Doing this will put them back in the process of deleting the excess backups for each course.
2029 *
2030 * This function manually recreates the file name, instead of using
2031 * {@link backup_plan_dbops::get_default_backup_filename()}, use it carefully if you're using it outside of the
2032 * usual upgrade process.
2033 *
2034 * @see backup_cron_automated_helper::remove_excess_backups()
2035 * @link http://tracker.moodle.org/browse/MDL-35116
2036 * @return void
5bcfd504 2037 * @since Moodle 2.4
d8271e39
FM
2038 */
2039function upgrade_rename_old_backup_files_using_shortname() {
2040 global $CFG;
2041 $dir = get_config('backup', 'backup_auto_destination');
2042 $useshortname = get_config('backup', 'backup_shortname');
2043 if (empty($dir) || !is_dir($dir) || !is_writable($dir)) {
2044 return;
2045 }
2046
d8271e39 2047 require_once($CFG->dirroot.'/backup/util/includes/backup_includes.php');
2f1e464a 2048 $backupword = str_replace(' ', '_', core_text::strtolower(get_string('backupfilename')));
d8271e39
FM
2049 $backupword = trim(clean_filename($backupword), '_');
2050 $filename = $backupword . '-' . backup::FORMAT_MOODLE . '-' . backup::TYPE_1COURSE . '-';
2051 $regex = '#^'.preg_quote($filename, '#').'.*\.mbz$#';
2052 $thirtyapril = strtotime('30 April 2012 00:00');
2053
2054 // Reading the directory.
2055 if (!$files = scandir($dir)) {
2056 return;
2057 }
2058 foreach ($files as $file) {
2059 // Skip directories and files which do not start with the common prefix.
2060 // This avoids working on files which are not related to this issue.
2061 if (!is_file($dir . '/' . $file) || !preg_match($regex, $file)) {
2062 continue;
2063 }
2064
2065 // Extract the information from the XML file.
2066 try {
2067 $bcinfo = backup_general_helper::get_backup_information_from_mbz($dir . '/' . $file);
2068 } catch (backup_helper_exception $e) {
2069 // Some error while retrieving the backup informations, skipping...
2070 continue;
2071 }
2072
2073 // Make sure this a course backup.
2074 if ($bcinfo->format !== backup::FORMAT_MOODLE || $bcinfo->type !== backup::TYPE_1COURSE) {
2075 continue;
2076 }
2077
2078 // Skip the backups created before the short name option was initially introduced (MDL-28657).
2079 // This was integrated on the 2nd of May 2012. Let's play safe with timezone and use the 30th of April.
2080 if ($bcinfo->backup_date < $thirtyapril) {
2081 continue;
2082 }
2083
2084 // Let's check if the file name contains the ID where it is supposed to be, if it is the case then
2085 // we will skip the file. Of course it could happen that the course ID is identical to the course short name
2086 // even though really unlikely, but then renaming this file is not necessary. If the ID is not found in the
2087 // file name then it was probably the short name which was used.
2088 $idfilename = $filename . $bcinfo->original_course_id . '-';
2089 $idregex = '#^'.preg_quote($idfilename, '#').'.*\.mbz$#';
2090 if (preg_match($idregex, $file)) {
2091 continue;
2092 }
2093
2094 // Generating the file name manually. We do not use backup_plan_dbops::get_default_backup_filename() because
2095 // it will query the database to get some course information, and the course could not exist any more.
2096 $newname = $filename . $bcinfo->original_course_id . '-';
2097 if ($useshortname) {
2098 $shortname = str_replace(' ', '_', $bcinfo->original_course_shortname);
2f1e464a 2099 $shortname = core_text::strtolower(trim(clean_filename($shortname), '_'));
d8271e39
FM
2100 $newname .= $shortname . '-';
2101 }
2102
2103 $backupdateformat = str_replace(' ', '_', get_string('backupnameformat', 'langconfig'));
2104 $date = userdate($bcinfo->backup_date, $backupdateformat, 99, false);
2f1e464a 2105 $date = core_text::strtolower(trim(clean_filename($date), '_'));
d8271e39
FM
2106 $newname .= $date;
2107
2108 if (isset($bcinfo->root_settings['users']) && !$bcinfo->root_settings['users']) {
2109 $newname .= '-nu';
2110 } else if (isset($bcinfo->root_settings['anonymize']) && $bcinfo->root_settings['anonymize']) {
2111 $newname .= '-an';
2112 }
2113 $newname .= '.mbz';
2114
2115 // Final check before attempting the renaming.
2116 if ($newname == $file || file_exists($dir . '/' . $newname)) {
2117 continue;
2118 }
2119 @rename($dir . '/' . $file, $dir . '/' . $newname);
2120 }
2121}
2a9d7a42
DP
2122
2123/**
2124 * Detect duplicate grade item sortorders and resort the
2125 * items to remove them.
2126 */
2127function upgrade_grade_item_fix_sortorder() {
2128 global $DB;
2129
2130 // The simple way to fix these sortorder duplicates would be simply to resort each
2131 // affected course. But in order to reduce the impact of this upgrade step we're trying
2132 // to do it more efficiently by doing a series of update statements rather than updating
2133 // every single grade item in affected courses.
2134
800e9028 2135 $sql = "SELECT DISTINCT g1.courseid
2a9d7a42
DP
2136 FROM {grade_items} g1
2137 JOIN {grade_items} g2 ON g1.courseid = g2.courseid
2138 WHERE g1.sortorder = g2.sortorder AND g1.id != g2.id
800e9028
TL
2139 ORDER BY g1.courseid ASC";
2140 foreach ($DB->get_fieldset_sql($sql) as $courseid) {
2141 $transaction = $DB->start_delegated_transaction();
2142 $items = $DB->get_records('grade_items', array('courseid' => $courseid), '', 'id, sortorder, sortorder AS oldsort');
2143
2144 // Get all duplicates in course order, highest sort order, and higest id first so that we can make space at the
2145 // bottom higher end of the sort orders and work down by id.
2146 $sql = "SELECT DISTINCT g1.id, g1.sortorder
2147 FROM {grade_items} g1
2148 JOIN {grade_items} g2 ON g1.courseid = g2.courseid
2149 WHERE g1.sortorder = g2.sortorder AND g1.id != g2.id AND g1.courseid = :courseid
2150 ORDER BY g1.sortorder DESC, g1.id DESC";
2151
2152 // This is the O(N*N) like the database version we're replacing, but at least the constants are a billion times smaller...
2153 foreach ($DB->get_records_sql($sql, array('courseid' => $courseid)) as $duplicate) {
2154 foreach ($items as $item) {
2155 if ($item->sortorder > $duplicate->sortorder || ($item->sortorder == $duplicate->sortorder && $item->id > $duplicate->id)) {
2156 $item->sortorder += 1;
2157 }
2158 }
2159 }
2160 foreach ($items as $item) {
2161 if ($item->sortorder != $item->oldsort) {
2162 $DB->update_record('grade_items', array('id' => $item->id, 'sortorder' => $item->sortorder));
2163 }
2164 }
2a9d7a42 2165
800e9028 2166 $transaction->allow_commit();
2a9d7a42 2167 }
2a9d7a42 2168}
119cf17e
DP
2169
2170/**
2171 * Detect file areas with missing root directory records and add them.
2172 */
2173function upgrade_fix_missing_root_folders() {
2174 global $DB, $USER;
2175
2176 $transaction = $DB->start_delegated_transaction();
40c761e0
DP
2177
2178 $sql = "SELECT contextid, component, filearea, itemid
2179 FROM {files}
2180 WHERE (component <> 'user' OR filearea <> 'draft')
2181 GROUP BY contextid, component, filearea, itemid
2182 HAVING MAX(CASE WHEN filename = '.' AND filepath = '/' THEN 1 ELSE 0 END) = 0";
2183
119cf17e
DP
2184 $rs = $DB->get_recordset_sql($sql);
2185 $defaults = array('filepath' => '/',
2186 'filename' => '.',
6c704b15 2187 'userid' => 0, // Don't rely on any particular user for these system records.
119cf17e
DP
2188 'filesize' => 0,
2189 'timecreated' => time(),
2190 'timemodified' => time(),
2191 'contenthash' => sha1(''));
2192 foreach ($rs as $r) {
6c704b15 2193 $pathhash = sha1("/$r->contextid/$r->component/$r->filearea/$r->itemid/.");
119cf17e
DP
2194 $DB->insert_record('files', (array)$r + $defaults +
2195 array('pathnamehash' => $pathhash));
2196 }
2197 $rs->close();
2198 $transaction->allow_commit();
2199}
941de296
MG
2200
2201/**
2202 * Detect draft file areas with missing root directory records and add them.
2203 */
2204function upgrade_fix_missing_root_folders_draft() {
2205 global $DB;
2206
2207 $transaction = $DB->start_delegated_transaction();
2208
2209 $sql = "SELECT contextid, itemid, MAX(timecreated) AS timecreated, MAX(timemodified) AS timemodified
2210 FROM {files}
2211 WHERE (component = 'user' AND filearea = 'draft')
2212 GROUP BY contextid, itemid
2213 HAVING MAX(CASE WHEN filename = '.' AND filepath = '/' THEN 1 ELSE 0 END) = 0";
2214
2215 $rs = $DB->get_recordset_sql($sql);
2216 $defaults = array('component' => 'user',
2217 'filearea' => 'draft',
2218 'filepath' => '/',
2219 'filename' => '.',
2220 'userid' => 0, // Don't rely on any particular user for these system records.
2221 'filesize' => 0,
2222 'contenthash' => sha1(''));
2223 foreach ($rs as $r) {
2224 $r->pathnamehash = sha1("/$r->contextid/user/draft/$r->itemid/.");
2225 $DB->insert_record('files', (array)$r + $defaults);
2226 }
2227 $rs->close();
2228 $transaction->allow_commit();
2229}
71611510
MN
2230
2231/**
2232 * This function verifies that the database is not using an unsupported storage engine.
2233 *
2234 * @param environment_results $result object to update, if relevant
2235 * @return environment_results|null updated results object, or null if the storage engine is supported
2236 */
2237function check_database_storage_engine(environment_results $result) {
2238 global $DB;
2239
2240 // Check if MySQL is the DB family (this will also be the same for MariaDB).
2241 if ($DB->get_dbfamily() == 'mysql') {
2242 // Get the database engine we will either be using to install the tables, or what we are currently using.
2243 $engine = $DB->get_dbengine();
2244 // Check if MyISAM is the storage engine that will be used, if so, do not proceed and display an error.
2245 if ($engine == 'MyISAM') {
2246 $result->setInfo('unsupported_db_storage_engine');
2247 $result->setStatus(false);
2248 return $result;
2249 }
2250 }
2251
2252 return null;
2253}
1bd4b9fc
SL
2254
2255/**
2256 * Method used to check the usage of slasharguments config and display a warning message.
2257 *
2258 * @param environment_results $result object to update, if relevant.
2259 * @return environment_results|null updated results or null if slasharguments is disabled.
2260 */
2261function check_slasharguments(environment_results $result){
2262 global $CFG;
2263
e284ac02 2264 if (!during_initial_install() && empty($CFG->slasharguments)) {
1bd4b9fc
SL
2265 $result->setInfo('slasharguments');
2266 $result->setStatus(false);
2267 return $result;
2268 }
2269
2270 return null;
2271}
9b8104ce
SL
2272
2273/**
2274 * This function verifies if the database has tables using innoDB Antelope row format.
2275 *
2276 * @param environment_results $result
2277 * @return environment_results|null updated results object, or null if no Antelope table has been found.
2278 */
2279function check_database_tables_row_format(environment_results $result) {
2280 global $DB;
2281
2282 if ($DB->get_dbfamily() == 'mysql') {
2283 $generator = $DB->get_manager()->generator;
2284
2285 foreach ($DB->get_tables(false) as $table) {
2286 $columns = $DB->get_columns($table, false);
c7ccb543 2287 $size = $generator->guess_antelope_row_size($columns);
9b8104ce
SL
2288 $format = $DB->get_row_format($table);
2289
2290 if ($size <= $generator::ANTELOPE_MAX_ROW_SIZE) {
2291 continue;
2292 }
2293
2294 if ($format === 'Compact' or $format === 'Redundant') {
2295 $result->setInfo('unsupported_db_table_row_format');
2296 $result->setStatus(false);
2297 return $result;
2298 }
2299 }
2300 }
2301
2302 return null;
2303}
ebea19cb
FM
2304
2305/**
2306 * Upgrade the minmaxgrade setting.
2307 *
2308 * This step should only be run for sites running 2.8 or later. Sites using 2.7 will be fine
2309 * using the new default system setting $CFG->grade_minmaxtouse.
2310 *
2311 * @return void
2312 */
2313function upgrade_minmaxgrade() {
2314 global $CFG, $DB;
2315
2316 // 2 is a copy of GRADE_MIN_MAX_FROM_GRADE_GRADE.
2317 $settingvalue = 2;
2318
2319 // Set the course setting when:
2320 // - The system setting does not exist yet.
2321 // - The system seeting is not set to what we'd set the course setting.
2322 $setcoursesetting = !isset($CFG->grade_minmaxtouse) || $CFG->grade_minmaxtouse != $settingvalue;
2323
2324 // Identify the courses that have inconsistencies grade_item vs grade_grade.
2325 $sql = "SELECT DISTINCT(gi.courseid)
82cca1ab
G
2326 FROM {grade_grades} gg
2327 JOIN {grade_items} gi
ebea19cb 2328 ON gg.itemid = gi.id
82cca1ab 2329 WHERE gi.itemtype NOT IN (?, ?)
ebea19cb
FM
2330 AND (gg.rawgrademax != gi.grademax OR gg.rawgrademin != gi.grademin)";
2331
2332 $rs = $DB->get_recordset_sql($sql, array('course', 'category'));
2333 foreach ($rs as $record) {
2334 // Flag the course to show a notice in the gradebook.
2335 set_config('show_min_max_grades_changed_' . $record->courseid, 1);
2336
2337 // Set the appropriate course setting so that grades displayed are not changed.
2338 $configname = 'minmaxtouse';
2339 if ($setcoursesetting &&
2340 !$DB->record_exists('grade_settings', array('courseid' => $record->courseid, 'name' => $configname))) {
2341 // Do not set the setting when the course already defines it.
2342 $data = new stdClass();
2343 $data->courseid = $record->courseid;
2344 $data->name = $configname;
2345 $data->value = $settingvalue;
2346 $DB->insert_record('grade_settings', $data);
2347 }
2348
2349 // Mark the grades to be regraded.
2350 $DB->set_field('grade_items', 'needsupdate', 1, array('courseid' => $record->courseid));
2351 }
2352 $rs->close();
2353}
98b32c9e
DM
2354
2355
2356/**
2357 * Assert the upgrade key is provided, if it is defined.
2358 *
2359 * The upgrade key can be defined in the main config.php as $CFG->upgradekey. If
2360 * it is defined there, then its value must be provided every time the site is
2361 * being upgraded, regardless the administrator is logged in or not.
2362 *
2363 * This is supposed to be used at certain places in /admin/index.php only.
2364 *
2365 * @param string|null $upgradekeyhash the SHA-1 of the value provided by the user
2366 */
2367function check_upgrade_key($upgradekeyhash) {
2368 global $CFG, $PAGE;
2369
2370 if (isset($CFG->config_php_settings['upgradekey'])) {
2371 if ($upgradekeyhash === null or $upgradekeyhash !== sha1($CFG->config_php_settings['upgradekey'])) {
2372 if (!$PAGE->headerprinted) {
2373 $output = $PAGE->get_renderer('core', 'admin');
2374 echo $output->upgradekey_form_page(new moodle_url('/admin/index.php', array('cache' => 0)));
2375 die();
2376 } else {
2377 // This should not happen.
2378 die('Upgrade locked');
2379 }
2380 }
2381 }
2382}
531381f9
DM
2383
2384/**
2385 * Helper procedure/macro for installing remote plugins at admin/index.php
2386 *
2387 * Does not return, always redirects or exits.
2388 *
2389 * @param array $installable list of \core\update\remote_info
2390 * @param bool $confirmed false: display the validation screen, true: proceed installation
2391 * @param string $heading validation screen heading
2392 * @param moodle_url|string|null $continue URL to proceed with installation at the validation screen
8726c07c 2393 * @param moodle_url|string|null $return URL to go back on cancelling at the validation screen
531381f9 2394 */
2d00be61 2395function upgrade_install_plugins(array $installable, $confirmed, $heading='', $continue=null, $return=null) {
b0fc7898 2396 global $CFG, $PAGE;
531381f9
DM
2397
2398 if (empty($return)) {
2399 $return = $PAGE->url;
2400 }
2401
b0fc7898
DM
2402 if (!empty($CFG->disableupdateautodeploy)) {
2403 redirect($return);
2404 }
2405
531381f9
DM
2406 if (empty($installable)) {
2407 redirect($return);
2408 }
2409
2410 $pluginman = core_plugin_manager::instance();
2411
2412 if ($confirmed) {
2413 // Installation confirmed at the validation results page.
2d00be61
DM
2414 if (!$pluginman->install_plugins($installable, true, true)) {
2415 throw new moodle_exception('install_plugins_failed', 'core_plugin', $return);
531381f9 2416 }
d9a5b810 2417
8726c07c 2418 // Always redirect to admin/index.php to perform the database upgrade.
d9a5b810
DM
2419 // Do not throw away the existing $PAGE->url parameters such as
2420 // confirmupgrade or confirmrelease if $PAGE->url is a superset of the
2421 // URL we must go to.
2422 $mustgoto = new moodle_url('/admin/index.php', array('cache' => 0, 'confirmplugincheck' => 0));
2423 if ($mustgoto->compare($PAGE->url, URL_MATCH_PARAMS)) {
2424 redirect($PAGE->url);
2425 } else {
2426 redirect($mustgoto);
2427 }
531381f9
DM
2428
2429 } else {
2430 $output = $PAGE->get_renderer('core', 'admin');
2431 echo $output->header();
2432 if ($heading) {
2433 echo $output->heading($heading, 3);
2434 }
2435 echo html_writer::start_tag('pre', array('class' => 'plugin-install-console'));
2d00be61 2436 $validated = $pluginman->install_plugins($installable, false, false);
531381f9
DM
2437 echo html_writer::end_tag('pre');
2438 if ($validated) {
4d7528f9 2439 echo $output->plugins_management_confirm_buttons($continue, $return);
531381f9 2440 } else {
4d7528f9 2441 echo $output->plugins_management_confirm_buttons(null, $return);
531381f9
DM
2442 }
2443 echo $output->footer();
2444 die();
2445 }
2446}