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