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 defined('MOODLE_INTERNAL') ||
die();
29 /** UPGRADE_LOG_NORMAL = 0 */
30 define('UPGRADE_LOG_NORMAL', 0);
31 /** UPGRADE_LOG_NOTICE = 1 */
32 define('UPGRADE_LOG_NOTICE', 1);
33 /** UPGRADE_LOG_ERROR = 2 */
34 define('UPGRADE_LOG_ERROR', 2);
37 * Exception indicating unknown error during upgrade.
41 * @copyright 2009 Petr Skoda {@link http://skodak.org}
42 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
44 class upgrade_exception
extends moodle_exception
{
45 function __construct($plugin, $version, $debuginfo=NULL) {
47 $a = (object)array('plugin'=>$plugin, 'version'=>$version);
48 parent
::__construct('upgradeerror', 'admin', "$CFG->wwwroot/$CFG->admin/index.php", $a, $debuginfo);
53 * Exception indicating downgrade error during upgrade.
57 * @copyright 2009 Petr Skoda {@link http://skodak.org}
58 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
60 class downgrade_exception
extends moodle_exception
{
61 function __construct($plugin, $oldversion, $newversion) {
63 $plugin = is_null($plugin) ?
'moodle' : $plugin;
64 $a = (object)array('plugin'=>$plugin, 'oldversion'=>$oldversion, 'newversion'=>$newversion);
65 parent
::__construct('cannotdowngrade', 'debug', "$CFG->wwwroot/$CFG->admin/index.php", $a);
72 * @copyright 2009 Petr Skoda {@link http://skodak.org}
73 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
75 class upgrade_requires_exception
extends moodle_exception
{
76 function __construct($plugin, $pluginversion, $currentmoodle, $requiremoodle) {
79 $a->pluginname
= $plugin;
80 $a->pluginversion
= $pluginversion;
81 $a->currentmoodle
= $currentmoodle;
82 $a->requiremoodle
= $requiremoodle;
83 parent
::__construct('pluginrequirementsnotmet', 'error', "$CFG->wwwroot/$CFG->admin/index.php", $a);
90 * @copyright 2009 Petr Skoda {@link http://skodak.org}
91 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
93 class plugin_defective_exception
extends moodle_exception
{
94 function __construct($plugin, $details) {
96 parent
::__construct('detectedbrokenplugin', 'error', "$CFG->wwwroot/$CFG->admin/index.php", $plugin, $details);
101 * Sets maximum expected time needed for upgrade task.
102 * Please always make sure that upgrade will not run longer!
104 * The script may be automatically aborted if upgrade times out.
107 * @param int $max_execution_time in seconds (can not be less than 60 s)
109 function upgrade_set_timeout($max_execution_time=300) {
112 if (!isset($CFG->upgraderunning
) or $CFG->upgraderunning
< time()) {
113 $upgraderunning = get_config(null, 'upgraderunning');
115 $upgraderunning = $CFG->upgraderunning
;
118 if (!$upgraderunning) {
120 // never stop CLI upgrades
123 // web upgrade not running or aborted
124 print_error('upgradetimedout', 'admin', "$CFG->wwwroot/$CFG->admin/");
128 if ($max_execution_time < 60) {
129 // protection against 0 here
130 $max_execution_time = 60;
133 $expected_end = time() +
$max_execution_time;
135 if ($expected_end < $upgraderunning +
10 and $expected_end > $upgraderunning - 10) {
136 // no need to store new end, it is nearly the same ;-)
141 // there is no point in timing out of CLI scripts, admins can stop them if necessary
144 set_time_limit($max_execution_time);
146 set_config('upgraderunning', $expected_end); // keep upgrade locked until this time
150 * Upgrade savepoint, marks end of each upgrade block.
151 * It stores new main version, resets upgrade timeout
152 * and abort upgrade if user cancels page loading.
154 * Please do not make large upgrade blocks with lots of operations,
155 * for example when adding tables keep only one table operation per block.
158 * @param bool $result false if upgrade step failed, true if completed
159 * @param string or float $version main version
160 * @param bool $allowabort allow user to abort script execution here
163 function upgrade_main_savepoint($result, $version, $allowabort=true) {
166 //sanity check to avoid confusion with upgrade_mod_savepoint usage.
167 if (!is_bool($allowabort)) {
168 $errormessage = 'Parameter type mismatch. Are you mixing up upgrade_main_savepoint() and upgrade_mod_savepoint()?';
169 throw new coding_exception($errormessage);
173 throw new upgrade_exception(null, $version);
176 if ($CFG->version
>= $version) {
177 // something really wrong is going on in main upgrade script
178 throw new downgrade_exception(null, $CFG->version
, $version);
181 set_config('version', $version);
182 upgrade_log(UPGRADE_LOG_NORMAL
, null, 'Upgrade savepoint reached');
184 // reset upgrade timeout to default
185 upgrade_set_timeout();
187 // this is a safe place to stop upgrades if user aborts page loading
188 if ($allowabort and connection_aborted()) {
194 * Module upgrade savepoint, marks end of module upgrade blocks
195 * It stores module version, resets upgrade timeout
196 * and abort upgrade if user cancels page loading.
199 * @param bool $result false if upgrade step failed, true if completed
200 * @param string or float $version main version
201 * @param string $modname name of module
202 * @param bool $allowabort allow user to abort script execution here
205 function upgrade_mod_savepoint($result, $version, $modname, $allowabort=true) {
209 throw new upgrade_exception("mod_$modname", $version);
212 if (!$module = $DB->get_record('modules', array('name'=>$modname))) {
213 print_error('modulenotexist', 'debug', '', $modname);
216 if ($module->version
>= $version) {
217 // something really wrong is going on in upgrade script
218 throw new downgrade_exception("mod_$modname", $module->version
, $version);
220 $module->version
= $version;
221 $DB->update_record('modules', $module);
222 upgrade_log(UPGRADE_LOG_NORMAL
, "mod_$modname", 'Upgrade savepoint reached');
224 // reset upgrade timeout to default
225 upgrade_set_timeout();
227 // this is a safe place to stop upgrades if user aborts page loading
228 if ($allowabort and connection_aborted()) {
234 * Blocks upgrade savepoint, marks end of blocks upgrade blocks
235 * It stores block version, resets upgrade timeout
236 * and abort upgrade if user cancels page loading.
239 * @param bool $result false if upgrade step failed, true if completed
240 * @param string or float $version main version
241 * @param string $blockname name of block
242 * @param bool $allowabort allow user to abort script execution here
245 function upgrade_block_savepoint($result, $version, $blockname, $allowabort=true) {
249 throw new upgrade_exception("block_$blockname", $version);
252 if (!$block = $DB->get_record('block', array('name'=>$blockname))) {
253 print_error('blocknotexist', 'debug', '', $blockname);
256 if ($block->version
>= $version) {
257 // something really wrong is going on in upgrade script
258 throw new downgrade_exception("block_$blockname", $block->version
, $version);
260 $block->version
= $version;
261 $DB->update_record('block', $block);
262 upgrade_log(UPGRADE_LOG_NORMAL
, "block_$blockname", 'Upgrade savepoint reached');
264 // reset upgrade timeout to default
265 upgrade_set_timeout();
267 // this is a safe place to stop upgrades if user aborts page loading
268 if ($allowabort and connection_aborted()) {
274 * Plugins upgrade savepoint, marks end of blocks upgrade blocks
275 * It stores plugin version, resets upgrade timeout
276 * and abort upgrade if user cancels page loading.
279 * @param bool $result false if upgrade step failed, true if completed
280 * @param string or float $version main version
281 * @param string $type name of plugin
282 * @param string $dir location of plugin
283 * @param bool $allowabort allow user to abort script execution here
286 function upgrade_plugin_savepoint($result, $version, $type, $plugin, $allowabort=true) {
287 $component = $type.'_'.$plugin;
290 throw new upgrade_exception($component, $version);
293 $installedversion = get_config($component, 'version');
294 if ($installedversion >= $version) {
295 // Something really wrong is going on in the upgrade script
296 throw new downgrade_exception($component, $installedversion, $version);
298 set_config('version', $version, $component);
299 upgrade_log(UPGRADE_LOG_NORMAL
, $component, 'Upgrade savepoint reached');
301 // Reset upgrade timeout to default
302 upgrade_set_timeout();
304 // This is a safe place to stop upgrades if user aborts page loading
305 if ($allowabort and connection_aborted()) {
311 * Detect if there are leftovers in PHP source files.
313 * During main version upgrades administrators MUST move away
314 * old PHP source files and start from scratch (or better
317 * @return bool true means borked upgrade, false means previous PHP files were properly removed
319 function upgrade_stale_php_files_present() {
322 $someexamplesofremovedfiles = array(
324 '/admin/tool/unittest/simpletestlib.php',
326 '/lib/minify/builder/',
328 '/lib/yui/3.4.1pr1/',
330 '/search/cron_php5.php',
331 '/course/report/log/indexlive.php',
332 '/admin/report/backups/index.php',
333 '/admin/generator.php',
337 '/blocks/admin/block_admin.php',
338 '/blocks/admin_tree/block_admin_tree.php',
341 foreach ($someexamplesofremovedfiles as $file) {
342 if (file_exists($CFG->dirroot
.$file)) {
352 * @param string $type The type of plugins that should be updated (e.g. 'enrol', 'qtype')
355 function upgrade_plugins($type, $startcallback, $endcallback, $verbose) {
359 if ($type === 'mod') {
360 return upgrade_plugins_modules($startcallback, $endcallback, $verbose);
361 } else if ($type === 'block') {
362 return upgrade_plugins_blocks($startcallback, $endcallback, $verbose);
365 $plugs = get_plugin_list($type);
367 foreach ($plugs as $plug=>$fullplug) {
368 // Reset time so that it works when installing a large number of plugins
370 $component = clean_param($type.'_'.$plug, PARAM_COMPONENT
); // standardised plugin name
372 // check plugin dir is valid name
373 if (empty($component)) {
374 throw new plugin_defective_exception($type.'_'.$plug, 'Invalid plugin directory name.');
377 if (!is_readable($fullplug.'/version.php')) {
381 $plugin = new stdClass();
382 require($fullplug.'/version.php'); // defines $plugin with version etc
384 // if plugin tells us it's full name we may check the location
385 if (isset($plugin->component
)) {
386 if ($plugin->component
!== $component) {
387 throw new plugin_defective_exception($component, 'Plugin installed in wrong folder.');
391 if (empty($plugin->version
)) {
392 throw new plugin_defective_exception($component, 'Missing version value in version.php');
395 $plugin->name
= $plug;
396 $plugin->fullname
= $component;
399 if (!empty($plugin->requires
)) {
400 if ($plugin->requires
> $CFG->version
) {
401 throw new upgrade_requires_exception($component, $plugin->version
, $CFG->version
, $plugin->requires
);
402 } else if ($plugin->requires
< 2010000000) {
403 throw new plugin_defective_exception($component, 'Plugin is not compatible with Moodle 2.x or later.');
407 // try to recover from interrupted install.php if needed
408 if (file_exists($fullplug.'/db/install.php')) {
409 if (get_config($plugin->fullname
, 'installrunning')) {
410 require_once($fullplug.'/db/install.php');
411 $recover_install_function = 'xmldb_'.$plugin->fullname
.'_install_recovery';
412 if (function_exists($recover_install_function)) {
413 $startcallback($component, true, $verbose);
414 $recover_install_function();
415 unset_config('installrunning', $plugin->fullname
);
416 update_capabilities($component);
417 log_update_descriptions($component);
418 external_update_descriptions($component);
419 events_update_definition($component);
420 message_update_providers($component);
421 if ($type === 'message') {
422 message_update_processors($plug);
424 upgrade_plugin_mnet_functions($component);
425 $endcallback($component, true, $verbose);
430 $installedversion = get_config($plugin->fullname
, 'version');
431 if (empty($installedversion)) { // new installation
432 $startcallback($component, true, $verbose);
434 /// Install tables if defined
435 if (file_exists($fullplug.'/db/install.xml')) {
436 $DB->get_manager()->install_from_xmldb_file($fullplug.'/db/install.xml');
440 upgrade_plugin_savepoint(true, $plugin->version
, $type, $plug, false);
442 /// execute post install file
443 if (file_exists($fullplug.'/db/install.php')) {
444 require_once($fullplug.'/db/install.php');
445 set_config('installrunning', 1, $plugin->fullname
);
446 $post_install_function = 'xmldb_'.$plugin->fullname
.'_install';
447 $post_install_function();
448 unset_config('installrunning', $plugin->fullname
);
451 /// Install various components
452 update_capabilities($component);
453 log_update_descriptions($component);
454 external_update_descriptions($component);
455 events_update_definition($component);
456 message_update_providers($component);
457 if ($type === 'message') {
458 message_update_processors($plug);
460 upgrade_plugin_mnet_functions($component);
463 $endcallback($component, true, $verbose);
465 } else if ($installedversion < $plugin->version
) { // upgrade
466 /// Run the upgrade function for the plugin.
467 $startcallback($component, false, $verbose);
469 if (is_readable($fullplug.'/db/upgrade.php')) {
470 require_once($fullplug.'/db/upgrade.php'); // defines upgrading function
472 $newupgrade_function = 'xmldb_'.$plugin->fullname
.'_upgrade';
473 $result = $newupgrade_function($installedversion);
478 $installedversion = get_config($plugin->fullname
, 'version');
479 if ($installedversion < $plugin->version
) {
480 // store version if not already there
481 upgrade_plugin_savepoint($result, $plugin->version
, $type, $plug, false);
484 /// Upgrade various components
485 update_capabilities($component);
486 log_update_descriptions($component);
487 external_update_descriptions($component);
488 events_update_definition($component);
489 message_update_providers($component);
490 if ($type === 'message') {
491 message_update_processors($plug);
493 upgrade_plugin_mnet_functions($component);
496 $endcallback($component, false, $verbose);
498 } else if ($installedversion > $plugin->version
) {
499 throw new downgrade_exception($component, $installedversion, $plugin->version
);
505 * Find and check all modules and load them up or upgrade them if necessary
510 function upgrade_plugins_modules($startcallback, $endcallback, $verbose) {
513 $mods = get_plugin_list('mod');
515 foreach ($mods as $mod=>$fullmod) {
517 if ($mod === 'NEWMODULE') { // Someone has unzipped the template, ignore it
521 $component = clean_param('mod_'.$mod, PARAM_COMPONENT
);
523 // check module dir is valid name
524 if (empty($component)) {
525 throw new plugin_defective_exception('mod_'.$mod, 'Invalid plugin directory name.');
528 if (!is_readable($fullmod.'/version.php')) {
529 throw new plugin_defective_exception($component, 'Missing version.php');
532 $module = new stdClass();
533 require($fullmod .'/version.php'); // defines $module with version etc
535 // if plugin tells us it's full name we may check the location
536 if (isset($module->component
)) {
537 if ($module->component
!== $component) {
538 throw new plugin_defective_exception($component, 'Plugin installed in wrong folder.');
542 if (empty($module->version
)) {
543 if (isset($module->version
)) {
544 // Version is empty but is set - it means its value is 0 or ''. Let us skip such module.
545 // This is intended for developers so they can work on the early stages of the module.
548 throw new plugin_defective_exception($component, 'Missing version value in version.php');
551 if (!empty($module->requires
)) {
552 if ($module->requires
> $CFG->version
) {
553 throw new upgrade_requires_exception($component, $module->version
, $CFG->version
, $module->requires
);
554 } else if ($module->requires
< 2010000000) {
555 throw new plugin_defective_exception($component, 'Plugin is not compatible with Moodle 2.x or later.');
559 if (empty($module->cron
)) {
563 // all modules must have en lang pack
564 if (!is_readable("$fullmod/lang/en/$mod.php")) {
565 throw new plugin_defective_exception($component, 'Missing mandatory en language pack.');
568 $module->name
= $mod; // The name MUST match the directory
570 $currmodule = $DB->get_record('modules', array('name'=>$module->name
));
572 if (file_exists($fullmod.'/db/install.php')) {
573 if (get_config($module->name
, 'installrunning')) {
574 require_once($fullmod.'/db/install.php');
575 $recover_install_function = 'xmldb_'.$module->name
.'_install_recovery';
576 if (function_exists($recover_install_function)) {
577 $startcallback($component, true, $verbose);
578 $recover_install_function();
579 unset_config('installrunning', $module->name
);
580 // Install various components too
581 update_capabilities($component);
582 log_update_descriptions($component);
583 external_update_descriptions($component);
584 events_update_definition($component);
585 message_update_providers($component);
586 upgrade_plugin_mnet_functions($component);
587 $endcallback($component, true, $verbose);
592 if (empty($currmodule->version
)) {
593 $startcallback($component, true, $verbose);
595 /// Execute install.xml (XMLDB) - must be present in all modules
596 $DB->get_manager()->install_from_xmldb_file($fullmod.'/db/install.xml');
598 /// Add record into modules table - may be needed in install.php already
599 $module->id
= $DB->insert_record('modules', $module);
601 /// Post installation hook - optional
602 if (file_exists("$fullmod/db/install.php")) {
603 require_once("$fullmod/db/install.php");
604 // Set installation running flag, we need to recover after exception or error
605 set_config('installrunning', 1, $module->name
);
606 $post_install_function = 'xmldb_'.$module->name
.'_install';
607 $post_install_function();
608 unset_config('installrunning', $module->name
);
611 /// Install various components
612 update_capabilities($component);
613 log_update_descriptions($component);
614 external_update_descriptions($component);
615 events_update_definition($component);
616 message_update_providers($component);
617 upgrade_plugin_mnet_functions($component);
620 $endcallback($component, true, $verbose);
622 } else if ($currmodule->version
< $module->version
) {
623 /// If versions say that we need to upgrade but no upgrade files are available, notify and continue
624 $startcallback($component, false, $verbose);
626 if (is_readable($fullmod.'/db/upgrade.php')) {
627 require_once($fullmod.'/db/upgrade.php'); // defines new upgrading function
628 $newupgrade_function = 'xmldb_'.$module->name
.'_upgrade';
629 $result = $newupgrade_function($currmodule->version
, $module);
634 $currmodule = $DB->get_record('modules', array('name'=>$module->name
));
635 if ($currmodule->version
< $module->version
) {
636 // store version if not already there
637 upgrade_mod_savepoint($result, $module->version
, $mod, false);
640 // update cron flag if needed
641 if ($currmodule->cron
!= $module->cron
) {
642 $DB->set_field('modules', 'cron', $module->cron
, array('name' => $module->name
));
645 // Upgrade various components
646 update_capabilities($component);
647 log_update_descriptions($component);
648 external_update_descriptions($component);
649 events_update_definition($component);
650 message_update_providers($component);
651 upgrade_plugin_mnet_functions($component);
655 $endcallback($component, false, $verbose);
657 } else if ($currmodule->version
> $module->version
) {
658 throw new downgrade_exception($component, $currmodule->version
, $module->version
);
665 * This function finds all available blocks and install them
666 * into blocks table or do all the upgrade process if newer.
671 function upgrade_plugins_blocks($startcallback, $endcallback, $verbose) {
674 require_once($CFG->dirroot
.'/blocks/moodleblock.class.php');
676 $blocktitles = array(); // we do not want duplicate titles
678 //Is this a first install
679 $first_install = null;
681 $blocks = get_plugin_list('block');
683 foreach ($blocks as $blockname=>$fullblock) {
685 if (is_null($first_install)) {
686 $first_install = ($DB->count_records('block_instances') == 0);
689 if ($blockname === 'NEWBLOCK') { // Someone has unzipped the template, ignore it
693 $component = clean_param('block_'.$blockname, PARAM_COMPONENT
);
695 // check block dir is valid name
696 if (empty($component)) {
697 throw new plugin_defective_exception('block_'.$blockname, 'Invalid plugin directory name.');
700 if (!is_readable($fullblock.'/version.php')) {
701 throw new plugin_defective_exception('block/'.$blockname, 'Missing version.php file.');
703 $plugin = new stdClass();
704 $plugin->version
= NULL;
706 include($fullblock.'/version.php');
709 // if plugin tells us it's full name we may check the location
710 if (isset($block->component
)) {
711 if ($block->component
!== $component) {
712 throw new plugin_defective_exception($component, 'Plugin installed in wrong folder.');
716 if (!empty($plugin->requires
)) {
717 if ($plugin->requires
> $CFG->version
) {
718 throw new upgrade_requires_exception($component, $plugin->version
, $CFG->version
, $plugin->requires
);
719 } else if ($plugin->requires
< 2010000000) {
720 throw new plugin_defective_exception($component, 'Plugin is not compatible with Moodle 2.x or later.');
724 if (!is_readable($fullblock.'/block_'.$blockname.'.php')) {
725 throw new plugin_defective_exception('block/'.$blockname, 'Missing main block class file.');
727 include_once($fullblock.'/block_'.$blockname.'.php');
729 $classname = 'block_'.$blockname;
731 if (!class_exists($classname)) {
732 throw new plugin_defective_exception($component, 'Can not load main class.');
735 $blockobj = new $classname; // This is what we'll be testing
736 $blocktitle = $blockobj->get_title();
738 // OK, it's as we all hoped. For further tests, the object will do them itself.
739 if (!$blockobj->_self_test()) {
740 throw new plugin_defective_exception($component, 'Self test failed.');
743 $block->name
= $blockname; // The name MUST match the directory
745 if (empty($block->version
)) {
746 throw new plugin_defective_exception($component, 'Missing block version.');
749 $currblock = $DB->get_record('block', array('name'=>$block->name
));
751 if (file_exists($fullblock.'/db/install.php')) {
752 if (get_config('block_'.$blockname, 'installrunning')) {
753 require_once($fullblock.'/db/install.php');
754 $recover_install_function = 'xmldb_block_'.$blockname.'_install_recovery';
755 if (function_exists($recover_install_function)) {
756 $startcallback($component, true, $verbose);
757 $recover_install_function();
758 unset_config('installrunning', 'block_'.$blockname);
759 // Install various components
760 update_capabilities($component);
761 log_update_descriptions($component);
762 external_update_descriptions($component);
763 events_update_definition($component);
764 message_update_providers($component);
765 upgrade_plugin_mnet_functions($component);
766 $endcallback($component, true, $verbose);
771 if (empty($currblock->version
)) { // block not installed yet, so install it
772 $conflictblock = array_search($blocktitle, $blocktitles);
773 if ($conflictblock !== false) {
774 // Duplicate block titles are not allowed, they confuse people
775 // AND PHP's associative arrays ;)
776 throw new plugin_defective_exception($component, get_string('blocknameconflict', 'error', (object)array('name'=>$block->name
, 'conflict'=>$conflictblock)));
778 $startcallback($component, true, $verbose);
780 if (file_exists($fullblock.'/db/install.xml')) {
781 $DB->get_manager()->install_from_xmldb_file($fullblock.'/db/install.xml');
783 $block->id
= $DB->insert_record('block', $block);
785 if (file_exists($fullblock.'/db/install.php')) {
786 require_once($fullblock.'/db/install.php');
787 // Set installation running flag, we need to recover after exception or error
788 set_config('installrunning', 1, 'block_'.$blockname);
789 $post_install_function = 'xmldb_block_'.$blockname.'_install';;
790 $post_install_function();
791 unset_config('installrunning', 'block_'.$blockname);
794 $blocktitles[$block->name
] = $blocktitle;
796 // Install various components
797 update_capabilities($component);
798 log_update_descriptions($component);
799 external_update_descriptions($component);
800 events_update_definition($component);
801 message_update_providers($component);
802 upgrade_plugin_mnet_functions($component);
805 $endcallback($component, true, $verbose);
807 } else if ($currblock->version
< $block->version
) {
808 $startcallback($component, false, $verbose);
810 if (is_readable($fullblock.'/db/upgrade.php')) {
811 require_once($fullblock.'/db/upgrade.php'); // defines new upgrading function
812 $newupgrade_function = 'xmldb_block_'.$blockname.'_upgrade';
813 $result = $newupgrade_function($currblock->version
, $block);
818 $currblock = $DB->get_record('block', array('name'=>$block->name
));
819 if ($currblock->version
< $block->version
) {
820 // store version if not already there
821 upgrade_block_savepoint($result, $block->version
, $block->name
, false);
824 if ($currblock->cron
!= $block->cron
) {
825 // update cron flag if needed
826 $currblock->cron
= $block->cron
;
827 $DB->update_record('block', $currblock);
830 // Upgrade various components
831 update_capabilities($component);
832 log_update_descriptions($component);
833 external_update_descriptions($component);
834 events_update_definition($component);
835 message_update_providers($component);
836 upgrade_plugin_mnet_functions($component);
839 $endcallback($component, false, $verbose);
841 } else if ($currblock->version
> $block->version
) {
842 throw new downgrade_exception($component, $currblock->version
, $block->version
);
847 // Finally, if we are in the first_install of BLOCKS setup frontpage and admin page blocks
848 if ($first_install) {
849 //Iterate over each course - there should be only site course here now
850 if ($courses = $DB->get_records('course')) {
851 foreach ($courses as $course) {
852 blocks_add_default_course_blocks($course);
856 blocks_add_default_system_blocks();
862 * Log_display description function used during install and upgrade.
864 * @param string $component name of component (moodle, mod_assignment, etc.)
867 function log_update_descriptions($component) {
870 $defpath = get_component_directory($component).'/db/log.php';
872 if (!file_exists($defpath)) {
873 $DB->delete_records('log_display', array('component'=>$component));
881 foreach ($logs as $log) {
882 $newlogs[$log['module'].'-'.$log['action']] = $log; // kind of unique name
887 $fields = array('module', 'action', 'mtable', 'field');
888 // update all log fist
889 $dblogs = $DB->get_records('log_display', array('component'=>$component));
890 foreach ($dblogs as $dblog) {
891 $name = $dblog->module
.'-'.$dblog->action
;
893 if (empty($logs[$name])) {
894 $DB->delete_records('log_display', array('id'=>$dblog->id
));
902 foreach ($fields as $field) {
903 if ($dblog->$field != $log[$field]) {
904 $dblog->$field = $log[$field];
909 $DB->update_record('log_display', $dblog);
912 foreach ($logs as $log) {
913 $dblog = (object)$log;
914 $dblog->component
= $component;
915 $DB->insert_record('log_display', $dblog);
920 * Web service discovery function used during install and upgrade.
921 * @param string $component name of component (moodle, mod_assignment, etc.)
924 function external_update_descriptions($component) {
927 $defpath = get_component_directory($component).'/db/services.php';
929 if (!file_exists($defpath)) {
930 require_once($CFG->dirroot
.'/lib/externallib.php');
931 external_delete_descriptions($component);
936 $functions = array();
940 // update all function fist
941 $dbfunctions = $DB->get_records('external_functions', array('component'=>$component));
942 foreach ($dbfunctions as $dbfunction) {
943 if (empty($functions[$dbfunction->name
])) {
944 $DB->delete_records('external_functions', array('id'=>$dbfunction->id
));
945 // do not delete functions from external_services_functions, beacuse
946 // we want to notify admins when functions used in custom services disappear
948 //TODO: this looks wrong, we have to delete it eventually (skodak)
952 $function = $functions[$dbfunction->name
];
953 unset($functions[$dbfunction->name
]);
954 $function['classpath'] = empty($function['classpath']) ?
null : $function['classpath'];
957 if ($dbfunction->classname
!= $function['classname']) {
958 $dbfunction->classname
= $function['classname'];
961 if ($dbfunction->methodname
!= $function['methodname']) {
962 $dbfunction->methodname
= $function['methodname'];
965 if ($dbfunction->classpath
!= $function['classpath']) {
966 $dbfunction->classpath
= $function['classpath'];
969 $functioncapabilities = array_key_exists('capabilities', $function)?
$function['capabilities']:'';
970 if ($dbfunction->capabilities
!= $functioncapabilities) {
971 $dbfunction->capabilities
= $functioncapabilities;
975 $DB->update_record('external_functions', $dbfunction);
978 foreach ($functions as $fname => $function) {
979 $dbfunction = new stdClass();
980 $dbfunction->name
= $fname;
981 $dbfunction->classname
= $function['classname'];
982 $dbfunction->methodname
= $function['methodname'];
983 $dbfunction->classpath
= empty($function['classpath']) ?
null : $function['classpath'];
984 $dbfunction->component
= $component;
985 $dbfunction->capabilities
= array_key_exists('capabilities', $function)?
$function['capabilities']:'';
986 $dbfunction->id
= $DB->insert_record('external_functions', $dbfunction);
990 // now deal with services
991 $dbservices = $DB->get_records('external_services', array('component'=>$component));
992 foreach ($dbservices as $dbservice) {
993 if (empty($services[$dbservice->name
])) {
994 $DB->delete_records('external_tokens', array('externalserviceid'=>$dbservice->id
));
995 $DB->delete_records('external_services_functions', array('externalserviceid'=>$dbservice->id
));
996 $DB->delete_records('external_services_users', array('externalserviceid'=>$dbservice->id
));
997 $DB->delete_records('external_services', array('id'=>$dbservice->id
));
1000 $service = $services[$dbservice->name
];
1001 unset($services[$dbservice->name
]);
1002 $service['enabled'] = empty($service['enabled']) ?
0 : $service['enabled'];
1003 $service['requiredcapability'] = empty($service['requiredcapability']) ?
null : $service['requiredcapability'];
1004 $service['restrictedusers'] = !isset($service['restrictedusers']) ?
1 : $service['restrictedusers'];
1005 $service['downloadfiles'] = !isset($service['downloadfiles']) ?
0 : $service['downloadfiles'];
1006 $service['shortname'] = !isset($service['shortname']) ?
null : $service['shortname'];
1009 if ($dbservice->requiredcapability
!= $service['requiredcapability']) {
1010 $dbservice->requiredcapability
= $service['requiredcapability'];
1013 if ($dbservice->restrictedusers
!= $service['restrictedusers']) {
1014 $dbservice->restrictedusers
= $service['restrictedusers'];
1017 if ($dbservice->downloadfiles
!= $service['downloadfiles']) {
1018 $dbservice->downloadfiles
= $service['downloadfiles'];
1021 //if shortname is not a PARAM_ALPHANUMEXT, fail (tested here for service update and creation)
1022 if (isset($service['shortname']) and
1023 (clean_param($service['shortname'], PARAM_ALPHANUMEXT
) != $service['shortname'])) {
1024 throw new moodle_exception('installserviceshortnameerror', 'webservice', '', $service['shortname']);
1026 if ($dbservice->shortname
!= $service['shortname']) {
1027 //check that shortname is unique
1028 if (isset($service['shortname'])) { //we currently accepts multiple shortname == null
1029 $existingservice = $DB->get_record('external_services',
1030 array('shortname' => $service['shortname']));
1031 if (!empty($existingservice)) {
1032 throw new moodle_exception('installexistingserviceshortnameerror', 'webservice', '', $service['shortname']);
1035 $dbservice->shortname
= $service['shortname'];
1039 $DB->update_record('external_services', $dbservice);
1042 $functions = $DB->get_records('external_services_functions', array('externalserviceid'=>$dbservice->id
));
1043 foreach ($functions as $function) {
1044 $key = array_search($function->functionname
, $service['functions']);
1045 if ($key === false) {
1046 $DB->delete_records('external_services_functions', array('id'=>$function->id
));
1048 unset($service['functions'][$key]);
1051 foreach ($service['functions'] as $fname) {
1052 $newf = new stdClass();
1053 $newf->externalserviceid
= $dbservice->id
;
1054 $newf->functionname
= $fname;
1055 $DB->insert_record('external_services_functions', $newf);
1059 foreach ($services as $name => $service) {
1060 //check that shortname is unique
1061 if (isset($service['shortname'])) { //we currently accepts multiple shortname == null
1062 $existingservice = $DB->get_record('external_services',
1063 array('shortname' => $service['shortname']));
1064 if (!empty($existingservice)) {
1065 throw new moodle_exception('installserviceshortnameerror', 'webservice');
1069 $dbservice = new stdClass();
1070 $dbservice->name
= $name;
1071 $dbservice->enabled
= empty($service['enabled']) ?
0 : $service['enabled'];
1072 $dbservice->requiredcapability
= empty($service['requiredcapability']) ?
null : $service['requiredcapability'];
1073 $dbservice->restrictedusers
= !isset($service['restrictedusers']) ?
1 : $service['restrictedusers'];
1074 $dbservice->downloadfiles
= !isset($service['downloadfiles']) ?
0 : $service['downloadfiles'];
1075 $dbservice->shortname
= !isset($service['shortname']) ?
null : $service['shortname'];
1076 $dbservice->component
= $component;
1077 $dbservice->timecreated
= time();
1078 $dbservice->id
= $DB->insert_record('external_services', $dbservice);
1079 foreach ($service['functions'] as $fname) {
1080 $newf = new stdClass();
1081 $newf->externalserviceid
= $dbservice->id
;
1082 $newf->functionname
= $fname;
1083 $DB->insert_record('external_services_functions', $newf);
1089 * upgrade logging functions
1091 function upgrade_handle_exception($ex, $plugin = null) {
1094 // rollback everything, we need to log all upgrade problems
1095 abort_all_db_transactions();
1097 $info = get_exception_info($ex);
1099 // First log upgrade error
1100 upgrade_log(UPGRADE_LOG_ERROR
, $plugin, 'Exception: ' . get_class($ex), $info->message
, $info->backtrace
);
1102 // Always turn on debugging - admins need to know what is going on
1103 $CFG->debug
= DEBUG_DEVELOPER
;
1105 default_exception_handler($ex, true, $plugin);
1109 * Adds log entry into upgrade_log table
1111 * @param int $type UPGRADE_LOG_NORMAL, UPGRADE_LOG_NOTICE or UPGRADE_LOG_ERROR
1112 * @param string $plugin frankenstyle component name
1113 * @param string $info short description text of log entry
1114 * @param string $details long problem description
1115 * @param string $backtrace string used for errors only
1118 function upgrade_log($type, $plugin, $info, $details=null, $backtrace=null) {
1119 global $DB, $USER, $CFG;
1121 if (empty($plugin)) {
1125 list($plugintype, $pluginname) = normalize_component($plugin);
1126 $component = is_null($pluginname) ?
$plugintype : $plugintype . '_' . $pluginname;
1128 $backtrace = format_backtrace($backtrace, true);
1130 $currentversion = null;
1131 $targetversion = null;
1133 //first try to find out current version number
1134 if ($plugintype === 'core') {
1136 $currentversion = $CFG->version
;
1139 include("$CFG->dirroot/version.php");
1140 $targetversion = $version;
1142 } else if ($plugintype === 'mod') {
1144 $currentversion = $DB->get_field('modules', 'version', array('name'=>$pluginname));
1145 $currentversion = ($currentversion === false) ?
null : $currentversion;
1146 } catch (Exception
$ignored) {
1148 $cd = get_component_directory($component);
1149 if (file_exists("$cd/version.php")) {
1150 $module = new stdClass();
1151 $module->version
= null;
1152 include("$cd/version.php");
1153 $targetversion = $module->version
;
1156 } else if ($plugintype === 'block') {
1158 if ($block = $DB->get_record('block', array('name'=>$pluginname))) {
1159 $currentversion = $block->version
;
1161 } catch (Exception
$ignored) {
1163 $cd = get_component_directory($component);
1164 if (file_exists("$cd/version.php")) {
1165 $plugin = new stdClass();
1166 $plugin->version
= null;
1167 include("$cd/version.php");
1168 $targetversion = $plugin->version
;
1172 $pluginversion = get_config($component, 'version');
1173 if (!empty($pluginversion)) {
1174 $currentversion = $pluginversion;
1176 $cd = get_component_directory($component);
1177 if (file_exists("$cd/version.php")) {
1178 $plugin = new stdClass();
1179 $plugin->version
= null;
1180 include("$cd/version.php");
1181 $targetversion = $plugin->version
;
1185 $log = new stdClass();
1187 $log->plugin
= $component;
1188 $log->version
= $currentversion;
1189 $log->targetversion
= $targetversion;
1191 $log->details
= $details;
1192 $log->backtrace
= $backtrace;
1193 $log->userid
= $USER->id
;
1194 $log->timemodified
= time();
1196 $DB->insert_record('upgrade_log', $log);
1197 } catch (Exception
$ignored) {
1198 // possible during install or 2.0 upgrade
1203 * Marks start of upgrade, blocks any other access to site.
1204 * The upgrade is finished at the end of script or after timeout.
1210 function upgrade_started($preinstall=false) {
1211 global $CFG, $DB, $PAGE, $OUTPUT;
1213 static $started = false;
1216 ignore_user_abort(true);
1217 upgrade_setup_debug(true);
1219 } else if ($started) {
1220 upgrade_set_timeout(120);
1223 if (!CLI_SCRIPT
and !$PAGE->headerprinted
) {
1224 $strupgrade = get_string('upgradingversion', 'admin');
1225 $PAGE->set_pagelayout('maintenance');
1226 upgrade_init_javascript();
1227 $PAGE->set_title($strupgrade.' - Moodle '.$CFG->target_release
);
1228 $PAGE->set_heading($strupgrade);
1229 $PAGE->navbar
->add($strupgrade);
1230 $PAGE->set_cacheable(false);
1231 echo $OUTPUT->header();
1234 ignore_user_abort(true);
1235 register_shutdown_function('upgrade_finished_handler');
1236 upgrade_setup_debug(true);
1237 set_config('upgraderunning', time()+
300);
1243 * Internal function - executed if upgrade interrupted.
1245 function upgrade_finished_handler() {
1250 * Indicates upgrade is finished.
1252 * This function may be called repeatedly.
1257 function upgrade_finished($continueurl=null) {
1258 global $CFG, $DB, $OUTPUT;
1260 if (!empty($CFG->upgraderunning
)) {
1261 unset_config('upgraderunning');
1262 upgrade_setup_debug(false);
1263 ignore_user_abort(false);
1265 echo $OUTPUT->continue_button($continueurl);
1266 echo $OUTPUT->footer();
1276 function upgrade_setup_debug($starting) {
1279 static $originaldebug = null;
1282 if ($originaldebug === null) {
1283 $originaldebug = $DB->get_debug();
1285 if (!empty($CFG->upgradeshowsql
)) {
1286 $DB->set_debug(true);
1289 $DB->set_debug($originaldebug);
1293 function print_upgrade_separator() {
1300 * Default start upgrade callback
1301 * @param string $plugin
1302 * @param bool $installation true if installation, false means upgrade
1304 function print_upgrade_part_start($plugin, $installation, $verbose) {
1306 if (empty($plugin) or $plugin == 'moodle') {
1307 upgrade_started($installation); // does not store upgrade running flag yet
1309 echo $OUTPUT->heading(get_string('coresystem'));
1314 echo $OUTPUT->heading($plugin);
1317 if ($installation) {
1318 if (empty($plugin) or $plugin == 'moodle') {
1319 // no need to log - log table not yet there ;-)
1321 upgrade_log(UPGRADE_LOG_NORMAL
, $plugin, 'Starting plugin installation');
1324 if (empty($plugin) or $plugin == 'moodle') {
1325 upgrade_log(UPGRADE_LOG_NORMAL
, $plugin, 'Starting core upgrade');
1327 upgrade_log(UPGRADE_LOG_NORMAL
, $plugin, 'Starting plugin upgrade');
1333 * Default end upgrade callback
1334 * @param string $plugin
1335 * @param bool $installation true if installation, false means upgrade
1337 function print_upgrade_part_end($plugin, $installation, $verbose) {
1340 if ($installation) {
1341 if (empty($plugin) or $plugin == 'moodle') {
1342 upgrade_log(UPGRADE_LOG_NORMAL
, $plugin, 'Core installed');
1344 upgrade_log(UPGRADE_LOG_NORMAL
, $plugin, 'Plugin installed');
1347 if (empty($plugin) or $plugin == 'moodle') {
1348 upgrade_log(UPGRADE_LOG_NORMAL
, $plugin, 'Core upgraded');
1350 upgrade_log(UPGRADE_LOG_NORMAL
, $plugin, 'Plugin upgraded');
1354 echo $OUTPUT->notification(get_string('success'), 'notifysuccess');
1355 print_upgrade_separator();
1360 * Sets up JS code required for all upgrade scripts.
1363 function upgrade_init_javascript() {
1365 // scroll to the end of each upgrade page so that ppl see either error or continue button,
1366 // no need to scroll continuously any more, it is enough to jump to end once the footer is printed ;-)
1367 $js = "window.scrollTo(0, 5000000);";
1368 $PAGE->requires
->js_init_code($js);
1372 * Try to upgrade the given language pack (or current language)
1374 * @param string $lang the code of the language to update, defaults to the current language
1376 function upgrade_language_pack($lang = null) {
1379 if (!empty($CFG->skiplangupgrade
)) {
1383 if (!file_exists("$CFG->dirroot/$CFG->admin/tool/langimport/lib.php")) {
1384 // weird, somebody uninstalled the import utility
1389 $lang = current_language();
1392 if (!get_string_manager()->translation_exists($lang)) {
1396 get_string_manager()->reset_caches();
1398 if ($lang === 'en') {
1399 return; // Nothing to do
1402 upgrade_started(false);
1404 require_once("$CFG->dirroot/$CFG->admin/tool/langimport/lib.php");
1405 tool_langimport_preupgrade_update($lang);
1407 get_string_manager()->reset_caches();
1409 print_upgrade_separator();
1413 * Install core moodle tables and initialize
1414 * @param float $version target version
1415 * @param bool $verbose
1416 * @return void, may throw exception
1418 function install_core($version, $verbose) {
1422 // Disable the use of cache stores here. We will reset the factory after we've performed the installation.
1423 // This ensures that we don't permanently cache anything during installation.
1424 cache_factory
::disable_stores();
1426 set_time_limit(600);
1427 print_upgrade_part_start('moodle', true, $verbose); // does not store upgrade running flag
1429 $DB->get_manager()->install_from_xmldb_file("$CFG->libdir/db/install.xml");
1430 upgrade_started(); // we want the flag to be stored in config table ;-)
1432 // set all core default records and default settings
1433 require_once("$CFG->libdir/db/install.php");
1434 xmldb_main_install(); // installs the capabilities too
1437 upgrade_main_savepoint(true, $version, false);
1439 // Continue with the installation
1440 log_update_descriptions('moodle');
1441 external_update_descriptions('moodle');
1442 events_update_definition('moodle');
1443 message_update_providers('moodle');
1445 // Write default settings unconditionally
1446 admin_apply_default_settings(NULL, true);
1448 print_upgrade_part_end(null, true, $verbose);
1450 // Reset the cache, this returns it to a normal operation state.
1451 cache_factory
::reset();
1452 } catch (exception
$ex) {
1453 upgrade_handle_exception($ex);
1458 * Upgrade moodle core
1459 * @param float $version target version
1460 * @param bool $verbose
1461 * @return void, may throw exception
1463 function upgrade_core($version, $verbose) {
1466 raise_memory_limit(MEMORY_EXTRA
);
1468 require_once($CFG->libdir
.'/db/upgrade.php'); // Defines upgrades
1471 // Reset caches before any output
1473 // Disable the use of cache stores here. We will reset the factory after we've performed the installation.
1474 // This ensures that we don't permanently cache anything during installation.
1475 cache_factory
::disable_stores();
1477 // Upgrade current language pack if we can
1478 upgrade_language_pack();
1480 print_upgrade_part_start('moodle', false, $verbose);
1482 // one time special local migration pre 2.0 upgrade script
1483 if ($CFG->version
< 2007101600) {
1484 $pre20upgradefile = "$CFG->dirroot/local/upgrade_pre20.php";
1485 if (file_exists($pre20upgradefile)) {
1487 require($pre20upgradefile);
1488 // reset upgrade timeout to default
1489 upgrade_set_timeout();
1493 $result = xmldb_main_upgrade($CFG->version
);
1494 if ($version > $CFG->version
) {
1495 // store version if not already there
1496 upgrade_main_savepoint($result, $version, false);
1499 // perform all other component upgrade routines
1500 update_capabilities('moodle');
1501 log_update_descriptions('moodle');
1502 external_update_descriptions('moodle');
1503 events_update_definition('moodle');
1504 message_update_providers('moodle');
1505 // Update core definitions.
1506 cache_helper
::update_definitions(true);
1508 // Reset the cache, this returns it to a normal operation state.
1509 cache_factory
::reset();
1510 // Purge caches again, just to be sure we arn't holding onto old stuff now.
1513 // Clean up contexts - more and more stuff depends on existence of paths and contexts
1514 context_helper
::cleanup_instances();
1515 context_helper
::create_instances(null, false);
1516 context_helper
::build_all_paths(false);
1517 $syscontext = context_system
::instance();
1518 $syscontext->mark_dirty();
1520 print_upgrade_part_end('moodle', false, $verbose);
1521 } catch (Exception
$ex) {
1522 upgrade_handle_exception($ex);
1527 * Upgrade/install other parts of moodle
1528 * @param bool $verbose
1529 * @return void, may throw exception
1531 function upgrade_noncore($verbose) {
1534 raise_memory_limit(MEMORY_EXTRA
);
1536 // upgrade all plugins types
1538 // Disable the use of cache stores here. We will reset the factory after we've performed the installation.
1539 // This ensures that we don't permanently cache anything during installation.
1540 cache_factory
::disable_stores();
1542 $plugintypes = get_plugin_types();
1543 foreach ($plugintypes as $type=>$location) {
1544 upgrade_plugins($type, 'print_upgrade_part_start', 'print_upgrade_part_end', $verbose);
1546 // Update cache definitions. Involves scanning each plugin for any changes.
1547 cache_helper
::update_definitions();
1548 // Reset the cache system to a normal state.
1549 cache_factory
::reset();
1550 } catch (Exception
$ex) {
1551 upgrade_handle_exception($ex);
1556 * Checks if the main tables have been installed yet or not.
1559 function core_tables_exist() {
1562 if (!$tables = $DB->get_tables() ) { // No tables yet at all.
1565 } else { // Check for missing main tables
1566 $mtables = array('config', 'course', 'groupings'); // some tables used in 1.9 and 2.0, preferable something from the start and end of install.xml
1567 foreach ($mtables as $mtable) {
1568 if (!in_array($mtable, $tables)) {
1577 * upgrades the mnet rpc definitions for the given component.
1578 * this method doesn't return status, an exception will be thrown in the case of an error
1580 * @param string $component the plugin to upgrade, eg auth_mnet
1582 function upgrade_plugin_mnet_functions($component) {
1585 list($type, $plugin) = explode('_', $component);
1586 $path = get_plugin_directory($type, $plugin);
1588 $publishes = array();
1589 $subscribes = array();
1590 if (file_exists($path . '/db/mnet.php')) {
1591 require_once($path . '/db/mnet.php'); // $publishes comes from this file
1593 if (empty($publishes)) {
1594 $publishes = array(); // still need this to be able to disable stuff later
1596 if (empty($subscribes)) {
1597 $subscribes = array(); // still need this to be able to disable stuff later
1600 static $servicecache = array();
1602 // rekey an array based on the rpc method for easy lookups later
1603 $publishmethodservices = array();
1604 $subscribemethodservices = array();
1605 foreach($publishes as $servicename => $service) {
1606 if (is_array($service['methods'])) {
1607 foreach($service['methods'] as $methodname) {
1608 $service['servicename'] = $servicename;
1609 $publishmethodservices[$methodname][] = $service;
1614 // Disable functions that don't exist (any more) in the source
1615 // Should these be deleted? What about their permissions records?
1616 foreach ($DB->get_records('mnet_rpc', array('pluginname'=>$plugin, 'plugintype'=>$type), 'functionname ASC ') as $rpc) {
1617 if (!array_key_exists($rpc->functionname
, $publishmethodservices) && $rpc->enabled
) {
1618 $DB->set_field('mnet_rpc', 'enabled', 0, array('id' => $rpc->id
));
1619 } else if (array_key_exists($rpc->functionname
, $publishmethodservices) && !$rpc->enabled
) {
1620 $DB->set_field('mnet_rpc', 'enabled', 1, array('id' => $rpc->id
));
1624 // reflect all the services we're publishing and save them
1625 require_once($CFG->dirroot
. '/lib/zend/Zend/Server/Reflection.php');
1626 static $cachedclasses = array(); // to store reflection information in
1627 foreach ($publishes as $service => $data) {
1628 $f = $data['filename'];
1629 $c = $data['classname'];
1630 foreach ($data['methods'] as $method) {
1631 $dataobject = new stdClass();
1632 $dataobject->plugintype
= $type;
1633 $dataobject->pluginname
= $plugin;
1634 $dataobject->enabled
= 1;
1635 $dataobject->classname
= $c;
1636 $dataobject->filename
= $f;
1638 if (is_string($method)) {
1639 $dataobject->functionname
= $method;
1641 } else if (is_array($method)) { // wants to override file or class
1642 $dataobject->functionname
= $method['method'];
1643 $dataobject->classname
= $method['classname'];
1644 $dataobject->filename
= $method['filename'];
1646 $dataobject->xmlrpcpath
= $type.'/'.$plugin.'/'.$dataobject->filename
.'/'.$method;
1647 $dataobject->static = false;
1649 require_once($path . '/' . $dataobject->filename
);
1650 $functionreflect = null; // slightly different ways to get this depending on whether it's a class method or a function
1651 if (!empty($dataobject->classname
)) {
1652 if (!class_exists($dataobject->classname
)) {
1653 throw new moodle_exception('installnosuchmethod', 'mnet', '', (object)array('method' => $dataobject->functionname
, 'class' => $dataobject->classname
));
1655 $key = $dataobject->filename
. '|' . $dataobject->classname
;
1656 if (!array_key_exists($key, $cachedclasses)) { // look to see if we've already got a reflection object
1658 $cachedclasses[$key] = Zend_Server_Reflection
::reflectClass($dataobject->classname
);
1659 } catch (Zend_Server_Reflection_Exception
$e) { // catch these and rethrow them to something more helpful
1660 throw new moodle_exception('installreflectionclasserror', 'mnet', '', (object)array('method' => $dataobject->functionname
, 'class' => $dataobject->classname
, 'error' => $e->getMessage()));
1663 $r =& $cachedclasses[$key];
1664 if (!$r->hasMethod($dataobject->functionname
)) {
1665 throw new moodle_exception('installnosuchmethod', 'mnet', '', (object)array('method' => $dataobject->functionname
, 'class' => $dataobject->classname
));
1667 // stupid workaround for zend not having a getMethod($name) function
1668 $ms = $r->getMethods();
1669 foreach ($ms as $m) {
1670 if ($m->getName() == $dataobject->functionname
) {
1671 $functionreflect = $m;
1675 $dataobject->static = (int)$functionreflect->isStatic();
1677 if (!function_exists($dataobject->functionname
)) {
1678 throw new moodle_exception('installnosuchfunction', 'mnet', '', (object)array('method' => $dataobject->functionname
, 'file' => $dataobject->filename
));
1681 $functionreflect = Zend_Server_Reflection
::reflectFunction($dataobject->functionname
);
1682 } catch (Zend_Server_Reflection_Exception
$e) { // catch these and rethrow them to something more helpful
1683 throw new moodle_exception('installreflectionfunctionerror', 'mnet', '', (object)array('method' => $dataobject->functionname
, '' => $dataobject->filename
, 'error' => $e->getMessage()));
1686 $dataobject->profile
= serialize(admin_mnet_method_profile($functionreflect));
1687 $dataobject->help
= $functionreflect->getDescription();
1689 if ($record_exists = $DB->get_record('mnet_rpc', array('xmlrpcpath'=>$dataobject->xmlrpcpath
))) {
1690 $dataobject->id
= $record_exists->id
;
1691 $dataobject->enabled
= $record_exists->enabled
;
1692 $DB->update_record('mnet_rpc', $dataobject);
1694 $dataobject->id
= $DB->insert_record('mnet_rpc', $dataobject, true);
1697 // TODO this API versioning must be reworked, here the recently processed method
1698 // sets the service API which may not be correct
1699 foreach ($publishmethodservices[$dataobject->functionname
] as $service) {
1700 if ($serviceobj = $DB->get_record('mnet_service', array('name'=>$service['servicename']))) {
1701 $serviceobj->apiversion
= $service['apiversion'];
1702 $DB->update_record('mnet_service', $serviceobj);
1704 $serviceobj = new stdClass();
1705 $serviceobj->name
= $service['servicename'];
1706 $serviceobj->description
= empty($service['description']) ?
'' : $service['description'];
1707 $serviceobj->apiversion
= $service['apiversion'];
1708 $serviceobj->offer
= 1;
1709 $serviceobj->id
= $DB->insert_record('mnet_service', $serviceobj);
1711 $servicecache[$service['servicename']] = $serviceobj;
1712 if (!$DB->record_exists('mnet_service2rpc', array('rpcid'=>$dataobject->id
, 'serviceid'=>$serviceobj->id
))) {
1713 $obj = new stdClass();
1714 $obj->rpcid
= $dataobject->id
;
1715 $obj->serviceid
= $serviceobj->id
;
1716 $DB->insert_record('mnet_service2rpc', $obj, true);
1721 // finished with methods we publish, now do subscribable methods
1722 foreach($subscribes as $service => $methods) {
1723 if (!array_key_exists($service, $servicecache)) {
1724 if (!$serviceobj = $DB->get_record('mnet_service', array('name' => $service))) {
1725 debugging("TODO: skipping unknown service $service - somebody needs to fix MDL-21993");
1728 $servicecache[$service] = $serviceobj;
1730 $serviceobj = $servicecache[$service];
1732 foreach ($methods as $method => $xmlrpcpath) {
1733 if (!$rpcid = $DB->get_field('mnet_remote_rpc', 'id', array('xmlrpcpath'=>$xmlrpcpath))) {
1734 $remoterpc = (object)array(
1735 'functionname' => $method,
1736 'xmlrpcpath' => $xmlrpcpath,
1737 'plugintype' => $type,
1738 'pluginname' => $plugin,
1741 $rpcid = $remoterpc->id
= $DB->insert_record('mnet_remote_rpc', $remoterpc, true);
1743 if (!$DB->record_exists('mnet_remote_service2rpc', array('rpcid'=>$rpcid, 'serviceid'=>$serviceobj->id
))) {
1744 $obj = new stdClass();
1745 $obj->rpcid
= $rpcid;
1746 $obj->serviceid
= $serviceobj->id
;
1747 $DB->insert_record('mnet_remote_service2rpc', $obj, true);
1749 $subscribemethodservices[$method][] = $service;
1753 foreach ($DB->get_records('mnet_remote_rpc', array('pluginname'=>$plugin, 'plugintype'=>$type), 'functionname ASC ') as $rpc) {
1754 if (!array_key_exists($rpc->functionname
, $subscribemethodservices) && $rpc->enabled
) {
1755 $DB->set_field('mnet_remote_rpc', 'enabled', 0, array('id' => $rpc->id
));
1756 } else if (array_key_exists($rpc->functionname
, $subscribemethodservices) && !$rpc->enabled
) {
1757 $DB->set_field('mnet_remote_rpc', 'enabled', 1, array('id' => $rpc->id
));
1765 * Given some sort of Zend Reflection function/method object, return a profile array, ready to be serialized and stored
1767 * @param Zend_Server_Reflection_Function_Abstract $function can be any subclass of this object type
1771 function admin_mnet_method_profile(Zend_Server_Reflection_Function_Abstract
$function) {
1772 $protos = $function->getPrototypes();
1773 $proto = array_pop($protos);
1774 $ret = $proto->getReturnValue();
1776 'parameters' => array(),
1778 'type' => $ret->getType(),
1779 'description' => $ret->getDescription(),
1782 foreach ($proto->getParameters() as $p) {
1783 $profile['parameters'][] = array(
1784 'name' => $p->getName(),
1785 'type' => $p->getType(),
1786 'description' => $p->getDescription(),
1794 * This function finds duplicate records (based on combinations of fields that should be unique)
1795 * and then progamatically generated a "most correct" version of the data, update and removing
1796 * records as appropriate
1798 * Thanks to Dan Marsden for help
1800 * @param string $table Table name
1801 * @param array $uniques Array of field names that should be unique
1802 * @param array $fieldstocheck Array of fields to generate "correct" data from (optional)
1805 function upgrade_course_completion_remove_duplicates($table, $uniques, $fieldstocheck = array()) {
1809 $sql_cols = implode(', ', $uniques);
1811 $sql = "SELECT {$sql_cols} FROM {{$table}} GROUP BY {$sql_cols} HAVING (count(id) > 1)";
1812 $duplicates = $DB->get_recordset_sql($sql, array());
1814 // Loop through duplicates
1815 foreach ($duplicates as $duplicate) {
1818 // Generate SQL for finding records with these duplicate uniques
1819 $sql_select = implode(' = ? AND ', $uniques).' = ?'; // builds "fieldname = ? AND fieldname = ?"
1820 $uniq_values = array();
1821 foreach ($uniques as $u) {
1822 $uniq_values[] = $duplicate->$u;
1825 $sql_order = implode(' DESC, ', $uniques).' DESC'; // builds "fieldname DESC, fieldname DESC"
1827 // Get records with these duplicate uniques
1828 $records = $DB->get_records_select(
1835 // Loop through and build a "correct" record, deleting the others
1836 $needsupdate = false;
1838 foreach ($records as $record) {
1840 if ($pointer === 1) { // keep 1st record but delete all others.
1841 $origrecord = $record;
1843 // If we have fields to check, update original record
1844 if ($fieldstocheck) {
1845 // we need to keep the "oldest" of all these fields as the valid completion record.
1846 // but we want to ignore null values
1847 foreach ($fieldstocheck as $f) {
1848 if ($record->$f && (($origrecord->$f > $record->$f) ||
!$origrecord->$f)) {
1849 $origrecord->$f = $record->$f;
1850 $needsupdate = true;
1854 $DB->delete_records($table, array('id' => $record->id
));
1857 if ($needsupdate ||
isset($origrecord->reaggregate
)) {
1858 // If this table has a reaggregate field, update to force recheck on next cron run
1859 if (isset($origrecord->reaggregate
)) {
1860 $origrecord->reaggregate
= time();
1862 $DB->update_record($table, $origrecord);
1868 * Find questions missing an existing category and associate them with
1869 * a category which purpose is to gather them.
1873 function upgrade_save_orphaned_questions() {
1876 // Looking for orphaned questions
1877 $orphans = $DB->record_exists_select('question',
1878 'NOT EXISTS (SELECT 1 FROM {question_categories} WHERE {question_categories}.id = {question}.category)');
1883 // Generate a unique stamp for the orphaned questions category, easier to identify it later on
1884 $uniquestamp = "unknownhost+120719170400+orphan";
1885 $systemcontext = context_system
::instance();
1887 // Create the orphaned category at system level
1888 $cat = $DB->get_record('question_categories', array('stamp' => $uniquestamp,
1889 'contextid' => $systemcontext->id
));
1891 $cat = new stdClass();
1893 $cat->contextid
= $systemcontext->id
;
1894 $cat->name
= get_string('orphanedquestionscategory', 'question');
1895 $cat->info
= get_string('orphanedquestionscategoryinfo', 'question');
1896 $cat->sortorder
= 999;
1897 $cat->stamp
= $uniquestamp;
1898 $cat->id
= $DB->insert_record("question_categories", $cat);
1901 // Set a category to those orphans
1902 $params = array('catid' => $cat->id
);
1903 $DB->execute('UPDATE {question} SET category = :catid WHERE NOT EXISTS
1904 (SELECT 1 FROM {question_categories} WHERE {question_categories}.id = {question}.category)', $params);
1908 * Rename old backup files to current backup files.
1910 * When added the setting 'backup_shortname' (MDL-28657) the backup file names did not contain the id of the course.
1911 * Further we fixed that behaviour by forcing the id to be always present in the file name (MDL-33812).
1912 * This function will explore the backup directory and attempt to rename the previously created files to include
1913 * the id in the name. Doing this will put them back in the process of deleting the excess backups for each course.
1915 * This function manually recreates the file name, instead of using
1916 * {@link backup_plan_dbops::get_default_backup_filename()}, use it carefully if you're using it outside of the
1917 * usual upgrade process.
1919 * @see backup_cron_automated_helper::remove_excess_backups()
1920 * @link http://tracker.moodle.org/browse/MDL-35116
1924 function upgrade_rename_old_backup_files_using_shortname() {
1926 $dir = get_config('backup', 'backup_auto_destination');
1927 $useshortname = get_config('backup', 'backup_shortname');
1928 if (empty($dir) ||
!is_dir($dir) ||
!is_writable($dir)) {
1932 require_once($CFG->libdir
.'/textlib.class.php');
1933 require_once($CFG->dirroot
.'/backup/util/includes/backup_includes.php');
1934 $backupword = str_replace(' ', '_', textlib
::strtolower(get_string('backupfilename')));
1935 $backupword = trim(clean_filename($backupword), '_');
1936 $filename = $backupword . '-' . backup
::FORMAT_MOODLE
. '-' . backup
::TYPE_1COURSE
. '-';
1937 $regex = '#^'.preg_quote($filename, '#').'.*\.mbz$#';
1938 $thirtyapril = strtotime('30 April 2012 00:00');
1940 // Reading the directory.
1941 if (!$files = scandir($dir)) {
1944 foreach ($files as $file) {
1945 // Skip directories and files which do not start with the common prefix.
1946 // This avoids working on files which are not related to this issue.
1947 if (!is_file($dir . '/' . $file) ||
!preg_match($regex, $file)) {
1951 // Extract the information from the XML file.
1953 $bcinfo = backup_general_helper
::get_backup_information_from_mbz($dir . '/' . $file);
1954 } catch (backup_helper_exception
$e) {
1955 // Some error while retrieving the backup informations, skipping...
1959 // Make sure this a course backup.
1960 if ($bcinfo->format
!== backup
::FORMAT_MOODLE ||
$bcinfo->type
!== backup
::TYPE_1COURSE
) {
1964 // Skip the backups created before the short name option was initially introduced (MDL-28657).
1965 // This was integrated on the 2nd of May 2012. Let's play safe with timezone and use the 30th of April.
1966 if ($bcinfo->backup_date
< $thirtyapril) {
1970 // Let's check if the file name contains the ID where it is supposed to be, if it is the case then
1971 // we will skip the file. Of course it could happen that the course ID is identical to the course short name
1972 // even though really unlikely, but then renaming this file is not necessary. If the ID is not found in the
1973 // file name then it was probably the short name which was used.
1974 $idfilename = $filename . $bcinfo->original_course_id
. '-';
1975 $idregex = '#^'.preg_quote($idfilename, '#').'.*\.mbz$#';
1976 if (preg_match($idregex, $file)) {
1980 // Generating the file name manually. We do not use backup_plan_dbops::get_default_backup_filename() because
1981 // it will query the database to get some course information, and the course could not exist any more.
1982 $newname = $filename . $bcinfo->original_course_id
. '-';
1983 if ($useshortname) {
1984 $shortname = str_replace(' ', '_', $bcinfo->original_course_shortname
);
1985 $shortname = textlib
::strtolower(trim(clean_filename($shortname), '_'));
1986 $newname .= $shortname . '-';
1989 $backupdateformat = str_replace(' ', '_', get_string('backupnameformat', 'langconfig'));
1990 $date = userdate($bcinfo->backup_date
, $backupdateformat, 99, false);
1991 $date = textlib
::strtolower(trim(clean_filename($date), '_'));
1994 if (isset($bcinfo->root_settings
['users']) && !$bcinfo->root_settings
['users']) {
1996 } else if (isset($bcinfo->root_settings
['anonymize']) && $bcinfo->root_settings
['anonymize']) {
2001 // Final check before attempting the renaming.
2002 if ($newname == $file ||
file_exists($dir . '/' . $newname)) {
2005 @rename
($dir . '/' . $file, $dir . '/' . $newname);