ccfe57a8858442480ab4fbeee1c6aad6b4f01d95
[moodle.git] / lib / pluginlib.php
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 // GNU General Public License for more details.
13 //
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
17 /**
18  * Defines classes used for plugins management
19  *
20  * This library provides a unified interface to various plugin types in
21  * Moodle. It is mainly used by the plugins management admin page and the
22  * plugins check page during the upgrade.
23  *
24  * @package    core
25  * @subpackage admin
26  * @copyright  2011 David Mudrak <david@moodle.com>
27  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
28  */
30 defined('MOODLE_INTERNAL') || die();
32 /**
33  * Singleton class providing general plugins management functionality
34  */
35 class plugin_manager {
37     /** the plugin is shipped with standard Moodle distribution */
38     const PLUGIN_SOURCE_STANDARD    = 'std';
39     /** the plugin is added extension */
40     const PLUGIN_SOURCE_EXTENSION   = 'ext';
42     /** the plugin uses neither database nor capabilities, no versions */
43     const PLUGIN_STATUS_NODB        = 'nodb';
44     /** the plugin is up-to-date */
45     const PLUGIN_STATUS_UPTODATE    = 'uptodate';
46     /** the plugin is about to be installed */
47     const PLUGIN_STATUS_NEW         = 'new';
48     /** the plugin is about to be upgraded */
49     const PLUGIN_STATUS_UPGRADE     = 'upgrade';
50     /** the version at the disk is lower than the one already installed */
51     const PLUGIN_STATUS_DOWNGRADE   = 'downgrade';
52     /** the plugin is installed but missing from disk */
53     const PLUGIN_STATUS_MISSING     = 'missing';
55     /** @var plugin_manager holds the singleton instance */
56     protected static $singletoninstance;
57     /** @var array of raw plugins information */
58     protected $pluginsinfo = null;
59     /** @var array of raw subplugins information */
60     protected $subpluginsinfo = null;
62     /**
63      * Direct initiation not allowed, use the factory method {@link self::instance()}
64      *
65      * @todo we might want to specify just a single plugin type to work with
66      */
67     protected function __construct() {
68         $this->get_plugins(true);
69     }
71     /**
72      * Sorry, this is singleton
73      */
74     protected function __clone() {
75     }
77     /**
78      * Factory method for this class
79      *
80      * @return plugin_manager the singleton instance
81      */
82     public static function instance() {
83         global $CFG;
85         if (is_null(self::$singletoninstance)) {
86             self::$singletoninstance = new self();
87         }
88         return self::$singletoninstance;
89     }
91     /**
92      * Returns a tree of known plugins and information about them
93      *
94      * @param bool $disablecache force reload, cache can be used otherwise
95      * @return array
96      */
97     public function get_plugins($disablecache=false) {
99         if ($disablecache or is_null($this->pluginsinfo)) {
100             $this->pluginsinfo = array();
101             $plugintypes = get_plugin_types();
102             foreach ($plugintypes as $plugintype => $plugintyperootdir) {
103                 if (in_array($plugintype, array('base', 'general'))) {
104                     throw new coding_exception('Illegal usage of reserved word for plugin type');
105                 }
106                 if (class_exists('plugintype_' . $plugintype)) {
107                     $plugintypeclass = 'plugintype_' . $plugintype;
108                 } else {
109                     $plugintypeclass = 'plugintype_general';
110                 }
111                 if (!in_array('plugintype_interface', class_implements($plugintypeclass))) {
112                     throw new coding_exception('Class ' . $plugintypeclass . ' must implement plugintype_interface');
113                 }
114                 $plugins = call_user_func(array($plugintypeclass, 'get_plugins'), $plugintype, $plugintyperootdir, $plugintypeclass);
115                 $this->pluginsinfo[$plugintype] = $plugins;
116             }
117         }
119         return $this->pluginsinfo;
120     }
122     /**
123      * Returns list of plugins that define their subplugins and information about them
124      *
125      * At the moment, only activity modules can define subplugins.
126      *
127      * @param double $disablecache force reload, cache can be used otherwise
128      * @return array
129      */
130     public function get_subplugins($disablecache=false) {
132         if ($disablecache or is_null($this->subpluginsinfo)) {
133             $this->subpluginsinfo = array();
134             $mods = get_plugin_list('mod');
135             foreach ($mods as $mod => $moddir) {
136                 $modsubplugins = array();
137                 if (file_exists($moddir . '/db/subplugins.php')) {
138                     include($moddir . '/db/subplugins.php');
139                     foreach ($subplugins as $subplugintype => $subplugintyperootdir) {
140                         $subplugin = new stdClass();
141                         $subplugin->type = $subplugintype;
142                         $subplugin->typerootdir = $subplugintyperootdir;
143                         $modsubplugins[$subplugintype] = $subplugin;
144                     }
145                 $this->subpluginsinfo['mod_' . $mod] = $modsubplugins;
146                 }
147             }
148         }
150         return $this->subpluginsinfo;
151     }
153     /**
154      * Returns the name of the plugin that defines the given subplugin type
155      *
156      * If the given subplugin type is not actually a subplugin, returns false.
157      *
158      * @param string $subplugintype the name of subplugin type, eg. workshopform or quiz
159      * @return false|string the name of the parent plugin, eg. mod_workshop
160      */
161     public function get_parent_of_subplugin($subplugintype) {
163         $parent = false;
164         foreach ($this->get_subplugins() as $pluginname => $subplugintypes) {
165             if (isset($subplugintypes[$subplugintype])) {
166                 $parent = $pluginname;
167                 break;
168             }
169         }
171         return $parent;
172     }
174     /**
175      * Returns a localized name of a given plugin
176      *
177      * @param string $plugin name of the plugin, eg mod_workshop or auth_ldap
178      * @return string
179      */
180     public function plugin_name($plugin) {
181         list($type, $name) = normalize_component($plugin);
182         return $this->pluginsinfo[$type][$name]->displayname;
183     }
185     /**
186      * Returns a localized name of a plugin type in plural form
187      *
188      * Most plugin types define their names in core_plugin lang file. In case of subplugins,
189      * we try to ask the parent plugin for the name. In the worst case, we will return
190      * the value of the passed $type parameter.
191      *
192      * @param string $type the type of the plugin, e.g. mod or workshopform
193      * @return string
194      */
195     public function plugintype_name_plural($type) {
197         if (get_string_manager()->string_exists('type_' . $type . '_plural', 'core_plugin')) {
198             // for most plugin types, their names are defined in core_plugin lang file
199             return get_string('type_' . $type . '_plural', 'core_plugin');
201         } else if ($parent = $this->get_parent_of_subplugin($type)) {
202             // if this is a subplugin, try to ask the parent plugin for the name
203             if (get_string_manager()->string_exists('subplugintype_' . $type . '_plural', $parent)) {
204                 return $this->plugin_name($parent) . ' / ' . get_string('subplugintype_' . $type . '_plural', $parent);
205             } else {
206                 return $this->plugin_name($parent) . ' / ' . $type;
207             }
209         } else {
210             return $type;
211         }
212     }
214     /**
215      * Defines a white list of all plugins shipped in the standard Moodle distribution
216      *
217      * @return false|array array of standard plugins or false if the type is unknown
218      */
219     public static function standard_plugins_list($type) {
220         static $standard_plugins = array(
222             'assignment' => array(
223                 'offline', 'online', 'upload', 'uploadsingle'
224             ),
226             'auth' => array(
227                 'cas', 'db', 'email', 'fc', 'imap', 'ldap', 'manual', 'mnet',
228                 'nntp', 'nologin', 'none', 'pam', 'pop3', 'radius',
229                 'shibboleth', 'webservice'
230             ),
232             'block' => array(
233                 'activity_modules', 'admin_bookmarks', 'blog_menu',
234                 'blog_recent', 'blog_tags', 'calendar_month',
235                 'calendar_upcoming', 'comments', 'community',
236                 'completionstatus', 'course_list', 'course_overview',
237                 'course_summary', 'feedback', 'glossary_random', 'html',
238                 'login', 'mentees', 'messages', 'mnet_hosts', 'myprofile',
239                 'navigation', 'news_items', 'online_users', 'participants',
240                 'private_files', 'quiz_results', 'recent_activity',
241                 'rss_client', 'search', 'search_forums', 'section_links',
242                 'selfcompletion', 'settings', 'site_main_menu',
243                 'social_activities', 'tag_flickr', 'tag_youtube', 'tags'
244             ),
246             'coursereport' => array(
247                 'completion', 'log', 'outline', 'participation', 'progress', 'stats'
248             ),
250             'datafield' => array(
251                 'checkbox', 'date', 'file', 'latlong', 'menu', 'multimenu',
252                 'number', 'picture', 'radiobutton', 'text', 'textarea', 'url'
253             ),
255             'datapreset' => array(
256                 'imagegallery'
257             ),
259             'editor' => array(
260                 'textarea', 'tinymce'
261             ),
263             'enrol' => array(
264                 'authorize', 'category', 'cohort', 'database', 'flatfile',
265                 'guest', 'imsenterprise', 'ldap', 'manual', 'meta', 'mnet',
266                 'paypal', 'self'
267             ),
269             'filter' => array(
270                 'activitynames', 'algebra', 'censor', 'emailprotect',
271                 'emoticon', 'mediaplugin', 'multilang', 'tex', 'tidy',
272                 'urltolink', 'mod_data', 'mod_glossary'
273             ),
275             'format' => array(
276                 'scorm', 'social', 'topics', 'weeks'
277             ),
279             'gradeexport' => array(
280                 'ods', 'txt', 'xls', 'xml'
281             ),
283             'gradeimport' => array(
284                 'csv', 'xml'
285             ),
287             'gradereport' => array(
288                 'grader', 'outcomes', 'overview', 'user'
289             ),
291             'local' => array(
292             ),
294             'message' => array(
295                 'email', 'jabber', 'popup'
296             ),
298             'mnetservice' => array(
299                 'enrol'
300             ),
302             'mod' => array(
303                 'assignment', 'chat', 'choice', 'data', 'feedback', 'folder',
304                 'forum', 'glossary', 'imscp', 'label', 'lesson', 'page',
305                 'quiz', 'resource', 'scorm', 'survey', 'url', 'wiki', 'workshop'
306             ),
308             'plagiarism' => array(
309             ),
311             'portfolio' => array(
312                 'boxnet', 'download', 'flickr', 'googledocs', 'mahara', 'picasa'
313             ),
315             'profilefield' => array(
316                 'checkbox', 'datetime', 'menu', 'text', 'textarea'
317             ),
319             'qformat' => array(
320                 'aiken', 'blackboard', 'blackboard_six', 'examview', 'gift',
321                 'learnwise', 'missingword', 'multianswer', 'qti_two', 'webct',
322                 'xhtml', 'xml'
323             ),
325             'qtype' => array(
326                 'calculated', 'calculatedmulti', 'calculatedsimple',
327                 'description', 'essay', 'match', 'missingtype', 'multianswer',
328                 'multichoice', 'numerical', 'random', 'randomsamatch',
329                 'shortanswer', 'truefalse'
330             ),
332             'quiz' => array(
333                 'grading', 'overview', 'responses', 'statistics'
334             ),
336             'report' => array(
337                 'backups', 'capability', 'configlog', 'courseoverview',
338                 'customlang', 'log', 'profiling', 'questioninstances',
339                 'security', 'spamcleaner', 'stats', 'unittest', 'unsuproles'
340             ),
342             'repository' => array(
343                 'alfresco', 'boxnet', 'coursefiles', 'dropbox', 'filesystem',
344                 'flickr', 'flickr_public', 'googledocs', 'local', 'merlot',
345                 'picasa', 'recent', 's3', 'upload', 'url', 'user', 'webdav',
346                 'wikimedia', 'youtube'
347             ),
349             'theme' => array(
350                 'afterburner', 'anomaly', 'arialist', 'base', 'binarius',
351                 'boxxie', 'brick', 'canvas', 'formal_white', 'formfactor',
352                 'fusion', 'leatherbound', 'magazine', 'nimble', 'nonzero',
353                 'overlay', 'serenity', 'sky_high', 'splash', 'standard',
354                 'standardold'
355             ),
357             'webservice' => array(
358                 'amf', 'rest', 'soap', 'xmlrpc'
359             ),
361             'workshopallocation' => array(
362                 'manual', 'random'
363             ),
365             'workshopeval' => array(
366                 'best'
367             ),
369             'workshopform' => array(
370                 'accumulative', 'comments', 'numerrors', 'rubric'
371             )
372         );
374         if (isset($standard_plugins[$type])) {
375             return $standard_plugins[$type];
377         } else {
378             return false;
379         }
380     }
383 /**
384  * All classes that represent a plugin of some type must implement this interface
385  */
386 interface plugintype_interface {
388     /**
389      * Gathers and returns the information about all plugins of the given type
390      *
391      * Passing the parameter $typeclass allows us to reach the same effect as with the
392      * late binding in PHP 5.3. Once PHP 5.3 is required, we can refactor this to use
393      * {@example $plugin = new static();} instead of {@example $plugin = new $typeclass()}
394      *
395      * @param string $type the name of the plugintype, eg. mod, auth or workshopform
396      * @param string $typerootdir full path to the location of the plugin dir
397      * @param string $typeclass the name of the actually called class
398      * @return array of plugintype classes, indexed by the plugin name
399      */
400     public static function get_plugins($type, $typerootdir, $typeclass);
402     /**
403      * Sets $displayname property to a localized name of the plugin
404      *
405      * @return void
406      */
407     public function set_display_name();
409     /**
410      * Sets $versiondisk property to a numerical value representing the
411      * version of the plugin's source code.
412      *
413      * If the value is null after calling this method, either the plugin
414      * does not use versioning (typically does not have any database
415      * data) or is missing from disk.
416      *
417      * @return void
418      */
419     public function set_version_disk();
421     /**
422      * Sets $versiondb property to a numerical value representing the
423      * currently installed version of the plugin.
424      *
425      * If the value is null after calling this method, either the plugin
426      * does not use versioning (typically does not have any database
427      * data) or has not been installed yet.
428      *
429      * @return void
430      */
431     public function set_version_db();
433     /**
434      * Sets $versionrequires property to a numerical value representing
435      * the version of Moodle core that this plugin requires.
436      *
437      * @return void
438      */
439     public function set_version_requires();
441     /**
442      * Sets $source property to one of plugin_manager::PLUGIN_SOURCE_xxx
443      * constants.
444      *
445      * If the property's value is null after calling this method, then
446      * the type of the plugin has not been recognized and you should throw
447      * an exception.
448      *
449      * @return void
450      */
451     public function set_source();
453     /**
454      * Returns true if the plugin is shipped with the official distribution
455      * of the current Moodle version, false otherwise.
456      *
457      * @return bool
458      */
459     public function is_standard();
461     /**
462      * Returns the status of the plugin
463      *
464      * @return string one of plugin_manager::PLUGIN_STATUS_xxx constants
465      */
466     public function get_status();
468     /**
469      * Returns the information about plugin availability
470      *
471      * True means that the plugin is enabled. False means that the plugin is
472      * disabled. Null means that the information is not available, or the
473      * plugin does not support configurable availability or the availability
474      * can not be changed.
475      *
476      * @return null|bool
477      */
478     public function is_enabled();
480     /**
481      * Returns the URL of the plugin settings screen
482      *
483      * Null value means that the plugin either does not have the settings screen
484      * or its location is not available via this library.
485      *
486      * @return null|moodle_url
487      */
488     public function get_settings_url();
490     /**
491      * Returns the URL of the screen where this plugin can be uninstalled
492      *
493      * Visiting that URL must be safe, that is a manual confirmation is needed
494      * for actual uninstallation of the plugin. Null value means that the
495      * plugin either does not support uninstallation, or does not require any
496      * database cleanup or the location of the screen is not available via this
497      * library.
498      *
499      * @return null|moodle_url
500      */
501     public function get_uninstall_url();
503     /**
504      * Returns relative directory of the plugin with heading '/'
505      *
506      * @example /mod/workshop
507      * @return string
508      */
509     public function get_dir();
512 /**
513  * Defines public properties that all plugintype classes must have
514  * and provides default implementation of required methods.
515  */
516 abstract class plugintype_base {
518     /** @var string the plugintype name, eg. mod, auth or workshopform */
519     public $type;
520     /** @var string full path to the location of all the plugins of this type */
521     public $typerootdir;
522     /** @var string the plugin name, eg. assignment, ldap */
523     public $name;
524     /** @var string the localized plugin name */
525     public $displayname;
526     /** @var string the plugin source, one of plugin_manager::PLUGIN_SOURCE_xxx constants */
527     public $source;
528     /** @var fullpath to the location of this plugin */
529     public $rootdir;
530     /** @var int|string the version of the plugin's source code */
531     public $versiondisk;
532     /** @var int|string the version of the installed plugin */
533     public $versiondb;
534     /** @var int|float|string required version of Moodle core  */
535     public $versionrequires;
536     /** @var int number of instances of the plugin - not supported yet */
537     public $instances;
538     /** @var int order of the plugin among other plugins of the same type - not supported yet */
539     public $sortorder;
541     /**
542      * @see plugintype_interface::get_plugins()
543      */
544     public static function get_plugins($type, $typerootdir, $typeclass) {
546         // get the information about plugins at the disk
547         $plugins = get_plugin_list($type);
548         $ondisk = array();
549         foreach ($plugins as $pluginname => $pluginrootdir) {
550             $plugin                 = new $typeclass();
551             $plugin->type           = $type;
552             $plugin->typerootdir    = $typerootdir;
553             $plugin->name           = $pluginname;
554             $plugin->rootdir        = $pluginrootdir;
556             $plugin->set_display_name();
557             $plugin->set_version_disk();
558             $plugin->set_version_db();
559             $plugin->set_version_requires();
560             $plugin->set_source();
562             $ondisk[$pluginname] = $plugin;
563         }
564         return $ondisk;
565     }
567     /**
568      * @see plugintype_interface::set_display_name()
569      */
570     public function set_display_name() {
571         if (! get_string_manager()->string_exists('pluginname', $this->type . '_' . $this->name)) {
572             $this->displayname = '[pluginname,' . $this->type . '_' . $this->name . ']';
573         } else {
574             $this->displayname = get_string('pluginname', $this->type . '_' . $this->name);
575         }
576     }
578     /**
579      * @see plugintype_interface::set_version_disk()
580      */
581     public function set_version_disk() {
583         if (empty($this->rootdir)) {
584             return;
585         }
587         $versionfile = $this->rootdir . '/version.php';
589         if (is_readable($versionfile)) {
590             include($versionfile);
591             if (isset($plugin->version)) {
592                 $this->versiondisk = $plugin->version;
593             }
594         }
595     }
597     /**
598      * @see plugintype_interface::set_version_db()
599      */
600     public function set_version_db() {
602         if ($ver = self::get_version_from_config_plugins($this->type . '_' . $this->name)) {
603             $this->versiondb = $ver;
604         }
605     }
607     /**
608      * @see plugintype_interface::set_version_requires()
609      */
610     public function set_version_requires() {
612         if (empty($this->rootdir)) {
613             return;
614         }
616         $versionfile = $this->rootdir . '/version.php';
618         if (is_readable($versionfile)) {
619             include($versionfile);
620             if (isset($plugin->requires)) {
621                 $this->versionrequires = $plugin->requires;
622             }
623         }
624     }
626     /**
627      * @see plugintype_interface::set_source()
628      */
629     public function set_source() {
631         $standard = plugin_manager::standard_plugins_list($this->type);
633         if ($standard !== false) {
634             $standard = array_flip($standard);
635             if (isset($standard[$this->name])) {
636                 $this->source = plugin_manager::PLUGIN_SOURCE_STANDARD;
637             } else {
638                 $this->source = plugin_manager::PLUGIN_SOURCE_EXTENSION;
639             }
640         }
641     }
643     /**
644      * @see plugintype_interface::is_standard()
645      */
646     public function is_standard() {
647         return $this->source === plugin_manager::PLUGIN_SOURCE_STANDARD;
648     }
650     /**
651      * @see plugintype_interface::get_status()
652      */
653     public function get_status() {
655         if (is_null($this->versiondb) and is_null($this->versiondisk)) {
656             return plugin_manager::PLUGIN_STATUS_NODB;
658         } else if (is_null($this->versiondb) and !is_null($this->versiondisk)) {
659             return plugin_manager::PLUGIN_STATUS_NEW;
661         } else if (!is_null($this->versiondb) and is_null($this->versiondisk)) {
662             return plugin_manager::PLUGIN_STATUS_MISSING;
664         } else if ((string)$this->versiondb === (string)$this->versiondisk) {
665             return plugin_manager::PLUGIN_STATUS_UPTODATE;
667         } else if ($this->versiondb < $this->versiondisk) {
668             return plugin_manager::PLUGIN_STATUS_UPGRADE;
670         } else if ($this->versiondb > $this->versiondisk) {
671             return plugin_manager::PLUGIN_STATUS_DOWNGRADE;
673         } else {
674             // $version = pi(); and similar funny jokes - hopefully Donald E. Knuth will never contribute to Moodle ;-)
675             throw new coding_exception('Unable to determine plugin state, check the plugin versions');
676         }
677     }
679     /**
680      * @see plugintype_interface::is_enabled()
681      */
682     public function is_enabled() {
683         return null;
684     }
686     /**
687      * @see plugintype_interface::get_settings_url()
688      */
689     public function get_settings_url() {
690         return null;
691     }
693     /**
694      * @see plugintype_interface::get_uninstall_url()
695      */
696     public function get_uninstall_url() {
697         return null;
698     }
700     /**
701      * @see plugintype_interface::get_dir()
702      */
703     public function get_dir() {
704         global $CFG;
706         return substr($this->rootdir, strlen($CFG->dirroot));
707     }
709     /**
710      * Provides access to plugin versions from {config_plugins}
711      *
712      * @param string $plugin plugin name
713      * @param double $disablecache optional, defaults to false
714      * @return int|false the stored value or false if not found
715      */
716     protected function get_version_from_config_plugins($plugin, $disablecache=false) {
717         global $DB;
718         static $pluginversions = null;
720         if (is_null($pluginversions) or $disablecache) {
721             $pluginversions = $DB->get_records_menu('config_plugins', array('name' => 'version'), 'plugin', 'plugin,value');
722         }
724         if (!array_key_exists($plugin, $pluginversions)) {
725             return false;
726         }
728         return $pluginversions[$plugin];
729     }
732 /**
733  * General class for all plugin types that do not have their own class
734  */
735 class plugintype_general extends plugintype_base implements plugintype_interface {
739 /**
740  * Class for page side blocks
741  */
742 class plugintype_block extends plugintype_base implements plugintype_interface {
744     /**
745      * @see plugintype_interface::get_plugins()
746      */
747     public static function get_plugins($type, $typerootdir, $typeclass) {
749         // get the information about blocks at the disk
750         $blocks = parent::get_plugins($type, $typerootdir, $typeclass);
752         // add blocks missing from disk
753         $blocksinfo = self::get_blocks_info();
754         foreach ($blocksinfo as $blockname => $blockinfo) {
755             if (isset($blocks[$blockname])) {
756                 continue;
757             }
758             $plugin                 = new $typeclass();
759             $plugin->type           = $type;
760             $plugin->typerootdir    = $typerootdir;
761             $plugin->name           = $blockname;
762             $plugin->rootdir        = null;
763             $plugin->displayname    = $blockname;
764             $plugin->versiondb      = $blockinfo->version;
765             $plugin->set_source();
767             $blocks[$blockname]   = $plugin;
768         }
770         return $blocks;
771     }
773     /**
774      * @see plugintype_interface::set_display_name()
775      */
776     public function set_display_name() {
778         if (get_string_manager()->string_exists('pluginname', 'block_' . $this->name)) {
779             $this->displayname = get_string('pluginname', 'block_' . $this->name);
781         } else if (($block = block_instance($this->name)) !== false) {
782             $this->displayname = $block->get_title();
784         } else {
785             parent::set_display_name();
786         }
787     }
789     /**
790      * @see plugintype_interface::set_version_db()
791      */
792     public function set_version_db() {
793         global $DB;
795         $blocksinfo = self::get_blocks_info();
796         if (isset($blocksinfo[$this->name]->version)) {
797             $this->versiondb = $blocksinfo[$this->name]->version;
798         }
799     }
801     /**
802      * @see plugintype_interface::is_enabled()
803      */
804     public function is_enabled() {
806         $blocksinfo = self::get_blocks_info();
807         if (isset($blocksinfo[$this->name]->visible)) {
808             if ($blocksinfo[$this->name]->visible) {
809                 return true;
810             } else {
811                 return false;
812             }
813         } else {
814             return parent::is_enabled();
815         }
816     }
818     /**
819      * @see plugintype_interface::get_settings_url()
820      */
821     public function get_settings_url() {
823         if (($block = block_instance($this->name)) === false) {
824             return parent::get_settings_url();
826         } else if ($block->has_config()) {
827             if (!empty($this->rootdir) and file_exists($this->rootdir . '/settings.php')) {
828                 return new moodle_url('/admin/settings.php', array('section' => 'blocksetting' . $this->name));
829             } else {
830                 $blocksinfo = self::get_blocks_info();
831                 return new moodle_url('/admin/block.php', array('block' => $blocksinfo[$this->name]->id));
832             }
834         } else {
835             return parent::get_settings_url();
836         }
837     }
839     /**
840      * @see plugintype_interface::get_uninstall_url()
841      */
842     public function get_uninstall_url() {
844         $blocksinfo = self::get_blocks_info();
845         return new moodle_url('/admin/blocks.php', array('delete' => $blocksinfo[$this->name]->id, 'sesskey' => sesskey()));
846     }
848     /**
849      * Provides access to the records in {block} table
850      *
851      * @param bool $disablecache do not use internal static cache
852      * @return array array of stdClasses
853      */
854     protected static function get_blocks_info($disablecache=false) {
855         global $DB;
856         static $blocksinfocache = null;
858         if (is_null($blocksinfocache) or $disablecache) {
859             $blocksinfocache = $DB->get_records('block', null, 'name', 'name,id,version,visible');
860         }
862         return $blocksinfocache;
863     }
866 /**
867  * Class for text filters
868  */
869 class plugintype_filter extends plugintype_base implements plugintype_interface {
871     /**
872      * @see plugintype_interface::get_plugins()
873      */
874     public static function get_plugins($type, $typerootdir, $typeclass) {
875         global $CFG, $DB;
877         $filters = array();
879         // get the list of filters from both /filter and /mod location
880         $installed = filter_get_all_installed();
882         foreach ($installed as $filterlegacyname => $displayname) {
883             $plugin                 = new $typeclass();
884             $plugin->type           = $type;
885             $plugin->typerootdir    = $typerootdir;
886             $plugin->name           = self::normalize_legacy_name($filterlegacyname);
887             $plugin->rootdir        = $CFG->dirroot . '/' . $filterlegacyname;
888             $plugin->displayname    = $displayname;
890             $plugin->set_version_disk();
891             $plugin->set_version_db();
892             $plugin->set_version_requires();
893             $plugin->set_source();
895             $filters[$plugin->name] = $plugin;
896         }
898         $globalstates = self::get_global_states();
900         if ($DB->get_manager()->table_exists('filter_active')) {
901             // if we're upgrading from 1.9, the table does not exist yet
902             // if it does, make sure that all installed filters are registered
903             $needsreload  = false;
904             foreach (array_keys($installed) as $filterlegacyname) {
905                 if (!isset($globalstates[self::normalize_legacy_name($filterlegacyname)])) {
906                     filter_set_global_state($filterlegacyname, TEXTFILTER_DISABLED);
907                     $needsreload = true;
908                 }
909             }
910             if ($needsreload) {
911                 $globalstates = self::get_global_states(true);
912             }
913         }
915         // make sure that all registered filters are installed, just in case
916         foreach ($globalstates as $name => $info) {
917             if (!isset($filters[$name])) {
918                 // oops, there is a record in filter_active but the filter is not installed
919                 $plugin                 = new $typeclass();
920                 $plugin->type           = $type;
921                 $plugin->typerootdir    = $typerootdir;
922                 $plugin->name           = $name;
923                 $plugin->rootdir        = $CFG->dirroot . '/' . $info->legacyname;
924                 $plugin->displayname    = $info->legacyname;
926                 $plugin->set_version_db();
928                 if (is_null($plugin->versiondb)) {
929                     // this is a hack to stimulate 'Missing from disk' error
930                     // because $plugin->versiondisk will be null !== false
931                     $plugin->versiondb = false;
932                 }
934                 $filters[$plugin->name] = $plugin;
935             }
936         }
938         return $filters;
939     }
941     /**
942      * @see plugintype_interface::set_display_name()
943      */
944     public function set_display_name() {
945         // do nothing, the name is set in self::get_plugins()
946     }
948     /**
949      * @see plugintype_interface::set_version_disk()
950      */
951     public function set_version_disk() {
953         if (strpos($this->name, 'mod_') === 0) {
954             // filters bundled with modules do not use versioning
955             return;
956         }
958         return parent::set_version_disk();
959     }
961     /**
962      * @see plugintype_interface::set_version_requires()
963      */
964     public function set_version_requires() {
966         if (strpos($this->name, 'mod_') === 0) {
967             // filters bundled with modules do not use versioning
968             return;
969         }
971         return parent::set_version_requires();
972     }
974     /**
975      * @see plugintype_interface::is_enabled()
976      */
977     public function is_enabled() {
979         $globalstates = self::get_global_states();
981         foreach ($globalstates as $filterlegacyname => $info) {
982             $name = self::normalize_legacy_name($filterlegacyname);
983             if ($name === $this->name) {
984                 if ($info->active == TEXTFILTER_DISABLED) {
985                     return false;
986                 } else {
987                     // it may be 'On' or 'Off, but available'
988                     return null;
989                 }
990             }
991         }
993         return null;
994     }
996     /**
997      * @see plugintype_interface::get_settings_url()
998      */
999     public function get_settings_url() {
1001         $globalstates = self::get_global_states();
1002         $legacyname = $globalstates[$this->name]->legacyname;
1003         if (filter_has_global_settings($legacyname)) {
1004             return new moodle_url('/admin/settings.php', array('section' => 'filtersetting' . str_replace('/', '', $legacyname)));
1005         } else {
1006             return null;
1007         }
1008     }
1010     /**
1011      * @see plugintype_interface::get_uninstall_url()
1012      */
1013     public function get_uninstall_url() {
1015         if (strpos($this->name, 'mod_') === 0) {
1016             return null;
1017         } else {
1018             $globalstates = self::get_global_states();
1019             $legacyname = $globalstates[$this->name]->legacyname;
1020             return new moodle_url('/admin/filters.php', array('sesskey' => sesskey(), 'filterpath' => $legacyname, 'action' => 'delete'));
1021         }
1022     }
1024     /**
1025      * Convert legacy filter names like 'filter/foo' or 'mod/bar' into frankenstyle
1026      *
1027      * @param string $legacyfiltername legacy filter name
1028      * @return string frankenstyle-like name
1029      */
1030     protected static function normalize_legacy_name($legacyfiltername) {
1032         $name = str_replace('/', '_', $legacyfiltername);
1033         if (strpos($name, 'filter_') === 0) {
1034             $name = substr($name, 7);
1035             if (empty($name)) {
1036                 throw new coding_exception('Unable to determine filter name: ' . $legacyfiltername);
1037             }
1038         }
1040         return $name;
1041     }
1043     /**
1044      * Provides access to the results of {@link filter_get_global_states()}
1045      * but indexed by the normalized filter name
1046      *
1047      * The legacy filter name is available as ->legacyname property.
1048      *
1049      * @param bool $disablecache
1050      * @return array
1051      */
1052     protected static function get_global_states($disablecache=false) {
1053         global $DB;
1054         static $globalstatescache = null;
1056         if ($disablecache or is_null($globalstatescache)) {
1058             if (!$DB->get_manager()->table_exists('filter_active')) {
1059                 // we're upgrading from 1.9 and the table used by {@link filter_get_global_states()}
1060                 // does not exist yet
1061                 $globalstatescache = array();
1063             } else {
1064                 foreach (filter_get_global_states() as $legacyname => $info) {
1065                     $name                       = self::normalize_legacy_name($legacyname);
1066                     $filterinfo                 = new stdClass();
1067                     $filterinfo->legacyname     = $legacyname;
1068                     $filterinfo->active         = $info->active;
1069                     $filterinfo->sortorder      = $info->sortorder;
1070                     $globalstatescache[$name]   = $filterinfo;
1071                 }
1072             }
1073         }
1075         return $globalstatescache;
1076     }
1079 /**
1080  * Class for activity modules
1081  */
1082 class plugintype_mod extends plugintype_base implements plugintype_interface {
1084     /**
1085      * @see plugintype_interface::get_plugins()
1086      */
1087     public static function get_plugins($type, $typerootdir, $typeclass) {
1089         // get the information about plugins at the disk
1090         $modules = parent::get_plugins($type, $typerootdir, $typeclass);
1092         // add modules missing from disk
1093         $modulesinfo = self::get_modules_info();
1094         foreach ($modulesinfo as $modulename => $moduleinfo) {
1095             if (isset($modules[$modulename])) {
1096                 continue;
1097             }
1098             $plugin                 = new $typeclass();
1099             $plugin->type           = $type;
1100             $plugin->typerootdir    = $typerootdir;
1101             $plugin->name           = $modulename;
1102             $plugin->rootdir        = null;
1103             $plugin->displayname    = $modulename;
1104             $plugin->versiondb      = $moduleinfo->version;
1105             $plugin->set_source();
1107             $modules[$modulename]   = $plugin;
1108         }
1110         return $modules;
1111     }
1113     /**
1114      * @see plugintype_interface::set_display_name()
1115      */
1116     public function set_display_name() {
1117         if (get_string_manager()->string_exists('pluginname', $this->type . '_' . $this->name)) {
1118             $this->displayname = get_string('pluginname', $this->type . '_' . $this->name);
1119         } else {
1120             $this->displayname = get_string('modulename', $this->type . '_' . $this->name);
1121         }
1122     }
1124     /**
1125      * @see plugintype_interface::set_version_disk()
1126      */
1127     public function set_version_disk() {
1129         if (empty($this->rootdir)) {
1130             return;
1131         }
1133         $versionfile = $this->rootdir . '/version.php';
1135         if (is_readable($versionfile)) {
1136             include($versionfile);
1137             if (isset($module->version)) {
1138                 $this->versiondisk = $module->version;
1139             }
1140         }
1141     }
1143     /**
1144      * @see plugintype_interface::set_version_db()
1145      */
1146     public function set_version_db() {
1147         global $DB;
1149         $modulesinfo = self::get_modules_info();
1150         if (isset($modulesinfo[$this->name]->version)) {
1151             $this->versiondb = $modulesinfo[$this->name]->version;
1152         }
1153     }
1155     /**
1156      * @see plugintype_interface::set_version_requires()
1157      */
1158     public function set_version_requires() {
1160         if (empty($this->rootdir)) {
1161             return;
1162         }
1164         $versionfile = $this->rootdir . '/version.php';
1166         if (is_readable($versionfile)) {
1167             include($versionfile);
1168             if (isset($module->requires)) {
1169                 $this->versionrequires = $module->requires;
1170             }
1171         }
1172     }
1174     /**
1175      * @see plugintype_interface::is_enabled()
1176      */
1177     public function is_enabled() {
1179         $modulesinfo = self::get_modules_info();
1180         if (isset($modulesinfo[$this->name]->visible)) {
1181             if ($modulesinfo[$this->name]->visible) {
1182                 return true;
1183             } else {
1184                 return false;
1185             }
1186         } else {
1187             return parent::is_enabled();
1188         }
1189     }
1191     /**
1192      * @see plugintype_interface::get_settings_url()
1193      */
1194     public function get_settings_url() {
1196         if (!empty($this->rootdir) and (file_exists($this->rootdir . '/settings.php') or file_exists($this->rootdir . '/settingstree.php'))) {
1197             return new moodle_url('/admin/settings.php', array('section' => 'modsetting' . $this->name));
1198         } else {
1199             return parent::get_settings_url();
1200         }
1201     }
1203     /**
1204      * @see plugintype_interface::get_uninstall_url()
1205      */
1206     public function get_uninstall_url() {
1208         if ($this->name !== 'forum') {
1209             return new moodle_url('/admin/modules.php', array('delete' => $this->name, 'sesskey' => sesskey()));
1210         } else {
1211             return null;
1212         }
1213     }
1215     /**
1216      * Provides access to the records in {modules} table
1217      *
1218      * @param bool $disablecache do not use internal static cache
1219      * @return array array of stdClasses
1220      */
1221     protected static function get_modules_info($disablecache=false) {
1222         global $DB;
1223         static $modulesinfocache = null;
1225         if (is_null($modulesinfocache) or $disablecache) {
1226             $modulesinfocache = $DB->get_records('modules', null, 'name', 'name,id,version,visible');
1227         }
1229         return $modulesinfocache;
1230     }
1233 /**
1234  * Class for question types
1235  */
1236 class plugintype_qtype extends plugintype_base implements plugintype_interface {
1238     /**
1239      * @see plugintype_interface::set_display_name()
1240      */
1241     public function set_display_name() {
1242         $this->displayname = get_string($this->name, 'qtype_' . $this->name);
1243     }
1246 /**
1247  * Class for question formats
1248  */
1249 class plugintype_qformat extends plugintype_base implements plugintype_interface {
1251     /**
1252      * @see plugintype_interface::set_display_name()
1253      */
1254     public function set_display_name() {
1255         $this->displayname = get_string($this->name, 'qformat_' . $this->name);
1256     }
1259 /**
1260  * Class for authentication plugins
1261  */
1262 class plugintype_auth extends plugintype_base implements plugintype_interface {
1264     /**
1265      * @see plugintype_interface::is_enabled()
1266      */
1267     public function is_enabled() {
1268         global $CFG;
1269         /** @var null|array list of enabled authentication plugins */
1270         static $enabled = null;
1272         if (in_array($this->name, array('nologin', 'manual'))) {
1273             // these two are always enabled and can't be disabled
1274             return null;
1275         }
1277         if (is_null($enabled)) {
1278             $enabled = explode(',', $CFG->auth);
1279         }
1281         return isset($enabled[$this->name]);
1282     }
1284     /**
1285      * @see plugintype_interface::get_settings_url()
1286      */
1287     public function get_settings_url() {
1289         if (!empty($this->rootdir) and file_exists($this->rootdir . '/settings.php')) {
1290             return new moodle_url('/admin/settings.php', array('section' => 'authsetting' . $this->name));
1291         } else {
1292             return new moodle_url('/admin/auth_config.php', array('auth' => $this->name));
1293         }
1294     }
1297 /**
1298  * Class for enrolment plugins
1299  */
1300 class plugintype_enrol extends plugintype_base implements plugintype_interface {
1302     /**
1303      * We do not actually need whole enrolment classes here so we do not call
1304      * {@link enrol_get_plugins()}. Note that this may produce slightly different
1305      * results, for example if the enrolment plugin does not contain lib.php
1306      * but it is listed in $CFG->enrol_plugins_enabled
1307      *
1308      * @see plugintype_interface::is_enabled()
1309      */
1310     public function is_enabled() {
1311         global $CFG;
1312         /** @var null|array list of enabled enrolment plugins */
1313         static $enabled = null;
1315         if (is_null($enabled)) {
1316             $enabled = explode(',', $CFG->enrol_plugins_enabled);
1317         }
1319         return isset($enabled[$this->name]);
1320     }
1322     /**
1323      * @see plugintype_interface::get_settings_url()
1324      */
1325     public function get_settings_url() {
1327         if ($this->is_enabled() or (!empty($this->rootdir) and file_exists($this->rootdir . '/settings.php'))) {
1328             return new moodle_url('/admin/settings.php', array('section' => 'enrolsettings' . $this->name));
1329         } else {
1330             return parent::get_settings_url();
1331         }
1332     }
1334     /**
1335      * @see plugintype_interface::get_uninstall_url()
1336      */
1337     public function get_uninstall_url() {
1338         return new moodle_url('/admin/enrol.php', array('action' => 'uninstall', 'enrol' => $this->name, 'sesskey' => sesskey()));
1339     }
1342 /**
1343  * Class for messaging processors
1344  */
1345 class plugintype_message extends plugintype_base implements plugintype_interface {
1347     /**
1348      * @see plugintype_interface::get_settings_url()
1349      */
1350     public function get_settings_url() {
1352         if ($this->name === 'jabber') {
1353             return new moodle_url('/admin/settings.php', array('section' => 'jabber'));
1354         }
1356         if ($this->name === 'email') {
1357             return new moodle_url('/admin/settings.php', array('section' => 'mail'));
1358         }
1360     }
1363 /**
1364  * Class for repositories
1365  */
1366 class plugintype_repository extends plugintype_base implements plugintype_interface {
1368     /**
1369      * @see plugintype_interface::is_enabled()
1370      */
1371     public function is_enabled() {
1373         $enabled = self::get_enabled_repositories();
1375         return isset($enabled[$this->name]);
1376     }
1378     /**
1379      * @see plugintype_interface::get_settings_url()
1380      */
1381     public function get_settings_url() {
1383         if ($this->is_enabled()) {
1384             return new moodle_url('/admin/repository.php', array('sesskey' => sesskey(), 'action' => 'edit', 'repos' => $this->name));
1385         } else {
1386             return parent::get_settings_url();
1387         }
1388     }
1390     /**
1391      * Provides access to the records in {repository} table
1392      *
1393      * @param bool $disablecache do not use internal static cache
1394      * @return array array of stdClasses
1395      */
1396     protected static function get_enabled_repositories($disablecache=false) {
1397         global $DB;
1398         static $repositories = null;
1400         if (is_null($repositories) or $disablecache) {
1401             $repositories = $DB->get_records('repository', null, 'type', 'type,visible,sortorder');
1402         }
1404         return $repositories;
1405     }
1408 /**
1409  * Class for portfolios
1410  */
1411 class plugintype_portfolio extends plugintype_base implements plugintype_interface {
1413     /**
1414      * @see plugintype_interface::is_enabled()
1415      */
1416     public function is_enabled() {
1418         $enabled = self::get_enabled_portfolios();
1420         return isset($enabled[$this->name]);
1421     }
1423     /**
1424      * Provides access to the records in {portfolio_instance} table
1425      *
1426      * @param bool $disablecache do not use internal static cache
1427      * @return array array of stdClasses
1428      */
1429     protected static function get_enabled_portfolios($disablecache=false) {
1430         global $DB;
1431         static $portfolios = null;
1433         if (is_null($portfolios) or $disablecache) {
1434             $portfolios = array();
1435             $instances  = $DB->get_recordset('portfolio_instance', null, 'plugin');
1436             foreach ($instances as $instance) {
1437                 if (isset($portfolios[$instance->plugin])) {
1438                     if ($instance->visible) {
1439                         $portfolios[$instance->plugin]->visible = $instance->visible;
1440                     }
1441                 } else {
1442                     $portfolios[$instance->plugin] = $instance;
1443                 }
1444             }
1445         }
1447         return $portfolios;
1448     }
1451 /**
1452  * Class for themes
1453  */
1454 class plugintype_theme extends plugintype_base implements plugintype_interface {
1456     /**
1457      * @see plugintype_interface::is_enabled()
1458      */
1459     public function is_enabled() {
1460         global $CFG;
1462         if ((!empty($CFG->theme) and $CFG->theme === $this->name) or
1463             (!empty($CFG->themelegacy) and $CFG->themelegacy === $this->name)) {
1464             return true;
1465         } else {
1466             return parent::is_enabled();
1467         }
1468     }
1471 /**
1472  * Class representing an MNet service
1473  */
1474 class plugintype_mnetservice extends plugintype_base implements plugintype_interface {
1476     /**
1477      * @see plugintype_interface::is_enabled()
1478      */
1479     public function is_enabled() {
1480         global $CFG;
1482         if (empty($CFG->mnet_dispatcher_mode) || $CFG->mnet_dispatcher_mode !== 'strict') {
1483             return false;
1484         } else {
1485             return parent::is_enabled();
1486         }
1487     }