MDL-27588 Fixed up several bugs with the formal_white theme
[moodle.git] / lib / upgradelib.php
blob5a36a644598863f683969fb90e1597b0b92c5b16
1 <?php
3 // This file is part of Moodle - http://moodle.org/
4 //
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
9 //
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 /**
19 * Various upgrade/install related functions and classes.
21 * @package core
22 * @subpackage upgrade
23 * @copyright 1999 onwards Martin Dougiamas (http://dougiamas.com)
24 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
27 defined('MOODLE_INTERNAL') || die();
29 /** UPGRADE_LOG_NORMAL = 0 */
30 define('UPGRADE_LOG_NORMAL', 0);
31 /** UPGRADE_LOG_NOTICE = 1 */
32 define('UPGRADE_LOG_NOTICE', 1);
33 /** UPGRADE_LOG_ERROR = 2 */
34 define('UPGRADE_LOG_ERROR', 2);
36 /**
37 * Exception indicating unknown error during upgrade.
39 * @package core
40 * @subpackage upgrade
41 * @copyright 2009 Petr Skoda {@link http://skodak.org}
42 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
44 class upgrade_exception extends moodle_exception {
45 function __construct($plugin, $version, $debuginfo=NULL) {
46 global $CFG;
47 $a = (object)array('plugin'=>$plugin, 'version'=>$version);
48 parent::__construct('upgradeerror', 'admin', "$CFG->wwwroot/$CFG->admin/index.php", $a, $debuginfo);
52 /**
53 * Exception indicating downgrade error during upgrade.
55 * @package core
56 * @subpackage upgrade
57 * @copyright 2009 Petr Skoda {@link http://skodak.org}
58 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
60 class downgrade_exception extends moodle_exception {
61 function __construct($plugin, $oldversion, $newversion) {
62 global $CFG;
63 $plugin = is_null($plugin) ? 'moodle' : $plugin;
64 $a = (object)array('plugin'=>$plugin, 'oldversion'=>$oldversion, 'newversion'=>$newversion);
65 parent::__construct('cannotdowngrade', 'debug', "$CFG->wwwroot/$CFG->admin/index.php", $a);
69 /**
70 * @package core
71 * @subpackage upgrade
72 * @copyright 2009 Petr Skoda {@link http://skodak.org}
73 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
75 class upgrade_requires_exception extends moodle_exception {
76 function __construct($plugin, $pluginversion, $currentmoodle, $requiremoodle) {
77 global $CFG;
78 $a = new stdClass();
79 $a->pluginname = $plugin;
80 $a->pluginversion = $pluginversion;
81 $a->currentmoodle = $currentmoodle;
82 $a->requiremoodle = $requiremoodle;
83 parent::__construct('pluginrequirementsnotmet', 'error', "$CFG->wwwroot/$CFG->admin/index.php", $a);
87 /**
88 * @package core
89 * @subpackage upgrade
90 * @copyright 2009 Petr Skoda {@link http://skodak.org}
91 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
93 class plugin_defective_exception extends moodle_exception {
94 function __construct($plugin, $details) {
95 global $CFG;
96 parent::__construct('detectedbrokenplugin', 'error', "$CFG->wwwroot/$CFG->admin/index.php", $plugin, $details);
101 * Upgrade savepoint, marks end of each upgrade block.
102 * It stores new main version, resets upgrade timeout
103 * and abort upgrade if user cancels page loading.
105 * Please do not make large upgrade blocks with lots of operations,
106 * for example when adding tables keep only one table operation per block.
108 * @global object
109 * @param bool $result false if upgrade step failed, true if completed
110 * @param string or float $version main version
111 * @param bool $allowabort allow user to abort script execution here
112 * @return void
114 function upgrade_main_savepoint($result, $version, $allowabort=true) {
115 global $CFG;
117 if (!$result) {
118 throw new upgrade_exception(null, $version);
121 if ($CFG->version >= $version) {
122 // something really wrong is going on in main upgrade script
123 throw new downgrade_exception(null, $CFG->version, $version);
126 set_config('version', $version);
127 upgrade_log(UPGRADE_LOG_NORMAL, null, 'Upgrade savepoint reached');
129 // reset upgrade timeout to default
130 upgrade_set_timeout();
132 // this is a safe place to stop upgrades if user aborts page loading
133 if ($allowabort and connection_aborted()) {
134 die;
139 * Module upgrade savepoint, marks end of module upgrade blocks
140 * It stores module version, resets upgrade timeout
141 * and abort upgrade if user cancels page loading.
143 * @global object
144 * @param bool $result false if upgrade step failed, true if completed
145 * @param string or float $version main version
146 * @param string $modname name of module
147 * @param bool $allowabort allow user to abort script execution here
148 * @return void
150 function upgrade_mod_savepoint($result, $version, $modname, $allowabort=true) {
151 global $DB;
153 if (!$result) {
154 throw new upgrade_exception("mod_$modname", $version);
157 if (!$module = $DB->get_record('modules', array('name'=>$modname))) {
158 print_error('modulenotexist', 'debug', '', $modname);
161 if ($module->version >= $version) {
162 // something really wrong is going on in upgrade script
163 throw new downgrade_exception("mod_$modname", $module->version, $version);
165 $module->version = $version;
166 $DB->update_record('modules', $module);
167 upgrade_log(UPGRADE_LOG_NORMAL, "mod_$modname", 'Upgrade savepoint reached');
169 // reset upgrade timeout to default
170 upgrade_set_timeout();
172 // this is a safe place to stop upgrades if user aborts page loading
173 if ($allowabort and connection_aborted()) {
174 die;
179 * Blocks upgrade savepoint, marks end of blocks upgrade blocks
180 * It stores block version, resets upgrade timeout
181 * and abort upgrade if user cancels page loading.
183 * @global object
184 * @param bool $result false if upgrade step failed, true if completed
185 * @param string or float $version main version
186 * @param string $blockname name of block
187 * @param bool $allowabort allow user to abort script execution here
188 * @return void
190 function upgrade_block_savepoint($result, $version, $blockname, $allowabort=true) {
191 global $DB;
193 if (!$result) {
194 throw new upgrade_exception("block_$blockname", $version);
197 if (!$block = $DB->get_record('block', array('name'=>$blockname))) {
198 print_error('blocknotexist', 'debug', '', $blockname);
201 if ($block->version >= $version) {
202 // something really wrong is going on in upgrade script
203 throw new downgrade_exception("block_$blockname", $block->version, $version);
205 $block->version = $version;
206 $DB->update_record('block', $block);
207 upgrade_log(UPGRADE_LOG_NORMAL, "block_$blockname", 'Upgrade savepoint reached');
209 // reset upgrade timeout to default
210 upgrade_set_timeout();
212 // this is a safe place to stop upgrades if user aborts page loading
213 if ($allowabort and connection_aborted()) {
214 die;
219 * Plugins upgrade savepoint, marks end of blocks upgrade blocks
220 * It stores plugin version, resets upgrade timeout
221 * and abort upgrade if user cancels page loading.
223 * @param bool $result false if upgrade step failed, true if completed
224 * @param string or float $version main version
225 * @param string $type name of plugin
226 * @param string $dir location of plugin
227 * @param bool $allowabort allow user to abort script execution here
228 * @return void
230 function upgrade_plugin_savepoint($result, $version, $type, $plugin, $allowabort=true) {
231 $component = $type.'_'.$plugin;
233 if (!$result) {
234 throw new upgrade_exception($component, $version);
237 $installedversion = get_config($component, 'version');
238 if ($installedversion >= $version) {
239 // Something really wrong is going on in the upgrade script
240 throw new downgrade_exception($component, $installedversion, $version);
242 set_config('version', $version, $component);
243 upgrade_log(UPGRADE_LOG_NORMAL, $component, 'Upgrade savepoint reached');
245 // Reset upgrade timeout to default
246 upgrade_set_timeout();
248 // This is a safe place to stop upgrades if user aborts page loading
249 if ($allowabort and connection_aborted()) {
250 die;
256 * Upgrade plugins
257 * @param string $type The type of plugins that should be updated (e.g. 'enrol', 'qtype')
258 * return void
260 function upgrade_plugins($type, $startcallback, $endcallback, $verbose) {
261 global $CFG, $DB;
263 /// special cases
264 if ($type === 'mod') {
265 return upgrade_plugins_modules($startcallback, $endcallback, $verbose);
266 } else if ($type === 'block') {
267 return upgrade_plugins_blocks($startcallback, $endcallback, $verbose);
270 $plugs = get_plugin_list($type);
272 foreach ($plugs as $plug=>$fullplug) {
273 $component = $type.'_'.$plug; // standardised plugin name
275 // check plugin dir is valid name
276 $cplug = strtolower($plug);
277 $cplug = clean_param($cplug, PARAM_SAFEDIR);
278 $cplug = str_replace('-', '', $cplug);
279 if ($plug !== $cplug) {
280 throw new plugin_defective_exception($component, 'Invalid plugin directory name.');
283 if (!is_readable($fullplug.'/version.php')) {
284 continue;
287 $plugin = new stdClass();
288 require($fullplug.'/version.php'); // defines $plugin with version etc
290 // if plugin tells us it's full name we may check the location
291 if (isset($plugin->component)) {
292 if ($plugin->component !== $component) {
293 throw new plugin_defective_exception($component, 'Plugin installed in wrong folder.');
297 if (empty($plugin->version)) {
298 throw new plugin_defective_exception($component, 'Missing version value in version.php');
301 $plugin->name = $plug;
302 $plugin->fullname = $component;
305 if (!empty($plugin->requires)) {
306 if ($plugin->requires > $CFG->version) {
307 throw new upgrade_requires_exception($component, $plugin->version, $CFG->version, $plugin->requires);
308 } else if ($plugin->requires < 2010000000) {
309 throw new plugin_defective_exception($component, 'Plugin is not compatible with Moodle 2.x or later.');
313 // try to recover from interrupted install.php if needed
314 if (file_exists($fullplug.'/db/install.php')) {
315 if (get_config($plugin->fullname, 'installrunning')) {
316 require_once($fullplug.'/db/install.php');
317 $recover_install_function = 'xmldb_'.$plugin->fullname.'_install_recovery';
318 if (function_exists($recover_install_function)) {
319 $startcallback($component, true, $verbose);
320 $recover_install_function();
321 unset_config('installrunning', $plugin->fullname);
322 update_capabilities($component);
323 log_update_descriptions($component);
324 external_update_descriptions($component);
325 events_update_definition($component);
326 message_update_providers($component);
327 if ($type === 'message') {
328 message_update_processors($plug);
330 upgrade_plugin_mnet_functions($component);
331 $endcallback($component, true, $verbose);
336 $installedversion = get_config($plugin->fullname, 'version');
337 if (empty($installedversion)) { // new installation
338 $startcallback($component, true, $verbose);
340 /// Install tables if defined
341 if (file_exists($fullplug.'/db/install.xml')) {
342 $DB->get_manager()->install_from_xmldb_file($fullplug.'/db/install.xml');
345 /// store version
346 upgrade_plugin_savepoint(true, $plugin->version, $type, $plug, false);
348 /// execute post install file
349 if (file_exists($fullplug.'/db/install.php')) {
350 require_once($fullplug.'/db/install.php');
351 set_config('installrunning', 1, $plugin->fullname);
352 $post_install_function = 'xmldb_'.$plugin->fullname.'_install';
353 $post_install_function();
354 unset_config('installrunning', $plugin->fullname);
357 /// Install various components
358 update_capabilities($component);
359 log_update_descriptions($component);
360 external_update_descriptions($component);
361 events_update_definition($component);
362 message_update_providers($component);
363 if ($type === 'message') {
364 message_update_processors($plug);
366 upgrade_plugin_mnet_functions($component);
368 purge_all_caches();
369 $endcallback($component, true, $verbose);
371 } else if ($installedversion < $plugin->version) { // upgrade
372 /// Run the upgrade function for the plugin.
373 $startcallback($component, false, $verbose);
375 if (is_readable($fullplug.'/db/upgrade.php')) {
376 require_once($fullplug.'/db/upgrade.php'); // defines upgrading function
378 $newupgrade_function = 'xmldb_'.$plugin->fullname.'_upgrade';
379 $result = $newupgrade_function($installedversion);
380 } else {
381 $result = true;
384 $installedversion = get_config($plugin->fullname, 'version');
385 if ($installedversion < $plugin->version) {
386 // store version if not already there
387 upgrade_plugin_savepoint($result, $plugin->version, $type, $plug, false);
390 /// Upgrade various components
391 update_capabilities($component);
392 log_update_descriptions($component);
393 external_update_descriptions($component);
394 events_update_definition($component);
395 message_update_providers($component);
396 if ($type === 'message') {
397 message_update_processors($plug);
399 upgrade_plugin_mnet_functions($component);
401 purge_all_caches();
402 $endcallback($component, false, $verbose);
404 } else if ($installedversion > $plugin->version) {
405 throw new downgrade_exception($component, $installedversion, $plugin->version);
411 * Find and check all modules and load them up or upgrade them if necessary
413 * @global object
414 * @global object
416 function upgrade_plugins_modules($startcallback, $endcallback, $verbose) {
417 global $CFG, $DB;
419 $mods = get_plugin_list('mod');
421 foreach ($mods as $mod=>$fullmod) {
423 if ($mod === 'NEWMODULE') { // Someone has unzipped the template, ignore it
424 continue;
427 $component = 'mod_'.$mod;
429 // check module dir is valid name
430 $cmod = strtolower($mod);
431 $cmod = clean_param($cmod, PARAM_SAFEDIR);
432 $cmod = str_replace('-', '', $cmod);
433 $cmod = str_replace('_', '', $cmod); // modules MUST not have '_' in name and never will, sorry
434 if ($mod !== $cmod) {
435 throw new plugin_defective_exception($component, 'Invalid plugin directory name.');
438 if (!is_readable($fullmod.'/version.php')) {
439 throw new plugin_defective_exception($component, 'Missing version.php');
442 $module = new stdClass();
443 require($fullmod .'/version.php'); // defines $module with version etc
445 // if plugin tells us it's full name we may check the location
446 if (isset($module->component)) {
447 if ($module->component !== $component) {
448 throw new plugin_defective_exception($component, 'Plugin installed in wrong folder.');
452 if (empty($module->version)) {
453 if (isset($module->version)) {
454 // Version is empty but is set - it means its value is 0 or ''. Let us skip such module.
455 // This is intended for developers so they can work on the early stages of the module.
456 continue;
458 throw new plugin_defective_exception($component, 'Missing version value in version.php');
461 if (!empty($module->requires)) {
462 if ($module->requires > $CFG->version) {
463 throw new upgrade_requires_exception($component, $module->version, $CFG->version, $module->requires);
464 } else if ($module->requires < 2010000000) {
465 throw new plugin_defective_exception($component, 'Plugin is not compatible with Moodle 2.x or later.');
469 // all modules must have en lang pack
470 if (!is_readable("$fullmod/lang/en/$mod.php")) {
471 throw new plugin_defective_exception($component, 'Missing mandatory en language pack.');
474 $module->name = $mod; // The name MUST match the directory
476 $currmodule = $DB->get_record('modules', array('name'=>$module->name));
478 if (file_exists($fullmod.'/db/install.php')) {
479 if (get_config($module->name, 'installrunning')) {
480 require_once($fullmod.'/db/install.php');
481 $recover_install_function = 'xmldb_'.$module->name.'_install_recovery';
482 if (function_exists($recover_install_function)) {
483 $startcallback($component, true, $verbose);
484 $recover_install_function();
485 unset_config('installrunning', $module->name);
486 // Install various components too
487 update_capabilities($component);
488 log_update_descriptions($component);
489 external_update_descriptions($component);
490 events_update_definition($component);
491 message_update_providers($component);
492 upgrade_plugin_mnet_functions($component);
493 $endcallback($component, true, $verbose);
498 if (empty($currmodule->version)) {
499 $startcallback($component, true, $verbose);
501 /// Execute install.xml (XMLDB) - must be present in all modules
502 $DB->get_manager()->install_from_xmldb_file($fullmod.'/db/install.xml');
504 /// Add record into modules table - may be needed in install.php already
505 $module->id = $DB->insert_record('modules', $module);
507 /// Post installation hook - optional
508 if (file_exists("$fullmod/db/install.php")) {
509 require_once("$fullmod/db/install.php");
510 // Set installation running flag, we need to recover after exception or error
511 set_config('installrunning', 1, $module->name);
512 $post_install_function = 'xmldb_'.$module->name.'_install';;
513 $post_install_function();
514 unset_config('installrunning', $module->name);
517 /// Install various components
518 update_capabilities($component);
519 log_update_descriptions($component);
520 external_update_descriptions($component);
521 events_update_definition($component);
522 message_update_providers($component);
523 upgrade_plugin_mnet_functions($component);
525 purge_all_caches();
526 $endcallback($component, true, $verbose);
528 } else if ($currmodule->version < $module->version) {
529 /// If versions say that we need to upgrade but no upgrade files are available, notify and continue
530 $startcallback($component, false, $verbose);
532 if (is_readable($fullmod.'/db/upgrade.php')) {
533 require_once($fullmod.'/db/upgrade.php'); // defines new upgrading function
534 $newupgrade_function = 'xmldb_'.$module->name.'_upgrade';
535 $result = $newupgrade_function($currmodule->version, $module);
536 } else {
537 $result = true;
540 $currmodule = $DB->get_record('modules', array('name'=>$module->name));
541 if ($currmodule->version < $module->version) {
542 // store version if not already there
543 upgrade_mod_savepoint($result, $module->version, $mod, false);
546 /// Upgrade various components
547 update_capabilities($component);
548 log_update_descriptions($component);
549 external_update_descriptions($component);
550 events_update_definition($component);
551 message_update_providers($component);
552 upgrade_plugin_mnet_functions($component);
554 purge_all_caches();
556 $endcallback($component, false, $verbose);
558 } else if ($currmodule->version > $module->version) {
559 throw new downgrade_exception($component, $currmodule->version, $module->version);
566 * This function finds all available blocks and install them
567 * into blocks table or do all the upgrade process if newer.
569 * @global object
570 * @global object
572 function upgrade_plugins_blocks($startcallback, $endcallback, $verbose) {
573 global $CFG, $DB;
575 require_once($CFG->dirroot.'/blocks/moodleblock.class.php');
577 $blocktitles = array(); // we do not want duplicate titles
579 //Is this a first install
580 $first_install = null;
582 $blocks = get_plugin_list('block');
584 foreach ($blocks as $blockname=>$fullblock) {
586 if (is_null($first_install)) {
587 $first_install = ($DB->count_records('block_instances') == 0);
590 if ($blockname == 'NEWBLOCK') { // Someone has unzipped the template, ignore it
591 continue;
594 $component = 'block_'.$blockname;
596 // check block dir is valid name
597 $cblockname = strtolower($blockname);
598 $cblockname = clean_param($cblockname, PARAM_SAFEDIR);
599 $cblockname = str_replace('-', '', $cblockname);
600 if ($blockname !== $cblockname) {
601 throw new plugin_defective_exception($component, 'Invalid plugin directory name.');
604 if (!is_readable($fullblock.'/version.php')) {
605 throw new plugin_defective_exception('block/'.$blockname, 'Missing version.php file.');
607 $plugin = new stdClass();
608 $plugin->version = NULL;
609 $plugin->cron = 0;
610 include($fullblock.'/version.php');
611 $block = $plugin;
613 // if plugin tells us it's full name we may check the location
614 if (isset($block->component)) {
615 if ($block->component !== $component) {
616 throw new plugin_defective_exception($component, 'Plugin installed in wrong folder.');
620 if (!empty($plugin->requires)) {
621 if ($plugin->requires > $CFG->version) {
622 throw new upgrade_requires_exception($component, $plugin->version, $CFG->version, $plugin->requires);
623 } else if ($plugin->requires < 2010000000) {
624 throw new plugin_defective_exception($component, 'Plugin is not compatible with Moodle 2.x or later.');
628 if (!is_readable($fullblock.'/block_'.$blockname.'.php')) {
629 throw new plugin_defective_exception('block/'.$blockname, 'Missing main block class file.');
631 include_once($fullblock.'/block_'.$blockname.'.php');
633 $classname = 'block_'.$blockname;
635 if (!class_exists($classname)) {
636 throw new plugin_defective_exception($component, 'Can not load main class.');
639 $blockobj = new $classname; // This is what we'll be testing
640 $blocktitle = $blockobj->get_title();
642 // OK, it's as we all hoped. For further tests, the object will do them itself.
643 if (!$blockobj->_self_test()) {
644 throw new plugin_defective_exception($component, 'Self test failed.');
647 $block->name = $blockname; // The name MUST match the directory
649 if (empty($block->version)) {
650 throw new plugin_defective_exception($component, 'Missing block version.');
653 $currblock = $DB->get_record('block', array('name'=>$block->name));
655 if (file_exists($fullblock.'/db/install.php')) {
656 if (get_config('block_'.$blockname, 'installrunning')) {
657 require_once($fullblock.'/db/install.php');
658 $recover_install_function = 'xmldb_block_'.$blockname.'_install_recovery';
659 if (function_exists($recover_install_function)) {
660 $startcallback($component, true, $verbose);
661 $recover_install_function();
662 unset_config('installrunning', 'block_'.$blockname);
663 // Install various components
664 update_capabilities($component);
665 log_update_descriptions($component);
666 external_update_descriptions($component);
667 events_update_definition($component);
668 message_update_providers($component);
669 upgrade_plugin_mnet_functions($component);
670 $endcallback($component, true, $verbose);
675 if (empty($currblock->version)) { // block not installed yet, so install it
676 $conflictblock = array_search($blocktitle, $blocktitles);
677 if ($conflictblock !== false) {
678 // Duplicate block titles are not allowed, they confuse people
679 // AND PHP's associative arrays ;)
680 throw new plugin_defective_exception($component, get_string('blocknameconflict', 'error', (object)array('name'=>$block->name, 'conflict'=>$conflictblock)));
682 $startcallback($component, true, $verbose);
684 if (file_exists($fullblock.'/db/install.xml')) {
685 $DB->get_manager()->install_from_xmldb_file($fullblock.'/db/install.xml');
687 $block->id = $DB->insert_record('block', $block);
689 if (file_exists($fullblock.'/db/install.php')) {
690 require_once($fullblock.'/db/install.php');
691 // Set installation running flag, we need to recover after exception or error
692 set_config('installrunning', 1, 'block_'.$blockname);
693 $post_install_function = 'xmldb_block_'.$blockname.'_install';;
694 $post_install_function();
695 unset_config('installrunning', 'block_'.$blockname);
698 $blocktitles[$block->name] = $blocktitle;
700 // Install various components
701 update_capabilities($component);
702 log_update_descriptions($component);
703 external_update_descriptions($component);
704 events_update_definition($component);
705 message_update_providers($component);
706 upgrade_plugin_mnet_functions($component);
708 purge_all_caches();
709 $endcallback($component, true, $verbose);
711 } else if ($currblock->version < $block->version) {
712 $startcallback($component, false, $verbose);
714 if (is_readable($fullblock.'/db/upgrade.php')) {
715 require_once($fullblock.'/db/upgrade.php'); // defines new upgrading function
716 $newupgrade_function = 'xmldb_block_'.$blockname.'_upgrade';
717 $result = $newupgrade_function($currblock->version, $block);
718 } else {
719 $result = true;
722 $currblock = $DB->get_record('block', array('name'=>$block->name));
723 if ($currblock->version < $block->version) {
724 // store version if not already there
725 upgrade_block_savepoint($result, $block->version, $block->name, false);
728 if ($currblock->cron != $block->cron) {
729 // update cron flag if needed
730 $currblock->cron = $block->cron;
731 $DB->update_record('block', $currblock);
734 // Upgrade various components
735 update_capabilities($component);
736 log_update_descriptions($component);
737 external_update_descriptions($component);
738 events_update_definition($component);
739 message_update_providers($component);
740 upgrade_plugin_mnet_functions($component);
742 purge_all_caches();
743 $endcallback($component, false, $verbose);
745 } else if ($currblock->version > $block->version) {
746 throw new downgrade_exception($component, $currblock->version, $block->version);
751 // Finally, if we are in the first_install of BLOCKS setup frontpage and admin page blocks
752 if ($first_install) {
753 //Iterate over each course - there should be only site course here now
754 if ($courses = $DB->get_records('course')) {
755 foreach ($courses as $course) {
756 blocks_add_default_course_blocks($course);
760 blocks_add_default_system_blocks();
766 * Log_display description function used during install and upgrade.
768 * @param string $component name of component (moodle, mod_assignment, etc.)
769 * @return void
771 function log_update_descriptions($component) {
772 global $DB;
774 $defpath = get_component_directory($component).'/db/log.php';
776 if (!file_exists($defpath)) {
777 $DB->delete_records('log_display', array('component'=>$component));
778 return;
781 // load new info
782 $logs = array();
783 include($defpath);
784 $newlogs = array();
785 foreach ($logs as $log) {
786 $newlogs[$log['module'].'-'.$log['action']] = $log; // kind of unique name
788 unset($logs);
789 $logs = $newlogs;
791 $fields = array('module', 'action', 'mtable', 'field');
792 // update all log fist
793 $dblogs = $DB->get_records('log_display', array('component'=>$component));
794 foreach ($dblogs as $dblog) {
795 $name = $dblog->module.'-'.$dblog->action;
797 if (empty($logs[$name])) {
798 $DB->delete_records('log_display', array('id'=>$dblog->id));
799 continue;
802 $log = $logs[$name];
803 unset($logs[$name]);
805 $update = false;
806 foreach ($fields as $field) {
807 if ($dblog->$field != $log[$field]) {
808 $dblog->$field = $log[$field];
809 $update = true;
812 if ($update) {
813 $DB->update_record('log_display', $dblog);
816 foreach ($logs as $log) {
817 $dblog = (object)$log;
818 $dblog->component = $component;
819 $DB->insert_record('log_display', $dblog);
824 * Web service discovery function used during install and upgrade.
825 * @param string $component name of component (moodle, mod_assignment, etc.)
826 * @return void
828 function external_update_descriptions($component) {
829 global $DB;
831 $defpath = get_component_directory($component).'/db/services.php';
833 if (!file_exists($defpath)) {
834 external_delete_descriptions($component);
835 return;
838 // load new info
839 $functions = array();
840 $services = array();
841 include($defpath);
843 // update all function fist
844 $dbfunctions = $DB->get_records('external_functions', array('component'=>$component));
845 foreach ($dbfunctions as $dbfunction) {
846 if (empty($functions[$dbfunction->name])) {
847 $DB->delete_records('external_functions', array('id'=>$dbfunction->id));
848 // do not delete functions from external_services_functions, beacuse
849 // we want to notify admins when functions used in custom services disappear
851 //TODO: this looks wrong, we have to delete it eventually (skodak)
852 continue;
855 $function = $functions[$dbfunction->name];
856 unset($functions[$dbfunction->name]);
857 $function['classpath'] = empty($function['classpath']) ? null : $function['classpath'];
859 $update = false;
860 if ($dbfunction->classname != $function['classname']) {
861 $dbfunction->classname = $function['classname'];
862 $update = true;
864 if ($dbfunction->methodname != $function['methodname']) {
865 $dbfunction->methodname = $function['methodname'];
866 $update = true;
868 if ($dbfunction->classpath != $function['classpath']) {
869 $dbfunction->classpath = $function['classpath'];
870 $update = true;
872 $functioncapabilities = key_exists('capabilities', $function)?$function['capabilities']:'';
873 if ($dbfunction->capabilities != $functioncapabilities) {
874 $dbfunction->capabilities = $functioncapabilities;
875 $update = true;
877 if ($update) {
878 $DB->update_record('external_functions', $dbfunction);
881 foreach ($functions as $fname => $function) {
882 $dbfunction = new stdClass();
883 $dbfunction->name = $fname;
884 $dbfunction->classname = $function['classname'];
885 $dbfunction->methodname = $function['methodname'];
886 $dbfunction->classpath = empty($function['classpath']) ? null : $function['classpath'];
887 $dbfunction->component = $component;
888 $dbfunction->capabilities = key_exists('capabilities', $function)?$function['capabilities']:'';
889 $dbfunction->id = $DB->insert_record('external_functions', $dbfunction);
891 unset($functions);
893 // now deal with services
894 $dbservices = $DB->get_records('external_services', array('component'=>$component));
895 foreach ($dbservices as $dbservice) {
896 if (empty($services[$dbservice->name])) {
897 $DB->delete_records('external_services_functions', array('externalserviceid'=>$dbservice->id));
898 $DB->delete_records('external_services_users', array('externalserviceid'=>$dbservice->id));
899 $DB->delete_records('external_services', array('id'=>$dbservice->id));
900 continue;
902 $service = $services[$dbservice->name];
903 unset($services[$dbservice->name]);
904 $service['enabled'] = empty($service['enabled']) ? 0 : $service['enabled'];
905 $service['requiredcapability'] = empty($service['requiredcapability']) ? null : $service['requiredcapability'];
906 $service['restrictedusers'] = !isset($service['restrictedusers']) ? 1 : $service['restrictedusers'];
908 $update = false;
909 if ($dbservice->enabled != $service['enabled']) {
910 $dbservice->enabled = $service['enabled'];
911 $update = true;
913 if ($dbservice->requiredcapability != $service['requiredcapability']) {
914 $dbservice->requiredcapability = $service['requiredcapability'];
915 $update = true;
917 if ($dbservice->restrictedusers != $service['restrictedusers']) {
918 $dbservice->restrictedusers = $service['restrictedusers'];
919 $update = true;
921 if ($update) {
922 $DB->update_record('external_services', $dbservice);
925 $functions = $DB->get_records('external_services_functions', array('externalserviceid'=>$dbservice->id));
926 foreach ($functions as $function) {
927 $key = array_search($function->functionname, $service['functions']);
928 if ($key === false) {
929 $DB->delete_records('external_services_functions', array('id'=>$function->id));
930 } else {
931 unset($service['functions'][$key]);
934 foreach ($service['functions'] as $fname) {
935 $newf = new stdClass();
936 $newf->externalserviceid = $dbservice->id;
937 $newf->functionname = $fname;
938 $DB->insert_record('external_services_functions', $newf);
940 unset($functions);
942 foreach ($services as $name => $service) {
943 $dbservice = new stdClass();
944 $dbservice->name = $name;
945 $dbservice->enabled = empty($service['enabled']) ? 0 : $service['enabled'];
946 $dbservice->requiredcapability = empty($service['requiredcapability']) ? null : $service['requiredcapability'];
947 $dbservice->restrictedusers = !isset($service['restrictedusers']) ? 1 : $service['restrictedusers'];
948 $dbservice->component = $component;
949 $dbservice->timecreated = time();
950 $dbservice->id = $DB->insert_record('external_services', $dbservice);
951 foreach ($service['functions'] as $fname) {
952 $newf = new stdClass();
953 $newf->externalserviceid = $dbservice->id;
954 $newf->functionname = $fname;
955 $DB->insert_record('external_services_functions', $newf);
961 * Delete all service and external functions information defined in the specified component.
962 * @param string $component name of component (moodle, mod_assignment, etc.)
963 * @return void
965 function external_delete_descriptions($component) {
966 global $DB;
968 $params = array($component);
970 $DB->delete_records_select('external_services_users', "externalserviceid IN (SELECT id FROM {external_services} WHERE component = ?)", $params);
971 $DB->delete_records_select('external_services_functions', "externalserviceid IN (SELECT id FROM {external_services} WHERE component = ?)", $params);
972 $DB->delete_records('external_services', array('component'=>$component));
973 $DB->delete_records('external_functions', array('component'=>$component));
977 * upgrade logging functions
979 function upgrade_handle_exception($ex, $plugin = null) {
980 global $CFG;
982 // rollback everything, we need to log all upgrade problems
983 abort_all_db_transactions();
985 $info = get_exception_info($ex);
987 // First log upgrade error
988 upgrade_log(UPGRADE_LOG_ERROR, $plugin, 'Exception: ' . get_class($ex), $info->message, $info->backtrace);
990 // Always turn on debugging - admins need to know what is going on
991 $CFG->debug = DEBUG_DEVELOPER;
993 default_exception_handler($ex, true, $plugin);
997 * Adds log entry into upgrade_log table
999 * @param int $type UPGRADE_LOG_NORMAL, UPGRADE_LOG_NOTICE or UPGRADE_LOG_ERROR
1000 * @param string $plugin frankenstyle component name
1001 * @param string $info short description text of log entry
1002 * @param string $details long problem description
1003 * @param string $backtrace string used for errors only
1004 * @return void
1006 function upgrade_log($type, $plugin, $info, $details=null, $backtrace=null) {
1007 global $DB, $USER, $CFG;
1009 if (empty($plugin)) {
1010 $plugin = 'core';
1013 list($plugintype, $pluginname) = normalize_component($plugin);
1014 $component = is_null($pluginname) ? $plugintype : $plugintype . '_' . $pluginname;
1016 $backtrace = format_backtrace($backtrace, true);
1018 $currentversion = null;
1019 $targetversion = null;
1021 //first try to find out current version number
1022 if ($plugintype === 'core') {
1023 //main
1024 $currentversion = $CFG->version;
1026 $version = null;
1027 include("$CFG->dirroot/version.php");
1028 $targetversion = $version;
1030 } else if ($plugintype === 'mod') {
1031 try {
1032 $currentversion = $DB->get_field('modules', 'version', array('name'=>$pluginname));
1033 $currentversion = ($currentversion === false) ? null : $currentversion;
1034 } catch (Exception $ignored) {
1036 $cd = get_component_directory($component);
1037 if (file_exists("$cd/version.php")) {
1038 $module = new stdClass();
1039 $module->version = null;
1040 include("$cd/version.php");
1041 $targetversion = $module->version;
1044 } else if ($plugintype === 'block') {
1045 try {
1046 if ($block = $DB->get_record('block', array('name'=>$pluginname))) {
1047 $currentversion = $block->version;
1049 } catch (Exception $ignored) {
1051 $cd = get_component_directory($component);
1052 if (file_exists("$cd/version.php")) {
1053 $plugin = new stdClass();
1054 $plugin->version = null;
1055 include("$cd/version.php");
1056 $targetversion = $plugin->version;
1059 } else {
1060 $pluginversion = get_config($component, 'version');
1061 if (!empty($pluginversion)) {
1062 $currentversion = $pluginversion;
1064 $cd = get_component_directory($component);
1065 if (file_exists("$cd/version.php")) {
1066 $plugin = new stdClass();
1067 $plugin->version = null;
1068 include("$cd/version.php");
1069 $targetversion = $plugin->version;
1073 $log = new stdClass();
1074 $log->type = $type;
1075 $log->plugin = $component;
1076 $log->version = $currentversion;
1077 $log->targetversion = $targetversion;
1078 $log->info = $info;
1079 $log->details = $details;
1080 $log->backtrace = $backtrace;
1081 $log->userid = $USER->id;
1082 $log->timemodified = time();
1083 try {
1084 $DB->insert_record('upgrade_log', $log);
1085 } catch (Exception $ignored) {
1086 // possible during install or 2.0 upgrade
1091 * Marks start of upgrade, blocks any other access to site.
1092 * The upgrade is finished at the end of script or after timeout.
1094 * @global object
1095 * @global object
1096 * @global object
1098 function upgrade_started($preinstall=false) {
1099 global $CFG, $DB, $PAGE, $OUTPUT;
1101 static $started = false;
1103 if ($preinstall) {
1104 ignore_user_abort(true);
1105 upgrade_setup_debug(true);
1107 } else if ($started) {
1108 upgrade_set_timeout(120);
1110 } else {
1111 if (!CLI_SCRIPT and !$PAGE->headerprinted) {
1112 $strupgrade = get_string('upgradingversion', 'admin');
1113 $PAGE->set_pagelayout('maintenance');
1114 upgrade_init_javascript();
1115 $PAGE->set_title($strupgrade.' - Moodle '.$CFG->target_release);
1116 $PAGE->set_heading($strupgrade);
1117 $PAGE->navbar->add($strupgrade);
1118 $PAGE->set_cacheable(false);
1119 echo $OUTPUT->header();
1122 ignore_user_abort(true);
1123 register_shutdown_function('upgrade_finished_handler');
1124 upgrade_setup_debug(true);
1125 set_config('upgraderunning', time()+300);
1126 $started = true;
1131 * Internal function - executed if upgrade interrupted.
1133 function upgrade_finished_handler() {
1134 upgrade_finished();
1138 * Indicates upgrade is finished.
1140 * This function may be called repeatedly.
1142 * @global object
1143 * @global object
1145 function upgrade_finished($continueurl=null) {
1146 global $CFG, $DB, $OUTPUT;
1148 if (!empty($CFG->upgraderunning)) {
1149 unset_config('upgraderunning');
1150 upgrade_setup_debug(false);
1151 ignore_user_abort(false);
1152 if ($continueurl) {
1153 echo $OUTPUT->continue_button($continueurl);
1154 echo $OUTPUT->footer();
1155 die;
1161 * @global object
1162 * @global object
1164 function upgrade_setup_debug($starting) {
1165 global $CFG, $DB;
1167 static $originaldebug = null;
1169 if ($starting) {
1170 if ($originaldebug === null) {
1171 $originaldebug = $DB->get_debug();
1173 if (!empty($CFG->upgradeshowsql)) {
1174 $DB->set_debug(true);
1176 } else {
1177 $DB->set_debug($originaldebug);
1182 * @global object
1184 function print_upgrade_reload($url) {
1185 global $OUTPUT;
1187 echo "<br />";
1188 echo '<div class="continuebutton">';
1189 echo '<a href="'.$url.'" title="'.get_string('reload').'" ><img src="'.$OUTPUT->pix_url('i/reload') . '" alt="" /> '.get_string('reload').'</a>';
1190 echo '</div><br />';
1193 function print_upgrade_separator() {
1194 if (!CLI_SCRIPT) {
1195 echo '<hr />';
1200 * Default start upgrade callback
1201 * @param string $plugin
1202 * @param bool $installation true if installation, false means upgrade
1204 function print_upgrade_part_start($plugin, $installation, $verbose) {
1205 global $OUTPUT;
1206 if (empty($plugin) or $plugin == 'moodle') {
1207 upgrade_started($installation); // does not store upgrade running flag yet
1208 if ($verbose) {
1209 echo $OUTPUT->heading(get_string('coresystem'));
1211 } else {
1212 upgrade_started();
1213 if ($verbose) {
1214 echo $OUTPUT->heading($plugin);
1217 if ($installation) {
1218 if (empty($plugin) or $plugin == 'moodle') {
1219 // no need to log - log table not yet there ;-)
1220 } else {
1221 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Starting plugin installation');
1223 } else {
1224 if (empty($plugin) or $plugin == 'moodle') {
1225 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Starting core upgrade');
1226 } else {
1227 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Starting plugin upgrade');
1233 * Default end upgrade callback
1234 * @param string $plugin
1235 * @param bool $installation true if installation, false means upgrade
1237 function print_upgrade_part_end($plugin, $installation, $verbose) {
1238 global $OUTPUT;
1239 upgrade_started();
1240 if ($installation) {
1241 if (empty($plugin) or $plugin == 'moodle') {
1242 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Core installed');
1243 } else {
1244 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Plugin installed');
1246 } else {
1247 if (empty($plugin) or $plugin == 'moodle') {
1248 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Core upgraded');
1249 } else {
1250 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Plugin upgraded');
1253 if ($verbose) {
1254 echo $OUTPUT->notification(get_string('success'), 'notifysuccess');
1255 print_upgrade_separator();
1260 * Sets up JS code required for all upgrade scripts.
1261 * @global object
1263 function upgrade_init_javascript() {
1264 global $PAGE;
1265 // scroll to the end of each upgrade page so that ppl see either error or continue button,
1266 // no need to scroll continuously any more, it is enough to jump to end once the footer is printed ;-)
1267 $js = "window.scrollTo(0, 5000000);";
1268 $PAGE->requires->js_init_code($js);
1272 * Try to upgrade the given language pack (or current language)
1274 * @param string $lang the code of the language to update, defaults to the current language
1276 function upgrade_language_pack($lang='') {
1277 global $CFG, $OUTPUT;
1279 get_string_manager()->reset_caches();
1281 if (empty($lang)) {
1282 $lang = current_language();
1285 if ($lang == 'en') {
1286 return true; // Nothing to do
1289 upgrade_started(false);
1290 echo $OUTPUT->heading(get_string('langimport', 'admin').': '.$lang);
1292 @mkdir ($CFG->dataroot.'/temp/'); //make it in case it's a fresh install, it might not be there
1293 @mkdir ($CFG->dataroot.'/lang/');
1295 require_once($CFG->libdir.'/componentlib.class.php');
1297 $installer = new lang_installer($lang);
1298 $results = $installer->run();
1299 foreach ($results as $langcode => $langstatus) {
1300 switch ($langstatus) {
1301 case lang_installer::RESULT_DOWNLOADERROR:
1302 echo $OUTPUT->notification($langcode . '.zip');
1303 break;
1304 case lang_installer::RESULT_INSTALLED:
1305 echo $OUTPUT->notification(get_string('langpackinstalled', 'admin', $langcode), 'notifysuccess');
1306 break;
1307 case lang_installer::RESULT_UPTODATE:
1308 echo $OUTPUT->notification(get_string('langpackuptodate', 'admin', $langcode), 'notifysuccess');
1309 break;
1313 get_string_manager()->reset_caches();
1315 print_upgrade_separator();
1319 * Install core moodle tables and initialize
1320 * @param float $version target version
1321 * @param bool $verbose
1322 * @return void, may throw exception
1324 function install_core($version, $verbose) {
1325 global $CFG, $DB;
1327 try {
1328 set_time_limit(600);
1329 print_upgrade_part_start('moodle', true, $verbose); // does not store upgrade running flag
1331 $DB->get_manager()->install_from_xmldb_file("$CFG->libdir/db/install.xml");
1332 upgrade_started(); // we want the flag to be stored in config table ;-)
1334 // set all core default records and default settings
1335 require_once("$CFG->libdir/db/install.php");
1336 xmldb_main_install(); // installs the capabilities too
1338 // store version
1339 upgrade_main_savepoint(true, $version, false);
1341 // Continue with the installation
1342 log_update_descriptions('moodle');
1343 external_update_descriptions('moodle');
1344 events_update_definition('moodle');
1345 message_update_providers('moodle');
1347 // Write default settings unconditionally
1348 admin_apply_default_settings(NULL, true);
1350 print_upgrade_part_end(null, true, $verbose);
1351 } catch (exception $ex) {
1352 upgrade_handle_exception($ex);
1357 * Upgrade moodle core
1358 * @param float $version target version
1359 * @param bool $verbose
1360 * @return void, may throw exception
1362 function upgrade_core($version, $verbose) {
1363 global $CFG;
1365 raise_memory_limit(MEMORY_EXTRA);
1367 require_once($CFG->libdir.'/db/upgrade.php'); // Defines upgrades
1369 try {
1370 // Reset caches before any output
1371 purge_all_caches();
1373 // Upgrade current language pack if we can
1374 if (empty($CFG->skiplangupgrade)) {
1375 if (get_string_manager()->translation_exists(current_language())) {
1376 upgrade_language_pack(false);
1380 print_upgrade_part_start('moodle', false, $verbose);
1382 // one time special local migration pre 2.0 upgrade script
1383 if ($CFG->version < 2007101600) {
1384 $pre20upgradefile = "$CFG->dirroot/local/upgrade_pre20.php";
1385 if (file_exists($pre20upgradefile)) {
1386 set_time_limit(0);
1387 require($pre20upgradefile);
1388 // reset upgrade timeout to default
1389 upgrade_set_timeout();
1393 $result = xmldb_main_upgrade($CFG->version);
1394 if ($version > $CFG->version) {
1395 // store version if not already there
1396 upgrade_main_savepoint($result, $version, false);
1399 // perform all other component upgrade routines
1400 update_capabilities('moodle');
1401 log_update_descriptions('moodle');
1402 external_update_descriptions('moodle');
1403 events_update_definition('moodle');
1404 message_update_providers('moodle');
1406 // Reset caches again, just to be sure
1407 purge_all_caches();
1409 // Clean up contexts - more and more stuff depends on existence of paths and contexts
1410 cleanup_contexts();
1411 create_contexts();
1412 build_context_path();
1413 $syscontext = get_context_instance(CONTEXT_SYSTEM);
1414 mark_context_dirty($syscontext->path);
1416 print_upgrade_part_end('moodle', false, $verbose);
1417 } catch (Exception $ex) {
1418 upgrade_handle_exception($ex);
1423 * Upgrade/install other parts of moodle
1424 * @param bool $verbose
1425 * @return void, may throw exception
1427 function upgrade_noncore($verbose) {
1428 global $CFG;
1430 raise_memory_limit(MEMORY_EXTRA);
1432 // upgrade all plugins types
1433 try {
1434 $plugintypes = get_plugin_types();
1435 foreach ($plugintypes as $type=>$location) {
1436 upgrade_plugins($type, 'print_upgrade_part_start', 'print_upgrade_part_end', $verbose);
1438 } catch (Exception $ex) {
1439 upgrade_handle_exception($ex);
1444 * Checks if the main tables have been installed yet or not.
1445 * @return bool
1447 function core_tables_exist() {
1448 global $DB;
1450 if (!$tables = $DB->get_tables() ) { // No tables yet at all.
1451 return false;
1453 } else { // Check for missing main tables
1454 $mtables = array('config', 'course', 'groupings'); // some tables used in 1.9 and 2.0, preferable something from the start and end of install.xml
1455 foreach ($mtables as $mtable) {
1456 if (!in_array($mtable, $tables)) {
1457 return false;
1460 return true;
1465 * upgrades the mnet rpc definitions for the given component.
1466 * this method doesn't return status, an exception will be thrown in the case of an error
1468 * @param string $component the plugin to upgrade, eg auth_mnet
1470 function upgrade_plugin_mnet_functions($component) {
1471 global $DB, $CFG;
1473 list($type, $plugin) = explode('_', $component);
1474 $path = get_plugin_directory($type, $plugin);
1476 $publishes = array();
1477 $subscribes = array();
1478 if (file_exists($path . '/db/mnet.php')) {
1479 require_once($path . '/db/mnet.php'); // $publishes comes from this file
1481 if (empty($publishes)) {
1482 $publishes = array(); // still need this to be able to disable stuff later
1484 if (empty($subscribes)) {
1485 $subscribes = array(); // still need this to be able to disable stuff later
1488 static $servicecache = array();
1490 // rekey an array based on the rpc method for easy lookups later
1491 $publishmethodservices = array();
1492 $subscribemethodservices = array();
1493 foreach($publishes as $servicename => $service) {
1494 if (is_array($service['methods'])) {
1495 foreach($service['methods'] as $methodname) {
1496 $service['servicename'] = $servicename;
1497 $publishmethodservices[$methodname][] = $service;
1502 // Disable functions that don't exist (any more) in the source
1503 // Should these be deleted? What about their permissions records?
1504 foreach ($DB->get_records('mnet_rpc', array('pluginname'=>$plugin, 'plugintype'=>$type), 'functionname ASC ') as $rpc) {
1505 if (!array_key_exists($rpc->functionname, $publishmethodservices) && $rpc->enabled) {
1506 $DB->set_field('mnet_rpc', 'enabled', 0, array('id' => $rpc->id));
1507 } else if (array_key_exists($rpc->functionname, $publishmethodservices) && !$rpc->enabled) {
1508 $DB->set_field('mnet_rpc', 'enabled', 1, array('id' => $rpc->id));
1512 // reflect all the services we're publishing and save them
1513 require_once($CFG->dirroot . '/lib/zend/Zend/Server/Reflection.php');
1514 static $cachedclasses = array(); // to store reflection information in
1515 foreach ($publishes as $service => $data) {
1516 $f = $data['filename'];
1517 $c = $data['classname'];
1518 foreach ($data['methods'] as $method) {
1519 $dataobject = new stdClass();
1520 $dataobject->plugintype = $type;
1521 $dataobject->pluginname = $plugin;
1522 $dataobject->enabled = 1;
1523 $dataobject->classname = $c;
1524 $dataobject->filename = $f;
1526 if (is_string($method)) {
1527 $dataobject->functionname = $method;
1529 } else if (is_array($method)) { // wants to override file or class
1530 $dataobject->functionname = $method['method'];
1531 $dataobject->classname = $method['classname'];
1532 $dataobject->filename = $method['filename'];
1534 $dataobject->xmlrpcpath = $type.'/'.$plugin.'/'.$dataobject->filename.'/'.$method;
1535 $dataobject->static = false;
1537 require_once($path . '/' . $dataobject->filename);
1538 $functionreflect = null; // slightly different ways to get this depending on whether it's a class method or a function
1539 if (!empty($dataobject->classname)) {
1540 if (!class_exists($dataobject->classname)) {
1541 throw new moodle_exception('installnosuchmethod', 'mnet', '', (object)array('method' => $dataobject->functionname, 'class' => $dataobject->classname));
1543 $key = $dataobject->filename . '|' . $dataobject->classname;
1544 if (!array_key_exists($key, $cachedclasses)) { // look to see if we've already got a reflection object
1545 try {
1546 $cachedclasses[$key] = Zend_Server_Reflection::reflectClass($dataobject->classname);
1547 } catch (Zend_Server_Reflection_Exception $e) { // catch these and rethrow them to something more helpful
1548 throw new moodle_exception('installreflectionclasserror', 'mnet', '', (object)array('method' => $dataobject->functionname, 'class' => $dataobject->classname, 'error' => $e->getMessage()));
1551 $r =& $cachedclasses[$key];
1552 if (!$r->hasMethod($dataobject->functionname)) {
1553 throw new moodle_exception('installnosuchmethod', 'mnet', '', (object)array('method' => $dataobject->functionname, 'class' => $dataobject->classname));
1555 // stupid workaround for zend not having a getMethod($name) function
1556 $ms = $r->getMethods();
1557 foreach ($ms as $m) {
1558 if ($m->getName() == $dataobject->functionname) {
1559 $functionreflect = $m;
1560 break;
1563 $dataobject->static = (int)$functionreflect->isStatic();
1564 } else {
1565 if (!function_exists($dataobject->functionname)) {
1566 throw new moodle_exception('installnosuchfunction', 'mnet', '', (object)array('method' => $dataobject->functionname, 'file' => $dataobject->filename));
1568 try {
1569 $functionreflect = Zend_Server_Reflection::reflectFunction($dataobject->functionname);
1570 } catch (Zend_Server_Reflection_Exception $e) { // catch these and rethrow them to something more helpful
1571 throw new moodle_exception('installreflectionfunctionerror', 'mnet', '', (object)array('method' => $dataobject->functionname, '' => $dataobject->filename, 'error' => $e->getMessage()));
1574 $dataobject->profile = serialize(admin_mnet_method_profile($functionreflect));
1575 $dataobject->help = $functionreflect->getDescription();
1577 if ($record_exists = $DB->get_record('mnet_rpc', array('xmlrpcpath'=>$dataobject->xmlrpcpath))) {
1578 $dataobject->id = $record_exists->id;
1579 $dataobject->enabled = $record_exists->enabled;
1580 $DB->update_record('mnet_rpc', $dataobject);
1581 } else {
1582 $dataobject->id = $DB->insert_record('mnet_rpc', $dataobject, true);
1585 // TODO this API versioning must be reworked, here the recently processed method
1586 // sets the service API which may not be correct
1587 foreach ($publishmethodservices[$dataobject->functionname] as $service) {
1588 if ($serviceobj = $DB->get_record('mnet_service', array('name'=>$service['servicename']))) {
1589 $serviceobj->apiversion = $service['apiversion'];
1590 $DB->update_record('mnet_service', $serviceobj);
1591 } else {
1592 $serviceobj = new stdClass();
1593 $serviceobj->name = $service['servicename'];
1594 $serviceobj->description = empty($service['description']) ? '' : $service['description'];
1595 $serviceobj->apiversion = $service['apiversion'];
1596 $serviceobj->offer = 1;
1597 $serviceobj->id = $DB->insert_record('mnet_service', $serviceobj);
1599 $servicecache[$service['servicename']] = $serviceobj;
1600 if (!$DB->record_exists('mnet_service2rpc', array('rpcid'=>$dataobject->id, 'serviceid'=>$serviceobj->id))) {
1601 $obj = new stdClass();
1602 $obj->rpcid = $dataobject->id;
1603 $obj->serviceid = $serviceobj->id;
1604 $DB->insert_record('mnet_service2rpc', $obj, true);
1609 // finished with methods we publish, now do subscribable methods
1610 foreach($subscribes as $service => $methods) {
1611 if (!array_key_exists($service, $servicecache)) {
1612 if (!$serviceobj = $DB->get_record('mnet_service', array('name' => $service))) {
1613 debugging("TODO: skipping unknown service $service - somebody needs to fix MDL-21993");
1614 continue;
1616 $servicecache[$service] = $serviceobj;
1617 } else {
1618 $serviceobj = $servicecache[$service];
1620 foreach ($methods as $method => $xmlrpcpath) {
1621 if (!$rpcid = $DB->get_field('mnet_remote_rpc', 'id', array('xmlrpcpath'=>$xmlrpcpath))) {
1622 $remoterpc = (object)array(
1623 'functionname' => $method,
1624 'xmlrpcpath' => $xmlrpcpath,
1625 'plugintype' => $type,
1626 'pluginname' => $plugin,
1627 'enabled' => 1,
1629 $rpcid = $remoterpc->id = $DB->insert_record('mnet_remote_rpc', $remoterpc, true);
1631 if (!$DB->record_exists('mnet_remote_service2rpc', array('rpcid'=>$rpcid, 'serviceid'=>$serviceobj->id))) {
1632 $obj = new stdClass();
1633 $obj->rpcid = $rpcid;
1634 $obj->serviceid = $serviceobj->id;
1635 $DB->insert_record('mnet_remote_service2rpc', $obj, true);
1637 $subscribemethodservices[$method][] = $service;
1641 foreach ($DB->get_records('mnet_remote_rpc', array('pluginname'=>$plugin, 'plugintype'=>$type), 'functionname ASC ') as $rpc) {
1642 if (!array_key_exists($rpc->functionname, $subscribemethodservices) && $rpc->enabled) {
1643 $DB->set_field('mnet_remote_rpc', 'enabled', 0, array('id' => $rpc->id));
1644 } else if (array_key_exists($rpc->functionname, $subscribemethodservices) && !$rpc->enabled) {
1645 $DB->set_field('mnet_remote_rpc', 'enabled', 1, array('id' => $rpc->id));
1649 return true;
1653 * Given some sort of Zend Reflection function/method object, return a profile array, ready to be serialized and stored
1655 * @param Zend_Server_Reflection_Function_Abstract $function can be any subclass of this object type
1657 * @return array
1659 function admin_mnet_method_profile(Zend_Server_Reflection_Function_Abstract $function) {
1660 $proto = array_pop($function->getPrototypes());
1661 $ret = $proto->getReturnValue();
1662 $profile = array(
1663 'parameters' => array(),
1664 'return' => array(
1665 'type' => $ret->getType(),
1666 'description' => $ret->getDescription(),
1669 foreach ($proto->getParameters() as $p) {
1670 $profile['parameters'][] = array(
1671 'name' => $p->getName(),
1672 'type' => $p->getType(),
1673 'description' => $p->getDescription(),
1676 return $profile;