MDL-26469 upgrade: cope with modules that do not set $module->cron.
[moodle.git] / lib / upgradelib.php
1 <?php
3 // This file is part of Moodle - http://moodle.org/
4 //
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
9 //
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 // GNU General Public License for more details.
14 //
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
18 /**
19  * Various upgrade/install related functions and classes.
20  *
21  * @package    core
22  * @subpackage upgrade
23  * @copyright  1999 onwards Martin Dougiamas (http://dougiamas.com)
24  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25  */
27 defined('MOODLE_INTERNAL') || die();
29 /** UPGRADE_LOG_NORMAL = 0 */
30 define('UPGRADE_LOG_NORMAL', 0);
31 /** UPGRADE_LOG_NOTICE = 1 */
32 define('UPGRADE_LOG_NOTICE', 1);
33 /** UPGRADE_LOG_ERROR = 2 */
34 define('UPGRADE_LOG_ERROR',  2);
36 /**
37  * Exception indicating unknown error during upgrade.
38  *
39  * @package    core
40  * @subpackage upgrade
41  * @copyright  2009 Petr Skoda {@link http://skodak.org}
42  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
43  */
44 class upgrade_exception extends moodle_exception {
45     function __construct($plugin, $version, $debuginfo=NULL) {
46         global $CFG;
47         $a = (object)array('plugin'=>$plugin, 'version'=>$version);
48         parent::__construct('upgradeerror', 'admin', "$CFG->wwwroot/$CFG->admin/index.php", $a, $debuginfo);
49     }
50 }
52 /**
53  * Exception indicating downgrade error during upgrade.
54  *
55  * @package    core
56  * @subpackage upgrade
57  * @copyright  2009 Petr Skoda {@link http://skodak.org}
58  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
59  */
60 class downgrade_exception extends moodle_exception {
61     function __construct($plugin, $oldversion, $newversion) {
62         global $CFG;
63         $plugin = is_null($plugin) ? 'moodle' : $plugin;
64         $a = (object)array('plugin'=>$plugin, 'oldversion'=>$oldversion, 'newversion'=>$newversion);
65         parent::__construct('cannotdowngrade', 'debug', "$CFG->wwwroot/$CFG->admin/index.php", $a);
66     }
67 }
69 /**
70  * @package    core
71  * @subpackage upgrade
72  * @copyright  2009 Petr Skoda {@link http://skodak.org}
73  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
74  */
75 class upgrade_requires_exception extends moodle_exception {
76     function __construct($plugin, $pluginversion, $currentmoodle, $requiremoodle) {
77         global $CFG;
78         $a = new stdClass();
79         $a->pluginname     = $plugin;
80         $a->pluginversion  = $pluginversion;
81         $a->currentmoodle  = $currentmoodle;
82         $a->requiremoodle  = $requiremoodle;
83         parent::__construct('pluginrequirementsnotmet', 'error', "$CFG->wwwroot/$CFG->admin/index.php", $a);
84     }
85 }
87 /**
88  * @package    core
89  * @subpackage upgrade
90  * @copyright  2009 Petr Skoda {@link http://skodak.org}
91  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
92  */
93 class plugin_defective_exception extends moodle_exception {
94     function __construct($plugin, $details) {
95         global $CFG;
96         parent::__construct('detectedbrokenplugin', 'error', "$CFG->wwwroot/$CFG->admin/index.php", $plugin, $details);
97     }
98 }
100 /**
101  * Upgrade savepoint, marks end of each upgrade block.
102  * It stores new main version, resets upgrade timeout
103  * and abort upgrade if user cancels page loading.
104  *
105  * Please do not make large upgrade blocks with lots of operations,
106  * for example when adding tables keep only one table operation per block.
107  *
108  * @global object
109  * @param bool $result false if upgrade step failed, true if completed
110  * @param string or float $version main version
111  * @param bool $allowabort allow user to abort script execution here
112  * @return void
113  */
114 function upgrade_main_savepoint($result, $version, $allowabort=true) {
115     global $CFG;
117     //sanity check to avoid confusion with upgrade_mod_savepoint usage.
118     if (!is_bool($allowabort)) {
119         $errormessage = 'Parameter type mismatch. Are you mixing up upgrade_main_savepoint() and upgrade_mod_savepoint()?';
120         throw new coding_exception($errormessage);
121     }
123     if (!$result) {
124         throw new upgrade_exception(null, $version);
125     }
127     if ($CFG->version >= $version) {
128         // something really wrong is going on in main upgrade script
129         throw new downgrade_exception(null, $CFG->version, $version);
130     }
132     set_config('version', $version);
133     upgrade_log(UPGRADE_LOG_NORMAL, null, 'Upgrade savepoint reached');
135     // reset upgrade timeout to default
136     upgrade_set_timeout();
138     // this is a safe place to stop upgrades if user aborts page loading
139     if ($allowabort and connection_aborted()) {
140         die;
141     }
144 /**
145  * Module upgrade savepoint, marks end of module upgrade blocks
146  * It stores module version, resets upgrade timeout
147  * and abort upgrade if user cancels page loading.
148  *
149  * @global object
150  * @param bool $result false if upgrade step failed, true if completed
151  * @param string or float $version main version
152  * @param string $modname name of module
153  * @param bool $allowabort allow user to abort script execution here
154  * @return void
155  */
156 function upgrade_mod_savepoint($result, $version, $modname, $allowabort=true) {
157     global $DB;
159     if (!$result) {
160         throw new upgrade_exception("mod_$modname", $version);
161     }
163     if (!$module = $DB->get_record('modules', array('name'=>$modname))) {
164         print_error('modulenotexist', 'debug', '', $modname);
165     }
167     if ($module->version >= $version) {
168         // something really wrong is going on in upgrade script
169         throw new downgrade_exception("mod_$modname", $module->version, $version);
170     }
171     $module->version = $version;
172     $DB->update_record('modules', $module);
173     upgrade_log(UPGRADE_LOG_NORMAL, "mod_$modname", 'Upgrade savepoint reached');
175     // reset upgrade timeout to default
176     upgrade_set_timeout();
178     // this is a safe place to stop upgrades if user aborts page loading
179     if ($allowabort and connection_aborted()) {
180         die;
181     }
184 /**
185  * Blocks upgrade savepoint, marks end of blocks upgrade blocks
186  * It stores block version, resets upgrade timeout
187  * and abort upgrade if user cancels page loading.
188  *
189  * @global object
190  * @param bool $result false if upgrade step failed, true if completed
191  * @param string or float $version main version
192  * @param string $blockname name of block
193  * @param bool $allowabort allow user to abort script execution here
194  * @return void
195  */
196 function upgrade_block_savepoint($result, $version, $blockname, $allowabort=true) {
197     global $DB;
199     if (!$result) {
200         throw new upgrade_exception("block_$blockname", $version);
201     }
203     if (!$block = $DB->get_record('block', array('name'=>$blockname))) {
204         print_error('blocknotexist', 'debug', '', $blockname);
205     }
207     if ($block->version >= $version) {
208         // something really wrong is going on in upgrade script
209         throw new downgrade_exception("block_$blockname", $block->version, $version);
210     }
211     $block->version = $version;
212     $DB->update_record('block', $block);
213     upgrade_log(UPGRADE_LOG_NORMAL, "block_$blockname", 'Upgrade savepoint reached');
215     // reset upgrade timeout to default
216     upgrade_set_timeout();
218     // this is a safe place to stop upgrades if user aborts page loading
219     if ($allowabort and connection_aborted()) {
220         die;
221     }
224 /**
225  * Plugins upgrade savepoint, marks end of blocks upgrade blocks
226  * It stores plugin version, resets upgrade timeout
227  * and abort upgrade if user cancels page loading.
228  *
229  * @param bool $result false if upgrade step failed, true if completed
230  * @param string or float $version main version
231  * @param string $type name of plugin
232  * @param string $dir location of plugin
233  * @param bool $allowabort allow user to abort script execution here
234  * @return void
235  */
236 function upgrade_plugin_savepoint($result, $version, $type, $plugin, $allowabort=true) {
237     $component = $type.'_'.$plugin;
239     if (!$result) {
240         throw new upgrade_exception($component, $version);
241     }
243     $installedversion = get_config($component, 'version');
244     if ($installedversion >= $version) {
245         // Something really wrong is going on in the upgrade script
246         throw new downgrade_exception($component, $installedversion, $version);
247     }
248     set_config('version', $version, $component);
249     upgrade_log(UPGRADE_LOG_NORMAL, $component, 'Upgrade savepoint reached');
251     // Reset upgrade timeout to default
252     upgrade_set_timeout();
254     // This is a safe place to stop upgrades if user aborts page loading
255     if ($allowabort and connection_aborted()) {
256         die;
257     }
261 /**
262  * Upgrade plugins
263  * @param string $type The type of plugins that should be updated (e.g. 'enrol', 'qtype')
264  * return void
265  */
266 function upgrade_plugins($type, $startcallback, $endcallback, $verbose) {
267     global $CFG, $DB;
269 /// special cases
270     if ($type === 'mod') {
271         return upgrade_plugins_modules($startcallback, $endcallback, $verbose);
272     } else if ($type === 'block') {
273         return upgrade_plugins_blocks($startcallback, $endcallback, $verbose);
274     }
276     $plugs = get_plugin_list($type);
278     foreach ($plugs as $plug=>$fullplug) {
279         $component = clean_param($type.'_'.$plug, PARAM_COMPONENT); // standardised plugin name
281         // check plugin dir is valid name
282         if (empty($component)) {
283             throw new plugin_defective_exception($type.'_'.$plug, 'Invalid plugin directory name.');
284         }
286         if (!is_readable($fullplug.'/version.php')) {
287             continue;
288         }
290         $plugin = new stdClass();
291         require($fullplug.'/version.php');  // defines $plugin with version etc
293         // if plugin tells us it's full name we may check the location
294         if (isset($plugin->component)) {
295             if ($plugin->component !== $component) {
296                 throw new plugin_defective_exception($component, 'Plugin installed in wrong folder.');
297             }
298         }
300         if (empty($plugin->version)) {
301             throw new plugin_defective_exception($component, 'Missing version value in version.php');
302         }
304         $plugin->name     = $plug;
305         $plugin->fullname = $component;
308         if (!empty($plugin->requires)) {
309             if ($plugin->requires > $CFG->version) {
310                 throw new upgrade_requires_exception($component, $plugin->version, $CFG->version, $plugin->requires);
311             } else if ($plugin->requires < 2010000000) {
312                 throw new plugin_defective_exception($component, 'Plugin is not compatible with Moodle 2.x or later.');
313             }
314         }
316         // try to recover from interrupted install.php if needed
317         if (file_exists($fullplug.'/db/install.php')) {
318             if (get_config($plugin->fullname, 'installrunning')) {
319                 require_once($fullplug.'/db/install.php');
320                 $recover_install_function = 'xmldb_'.$plugin->fullname.'_install_recovery';
321                 if (function_exists($recover_install_function)) {
322                     $startcallback($component, true, $verbose);
323                     $recover_install_function();
324                     unset_config('installrunning', $plugin->fullname);
325                     update_capabilities($component);
326                     log_update_descriptions($component);
327                     external_update_descriptions($component);
328                     events_update_definition($component);
329                     message_update_providers($component);
330                     if ($type === 'message') {
331                         message_update_processors($plug);
332                     }
333                     upgrade_plugin_mnet_functions($component);
334                     $endcallback($component, true, $verbose);
335                 }
336             }
337         }
339         $installedversion = get_config($plugin->fullname, 'version');
340         if (empty($installedversion)) { // new installation
341             $startcallback($component, true, $verbose);
343         /// Install tables if defined
344             if (file_exists($fullplug.'/db/install.xml')) {
345                 $DB->get_manager()->install_from_xmldb_file($fullplug.'/db/install.xml');
346             }
348         /// store version
349             upgrade_plugin_savepoint(true, $plugin->version, $type, $plug, false);
351         /// execute post install file
352             if (file_exists($fullplug.'/db/install.php')) {
353                 require_once($fullplug.'/db/install.php');
354                 set_config('installrunning', 1, $plugin->fullname);
355                 $post_install_function = 'xmldb_'.$plugin->fullname.'_install';
356                 $post_install_function();
357                 unset_config('installrunning', $plugin->fullname);
358             }
360         /// Install various components
361             update_capabilities($component);
362             log_update_descriptions($component);
363             external_update_descriptions($component);
364             events_update_definition($component);
365             message_update_providers($component);
366             if ($type === 'message') {
367                 message_update_processors($plug);
368             }
369             upgrade_plugin_mnet_functions($component);
371             purge_all_caches();
372             $endcallback($component, true, $verbose);
374         } else if ($installedversion < $plugin->version) { // upgrade
375         /// Run the upgrade function for the plugin.
376             $startcallback($component, false, $verbose);
378             if (is_readable($fullplug.'/db/upgrade.php')) {
379                 require_once($fullplug.'/db/upgrade.php');  // defines upgrading function
381                 $newupgrade_function = 'xmldb_'.$plugin->fullname.'_upgrade';
382                 $result = $newupgrade_function($installedversion);
383             } else {
384                 $result = true;
385             }
387             $installedversion = get_config($plugin->fullname, 'version');
388             if ($installedversion < $plugin->version) {
389                 // store version if not already there
390                 upgrade_plugin_savepoint($result, $plugin->version, $type, $plug, false);
391             }
393         /// Upgrade various components
394             update_capabilities($component);
395             log_update_descriptions($component);
396             external_update_descriptions($component);
397             events_update_definition($component);
398             message_update_providers($component);
399             if ($type === 'message') {
400                 message_update_processors($plug);
401             }
402             upgrade_plugin_mnet_functions($component);
404             purge_all_caches();
405             $endcallback($component, false, $verbose);
407         } else if ($installedversion > $plugin->version) {
408             throw new downgrade_exception($component, $installedversion, $plugin->version);
409         }
410     }
413 /**
414  * Find and check all modules and load them up or upgrade them if necessary
415  *
416  * @global object
417  * @global object
418  */
419 function upgrade_plugins_modules($startcallback, $endcallback, $verbose) {
420     global $CFG, $DB;
422     $mods = get_plugin_list('mod');
424     foreach ($mods as $mod=>$fullmod) {
426         if ($mod === 'NEWMODULE') {   // Someone has unzipped the template, ignore it
427             continue;
428         }
430         $component = clean_param('mod_'.$mod, PARAM_COMPONENT);
432         // check module dir is valid name
433         if (empty($component)) {
434             throw new plugin_defective_exception('mod_'.$mod, 'Invalid plugin directory name.');
435         }
437         if (!is_readable($fullmod.'/version.php')) {
438             throw new plugin_defective_exception($component, 'Missing version.php');
439         }
441         $module = new stdClass();
442         require($fullmod .'/version.php');  // defines $module with version etc
444         // if plugin tells us it's full name we may check the location
445         if (isset($module->component)) {
446             if ($module->component !== $component) {
447                 throw new plugin_defective_exception($component, 'Plugin installed in wrong folder.');
448             }
449         }
451         if (empty($module->version)) {
452             if (isset($module->version)) {
453                 // Version is empty but is set - it means its value is 0 or ''. Let us skip such module.
454                 // This is intended for developers so they can work on the early stages of the module.
455                 continue;
456             }
457             throw new plugin_defective_exception($component, 'Missing version value in version.php');
458         }
460         if (!empty($module->requires)) {
461             if ($module->requires > $CFG->version) {
462                 throw new upgrade_requires_exception($component, $module->version, $CFG->version, $module->requires);
463             } else if ($module->requires < 2010000000) {
464                 throw new plugin_defective_exception($component, 'Plugin is not compatible with Moodle 2.x or later.');
465             }
466         }
468         if (empty($module->cron)) {
469             $module->cron = 0;
470         }
472         // all modules must have en lang pack
473         if (!is_readable("$fullmod/lang/en/$mod.php")) {
474             throw new plugin_defective_exception($component, 'Missing mandatory en language pack.');
475         }
477         $module->name = $mod;   // The name MUST match the directory
479         $currmodule = $DB->get_record('modules', array('name'=>$module->name));
481         if (file_exists($fullmod.'/db/install.php')) {
482             if (get_config($module->name, 'installrunning')) {
483                 require_once($fullmod.'/db/install.php');
484                 $recover_install_function = 'xmldb_'.$module->name.'_install_recovery';
485                 if (function_exists($recover_install_function)) {
486                     $startcallback($component, true, $verbose);
487                     $recover_install_function();
488                     unset_config('installrunning', $module->name);
489                     // Install various components too
490                     update_capabilities($component);
491                     log_update_descriptions($component);
492                     external_update_descriptions($component);
493                     events_update_definition($component);
494                     message_update_providers($component);
495                     upgrade_plugin_mnet_functions($component);
496                     $endcallback($component, true, $verbose);
497                 }
498             }
499         }
501         if (empty($currmodule->version)) {
502             $startcallback($component, true, $verbose);
504         /// Execute install.xml (XMLDB) - must be present in all modules
505             $DB->get_manager()->install_from_xmldb_file($fullmod.'/db/install.xml');
507         /// Add record into modules table - may be needed in install.php already
508             $module->id = $DB->insert_record('modules', $module);
510         /// Post installation hook - optional
511             if (file_exists("$fullmod/db/install.php")) {
512                 require_once("$fullmod/db/install.php");
513                 // Set installation running flag, we need to recover after exception or error
514                 set_config('installrunning', 1, $module->name);
515                 $post_install_function = 'xmldb_'.$module->name.'_install';
516                 $post_install_function();
517                 unset_config('installrunning', $module->name);
518             }
520         /// Install various components
521             update_capabilities($component);
522             log_update_descriptions($component);
523             external_update_descriptions($component);
524             events_update_definition($component);
525             message_update_providers($component);
526             upgrade_plugin_mnet_functions($component);
528             purge_all_caches();
529             $endcallback($component, true, $verbose);
531         } else if ($currmodule->version < $module->version) {
532         /// If versions say that we need to upgrade but no upgrade files are available, notify and continue
533             $startcallback($component, false, $verbose);
535             if (is_readable($fullmod.'/db/upgrade.php')) {
536                 require_once($fullmod.'/db/upgrade.php');  // defines new upgrading function
537                 $newupgrade_function = 'xmldb_'.$module->name.'_upgrade';
538                 $result = $newupgrade_function($currmodule->version, $module);
539             } else {
540                 $result = true;
541             }
543             $currmodule = $DB->get_record('modules', array('name'=>$module->name));
544             if ($currmodule->version < $module->version) {
545                 // store version if not already there
546                 upgrade_mod_savepoint($result, $module->version, $mod, false);
547             }
549             // update cron flag if needed
550             if ($currmodule->cron != $module->cron) {
551                 $DB->set_field('modules', 'cron', $module->cron, array('name' => $module->name));
552             }
554             // Upgrade various components
555             update_capabilities($component);
556             log_update_descriptions($component);
557             external_update_descriptions($component);
558             events_update_definition($component);
559             message_update_providers($component);
560             upgrade_plugin_mnet_functions($component);
562             purge_all_caches();
564             $endcallback($component, false, $verbose);
566         } else if ($currmodule->version > $module->version) {
567             throw new downgrade_exception($component, $currmodule->version, $module->version);
568         }
569     }
573 /**
574  * This function finds all available blocks and install them
575  * into blocks table or do all the upgrade process if newer.
576  *
577  * @global object
578  * @global object
579  */
580 function upgrade_plugins_blocks($startcallback, $endcallback, $verbose) {
581     global $CFG, $DB;
583     require_once($CFG->dirroot.'/blocks/moodleblock.class.php');
585     $blocktitles   = array(); // we do not want duplicate titles
587     //Is this a first install
588     $first_install = null;
590     $blocks = get_plugin_list('block');
592     foreach ($blocks as $blockname=>$fullblock) {
594         if (is_null($first_install)) {
595             $first_install = ($DB->count_records('block_instances') == 0);
596         }
598         if ($blockname === 'NEWBLOCK') {   // Someone has unzipped the template, ignore it
599             continue;
600         }
602         $component = clean_param('block_'.$blockname, PARAM_COMPONENT);
604         // check block dir is valid name
605         if (empty($component)) {
606             throw new plugin_defective_exception('block_'.$blockname, 'Invalid plugin directory name.');
607         }
609         if (!is_readable($fullblock.'/version.php')) {
610             throw new plugin_defective_exception('block/'.$blockname, 'Missing version.php file.');
611         }
612         $plugin = new stdClass();
613         $plugin->version = NULL;
614         $plugin->cron    = 0;
615         include($fullblock.'/version.php');
616         $block = $plugin;
618         // if plugin tells us it's full name we may check the location
619         if (isset($block->component)) {
620             if ($block->component !== $component) {
621                 throw new plugin_defective_exception($component, 'Plugin installed in wrong folder.');
622             }
623         }
625         if (!empty($plugin->requires)) {
626             if ($plugin->requires > $CFG->version) {
627                 throw new upgrade_requires_exception($component, $plugin->version, $CFG->version, $plugin->requires);
628             } else if ($plugin->requires < 2010000000) {
629                 throw new plugin_defective_exception($component, 'Plugin is not compatible with Moodle 2.x or later.');
630             }
631         }
633         if (!is_readable($fullblock.'/block_'.$blockname.'.php')) {
634             throw new plugin_defective_exception('block/'.$blockname, 'Missing main block class file.');
635         }
636         include_once($fullblock.'/block_'.$blockname.'.php');
638         $classname = 'block_'.$blockname;
640         if (!class_exists($classname)) {
641             throw new plugin_defective_exception($component, 'Can not load main class.');
642         }
644         $blockobj    = new $classname;   // This is what we'll be testing
645         $blocktitle  = $blockobj->get_title();
647         // OK, it's as we all hoped. For further tests, the object will do them itself.
648         if (!$blockobj->_self_test()) {
649             throw new plugin_defective_exception($component, 'Self test failed.');
650         }
652         $block->name     = $blockname;   // The name MUST match the directory
654         if (empty($block->version)) {
655             throw new plugin_defective_exception($component, 'Missing block version.');
656         }
658         $currblock = $DB->get_record('block', array('name'=>$block->name));
660         if (file_exists($fullblock.'/db/install.php')) {
661             if (get_config('block_'.$blockname, 'installrunning')) {
662                 require_once($fullblock.'/db/install.php');
663                 $recover_install_function = 'xmldb_block_'.$blockname.'_install_recovery';
664                 if (function_exists($recover_install_function)) {
665                     $startcallback($component, true, $verbose);
666                     $recover_install_function();
667                     unset_config('installrunning', 'block_'.$blockname);
668                     // Install various components
669                     update_capabilities($component);
670                     log_update_descriptions($component);
671                     external_update_descriptions($component);
672                     events_update_definition($component);
673                     message_update_providers($component);
674                     upgrade_plugin_mnet_functions($component);
675                     $endcallback($component, true, $verbose);
676                 }
677             }
678         }
680         if (empty($currblock->version)) { // block not installed yet, so install it
681             $conflictblock = array_search($blocktitle, $blocktitles);
682             if ($conflictblock !== false) {
683                 // Duplicate block titles are not allowed, they confuse people
684                 // AND PHP's associative arrays ;)
685                 throw new plugin_defective_exception($component, get_string('blocknameconflict', 'error', (object)array('name'=>$block->name, 'conflict'=>$conflictblock)));
686             }
687             $startcallback($component, true, $verbose);
689             if (file_exists($fullblock.'/db/install.xml')) {
690                 $DB->get_manager()->install_from_xmldb_file($fullblock.'/db/install.xml');
691             }
692             $block->id = $DB->insert_record('block', $block);
694             if (file_exists($fullblock.'/db/install.php')) {
695                 require_once($fullblock.'/db/install.php');
696                 // Set installation running flag, we need to recover after exception or error
697                 set_config('installrunning', 1, 'block_'.$blockname);
698                 $post_install_function = 'xmldb_block_'.$blockname.'_install';;
699                 $post_install_function();
700                 unset_config('installrunning', 'block_'.$blockname);
701             }
703             $blocktitles[$block->name] = $blocktitle;
705             // Install various components
706             update_capabilities($component);
707             log_update_descriptions($component);
708             external_update_descriptions($component);
709             events_update_definition($component);
710             message_update_providers($component);
711             upgrade_plugin_mnet_functions($component);
713             purge_all_caches();
714             $endcallback($component, true, $verbose);
716         } else if ($currblock->version < $block->version) {
717             $startcallback($component, false, $verbose);
719             if (is_readable($fullblock.'/db/upgrade.php')) {
720                 require_once($fullblock.'/db/upgrade.php');  // defines new upgrading function
721                 $newupgrade_function = 'xmldb_block_'.$blockname.'_upgrade';
722                 $result = $newupgrade_function($currblock->version, $block);
723             } else {
724                 $result = true;
725             }
727             $currblock = $DB->get_record('block', array('name'=>$block->name));
728             if ($currblock->version < $block->version) {
729                 // store version if not already there
730                 upgrade_block_savepoint($result, $block->version, $block->name, false);
731             }
733             if ($currblock->cron != $block->cron) {
734                 // update cron flag if needed
735                 $currblock->cron = $block->cron;
736                 $DB->update_record('block', $currblock);
737             }
739             // Upgrade various components
740             update_capabilities($component);
741             log_update_descriptions($component);
742             external_update_descriptions($component);
743             events_update_definition($component);
744             message_update_providers($component);
745             upgrade_plugin_mnet_functions($component);
747             purge_all_caches();
748             $endcallback($component, false, $verbose);
750         } else if ($currblock->version > $block->version) {
751             throw new downgrade_exception($component, $currblock->version, $block->version);
752         }
753     }
756     // Finally, if we are in the first_install of BLOCKS setup frontpage and admin page blocks
757     if ($first_install) {
758         //Iterate over each course - there should be only site course here now
759         if ($courses = $DB->get_records('course')) {
760             foreach ($courses as $course) {
761                 blocks_add_default_course_blocks($course);
762             }
763         }
765         blocks_add_default_system_blocks();
766     }
770 /**
771  * Log_display description function used during install and upgrade.
772  *
773  * @param string $component name of component (moodle, mod_assignment, etc.)
774  * @return void
775  */
776 function log_update_descriptions($component) {
777     global $DB;
779     $defpath = get_component_directory($component).'/db/log.php';
781     if (!file_exists($defpath)) {
782         $DB->delete_records('log_display', array('component'=>$component));
783         return;
784     }
786     // load new info
787     $logs = array();
788     include($defpath);
789     $newlogs = array();
790     foreach ($logs as $log) {
791         $newlogs[$log['module'].'-'.$log['action']] = $log; // kind of unique name
792     }
793     unset($logs);
794     $logs = $newlogs;
796     $fields = array('module', 'action', 'mtable', 'field');
797     // update all log fist
798     $dblogs = $DB->get_records('log_display', array('component'=>$component));
799     foreach ($dblogs as $dblog) {
800         $name = $dblog->module.'-'.$dblog->action;
802         if (empty($logs[$name])) {
803             $DB->delete_records('log_display', array('id'=>$dblog->id));
804             continue;
805         }
807         $log = $logs[$name];
808         unset($logs[$name]);
810         $update = false;
811         foreach ($fields as $field) {
812             if ($dblog->$field != $log[$field]) {
813                 $dblog->$field = $log[$field];
814                 $update = true;
815             }
816         }
817         if ($update) {
818             $DB->update_record('log_display', $dblog);
819         }
820     }
821     foreach ($logs as $log) {
822         $dblog = (object)$log;
823         $dblog->component = $component;
824         $DB->insert_record('log_display', $dblog);
825     }
828 /**
829  * Web service discovery function used during install and upgrade.
830  * @param string $component name of component (moodle, mod_assignment, etc.)
831  * @return void
832  */
833 function external_update_descriptions($component) {
834     global $DB;
836     $defpath = get_component_directory($component).'/db/services.php';
838     if (!file_exists($defpath)) {
839         external_delete_descriptions($component);
840         return;
841     }
843     // load new info
844     $functions = array();
845     $services = array();
846     include($defpath);
848     // update all function fist
849     $dbfunctions = $DB->get_records('external_functions', array('component'=>$component));
850     foreach ($dbfunctions as $dbfunction) {
851         if (empty($functions[$dbfunction->name])) {
852             $DB->delete_records('external_functions', array('id'=>$dbfunction->id));
853             // do not delete functions from external_services_functions, beacuse
854             // we want to notify admins when functions used in custom services disappear
856             //TODO: this looks wrong, we have to delete it eventually (skodak)
857             continue;
858         }
860         $function = $functions[$dbfunction->name];
861         unset($functions[$dbfunction->name]);
862         $function['classpath'] = empty($function['classpath']) ? null : $function['classpath'];
864         $update = false;
865         if ($dbfunction->classname != $function['classname']) {
866             $dbfunction->classname = $function['classname'];
867             $update = true;
868         }
869         if ($dbfunction->methodname != $function['methodname']) {
870             $dbfunction->methodname = $function['methodname'];
871             $update = true;
872         }
873         if ($dbfunction->classpath != $function['classpath']) {
874             $dbfunction->classpath = $function['classpath'];
875             $update = true;
876         }
877         $functioncapabilities = key_exists('capabilities', $function)?$function['capabilities']:'';
878         if ($dbfunction->capabilities != $functioncapabilities) {
879             $dbfunction->capabilities = $functioncapabilities;
880             $update = true;
881         }
882         if ($update) {
883             $DB->update_record('external_functions', $dbfunction);
884         }
885     }
886     foreach ($functions as $fname => $function) {
887         $dbfunction = new stdClass();
888         $dbfunction->name       = $fname;
889         $dbfunction->classname  = $function['classname'];
890         $dbfunction->methodname = $function['methodname'];
891         $dbfunction->classpath  = empty($function['classpath']) ? null : $function['classpath'];
892         $dbfunction->component  = $component;
893         $dbfunction->capabilities = key_exists('capabilities', $function)?$function['capabilities']:'';
894         $dbfunction->id = $DB->insert_record('external_functions', $dbfunction);
895     }
896     unset($functions);
898     // now deal with services
899     $dbservices = $DB->get_records('external_services', array('component'=>$component));
900     foreach ($dbservices as $dbservice) {
901         if (empty($services[$dbservice->name])) {
902             $DB->delete_records('external_services_functions', array('externalserviceid'=>$dbservice->id));
903             $DB->delete_records('external_services_users', array('externalserviceid'=>$dbservice->id));
904             $DB->delete_records('external_services', array('id'=>$dbservice->id));
905             continue;
906         }
907         $service = $services[$dbservice->name];
908         unset($services[$dbservice->name]);
909         $service['enabled'] = empty($service['enabled']) ? 0 : $service['enabled'];
910         $service['requiredcapability'] = empty($service['requiredcapability']) ? null : $service['requiredcapability'];
911         $service['restrictedusers'] = !isset($service['restrictedusers']) ? 1 : $service['restrictedusers'];
912         $service['downloadfiles'] = !isset($service['downloadfiles']) ? 0 : $service['downloadfiles'];
913         $service['shortname'] = !isset($service['shortname']) ? null : $service['shortname'];
915         $update = false;
916         if ($dbservice->requiredcapability != $service['requiredcapability']) {
917             $dbservice->requiredcapability = $service['requiredcapability'];
918             $update = true;
919         }
920         if ($dbservice->restrictedusers != $service['restrictedusers']) {
921             $dbservice->restrictedusers = $service['restrictedusers'];
922             $update = true;
923         }
924         if ($dbservice->downloadfiles != $service['downloadfiles']) {
925             $dbservice->downloadfiles = $service['downloadfiles'];
926             $update = true;
927         }
928         //if shortname is not a PARAM_ALPHANUMEXT, fail (tested here for service update and creation)
929         if (isset($service['shortname']) and
930                 (clean_param($service['shortname'], PARAM_ALPHANUMEXT) != $service['shortname'])) {
931             throw new moodle_exception('installserviceshortnameerror', 'webservice', '', $service['shortname']);
932         }
933         if ($dbservice->shortname != $service['shortname']) {
934             //check that shortname is unique
935             if (isset($service['shortname'])) { //we currently accepts multiple shortname == null
936                 $existingservice = $DB->get_record('external_services',
937                         array('shortname' => $service['shortname']));
938                 if (!empty($existingservice)) {
939                     throw new moodle_exception('installexistingserviceshortnameerror', 'webservice', '', $service['shortname']);
940                 }
941             }
942             $dbservice->shortname = $service['shortname'];
943             $update = true;
944         }
945         if ($update) {
946             $DB->update_record('external_services', $dbservice);
947         }
949         $functions = $DB->get_records('external_services_functions', array('externalserviceid'=>$dbservice->id));
950         foreach ($functions as $function) {
951             $key = array_search($function->functionname, $service['functions']);
952             if ($key === false) {
953                 $DB->delete_records('external_services_functions', array('id'=>$function->id));
954             } else {
955                 unset($service['functions'][$key]);
956             }
957         }
958         foreach ($service['functions'] as $fname) {
959             $newf = new stdClass();
960             $newf->externalserviceid = $dbservice->id;
961             $newf->functionname      = $fname;
962             $DB->insert_record('external_services_functions', $newf);
963         }
964         unset($functions);
965     }
966     foreach ($services as $name => $service) {
967         //check that shortname is unique
968         if (isset($service['shortname'])) { //we currently accepts multiple shortname == null
969             $existingservice = $DB->get_record('external_services',
970                     array('shortname' => $service['shortname']));
971             if (!empty($existingservice)) {
972                 throw new moodle_exception('installserviceshortnameerror', 'webservice');
973             }
974         }
976         $dbservice = new stdClass();
977         $dbservice->name               = $name;
978         $dbservice->enabled            = empty($service['enabled']) ? 0 : $service['enabled'];
979         $dbservice->requiredcapability = empty($service['requiredcapability']) ? null : $service['requiredcapability'];
980         $dbservice->restrictedusers    = !isset($service['restrictedusers']) ? 1 : $service['restrictedusers'];
981         $dbservice->downloadfiles      = !isset($service['downloadfiles']) ? 0 : $service['downloadfiles'];
982         $dbservice->shortname          = !isset($service['shortname']) ? null : $service['shortname'];
983         $dbservice->component          = $component;
984         $dbservice->timecreated        = time();
985         $dbservice->id = $DB->insert_record('external_services', $dbservice);
986         foreach ($service['functions'] as $fname) {
987             $newf = new stdClass();
988             $newf->externalserviceid = $dbservice->id;
989             $newf->functionname      = $fname;
990             $DB->insert_record('external_services_functions', $newf);
991         }
992     }
995 /**
996  * Delete all service and external functions information defined in the specified component.
997  * @param string $component name of component (moodle, mod_assignment, etc.)
998  * @return void
999  */
1000 function external_delete_descriptions($component) {
1001     global $DB;
1003     $params = array($component);
1005     $DB->delete_records_select('external_services_users', "externalserviceid IN (SELECT id FROM {external_services} WHERE component = ?)", $params);
1006     $DB->delete_records_select('external_services_functions', "externalserviceid IN (SELECT id FROM {external_services} WHERE component = ?)", $params);
1007     $DB->delete_records('external_services', array('component'=>$component));
1008     $DB->delete_records('external_functions', array('component'=>$component));
1011 /**
1012  * upgrade logging functions
1013  */
1014 function upgrade_handle_exception($ex, $plugin = null) {
1015     global $CFG;
1017     // rollback everything, we need to log all upgrade problems
1018     abort_all_db_transactions();
1020     $info = get_exception_info($ex);
1022     // First log upgrade error
1023     upgrade_log(UPGRADE_LOG_ERROR, $plugin, 'Exception: ' . get_class($ex), $info->message, $info->backtrace);
1025     // Always turn on debugging - admins need to know what is going on
1026     $CFG->debug = DEBUG_DEVELOPER;
1028     default_exception_handler($ex, true, $plugin);
1031 /**
1032  * Adds log entry into upgrade_log table
1033  *
1034  * @param int $type UPGRADE_LOG_NORMAL, UPGRADE_LOG_NOTICE or UPGRADE_LOG_ERROR
1035  * @param string $plugin frankenstyle component name
1036  * @param string $info short description text of log entry
1037  * @param string $details long problem description
1038  * @param string $backtrace string used for errors only
1039  * @return void
1040  */
1041 function upgrade_log($type, $plugin, $info, $details=null, $backtrace=null) {
1042     global $DB, $USER, $CFG;
1044     if (empty($plugin)) {
1045         $plugin = 'core';
1046     }
1048     list($plugintype, $pluginname) = normalize_component($plugin);
1049     $component = is_null($pluginname) ? $plugintype : $plugintype . '_' . $pluginname;
1051     $backtrace = format_backtrace($backtrace, true);
1053     $currentversion = null;
1054     $targetversion  = null;
1056     //first try to find out current version number
1057     if ($plugintype === 'core') {
1058         //main
1059         $currentversion = $CFG->version;
1061         $version = null;
1062         include("$CFG->dirroot/version.php");
1063         $targetversion = $version;
1065     } else if ($plugintype === 'mod') {
1066         try {
1067             $currentversion = $DB->get_field('modules', 'version', array('name'=>$pluginname));
1068             $currentversion = ($currentversion === false) ? null : $currentversion;
1069         } catch (Exception $ignored) {
1070         }
1071         $cd = get_component_directory($component);
1072         if (file_exists("$cd/version.php")) {
1073             $module = new stdClass();
1074             $module->version = null;
1075             include("$cd/version.php");
1076             $targetversion = $module->version;
1077         }
1079     } else if ($plugintype === 'block') {
1080         try {
1081             if ($block = $DB->get_record('block', array('name'=>$pluginname))) {
1082                 $currentversion = $block->version;
1083             }
1084         } catch (Exception $ignored) {
1085         }
1086         $cd = get_component_directory($component);
1087         if (file_exists("$cd/version.php")) {
1088             $plugin = new stdClass();
1089             $plugin->version = null;
1090             include("$cd/version.php");
1091             $targetversion = $plugin->version;
1092         }
1094     } else {
1095         $pluginversion = get_config($component, 'version');
1096         if (!empty($pluginversion)) {
1097             $currentversion = $pluginversion;
1098         }
1099         $cd = get_component_directory($component);
1100         if (file_exists("$cd/version.php")) {
1101             $plugin = new stdClass();
1102             $plugin->version = null;
1103             include("$cd/version.php");
1104             $targetversion = $plugin->version;
1105         }
1106     }
1108     $log = new stdClass();
1109     $log->type          = $type;
1110     $log->plugin        = $component;
1111     $log->version       = $currentversion;
1112     $log->targetversion = $targetversion;
1113     $log->info          = $info;
1114     $log->details       = $details;
1115     $log->backtrace     = $backtrace;
1116     $log->userid        = $USER->id;
1117     $log->timemodified  = time();
1118     try {
1119         $DB->insert_record('upgrade_log', $log);
1120     } catch (Exception $ignored) {
1121         // possible during install or 2.0 upgrade
1122     }
1125 /**
1126  * Marks start of upgrade, blocks any other access to site.
1127  * The upgrade is finished at the end of script or after timeout.
1128  *
1129  * @global object
1130  * @global object
1131  * @global object
1132  */
1133 function upgrade_started($preinstall=false) {
1134     global $CFG, $DB, $PAGE, $OUTPUT;
1136     static $started = false;
1138     if ($preinstall) {
1139         ignore_user_abort(true);
1140         upgrade_setup_debug(true);
1142     } else if ($started) {
1143         upgrade_set_timeout(120);
1145     } else {
1146         if (!CLI_SCRIPT and !$PAGE->headerprinted) {
1147             $strupgrade  = get_string('upgradingversion', 'admin');
1148             $PAGE->set_pagelayout('maintenance');
1149             upgrade_init_javascript();
1150             $PAGE->set_title($strupgrade.' - Moodle '.$CFG->target_release);
1151             $PAGE->set_heading($strupgrade);
1152             $PAGE->navbar->add($strupgrade);
1153             $PAGE->set_cacheable(false);
1154             echo $OUTPUT->header();
1155         }
1157         ignore_user_abort(true);
1158         register_shutdown_function('upgrade_finished_handler');
1159         upgrade_setup_debug(true);
1160         set_config('upgraderunning', time()+300);
1161         $started = true;
1162     }
1165 /**
1166  * Internal function - executed if upgrade interrupted.
1167  */
1168 function upgrade_finished_handler() {
1169     upgrade_finished();
1172 /**
1173  * Indicates upgrade is finished.
1174  *
1175  * This function may be called repeatedly.
1176  *
1177  * @global object
1178  * @global object
1179  */
1180 function upgrade_finished($continueurl=null) {
1181     global $CFG, $DB, $OUTPUT;
1183     if (!empty($CFG->upgraderunning)) {
1184         unset_config('upgraderunning');
1185         upgrade_setup_debug(false);
1186         ignore_user_abort(false);
1187         if ($continueurl) {
1188             echo $OUTPUT->continue_button($continueurl);
1189             echo $OUTPUT->footer();
1190             die;
1191         }
1192     }
1195 /**
1196  * @global object
1197  * @global object
1198  */
1199 function upgrade_setup_debug($starting) {
1200     global $CFG, $DB;
1202     static $originaldebug = null;
1204     if ($starting) {
1205         if ($originaldebug === null) {
1206             $originaldebug = $DB->get_debug();
1207         }
1208         if (!empty($CFG->upgradeshowsql)) {
1209             $DB->set_debug(true);
1210         }
1211     } else {
1212         $DB->set_debug($originaldebug);
1213     }
1216 function print_upgrade_separator() {
1217     if (!CLI_SCRIPT) {
1218         echo '<hr />';
1219     }
1222 /**
1223  * Default start upgrade callback
1224  * @param string $plugin
1225  * @param bool $installation true if installation, false means upgrade
1226  */
1227 function print_upgrade_part_start($plugin, $installation, $verbose) {
1228     global $OUTPUT;
1229     if (empty($plugin) or $plugin == 'moodle') {
1230         upgrade_started($installation); // does not store upgrade running flag yet
1231         if ($verbose) {
1232             echo $OUTPUT->heading(get_string('coresystem'));
1233         }
1234     } else {
1235         upgrade_started();
1236         if ($verbose) {
1237             echo $OUTPUT->heading($plugin);
1238         }
1239     }
1240     if ($installation) {
1241         if (empty($plugin) or $plugin == 'moodle') {
1242             // no need to log - log table not yet there ;-)
1243         } else {
1244             upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Starting plugin installation');
1245         }
1246     } else {
1247         if (empty($plugin) or $plugin == 'moodle') {
1248             upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Starting core upgrade');
1249         } else {
1250             upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Starting plugin upgrade');
1251         }
1252     }
1255 /**
1256  * Default end upgrade callback
1257  * @param string $plugin
1258  * @param bool $installation true if installation, false means upgrade
1259  */
1260 function print_upgrade_part_end($plugin, $installation, $verbose) {
1261     global $OUTPUT;
1262     upgrade_started();
1263     if ($installation) {
1264         if (empty($plugin) or $plugin == 'moodle') {
1265             upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Core installed');
1266         } else {
1267             upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Plugin installed');
1268         }
1269     } else {
1270         if (empty($plugin) or $plugin == 'moodle') {
1271             upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Core upgraded');
1272         } else {
1273             upgrade_log(UPGRADE_LOG_NORMAL, $plugin, 'Plugin upgraded');
1274         }
1275     }
1276     if ($verbose) {
1277         echo $OUTPUT->notification(get_string('success'), 'notifysuccess');
1278         print_upgrade_separator();
1279     }
1282 /**
1283  * Sets up JS code required for all upgrade scripts.
1284  * @global object
1285  */
1286 function upgrade_init_javascript() {
1287     global $PAGE;
1288     // scroll to the end of each upgrade page so that ppl see either error or continue button,
1289     // no need to scroll continuously any more, it is enough to jump to end once the footer is printed ;-)
1290     $js = "window.scrollTo(0, 5000000);";
1291     $PAGE->requires->js_init_code($js);
1294 /**
1295  * Try to upgrade the given language pack (or current language)
1296  *
1297  * @param string $lang the code of the language to update, defaults to the current language
1298  */
1299 function upgrade_language_pack($lang = null) {
1300     global $CFG;
1302     if (!empty($CFG->skiplangupgrade)) {
1303         return;
1304     }
1306     if (!file_exists("$CFG->dirroot/$CFG->admin/tool/langimport/lib.php")) {
1307         // weird, somebody uninstalled the import utility
1308         return;
1309     }
1311     if (!$lang) {
1312         $lang = current_language();
1313     }
1315     if (!get_string_manager()->translation_exists($lang)) {
1316         return;
1317     }
1319     get_string_manager()->reset_caches();
1321     if ($lang === 'en') {
1322         return;  // Nothing to do
1323     }
1325     upgrade_started(false);
1327     require_once("$CFG->dirroot/$CFG->admin/tool/langimport/lib.php");
1328     tool_langimport_preupgrade_update($lang);
1330     get_string_manager()->reset_caches();
1332     print_upgrade_separator();
1335 /**
1336  * Install core moodle tables and initialize
1337  * @param float $version target version
1338  * @param bool $verbose
1339  * @return void, may throw exception
1340  */
1341 function install_core($version, $verbose) {
1342     global $CFG, $DB;
1344     try {
1345         set_time_limit(600);
1346         print_upgrade_part_start('moodle', true, $verbose); // does not store upgrade running flag
1348         $DB->get_manager()->install_from_xmldb_file("$CFG->libdir/db/install.xml");
1349         upgrade_started();     // we want the flag to be stored in config table ;-)
1351         // set all core default records and default settings
1352         require_once("$CFG->libdir/db/install.php");
1353         xmldb_main_install(); // installs the capabilities too
1355         // store version
1356         upgrade_main_savepoint(true, $version, false);
1358         // Continue with the installation
1359         log_update_descriptions('moodle');
1360         external_update_descriptions('moodle');
1361         events_update_definition('moodle');
1362         message_update_providers('moodle');
1364         // Write default settings unconditionally
1365         admin_apply_default_settings(NULL, true);
1367         print_upgrade_part_end(null, true, $verbose);
1368     } catch (exception $ex) {
1369         upgrade_handle_exception($ex);
1370     }
1373 /**
1374  * Upgrade moodle core
1375  * @param float $version target version
1376  * @param bool $verbose
1377  * @return void, may throw exception
1378  */
1379 function upgrade_core($version, $verbose) {
1380     global $CFG;
1382     raise_memory_limit(MEMORY_EXTRA);
1384     require_once($CFG->libdir.'/db/upgrade.php');    // Defines upgrades
1386     try {
1387         // Reset caches before any output
1388         purge_all_caches();
1390         // Upgrade current language pack if we can
1391         upgrade_language_pack();
1393         print_upgrade_part_start('moodle', false, $verbose);
1395         // one time special local migration pre 2.0 upgrade script
1396         if ($CFG->version < 2007101600) {
1397             $pre20upgradefile = "$CFG->dirroot/local/upgrade_pre20.php";
1398             if (file_exists($pre20upgradefile)) {
1399                 set_time_limit(0);
1400                 require($pre20upgradefile);
1401                 // reset upgrade timeout to default
1402                 upgrade_set_timeout();
1403             }
1404         }
1406         $result = xmldb_main_upgrade($CFG->version);
1407         if ($version > $CFG->version) {
1408             // store version if not already there
1409             upgrade_main_savepoint($result, $version, false);
1410         }
1412         // perform all other component upgrade routines
1413         update_capabilities('moodle');
1414         log_update_descriptions('moodle');
1415         external_update_descriptions('moodle');
1416         events_update_definition('moodle');
1417         message_update_providers('moodle');
1419         // Reset caches again, just to be sure
1420         purge_all_caches();
1422         // Clean up contexts - more and more stuff depends on existence of paths and contexts
1423         context_helper::cleanup_instances();
1424         context_helper::create_instances(null, false);
1425         context_helper::build_all_paths(false);
1426         $syscontext = context_system::instance();
1427         $syscontext->mark_dirty();
1429         print_upgrade_part_end('moodle', false, $verbose);
1430     } catch (Exception $ex) {
1431         upgrade_handle_exception($ex);
1432     }
1435 /**
1436  * Upgrade/install other parts of moodle
1437  * @param bool $verbose
1438  * @return void, may throw exception
1439  */
1440 function upgrade_noncore($verbose) {
1441     global $CFG;
1443     raise_memory_limit(MEMORY_EXTRA);
1445     // upgrade all plugins types
1446     try {
1447         $plugintypes = get_plugin_types();
1448         foreach ($plugintypes as $type=>$location) {
1449             upgrade_plugins($type, 'print_upgrade_part_start', 'print_upgrade_part_end', $verbose);
1450         }
1451     } catch (Exception $ex) {
1452         upgrade_handle_exception($ex);
1453     }
1456 /**
1457  * Checks if the main tables have been installed yet or not.
1458  * @return bool
1459  */
1460 function core_tables_exist() {
1461     global $DB;
1463     if (!$tables = $DB->get_tables() ) {    // No tables yet at all.
1464         return false;
1466     } else {                                 // Check for missing main tables
1467         $mtables = array('config', 'course', 'groupings'); // some tables used in 1.9 and 2.0, preferable something from the start and end of install.xml
1468         foreach ($mtables as $mtable) {
1469             if (!in_array($mtable, $tables)) {
1470                 return false;
1471             }
1472         }
1473         return true;
1474     }
1477 /**
1478  * upgrades the mnet rpc definitions for the given component.
1479  * this method doesn't return status, an exception will be thrown in the case of an error
1480  *
1481  * @param string $component the plugin to upgrade, eg auth_mnet
1482  */
1483 function upgrade_plugin_mnet_functions($component) {
1484     global $DB, $CFG;
1486     list($type, $plugin) = explode('_', $component);
1487     $path = get_plugin_directory($type, $plugin);
1489     $publishes = array();
1490     $subscribes = array();
1491     if (file_exists($path . '/db/mnet.php')) {
1492         require_once($path . '/db/mnet.php'); // $publishes comes from this file
1493     }
1494     if (empty($publishes)) {
1495         $publishes = array(); // still need this to be able to disable stuff later
1496     }
1497     if (empty($subscribes)) {
1498         $subscribes = array(); // still need this to be able to disable stuff later
1499     }
1501     static $servicecache = array();
1503     // rekey an array based on the rpc method for easy lookups later
1504     $publishmethodservices = array();
1505     $subscribemethodservices = array();
1506     foreach($publishes as $servicename => $service) {
1507         if (is_array($service['methods'])) {
1508             foreach($service['methods'] as $methodname) {
1509                 $service['servicename'] = $servicename;
1510                 $publishmethodservices[$methodname][] = $service;
1511             }
1512         }
1513     }
1515     // Disable functions that don't exist (any more) in the source
1516     // Should these be deleted? What about their permissions records?
1517     foreach ($DB->get_records('mnet_rpc', array('pluginname'=>$plugin, 'plugintype'=>$type), 'functionname ASC ') as $rpc) {
1518         if (!array_key_exists($rpc->functionname, $publishmethodservices) && $rpc->enabled) {
1519             $DB->set_field('mnet_rpc', 'enabled', 0, array('id' => $rpc->id));
1520         } else if (array_key_exists($rpc->functionname, $publishmethodservices) && !$rpc->enabled) {
1521             $DB->set_field('mnet_rpc', 'enabled', 1, array('id' => $rpc->id));
1522         }
1523     }
1525     // reflect all the services we're publishing and save them
1526     require_once($CFG->dirroot . '/lib/zend/Zend/Server/Reflection.php');
1527     static $cachedclasses = array(); // to store reflection information in
1528     foreach ($publishes as $service => $data) {
1529         $f = $data['filename'];
1530         $c = $data['classname'];
1531         foreach ($data['methods'] as $method) {
1532             $dataobject = new stdClass();
1533             $dataobject->plugintype  = $type;
1534             $dataobject->pluginname  = $plugin;
1535             $dataobject->enabled     = 1;
1536             $dataobject->classname   = $c;
1537             $dataobject->filename    = $f;
1539             if (is_string($method)) {
1540                 $dataobject->functionname = $method;
1542             } else if (is_array($method)) { // wants to override file or class
1543                 $dataobject->functionname = $method['method'];
1544                 $dataobject->classname     = $method['classname'];
1545                 $dataobject->filename      = $method['filename'];
1546             }
1547             $dataobject->xmlrpcpath = $type.'/'.$plugin.'/'.$dataobject->filename.'/'.$method;
1548             $dataobject->static = false;
1550             require_once($path . '/' . $dataobject->filename);
1551             $functionreflect = null; // slightly different ways to get this depending on whether it's a class method or a function
1552             if (!empty($dataobject->classname)) {
1553                 if (!class_exists($dataobject->classname)) {
1554                     throw new moodle_exception('installnosuchmethod', 'mnet', '', (object)array('method' => $dataobject->functionname, 'class' => $dataobject->classname));
1555                 }
1556                 $key = $dataobject->filename . '|' . $dataobject->classname;
1557                 if (!array_key_exists($key, $cachedclasses)) { // look to see if we've already got a reflection object
1558                     try {
1559                         $cachedclasses[$key] = Zend_Server_Reflection::reflectClass($dataobject->classname);
1560                     } catch (Zend_Server_Reflection_Exception $e) { // catch these and rethrow them to something more helpful
1561                         throw new moodle_exception('installreflectionclasserror', 'mnet', '', (object)array('method' => $dataobject->functionname, 'class' => $dataobject->classname, 'error' => $e->getMessage()));
1562                     }
1563                 }
1564                 $r =& $cachedclasses[$key];
1565                 if (!$r->hasMethod($dataobject->functionname)) {
1566                     throw new moodle_exception('installnosuchmethod', 'mnet', '', (object)array('method' => $dataobject->functionname, 'class' => $dataobject->classname));
1567                 }
1568                 // stupid workaround for zend not having a getMethod($name) function
1569                 $ms = $r->getMethods();
1570                 foreach ($ms as $m) {
1571                     if ($m->getName() == $dataobject->functionname) {
1572                         $functionreflect = $m;
1573                         break;
1574                     }
1575                 }
1576                 $dataobject->static = (int)$functionreflect->isStatic();
1577             } else {
1578                 if (!function_exists($dataobject->functionname)) {
1579                     throw new moodle_exception('installnosuchfunction', 'mnet', '', (object)array('method' => $dataobject->functionname, 'file' => $dataobject->filename));
1580                 }
1581                 try {
1582                     $functionreflect = Zend_Server_Reflection::reflectFunction($dataobject->functionname);
1583                 } catch (Zend_Server_Reflection_Exception $e) { // catch these and rethrow them to something more helpful
1584                     throw new moodle_exception('installreflectionfunctionerror', 'mnet', '', (object)array('method' => $dataobject->functionname, '' => $dataobject->filename, 'error' => $e->getMessage()));
1585                 }
1586             }
1587             $dataobject->profile =  serialize(admin_mnet_method_profile($functionreflect));
1588             $dataobject->help = $functionreflect->getDescription();
1590             if ($record_exists = $DB->get_record('mnet_rpc', array('xmlrpcpath'=>$dataobject->xmlrpcpath))) {
1591                 $dataobject->id      = $record_exists->id;
1592                 $dataobject->enabled = $record_exists->enabled;
1593                 $DB->update_record('mnet_rpc', $dataobject);
1594             } else {
1595                 $dataobject->id = $DB->insert_record('mnet_rpc', $dataobject, true);
1596             }
1598             // TODO this API versioning must be reworked, here the recently processed method
1599             // sets the service API which may not be correct
1600             foreach ($publishmethodservices[$dataobject->functionname] as $service) {
1601                 if ($serviceobj = $DB->get_record('mnet_service', array('name'=>$service['servicename']))) {
1602                     $serviceobj->apiversion = $service['apiversion'];
1603                     $DB->update_record('mnet_service', $serviceobj);
1604                 } else {
1605                     $serviceobj = new stdClass();
1606                     $serviceobj->name        = $service['servicename'];
1607                     $serviceobj->description = empty($service['description']) ? '' : $service['description'];
1608                     $serviceobj->apiversion  = $service['apiversion'];
1609                     $serviceobj->offer       = 1;
1610                     $serviceobj->id          = $DB->insert_record('mnet_service', $serviceobj);
1611                 }
1612                 $servicecache[$service['servicename']] = $serviceobj;
1613                 if (!$DB->record_exists('mnet_service2rpc', array('rpcid'=>$dataobject->id, 'serviceid'=>$serviceobj->id))) {
1614                     $obj = new stdClass();
1615                     $obj->rpcid = $dataobject->id;
1616                     $obj->serviceid = $serviceobj->id;
1617                     $DB->insert_record('mnet_service2rpc', $obj, true);
1618                 }
1619             }
1620         }
1621     }
1622     // finished with methods we publish, now do subscribable methods
1623     foreach($subscribes as $service => $methods) {
1624         if (!array_key_exists($service, $servicecache)) {
1625             if (!$serviceobj = $DB->get_record('mnet_service', array('name' =>  $service))) {
1626                 debugging("TODO: skipping unknown service $service - somebody needs to fix MDL-21993");
1627                 continue;
1628             }
1629             $servicecache[$service] = $serviceobj;
1630         } else {
1631             $serviceobj = $servicecache[$service];
1632         }
1633         foreach ($methods as $method => $xmlrpcpath) {
1634             if (!$rpcid = $DB->get_field('mnet_remote_rpc', 'id', array('xmlrpcpath'=>$xmlrpcpath))) {
1635                 $remoterpc = (object)array(
1636                     'functionname' => $method,
1637                     'xmlrpcpath' => $xmlrpcpath,
1638                     'plugintype' => $type,
1639                     'pluginname' => $plugin,
1640                     'enabled'    => 1,
1641                 );
1642                 $rpcid = $remoterpc->id = $DB->insert_record('mnet_remote_rpc', $remoterpc, true);
1643             }
1644             if (!$DB->record_exists('mnet_remote_service2rpc', array('rpcid'=>$rpcid, 'serviceid'=>$serviceobj->id))) {
1645                 $obj = new stdClass();
1646                 $obj->rpcid = $rpcid;
1647                 $obj->serviceid = $serviceobj->id;
1648                 $DB->insert_record('mnet_remote_service2rpc', $obj, true);
1649             }
1650             $subscribemethodservices[$method][] = $service;
1651         }
1652     }
1654     foreach ($DB->get_records('mnet_remote_rpc', array('pluginname'=>$plugin, 'plugintype'=>$type), 'functionname ASC ') as $rpc) {
1655         if (!array_key_exists($rpc->functionname, $subscribemethodservices) && $rpc->enabled) {
1656             $DB->set_field('mnet_remote_rpc', 'enabled', 0, array('id' => $rpc->id));
1657         } else if (array_key_exists($rpc->functionname, $subscribemethodservices) && !$rpc->enabled) {
1658             $DB->set_field('mnet_remote_rpc', 'enabled', 1, array('id' => $rpc->id));
1659         }
1660     }
1662     return true;
1665 /**
1666  * Given some sort of Zend Reflection function/method object, return a profile array, ready to be serialized and stored
1667  *
1668  * @param Zend_Server_Reflection_Function_Abstract $function can be any subclass of this object type
1669  *
1670  * @return array
1671  */
1672 function admin_mnet_method_profile(Zend_Server_Reflection_Function_Abstract $function) {
1673     $proto = array_pop($function->getPrototypes());
1674     $ret = $proto->getReturnValue();
1675     $profile = array(
1676         'parameters' =>  array(),
1677         'return'     =>  array(
1678             'type'        => $ret->getType(),
1679             'description' => $ret->getDescription(),
1680         ),
1681     );
1682     foreach ($proto->getParameters() as $p) {
1683         $profile['parameters'][] = array(
1684             'name' => $p->getName(),
1685             'type' => $p->getType(),
1686             'description' => $p->getDescription(),
1687         );
1688     }
1689     return $profile;