Merge branch 'MDL-34171_22' of git://github.com/timhunt/moodle into MOODLE_22_STABLE
[moodle.git] / lib / upgradelib.php
bloba81c98b9a8d9fd7433acf4685c9d55d1dad98c44
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 // Reset time so that it works when installing a large number of plugins
280 set_time_limit(600);
281 $component = clean_param($type.'_'.$plug, PARAM_COMPONENT); // standardised plugin name
283 // check plugin dir is valid name
284 if (empty($component)) {
285 throw new plugin_defective_exception($type.'_'.$plug, 'Invalid plugin directory name.');
288 if (!is_readable($fullplug.'/version.php')) {
289 continue;
292 $plugin = new stdClass();
293 require($fullplug.'/version.php'); // defines $plugin with version etc
295 // if plugin tells us it's full name we may check the location
296 if (isset($plugin->component)) {
297 if ($plugin->component !== $component) {
298 throw new plugin_defective_exception($component, 'Plugin installed in wrong folder.');
302 if (empty($plugin->version)) {
303 throw new plugin_defective_exception($component, 'Missing version value in version.php');
306 $plugin->name = $plug;
307 $plugin->fullname = $component;
310 if (!empty($plugin->requires)) {
311 if ($plugin->requires > $CFG->version) {
312 throw new upgrade_requires_exception($component, $plugin->version, $CFG->version, $plugin->requires);
313 } else if ($plugin->requires < 2010000000) {
314 throw new plugin_defective_exception($component, 'Plugin is not compatible with Moodle 2.x or later.');
318 // try to recover from interrupted install.php if needed
319 if (file_exists($fullplug.'/db/install.php')) {
320 if (get_config($plugin->fullname, 'installrunning')) {
321 require_once($fullplug.'/db/install.php');
322 $recover_install_function = 'xmldb_'.$plugin->fullname.'_install_recovery';
323 if (function_exists($recover_install_function)) {
324 $startcallback($component, true, $verbose);
325 $recover_install_function();
326 unset_config('installrunning', $plugin->fullname);
327 update_capabilities($component);
328 log_update_descriptions($component);
329 external_update_descriptions($component);
330 events_update_definition($component);
331 message_update_providers($component);
332 if ($type === 'message') {
333 message_update_processors($plug);
335 upgrade_plugin_mnet_functions($component);
336 $endcallback($component, true, $verbose);
341 $installedversion = get_config($plugin->fullname, 'version');
342 if (empty($installedversion)) { // new installation
343 $startcallback($component, true, $verbose);
345 /// Install tables if defined
346 if (file_exists($fullplug.'/db/install.xml')) {
347 $DB->get_manager()->install_from_xmldb_file($fullplug.'/db/install.xml');
350 /// store version
351 upgrade_plugin_savepoint(true, $plugin->version, $type, $plug, false);
353 /// execute post install file
354 if (file_exists($fullplug.'/db/install.php')) {
355 require_once($fullplug.'/db/install.php');
356 set_config('installrunning', 1, $plugin->fullname);
357 $post_install_function = 'xmldb_'.$plugin->fullname.'_install';
358 $post_install_function();
359 unset_config('installrunning', $plugin->fullname);
362 /// Install various components
363 update_capabilities($component);
364 log_update_descriptions($component);
365 external_update_descriptions($component);
366 events_update_definition($component);
367 message_update_providers($component);
368 if ($type === 'message') {
369 message_update_processors($plug);
371 upgrade_plugin_mnet_functions($component);
373 purge_all_caches();
374 $endcallback($component, true, $verbose);
376 } else if ($installedversion < $plugin->version) { // upgrade
377 /// Run the upgrade function for the plugin.
378 $startcallback($component, false, $verbose);
380 if (is_readable($fullplug.'/db/upgrade.php')) {
381 require_once($fullplug.'/db/upgrade.php'); // defines upgrading function
383 $newupgrade_function = 'xmldb_'.$plugin->fullname.'_upgrade';
384 $result = $newupgrade_function($installedversion);
385 } else {
386 $result = true;
389 $installedversion = get_config($plugin->fullname, 'version');
390 if ($installedversion < $plugin->version) {
391 // store version if not already there
392 upgrade_plugin_savepoint($result, $plugin->version, $type, $plug, false);
395 /// Upgrade various components
396 update_capabilities($component);
397 log_update_descriptions($component);
398 external_update_descriptions($component);
399 events_update_definition($component);
400 message_update_providers($component);
401 if ($type === 'message') {
402 message_update_processors($plug);
404 upgrade_plugin_mnet_functions($component);
406 purge_all_caches();
407 $endcallback($component, false, $verbose);
409 } else if ($installedversion > $plugin->version) {
410 throw new downgrade_exception($component, $installedversion, $plugin->version);
416 * Find and check all modules and load them up or upgrade them if necessary
418 * @global object
419 * @global object
421 function upgrade_plugins_modules($startcallback, $endcallback, $verbose) {
422 global $CFG, $DB;
424 $mods = get_plugin_list('mod');
426 foreach ($mods as $mod=>$fullmod) {
428 if ($mod === 'NEWMODULE') { // Someone has unzipped the template, ignore it
429 continue;
432 $component = clean_param('mod_'.$mod, PARAM_COMPONENT);
434 // check module dir is valid name
435 if (empty($component)) {
436 throw new plugin_defective_exception('mod_'.$mod, 'Invalid plugin directory name.');
439 if (!is_readable($fullmod.'/version.php')) {
440 throw new plugin_defective_exception($component, 'Missing version.php');
443 $module = new stdClass();
444 require($fullmod .'/version.php'); // defines $module with version etc
446 // if plugin tells us it's full name we may check the location
447 if (isset($module->component)) {
448 if ($module->component !== $component) {
449 throw new plugin_defective_exception($component, 'Plugin installed in wrong folder.');
453 if (empty($module->version)) {
454 if (isset($module->version)) {
455 // Version is empty but is set - it means its value is 0 or ''. Let us skip such module.
456 // This is intended for developers so they can work on the early stages of the module.
457 continue;
459 throw new plugin_defective_exception($component, 'Missing version value in version.php');
462 if (!empty($module->requires)) {
463 if ($module->requires > $CFG->version) {
464 throw new upgrade_requires_exception($component, $module->version, $CFG->version, $module->requires);
465 } else if ($module->requires < 2010000000) {
466 throw new plugin_defective_exception($component, 'Plugin is not compatible with Moodle 2.x or later.');
470 if (empty($module->cron)) {
471 $module->cron = 0;
474 // all modules must have en lang pack
475 if (!is_readable("$fullmod/lang/en/$mod.php")) {
476 throw new plugin_defective_exception($component, 'Missing mandatory en language pack.');
479 $module->name = $mod; // The name MUST match the directory
481 $currmodule = $DB->get_record('modules', array('name'=>$module->name));
483 if (file_exists($fullmod.'/db/install.php')) {
484 if (get_config($module->name, 'installrunning')) {
485 require_once($fullmod.'/db/install.php');
486 $recover_install_function = 'xmldb_'.$module->name.'_install_recovery';
487 if (function_exists($recover_install_function)) {
488 $startcallback($component, true, $verbose);
489 $recover_install_function();
490 unset_config('installrunning', $module->name);
491 // Install various components too
492 update_capabilities($component);
493 log_update_descriptions($component);
494 external_update_descriptions($component);
495 events_update_definition($component);
496 message_update_providers($component);
497 upgrade_plugin_mnet_functions($component);
498 $endcallback($component, true, $verbose);
503 if (empty($currmodule->version)) {
504 $startcallback($component, true, $verbose);
506 /// Execute install.xml (XMLDB) - must be present in all modules
507 $DB->get_manager()->install_from_xmldb_file($fullmod.'/db/install.xml');
509 /// Add record into modules table - may be needed in install.php already
510 $module->id = $DB->insert_record('modules', $module);
512 /// Post installation hook - optional
513 if (file_exists("$fullmod/db/install.php")) {
514 require_once("$fullmod/db/install.php");
515 // Set installation running flag, we need to recover after exception or error
516 set_config('installrunning', 1, $module->name);
517 $post_install_function = 'xmldb_'.$module->name.'_install';
518 $post_install_function();
519 unset_config('installrunning', $module->name);
522 /// Install various components
523 update_capabilities($component);
524 log_update_descriptions($component);
525 external_update_descriptions($component);
526 events_update_definition($component);
527 message_update_providers($component);
528 upgrade_plugin_mnet_functions($component);
530 purge_all_caches();
531 $endcallback($component, true, $verbose);
533 } else if ($currmodule->version < $module->version) {
534 /// If versions say that we need to upgrade but no upgrade files are available, notify and continue
535 $startcallback($component, false, $verbose);
537 if (is_readable($fullmod.'/db/upgrade.php')) {
538 require_once($fullmod.'/db/upgrade.php'); // defines new upgrading function
539 $newupgrade_function = 'xmldb_'.$module->name.'_upgrade';
540 $result = $newupgrade_function($currmodule->version, $module);
541 } else {
542 $result = true;
545 $currmodule = $DB->get_record('modules', array('name'=>$module->name));
546 if ($currmodule->version < $module->version) {
547 // store version if not already there
548 upgrade_mod_savepoint($result, $module->version, $mod, false);
551 // update cron flag if needed
552 if ($currmodule->cron != $module->cron) {
553 $DB->set_field('modules', 'cron', $module->cron, array('name' => $module->name));
556 // Upgrade various components
557 update_capabilities($component);
558 log_update_descriptions($component);
559 external_update_descriptions($component);
560 events_update_definition($component);
561 message_update_providers($component);
562 upgrade_plugin_mnet_functions($component);
564 purge_all_caches();
566 $endcallback($component, false, $verbose);
568 } else if ($currmodule->version > $module->version) {
569 throw new downgrade_exception($component, $currmodule->version, $module->version);
576 * This function finds all available blocks and install them
577 * into blocks table or do all the upgrade process if newer.
579 * @global object
580 * @global object
582 function upgrade_plugins_blocks($startcallback, $endcallback, $verbose) {
583 global $CFG, $DB;
585 require_once($CFG->dirroot.'/blocks/moodleblock.class.php');
587 $blocktitles = array(); // we do not want duplicate titles
589 //Is this a first install
590 $first_install = null;
592 $blocks = get_plugin_list('block');
594 foreach ($blocks as $blockname=>$fullblock) {
596 if (is_null($first_install)) {
597 $first_install = ($DB->count_records('block_instances') == 0);
600 if ($blockname === 'NEWBLOCK') { // Someone has unzipped the template, ignore it
601 continue;
604 $component = clean_param('block_'.$blockname, PARAM_COMPONENT);
606 // check block dir is valid name
607 if (empty($component)) {
608 throw new plugin_defective_exception('block_'.$blockname, 'Invalid plugin directory name.');
611 if (!is_readable($fullblock.'/version.php')) {
612 throw new plugin_defective_exception('block/'.$blockname, 'Missing version.php file.');
614 $plugin = new stdClass();
615 $plugin->version = NULL;
616 $plugin->cron = 0;
617 include($fullblock.'/version.php');
618 $block = $plugin;
620 // if plugin tells us it's full name we may check the location
621 if (isset($block->component)) {
622 if ($block->component !== $component) {
623 throw new plugin_defective_exception($component, 'Plugin installed in wrong folder.');
627 if (!empty($plugin->requires)) {
628 if ($plugin->requires > $CFG->version) {
629 throw new upgrade_requires_exception($component, $plugin->version, $CFG->version, $plugin->requires);
630 } else if ($plugin->requires < 2010000000) {
631 throw new plugin_defective_exception($component, 'Plugin is not compatible with Moodle 2.x or later.');
635 if (!is_readable($fullblock.'/block_'.$blockname.'.php')) {
636 throw new plugin_defective_exception('block/'.$blockname, 'Missing main block class file.');
638 include_once($fullblock.'/block_'.$blockname.'.php');
640 $classname = 'block_'.$blockname;
642 if (!class_exists($classname)) {
643 throw new plugin_defective_exception($component, 'Can not load main class.');
646 $blockobj = new $classname; // This is what we'll be testing
647 $blocktitle = $blockobj->get_title();
649 // OK, it's as we all hoped. For further tests, the object will do them itself.
650 if (!$blockobj->_self_test()) {
651 throw new plugin_defective_exception($component, 'Self test failed.');
654 $block->name = $blockname; // The name MUST match the directory
656 if (empty($block->version)) {
657 throw new plugin_defective_exception($component, 'Missing block version.');
660 $currblock = $DB->get_record('block', array('name'=>$block->name));
662 if (file_exists($fullblock.'/db/install.php')) {
663 if (get_config('block_'.$blockname, 'installrunning')) {
664 require_once($fullblock.'/db/install.php');
665 $recover_install_function = 'xmldb_block_'.$blockname.'_install_recovery';
666 if (function_exists($recover_install_function)) {
667 $startcallback($component, true, $verbose);
668 $recover_install_function();
669 unset_config('installrunning', 'block_'.$blockname);
670 // Install various components
671 update_capabilities($component);
672 log_update_descriptions($component);
673 external_update_descriptions($component);
674 events_update_definition($component);
675 message_update_providers($component);
676 upgrade_plugin_mnet_functions($component);
677 $endcallback($component, true, $verbose);
682 if (empty($currblock->version)) { // block not installed yet, so install it
683 $conflictblock = array_search($blocktitle, $blocktitles);
684 if ($conflictblock !== false) {
685 // Duplicate block titles are not allowed, they confuse people
686 // AND PHP's associative arrays ;)
687 throw new plugin_defective_exception($component, get_string('blocknameconflict', 'error', (object)array('name'=>$block->name, 'conflict'=>$conflictblock)));
689 $startcallback($component, true, $verbose);
691 if (file_exists($fullblock.'/db/install.xml')) {
692 $DB->get_manager()->install_from_xmldb_file($fullblock.'/db/install.xml');
694 $block->id = $DB->insert_record('block', $block);
696 if (file_exists($fullblock.'/db/install.php')) {
697 require_once($fullblock.'/db/install.php');
698 // Set installation running flag, we need to recover after exception or error
699 set_config('installrunning', 1, 'block_'.$blockname);
700 $post_install_function = 'xmldb_block_'.$blockname.'_install';;
701 $post_install_function();
702 unset_config('installrunning', 'block_'.$blockname);
705 $blocktitles[$block->name] = $blocktitle;
707 // Install various components
708 update_capabilities($component);
709 log_update_descriptions($component);
710 external_update_descriptions($component);
711 events_update_definition($component);
712 message_update_providers($component);
713 upgrade_plugin_mnet_functions($component);
715 purge_all_caches();
716 $endcallback($component, true, $verbose);
718 } else if ($currblock->version < $block->version) {
719 $startcallback($component, false, $verbose);
721 if (is_readable($fullblock.'/db/upgrade.php')) {
722 require_once($fullblock.'/db/upgrade.php'); // defines new upgrading function
723 $newupgrade_function = 'xmldb_block_'.$blockname.'_upgrade';
724 $result = $newupgrade_function($currblock->version, $block);
725 } else {
726 $result = true;
729 $currblock = $DB->get_record('block', array('name'=>$block->name));
730 if ($currblock->version < $block->version) {
731 // store version if not already there
732 upgrade_block_savepoint($result, $block->version, $block->name, false);
735 if ($currblock->cron != $block->cron) {
736 // update cron flag if needed
737 $currblock->cron = $block->cron;
738 $DB->update_record('block', $currblock);
741 // Upgrade various components
742 update_capabilities($component);
743 log_update_descriptions($component);
744 external_update_descriptions($component);
745 events_update_definition($component);
746 message_update_providers($component);
747 upgrade_plugin_mnet_functions($component);
749 purge_all_caches();
750 $endcallback($component, false, $verbose);
752 } else if ($currblock->version > $block->version) {
753 throw new downgrade_exception($component, $currblock->version, $block->version);
758 // Finally, if we are in the first_install of BLOCKS setup frontpage and admin page blocks
759 if ($first_install) {
760 //Iterate over each course - there should be only site course here now
761 if ($courses = $DB->get_records('course')) {
762 foreach ($courses as $course) {
763 blocks_add_default_course_blocks($course);
767 blocks_add_default_system_blocks();
773 * Log_display description function used during install and upgrade.
775 * @param string $component name of component (moodle, mod_assignment, etc.)
776 * @return void
778 function log_update_descriptions($component) {
779 global $DB;
781 $defpath = get_component_directory($component).'/db/log.php';
783 if (!file_exists($defpath)) {
784 $DB->delete_records('log_display', array('component'=>$component));
785 return;
788 // load new info
789 $logs = array();
790 include($defpath);
791 $newlogs = array();
792 foreach ($logs as $log) {
793 $newlogs[$log['module'].'-'.$log['action']] = $log; // kind of unique name
795 unset($logs);
796 $logs = $newlogs;
798 $fields = array('module', 'action', 'mtable', 'field');
799 // update all log fist
800 $dblogs = $DB->get_records('log_display', array('component'=>$component));
801 foreach ($dblogs as $dblog) {
802 $name = $dblog->module.'-'.$dblog->action;
804 if (empty($logs[$name])) {
805 $DB->delete_records('log_display', array('id'=>$dblog->id));
806 continue;
809 $log = $logs[$name];
810 unset($logs[$name]);
812 $update = false;
813 foreach ($fields as $field) {
814 if ($dblog->$field != $log[$field]) {
815 $dblog->$field = $log[$field];
816 $update = true;
819 if ($update) {
820 $DB->update_record('log_display', $dblog);
823 foreach ($logs as $log) {
824 $dblog = (object)$log;
825 $dblog->component = $component;
826 $DB->insert_record('log_display', $dblog);
831 * Web service discovery function used during install and upgrade.
832 * @param string $component name of component (moodle, mod_assignment, etc.)
833 * @return void
835 function external_update_descriptions($component) {
836 global $DB, $CFG;
838 $defpath = get_component_directory($component).'/db/services.php';
840 if (!file_exists($defpath)) {
841 require_once($CFG->dirroot.'/lib/externallib.php');
842 external_delete_descriptions($component);
843 return;
846 // load new info
847 $functions = array();
848 $services = array();
849 include($defpath);
851 // update all function fist
852 $dbfunctions = $DB->get_records('external_functions', array('component'=>$component));
853 foreach ($dbfunctions as $dbfunction) {
854 if (empty($functions[$dbfunction->name])) {
855 $DB->delete_records('external_functions', array('id'=>$dbfunction->id));
856 // do not delete functions from external_services_functions, beacuse
857 // we want to notify admins when functions used in custom services disappear
859 //TODO: this looks wrong, we have to delete it eventually (skodak)
860 continue;
863 $function = $functions[$dbfunction->name];
864 unset($functions[$dbfunction->name]);
865 $function['classpath'] = empty($function['classpath']) ? null : $function['classpath'];
867 $update = false;
868 if ($dbfunction->classname != $function['classname']) {
869 $dbfunction->classname = $function['classname'];
870 $update = true;
872 if ($dbfunction->methodname != $function['methodname']) {
873 $dbfunction->methodname = $function['methodname'];
874 $update = true;
876 if ($dbfunction->classpath != $function['classpath']) {
877 $dbfunction->classpath = $function['classpath'];
878 $update = true;
880 $functioncapabilities = key_exists('capabilities', $function)?$function['capabilities']:'';
881 if ($dbfunction->capabilities != $functioncapabilities) {
882 $dbfunction->capabilities = $functioncapabilities;
883 $update = true;
885 if ($update) {
886 $DB->update_record('external_functions', $dbfunction);
889 foreach ($functions as $fname => $function) {
890 $dbfunction = new stdClass();
891 $dbfunction->name = $fname;
892 $dbfunction->classname = $function['classname'];
893 $dbfunction->methodname = $function['methodname'];
894 $dbfunction->classpath = empty($function['classpath']) ? null : $function['classpath'];
895 $dbfunction->component = $component;
896 $dbfunction->capabilities = key_exists('capabilities', $function)?$function['capabilities']:'';
897 $dbfunction->id = $DB->insert_record('external_functions', $dbfunction);
899 unset($functions);
901 // now deal with services
902 $dbservices = $DB->get_records('external_services', array('component'=>$component));
903 foreach ($dbservices as $dbservice) {
904 if (empty($services[$dbservice->name])) {
905 $DB->delete_records('external_tokens', array('externalserviceid'=>$dbservice->id));
906 $DB->delete_records('external_services_functions', array('externalserviceid'=>$dbservice->id));
907 $DB->delete_records('external_services_users', array('externalserviceid'=>$dbservice->id));
908 $DB->delete_records('external_services', array('id'=>$dbservice->id));
909 continue;
911 $service = $services[$dbservice->name];
912 unset($services[$dbservice->name]);
913 $service['enabled'] = empty($service['enabled']) ? 0 : $service['enabled'];
914 $service['requiredcapability'] = empty($service['requiredcapability']) ? null : $service['requiredcapability'];
915 $service['restrictedusers'] = !isset($service['restrictedusers']) ? 1 : $service['restrictedusers'];
916 $service['downloadfiles'] = !isset($service['downloadfiles']) ? 0 : $service['downloadfiles'];
917 $service['shortname'] = !isset($service['shortname']) ? null : $service['shortname'];
919 $update = false;
920 if ($dbservice->requiredcapability != $service['requiredcapability']) {
921 $dbservice->requiredcapability = $service['requiredcapability'];
922 $update = true;
924 if ($dbservice->restrictedusers != $service['restrictedusers']) {
925 $dbservice->restrictedusers = $service['restrictedusers'];
926 $update = true;
928 if ($dbservice->downloadfiles != $service['downloadfiles']) {
929 $dbservice->downloadfiles = $service['downloadfiles'];
930 $update = true;
932 //if shortname is not a PARAM_ALPHANUMEXT, fail (tested here for service update and creation)
933 if (isset($service['shortname']) and
934 (clean_param($service['shortname'], PARAM_ALPHANUMEXT) != $service['shortname'])) {
935 throw new moodle_exception('installserviceshortnameerror', 'webservice', '', $service['shortname']);
937 if ($dbservice->shortname != $service['shortname']) {
938 //check that shortname is unique
939 if (isset($service['shortname'])) { //we currently accepts multiple shortname == null
940 $existingservice = $DB->get_record('external_services',
941 array('shortname' => $service['shortname']));
942 if (!empty($existingservice)) {
943 throw new moodle_exception('installexistingserviceshortnameerror', 'webservice', '', $service['shortname']);
946 $dbservice->shortname = $service['shortname'];
947 $update = true;
949 if ($update) {
950 $DB->update_record('external_services', $dbservice);
953 $functions = $DB->get_records('external_services_functions', array('externalserviceid'=>$dbservice->id));
954 foreach ($functions as $function) {
955 $key = array_search($function->functionname, $service['functions']);
956 if ($key === false) {
957 $DB->delete_records('external_services_functions', array('id'=>$function->id));
958 } else {
959 unset($service['functions'][$key]);
962 foreach ($service['functions'] as $fname) {
963 $newf = new stdClass();
964 $newf->externalserviceid = $dbservice->id;
965 $newf->functionname = $fname;
966 $DB->insert_record('external_services_functions', $newf);
968 unset($functions);
970 foreach ($services as $name => $service) {
971 //check that shortname is unique
972 if (isset($service['shortname'])) { //we currently accepts multiple shortname == null
973 $existingservice = $DB->get_record('external_services',
974 array('shortname' => $service['shortname']));
975 if (!empty($existingservice)) {
976 throw new moodle_exception('installserviceshortnameerror', 'webservice');
980 $dbservice = new stdClass();
981 $dbservice->name = $name;
982 $dbservice->enabled = empty($service['enabled']) ? 0 : $service['enabled'];
983 $dbservice->requiredcapability = empty($service['requiredcapability']) ? null : $service['requiredcapability'];
984 $dbservice->restrictedusers = !isset($service['restrictedusers']) ? 1 : $service['restrictedusers'];
985 $dbservice->downloadfiles = !isset($service['downloadfiles']) ? 0 : $service['downloadfiles'];
986 $dbservice->shortname = !isset($service['shortname']) ? null : $service['shortname'];
987 $dbservice->component = $component;
988 $dbservice->timecreated = time();
989 $dbservice->id = $DB->insert_record('external_services', $dbservice);
990 foreach ($service['functions'] as $fname) {
991 $newf = new stdClass();
992 $newf->externalserviceid = $dbservice->id;
993 $newf->functionname = $fname;
994 $DB->insert_record('external_services_functions', $newf);
1000 * upgrade logging functions
1002 function upgrade_handle_exception($ex, $plugin = null) {
1003 global $CFG;
1005 // rollback everything, we need to log all upgrade problems
1006 abort_all_db_transactions();
1008 $info = get_exception_info($ex);
1010 // First log upgrade error
1011 upgrade_log(UPGRADE_LOG_ERROR, $plugin, 'Exception: ' . get_class($ex), $info->message, $info->backtrace);
1013 // Always turn on debugging - admins need to know what is going on
1014 $CFG->debug = DEBUG_DEVELOPER;
1016 default_exception_handler($ex, true, $plugin);
1020 * Adds log entry into upgrade_log table
1022 * @param int $type UPGRADE_LOG_NORMAL, UPGRADE_LOG_NOTICE or UPGRADE_LOG_ERROR
1023 * @param string $plugin frankenstyle component name
1024 * @param string $info short description text of log entry
1025 * @param string $details long problem description
1026 * @param string $backtrace string used for errors only
1027 * @return void
1029 function upgrade_log($type, $plugin, $info, $details=null, $backtrace=null) {
1030 global $DB, $USER, $CFG;
1032 if (empty($plugin)) {
1033 $plugin = 'core';
1036 list($plugintype, $pluginname) = normalize_component($plugin);
1037 $component = is_null($pluginname) ? $plugintype : $plugintype . '_' . $pluginname;
1039 $backtrace = format_backtrace($backtrace, true);
1041 $currentversion = null;
1042 $targetversion = null;
1044 //first try to find out current version number
1045 if ($plugintype === 'core') {
1046 //main
1047 $currentversion = $CFG->version;
1049 $version = null;
1050 include("$CFG->dirroot/version.php");
1051 $targetversion = $version;
1053 } else if ($plugintype === 'mod') {
1054 try {
1055 $currentversion = $DB->get_field('modules', 'version', array('name'=>$pluginname));
1056 $currentversion = ($currentversion === false) ? null : $currentversion;
1057 } catch (Exception $ignored) {
1059 $cd = get_component_directory($component);
1060 if (file_exists("$cd/version.php")) {
1061 $module = new stdClass();
1062 $module->version = null;
1063 include("$cd/version.php");
1064 $targetversion = $module->version;
1067 } else if ($plugintype === 'block') {
1068 try {
1069 if ($block = $DB->get_record('block', array('name'=>$pluginname))) {
1070 $currentversion = $block->version;
1072 } catch (Exception $ignored) {
1074 $cd = get_component_directory($component);
1075 if (file_exists("$cd/version.php")) {
1076 $plugin = new stdClass();
1077 $plugin->version = null;
1078 include("$cd/version.php");
1079 $targetversion = $plugin->version;
1082 } else {
1083 $pluginversion = get_config($component, 'version');
1084 if (!empty($pluginversion)) {
1085 $currentversion = $pluginversion;
1087 $cd = get_component_directory($component);
1088 if (file_exists("$cd/version.php")) {
1089 $plugin = new stdClass();
1090 $plugin->version = null;
1091 include("$cd/version.php");
1092 $targetversion = $plugin->version;
1096 $log = new stdClass();
1097 $log->type = $type;
1098 $log->plugin = $component;
1099 $log->version = $currentversion;
1100 $log->targetversion = $targetversion;
1101 $log->info = $info;
1102 $log->details = $details;
1103 $log->backtrace = $backtrace;
1104 $log->userid = $USER->id;
1105 $log->timemodified = time();
1106 try {
1107 $DB->insert_record('upgrade_log', $log);
1108 } catch (Exception $ignored) {
1109 // possible during install or 2.0 upgrade
1114 * Marks start of upgrade, blocks any other access to site.
1115 * The upgrade is finished at the end of script or after timeout.
1117 * @global object
1118 * @global object
1119 * @global object
1121 function upgrade_started($preinstall=false) {
1122 global $CFG, $DB, $PAGE, $OUTPUT;
1124 static $started = false;
1126 if ($preinstall) {
1127 ignore_user_abort(true);
1128 upgrade_setup_debug(true);
1130 } else if ($started) {
1131 upgrade_set_timeout(120);
1133 } else {
1134 if (!CLI_SCRIPT and !$PAGE->headerprinted) {
1135 $strupgrade = get_string('upgradingversion', 'admin');
1136 $PAGE->set_pagelayout('maintenance');
1137 upgrade_init_javascript();
1138 $PAGE->set_title($strupgrade.' - Moodle '.$CFG->target_release);
1139 $PAGE->set_heading($strupgrade);
1140 $PAGE->navbar->add($strupgrade);
1141 $PAGE->set_cacheable(false);
1142 echo $OUTPUT->header();
1145 ignore_user_abort(true);
1146 register_shutdown_function('upgrade_finished_handler');
1147 upgrade_setup_debug(true);
1148 set_config('upgraderunning', time()+300);
1149 $started = true;
1154 * Internal function - executed if upgrade interrupted.
1156 function upgrade_finished_handler() {
1157 upgrade_finished();
1161 * Indicates upgrade is finished.
1163 * This function may be called repeatedly.
1165 * @global object
1166 * @global object
1168 function upgrade_finished($continueurl=null) {
1169 global $CFG, $DB, $OUTPUT;
1171 if (!empty($CFG->upgraderunning)) {
1172 unset_config('upgraderunning');
1173 upgrade_setup_debug(false);
1174 ignore_user_abort(false);
1175 if ($continueurl) {
1176 echo $OUTPUT->continue_button($continueurl);
1177 echo $OUTPUT->footer();
1178 die;
1184 * @global object
1185 * @global object
1187 function upgrade_setup_debug($starting) {
1188 global $CFG, $DB;
1190 static $originaldebug = null;
1192 if ($starting) {
1193 if ($originaldebug === null) {
1194 $originaldebug = $DB->get_debug();
1196 if (!empty($CFG->upgradeshowsql)) {
1197 $DB->set_debug(true);
1199 } else {
1200 $DB->set_debug($originaldebug);
1204 function print_upgrade_separator() {
1205 if (!CLI_SCRIPT) {
1206 echo '<hr />';
1211 * Default start upgrade callback
1212 * @param string $plugin
1213 * @param bool $installation true if installation, false means upgrade
1215 function print_upgrade_part_start($plugin, $installation, $verbose) {
1216 global $OUTPUT;
1217 if (empty($plugin) or $plugin == 'moodle') {
1218 upgrade_started($installation); // does not store upgrade running flag yet
1219 if ($verbose) {
1220 echo $OUTPUT->heading(get_string('coresystem'));
1222 } else {
1223 upgrade_started();
1224 if ($verbose) {
1225 echo $OUTPUT->heading($plugin);
1228 if ($installation) {
1229 if (empty($plugin) or $plugin == 'moodle') {
1230 // no need to log - log table not yet there ;-)
1231 } else {
1232 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Starting plugin installation');
1234 } else {
1235 if (empty($plugin) or $plugin == 'moodle') {
1236 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Starting core upgrade');
1237 } else {
1238 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Starting plugin upgrade');
1244 * Default end upgrade callback
1245 * @param string $plugin
1246 * @param bool $installation true if installation, false means upgrade
1248 function print_upgrade_part_end($plugin, $installation, $verbose) {
1249 global $OUTPUT;
1250 upgrade_started();
1251 if ($installation) {
1252 if (empty($plugin) or $plugin == 'moodle') {
1253 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Core installed');
1254 } else {
1255 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Plugin installed');
1257 } else {
1258 if (empty($plugin) or $plugin == 'moodle') {
1259 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Core upgraded');
1260 } else {
1261 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Plugin upgraded');
1264 if ($verbose) {
1265 echo $OUTPUT->notification(get_string('success'), 'notifysuccess');
1266 print_upgrade_separator();
1271 * Sets up JS code required for all upgrade scripts.
1272 * @global object
1274 function upgrade_init_javascript() {
1275 global $PAGE;
1276 // scroll to the end of each upgrade page so that ppl see either error or continue button,
1277 // no need to scroll continuously any more, it is enough to jump to end once the footer is printed ;-)
1278 $js = "window.scrollTo(0, 5000000);";
1279 $PAGE->requires->js_init_code($js);
1283 * Try to upgrade the given language pack (or current language)
1285 * @param string $lang the code of the language to update, defaults to the current language
1287 function upgrade_language_pack($lang = null) {
1288 global $CFG;
1290 if (!empty($CFG->skiplangupgrade)) {
1291 return;
1294 if (!file_exists("$CFG->dirroot/$CFG->admin/tool/langimport/lib.php")) {
1295 // weird, somebody uninstalled the import utility
1296 return;
1299 if (!$lang) {
1300 $lang = current_language();
1303 if (!get_string_manager()->translation_exists($lang)) {
1304 return;
1307 get_string_manager()->reset_caches();
1309 if ($lang === 'en') {
1310 return; // Nothing to do
1313 upgrade_started(false);
1315 require_once("$CFG->dirroot/$CFG->admin/tool/langimport/lib.php");
1316 tool_langimport_preupgrade_update($lang);
1318 get_string_manager()->reset_caches();
1320 print_upgrade_separator();
1324 * Install core moodle tables and initialize
1325 * @param float $version target version
1326 * @param bool $verbose
1327 * @return void, may throw exception
1329 function install_core($version, $verbose) {
1330 global $CFG, $DB;
1332 try {
1333 set_time_limit(600);
1334 print_upgrade_part_start('moodle', true, $verbose); // does not store upgrade running flag
1336 $DB->get_manager()->install_from_xmldb_file("$CFG->libdir/db/install.xml");
1337 upgrade_started(); // we want the flag to be stored in config table ;-)
1339 // set all core default records and default settings
1340 require_once("$CFG->libdir/db/install.php");
1341 xmldb_main_install(); // installs the capabilities too
1343 // store version
1344 upgrade_main_savepoint(true, $version, false);
1346 // Continue with the installation
1347 log_update_descriptions('moodle');
1348 external_update_descriptions('moodle');
1349 events_update_definition('moodle');
1350 message_update_providers('moodle');
1352 // Write default settings unconditionally
1353 admin_apply_default_settings(NULL, true);
1355 print_upgrade_part_end(null, true, $verbose);
1356 } catch (exception $ex) {
1357 upgrade_handle_exception($ex);
1362 * Upgrade moodle core
1363 * @param float $version target version
1364 * @param bool $verbose
1365 * @return void, may throw exception
1367 function upgrade_core($version, $verbose) {
1368 global $CFG;
1370 raise_memory_limit(MEMORY_EXTRA);
1372 require_once($CFG->libdir.'/db/upgrade.php'); // Defines upgrades
1374 try {
1375 // Reset caches before any output
1376 purge_all_caches();
1378 // Upgrade current language pack if we can
1379 upgrade_language_pack();
1381 print_upgrade_part_start('moodle', false, $verbose);
1383 // one time special local migration pre 2.0 upgrade script
1384 if ($CFG->version < 2007101600) {
1385 $pre20upgradefile = "$CFG->dirroot/local/upgrade_pre20.php";
1386 if (file_exists($pre20upgradefile)) {
1387 set_time_limit(0);
1388 require($pre20upgradefile);
1389 // reset upgrade timeout to default
1390 upgrade_set_timeout();
1394 $result = xmldb_main_upgrade($CFG->version);
1395 if ($version > $CFG->version) {
1396 // store version if not already there
1397 upgrade_main_savepoint($result, $version, false);
1400 // perform all other component upgrade routines
1401 update_capabilities('moodle');
1402 log_update_descriptions('moodle');
1403 external_update_descriptions('moodle');
1404 events_update_definition('moodle');
1405 message_update_providers('moodle');
1407 // Reset caches again, just to be sure
1408 purge_all_caches();
1410 // Clean up contexts - more and more stuff depends on existence of paths and contexts
1411 context_helper::cleanup_instances();
1412 context_helper::create_instances(null, false);
1413 context_helper::build_all_paths(false);
1414 $syscontext = context_system::instance();
1415 $syscontext->mark_dirty();
1417 print_upgrade_part_end('moodle', false, $verbose);
1418 } catch (Exception $ex) {
1419 upgrade_handle_exception($ex);
1424 * Upgrade/install other parts of moodle
1425 * @param bool $verbose
1426 * @return void, may throw exception
1428 function upgrade_noncore($verbose) {
1429 global $CFG;
1431 raise_memory_limit(MEMORY_EXTRA);
1433 // upgrade all plugins types
1434 try {
1435 $plugintypes = get_plugin_types();
1436 foreach ($plugintypes as $type=>$location) {
1437 upgrade_plugins($type, 'print_upgrade_part_start', 'print_upgrade_part_end', $verbose);
1439 } catch (Exception $ex) {
1440 upgrade_handle_exception($ex);
1445 * Checks if the main tables have been installed yet or not.
1446 * @return bool
1448 function core_tables_exist() {
1449 global $DB;
1451 if (!$tables = $DB->get_tables() ) { // No tables yet at all.
1452 return false;
1454 } else { // Check for missing main tables
1455 $mtables = array('config', 'course', 'groupings'); // some tables used in 1.9 and 2.0, preferable something from the start and end of install.xml
1456 foreach ($mtables as $mtable) {
1457 if (!in_array($mtable, $tables)) {
1458 return false;
1461 return true;
1466 * upgrades the mnet rpc definitions for the given component.
1467 * this method doesn't return status, an exception will be thrown in the case of an error
1469 * @param string $component the plugin to upgrade, eg auth_mnet
1471 function upgrade_plugin_mnet_functions($component) {
1472 global $DB, $CFG;
1474 list($type, $plugin) = explode('_', $component);
1475 $path = get_plugin_directory($type, $plugin);
1477 $publishes = array();
1478 $subscribes = array();
1479 if (file_exists($path . '/db/mnet.php')) {
1480 require_once($path . '/db/mnet.php'); // $publishes comes from this file
1482 if (empty($publishes)) {
1483 $publishes = array(); // still need this to be able to disable stuff later
1485 if (empty($subscribes)) {
1486 $subscribes = array(); // still need this to be able to disable stuff later
1489 static $servicecache = array();
1491 // rekey an array based on the rpc method for easy lookups later
1492 $publishmethodservices = array();
1493 $subscribemethodservices = array();
1494 foreach($publishes as $servicename => $service) {
1495 if (is_array($service['methods'])) {
1496 foreach($service['methods'] as $methodname) {
1497 $service['servicename'] = $servicename;
1498 $publishmethodservices[$methodname][] = $service;
1503 // Disable functions that don't exist (any more) in the source
1504 // Should these be deleted? What about their permissions records?
1505 foreach ($DB->get_records('mnet_rpc', array('pluginname'=>$plugin, 'plugintype'=>$type), 'functionname ASC ') as $rpc) {
1506 if (!array_key_exists($rpc->functionname, $publishmethodservices) && $rpc->enabled) {
1507 $DB->set_field('mnet_rpc', 'enabled', 0, array('id' => $rpc->id));
1508 } else if (array_key_exists($rpc->functionname, $publishmethodservices) && !$rpc->enabled) {
1509 $DB->set_field('mnet_rpc', 'enabled', 1, array('id' => $rpc->id));
1513 // reflect all the services we're publishing and save them
1514 require_once($CFG->dirroot . '/lib/zend/Zend/Server/Reflection.php');
1515 static $cachedclasses = array(); // to store reflection information in
1516 foreach ($publishes as $service => $data) {
1517 $f = $data['filename'];
1518 $c = $data['classname'];
1519 foreach ($data['methods'] as $method) {
1520 $dataobject = new stdClass();
1521 $dataobject->plugintype = $type;
1522 $dataobject->pluginname = $plugin;
1523 $dataobject->enabled = 1;
1524 $dataobject->classname = $c;
1525 $dataobject->filename = $f;
1527 if (is_string($method)) {
1528 $dataobject->functionname = $method;
1530 } else if (is_array($method)) { // wants to override file or class
1531 $dataobject->functionname = $method['method'];
1532 $dataobject->classname = $method['classname'];
1533 $dataobject->filename = $method['filename'];
1535 $dataobject->xmlrpcpath = $type.'/'.$plugin.'/'.$dataobject->filename.'/'.$method;
1536 $dataobject->static = false;
1538 require_once($path . '/' . $dataobject->filename);
1539 $functionreflect = null; // slightly different ways to get this depending on whether it's a class method or a function
1540 if (!empty($dataobject->classname)) {
1541 if (!class_exists($dataobject->classname)) {
1542 throw new moodle_exception('installnosuchmethod', 'mnet', '', (object)array('method' => $dataobject->functionname, 'class' => $dataobject->classname));
1544 $key = $dataobject->filename . '|' . $dataobject->classname;
1545 if (!array_key_exists($key, $cachedclasses)) { // look to see if we've already got a reflection object
1546 try {
1547 $cachedclasses[$key] = Zend_Server_Reflection::reflectClass($dataobject->classname);
1548 } catch (Zend_Server_Reflection_Exception $e) { // catch these and rethrow them to something more helpful
1549 throw new moodle_exception('installreflectionclasserror', 'mnet', '', (object)array('method' => $dataobject->functionname, 'class' => $dataobject->classname, 'error' => $e->getMessage()));
1552 $r =& $cachedclasses[$key];
1553 if (!$r->hasMethod($dataobject->functionname)) {
1554 throw new moodle_exception('installnosuchmethod', 'mnet', '', (object)array('method' => $dataobject->functionname, 'class' => $dataobject->classname));
1556 // stupid workaround for zend not having a getMethod($name) function
1557 $ms = $r->getMethods();
1558 foreach ($ms as $m) {
1559 if ($m->getName() == $dataobject->functionname) {
1560 $functionreflect = $m;
1561 break;
1564 $dataobject->static = (int)$functionreflect->isStatic();
1565 } else {
1566 if (!function_exists($dataobject->functionname)) {
1567 throw new moodle_exception('installnosuchfunction', 'mnet', '', (object)array('method' => $dataobject->functionname, 'file' => $dataobject->filename));
1569 try {
1570 $functionreflect = Zend_Server_Reflection::reflectFunction($dataobject->functionname);
1571 } catch (Zend_Server_Reflection_Exception $e) { // catch these and rethrow them to something more helpful
1572 throw new moodle_exception('installreflectionfunctionerror', 'mnet', '', (object)array('method' => $dataobject->functionname, '' => $dataobject->filename, 'error' => $e->getMessage()));
1575 $dataobject->profile = serialize(admin_mnet_method_profile($functionreflect));
1576 $dataobject->help = $functionreflect->getDescription();
1578 if ($record_exists = $DB->get_record('mnet_rpc', array('xmlrpcpath'=>$dataobject->xmlrpcpath))) {
1579 $dataobject->id = $record_exists->id;
1580 $dataobject->enabled = $record_exists->enabled;
1581 $DB->update_record('mnet_rpc', $dataobject);
1582 } else {
1583 $dataobject->id = $DB->insert_record('mnet_rpc', $dataobject, true);
1586 // TODO this API versioning must be reworked, here the recently processed method
1587 // sets the service API which may not be correct
1588 foreach ($publishmethodservices[$dataobject->functionname] as $service) {
1589 if ($serviceobj = $DB->get_record('mnet_service', array('name'=>$service['servicename']))) {
1590 $serviceobj->apiversion = $service['apiversion'];
1591 $DB->update_record('mnet_service', $serviceobj);
1592 } else {
1593 $serviceobj = new stdClass();
1594 $serviceobj->name = $service['servicename'];
1595 $serviceobj->description = empty($service['description']) ? '' : $service['description'];
1596 $serviceobj->apiversion = $service['apiversion'];
1597 $serviceobj->offer = 1;
1598 $serviceobj->id = $DB->insert_record('mnet_service', $serviceobj);
1600 $servicecache[$service['servicename']] = $serviceobj;
1601 if (!$DB->record_exists('mnet_service2rpc', array('rpcid'=>$dataobject->id, 'serviceid'=>$serviceobj->id))) {
1602 $obj = new stdClass();
1603 $obj->rpcid = $dataobject->id;
1604 $obj->serviceid = $serviceobj->id;
1605 $DB->insert_record('mnet_service2rpc', $obj, true);
1610 // finished with methods we publish, now do subscribable methods
1611 foreach($subscribes as $service => $methods) {
1612 if (!array_key_exists($service, $servicecache)) {
1613 if (!$serviceobj = $DB->get_record('mnet_service', array('name' => $service))) {
1614 debugging("TODO: skipping unknown service $service - somebody needs to fix MDL-21993");
1615 continue;
1617 $servicecache[$service] = $serviceobj;
1618 } else {
1619 $serviceobj = $servicecache[$service];
1621 foreach ($methods as $method => $xmlrpcpath) {
1622 if (!$rpcid = $DB->get_field('mnet_remote_rpc', 'id', array('xmlrpcpath'=>$xmlrpcpath))) {
1623 $remoterpc = (object)array(
1624 'functionname' => $method,
1625 'xmlrpcpath' => $xmlrpcpath,
1626 'plugintype' => $type,
1627 'pluginname' => $plugin,
1628 'enabled' => 1,
1630 $rpcid = $remoterpc->id = $DB->insert_record('mnet_remote_rpc', $remoterpc, true);
1632 if (!$DB->record_exists('mnet_remote_service2rpc', array('rpcid'=>$rpcid, 'serviceid'=>$serviceobj->id))) {
1633 $obj = new stdClass();
1634 $obj->rpcid = $rpcid;
1635 $obj->serviceid = $serviceobj->id;
1636 $DB->insert_record('mnet_remote_service2rpc', $obj, true);
1638 $subscribemethodservices[$method][] = $service;
1642 foreach ($DB->get_records('mnet_remote_rpc', array('pluginname'=>$plugin, 'plugintype'=>$type), 'functionname ASC ') as $rpc) {
1643 if (!array_key_exists($rpc->functionname, $subscribemethodservices) && $rpc->enabled) {
1644 $DB->set_field('mnet_remote_rpc', 'enabled', 0, array('id' => $rpc->id));
1645 } else if (array_key_exists($rpc->functionname, $subscribemethodservices) && !$rpc->enabled) {
1646 $DB->set_field('mnet_remote_rpc', 'enabled', 1, array('id' => $rpc->id));
1650 return true;
1654 * Given some sort of Zend Reflection function/method object, return a profile array, ready to be serialized and stored
1656 * @param Zend_Server_Reflection_Function_Abstract $function can be any subclass of this object type
1658 * @return array
1660 function admin_mnet_method_profile(Zend_Server_Reflection_Function_Abstract $function) {
1661 $proto = array_pop($function->getPrototypes());
1662 $ret = $proto->getReturnValue();
1663 $profile = array(
1664 'parameters' => array(),
1665 'return' => array(
1666 'type' => $ret->getType(),
1667 'description' => $ret->getDescription(),
1670 foreach ($proto->getParameters() as $p) {
1671 $profile['parameters'][] = array(
1672 'name' => $p->getName(),
1673 'type' => $p->getType(),
1674 'description' => $p->getDescription(),
1677 return $profile;