3 // This file is part of Moodle - http://moodle.org/
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.
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/>.
19 * Various upgrade/install related functions and classes.
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);
37 * Exception indicating unknown error during 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) {
47 $a = (object)array('plugin'=>$plugin, 'version'=>$version);
48 parent::__construct('upgradeerror', 'admin', "$CFG->wwwroot/$CFG->admin/index.php", $a, $debuginfo);
53 * Exception indicating downgrade error during 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) {
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);
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) {
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);
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) {
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.
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
114 function upgrade_main_savepoint($result, $version, $allowabort=true) {
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);
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()) {
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.
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
156 function upgrade_mod_savepoint($result, $version, $modname, $allowabort=true) {
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()) {
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.
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
196 function upgrade_block_savepoint($result, $version, $blockname, $allowabort=true) {
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()) {
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
236 function upgrade_plugin_savepoint($result, $version, $type, $plugin, $allowabort=true) {
237 $component = $type.'_'.$plugin;
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()) {
263 * @param string $type The type of plugins that should be updated (e.g. 'enrol', 'qtype')
266 function upgrade_plugins($type, $startcallback, $endcallback, $verbose) {
270 if ($type === 'mod') {
271 return upgrade_plugins_modules($startcallback, $endcallback, $verbose);
272 } else if ($type === 'block') {
273 return upgrade_plugins_blocks($startcallback, $endcallback, $verbose);
276 $plugs = get_plugin_list($type);
278 foreach ($plugs as $plug=>$fullplug) {
279 $component = $type.'_'.$plug; // standardised plugin name
281 // check plugin dir is valid name
282 $cplug = strtolower($plug);
283 $cplug = clean_param($cplug, PARAM_SAFEDIR);
284 $cplug = str_replace('-', '', $cplug);
285 if ($plug !== $cplug) {
286 throw new plugin_defective_exception($component, 'Invalid plugin directory name.');
289 if (!is_readable($fullplug.'/version.php')) {
293 $plugin = new stdClass();
294 require($fullplug.'/version.php'); // defines $plugin with version etc
296 // if plugin tells us it's full name we may check the location
297 if (isset($plugin->component)) {
298 if ($plugin->component !== $component) {
299 throw new plugin_defective_exception($component, 'Plugin installed in wrong folder.');
303 if (empty($plugin->version)) {
304 throw new plugin_defective_exception($component, 'Missing version value in version.php');
307 $plugin->name = $plug;
308 $plugin->fullname = $component;
311 if (!empty($plugin->requires)) {
312 if ($plugin->requires > $CFG->version) {
313 throw new upgrade_requires_exception($component, $plugin->version, $CFG->version, $plugin->requires);
314 } else if ($plugin->requires < 2010000000) {
315 throw new plugin_defective_exception($component, 'Plugin is not compatible with Moodle 2.x or later.');
319 // try to recover from interrupted install.php if needed
320 if (file_exists($fullplug.'/db/install.php')) {
321 if (get_config($plugin->fullname, 'installrunning')) {
322 require_once($fullplug.'/db/install.php');
323 $recover_install_function = 'xmldb_'.$plugin->fullname.'_install_recovery';
324 if (function_exists($recover_install_function)) {
325 $startcallback($component, true, $verbose);
326 $recover_install_function();
327 unset_config('installrunning', $plugin->fullname);
328 update_capabilities($component);
329 log_update_descriptions($component);
330 external_update_descriptions($component);
331 events_update_definition($component);
332 message_update_providers($component);
333 if ($type === 'message') {
334 message_update_processors($plug);
336 upgrade_plugin_mnet_functions($component);
337 $endcallback($component, true, $verbose);
342 $installedversion = get_config($plugin->fullname, 'version');
343 if (empty($installedversion)) { // new installation
344 $startcallback($component, true, $verbose);
346 /// Install tables if defined
347 if (file_exists($fullplug.'/db/install.xml')) {
348 $DB->get_manager()->install_from_xmldb_file($fullplug.'/db/install.xml');
352 upgrade_plugin_savepoint(true, $plugin->version, $type, $plug, false);
354 /// execute post install file
355 if (file_exists($fullplug.'/db/install.php')) {
356 require_once($fullplug.'/db/install.php');
357 set_config('installrunning', 1, $plugin->fullname);
358 $post_install_function = 'xmldb_'.$plugin->fullname.'_install';
359 $post_install_function();
360 unset_config('installrunning', $plugin->fullname);
363 /// Install various components
364 update_capabilities($component);
365 log_update_descriptions($component);
366 external_update_descriptions($component);
367 events_update_definition($component);
368 message_update_providers($component);
369 if ($type === 'message') {
370 message_update_processors($plug);
372 upgrade_plugin_mnet_functions($component);
375 $endcallback($component, true, $verbose);
377 } else if ($installedversion < $plugin->version) { // upgrade
378 /// Run the upgrade function for the plugin.
379 $startcallback($component, false, $verbose);
381 if (is_readable($fullplug.'/db/upgrade.php')) {
382 require_once($fullplug.'/db/upgrade.php'); // defines upgrading function
384 $newupgrade_function = 'xmldb_'.$plugin->fullname.'_upgrade';
385 $result = $newupgrade_function($installedversion);
390 $installedversion = get_config($plugin->fullname, 'version');
391 if ($installedversion < $plugin->version) {
392 // store version if not already there
393 upgrade_plugin_savepoint($result, $plugin->version, $type, $plug, false);
396 /// Upgrade various components
397 update_capabilities($component);
398 log_update_descriptions($component);
399 external_update_descriptions($component);
400 events_update_definition($component);
401 message_update_providers($component);
402 if ($type === 'message') {
403 message_update_processors($plug);
405 upgrade_plugin_mnet_functions($component);
408 $endcallback($component, false, $verbose);
410 } else if ($installedversion > $plugin->version) {
411 throw new downgrade_exception($component, $installedversion, $plugin->version);
417 * Find and check all modules and load them up or upgrade them if necessary
422 function upgrade_plugins_modules($startcallback, $endcallback, $verbose) {
425 $mods = get_plugin_list('mod');
427 foreach ($mods as $mod=>$fullmod) {
429 if ($mod === 'NEWMODULE') { // Someone has unzipped the template, ignore it
433 $component = 'mod_'.$mod;
435 // check module dir is valid name
436 $cmod = strtolower($mod);
437 $cmod = clean_param($cmod, PARAM_SAFEDIR);
438 $cmod = str_replace('-', '', $cmod);
439 $cmod = str_replace('_', '', $cmod); // modules MUST not have '_' in name and never will, sorry
440 if ($mod !== $cmod) {
441 throw new plugin_defective_exception($component, 'Invalid plugin directory name.');
444 if (!is_readable($fullmod.'/version.php')) {
445 throw new plugin_defective_exception($component, 'Missing version.php');
448 $module = new stdClass();
449 require($fullmod .'/version.php'); // defines $module with version etc
451 // if plugin tells us it's full name we may check the location
452 if (isset($module->component)) {
453 if ($module->component !== $component) {
454 throw new plugin_defective_exception($component, 'Plugin installed in wrong folder.');
458 if (empty($module->version)) {
459 if (isset($module->version)) {
460 // Version is empty but is set - it means its value is 0 or ''. Let us skip such module.
461 // This is intended for developers so they can work on the early stages of the module.
464 throw new plugin_defective_exception($component, 'Missing version value in version.php');
467 if (!empty($module->requires)) {
468 if ($module->requires > $CFG->version) {
469 throw new upgrade_requires_exception($component, $module->version, $CFG->version, $module->requires);
470 } else if ($module->requires < 2010000000) {
471 throw new plugin_defective_exception($component, 'Plugin is not compatible with Moodle 2.x or later.');
475 // all modules must have en lang pack
476 if (!is_readable("$fullmod/lang/en/$mod.php")) {
477 throw new plugin_defective_exception($component, 'Missing mandatory en language pack.');
480 $module->name = $mod; // The name MUST match the directory
482 $currmodule = $DB->get_record('modules', array('name'=>$module->name));
484 if (file_exists($fullmod.'/db/install.php')) {
485 if (get_config($module->name, 'installrunning')) {
486 require_once($fullmod.'/db/install.php');
487 $recover_install_function = 'xmldb_'.$module->name.'_install_recovery';
488 if (function_exists($recover_install_function)) {
489 $startcallback($component, true, $verbose);
490 $recover_install_function();
491 unset_config('installrunning', $module->name);
492 // Install various components too
493 update_capabilities($component);
494 log_update_descriptions($component);
495 external_update_descriptions($component);
496 events_update_definition($component);
497 message_update_providers($component);
498 upgrade_plugin_mnet_functions($component);
499 $endcallback($component, true, $verbose);
504 if (empty($currmodule->version)) {
505 $startcallback($component, true, $verbose);
507 /// Execute install.xml (XMLDB) - must be present in all modules
508 $DB->get_manager()->install_from_xmldb_file($fullmod.'/db/install.xml');
510 /// Add record into modules table - may be needed in install.php already
511 $module->id = $DB->insert_record('modules', $module);
513 /// Post installation hook - optional
514 if (file_exists("$fullmod/db/install.php")) {
515 require_once("$fullmod/db/install.php");
516 // Set installation running flag, we need to recover after exception or error
517 set_config('installrunning', 1, $module->name);
518 $post_install_function = 'xmldb_'.$module->name.'_install';;
519 $post_install_function();
520 unset_config('installrunning', $module->name);
523 /// Install various components
524 update_capabilities($component);
525 log_update_descriptions($component);
526 external_update_descriptions($component);
527 events_update_definition($component);
528 message_update_providers($component);
529 upgrade_plugin_mnet_functions($component);
532 $endcallback($component, true, $verbose);
534 } else if ($currmodule->version < $module->version) {
535 /// If versions say that we need to upgrade but no upgrade files are available, notify and continue
536 $startcallback($component, false, $verbose);
538 if (is_readable($fullmod.'/db/upgrade.php')) {
539 require_once($fullmod.'/db/upgrade.php'); // defines new upgrading function
540 $newupgrade_function = 'xmldb_'.$module->name.'_upgrade';
541 $result = $newupgrade_function($currmodule->version, $module);
546 $currmodule = $DB->get_record('modules', array('name'=>$module->name));
547 if ($currmodule->version < $module->version) {
548 // store version if not already there
549 upgrade_mod_savepoint($result, $module->version, $mod, false);
552 /// Upgrade various components
553 update_capabilities($component);
554 log_update_descriptions($component);
555 external_update_descriptions($component);
556 events_update_definition($component);
557 message_update_providers($component);
558 upgrade_plugin_mnet_functions($component);
562 $endcallback($component, false, $verbose);
564 } else if ($currmodule->version > $module->version) {
565 throw new downgrade_exception($component, $currmodule->version, $module->version);
572 * This function finds all available blocks and install them
573 * into blocks table or do all the upgrade process if newer.
578 function upgrade_plugins_blocks($startcallback, $endcallback, $verbose) {
581 require_once($CFG->dirroot.'/blocks/moodleblock.class.php');
583 $blocktitles = array(); // we do not want duplicate titles
585 //Is this a first install
586 $first_install = null;
588 $blocks = get_plugin_list('block');
590 foreach ($blocks as $blockname=>$fullblock) {
592 if (is_null($first_install)) {
593 $first_install = ($DB->count_records('block_instances') == 0);
596 if ($blockname == 'NEWBLOCK') { // Someone has unzipped the template, ignore it
600 $component = 'block_'.$blockname;
602 // check block dir is valid name
603 $cblockname = strtolower($blockname);
604 $cblockname = clean_param($cblockname, PARAM_SAFEDIR);
605 $cblockname = str_replace('-', '', $cblockname);
606 if ($blockname !== $cblockname) {
607 throw new plugin_defective_exception($component, 'Invalid plugin directory name.');
610 if (!is_readable($fullblock.'/version.php')) {
611 throw new plugin_defective_exception('block/'.$blockname, 'Missing version.php file.');
613 $plugin = new stdClass();
614 $plugin->version = NULL;
616 include($fullblock.'/version.php');
619 // if plugin tells us it's full name we may check the location
620 if (isset($block->component)) {
621 if ($block->component !== $component) {
622 throw new plugin_defective_exception($component, 'Plugin installed in wrong folder.');
626 if (!empty($plugin->requires)) {
627 if ($plugin->requires > $CFG->version) {
628 throw new upgrade_requires_exception($component, $plugin->version, $CFG->version, $plugin->requires);
629 } else if ($plugin->requires < 2010000000) {
630 throw new plugin_defective_exception($component, 'Plugin is not compatible with Moodle 2.x or later.');
634 if (!is_readable($fullblock.'/block_'.$blockname.'.php')) {
635 throw new plugin_defective_exception('block/'.$blockname, 'Missing main block class file.');
637 include_once($fullblock.'/block_'.$blockname.'.php');
639 $classname = 'block_'.$blockname;
641 if (!class_exists($classname)) {
642 throw new plugin_defective_exception($component, 'Can not load main class.');
645 $blockobj = new $classname; // This is what we'll be testing
646 $blocktitle = $blockobj->get_title();
648 // OK, it's as we all hoped. For further tests, the object will do them itself.
649 if (!$blockobj->_self_test()) {
650 throw new plugin_defective_exception($component, 'Self test failed.');
653 $block->name = $blockname; // The name MUST match the directory
655 if (empty($block->version)) {
656 throw new plugin_defective_exception($component, 'Missing block version.');
659 $currblock = $DB->get_record('block', array('name'=>$block->name));
661 if (file_exists($fullblock.'/db/install.php')) {
662 if (get_config('block_'.$blockname, 'installrunning')) {
663 require_once($fullblock.'/db/install.php');
664 $recover_install_function = 'xmldb_block_'.$blockname.'_install_recovery';
665 if (function_exists($recover_install_function)) {
666 $startcallback($component, true, $verbose);
667 $recover_install_function();
668 unset_config('installrunning', 'block_'.$blockname);
669 // Install various components
670 update_capabilities($component);
671 log_update_descriptions($component);
672 external_update_descriptions($component);
673 events_update_definition($component);
674 message_update_providers($component);
675 upgrade_plugin_mnet_functions($component);
676 $endcallback($component, true, $verbose);
681 if (empty($currblock->version)) { // block not installed yet, so install it
682 $conflictblock = array_search($blocktitle, $blocktitles);
683 if ($conflictblock !== false) {
684 // Duplicate block titles are not allowed, they confuse people
685 // AND PHP's associative arrays ;)
686 throw new plugin_defective_exception($component, get_string('blocknameconflict', 'error', (object)array('name'=>$block->name, 'conflict'=>$conflictblock)));
688 $startcallback($component, true, $verbose);
690 if (file_exists($fullblock.'/db/install.xml')) {
691 $DB->get_manager()->install_from_xmldb_file($fullblock.'/db/install.xml');
693 $block->id = $DB->insert_record('block', $block);
695 if (file_exists($fullblock.'/db/install.php')) {
696 require_once($fullblock.'/db/install.php');
697 // Set installation running flag, we need to recover after exception or error
698 set_config('installrunning', 1, 'block_'.$blockname);
699 $post_install_function = 'xmldb_block_'.$blockname.'_install';;
700 $post_install_function();
701 unset_config('installrunning', 'block_'.$blockname);
704 $blocktitles[$block->name] = $blocktitle;
706 // Install various components
707 update_capabilities($component);
708 log_update_descriptions($component);
709 external_update_descriptions($component);
710 events_update_definition($component);
711 message_update_providers($component);
712 upgrade_plugin_mnet_functions($component);
715 $endcallback($component, true, $verbose);
717 } else if ($currblock->version < $block->version) {
718 $startcallback($component, false, $verbose);
720 if (is_readable($fullblock.'/db/upgrade.php')) {
721 require_once($fullblock.'/db/upgrade.php'); // defines new upgrading function
722 $newupgrade_function = 'xmldb_block_'.$blockname.'_upgrade';
723 $result = $newupgrade_function($currblock->version, $block);
728 $currblock = $DB->get_record('block', array('name'=>$block->name));
729 if ($currblock->version < $block->version) {
730 // store version if not already there
731 upgrade_block_savepoint($result, $block->version, $block->name, false);
734 if ($currblock->cron != $block->cron) {
735 // update cron flag if needed
736 $currblock->cron = $block->cron;
737 $DB->update_record('block', $currblock);
740 // Upgrade various components
741 update_capabilities($component);
742 log_update_descriptions($component);
743 external_update_descriptions($component);
744 events_update_definition($component);
745 message_update_providers($component);
746 upgrade_plugin_mnet_functions($component);
749 $endcallback($component, false, $verbose);
751 } else if ($currblock->version > $block->version) {
752 throw new downgrade_exception($component, $currblock->version, $block->version);
757 // Finally, if we are in the first_install of BLOCKS setup frontpage and admin page blocks
758 if ($first_install) {
759 //Iterate over each course - there should be only site course here now
760 if ($courses = $DB->get_records('course')) {
761 foreach ($courses as $course) {
762 blocks_add_default_course_blocks($course);
766 blocks_add_default_system_blocks();
772 * Log_display description function used during install and upgrade.
774 * @param string $component name of component (moodle, mod_assignment, etc.)
777 function log_update_descriptions($component) {
780 $defpath = get_component_directory($component).'/db/log.php';
782 if (!file_exists($defpath)) {
783 $DB->delete_records('log_display', array('component'=>$component));
791 foreach ($logs as $log) {
792 $newlogs[$log['module'].'-'.$log['action']] = $log; // kind of unique name
797 $fields = array('module', 'action', 'mtable', 'field');
798 // update all log fist
799 $dblogs = $DB->get_records('log_display', array('component'=>$component));
800 foreach ($dblogs as $dblog) {
801 $name = $dblog->module.'-'.$dblog->action;
803 if (empty($logs[$name])) {
804 $DB->delete_records('log_display', array('id'=>$dblog->id));
812 foreach ($fields as $field) {
813 if ($dblog->$field != $log[$field]) {
814 $dblog->$field = $log[$field];
819 $DB->update_record('log_display', $dblog);
822 foreach ($logs as $log) {
823 $dblog = (object)$log;
824 $dblog->component = $component;
825 $DB->insert_record('log_display', $dblog);
830 * Web service discovery function used during install and upgrade.
831 * @param string $component name of component (moodle, mod_assignment, etc.)
834 function external_update_descriptions($component) {
837 $defpath = get_component_directory($component).'/db/services.php';
839 if (!file_exists($defpath)) {
840 external_delete_descriptions($component);
845 $functions = array();
849 // update all function fist
850 $dbfunctions = $DB->get_records('external_functions', array('component'=>$component));
851 foreach ($dbfunctions as $dbfunction) {
852 if (empty($functions[$dbfunction->name])) {
853 $DB->delete_records('external_functions', array('id'=>$dbfunction->id));
854 // do not delete functions from external_services_functions, beacuse
855 // we want to notify admins when functions used in custom services disappear
857 //TODO: this looks wrong, we have to delete it eventually (skodak)
861 $function = $functions[$dbfunction->name];
862 unset($functions[$dbfunction->name]);
863 $function['classpath'] = empty($function['classpath']) ? null : $function['classpath'];
866 if ($dbfunction->classname != $function['classname']) {
867 $dbfunction->classname = $function['classname'];
870 if ($dbfunction->methodname != $function['methodname']) {
871 $dbfunction->methodname = $function['methodname'];
874 if ($dbfunction->classpath != $function['classpath']) {
875 $dbfunction->classpath = $function['classpath'];
878 $functioncapabilities = key_exists('capabilities', $function)?$function['capabilities']:'';
879 if ($dbfunction->capabilities != $functioncapabilities) {
880 $dbfunction->capabilities = $functioncapabilities;
884 $DB->update_record('external_functions', $dbfunction);
887 foreach ($functions as $fname => $function) {
888 $dbfunction = new stdClass();
889 $dbfunction->name = $fname;
890 $dbfunction->classname = $function['classname'];
891 $dbfunction->methodname = $function['methodname'];
892 $dbfunction->classpath = empty($function['classpath']) ? null : $function['classpath'];
893 $dbfunction->component = $component;
894 $dbfunction->capabilities = key_exists('capabilities', $function)?$function['capabilities']:'';
895 $dbfunction->id = $DB->insert_record('external_functions', $dbfunction);
899 // now deal with services
900 $dbservices = $DB->get_records('external_services', array('component'=>$component));
901 foreach ($dbservices as $dbservice) {
902 if (empty($services[$dbservice->name])) {
903 $DB->delete_records('external_services_functions', array('externalserviceid'=>$dbservice->id));
904 $DB->delete_records('external_services_users', array('externalserviceid'=>$dbservice->id));
905 $DB->delete_records('external_services', array('id'=>$dbservice->id));
908 $service = $services[$dbservice->name];
909 unset($services[$dbservice->name]);
910 $service['enabled'] = empty($service['enabled']) ? 0 : $service['enabled'];
911 $service['requiredcapability'] = empty($service['requiredcapability']) ? null : $service['requiredcapability'];
912 $service['restrictedusers'] = !isset($service['restrictedusers']) ? 1 : $service['restrictedusers'];
913 $service['shortname'] = !isset($service['shortname']) ? null : $service['shortname'];
916 if ($dbservice->requiredcapability != $service['requiredcapability']) {
917 $dbservice->requiredcapability = $service['requiredcapability'];
920 if ($dbservice->restrictedusers != $service['restrictedusers']) {
921 $dbservice->restrictedusers = $service['restrictedusers'];
924 //if shortname is not a PARAM_ALPHANUMEXT, fail (tested here for service update and creation)
925 if (isset($service['shortname']) and
926 (clean_param($service['shortname'], PARAM_ALPHANUMEXT) != $service['shortname'])) {
927 throw new moodle_exception('installserviceshortnameerror', 'webservice', '', $service['shortname']);
929 if ($dbservice->shortname != $service['shortname']) {
930 //check that shortname is unique
931 if (isset($service['shortname'])) { //we currently accepts multiple shortname == null
932 $existingservice = $DB->get_record('external_services',
933 array('shortname' => $service['shortname']));
934 if (!empty($existingservice)) {
935 throw new moodle_exception('installexistingserviceshortnameerror', 'webservice', '', $service['shortname']);
938 $dbservice->shortname = $service['shortname'];
942 $DB->update_record('external_services', $dbservice);
945 $functions = $DB->get_records('external_services_functions', array('externalserviceid'=>$dbservice->id));
946 foreach ($functions as $function) {
947 $key = array_search($function->functionname, $service['functions']);
948 if ($key === false) {
949 $DB->delete_records('external_services_functions', array('id'=>$function->id));
951 unset($service['functions'][$key]);
954 foreach ($service['functions'] as $fname) {
955 $newf = new stdClass();
956 $newf->externalserviceid = $dbservice->id;
957 $newf->functionname = $fname;
958 $DB->insert_record('external_services_functions', $newf);
962 foreach ($services as $name => $service) {
963 //check that shortname is unique
964 if (isset($service['shortname'])) { //we currently accepts multiple shortname == null
965 $existingservice = $DB->get_record('external_services',
966 array('shortname' => $service['shortname']));
967 if (!empty($existingservice)) {
968 throw new moodle_exception('installserviceshortnameerror', 'webservice');
972 $dbservice = new stdClass();
973 $dbservice->name = $name;
974 $dbservice->enabled = empty($service['enabled']) ? 0 : $service['enabled'];
975 $dbservice->requiredcapability = empty($service['requiredcapability']) ? null : $service['requiredcapability'];
976 $dbservice->restrictedusers = !isset($service['restrictedusers']) ? 1 : $service['restrictedusers'];
977 $dbservice->shortname = !isset($service['shortname']) ? null : $service['shortname'];
978 $dbservice->component = $component;
979 $dbservice->timecreated = time();
980 $dbservice->id = $DB->insert_record('external_services', $dbservice);
981 foreach ($service['functions'] as $fname) {
982 $newf = new stdClass();
983 $newf->externalserviceid = $dbservice->id;
984 $newf->functionname = $fname;
985 $DB->insert_record('external_services_functions', $newf);
991 * Delete all service and external functions information defined in the specified component.
992 * @param string $component name of component (moodle, mod_assignment, etc.)
995 function external_delete_descriptions($component) {
998 $params = array($component);
1000 $DB->delete_records_select('external_services_users', "externalserviceid IN (SELECT id FROM {external_services} WHERE component = ?)", $params);
1001 $DB->delete_records_select('external_services_functions', "externalserviceid IN (SELECT id FROM {external_services} WHERE component = ?)", $params);
1002 $DB->delete_records('external_services', array('component'=>$component));
1003 $DB->delete_records('external_functions', array('component'=>$component));
1007 * upgrade logging functions
1009 function upgrade_handle_exception($ex, $plugin = null) {
1012 // rollback everything, we need to log all upgrade problems
1013 abort_all_db_transactions();
1015 $info = get_exception_info($ex);
1017 // First log upgrade error
1018 upgrade_log(UPGRADE_LOG_ERROR, $plugin, 'Exception: ' . get_class($ex), $info->message, $info->backtrace);
1020 // Always turn on debugging - admins need to know what is going on
1021 $CFG->debug = DEBUG_DEVELOPER;
1023 default_exception_handler($ex, true, $plugin);
1027 * Adds log entry into upgrade_log table
1029 * @param int $type UPGRADE_LOG_NORMAL, UPGRADE_LOG_NOTICE or UPGRADE_LOG_ERROR
1030 * @param string $plugin frankenstyle component name
1031 * @param string $info short description text of log entry
1032 * @param string $details long problem description
1033 * @param string $backtrace string used for errors only
1036 function upgrade_log($type, $plugin, $info, $details=null, $backtrace=null) {
1037 global $DB, $USER, $CFG;
1039 if (empty($plugin)) {
1043 list($plugintype, $pluginname) = normalize_component($plugin);
1044 $component = is_null($pluginname) ? $plugintype : $plugintype . '_' . $pluginname;
1046 $backtrace = format_backtrace($backtrace, true);
1048 $currentversion = null;
1049 $targetversion = null;
1051 //first try to find out current version number
1052 if ($plugintype === 'core') {
1054 $currentversion = $CFG->version;
1057 include("$CFG->dirroot/version.php");
1058 $targetversion = $version;
1060 } else if ($plugintype === 'mod') {
1062 $currentversion = $DB->get_field('modules', 'version', array('name'=>$pluginname));
1063 $currentversion = ($currentversion === false) ? null : $currentversion;
1064 } catch (Exception $ignored) {
1066 $cd = get_component_directory($component);
1067 if (file_exists("$cd/version.php")) {
1068 $module = new stdClass();
1069 $module->version = null;
1070 include("$cd/version.php");
1071 $targetversion = $module->version;
1074 } else if ($plugintype === 'block') {
1076 if ($block = $DB->get_record('block', array('name'=>$pluginname))) {
1077 $currentversion = $block->version;
1079 } catch (Exception $ignored) {
1081 $cd = get_component_directory($component);
1082 if (file_exists("$cd/version.php")) {
1083 $plugin = new stdClass();
1084 $plugin->version = null;
1085 include("$cd/version.php");
1086 $targetversion = $plugin->version;
1090 $pluginversion = get_config($component, 'version');
1091 if (!empty($pluginversion)) {
1092 $currentversion = $pluginversion;
1094 $cd = get_component_directory($component);
1095 if (file_exists("$cd/version.php")) {
1096 $plugin = new stdClass();
1097 $plugin->version = null;
1098 include("$cd/version.php");
1099 $targetversion = $plugin->version;
1103 $log = new stdClass();
1105 $log->plugin = $component;
1106 $log->version = $currentversion;
1107 $log->targetversion = $targetversion;
1109 $log->details = $details;
1110 $log->backtrace = $backtrace;
1111 $log->userid = $USER->id;
1112 $log->timemodified = time();
1114 $DB->insert_record('upgrade_log', $log);
1115 } catch (Exception $ignored) {
1116 // possible during install or 2.0 upgrade
1121 * Marks start of upgrade, blocks any other access to site.
1122 * The upgrade is finished at the end of script or after timeout.
1128 function upgrade_started($preinstall=false) {
1129 global $CFG, $DB, $PAGE, $OUTPUT;
1131 static $started = false;
1134 ignore_user_abort(true);
1135 upgrade_setup_debug(true);
1137 } else if ($started) {
1138 upgrade_set_timeout(120);
1141 if (!CLI_SCRIPT and !$PAGE->headerprinted) {
1142 $strupgrade = get_string('upgradingversion', 'admin');
1143 $PAGE->set_pagelayout('maintenance');
1144 upgrade_init_javascript();
1145 $PAGE->set_title($strupgrade.' - Moodle '.$CFG->target_release);
1146 $PAGE->set_heading($strupgrade);
1147 $PAGE->navbar->add($strupgrade);
1148 $PAGE->set_cacheable(false);
1149 echo $OUTPUT->header();
1152 ignore_user_abort(true);
1153 register_shutdown_function('upgrade_finished_handler');
1154 upgrade_setup_debug(true);
1155 set_config('upgraderunning', time()+300);
1161 * Internal function - executed if upgrade interrupted.
1163 function upgrade_finished_handler() {
1168 * Indicates upgrade is finished.
1170 * This function may be called repeatedly.
1175 function upgrade_finished($continueurl=null) {
1176 global $CFG, $DB, $OUTPUT;
1178 if (!empty($CFG->upgraderunning)) {
1179 unset_config('upgraderunning');
1180 upgrade_setup_debug(false);
1181 ignore_user_abort(false);
1183 echo $OUTPUT->continue_button($continueurl);
1184 echo $OUTPUT->footer();
1194 function upgrade_setup_debug($starting) {
1197 static $originaldebug = null;
1200 if ($originaldebug === null) {
1201 $originaldebug = $DB->get_debug();
1203 if (!empty($CFG->upgradeshowsql)) {
1204 $DB->set_debug(true);
1207 $DB->set_debug($originaldebug);
1214 function print_upgrade_reload($url) {
1218 echo '<div class="continuebutton">';
1219 echo '<a href="'.$url.'" title="'.get_string('reload').'" ><img src="'.$OUTPUT->pix_url('i/reload') . '" alt="" /> '.get_string('reload').'</a>';
1220 echo '</div><br />';
1223 function print_upgrade_separator() {
1230 * Default start upgrade callback
1231 * @param string $plugin
1232 * @param bool $installation true if installation, false means upgrade
1234 function print_upgrade_part_start($plugin, $installation, $verbose) {
1236 if (empty($plugin) or $plugin == 'moodle') {
1237 upgrade_started($installation); // does not store upgrade running flag yet
1239 echo $OUTPUT->heading(get_string('coresystem'));
1244 echo $OUTPUT->heading($plugin);
1247 if ($installation) {
1248 if (empty($plugin) or $plugin == 'moodle') {
1249 // no need to log - log table not yet there ;-)
1251 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Starting plugin installation');
1254 if (empty($plugin) or $plugin == 'moodle') {
1255 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Starting core upgrade');
1257 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Starting plugin upgrade');
1263 * Default end upgrade callback
1264 * @param string $plugin
1265 * @param bool $installation true if installation, false means upgrade
1267 function print_upgrade_part_end($plugin, $installation, $verbose) {
1270 if ($installation) {
1271 if (empty($plugin) or $plugin == 'moodle') {
1272 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Core installed');
1274 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Plugin installed');
1277 if (empty($plugin) or $plugin == 'moodle') {
1278 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Core upgraded');
1280 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Plugin upgraded');
1284 echo $OUTPUT->notification(get_string('success'), 'notifysuccess');
1285 print_upgrade_separator();
1290 * Sets up JS code required for all upgrade scripts.
1293 function upgrade_init_javascript() {
1295 // scroll to the end of each upgrade page so that ppl see either error or continue button,
1296 // no need to scroll continuously any more, it is enough to jump to end once the footer is printed ;-)
1297 $js = "window.scrollTo(0, 5000000);";
1298 $PAGE->requires->js_init_code($js);
1302 * Try to upgrade the given language pack (or current language)
1304 * @param string $lang the code of the language to update, defaults to the current language
1306 function upgrade_language_pack($lang='') {
1307 global $CFG, $OUTPUT;
1309 get_string_manager()->reset_caches();
1312 $lang = current_language();
1315 if ($lang == 'en') {
1316 return true; // Nothing to do
1319 upgrade_started(false);
1320 echo $OUTPUT->heading(get_string('langimport', 'admin').': '.$lang);
1322 @mkdir ($CFG->tempdir.'/'); //make it in case it's a fresh install, it might not be there
1323 @mkdir ($CFG->dataroot.'/lang/');
1325 require_once($CFG->libdir.'/componentlib.class.php');
1327 $installer = new lang_installer($lang);
1328 $results = $installer->run();
1329 foreach ($results as $langcode => $langstatus) {
1330 switch ($langstatus) {
1331 case lang_installer::RESULT_DOWNLOADERROR:
1332 echo $OUTPUT->notification($langcode . '.zip');
1334 case lang_installer::RESULT_INSTALLED:
1335 echo $OUTPUT->notification(get_string('langpackinstalled', 'admin', $langcode), 'notifysuccess');
1337 case lang_installer::RESULT_UPTODATE:
1338 echo $OUTPUT->notification(get_string('langpackuptodate', 'admin', $langcode), 'notifysuccess');
1343 get_string_manager()->reset_caches();
1345 print_upgrade_separator();
1349 * Install core moodle tables and initialize
1350 * @param float $version target version
1351 * @param bool $verbose
1352 * @return void, may throw exception
1354 function install_core($version, $verbose) {
1358 set_time_limit(600);
1359 print_upgrade_part_start('moodle', true, $verbose); // does not store upgrade running flag
1361 $DB->get_manager()->install_from_xmldb_file("$CFG->libdir/db/install.xml");
1362 upgrade_started(); // we want the flag to be stored in config table ;-)
1364 // set all core default records and default settings
1365 require_once("$CFG->libdir/db/install.php");
1366 xmldb_main_install(); // installs the capabilities too
1369 upgrade_main_savepoint(true, $version, false);
1371 // Continue with the installation
1372 log_update_descriptions('moodle');
1373 external_update_descriptions('moodle');
1374 events_update_definition('moodle');
1375 message_update_providers('moodle');
1377 // Write default settings unconditionally
1378 admin_apply_default_settings(NULL, true);
1380 print_upgrade_part_end(null, true, $verbose);
1381 } catch (exception $ex) {
1382 upgrade_handle_exception($ex);
1387 * Upgrade moodle core
1388 * @param float $version target version
1389 * @param bool $verbose
1390 * @return void, may throw exception
1392 function upgrade_core($version, $verbose) {
1395 raise_memory_limit(MEMORY_EXTRA);
1397 require_once($CFG->libdir.'/db/upgrade.php'); // Defines upgrades
1400 // Reset caches before any output
1403 // Upgrade current language pack if we can
1404 if (empty($CFG->skiplangupgrade)) {
1405 if (get_string_manager()->translation_exists(current_language())) {
1406 upgrade_language_pack(false);
1410 print_upgrade_part_start('moodle', false, $verbose);
1412 // one time special local migration pre 2.0 upgrade script
1413 if ($CFG->version < 2007101600) {
1414 $pre20upgradefile = "$CFG->dirroot/local/upgrade_pre20.php";
1415 if (file_exists($pre20upgradefile)) {
1417 require($pre20upgradefile);
1418 // reset upgrade timeout to default
1419 upgrade_set_timeout();
1423 $result = xmldb_main_upgrade($CFG->version);
1424 if ($version > $CFG->version) {
1425 // store version if not already there
1426 upgrade_main_savepoint($result, $version, false);
1429 // perform all other component upgrade routines
1430 update_capabilities('moodle');
1431 log_update_descriptions('moodle');
1432 external_update_descriptions('moodle');
1433 events_update_definition('moodle');
1434 message_update_providers('moodle');
1436 // Reset caches again, just to be sure
1439 // Clean up contexts - more and more stuff depends on existence of paths and contexts
1442 build_context_path();
1443 $syscontext = get_context_instance(CONTEXT_SYSTEM);
1444 mark_context_dirty($syscontext->path);
1446 print_upgrade_part_end('moodle', false, $verbose);
1447 } catch (Exception $ex) {
1448 upgrade_handle_exception($ex);
1453 * Upgrade/install other parts of moodle
1454 * @param bool $verbose
1455 * @return void, may throw exception
1457 function upgrade_noncore($verbose) {
1460 raise_memory_limit(MEMORY_EXTRA);
1462 // upgrade all plugins types
1464 $plugintypes = get_plugin_types();
1465 foreach ($plugintypes as $type=>$location) {
1466 upgrade_plugins($type, 'print_upgrade_part_start', 'print_upgrade_part_end', $verbose);
1468 } catch (Exception $ex) {
1469 upgrade_handle_exception($ex);
1474 * Checks if the main tables have been installed yet or not.
1477 function core_tables_exist() {
1480 if (!$tables = $DB->get_tables() ) { // No tables yet at all.
1483 } else { // Check for missing main tables
1484 $mtables = array('config', 'course', 'groupings'); // some tables used in 1.9 and 2.0, preferable something from the start and end of install.xml
1485 foreach ($mtables as $mtable) {
1486 if (!in_array($mtable, $tables)) {
1495 * upgrades the mnet rpc definitions for the given component.
1496 * this method doesn't return status, an exception will be thrown in the case of an error
1498 * @param string $component the plugin to upgrade, eg auth_mnet
1500 function upgrade_plugin_mnet_functions($component) {
1503 list($type, $plugin) = explode('_', $component);
1504 $path = get_plugin_directory($type, $plugin);
1506 $publishes = array();
1507 $subscribes = array();
1508 if (file_exists($path . '/db/mnet.php')) {
1509 require_once($path . '/db/mnet.php'); // $publishes comes from this file
1511 if (empty($publishes)) {
1512 $publishes = array(); // still need this to be able to disable stuff later
1514 if (empty($subscribes)) {
1515 $subscribes = array(); // still need this to be able to disable stuff later
1518 static $servicecache = array();
1520 // rekey an array based on the rpc method for easy lookups later
1521 $publishmethodservices = array();
1522 $subscribemethodservices = array();
1523 foreach($publishes as $servicename => $service) {
1524 if (is_array($service['methods'])) {
1525 foreach($service['methods'] as $methodname) {
1526 $service['servicename'] = $servicename;
1527 $publishmethodservices[$methodname][] = $service;
1532 // Disable functions that don't exist (any more) in the source
1533 // Should these be deleted? What about their permissions records?
1534 foreach ($DB->get_records('mnet_rpc', array('pluginname'=>$plugin, 'plugintype'=>$type), 'functionname ASC ') as $rpc) {
1535 if (!array_key_exists($rpc->functionname, $publishmethodservices) && $rpc->enabled) {
1536 $DB->set_field('mnet_rpc', 'enabled', 0, array('id' => $rpc->id));
1537 } else if (array_key_exists($rpc->functionname, $publishmethodservices) && !$rpc->enabled) {
1538 $DB->set_field('mnet_rpc', 'enabled', 1, array('id' => $rpc->id));
1542 // reflect all the services we're publishing and save them
1543 require_once($CFG->dirroot . '/lib/zend/Zend/Server/Reflection.php');
1544 static $cachedclasses = array(); // to store reflection information in
1545 foreach ($publishes as $service => $data) {
1546 $f = $data['filename'];
1547 $c = $data['classname'];
1548 foreach ($data['methods'] as $method) {
1549 $dataobject = new stdClass();
1550 $dataobject->plugintype = $type;
1551 $dataobject->pluginname = $plugin;
1552 $dataobject->enabled = 1;
1553 $dataobject->classname = $c;
1554 $dataobject->filename = $f;
1556 if (is_string($method)) {
1557 $dataobject->functionname = $method;
1559 } else if (is_array($method)) { // wants to override file or class
1560 $dataobject->functionname = $method['method'];
1561 $dataobject->classname = $method['classname'];
1562 $dataobject->filename = $method['filename'];
1564 $dataobject->xmlrpcpath = $type.'/'.$plugin.'/'.$dataobject->filename.'/'.$method;
1565 $dataobject->static = false;
1567 require_once($path . '/' . $dataobject->filename);
1568 $functionreflect = null; // slightly different ways to get this depending on whether it's a class method or a function
1569 if (!empty($dataobject->classname)) {
1570 if (!class_exists($dataobject->classname)) {
1571 throw new moodle_exception('installnosuchmethod', 'mnet', '', (object)array('method' => $dataobject->functionname, 'class' => $dataobject->classname));
1573 $key = $dataobject->filename . '|' . $dataobject->classname;
1574 if (!array_key_exists($key, $cachedclasses)) { // look to see if we've already got a reflection object
1576 $cachedclasses[$key] = Zend_Server_Reflection::reflectClass($dataobject->classname);
1577 } catch (Zend_Server_Reflection_Exception $e) { // catch these and rethrow them to something more helpful
1578 throw new moodle_exception('installreflectionclasserror', 'mnet', '', (object)array('method' => $dataobject->functionname, 'class' => $dataobject->classname, 'error' => $e->getMessage()));
1581 $r =& $cachedclasses[$key];
1582 if (!$r->hasMethod($dataobject->functionname)) {
1583 throw new moodle_exception('installnosuchmethod', 'mnet', '', (object)array('method' => $dataobject->functionname, 'class' => $dataobject->classname));
1585 // stupid workaround for zend not having a getMethod($name) function
1586 $ms = $r->getMethods();
1587 foreach ($ms as $m) {
1588 if ($m->getName() == $dataobject->functionname) {
1589 $functionreflect = $m;
1593 $dataobject->static = (int)$functionreflect->isStatic();
1595 if (!function_exists($dataobject->functionname)) {
1596 throw new moodle_exception('installnosuchfunction', 'mnet', '', (object)array('method' => $dataobject->functionname, 'file' => $dataobject->filename));
1599 $functionreflect = Zend_Server_Reflection::reflectFunction($dataobject->functionname);
1600 } catch (Zend_Server_Reflection_Exception $e) { // catch these and rethrow them to something more helpful
1601 throw new moodle_exception('installreflectionfunctionerror', 'mnet', '', (object)array('method' => $dataobject->functionname, '' => $dataobject->filename, 'error' => $e->getMessage()));
1604 $dataobject->profile = serialize(admin_mnet_method_profile($functionreflect));
1605 $dataobject->help = $functionreflect->getDescription();
1607 if ($record_exists = $DB->get_record('mnet_rpc', array('xmlrpcpath'=>$dataobject->xmlrpcpath))) {
1608 $dataobject->id = $record_exists->id;
1609 $dataobject->enabled = $record_exists->enabled;
1610 $DB->update_record('mnet_rpc', $dataobject);
1612 $dataobject->id = $DB->insert_record('mnet_rpc', $dataobject, true);
1615 // TODO this API versioning must be reworked, here the recently processed method
1616 // sets the service API which may not be correct
1617 foreach ($publishmethodservices[$dataobject->functionname] as $service) {
1618 if ($serviceobj = $DB->get_record('mnet_service', array('name'=>$service['servicename']))) {
1619 $serviceobj->apiversion = $service['apiversion'];
1620 $DB->update_record('mnet_service', $serviceobj);
1622 $serviceobj = new stdClass();
1623 $serviceobj->name = $service['servicename'];
1624 $serviceobj->description = empty($service['description']) ? '' : $service['description'];
1625 $serviceobj->apiversion = $service['apiversion'];
1626 $serviceobj->offer = 1;
1627 $serviceobj->id = $DB->insert_record('mnet_service', $serviceobj);
1629 $servicecache[$service['servicename']] = $serviceobj;
1630 if (!$DB->record_exists('mnet_service2rpc', array('rpcid'=>$dataobject->id, 'serviceid'=>$serviceobj->id))) {
1631 $obj = new stdClass();
1632 $obj->rpcid = $dataobject->id;
1633 $obj->serviceid = $serviceobj->id;
1634 $DB->insert_record('mnet_service2rpc', $obj, true);
1639 // finished with methods we publish, now do subscribable methods
1640 foreach($subscribes as $service => $methods) {
1641 if (!array_key_exists($service, $servicecache)) {
1642 if (!$serviceobj = $DB->get_record('mnet_service', array('name' => $service))) {
1643 debugging("TODO: skipping unknown service $service - somebody needs to fix MDL-21993");
1646 $servicecache[$service] = $serviceobj;
1648 $serviceobj = $servicecache[$service];
1650 foreach ($methods as $method => $xmlrpcpath) {
1651 if (!$rpcid = $DB->get_field('mnet_remote_rpc', 'id', array('xmlrpcpath'=>$xmlrpcpath))) {
1652 $remoterpc = (object)array(
1653 'functionname' => $method,
1654 'xmlrpcpath' => $xmlrpcpath,
1655 'plugintype' => $type,
1656 'pluginname' => $plugin,
1659 $rpcid = $remoterpc->id = $DB->insert_record('mnet_remote_rpc', $remoterpc, true);
1661 if (!$DB->record_exists('mnet_remote_service2rpc', array('rpcid'=>$rpcid, 'serviceid'=>$serviceobj->id))) {
1662 $obj = new stdClass();
1663 $obj->rpcid = $rpcid;
1664 $obj->serviceid = $serviceobj->id;
1665 $DB->insert_record('mnet_remote_service2rpc', $obj, true);
1667 $subscribemethodservices[$method][] = $service;
1671 foreach ($DB->get_records('mnet_remote_rpc', array('pluginname'=>$plugin, 'plugintype'=>$type), 'functionname ASC ') as $rpc) {
1672 if (!array_key_exists($rpc->functionname, $subscribemethodservices) && $rpc->enabled) {
1673 $DB->set_field('mnet_remote_rpc', 'enabled', 0, array('id' => $rpc->id));
1674 } else if (array_key_exists($rpc->functionname, $subscribemethodservices) && !$rpc->enabled) {
1675 $DB->set_field('mnet_remote_rpc', 'enabled', 1, array('id' => $rpc->id));
1683 * Given some sort of Zend Reflection function/method object, return a profile array, ready to be serialized and stored
1685 * @param Zend_Server_Reflection_Function_Abstract $function can be any subclass of this object type
1689 function admin_mnet_method_profile(Zend_Server_Reflection_Function_Abstract $function) {
1690 $proto = array_pop($function->getPrototypes());
1691 $ret = $proto->getReturnValue();
1693 'parameters' => array(),
1695 'type' => $ret->getType(),
1696 'description' => $ret->getDescription(),
1699 foreach ($proto->getParameters() as $p) {
1700 $profile['parameters'][] = array(
1701 'name' => $p->getName(),
1702 'type' => $p->getType(),
1703 'description' => $p->getDescription(),