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 * Defines classes used for plugins management
21 * This library provides a unified interface to various plugin types in
22 * Moodle. It is mainly used by the plugins management admin page and the
23 * plugins check page during the upgrade.
27 * @copyright 2011 David Mudrak <david@moodle.com>
28 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
31 defined('MOODLE_INTERNAL') ||
die();
33 require_once($CFG->libdir
.'/filelib.php'); // curl class needed here
36 * Singleton class providing general plugins management functionality
38 class plugin_manager
{
40 /** the plugin is shipped with standard Moodle distribution */
41 const PLUGIN_SOURCE_STANDARD
= 'std';
42 /** the plugin is added extension */
43 const PLUGIN_SOURCE_EXTENSION
= 'ext';
45 /** the plugin uses neither database nor capabilities, no versions */
46 const PLUGIN_STATUS_NODB
= 'nodb';
47 /** the plugin is up-to-date */
48 const PLUGIN_STATUS_UPTODATE
= 'uptodate';
49 /** the plugin is about to be installed */
50 const PLUGIN_STATUS_NEW
= 'new';
51 /** the plugin is about to be upgraded */
52 const PLUGIN_STATUS_UPGRADE
= 'upgrade';
53 /** the standard plugin is about to be deleted */
54 const PLUGIN_STATUS_DELETE
= 'delete';
55 /** the version at the disk is lower than the one already installed */
56 const PLUGIN_STATUS_DOWNGRADE
= 'downgrade';
57 /** the plugin is installed but missing from disk */
58 const PLUGIN_STATUS_MISSING
= 'missing';
60 /** @var plugin_manager holds the singleton instance */
61 protected static $singletoninstance;
62 /** @var array of raw plugins information */
63 protected $pluginsinfo = null;
64 /** @var array of raw subplugins information */
65 protected $subpluginsinfo = null;
68 * Direct initiation not allowed, use the factory method {@link self::instance()}
70 protected function __construct() {
74 * Sorry, this is singleton
76 protected function __clone() {
80 * Factory method for this class
82 * @return plugin_manager the singleton instance
84 public static function instance() {
85 if (is_null(self
::$singletoninstance)) {
86 self
::$singletoninstance = new self();
88 return self
::$singletoninstance;
92 * Returns a tree of known plugins and information about them
94 * @param bool $disablecache force reload, cache can be used otherwise
95 * @return array 2D array. The first keys are plugin type names (e.g. qtype);
96 * the second keys are the plugin local name (e.g. multichoice); and
97 * the values are the corresponding objects extending {@link plugininfo_base}
99 public function get_plugins($disablecache=false) {
101 if ($disablecache or is_null($this->pluginsinfo
)) {
102 $this->pluginsinfo
= array();
103 $plugintypes = get_plugin_types();
104 $plugintypes = $this->reorder_plugin_types($plugintypes);
105 foreach ($plugintypes as $plugintype => $plugintyperootdir) {
106 if (in_array($plugintype, array('base', 'general'))) {
107 throw new coding_exception('Illegal usage of reserved word for plugin type');
109 if (class_exists('plugininfo_' . $plugintype)) {
110 $plugintypeclass = 'plugininfo_' . $plugintype;
112 $plugintypeclass = 'plugininfo_general';
114 if (!in_array('plugininfo_base', class_parents($plugintypeclass))) {
115 throw new coding_exception('Class ' . $plugintypeclass . ' must extend plugininfo_base');
117 $plugins = call_user_func(array($plugintypeclass, 'get_plugins'), $plugintype, $plugintyperootdir, $plugintypeclass);
118 $this->pluginsinfo
[$plugintype] = $plugins;
121 // TODO: MDL-20438 verify this is the correct solution/replace
122 if (!during_initial_install()) {
123 // append the information about available updates provided by {@link available_update_checker()}
124 $provider = available_update_checker
::instance();
125 foreach ($this->pluginsinfo
as $plugintype => $plugins) {
126 foreach ($plugins as $plugininfoholder) {
127 $plugininfoholder->check_available_updates($provider);
133 return $this->pluginsinfo
;
137 * Returns list of plugins that define their subplugins and the information
138 * about them from the db/subplugins.php file.
140 * At the moment, only activity modules can define subplugins.
142 * @param bool $disablecache force reload, cache can be used otherwise
143 * @return array with keys like 'mod_quiz', and values the data from the
144 * corresponding db/subplugins.php file.
146 public function get_subplugins($disablecache=false) {
148 if ($disablecache or is_null($this->subpluginsinfo
)) {
149 $this->subpluginsinfo
= array();
150 $mods = get_plugin_list('mod');
151 foreach ($mods as $mod => $moddir) {
152 $modsubplugins = array();
153 if (file_exists($moddir . '/db/subplugins.php')) {
154 include($moddir . '/db/subplugins.php');
155 foreach ($subplugins as $subplugintype => $subplugintyperootdir) {
156 $subplugin = new stdClass();
157 $subplugin->type
= $subplugintype;
158 $subplugin->typerootdir
= $subplugintyperootdir;
159 $modsubplugins[$subplugintype] = $subplugin;
161 $this->subpluginsinfo
['mod_' . $mod] = $modsubplugins;
166 return $this->subpluginsinfo
;
170 * Returns the name of the plugin that defines the given subplugin type
172 * If the given subplugin type is not actually a subplugin, returns false.
174 * @param string $subplugintype the name of subplugin type, eg. workshopform or quiz
175 * @return false|string the name of the parent plugin, eg. mod_workshop
177 public function get_parent_of_subplugin($subplugintype) {
180 foreach ($this->get_subplugins() as $pluginname => $subplugintypes) {
181 if (isset($subplugintypes[$subplugintype])) {
182 $parent = $pluginname;
191 * Returns a localized name of a given plugin
193 * @param string $plugin name of the plugin, eg mod_workshop or auth_ldap
196 public function plugin_name($plugin) {
197 list($type, $name) = normalize_component($plugin);
198 return $this->pluginsinfo
[$type][$name]->displayname
;
202 * Returns a localized name of a plugin type in plural form
204 * Most plugin types define their names in core_plugin lang file. In case of subplugins,
205 * we try to ask the parent plugin for the name. In the worst case, we will return
206 * the value of the passed $type parameter.
208 * @param string $type the type of the plugin, e.g. mod or workshopform
211 public function plugintype_name_plural($type) {
213 if (get_string_manager()->string_exists('type_' . $type . '_plural', 'core_plugin')) {
214 // for most plugin types, their names are defined in core_plugin lang file
215 return get_string('type_' . $type . '_plural', 'core_plugin');
217 } else if ($parent = $this->get_parent_of_subplugin($type)) {
218 // if this is a subplugin, try to ask the parent plugin for the name
219 if (get_string_manager()->string_exists('subplugintype_' . $type . '_plural', $parent)) {
220 return $this->plugin_name($parent) . ' / ' . get_string('subplugintype_' . $type . '_plural', $parent);
222 return $this->plugin_name($parent) . ' / ' . $type;
231 * @param string $component frankenstyle component name.
232 * @return plugininfo_base|null the corresponding plugin information.
234 public function get_plugin_info($component) {
235 list($type, $name) = normalize_component($component);
236 $plugins = $this->get_plugins();
237 if (isset($plugins[$type][$name])) {
238 return $plugins[$type][$name];
245 * Get a list of any other plugins that require this one.
246 * @param string $component frankenstyle component name.
247 * @return array of frankensyle component names that require this one.
249 public function other_plugins_that_require($component) {
251 foreach ($this->get_plugins() as $type => $plugins) {
252 foreach ($plugins as $plugin) {
253 $required = $plugin->get_other_required_plugins();
254 if (isset($required[$component])) {
255 $others[] = $plugin->component
;
263 * Check a dependencies list against the list of installed plugins.
264 * @param array $dependencies compenent name to required version or ANY_VERSION.
265 * @return bool true if all the dependencies are satisfied.
267 public function are_dependencies_satisfied($dependencies) {
268 foreach ($dependencies as $component => $requiredversion) {
269 $otherplugin = $this->get_plugin_info($component);
270 if (is_null($otherplugin)) {
274 if ($requiredversion != ANY_VERSION
and $otherplugin->versiondisk
< $requiredversion) {
283 * Checks all dependencies for all installed plugins. Used by install and upgrade.
284 * @param int $moodleversion the version from version.php.
285 * @return bool true if all the dependencies are satisfied for all plugins.
287 public function all_plugins_ok($moodleversion) {
288 foreach ($this->get_plugins() as $type => $plugins) {
289 foreach ($plugins as $plugin) {
291 if (!empty($plugin->versionrequires
) && $plugin->versionrequires
> $moodleversion) {
295 if (!$this->are_dependencies_satisfied($plugin->get_other_required_plugins())) {
305 * Checks if there are some plugins with a known available update
307 * @return bool true if there is at least one available update
309 public function some_plugins_updatable() {
310 foreach ($this->get_plugins() as $type => $plugins) {
311 foreach ($plugins as $plugin) {
312 if ($plugin->available_updates()) {
322 * Defines a list of all plugins that were originally shipped in the standard Moodle distribution,
323 * but are not anymore and are deleted during upgrades.
325 * The main purpose of this list is to hide missing plugins during upgrade.
327 * @param string $type plugin type
328 * @param string $name plugin name
331 public static function is_deleted_standard_plugin($type, $name) {
332 static $plugins = array(
333 // do not add 1.9-2.2 plugin removals here
336 if (!isset($plugins[$type])) {
339 return in_array($name, $plugins[$type]);
343 * Defines a white list of all plugins shipped in the standard Moodle distribution
345 * @param string $type
346 * @return false|array array of standard plugins or false if the type is unknown
348 public static function standard_plugins_list($type) {
349 static $standard_plugins = array(
351 'assignment' => array(
352 'offline', 'online', 'upload', 'uploadsingle'
356 'cas', 'db', 'email', 'fc', 'imap', 'ldap', 'manual', 'mnet',
357 'nntp', 'nologin', 'none', 'pam', 'pop3', 'radius',
358 'shibboleth', 'webservice'
362 'activity_modules', 'admin_bookmarks', 'blog_menu',
363 'blog_recent', 'blog_tags', 'calendar_month',
364 'calendar_upcoming', 'comments', 'community',
365 'completionstatus', 'course_list', 'course_overview',
366 'course_summary', 'feedback', 'glossary_random', 'html',
367 'login', 'mentees', 'messages', 'mnet_hosts', 'myprofile',
368 'navigation', 'news_items', 'online_users', 'participants',
369 'private_files', 'quiz_results', 'recent_activity',
370 'rss_client', 'search_forums', 'section_links',
371 'selfcompletion', 'settings', 'site_main_menu',
372 'social_activities', 'tag_flickr', 'tag_youtube', 'tags'
375 'coursereport' => array(
379 'datafield' => array(
380 'checkbox', 'date', 'file', 'latlong', 'menu', 'multimenu',
381 'number', 'picture', 'radiobutton', 'text', 'textarea', 'url'
384 'datapreset' => array(
389 'textarea', 'tinymce'
393 'authorize', 'category', 'cohort', 'database', 'flatfile',
394 'guest', 'imsenterprise', 'ldap', 'manual', 'meta', 'mnet',
399 'activitynames', 'algebra', 'censor', 'emailprotect',
400 'emoticon', 'mediaplugin', 'multilang', 'tex', 'tidy',
401 'urltolink', 'data', 'glossary'
405 'scorm', 'social', 'topics', 'weeks'
408 'gradeexport' => array(
409 'ods', 'txt', 'xls', 'xml'
412 'gradeimport' => array(
416 'gradereport' => array(
417 'grader', 'outcomes', 'overview', 'user'
420 'gradingform' => array(
428 'email', 'jabber', 'popup'
431 'mnetservice' => array(
436 'assignment', 'chat', 'choice', 'data', 'feedback', 'folder',
437 'forum', 'glossary', 'imscp', 'label', 'lesson', 'lti', 'page',
438 'quiz', 'resource', 'scorm', 'survey', 'url', 'wiki', 'workshop'
441 'plagiarism' => array(
444 'portfolio' => array(
445 'boxnet', 'download', 'flickr', 'googledocs', 'mahara', 'picasa'
448 'profilefield' => array(
449 'checkbox', 'datetime', 'menu', 'text', 'textarea'
452 'qbehaviour' => array(
453 'adaptive', 'adaptivenopenalty', 'deferredcbm',
454 'deferredfeedback', 'immediatecbm', 'immediatefeedback',
455 'informationitem', 'interactive', 'interactivecountback',
456 'manualgraded', 'missing'
460 'aiken', 'blackboard', 'blackboard_six', 'examview', 'gift',
461 'learnwise', 'missingword', 'multianswer', 'webct',
466 'calculated', 'calculatedmulti', 'calculatedsimple',
467 'description', 'essay', 'match', 'missingtype', 'multianswer',
468 'multichoice', 'numerical', 'random', 'randomsamatch',
469 'shortanswer', 'truefalse'
473 'grading', 'overview', 'responses', 'statistics'
476 'quizaccess' => array(
477 'delaybetweenattempts', 'ipaddress', 'numattempts', 'openclosedate',
478 'password', 'safebrowser', 'securewindow', 'timelimit'
482 'backups', 'completion', 'configlog', 'courseoverview',
483 'log', 'loglive', 'outline', 'participation', 'progress', 'questioninstances', 'security', 'stats'
486 'repository' => array(
487 'alfresco', 'boxnet', 'coursefiles', 'dropbox', 'filesystem',
488 'flickr', 'flickr_public', 'googledocs', 'local', 'merlot',
489 'picasa', 'recent', 's3', 'upload', 'url', 'user', 'webdav',
490 'wikimedia', 'youtube'
493 'scormreport' => array(
500 'afterburner', 'anomaly', 'arialist', 'base', 'binarius',
501 'boxxie', 'brick', 'canvas', 'formal_white', 'formfactor',
502 'fusion', 'leatherbound', 'magazine', 'mymobile', 'nimble',
503 'nonzero', 'overlay', 'serenity', 'sky_high', 'splash',
504 'standard', 'standardold'
508 'bloglevelupgrade', 'capability', 'customlang', 'dbtransfer', 'generator',
509 'health', 'innodb', 'langimport', 'multilangupgrade', 'phpunit', 'profiling',
510 'qeupgradehelper', 'replace', 'spamcleaner', 'timezoneimport', 'unittest',
511 'uploaduser', 'unsuproles', 'xmldb'
514 'webservice' => array(
515 'amf', 'rest', 'soap', 'xmlrpc'
518 'workshopallocation' => array(
519 'manual', 'random', 'scheduled'
522 'workshopeval' => array(
526 'workshopform' => array(
527 'accumulative', 'comments', 'numerrors', 'rubric'
531 if (isset($standard_plugins[$type])) {
532 return $standard_plugins[$type];
539 * Reorders plugin types into a sequence to be displayed
541 * For technical reasons, plugin types returned by {@link get_plugin_types()} are
542 * in a certain order that does not need to fit the expected order for the display.
543 * Particularly, activity modules should be displayed first as they represent the
544 * real heart of Moodle. They should be followed by other plugin types that are
545 * used to build the courses (as that is what one expects from LMS). After that,
546 * other supportive plugin types follow.
548 * @param array $types associative array
549 * @return array same array with altered order of items
551 protected function reorder_plugin_types(array $types) {
553 'mod' => $types['mod'],
554 'block' => $types['block'],
555 'qtype' => $types['qtype'],
556 'qbehaviour' => $types['qbehaviour'],
557 'qformat' => $types['qformat'],
558 'filter' => $types['filter'],
559 'enrol' => $types['enrol'],
561 foreach ($types as $type => $path) {
562 if (!isset($fix[$type])) {
572 * General exception thrown by the {@link available_update_checker} class
574 class available_update_checker_exception
extends moodle_exception
{
577 * @param string $errorcode exception description identifier
578 * @param mixed $debuginfo debugging data to display
580 public function __construct($errorcode, $debuginfo=null) {
581 parent
::__construct($errorcode, 'core_plugin', '', null, print_r($debuginfo, true));
587 * Singleton class that handles checking for available updates
589 class available_update_checker
{
591 /** @var available_update_checker holds the singleton instance */
592 protected static $singletoninstance;
593 /** @var null|int the timestamp of when the most recent response was fetched */
594 protected $recentfetch = null;
595 /** @var null|array the recent response from the update notification provider */
596 protected $recentresponse = null;
597 /** @var null|string the numerical version of the local Moodle code */
598 protected $currentversion = null;
599 /** @var null|string the release info of the local Moodle code */
600 protected $currentrelease = null;
601 /** @var null|string branch of the local Moodle code */
602 protected $currentbranch = null;
603 /** @var array of (string)frankestyle => (string)version list of additional plugins deployed at this site */
604 protected $currentplugins = array();
607 * Direct initiation not allowed, use the factory method {@link self::instance()}
609 protected function __construct() {
613 * Sorry, this is singleton
615 protected function __clone() {
619 * Factory method for this class
621 * @return available_update_checker the singleton instance
623 public static function instance() {
624 if (is_null(self
::$singletoninstance)) {
625 self
::$singletoninstance = new self();
627 return self
::$singletoninstance;
631 * Returns the timestamp of the last execution of {@link fetch()}
633 * @return int|null null if it has never been executed or we don't known
635 public function get_last_timefetched() {
637 $this->restore_response();
639 if (!empty($this->recentfetch
)) {
640 return $this->recentfetch
;
648 * Fetches the available update status from the remote site
650 * @throws available_update_checker_exception
652 public function fetch() {
653 $response = $this->get_response();
654 $this->validate_response($response);
655 $this->store_response($response);
659 * Returns the available update information for the given component
661 * This method returns null if the most recent response does not contain any information
662 * about it. The returned structure is an array of available updates for the given
663 * component. Each update info is an object with at least one property called
664 * 'version'. Other possible properties are 'release', 'maturity', 'url' and 'downloadurl'.
666 * For the 'core' component, the method returns real updates only (those with higher version).
667 * For all other components, the list of all known remote updates is returned and the caller
668 * (usually the {@link plugin_manager}) is supposed to make the actual comparison of versions.
670 * @param string $component frankenstyle
671 * @param array $options with supported keys 'minmaturity' and/or 'notifybuilds'
672 * @return null|array null or array of available_update_info objects
674 public function get_update_info($component, array $options = array()) {
676 if (!isset($options['minmaturity'])) {
677 $options['minmaturity'] = 0;
680 if (!isset($options['notifybuilds'])) {
681 $options['notifybuilds'] = false;
684 if ($component == 'core') {
685 $this->load_current_environment();
688 $this->restore_response();
690 if (empty($this->recentresponse
['updates'][$component])) {
695 foreach ($this->recentresponse
['updates'][$component] as $info) {
696 $update = new available_update_info($component, $info);
697 if (isset($update->maturity
) and ($update->maturity
< $options['minmaturity'])) {
700 if ($component == 'core') {
701 if ($update->version
<= $this->currentversion
) {
704 if (empty($options['notifybuilds']) and $this->is_same_release($update->release
)) {
708 $updates[] = $update;
711 if (empty($updates)) {
719 * The method being run via cron.php
721 public function cron() {
724 if (!$this->cron_autocheck_enabled()) {
725 $this->cron_mtrace('Automatic check for available updates not enabled, skipping.');
729 $now = $this->cron_current_timestamp();
731 if ($this->cron_has_fresh_fetch($now)) {
732 $this->cron_mtrace('Recently fetched info about available updates is still fresh enough, skipping.');
736 if ($this->cron_has_outdated_fetch($now)) {
737 $this->cron_mtrace('Outdated or missing info about available updates, forced fetching ... ', '');
738 $this->cron_execute();
742 $offset = $this->cron_execution_offset();
743 $start = mktime(1, 0, 0, date('n', $now), date('j', $now), date('Y', $now)); // 01:00 AM today local time
744 if ($now > $start +
$offset) {
745 $this->cron_mtrace('Regular daily check for available updates ... ', '');
746 $this->cron_execute();
751 /// end of public API //////////////////////////////////////////////////////
754 * Makes cURL request to get data from the remote site
756 * @return string raw request result
757 * @throws available_update_checker_exception
759 protected function get_response() {
760 $curl = new curl(array('proxy' => true));
761 $response = $curl->post($this->prepare_request_url(), $this->prepare_request_params());
762 $curlinfo = $curl->get_info();
763 if ($curlinfo['http_code'] != 200) {
764 throw new available_update_checker_exception('err_response_http_code', $curlinfo['http_code']);
770 * Makes sure the response is valid, has correct API format etc.
772 * @param string $response raw response as returned by the {@link self::get_response()}
773 * @throws available_update_checker_exception
775 protected function validate_response($response) {
777 $response = $this->decode_response($response);
779 if (empty($response)) {
780 throw new available_update_checker_exception('err_response_empty');
783 if (empty($response['status']) or $response['status'] !== 'OK') {
784 throw new available_update_checker_exception('err_response_status', $response['status']);
787 if (empty($response['apiver']) or $response['apiver'] !== '1.0') {
788 throw new available_update_checker_exception('err_response_format_version', $response['apiver']);
791 if (empty($response['forbranch']) or $response['forbranch'] !== moodle_major_version(true)) {
792 throw new available_update_checker_exception('err_response_target_version', $response['target']);
797 * Decodes the raw string response from the update notifications provider
799 * @param string $response as returned by {@link self::get_response()}
800 * @return array decoded response structure
802 protected function decode_response($response) {
803 return json_decode($response, true);
807 * Stores the valid fetched response for later usage
809 * This implementation uses the config_plugins table as the permanent storage.
811 * @param string $response raw valid data returned by {@link self::get_response()}
813 protected function store_response($response) {
815 set_config('recentfetch', time(), 'core_plugin');
816 set_config('recentresponse', $response, 'core_plugin');
818 $this->restore_response(true);
822 * Loads the most recent raw response record we have fetched
824 * This implementation uses the config_plugins table as the permanent storage.
826 * @param bool $forcereload reload even if it was already loaded
828 protected function restore_response($forcereload = false) {
830 if (!$forcereload and !is_null($this->recentresponse
)) {
831 // we already have it, nothing to do
835 $config = get_config('core_plugin');
837 if (!empty($config->recentresponse
) and !empty($config->recentfetch
)) {
839 $this->validate_response($config->recentresponse
);
840 $this->recentfetch
= $config->recentfetch
;
841 $this->recentresponse
= $this->decode_response($config->recentresponse
);
842 } catch (available_update_checker_exception
$e) {
843 // do not set recentresponse if the validation fails
847 $this->recentresponse
= array();
852 * Compares two raw {@link $recentresponse} records and returns the list of changed updates
854 * This method is used to populate potential update info to be sent to site admins.
858 * @throws available_update_checker_exception
859 * @return array parts of $new['updates'] that have changed
861 protected function compare_responses(array $old, array $new) {
867 if (!array_key_exists('updates', $new)) {
868 throw new available_update_checker_exception('err_response_format');
872 return $new['updates'];
875 if (!array_key_exists('updates', $old)) {
876 throw new available_update_checker_exception('err_response_format');
881 foreach ($new['updates'] as $newcomponent => $newcomponentupdates) {
882 if (empty($old['updates'][$newcomponent])) {
883 $changes[$newcomponent] = $newcomponentupdates;
886 foreach ($newcomponentupdates as $newcomponentupdate) {
888 foreach ($old['updates'][$newcomponent] as $oldcomponentupdate) {
889 if ($newcomponentupdate['version'] == $oldcomponentupdate['version']) {
894 if (!isset($changes[$newcomponent])) {
895 $changes[$newcomponent] = array();
897 $changes[$newcomponent][] = $newcomponentupdate;
906 * Returns the URL to send update requests to
908 * During the development or testing, you can set $CFG->alternativeupdateproviderurl
909 * to a custom URL that will be used. Otherwise the standard URL will be returned.
913 protected function prepare_request_url() {
916 if (!empty($CFG->alternativeupdateproviderurl
)) {
917 return $CFG->alternativeupdateproviderurl
;
919 return 'http://download.moodle.org/api/1.0/updates.php';
924 * Sets the properties currentversion, currentrelease, currentbranch and currentplugins
926 * @param bool $forcereload
928 protected function load_current_environment($forcereload=false) {
931 if (!is_null($this->currentversion
) and !$forcereload) {
936 require($CFG->dirroot
.'/version.php');
937 $this->currentversion
= $version;
938 $this->currentrelease
= $release;
939 $this->currentbranch
= moodle_major_version(true);
941 $pluginman = plugin_manager
::instance();
942 foreach ($pluginman->get_plugins() as $type => $plugins) {
943 foreach ($plugins as $plugin) {
944 if (!$plugin->is_standard()) {
945 $this->currentplugins
[$plugin->component
] = $plugin->versiondisk
;
952 * Returns the list of HTTP params to be sent to the updates provider URL
954 * @return array of (string)param => (string)value
956 protected function prepare_request_params() {
959 $this->load_current_environment();
960 $this->restore_response();
963 $params['format'] = 'json';
965 if (isset($this->recentresponse
['ticket'])) {
966 $params['ticket'] = $this->recentresponse
['ticket'];
969 if (isset($this->currentversion
)) {
970 $params['version'] = $this->currentversion
;
972 throw new coding_exception('Main Moodle version must be already known here');
975 if (isset($this->currentbranch
)) {
976 $params['branch'] = $this->currentbranch
;
978 throw new coding_exception('Moodle release must be already known here');
982 foreach ($this->currentplugins
as $plugin => $version) {
983 $plugins[] = $plugin.'@'.$version;
985 if (!empty($plugins)) {
986 $params['plugins'] = implode(',', $plugins);
993 * Returns the current timestamp
995 * @return int the timestamp
997 protected function cron_current_timestamp() {
1002 * Output cron debugging info
1005 * @param string $msg output message
1006 * @param string $eol end of line
1008 protected function cron_mtrace($msg, $eol = PHP_EOL
) {
1013 * Decide if the autocheck feature is disabled in the server setting
1015 * @return bool true if autocheck enabled, false if disabled
1017 protected function cron_autocheck_enabled() {
1020 if (empty($CFG->updateautocheck
)) {
1028 * Decide if the recently fetched data are still fresh enough
1030 * @param int $now current timestamp
1031 * @return bool true if no need to re-fetch, false otherwise
1033 protected function cron_has_fresh_fetch($now) {
1034 $recent = $this->get_last_timefetched();
1036 if (empty($recent)) {
1040 if ($now < $recent) {
1041 $this->cron_mtrace('The most recent fetch is reported to be in the future, this is weird!');
1045 if ($now - $recent > HOURSECS
) {
1053 * Decide if the fetch is outadated or even missing
1055 * @param int $now current timestamp
1056 * @return bool false if no need to re-fetch, true otherwise
1058 protected function cron_has_outdated_fetch($now) {
1059 $recent = $this->get_last_timefetched();
1061 if (empty($recent)) {
1065 if ($now < $recent) {
1066 $this->cron_mtrace('The most recent fetch is reported to be in the future, this is weird!');
1070 if ($now - $recent > 48 * HOURSECS
) {
1078 * Returns the cron execution offset for this site
1080 * The main {@link self::cron()} is supposed to run every night in some random time
1081 * between 01:00 and 06:00 AM (local time). The exact moment is defined by so called
1082 * execution offset, that is the amount of time after 01:00 AM. The offset value is
1083 * initially generated randomly and then used consistently at the site. This way, the
1084 * regular checks against the download.moodle.org server are spread in time.
1086 * @return int the offset number of seconds from range 1 sec to 5 hours
1088 protected function cron_execution_offset() {
1091 if (empty($CFG->updatecronoffset
)) {
1092 set_config('updatecronoffset', rand(1, 5 * HOURSECS
));
1095 return $CFG->updatecronoffset
;
1099 * Fetch available updates info and eventually send notification to site admins
1101 protected function cron_execute() {
1103 $this->restore_response();
1104 $previous = $this->recentresponse
;
1106 $this->restore_response(true);
1107 $current = $this->recentresponse
;
1109 $changes = $this->compare_responses($previous, $current);
1110 $notifications = $this->cron_notifications($changes);
1111 $this->cron_notify($notifications);
1112 $this->cron_mtrace('done');
1113 } catch (available_update_checker_exception
$e) {
1114 $this->cron_mtrace('FAILED!');
1119 * Given the list of changes in available updates, pick those to send to site admins
1121 * @param array $changes as returned by {@link self::compare_responses()}
1122 * @return array of available_update_info objects to send to site admins
1124 protected function cron_notifications(array $changes) {
1127 $notifications = array();
1128 $pluginman = plugin_manager
::instance();
1129 $plugins = $pluginman->get_plugins(true);
1131 foreach ($changes as $component => $componentchanges) {
1132 if (empty($componentchanges)) {
1135 $componentupdates = $this->get_update_info($component,
1136 array('minmaturity' => $CFG->updateminmaturity
, 'notifybuilds' => $CFG->updatenotifybuilds
));
1137 if (empty($componentupdates)) {
1140 // notify only about those $componentchanges that are present in $componentupdates
1141 // to respect the preferences
1142 foreach ($componentchanges as $componentchange) {
1143 foreach ($componentupdates as $componentupdate) {
1144 if ($componentupdate->version
== $componentchange['version']) {
1145 if ($component == 'core') {
1146 // in case of 'core' this is enough, we already know that the
1147 // $componentupdate is a real update with higher version
1148 $notifications[] = $componentupdate;
1150 // use the plugin_manager to check if the reported $componentchange
1151 // is a real update with higher version. such a real update must be
1152 // present in the 'availableupdates' property of one of the component's
1153 // available_update_info object
1154 list($plugintype, $pluginname) = normalize_component($component);
1155 if (!empty($plugins[$plugintype][$pluginname]->availableupdates
)) {
1156 foreach ($plugins[$plugintype][$pluginname]->availableupdates
as $availableupdate) {
1157 if ($availableupdate->version
== $componentchange['version']) {
1158 $notifications[] = $componentupdate;
1168 return $notifications;
1172 * Sends the given notifications to site admins via messaging API
1174 * @param array $notifications array of available_update_info objects to send
1176 protected function cron_notify(array $notifications) {
1179 if (empty($notifications)) {
1183 $admins = get_admins();
1185 if (empty($admins)) {
1189 $this->cron_mtrace('sending notifications ... ', '');
1191 $text = get_string('updatenotifications', 'core_admin') . PHP_EOL
;
1192 $html = html_writer
::tag('h1', get_string('updatenotifications', 'core_admin')) . PHP_EOL
;
1194 $coreupdates = array();
1195 $pluginupdates = array();
1197 foreach ($notifications as $notification) {
1198 if ($notification->component
== 'core') {
1199 $coreupdates[] = $notification;
1201 $pluginupdates[] = $notification;
1205 if (!empty($coreupdates)) {
1206 $text .= PHP_EOL
. get_string('updateavailable', 'core_admin') . PHP_EOL
;
1207 $html .= html_writer
::tag('h2', get_string('updateavailable', 'core_admin')) . PHP_EOL
;
1208 $html .= html_writer
::start_tag('ul') . PHP_EOL
;
1209 foreach ($coreupdates as $coreupdate) {
1210 $html .= html_writer
::start_tag('li');
1211 if (isset($coreupdate->release
)) {
1212 $text .= get_string('updateavailable_release', 'core_admin', $coreupdate->release
);
1213 $html .= html_writer
::tag('strong', get_string('updateavailable_release', 'core_admin', $coreupdate->release
));
1215 if (isset($coreupdate->version
)) {
1216 $text .= ' '.get_string('updateavailable_version', 'core_admin', $coreupdate->version
);
1217 $html .= ' '.get_string('updateavailable_version', 'core_admin', $coreupdate->version
);
1219 if (isset($coreupdate->maturity
)) {
1220 $text .= ' ('.get_string('maturity'.$coreupdate->maturity
, 'core_admin').')';
1221 $html .= ' ('.get_string('maturity'.$coreupdate->maturity
, 'core_admin').')';
1224 $html .= html_writer
::end_tag('li') . PHP_EOL
;
1227 $html .= html_writer
::end_tag('ul') . PHP_EOL
;
1229 $a = array('url' => $CFG->wwwroot
.'/'.$CFG->admin
.'/index.php');
1230 $text .= get_string('updateavailabledetailslink', 'core_admin', $a) . PHP_EOL
;
1231 $a = array('url' => html_writer
::link($CFG->wwwroot
.'/'.$CFG->admin
.'/index.php', $CFG->wwwroot
.'/'.$CFG->admin
.'/index.php'));
1232 $html .= html_writer
::tag('p', get_string('updateavailabledetailslink', 'core_admin', $a)) . PHP_EOL
;
1235 if (!empty($pluginupdates)) {
1236 $text .= PHP_EOL
. get_string('updateavailableforplugin', 'core_admin') . PHP_EOL
;
1237 $html .= html_writer
::tag('h2', get_string('updateavailableforplugin', 'core_admin')) . PHP_EOL
;
1239 $html .= html_writer
::start_tag('ul') . PHP_EOL
;
1240 foreach ($pluginupdates as $pluginupdate) {
1241 $html .= html_writer
::start_tag('li');
1242 $text .= get_string('pluginname', $pluginupdate->component
);
1243 $html .= html_writer
::tag('strong', get_string('pluginname', $pluginupdate->component
));
1245 $text .= ' ('.$pluginupdate->component
.')';
1246 $html .= ' ('.$pluginupdate->component
.')';
1248 $text .= ' '.get_string('updateavailable', 'core_plugin', $pluginupdate->version
);
1249 $html .= ' '.get_string('updateavailable', 'core_plugin', $pluginupdate->version
);
1252 $html .= html_writer
::end_tag('li') . PHP_EOL
;
1255 $html .= html_writer
::end_tag('ul') . PHP_EOL
;
1257 $a = array('url' => $CFG->wwwroot
.'/'.$CFG->admin
.'/plugins.php');
1258 $text .= get_string('updateavailabledetailslink', 'core_admin', $a) . PHP_EOL
;
1259 $a = array('url' => html_writer
::link($CFG->wwwroot
.'/'.$CFG->admin
.'/plugins.php', $CFG->wwwroot
.'/'.$CFG->admin
.'/plugins.php'));
1260 $html .= html_writer
::tag('p', get_string('updateavailabledetailslink', 'core_admin', $a)) . PHP_EOL
;
1263 $a = array('siteurl' => $CFG->wwwroot
);
1264 $text .= get_string('updatenotificationfooter', 'core_admin', $a) . PHP_EOL
;
1265 $a = array('siteurl' => html_writer
::link($CFG->wwwroot
, $CFG->wwwroot
));
1266 $html .= html_writer
::tag('footer', html_writer
::tag('p', get_string('updatenotificationfooter', 'core_admin', $a),
1267 array('style' => 'font-size:smaller; color:#333;')));
1269 $mainadmin = reset($admins);
1271 foreach ($admins as $admin) {
1272 $message = new stdClass();
1273 $message->component
= 'moodle';
1274 $message->name
= 'availableupdate';
1275 $message->userfrom
= $mainadmin;
1276 $message->userto
= $admin;
1277 $message->subject
= get_string('updatenotifications', 'core_admin');
1278 $message->fullmessage
= $text;
1279 $message->fullmessageformat
= FORMAT_PLAIN
;
1280 $message->fullmessagehtml
= $html;
1281 $message->smallmessage
= get_string('updatenotifications', 'core_admin');
1282 $message->notification
= 1;
1283 message_send($message);
1288 * Compare two release labels and decide if they are the same
1290 * @param string $remote release info of the available update
1291 * @param null|string $local release info of the local code, defaults to $release defined in version.php
1292 * @return boolean true if the releases declare the same minor+major version
1294 protected function is_same_release($remote, $local=null) {
1296 if (is_null($local)) {
1297 $this->load_current_environment();
1298 $local = $this->currentrelease
;
1301 $pattern = '/^([0-9\.\+]+)([^(]*)/';
1303 preg_match($pattern, $remote, $remotematches);
1304 preg_match($pattern, $local, $localmatches);
1306 $remotematches[1] = str_replace('+', '', $remotematches[1]);
1307 $localmatches[1] = str_replace('+', '', $localmatches[1]);
1309 if ($remotematches[1] === $localmatches[1] and rtrim($remotematches[2]) === rtrim($localmatches[2])) {
1319 * Defines the structure of objects returned by {@link available_update_checker::get_update_info()}
1321 class available_update_info
{
1323 /** @var string frankenstyle component name */
1325 /** @var int the available version of the component */
1327 /** @var string|null optional release name */
1328 public $release = null;
1329 /** @var int|null optional maturity info, eg {@link MATURITY_STABLE} */
1330 public $maturity = null;
1331 /** @var string|null optional URL of a page with more info about the update */
1333 /** @var string|null optional URL of a ZIP package that can be downloaded and installed */
1334 public $download = null;
1337 * Creates new instance of the class
1339 * The $info array must provide at least the 'version' value and optionally all other
1340 * values to populate the object's properties.
1342 * @param string $name the frankenstyle component name
1343 * @param array $info associative array with other properties
1345 public function __construct($name, array $info) {
1346 $this->component
= $name;
1347 foreach ($info as $k => $v) {
1348 if (property_exists('available_update_info', $k) and $k != 'component') {
1357 * Factory class producing required subclasses of {@link plugininfo_base}
1359 class plugininfo_default_factory
{
1362 * Makes a new instance of the plugininfo class
1364 * @param string $type the plugin type, eg. 'mod'
1365 * @param string $typerootdir full path to the location of all the plugins of this type
1366 * @param string $name the plugin name, eg. 'workshop'
1367 * @param string $namerootdir full path to the location of the plugin
1368 * @param string $typeclass the name of class that holds the info about the plugin
1369 * @return plugininfo_base the instance of $typeclass
1371 public static function make($type, $typerootdir, $name, $namerootdir, $typeclass) {
1372 $plugin = new $typeclass();
1373 $plugin->type
= $type;
1374 $plugin->typerootdir
= $typerootdir;
1375 $plugin->name
= $name;
1376 $plugin->rootdir
= $namerootdir;
1378 $plugin->init_display_name();
1379 $plugin->load_disk_version();
1380 $plugin->load_db_version();
1381 $plugin->load_required_main_version();
1382 $plugin->init_is_standard();
1390 * Base class providing access to the information about a plugin
1392 * @property-read string component the component name, type_name
1394 abstract class plugininfo_base
{
1396 /** @var string the plugintype name, eg. mod, auth or workshopform */
1398 /** @var string full path to the location of all the plugins of this type */
1399 public $typerootdir;
1400 /** @var string the plugin name, eg. assignment, ldap */
1402 /** @var string the localized plugin name */
1403 public $displayname;
1404 /** @var string the plugin source, one of plugin_manager::PLUGIN_SOURCE_xxx constants */
1406 /** @var fullpath to the location of this plugin */
1408 /** @var int|string the version of the plugin's source code */
1409 public $versiondisk;
1410 /** @var int|string the version of the installed plugin */
1412 /** @var int|float|string required version of Moodle core */
1413 public $versionrequires;
1414 /** @var array other plugins that this one depends on, lazy-loaded by {@link get_other_required_plugins()} */
1415 public $dependencies;
1416 /** @var int number of instances of the plugin - not supported yet */
1418 /** @var int order of the plugin among other plugins of the same type - not supported yet */
1420 /** @var array|null array of {@link available_update_info} for this plugin */
1421 public $availableupdates;
1424 * Gathers and returns the information about all plugins of the given type
1426 * @param string $type the name of the plugintype, eg. mod, auth or workshopform
1427 * @param string $typerootdir full path to the location of the plugin dir
1428 * @param string $typeclass the name of the actually called class
1429 * @return array of plugintype classes, indexed by the plugin name
1431 public static function get_plugins($type, $typerootdir, $typeclass) {
1433 // get the information about plugins at the disk
1434 $plugins = get_plugin_list($type);
1436 foreach ($plugins as $pluginname => $pluginrootdir) {
1437 $ondisk[$pluginname] = plugininfo_default_factory
::make($type, $typerootdir,
1438 $pluginname, $pluginrootdir, $typeclass);
1444 * Sets {@link $displayname} property to a localized name of the plugin
1446 public function init_display_name() {
1447 if (!get_string_manager()->string_exists('pluginname', $this->component
)) {
1448 $this->displayname
= '[pluginname,' . $this->component
. ']';
1450 $this->displayname
= get_string('pluginname', $this->component
);
1455 * Magic method getter, redirects to read only values.
1457 * @param string $name
1460 public function __get($name) {
1462 case 'component': return $this->type
. '_' . $this->name
;
1465 debugging('Invalid plugin property accessed! '.$name);
1471 * Return the full path name of a file within the plugin.
1473 * No check is made to see if the file exists.
1475 * @param string $relativepath e.g. 'version.php'.
1476 * @return string e.g. $CFG->dirroot . '/mod/quiz/version.php'.
1478 public function full_path($relativepath) {
1479 if (empty($this->rootdir
)) {
1482 return $this->rootdir
. '/' . $relativepath;
1486 * Load the data from version.php.
1488 * @return stdClass the object called $plugin defined in version.php
1490 protected function load_version_php() {
1491 $versionfile = $this->full_path('version.php');
1493 $plugin = new stdClass();
1494 if (is_readable($versionfile)) {
1495 include($versionfile);
1501 * Sets {@link $versiondisk} property to a numerical value representing the
1502 * version of the plugin's source code.
1504 * If the value is null after calling this method, either the plugin
1505 * does not use versioning (typically does not have any database
1506 * data) or is missing from disk.
1508 public function load_disk_version() {
1509 $plugin = $this->load_version_php();
1510 if (isset($plugin->version
)) {
1511 $this->versiondisk
= $plugin->version
;
1516 * Sets {@link $versionrequires} property to a numerical value representing
1517 * the version of Moodle core that this plugin requires.
1519 public function load_required_main_version() {
1520 $plugin = $this->load_version_php();
1521 if (isset($plugin->requires
)) {
1522 $this->versionrequires
= $plugin->requires
;
1527 * Initialise {@link $dependencies} to the list of other plugins (in any)
1528 * that this one requires to be installed.
1530 protected function load_other_required_plugins() {
1531 $plugin = $this->load_version_php();
1532 if (!empty($plugin->dependencies
)) {
1533 $this->dependencies
= $plugin->dependencies
;
1535 $this->dependencies
= array(); // By default, no dependencies.
1540 * Get the list of other plugins that this plugin requires to be installed.
1542 * @return array with keys the frankenstyle plugin name, and values either
1543 * a version string (like '2011101700') or the constant ANY_VERSION.
1545 public function get_other_required_plugins() {
1546 if (is_null($this->dependencies
)) {
1547 $this->load_other_required_plugins();
1549 return $this->dependencies
;
1553 * Sets {@link $versiondb} property to a numerical value representing the
1554 * currently installed version of the plugin.
1556 * If the value is null after calling this method, either the plugin
1557 * does not use versioning (typically does not have any database
1558 * data) or has not been installed yet.
1560 public function load_db_version() {
1561 if ($ver = self
::get_version_from_config_plugins($this->component
)) {
1562 $this->versiondb
= $ver;
1567 * Sets {@link $source} property to one of plugin_manager::PLUGIN_SOURCE_xxx
1570 * If the property's value is null after calling this method, then
1571 * the type of the plugin has not been recognized and you should throw
1574 public function init_is_standard() {
1576 $standard = plugin_manager
::standard_plugins_list($this->type
);
1578 if ($standard !== false) {
1579 $standard = array_flip($standard);
1580 if (isset($standard[$this->name
])) {
1581 $this->source
= plugin_manager
::PLUGIN_SOURCE_STANDARD
;
1582 } else if (!is_null($this->versiondb
) and is_null($this->versiondisk
)
1583 and plugin_manager
::is_deleted_standard_plugin($this->type
, $this->name
)) {
1584 $this->source
= plugin_manager
::PLUGIN_SOURCE_STANDARD
; // to be deleted
1586 $this->source
= plugin_manager
::PLUGIN_SOURCE_EXTENSION
;
1592 * Returns true if the plugin is shipped with the official distribution
1593 * of the current Moodle version, false otherwise.
1597 public function is_standard() {
1598 return $this->source
=== plugin_manager
::PLUGIN_SOURCE_STANDARD
;
1602 * Returns the status of the plugin
1604 * @return string one of plugin_manager::PLUGIN_STATUS_xxx constants
1606 public function get_status() {
1608 if (is_null($this->versiondb
) and is_null($this->versiondisk
)) {
1609 return plugin_manager
::PLUGIN_STATUS_NODB
;
1611 } else if (is_null($this->versiondb
) and !is_null($this->versiondisk
)) {
1612 return plugin_manager
::PLUGIN_STATUS_NEW
;
1614 } else if (!is_null($this->versiondb
) and is_null($this->versiondisk
)) {
1615 if (plugin_manager
::is_deleted_standard_plugin($this->type
, $this->name
)) {
1616 return plugin_manager
::PLUGIN_STATUS_DELETE
;
1618 return plugin_manager
::PLUGIN_STATUS_MISSING
;
1621 } else if ((string)$this->versiondb
=== (string)$this->versiondisk
) {
1622 return plugin_manager
::PLUGIN_STATUS_UPTODATE
;
1624 } else if ($this->versiondb
< $this->versiondisk
) {
1625 return plugin_manager
::PLUGIN_STATUS_UPGRADE
;
1627 } else if ($this->versiondb
> $this->versiondisk
) {
1628 return plugin_manager
::PLUGIN_STATUS_DOWNGRADE
;
1631 // $version = pi(); and similar funny jokes - hopefully Donald E. Knuth will never contribute to Moodle ;-)
1632 throw new coding_exception('Unable to determine plugin state, check the plugin versions');
1637 * Returns the information about plugin availability
1639 * True means that the plugin is enabled. False means that the plugin is
1640 * disabled. Null means that the information is not available, or the
1641 * plugin does not support configurable availability or the availability
1642 * can not be changed.
1646 public function is_enabled() {
1651 * Populates the property {@link $availableupdates} with the information provided by
1652 * available update checker
1654 * @param available_update_checker $provider the class providing the available update info
1656 public function check_available_updates(available_update_checker
$provider) {
1659 if (isset($CFG->updateminmaturity
)) {
1660 $minmaturity = $CFG->updateminmaturity
;
1662 // this can happen during the very first upgrade to 2.3
1663 $minmaturity = MATURITY_STABLE
;
1666 $this->availableupdates
= $provider->get_update_info($this->component
,
1667 array('minmaturity' => $minmaturity));
1671 * If there are updates for this plugin available, returns them.
1673 * Returns array of {@link available_update_info} objects, if some update
1674 * is available. Returns null if there is no update available or if the update
1675 * availability is unknown.
1677 * @return array|null
1679 public function available_updates() {
1681 if (empty($this->availableupdates
) or !is_array($this->availableupdates
)) {
1687 foreach ($this->availableupdates
as $availableupdate) {
1688 if ($availableupdate->version
> $this->versiondisk
) {
1689 $updates[] = $availableupdate;
1693 if (empty($updates)) {
1701 * Returns the URL of the plugin settings screen
1703 * Null value means that the plugin either does not have the settings screen
1704 * or its location is not available via this library.
1706 * @return null|moodle_url
1708 public function get_settings_url() {
1713 * Returns the URL of the screen where this plugin can be uninstalled
1715 * Visiting that URL must be safe, that is a manual confirmation is needed
1716 * for actual uninstallation of the plugin. Null value means that the
1717 * plugin either does not support uninstallation, or does not require any
1718 * database cleanup or the location of the screen is not available via this
1721 * @return null|moodle_url
1723 public function get_uninstall_url() {
1728 * Returns relative directory of the plugin with heading '/'
1732 public function get_dir() {
1735 return substr($this->rootdir
, strlen($CFG->dirroot
));
1739 * Provides access to plugin versions from {config_plugins}
1741 * @param string $plugin plugin name
1742 * @param double $disablecache optional, defaults to false
1743 * @return int|false the stored value or false if not found
1745 protected function get_version_from_config_plugins($plugin, $disablecache=false) {
1747 static $pluginversions = null;
1749 if (is_null($pluginversions) or $disablecache) {
1751 $pluginversions = $DB->get_records_menu('config_plugins', array('name' => 'version'), 'plugin', 'plugin,value');
1752 } catch (dml_exception
$e) {
1754 $pluginversions = array();
1758 if (!array_key_exists($plugin, $pluginversions)) {
1762 return $pluginversions[$plugin];
1768 * General class for all plugin types that do not have their own class
1770 class plugininfo_general
extends plugininfo_base
{
1775 * Class for page side blocks
1777 class plugininfo_block
extends plugininfo_base
{
1779 public static function get_plugins($type, $typerootdir, $typeclass) {
1781 // get the information about blocks at the disk
1782 $blocks = parent
::get_plugins($type, $typerootdir, $typeclass);
1784 // add blocks missing from disk
1785 $blocksinfo = self
::get_blocks_info();
1786 foreach ($blocksinfo as $blockname => $blockinfo) {
1787 if (isset($blocks[$blockname])) {
1790 $plugin = new $typeclass();
1791 $plugin->type
= $type;
1792 $plugin->typerootdir
= $typerootdir;
1793 $plugin->name
= $blockname;
1794 $plugin->rootdir
= null;
1795 $plugin->displayname
= $blockname;
1796 $plugin->versiondb
= $blockinfo->version
;
1797 $plugin->init_is_standard();
1799 $blocks[$blockname] = $plugin;
1805 public function init_display_name() {
1807 if (get_string_manager()->string_exists('pluginname', 'block_' . $this->name
)) {
1808 $this->displayname
= get_string('pluginname', 'block_' . $this->name
);
1810 } else if (($block = block_instance($this->name
)) !== false) {
1811 $this->displayname
= $block->get_title();
1814 parent
::init_display_name();
1818 public function load_db_version() {
1821 $blocksinfo = self
::get_blocks_info();
1822 if (isset($blocksinfo[$this->name
]->version
)) {
1823 $this->versiondb
= $blocksinfo[$this->name
]->version
;
1827 public function is_enabled() {
1829 $blocksinfo = self
::get_blocks_info();
1830 if (isset($blocksinfo[$this->name
]->visible
)) {
1831 if ($blocksinfo[$this->name
]->visible
) {
1837 return parent
::is_enabled();
1841 public function get_settings_url() {
1843 if (($block = block_instance($this->name
)) === false) {
1844 return parent
::get_settings_url();
1846 } else if ($block->has_config()) {
1847 if (file_exists($this->full_path('settings.php'))) {
1848 return new moodle_url('/admin/settings.php', array('section' => 'blocksetting' . $this->name
));
1850 $blocksinfo = self
::get_blocks_info();
1851 return new moodle_url('/admin/block.php', array('block' => $blocksinfo[$this->name
]->id
));
1855 return parent
::get_settings_url();
1859 public function get_uninstall_url() {
1861 $blocksinfo = self
::get_blocks_info();
1862 return new moodle_url('/admin/blocks.php', array('delete' => $blocksinfo[$this->name
]->id
, 'sesskey' => sesskey()));
1866 * Provides access to the records in {block} table
1868 * @param bool $disablecache do not use internal static cache
1869 * @return array array of stdClasses
1871 protected static function get_blocks_info($disablecache=false) {
1873 static $blocksinfocache = null;
1875 if (is_null($blocksinfocache) or $disablecache) {
1877 $blocksinfocache = $DB->get_records('block', null, 'name', 'name,id,version,visible');
1878 } catch (dml_exception
$e) {
1880 $blocksinfocache = array();
1884 return $blocksinfocache;
1890 * Class for text filters
1892 class plugininfo_filter
extends plugininfo_base
{
1894 public static function get_plugins($type, $typerootdir, $typeclass) {
1899 // get the list of filters from both /filter and /mod location
1900 $installed = filter_get_all_installed();
1902 foreach ($installed as $filterlegacyname => $displayname) {
1903 $plugin = new $typeclass();
1904 $plugin->type
= $type;
1905 $plugin->typerootdir
= $typerootdir;
1906 $plugin->name
= self
::normalize_legacy_name($filterlegacyname);
1907 $plugin->rootdir
= $CFG->dirroot
. '/' . $filterlegacyname;
1908 $plugin->displayname
= $displayname;
1910 $plugin->load_disk_version();
1911 $plugin->load_db_version();
1912 $plugin->load_required_main_version();
1913 $plugin->init_is_standard();
1915 $filters[$plugin->name
] = $plugin;
1918 $globalstates = self
::get_global_states();
1920 if ($DB->get_manager()->table_exists('filter_active')) {
1921 // if we're upgrading from 1.9, the table does not exist yet
1922 // if it does, make sure that all installed filters are registered
1923 $needsreload = false;
1924 foreach (array_keys($installed) as $filterlegacyname) {
1925 if (!isset($globalstates[self
::normalize_legacy_name($filterlegacyname)])) {
1926 filter_set_global_state($filterlegacyname, TEXTFILTER_DISABLED
);
1927 $needsreload = true;
1931 $globalstates = self
::get_global_states(true);
1935 // make sure that all registered filters are installed, just in case
1936 foreach ($globalstates as $name => $info) {
1937 if (!isset($filters[$name])) {
1938 // oops, there is a record in filter_active but the filter is not installed
1939 $plugin = new $typeclass();
1940 $plugin->type
= $type;
1941 $plugin->typerootdir
= $typerootdir;
1942 $plugin->name
= $name;
1943 $plugin->rootdir
= $CFG->dirroot
. '/' . $info->legacyname
;
1944 $plugin->displayname
= $info->legacyname
;
1946 $plugin->load_db_version();
1948 if (is_null($plugin->versiondb
)) {
1949 // this is a hack to stimulate 'Missing from disk' error
1950 // because $plugin->versiondisk will be null !== false
1951 $plugin->versiondb
= false;
1954 $filters[$plugin->name
] = $plugin;
1961 public function init_display_name() {
1962 // do nothing, the name is set in self::get_plugins()
1966 * @see load_version_php()
1968 protected function load_version_php() {
1969 if (strpos($this->name
, 'mod_') === 0) {
1970 // filters bundled with modules do not have a version.php and so
1971 // do not provide their own versioning information.
1972 return new stdClass();
1974 return parent
::load_version_php();
1977 public function is_enabled() {
1979 $globalstates = self
::get_global_states();
1981 foreach ($globalstates as $filterlegacyname => $info) {
1982 $name = self
::normalize_legacy_name($filterlegacyname);
1983 if ($name === $this->name
) {
1984 if ($info->active
== TEXTFILTER_DISABLED
) {
1987 // it may be 'On' or 'Off, but available'
1996 public function get_settings_url() {
1998 $globalstates = self
::get_global_states();
1999 $legacyname = $globalstates[$this->name
]->legacyname
;
2000 if (filter_has_global_settings($legacyname)) {
2001 return new moodle_url('/admin/settings.php', array('section' => 'filtersetting' . str_replace('/', '', $legacyname)));
2007 public function get_uninstall_url() {
2009 if (strpos($this->name
, 'mod_') === 0) {
2012 $globalstates = self
::get_global_states();
2013 $legacyname = $globalstates[$this->name
]->legacyname
;
2014 return new moodle_url('/admin/filters.php', array('sesskey' => sesskey(), 'filterpath' => $legacyname, 'action' => 'delete'));
2019 * Convert legacy filter names like 'filter/foo' or 'mod/bar' into frankenstyle
2021 * @param string $legacyfiltername legacy filter name
2022 * @return string frankenstyle-like name
2024 protected static function normalize_legacy_name($legacyfiltername) {
2026 $name = str_replace('/', '_', $legacyfiltername);
2027 if (strpos($name, 'filter_') === 0) {
2028 $name = substr($name, 7);
2030 throw new coding_exception('Unable to determine filter name: ' . $legacyfiltername);
2038 * Provides access to the results of {@link filter_get_global_states()}
2039 * but indexed by the normalized filter name
2041 * The legacy filter name is available as ->legacyname property.
2043 * @param bool $disablecache
2046 protected static function get_global_states($disablecache=false) {
2048 static $globalstatescache = null;
2050 if ($disablecache or is_null($globalstatescache)) {
2052 if (!$DB->get_manager()->table_exists('filter_active')) {
2053 // we're upgrading from 1.9 and the table used by {@link filter_get_global_states()}
2054 // does not exist yet
2055 $globalstatescache = array();
2058 foreach (filter_get_global_states() as $legacyname => $info) {
2059 $name = self
::normalize_legacy_name($legacyname);
2060 $filterinfo = new stdClass();
2061 $filterinfo->legacyname
= $legacyname;
2062 $filterinfo->active
= $info->active
;
2063 $filterinfo->sortorder
= $info->sortorder
;
2064 $globalstatescache[$name] = $filterinfo;
2069 return $globalstatescache;
2075 * Class for activity modules
2077 class plugininfo_mod
extends plugininfo_base
{
2079 public static function get_plugins($type, $typerootdir, $typeclass) {
2081 // get the information about plugins at the disk
2082 $modules = parent
::get_plugins($type, $typerootdir, $typeclass);
2084 // add modules missing from disk
2085 $modulesinfo = self
::get_modules_info();
2086 foreach ($modulesinfo as $modulename => $moduleinfo) {
2087 if (isset($modules[$modulename])) {
2090 $plugin = new $typeclass();
2091 $plugin->type
= $type;
2092 $plugin->typerootdir
= $typerootdir;
2093 $plugin->name
= $modulename;
2094 $plugin->rootdir
= null;
2095 $plugin->displayname
= $modulename;
2096 $plugin->versiondb
= $moduleinfo->version
;
2097 $plugin->init_is_standard();
2099 $modules[$modulename] = $plugin;
2105 public function init_display_name() {
2106 if (get_string_manager()->string_exists('pluginname', $this->component
)) {
2107 $this->displayname
= get_string('pluginname', $this->component
);
2109 $this->displayname
= get_string('modulename', $this->component
);
2114 * Load the data from version.php.
2115 * @return object the data object defined in version.php.
2117 protected function load_version_php() {
2118 $versionfile = $this->full_path('version.php');
2120 $module = new stdClass();
2121 if (is_readable($versionfile)) {
2122 include($versionfile);
2127 public function load_db_version() {
2130 $modulesinfo = self
::get_modules_info();
2131 if (isset($modulesinfo[$this->name
]->version
)) {
2132 $this->versiondb
= $modulesinfo[$this->name
]->version
;
2136 public function is_enabled() {
2138 $modulesinfo = self
::get_modules_info();
2139 if (isset($modulesinfo[$this->name
]->visible
)) {
2140 if ($modulesinfo[$this->name
]->visible
) {
2146 return parent
::is_enabled();
2150 public function get_settings_url() {
2152 if (file_exists($this->full_path('settings.php')) or file_exists($this->full_path('settingstree.php'))) {
2153 return new moodle_url('/admin/settings.php', array('section' => 'modsetting' . $this->name
));
2155 return parent
::get_settings_url();
2159 public function get_uninstall_url() {
2161 if ($this->name
!== 'forum') {
2162 return new moodle_url('/admin/modules.php', array('delete' => $this->name
, 'sesskey' => sesskey()));
2169 * Provides access to the records in {modules} table
2171 * @param bool $disablecache do not use internal static cache
2172 * @return array array of stdClasses
2174 protected static function get_modules_info($disablecache=false) {
2176 static $modulesinfocache = null;
2178 if (is_null($modulesinfocache) or $disablecache) {
2180 $modulesinfocache = $DB->get_records('modules', null, 'name', 'name,id,version,visible');
2181 } catch (dml_exception
$e) {
2183 $modulesinfocache = array();
2187 return $modulesinfocache;
2193 * Class for question behaviours.
2195 class plugininfo_qbehaviour
extends plugininfo_base
{
2197 public function get_uninstall_url() {
2198 return new moodle_url('/admin/qbehaviours.php',
2199 array('delete' => $this->name
, 'sesskey' => sesskey()));
2205 * Class for question types
2207 class plugininfo_qtype
extends plugininfo_base
{
2209 public function get_uninstall_url() {
2210 return new moodle_url('/admin/qtypes.php',
2211 array('delete' => $this->name
, 'sesskey' => sesskey()));
2217 * Class for authentication plugins
2219 class plugininfo_auth
extends plugininfo_base
{
2221 public function is_enabled() {
2223 /** @var null|array list of enabled authentication plugins */
2224 static $enabled = null;
2226 if (in_array($this->name
, array('nologin', 'manual'))) {
2227 // these two are always enabled and can't be disabled
2231 if (is_null($enabled)) {
2232 $enabled = array_flip(explode(',', $CFG->auth
));
2235 return isset($enabled[$this->name
]);
2238 public function get_settings_url() {
2239 if (file_exists($this->full_path('settings.php'))) {
2240 return new moodle_url('/admin/settings.php', array('section' => 'authsetting' . $this->name
));
2242 return new moodle_url('/admin/auth_config.php', array('auth' => $this->name
));
2249 * Class for enrolment plugins
2251 class plugininfo_enrol
extends plugininfo_base
{
2253 public function is_enabled() {
2255 /** @var null|array list of enabled enrolment plugins */
2256 static $enabled = null;
2258 // We do not actually need whole enrolment classes here so we do not call
2259 // {@link enrol_get_plugins()}. Note that this may produce slightly different
2260 // results, for example if the enrolment plugin does not contain lib.php
2261 // but it is listed in $CFG->enrol_plugins_enabled
2263 if (is_null($enabled)) {
2264 $enabled = array_flip(explode(',', $CFG->enrol_plugins_enabled
));
2267 return isset($enabled[$this->name
]);
2270 public function get_settings_url() {
2272 if ($this->is_enabled() or file_exists($this->full_path('settings.php'))) {
2273 return new moodle_url('/admin/settings.php', array('section' => 'enrolsettings' . $this->name
));
2275 return parent
::get_settings_url();
2279 public function get_uninstall_url() {
2280 return new moodle_url('/admin/enrol.php', array('action' => 'uninstall', 'enrol' => $this->name
, 'sesskey' => sesskey()));
2286 * Class for messaging processors
2288 class plugininfo_message
extends plugininfo_base
{
2290 public function get_settings_url() {
2291 $processors = get_message_processors();
2292 if (isset($processors[$this->name
])) {
2293 $processor = $processors[$this->name
];
2294 if ($processor->available
&& $processor->hassettings
) {
2295 return new moodle_url('settings.php', array('section' => 'messagesetting'.$processor->name
));
2298 return parent
::get_settings_url();
2302 * @see plugintype_interface::is_enabled()
2304 public function is_enabled() {
2305 $processors = get_message_processors();
2306 if (isset($processors[$this->name
])) {
2307 return $processors[$this->name
]->configured
&& $processors[$this->name
]->enabled
;
2309 return parent
::is_enabled();
2314 * @see plugintype_interface::get_uninstall_url()
2316 public function get_uninstall_url() {
2317 $processors = get_message_processors();
2318 if (isset($processors[$this->name
])) {
2319 return new moodle_url('message.php', array('uninstall' => $processors[$this->name
]->id
, 'sesskey' => sesskey()));
2321 return parent
::get_uninstall_url();
2328 * Class for repositories
2330 class plugininfo_repository
extends plugininfo_base
{
2332 public function is_enabled() {
2334 $enabled = self
::get_enabled_repositories();
2336 return isset($enabled[$this->name
]);
2339 public function get_settings_url() {
2341 if ($this->is_enabled()) {
2342 return new moodle_url('/admin/repository.php', array('sesskey' => sesskey(), 'action' => 'edit', 'repos' => $this->name
));
2344 return parent
::get_settings_url();
2349 * Provides access to the records in {repository} table
2351 * @param bool $disablecache do not use internal static cache
2352 * @return array array of stdClasses
2354 protected static function get_enabled_repositories($disablecache=false) {
2356 static $repositories = null;
2358 if (is_null($repositories) or $disablecache) {
2359 $repositories = $DB->get_records('repository', null, 'type', 'type,visible,sortorder');
2362 return $repositories;
2368 * Class for portfolios
2370 class plugininfo_portfolio
extends plugininfo_base
{
2372 public function is_enabled() {
2374 $enabled = self
::get_enabled_portfolios();
2376 return isset($enabled[$this->name
]);
2380 * Provides access to the records in {portfolio_instance} table
2382 * @param bool $disablecache do not use internal static cache
2383 * @return array array of stdClasses
2385 protected static function get_enabled_portfolios($disablecache=false) {
2387 static $portfolios = null;
2389 if (is_null($portfolios) or $disablecache) {
2390 $portfolios = array();
2391 $instances = $DB->get_recordset('portfolio_instance', null, 'plugin');
2392 foreach ($instances as $instance) {
2393 if (isset($portfolios[$instance->plugin
])) {
2394 if ($instance->visible
) {
2395 $portfolios[$instance->plugin
]->visible
= $instance->visible
;
2398 $portfolios[$instance->plugin
] = $instance;
2411 class plugininfo_theme
extends plugininfo_base
{
2413 public function is_enabled() {
2416 if ((!empty($CFG->theme
) and $CFG->theme
=== $this->name
) or
2417 (!empty($CFG->themelegacy
) and $CFG->themelegacy
=== $this->name
)) {
2420 return parent
::is_enabled();
2427 * Class representing an MNet service
2429 class plugininfo_mnetservice
extends plugininfo_base
{
2431 public function is_enabled() {
2434 if (empty($CFG->mnet_dispatcher_mode
) ||
$CFG->mnet_dispatcher_mode
!== 'strict') {
2437 return parent
::is_enabled();
2444 * Class for admin tool plugins
2446 class plugininfo_tool
extends plugininfo_base
{
2448 public function get_uninstall_url() {
2449 return new moodle_url('/admin/tools.php', array('delete' => $this->name
, 'sesskey' => sesskey()));
2455 * Class for admin tool plugins
2457 class plugininfo_report
extends plugininfo_base
{
2459 public function get_uninstall_url() {
2460 return new moodle_url('/admin/reports.php', array('delete' => $this->name
, 'sesskey' => sesskey()));