3 // This file is part of Moodle - http://moodle.org/
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
19 * Various upgrade/install related functions and classes.
23 * @copyright 1999 onwards Martin Dougiamas (http://dougiamas.com)
24 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
27 /** UPGRADE_LOG_NORMAL = 0 */
28 define('UPGRADE_LOG_NORMAL', 0);
29 /** UPGRADE_LOG_NOTICE = 1 */
30 define('UPGRADE_LOG_NOTICE', 1);
31 /** UPGRADE_LOG_ERROR = 2 */
32 define('UPGRADE_LOG_ERROR', 2);
35 * Exception indicating unknown error during upgrade.
39 * @copyright 1999 onwards Martin Dougiamas (http://dougiamas.com)
40 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
42 class upgrade_exception extends moodle_exception {
43 function __construct($plugin, $version, $debuginfo=NULL) {
45 $a = (object)array('plugin'=>$plugin, 'version'=>$version);
46 parent::__construct('upgradeerror', 'admin', "$CFG->wwwroot/$CFG->admin/index.php", $a, $debuginfo);
51 * Exception indicating downgrade error during upgrade.
55 * @copyright 1999 onwards Martin Dougiamas (http://dougiamas.com)
56 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
58 class downgrade_exception extends moodle_exception {
59 function __construct($plugin, $oldversion, $newversion) {
61 $plugin = is_null($plugin) ? 'moodle' : $plugin;
62 $a = (object)array('plugin'=>$plugin, 'oldversion'=>$oldversion, 'newversion'=>$newversion);
63 parent::__construct('cannotdowngrade', 'debug', "$CFG->wwwroot/$CFG->admin/index.php", $a);
70 * @copyright 1999 onwards Martin Dougiamas (http://dougiamas.com)
71 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
73 class upgrade_requires_exception extends moodle_exception {
74 function __construct($plugin, $pluginversion, $currentmoodle, $requiremoodle) {
77 $a->pluginname = $plugin;
78 $a->pluginversion = $pluginversion;
79 $a->currentmoodle = $currentmoodle;
80 $a->requiremoodle = $requiremoodle;
81 parent::__construct('pluginrequirementsnotmet', 'error', "$CFG->wwwroot/$CFG->admin/index.php", $a);
88 * @copyright 1999 onwards Martin Dougiamas (http://dougiamas.com)
89 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
91 class plugin_defective_exception extends moodle_exception {
92 function __construct($plugin, $details) {
94 parent::__construct('detectedbrokenplugin', 'error', "$CFG->wwwroot/$CFG->admin/index.php", $plugin, $details);
99 * Insert or update log display entry. Entry may already exist.
100 * $module, $action must be unique
103 * @param string $module
104 * @param string $action
105 * @param string $mtable
106 * @param string $field
110 function update_log_display_entry($module, $action, $mtable, $field) {
113 if ($type = $DB->get_record('log_display', array('module'=>$module, 'action'=>$action))) {
114 $type->mtable = $mtable;
115 $type->field = $field;
116 $DB->update_record('log_display', $type);
119 $type = new object();
120 $type->module = $module;
121 $type->action = $action;
122 $type->mtable = $mtable;
123 $type->field = $field;
125 $DB->insert_record('log_display', $type, false);
130 * Upgrade savepoint, marks end of each upgrade block.
131 * It stores new main version, resets upgrade timeout
132 * and abort upgrade if user cancels page loading.
134 * Please do not make large upgrade blocks with lots of operations,
135 * for example when adding tables keep only one table operation per block.
138 * @param bool $result false if upgrade step failed, true if completed
139 * @param string or float $version main version
140 * @param bool $allowabort allow user to abort script execution here
143 function upgrade_main_savepoint($result, $version, $allowabort=true) {
147 throw new upgrade_exception(null, $version);
150 if ($CFG->version >= $version) {
151 // something really wrong is going on in main upgrade script
152 throw new downgrade_exception(null, $CFG->version, $version);
155 set_config('version', $version);
156 upgrade_log(UPGRADE_LOG_NORMAL, null, 'Upgrade savepoint reached');
158 // reset upgrade timeout to default
159 upgrade_set_timeout();
161 // this is a safe place to stop upgrades if user aborts page loading
162 if ($allowabort and connection_aborted()) {
168 * Module upgrade savepoint, marks end of module upgrade blocks
169 * It stores module version, resets upgrade timeout
170 * and abort upgrade if user cancels page loading.
173 * @param bool $result false if upgrade step failed, true if completed
174 * @param string or float $version main version
175 * @param string $modname name of module
176 * @param bool $allowabort allow user to abort script execution here
179 function upgrade_mod_savepoint($result, $version, $modname, $allowabort=true) {
183 throw new upgrade_exception("mod_$modname", $version);
186 if (!$module = $DB->get_record('modules', array('name'=>$modname))) {
187 print_error('modulenotexist', 'debug', '', $modname);
190 if ($module->version >= $version) {
191 // something really wrong is going on in upgrade script
192 throw new downgrade_exception("mod_$modname", $module->version, $version);
194 $module->version = $version;
195 $DB->update_record('modules', $module);
196 upgrade_log(UPGRADE_LOG_NORMAL, "mod_$modname", 'Upgrade savepoint reached');
198 // reset upgrade timeout to default
199 upgrade_set_timeout();
201 // this is a safe place to stop upgrades if user aborts page loading
202 if ($allowabort and connection_aborted()) {
208 * Blocks upgrade savepoint, marks end of blocks upgrade blocks
209 * It stores block version, resets upgrade timeout
210 * and abort upgrade if user cancels page loading.
213 * @param bool $result false if upgrade step failed, true if completed
214 * @param string or float $version main version
215 * @param string $blockname name of block
216 * @param bool $allowabort allow user to abort script execution here
219 function upgrade_block_savepoint($result, $version, $blockname, $allowabort=true) {
223 throw new upgrade_exception("block_$blockname", $version);
226 if (!$block = $DB->get_record('block', array('name'=>$blockname))) {
227 print_error('blocknotexist', 'debug', '', $blockname);
230 if ($block->version >= $version) {
231 // something really wrong is going on in upgrade script
232 throw new downgrade_exception("block_$blockname", $block->version, $version);
234 $block->version = $version;
235 $DB->update_record('block', $block);
236 upgrade_log(UPGRADE_LOG_NORMAL, "block_$blockname", 'Upgrade savepoint reached');
238 // reset upgrade timeout to default
239 upgrade_set_timeout();
241 // this is a safe place to stop upgrades if user aborts page loading
242 if ($allowabort and connection_aborted()) {
248 * Plugins upgrade savepoint, marks end of blocks upgrade blocks
249 * It stores plugin version, resets upgrade timeout
250 * and abort upgrade if user cancels page loading.
252 * @param bool $result false if upgrade step failed, true if completed
253 * @param string or float $version main version
254 * @param string $type name of plugin
255 * @param string $dir location of plugin
256 * @param bool $allowabort allow user to abort script execution here
259 function upgrade_plugin_savepoint($result, $version, $type, $plugin, $allowabort=true) {
260 $component = $type.'_'.$plugin;
263 throw new upgrade_exception($component, $version);
266 $installedversion = get_config($component, 'version');
267 if ($installedversion >= $version) {
268 // Something really wrong is going on in the upgrade script
269 throw new downgrade_exception($component, $installedversion, $version);
271 set_config('version', $version, $component);
272 upgrade_log(UPGRADE_LOG_NORMAL, $component, 'Upgrade savepoint reached');
274 // Reset upgrade timeout to default
275 upgrade_set_timeout();
277 // This is a safe place to stop upgrades if user aborts page loading
278 if ($allowabort and connection_aborted()) {
286 * @param string $type The type of plugins that should be updated (e.g. 'enrol', 'qtype')
289 function upgrade_plugins($type, $startcallback, $endcallback, $verbose) {
293 if ($type === 'mod') {
294 return upgrade_plugins_modules($startcallback, $endcallback, $verbose);
295 } else if ($type === 'block') {
296 return upgrade_plugins_blocks($startcallback, $endcallback, $verbose);
299 $plugs = get_plugin_list($type);
301 foreach ($plugs as $plug=>$fullplug) {
302 $component = $type.'_'.$plug; // standardised plugin name
304 if (!is_readable($fullplug.'/version.php')) {
308 $plugin = new object();
309 require($fullplug.'/version.php'); // defines $plugin with version etc
311 if (empty($plugin->version)) {
312 throw new plugin_defective_exception($component, 'Missing version value in version.php');
315 $plugin->name = $plug;
316 $plugin->fullname = $component;
319 if (!empty($plugin->requires)) {
320 if ($plugin->requires > $CFG->version) {
321 throw new upgrade_requires_exception($component, $plugin->version, $CFG->version, $plugin->requires);
325 // try to recover from interrupted install.php if needed
326 if (file_exists($fullplug.'/db/install.php')) {
327 if (get_config($plugin->fullname, 'installrunning')) {
328 require_once($fullplug.'/db/install.php');
329 $recover_install_function = 'xmldb_'.$plugin->fullname.'_install_recovery';
330 if (function_exists($recover_install_function)) {
331 $startcallback($component, true, $verbose);
332 $recover_install_function();
333 unset_config('installrunning', 'block_'.$plugin->fullname);
334 update_capabilities($component);
335 external_update_descriptions($component);
336 events_update_definition($component);
337 message_update_providers($component);
338 upgrade_plugin_mnet_functions($component);
339 $endcallback($component, true, $verbose);
344 $installedversion = get_config($plugin->fullname, 'version');
345 if (empty($installedversion)) { // new installation
346 $startcallback($component, true, $verbose);
348 /// Install tables if defined
349 if (file_exists($fullplug.'/db/install.xml')) {
350 $DB->get_manager()->install_from_xmldb_file($fullplug.'/db/install.xml');
354 upgrade_plugin_savepoint(true, $plugin->version, $type, $plug, false);
356 /// execute post install file
357 if (file_exists($fullplug.'/db/install.php')) {
358 require_once($fullplug.'/db/install.php');
359 set_config('installrunning', 1, 'block_'.$plugin->fullname);
360 $post_install_function = 'xmldb_'.$plugin->fullname.'_install';;
361 $post_install_function();
362 unset_config('installrunning', 'block_'.$plugin->fullname);
365 /// Install various components
366 update_capabilities($component);
367 external_update_descriptions($component);
368 events_update_definition($component);
369 message_update_providers($component);
370 upgrade_plugin_mnet_functions($component);
372 upgrade_reset_caches();
373 $endcallback($component, true, $verbose);
375 } else if ($installedversion < $plugin->version) { // upgrade
376 /// Run the upgrade function for the plugin.
377 $startcallback($component, false, $verbose);
379 if (is_readable($fullplug.'/db/upgrade.php')) {
380 require_once($fullplug.'/db/upgrade.php'); // defines upgrading function
382 $newupgrade_function = 'xmldb_'.$plugin->fullname.'_upgrade';
383 $result = $newupgrade_function($installedversion);
388 $installedversion = get_config($plugin->fullname, 'version');
389 if ($installedversion < $plugin->version) {
390 // store version if not already there
391 upgrade_plugin_savepoint($result, $plugin->version, $type, $plug, false);
394 /// Upgrade various components
395 update_capabilities($component);
396 external_update_descriptions($component);
397 events_update_definition($component);
398 message_update_providers($component);
399 upgrade_plugin_mnet_functions($component);
401 upgrade_reset_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
416 function upgrade_plugins_modules($startcallback, $endcallback, $verbose) {
419 $mods = get_plugin_list('mod');
421 foreach ($mods as $mod=>$fullmod) {
423 if ($mod == 'NEWMODULE') { // Someone has unzipped the template, ignore it
427 $component = 'mod_'.$mod;
429 if (!is_readable($fullmod.'/version.php')) {
430 throw new plugin_defective_exception($component, 'Missing version.php');
433 $module = new object();
434 require($fullmod .'/version.php'); // defines $module with version etc
436 if (empty($module->version)) {
437 if (isset($module->version)) {
438 // Version is empty but is set - it means its value is 0 or ''. Let us skip such module.
439 // This is intended for developers so they can work on the early stages of the module.
442 throw new plugin_defective_exception($component, 'Missing version value in version.php');
445 if (!empty($module->requires)) {
446 if ($module->requires > $CFG->version) {
447 throw new upgrade_requires_exception($component, $module->version, $CFG->version, $module->requires);
451 $module->name = $mod; // The name MUST match the directory
453 $currmodule = $DB->get_record('modules', array('name'=>$module->name));
455 if (file_exists($fullmod.'/db/install.php')) {
456 if (get_config($module->name, 'installrunning')) {
457 require_once($fullmod.'/db/install.php');
458 $recover_install_function = 'xmldb_'.$module->name.'_install_recovery';
459 if (function_exists($recover_install_function)) {
460 $startcallback($component, true, $verbose);
461 $recover_install_function();
462 unset_config('installrunning', $module->name);
463 // Install various components too
464 update_capabilities($component);
465 external_update_descriptions($component);
466 events_update_definition($component);
467 message_update_providers($component);
468 upgrade_plugin_mnet_functions($component);
469 $endcallback($component, true, $verbose);
474 if (empty($currmodule->version)) {
475 $startcallback($component, true, $verbose);
477 /// Execute install.xml (XMLDB) - must be present in all modules
478 $DB->get_manager()->install_from_xmldb_file($fullmod.'/db/install.xml');
480 /// Add record into modules table - may be needed in install.php already
481 $module->id = $DB->insert_record('modules', $module);
483 /// Post installation hook - optional
484 if (file_exists("$fullmod/db/install.php")) {
485 require_once("$fullmod/db/install.php");
486 // Set installation running flag, we need to recover after exception or error
487 set_config('installrunning', 1, $module->name);
488 $post_install_function = 'xmldb_'.$module->name.'_install';;
489 $post_install_function();
490 unset_config('installrunning', $module->name);
493 /// Install various components
494 update_capabilities($component);
495 external_update_descriptions($component);
496 events_update_definition($component);
497 message_update_providers($component);
498 upgrade_plugin_mnet_functions($component);
500 upgrade_reset_caches();
501 $endcallback($component, true, $verbose);
503 } else if ($currmodule->version < $module->version) {
504 /// If versions say that we need to upgrade but no upgrade files are available, notify and continue
505 $startcallback($component, false, $verbose);
507 if (is_readable($fullmod.'/db/upgrade.php')) {
508 require_once($fullmod.'/db/upgrade.php'); // defines new upgrading function
509 $newupgrade_function = 'xmldb_'.$module->name.'_upgrade';
510 $result = $newupgrade_function($currmodule->version, $module);
515 $currmodule = $DB->get_record('modules', array('name'=>$module->name));
516 if ($currmodule->version < $module->version) {
517 // store version if not already there
518 upgrade_mod_savepoint($result, $module->version, $mod, false);
521 /// Upgrade various components
522 update_capabilities($component);
523 external_update_descriptions($component);
524 events_update_definition($component);
525 message_update_providers($component);
526 upgrade_plugin_mnet_functions($component);
528 upgrade_reset_caches();
529 remove_dir($CFG->dataroot.'/cache', true); // flush cache
531 $endcallback($component, false, $verbose);
533 } else if ($currmodule->version > $module->version) {
534 throw new downgrade_exception($component, $currmodule->version, $module->version);
541 * This function finds all available blocks and install them
542 * into blocks table or do all the upgrade process if newer.
547 function upgrade_plugins_blocks($startcallback, $endcallback, $verbose) {
550 require_once($CFG->dirroot.'/blocks/moodleblock.class.php');
552 $blocktitles = array(); // we do not want duplicate titles
554 //Is this a first install
555 $first_install = null;
557 $blocks = get_plugin_list('block');
559 foreach ($blocks as $blockname=>$fullblock) {
561 if (is_null($first_install)) {
562 $first_install = ($DB->count_records('block_instances') == 0);
565 if ($blockname == 'NEWBLOCK') { // Someone has unzipped the template, ignore it
569 $component = 'block_'.$blockname;
571 if (!is_readable($fullblock.'/version.php')) {
572 throw new plugin_defective_exception('block/'.$blockname, 'Missing version.php file.');
574 $plugin = new object();
575 $plugin->version = NULL;
577 include($fullblock.'/version.php');
580 if (!is_readable($fullblock.'/block_'.$blockname.'.php')) {
581 throw new plugin_defective_exception('block/'.$blockname, 'Missing main block class file.');
583 include_once($fullblock.'/block_'.$blockname.'.php');
585 $classname = 'block_'.$blockname;
587 if (!class_exists($classname)) {
588 throw new plugin_defective_exception($component, 'Can not load main class.');
591 $blockobj = new $classname; // This is what we'll be testing
592 $blocktitle = $blockobj->get_title();
594 // OK, it's as we all hoped. For further tests, the object will do them itself.
595 if (!$blockobj->_self_test()) {
596 throw new plugin_defective_exception($component, 'Self test failed.');
599 $block->name = $blockname; // The name MUST match the directory
600 $block->multiple = $blockobj->instance_allow_multiple() ? 1 : 0;
602 if (empty($block->version)) {
603 throw new plugin_defective_exception($component, 'Missing block version.');
606 $currblock = $DB->get_record('block', array('name'=>$block->name));
608 if (file_exists($fullblock.'/db/install.php')) {
609 if (get_config('block_'.$blockname, 'installrunning')) {
610 require_once($fullblock.'/db/install.php');
611 $recover_install_function = 'xmldb_block_'.$blockname.'_install_recovery';
612 if (function_exists($recover_install_function)) {
613 $startcallback($component, true, $verbose);
614 $recover_install_function();
615 unset_config('installrunning', 'block_'.$blockname);
616 // Install various components
617 update_capabilities($component);
618 external_update_descriptions($component);
619 events_update_definition($component);
620 message_update_providers($component);
621 upgrade_plugin_mnet_functions($component);
622 $endcallback($component, true, $verbose);
627 if (empty($currblock->version)) { // block not installed yet, so install it
628 // If it allows multiples, start with it enabled
630 $conflictblock = array_search($blocktitle, $blocktitles);
631 if ($conflictblock !== false) {
632 // Duplicate block titles are not allowed, they confuse people
633 // AND PHP's associative arrays ;)
634 throw new plugin_defective_exception($component, get_string('blocknameconflict', '', (object)array('name'=>$block->name, 'conflict'=>$conflictblock)));
636 $startcallback($component, true, $verbose);
638 if (file_exists($fullblock.'/db/install.xml')) {
639 $DB->get_manager()->install_from_xmldb_file($fullblock.'/db/install.xml');
641 $block->id = $DB->insert_record('block', $block);
643 if (file_exists($fullblock.'/db/install.php')) {
644 require_once($fullblock.'/db/install.php');
645 // Set installation running flag, we need to recover after exception or error
646 set_config('installrunning', 1, 'block_'.$blockname);
647 $post_install_function = 'xmldb_block_'.$blockname.'_install';;
648 $post_install_function();
649 unset_config('installrunning', 'block_'.$blockname);
652 $blocktitles[$block->name] = $blocktitle;
654 // Install various components
655 update_capabilities($component);
656 external_update_descriptions($component);
657 events_update_definition($component);
658 message_update_providers($component);
659 upgrade_plugin_mnet_functions($component);
661 upgrade_reset_caches();
662 $endcallback($component, true, $verbose);
664 } else if ($currblock->version < $block->version) {
665 $startcallback($component, false, $verbose);
667 if (is_readable($fullblock.'/db/upgrade.php')) {
668 require_once($fullblock.'/db/upgrade.php'); // defines new upgrading function
669 $newupgrade_function = 'xmldb_block_'.$blockname.'_upgrade';
670 $result = $newupgrade_function($currblock->version, $block);
675 $currblock = $DB->get_record('block', array('name'=>$block->name));
676 if ($currblock->version < $block->version) {
677 // store version if not already there
678 upgrade_block_savepoint($result, $block->version, $block->name, false);
681 if ($currblock->cron != $block->cron) {
682 // update cron flag if needed
683 $currblock->cron = $block->cron;
684 $DB->update_record('block', $currblock);
687 // Upgrade various components
688 update_capabilities($component);
689 external_update_descriptions($component);
690 events_update_definition($component);
691 message_update_providers($component);
692 upgrade_plugin_mnet_functions($component);
694 upgrade_reset_caches();
695 $endcallback($component, false, $verbose);
697 } else if ($currblock->version > $block->version) {
698 throw new downgrade_exception($component, $currblock->version, $block->version);
703 // Finally, if we are in the first_install of BLOCKS setup frontpage and admin page blocks
704 if ($first_install) {
705 //Iterate over each course - there should be only site course here now
706 if ($courses = $DB->get_records('course')) {
707 foreach ($courses as $course) {
708 blocks_add_default_course_blocks($course);
712 blocks_add_default_system_blocks();
717 * Web service discovery function used during install and upgrade.
718 * @param string $component name of component (moodle, mod_assignment, etc.)
721 function external_update_descriptions($component) {
724 $defpath = get_component_directory($component).'/db/services.php';
726 if (!file_exists($defpath)) {
727 external_delete_descriptions($component);
732 $functions = array();
736 // update all function fist
737 $dbfunctions = $DB->get_records('external_functions', array('component'=>$component));
738 foreach ($dbfunctions as $dbfunction) {
739 if (empty($functions[$dbfunction->name])) {
740 $DB->delete_records('external_functions', array('id'=>$dbfunction->id));
741 // do not delete functions from external_services_functions, beacuse
742 // we want to notify admins when functions used in custom services disappear
746 $function = $functions[$dbfunction->name];
747 unset($functions[$dbfunction->name]);
748 $function['classpath'] = empty($function['classpath']) ? null : $function['classpath'];
751 if ($dbfunction->classname != $function['classname']) {
752 $dbfunction->classname = $function['classname'];
755 if ($dbfunction->methodname != $function['methodname']) {
756 $dbfunction->methodname = $function['methodname'];
759 if ($dbfunction->classpath != $function['classpath']) {
760 $dbfunction->classpath = $function['classpath'];
764 $DB->update_record('external_functions', $dbfunction);
767 foreach ($functions as $fname => $function) {
768 $dbfunction = new object();
769 $dbfunction->name = $fname;
770 $dbfunction->classname = $function['classname'];
771 $dbfunction->methodname = $function['methodname'];
772 $dbfunction->classpath = empty($function['classpath']) ? null : $function['classpath'];
773 $dbfunction->component = $component;
774 $dbfunction->id = $DB->insert_record('external_functions', $dbfunction);
778 // now deal with services
779 $dbservices = $DB->get_records('external_services', array('component'=>$component));
780 foreach ($dbservices as $dbservice) {
781 if (empty($services[$dbservice->name])) {
782 $DB->delete_records('external_services_functions', array('externalserviceid'=>$dbservice->id));
783 $DB->delete_records('external_services_users', array('externalserviceid'=>$dbservice->id));
784 $DB->delete_records('external_services', array('id'=>$dbservice->id));
787 $service = $services[$dbservice->name];
788 unset($services[$dbservice->name]);
789 $service['enabled'] = empty($service['enabled']) ? 0 : $service['enabled'];
790 $service['requiredcapability'] = empty($service['requiredcapability']) ? null : $service['requiredcapability'];
791 $service['restrictedusers'] = !isset($service['restrictedusers']) ? 1 : $service['restrictedusers'];
794 if ($dbservice->enabled != $service['enabled']) {
795 $dbservice->enabled = $service['enabled'];
798 if ($dbservice->requiredcapability != $service['requiredcapability']) {
799 $dbservice->requiredcapability = $service['requiredcapability'];
802 if ($dbservice->restrictedusers != $service['restrictedusers']) {
803 $dbservice->restrictedusers = $service['restrictedusers'];
807 $DB->update_record('external_services', $dbservice);
810 $functions = $DB->get_records('external_services_functions', array('externalserviceid'=>$dbservice->id));
811 foreach ($functions as $function) {
812 $key = array_search($function->functionname, $service['functions']);
813 if ($key === false) {
814 $DB->delete_records('external_services_functions', array('id'=>$function->id));
816 unset($service['functions'][$key]);
819 foreach ($service['functions'] as $fname) {
820 $newf = new object();
821 $newf->externalserviceid = $dbservice->id;
822 $newf->functionname = $fname;
823 $DB->insert_record('external_services_functions', $newf);
827 foreach ($services as $name => $service) {
828 $dbservice = new object();
829 $dbservice->name = $name;
830 $dbservice->enabled = empty($service['enabled']) ? 0 : $service['enabled'];
831 $dbservice->requiredcapability = empty($service['requiredcapability']) ? null : $service['requiredcapability'];
832 $dbservice->restrictedusers = !isset($service['restrictedusers']) ? 1 : $service['restrictedusers'];
833 $dbservice->component = $component;
834 $dbservice->timecreated = time();
835 $dbservice->id = $DB->insert_record('external_services', $dbservice);
836 foreach ($service['functions'] as $fname) {
837 $newf = new object();
838 $newf->externalserviceid = $dbservice->id;
839 $newf->functionname = $fname;
840 $DB->insert_record('external_services_functions', $newf);
846 * Delete all service and external functions information defined in the specified component.
847 * @param string $component name of component (moodle, mod_assignment, etc.)
850 function external_delete_descriptions($component) {
853 $params = array($component);
855 $DB->delete_records_select('external_services_users', "externalserviceid IN (SELECT id FROM {external_services} WHERE component = ?)", $params);
856 $DB->delete_records_select('external_services_functions', "externalserviceid IN (SELECT id FROM {external_services} WHERE component = ?)", $params);
857 $DB->delete_records('external_services', array('component'=>$component));
858 $DB->delete_records('external_functions', array('component'=>$component));
862 * upgrade logging functions
864 function upgrade_handle_exception($ex, $plugin = null) {
865 // rollback everything, we need to log all upgrade problems
866 abort_all_db_transactions();
868 $info = get_exception_info($ex);
870 // First log upgrade error
871 upgrade_log(UPGRADE_LOG_ERROR, $plugin, 'Exception: ' . get_class($ex), $info->message, $info->backtrace);
873 // Always turn on debugging - admins need to know what is going on
874 $CFG->debug = DEBUG_DEVELOPER;
876 default_exception_handler($ex, true, $plugin);
880 * Adds log entry into upgrade_log table
885 * @param int $type UPGRADE_LOG_NORMAL, UPGRADE_LOG_NOTICE or UPGRADE_LOG_ERROR
886 * @param string $plugin plugin or null if main
887 * @param string $info short description text of log entry
888 * @param string $details long problem description
889 * @param string $backtrace string used for errors only
892 function upgrade_log($type, $plugin, $info, $details=null, $backtrace=null) {
893 global $DB, $USER, $CFG;
895 $plugin = ($plugin==='moodle') ? null : $plugin;
897 $backtrace = format_backtrace($backtrace, true);
901 //first try to find out current version number
902 if (empty($plugin) or $plugin === 'moodle') {
904 $version = $CFG->version;
906 } else if ($plugin === 'local') {
908 $version = $CFG->local_version;
910 } else if (strpos($plugin, 'mod/') === 0) {
912 $modname = substr($plugin, strlen('mod/'));
913 $version = $DB->get_field('modules', 'version', array('name'=>$modname));
914 $version = ($version === false) ? null : $version;
915 } catch (Exception $ignored) {
918 } else if (strpos($plugin, 'block/') === 0) {
920 $blockname = substr($plugin, strlen('block/'));
921 if ($block = $DB->get_record('block', array('name'=>$blockname))) {
922 $version = $block->version;
924 } catch (Exception $ignored) {
928 $pluginversion = get_config(str_replace('/', '_', $plugin), 'version');
929 if (!empty($pluginversion)) {
930 $version = $pluginversion;
936 $log->plugin = $plugin;
937 $log->version = $version;
939 $log->details = $details;
940 $log->backtrace = $backtrace;
941 $log->userid = $USER->id;
942 $log->timemodified = time();
944 $DB->insert_record('upgrade_log', $log);
945 } catch (Exception $ignored) {
946 // possible during install or 2.0 upgrade
951 * Marks start of upgrade, blocks any other access to site.
952 * The upgrade is finished at the end of script or after timeout.
958 function upgrade_started($preinstall=false) {
959 global $CFG, $DB, $PAGE, $OUTPUT;
961 static $started = false;
964 ignore_user_abort(true);
965 upgrade_setup_debug(true);
967 } else if ($started) {
968 upgrade_set_timeout(120);
971 if (!CLI_SCRIPT and !$PAGE->headerprinted) {
972 $strupgrade = get_string('upgradingversion', 'admin');
973 $PAGE->set_pagelayout('maintenance');
974 upgrade_init_javascript();
975 $PAGE->set_title($strupgrade.' - Moodle '.$CFG->target_release);
976 $PAGE->set_heading($strupgrade);
977 $PAGE->navbar->add($strupgrade);
978 $PAGE->set_cacheable(false);
979 echo $OUTPUT->header();
982 ignore_user_abort(true);
983 register_shutdown_function('upgrade_finished_handler');
984 upgrade_setup_debug(true);
985 set_config('upgraderunning', time()+300);
991 * Internal function - executed if upgrade interrupted.
993 function upgrade_finished_handler() {
998 * Indicates upgrade is finished.
1000 * This function may be called repeatedly.
1005 function upgrade_finished($continueurl=null) {
1006 global $CFG, $DB, $OUTPUT;
1008 if (!empty($CFG->upgraderunning)) {
1009 unset_config('upgraderunning');
1010 upgrade_setup_debug(false);
1011 ignore_user_abort(false);
1013 echo $OUTPUT->continue_button($continueurl);
1014 echo $OUTPUT->footer();
1024 function upgrade_setup_debug($starting) {
1027 static $originaldebug = null;
1030 if ($originaldebug === null) {
1031 $originaldebug = $DB->get_debug();
1033 if (!empty($CFG->upgradeshowsql)) {
1034 $DB->set_debug(true);
1037 $DB->set_debug($originaldebug);
1044 function print_upgrade_reload($url) {
1048 echo '<div class="continuebutton">';
1049 echo '<a href="'.$url.'" title="'.get_string('reload').'" ><img src="'.$OUTPUT->pix_url('i/reload') . '" alt="" /> '.get_string('reload').'</a>';
1050 echo '</div><br />';
1053 function print_upgrade_separator() {
1060 * Default start upgrade callback
1061 * @param string $plugin
1062 * @param bool $installation true if installation, false means upgrade
1064 function print_upgrade_part_start($plugin, $installation, $verbose) {
1066 if (empty($plugin) or $plugin == 'moodle') {
1067 upgrade_started($installation); // does not store upgrade running flag yet
1069 echo $OUTPUT->heading(get_string('coresystem'));
1074 echo $OUTPUT->heading($plugin);
1077 if ($installation) {
1078 if (empty($plugin) or $plugin == 'moodle') {
1079 // no need to log - log table not yet there ;-)
1081 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Starting plugin installation');
1084 if (empty($plugin) or $plugin == 'moodle') {
1085 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Starting core upgrade');
1087 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Starting plugin upgrade');
1093 * Default end upgrade callback
1094 * @param string $plugin
1095 * @param bool $installation true if installation, false means upgrade
1097 function print_upgrade_part_end($plugin, $installation, $verbose) {
1100 if ($installation) {
1101 if (empty($plugin) or $plugin == 'moodle') {
1102 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Core installed');
1104 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Plugin installed');
1107 if (empty($plugin) or $plugin == 'moodle') {
1108 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Core upgraded');
1110 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Plugin upgraded');
1114 echo $OUTPUT->notification(get_string('success'), 'notifysuccess');
1115 print_upgrade_separator();
1120 * Sets up JS code required for all upgrade scripts.
1123 function upgrade_init_javascript() {
1125 // scroll to the end of each upgrade page so that ppl see either error or continue button,
1126 // no need to scroll continuously any more, it is enough to jump to end once the footer is printed ;-)
1127 $js = "window.scrollTo(0, 5000000);";
1128 $PAGE->requires->js_init_code($js);
1133 * Try to upgrade the given language pack (or current language)
1135 * @todo hardcoded Moodle version here - shall be provided by version.php or similar script
1137 function upgrade_language_pack($lang='') {
1138 global $CFG, $OUTPUT;
1140 get_string_manager()->reset_caches();
1143 $lang = current_language();
1146 if ($lang == 'en') {
1147 return true; // Nothing to do
1150 upgrade_started(false);
1151 echo $OUTPUT->heading(get_string('langimport', 'admin').': '.$lang);
1153 @mkdir ($CFG->dataroot.'/temp/'); //make it in case it's a fresh install, it might not be there
1154 @mkdir ($CFG->dataroot.'/lang/');
1156 require_once($CFG->libdir.'/componentlib.class.php');
1158 if ($cd = new component_installer('http://download.moodle.org', 'langpack/2.0', $lang.'.zip', 'languages.md5', 'lang')) {
1159 $status = $cd->install(); //returns COMPONENT_(ERROR | UPTODATE | INSTALLED)
1161 if ($status == COMPONENT_INSTALLED) {
1162 remove_dir($CFG->dataroot.'/cache/languages');
1163 if ($parentlang = get_parent_language($lang)) {
1164 if ($cd = new component_installer('http://download.moodle.org', 'langpack/2.0', $parentlang.'.zip', 'languages.md5', 'lang')) {
1168 echo $OUTPUT->notification(get_string('success'), 'notifysuccess');
1172 get_string_manager()->reset_caches();
1174 print_upgrade_separator();
1178 * Install core moodle tables and initialize
1179 * @param float $version target version
1180 * @param bool $verbose
1181 * @return void, may throw exception
1183 function install_core($version, $verbose) {
1187 set_time_limit(600);
1188 print_upgrade_part_start('moodle', true, $verbose); // does not store upgrade running flag
1190 $DB->get_manager()->install_from_xmldb_file("$CFG->libdir/db/install.xml");
1191 upgrade_started(); // we want the flag to be stored in config table ;-)
1193 // set all core default records and default settings
1194 require_once("$CFG->libdir/db/install.php");
1195 xmldb_main_install();
1198 upgrade_main_savepoint(true, $version, false);
1200 // Continue with the installation
1201 events_update_definition('moodle');
1202 message_update_providers('moodle');
1204 // Write default settings unconditionally
1205 admin_apply_default_settings(NULL, true);
1207 print_upgrade_part_end(null, true, $verbose);
1208 } catch (exception $ex) {
1209 upgrade_handle_exception($ex);
1214 * Upgrade moodle core
1215 * @param float $version target version
1216 * @param bool $verbose
1217 * @return void, may throw exception
1219 function upgrade_core($version, $verbose) {
1222 require_once($CFG->libdir.'/db/upgrade.php'); // Defines upgrades
1225 // Reset caches before any output
1226 upgrade_reset_caches();
1227 remove_dir($CFG->dataroot . '/cache', true); // flush cache
1229 // Upgrade current language pack if we can
1230 if (empty($CFG->skiplangupgrade)) {
1231 upgrade_language_pack(false);
1234 print_upgrade_part_start('moodle', false, $verbose);
1236 // one time special local migration pre 2.0 upgrade script
1237 if ($version < 2007101600) {
1238 $pre20upgradefile = "$CFG->dirrot/local/upgrade_pre20.php";
1239 if (file_exists($pre20upgradefile)) {
1241 require($pre20upgradefile);
1242 // reset upgrade timeout to default
1243 upgrade_set_timeout();
1247 $result = xmldb_main_upgrade($CFG->version);
1248 if ($version > $CFG->version) {
1249 // store version if not already there
1250 upgrade_main_savepoint($result, $version, false);
1253 // perform all other component upgrade routines
1254 update_capabilities('moodle');
1255 external_update_descriptions('moodle');
1256 events_update_definition('moodle');
1257 message_update_providers('moodle');
1259 // Reset caches again, just to be sure
1260 upgrade_reset_caches();
1261 remove_dir($CFG->dataroot . '/cache', true); // flush cache
1262 $syscontext = get_context_instance(CONTEXT_SYSTEM);
1263 mark_context_dirty($syscontext->path);
1265 print_upgrade_part_end('moodle', false, $verbose);
1266 } catch (Exception $ex) {
1267 upgrade_handle_exception($ex);
1272 * Upgrade/install other parts of moodle
1273 * @param bool $verbose
1274 * @return void, may throw exception
1276 function upgrade_noncore($verbose) {
1279 // upgrade all plugins types
1281 $plugintypes = get_plugin_types();
1282 foreach ($plugintypes as $type=>$location) {
1283 upgrade_plugins($type, 'print_upgrade_part_start', 'print_upgrade_part_end', $verbose);
1285 } catch (Exception $ex) {
1286 upgrade_handle_exception($ex);
1291 * Checks if the main tables have been installed yet or not.
1294 function core_tables_exist() {
1297 if (!$tables = $DB->get_tables() ) { // No tables yet at all.
1300 } else { // Check for missing main tables
1301 $mtables = array('config', 'course', 'groupings'); // some tables used in 1.9 and 2.0, preferable something from the start and end of install.xml
1302 foreach ($mtables as $mtable) {
1303 if (!in_array($mtable, $tables)) {
1312 * Invalidates browser caches and cached data in temp
1315 function upgrade_reset_caches() {
1316 js_reset_all_caches();
1317 theme_reset_all_caches();
1318 get_string_manager()->reset_caches();
1322 * upgrades the mnet rpc definitions for the given component.
1323 * this method doesn't return status, an exception will be thrown in the case of an error
1325 * @param string $component the plugin to upgrade, eg auth_mnet
1327 function upgrade_plugin_mnet_functions($component) {
1330 list($type, $plugin) = explode('_', $component);
1331 $path = get_plugin_directory($type, $plugin);
1333 if (file_exists($path . '/db/mnet.php')) {
1334 require_once($path . '/db/mnet.php'); // $publishes comes from this file
1336 if (empty($publishes)) {
1337 $publishes = array(); // still need this to be able to disable stuff later
1339 if (empty($subscribes)) {
1340 $subscribes = array(); // still need this to be able to disable stuff later
1343 static $servicecache = array();
1345 // rekey an array based on the rpc method for easy lookups later
1346 $publishmethodservices = array();
1347 $subscribemethodservices = array();
1348 foreach($publishes as $servicename => $service) {
1349 if (is_array($service['methods'])) {
1350 foreach($service['methods'] as $methodname) {
1351 $service['servicename'] = $servicename;
1352 $publishmethodservices[$methodname][] = $service;
1357 // Disable functions that don't exist (any more) in the source
1358 // Should these be deleted? What about their permissions records?
1359 foreach ($DB->get_records('mnet_rpc', array('pluginname'=>$plugin, 'plugintype'=>$type), 'functionname ASC ') as $rpc) {
1360 if (!array_key_exists($rpc->functionname, $publishmethodservices) && $rpc->enabled) {
1361 $DB->set_field('mnet_rpc', 'enabled', 0, array('id' => $rpc->id));
1362 } else if (array_key_exists($rpc->functionname, $publishmethodservices) && !$rpc->enabled) {
1363 $DB->set_field('mnet_rpc', 'enabled', 1, array('id' => $rpc->id));
1367 // reflect all the services we're publishing and save them
1368 require_once($CFG->dirroot . '/lib/zend/Zend/Server/Reflection.php');
1369 static $cachedclasses = array(); // to store reflection information in
1370 foreach ($publishes as $service => $data) {
1371 $f = $data['filename'];
1372 $c = $data['classname'];
1373 foreach ($data['methods'] as $method) {
1374 $dataobject = new stdclass;
1375 $dataobject->plugintype = $type;
1376 $dataobject->pluginname = $plugin;
1377 $dataobject->enabled = 1;
1378 $dataobject->classname = $c;
1379 $dataobject->filename = $f;
1381 if (is_string($method)) {
1382 $dataobject->functionname = $method;
1384 } else if (is_array($method)) { // wants to override file or class
1385 $dataobject->functionname = $method['method'];
1386 $dataobject->classname = $method['classname'];
1387 $dataobject->filename = $method['filename'];
1389 $dataobject->xmlrpcpath = $type.'/'.$plugin.'/'.$dataobject->filename.'/'.$method;
1390 $dataobject->static = false;
1392 require_once($path . '/' . $dataobject->filename);
1393 $functionreflect = null; // slightly different ways to get this depending on whether it's a class method or a function
1394 if (!empty($dataobject->classname)) {
1395 if (!class_exists($dataobject->classname)) {
1396 throw new moodle_exception('installnosuchmethod', 'mnet', '', (object)array('method' => $dataobject->functionname, 'class' => $dataobject->classname));
1398 $key = $dataobject->filename . '|' . $dataobject->classname;
1399 if (!array_key_exists($key, $cachedclasses)) { // look to see if we've already got a reflection object
1401 $cachedclasses[$key] = Zend_Server_Reflection::reflectClass($dataobject->classname);
1402 } catch (Zend_Server_Reflection_Exception $e) { // catch these and rethrow them to something more helpful
1403 throw new moodle_exception('installreflectionclasserror', 'mnet', '', (object)array('method' => $dataobject->functionname, 'class' => $dataobject->classname, 'error' => $e->getMessage()));
1406 $r =& $cachedclasses[$key];
1407 if (!$r->hasMethod($dataobject->functionname)) {
1408 throw new moodle_exception('installnosuchmethod', 'mnet', '', (object)array('method' => $dataobject->functionname, 'class' => $dataobject->classname));
1410 // stupid workaround for zend not having a getMethod($name) function
1411 $ms = $r->getMethods();
1412 foreach ($ms as $m) {
1413 if ($m->getName() == $dataobject->functionname) {
1414 $functionreflect = $m;
1418 $dataobject->static = (int)$functionreflect->isStatic();
1420 if (!function_exists($dataobject->functionname)) {
1421 throw new moodle_exception('installnosuchfunction', 'mnet', '', (object)array('method' => $dataobject->functionname, 'file' => $dataobject->filename));
1424 $functionreflect = Zend_Server_Reflection::reflectFunction($dataobject->functionname);
1425 } catch (Zend_Server_Reflection_Exception $e) { // catch these and rethrow them to something more helpful
1426 throw new moodle_exception('installreflectionfunctionerror', 'mnet', '', (object)array('method' => $dataobject->functionname, '' => $dataobject->filename, 'error' => $e->getMessage()));
1429 $dataobject->profile = serialize(admin_mnet_method_profile($functionreflect));
1430 $dataobject->help = $functionreflect->getDescription();
1432 if ($record_exists = $DB->get_record('mnet_rpc', array('xmlrpcpath'=>$dataobject->xmlrpcpath))) {
1433 $dataobject->id = $record_exists->id;
1434 $dataobject->enabled = $record_exists->enabled;
1435 $DB->update_record('mnet_rpc', $dataobject);
1437 $dataobject->id = $DB->insert_record('mnet_rpc', $dataobject, true);
1440 foreach ($publishmethodservices[$dataobject->functionname] as $service) {
1441 if ($serviceobj = $DB->get_record('mnet_service', array('name'=>$service['servicename']))) {
1442 $serviceobj->apiversion = $service['apiversion'];
1443 $DB->update_record('mnet_service', $serviceobj);
1445 $serviceobj = new stdClass();
1446 $serviceobj->name = $service['servicename'];
1447 $serviceobj->apiversion = $service['apiversion'];
1448 $serviceobj->offer = 1;
1449 $serviceobj->id = $DB->insert_record('mnet_service', $serviceobj);
1451 $servicecache[$service['servicename']] = $serviceobj;
1452 if (!$DB->record_exists('mnet_service2rpc', array('rpcid'=>$dataobject->id, 'serviceid'=>$serviceobj->id))) {
1453 $obj = new stdClass();
1454 $obj->rpcid = $dataobject->id;
1455 $obj->serviceid = $serviceobj->id;
1456 $DB->insert_record('mnet_service2rpc', $obj, true);
1461 // finished with methods we publish, now do subscribable methods
1462 foreach($subscribes as $service => $methods) {
1463 if (!array_key_exists($service, $servicecache)) {
1464 if (!$serviceobj = $DB->get_record('mnet_service', array('name' => $service))) {
1465 debugging("TODO: skipping unknown service $service - somebody needs to fix MDL-21993");
1468 $servicecache[$service] = $serviceobj;
1470 $serviceobj = $servicecache[$service];
1472 foreach ($methods as $method => $xmlrpcpath) {
1473 if (!$rpcid = $DB->get_field('mnet_remote_rpc', 'id', array('xmlrpcpath'=>$xmlrpcpath))) {
1474 $remoterpc = (object)array(
1475 'functionname' => $method,
1476 'xmlrpcpath' => $xmlrpcpath,
1477 'plugintype' => $type,
1478 'pluginname' => $plugin,
1481 $rpcid = $remoterpc->id = $DB->insert_record('mnet_remote_rpc', $remoterpc, true);
1483 if (!$DB->record_exists('mnet_remote_service2rpc', array('rpcid'=>$rpcid, 'serviceid'=>$serviceobj->id))) {
1484 $obj = new stdClass();
1485 $obj->rpcid = $rpcid;
1486 $obj->serviceid = $serviceobj->id;
1487 $DB->insert_record('mnet_remote_service2rpc', $obj, true);
1489 $subscribemethodservices[$method][] = $service;
1493 foreach ($DB->get_records('mnet_remote_rpc', array('pluginname'=>$plugin, 'plugintype'=>$type), 'functionname ASC ') as $rpc) {
1494 if (!array_key_exists($rpc->functionname, $subscribemethodservices) && $rpc->enabled) {
1495 $DB->set_field('mnet_remote_rpc', 'enabled', 0, array('id' => $rpc->id));
1496 } else if (array_key_exists($rpc->functionname, $subscribemethodservices) && !$rpc->enabled) {
1497 $DB->set_field('mnet_remote_rpc', 'enabled', 1, array('id' => $rpc->id));
1505 * Given some sort of Zend Reflection function/method object, return a profile array, ready to be serialized and stored
1507 * @param Zend_Server_Reflection_Function_Abstract $function can be any subclass of this object type
1511 function admin_mnet_method_profile(Zend_Server_Reflection_Function_Abstract $function) {
1512 $proto = array_pop($function->getPrototypes());
1513 $ret = $proto->getReturnValue();
1515 'parameters' => array(),
1517 'type' => $ret->getType(),
1518 'description' => $ret->getDescription(),
1521 foreach ($proto->getParameters() as $p) {
1522 $profile['parameters'][] = array(
1523 'name' => $p->getName(),
1524 'type' => $p->getType(),
1525 'description' => $p->getDescription(),