MDL-44084 atto: correct standard plugins list and namespace bug fix
[moodle.git] / lib / classes / plugin_manager.php
CommitLineData
e87214bd
PS
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/>.
16
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 * @copyright 2011 David Mudrak <david@moodle.com>
26 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
27 */
28
29defined('MOODLE_INTERNAL') || die();
30
31/**
32 * Singleton class providing general plugins management functionality.
33 */
34class core_plugin_manager {
35
36 /** the plugin is shipped with standard Moodle distribution */
37 const PLUGIN_SOURCE_STANDARD = 'std';
38 /** the plugin is added extension */
39 const PLUGIN_SOURCE_EXTENSION = 'ext';
40
41 /** the plugin uses neither database nor capabilities, no versions */
42 const PLUGIN_STATUS_NODB = 'nodb';
43 /** the plugin is up-to-date */
44 const PLUGIN_STATUS_UPTODATE = 'uptodate';
45 /** the plugin is about to be installed */
46 const PLUGIN_STATUS_NEW = 'new';
47 /** the plugin is about to be upgraded */
48 const PLUGIN_STATUS_UPGRADE = 'upgrade';
49 /** the standard plugin is about to be deleted */
50 const PLUGIN_STATUS_DELETE = 'delete';
51 /** the version at the disk is lower than the one already installed */
52 const PLUGIN_STATUS_DOWNGRADE = 'downgrade';
53 /** the plugin is installed but missing from disk */
54 const PLUGIN_STATUS_MISSING = 'missing';
55
56 /** @var core_plugin_manager holds the singleton instance */
57 protected static $singletoninstance;
58 /** @var array of raw plugins information */
59 protected $pluginsinfo = null;
60 /** @var array of raw subplugins information */
61 protected $subpluginsinfo = null;
62 /** @var array list of installed plugins $name=>$version */
63 protected $installedplugins = null;
64 /** @var array list of all enabled plugins $name=>$name */
65 protected $enabledplugins = null;
66 /** @var array list of all enabled plugins $name=>$diskversion */
67 protected $presentplugins = null;
68 /** @var array reordered list of plugin types */
69 protected $plugintypes = null;
70
71 /**
72 * Direct initiation not allowed, use the factory method {@link self::instance()}
73 */
74 protected function __construct() {
75 }
76
77 /**
78 * Sorry, this is singleton
79 */
80 protected function __clone() {
81 }
82
83 /**
84 * Factory method for this class
85 *
86 * @return core_plugin_manager the singleton instance
87 */
88 public static function instance() {
89 if (is_null(self::$singletoninstance)) {
90 self::$singletoninstance = new self();
91 }
92 return self::$singletoninstance;
93 }
94
95 /**
96 * Reset all caches.
97 * @param bool $phpunitreset
98 */
99 public static function reset_caches($phpunitreset = false) {
100 if ($phpunitreset) {
101 self::$singletoninstance = null;
102 } else {
103 if (self::$singletoninstance) {
104 self::$singletoninstance->pluginsinfo = null;
105 self::$singletoninstance->subpluginsinfo = null;
106 self::$singletoninstance->installedplugins = null;
107 self::$singletoninstance->enabledplugins = null;
108 self::$singletoninstance->presentplugins = null;
109 self::$singletoninstance->plugintypes = null;
110 }
111 }
112 $cache = cache::make('core', 'plugin_manager');
113 $cache->purge();
114 }
115
116 /**
117 * Returns the result of {@link core_component::get_plugin_types()} ordered for humans
118 *
119 * @see self::reorder_plugin_types()
120 * @return array (string)name => (string)location
121 */
122 public function get_plugin_types() {
123 if (func_num_args() > 0) {
124 if (!func_get_arg(0)) {
125 throw coding_exception('core_plugin_manager->get_plugin_types() does not support relative paths.');
126 }
127 }
128 if ($this->plugintypes) {
129 return $this->plugintypes;
130 }
131
132 $this->plugintypes = $this->reorder_plugin_types(core_component::get_plugin_types());
133 return $this->plugintypes;
134 }
135
136 /**
137 * Load list of installed plugins,
138 * always call before using $this->installedplugins.
139 *
140 * This method is caching results for all plugins.
141 */
142 protected function load_installed_plugins() {
143 global $DB, $CFG;
144
145 if ($this->installedplugins) {
146 return;
147 }
148
149 if (empty($CFG->version)) {
150 // Nothing installed yet.
151 $this->installedplugins = array();
152 return;
153 }
154
155 $cache = cache::make('core', 'plugin_manager');
156 $installed = $cache->get('installed');
157
158 if (is_array($installed)) {
159 $this->installedplugins = $installed;
160 return;
161 }
162
163 $this->installedplugins = array();
164
994e5662 165 // TODO: Delete this block once Moodle 2.6 or later becomes minimum required version to upgrade.
e87214bd
PS
166 if ($CFG->version < 2013092001.02) {
167 // We did not upgrade the database yet.
168 $modules = $DB->get_records('modules', array(), 'name ASC', 'id, name, version');
169 foreach ($modules as $module) {
170 $this->installedplugins['mod'][$module->name] = $module->version;
171 }
172 $blocks = $DB->get_records('block', array(), 'name ASC', 'id, name, version');
173 foreach ($blocks as $block) {
174 $this->installedplugins['block'][$block->name] = $block->version;
175 }
176 }
177
178 $versions = $DB->get_records('config_plugins', array('name'=>'version'));
179 foreach ($versions as $version) {
180 $parts = explode('_', $version->plugin, 2);
181 if (!isset($parts[1])) {
182 // Invalid component, there must be at least one "_".
183 continue;
184 }
185 // Do not verify here if plugin type and name are valid.
186 $this->installedplugins[$parts[0]][$parts[1]] = $version->value;
187 }
188
189 foreach ($this->installedplugins as $key => $value) {
190 ksort($this->installedplugins[$key]);
191 }
192
193 $cache->set('installed', $this->installedplugins);
194 }
195
196 /**
197 * Return list of installed plugins of given type.
198 * @param string $type
199 * @return array $name=>$version
200 */
201 public function get_installed_plugins($type) {
202 $this->load_installed_plugins();
203 if (isset($this->installedplugins[$type])) {
204 return $this->installedplugins[$type];
205 }
206 return array();
207 }
208
209 /**
210 * Load list of all enabled plugins,
211 * call before using $this->enabledplugins.
212 *
213 * This method is caching results from individual plugin info classes.
214 */
215 protected function load_enabled_plugins() {
216 global $CFG;
217
218 if ($this->enabledplugins) {
219 return;
220 }
221
222 if (empty($CFG->version)) {
223 $this->enabledplugins = array();
224 return;
225 }
226
227 $cache = cache::make('core', 'plugin_manager');
228 $enabled = $cache->get('enabled');
229
230 if (is_array($enabled)) {
231 $this->enabledplugins = $enabled;
232 return;
233 }
234
235 $this->enabledplugins = array();
236
237 require_once($CFG->libdir.'/adminlib.php');
238
239 $plugintypes = core_component::get_plugin_types();
240 foreach ($plugintypes as $plugintype => $fulldir) {
241 $plugininfoclass = self::resolve_plugininfo_class($plugintype);
242 if (class_exists($plugininfoclass)) {
243 $enabled = $plugininfoclass::get_enabled_plugins();
244 if (!is_array($enabled)) {
245 continue;
246 }
247 $this->enabledplugins[$plugintype] = $enabled;
248 }
249 }
250
251 $cache->set('enabled', $this->enabledplugins);
252 }
253
254 /**
255 * Get list of enabled plugins of given type,
256 * the result may contain missing plugins.
257 *
258 * @param string $type
259 * @return array|null list of enabled plugins of this type, null if unknown
260 */
261 public function get_enabled_plugins($type) {
262 $this->load_enabled_plugins();
263 if (isset($this->enabledplugins[$type])) {
264 return $this->enabledplugins[$type];
265 }
266 return null;
267 }
268
269 /**
270 * Load list of all present plugins - call before using $this->presentplugins.
271 */
272 protected function load_present_plugins() {
273 if ($this->presentplugins) {
274 return;
275 }
276
277 $cache = cache::make('core', 'plugin_manager');
278 $present = $cache->get('present');
279
280 if (is_array($present)) {
281 $this->presentplugins = $present;
282 return;
283 }
284
285 $this->presentplugins = array();
286
287 $plugintypes = core_component::get_plugin_types();
288 foreach ($plugintypes as $type => $typedir) {
289 $plugs = core_component::get_plugin_list($type);
290 foreach ($plugs as $plug => $fullplug) {
291 $plugin = new stdClass();
292 $plugin->version = null;
293 $module = $plugin;
294 @include($fullplug.'/version.php');
295 $this->presentplugins[$type][$plug] = $plugin;
296 }
297 }
298
299 $cache->set('present', $this->presentplugins);
300 }
301
302 /**
303 * Get list of present plugins of given type.
304 *
305 * @param string $type
306 * @return array|null list of presnet plugins $name=>$diskversion, null if unknown
307 */
308 public function get_present_plugins($type) {
309 $this->load_present_plugins();
310 if (isset($this->presentplugins[$type])) {
311 return $this->presentplugins[$type];
312 }
313 return null;
314 }
315
316 /**
317 * Returns a tree of known plugins and information about them
318 *
319 * @return array 2D array. The first keys are plugin type names (e.g. qtype);
320 * the second keys are the plugin local name (e.g. multichoice); and
321 * the values are the corresponding objects extending {@link \core\plugininfo\base}
322 */
323 public function get_plugins() {
324 $this->init_pluginsinfo_property();
325
326 // Make sure all types are initialised.
327 foreach ($this->pluginsinfo as $plugintype => $list) {
328 if ($list === null) {
329 $this->get_plugins_of_type($plugintype);
330 }
331 }
332
333 return $this->pluginsinfo;
334 }
335
336 /**
337 * Returns list of known plugins of the given type.
338 *
339 * This method returns the subset of the tree returned by {@link self::get_plugins()}.
340 * If the given type is not known, empty array is returned.
341 *
342 * @param string $type plugin type, e.g. 'mod' or 'workshopallocation'
343 * @return \core\plugininfo\base[] (string)plugin name (e.g. 'workshop') => corresponding subclass of {@link \core\plugininfo\base}
344 */
345 public function get_plugins_of_type($type) {
346 global $CFG;
347
348 $this->init_pluginsinfo_property();
349
350 if (!array_key_exists($type, $this->pluginsinfo)) {
351 return array();
352 }
353
354 if (is_array($this->pluginsinfo[$type])) {
355 return $this->pluginsinfo[$type];
356 }
357
358 $types = core_component::get_plugin_types();
359
a35fce24
PS
360 if (!isset($types[$type])) {
361 // Orphaned subplugins!
362 $plugintypeclass = self::resolve_plugininfo_class($type);
363 $this->pluginsinfo[$type] = $plugintypeclass::get_plugins($type, null, $plugintypeclass);
364 return $this->pluginsinfo[$type];
365 }
366
e87214bd
PS
367 /** @var \core\plugininfo\base $plugintypeclass */
368 $plugintypeclass = self::resolve_plugininfo_class($type);
369 $plugins = $plugintypeclass::get_plugins($type, $types[$type], $plugintypeclass);
370 $this->pluginsinfo[$type] = $plugins;
371
372 if (empty($CFG->disableupdatenotifications) and !during_initial_install()) {
373 // Append the information about available updates provided by {@link \core\update\checker()}.
374 $provider = \core\update\checker::instance();
375 foreach ($plugins as $plugininfoholder) {
376 $plugininfoholder->check_available_updates($provider);
377 }
378 }
379
380 return $this->pluginsinfo[$type];
381 }
382
383 /**
384 * Init placeholder array for plugin infos.
385 */
386 protected function init_pluginsinfo_property() {
387 if (is_array($this->pluginsinfo)) {
388 return;
389 }
390 $this->pluginsinfo = array();
391
392 $plugintypes = $this->get_plugin_types();
393
394 foreach ($plugintypes as $plugintype => $plugintyperootdir) {
395 $this->pluginsinfo[$plugintype] = null;
396 }
a35fce24
PS
397
398 // Add orphaned subplugin types.
399 $this->load_installed_plugins();
400 foreach ($this->installedplugins as $plugintype => $unused) {
401 if (!isset($plugintypes[$plugintype])) {
402 $this->pluginsinfo[$plugintype] = null;
403 }
404 }
e87214bd
PS
405 }
406
407 /**
408 * Find the plugin info class for given type.
409 *
410 * @param string $type
411 * @return string name of pluginfo class for give plugin type
412 */
413 public static function resolve_plugininfo_class($type) {
a35fce24
PS
414 $plugintypes = core_component::get_plugin_types();
415 if (!isset($plugintypes[$type])) {
416 return '\core\plugininfo\orphaned';
417 }
418
e87214bd
PS
419 $parent = core_component::get_subtype_parent($type);
420
421 if ($parent) {
422 $class = '\\'.$parent.'\plugininfo\\' . $type;
423 if (class_exists($class)) {
424 $plugintypeclass = $class;
425 } else {
426 if ($dir = core_component::get_component_directory($parent)) {
427 // BC only - use namespace instead!
428 if (file_exists("$dir/adminlib.php")) {
429 global $CFG;
430 include_once("$dir/adminlib.php");
431 }
432 if (class_exists('plugininfo_' . $type)) {
433 $plugintypeclass = 'plugininfo_' . $type;
434 debugging('Class "'.$plugintypeclass.'" is deprecated, migrate to "'.$class.'"', DEBUG_DEVELOPER);
435 } else {
436 debugging('Subplugin type "'.$type.'" should define class "'.$class.'"', DEBUG_DEVELOPER);
437 $plugintypeclass = '\core\plugininfo\general';
438 }
439 } else {
440 $plugintypeclass = '\core\plugininfo\general';
441 }
442 }
443 } else {
444 $class = '\core\plugininfo\\' . $type;
445 if (class_exists($class)) {
446 $plugintypeclass = $class;
447 } else {
448 debugging('All standard types including "'.$type.'" should have plugininfo class!', DEBUG_DEVELOPER);
449 $plugintypeclass = '\core\plugininfo\general';
450 }
451 }
452
453 if (!in_array('core\plugininfo\base', class_parents($plugintypeclass))) {
454 throw new coding_exception('Class ' . $plugintypeclass . ' must extend \core\plugininfo\base');
455 }
456
457 return $plugintypeclass;
458 }
459
460 /**
461 * Returns list of all known subplugins of the given plugin.
462 *
463 * For plugins that do not provide subplugins (i.e. there is no support for it),
464 * empty array is returned.
465 *
466 * @param string $component full component name, e.g. 'mod_workshop'
467 * @return array (string) component name (e.g. 'workshopallocation_random') => subclass of {@link \core\plugininfo\base}
468 */
469 public function get_subplugins_of_plugin($component) {
470
471 $pluginfo = $this->get_plugin_info($component);
472
473 if (is_null($pluginfo)) {
474 return array();
475 }
476
477 $subplugins = $this->get_subplugins();
478
479 if (!isset($subplugins[$pluginfo->component])) {
480 return array();
481 }
482
483 $list = array();
484
485 foreach ($subplugins[$pluginfo->component] as $subdata) {
486 foreach ($this->get_plugins_of_type($subdata->type) as $subpluginfo) {
487 $list[$subpluginfo->component] = $subpluginfo;
488 }
489 }
490
491 return $list;
492 }
493
494 /**
495 * Returns list of plugins that define their subplugins and the information
496 * about them from the db/subplugins.php file.
497 *
498 * @return array with keys like 'mod_quiz', and values the data from the
499 * corresponding db/subplugins.php file.
500 */
501 public function get_subplugins() {
502
503 if (is_array($this->subpluginsinfo)) {
504 return $this->subpluginsinfo;
505 }
506
507 $plugintypes = core_component::get_plugin_types();
508
509 $this->subpluginsinfo = array();
510 foreach (core_component::get_plugin_types_with_subplugins() as $type => $ignored) {
511 foreach (core_component::get_plugin_list($type) as $plugin => $componentdir) {
512 $component = $type.'_'.$plugin;
513 $subplugins = core_component::get_subplugins($component);
514 if (!$subplugins) {
515 continue;
516 }
517 $this->subpluginsinfo[$component] = array();
518 foreach ($subplugins as $subplugintype => $ignored) {
519 $subplugin = new stdClass();
520 $subplugin->type = $subplugintype;
521 $subplugin->typerootdir = $plugintypes[$subplugintype];
522 $this->subpluginsinfo[$component][$subplugintype] = $subplugin;
523 }
524 }
525 }
526 return $this->subpluginsinfo;
527 }
528
529 /**
530 * Returns the name of the plugin that defines the given subplugin type
531 *
532 * If the given subplugin type is not actually a subplugin, returns false.
533 *
534 * @param string $subplugintype the name of subplugin type, eg. workshopform or quiz
535 * @return false|string the name of the parent plugin, eg. mod_workshop
536 */
537 public function get_parent_of_subplugin($subplugintype) {
538 $parent = core_component::get_subtype_parent($subplugintype);
539 if (!$parent) {
540 return false;
541 }
542 return $parent;
543 }
544
545 /**
546 * Returns a localized name of a given plugin
547 *
548 * @param string $component name of the plugin, eg mod_workshop or auth_ldap
549 * @return string
550 */
551 public function plugin_name($component) {
552
553 $pluginfo = $this->get_plugin_info($component);
554
555 if (is_null($pluginfo)) {
556 throw new moodle_exception('err_unknown_plugin', 'core_plugin', '', array('plugin' => $component));
557 }
558
559 return $pluginfo->displayname;
560 }
561
562 /**
563 * Returns a localized name of a plugin typed in singular form
564 *
565 * Most plugin types define their names in core_plugin lang file. In case of subplugins,
566 * we try to ask the parent plugin for the name. In the worst case, we will return
567 * the value of the passed $type parameter.
568 *
569 * @param string $type the type of the plugin, e.g. mod or workshopform
570 * @return string
571 */
572 public function plugintype_name($type) {
573
574 if (get_string_manager()->string_exists('type_' . $type, 'core_plugin')) {
575 // For most plugin types, their names are defined in core_plugin lang file.
576 return get_string('type_' . $type, 'core_plugin');
577
578 } else if ($parent = $this->get_parent_of_subplugin($type)) {
579 // If this is a subplugin, try to ask the parent plugin for the name.
580 if (get_string_manager()->string_exists('subplugintype_' . $type, $parent)) {
581 return $this->plugin_name($parent) . ' / ' . get_string('subplugintype_' . $type, $parent);
582 } else {
583 return $this->plugin_name($parent) . ' / ' . $type;
584 }
585
586 } else {
587 return $type;
588 }
589 }
590
591 /**
592 * Returns a localized name of a plugin type in plural form
593 *
594 * Most plugin types define their names in core_plugin lang file. In case of subplugins,
595 * we try to ask the parent plugin for the name. In the worst case, we will return
596 * the value of the passed $type parameter.
597 *
598 * @param string $type the type of the plugin, e.g. mod or workshopform
599 * @return string
600 */
601 public function plugintype_name_plural($type) {
602
603 if (get_string_manager()->string_exists('type_' . $type . '_plural', 'core_plugin')) {
604 // For most plugin types, their names are defined in core_plugin lang file.
605 return get_string('type_' . $type . '_plural', 'core_plugin');
606
607 } else if ($parent = $this->get_parent_of_subplugin($type)) {
608 // If this is a subplugin, try to ask the parent plugin for the name.
609 if (get_string_manager()->string_exists('subplugintype_' . $type . '_plural', $parent)) {
610 return $this->plugin_name($parent) . ' / ' . get_string('subplugintype_' . $type . '_plural', $parent);
611 } else {
612 return $this->plugin_name($parent) . ' / ' . $type;
613 }
614
615 } else {
616 return $type;
617 }
618 }
619
620 /**
621 * Returns information about the known plugin, or null
622 *
623 * @param string $component frankenstyle component name.
624 * @return \core\plugininfo\base|null the corresponding plugin information.
625 */
626 public function get_plugin_info($component) {
627 list($type, $name) = core_component::normalize_component($component);
2384d331
PS
628 $plugins = $this->get_plugins_of_type($type);
629 if (isset($plugins[$name])) {
630 return $plugins[$name];
e87214bd
PS
631 } else {
632 return null;
633 }
634 }
635
636 /**
637 * Check to see if the current version of the plugin seems to be a checkout of an external repository.
638 *
639 * @see \core\update\deployer::plugin_external_source()
640 * @param string $component frankenstyle component name
641 * @return false|string
642 */
643 public function plugin_external_source($component) {
644
645 $plugininfo = $this->get_plugin_info($component);
646
647 if (is_null($plugininfo)) {
648 return false;
649 }
650
651 $pluginroot = $plugininfo->rootdir;
652
653 if (is_dir($pluginroot.'/.git')) {
654 return 'git';
655 }
656
657 if (is_dir($pluginroot.'/CVS')) {
658 return 'cvs';
659 }
660
661 if (is_dir($pluginroot.'/.svn')) {
662 return 'svn';
663 }
664
0b515736
OS
665 if (is_dir($pluginroot.'/.hg')) {
666 return 'mercurial';
667 }
668
e87214bd
PS
669 return false;
670 }
671
672 /**
673 * Get a list of any other plugins that require this one.
674 * @param string $component frankenstyle component name.
675 * @return array of frankensyle component names that require this one.
676 */
677 public function other_plugins_that_require($component) {
678 $others = array();
679 foreach ($this->get_plugins() as $type => $plugins) {
680 foreach ($plugins as $plugin) {
681 $required = $plugin->get_other_required_plugins();
682 if (isset($required[$component])) {
683 $others[] = $plugin->component;
684 }
685 }
686 }
687 return $others;
688 }
689
690 /**
691 * Check a dependencies list against the list of installed plugins.
692 * @param array $dependencies compenent name to required version or ANY_VERSION.
693 * @return bool true if all the dependencies are satisfied.
694 */
695 public function are_dependencies_satisfied($dependencies) {
696 foreach ($dependencies as $component => $requiredversion) {
697 $otherplugin = $this->get_plugin_info($component);
698 if (is_null($otherplugin)) {
699 return false;
700 }
701
702 if ($requiredversion != ANY_VERSION and $otherplugin->versiondisk < $requiredversion) {
703 return false;
704 }
705 }
706
707 return true;
708 }
709
710 /**
711 * Checks all dependencies for all installed plugins
712 *
713 * This is used by install and upgrade. The array passed by reference as the second
714 * argument is populated with the list of plugins that have failed dependencies (note that
715 * a single plugin can appear multiple times in the $failedplugins).
716 *
717 * @param int $moodleversion the version from version.php.
718 * @param array $failedplugins to return the list of plugins with non-satisfied dependencies
719 * @return bool true if all the dependencies are satisfied for all plugins.
720 */
721 public function all_plugins_ok($moodleversion, &$failedplugins = array()) {
722
723 $return = true;
724 foreach ($this->get_plugins() as $type => $plugins) {
725 foreach ($plugins as $plugin) {
726
727 if (!$plugin->is_core_dependency_satisfied($moodleversion)) {
728 $return = false;
729 $failedplugins[] = $plugin->component;
730 }
731
732 if (!$this->are_dependencies_satisfied($plugin->get_other_required_plugins())) {
733 $return = false;
734 $failedplugins[] = $plugin->component;
735 }
736 }
737 }
738
739 return $return;
740 }
741
742 /**
743 * Is it possible to uninstall the given plugin?
744 *
745 * False is returned if the plugininfo subclass declares the uninstall should
746 * not be allowed via {@link \core\plugininfo\base::is_uninstall_allowed()} or if the
747 * core vetoes it (e.g. becase the plugin or some of its subplugins is required
748 * by some other installed plugin).
749 *
750 * @param string $component full frankenstyle name, e.g. mod_foobar
751 * @return bool
752 */
753 public function can_uninstall_plugin($component) {
754
755 $pluginfo = $this->get_plugin_info($component);
756
757 if (is_null($pluginfo)) {
758 return false;
759 }
760
761 if (!$this->common_uninstall_check($pluginfo)) {
762 return false;
763 }
764
765 // Verify only if something else requires the subplugins, do not verify their common_uninstall_check()!
766 $subplugins = $this->get_subplugins_of_plugin($pluginfo->component);
767 foreach ($subplugins as $subpluginfo) {
768 // Check if there are some other plugins requiring this subplugin
769 // (but the parent and siblings).
770 foreach ($this->other_plugins_that_require($subpluginfo->component) as $requiresme) {
771 $ismyparent = ($pluginfo->component === $requiresme);
772 $ismysibling = in_array($requiresme, array_keys($subplugins));
773 if (!$ismyparent and !$ismysibling) {
774 return false;
775 }
776 }
777 }
778
779 // Check if there are some other plugins requiring this plugin
780 // (but its subplugins).
781 foreach ($this->other_plugins_that_require($pluginfo->component) as $requiresme) {
782 $ismysubplugin = in_array($requiresme, array_keys($subplugins));
783 if (!$ismysubplugin) {
784 return false;
785 }
786 }
787
788 return true;
789 }
790
791 /**
792 * Returns uninstall URL if exists.
793 *
794 * @param string $component
795 * @param string $return either 'overview' or 'manage'
796 * @return moodle_url uninstall URL, null if uninstall not supported
797 */
798 public function get_uninstall_url($component, $return = 'overview') {
799 if (!$this->can_uninstall_plugin($component)) {
800 return null;
801 }
802
803 $pluginfo = $this->get_plugin_info($component);
804
805 if (is_null($pluginfo)) {
806 return null;
807 }
808
809 if (method_exists($pluginfo, 'get_uninstall_url')) {
810 debugging('plugininfo method get_uninstall_url() is deprecated, all plugins should be uninstalled via standard URL only.');
811 return $pluginfo->get_uninstall_url($return);
812 }
813
814 return $pluginfo->get_default_uninstall_url($return);
815 }
816
817 /**
818 * Uninstall the given plugin.
819 *
820 * Automatically cleans-up all remaining configuration data, log records, events,
821 * files from the file pool etc.
822 *
823 * In the future, the functionality of {@link uninstall_plugin()} function may be moved
824 * into this method and all the code should be refactored to use it. At the moment, we
825 * mimic this future behaviour by wrapping that function call.
826 *
827 * @param string $component
828 * @param progress_trace $progress traces the process
829 * @return bool true on success, false on errors/problems
830 */
831 public function uninstall_plugin($component, progress_trace $progress) {
832
833 $pluginfo = $this->get_plugin_info($component);
834
835 if (is_null($pluginfo)) {
836 return false;
837 }
838
839 // Give the pluginfo class a chance to execute some steps.
840 $result = $pluginfo->uninstall($progress);
841 if (!$result) {
842 return false;
843 }
844
845 // Call the legacy core function to uninstall the plugin.
846 ob_start();
847 uninstall_plugin($pluginfo->type, $pluginfo->name);
848 $progress->output(ob_get_clean());
849
850 return true;
851 }
852
853 /**
854 * Checks if there are some plugins with a known available update
855 *
856 * @return bool true if there is at least one available update
857 */
858 public function some_plugins_updatable() {
859 foreach ($this->get_plugins() as $type => $plugins) {
860 foreach ($plugins as $plugin) {
861 if ($plugin->available_updates()) {
862 return true;
863 }
864 }
865 }
866
867 return false;
868 }
869
870 /**
871 * Check to see if the given plugin folder can be removed by the web server process.
872 *
873 * @param string $component full frankenstyle component
874 * @return bool
875 */
876 public function is_plugin_folder_removable($component) {
877
878 $pluginfo = $this->get_plugin_info($component);
879
880 if (is_null($pluginfo)) {
881 return false;
882 }
883
884 // To be able to remove the plugin folder, its parent must be writable, too.
885 if (!is_writable(dirname($pluginfo->rootdir))) {
886 return false;
887 }
888
889 // Check that the folder and all its content is writable (thence removable).
890 return $this->is_directory_removable($pluginfo->rootdir);
891 }
892
893 /**
894 * Defines a list of all plugins that were originally shipped in the standard Moodle distribution,
895 * but are not anymore and are deleted during upgrades.
896 *
897 * The main purpose of this list is to hide missing plugins during upgrade.
898 *
899 * @param string $type plugin type
900 * @param string $name plugin name
901 * @return bool
902 */
903 public static function is_deleted_standard_plugin($type, $name) {
904 // Do not include plugins that were removed during upgrades to versions that are
905 // not supported as source versions for upgrade any more. For example, at MOODLE_23_STABLE
906 // branch, listed should be no plugins that were removed at 1.9.x - 2.1.x versions as
907 // Moodle 2.3 supports upgrades from 2.2.x only.
908 $plugins = array(
909 'qformat' => array('blackboard'),
910 'enrol' => array('authorize'),
911 'tool' => array('bloglevelupgrade'),
7a2dabcb
FM
912 'theme' => array('mymobile', 'afterburner', 'anomaly', 'arialist', 'binarius', 'boxxie', 'brick', 'formal_white',
913 'formfactor', 'fusion', 'leatherbound', 'magazine', 'nimble', 'nonzero', 'overlay', 'serenity', 'sky_high',
914 'splash', 'standard', 'standardold'),
e87214bd
PS
915 );
916
917 if (!isset($plugins[$type])) {
918 return false;
919 }
920 return in_array($name, $plugins[$type]);
921 }
922
923 /**
924 * Defines a white list of all plugins shipped in the standard Moodle distribution
925 *
926 * @param string $type
927 * @return false|array array of standard plugins or false if the type is unknown
928 */
929 public static function standard_plugins_list($type) {
930
931 $standard_plugins = array(
932
adca7326 933 'atto' => array(
205c6db5
MG
934 'accessibilitychecker', 'accessibilityhelper', 'align',
935 'backcolor', 'bold', 'charmap', 'clear', 'collapse', 'emoticon',
936 'equation', 'fontcolor', 'html', 'image', 'indent', 'italic',
937 'link', 'managefiles', 'media', 'noautolink', 'orderedlist',
938 'rtl', 'strike', 'subscript', 'superscript', 'table', 'title',
939 'underline', 'undo', 'unlink', 'unorderedlist'
adca7326
DW
940 ),
941
e87214bd
PS
942 'assignment' => array(
943 'offline', 'online', 'upload', 'uploadsingle'
944 ),
945
946 'assignsubmission' => array(
947 'comments', 'file', 'onlinetext'
948 ),
949
950 'assignfeedback' => array(
951 'comments', 'file', 'offline', 'editpdf'
952 ),
953
e87214bd
PS
954 'auth' => array(
955 'cas', 'db', 'email', 'fc', 'imap', 'ldap', 'manual', 'mnet',
956 'nntp', 'nologin', 'none', 'pam', 'pop3', 'radius',
957 'shibboleth', 'webservice'
958 ),
959
960 'block' => array(
961 'activity_modules', 'admin_bookmarks', 'badges', 'blog_menu',
962 'blog_recent', 'blog_tags', 'calendar_month',
963 'calendar_upcoming', 'comments', 'community',
964 'completionstatus', 'course_list', 'course_overview',
965 'course_summary', 'feedback', 'glossary_random', 'html',
966 'login', 'mentees', 'messages', 'mnet_hosts', 'myprofile',
967 'navigation', 'news_items', 'online_users', 'participants',
968 'private_files', 'quiz_results', 'recent_activity',
969 'rss_client', 'search_forums', 'section_links',
970 'selfcompletion', 'settings', 'site_main_menu',
971 'social_activities', 'tag_flickr', 'tag_youtube', 'tags'
972 ),
973
974 'booktool' => array(
975 'exportimscp', 'importhtml', 'print'
976 ),
977
978 'cachelock' => array(
979 'file'
980 ),
981
982 'cachestore' => array(
983 'file', 'memcache', 'memcached', 'mongodb', 'session', 'static'
984 ),
985
986 'calendartype' => array(
987 'gregorian'
988 ),
989
990 'coursereport' => array(
991 // Deprecated!
992 ),
993
994 'datafield' => array(
995 'checkbox', 'date', 'file', 'latlong', 'menu', 'multimenu',
996 'number', 'picture', 'radiobutton', 'text', 'textarea', 'url'
997 ),
998
999 'datapreset' => array(
1000 'imagegallery'
1001 ),
1002
1003 'editor' => array(
205c6db5 1004 'atto', 'textarea', 'tinymce'
e87214bd
PS
1005 ),
1006
1007 'enrol' => array(
1008 'category', 'cohort', 'database', 'flatfile',
1009 'guest', 'imsenterprise', 'ldap', 'manual', 'meta', 'mnet',
1010 'paypal', 'self'
1011 ),
1012
1013 'filter' => array(
1014 'activitynames', 'algebra', 'censor', 'emailprotect',
1015 'emoticon', 'mediaplugin', 'multilang', 'tex', 'tidy',
1016 'urltolink', 'data', 'glossary'
1017 ),
1018
1019 'format' => array(
1020 'singleactivity', 'social', 'topics', 'weeks'
1021 ),
1022
1023 'gradeexport' => array(
1024 'ods', 'txt', 'xls', 'xml'
1025 ),
1026
1027 'gradeimport' => array(
1028 'csv', 'xml'
1029 ),
1030
1031 'gradereport' => array(
1032 'grader', 'outcomes', 'overview', 'user'
1033 ),
1034
1035 'gradingform' => array(
1036 'rubric', 'guide'
1037 ),
1038
1039 'local' => array(
1040 ),
1041
7eaca5a8
1042 'logstore' => array(
1043 'database', 'legacy', 'standard',
1044 ),
1045
e87214bd
PS
1046 'message' => array(
1047 'email', 'jabber', 'popup'
1048 ),
1049
1050 'mnetservice' => array(
1051 'enrol'
1052 ),
1053
1054 'mod' => array(
1055 'assign', 'assignment', 'book', 'chat', 'choice', 'data', 'feedback', 'folder',
1056 'forum', 'glossary', 'imscp', 'label', 'lesson', 'lti', 'page',
1057 'quiz', 'resource', 'scorm', 'survey', 'url', 'wiki', 'workshop'
1058 ),
1059
1060 'plagiarism' => array(
1061 ),
1062
1063 'portfolio' => array(
1064 'boxnet', 'download', 'flickr', 'googledocs', 'mahara', 'picasa'
1065 ),
1066
1067 'profilefield' => array(
1068 'checkbox', 'datetime', 'menu', 'text', 'textarea'
1069 ),
1070
1071 'qbehaviour' => array(
1072 'adaptive', 'adaptivenopenalty', 'deferredcbm',
1073 'deferredfeedback', 'immediatecbm', 'immediatefeedback',
1074 'informationitem', 'interactive', 'interactivecountback',
1075 'manualgraded', 'missing'
1076 ),
1077
1078 'qformat' => array(
1079 'aiken', 'blackboard_six', 'examview', 'gift',
1080 'learnwise', 'missingword', 'multianswer', 'webct',
1081 'xhtml', 'xml'
1082 ),
1083
1084 'qtype' => array(
1085 'calculated', 'calculatedmulti', 'calculatedsimple',
1086 'description', 'essay', 'match', 'missingtype', 'multianswer',
1087 'multichoice', 'numerical', 'random', 'randomsamatch',
1088 'shortanswer', 'truefalse'
1089 ),
1090
1091 'quiz' => array(
1092 'grading', 'overview', 'responses', 'statistics'
1093 ),
1094
1095 'quizaccess' => array(
1096 'delaybetweenattempts', 'ipaddress', 'numattempts', 'openclosedate',
1097 'password', 'safebrowser', 'securewindow', 'timelimit'
1098 ),
1099
1100 'report' => array(
1101 'backups', 'completion', 'configlog', 'courseoverview',
1102 'log', 'loglive', 'outline', 'participation', 'progress', 'questioninstances', 'security', 'stats', 'performance'
1103 ),
1104
1105 'repository' => array(
1106 'alfresco', 'areafiles', 'boxnet', 'coursefiles', 'dropbox', 'equella', 'filesystem',
1107 'flickr', 'flickr_public', 'googledocs', 'local', 'merlot',
1108 'picasa', 'recent', 'skydrive', 's3', 'upload', 'url', 'user', 'webdav',
1109 'wikimedia', 'youtube'
1110 ),
1111
1112 'scormreport' => array(
1113 'basic',
1114 'interactions',
1115 'graphs',
1116 'objectives'
1117 ),
1118
1119 'tinymce' => array(
1120 'ctrlhelp', 'dragmath', 'managefiles', 'moodleemoticon', 'moodleimage',
1121 'moodlemedia', 'moodlenolink', 'pdw', 'spellchecker', 'wrap'
1122 ),
1123
1124 'theme' => array(
bfb6e97e 1125 'base', 'bootstrapbase', 'canvas', 'clean', 'more'
e87214bd
PS
1126 ),
1127
1128 'tool' => array(
1129 'assignmentupgrade', 'behat', 'capability', 'customlang',
1130 'dbtransfer', 'generator', 'health', 'innodb', 'installaddon',
7eaca5a8 1131 'langimport', 'log', 'multilangupgrade', 'phpunit', 'profiling',
309ae892 1132 'qeupgradehelper', 'replace', 'spamcleaner', 'task', 'timezoneimport',
e87214bd
PS
1133 'unittest', 'uploadcourse', 'uploaduser', 'unsuproles', 'xmldb'
1134 ),
1135
1136 'webservice' => array(
1137 'amf', 'rest', 'soap', 'xmlrpc'
1138 ),
1139
1140 'workshopallocation' => array(
1141 'manual', 'random', 'scheduled'
1142 ),
1143
1144 'workshopeval' => array(
1145 'best'
1146 ),
1147
1148 'workshopform' => array(
1149 'accumulative', 'comments', 'numerrors', 'rubric'
1150 )
1151 );
1152
1153 if (isset($standard_plugins[$type])) {
1154 return $standard_plugins[$type];
1155 } else {
1156 return false;
1157 }
1158 }
1159
1160 /**
1161 * Reorders plugin types into a sequence to be displayed
1162 *
1163 * For technical reasons, plugin types returned by {@link core_component::get_plugin_types()} are
1164 * in a certain order that does not need to fit the expected order for the display.
1165 * Particularly, activity modules should be displayed first as they represent the
1166 * real heart of Moodle. They should be followed by other plugin types that are
1167 * used to build the courses (as that is what one expects from LMS). After that,
1168 * other supportive plugin types follow.
1169 *
1170 * @param array $types associative array
1171 * @return array same array with altered order of items
1172 */
1173 protected function reorder_plugin_types(array $types) {
1174 $fix = array('mod' => $types['mod']);
1175 foreach (core_component::get_plugin_list('mod') as $plugin => $fulldir) {
1176 if (!$subtypes = core_component::get_subplugins('mod_'.$plugin)) {
1177 continue;
1178 }
1179 foreach ($subtypes as $subtype => $ignored) {
1180 $fix[$subtype] = $types[$subtype];
1181 }
1182 }
1183
1184 $fix['mod'] = $types['mod'];
1185 $fix['block'] = $types['block'];
1186 $fix['qtype'] = $types['qtype'];
1187 $fix['qbehaviour'] = $types['qbehaviour'];
1188 $fix['qformat'] = $types['qformat'];
1189 $fix['filter'] = $types['filter'];
1190
1191 $fix['editor'] = $types['editor'];
1192 foreach (core_component::get_plugin_list('editor') as $plugin => $fulldir) {
1193 if (!$subtypes = core_component::get_subplugins('editor_'.$plugin)) {
1194 continue;
1195 }
1196 foreach ($subtypes as $subtype => $ignored) {
1197 $fix[$subtype] = $types[$subtype];
1198 }
1199 }
1200
1201 $fix['enrol'] = $types['enrol'];
1202 $fix['auth'] = $types['auth'];
1203 $fix['tool'] = $types['tool'];
1204 foreach (core_component::get_plugin_list('tool') as $plugin => $fulldir) {
1205 if (!$subtypes = core_component::get_subplugins('tool_'.$plugin)) {
1206 continue;
1207 }
1208 foreach ($subtypes as $subtype => $ignored) {
1209 $fix[$subtype] = $types[$subtype];
1210 }
1211 }
1212
1213 foreach ($types as $type => $path) {
1214 if (!isset($fix[$type])) {
1215 $fix[$type] = $path;
1216 }
1217 }
1218 return $fix;
1219 }
1220
1221 /**
1222 * Check if the given directory can be removed by the web server process.
1223 *
1224 * This recursively checks that the given directory and all its contents
1225 * it writable.
1226 *
1227 * @param string $fullpath
1228 * @return boolean
1229 */
1230 protected function is_directory_removable($fullpath) {
1231
1232 if (!is_writable($fullpath)) {
1233 return false;
1234 }
1235
1236 if (is_dir($fullpath)) {
1237 $handle = opendir($fullpath);
1238 } else {
1239 return false;
1240 }
1241
1242 $result = true;
1243
1244 while ($filename = readdir($handle)) {
1245
1246 if ($filename === '.' or $filename === '..') {
1247 continue;
1248 }
1249
1250 $subfilepath = $fullpath.'/'.$filename;
1251
1252 if (is_dir($subfilepath)) {
1253 $result = $result && $this->is_directory_removable($subfilepath);
1254
1255 } else {
1256 $result = $result && is_writable($subfilepath);
1257 }
1258 }
1259
1260 closedir($handle);
1261
1262 return $result;
1263 }
1264
1265 /**
1266 * Helper method that implements common uninstall prerequisites
1267 *
1268 * @param \core\plugininfo\base $pluginfo
1269 * @return bool
1270 */
1271 protected function common_uninstall_check(\core\plugininfo\base $pluginfo) {
1272
1273 if (!$pluginfo->is_uninstall_allowed()) {
1274 // The plugin's plugininfo class declares it should not be uninstalled.
1275 return false;
1276 }
1277
1278 if ($pluginfo->get_status() === self::PLUGIN_STATUS_NEW) {
1279 // The plugin is not installed. It should be either installed or removed from the disk.
1280 // Relying on this temporary state may be tricky.
1281 return false;
1282 }
1283
1284 if (method_exists($pluginfo, 'get_uninstall_url') and is_null($pluginfo->get_uninstall_url())) {
1285 // Backwards compatibility.
1286 debugging('\core\plugininfo\base subclasses should use is_uninstall_allowed() instead of returning null in get_uninstall_url()',
1287 DEBUG_DEVELOPER);
1288 return false;
1289 }
1290
1291 return true;
1292 }
1293}