MDL-32262 theme_afterburner: fixed missing comma in afterburner_styles.css
[moodle.git] / lib / upgradelib.php
blob4f2544822bc9b79ebf2b7a1bb5f176f7573560e8
1 <?php
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.
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/>.
18 /**
19 * Various upgrade/install related functions and classes.
21 * @package core
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
27 defined('MOODLE_INTERNAL') || die();
29 /** UPGRADE_LOG_NORMAL = 0 */
30 define('UPGRADE_LOG_NORMAL', 0);
31 /** UPGRADE_LOG_NOTICE = 1 */
32 define('UPGRADE_LOG_NOTICE', 1);
33 /** UPGRADE_LOG_ERROR = 2 */
34 define('UPGRADE_LOG_ERROR', 2);
36 /**
37 * Exception indicating unknown error during upgrade.
39 * @package core
40 * @subpackage upgrade
41 * @copyright 2009 Petr Skoda {@link http://skodak.org}
42 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
44 class upgrade_exception extends moodle_exception {
45 function __construct($plugin, $version, $debuginfo=NULL) {
46 global $CFG;
47 $a = (object)array('plugin'=>$plugin, 'version'=>$version);
48 parent::__construct('upgradeerror', 'admin', "$CFG->wwwroot/$CFG->admin/index.php", $a, $debuginfo);
52 /**
53 * Exception indicating downgrade error during upgrade.
55 * @package core
56 * @subpackage upgrade
57 * @copyright 2009 Petr Skoda {@link http://skodak.org}
58 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
60 class 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);
69 /**
70 * @package core
71 * @subpackage upgrade
72 * @copyright 2009 Petr Skoda {@link http://skodak.org}
73 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
75 class upgrade_requires_exception extends moodle_exception {
76 function __construct($plugin, $pluginversion, $currentmoodle, $requiremoodle) {
77 global $CFG;
78 $a = new stdClass();
79 $a->pluginname = $plugin;
80 $a->pluginversion = $pluginversion;
81 $a->currentmoodle = $currentmoodle;
82 $a->requiremoodle = $requiremoodle;
83 parent::__construct('pluginrequirementsnotmet', 'error', "$CFG->wwwroot/$CFG->admin/index.php", $a);
87 /**
88 * @package core
89 * @subpackage upgrade
90 * @copyright 2009 Petr Skoda {@link http://skodak.org}
91 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
93 class 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);
101 * Upgrade savepoint, marks end of each upgrade block.
102 * It stores new main version, resets upgrade timeout
103 * and abort upgrade if user cancels page loading.
105 * Please do not make large upgrade blocks with lots of operations,
106 * for example when adding tables keep only one table operation per block.
108 * @global object
109 * @param bool $result false if upgrade step failed, true if completed
110 * @param string or float $version main version
111 * @param bool $allowabort allow user to abort script execution here
112 * @return void
114 function upgrade_main_savepoint($result, $version, $allowabort=true) {
115 global $CFG;
117 //sanity check to avoid confusion with upgrade_mod_savepoint usage.
118 if (!is_bool($allowabort)) {
119 $errormessage = 'Parameter type mismatch. Are you mixing up upgrade_main_savepoint() and upgrade_mod_savepoint()?';
120 throw new coding_exception($errormessage);
123 if (!$result) {
124 throw new upgrade_exception(null, $version);
127 if ($CFG->version >= $version) {
128 // something really wrong is going on in main upgrade script
129 throw new downgrade_exception(null, $CFG->version, $version);
132 set_config('version', $version);
133 upgrade_log(UPGRADE_LOG_NORMAL, null, 'Upgrade savepoint reached');
135 // reset upgrade timeout to default
136 upgrade_set_timeout();
138 // this is a safe place to stop upgrades if user aborts page loading
139 if ($allowabort and connection_aborted()) {
140 die;
145 * Module upgrade savepoint, marks end of module upgrade blocks
146 * It stores module version, resets upgrade timeout
147 * and abort upgrade if user cancels page loading.
149 * @global object
150 * @param bool $result false if upgrade step failed, true if completed
151 * @param string or float $version main version
152 * @param string $modname name of module
153 * @param bool $allowabort allow user to abort script execution here
154 * @return void
156 function upgrade_mod_savepoint($result, $version, $modname, $allowabort=true) {
157 global $DB;
159 if (!$result) {
160 throw new upgrade_exception("mod_$modname", $version);
163 if (!$module = $DB->get_record('modules', array('name'=>$modname))) {
164 print_error('modulenotexist', 'debug', '', $modname);
167 if ($module->version >= $version) {
168 // something really wrong is going on in upgrade script
169 throw new downgrade_exception("mod_$modname", $module->version, $version);
171 $module->version = $version;
172 $DB->update_record('modules', $module);
173 upgrade_log(UPGRADE_LOG_NORMAL, "mod_$modname", 'Upgrade savepoint reached');
175 // reset upgrade timeout to default
176 upgrade_set_timeout();
178 // this is a safe place to stop upgrades if user aborts page loading
179 if ($allowabort and connection_aborted()) {
180 die;
185 * Blocks upgrade savepoint, marks end of blocks upgrade blocks
186 * It stores block version, resets upgrade timeout
187 * and abort upgrade if user cancels page loading.
189 * @global object
190 * @param bool $result false if upgrade step failed, true if completed
191 * @param string or float $version main version
192 * @param string $blockname name of block
193 * @param bool $allowabort allow user to abort script execution here
194 * @return void
196 function upgrade_block_savepoint($result, $version, $blockname, $allowabort=true) {
197 global $DB;
199 if (!$result) {
200 throw new upgrade_exception("block_$blockname", $version);
203 if (!$block = $DB->get_record('block', array('name'=>$blockname))) {
204 print_error('blocknotexist', 'debug', '', $blockname);
207 if ($block->version >= $version) {
208 // something really wrong is going on in upgrade script
209 throw new downgrade_exception("block_$blockname", $block->version, $version);
211 $block->version = $version;
212 $DB->update_record('block', $block);
213 upgrade_log(UPGRADE_LOG_NORMAL, "block_$blockname", 'Upgrade savepoint reached');
215 // reset upgrade timeout to default
216 upgrade_set_timeout();
218 // this is a safe place to stop upgrades if user aborts page loading
219 if ($allowabort and connection_aborted()) {
220 die;
225 * Plugins upgrade savepoint, marks end of blocks upgrade blocks
226 * It stores plugin version, resets upgrade timeout
227 * and abort upgrade if user cancels page loading.
229 * @param bool $result false if upgrade step failed, true if completed
230 * @param string or float $version main version
231 * @param string $type name of plugin
232 * @param string $dir location of plugin
233 * @param bool $allowabort allow user to abort script execution here
234 * @return void
236 function upgrade_plugin_savepoint($result, $version, $type, $plugin, $allowabort=true) {
237 $component = $type.'_'.$plugin;
239 if (!$result) {
240 throw new upgrade_exception($component, $version);
243 $installedversion = get_config($component, 'version');
244 if ($installedversion >= $version) {
245 // Something really wrong is going on in the upgrade script
246 throw new downgrade_exception($component, $installedversion, $version);
248 set_config('version', $version, $component);
249 upgrade_log(UPGRADE_LOG_NORMAL, $component, 'Upgrade savepoint reached');
251 // Reset upgrade timeout to default
252 upgrade_set_timeout();
254 // This is a safe place to stop upgrades if user aborts page loading
255 if ($allowabort and connection_aborted()) {
256 die;
261 * Detect if there are leftovers in PHP source files.
263 * During main version upgrades administrators MUST move away
264 * old PHP source files and start from scratch (or better
265 * use git).
267 * @return bool true means borked upgrade, false means previous PHP files were properly removed
269 function upgrade_stale_php_files_present() {
270 global $CFG;
272 $someexamplesofremovedfiles = array(
273 // removed in 2.3dev
274 '/lib/minify/builder/',
275 // removed in 2.2dev
276 '/lib/yui/3.4.1pr1/',
277 // removed in 2.2
278 '/search/cron_php5.php',
279 '/course/report/log/indexlive.php',
280 '/admin/report/backups/index.php',
281 '/admin/generator.php',
282 // removed in 2.1
283 '/lib/yui/2.8.0r4/',
284 // removed in 2.0
285 '/blocks/admin/block_admin.php',
286 '/blocks/admin_tree/block_admin_tree.php',
289 foreach ($someexamplesofremovedfiles as $file) {
290 if (file_exists($CFG->dirroot.$file)) {
291 return true;
295 return false;
299 * Upgrade plugins
300 * @param string $type The type of plugins that should be updated (e.g. 'enrol', 'qtype')
301 * return void
303 function upgrade_plugins($type, $startcallback, $endcallback, $verbose) {
304 global $CFG, $DB;
306 /// special cases
307 if ($type === 'mod') {
308 return upgrade_plugins_modules($startcallback, $endcallback, $verbose);
309 } else if ($type === 'block') {
310 return upgrade_plugins_blocks($startcallback, $endcallback, $verbose);
313 $plugs = get_plugin_list($type);
315 foreach ($plugs as $plug=>$fullplug) {
316 $component = clean_param($type.'_'.$plug, PARAM_COMPONENT); // standardised plugin name
318 // check plugin dir is valid name
319 if (empty($component)) {
320 throw new plugin_defective_exception($type.'_'.$plug, 'Invalid plugin directory name.');
323 if (!is_readable($fullplug.'/version.php')) {
324 continue;
327 $plugin = new stdClass();
328 require($fullplug.'/version.php'); // defines $plugin with version etc
330 // if plugin tells us it's full name we may check the location
331 if (isset($plugin->component)) {
332 if ($plugin->component !== $component) {
333 throw new plugin_defective_exception($component, 'Plugin installed in wrong folder.');
337 if (empty($plugin->version)) {
338 throw new plugin_defective_exception($component, 'Missing version value in version.php');
341 $plugin->name = $plug;
342 $plugin->fullname = $component;
345 if (!empty($plugin->requires)) {
346 if ($plugin->requires > $CFG->version) {
347 throw new upgrade_requires_exception($component, $plugin->version, $CFG->version, $plugin->requires);
348 } else if ($plugin->requires < 2010000000) {
349 throw new plugin_defective_exception($component, 'Plugin is not compatible with Moodle 2.x or later.');
353 // try to recover from interrupted install.php if needed
354 if (file_exists($fullplug.'/db/install.php')) {
355 if (get_config($plugin->fullname, 'installrunning')) {
356 require_once($fullplug.'/db/install.php');
357 $recover_install_function = 'xmldb_'.$plugin->fullname.'_install_recovery';
358 if (function_exists($recover_install_function)) {
359 $startcallback($component, true, $verbose);
360 $recover_install_function();
361 unset_config('installrunning', $plugin->fullname);
362 update_capabilities($component);
363 log_update_descriptions($component);
364 external_update_descriptions($component);
365 events_update_definition($component);
366 message_update_providers($component);
367 if ($type === 'message') {
368 message_update_processors($plug);
370 upgrade_plugin_mnet_functions($component);
371 $endcallback($component, true, $verbose);
376 $installedversion = get_config($plugin->fullname, 'version');
377 if (empty($installedversion)) { // new installation
378 $startcallback($component, true, $verbose);
380 /// Install tables if defined
381 if (file_exists($fullplug.'/db/install.xml')) {
382 $DB->get_manager()->install_from_xmldb_file($fullplug.'/db/install.xml');
385 /// store version
386 upgrade_plugin_savepoint(true, $plugin->version, $type, $plug, false);
388 /// execute post install file
389 if (file_exists($fullplug.'/db/install.php')) {
390 require_once($fullplug.'/db/install.php');
391 set_config('installrunning', 1, $plugin->fullname);
392 $post_install_function = 'xmldb_'.$plugin->fullname.'_install';
393 $post_install_function();
394 unset_config('installrunning', $plugin->fullname);
397 /// Install various components
398 update_capabilities($component);
399 log_update_descriptions($component);
400 external_update_descriptions($component);
401 events_update_definition($component);
402 message_update_providers($component);
403 if ($type === 'message') {
404 message_update_processors($plug);
406 upgrade_plugin_mnet_functions($component);
408 purge_all_caches();
409 $endcallback($component, true, $verbose);
411 } else if ($installedversion < $plugin->version) { // upgrade
412 /// Run the upgrade function for the plugin.
413 $startcallback($component, false, $verbose);
415 if (is_readable($fullplug.'/db/upgrade.php')) {
416 require_once($fullplug.'/db/upgrade.php'); // defines upgrading function
418 $newupgrade_function = 'xmldb_'.$plugin->fullname.'_upgrade';
419 $result = $newupgrade_function($installedversion);
420 } else {
421 $result = true;
424 $installedversion = get_config($plugin->fullname, 'version');
425 if ($installedversion < $plugin->version) {
426 // store version if not already there
427 upgrade_plugin_savepoint($result, $plugin->version, $type, $plug, false);
430 /// Upgrade various components
431 update_capabilities($component);
432 log_update_descriptions($component);
433 external_update_descriptions($component);
434 events_update_definition($component);
435 message_update_providers($component);
436 if ($type === 'message') {
437 message_update_processors($plug);
439 upgrade_plugin_mnet_functions($component);
441 purge_all_caches();
442 $endcallback($component, false, $verbose);
444 } else if ($installedversion > $plugin->version) {
445 throw new downgrade_exception($component, $installedversion, $plugin->version);
451 * Find and check all modules and load them up or upgrade them if necessary
453 * @global object
454 * @global object
456 function upgrade_plugins_modules($startcallback, $endcallback, $verbose) {
457 global $CFG, $DB;
459 $mods = get_plugin_list('mod');
461 foreach ($mods as $mod=>$fullmod) {
463 if ($mod === 'NEWMODULE') { // Someone has unzipped the template, ignore it
464 continue;
467 $component = clean_param('mod_'.$mod, PARAM_COMPONENT);
469 // check module dir is valid name
470 if (empty($component)) {
471 throw new plugin_defective_exception('mod_'.$mod, 'Invalid plugin directory name.');
474 if (!is_readable($fullmod.'/version.php')) {
475 throw new plugin_defective_exception($component, 'Missing version.php');
478 $module = new stdClass();
479 require($fullmod .'/version.php'); // defines $module with version etc
481 // if plugin tells us it's full name we may check the location
482 if (isset($module->component)) {
483 if ($module->component !== $component) {
484 throw new plugin_defective_exception($component, 'Plugin installed in wrong folder.');
488 if (empty($module->version)) {
489 if (isset($module->version)) {
490 // Version is empty but is set - it means its value is 0 or ''. Let us skip such module.
491 // This is intended for developers so they can work on the early stages of the module.
492 continue;
494 throw new plugin_defective_exception($component, 'Missing version value in version.php');
497 if (!empty($module->requires)) {
498 if ($module->requires > $CFG->version) {
499 throw new upgrade_requires_exception($component, $module->version, $CFG->version, $module->requires);
500 } else if ($module->requires < 2010000000) {
501 throw new plugin_defective_exception($component, 'Plugin is not compatible with Moodle 2.x or later.');
505 if (empty($module->cron)) {
506 $module->cron = 0;
509 // all modules must have en lang pack
510 if (!is_readable("$fullmod/lang/en/$mod.php")) {
511 throw new plugin_defective_exception($component, 'Missing mandatory en language pack.');
514 $module->name = $mod; // The name MUST match the directory
516 $currmodule = $DB->get_record('modules', array('name'=>$module->name));
518 if (file_exists($fullmod.'/db/install.php')) {
519 if (get_config($module->name, 'installrunning')) {
520 require_once($fullmod.'/db/install.php');
521 $recover_install_function = 'xmldb_'.$module->name.'_install_recovery';
522 if (function_exists($recover_install_function)) {
523 $startcallback($component, true, $verbose);
524 $recover_install_function();
525 unset_config('installrunning', $module->name);
526 // Install various components too
527 update_capabilities($component);
528 log_update_descriptions($component);
529 external_update_descriptions($component);
530 events_update_definition($component);
531 message_update_providers($component);
532 upgrade_plugin_mnet_functions($component);
533 $endcallback($component, true, $verbose);
538 if (empty($currmodule->version)) {
539 $startcallback($component, true, $verbose);
541 /// Execute install.xml (XMLDB) - must be present in all modules
542 $DB->get_manager()->install_from_xmldb_file($fullmod.'/db/install.xml');
544 /// Add record into modules table - may be needed in install.php already
545 $module->id = $DB->insert_record('modules', $module);
547 /// Post installation hook - optional
548 if (file_exists("$fullmod/db/install.php")) {
549 require_once("$fullmod/db/install.php");
550 // Set installation running flag, we need to recover after exception or error
551 set_config('installrunning', 1, $module->name);
552 $post_install_function = 'xmldb_'.$module->name.'_install';
553 $post_install_function();
554 unset_config('installrunning', $module->name);
557 /// Install various components
558 update_capabilities($component);
559 log_update_descriptions($component);
560 external_update_descriptions($component);
561 events_update_definition($component);
562 message_update_providers($component);
563 upgrade_plugin_mnet_functions($component);
565 purge_all_caches();
566 $endcallback($component, true, $verbose);
568 } else if ($currmodule->version < $module->version) {
569 /// If versions say that we need to upgrade but no upgrade files are available, notify and continue
570 $startcallback($component, false, $verbose);
572 if (is_readable($fullmod.'/db/upgrade.php')) {
573 require_once($fullmod.'/db/upgrade.php'); // defines new upgrading function
574 $newupgrade_function = 'xmldb_'.$module->name.'_upgrade';
575 $result = $newupgrade_function($currmodule->version, $module);
576 } else {
577 $result = true;
580 $currmodule = $DB->get_record('modules', array('name'=>$module->name));
581 if ($currmodule->version < $module->version) {
582 // store version if not already there
583 upgrade_mod_savepoint($result, $module->version, $mod, false);
586 // update cron flag if needed
587 if ($currmodule->cron != $module->cron) {
588 $DB->set_field('modules', 'cron', $module->cron, array('name' => $module->name));
591 // Upgrade various components
592 update_capabilities($component);
593 log_update_descriptions($component);
594 external_update_descriptions($component);
595 events_update_definition($component);
596 message_update_providers($component);
597 upgrade_plugin_mnet_functions($component);
599 purge_all_caches();
601 $endcallback($component, false, $verbose);
603 } else if ($currmodule->version > $module->version) {
604 throw new downgrade_exception($component, $currmodule->version, $module->version);
611 * This function finds all available blocks and install them
612 * into blocks table or do all the upgrade process if newer.
614 * @global object
615 * @global object
617 function upgrade_plugins_blocks($startcallback, $endcallback, $verbose) {
618 global $CFG, $DB;
620 require_once($CFG->dirroot.'/blocks/moodleblock.class.php');
622 $blocktitles = array(); // we do not want duplicate titles
624 //Is this a first install
625 $first_install = null;
627 $blocks = get_plugin_list('block');
629 foreach ($blocks as $blockname=>$fullblock) {
631 if (is_null($first_install)) {
632 $first_install = ($DB->count_records('block_instances') == 0);
635 if ($blockname === 'NEWBLOCK') { // Someone has unzipped the template, ignore it
636 continue;
639 $component = clean_param('block_'.$blockname, PARAM_COMPONENT);
641 // check block dir is valid name
642 if (empty($component)) {
643 throw new plugin_defective_exception('block_'.$blockname, 'Invalid plugin directory name.');
646 if (!is_readable($fullblock.'/version.php')) {
647 throw new plugin_defective_exception('block/'.$blockname, 'Missing version.php file.');
649 $plugin = new stdClass();
650 $plugin->version = NULL;
651 $plugin->cron = 0;
652 include($fullblock.'/version.php');
653 $block = $plugin;
655 // if plugin tells us it's full name we may check the location
656 if (isset($block->component)) {
657 if ($block->component !== $component) {
658 throw new plugin_defective_exception($component, 'Plugin installed in wrong folder.');
662 if (!empty($plugin->requires)) {
663 if ($plugin->requires > $CFG->version) {
664 throw new upgrade_requires_exception($component, $plugin->version, $CFG->version, $plugin->requires);
665 } else if ($plugin->requires < 2010000000) {
666 throw new plugin_defective_exception($component, 'Plugin is not compatible with Moodle 2.x or later.');
670 if (!is_readable($fullblock.'/block_'.$blockname.'.php')) {
671 throw new plugin_defective_exception('block/'.$blockname, 'Missing main block class file.');
673 include_once($fullblock.'/block_'.$blockname.'.php');
675 $classname = 'block_'.$blockname;
677 if (!class_exists($classname)) {
678 throw new plugin_defective_exception($component, 'Can not load main class.');
681 $blockobj = new $classname; // This is what we'll be testing
682 $blocktitle = $blockobj->get_title();
684 // OK, it's as we all hoped. For further tests, the object will do them itself.
685 if (!$blockobj->_self_test()) {
686 throw new plugin_defective_exception($component, 'Self test failed.');
689 $block->name = $blockname; // The name MUST match the directory
691 if (empty($block->version)) {
692 throw new plugin_defective_exception($component, 'Missing block version.');
695 $currblock = $DB->get_record('block', array('name'=>$block->name));
697 if (file_exists($fullblock.'/db/install.php')) {
698 if (get_config('block_'.$blockname, 'installrunning')) {
699 require_once($fullblock.'/db/install.php');
700 $recover_install_function = 'xmldb_block_'.$blockname.'_install_recovery';
701 if (function_exists($recover_install_function)) {
702 $startcallback($component, true, $verbose);
703 $recover_install_function();
704 unset_config('installrunning', 'block_'.$blockname);
705 // Install various components
706 update_capabilities($component);
707 log_update_descriptions($component);
708 external_update_descriptions($component);
709 events_update_definition($component);
710 message_update_providers($component);
711 upgrade_plugin_mnet_functions($component);
712 $endcallback($component, true, $verbose);
717 if (empty($currblock->version)) { // block not installed yet, so install it
718 $conflictblock = array_search($blocktitle, $blocktitles);
719 if ($conflictblock !== false) {
720 // Duplicate block titles are not allowed, they confuse people
721 // AND PHP's associative arrays ;)
722 throw new plugin_defective_exception($component, get_string('blocknameconflict', 'error', (object)array('name'=>$block->name, 'conflict'=>$conflictblock)));
724 $startcallback($component, true, $verbose);
726 if (file_exists($fullblock.'/db/install.xml')) {
727 $DB->get_manager()->install_from_xmldb_file($fullblock.'/db/install.xml');
729 $block->id = $DB->insert_record('block', $block);
731 if (file_exists($fullblock.'/db/install.php')) {
732 require_once($fullblock.'/db/install.php');
733 // Set installation running flag, we need to recover after exception or error
734 set_config('installrunning', 1, 'block_'.$blockname);
735 $post_install_function = 'xmldb_block_'.$blockname.'_install';;
736 $post_install_function();
737 unset_config('installrunning', 'block_'.$blockname);
740 $blocktitles[$block->name] = $blocktitle;
742 // Install various components
743 update_capabilities($component);
744 log_update_descriptions($component);
745 external_update_descriptions($component);
746 events_update_definition($component);
747 message_update_providers($component);
748 upgrade_plugin_mnet_functions($component);
750 purge_all_caches();
751 $endcallback($component, true, $verbose);
753 } else if ($currblock->version < $block->version) {
754 $startcallback($component, false, $verbose);
756 if (is_readable($fullblock.'/db/upgrade.php')) {
757 require_once($fullblock.'/db/upgrade.php'); // defines new upgrading function
758 $newupgrade_function = 'xmldb_block_'.$blockname.'_upgrade';
759 $result = $newupgrade_function($currblock->version, $block);
760 } else {
761 $result = true;
764 $currblock = $DB->get_record('block', array('name'=>$block->name));
765 if ($currblock->version < $block->version) {
766 // store version if not already there
767 upgrade_block_savepoint($result, $block->version, $block->name, false);
770 if ($currblock->cron != $block->cron) {
771 // update cron flag if needed
772 $currblock->cron = $block->cron;
773 $DB->update_record('block', $currblock);
776 // Upgrade various components
777 update_capabilities($component);
778 log_update_descriptions($component);
779 external_update_descriptions($component);
780 events_update_definition($component);
781 message_update_providers($component);
782 upgrade_plugin_mnet_functions($component);
784 purge_all_caches();
785 $endcallback($component, false, $verbose);
787 } else if ($currblock->version > $block->version) {
788 throw new downgrade_exception($component, $currblock->version, $block->version);
793 // Finally, if we are in the first_install of BLOCKS setup frontpage and admin page blocks
794 if ($first_install) {
795 //Iterate over each course - there should be only site course here now
796 if ($courses = $DB->get_records('course')) {
797 foreach ($courses as $course) {
798 blocks_add_default_course_blocks($course);
802 blocks_add_default_system_blocks();
808 * Log_display description function used during install and upgrade.
810 * @param string $component name of component (moodle, mod_assignment, etc.)
811 * @return void
813 function log_update_descriptions($component) {
814 global $DB;
816 $defpath = get_component_directory($component).'/db/log.php';
818 if (!file_exists($defpath)) {
819 $DB->delete_records('log_display', array('component'=>$component));
820 return;
823 // load new info
824 $logs = array();
825 include($defpath);
826 $newlogs = array();
827 foreach ($logs as $log) {
828 $newlogs[$log['module'].'-'.$log['action']] = $log; // kind of unique name
830 unset($logs);
831 $logs = $newlogs;
833 $fields = array('module', 'action', 'mtable', 'field');
834 // update all log fist
835 $dblogs = $DB->get_records('log_display', array('component'=>$component));
836 foreach ($dblogs as $dblog) {
837 $name = $dblog->module.'-'.$dblog->action;
839 if (empty($logs[$name])) {
840 $DB->delete_records('log_display', array('id'=>$dblog->id));
841 continue;
844 $log = $logs[$name];
845 unset($logs[$name]);
847 $update = false;
848 foreach ($fields as $field) {
849 if ($dblog->$field != $log[$field]) {
850 $dblog->$field = $log[$field];
851 $update = true;
854 if ($update) {
855 $DB->update_record('log_display', $dblog);
858 foreach ($logs as $log) {
859 $dblog = (object)$log;
860 $dblog->component = $component;
861 $DB->insert_record('log_display', $dblog);
866 * Web service discovery function used during install and upgrade.
867 * @param string $component name of component (moodle, mod_assignment, etc.)
868 * @return void
870 function external_update_descriptions($component) {
871 global $DB;
873 $defpath = get_component_directory($component).'/db/services.php';
875 if (!file_exists($defpath)) {
876 external_delete_descriptions($component);
877 return;
880 // load new info
881 $functions = array();
882 $services = array();
883 include($defpath);
885 // update all function fist
886 $dbfunctions = $DB->get_records('external_functions', array('component'=>$component));
887 foreach ($dbfunctions as $dbfunction) {
888 if (empty($functions[$dbfunction->name])) {
889 $DB->delete_records('external_functions', array('id'=>$dbfunction->id));
890 // do not delete functions from external_services_functions, beacuse
891 // we want to notify admins when functions used in custom services disappear
893 //TODO: this looks wrong, we have to delete it eventually (skodak)
894 continue;
897 $function = $functions[$dbfunction->name];
898 unset($functions[$dbfunction->name]);
899 $function['classpath'] = empty($function['classpath']) ? null : $function['classpath'];
901 $update = false;
902 if ($dbfunction->classname != $function['classname']) {
903 $dbfunction->classname = $function['classname'];
904 $update = true;
906 if ($dbfunction->methodname != $function['methodname']) {
907 $dbfunction->methodname = $function['methodname'];
908 $update = true;
910 if ($dbfunction->classpath != $function['classpath']) {
911 $dbfunction->classpath = $function['classpath'];
912 $update = true;
914 $functioncapabilities = key_exists('capabilities', $function)?$function['capabilities']:'';
915 if ($dbfunction->capabilities != $functioncapabilities) {
916 $dbfunction->capabilities = $functioncapabilities;
917 $update = true;
919 if ($update) {
920 $DB->update_record('external_functions', $dbfunction);
923 foreach ($functions as $fname => $function) {
924 $dbfunction = new stdClass();
925 $dbfunction->name = $fname;
926 $dbfunction->classname = $function['classname'];
927 $dbfunction->methodname = $function['methodname'];
928 $dbfunction->classpath = empty($function['classpath']) ? null : $function['classpath'];
929 $dbfunction->component = $component;
930 $dbfunction->capabilities = key_exists('capabilities', $function)?$function['capabilities']:'';
931 $dbfunction->id = $DB->insert_record('external_functions', $dbfunction);
933 unset($functions);
935 // now deal with services
936 $dbservices = $DB->get_records('external_services', array('component'=>$component));
937 foreach ($dbservices as $dbservice) {
938 if (empty($services[$dbservice->name])) {
939 $DB->delete_records('external_services_functions', array('externalserviceid'=>$dbservice->id));
940 $DB->delete_records('external_services_users', array('externalserviceid'=>$dbservice->id));
941 $DB->delete_records('external_services', array('id'=>$dbservice->id));
942 continue;
944 $service = $services[$dbservice->name];
945 unset($services[$dbservice->name]);
946 $service['enabled'] = empty($service['enabled']) ? 0 : $service['enabled'];
947 $service['requiredcapability'] = empty($service['requiredcapability']) ? null : $service['requiredcapability'];
948 $service['restrictedusers'] = !isset($service['restrictedusers']) ? 1 : $service['restrictedusers'];
949 $service['downloadfiles'] = !isset($service['downloadfiles']) ? 0 : $service['downloadfiles'];
950 $service['shortname'] = !isset($service['shortname']) ? null : $service['shortname'];
952 $update = false;
953 if ($dbservice->requiredcapability != $service['requiredcapability']) {
954 $dbservice->requiredcapability = $service['requiredcapability'];
955 $update = true;
957 if ($dbservice->restrictedusers != $service['restrictedusers']) {
958 $dbservice->restrictedusers = $service['restrictedusers'];
959 $update = true;
961 if ($dbservice->downloadfiles != $service['downloadfiles']) {
962 $dbservice->downloadfiles = $service['downloadfiles'];
963 $update = true;
965 //if shortname is not a PARAM_ALPHANUMEXT, fail (tested here for service update and creation)
966 if (isset($service['shortname']) and
967 (clean_param($service['shortname'], PARAM_ALPHANUMEXT) != $service['shortname'])) {
968 throw new moodle_exception('installserviceshortnameerror', 'webservice', '', $service['shortname']);
970 if ($dbservice->shortname != $service['shortname']) {
971 //check that shortname is unique
972 if (isset($service['shortname'])) { //we currently accepts multiple shortname == null
973 $existingservice = $DB->get_record('external_services',
974 array('shortname' => $service['shortname']));
975 if (!empty($existingservice)) {
976 throw new moodle_exception('installexistingserviceshortnameerror', 'webservice', '', $service['shortname']);
979 $dbservice->shortname = $service['shortname'];
980 $update = true;
982 if ($update) {
983 $DB->update_record('external_services', $dbservice);
986 $functions = $DB->get_records('external_services_functions', array('externalserviceid'=>$dbservice->id));
987 foreach ($functions as $function) {
988 $key = array_search($function->functionname, $service['functions']);
989 if ($key === false) {
990 $DB->delete_records('external_services_functions', array('id'=>$function->id));
991 } else {
992 unset($service['functions'][$key]);
995 foreach ($service['functions'] as $fname) {
996 $newf = new stdClass();
997 $newf->externalserviceid = $dbservice->id;
998 $newf->functionname = $fname;
999 $DB->insert_record('external_services_functions', $newf);
1001 unset($functions);
1003 foreach ($services as $name => $service) {
1004 //check that shortname is unique
1005 if (isset($service['shortname'])) { //we currently accepts multiple shortname == null
1006 $existingservice = $DB->get_record('external_services',
1007 array('shortname' => $service['shortname']));
1008 if (!empty($existingservice)) {
1009 throw new moodle_exception('installserviceshortnameerror', 'webservice');
1013 $dbservice = new stdClass();
1014 $dbservice->name = $name;
1015 $dbservice->enabled = empty($service['enabled']) ? 0 : $service['enabled'];
1016 $dbservice->requiredcapability = empty($service['requiredcapability']) ? null : $service['requiredcapability'];
1017 $dbservice->restrictedusers = !isset($service['restrictedusers']) ? 1 : $service['restrictedusers'];
1018 $dbservice->downloadfiles = !isset($service['downloadfiles']) ? 0 : $service['downloadfiles'];
1019 $dbservice->shortname = !isset($service['shortname']) ? null : $service['shortname'];
1020 $dbservice->component = $component;
1021 $dbservice->timecreated = time();
1022 $dbservice->id = $DB->insert_record('external_services', $dbservice);
1023 foreach ($service['functions'] as $fname) {
1024 $newf = new stdClass();
1025 $newf->externalserviceid = $dbservice->id;
1026 $newf->functionname = $fname;
1027 $DB->insert_record('external_services_functions', $newf);
1033 * Delete all service and external functions information defined in the specified component.
1034 * @param string $component name of component (moodle, mod_assignment, etc.)
1035 * @return void
1037 function external_delete_descriptions($component) {
1038 global $DB;
1040 $params = array($component);
1042 $DB->delete_records_select('external_services_users', "externalserviceid IN (SELECT id FROM {external_services} WHERE component = ?)", $params);
1043 $DB->delete_records_select('external_services_functions', "externalserviceid IN (SELECT id FROM {external_services} WHERE component = ?)", $params);
1044 $DB->delete_records('external_services', array('component'=>$component));
1045 $DB->delete_records('external_functions', array('component'=>$component));
1049 * upgrade logging functions
1051 function upgrade_handle_exception($ex, $plugin = null) {
1052 global $CFG;
1054 // rollback everything, we need to log all upgrade problems
1055 abort_all_db_transactions();
1057 $info = get_exception_info($ex);
1059 // First log upgrade error
1060 upgrade_log(UPGRADE_LOG_ERROR, $plugin, 'Exception: ' . get_class($ex), $info->message, $info->backtrace);
1062 // Always turn on debugging - admins need to know what is going on
1063 $CFG->debug = DEBUG_DEVELOPER;
1065 default_exception_handler($ex, true, $plugin);
1069 * Adds log entry into upgrade_log table
1071 * @param int $type UPGRADE_LOG_NORMAL, UPGRADE_LOG_NOTICE or UPGRADE_LOG_ERROR
1072 * @param string $plugin frankenstyle component name
1073 * @param string $info short description text of log entry
1074 * @param string $details long problem description
1075 * @param string $backtrace string used for errors only
1076 * @return void
1078 function upgrade_log($type, $plugin, $info, $details=null, $backtrace=null) {
1079 global $DB, $USER, $CFG;
1081 if (empty($plugin)) {
1082 $plugin = 'core';
1085 list($plugintype, $pluginname) = normalize_component($plugin);
1086 $component = is_null($pluginname) ? $plugintype : $plugintype . '_' . $pluginname;
1088 $backtrace = format_backtrace($backtrace, true);
1090 $currentversion = null;
1091 $targetversion = null;
1093 //first try to find out current version number
1094 if ($plugintype === 'core') {
1095 //main
1096 $currentversion = $CFG->version;
1098 $version = null;
1099 include("$CFG->dirroot/version.php");
1100 $targetversion = $version;
1102 } else if ($plugintype === 'mod') {
1103 try {
1104 $currentversion = $DB->get_field('modules', 'version', array('name'=>$pluginname));
1105 $currentversion = ($currentversion === false) ? null : $currentversion;
1106 } catch (Exception $ignored) {
1108 $cd = get_component_directory($component);
1109 if (file_exists("$cd/version.php")) {
1110 $module = new stdClass();
1111 $module->version = null;
1112 include("$cd/version.php");
1113 $targetversion = $module->version;
1116 } else if ($plugintype === 'block') {
1117 try {
1118 if ($block = $DB->get_record('block', array('name'=>$pluginname))) {
1119 $currentversion = $block->version;
1121 } catch (Exception $ignored) {
1123 $cd = get_component_directory($component);
1124 if (file_exists("$cd/version.php")) {
1125 $plugin = new stdClass();
1126 $plugin->version = null;
1127 include("$cd/version.php");
1128 $targetversion = $plugin->version;
1131 } else {
1132 $pluginversion = get_config($component, 'version');
1133 if (!empty($pluginversion)) {
1134 $currentversion = $pluginversion;
1136 $cd = get_component_directory($component);
1137 if (file_exists("$cd/version.php")) {
1138 $plugin = new stdClass();
1139 $plugin->version = null;
1140 include("$cd/version.php");
1141 $targetversion = $plugin->version;
1145 $log = new stdClass();
1146 $log->type = $type;
1147 $log->plugin = $component;
1148 $log->version = $currentversion;
1149 $log->targetversion = $targetversion;
1150 $log->info = $info;
1151 $log->details = $details;
1152 $log->backtrace = $backtrace;
1153 $log->userid = $USER->id;
1154 $log->timemodified = time();
1155 try {
1156 $DB->insert_record('upgrade_log', $log);
1157 } catch (Exception $ignored) {
1158 // possible during install or 2.0 upgrade
1163 * Marks start of upgrade, blocks any other access to site.
1164 * The upgrade is finished at the end of script or after timeout.
1166 * @global object
1167 * @global object
1168 * @global object
1170 function upgrade_started($preinstall=false) {
1171 global $CFG, $DB, $PAGE, $OUTPUT;
1173 static $started = false;
1175 if ($preinstall) {
1176 ignore_user_abort(true);
1177 upgrade_setup_debug(true);
1179 } else if ($started) {
1180 upgrade_set_timeout(120);
1182 } else {
1183 if (!CLI_SCRIPT and !$PAGE->headerprinted) {
1184 $strupgrade = get_string('upgradingversion', 'admin');
1185 $PAGE->set_pagelayout('maintenance');
1186 upgrade_init_javascript();
1187 $PAGE->set_title($strupgrade.' - Moodle '.$CFG->target_release);
1188 $PAGE->set_heading($strupgrade);
1189 $PAGE->navbar->add($strupgrade);
1190 $PAGE->set_cacheable(false);
1191 echo $OUTPUT->header();
1194 ignore_user_abort(true);
1195 register_shutdown_function('upgrade_finished_handler');
1196 upgrade_setup_debug(true);
1197 set_config('upgraderunning', time()+300);
1198 $started = true;
1203 * Internal function - executed if upgrade interrupted.
1205 function upgrade_finished_handler() {
1206 upgrade_finished();
1210 * Indicates upgrade is finished.
1212 * This function may be called repeatedly.
1214 * @global object
1215 * @global object
1217 function upgrade_finished($continueurl=null) {
1218 global $CFG, $DB, $OUTPUT;
1220 if (!empty($CFG->upgraderunning)) {
1221 unset_config('upgraderunning');
1222 upgrade_setup_debug(false);
1223 ignore_user_abort(false);
1224 if ($continueurl) {
1225 echo $OUTPUT->continue_button($continueurl);
1226 echo $OUTPUT->footer();
1227 die;
1233 * @global object
1234 * @global object
1236 function upgrade_setup_debug($starting) {
1237 global $CFG, $DB;
1239 static $originaldebug = null;
1241 if ($starting) {
1242 if ($originaldebug === null) {
1243 $originaldebug = $DB->get_debug();
1245 if (!empty($CFG->upgradeshowsql)) {
1246 $DB->set_debug(true);
1248 } else {
1249 $DB->set_debug($originaldebug);
1253 function print_upgrade_separator() {
1254 if (!CLI_SCRIPT) {
1255 echo '<hr />';
1260 * Default start upgrade callback
1261 * @param string $plugin
1262 * @param bool $installation true if installation, false means upgrade
1264 function print_upgrade_part_start($plugin, $installation, $verbose) {
1265 global $OUTPUT;
1266 if (empty($plugin) or $plugin == 'moodle') {
1267 upgrade_started($installation); // does not store upgrade running flag yet
1268 if ($verbose) {
1269 echo $OUTPUT->heading(get_string('coresystem'));
1271 } else {
1272 upgrade_started();
1273 if ($verbose) {
1274 echo $OUTPUT->heading($plugin);
1277 if ($installation) {
1278 if (empty($plugin) or $plugin == 'moodle') {
1279 // no need to log - log table not yet there ;-)
1280 } else {
1281 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Starting plugin installation');
1283 } else {
1284 if (empty($plugin) or $plugin == 'moodle') {
1285 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Starting core upgrade');
1286 } else {
1287 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Starting plugin upgrade');
1293 * Default end upgrade callback
1294 * @param string $plugin
1295 * @param bool $installation true if installation, false means upgrade
1297 function print_upgrade_part_end($plugin, $installation, $verbose) {
1298 global $OUTPUT;
1299 upgrade_started();
1300 if ($installation) {
1301 if (empty($plugin) or $plugin == 'moodle') {
1302 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Core installed');
1303 } else {
1304 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Plugin installed');
1306 } else {
1307 if (empty($plugin) or $plugin == 'moodle') {
1308 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Core upgraded');
1309 } else {
1310 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Plugin upgraded');
1313 if ($verbose) {
1314 echo $OUTPUT->notification(get_string('success'), 'notifysuccess');
1315 print_upgrade_separator();
1320 * Sets up JS code required for all upgrade scripts.
1321 * @global object
1323 function upgrade_init_javascript() {
1324 global $PAGE;
1325 // scroll to the end of each upgrade page so that ppl see either error or continue button,
1326 // no need to scroll continuously any more, it is enough to jump to end once the footer is printed ;-)
1327 $js = "window.scrollTo(0, 5000000);";
1328 $PAGE->requires->js_init_code($js);
1332 * Try to upgrade the given language pack (or current language)
1334 * @param string $lang the code of the language to update, defaults to the current language
1336 function upgrade_language_pack($lang = null) {
1337 global $CFG;
1339 if (!empty($CFG->skiplangupgrade)) {
1340 return;
1343 if (!file_exists("$CFG->dirroot/$CFG->admin/tool/langimport/lib.php")) {
1344 // weird, somebody uninstalled the import utility
1345 return;
1348 if (!$lang) {
1349 $lang = current_language();
1352 if (!get_string_manager()->translation_exists($lang)) {
1353 return;
1356 get_string_manager()->reset_caches();
1358 if ($lang === 'en') {
1359 return; // Nothing to do
1362 upgrade_started(false);
1364 require_once("$CFG->dirroot/$CFG->admin/tool/langimport/lib.php");
1365 tool_langimport_preupgrade_update($lang);
1367 get_string_manager()->reset_caches();
1369 print_upgrade_separator();
1373 * Install core moodle tables and initialize
1374 * @param float $version target version
1375 * @param bool $verbose
1376 * @return void, may throw exception
1378 function install_core($version, $verbose) {
1379 global $CFG, $DB;
1381 try {
1382 set_time_limit(600);
1383 print_upgrade_part_start('moodle', true, $verbose); // does not store upgrade running flag
1385 $DB->get_manager()->install_from_xmldb_file("$CFG->libdir/db/install.xml");
1386 upgrade_started(); // we want the flag to be stored in config table ;-)
1388 // set all core default records and default settings
1389 require_once("$CFG->libdir/db/install.php");
1390 xmldb_main_install(); // installs the capabilities too
1392 // store version
1393 upgrade_main_savepoint(true, $version, false);
1395 // Continue with the installation
1396 log_update_descriptions('moodle');
1397 external_update_descriptions('moodle');
1398 events_update_definition('moodle');
1399 message_update_providers('moodle');
1401 // Write default settings unconditionally
1402 admin_apply_default_settings(NULL, true);
1404 print_upgrade_part_end(null, true, $verbose);
1405 } catch (exception $ex) {
1406 upgrade_handle_exception($ex);
1411 * Upgrade moodle core
1412 * @param float $version target version
1413 * @param bool $verbose
1414 * @return void, may throw exception
1416 function upgrade_core($version, $verbose) {
1417 global $CFG;
1419 raise_memory_limit(MEMORY_EXTRA);
1421 require_once($CFG->libdir.'/db/upgrade.php'); // Defines upgrades
1423 try {
1424 // Reset caches before any output
1425 purge_all_caches();
1427 // Upgrade current language pack if we can
1428 upgrade_language_pack();
1430 print_upgrade_part_start('moodle', false, $verbose);
1432 // one time special local migration pre 2.0 upgrade script
1433 if ($CFG->version < 2007101600) {
1434 $pre20upgradefile = "$CFG->dirroot/local/upgrade_pre20.php";
1435 if (file_exists($pre20upgradefile)) {
1436 set_time_limit(0);
1437 require($pre20upgradefile);
1438 // reset upgrade timeout to default
1439 upgrade_set_timeout();
1443 $result = xmldb_main_upgrade($CFG->version);
1444 if ($version > $CFG->version) {
1445 // store version if not already there
1446 upgrade_main_savepoint($result, $version, false);
1449 // perform all other component upgrade routines
1450 update_capabilities('moodle');
1451 log_update_descriptions('moodle');
1452 external_update_descriptions('moodle');
1453 events_update_definition('moodle');
1454 message_update_providers('moodle');
1456 // Reset caches again, just to be sure
1457 purge_all_caches();
1459 // Clean up contexts - more and more stuff depends on existence of paths and contexts
1460 context_helper::cleanup_instances();
1461 context_helper::create_instances(null, false);
1462 context_helper::build_all_paths(false);
1463 $syscontext = context_system::instance();
1464 $syscontext->mark_dirty();
1466 print_upgrade_part_end('moodle', false, $verbose);
1467 } catch (Exception $ex) {
1468 upgrade_handle_exception($ex);
1473 * Upgrade/install other parts of moodle
1474 * @param bool $verbose
1475 * @return void, may throw exception
1477 function upgrade_noncore($verbose) {
1478 global $CFG;
1480 raise_memory_limit(MEMORY_EXTRA);
1482 // upgrade all plugins types
1483 try {
1484 $plugintypes = get_plugin_types();
1485 foreach ($plugintypes as $type=>$location) {
1486 upgrade_plugins($type, 'print_upgrade_part_start', 'print_upgrade_part_end', $verbose);
1488 } catch (Exception $ex) {
1489 upgrade_handle_exception($ex);
1494 * Checks if the main tables have been installed yet or not.
1495 * @return bool
1497 function core_tables_exist() {
1498 global $DB;
1500 if (!$tables = $DB->get_tables() ) { // No tables yet at all.
1501 return false;
1503 } else { // Check for missing main tables
1504 $mtables = array('config', 'course', 'groupings'); // some tables used in 1.9 and 2.0, preferable something from the start and end of install.xml
1505 foreach ($mtables as $mtable) {
1506 if (!in_array($mtable, $tables)) {
1507 return false;
1510 return true;
1515 * upgrades the mnet rpc definitions for the given component.
1516 * this method doesn't return status, an exception will be thrown in the case of an error
1518 * @param string $component the plugin to upgrade, eg auth_mnet
1520 function upgrade_plugin_mnet_functions($component) {
1521 global $DB, $CFG;
1523 list($type, $plugin) = explode('_', $component);
1524 $path = get_plugin_directory($type, $plugin);
1526 $publishes = array();
1527 $subscribes = array();
1528 if (file_exists($path . '/db/mnet.php')) {
1529 require_once($path . '/db/mnet.php'); // $publishes comes from this file
1531 if (empty($publishes)) {
1532 $publishes = array(); // still need this to be able to disable stuff later
1534 if (empty($subscribes)) {
1535 $subscribes = array(); // still need this to be able to disable stuff later
1538 static $servicecache = array();
1540 // rekey an array based on the rpc method for easy lookups later
1541 $publishmethodservices = array();
1542 $subscribemethodservices = array();
1543 foreach($publishes as $servicename => $service) {
1544 if (is_array($service['methods'])) {
1545 foreach($service['methods'] as $methodname) {
1546 $service['servicename'] = $servicename;
1547 $publishmethodservices[$methodname][] = $service;
1552 // Disable functions that don't exist (any more) in the source
1553 // Should these be deleted? What about their permissions records?
1554 foreach ($DB->get_records('mnet_rpc', array('pluginname'=>$plugin, 'plugintype'=>$type), 'functionname ASC ') as $rpc) {
1555 if (!array_key_exists($rpc->functionname, $publishmethodservices) && $rpc->enabled) {
1556 $DB->set_field('mnet_rpc', 'enabled', 0, array('id' => $rpc->id));
1557 } else if (array_key_exists($rpc->functionname, $publishmethodservices) && !$rpc->enabled) {
1558 $DB->set_field('mnet_rpc', 'enabled', 1, array('id' => $rpc->id));
1562 // reflect all the services we're publishing and save them
1563 require_once($CFG->dirroot . '/lib/zend/Zend/Server/Reflection.php');
1564 static $cachedclasses = array(); // to store reflection information in
1565 foreach ($publishes as $service => $data) {
1566 $f = $data['filename'];
1567 $c = $data['classname'];
1568 foreach ($data['methods'] as $method) {
1569 $dataobject = new stdClass();
1570 $dataobject->plugintype = $type;
1571 $dataobject->pluginname = $plugin;
1572 $dataobject->enabled = 1;
1573 $dataobject->classname = $c;
1574 $dataobject->filename = $f;
1576 if (is_string($method)) {
1577 $dataobject->functionname = $method;
1579 } else if (is_array($method)) { // wants to override file or class
1580 $dataobject->functionname = $method['method'];
1581 $dataobject->classname = $method['classname'];
1582 $dataobject->filename = $method['filename'];
1584 $dataobject->xmlrpcpath = $type.'/'.$plugin.'/'.$dataobject->filename.'/'.$method;
1585 $dataobject->static = false;
1587 require_once($path . '/' . $dataobject->filename);
1588 $functionreflect = null; // slightly different ways to get this depending on whether it's a class method or a function
1589 if (!empty($dataobject->classname)) {
1590 if (!class_exists($dataobject->classname)) {
1591 throw new moodle_exception('installnosuchmethod', 'mnet', '', (object)array('method' => $dataobject->functionname, 'class' => $dataobject->classname));
1593 $key = $dataobject->filename . '|' . $dataobject->classname;
1594 if (!array_key_exists($key, $cachedclasses)) { // look to see if we've already got a reflection object
1595 try {
1596 $cachedclasses[$key] = Zend_Server_Reflection::reflectClass($dataobject->classname);
1597 } catch (Zend_Server_Reflection_Exception $e) { // catch these and rethrow them to something more helpful
1598 throw new moodle_exception('installreflectionclasserror', 'mnet', '', (object)array('method' => $dataobject->functionname, 'class' => $dataobject->classname, 'error' => $e->getMessage()));
1601 $r =& $cachedclasses[$key];
1602 if (!$r->hasMethod($dataobject->functionname)) {
1603 throw new moodle_exception('installnosuchmethod', 'mnet', '', (object)array('method' => $dataobject->functionname, 'class' => $dataobject->classname));
1605 // stupid workaround for zend not having a getMethod($name) function
1606 $ms = $r->getMethods();
1607 foreach ($ms as $m) {
1608 if ($m->getName() == $dataobject->functionname) {
1609 $functionreflect = $m;
1610 break;
1613 $dataobject->static = (int)$functionreflect->isStatic();
1614 } else {
1615 if (!function_exists($dataobject->functionname)) {
1616 throw new moodle_exception('installnosuchfunction', 'mnet', '', (object)array('method' => $dataobject->functionname, 'file' => $dataobject->filename));
1618 try {
1619 $functionreflect = Zend_Server_Reflection::reflectFunction($dataobject->functionname);
1620 } catch (Zend_Server_Reflection_Exception $e) { // catch these and rethrow them to something more helpful
1621 throw new moodle_exception('installreflectionfunctionerror', 'mnet', '', (object)array('method' => $dataobject->functionname, '' => $dataobject->filename, 'error' => $e->getMessage()));
1624 $dataobject->profile = serialize(admin_mnet_method_profile($functionreflect));
1625 $dataobject->help = $functionreflect->getDescription();
1627 if ($record_exists = $DB->get_record('mnet_rpc', array('xmlrpcpath'=>$dataobject->xmlrpcpath))) {
1628 $dataobject->id = $record_exists->id;
1629 $dataobject->enabled = $record_exists->enabled;
1630 $DB->update_record('mnet_rpc', $dataobject);
1631 } else {
1632 $dataobject->id = $DB->insert_record('mnet_rpc', $dataobject, true);
1635 // TODO this API versioning must be reworked, here the recently processed method
1636 // sets the service API which may not be correct
1637 foreach ($publishmethodservices[$dataobject->functionname] as $service) {
1638 if ($serviceobj = $DB->get_record('mnet_service', array('name'=>$service['servicename']))) {
1639 $serviceobj->apiversion = $service['apiversion'];
1640 $DB->update_record('mnet_service', $serviceobj);
1641 } else {
1642 $serviceobj = new stdClass();
1643 $serviceobj->name = $service['servicename'];
1644 $serviceobj->description = empty($service['description']) ? '' : $service['description'];
1645 $serviceobj->apiversion = $service['apiversion'];
1646 $serviceobj->offer = 1;
1647 $serviceobj->id = $DB->insert_record('mnet_service', $serviceobj);
1649 $servicecache[$service['servicename']] = $serviceobj;
1650 if (!$DB->record_exists('mnet_service2rpc', array('rpcid'=>$dataobject->id, 'serviceid'=>$serviceobj->id))) {
1651 $obj = new stdClass();
1652 $obj->rpcid = $dataobject->id;
1653 $obj->serviceid = $serviceobj->id;
1654 $DB->insert_record('mnet_service2rpc', $obj, true);
1659 // finished with methods we publish, now do subscribable methods
1660 foreach($subscribes as $service => $methods) {
1661 if (!array_key_exists($service, $servicecache)) {
1662 if (!$serviceobj = $DB->get_record('mnet_service', array('name' => $service))) {
1663 debugging("TODO: skipping unknown service $service - somebody needs to fix MDL-21993");
1664 continue;
1666 $servicecache[$service] = $serviceobj;
1667 } else {
1668 $serviceobj = $servicecache[$service];
1670 foreach ($methods as $method => $xmlrpcpath) {
1671 if (!$rpcid = $DB->get_field('mnet_remote_rpc', 'id', array('xmlrpcpath'=>$xmlrpcpath))) {
1672 $remoterpc = (object)array(
1673 'functionname' => $method,
1674 'xmlrpcpath' => $xmlrpcpath,
1675 'plugintype' => $type,
1676 'pluginname' => $plugin,
1677 'enabled' => 1,
1679 $rpcid = $remoterpc->id = $DB->insert_record('mnet_remote_rpc', $remoterpc, true);
1681 if (!$DB->record_exists('mnet_remote_service2rpc', array('rpcid'=>$rpcid, 'serviceid'=>$serviceobj->id))) {
1682 $obj = new stdClass();
1683 $obj->rpcid = $rpcid;
1684 $obj->serviceid = $serviceobj->id;
1685 $DB->insert_record('mnet_remote_service2rpc', $obj, true);
1687 $subscribemethodservices[$method][] = $service;
1691 foreach ($DB->get_records('mnet_remote_rpc', array('pluginname'=>$plugin, 'plugintype'=>$type), 'functionname ASC ') as $rpc) {
1692 if (!array_key_exists($rpc->functionname, $subscribemethodservices) && $rpc->enabled) {
1693 $DB->set_field('mnet_remote_rpc', 'enabled', 0, array('id' => $rpc->id));
1694 } else if (array_key_exists($rpc->functionname, $subscribemethodservices) && !$rpc->enabled) {
1695 $DB->set_field('mnet_remote_rpc', 'enabled', 1, array('id' => $rpc->id));
1699 return true;
1703 * Given some sort of Zend Reflection function/method object, return a profile array, ready to be serialized and stored
1705 * @param Zend_Server_Reflection_Function_Abstract $function can be any subclass of this object type
1707 * @return array
1709 function admin_mnet_method_profile(Zend_Server_Reflection_Function_Abstract $function) {
1710 $protos = $function->getPrototypes();
1711 $proto = array_pop($protos);
1712 $ret = $proto->getReturnValue();
1713 $profile = array(
1714 'parameters' => array(),
1715 'return' => array(
1716 'type' => $ret->getType(),
1717 'description' => $ret->getDescription(),
1720 foreach ($proto->getParameters() as $p) {
1721 $profile['parameters'][] = array(
1722 'name' => $p->getName(),
1723 'type' => $p->getType(),
1724 'description' => $p->getDescription(),
1727 return $profile;