Merge branch 'wip-MDL-25454-master' of git://github.com/marinaglancy/moodle
[moodle.git] / lib / upgradelib.php
blob8ea6abd93ba3a1bf96341ca87d2bcba075889250
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 = clean_param($type.'_'.$plug, PARAM_COMPONENT); // standardised plugin name
281 // check plugin dir is valid name
282 if (empty($component)) {
283 throw new plugin_defective_exception($type.'_'.$plug, 'Invalid plugin directory name.');
286 if (!is_readable($fullplug.'/version.php')) {
287 continue;
290 $plugin = new stdClass();
291 require($fullplug.'/version.php'); // defines $plugin with version etc
293 // if plugin tells us it's full name we may check the location
294 if (isset($plugin->component)) {
295 if ($plugin->component !== $component) {
296 throw new plugin_defective_exception($component, 'Plugin installed in wrong folder.');
300 if (empty($plugin->version)) {
301 throw new plugin_defective_exception($component, 'Missing version value in version.php');
304 $plugin->name = $plug;
305 $plugin->fullname = $component;
308 if (!empty($plugin->requires)) {
309 if ($plugin->requires > $CFG->version) {
310 throw new upgrade_requires_exception($component, $plugin->version, $CFG->version, $plugin->requires);
311 } else if ($plugin->requires < 2010000000) {
312 throw new plugin_defective_exception($component, 'Plugin is not compatible with Moodle 2.x or later.');
316 // try to recover from interrupted install.php if needed
317 if (file_exists($fullplug.'/db/install.php')) {
318 if (get_config($plugin->fullname, 'installrunning')) {
319 require_once($fullplug.'/db/install.php');
320 $recover_install_function = 'xmldb_'.$plugin->fullname.'_install_recovery';
321 if (function_exists($recover_install_function)) {
322 $startcallback($component, true, $verbose);
323 $recover_install_function();
324 unset_config('installrunning', $plugin->fullname);
325 update_capabilities($component);
326 log_update_descriptions($component);
327 external_update_descriptions($component);
328 events_update_definition($component);
329 message_update_providers($component);
330 if ($type === 'message') {
331 message_update_processors($plug);
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 if ($type === 'message') {
367 message_update_processors($plug);
369 upgrade_plugin_mnet_functions($component);
371 purge_all_caches();
372 $endcallback($component, true, $verbose);
374 } else if ($installedversion < $plugin->version) { // upgrade
375 /// Run the upgrade function for the plugin.
376 $startcallback($component, false, $verbose);
378 if (is_readable($fullplug.'/db/upgrade.php')) {
379 require_once($fullplug.'/db/upgrade.php'); // defines upgrading function
381 $newupgrade_function = 'xmldb_'.$plugin->fullname.'_upgrade';
382 $result = $newupgrade_function($installedversion);
383 } else {
384 $result = true;
387 $installedversion = get_config($plugin->fullname, 'version');
388 if ($installedversion < $plugin->version) {
389 // store version if not already there
390 upgrade_plugin_savepoint($result, $plugin->version, $type, $plug, false);
393 /// Upgrade various components
394 update_capabilities($component);
395 log_update_descriptions($component);
396 external_update_descriptions($component);
397 events_update_definition($component);
398 message_update_providers($component);
399 if ($type === 'message') {
400 message_update_processors($plug);
402 upgrade_plugin_mnet_functions($component);
404 purge_all_caches();
405 $endcallback($component, false, $verbose);
407 } else if ($installedversion > $plugin->version) {
408 throw new downgrade_exception($component, $installedversion, $plugin->version);
414 * Find and check all modules and load them up or upgrade them if necessary
416 * @global object
417 * @global object
419 function upgrade_plugins_modules($startcallback, $endcallback, $verbose) {
420 global $CFG, $DB;
422 $mods = get_plugin_list('mod');
424 foreach ($mods as $mod=>$fullmod) {
426 if ($mod === 'NEWMODULE') { // Someone has unzipped the template, ignore it
427 continue;
430 $component = clean_param('mod_'.$mod, PARAM_COMPONENT);
432 // check module dir is valid name
433 if (empty($component)) {
434 throw new plugin_defective_exception('mod_'.$mod, 'Invalid plugin directory name.');
437 if (!is_readable($fullmod.'/version.php')) {
438 throw new plugin_defective_exception($component, 'Missing version.php');
441 $module = new stdClass();
442 require($fullmod .'/version.php'); // defines $module with version etc
444 // if plugin tells us it's full name we may check the location
445 if (isset($module->component)) {
446 if ($module->component !== $component) {
447 throw new plugin_defective_exception($component, 'Plugin installed in wrong folder.');
451 if (empty($module->version)) {
452 if (isset($module->version)) {
453 // Version is empty but is set - it means its value is 0 or ''. Let us skip such module.
454 // This is intended for developers so they can work on the early stages of the module.
455 continue;
457 throw new plugin_defective_exception($component, 'Missing version value in version.php');
460 if (!empty($module->requires)) {
461 if ($module->requires > $CFG->version) {
462 throw new upgrade_requires_exception($component, $module->version, $CFG->version, $module->requires);
463 } else if ($module->requires < 2010000000) {
464 throw new plugin_defective_exception($component, 'Plugin is not compatible with Moodle 2.x or later.');
468 // all modules must have en lang pack
469 if (!is_readable("$fullmod/lang/en/$mod.php")) {
470 throw new plugin_defective_exception($component, 'Missing mandatory en language pack.');
473 $module->name = $mod; // The name MUST match the directory
475 $currmodule = $DB->get_record('modules', array('name'=>$module->name));
477 if (file_exists($fullmod.'/db/install.php')) {
478 if (get_config($module->name, 'installrunning')) {
479 require_once($fullmod.'/db/install.php');
480 $recover_install_function = 'xmldb_'.$module->name.'_install_recovery';
481 if (function_exists($recover_install_function)) {
482 $startcallback($component, true, $verbose);
483 $recover_install_function();
484 unset_config('installrunning', $module->name);
485 // Install various components too
486 update_capabilities($component);
487 log_update_descriptions($component);
488 external_update_descriptions($component);
489 events_update_definition($component);
490 message_update_providers($component);
491 upgrade_plugin_mnet_functions($component);
492 $endcallback($component, true, $verbose);
497 if (empty($currmodule->version)) {
498 $startcallback($component, true, $verbose);
500 /// Execute install.xml (XMLDB) - must be present in all modules
501 $DB->get_manager()->install_from_xmldb_file($fullmod.'/db/install.xml');
503 /// Add record into modules table - may be needed in install.php already
504 $module->id = $DB->insert_record('modules', $module);
506 /// Post installation hook - optional
507 if (file_exists("$fullmod/db/install.php")) {
508 require_once("$fullmod/db/install.php");
509 // Set installation running flag, we need to recover after exception or error
510 set_config('installrunning', 1, $module->name);
511 $post_install_function = 'xmldb_'.$module->name.'_install';;
512 $post_install_function();
513 unset_config('installrunning', $module->name);
516 /// Install various components
517 update_capabilities($component);
518 log_update_descriptions($component);
519 external_update_descriptions($component);
520 events_update_definition($component);
521 message_update_providers($component);
522 upgrade_plugin_mnet_functions($component);
524 purge_all_caches();
525 $endcallback($component, true, $verbose);
527 } else if ($currmodule->version < $module->version) {
528 /// If versions say that we need to upgrade but no upgrade files are available, notify and continue
529 $startcallback($component, false, $verbose);
531 if (is_readable($fullmod.'/db/upgrade.php')) {
532 require_once($fullmod.'/db/upgrade.php'); // defines new upgrading function
533 $newupgrade_function = 'xmldb_'.$module->name.'_upgrade';
534 $result = $newupgrade_function($currmodule->version, $module);
535 } else {
536 $result = true;
539 $currmodule = $DB->get_record('modules', array('name'=>$module->name));
540 if ($currmodule->version < $module->version) {
541 // store version if not already there
542 upgrade_mod_savepoint($result, $module->version, $mod, false);
545 /// Upgrade various components
546 update_capabilities($component);
547 log_update_descriptions($component);
548 external_update_descriptions($component);
549 events_update_definition($component);
550 message_update_providers($component);
551 upgrade_plugin_mnet_functions($component);
553 purge_all_caches();
555 $endcallback($component, false, $verbose);
557 } else if ($currmodule->version > $module->version) {
558 throw new downgrade_exception($component, $currmodule->version, $module->version);
565 * This function finds all available blocks and install them
566 * into blocks table or do all the upgrade process if newer.
568 * @global object
569 * @global object
571 function upgrade_plugins_blocks($startcallback, $endcallback, $verbose) {
572 global $CFG, $DB;
574 require_once($CFG->dirroot.'/blocks/moodleblock.class.php');
576 $blocktitles = array(); // we do not want duplicate titles
578 //Is this a first install
579 $first_install = null;
581 $blocks = get_plugin_list('block');
583 foreach ($blocks as $blockname=>$fullblock) {
585 if (is_null($first_install)) {
586 $first_install = ($DB->count_records('block_instances') == 0);
589 if ($blockname === 'NEWBLOCK') { // Someone has unzipped the template, ignore it
590 continue;
593 $component = clean_param('block_'.$blockname, PARAM_COMPONENT);
595 // check block dir is valid name
596 if (empty($component)) {
597 throw new plugin_defective_exception('block_'.$blockname, 'Invalid plugin directory name.');
600 if (!is_readable($fullblock.'/version.php')) {
601 throw new plugin_defective_exception('block/'.$blockname, 'Missing version.php file.');
603 $plugin = new stdClass();
604 $plugin->version = NULL;
605 $plugin->cron = 0;
606 include($fullblock.'/version.php');
607 $block = $plugin;
609 // if plugin tells us it's full name we may check the location
610 if (isset($block->component)) {
611 if ($block->component !== $component) {
612 throw new plugin_defective_exception($component, 'Plugin installed in wrong folder.');
616 if (!empty($plugin->requires)) {
617 if ($plugin->requires > $CFG->version) {
618 throw new upgrade_requires_exception($component, $plugin->version, $CFG->version, $plugin->requires);
619 } else if ($plugin->requires < 2010000000) {
620 throw new plugin_defective_exception($component, 'Plugin is not compatible with Moodle 2.x or later.');
624 if (!is_readable($fullblock.'/block_'.$blockname.'.php')) {
625 throw new plugin_defective_exception('block/'.$blockname, 'Missing main block class file.');
627 include_once($fullblock.'/block_'.$blockname.'.php');
629 $classname = 'block_'.$blockname;
631 if (!class_exists($classname)) {
632 throw new plugin_defective_exception($component, 'Can not load main class.');
635 $blockobj = new $classname; // This is what we'll be testing
636 $blocktitle = $blockobj->get_title();
638 // OK, it's as we all hoped. For further tests, the object will do them itself.
639 if (!$blockobj->_self_test()) {
640 throw new plugin_defective_exception($component, 'Self test failed.');
643 $block->name = $blockname; // The name MUST match the directory
645 if (empty($block->version)) {
646 throw new plugin_defective_exception($component, 'Missing block version.');
649 $currblock = $DB->get_record('block', array('name'=>$block->name));
651 if (file_exists($fullblock.'/db/install.php')) {
652 if (get_config('block_'.$blockname, 'installrunning')) {
653 require_once($fullblock.'/db/install.php');
654 $recover_install_function = 'xmldb_block_'.$blockname.'_install_recovery';
655 if (function_exists($recover_install_function)) {
656 $startcallback($component, true, $verbose);
657 $recover_install_function();
658 unset_config('installrunning', 'block_'.$blockname);
659 // Install various components
660 update_capabilities($component);
661 log_update_descriptions($component);
662 external_update_descriptions($component);
663 events_update_definition($component);
664 message_update_providers($component);
665 upgrade_plugin_mnet_functions($component);
666 $endcallback($component, true, $verbose);
671 if (empty($currblock->version)) { // block not installed yet, so install it
672 $conflictblock = array_search($blocktitle, $blocktitles);
673 if ($conflictblock !== false) {
674 // Duplicate block titles are not allowed, they confuse people
675 // AND PHP's associative arrays ;)
676 throw new plugin_defective_exception($component, get_string('blocknameconflict', 'error', (object)array('name'=>$block->name, 'conflict'=>$conflictblock)));
678 $startcallback($component, true, $verbose);
680 if (file_exists($fullblock.'/db/install.xml')) {
681 $DB->get_manager()->install_from_xmldb_file($fullblock.'/db/install.xml');
683 $block->id = $DB->insert_record('block', $block);
685 if (file_exists($fullblock.'/db/install.php')) {
686 require_once($fullblock.'/db/install.php');
687 // Set installation running flag, we need to recover after exception or error
688 set_config('installrunning', 1, 'block_'.$blockname);
689 $post_install_function = 'xmldb_block_'.$blockname.'_install';;
690 $post_install_function();
691 unset_config('installrunning', 'block_'.$blockname);
694 $blocktitles[$block->name] = $blocktitle;
696 // Install various components
697 update_capabilities($component);
698 log_update_descriptions($component);
699 external_update_descriptions($component);
700 events_update_definition($component);
701 message_update_providers($component);
702 upgrade_plugin_mnet_functions($component);
704 purge_all_caches();
705 $endcallback($component, true, $verbose);
707 } else if ($currblock->version < $block->version) {
708 $startcallback($component, false, $verbose);
710 if (is_readable($fullblock.'/db/upgrade.php')) {
711 require_once($fullblock.'/db/upgrade.php'); // defines new upgrading function
712 $newupgrade_function = 'xmldb_block_'.$blockname.'_upgrade';
713 $result = $newupgrade_function($currblock->version, $block);
714 } else {
715 $result = true;
718 $currblock = $DB->get_record('block', array('name'=>$block->name));
719 if ($currblock->version < $block->version) {
720 // store version if not already there
721 upgrade_block_savepoint($result, $block->version, $block->name, false);
724 if ($currblock->cron != $block->cron) {
725 // update cron flag if needed
726 $currblock->cron = $block->cron;
727 $DB->update_record('block', $currblock);
730 // Upgrade various components
731 update_capabilities($component);
732 log_update_descriptions($component);
733 external_update_descriptions($component);
734 events_update_definition($component);
735 message_update_providers($component);
736 upgrade_plugin_mnet_functions($component);
738 purge_all_caches();
739 $endcallback($component, false, $verbose);
741 } else if ($currblock->version > $block->version) {
742 throw new downgrade_exception($component, $currblock->version, $block->version);
747 // Finally, if we are in the first_install of BLOCKS setup frontpage and admin page blocks
748 if ($first_install) {
749 //Iterate over each course - there should be only site course here now
750 if ($courses = $DB->get_records('course')) {
751 foreach ($courses as $course) {
752 blocks_add_default_course_blocks($course);
756 blocks_add_default_system_blocks();
762 * Log_display description function used during install and upgrade.
764 * @param string $component name of component (moodle, mod_assignment, etc.)
765 * @return void
767 function log_update_descriptions($component) {
768 global $DB;
770 $defpath = get_component_directory($component).'/db/log.php';
772 if (!file_exists($defpath)) {
773 $DB->delete_records('log_display', array('component'=>$component));
774 return;
777 // load new info
778 $logs = array();
779 include($defpath);
780 $newlogs = array();
781 foreach ($logs as $log) {
782 $newlogs[$log['module'].'-'.$log['action']] = $log; // kind of unique name
784 unset($logs);
785 $logs = $newlogs;
787 $fields = array('module', 'action', 'mtable', 'field');
788 // update all log fist
789 $dblogs = $DB->get_records('log_display', array('component'=>$component));
790 foreach ($dblogs as $dblog) {
791 $name = $dblog->module.'-'.$dblog->action;
793 if (empty($logs[$name])) {
794 $DB->delete_records('log_display', array('id'=>$dblog->id));
795 continue;
798 $log = $logs[$name];
799 unset($logs[$name]);
801 $update = false;
802 foreach ($fields as $field) {
803 if ($dblog->$field != $log[$field]) {
804 $dblog->$field = $log[$field];
805 $update = true;
808 if ($update) {
809 $DB->update_record('log_display', $dblog);
812 foreach ($logs as $log) {
813 $dblog = (object)$log;
814 $dblog->component = $component;
815 $DB->insert_record('log_display', $dblog);
820 * Web service discovery function used during install and upgrade.
821 * @param string $component name of component (moodle, mod_assignment, etc.)
822 * @return void
824 function external_update_descriptions($component) {
825 global $DB;
827 $defpath = get_component_directory($component).'/db/services.php';
829 if (!file_exists($defpath)) {
830 external_delete_descriptions($component);
831 return;
834 // load new info
835 $functions = array();
836 $services = array();
837 include($defpath);
839 // update all function fist
840 $dbfunctions = $DB->get_records('external_functions', array('component'=>$component));
841 foreach ($dbfunctions as $dbfunction) {
842 if (empty($functions[$dbfunction->name])) {
843 $DB->delete_records('external_functions', array('id'=>$dbfunction->id));
844 // do not delete functions from external_services_functions, beacuse
845 // we want to notify admins when functions used in custom services disappear
847 //TODO: this looks wrong, we have to delete it eventually (skodak)
848 continue;
851 $function = $functions[$dbfunction->name];
852 unset($functions[$dbfunction->name]);
853 $function['classpath'] = empty($function['classpath']) ? null : $function['classpath'];
855 $update = false;
856 if ($dbfunction->classname != $function['classname']) {
857 $dbfunction->classname = $function['classname'];
858 $update = true;
860 if ($dbfunction->methodname != $function['methodname']) {
861 $dbfunction->methodname = $function['methodname'];
862 $update = true;
864 if ($dbfunction->classpath != $function['classpath']) {
865 $dbfunction->classpath = $function['classpath'];
866 $update = true;
868 $functioncapabilities = key_exists('capabilities', $function)?$function['capabilities']:'';
869 if ($dbfunction->capabilities != $functioncapabilities) {
870 $dbfunction->capabilities = $functioncapabilities;
871 $update = true;
873 if ($update) {
874 $DB->update_record('external_functions', $dbfunction);
877 foreach ($functions as $fname => $function) {
878 $dbfunction = new stdClass();
879 $dbfunction->name = $fname;
880 $dbfunction->classname = $function['classname'];
881 $dbfunction->methodname = $function['methodname'];
882 $dbfunction->classpath = empty($function['classpath']) ? null : $function['classpath'];
883 $dbfunction->component = $component;
884 $dbfunction->capabilities = key_exists('capabilities', $function)?$function['capabilities']:'';
885 $dbfunction->id = $DB->insert_record('external_functions', $dbfunction);
887 unset($functions);
889 // now deal with services
890 $dbservices = $DB->get_records('external_services', array('component'=>$component));
891 foreach ($dbservices as $dbservice) {
892 if (empty($services[$dbservice->name])) {
893 $DB->delete_records('external_services_functions', array('externalserviceid'=>$dbservice->id));
894 $DB->delete_records('external_services_users', array('externalserviceid'=>$dbservice->id));
895 $DB->delete_records('external_services', array('id'=>$dbservice->id));
896 continue;
898 $service = $services[$dbservice->name];
899 unset($services[$dbservice->name]);
900 $service['enabled'] = empty($service['enabled']) ? 0 : $service['enabled'];
901 $service['requiredcapability'] = empty($service['requiredcapability']) ? null : $service['requiredcapability'];
902 $service['restrictedusers'] = !isset($service['restrictedusers']) ? 1 : $service['restrictedusers'];
903 $service['shortname'] = !isset($service['shortname']) ? null : $service['shortname'];
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 shortname is not a PARAM_ALPHANUMEXT, fail (tested here for service update and creation)
915 if (isset($service['shortname']) and
916 (clean_param($service['shortname'], PARAM_ALPHANUMEXT) != $service['shortname'])) {
917 throw new moodle_exception('installserviceshortnameerror', 'webservice', '', $service['shortname']);
919 if ($dbservice->shortname != $service['shortname']) {
920 //check that shortname is unique
921 if (isset($service['shortname'])) { //we currently accepts multiple shortname == null
922 $existingservice = $DB->get_record('external_services',
923 array('shortname' => $service['shortname']));
924 if (!empty($existingservice)) {
925 throw new moodle_exception('installexistingserviceshortnameerror', 'webservice', '', $service['shortname']);
928 $dbservice->shortname = $service['shortname'];
929 $update = true;
931 if ($update) {
932 $DB->update_record('external_services', $dbservice);
935 $functions = $DB->get_records('external_services_functions', array('externalserviceid'=>$dbservice->id));
936 foreach ($functions as $function) {
937 $key = array_search($function->functionname, $service['functions']);
938 if ($key === false) {
939 $DB->delete_records('external_services_functions', array('id'=>$function->id));
940 } else {
941 unset($service['functions'][$key]);
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);
950 unset($functions);
952 foreach ($services as $name => $service) {
953 //check that shortname is unique
954 if (isset($service['shortname'])) { //we currently accepts multiple shortname == null
955 $existingservice = $DB->get_record('external_services',
956 array('shortname' => $service['shortname']));
957 if (!empty($existingservice)) {
958 throw new moodle_exception('installserviceshortnameerror', 'webservice');
962 $dbservice = new stdClass();
963 $dbservice->name = $name;
964 $dbservice->enabled = empty($service['enabled']) ? 0 : $service['enabled'];
965 $dbservice->requiredcapability = empty($service['requiredcapability']) ? null : $service['requiredcapability'];
966 $dbservice->restrictedusers = !isset($service['restrictedusers']) ? 1 : $service['restrictedusers'];
967 $dbservice->shortname = !isset($service['shortname']) ? null : $service['shortname'];
968 $dbservice->component = $component;
969 $dbservice->timecreated = time();
970 $dbservice->id = $DB->insert_record('external_services', $dbservice);
971 foreach ($service['functions'] as $fname) {
972 $newf = new stdClass();
973 $newf->externalserviceid = $dbservice->id;
974 $newf->functionname = $fname;
975 $DB->insert_record('external_services_functions', $newf);
981 * Delete all service and external functions information defined in the specified component.
982 * @param string $component name of component (moodle, mod_assignment, etc.)
983 * @return void
985 function external_delete_descriptions($component) {
986 global $DB;
988 $params = array($component);
990 $DB->delete_records_select('external_services_users', "externalserviceid IN (SELECT id FROM {external_services} WHERE component = ?)", $params);
991 $DB->delete_records_select('external_services_functions', "externalserviceid IN (SELECT id FROM {external_services} WHERE component = ?)", $params);
992 $DB->delete_records('external_services', array('component'=>$component));
993 $DB->delete_records('external_functions', array('component'=>$component));
997 * upgrade logging functions
999 function upgrade_handle_exception($ex, $plugin = null) {
1000 global $CFG;
1002 // rollback everything, we need to log all upgrade problems
1003 abort_all_db_transactions();
1005 $info = get_exception_info($ex);
1007 // First log upgrade error
1008 upgrade_log(UPGRADE_LOG_ERROR, $plugin, 'Exception: ' . get_class($ex), $info->message, $info->backtrace);
1010 // Always turn on debugging - admins need to know what is going on
1011 $CFG->debug = DEBUG_DEVELOPER;
1013 default_exception_handler($ex, true, $plugin);
1017 * Adds log entry into upgrade_log table
1019 * @param int $type UPGRADE_LOG_NORMAL, UPGRADE_LOG_NOTICE or UPGRADE_LOG_ERROR
1020 * @param string $plugin frankenstyle component name
1021 * @param string $info short description text of log entry
1022 * @param string $details long problem description
1023 * @param string $backtrace string used for errors only
1024 * @return void
1026 function upgrade_log($type, $plugin, $info, $details=null, $backtrace=null) {
1027 global $DB, $USER, $CFG;
1029 if (empty($plugin)) {
1030 $plugin = 'core';
1033 list($plugintype, $pluginname) = normalize_component($plugin);
1034 $component = is_null($pluginname) ? $plugintype : $plugintype . '_' . $pluginname;
1036 $backtrace = format_backtrace($backtrace, true);
1038 $currentversion = null;
1039 $targetversion = null;
1041 //first try to find out current version number
1042 if ($plugintype === 'core') {
1043 //main
1044 $currentversion = $CFG->version;
1046 $version = null;
1047 include("$CFG->dirroot/version.php");
1048 $targetversion = $version;
1050 } else if ($plugintype === 'mod') {
1051 try {
1052 $currentversion = $DB->get_field('modules', 'version', array('name'=>$pluginname));
1053 $currentversion = ($currentversion === false) ? null : $currentversion;
1054 } catch (Exception $ignored) {
1056 $cd = get_component_directory($component);
1057 if (file_exists("$cd/version.php")) {
1058 $module = new stdClass();
1059 $module->version = null;
1060 include("$cd/version.php");
1061 $targetversion = $module->version;
1064 } else if ($plugintype === 'block') {
1065 try {
1066 if ($block = $DB->get_record('block', array('name'=>$pluginname))) {
1067 $currentversion = $block->version;
1069 } catch (Exception $ignored) {
1071 $cd = get_component_directory($component);
1072 if (file_exists("$cd/version.php")) {
1073 $plugin = new stdClass();
1074 $plugin->version = null;
1075 include("$cd/version.php");
1076 $targetversion = $plugin->version;
1079 } else {
1080 $pluginversion = get_config($component, 'version');
1081 if (!empty($pluginversion)) {
1082 $currentversion = $pluginversion;
1084 $cd = get_component_directory($component);
1085 if (file_exists("$cd/version.php")) {
1086 $plugin = new stdClass();
1087 $plugin->version = null;
1088 include("$cd/version.php");
1089 $targetversion = $plugin->version;
1093 $log = new stdClass();
1094 $log->type = $type;
1095 $log->plugin = $component;
1096 $log->version = $currentversion;
1097 $log->targetversion = $targetversion;
1098 $log->info = $info;
1099 $log->details = $details;
1100 $log->backtrace = $backtrace;
1101 $log->userid = $USER->id;
1102 $log->timemodified = time();
1103 try {
1104 $DB->insert_record('upgrade_log', $log);
1105 } catch (Exception $ignored) {
1106 // possible during install or 2.0 upgrade
1111 * Marks start of upgrade, blocks any other access to site.
1112 * The upgrade is finished at the end of script or after timeout.
1114 * @global object
1115 * @global object
1116 * @global object
1118 function upgrade_started($preinstall=false) {
1119 global $CFG, $DB, $PAGE, $OUTPUT;
1121 static $started = false;
1123 if ($preinstall) {
1124 ignore_user_abort(true);
1125 upgrade_setup_debug(true);
1127 } else if ($started) {
1128 upgrade_set_timeout(120);
1130 } else {
1131 if (!CLI_SCRIPT and !$PAGE->headerprinted) {
1132 $strupgrade = get_string('upgradingversion', 'admin');
1133 $PAGE->set_pagelayout('maintenance');
1134 upgrade_init_javascript();
1135 $PAGE->set_title($strupgrade.' - Moodle '.$CFG->target_release);
1136 $PAGE->set_heading($strupgrade);
1137 $PAGE->navbar->add($strupgrade);
1138 $PAGE->set_cacheable(false);
1139 echo $OUTPUT->header();
1142 ignore_user_abort(true);
1143 register_shutdown_function('upgrade_finished_handler');
1144 upgrade_setup_debug(true);
1145 set_config('upgraderunning', time()+300);
1146 $started = true;
1151 * Internal function - executed if upgrade interrupted.
1153 function upgrade_finished_handler() {
1154 upgrade_finished();
1158 * Indicates upgrade is finished.
1160 * This function may be called repeatedly.
1162 * @global object
1163 * @global object
1165 function upgrade_finished($continueurl=null) {
1166 global $CFG, $DB, $OUTPUT;
1168 if (!empty($CFG->upgraderunning)) {
1169 unset_config('upgraderunning');
1170 upgrade_setup_debug(false);
1171 ignore_user_abort(false);
1172 if ($continueurl) {
1173 echo $OUTPUT->continue_button($continueurl);
1174 echo $OUTPUT->footer();
1175 die;
1181 * @global object
1182 * @global object
1184 function upgrade_setup_debug($starting) {
1185 global $CFG, $DB;
1187 static $originaldebug = null;
1189 if ($starting) {
1190 if ($originaldebug === null) {
1191 $originaldebug = $DB->get_debug();
1193 if (!empty($CFG->upgradeshowsql)) {
1194 $DB->set_debug(true);
1196 } else {
1197 $DB->set_debug($originaldebug);
1202 * @global object
1204 function print_upgrade_reload($url) {
1205 global $OUTPUT;
1207 echo "<br />";
1208 echo '<div class="continuebutton">';
1209 echo '<a href="'.$url.'" title="'.get_string('reload').'" ><img src="'.$OUTPUT->pix_url('i/reload') . '" alt="" /> '.get_string('reload').'</a>';
1210 echo '</div><br />';
1213 function print_upgrade_separator() {
1214 if (!CLI_SCRIPT) {
1215 echo '<hr />';
1220 * Default start upgrade callback
1221 * @param string $plugin
1222 * @param bool $installation true if installation, false means upgrade
1224 function print_upgrade_part_start($plugin, $installation, $verbose) {
1225 global $OUTPUT;
1226 if (empty($plugin) or $plugin == 'moodle') {
1227 upgrade_started($installation); // does not store upgrade running flag yet
1228 if ($verbose) {
1229 echo $OUTPUT->heading(get_string('coresystem'));
1231 } else {
1232 upgrade_started();
1233 if ($verbose) {
1234 echo $OUTPUT->heading($plugin);
1237 if ($installation) {
1238 if (empty($plugin) or $plugin == 'moodle') {
1239 // no need to log - log table not yet there ;-)
1240 } else {
1241 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Starting plugin installation');
1243 } else {
1244 if (empty($plugin) or $plugin == 'moodle') {
1245 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Starting core upgrade');
1246 } else {
1247 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Starting plugin upgrade');
1253 * Default end upgrade callback
1254 * @param string $plugin
1255 * @param bool $installation true if installation, false means upgrade
1257 function print_upgrade_part_end($plugin, $installation, $verbose) {
1258 global $OUTPUT;
1259 upgrade_started();
1260 if ($installation) {
1261 if (empty($plugin) or $plugin == 'moodle') {
1262 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Core installed');
1263 } else {
1264 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Plugin installed');
1266 } else {
1267 if (empty($plugin) or $plugin == 'moodle') {
1268 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Core upgraded');
1269 } else {
1270 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Plugin upgraded');
1273 if ($verbose) {
1274 echo $OUTPUT->notification(get_string('success'), 'notifysuccess');
1275 print_upgrade_separator();
1280 * Sets up JS code required for all upgrade scripts.
1281 * @global object
1283 function upgrade_init_javascript() {
1284 global $PAGE;
1285 // scroll to the end of each upgrade page so that ppl see either error or continue button,
1286 // no need to scroll continuously any more, it is enough to jump to end once the footer is printed ;-)
1287 $js = "window.scrollTo(0, 5000000);";
1288 $PAGE->requires->js_init_code($js);
1292 * Try to upgrade the given language pack (or current language)
1294 * @param string $lang the code of the language to update, defaults to the current language
1296 function upgrade_language_pack($lang = null) {
1297 global $CFG;
1299 if (!empty($CFG->skiplangupgrade)) {
1300 return;
1303 if (!file_exists("$CFG->dirroot/$CFG->admin/tool/langimport/lib.php")) {
1304 // weird, somebody uninstalled the import utility
1305 return;
1308 if (!$lang) {
1309 $lang = current_language();
1312 if (!get_string_manager()->translation_exists($lang)) {
1313 return;
1316 get_string_manager()->reset_caches();
1318 if ($lang === 'en') {
1319 return; // Nothing to do
1322 upgrade_started(false);
1324 require_once("$CFG->dirroot/$CFG->admin/tool/langimport/lib.php");
1325 tool_langimport_preupgrade_update($lang);
1327 get_string_manager()->reset_caches();
1329 print_upgrade_separator();
1333 * Install core moodle tables and initialize
1334 * @param float $version target version
1335 * @param bool $verbose
1336 * @return void, may throw exception
1338 function install_core($version, $verbose) {
1339 global $CFG, $DB;
1341 try {
1342 set_time_limit(600);
1343 print_upgrade_part_start('moodle', true, $verbose); // does not store upgrade running flag
1345 $DB->get_manager()->install_from_xmldb_file("$CFG->libdir/db/install.xml");
1346 upgrade_started(); // we want the flag to be stored in config table ;-)
1348 // set all core default records and default settings
1349 require_once("$CFG->libdir/db/install.php");
1350 xmldb_main_install(); // installs the capabilities too
1352 // store version
1353 upgrade_main_savepoint(true, $version, false);
1355 // Continue with the installation
1356 log_update_descriptions('moodle');
1357 external_update_descriptions('moodle');
1358 events_update_definition('moodle');
1359 message_update_providers('moodle');
1361 // Write default settings unconditionally
1362 admin_apply_default_settings(NULL, true);
1364 print_upgrade_part_end(null, true, $verbose);
1365 } catch (exception $ex) {
1366 upgrade_handle_exception($ex);
1371 * Upgrade moodle core
1372 * @param float $version target version
1373 * @param bool $verbose
1374 * @return void, may throw exception
1376 function upgrade_core($version, $verbose) {
1377 global $CFG;
1379 raise_memory_limit(MEMORY_EXTRA);
1381 require_once($CFG->libdir.'/db/upgrade.php'); // Defines upgrades
1383 try {
1384 // Reset caches before any output
1385 purge_all_caches();
1387 // Upgrade current language pack if we can
1388 upgrade_language_pack();
1390 print_upgrade_part_start('moodle', false, $verbose);
1392 // one time special local migration pre 2.0 upgrade script
1393 if ($CFG->version < 2007101600) {
1394 $pre20upgradefile = "$CFG->dirroot/local/upgrade_pre20.php";
1395 if (file_exists($pre20upgradefile)) {
1396 set_time_limit(0);
1397 require($pre20upgradefile);
1398 // reset upgrade timeout to default
1399 upgrade_set_timeout();
1403 $result = xmldb_main_upgrade($CFG->version);
1404 if ($version > $CFG->version) {
1405 // store version if not already there
1406 upgrade_main_savepoint($result, $version, false);
1409 // perform all other component upgrade routines
1410 update_capabilities('moodle');
1411 log_update_descriptions('moodle');
1412 external_update_descriptions('moodle');
1413 events_update_definition('moodle');
1414 message_update_providers('moodle');
1416 // Reset caches again, just to be sure
1417 purge_all_caches();
1419 // Clean up contexts - more and more stuff depends on existence of paths and contexts
1420 cleanup_contexts();
1421 create_contexts();
1422 build_context_path();
1423 $syscontext = get_context_instance(CONTEXT_SYSTEM);
1424 mark_context_dirty($syscontext->path);
1426 print_upgrade_part_end('moodle', false, $verbose);
1427 } catch (Exception $ex) {
1428 upgrade_handle_exception($ex);
1433 * Upgrade/install other parts of moodle
1434 * @param bool $verbose
1435 * @return void, may throw exception
1437 function upgrade_noncore($verbose) {
1438 global $CFG;
1440 raise_memory_limit(MEMORY_EXTRA);
1442 // upgrade all plugins types
1443 try {
1444 $plugintypes = get_plugin_types();
1445 foreach ($plugintypes as $type=>$location) {
1446 upgrade_plugins($type, 'print_upgrade_part_start', 'print_upgrade_part_end', $verbose);
1448 } catch (Exception $ex) {
1449 upgrade_handle_exception($ex);
1454 * Checks if the main tables have been installed yet or not.
1455 * @return bool
1457 function core_tables_exist() {
1458 global $DB;
1460 if (!$tables = $DB->get_tables() ) { // No tables yet at all.
1461 return false;
1463 } else { // Check for missing main tables
1464 $mtables = array('config', 'course', 'groupings'); // some tables used in 1.9 and 2.0, preferable something from the start and end of install.xml
1465 foreach ($mtables as $mtable) {
1466 if (!in_array($mtable, $tables)) {
1467 return false;
1470 return true;
1475 * upgrades the mnet rpc definitions for the given component.
1476 * this method doesn't return status, an exception will be thrown in the case of an error
1478 * @param string $component the plugin to upgrade, eg auth_mnet
1480 function upgrade_plugin_mnet_functions($component) {
1481 global $DB, $CFG;
1483 list($type, $plugin) = explode('_', $component);
1484 $path = get_plugin_directory($type, $plugin);
1486 $publishes = array();
1487 $subscribes = array();
1488 if (file_exists($path . '/db/mnet.php')) {
1489 require_once($path . '/db/mnet.php'); // $publishes comes from this file
1491 if (empty($publishes)) {
1492 $publishes = array(); // still need this to be able to disable stuff later
1494 if (empty($subscribes)) {
1495 $subscribes = array(); // still need this to be able to disable stuff later
1498 static $servicecache = array();
1500 // rekey an array based on the rpc method for easy lookups later
1501 $publishmethodservices = array();
1502 $subscribemethodservices = array();
1503 foreach($publishes as $servicename => $service) {
1504 if (is_array($service['methods'])) {
1505 foreach($service['methods'] as $methodname) {
1506 $service['servicename'] = $servicename;
1507 $publishmethodservices[$methodname][] = $service;
1512 // Disable functions that don't exist (any more) in the source
1513 // Should these be deleted? What about their permissions records?
1514 foreach ($DB->get_records('mnet_rpc', array('pluginname'=>$plugin, 'plugintype'=>$type), 'functionname ASC ') as $rpc) {
1515 if (!array_key_exists($rpc->functionname, $publishmethodservices) && $rpc->enabled) {
1516 $DB->set_field('mnet_rpc', 'enabled', 0, array('id' => $rpc->id));
1517 } else if (array_key_exists($rpc->functionname, $publishmethodservices) && !$rpc->enabled) {
1518 $DB->set_field('mnet_rpc', 'enabled', 1, array('id' => $rpc->id));
1522 // reflect all the services we're publishing and save them
1523 require_once($CFG->dirroot . '/lib/zend/Zend/Server/Reflection.php');
1524 static $cachedclasses = array(); // to store reflection information in
1525 foreach ($publishes as $service => $data) {
1526 $f = $data['filename'];
1527 $c = $data['classname'];
1528 foreach ($data['methods'] as $method) {
1529 $dataobject = new stdClass();
1530 $dataobject->plugintype = $type;
1531 $dataobject->pluginname = $plugin;
1532 $dataobject->enabled = 1;
1533 $dataobject->classname = $c;
1534 $dataobject->filename = $f;
1536 if (is_string($method)) {
1537 $dataobject->functionname = $method;
1539 } else if (is_array($method)) { // wants to override file or class
1540 $dataobject->functionname = $method['method'];
1541 $dataobject->classname = $method['classname'];
1542 $dataobject->filename = $method['filename'];
1544 $dataobject->xmlrpcpath = $type.'/'.$plugin.'/'.$dataobject->filename.'/'.$method;
1545 $dataobject->static = false;
1547 require_once($path . '/' . $dataobject->filename);
1548 $functionreflect = null; // slightly different ways to get this depending on whether it's a class method or a function
1549 if (!empty($dataobject->classname)) {
1550 if (!class_exists($dataobject->classname)) {
1551 throw new moodle_exception('installnosuchmethod', 'mnet', '', (object)array('method' => $dataobject->functionname, 'class' => $dataobject->classname));
1553 $key = $dataobject->filename . '|' . $dataobject->classname;
1554 if (!array_key_exists($key, $cachedclasses)) { // look to see if we've already got a reflection object
1555 try {
1556 $cachedclasses[$key] = Zend_Server_Reflection::reflectClass($dataobject->classname);
1557 } catch (Zend_Server_Reflection_Exception $e) { // catch these and rethrow them to something more helpful
1558 throw new moodle_exception('installreflectionclasserror', 'mnet', '', (object)array('method' => $dataobject->functionname, 'class' => $dataobject->classname, 'error' => $e->getMessage()));
1561 $r =& $cachedclasses[$key];
1562 if (!$r->hasMethod($dataobject->functionname)) {
1563 throw new moodle_exception('installnosuchmethod', 'mnet', '', (object)array('method' => $dataobject->functionname, 'class' => $dataobject->classname));
1565 // stupid workaround for zend not having a getMethod($name) function
1566 $ms = $r->getMethods();
1567 foreach ($ms as $m) {
1568 if ($m->getName() == $dataobject->functionname) {
1569 $functionreflect = $m;
1570 break;
1573 $dataobject->static = (int)$functionreflect->isStatic();
1574 } else {
1575 if (!function_exists($dataobject->functionname)) {
1576 throw new moodle_exception('installnosuchfunction', 'mnet', '', (object)array('method' => $dataobject->functionname, 'file' => $dataobject->filename));
1578 try {
1579 $functionreflect = Zend_Server_Reflection::reflectFunction($dataobject->functionname);
1580 } catch (Zend_Server_Reflection_Exception $e) { // catch these and rethrow them to something more helpful
1581 throw new moodle_exception('installreflectionfunctionerror', 'mnet', '', (object)array('method' => $dataobject->functionname, '' => $dataobject->filename, 'error' => $e->getMessage()));
1584 $dataobject->profile = serialize(admin_mnet_method_profile($functionreflect));
1585 $dataobject->help = $functionreflect->getDescription();
1587 if ($record_exists = $DB->get_record('mnet_rpc', array('xmlrpcpath'=>$dataobject->xmlrpcpath))) {
1588 $dataobject->id = $record_exists->id;
1589 $dataobject->enabled = $record_exists->enabled;
1590 $DB->update_record('mnet_rpc', $dataobject);
1591 } else {
1592 $dataobject->id = $DB->insert_record('mnet_rpc', $dataobject, true);
1595 // TODO this API versioning must be reworked, here the recently processed method
1596 // sets the service API which may not be correct
1597 foreach ($publishmethodservices[$dataobject->functionname] as $service) {
1598 if ($serviceobj = $DB->get_record('mnet_service', array('name'=>$service['servicename']))) {
1599 $serviceobj->apiversion = $service['apiversion'];
1600 $DB->update_record('mnet_service', $serviceobj);
1601 } else {
1602 $serviceobj = new stdClass();
1603 $serviceobj->name = $service['servicename'];
1604 $serviceobj->description = empty($service['description']) ? '' : $service['description'];
1605 $serviceobj->apiversion = $service['apiversion'];
1606 $serviceobj->offer = 1;
1607 $serviceobj->id = $DB->insert_record('mnet_service', $serviceobj);
1609 $servicecache[$service['servicename']] = $serviceobj;
1610 if (!$DB->record_exists('mnet_service2rpc', array('rpcid'=>$dataobject->id, 'serviceid'=>$serviceobj->id))) {
1611 $obj = new stdClass();
1612 $obj->rpcid = $dataobject->id;
1613 $obj->serviceid = $serviceobj->id;
1614 $DB->insert_record('mnet_service2rpc', $obj, true);
1619 // finished with methods we publish, now do subscribable methods
1620 foreach($subscribes as $service => $methods) {
1621 if (!array_key_exists($service, $servicecache)) {
1622 if (!$serviceobj = $DB->get_record('mnet_service', array('name' => $service))) {
1623 debugging("TODO: skipping unknown service $service - somebody needs to fix MDL-21993");
1624 continue;
1626 $servicecache[$service] = $serviceobj;
1627 } else {
1628 $serviceobj = $servicecache[$service];
1630 foreach ($methods as $method => $xmlrpcpath) {
1631 if (!$rpcid = $DB->get_field('mnet_remote_rpc', 'id', array('xmlrpcpath'=>$xmlrpcpath))) {
1632 $remoterpc = (object)array(
1633 'functionname' => $method,
1634 'xmlrpcpath' => $xmlrpcpath,
1635 'plugintype' => $type,
1636 'pluginname' => $plugin,
1637 'enabled' => 1,
1639 $rpcid = $remoterpc->id = $DB->insert_record('mnet_remote_rpc', $remoterpc, true);
1641 if (!$DB->record_exists('mnet_remote_service2rpc', array('rpcid'=>$rpcid, 'serviceid'=>$serviceobj->id))) {
1642 $obj = new stdClass();
1643 $obj->rpcid = $rpcid;
1644 $obj->serviceid = $serviceobj->id;
1645 $DB->insert_record('mnet_remote_service2rpc', $obj, true);
1647 $subscribemethodservices[$method][] = $service;
1651 foreach ($DB->get_records('mnet_remote_rpc', array('pluginname'=>$plugin, 'plugintype'=>$type), 'functionname ASC ') as $rpc) {
1652 if (!array_key_exists($rpc->functionname, $subscribemethodservices) && $rpc->enabled) {
1653 $DB->set_field('mnet_remote_rpc', 'enabled', 0, array('id' => $rpc->id));
1654 } else if (array_key_exists($rpc->functionname, $subscribemethodservices) && !$rpc->enabled) {
1655 $DB->set_field('mnet_remote_rpc', 'enabled', 1, array('id' => $rpc->id));
1659 return true;
1663 * Given some sort of Zend Reflection function/method object, return a profile array, ready to be serialized and stored
1665 * @param Zend_Server_Reflection_Function_Abstract $function can be any subclass of this object type
1667 * @return array
1669 function admin_mnet_method_profile(Zend_Server_Reflection_Function_Abstract $function) {
1670 $proto = array_pop($function->getPrototypes());
1671 $ret = $proto->getReturnValue();
1672 $profile = array(
1673 'parameters' => array(),
1674 'return' => array(
1675 'type' => $ret->getType(),
1676 'description' => $ret->getDescription(),
1679 foreach ($proto->getParameters() as $p) {
1680 $profile['parameters'][] = array(
1681 'name' => $p->getName(),
1682 'type' => $p->getType(),
1683 'description' => $p->getDescription(),
1686 return $profile;