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) {
45 $a = (object)array('plugin'=>$plugin, 'version'=>$version);
46 parent::__construct('upgradeerror', 'admin', "$CFG->wwwroot/$CFG->admin/index.php", $a);
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 inteded 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') == 0);
565 if ($blockname == 'NEWBLOCK') { // Someone has unzipped the template, ignore it
569 $component = 'block_'.$blockname;
571 if (!is_readable($fullblock.'/block_'.$blockname.'.php')) {
572 throw new plugin_defective_exception('block/'.$blockname, 'Missing main block class file.');
574 require_once($fullblock.'/block_'.$blockname.'.php');
576 $classname = 'block_'.$blockname;
578 if (!class_exists($classname)) {
579 throw new plugin_defective_exception($component, 'Can not load main class.');
582 $blockobj = new $classname; // This is what we 'll be testing
583 $blocktitle = $blockobj->get_title();
585 // OK, it's as we all hoped. For further tests, the object will do them itself.
586 if (!$blockobj->_self_test()) {
587 throw new plugin_defective_exception($component, 'Self test failed.');
590 $block = new object(); // This may be used to update the db below
591 $block->name = $blockname; // The name MUST match the directory
592 $block->version = $blockobj->get_version();
593 $block->cron = !empty($blockobj->cron) ? $blockobj->cron : 0;
594 $block->multiple = $blockobj->instance_allow_multiple() ? 1 : 0;
596 if (empty($block->version)) {
597 throw new plugin_defective_exception($component, 'Missing block version.');
600 $currblock = $DB->get_record('block', array('name'=>$block->name));
602 if (file_exists($fullblock.'/db/install.php')) {
603 if (get_config('block_'.$blockname, 'installrunning')) {
604 require_once($fullblock.'/db/install.php');
605 $recover_install_function = 'xmldb_block_'.$blockname.'_install_recovery';
606 if (function_exists($recover_install_function)) {
607 $startcallback($component, true, $verbose);
608 $recover_install_function();
609 unset_config('installrunning', 'block_'.$blockname);
610 // Install various components
611 update_capabilities($component);
612 external_update_descriptions($component);
613 events_update_definition($component);
614 message_update_providers($component);
615 upgrade_plugin_mnet_functions($component);
616 $endcallback($component, true, $verbose);
621 if (empty($currblock->version)) { // block not installed yet, so install it
622 // If it allows multiples, start with it enabled
624 $conflictblock = array_search($blocktitle, $blocktitles);
625 if ($conflictblock !== false) {
626 // Duplicate block titles are not allowed, they confuse people
627 // AND PHP's associative arrays ;)
628 throw new plugin_defective_exception($component, get_string('blocknameconflict', '', (object)array('name'=>$block->name, 'conflict'=>$conflictblock)));
630 $startcallback($component, true, $verbose);
632 if (file_exists($fullblock.'/db/install.xml')) {
633 $DB->get_manager()->install_from_xmldb_file($fullblock.'/db/install.xml');
635 $block->id = $DB->insert_record('block', $block);
637 if (file_exists($fullblock.'/db/install.php')) {
638 require_once($fullblock.'/db/install.php');
639 // Set installation running flag, we need to recover after exception or error
640 set_config('installrunning', 1, 'block_'.$blockname);
641 $post_install_function = 'xmldb_block_'.$blockname.'_install';;
642 $post_install_function();
643 unset_config('installrunning', 'block_'.$blockname);
646 $blocktitles[$block->name] = $blocktitle;
648 // Install various components
649 update_capabilities($component);
650 external_update_descriptions($component);
651 events_update_definition($component);
652 message_update_providers($component);
653 upgrade_plugin_mnet_functions($component);
655 upgrade_reset_caches();
656 $endcallback($component, true, $verbose);
658 } else if ($currblock->version < $block->version) {
659 $startcallback($component, false, $verbose);
661 if (is_readable($fullblock.'/db/upgrade.php')) {
662 require_once($fullblock.'/db/upgrade.php'); // defines new upgrading function
663 $newupgrade_function = 'xmldb_block_'.$blockname.'_upgrade';
664 $result = $newupgrade_function($currblock->version, $block);
669 $currblock = $DB->get_record('block', array('name'=>$block->name));
670 if ($currblock->version < $block->version) {
671 // store version if not already there
672 upgrade_block_savepoint($result, $block->version, $block->name, false);
675 if ($currblock->cron != $block->cron) {
676 // update cron flag if needed
677 $currblock->cron = $block->cron;
678 $DB->update_record('block', $currblock);
681 // Upgrade various componebts
682 update_capabilities($component);
683 external_update_descriptions($component);
684 events_update_definition($component);
685 message_update_providers($component);
686 upgrade_plugin_mnet_functions($component);
688 upgrade_reset_caches();
689 $endcallback($component, false, $verbose);
691 } else if ($currblock->version > $block->version) {
692 throw new downgrade_exception($component, $currblock->version, $block->version);
697 // Finally, if we are in the first_install of BLOCKS setup frontpage and admin page blocks
698 if ($first_install) {
699 //Iterate over each course - there should be only site course here now
700 if ($courses = $DB->get_records('course')) {
701 foreach ($courses as $course) {
702 blocks_add_default_course_blocks($course);
706 blocks_add_default_system_blocks();
711 * Web service discovery function used during install and upgrade.
712 * @param string $component name of component (moodle, mod_assignment, etc.)
715 function external_update_descriptions($component) {
718 $defpath = get_component_directory($component).'/db/services.php';
720 if (!file_exists($defpath)) {
721 external_delete_descriptions($component);
726 $functions = array();
730 // update all function fist
731 $dbfunctions = $DB->get_records('external_functions', array('component'=>$component));
732 foreach ($dbfunctions as $dbfunction) {
733 if (empty($functions[$dbfunction->name])) {
734 $DB->delete_records('external_functions', array('id'=>$dbfunction->id));
735 // do not delete functions from external_services_functions, beacuse
736 // we want to notify admins when functions used in custom services disappear
740 $function = $functions[$dbfunction->name];
741 unset($functions[$dbfunction->name]);
742 $function['classpath'] = empty($function['classpath']) ? null : $function['classpath'];
745 if ($dbfunction->classname != $function['classname']) {
746 $dbfunction->classname = $function['classname'];
749 if ($dbfunction->methodname != $function['methodname']) {
750 $dbfunction->methodname = $function['methodname'];
753 if ($dbfunction->classpath != $function['classpath']) {
754 $dbfunction->classpath = $function['classpath'];
758 $DB->update_record('external_functions', $dbfunction);
761 foreach ($functions as $fname => $function) {
762 $dbfunction = new object();
763 $dbfunction->name = $fname;
764 $dbfunction->classname = $function['classname'];
765 $dbfunction->methodname = $function['methodname'];
766 $dbfunction->classpath = empty($function['classpath']) ? null : $function['classpath'];
767 $dbfunction->component = $component;
768 $dbfunction->id = $DB->insert_record('external_functions', $dbfunction);
772 // now deal with services
773 $dbservices = $DB->get_records('external_services', array('component'=>$component));
774 foreach ($dbservices as $dbservice) {
775 if (empty($services[$dbservice->name])) {
776 $DB->delete_records('external_services_functions', array('externalserviceid'=>$dbservice->id));
777 $DB->delete_records('external_services_users', array('externalserviceid'=>$dbservice->id));
778 $DB->delete_records('external_services', array('id'=>$dbservice->id));
781 $service = $services[$dbservice->name];
782 unset($services[$dbservice->name]);
783 $service['enabled'] = empty($service['enabled']) ? 0 : $service['enabled'];
784 $service['requiredcapability'] = empty($service['requiredcapability']) ? null : $service['requiredcapability'];
785 $service['restrictedusers'] = !isset($service['restrictedusers']) ? 1 : $service['restrictedusers'];
788 if ($dbservice->enabled != $service['enabled']) {
789 $dbservice->enabled = $service['enabled'];
792 if ($dbservice->requiredcapability != $service['requiredcapability']) {
793 $dbservice->requiredcapability = $service['requiredcapability'];
796 if ($dbservice->restrictedusers != $service['restrictedusers']) {
797 $dbservice->restrictedusers = $service['restrictedusers'];
801 $DB->update_record('external_services', $dbservice);
804 $functions = $DB->get_records('external_services_functions', array('externalserviceid'=>$dbservice->id));
805 foreach ($functions as $function) {
806 $key = array_search($function->functionname, $service['functions']);
807 if ($key === false) {
808 $DB->delete_records('external_services_functions', array('id'=>$function->id));
810 unset($service['functions'][$key]);
813 foreach ($service['functions'] as $fname) {
814 $newf = new object();
815 $newf->externalserviceid = $dbservice->id;
816 $newf->functionname = $fname;
817 $DB->insert_record('external_services_functions', $newf);
821 foreach ($services as $name => $service) {
822 $dbservice = new object();
823 $dbservice->name = $name;
824 $dbservice->enabled = empty($service['enabled']) ? 0 : $service['enabled'];
825 $dbservice->requiredcapability = empty($service['requiredcapability']) ? null : $service['requiredcapability'];
826 $dbservice->restrictedusers = !isset($service['restrictedusers']) ? 1 : $service['restrictedusers'];
827 $dbservice->component = $component;
828 $dbservice->timecreated = time();
829 $dbservice->id = $DB->insert_record('external_services', $dbservice);
830 foreach ($service['functions'] as $fname) {
831 $newf = new object();
832 $newf->externalserviceid = $dbservice->id;
833 $newf->functionname = $fname;
834 $DB->insert_record('external_services_functions', $newf);
840 * Delete all service and external functions information defined in the specified compoment.
841 * @param string $component name of component (moodle, mod_assignment, etc.)
844 function external_delete_descriptions($component) {
847 $params = array($component);
849 $DB->delete_records_select('external_services_users', "externalserviceid IN (SELECT id FROM {external_services} WHERE component = ?)", $params);
850 $DB->delete_records_select('external_services_functions', "externalserviceid IN (SELECT id FROM {external_services} WHERE component = ?)", $params);
851 $DB->delete_records('external_services', array('component'=>$component));
852 $DB->delete_records('external_functions', array('component'=>$component));
856 * upgrade logging functions
858 function upgrade_handle_exception($ex, $plugin = null) {
859 // rollback everything, we need to log all upgrade problems
860 abort_all_db_transactions();
862 $info = get_exception_info($ex);
864 // First log upgrade error
865 upgrade_log(UPGRADE_LOG_ERROR, $plugin, 'Exception: ' . get_class($ex), $info->message, $info->backtrace);
867 // Always turn on debugging - admins need to know what is going on
868 $CFG->debug = DEBUG_DEVELOPER;
870 default_exception_handler($ex, true, $plugin);
874 * Adds log entry into upgrade_log table
879 * @param int $type UPGRADE_LOG_NORMAL, UPGRADE_LOG_NOTICE or UPGRADE_LOG_ERROR
880 * @param string $plugin plugin or null if main
881 * @param string $info short description text of log entry
882 * @param string $details long problem description
883 * @param string $backtrace string used for errors only
886 function upgrade_log($type, $plugin, $info, $details=null, $backtrace=null) {
887 global $DB, $USER, $CFG;
889 $plugin = ($plugin==='moodle') ? null : $plugin;
891 $backtrace = format_backtrace($backtrace, true);
895 //first try to find out current version number
896 if (empty($plugin) or $plugin === 'moodle') {
898 $version = $CFG->version;
900 } else if ($plugin === 'local') {
902 $version = $CFG->local_version;
904 } else if (strpos($plugin, 'mod/') === 0) {
906 $modname = substr($plugin, strlen('mod/'));
907 $version = $DB->get_field('modules', 'version', array('name'=>$modname));
908 $version = ($version === false) ? null : $version;
909 } catch (Exception $ignored) {
912 } else if (strpos($plugin, 'block/') === 0) {
914 $blockname = substr($plugin, strlen('block/'));
915 if ($block = $DB->get_record('block', array('name'=>$blockname))) {
916 $version = $block->version;
918 } catch (Exception $ignored) {
922 $pluginversion = get_config(str_replace('/', '_', $plugin), 'version');
923 if (!empty($pluginversion)) {
924 $version = $pluginversion;
930 $log->plugin = $plugin;
931 $log->version = $version;
933 $log->details = $details;
934 $log->backtrace = $backtrace;
935 $log->userid = $USER->id;
936 $log->timemodified = time();
938 $DB->insert_record('upgrade_log', $log);
939 } catch (Exception $ignored) {
940 // possible during install or 2.0 upgrade
945 * Marks start of upgrade, blocks any other access to site.
946 * The upgrade is finished at the end of script or after timeout.
952 function upgrade_started($preinstall=false) {
953 global $CFG, $DB, $PAGE, $OUTPUT;
955 static $started = false;
958 ignore_user_abort(true);
959 upgrade_setup_debug(true);
961 } else if ($started) {
962 upgrade_set_timeout(120);
965 if (!CLI_SCRIPT and !$PAGE->headerprinted) {
966 $strupgrade = get_string('upgradingversion', 'admin');
967 $PAGE->set_pagelayout('maintenance');
968 upgrade_init_javascript();
969 $PAGE->set_title($strupgrade.' - Moodle '.$CFG->target_release);
970 $PAGE->set_heading($strupgrade);
971 $PAGE->navbar->add($strupgrade);
972 $PAGE->set_cacheable(false);
973 echo $OUTPUT->header();
976 ignore_user_abort(true);
977 register_shutdown_function('upgrade_finished_handler');
978 upgrade_setup_debug(true);
979 set_config('upgraderunning', time()+300);
985 * Internal function - executed if upgrade interruped.
987 function upgrade_finished_handler() {
992 * Indicates upgrade is finished.
994 * This function may be called repeatedly.
999 function upgrade_finished($continueurl=null) {
1000 global $CFG, $DB, $OUTPUT;
1002 if (!empty($CFG->upgraderunning)) {
1003 unset_config('upgraderunning');
1004 upgrade_setup_debug(false);
1005 ignore_user_abort(false);
1007 echo $OUTPUT->continue_button($continueurl);
1008 echo $OUTPUT->footer();
1018 function upgrade_setup_debug($starting) {
1021 static $originaldebug = null;
1024 if ($originaldebug === null) {
1025 $originaldebug = $DB->get_debug();
1027 if (!empty($CFG->upgradeshowsql)) {
1028 $DB->set_debug(true);
1031 $DB->set_debug($originaldebug);
1038 function print_upgrade_reload($url) {
1042 echo '<div class="continuebutton">';
1043 echo '<a href="'.$url.'" title="'.get_string('reload').'" ><img src="'.$OUTPUT->pix_url('i/reload') . '" alt="" /> '.get_string('reload').'</a>';
1044 echo '</div><br />';
1047 function print_upgrade_separator() {
1054 * Default start upgrade callback
1055 * @param string $plugin
1056 * @param bool $installation true if installation, false menas upgrade
1058 function print_upgrade_part_start($plugin, $installation, $verbose) {
1060 if (empty($plugin) or $plugin == 'moodle') {
1061 upgrade_started($installation); // does not store upgrade running flag yet
1063 echo $OUTPUT->heading(get_string('coresystem'));
1068 echo $OUTPUT->heading($plugin);
1071 if ($installation) {
1072 if (empty($plugin) or $plugin == 'moodle') {
1073 // no need to log - log table not yet there ;-)
1075 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Starting plugin installation');
1078 if (empty($plugin) or $plugin == 'moodle') {
1079 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Starting core upgrade');
1081 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Starting plugin upgrade');
1087 * Default end upgrade callback
1088 * @param string $plugin
1089 * @param bool $installation true if installation, false menas upgrade
1091 function print_upgrade_part_end($plugin, $installation, $verbose) {
1094 if ($installation) {
1095 if (empty($plugin) or $plugin == 'moodle') {
1096 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Core installed');
1098 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Plugin installed');
1101 if (empty($plugin) or $plugin == 'moodle') {
1102 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Core upgraded');
1104 upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Plugin upgraded');
1108 echo $OUTPUT->notification(get_string('success'), 'notifysuccess');
1109 print_upgrade_separator();
1114 * Sets up JS code required for all ugprade scripts.
1117 function upgrade_init_javascript() {
1119 // scroll to the end of each upgrade page so that ppl see either error or continue button,
1120 // no need to scroll continuously any more, it is enough to jump to end once the footer is printed ;-)
1121 $js = "window.scrollTo(0, 5000000);";
1122 $PAGE->requires->js_init_code($js);
1127 * Try to upgrade the given language pack (or current language)
1130 function upgrade_language_pack($lang='') {
1131 global $CFG, $OUTPUT;
1134 $lang = current_language();
1137 if ($lang == 'en_utf8') {
1138 return true; // Nothing to do
1141 upgrade_started(false);
1142 echo $OUTPUT->heading(get_string('langimport', 'admin').': '.$lang);
1144 @mkdir ($CFG->dataroot.'/temp/'); //make it in case it's a fresh install, it might not be there
1145 @mkdir ($CFG->dataroot.'/lang/');
1147 require_once($CFG->libdir.'/componentlib.class.php');
1149 if ($cd = new component_installer('http://download.moodle.org', 'lang16', $lang.'.zip', 'languages.md5', 'lang')) {
1150 $status = $cd->install(); //returns COMPONENT_(ERROR | UPTODATE | INSTALLED)
1152 if ($status == COMPONENT_INSTALLED) {
1153 @unlink($CFG->dataroot.'/cache/languages');
1154 if ($parentlang = get_parent_language($lang)) {
1155 if ($cd = new component_installer('http://download.moodle.org', 'lang16', $parentlang.'.zip', 'languages.md5', 'lang')) {
1159 echo $OUTPUT->notification(get_string('success'), 'notifysuccess');
1163 print_upgrade_separator();
1167 * Install core moodle tables and initialize
1168 * @param float $version target version
1169 * @param bool $verbose
1170 * @return void, may throw exception
1172 function install_core($version, $verbose) {
1176 set_time_limit(600);
1177 print_upgrade_part_start('moodle', true, $verbose); // does not store upgrade running flag
1179 $DB->get_manager()->install_from_xmldb_file("$CFG->libdir/db/install.xml");
1180 upgrade_started(); // we want the flag to be stored in config table ;-)
1182 // set all core default records and default settings
1183 require_once("$CFG->libdir/db/install.php");
1184 xmldb_main_install();
1187 upgrade_main_savepoint(true, $version, false);
1189 // Continue with the instalation
1190 events_update_definition('moodle');
1191 message_update_providers('moodle');
1193 // Write default settings unconditionlly
1194 admin_apply_default_settings(NULL, true);
1196 print_upgrade_part_end(null, true, $verbose);
1197 } catch (exception $ex) {
1198 upgrade_handle_exception($ex);
1203 * Upgrade moodle core
1204 * @param float $version target version
1205 * @param bool $verbose
1206 * @return void, may throw exception
1208 function upgrade_core($version, $verbose) {
1211 require_once($CFG->libdir.'/db/upgrade.php'); // Defines upgrades
1214 // Upgrade current language pack if we can
1215 if (empty($CFG->skiplangupgrade)) {
1216 upgrade_language_pack(false);
1219 print_upgrade_part_start('moodle', false, $verbose);
1221 // one time special local migration pre 2.0 upgrade script
1222 if ($version < 2007101600) {
1223 $pre20upgradefile = "$CFG->dirrot/local/upgrade_pre20.php";
1224 if (file_exists($pre20upgradefile)) {
1226 require($pre20upgradefile);
1227 // reset upgrade timeout to default
1228 upgrade_set_timeout();
1232 $result = xmldb_main_upgrade($CFG->version);
1233 if ($version > $CFG->version) {
1234 // store version if not already there
1235 upgrade_main_savepoint($result, $version, false);
1238 // perform all other component upgrade routines
1239 update_capabilities('moodle');
1240 external_update_descriptions('moodle');
1241 events_update_definition('moodle');
1242 message_update_providers('moodle');
1244 upgrade_reset_caches();
1245 remove_dir($CFG->dataroot . '/cache', true); // flush cache
1247 print_upgrade_part_end('moodle', false, $verbose);
1248 } catch (Exception $ex) {
1249 upgrade_handle_exception($ex);
1254 * Upgrade/install other parts of moodle
1255 * @param bool $verbose
1256 * @return void, may throw exception
1258 function upgrade_noncore($verbose) {
1261 // upgrade all plugins types
1263 $plugintypes = get_plugin_types();
1264 foreach ($plugintypes as $type=>$location) {
1265 upgrade_plugins($type, 'print_upgrade_part_start', 'print_upgrade_part_end', $verbose);
1267 } catch (Exception $ex) {
1268 upgrade_handle_exception($ex);
1273 * Checks if the main tables have been installed yet or not.
1276 function core_tables_exist() {
1279 if (!$tables = $DB->get_tables() ) { // No tables yet at all.
1282 } else { // Check for missing main tables
1283 $mtables = array('config', 'course', 'groupings'); // some tables used in 1.9 and 2.0, preferable something from the start and end of install.xml
1284 foreach ($mtables as $mtable) {
1285 if (!in_array($mtable, $tables)) {
1294 * Invalidates browser caches and cached data in temp
1297 function upgrade_reset_caches() {
1298 js_reset_all_caches();
1299 theme_reset_all_caches();
1303 * upgrades the mnet rpc definitions for the given component.
1304 * this method doesn't return status, an exception will be thrown in the case of an error
1306 * @param string $component the plugin to upgrade, eg auth_mnet
1308 function upgrade_plugin_mnet_functions($component) {
1311 list($type, $plugin) = explode('_', $component);
1312 $path = get_plugin_directory($type, $plugin);
1314 if (file_exists($path . '/db/mnet.php')) {
1315 require_once($path . '/db/mnet.php'); // $publishes comes from this file
1317 if (empty($publishes)) {
1318 $publishes = array(); // still need this to be able to disable stuff later
1320 if (empty($subscribes)) {
1321 $subscribes = array(); // still need this to be able to disable stuff later
1324 static $servicecache = array();
1326 // rekey an array based on the rpc method for easy lookups later
1327 $publishmethodservices = array();
1328 $subscribemethodservices = array();
1329 foreach($publishes as $servicename => $service) {
1330 if (is_array($service['methods'])) {
1331 foreach($service['methods'] as $methodname) {
1332 $service['servicename'] = $servicename;
1333 $publishmethodservices[$methodname][] = $service;
1338 // Disable functions that don't exist (any more) in the source
1339 // Should these be deleted? What about their permissions records?
1340 foreach ($DB->get_records('mnet_rpc', array('pluginname'=>$plugin, 'plugintype'=>$type), 'functionname ASC ') as $rpc) {
1341 if (!array_key_exists($rpc->functionname, $publishmethodservices) && $rpc->enabled) {
1342 $DB->set_field('mnet_rpc', 'enabled', 0, array('id' => $rpc->id));
1343 } else if (array_key_exists($rpc->functionname, $publishmethodservices) && !$rpc->enabled) {
1344 $DB->set_field('mnet_rpc', 'enabled', 1, array('id' => $rpc->id));
1348 // reflect all the services we're publishing and save them
1349 require_once($CFG->dirroot . '/lib/zend/Zend/Server/Reflection.php');
1350 static $cachedclasses = array(); // to store reflection information in
1351 foreach ($publishes as $service => $data) {
1352 $f = $data['filename'];
1353 $c = $data['classname'];
1354 foreach ($data['methods'] as $method) {
1355 $dataobject = new stdclass;
1356 $dataobject->plugintype = $type;
1357 $dataobject->pluginname = $plugin;
1358 $dataobject->enabled = 1;
1359 $dataobject->classname = $c;
1360 $dataobject->filename = $f;
1362 if (is_string($method)) {
1363 $dataobject->functionname = $method;
1365 } else if (is_array($method)) { // wants to override file or class
1366 $dataobject->functionname = $method['method'];
1367 $dataobject->classname = $method['classname'];
1368 $dataobject->filename = $method['filename'];
1370 $dataobject->xmlrpcpath = $type.'/'.$plugin.'/'.$dataobject->filename.'/'.$method;
1371 $dataobject->static = false;
1373 require_once($path . '/' . $dataobject->filename);
1374 $functionreflect = null; // slightly different ways to get this depending on whether it's a class method or a function
1375 if (!empty($dataobject->classname)) {
1376 if (!class_exists($dataobject->classname)) {
1377 throw new moodle_exception('installnosuchmethod', 'mnet', '', (object)array('method' => $dataobject->functionname, 'class' => $dataobject->classname));
1379 $key = $dataobject->filename . '|' . $dataobject->classname;
1380 if (!array_key_exists($key, $cachedclasses)) { // look to see if we've already got a reflection object
1382 $cachedclasses[$key] = Zend_Server_Reflection::reflectClass($dataobject->classname);
1383 } catch (Zend_Server_Reflection_Exception $e) { // catch these and rethrow them to something more helpful
1384 throw new moodle_exception('installreflectionclasserror', 'mnet', '', (object)array('method' => $dataobject->functionname, 'class' => $dataobject->classname, 'error' => $e->getMessage()));
1387 $r =& $cachedclasses[$key];
1388 if (!$r->hasMethod($dataobject->functionname)) {
1389 throw new moodle_exception('installnosuchmethod', 'mnet', '', (object)array('method' => $dataobject->functionname, 'class' => $dataobject->classname));
1391 // stupid workaround for zend not having a getMethod($name) function
1392 $ms = $r->getMethods();
1393 foreach ($ms as $m) {
1394 if ($m->getName() == $dataobject->functionname) {
1395 $functionreflect = $m;
1399 $dataobject->static = (int)$functionreflect->isStatic();
1401 if (!function_exists($dataobject->functionname)) {
1402 throw new moodle_exception('installnosuchfunction', 'mnet', '', (object)array('method' => $dataobject->functionname, 'file' => $dataobject->filename));
1405 $functionreflect = Zend_Server_Reflection::reflectFunction($dataobject->functionname);
1406 } catch (Zend_Server_Reflection_Exception $e) { // catch these and rethrow them to something more helpful
1407 throw new moodle_exception('installreflectionfunctionerror', 'mnet', '', (object)array('method' => $dataobject->functionname, '' => $dataobject->filename, 'error' => $e->getMessage()));
1410 $dataobject->profile = serialize(admin_mnet_method_profile($functionreflect));
1411 $dataobject->help = $functionreflect->getDescription();
1413 if ($record_exists = $DB->get_record('mnet_rpc', array('xmlrpcpath'=>$dataobject->xmlrpcpath))) {
1414 $dataobject->id = $record_exists->id;
1415 $dataobject->enabled = $record_exists->enabled;
1416 $DB->update_record('mnet_rpc', $dataobject);
1418 $dataobject->id = $DB->insert_record('mnet_rpc', $dataobject, true);
1421 foreach ($publishmethodservices[$dataobject->functionname] as $service) {
1422 if ($serviceobj = $DB->get_record('mnet_service', array('name'=>$service['servicename']))) {
1423 $serviceobj->apiversion = $service['apiversion'];
1424 $DB->update_record('mnet_service', $serviceobj);
1426 $serviceobj = new stdClass();
1427 $serviceobj->name = $service['servicename'];
1428 $serviceobj->apiversion = $service['apiversion'];
1429 $serviceobj->offer = 1;
1430 $serviceobj->id = $DB->insert_record('mnet_service', $serviceobj);
1432 $servicecache[$service['servicename']] = $serviceobj;
1433 if (!$DB->record_exists('mnet_service2rpc', array('rpcid'=>$dataobject->id, 'serviceid'=>$serviceobj->id))) {
1434 $obj = new stdClass();
1435 $obj->rpcid = $dataobject->id;
1436 $obj->serviceid = $serviceobj->id;
1437 $DB->insert_record('mnet_service2rpc', $obj, true);
1442 // finished with methods we publish, now do subscribable methods
1443 foreach($subscribes as $service => $methods) {
1444 if (!array_key_exists($service, $servicecache)) {
1445 if (!$serviceobj = $DB->get_record('mnet_service', array('name' => $service))) {
1446 debugging("TODO: skipping unknown service $service - somebody needs to fix MDL-21993");
1449 $servicecache[$service] = $serviceobj;
1451 $serviceobj = $servicecache[$service];
1453 foreach ($methods as $method => $xmlrpcpath) {
1454 if (!$rpcid = $DB->get_field('mnet_remote_rpc', 'id', array('xmlrpcpath'=>$xmlrpcpath))) {
1455 $remoterpc = (object)array(
1456 'functionname' => $method,
1457 'xmlrpcpath' => $xmlrpcpath,
1458 'plugintype' => $type,
1459 'pluginname' => $plugin,
1462 $rpcid = $remoterpc->id = $DB->insert_record('mnet_remote_rpc', $remoterpc, true);
1464 if (!$DB->record_exists('mnet_remote_service2rpc', array('rpcid'=>$rpcid, 'serviceid'=>$serviceobj->id))) {
1465 $obj = new stdClass();
1466 $obj->rpcid = $rpcid;
1467 $obj->serviceid = $serviceobj->id;
1468 $DB->insert_record('mnet_remote_service2rpc', $obj, true);
1470 $subscribemethodservices[$method][] = $service;
1474 foreach ($DB->get_records('mnet_remote_rpc', array('pluginname'=>$plugin, 'plugintype'=>$type), 'functionname ASC ') as $rpc) {
1475 if (!array_key_exists($rpc->functionname, $subscribemethodservices) && $rpc->enabled) {
1476 $DB->set_field('mnet_remote_rpc', 'enabled', 0, array('id' => $rpc->id));
1477 } else if (array_key_exists($rpc->functionname, $subscribemethodservices) && !$rpc->enabled) {
1478 $DB->set_field('mnet_remote_rpc', 'enabled', 1, array('id' => $rpc->id));
1486 * Given some sort of Zend Reflection function/method object, return a profile array, ready to be serialized and stored
1488 * @param Zend_Server_Reflection_Function_Abstract $function can be any subclass of this object type
1492 function admin_mnet_method_profile(Zend_Server_Reflection_Function_Abstract $function) {
1493 $proto = array_pop($function->getPrototypes());
1494 $ret = $proto->getReturnValue();
1496 'parameters' => array(),
1498 'type' => $ret->getType(),
1499 'description' => $ret->getDescription(),
1502 foreach ($proto->getParameters() as $p) {
1503 $profile['parameters'][] = array(
1504 'name' => $p->getName(),
1505 'type' => $p->getType(),
1506 'description' => $p->getDescription(),