MDL-27542 calendar export: deleting remaining debugging
[moodle.git] / lib / upgradelib.php
bloba6c0797330c8b973c8a491ef76de761b8cbcb608
1 <?php
3 // This file is part of Moodle - http://moodle.org/
4 //
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
9 //
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 /**
19 * Various upgrade/install related functions and classes.
21 * @package core
22 * @subpackage upgrade
23 * @copyright 1999 onwards Martin Dougiamas (http://dougiamas.com)
24 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
27 defined('MOODLE_INTERNAL') || die();
29 /** UPGRADE_LOG_NORMAL = 0 */
30 define('UPGRADE_LOG_NORMAL', 0);
31 /** UPGRADE_LOG_NOTICE = 1 */
32 define('UPGRADE_LOG_NOTICE', 1);
33 /** UPGRADE_LOG_ERROR = 2 */
34 define('UPGRADE_LOG_ERROR', 2);
36 /**
37 * Exception indicating unknown error during upgrade.
39 * @package core
40 * @subpackage upgrade
41 * @copyright 2009 Petr Skoda {@link http://skodak.org}
42 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
44 class upgrade_exception extends moodle_exception {
45 function __construct($plugin, $version, $debuginfo=NULL) {
46 global $CFG;
47 $a = (object)array('plugin'=>$plugin, 'version'=>$version);
48 parent::__construct('upgradeerror', 'admin', "$CFG->wwwroot/$CFG->admin/index.php", $a, $debuginfo);
52 /**
53 * Exception indicating downgrade error during upgrade.
55 * @package core
56 * @subpackage upgrade
57 * @copyright 2009 Petr Skoda {@link http://skodak.org}
58 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
60 class downgrade_exception extends moodle_exception {
61 function __construct($plugin, $oldversion, $newversion) {
62 global $CFG;
63 $plugin = is_null($plugin) ? 'moodle' : $plugin;
64 $a = (object)array('plugin'=>$plugin, 'oldversion'=>$oldversion, 'newversion'=>$newversion);
65 parent::__construct('cannotdowngrade', 'debug', "$CFG->wwwroot/$CFG->admin/index.php", $a);
69 /**
70 * @package core
71 * @subpackage upgrade
72 * @copyright 2009 Petr Skoda {@link http://skodak.org}
73 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
75 class upgrade_requires_exception extends moodle_exception {
76 function __construct($plugin, $pluginversion, $currentmoodle, $requiremoodle) {
77 global $CFG;
78 $a = new stdClass();
79 $a->pluginname = $plugin;
80 $a->pluginversion = $pluginversion;
81 $a->currentmoodle = $currentmoodle;
82 $a->requiremoodle = $requiremoodle;
83 parent::__construct('pluginrequirementsnotmet', 'error', "$CFG->wwwroot/$CFG->admin/index.php", $a);
87 /**
88 * @package core
89 * @subpackage upgrade
90 * @copyright 2009 Petr Skoda {@link http://skodak.org}
91 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
93 class plugin_defective_exception extends moodle_exception {
94 function __construct($plugin, $details) {
95 global $CFG;
96 parent::__construct('detectedbrokenplugin', 'error', "$CFG->wwwroot/$CFG->admin/index.php", $plugin, $details);
101 * Upgrade savepoint, marks end of each upgrade block.
102 * It stores new main version, resets upgrade timeout
103 * and abort upgrade if user cancels page loading.
105 * Please do not make large upgrade blocks with lots of operations,
106 * for example when adding tables keep only one table operation per block.
108 * @global object
109 * @param bool $result false if upgrade step failed, true if completed
110 * @param string or float $version main version
111 * @param bool $allowabort allow user to abort script execution here
112 * @return void
114 function upgrade_main_savepoint($result, $version, $allowabort=true) {
115 global $CFG;
117 //sanity check to avoid confusion with upgrade_mod_savepoint usage.
118 if (!is_bool($allowabort)) {
119 $errormessage = 'Parameter type mismatch. Are you mixing up upgrade_main_savepoint() and upgrade_mod_savepoint()?';
120 throw new coding_exception($errormessage);
123 if (!$result) {
124 throw new upgrade_exception(null, $version);
127 if ($CFG->version >= $version) {
128 // something really wrong is going on in main upgrade script
129 throw new downgrade_exception(null, $CFG->version, $version);
132 set_config('version', $version);
133 upgrade_log(UPGRADE_LOG_NORMAL, null, 'Upgrade savepoint reached');
135 // reset upgrade timeout to default
136 upgrade_set_timeout();
138 // this is a safe place to stop upgrades if user aborts page loading
139 if ($allowabort and connection_aborted()) {
140 die;
145 * Module upgrade savepoint, marks end of module upgrade blocks
146 * It stores module version, resets upgrade timeout
147 * and abort upgrade if user cancels page loading.
149 * @global object
150 * @param bool $result false if upgrade step failed, true if completed
151 * @param string or float $version main version
152 * @param string $modname name of module
153 * @param bool $allowabort allow user to abort script execution here
154 * @return void
156 function upgrade_mod_savepoint($result, $version, $modname, $allowabort=true) {
157 global $DB;
159 if (!$result) {
160 throw new upgrade_exception("mod_$modname", $version);
163 if (!$module = $DB->get_record('modules', array('name'=>$modname))) {
164 print_error('modulenotexist', 'debug', '', $modname);
167 if ($module->version >= $version) {
168 // something really wrong is going on in upgrade script
169 throw new downgrade_exception("mod_$modname", $module->version, $version);
171 $module->version = $version;
172 $DB->update_record('modules', $module);
173 upgrade_log(UPGRADE_LOG_NORMAL, "mod_$modname", 'Upgrade savepoint reached');
175 // reset upgrade timeout to default
176 upgrade_set_timeout();
178 // this is a safe place to stop upgrades if user aborts page loading
179 if ($allowabort and connection_aborted()) {
180 die;
185 * Blocks upgrade savepoint, marks end of blocks upgrade blocks
186 * It stores block version, resets upgrade timeout
187 * and abort upgrade if user cancels page loading.
189 * @global object
190 * @param bool $result false if upgrade step failed, true if completed
191 * @param string or float $version main version
192 * @param string $blockname name of block
193 * @param bool $allowabort allow user to abort script execution here
194 * @return void
196 function upgrade_block_savepoint($result, $version, $blockname, $allowabort=true) {
197 global $DB;
199 if (!$result) {
200 throw new upgrade_exception("block_$blockname", $version);
203 if (!$block = $DB->get_record('block', array('name'=>$blockname))) {
204 print_error('blocknotexist', 'debug', '', $blockname);
207 if ($block->version >= $version) {
208 // something really wrong is going on in upgrade script
209 throw new downgrade_exception("block_$blockname", $block->version, $version);
211 $block->version = $version;
212 $DB->update_record('block', $block);
213 upgrade_log(UPGRADE_LOG_NORMAL, "block_$blockname", 'Upgrade savepoint reached');
215 // reset upgrade timeout to default
216 upgrade_set_timeout();
218 // this is a safe place to stop upgrades if user aborts page loading
219 if ($allowabort and connection_aborted()) {
220 die;
225 * Plugins upgrade savepoint, marks end of blocks upgrade blocks
226 * It stores plugin version, resets upgrade timeout
227 * and abort upgrade if user cancels page loading.
229 * @param bool $result false if upgrade step failed, true if completed
230 * @param string or float $version main version
231 * @param string $type name of plugin
232 * @param string $dir location of plugin
233 * @param bool $allowabort allow user to abort script execution here
234 * @return void
236 function upgrade_plugin_savepoint($result, $version, $type, $plugin, $allowabort=true) {
237 $component = $type.'_'.$plugin;
239 if (!$result) {
240 throw new upgrade_exception($component, $version);
243 $installedversion = get_config($component, 'version');
244 if ($installedversion >= $version) {
245 // Something really wrong is going on in the upgrade script
246 throw new downgrade_exception($component, $installedversion, $version);
248 set_config('version', $version, $component);
249 upgrade_log(UPGRADE_LOG_NORMAL, $component, 'Upgrade savepoint reached');
251 // Reset upgrade timeout to default
252 upgrade_set_timeout();
254 // This is a safe place to stop upgrades if user aborts page loading
255 if ($allowabort and connection_aborted()) {
256 die;
262 * Upgrade plugins
263 * @param string $type The type of plugins that should be updated (e.g. 'enrol', 'qtype')
264 * return void
266 function upgrade_plugins($type, $startcallback, $endcallback, $verbose) {
267 global $CFG, $DB;
269 /// special cases
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')) {
290 continue;
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 upgrade_plugin_mnet_functions($component);
334 $endcallback($component, true, $verbose);
339 $installedversion = get_config($plugin->fullname, 'version');
340 if (empty($installedversion)) { // new installation
341 $startcallback($component, true, $verbose);
343 /// Install tables if defined
344 if (file_exists($fullplug.'/db/install.xml')) {
345 $DB->get_manager()->install_from_xmldb_file($fullplug.'/db/install.xml');
348 /// store version
349 upgrade_plugin_savepoint(true, $plugin->version, $type, $plug, false);
351 /// execute post install file
352 if (file_exists($fullplug.'/db/install.php')) {
353 require_once($fullplug.'/db/install.php');
354 set_config('installrunning', 1, $plugin->fullname);
355 $post_install_function = 'xmldb_'.$plugin->fullname.'_install';
356 $post_install_function();
357 unset_config('installrunning', $plugin->fullname);
360 /// Install various components
361 update_capabilities($component);
362 log_update_descriptions($component);
363 external_update_descriptions($component);
364 events_update_definition($component);
365 message_update_providers($component);
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 upgrade_plugin_mnet_functions($component);
398 purge_all_caches();
399 $endcallback($component, false, $verbose);
401 } else if ($installedversion > $plugin->version) {
402 throw new downgrade_exception($component, $installedversion, $plugin->version);
408 * Find and check all modules and load them up or upgrade them if necessary
410 * @global object
411 * @global object
413 function upgrade_plugins_modules($startcallback, $endcallback, $verbose) {
414 global $CFG, $DB;
416 $mods = get_plugin_list('mod');
418 foreach ($mods as $mod=>$fullmod) {
420 if ($mod === 'NEWMODULE') { // Someone has unzipped the template, ignore it
421 continue;
424 $component = 'mod_'.$mod;
426 // check module dir is valid name
427 $cmod = strtolower($mod);
428 $cmod = clean_param($cmod, PARAM_SAFEDIR);
429 $cmod = str_replace('-', '', $cmod);
430 $cmod = str_replace('_', '', $cmod); // modules MUST not have '_' in name and never will, sorry
431 if ($mod !== $cmod) {
432 throw new plugin_defective_exception($component, 'Invalid plugin directory name.');
435 if (!is_readable($fullmod.'/version.php')) {
436 throw new plugin_defective_exception($component, 'Missing version.php');
439 $module = new stdClass();
440 require($fullmod .'/version.php'); // defines $module with version etc
442 // if plugin tells us it's full name we may check the location
443 if (isset($module->component)) {
444 if ($module->component !== $component) {
445 throw new plugin_defective_exception($component, 'Plugin installed in wrong folder.');
449 if (empty($module->version)) {
450 if (isset($module->version)) {
451 // Version is empty but is set - it means its value is 0 or ''. Let us skip such module.
452 // This is intended for developers so they can work on the early stages of the module.
453 continue;
455 throw new plugin_defective_exception($component, 'Missing version value in version.php');
458 if (!empty($module->requires)) {
459 if ($module->requires > $CFG->version) {
460 throw new upgrade_requires_exception($component, $module->version, $CFG->version, $module->requires);
461 } else if ($module->requires < 2010000000) {
462 throw new plugin_defective_exception($component, 'Plugin is not compatible with Moodle 2.x or later.');
466 // all modules must have en lang pack
467 if (!is_readable("$fullmod/lang/en/$mod.php")) {
468 throw new plugin_defective_exception($component, 'Missing mandatory en language pack.');
471 $module->name = $mod; // The name MUST match the directory
473 $currmodule = $DB->get_record('modules', array('name'=>$module->name));
475 if (file_exists($fullmod.'/db/install.php')) {
476 if (get_config($module->name, 'installrunning')) {
477 require_once($fullmod.'/db/install.php');
478 $recover_install_function = 'xmldb_'.$module->name.'_install_recovery';
479 if (function_exists($recover_install_function)) {
480 $startcallback($component, true, $verbose);
481 $recover_install_function();
482 unset_config('installrunning', $module->name);
483 // Install various components too
484 update_capabilities($component);
485 log_update_descriptions($component);
486 external_update_descriptions($component);
487 events_update_definition($component);
488 message_update_providers($component);
489 upgrade_plugin_mnet_functions($component);
490 $endcallback($component, true, $verbose);
495 if (empty($currmodule->version)) {
496 $startcallback($component, true, $verbose);
498 /// Execute install.xml (XMLDB) - must be present in all modules
499 $DB->get_manager()->install_from_xmldb_file($fullmod.'/db/install.xml');
501 /// Add record into modules table - may be needed in install.php already
502 $module->id = $DB->insert_record('modules', $module);
504 /// Post installation hook - optional
505 if (file_exists("$fullmod/db/install.php")) {
506 require_once("$fullmod/db/install.php");
507 // Set installation running flag, we need to recover after exception or error
508 set_config('installrunning', 1, $module->name);
509 $post_install_function = 'xmldb_'.$module->name.'_install';;
510 $post_install_function();
511 unset_config('installrunning', $module->name);
514 /// Install various components
515 update_capabilities($component);
516 log_update_descriptions($component);
517 external_update_descriptions($component);
518 events_update_definition($component);
519 message_update_providers($component);
520 upgrade_plugin_mnet_functions($component);
522 purge_all_caches();
523 $endcallback($component, true, $verbose);
525 } else if ($currmodule->version < $module->version) {
526 /// If versions say that we need to upgrade but no upgrade files are available, notify and continue
527 $startcallback($component, false, $verbose);
529 if (is_readable($fullmod.'/db/upgrade.php')) {
530 require_once($fullmod.'/db/upgrade.php'); // defines new upgrading function
531 $newupgrade_function = 'xmldb_'.$module->name.'_upgrade';
532 $result = $newupgrade_function($currmodule->version, $module);
533 } else {
534 $result = true;
537 $currmodule = $DB->get_record('modules', array('name'=>$module->name));
538 if ($currmodule->version < $module->version) {
539 // store version if not already there
540 upgrade_mod_savepoint($result, $module->version, $mod, false);
543 /// Upgrade various components
544 update_capabilities($component);
545 log_update_descriptions($component);
546 external_update_descriptions($component);
547 events_update_definition($component);
548 message_update_providers($component);
549 upgrade_plugin_mnet_functions($component);
551 purge_all_caches();
553 $endcallback($component, false, $verbose);
555 } else if ($currmodule->version > $module->version) {
556 throw new downgrade_exception($component, $currmodule->version, $module->version);
563 * This function finds all available blocks and install them
564 * into blocks table or do all the upgrade process if newer.
566 * @global object
567 * @global object
569 function upgrade_plugins_blocks($startcallback, $endcallback, $verbose) {
570 global $CFG, $DB;
572 require_once($CFG->dirroot.'/blocks/moodleblock.class.php');
574 $blocktitles = array(); // we do not want duplicate titles
576 //Is this a first install
577 $first_install = null;
579 $blocks = get_plugin_list('block');
581 foreach ($blocks as $blockname=>$fullblock) {
583 if (is_null($first_install)) {
584 $first_install = ($DB->count_records('block_instances') == 0);
587 if ($blockname == 'NEWBLOCK') { // Someone has unzipped the template, ignore it
588 continue;
591 $component = 'block_'.$blockname;
593 // check block dir is valid name
594 $cblockname = strtolower($blockname);
595 $cblockname = clean_param($cblockname, PARAM_SAFEDIR);
596 $cblockname = str_replace('-', '', $cblockname);
597 if ($blockname !== $cblockname) {
598 throw new plugin_defective_exception($component, 'Invalid plugin directory name.');
601 if (!is_readable($fullblock.'/version.php')) {
602 throw new plugin_defective_exception('block/'.$blockname, 'Missing version.php file.');
604 $plugin = new stdClass();
605 $plugin->version = NULL;
606 $plugin->cron = 0;
607 include($fullblock.'/version.php');
608 $block = $plugin;
610 // if plugin tells us it's full name we may check the location
611 if (isset($block->component)) {
612 if ($block->component !== $component) {
613 throw new plugin_defective_exception($component, 'Plugin installed in wrong folder.');
617 if (!empty($plugin->requires)) {
618 if ($plugin->requires > $CFG->version) {
619 throw new upgrade_requires_exception($component, $plugin->version, $CFG->version, $plugin->requires);
620 } else if ($plugin->requires < 2010000000) {
621 throw new plugin_defective_exception($component, 'Plugin is not compatible with Moodle 2.x or later.');
625 if (!is_readable($fullblock.'/block_'.$blockname.'.php')) {
626 throw new plugin_defective_exception('block/'.$blockname, 'Missing main block class file.');
628 include_once($fullblock.'/block_'.$blockname.'.php');
630 $classname = 'block_'.$blockname;
632 if (!class_exists($classname)) {
633 throw new plugin_defective_exception($component, 'Can not load main class.');
636 $blockobj = new $classname; // This is what we'll be testing
637 $blocktitle = $blockobj->get_title();
639 // OK, it's as we all hoped. For further tests, the object will do them itself.
640 if (!$blockobj->_self_test()) {
641 throw new plugin_defective_exception($component, 'Self test failed.');
644 $block->name = $blockname; // The name MUST match the directory
646 if (empty($block->version)) {
647 throw new plugin_defective_exception($component, 'Missing block version.');
650 $currblock = $DB->get_record('block', array('name'=>$block->name));
652 if (file_exists($fullblock.'/db/install.php')) {
653 if (get_config('block_'.$blockname, 'installrunning')) {
654 require_once($fullblock.'/db/install.php');
655 $recover_install_function = 'xmldb_block_'.$blockname.'_install_recovery';
656 if (function_exists($recover_install_function)) {
657 $startcallback($component, true, $verbose);
658 $recover_install_function();
659 unset_config('installrunning', 'block_'.$blockname);
660 // Install various components
661 update_capabilities($component);
662 log_update_descriptions($component);
663 external_update_descriptions($component);
664 events_update_definition($component);
665 message_update_providers($component);
666 upgrade_plugin_mnet_functions($component);
667 $endcallback($component, true, $verbose);
672 if (empty($currblock->version)) { // block not installed yet, so install it
673 $conflictblock = array_search($blocktitle, $blocktitles);
674 if ($conflictblock !== false) {
675 // Duplicate block titles are not allowed, they confuse people
676 // AND PHP's associative arrays ;)
677 throw new plugin_defective_exception($component, get_string('blocknameconflict', 'error', (object)array('name'=>$block->name, 'conflict'=>$conflictblock)));
679 $startcallback($component, true, $verbose);
681 if (file_exists($fullblock.'/db/install.xml')) {
682 $DB->get_manager()->install_from_xmldb_file($fullblock.'/db/install.xml');
684 $block->id = $DB->insert_record('block', $block);
686 if (file_exists($fullblock.'/db/install.php')) {
687 require_once($fullblock.'/db/install.php');
688 // Set installation running flag, we need to recover after exception or error
689 set_config('installrunning', 1, 'block_'.$blockname);
690 $post_install_function = 'xmldb_block_'.$blockname.'_install';;
691 $post_install_function();
692 unset_config('installrunning', 'block_'.$blockname);
695 $blocktitles[$block->name] = $blocktitle;
697 // Install various components
698 update_capabilities($component);
699 log_update_descriptions($component);
700 external_update_descriptions($component);
701 events_update_definition($component);
702 message_update_providers($component);
703 upgrade_plugin_mnet_functions($component);
705 purge_all_caches();
706 $endcallback($component, true, $verbose);
708 } else if ($currblock->version < $block->version) {
709 $startcallback($component, false, $verbose);
711 if (is_readable($fullblock.'/db/upgrade.php')) {
712 require_once($fullblock.'/db/upgrade.php'); // defines new upgrading function
713 $newupgrade_function = 'xmldb_block_'.$blockname.'_upgrade';
714 $result = $newupgrade_function($currblock->version, $block);
715 } else {
716 $result = true;
719 $currblock = $DB->get_record('block', array('name'=>$block->name));
720 if ($currblock->version < $block->version) {
721 // store version if not already there
722 upgrade_block_savepoint($result, $block->version, $block->name, false);
725 if ($currblock->cron != $block->cron) {
726 // update cron flag if needed
727 $currblock->cron = $block->cron;
728 $DB->update_record('block', $currblock);
731 // Upgrade various components
732 update_capabilities($component);
733 log_update_descriptions($component);
734 external_update_descriptions($component);
735 events_update_definition($component);
736 message_update_providers($component);
737 upgrade_plugin_mnet_functions($component);
739 purge_all_caches();
740 $endcallback($component, false, $verbose);
742 } else if ($currblock->version > $block->version) {
743 throw new downgrade_exception($component, $currblock->version, $block->version);
748 // Finally, if we are in the first_install of BLOCKS setup frontpage and admin page blocks
749 if ($first_install) {
750 //Iterate over each course - there should be only site course here now
751 if ($courses = $DB->get_records('course')) {
752 foreach ($courses as $course) {
753 blocks_add_default_course_blocks($course);
757 blocks_add_default_system_blocks();
763 * Log_display description function used during install and upgrade.
765 * @param string $component name of component (moodle, mod_assignment, etc.)
766 * @return void
768 function log_update_descriptions($component) {
769 global $DB;
771 $defpath = get_component_directory($component).'/db/log.php';
773 if (!file_exists($defpath)) {
774 $DB->delete_records('log_display', array('component'=>$component));
775 return;
778 // load new info
779 $logs = array();
780 include($defpath);
781 $newlogs = array();
782 foreach ($logs as $log) {
783 $newlogs[$log['module'].'-'.$log['action']] = $log; // kind of unique name
785 unset($logs);
786 $logs = $newlogs;
788 $fields = array('module', 'action', 'mtable', 'field');
789 // update all log fist
790 $dblogs = $DB->get_records('log_display', array('component'=>$component));
791 foreach ($dblogs as $dblog) {
792 $name = $dblog->module.'-'.$dblog->action;
794 if (empty($logs[$name])) {
795 $DB->delete_records('log_display', array('id'=>$dblog->id));
796 continue;
799 $log = $logs[$name];
800 unset($logs[$name]);
802 $update = false;
803 foreach ($fields as $field) {
804 if ($dblog->$field != $log[$field]) {
805 $dblog->$field = $log[$field];
806 $update = true;
809 if ($update) {
810 $DB->update_record('log_display', $dblog);
813 foreach ($logs as $log) {
814 $dblog = (object)$log;
815 $dblog->component = $component;
816 $DB->insert_record('log_display', $dblog);
821 * Web service discovery function used during install and upgrade.
822 * @param string $component name of component (moodle, mod_assignment, etc.)
823 * @return void
825 function external_update_descriptions($component) {
826 global $DB;
828 $defpath = get_component_directory($component).'/db/services.php';
830 if (!file_exists($defpath)) {
831 external_delete_descriptions($component);
832 return;
835 // load new info
836 $functions = array();
837 $services = array();
838 include($defpath);
840 // update all function fist
841 $dbfunctions = $DB->get_records('external_functions', array('component'=>$component));
842 foreach ($dbfunctions as $dbfunction) {
843 if (empty($functions[$dbfunction->name])) {
844 $DB->delete_records('external_functions', array('id'=>$dbfunction->id));
845 // do not delete functions from external_services_functions, beacuse
846 // we want to notify admins when functions used in custom services disappear
848 //TODO: this looks wrong, we have to delete it eventually (skodak)
849 continue;
852 $function = $functions[$dbfunction->name];
853 unset($functions[$dbfunction->name]);
854 $function['classpath'] = empty($function['classpath']) ? null : $function['classpath'];
856 $update = false;
857 if ($dbfunction->classname != $function['classname']) {
858 $dbfunction->classname = $function['classname'];
859 $update = true;
861 if ($dbfunction->methodname != $function['methodname']) {
862 $dbfunction->methodname = $function['methodname'];
863 $update = true;
865 if ($dbfunction->classpath != $function['classpath']) {
866 $dbfunction->classpath = $function['classpath'];
867 $update = true;
869 $functioncapabilities = key_exists('capabilities', $function)?$function['capabilities']:'';
870 if ($dbfunction->capabilities != $functioncapabilities) {
871 $dbfunction->capabilities = $functioncapabilities;
872 $update = true;
874 if ($update) {
875 $DB->update_record('external_functions', $dbfunction);
878 foreach ($functions as $fname => $function) {
879 $dbfunction = new stdClass();
880 $dbfunction->name = $fname;
881 $dbfunction->classname = $function['classname'];
882 $dbfunction->methodname = $function['methodname'];
883 $dbfunction->classpath = empty($function['classpath']) ? null : $function['classpath'];
884 $dbfunction->component = $component;
885 $dbfunction->capabilities = key_exists('capabilities', $function)?$function['capabilities']:'';
886 $dbfunction->id = $DB->insert_record('external_functions', $dbfunction);
888 unset($functions);
890 // now deal with services
891 $dbservices = $DB->get_records('external_services', array('component'=>$component));
892 foreach ($dbservices as $dbservice) {
893 if (empty($services[$dbservice->name])) {
894 $DB->delete_records('external_services_functions', array('externalserviceid'=>$dbservice->id));
895 $DB->delete_records('external_services_users', array('externalserviceid'=>$dbservice->id));
896 $DB->delete_records('external_services', array('id'=>$dbservice->id));
897 continue;
899 $service = $services[$dbservice->name];
900 unset($services[$dbservice->name]);
901 $service['enabled'] = empty($service['enabled']) ? 0 : $service['enabled'];
902 $service['requiredcapability'] = empty($service['requiredcapability']) ? null : $service['requiredcapability'];
903 $service['restrictedusers'] = !isset($service['restrictedusers']) ? 1 : $service['restrictedusers'];
905 $update = false;
906 if ($dbservice->requiredcapability != $service['requiredcapability']) {
907 $dbservice->requiredcapability = $service['requiredcapability'];
908 $update = true;
910 if ($dbservice->restrictedusers != $service['restrictedusers']) {
911 $dbservice->restrictedusers = $service['restrictedusers'];
912 $update = true;
914 if ($update) {
915 $DB->update_record('external_services', $dbservice);
918 $functions = $DB->get_records('external_services_functions', array('externalserviceid'=>$dbservice->id));
919 foreach ($functions as $function) {
920 $key = array_search($function->functionname, $service['functions']);
921 if ($key === false) {
922 $DB->delete_records('external_services_functions', array('id'=>$function->id));
923 } else {
924 unset($service['functions'][$key]);
927 foreach ($service['functions'] as $fname) {
928 $newf = new stdClass();
929 $newf->externalserviceid = $dbservice->id;
930 $newf->functionname = $fname;
931 $DB->insert_record('external_services_functions', $newf);
933 unset($functions);
935 foreach ($services as $name => $service) {
936 $dbservice = new stdClass();
937 $dbservice->name = $name;
938 $dbservice->enabled = empty($service['enabled']) ? 0 : $service['enabled'];
939 $dbservice->requiredcapability = empty($service['requiredcapability']) ? null : $service['requiredcapability'];
940 $dbservice->restrictedusers = !isset($service['restrictedusers']) ? 1 : $service['restrictedusers'];
941 $dbservice->component = $component;
942 $dbservice->timecreated = time();
943 $dbservice->id = $DB->insert_record('external_services', $dbservice);
944 foreach ($service['functions'] as $fname) {
945 $newf = new stdClass();
946 $newf->externalserviceid = $dbservice->id;
947 $newf->functionname = $fname;
948 $DB->insert_record('external_services_functions', $newf);
954 * Delete all service and external functions information defined in the specified component.
955 * @param string $component name of component (moodle, mod_assignment, etc.)
956 * @return void
958 function external_delete_descriptions($component) {
959 global $DB;
961 $params = array($component);
963 $DB->delete_records_select('external_services_users', "externalserviceid IN (SELECT id FROM {external_services} WHERE component = ?)", $params);
964 $DB->delete_records_select('external_services_functions', "externalserviceid IN (SELECT id FROM {external_services} WHERE component = ?)", $params);
965 $DB->delete_records('external_services', array('component'=>$component));
966 $DB->delete_records('external_functions', array('component'=>$component));
970 * upgrade logging functions
972 function upgrade_handle_exception($ex, $plugin = null) {
973 global $CFG;
975 // rollback everything, we need to log all upgrade problems
976 abort_all_db_transactions();
978 $info = get_exception_info($ex);
980 // First log upgrade error
981 upgrade_log(UPGRADE_LOG_ERROR, $plugin, 'Exception: ' . get_class($ex), $info->message, $info->backtrace);
983 // Always turn on debugging - admins need to know what is going on
984 $CFG->debug = DEBUG_DEVELOPER;
986 default_exception_handler($ex, true, $plugin);
990 * Adds log entry into upgrade_log table
992 * @param int $type UPGRADE_LOG_NORMAL, UPGRADE_LOG_NOTICE or UPGRADE_LOG_ERROR
993 * @param string $plugin frankenstyle component name
994 * @param string $info short description text of log entry
995 * @param string $details long problem description
996 * @param string $backtrace string used for errors only
997 * @return void
999 function upgrade_log($type, $plugin, $info, $details=null, $backtrace=null) {
1000 global $DB, $USER, $CFG;
1002 if (empty($plugin)) {
1003 $plugin = 'core';
1006 list($plugintype, $pluginname) = normalize_component($plugin);
1007 $component = is_null($pluginname) ? $plugintype : $plugintype . '_' . $pluginname;
1009 $backtrace = format_backtrace($backtrace, true);
1011 $currentversion = null;
1012 $targetversion = null;
1014 //first try to find out current version number
1015 if ($plugintype === 'core') {
1016 //main
1017 $currentversion = $CFG->version;
1019 $version = null;
1020 include("$CFG->dirroot/version.php");
1021 $targetversion = $version;
1023 } else if ($plugintype === 'mod') {
1024 try {
1025 $currentversion = $DB->get_field('modules', 'version', array('name'=>$pluginname));
1026 $currentversion = ($currentversion === false) ? null : $currentversion;
1027 } catch (Exception $ignored) {
1029 $cd = get_component_directory($component);
1030 if (file_exists("$cd/version.php")) {
1031 $module = new stdClass();
1032 $module->version = null;
1033 include("$cd/version.php");
1034 $targetversion = $module->version;
1037 } else if ($plugintype === 'block') {
1038 try {
1039 if ($block = $DB->get_record('block', array('name'=>$pluginname))) {
1040 $currentversion = $block->version;
1042 } catch (Exception $ignored) {
1044 $cd = get_component_directory($component);
1045 if (file_exists("$cd/version.php")) {
1046 $plugin = new stdClass();
1047 $plugin->version = null;
1048 include("$cd/version.php");
1049 $targetversion = $plugin->version;
1052 } else {
1053 $pluginversion = get_config($component, 'version');
1054 if (!empty($pluginversion)) {
1055 $currentversion = $pluginversion;
1057 $cd = get_component_directory($component);
1058 if (file_exists("$cd/version.php")) {
1059 $plugin = new stdClass();
1060 $plugin->version = null;
1061 include("$cd/version.php");
1062 $targetversion = $plugin->version;
1066 $log = new stdClass();
1067 $log->type = $type;
1068 $log->plugin = $component;
1069 $log->version = $currentversion;
1070 $log->targetversion = $targetversion;
1071 $log->info = $info;
1072 $log->details = $details;
1073 $log->backtrace = $backtrace;
1074 $log->userid = $USER->id;
1075 $log->timemodified = time();
1076 try {
1077 $DB->insert_record('upgrade_log', $log);
1078 } catch (Exception $ignored) {
1079 // possible during install or 2.0 upgrade
1084 * Marks start of upgrade, blocks any other access to site.
1085 * The upgrade is finished at the end of script or after timeout.
1087 * @global object
1088 * @global object
1089 * @global object
1091 function upgrade_started($preinstall=false) {
1092 global $CFG, $DB, $PAGE, $OUTPUT;
1094 static $started = false;
1096 if ($preinstall) {
1097 ignore_user_abort(true);
1098 upgrade_setup_debug(true);
1100 } else if ($started) {
1101 upgrade_set_timeout(120);
1103 } else {
1104 if (!CLI_SCRIPT and !$PAGE->headerprinted) {
1105 $strupgrade = get_string('upgradingversion', 'admin');
1106 $PAGE->set_pagelayout('maintenance');
1107 upgrade_init_javascript();
1108 $PAGE->set_title($strupgrade.' - Moodle '.$CFG->target_release);
1109 $PAGE->set_heading($strupgrade);
1110 $PAGE->navbar->add($strupgrade);
1111 $PAGE->set_cacheable(false);
1112 echo $OUTPUT->header();
1115 ignore_user_abort(true);
1116 register_shutdown_function('upgrade_finished_handler');
1117 upgrade_setup_debug(true);
1118 set_config('upgraderunning', time()+300);
1119 $started = true;
1124 * Internal function - executed if upgrade interrupted.
1126 function upgrade_finished_handler() {
1127 upgrade_finished();
1131 * Indicates upgrade is finished.
1133 * This function may be called repeatedly.
1135 * @global object
1136 * @global object
1138 function upgrade_finished($continueurl=null) {
1139 global $CFG, $DB, $OUTPUT;
1141 if (!empty($CFG->upgraderunning)) {
1142 unset_config('upgraderunning');
1143 upgrade_setup_debug(false);
1144 ignore_user_abort(false);
1145 if ($continueurl) {
1146 echo $OUTPUT->continue_button($continueurl);
1147 echo $OUTPUT->footer();
1148 die;
1154 * @global object
1155 * @global object
1157 function upgrade_setup_debug($starting) {
1158 global $CFG, $DB;
1160 static $originaldebug = null;
1162 if ($starting) {
1163 if ($originaldebug === null) {
1164 $originaldebug = $DB->get_debug();
1166 if (!empty($CFG->upgradeshowsql)) {
1167 $DB->set_debug(true);
1169 } else {
1170 $DB->set_debug($originaldebug);
1175 * @global object
1177 function print_upgrade_reload($url) {
1178 global $OUTPUT;
1180 echo "<br />";
1181 echo '<div class="continuebutton">';
1182 echo '<a href="'.$url.'" title="'.get_string('reload').'" ><img src="'.$OUTPUT->pix_url('i/reload') . '" alt="" /> '.get_string('reload').'</a>';
1183 echo '</div><br />';
1186 function print_upgrade_separator() {
1187 if (!CLI_SCRIPT) {
1188 echo '<hr />';
1193 * Default start upgrade callback
1194 * @param string $plugin
1195 * @param bool $installation true if installation, false means upgrade
1197 function print_upgrade_part_start($plugin, $installation, $verbose) {
1198 global $OUTPUT;
1199 if (empty($plugin) or $plugin == 'moodle') {
1200 upgrade_started($installation); // does not store upgrade running flag yet
1201 if ($verbose) {
1202 echo $OUTPUT->heading(get_string('coresystem'));
1204 } else {
1205 upgrade_started();
1206 if ($verbose) {
1207 echo $OUTPUT->heading($plugin);
1210 if ($installation) {
1211 if (empty($plugin) or $plugin == 'moodle') {
1212 // no need to log - log table not yet there ;-)
1213 } else {
1214 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Starting plugin installation');
1216 } else {
1217 if (empty($plugin) or $plugin == 'moodle') {
1218 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Starting core upgrade');
1219 } else {
1220 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Starting plugin upgrade');
1226 * Default end upgrade callback
1227 * @param string $plugin
1228 * @param bool $installation true if installation, false means upgrade
1230 function print_upgrade_part_end($plugin, $installation, $verbose) {
1231 global $OUTPUT;
1232 upgrade_started();
1233 if ($installation) {
1234 if (empty($plugin) or $plugin == 'moodle') {
1235 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Core installed');
1236 } else {
1237 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Plugin installed');
1239 } else {
1240 if (empty($plugin) or $plugin == 'moodle') {
1241 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Core upgraded');
1242 } else {
1243 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Plugin upgraded');
1246 if ($verbose) {
1247 echo $OUTPUT->notification(get_string('success'), 'notifysuccess');
1248 print_upgrade_separator();
1253 * Sets up JS code required for all upgrade scripts.
1254 * @global object
1256 function upgrade_init_javascript() {
1257 global $PAGE;
1258 // scroll to the end of each upgrade page so that ppl see either error or continue button,
1259 // no need to scroll continuously any more, it is enough to jump to end once the footer is printed ;-)
1260 $js = "window.scrollTo(0, 5000000);";
1261 $PAGE->requires->js_init_code($js);
1266 * Try to upgrade the given language pack (or current language)
1268 * @todo hardcoded Moodle version here - shall be provided by version.php or similar script
1270 function upgrade_language_pack($lang='') {
1271 global $CFG, $OUTPUT;
1273 get_string_manager()->reset_caches();
1275 if (empty($lang)) {
1276 $lang = current_language();
1279 if ($lang == 'en') {
1280 return true; // Nothing to do
1283 upgrade_started(false);
1284 echo $OUTPUT->heading(get_string('langimport', 'admin').': '.$lang);
1286 @mkdir ($CFG->dataroot.'/temp/'); //make it in case it's a fresh install, it might not be there
1287 @mkdir ($CFG->dataroot.'/lang/');
1289 require_once($CFG->libdir.'/componentlib.class.php');
1291 if ($cd = new component_installer('http://download.moodle.org', 'langpack/2.0', $lang.'.zip', 'languages.md5', 'lang')) {
1292 $status = $cd->install(); //returns COMPONENT_(ERROR | UPTODATE | INSTALLED)
1294 if ($status == COMPONENT_INSTALLED) {
1295 if ($parentlang = get_parent_language($lang)) {
1296 if ($cd = new component_installer('http://download.moodle.org', 'langpack/2.0', $parentlang.'.zip', 'languages.md5', 'lang')) {
1297 $cd->install();
1300 echo $OUTPUT->notification(get_string('success'), 'notifysuccess');
1304 get_string_manager()->reset_caches();
1306 print_upgrade_separator();
1310 * Install core moodle tables and initialize
1311 * @param float $version target version
1312 * @param bool $verbose
1313 * @return void, may throw exception
1315 function install_core($version, $verbose) {
1316 global $CFG, $DB;
1318 try {
1319 set_time_limit(600);
1320 print_upgrade_part_start('moodle', true, $verbose); // does not store upgrade running flag
1322 $DB->get_manager()->install_from_xmldb_file("$CFG->libdir/db/install.xml");
1323 upgrade_started(); // we want the flag to be stored in config table ;-)
1325 // set all core default records and default settings
1326 require_once("$CFG->libdir/db/install.php");
1327 xmldb_main_install(); // installs the capabilities too
1329 // store version
1330 upgrade_main_savepoint(true, $version, false);
1332 // Continue with the installation
1333 log_update_descriptions('moodle');
1334 external_update_descriptions('moodle');
1335 events_update_definition('moodle');
1336 message_update_providers('moodle');
1338 // Write default settings unconditionally
1339 admin_apply_default_settings(NULL, true);
1341 print_upgrade_part_end(null, true, $verbose);
1342 } catch (exception $ex) {
1343 upgrade_handle_exception($ex);
1348 * Upgrade moodle core
1349 * @param float $version target version
1350 * @param bool $verbose
1351 * @return void, may throw exception
1353 function upgrade_core($version, $verbose) {
1354 global $CFG;
1356 raise_memory_limit(MEMORY_EXTRA);
1358 require_once($CFG->libdir.'/db/upgrade.php'); // Defines upgrades
1360 try {
1361 // Reset caches before any output
1362 purge_all_caches();
1364 // Upgrade current language pack if we can
1365 if (empty($CFG->skiplangupgrade)) {
1366 if (get_string_manager()->translation_exists(current_language())) {
1367 upgrade_language_pack(false);
1371 print_upgrade_part_start('moodle', false, $verbose);
1373 // one time special local migration pre 2.0 upgrade script
1374 if ($CFG->version < 2007101600) {
1375 $pre20upgradefile = "$CFG->dirroot/local/upgrade_pre20.php";
1376 if (file_exists($pre20upgradefile)) {
1377 set_time_limit(0);
1378 require($pre20upgradefile);
1379 // reset upgrade timeout to default
1380 upgrade_set_timeout();
1384 $result = xmldb_main_upgrade($CFG->version);
1385 if ($version > $CFG->version) {
1386 // store version if not already there
1387 upgrade_main_savepoint($result, $version, false);
1390 // perform all other component upgrade routines
1391 update_capabilities('moodle');
1392 log_update_descriptions('moodle');
1393 external_update_descriptions('moodle');
1394 events_update_definition('moodle');
1395 message_update_providers('moodle');
1397 // Reset caches again, just to be sure
1398 purge_all_caches();
1400 // Clean up contexts - more and more stuff depends on existence of paths and contexts
1401 cleanup_contexts();
1402 create_contexts();
1403 build_context_path();
1404 $syscontext = get_context_instance(CONTEXT_SYSTEM);
1405 mark_context_dirty($syscontext->path);
1407 print_upgrade_part_end('moodle', false, $verbose);
1408 } catch (Exception $ex) {
1409 upgrade_handle_exception($ex);
1414 * Upgrade/install other parts of moodle
1415 * @param bool $verbose
1416 * @return void, may throw exception
1418 function upgrade_noncore($verbose) {
1419 global $CFG;
1421 raise_memory_limit(MEMORY_EXTRA);
1423 // upgrade all plugins types
1424 try {
1425 $plugintypes = get_plugin_types();
1426 foreach ($plugintypes as $type=>$location) {
1427 upgrade_plugins($type, 'print_upgrade_part_start', 'print_upgrade_part_end', $verbose);
1429 } catch (Exception $ex) {
1430 upgrade_handle_exception($ex);
1435 * Checks if the main tables have been installed yet or not.
1436 * @return bool
1438 function core_tables_exist() {
1439 global $DB;
1441 if (!$tables = $DB->get_tables() ) { // No tables yet at all.
1442 return false;
1444 } else { // Check for missing main tables
1445 $mtables = array('config', 'course', 'groupings'); // some tables used in 1.9 and 2.0, preferable something from the start and end of install.xml
1446 foreach ($mtables as $mtable) {
1447 if (!in_array($mtable, $tables)) {
1448 return false;
1451 return true;
1456 * upgrades the mnet rpc definitions for the given component.
1457 * this method doesn't return status, an exception will be thrown in the case of an error
1459 * @param string $component the plugin to upgrade, eg auth_mnet
1461 function upgrade_plugin_mnet_functions($component) {
1462 global $DB, $CFG;
1464 list($type, $plugin) = explode('_', $component);
1465 $path = get_plugin_directory($type, $plugin);
1467 $publishes = array();
1468 $subscribes = array();
1469 if (file_exists($path . '/db/mnet.php')) {
1470 require_once($path . '/db/mnet.php'); // $publishes comes from this file
1472 if (empty($publishes)) {
1473 $publishes = array(); // still need this to be able to disable stuff later
1475 if (empty($subscribes)) {
1476 $subscribes = array(); // still need this to be able to disable stuff later
1479 static $servicecache = array();
1481 // rekey an array based on the rpc method for easy lookups later
1482 $publishmethodservices = array();
1483 $subscribemethodservices = array();
1484 foreach($publishes as $servicename => $service) {
1485 if (is_array($service['methods'])) {
1486 foreach($service['methods'] as $methodname) {
1487 $service['servicename'] = $servicename;
1488 $publishmethodservices[$methodname][] = $service;
1493 // Disable functions that don't exist (any more) in the source
1494 // Should these be deleted? What about their permissions records?
1495 foreach ($DB->get_records('mnet_rpc', array('pluginname'=>$plugin, 'plugintype'=>$type), 'functionname ASC ') as $rpc) {
1496 if (!array_key_exists($rpc->functionname, $publishmethodservices) && $rpc->enabled) {
1497 $DB->set_field('mnet_rpc', 'enabled', 0, array('id' => $rpc->id));
1498 } else if (array_key_exists($rpc->functionname, $publishmethodservices) && !$rpc->enabled) {
1499 $DB->set_field('mnet_rpc', 'enabled', 1, array('id' => $rpc->id));
1503 // reflect all the services we're publishing and save them
1504 require_once($CFG->dirroot . '/lib/zend/Zend/Server/Reflection.php');
1505 static $cachedclasses = array(); // to store reflection information in
1506 foreach ($publishes as $service => $data) {
1507 $f = $data['filename'];
1508 $c = $data['classname'];
1509 foreach ($data['methods'] as $method) {
1510 $dataobject = new stdClass();
1511 $dataobject->plugintype = $type;
1512 $dataobject->pluginname = $plugin;
1513 $dataobject->enabled = 1;
1514 $dataobject->classname = $c;
1515 $dataobject->filename = $f;
1517 if (is_string($method)) {
1518 $dataobject->functionname = $method;
1520 } else if (is_array($method)) { // wants to override file or class
1521 $dataobject->functionname = $method['method'];
1522 $dataobject->classname = $method['classname'];
1523 $dataobject->filename = $method['filename'];
1525 $dataobject->xmlrpcpath = $type.'/'.$plugin.'/'.$dataobject->filename.'/'.$method;
1526 $dataobject->static = false;
1528 require_once($path . '/' . $dataobject->filename);
1529 $functionreflect = null; // slightly different ways to get this depending on whether it's a class method or a function
1530 if (!empty($dataobject->classname)) {
1531 if (!class_exists($dataobject->classname)) {
1532 throw new moodle_exception('installnosuchmethod', 'mnet', '', (object)array('method' => $dataobject->functionname, 'class' => $dataobject->classname));
1534 $key = $dataobject->filename . '|' . $dataobject->classname;
1535 if (!array_key_exists($key, $cachedclasses)) { // look to see if we've already got a reflection object
1536 try {
1537 $cachedclasses[$key] = Zend_Server_Reflection::reflectClass($dataobject->classname);
1538 } catch (Zend_Server_Reflection_Exception $e) { // catch these and rethrow them to something more helpful
1539 throw new moodle_exception('installreflectionclasserror', 'mnet', '', (object)array('method' => $dataobject->functionname, 'class' => $dataobject->classname, 'error' => $e->getMessage()));
1542 $r =& $cachedclasses[$key];
1543 if (!$r->hasMethod($dataobject->functionname)) {
1544 throw new moodle_exception('installnosuchmethod', 'mnet', '', (object)array('method' => $dataobject->functionname, 'class' => $dataobject->classname));
1546 // stupid workaround for zend not having a getMethod($name) function
1547 $ms = $r->getMethods();
1548 foreach ($ms as $m) {
1549 if ($m->getName() == $dataobject->functionname) {
1550 $functionreflect = $m;
1551 break;
1554 $dataobject->static = (int)$functionreflect->isStatic();
1555 } else {
1556 if (!function_exists($dataobject->functionname)) {
1557 throw new moodle_exception('installnosuchfunction', 'mnet', '', (object)array('method' => $dataobject->functionname, 'file' => $dataobject->filename));
1559 try {
1560 $functionreflect = Zend_Server_Reflection::reflectFunction($dataobject->functionname);
1561 } catch (Zend_Server_Reflection_Exception $e) { // catch these and rethrow them to something more helpful
1562 throw new moodle_exception('installreflectionfunctionerror', 'mnet', '', (object)array('method' => $dataobject->functionname, '' => $dataobject->filename, 'error' => $e->getMessage()));
1565 $dataobject->profile = serialize(admin_mnet_method_profile($functionreflect));
1566 $dataobject->help = $functionreflect->getDescription();
1568 if ($record_exists = $DB->get_record('mnet_rpc', array('xmlrpcpath'=>$dataobject->xmlrpcpath))) {
1569 $dataobject->id = $record_exists->id;
1570 $dataobject->enabled = $record_exists->enabled;
1571 $DB->update_record('mnet_rpc', $dataobject);
1572 } else {
1573 $dataobject->id = $DB->insert_record('mnet_rpc', $dataobject, true);
1576 // TODO this API versioning must be reworked, here the recently processed method
1577 // sets the service API which may not be correct
1578 foreach ($publishmethodservices[$dataobject->functionname] as $service) {
1579 if ($serviceobj = $DB->get_record('mnet_service', array('name'=>$service['servicename']))) {
1580 $serviceobj->apiversion = $service['apiversion'];
1581 $DB->update_record('mnet_service', $serviceobj);
1582 } else {
1583 $serviceobj = new stdClass();
1584 $serviceobj->name = $service['servicename'];
1585 $serviceobj->description = empty($service['description']) ? '' : $service['description'];
1586 $serviceobj->apiversion = $service['apiversion'];
1587 $serviceobj->offer = 1;
1588 $serviceobj->id = $DB->insert_record('mnet_service', $serviceobj);
1590 $servicecache[$service['servicename']] = $serviceobj;
1591 if (!$DB->record_exists('mnet_service2rpc', array('rpcid'=>$dataobject->id, 'serviceid'=>$serviceobj->id))) {
1592 $obj = new stdClass();
1593 $obj->rpcid = $dataobject->id;
1594 $obj->serviceid = $serviceobj->id;
1595 $DB->insert_record('mnet_service2rpc', $obj, true);
1600 // finished with methods we publish, now do subscribable methods
1601 foreach($subscribes as $service => $methods) {
1602 if (!array_key_exists($service, $servicecache)) {
1603 if (!$serviceobj = $DB->get_record('mnet_service', array('name' => $service))) {
1604 debugging("TODO: skipping unknown service $service - somebody needs to fix MDL-21993");
1605 continue;
1607 $servicecache[$service] = $serviceobj;
1608 } else {
1609 $serviceobj = $servicecache[$service];
1611 foreach ($methods as $method => $xmlrpcpath) {
1612 if (!$rpcid = $DB->get_field('mnet_remote_rpc', 'id', array('xmlrpcpath'=>$xmlrpcpath))) {
1613 $remoterpc = (object)array(
1614 'functionname' => $method,
1615 'xmlrpcpath' => $xmlrpcpath,
1616 'plugintype' => $type,
1617 'pluginname' => $plugin,
1618 'enabled' => 1,
1620 $rpcid = $remoterpc->id = $DB->insert_record('mnet_remote_rpc', $remoterpc, true);
1622 if (!$DB->record_exists('mnet_remote_service2rpc', array('rpcid'=>$rpcid, 'serviceid'=>$serviceobj->id))) {
1623 $obj = new stdClass();
1624 $obj->rpcid = $rpcid;
1625 $obj->serviceid = $serviceobj->id;
1626 $DB->insert_record('mnet_remote_service2rpc', $obj, true);
1628 $subscribemethodservices[$method][] = $service;
1632 foreach ($DB->get_records('mnet_remote_rpc', array('pluginname'=>$plugin, 'plugintype'=>$type), 'functionname ASC ') as $rpc) {
1633 if (!array_key_exists($rpc->functionname, $subscribemethodservices) && $rpc->enabled) {
1634 $DB->set_field('mnet_remote_rpc', 'enabled', 0, array('id' => $rpc->id));
1635 } else if (array_key_exists($rpc->functionname, $subscribemethodservices) && !$rpc->enabled) {
1636 $DB->set_field('mnet_remote_rpc', 'enabled', 1, array('id' => $rpc->id));
1640 return true;
1644 * Given some sort of Zend Reflection function/method object, return a profile array, ready to be serialized and stored
1646 * @param Zend_Server_Reflection_Function_Abstract $function can be any subclass of this object type
1648 * @return array
1650 function admin_mnet_method_profile(Zend_Server_Reflection_Function_Abstract $function) {
1651 $proto = array_pop($function->getPrototypes());
1652 $ret = $proto->getReturnValue();
1653 $profile = array(
1654 'parameters' => array(),
1655 'return' => array(
1656 'type' => $ret->getType(),
1657 'description' => $ret->getDescription(),
1660 foreach ($proto->getParameters() as $p) {
1661 $profile['parameters'][] = array(
1662 'name' => $p->getName(),
1663 'type' => $p->getType(),
1664 'description' => $p->getDescription(),
1667 return $profile;