MDL-27925 A way to get the all the keys of the child nodes of a node.
[moodle.git] / lib / upgradelib.php
blobf6e6c74d78c3089645d7ab085cb9bf7e8a5fa6a0
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 if (!$result) {
118 throw new upgrade_exception(null, $version);
121 if ($CFG->version >= $version) {
122 // something really wrong is going on in main upgrade script
123 throw new downgrade_exception(null, $CFG->version, $version);
126 set_config('version', $version);
127 upgrade_log(UPGRADE_LOG_NORMAL, null, 'Upgrade savepoint reached');
129 // reset upgrade timeout to default
130 upgrade_set_timeout();
132 // this is a safe place to stop upgrades if user aborts page loading
133 if ($allowabort and connection_aborted()) {
134 die;
139 * Module upgrade savepoint, marks end of module upgrade blocks
140 * It stores module version, resets upgrade timeout
141 * and abort upgrade if user cancels page loading.
143 * @global object
144 * @param bool $result false if upgrade step failed, true if completed
145 * @param string or float $version main version
146 * @param string $modname name of module
147 * @param bool $allowabort allow user to abort script execution here
148 * @return void
150 function upgrade_mod_savepoint($result, $version, $modname, $allowabort=true) {
151 global $DB;
153 if (!$result) {
154 throw new upgrade_exception("mod_$modname", $version);
157 if (!$module = $DB->get_record('modules', array('name'=>$modname))) {
158 print_error('modulenotexist', 'debug', '', $modname);
161 if ($module->version >= $version) {
162 // something really wrong is going on in upgrade script
163 throw new downgrade_exception("mod_$modname", $module->version, $version);
165 $module->version = $version;
166 $DB->update_record('modules', $module);
167 upgrade_log(UPGRADE_LOG_NORMAL, "mod_$modname", 'Upgrade savepoint reached');
169 // reset upgrade timeout to default
170 upgrade_set_timeout();
172 // this is a safe place to stop upgrades if user aborts page loading
173 if ($allowabort and connection_aborted()) {
174 die;
179 * Blocks upgrade savepoint, marks end of blocks upgrade blocks
180 * It stores block version, resets upgrade timeout
181 * and abort upgrade if user cancels page loading.
183 * @global object
184 * @param bool $result false if upgrade step failed, true if completed
185 * @param string or float $version main version
186 * @param string $blockname name of block
187 * @param bool $allowabort allow user to abort script execution here
188 * @return void
190 function upgrade_block_savepoint($result, $version, $blockname, $allowabort=true) {
191 global $DB;
193 if (!$result) {
194 throw new upgrade_exception("block_$blockname", $version);
197 if (!$block = $DB->get_record('block', array('name'=>$blockname))) {
198 print_error('blocknotexist', 'debug', '', $blockname);
201 if ($block->version >= $version) {
202 // something really wrong is going on in upgrade script
203 throw new downgrade_exception("block_$blockname", $block->version, $version);
205 $block->version = $version;
206 $DB->update_record('block', $block);
207 upgrade_log(UPGRADE_LOG_NORMAL, "block_$blockname", 'Upgrade savepoint reached');
209 // reset upgrade timeout to default
210 upgrade_set_timeout();
212 // this is a safe place to stop upgrades if user aborts page loading
213 if ($allowabort and connection_aborted()) {
214 die;
219 * Plugins upgrade savepoint, marks end of blocks upgrade blocks
220 * It stores plugin version, resets upgrade timeout
221 * and abort upgrade if user cancels page loading.
223 * @param bool $result false if upgrade step failed, true if completed
224 * @param string or float $version main version
225 * @param string $type name of plugin
226 * @param string $dir location of plugin
227 * @param bool $allowabort allow user to abort script execution here
228 * @return void
230 function upgrade_plugin_savepoint($result, $version, $type, $plugin, $allowabort=true) {
231 $component = $type.'_'.$plugin;
233 if (!$result) {
234 throw new upgrade_exception($component, $version);
237 $installedversion = get_config($component, 'version');
238 if ($installedversion >= $version) {
239 // Something really wrong is going on in the upgrade script
240 throw new downgrade_exception($component, $installedversion, $version);
242 set_config('version', $version, $component);
243 upgrade_log(UPGRADE_LOG_NORMAL, $component, 'Upgrade savepoint reached');
245 // Reset upgrade timeout to default
246 upgrade_set_timeout();
248 // This is a safe place to stop upgrades if user aborts page loading
249 if ($allowabort and connection_aborted()) {
250 die;
256 * Upgrade plugins
257 * @param string $type The type of plugins that should be updated (e.g. 'enrol', 'qtype')
258 * return void
260 function upgrade_plugins($type, $startcallback, $endcallback, $verbose) {
261 global $CFG, $DB;
263 /// special cases
264 if ($type === 'mod') {
265 return upgrade_plugins_modules($startcallback, $endcallback, $verbose);
266 } else if ($type === 'block') {
267 return upgrade_plugins_blocks($startcallback, $endcallback, $verbose);
270 $plugs = get_plugin_list($type);
272 foreach ($plugs as $plug=>$fullplug) {
273 $component = $type.'_'.$plug; // standardised plugin name
275 // check plugin dir is valid name
276 $cplug = strtolower($plug);
277 $cplug = clean_param($cplug, PARAM_SAFEDIR);
278 $cplug = str_replace('-', '', $cplug);
279 if ($plug !== $cplug) {
280 throw new plugin_defective_exception($component, 'Invalid plugin directory name.');
283 if (!is_readable($fullplug.'/version.php')) {
284 continue;
287 $plugin = new stdClass();
288 require($fullplug.'/version.php'); // defines $plugin with version etc
290 // if plugin tells us it's full name we may check the location
291 if (isset($plugin->component)) {
292 if ($plugin->component !== $component) {
293 throw new plugin_defective_exception($component, 'Plugin installed in wrong folder.');
297 if (empty($plugin->version)) {
298 throw new plugin_defective_exception($component, 'Missing version value in version.php');
301 $plugin->name = $plug;
302 $plugin->fullname = $component;
305 if (!empty($plugin->requires)) {
306 if ($plugin->requires > $CFG->version) {
307 throw new upgrade_requires_exception($component, $plugin->version, $CFG->version, $plugin->requires);
308 } else if ($plugin->requires < 2010000000) {
309 throw new plugin_defective_exception($component, 'Plugin is not compatible with Moodle 2.x or later.');
313 // try to recover from interrupted install.php if needed
314 if (file_exists($fullplug.'/db/install.php')) {
315 if (get_config($plugin->fullname, 'installrunning')) {
316 require_once($fullplug.'/db/install.php');
317 $recover_install_function = 'xmldb_'.$plugin->fullname.'_install_recovery';
318 if (function_exists($recover_install_function)) {
319 $startcallback($component, true, $verbose);
320 $recover_install_function();
321 unset_config('installrunning', $plugin->fullname);
322 update_capabilities($component);
323 log_update_descriptions($component);
324 external_update_descriptions($component);
325 events_update_definition($component);
326 message_update_providers($component);
327 if ($type === 'message') {
328 message_update_processors($plug);
330 upgrade_plugin_mnet_functions($component);
331 $endcallback($component, true, $verbose);
336 $installedversion = get_config($plugin->fullname, 'version');
337 if (empty($installedversion)) { // new installation
338 $startcallback($component, true, $verbose);
340 /// Install tables if defined
341 if (file_exists($fullplug.'/db/install.xml')) {
342 $DB->get_manager()->install_from_xmldb_file($fullplug.'/db/install.xml');
345 /// store version
346 upgrade_plugin_savepoint(true, $plugin->version, $type, $plug, false);
348 /// execute post install file
349 if (file_exists($fullplug.'/db/install.php')) {
350 require_once($fullplug.'/db/install.php');
351 set_config('installrunning', 1, $plugin->fullname);
352 $post_install_function = 'xmldb_'.$plugin->fullname.'_install';
353 $post_install_function();
354 unset_config('installrunning', $plugin->fullname);
357 /// Install various components
358 update_capabilities($component);
359 log_update_descriptions($component);
360 external_update_descriptions($component);
361 events_update_definition($component);
362 message_update_providers($component);
363 if ($type === 'message') {
364 message_update_processors($plug);
366 upgrade_plugin_mnet_functions($component);
368 purge_all_caches();
369 $endcallback($component, true, $verbose);
371 } else if ($installedversion < $plugin->version) { // upgrade
372 /// Run the upgrade function for the plugin.
373 $startcallback($component, false, $verbose);
375 if (is_readable($fullplug.'/db/upgrade.php')) {
376 require_once($fullplug.'/db/upgrade.php'); // defines upgrading function
378 $newupgrade_function = 'xmldb_'.$plugin->fullname.'_upgrade';
379 $result = $newupgrade_function($installedversion);
380 } else {
381 $result = true;
384 $installedversion = get_config($plugin->fullname, 'version');
385 if ($installedversion < $plugin->version) {
386 // store version if not already there
387 upgrade_plugin_savepoint($result, $plugin->version, $type, $plug, false);
390 /// Upgrade various components
391 update_capabilities($component);
392 log_update_descriptions($component);
393 external_update_descriptions($component);
394 events_update_definition($component);
395 message_update_providers($component);
396 if ($type === 'message') {
397 message_update_processors($plug);
399 upgrade_plugin_mnet_functions($component);
401 purge_all_caches();
402 $endcallback($component, false, $verbose);
404 } else if ($installedversion > $plugin->version) {
405 throw new downgrade_exception($component, $installedversion, $plugin->version);
411 * Find and check all modules and load them up or upgrade them if necessary
413 * @global object
414 * @global object
416 function upgrade_plugins_modules($startcallback, $endcallback, $verbose) {
417 global $CFG, $DB;
419 $mods = get_plugin_list('mod');
421 foreach ($mods as $mod=>$fullmod) {
423 if ($mod === 'NEWMODULE') { // Someone has unzipped the template, ignore it
424 continue;
427 $component = 'mod_'.$mod;
429 // check module dir is valid name
430 $cmod = strtolower($mod);
431 $cmod = clean_param($cmod, PARAM_SAFEDIR);
432 $cmod = str_replace('-', '', $cmod);
433 $cmod = str_replace('_', '', $cmod); // modules MUST not have '_' in name and never will, sorry
434 if ($mod !== $cmod) {
435 throw new plugin_defective_exception($component, 'Invalid plugin directory name.');
438 if (!is_readable($fullmod.'/version.php')) {
439 throw new plugin_defective_exception($component, 'Missing version.php');
442 $module = new stdClass();
443 require($fullmod .'/version.php'); // defines $module with version etc
445 // if plugin tells us it's full name we may check the location
446 if (isset($module->component)) {
447 if ($module->component !== $component) {
448 throw new plugin_defective_exception($component, 'Plugin installed in wrong folder.');
452 if (empty($module->version)) {
453 if (isset($module->version)) {
454 // Version is empty but is set - it means its value is 0 or ''. Let us skip such module.
455 // This is intended for developers so they can work on the early stages of the module.
456 continue;
458 throw new plugin_defective_exception($component, 'Missing version value in version.php');
461 if (!empty($module->requires)) {
462 if ($module->requires > $CFG->version) {
463 throw new upgrade_requires_exception($component, $module->version, $CFG->version, $module->requires);
464 } else if ($module->requires < 2010000000) {
465 throw new plugin_defective_exception($component, 'Plugin is not compatible with Moodle 2.x or later.');
469 // all modules must have en lang pack
470 if (!is_readable("$fullmod/lang/en/$mod.php")) {
471 throw new plugin_defective_exception($component, 'Missing mandatory en language pack.');
474 $module->name = $mod; // The name MUST match the directory
476 $currmodule = $DB->get_record('modules', array('name'=>$module->name));
478 if (file_exists($fullmod.'/db/install.php')) {
479 if (get_config($module->name, 'installrunning')) {
480 require_once($fullmod.'/db/install.php');
481 $recover_install_function = 'xmldb_'.$module->name.'_install_recovery';
482 if (function_exists($recover_install_function)) {
483 $startcallback($component, true, $verbose);
484 $recover_install_function();
485 unset_config('installrunning', $module->name);
486 // Install various components too
487 update_capabilities($component);
488 log_update_descriptions($component);
489 external_update_descriptions($component);
490 events_update_definition($component);
491 message_update_providers($component);
492 upgrade_plugin_mnet_functions($component);
493 $endcallback($component, true, $verbose);
498 if (empty($currmodule->version)) {
499 $startcallback($component, true, $verbose);
501 /// Execute install.xml (XMLDB) - must be present in all modules
502 $DB->get_manager()->install_from_xmldb_file($fullmod.'/db/install.xml');
504 /// Add record into modules table - may be needed in install.php already
505 $module->id = $DB->insert_record('modules', $module);
507 /// Post installation hook - optional
508 if (file_exists("$fullmod/db/install.php")) {
509 require_once("$fullmod/db/install.php");
510 // Set installation running flag, we need to recover after exception or error
511 set_config('installrunning', 1, $module->name);
512 $post_install_function = 'xmldb_'.$module->name.'_install';;
513 $post_install_function();
514 unset_config('installrunning', $module->name);
517 /// Install various components
518 update_capabilities($component);
519 log_update_descriptions($component);
520 external_update_descriptions($component);
521 events_update_definition($component);
522 message_update_providers($component);
523 upgrade_plugin_mnet_functions($component);
525 purge_all_caches();
526 $endcallback($component, true, $verbose);
528 } else if ($currmodule->version < $module->version) {
529 /// If versions say that we need to upgrade but no upgrade files are available, notify and continue
530 $startcallback($component, false, $verbose);
532 if (is_readable($fullmod.'/db/upgrade.php')) {
533 require_once($fullmod.'/db/upgrade.php'); // defines new upgrading function
534 $newupgrade_function = 'xmldb_'.$module->name.'_upgrade';
535 $result = $newupgrade_function($currmodule->version, $module);
536 } else {
537 $result = true;
540 $currmodule = $DB->get_record('modules', array('name'=>$module->name));
541 if ($currmodule->version < $module->version) {
542 // store version if not already there
543 upgrade_mod_savepoint($result, $module->version, $mod, false);
546 /// Upgrade various components
547 update_capabilities($component);
548 log_update_descriptions($component);
549 external_update_descriptions($component);
550 events_update_definition($component);
551 message_update_providers($component);
552 upgrade_plugin_mnet_functions($component);
554 purge_all_caches();
556 $endcallback($component, false, $verbose);
558 } else if ($currmodule->version > $module->version) {
559 throw new downgrade_exception($component, $currmodule->version, $module->version);
566 * This function finds all available blocks and install them
567 * into blocks table or do all the upgrade process if newer.
569 * @global object
570 * @global object
572 function upgrade_plugins_blocks($startcallback, $endcallback, $verbose) {
573 global $CFG, $DB;
575 require_once($CFG->dirroot.'/blocks/moodleblock.class.php');
577 $blocktitles = array(); // we do not want duplicate titles
579 //Is this a first install
580 $first_install = null;
582 $blocks = get_plugin_list('block');
584 foreach ($blocks as $blockname=>$fullblock) {
586 if (is_null($first_install)) {
587 $first_install = ($DB->count_records('block_instances') == 0);
590 if ($blockname == 'NEWBLOCK') { // Someone has unzipped the template, ignore it
591 continue;
594 $component = 'block_'.$blockname;
596 // check block dir is valid name
597 $cblockname = strtolower($blockname);
598 $cblockname = clean_param($cblockname, PARAM_SAFEDIR);
599 $cblockname = str_replace('-', '', $cblockname);
600 if ($blockname !== $cblockname) {
601 throw new plugin_defective_exception($component, 'Invalid plugin directory name.');
604 if (!is_readable($fullblock.'/version.php')) {
605 throw new plugin_defective_exception('block/'.$blockname, 'Missing version.php file.');
607 $plugin = new stdClass();
608 $plugin->version = NULL;
609 $plugin->cron = 0;
610 include($fullblock.'/version.php');
611 $block = $plugin;
613 // if plugin tells us it's full name we may check the location
614 if (isset($block->component)) {
615 if ($block->component !== $component) {
616 throw new plugin_defective_exception($component, 'Plugin installed in wrong folder.');
620 if (!empty($plugin->requires)) {
621 if ($plugin->requires > $CFG->version) {
622 throw new upgrade_requires_exception($component, $plugin->version, $CFG->version, $plugin->requires);
623 } else if ($plugin->requires < 2010000000) {
624 throw new plugin_defective_exception($component, 'Plugin is not compatible with Moodle 2.x or later.');
628 if (!is_readable($fullblock.'/block_'.$blockname.'.php')) {
629 throw new plugin_defective_exception('block/'.$blockname, 'Missing main block class file.');
631 include_once($fullblock.'/block_'.$blockname.'.php');
633 $classname = 'block_'.$blockname;
635 if (!class_exists($classname)) {
636 throw new plugin_defective_exception($component, 'Can not load main class.');
639 $blockobj = new $classname; // This is what we'll be testing
640 $blocktitle = $blockobj->get_title();
642 // OK, it's as we all hoped. For further tests, the object will do them itself.
643 if (!$blockobj->_self_test()) {
644 throw new plugin_defective_exception($component, 'Self test failed.');
647 $block->name = $blockname; // The name MUST match the directory
649 if (empty($block->version)) {
650 throw new plugin_defective_exception($component, 'Missing block version.');
653 $currblock = $DB->get_record('block', array('name'=>$block->name));
655 if (file_exists($fullblock.'/db/install.php')) {
656 if (get_config('block_'.$blockname, 'installrunning')) {
657 require_once($fullblock.'/db/install.php');
658 $recover_install_function = 'xmldb_block_'.$blockname.'_install_recovery';
659 if (function_exists($recover_install_function)) {
660 $startcallback($component, true, $verbose);
661 $recover_install_function();
662 unset_config('installrunning', 'block_'.$blockname);
663 // Install various components
664 update_capabilities($component);
665 log_update_descriptions($component);
666 external_update_descriptions($component);
667 events_update_definition($component);
668 message_update_providers($component);
669 upgrade_plugin_mnet_functions($component);
670 $endcallback($component, true, $verbose);
675 if (empty($currblock->version)) { // block not installed yet, so install it
676 $conflictblock = array_search($blocktitle, $blocktitles);
677 if ($conflictblock !== false) {
678 // Duplicate block titles are not allowed, they confuse people
679 // AND PHP's associative arrays ;)
680 throw new plugin_defective_exception($component, get_string('blocknameconflict', 'error', (object)array('name'=>$block->name, 'conflict'=>$conflictblock)));
682 $startcallback($component, true, $verbose);
684 if (file_exists($fullblock.'/db/install.xml')) {
685 $DB->get_manager()->install_from_xmldb_file($fullblock.'/db/install.xml');
687 $block->id = $DB->insert_record('block', $block);
689 if (file_exists($fullblock.'/db/install.php')) {
690 require_once($fullblock.'/db/install.php');
691 // Set installation running flag, we need to recover after exception or error
692 set_config('installrunning', 1, 'block_'.$blockname);
693 $post_install_function = 'xmldb_block_'.$blockname.'_install';;
694 $post_install_function();
695 unset_config('installrunning', 'block_'.$blockname);
698 $blocktitles[$block->name] = $blocktitle;
700 // Install various components
701 update_capabilities($component);
702 log_update_descriptions($component);
703 external_update_descriptions($component);
704 events_update_definition($component);
705 message_update_providers($component);
706 upgrade_plugin_mnet_functions($component);
708 purge_all_caches();
709 $endcallback($component, true, $verbose);
711 } else if ($currblock->version < $block->version) {
712 $startcallback($component, false, $verbose);
714 if (is_readable($fullblock.'/db/upgrade.php')) {
715 require_once($fullblock.'/db/upgrade.php'); // defines new upgrading function
716 $newupgrade_function = 'xmldb_block_'.$blockname.'_upgrade';
717 $result = $newupgrade_function($currblock->version, $block);
718 } else {
719 $result = true;
722 $currblock = $DB->get_record('block', array('name'=>$block->name));
723 if ($currblock->version < $block->version) {
724 // store version if not already there
725 upgrade_block_savepoint($result, $block->version, $block->name, false);
728 if ($currblock->cron != $block->cron) {
729 // update cron flag if needed
730 $currblock->cron = $block->cron;
731 $DB->update_record('block', $currblock);
734 // Upgrade various components
735 update_capabilities($component);
736 log_update_descriptions($component);
737 external_update_descriptions($component);
738 events_update_definition($component);
739 message_update_providers($component);
740 upgrade_plugin_mnet_functions($component);
742 purge_all_caches();
743 $endcallback($component, false, $verbose);
745 } else if ($currblock->version > $block->version) {
746 throw new downgrade_exception($component, $currblock->version, $block->version);
751 // Finally, if we are in the first_install of BLOCKS setup frontpage and admin page blocks
752 if ($first_install) {
753 //Iterate over each course - there should be only site course here now
754 if ($courses = $DB->get_records('course')) {
755 foreach ($courses as $course) {
756 blocks_add_default_course_blocks($course);
760 blocks_add_default_system_blocks();
766 * Log_display description function used during install and upgrade.
768 * @param string $component name of component (moodle, mod_assignment, etc.)
769 * @return void
771 function log_update_descriptions($component) {
772 global $DB;
774 $defpath = get_component_directory($component).'/db/log.php';
776 if (!file_exists($defpath)) {
777 $DB->delete_records('log_display', array('component'=>$component));
778 return;
781 // load new info
782 $logs = array();
783 include($defpath);
784 $newlogs = array();
785 foreach ($logs as $log) {
786 $newlogs[$log['module'].'-'.$log['action']] = $log; // kind of unique name
788 unset($logs);
789 $logs = $newlogs;
791 $fields = array('module', 'action', 'mtable', 'field');
792 // update all log fist
793 $dblogs = $DB->get_records('log_display', array('component'=>$component));
794 foreach ($dblogs as $dblog) {
795 $name = $dblog->module.'-'.$dblog->action;
797 if (empty($logs[$name])) {
798 $DB->delete_records('log_display', array('id'=>$dblog->id));
799 continue;
802 $log = $logs[$name];
803 unset($logs[$name]);
805 $update = false;
806 foreach ($fields as $field) {
807 if ($dblog->$field != $log[$field]) {
808 $dblog->$field = $log[$field];
809 $update = true;
812 if ($update) {
813 $DB->update_record('log_display', $dblog);
816 foreach ($logs as $log) {
817 $dblog = (object)$log;
818 $dblog->component = $component;
819 $DB->insert_record('log_display', $dblog);
824 * Web service discovery function used during install and upgrade.
825 * @param string $component name of component (moodle, mod_assignment, etc.)
826 * @return void
828 function external_update_descriptions($component) {
829 global $DB;
831 $defpath = get_component_directory($component).'/db/services.php';
833 if (!file_exists($defpath)) {
834 external_delete_descriptions($component);
835 return;
838 // load new info
839 $functions = array();
840 $services = array();
841 include($defpath);
843 // update all function fist
844 $dbfunctions = $DB->get_records('external_functions', array('component'=>$component));
845 foreach ($dbfunctions as $dbfunction) {
846 if (empty($functions[$dbfunction->name])) {
847 $DB->delete_records('external_functions', array('id'=>$dbfunction->id));
848 // do not delete functions from external_services_functions, beacuse
849 // we want to notify admins when functions used in custom services disappear
851 //TODO: this looks wrong, we have to delete it eventually (skodak)
852 continue;
855 $function = $functions[$dbfunction->name];
856 unset($functions[$dbfunction->name]);
857 $function['classpath'] = empty($function['classpath']) ? null : $function['classpath'];
859 $update = false;
860 if ($dbfunction->classname != $function['classname']) {
861 $dbfunction->classname = $function['classname'];
862 $update = true;
864 if ($dbfunction->methodname != $function['methodname']) {
865 $dbfunction->methodname = $function['methodname'];
866 $update = true;
868 if ($dbfunction->classpath != $function['classpath']) {
869 $dbfunction->classpath = $function['classpath'];
870 $update = true;
872 $functioncapabilities = key_exists('capabilities', $function)?$function['capabilities']:'';
873 if ($dbfunction->capabilities != $functioncapabilities) {
874 $dbfunction->capabilities = $functioncapabilities;
875 $update = true;
877 if ($update) {
878 $DB->update_record('external_functions', $dbfunction);
881 foreach ($functions as $fname => $function) {
882 $dbfunction = new stdClass();
883 $dbfunction->name = $fname;
884 $dbfunction->classname = $function['classname'];
885 $dbfunction->methodname = $function['methodname'];
886 $dbfunction->classpath = empty($function['classpath']) ? null : $function['classpath'];
887 $dbfunction->component = $component;
888 $dbfunction->capabilities = key_exists('capabilities', $function)?$function['capabilities']:'';
889 $dbfunction->id = $DB->insert_record('external_functions', $dbfunction);
891 unset($functions);
893 // now deal with services
894 $dbservices = $DB->get_records('external_services', array('component'=>$component));
895 foreach ($dbservices as $dbservice) {
896 if (empty($services[$dbservice->name])) {
897 $DB->delete_records('external_services_functions', array('externalserviceid'=>$dbservice->id));
898 $DB->delete_records('external_services_users', array('externalserviceid'=>$dbservice->id));
899 $DB->delete_records('external_services', array('id'=>$dbservice->id));
900 continue;
902 $service = $services[$dbservice->name];
903 unset($services[$dbservice->name]);
904 $service['enabled'] = empty($service['enabled']) ? 0 : $service['enabled'];
905 $service['requiredcapability'] = empty($service['requiredcapability']) ? null : $service['requiredcapability'];
906 $service['restrictedusers'] = !isset($service['restrictedusers']) ? 1 : $service['restrictedusers'];
907 $service['shortname'] = !isset($service['shortname']) ? null : $service['shortname'];
909 $update = false;
910 if ($dbservice->requiredcapability != $service['requiredcapability']) {
911 $dbservice->requiredcapability = $service['requiredcapability'];
912 $update = true;
914 if ($dbservice->restrictedusers != $service['restrictedusers']) {
915 $dbservice->restrictedusers = $service['restrictedusers'];
916 $update = true;
918 //if shortname is not a PARAM_ALPHANUMEXT, fail (tested here for service update and creation)
919 if (isset($service['shortname']) and
920 (clean_param($service['shortname'], PARAM_ALPHANUMEXT) != $service['shortname'])) {
921 throw new moodle_exception('installserviceshortnameerror', 'webservice', '', $service['shortname']);
923 if ($dbservice->shortname != $service['shortname']) {
924 //check that shortname is unique
925 if (isset($service['shortname'])) { //we currently accepts multiple shortname == null
926 $existingservice = $DB->get_record('external_services',
927 array('shortname' => $service['shortname']));
928 if (!empty($existingservice)) {
929 throw new moodle_exception('installexistingserviceshortnameerror', 'webservice', '', $service['shortname']);
932 $dbservice->shortname = $service['shortname'];
933 $update = true;
935 if ($update) {
936 $DB->update_record('external_services', $dbservice);
939 $functions = $DB->get_records('external_services_functions', array('externalserviceid'=>$dbservice->id));
940 foreach ($functions as $function) {
941 $key = array_search($function->functionname, $service['functions']);
942 if ($key === false) {
943 $DB->delete_records('external_services_functions', array('id'=>$function->id));
944 } else {
945 unset($service['functions'][$key]);
948 foreach ($service['functions'] as $fname) {
949 $newf = new stdClass();
950 $newf->externalserviceid = $dbservice->id;
951 $newf->functionname = $fname;
952 $DB->insert_record('external_services_functions', $newf);
954 unset($functions);
956 foreach ($services as $name => $service) {
957 //check that shortname is unique
958 if (isset($service['shortname'])) { //we currently accepts multiple shortname == null
959 $existingservice = $DB->get_record('external_services',
960 array('shortname' => $service['shortname']));
961 if (!empty($existingservice)) {
962 throw new moodle_exception('installserviceshortnameerror', 'webservice');
966 $dbservice = new stdClass();
967 $dbservice->name = $name;
968 $dbservice->enabled = empty($service['enabled']) ? 0 : $service['enabled'];
969 $dbservice->requiredcapability = empty($service['requiredcapability']) ? null : $service['requiredcapability'];
970 $dbservice->restrictedusers = !isset($service['restrictedusers']) ? 1 : $service['restrictedusers'];
971 $dbservice->shortname = !isset($service['shortname']) ? null : $service['shortname'];
972 $dbservice->component = $component;
973 $dbservice->timecreated = time();
974 $dbservice->id = $DB->insert_record('external_services', $dbservice);
975 foreach ($service['functions'] as $fname) {
976 $newf = new stdClass();
977 $newf->externalserviceid = $dbservice->id;
978 $newf->functionname = $fname;
979 $DB->insert_record('external_services_functions', $newf);
985 * Delete all service and external functions information defined in the specified component.
986 * @param string $component name of component (moodle, mod_assignment, etc.)
987 * @return void
989 function external_delete_descriptions($component) {
990 global $DB;
992 $params = array($component);
994 $DB->delete_records_select('external_services_users', "externalserviceid IN (SELECT id FROM {external_services} WHERE component = ?)", $params);
995 $DB->delete_records_select('external_services_functions', "externalserviceid IN (SELECT id FROM {external_services} WHERE component = ?)", $params);
996 $DB->delete_records('external_services', array('component'=>$component));
997 $DB->delete_records('external_functions', array('component'=>$component));
1001 * upgrade logging functions
1003 function upgrade_handle_exception($ex, $plugin = null) {
1004 global $CFG;
1006 // rollback everything, we need to log all upgrade problems
1007 abort_all_db_transactions();
1009 $info = get_exception_info($ex);
1011 // First log upgrade error
1012 upgrade_log(UPGRADE_LOG_ERROR, $plugin, 'Exception: ' . get_class($ex), $info->message, $info->backtrace);
1014 // Always turn on debugging - admins need to know what is going on
1015 $CFG->debug = DEBUG_DEVELOPER;
1017 default_exception_handler($ex, true, $plugin);
1021 * Adds log entry into upgrade_log table
1023 * @param int $type UPGRADE_LOG_NORMAL, UPGRADE_LOG_NOTICE or UPGRADE_LOG_ERROR
1024 * @param string $plugin frankenstyle component name
1025 * @param string $info short description text of log entry
1026 * @param string $details long problem description
1027 * @param string $backtrace string used for errors only
1028 * @return void
1030 function upgrade_log($type, $plugin, $info, $details=null, $backtrace=null) {
1031 global $DB, $USER, $CFG;
1033 if (empty($plugin)) {
1034 $plugin = 'core';
1037 list($plugintype, $pluginname) = normalize_component($plugin);
1038 $component = is_null($pluginname) ? $plugintype : $plugintype . '_' . $pluginname;
1040 $backtrace = format_backtrace($backtrace, true);
1042 $currentversion = null;
1043 $targetversion = null;
1045 //first try to find out current version number
1046 if ($plugintype === 'core') {
1047 //main
1048 $currentversion = $CFG->version;
1050 $version = null;
1051 include("$CFG->dirroot/version.php");
1052 $targetversion = $version;
1054 } else if ($plugintype === 'mod') {
1055 try {
1056 $currentversion = $DB->get_field('modules', 'version', array('name'=>$pluginname));
1057 $currentversion = ($currentversion === false) ? null : $currentversion;
1058 } catch (Exception $ignored) {
1060 $cd = get_component_directory($component);
1061 if (file_exists("$cd/version.php")) {
1062 $module = new stdClass();
1063 $module->version = null;
1064 include("$cd/version.php");
1065 $targetversion = $module->version;
1068 } else if ($plugintype === 'block') {
1069 try {
1070 if ($block = $DB->get_record('block', array('name'=>$pluginname))) {
1071 $currentversion = $block->version;
1073 } catch (Exception $ignored) {
1075 $cd = get_component_directory($component);
1076 if (file_exists("$cd/version.php")) {
1077 $plugin = new stdClass();
1078 $plugin->version = null;
1079 include("$cd/version.php");
1080 $targetversion = $plugin->version;
1083 } else {
1084 $pluginversion = get_config($component, 'version');
1085 if (!empty($pluginversion)) {
1086 $currentversion = $pluginversion;
1088 $cd = get_component_directory($component);
1089 if (file_exists("$cd/version.php")) {
1090 $plugin = new stdClass();
1091 $plugin->version = null;
1092 include("$cd/version.php");
1093 $targetversion = $plugin->version;
1097 $log = new stdClass();
1098 $log->type = $type;
1099 $log->plugin = $component;
1100 $log->version = $currentversion;
1101 $log->targetversion = $targetversion;
1102 $log->info = $info;
1103 $log->details = $details;
1104 $log->backtrace = $backtrace;
1105 $log->userid = $USER->id;
1106 $log->timemodified = time();
1107 try {
1108 $DB->insert_record('upgrade_log', $log);
1109 } catch (Exception $ignored) {
1110 // possible during install or 2.0 upgrade
1115 * Marks start of upgrade, blocks any other access to site.
1116 * The upgrade is finished at the end of script or after timeout.
1118 * @global object
1119 * @global object
1120 * @global object
1122 function upgrade_started($preinstall=false) {
1123 global $CFG, $DB, $PAGE, $OUTPUT;
1125 static $started = false;
1127 if ($preinstall) {
1128 ignore_user_abort(true);
1129 upgrade_setup_debug(true);
1131 } else if ($started) {
1132 upgrade_set_timeout(120);
1134 } else {
1135 if (!CLI_SCRIPT and !$PAGE->headerprinted) {
1136 $strupgrade = get_string('upgradingversion', 'admin');
1137 $PAGE->set_pagelayout('maintenance');
1138 upgrade_init_javascript();
1139 $PAGE->set_title($strupgrade.' - Moodle '.$CFG->target_release);
1140 $PAGE->set_heading($strupgrade);
1141 $PAGE->navbar->add($strupgrade);
1142 $PAGE->set_cacheable(false);
1143 echo $OUTPUT->header();
1146 ignore_user_abort(true);
1147 register_shutdown_function('upgrade_finished_handler');
1148 upgrade_setup_debug(true);
1149 set_config('upgraderunning', time()+300);
1150 $started = true;
1155 * Internal function - executed if upgrade interrupted.
1157 function upgrade_finished_handler() {
1158 upgrade_finished();
1162 * Indicates upgrade is finished.
1164 * This function may be called repeatedly.
1166 * @global object
1167 * @global object
1169 function upgrade_finished($continueurl=null) {
1170 global $CFG, $DB, $OUTPUT;
1172 if (!empty($CFG->upgraderunning)) {
1173 unset_config('upgraderunning');
1174 upgrade_setup_debug(false);
1175 ignore_user_abort(false);
1176 if ($continueurl) {
1177 echo $OUTPUT->continue_button($continueurl);
1178 echo $OUTPUT->footer();
1179 die;
1185 * @global object
1186 * @global object
1188 function upgrade_setup_debug($starting) {
1189 global $CFG, $DB;
1191 static $originaldebug = null;
1193 if ($starting) {
1194 if ($originaldebug === null) {
1195 $originaldebug = $DB->get_debug();
1197 if (!empty($CFG->upgradeshowsql)) {
1198 $DB->set_debug(true);
1200 } else {
1201 $DB->set_debug($originaldebug);
1206 * @global object
1208 function print_upgrade_reload($url) {
1209 global $OUTPUT;
1211 echo "<br />";
1212 echo '<div class="continuebutton">';
1213 echo '<a href="'.$url.'" title="'.get_string('reload').'" ><img src="'.$OUTPUT->pix_url('i/reload') . '" alt="" /> '.get_string('reload').'</a>';
1214 echo '</div><br />';
1217 function print_upgrade_separator() {
1218 if (!CLI_SCRIPT) {
1219 echo '<hr />';
1224 * Default start upgrade callback
1225 * @param string $plugin
1226 * @param bool $installation true if installation, false means upgrade
1228 function print_upgrade_part_start($plugin, $installation, $verbose) {
1229 global $OUTPUT;
1230 if (empty($plugin) or $plugin == 'moodle') {
1231 upgrade_started($installation); // does not store upgrade running flag yet
1232 if ($verbose) {
1233 echo $OUTPUT->heading(get_string('coresystem'));
1235 } else {
1236 upgrade_started();
1237 if ($verbose) {
1238 echo $OUTPUT->heading($plugin);
1241 if ($installation) {
1242 if (empty($plugin) or $plugin == 'moodle') {
1243 // no need to log - log table not yet there ;-)
1244 } else {
1245 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Starting plugin installation');
1247 } else {
1248 if (empty($plugin) or $plugin == 'moodle') {
1249 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Starting core upgrade');
1250 } else {
1251 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Starting plugin upgrade');
1257 * Default end upgrade callback
1258 * @param string $plugin
1259 * @param bool $installation true if installation, false means upgrade
1261 function print_upgrade_part_end($plugin, $installation, $verbose) {
1262 global $OUTPUT;
1263 upgrade_started();
1264 if ($installation) {
1265 if (empty($plugin) or $plugin == 'moodle') {
1266 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Core installed');
1267 } else {
1268 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Plugin installed');
1270 } else {
1271 if (empty($plugin) or $plugin == 'moodle') {
1272 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Core upgraded');
1273 } else {
1274 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Plugin upgraded');
1277 if ($verbose) {
1278 echo $OUTPUT->notification(get_string('success'), 'notifysuccess');
1279 print_upgrade_separator();
1284 * Sets up JS code required for all upgrade scripts.
1285 * @global object
1287 function upgrade_init_javascript() {
1288 global $PAGE;
1289 // scroll to the end of each upgrade page so that ppl see either error or continue button,
1290 // no need to scroll continuously any more, it is enough to jump to end once the footer is printed ;-)
1291 $js = "window.scrollTo(0, 5000000);";
1292 $PAGE->requires->js_init_code($js);
1296 * Try to upgrade the given language pack (or current language)
1298 * @param string $lang the code of the language to update, defaults to the current language
1300 function upgrade_language_pack($lang='') {
1301 global $CFG, $OUTPUT;
1303 get_string_manager()->reset_caches();
1305 if (empty($lang)) {
1306 $lang = current_language();
1309 if ($lang == 'en') {
1310 return true; // Nothing to do
1313 upgrade_started(false);
1314 echo $OUTPUT->heading(get_string('langimport', 'admin').': '.$lang);
1316 @mkdir ($CFG->dataroot.'/temp/'); //make it in case it's a fresh install, it might not be there
1317 @mkdir ($CFG->dataroot.'/lang/');
1319 require_once($CFG->libdir.'/componentlib.class.php');
1321 $installer = new lang_installer($lang);
1322 $results = $installer->run();
1323 foreach ($results as $langcode => $langstatus) {
1324 switch ($langstatus) {
1325 case lang_installer::RESULT_DOWNLOADERROR:
1326 echo $OUTPUT->notification($langcode . '.zip');
1327 break;
1328 case lang_installer::RESULT_INSTALLED:
1329 echo $OUTPUT->notification(get_string('langpackinstalled', 'admin', $langcode), 'notifysuccess');
1330 break;
1331 case lang_installer::RESULT_UPTODATE:
1332 echo $OUTPUT->notification(get_string('langpackuptodate', 'admin', $langcode), 'notifysuccess');
1333 break;
1337 get_string_manager()->reset_caches();
1339 print_upgrade_separator();
1343 * Install core moodle tables and initialize
1344 * @param float $version target version
1345 * @param bool $verbose
1346 * @return void, may throw exception
1348 function install_core($version, $verbose) {
1349 global $CFG, $DB;
1351 try {
1352 set_time_limit(600);
1353 print_upgrade_part_start('moodle', true, $verbose); // does not store upgrade running flag
1355 $DB->get_manager()->install_from_xmldb_file("$CFG->libdir/db/install.xml");
1356 upgrade_started(); // we want the flag to be stored in config table ;-)
1358 // set all core default records and default settings
1359 require_once("$CFG->libdir/db/install.php");
1360 xmldb_main_install(); // installs the capabilities too
1362 // store version
1363 upgrade_main_savepoint(true, $version, false);
1365 // Continue with the installation
1366 log_update_descriptions('moodle');
1367 external_update_descriptions('moodle');
1368 events_update_definition('moodle');
1369 message_update_providers('moodle');
1371 // Write default settings unconditionally
1372 admin_apply_default_settings(NULL, true);
1374 print_upgrade_part_end(null, true, $verbose);
1375 } catch (exception $ex) {
1376 upgrade_handle_exception($ex);
1381 * Upgrade moodle core
1382 * @param float $version target version
1383 * @param bool $verbose
1384 * @return void, may throw exception
1386 function upgrade_core($version, $verbose) {
1387 global $CFG;
1389 raise_memory_limit(MEMORY_EXTRA);
1391 require_once($CFG->libdir.'/db/upgrade.php'); // Defines upgrades
1393 try {
1394 // Reset caches before any output
1395 purge_all_caches();
1397 // Upgrade current language pack if we can
1398 if (empty($CFG->skiplangupgrade)) {
1399 if (get_string_manager()->translation_exists(current_language())) {
1400 upgrade_language_pack(false);
1404 print_upgrade_part_start('moodle', false, $verbose);
1406 // one time special local migration pre 2.0 upgrade script
1407 if ($CFG->version < 2007101600) {
1408 $pre20upgradefile = "$CFG->dirroot/local/upgrade_pre20.php";
1409 if (file_exists($pre20upgradefile)) {
1410 set_time_limit(0);
1411 require($pre20upgradefile);
1412 // reset upgrade timeout to default
1413 upgrade_set_timeout();
1417 $result = xmldb_main_upgrade($CFG->version);
1418 if ($version > $CFG->version) {
1419 // store version if not already there
1420 upgrade_main_savepoint($result, $version, false);
1423 // perform all other component upgrade routines
1424 update_capabilities('moodle');
1425 log_update_descriptions('moodle');
1426 external_update_descriptions('moodle');
1427 events_update_definition('moodle');
1428 message_update_providers('moodle');
1430 // Reset caches again, just to be sure
1431 purge_all_caches();
1433 // Clean up contexts - more and more stuff depends on existence of paths and contexts
1434 cleanup_contexts();
1435 create_contexts();
1436 build_context_path();
1437 $syscontext = get_context_instance(CONTEXT_SYSTEM);
1438 mark_context_dirty($syscontext->path);
1440 print_upgrade_part_end('moodle', false, $verbose);
1441 } catch (Exception $ex) {
1442 upgrade_handle_exception($ex);
1447 * Upgrade/install other parts of moodle
1448 * @param bool $verbose
1449 * @return void, may throw exception
1451 function upgrade_noncore($verbose) {
1452 global $CFG;
1454 raise_memory_limit(MEMORY_EXTRA);
1456 // upgrade all plugins types
1457 try {
1458 $plugintypes = get_plugin_types();
1459 foreach ($plugintypes as $type=>$location) {
1460 upgrade_plugins($type, 'print_upgrade_part_start', 'print_upgrade_part_end', $verbose);
1462 } catch (Exception $ex) {
1463 upgrade_handle_exception($ex);
1468 * Checks if the main tables have been installed yet or not.
1469 * @return bool
1471 function core_tables_exist() {
1472 global $DB;
1474 if (!$tables = $DB->get_tables() ) { // No tables yet at all.
1475 return false;
1477 } else { // Check for missing main tables
1478 $mtables = array('config', 'course', 'groupings'); // some tables used in 1.9 and 2.0, preferable something from the start and end of install.xml
1479 foreach ($mtables as $mtable) {
1480 if (!in_array($mtable, $tables)) {
1481 return false;
1484 return true;
1489 * upgrades the mnet rpc definitions for the given component.
1490 * this method doesn't return status, an exception will be thrown in the case of an error
1492 * @param string $component the plugin to upgrade, eg auth_mnet
1494 function upgrade_plugin_mnet_functions($component) {
1495 global $DB, $CFG;
1497 list($type, $plugin) = explode('_', $component);
1498 $path = get_plugin_directory($type, $plugin);
1500 $publishes = array();
1501 $subscribes = array();
1502 if (file_exists($path . '/db/mnet.php')) {
1503 require_once($path . '/db/mnet.php'); // $publishes comes from this file
1505 if (empty($publishes)) {
1506 $publishes = array(); // still need this to be able to disable stuff later
1508 if (empty($subscribes)) {
1509 $subscribes = array(); // still need this to be able to disable stuff later
1512 static $servicecache = array();
1514 // rekey an array based on the rpc method for easy lookups later
1515 $publishmethodservices = array();
1516 $subscribemethodservices = array();
1517 foreach($publishes as $servicename => $service) {
1518 if (is_array($service['methods'])) {
1519 foreach($service['methods'] as $methodname) {
1520 $service['servicename'] = $servicename;
1521 $publishmethodservices[$methodname][] = $service;
1526 // Disable functions that don't exist (any more) in the source
1527 // Should these be deleted? What about their permissions records?
1528 foreach ($DB->get_records('mnet_rpc', array('pluginname'=>$plugin, 'plugintype'=>$type), 'functionname ASC ') as $rpc) {
1529 if (!array_key_exists($rpc->functionname, $publishmethodservices) && $rpc->enabled) {
1530 $DB->set_field('mnet_rpc', 'enabled', 0, array('id' => $rpc->id));
1531 } else if (array_key_exists($rpc->functionname, $publishmethodservices) && !$rpc->enabled) {
1532 $DB->set_field('mnet_rpc', 'enabled', 1, array('id' => $rpc->id));
1536 // reflect all the services we're publishing and save them
1537 require_once($CFG->dirroot . '/lib/zend/Zend/Server/Reflection.php');
1538 static $cachedclasses = array(); // to store reflection information in
1539 foreach ($publishes as $service => $data) {
1540 $f = $data['filename'];
1541 $c = $data['classname'];
1542 foreach ($data['methods'] as $method) {
1543 $dataobject = new stdClass();
1544 $dataobject->plugintype = $type;
1545 $dataobject->pluginname = $plugin;
1546 $dataobject->enabled = 1;
1547 $dataobject->classname = $c;
1548 $dataobject->filename = $f;
1550 if (is_string($method)) {
1551 $dataobject->functionname = $method;
1553 } else if (is_array($method)) { // wants to override file or class
1554 $dataobject->functionname = $method['method'];
1555 $dataobject->classname = $method['classname'];
1556 $dataobject->filename = $method['filename'];
1558 $dataobject->xmlrpcpath = $type.'/'.$plugin.'/'.$dataobject->filename.'/'.$method;
1559 $dataobject->static = false;
1561 require_once($path . '/' . $dataobject->filename);
1562 $functionreflect = null; // slightly different ways to get this depending on whether it's a class method or a function
1563 if (!empty($dataobject->classname)) {
1564 if (!class_exists($dataobject->classname)) {
1565 throw new moodle_exception('installnosuchmethod', 'mnet', '', (object)array('method' => $dataobject->functionname, 'class' => $dataobject->classname));
1567 $key = $dataobject->filename . '|' . $dataobject->classname;
1568 if (!array_key_exists($key, $cachedclasses)) { // look to see if we've already got a reflection object
1569 try {
1570 $cachedclasses[$key] = Zend_Server_Reflection::reflectClass($dataobject->classname);
1571 } catch (Zend_Server_Reflection_Exception $e) { // catch these and rethrow them to something more helpful
1572 throw new moodle_exception('installreflectionclasserror', 'mnet', '', (object)array('method' => $dataobject->functionname, 'class' => $dataobject->classname, 'error' => $e->getMessage()));
1575 $r =& $cachedclasses[$key];
1576 if (!$r->hasMethod($dataobject->functionname)) {
1577 throw new moodle_exception('installnosuchmethod', 'mnet', '', (object)array('method' => $dataobject->functionname, 'class' => $dataobject->classname));
1579 // stupid workaround for zend not having a getMethod($name) function
1580 $ms = $r->getMethods();
1581 foreach ($ms as $m) {
1582 if ($m->getName() == $dataobject->functionname) {
1583 $functionreflect = $m;
1584 break;
1587 $dataobject->static = (int)$functionreflect->isStatic();
1588 } else {
1589 if (!function_exists($dataobject->functionname)) {
1590 throw new moodle_exception('installnosuchfunction', 'mnet', '', (object)array('method' => $dataobject->functionname, 'file' => $dataobject->filename));
1592 try {
1593 $functionreflect = Zend_Server_Reflection::reflectFunction($dataobject->functionname);
1594 } catch (Zend_Server_Reflection_Exception $e) { // catch these and rethrow them to something more helpful
1595 throw new moodle_exception('installreflectionfunctionerror', 'mnet', '', (object)array('method' => $dataobject->functionname, '' => $dataobject->filename, 'error' => $e->getMessage()));
1598 $dataobject->profile = serialize(admin_mnet_method_profile($functionreflect));
1599 $dataobject->help = $functionreflect->getDescription();
1601 if ($record_exists = $DB->get_record('mnet_rpc', array('xmlrpcpath'=>$dataobject->xmlrpcpath))) {
1602 $dataobject->id = $record_exists->id;
1603 $dataobject->enabled = $record_exists->enabled;
1604 $DB->update_record('mnet_rpc', $dataobject);
1605 } else {
1606 $dataobject->id = $DB->insert_record('mnet_rpc', $dataobject, true);
1609 // TODO this API versioning must be reworked, here the recently processed method
1610 // sets the service API which may not be correct
1611 foreach ($publishmethodservices[$dataobject->functionname] as $service) {
1612 if ($serviceobj = $DB->get_record('mnet_service', array('name'=>$service['servicename']))) {
1613 $serviceobj->apiversion = $service['apiversion'];
1614 $DB->update_record('mnet_service', $serviceobj);
1615 } else {
1616 $serviceobj = new stdClass();
1617 $serviceobj->name = $service['servicename'];
1618 $serviceobj->description = empty($service['description']) ? '' : $service['description'];
1619 $serviceobj->apiversion = $service['apiversion'];
1620 $serviceobj->offer = 1;
1621 $serviceobj->id = $DB->insert_record('mnet_service', $serviceobj);
1623 $servicecache[$service['servicename']] = $serviceobj;
1624 if (!$DB->record_exists('mnet_service2rpc', array('rpcid'=>$dataobject->id, 'serviceid'=>$serviceobj->id))) {
1625 $obj = new stdClass();
1626 $obj->rpcid = $dataobject->id;
1627 $obj->serviceid = $serviceobj->id;
1628 $DB->insert_record('mnet_service2rpc', $obj, true);
1633 // finished with methods we publish, now do subscribable methods
1634 foreach($subscribes as $service => $methods) {
1635 if (!array_key_exists($service, $servicecache)) {
1636 if (!$serviceobj = $DB->get_record('mnet_service', array('name' => $service))) {
1637 debugging("TODO: skipping unknown service $service - somebody needs to fix MDL-21993");
1638 continue;
1640 $servicecache[$service] = $serviceobj;
1641 } else {
1642 $serviceobj = $servicecache[$service];
1644 foreach ($methods as $method => $xmlrpcpath) {
1645 if (!$rpcid = $DB->get_field('mnet_remote_rpc', 'id', array('xmlrpcpath'=>$xmlrpcpath))) {
1646 $remoterpc = (object)array(
1647 'functionname' => $method,
1648 'xmlrpcpath' => $xmlrpcpath,
1649 'plugintype' => $type,
1650 'pluginname' => $plugin,
1651 'enabled' => 1,
1653 $rpcid = $remoterpc->id = $DB->insert_record('mnet_remote_rpc', $remoterpc, true);
1655 if (!$DB->record_exists('mnet_remote_service2rpc', array('rpcid'=>$rpcid, 'serviceid'=>$serviceobj->id))) {
1656 $obj = new stdClass();
1657 $obj->rpcid = $rpcid;
1658 $obj->serviceid = $serviceobj->id;
1659 $DB->insert_record('mnet_remote_service2rpc', $obj, true);
1661 $subscribemethodservices[$method][] = $service;
1665 foreach ($DB->get_records('mnet_remote_rpc', array('pluginname'=>$plugin, 'plugintype'=>$type), 'functionname ASC ') as $rpc) {
1666 if (!array_key_exists($rpc->functionname, $subscribemethodservices) && $rpc->enabled) {
1667 $DB->set_field('mnet_remote_rpc', 'enabled', 0, array('id' => $rpc->id));
1668 } else if (array_key_exists($rpc->functionname, $subscribemethodservices) && !$rpc->enabled) {
1669 $DB->set_field('mnet_remote_rpc', 'enabled', 1, array('id' => $rpc->id));
1673 return true;
1677 * Given some sort of Zend Reflection function/method object, return a profile array, ready to be serialized and stored
1679 * @param Zend_Server_Reflection_Function_Abstract $function can be any subclass of this object type
1681 * @return array
1683 function admin_mnet_method_profile(Zend_Server_Reflection_Function_Abstract $function) {
1684 $proto = array_pop($function->getPrototypes());
1685 $ret = $proto->getReturnValue();
1686 $profile = array(
1687 'parameters' => array(),
1688 'return' => array(
1689 'type' => $ret->getType(),
1690 'description' => $ret->getDescription(),
1693 foreach ($proto->getParameters() as $p) {
1694 $profile['parameters'][] = array(
1695 'name' => $p->getName(),
1696 'type' => $p->getType(),
1697 'description' => $p->getDescription(),
1700 return $profile;