Proyectos de Subversion Moodle

Rev

| Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1 efrain 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
namespace core;
18
 
19
use cache;
20
use coding_exception;
21
use core_component;
22
use moodle_exception;
23
use moodle_url;
24
use progress_trace;
25
use stdClass;
26
 
27
/**
28
 * Defines classes used for plugins management
29
 *
30
 * This library provides a unified interface to various plugin types in
31
 * Moodle. It is mainly used by the plugins management admin page and the
32
 * plugins check page during the upgrade.
33
 *
34
 * @package    core
35
 * @copyright  2011 David Mudrak <david@moodle.com>
36
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
37
 */
38
class plugin_manager {
39
    /** the plugin is shipped with standard Moodle distribution */
40
    const PLUGIN_SOURCE_STANDARD    = 'std';
41
    /** the plugin is added extension */
42
    const PLUGIN_SOURCE_EXTENSION   = 'ext';
43
 
44
    /** the plugin uses neither database nor capabilities, no versions */
45
    const PLUGIN_STATUS_NODB        = 'nodb';
46
    /** the plugin is up-to-date */
47
    const PLUGIN_STATUS_UPTODATE    = 'uptodate';
48
    /** the plugin is about to be installed */
49
    const PLUGIN_STATUS_NEW         = 'new';
50
    /** the plugin is about to be upgraded */
51
    const PLUGIN_STATUS_UPGRADE     = 'upgrade';
52
    /** the standard plugin is about to be deleted */
53
    const PLUGIN_STATUS_DELETE     = 'delete';
54
    /** the version at the disk is lower than the one already installed */
55
    const PLUGIN_STATUS_DOWNGRADE   = 'downgrade';
56
    /** the plugin is installed but missing from disk */
57
    const PLUGIN_STATUS_MISSING     = 'missing';
58
 
59
    /** the given requirement/dependency is fulfilled */
60
    const REQUIREMENT_STATUS_OK = 'ok';
61
    /** the plugin requires higher core/other plugin version than is currently installed */
62
    const REQUIREMENT_STATUS_OUTDATED = 'outdated';
63
    /** the required dependency is not installed */
64
    const REQUIREMENT_STATUS_MISSING = 'missing';
65
    /** the current Moodle version is too high for plugin. */
66
    const REQUIREMENT_STATUS_NEWER = 'newer';
67
 
68
    /** the required dependency is available in the plugins directory */
69
    const REQUIREMENT_AVAILABLE = 'available';
70
    /** the required dependency is available in the plugins directory */
71
    const REQUIREMENT_UNAVAILABLE = 'unavailable';
72
 
73
    /** the moodle version is explicitly supported */
74
    const VERSION_SUPPORTED = 'supported';
75
    /** the moodle version is not explicitly supported */
76
    const VERSION_NOT_SUPPORTED = 'notsupported';
77
    /** the plugin does not specify supports */
78
    const VERSION_NO_SUPPORTS = 'nosupports';
79
 
80
    /** @var plugin_manager holds the singleton instance */
81
    protected static $singletoninstance;
82
    /** @var stdClass cache of standard plugins */
83
    protected static ?stdClass $standardplugincache = null;
84
    /** @var array of raw plugins information */
85
    protected $pluginsinfo = null;
86
    /** @var array of raw subplugins information */
87
    protected $subpluginsinfo = null;
88
    /** @var array cache information about availability in the plugins directory if requesting "at least" version */
89
    protected $remotepluginsinfoatleast = null;
90
    /** @var array cache information about availability in the plugins directory if requesting exact version */
91
    protected $remotepluginsinfoexact = null;
92
    /** @var array list of installed plugins $name=>$version */
93
    protected $installedplugins = null;
94
    /** @var array list of all enabled plugins $name=>$name */
95
    protected $enabledplugins = null;
96
    /** @var array list of all enabled plugins $name=>$diskversion */
97
    protected $presentplugins = null;
98
    /** @var array reordered list of plugin types */
99
    protected $plugintypes = null;
100
    /** @var \core\update\code_manager code manager to use for plugins code operations */
101
    protected $codemanager = null;
102
    /** @var \core\update\api client instance to use for accessing download.moodle.org/api/ */
103
    protected $updateapiclient = null;
104
 
105
    /**
106
     * Direct initiation not allowed, use the factory method {@link self::instance()}
107
     */
108
    protected function __construct() {
109
    }
110
 
111
    /**
112
     * Sorry, this is singleton
113
     */
114
    protected function __clone() {
115
    }
116
 
117
    /**
118
     * Factory method for this class
119
     *
120
     * @return static the singleton instance
121
     */
122
    public static function instance() {
123
        if (is_null(static::$singletoninstance)) {
124
            static::$singletoninstance = new static();
125
        }
126
        return static::$singletoninstance;
127
    }
128
 
129
    /**
130
     * Reset all caches.
131
     * @param bool $phpunitreset
132
     */
133
    public static function reset_caches($phpunitreset = false) {
134
        static::$standardplugincache = null;
135
        if ($phpunitreset) {
136
            static::$singletoninstance = null;
137
        } else {
138
            if (static::$singletoninstance) {
139
                static::$singletoninstance->pluginsinfo = null;
140
                static::$singletoninstance->subpluginsinfo = null;
141
                static::$singletoninstance->remotepluginsinfoatleast = null;
142
                static::$singletoninstance->remotepluginsinfoexact = null;
143
                static::$singletoninstance->installedplugins = null;
144
                static::$singletoninstance->enabledplugins = null;
145
                static::$singletoninstance->presentplugins = null;
146
                static::$singletoninstance->plugintypes = null;
147
                static::$singletoninstance->codemanager = null;
148
                static::$singletoninstance->updateapiclient = null;
149
            }
150
        }
151
        $cache = cache::make('core', 'plugin_manager');
152
        $cache->purge();
153
    }
154
 
155
    /**
156
     * Returns the result of {@link core_component::get_plugin_types()} ordered for humans
157
     *
158
     * @see self::reorder_plugin_types()
159
     * @return array (string)name => (string)location
160
     */
161
    public function get_plugin_types() {
162
        if (func_num_args() > 0) {
163
            if (!func_get_arg(0)) {
164
                throw new coding_exception('core_plugin_manager->get_plugin_types() does not support relative paths.');
165
            }
166
        }
167
        if ($this->plugintypes) {
168
            return $this->plugintypes;
169
        }
170
 
171
        $this->plugintypes = $this->reorder_plugin_types(core_component::get_plugin_types());
172
        return $this->plugintypes;
173
    }
174
 
175
    /**
176
     * Load list of installed plugins,
177
     * always call before using $this->installedplugins.
178
     *
179
     * This method is caching results for all plugins.
180
     */
181
    protected function load_installed_plugins() {
182
        global $DB, $CFG;
183
 
184
        if ($this->installedplugins) {
185
            return;
186
        }
187
 
188
        if (empty($CFG->version)) {
189
            // Nothing installed yet.
190
            $this->installedplugins = [];
191
            return;
192
        }
193
 
194
        $cache = cache::make('core', 'plugin_manager');
195
        $installed = $cache->get('installed');
196
 
197
        if (is_array($installed)) {
198
            $this->installedplugins = $installed;
199
            return;
200
        }
201
 
202
        $this->installedplugins = [];
203
 
204
        $versions = $DB->get_records('config_plugins', ['name' => 'version']);
205
        foreach ($versions as $version) {
206
            $parts = explode('_', $version->plugin, 2);
207
            if (!isset($parts[1])) {
208
                // Invalid component, there must be at least one "_".
209
                continue;
210
            }
211
            // Do not verify here if plugin type and name are valid.
212
            $this->installedplugins[$parts[0]][$parts[1]] = $version->value;
213
        }
214
 
215
        foreach ($this->installedplugins as $key => $value) {
216
            ksort($this->installedplugins[$key]);
217
        }
218
 
219
        $cache->set('installed', $this->installedplugins);
220
    }
221
 
222
    /**
223
     * Return list of installed plugins of given type.
224
     * @param string $type
225
     * @return array $name=>$version
226
     */
227
    public function get_installed_plugins($type) {
228
        $this->load_installed_plugins();
229
        if (isset($this->installedplugins[$type])) {
230
            return $this->installedplugins[$type];
231
        }
232
        return [];
233
    }
234
 
235
    /**
236
     * Load list of all enabled plugins,
237
     * call before using $this->enabledplugins.
238
     *
239
     * This method is caching results from individual plugin info classes.
240
     */
241
    protected function load_enabled_plugins() {
242
        global $CFG;
243
 
244
        if ($this->enabledplugins) {
245
            return;
246
        }
247
 
248
        if (empty($CFG->version)) {
249
            $this->enabledplugins = [];
250
            return;
251
        }
252
 
253
        $cache = cache::make('core', 'plugin_manager');
254
        $enabled = $cache->get('enabled');
255
 
256
        if (is_array($enabled)) {
257
            $this->enabledplugins = $enabled;
258
            return;
259
        }
260
 
261
        $this->enabledplugins = [];
262
 
263
        require_once($CFG->libdir . '/adminlib.php');
264
 
265
        $plugintypes = core_component::get_plugin_types();
266
        foreach ($plugintypes as $plugintype => $fulldir) {
267
            $plugininfoclass = static::resolve_plugininfo_class($plugintype);
268
            if (class_exists($plugininfoclass)) {
269
                $enabled = $plugininfoclass::get_enabled_plugins();
270
                if (!is_array($enabled)) {
271
                    continue;
272
                }
273
                $this->enabledplugins[$plugintype] = $enabled;
274
            }
275
        }
276
 
277
        $cache->set('enabled', $this->enabledplugins);
278
    }
279
 
280
    /**
281
     * Get list of enabled plugins of given type,
282
     * the result may contain missing plugins.
283
     *
284
     * @param string $type
285
     * @return array|null  list of enabled plugins of this type, null if unknown
286
     */
287
    public function get_enabled_plugins($type) {
288
        $this->load_enabled_plugins();
289
        if (isset($this->enabledplugins[$type])) {
290
            return $this->enabledplugins[$type];
291
        }
292
        return null;
293
    }
294
 
295
    /**
296
     * Load list of all present plugins - call before using $this->presentplugins.
297
     */
298
    protected function load_present_plugins() {
299
        if ($this->presentplugins) {
300
            return;
301
        }
302
 
303
        $cache = cache::make('core', 'plugin_manager');
304
        $present = $cache->get('present');
305
 
306
        if (is_array($present)) {
307
            $this->presentplugins = $present;
308
            return;
309
        }
310
 
311
        $this->presentplugins = [];
312
 
313
        $plugintypes = core_component::get_plugin_types();
314
        foreach ($plugintypes as $type => $typedir) {
315
            $plugs = core_component::get_plugin_list($type);
316
            foreach ($plugs as $plug => $fullplug) {
317
                $module = new stdClass();
318
                $plugin = new stdClass();
319
                $plugin->version = null;
320
                include($fullplug . '/version.php');
321
 
322
                // Check if the legacy $module syntax is still used.
323
                if (!is_object($module) || (count((array)$module) > 0)) {
324
                    debugging('Unsupported $module syntax detected in version.php of the ' . $type . '_' . $plug . ' plugin.');
325
                    $skipcache = true;
326
                }
327
 
328
                // Check if the component is properly declared.
329
                if (empty($plugin->component) || ($plugin->component !== $type . '_' . $plug)) {
330
                    debugging('Plugin ' . $type . '_' . $plug . ' does not declare valid $plugin->component in its version.php.');
331
                    $skipcache = true;
332
                }
333
 
334
                $this->presentplugins[$type][$plug] = $plugin;
335
            }
336
        }
337
 
338
        if (empty($skipcache)) {
339
            $cache->set('present', $this->presentplugins);
340
        }
341
    }
342
 
343
    /**
344
     * Load the standard plugin data from the plugins.json file.
345
     *
346
     * @return stdClass
347
     */
348
    protected static function load_standard_plugins(): stdClass {
349
        if (static::$standardplugincache === null) {
350
            $data = file_get_contents(dirname(__DIR__) . '/plugins.json');
351
            static::$standardplugincache = json_decode($data, false);
352
        }
353
 
354
        return static::$standardplugincache;
355
    }
356
 
357
    /**
358
     * Get list of present plugins of given type.
359
     *
360
     * @param string $type
361
     * @return array|null  list of presnet plugins $name=>$diskversion, null if unknown
362
     */
363
    public function get_present_plugins($type) {
364
        $this->load_present_plugins();
365
        if (isset($this->presentplugins[$type])) {
366
            return $this->presentplugins[$type];
367
        }
368
        return null;
369
    }
370
 
371
    /**
372
     * Returns a tree of known plugins and information about them
373
     *
374
     * @return array 2D array. The first keys are plugin type names (e.g. qtype);
375
     *      the second keys are the plugin local name (e.g. multichoice); and
376
     *      the values are the corresponding objects extending {@link \core\plugininfo\base}
377
     */
378
    public function get_plugins() {
379
        $this->init_pluginsinfo_property();
380
 
381
        // Make sure all types are initialised.
382
        foreach ($this->pluginsinfo as $plugintype => $list) {
383
            if ($list === null) {
384
                $this->get_plugins_of_type($plugintype);
385
            }
386
        }
387
 
388
        return $this->pluginsinfo;
389
    }
390
 
391
    /**
392
     * Returns list of known plugins of the given type.
393
     *
394
     * This method returns the subset of the tree returned by {@link self::get_plugins()}.
395
     * If the given type is not known, empty array is returned.
396
     *
397
     * @param string $type plugin type, e.g. 'mod' or 'workshopallocation'
398
     * @return \core\plugininfo\base[] (string) plugin name => corresponding subclass of {@link \core\plugininfo\base}
399
     */
400
    public function get_plugins_of_type($type) {
401
        global $CFG;
402
 
403
        $this->init_pluginsinfo_property();
404
 
405
        if (!array_key_exists($type, $this->pluginsinfo)) {
406
            return [];
407
        }
408
 
409
        if (is_array($this->pluginsinfo[$type])) {
410
            return $this->pluginsinfo[$type];
411
        }
412
 
413
        $types = core_component::get_plugin_types();
414
 
415
        if (!isset($types[$type])) {
416
            // Orphaned subplugins!
417
            $plugintypeclass = static::resolve_plugininfo_class($type);
418
            $this->pluginsinfo[$type] = $plugintypeclass::get_plugins($type, null, $plugintypeclass, $this);
419
            return $this->pluginsinfo[$type];
420
        }
421
 
422
        $plugintypeclass = static::resolve_plugininfo_class($type);
423
        $plugins = $plugintypeclass::get_plugins($type, $types[$type], $plugintypeclass, $this);
424
        $this->pluginsinfo[$type] = $plugins;
425
 
426
        return $this->pluginsinfo[$type];
427
    }
428
 
429
    /**
430
     * Init placeholder array for plugin infos.
431
     */
432
    protected function init_pluginsinfo_property() {
433
        if (is_array($this->pluginsinfo)) {
434
            return;
435
        }
436
        $this->pluginsinfo = [];
437
 
438
        $plugintypes = $this->get_plugin_types();
439
 
440
        foreach ($plugintypes as $plugintype => $plugintyperootdir) {
441
            $this->pluginsinfo[$plugintype] = null;
442
        }
443
 
444
        // Add orphaned subplugin types.
445
        $this->load_installed_plugins();
446
        foreach ($this->installedplugins as $plugintype => $unused) {
447
            if (!isset($plugintypes[$plugintype])) {
448
                $this->pluginsinfo[$plugintype] = null;
449
            }
450
        }
451
    }
452
 
453
    /**
454
     * Find the plugin info class for given type.
455
     *
456
     * @param string $type
457
     * @return string name of pluginfo class for give plugin type
458
     */
459
    public static function resolve_plugininfo_class($type) {
460
        $plugintypes = core_component::get_plugin_types();
461
        if (!isset($plugintypes[$type])) {
462
            return '\core\plugininfo\orphaned';
463
        }
464
 
465
        $parent = core_component::get_subtype_parent($type);
466
 
467
        if ($parent) {
468
            $class = '\\' . $parent . '\plugininfo\\' . $type;
469
            if (class_exists($class)) {
470
                $plugintypeclass = $class;
471
            } else {
472
                if ($dir = core_component::get_component_directory($parent)) {
473
                    // BC only - use namespace instead!
474
                    if (file_exists("$dir/adminlib.php")) {
475
                        global $CFG;
476
                        include_once("$dir/adminlib.php");
477
                    }
478
                    if (class_exists('plugininfo_' . $type)) {
479
                        $plugintypeclass = 'plugininfo_' . $type;
480
                        debugging('Class "' . $plugintypeclass . '" is deprecated, migrate to "' . $class . '"', DEBUG_DEVELOPER);
481
                    } else {
482
                        debugging('Subplugin type "' . $type . '" should define class "' . $class . '"', DEBUG_DEVELOPER);
483
                        $plugintypeclass = '\core\plugininfo\general';
484
                    }
485
                } else {
486
                    $plugintypeclass = '\core\plugininfo\general';
487
                }
488
            }
489
        } else {
490
            $class = '\core\plugininfo\\' . $type;
491
            if (class_exists($class)) {
492
                $plugintypeclass = $class;
493
            } else {
494
                debugging('All standard types including "' . $type . '" should have plugininfo class!', DEBUG_DEVELOPER);
495
                $plugintypeclass = '\core\plugininfo\general';
496
            }
497
        }
498
 
499
        if (!in_array('core\plugininfo\base', class_parents($plugintypeclass))) {
500
            throw new coding_exception('Class ' . $plugintypeclass . ' must extend \core\plugininfo\base');
501
        }
502
 
503
        return $plugintypeclass;
504
    }
505
 
506
    /**
507
     * Returns list of all known subplugins of the given plugin.
508
     *
509
     * For plugins that do not provide subplugins (i.e. there is no support for it),
510
     * empty array is returned.
511
     *
512
     * @param string $component full component name, e.g. 'mod_workshop'
513
     * @return array (string) component name (e.g. 'workshopallocation_random') => subclass of {@link \core\plugininfo\base}
514
     */
515
    public function get_subplugins_of_plugin($component) {
516
 
517
        $pluginfo = $this->get_plugin_info($component);
518
 
519
        if (is_null($pluginfo)) {
520
            return [];
521
        }
522
 
523
        $subplugins = $this->get_subplugins();
524
 
525
        if (!isset($subplugins[$pluginfo->component])) {
526
            return [];
527
        }
528
 
529
        $list = [];
530
 
531
        foreach ($subplugins[$pluginfo->component] as $subdata) {
532
            foreach ($this->get_plugins_of_type($subdata->type) as $subpluginfo) {
533
                $list[$subpluginfo->component] = $subpluginfo;
534
            }
535
        }
536
 
537
        return $list;
538
    }
539
 
540
    /**
541
     * Returns list of plugins that define their subplugins and the information
542
     * about them from the db/subplugins.json file.
543
     *
544
     * @return array with keys like 'mod_quiz', and values the data from the
545
     *      corresponding db/subplugins.json file.
546
     */
547
    public function get_subplugins() {
548
 
549
        if (is_array($this->subpluginsinfo)) {
550
            return $this->subpluginsinfo;
551
        }
552
 
553
        $plugintypes = core_component::get_plugin_types();
554
 
555
        $this->subpluginsinfo = [];
556
        foreach (core_component::get_plugin_types_with_subplugins() as $type => $ignored) {
557
            foreach (core_component::get_plugin_list($type) as $plugin => $componentdir) {
558
                $component = $type . '_' . $plugin;
559
                $subplugins = core_component::get_subplugins($component);
560
                if (!$subplugins) {
561
                    continue;
562
                }
563
                $this->subpluginsinfo[$component] = [];
564
                foreach ($subplugins as $subplugintype => $ignored) {
565
                    $subplugin = new stdClass();
566
                    $subplugin->type = $subplugintype;
567
                    $subplugin->typerootdir = $plugintypes[$subplugintype];
568
                    $this->subpluginsinfo[$component][$subplugintype] = $subplugin;
569
                }
570
            }
571
        }
572
        return $this->subpluginsinfo;
573
    }
574
 
575
    /**
576
     * Returns the name of the plugin that defines the given subplugin type
577
     *
578
     * If the given subplugin type is not actually a subplugin, returns false.
579
     *
580
     * @param string $subplugintype the name of subplugin type, eg. workshopform or quiz
581
     * @return false|string the name of the parent plugin, eg. mod_workshop
582
     */
583
    public function get_parent_of_subplugin($subplugintype) {
584
        $parent = core_component::get_subtype_parent($subplugintype);
585
        if (!$parent) {
586
            return false;
587
        }
588
        return $parent;
589
    }
590
 
591
    /**
592
     * Returns a localized name of a given plugin
593
     *
594
     * @param string $component name of the plugin, eg mod_workshop or auth_ldap
595
     * @return string
596
     */
597
    public function plugin_name($component) {
598
 
599
        $pluginfo = $this->get_plugin_info($component);
600
 
601
        if (is_null($pluginfo)) {
602
            throw new moodle_exception('err_unknown_plugin', 'core_plugin', '', ['plugin' => $component]);
603
        }
604
 
605
        return $pluginfo->displayname;
606
    }
607
 
608
    /**
609
     * Returns a localized name of a plugin typed in singular form
610
     *
611
     * Most plugin types define their names in core_plugin lang file. In case of subplugins,
612
     * we try to ask the parent plugin for the name. In the worst case, we will return
613
     * the value of the passed $type parameter.
614
     *
615
     * @param string $type the type of the plugin, e.g. mod or workshopform
616
     * @return string
617
     */
618
    public function plugintype_name($type) {
619
        if (get_string_manager()->string_exists('type_' . $type, 'core_plugin')) {
620
            // For most plugin types, their names are defined in core_plugin lang file.
621
            return get_string('type_' . $type, 'core_plugin');
622
        } else if ($parent = $this->get_parent_of_subplugin($type)) {
623
            // If this is a subplugin, try to ask the parent plugin for the name.
624
            return $this->plugin_name($parent) . ' / ' . get_string('subplugintype_' . $type, $parent);
625
        } else {
626
            return $type;
627
        }
628
    }
629
 
630
    /**
631
     * Returns a localized name of a plugin type in plural form
632
     *
633
     * Most plugin types define their names in core_plugin lang file. In case of subplugins,
634
     * we try to ask the parent plugin for the name. In the worst case, we will return
635
     * the value of the passed $type parameter.
636
     *
637
     * @param string $type the type of the plugin, e.g. mod or workshopform
638
     * @return string
639
     */
640
    public function plugintype_name_plural($type) {
641
        if (get_string_manager()->string_exists('type_' . $type . '_plural', 'core_plugin')) {
642
            // For most plugin types, their names are defined in core_plugin lang file.
643
            return get_string('type_' . $type . '_plural', 'core_plugin');
644
        } else if ($parent = $this->get_parent_of_subplugin($type)) {
645
            // If this is a subplugin, try to ask the parent plugin for the name.
646
            return $this->plugin_name($parent) . ' / ' . get_string('subplugintype_' . $type . '_plural', $parent);
647
        } else {
648
            return $type;
649
        }
650
    }
651
 
652
    /**
653
     * Returns information about the known plugin, or null
654
     *
655
     * @param string $component frankenstyle component name.
656
     * @return \core\plugininfo\base|null the corresponding plugin information.
657
     */
658
    public function get_plugin_info($component) {
659
        [$type, $name] = core_component::normalize_component($component);
660
        $plugins = $this->get_plugins_of_type($type);
661
        if (isset($plugins[$name])) {
662
            return $plugins[$name];
663
        } else {
664
            return null;
665
        }
666
    }
667
 
668
    /**
669
     * Check to see if the current version of the plugin seems to be a checkout of an external repository.
670
     *
671
     * @param string $component frankenstyle component name
672
     * @return false|string
673
     */
674
    public function plugin_external_source($component) {
675
 
676
        $plugininfo = $this->get_plugin_info($component);
677
 
678
        if (is_null($plugininfo)) {
679
            return false;
680
        }
681
 
682
        $pluginroot = $plugininfo->rootdir;
683
 
684
        if (is_dir($pluginroot . '/.git')) {
685
            return 'git';
686
        }
687
 
688
        if (is_file($pluginroot . '/.git')) {
689
            return 'git-submodule';
690
        }
691
 
692
        if (is_dir($pluginroot . '/CVS')) {
693
            return 'cvs';
694
        }
695
 
696
        if (is_dir($pluginroot . '/.svn')) {
697
            return 'svn';
698
        }
699
 
700
        if (is_dir($pluginroot . '/.hg')) {
701
            return 'mercurial';
702
        }
703
 
704
        return false;
705
    }
706
 
707
    /**
708
     * Get a list of any other plugins that require this one.
709
     * @param string $component frankenstyle component name.
710
     * @return array of frankensyle component names that require this one.
711
     */
712
    public function other_plugins_that_require($component) {
713
        $others = [];
714
        foreach ($this->get_plugins() as $type => $plugins) {
715
            foreach ($plugins as $plugin) {
716
                $required = $plugin->get_other_required_plugins();
717
                if (isset($required[$component])) {
718
                    $others[] = $plugin->component;
719
                }
720
            }
721
        }
722
        return $others;
723
    }
724
 
725
    /**
726
     * Check a dependencies list against the list of installed plugins.
727
     * @param array $dependencies compenent name to required version or ANY_VERSION.
728
     * @return bool true if all the dependencies are satisfied.
729
     */
730
    public function are_dependencies_satisfied($dependencies) {
731
        foreach ($dependencies as $component => $requiredversion) {
732
            $otherplugin = $this->get_plugin_info($component);
733
            if (is_null($otherplugin)) {
734
                return false;
735
            }
736
 
737
            if ($requiredversion != ANY_VERSION && $otherplugin->versiondisk < $requiredversion) {
738
                return false;
739
            }
740
        }
741
 
742
        return true;
743
    }
744
 
745
    /**
746
     * Checks all dependencies for all installed plugins
747
     *
748
     * This is used by install and upgrade. The array passed by reference as the second
749
     * argument is populated with the list of plugins that have failed dependencies (note that
750
     * a single plugin can appear multiple times in the $failedplugins).
751
     *
752
     * @param int $moodleversion the version from version.php.
753
     * @param array $failedplugins to return the list of plugins with non-satisfied dependencies
754
     * @param int $branch the current moodle branch, null if not provided
755
     * @return bool true if all the dependencies are satisfied for all plugins.
756
     */
757
    public function all_plugins_ok($moodleversion, &$failedplugins = [], $branch = null) {
758
        global $CFG;
759
        if (empty($branch)) {
760
            $branch = $CFG->branch ?? '';
761
            if (empty($branch)) {
762
                // During initial install there is no branch set.
763
                require($CFG->dirroot . '/version.php');
764
                $branch = (int)$branch;
765
                // Force CFG->branch to int value during install.
766
                $CFG->branch = $branch;
767
            }
768
        }
769
        $return = true;
770
        foreach ($this->get_plugins() as $type => $plugins) {
771
            foreach ($plugins as $plugin) {
772
                if (!$plugin->is_core_dependency_satisfied($moodleversion)) {
773
                    $return = false;
774
                    $failedplugins[] = $plugin->component;
775
                }
776
 
777
                if (!$this->are_dependencies_satisfied($plugin->get_other_required_plugins())) {
778
                    $return = false;
779
                    $failedplugins[] = $plugin->component;
780
                }
781
 
782
                if (!$plugin->is_core_compatible_satisfied($branch)) {
783
                    $return = false;
784
                    $failedplugins[] = $plugin->component;
785
                }
786
            }
787
        }
788
 
789
        return $return;
790
    }
791
 
792
    /**
793
     * Resolve requirements and dependencies of a plugin.
794
     *
795
     * Returns an array of objects describing the requirement/dependency,
796
     * indexed by the frankenstyle name of the component. The returned array
797
     * can be empty. The objects in the array have following properties:
798
     *
799
     *  ->(numeric)hasver
800
     *  ->(numeric)reqver
801
     *  ->(string)status
802
     *  ->(string)availability
803
     *
804
     * @param \core\plugininfo\base $plugin the plugin we are checking
805
     * @param null|string|int|double $moodleversion explicit moodle core version to check against, defaults to $CFG->version
806
     * @param null|string|int $moodlebranch explicit moodle core branch to check against, defaults to $CFG->branch
807
     * @return array of objects
808
     */
809
    public function resolve_requirements(\core\plugininfo\base $plugin, $moodleversion = null, $moodlebranch = null) {
810
        global $CFG;
811
 
812
        if ($plugin->versiondisk === null) {
813
            // Missing from disk, we have no version.php to read from.
814
            return [];
815
        }
816
 
817
        if ($moodleversion === null) {
818
            $moodleversion = $CFG->version;
819
        }
820
 
821
        if ($moodlebranch === null) {
822
            $moodlebranch = $CFG->branch;
823
        }
824
 
825
        $reqs = [];
826
        $reqcore = $this->resolve_core_requirements($plugin, $moodleversion, $moodlebranch);
827
 
828
        if (!empty($reqcore)) {
829
            $reqs['core'] = $reqcore;
830
        }
831
 
832
        foreach ($plugin->get_other_required_plugins() as $reqplug => $reqver) {
833
            $reqs[$reqplug] = $this->resolve_dependency_requirements($plugin, $reqplug, $reqver, $moodlebranch);
834
        }
835
 
836
        return $reqs;
837
    }
838
 
839
    /**
840
     * Helper method to resolve plugin's requirements on the moodle core.
841
     *
842
     * @param \core\plugininfo\base $plugin the plugin we are checking
843
     * @param string|int|double $moodleversion moodle core branch to check against
844
     * @return stdClass
845
     */
846
    protected function resolve_core_requirements(\core\plugininfo\base $plugin, $moodleversion, $moodlebranch) {
847
        $reqs = (object)[
848
            'hasver' => null,
849
            'reqver' => null,
850
            'status' => null,
851
            'availability' => null,
852
        ];
853
        $reqs->hasver = $moodleversion;
854
 
855
        if (empty($plugin->versionrequires)) {
856
            $reqs->reqver = ANY_VERSION;
857
        } else {
858
            $reqs->reqver = $plugin->versionrequires;
859
        }
860
 
861
        if ($plugin->is_core_dependency_satisfied($moodleversion)) {
862
            $reqs->status = self::REQUIREMENT_STATUS_OK;
863
        } else {
864
            $reqs->status = self::REQUIREMENT_STATUS_OUTDATED;
865
        }
866
 
867
        // Now check if there is an explicit incompatible, supersedes requires.
868
        if (isset($plugin->pluginincompatible) && $plugin->pluginincompatible != null) {
869
            if (!$plugin->is_core_compatible_satisfied($moodlebranch)) {
870
                $reqs->status = self::REQUIREMENT_STATUS_NEWER;
871
            }
872
        }
873
 
874
        return $reqs;
875
    }
876
 
877
    /**
878
     * Helper method to resolve plugin's dependecies on other plugins.
879
     *
880
     * @param \core\plugininfo\base $plugin the plugin we are checking
881
     * @param string $otherpluginname
882
     * @param string|int $requiredversion
883
     * @param string|int $moodlebranch explicit moodle core branch to check against, defaults to $CFG->branch
884
     * @return stdClass
885
     */
886
    protected function resolve_dependency_requirements(
887
        \core\plugininfo\base $plugin,
888
        $otherpluginname,
889
        $requiredversion,
890
        $moodlebranch
891
    ) {
892
 
893
        $reqs = (object)[
894
            'hasver' => null,
895
            'reqver' => null,
896
            'status' => null,
897
            'availability' => null,
898
        ];
899
 
900
        $otherplugin = $this->get_plugin_info($otherpluginname);
901
 
902
        if ($otherplugin !== null) {
903
            // The required plugin is installed.
904
            $reqs->hasver = $otherplugin->versiondisk;
905
            $reqs->reqver = $requiredversion;
906
            // Check it has sufficient version.
907
            if ($requiredversion == ANY_VERSION || $otherplugin->versiondisk >= $requiredversion) {
908
                $reqs->status = self::REQUIREMENT_STATUS_OK;
909
            } else {
910
                $reqs->status = self::REQUIREMENT_STATUS_OUTDATED;
911
            }
912
        } else {
913
            // The required plugin is not installed.
914
            $reqs->hasver = null;
915
            $reqs->reqver = $requiredversion;
916
            $reqs->status = self::REQUIREMENT_STATUS_MISSING;
917
        }
918
 
919
        if ($reqs->status !== self::REQUIREMENT_STATUS_OK) {
920
            if ($this->is_remote_plugin_available($otherpluginname, $requiredversion, false)) {
921
                $reqs->availability = self::REQUIREMENT_AVAILABLE;
922
            } else {
923
                $reqs->availability = self::REQUIREMENT_UNAVAILABLE;
924
            }
925
        }
926
 
927
        return $reqs;
928
    }
929
 
930
    /**
931
     * Helper method to determine whether a moodle version is explicitly supported.
932
     *
933
     * @param \core\plugininfo\base $plugin the plugin we are checking
934
     * @param int $branch the moodle branch to check support for
935
     * @return string
936
     */
937
    public function check_explicitly_supported($plugin, $branch): string {
938
        // Check for correctly formed supported.
939
        if (isset($plugin->pluginsupported)) {
940
            // Broken apart for readability.
941
            $error = false;
942
            if (!is_array($plugin->pluginsupported)) {
943
                $error = true;
944
            }
945
            if (!is_int($plugin->pluginsupported[0]) || !is_int($plugin->pluginsupported[1])) {
946
                $error = true;
947
            }
948
            if (count($plugin->pluginsupported) != 2) {
949
                $error = true;
950
            }
951
            if ($error) {
952
                throw new coding_exception(get_string('err_supported_syntax', 'core_plugin'));
953
            }
954
        }
955
 
956
        if (isset($plugin->pluginsupported) && $plugin->pluginsupported != null) {
957
            if ($plugin->pluginsupported[0] <= $branch && $branch <= $plugin->pluginsupported[1]) {
958
                return self::VERSION_SUPPORTED;
959
            } else {
960
                return self::VERSION_NOT_SUPPORTED;
961
            }
962
        } else {
963
            // If supports aren't specified, but incompatible is, return not supported if not incompatible.
964
            if (!isset($plugin->pluginsupported) && isset($plugin->pluginincompatible) && !empty($plugin->pluginincompatible)) {
965
                if (!$plugin->is_core_compatible_satisfied($branch)) {
966
                    return self::VERSION_NOT_SUPPORTED;
967
                }
968
            }
969
            return self::VERSION_NO_SUPPORTS;
970
        }
971
    }
972
 
973
    /**
974
     * Is the given plugin version available in the plugins directory?
975
     *
976
     * See {@link self::get_remote_plugin_info()} for the full explanation of how the $version
977
     * parameter is interpretted.
978
     *
979
     * @param string $component plugin frankenstyle name
980
     * @param string|int $version ANY_VERSION or the version number
981
     * @param bool $exactmatch false if "given version or higher" is requested
982
     * @return boolean
983
     */
984
    public function is_remote_plugin_available($component, $version, $exactmatch) {
985
 
986
        $info = $this->get_remote_plugin_info($component, $version, $exactmatch);
987
 
988
        if (empty($info)) {
989
            // There is no available plugin of that name.
990
            return false;
991
        }
992
 
993
        if (empty($info->version)) {
994
            // Plugin is known, but no suitable version was found.
995
            return false;
996
        }
997
 
998
        return true;
999
    }
1000
 
1001
    /**
1002
     * Can the given plugin version be installed via the admin UI?
1003
     *
1004
     * This check should be used whenever attempting to install a plugin from
1005
     * the plugins directory (new install, available update, missing dependency).
1006
     *
1007
     * @param string $component
1008
     * @param int $version version number
1009
     * @param string $reason returned code of the reason why it is not
1010
     * @param bool $checkremote check this version availability on moodle server
1011
     * @return boolean
1012
     */
1013
    public function is_remote_plugin_installable($component, $version, &$reason = null, $checkremote = true) {
1014
        global $CFG;
1015
 
1016
        // Make sure the feature is not disabled.
1017
        if (!empty($CFG->disableupdateautodeploy)) {
1018
            $reason = 'disabled';
1019
            return false;
1020
        }
1021
 
1022
        // Make sure the version is available.
1023
        if ($checkremote && !$this->is_remote_plugin_available($component, $version, true)) {
1024
            $reason = 'remoteunavailable';
1025
            return false;
1026
        }
1027
 
1028
        // Make sure the plugin type root directory is writable.
1029
        [$plugintype, $pluginname] = core_component::normalize_component($component);
1030
        if (!$this->is_plugintype_writable($plugintype)) {
1031
            $reason = 'notwritableplugintype';
1032
            return false;
1033
        }
1034
 
1035
        if (!$checkremote) {
1036
            $remoteversion = $version;
1037
        } else {
1038
            $remoteinfo = $this->get_remote_plugin_info($component, $version, true);
1039
            $remoteversion = $remoteinfo->version->version;
1040
        }
1041
        $localinfo = $this->get_plugin_info($component);
1042
 
1043
        if ($localinfo) {
1044
            // If the plugin is already present, prevent downgrade.
1045
            if ($localinfo->versiondb > $remoteversion) {
1046
                $reason = 'cannotdowngrade';
1047
                return false;
1048
            }
1049
 
1050
            // Make sure we have write access to all the existing code.
1051
            if (is_dir($localinfo->rootdir)) {
1052
                if (!$this->is_plugin_folder_removable($component)) {
1053
                    $reason = 'notwritableplugin';
1054
                    return false;
1055
                }
1056
            }
1057
        }
1058
 
1059
        // Looks like it could work.
1060
        return true;
1061
    }
1062
 
1063
    /**
1064
     * Given the list of remote plugin infos, return just those installable.
1065
     *
1066
     * This is typically used on lists returned by
1067
     * {@link self::available_updates()} or {@link self::missing_dependencies()}
1068
     * to perform bulk installation of remote plugins.
1069
     *
1070
     * @param array $remoteinfos list of {@link \core\update\remote_info}
1071
     * @return array
1072
     */
1073
    public function filter_installable($remoteinfos) {
1074
        global $CFG;
1075
 
1076
        if (!empty($CFG->disableupdateautodeploy)) {
1077
            return [];
1078
        }
1079
        if (empty($remoteinfos)) {
1080
            return [];
1081
        }
1082
        $installable = [];
1083
        foreach ($remoteinfos as $index => $remoteinfo) {
1084
            if ($this->is_remote_plugin_installable($remoteinfo->component, $remoteinfo->version->version)) {
1085
                $installable[$index] = $remoteinfo;
1086
            }
1087
        }
1088
        return $installable;
1089
    }
1090
 
1091
    /**
1092
     * Returns information about a plugin in the plugins directory.
1093
     *
1094
     * This is typically used when checking for available dependencies (in
1095
     * which case the $version represents minimal version we need), or
1096
     * when installing an available update or a new plugin from the plugins
1097
     * directory (in which case the $version is exact version we are
1098
     * interested in). The interpretation of the $version is controlled
1099
     * by the $exactmatch argument.
1100
     *
1101
     * If a plugin with the given component name is found, data about the
1102
     * plugin are returned as an object. The ->version property of the object
1103
     * contains the information about the particular plugin version that
1104
     * matches best the given critera. The ->version property is false if no
1105
     * suitable version of the plugin was found (yet the plugin itself is
1106
     * known).
1107
     *
1108
     * See {@link \core\update\api::validate_pluginfo_format()} for the
1109
     * returned data structure.
1110
     *
1111
     * @param string $component plugin frankenstyle name
1112
     * @param string|int $version ANY_VERSION or the version number
1113
     * @param bool $exactmatch false if "given version or higher" is requested
1114
     * @return \core\update\remote_info|bool
1115
     */
1116
    public function get_remote_plugin_info($component, $version, $exactmatch) {
1117
        if ($exactmatch && $version == ANY_VERSION) {
1118
            throw new coding_exception('Invalid request for exactly any version, it does not make sense.');
1119
        }
1120
 
1121
        $client = $this->get_update_api_client();
1122
 
1123
        if ($exactmatch) {
1124
            // Use client's get_plugin_info() method.
1125
            if (!isset($this->remotepluginsinfoexact[$component][$version])) {
1126
                $this->remotepluginsinfoexact[$component][$version] = $client->get_plugin_info($component, $version);
1127
            }
1128
            return $this->remotepluginsinfoexact[$component][$version];
1129
        } else {
1130
            // Use client's find_plugin() method.
1131
            if (!isset($this->remotepluginsinfoatleast[$component][$version])) {
1132
                $this->remotepluginsinfoatleast[$component][$version] = $client->find_plugin($component, $version);
1133
            }
1134
            return $this->remotepluginsinfoatleast[$component][$version];
1135
        }
1136
    }
1137
 
1138
    /**
1139
     * Obtain the plugin ZIP file from the given URL
1140
     *
1141
     * The caller is supposed to know both downloads URL and the MD5 hash of
1142
     * the ZIP contents in advance, typically by using the API requests against
1143
     * the plugins directory.
1144
     *
1145
     * @param string $url
1146
     * @param string $md5
1147
     * @return string|bool full path to the file, false on error
1148
     */
1149
    public function get_remote_plugin_zip($url, $md5) {
1150
        global $CFG;
1151
 
1152
        if (!empty($CFG->disableupdateautodeploy)) {
1153
            return false;
1154
        }
1155
        return $this->get_code_manager()->get_remote_plugin_zip($url, $md5);
1156
    }
1157
 
1158
    /**
1159
     * Extracts the saved plugin ZIP file.
1160
     *
1161
     * Returns the list of files found in the ZIP. The format of that list is
1162
     * array of (string)filerelpath => (bool|string) where the array value is
1163
     * either true or a string describing the problematic file.
1164
     *
1165
     * @see zip_packer::extract_to_pathname()
1166
     * @param string $zipfilepath full path to the saved ZIP file
1167
     * @param string $targetdir full path to the directory to extract the ZIP file to
1168
     * @param string $rootdir explicitly rename the root directory of the ZIP into this non-empty value
1169
     * @return array list of extracted files as returned by {@link zip_packer::extract_to_pathname()}
1170
     */
1171
    public function unzip_plugin_file($zipfilepath, $targetdir, $rootdir = '') {
1172
        return $this->get_code_manager()->unzip_plugin_file($zipfilepath, $targetdir, $rootdir);
1173
    }
1174
 
1175
    /**
1176
     * Detects the plugin's name from its ZIP file.
1177
     *
1178
     * Plugin ZIP packages are expected to contain a single directory and the
1179
     * directory name would become the plugin name once extracted to the Moodle
1180
     * dirroot.
1181
     *
1182
     * @param string $zipfilepath full path to the ZIP files
1183
     * @return string|bool false on error
1184
     */
1185
    public function get_plugin_zip_root_dir($zipfilepath) {
1186
        return $this->get_code_manager()->get_plugin_zip_root_dir($zipfilepath);
1187
    }
1188
 
1189
    /**
1190
     * Return a list of missing dependencies.
1191
     *
1192
     * This should provide the full list of plugins that should be installed to
1193
     * fulfill the requirements of all plugins, if possible.
1194
     *
1195
     * @param bool $availableonly return only available missing dependencies
1196
     * @return array of \core\update\remote_info|bool indexed by the component name
1197
     */
1198
    public function missing_dependencies($availableonly = false) {
1199
 
1200
        $dependencies = [];
1201
 
1202
        foreach ($this->get_plugins() as $plugintype => $pluginfos) {
1203
            foreach ($pluginfos as $pluginname => $pluginfo) {
1204
                foreach ($this->resolve_requirements($pluginfo) as $reqname => $reqinfo) {
1205
                    if ($reqname === 'core') {
1206
                        continue;
1207
                    }
1208
                    if ($reqinfo->status != self::REQUIREMENT_STATUS_OK) {
1209
                        if ($reqinfo->availability == self::REQUIREMENT_AVAILABLE) {
1210
                            $remoteinfo = $this->get_remote_plugin_info($reqname, $reqinfo->reqver, false);
1211
 
1212
                            if (empty($dependencies[$reqname])) {
1213
                                $dependencies[$reqname] = $remoteinfo;
1214
                            } else {
1215
                                // If resolving requirements has led to two different versions of the same
1216
                                // remote plugin, pick the higher version. This can happen in cases like one
1217
                                // plugin requiring ANY_VERSION and another plugin requiring specific higher
1218
                                // version with lower maturity of a remote plugin.
1219
                                if ($remoteinfo->version->version > $dependencies[$reqname]->version->version) {
1220
                                    $dependencies[$reqname] = $remoteinfo;
1221
                                }
1222
                            }
1223
                        } else {
1224
                            if (!isset($dependencies[$reqname])) {
1225
                                // Unable to find a plugin fulfilling the requirements.
1226
                                $dependencies[$reqname] = false;
1227
                            }
1228
                        }
1229
                    }
1230
                }
1231
            }
1232
        }
1233
 
1234
        if ($availableonly) {
1235
            foreach ($dependencies as $component => $info) {
1236
                if (empty($info) || empty($info->version)) {
1237
                    unset($dependencies[$component]);
1238
                }
1239
            }
1240
        }
1241
 
1242
        return $dependencies;
1243
    }
1244
 
1245
    /**
1246
     * Is it possible to uninstall the given plugin?
1247
     *
1248
     * False is returned if the plugininfo subclass declares the uninstall should
1249
     * not be allowed via {@link \core\plugininfo\base::is_uninstall_allowed()} or if the
1250
     * core vetoes it (e.g. becase the plugin or some of its subplugins is required
1251
     * by some other installed plugin).
1252
     *
1253
     * @param string $component full frankenstyle name, e.g. mod_foobar
1254
     * @return bool
1255
     */
1256
    public function can_uninstall_plugin($component) {
1257
 
1258
        $pluginfo = $this->get_plugin_info($component);
1259
 
1260
        if (is_null($pluginfo)) {
1261
            return false;
1262
        }
1263
 
1264
        if (!$this->common_uninstall_check($pluginfo)) {
1265
            return false;
1266
        }
1267
 
1268
        // Verify only if something else requires the subplugins, do not verify their common_uninstall_check()!
1269
        $subplugins = $this->get_subplugins_of_plugin($pluginfo->component);
1270
        foreach ($subplugins as $subpluginfo) {
1271
            // Check if there are some other plugins requiring this subplugin
1272
            // (but the parent and siblings).
1273
            foreach ($this->other_plugins_that_require($subpluginfo->component) as $requiresme) {
1274
                $ismyparent = ($pluginfo->component === $requiresme);
1275
                $ismysibling = in_array($requiresme, array_keys($subplugins));
1276
                if (!$ismyparent && !$ismysibling) {
1277
                    return false;
1278
                }
1279
            }
1280
        }
1281
 
1282
        // Check if there are some other plugins requiring this plugin
1283
        // (but its subplugins).
1284
        foreach ($this->other_plugins_that_require($pluginfo->component) as $requiresme) {
1285
            $ismysubplugin = in_array($requiresme, array_keys($subplugins));
1286
            if (!$ismysubplugin) {
1287
                return false;
1288
            }
1289
        }
1290
 
1291
        return true;
1292
    }
1293
 
1294
    /**
1295
     * Perform the installation of plugins.
1296
     *
1297
     * If used for installation of remote plugins from the Moodle Plugins
1298
     * directory, the $plugins must be list of {@link \core\update\remote_info}
1299
     * object that represent installable remote plugins. The caller can use
1300
     * {@link self::filter_installable()} to prepare the list.
1301
     *
1302
     * If used for installation of plugins from locally available ZIP files,
1303
     * the $plugins should be list of objects with properties ->component and
1304
     * ->zipfilepath.
1305
     *
1306
     * The method uses {@link mtrace()} to produce direct output and can be
1307
     * used in both web and cli interfaces.
1308
     *
1309
     * @param array $plugins list of plugins
1310
     * @param bool $confirmed should the files be really deployed into the dirroot?
1311
     * @param bool $silent perform without output
1312
     * @return bool true on success
1313
     */
1314
    public function install_plugins(array $plugins, $confirmed, $silent) {
1315
        global $CFG, $OUTPUT;
1316
 
1317
        if (!empty($CFG->disableupdateautodeploy)) {
1318
            return false;
1319
        }
1320
 
1321
        if (empty($plugins)) {
1322
            return false;
1323
        }
1324
 
1325
        $ok = get_string('statusok', 'core');
1326
 
1327
        // Let admins know they can expect more verbose output.
1328
        $silent || $this->mtrace(get_string('packagesdebug', 'core_plugin'), PHP_EOL, DEBUG_NORMAL);
1329
 
1330
        // Download all ZIP packages if we do not have them yet.
1331
        $zips = [];
1332
        foreach ($plugins as $plugin) {
1333
            if ($plugin instanceof \core\update\remote_info) {
1334
                $zips[$plugin->component] = $this->get_remote_plugin_zip(
1335
                    $plugin->version->downloadurl,
1336
                    $plugin->version->downloadmd5
1337
                );
1338
                $silent || $this->mtrace(get_string('packagesdownloading', 'core_plugin', $plugin->component), ' ... ');
1339
                $silent || $this->mtrace(PHP_EOL . ' <- ' . $plugin->version->downloadurl, '', DEBUG_DEVELOPER);
1340
                $silent || $this->mtrace(PHP_EOL . ' -> ' . $zips[$plugin->component], ' ... ', DEBUG_DEVELOPER);
1341
                if (!$zips[$plugin->component]) {
1342
                    $silent || $this->mtrace(get_string('error'));
1343
                    return false;
1344
                }
1345
                $silent || $this->mtrace($ok);
1346
            } else {
1347
                if (empty($plugin->zipfilepath)) {
1348
                    throw new coding_exception('Unexpected data structure provided');
1349
                }
1350
                $zips[$plugin->component] = $plugin->zipfilepath;
1351
                $silent || $this->mtrace('ZIP ' . $plugin->zipfilepath, PHP_EOL, DEBUG_DEVELOPER);
1352
            }
1353
        }
1354
 
1355
        // Validate all downloaded packages.
1356
        foreach ($plugins as $plugin) {
1357
            $zipfile = $zips[$plugin->component];
1358
            $silent || $this->mtrace(get_string('packagesvalidating', 'core_plugin', $plugin->component), ' ... ');
1359
            [$plugintype, $pluginname] = core_component::normalize_component($plugin->component);
1360
            $tmp = make_request_directory();
1361
            $zipcontents = $this->unzip_plugin_file($zipfile, $tmp, $pluginname);
1362
            if (empty($zipcontents)) {
1363
                $silent || $this->mtrace(get_string('error'));
1364
                $silent || $this->mtrace('Unable to unzip ' . $zipfile, PHP_EOL, DEBUG_DEVELOPER);
1365
                return false;
1366
            }
1367
 
1368
            $validator = \core\update\validator::instance($tmp, $zipcontents);
1369
            $validator->assert_plugin_type($plugintype);
1370
            $validator->assert_moodle_version($CFG->version);
1371
            // TODO Check for missing dependencies during validation.
1372
            $result = $validator->execute();
1373
            if (!$silent) {
1374
                $result ? $this->mtrace($ok) : $this->mtrace(get_string('error'));
1375
                foreach ($validator->get_messages() as $message) {
1376
                    if ($message->level === $validator::INFO) {
1377
                        // Display [OK] validation messages only if debugging mode is DEBUG_NORMAL.
1378
                        $level = DEBUG_NORMAL;
1379
                    } else if ($message->level === $validator::DEBUG) {
1380
                        // Display [Debug] validation messages only if debugging mode is DEBUG_ALL.
1381
                        $level = DEBUG_ALL;
1382
                    } else {
1383
                        // Display [Warning] and [Error] always.
1384
                        $level = null;
1385
                    }
1386
                    if ($message->level === $validator::WARNING && !CLI_SCRIPT) {
1387
                        $this->mtrace('  <strong>[' . $validator->message_level_name($message->level) . ']</strong>', ' ', $level);
1388
                    } else {
1389
                        $this->mtrace('  [' . $validator->message_level_name($message->level) . ']', ' ', $level);
1390
                    }
1391
                    $this->mtrace($validator->message_code_name($message->msgcode), ' ', $level);
1392
                    $info = $validator->message_code_info($message->msgcode, $message->addinfo);
1393
                    if ($info) {
1394
                        $this->mtrace('[' . s($info) . ']', ' ', $level);
1395
                    } else if (is_string($message->addinfo)) {
1396
                        $this->mtrace('[' . s($message->addinfo, true) . ']', ' ', $level);
1397
                    } else {
1398
                        $this->mtrace('[' . s(json_encode($message->addinfo, true)) . ']', ' ', $level);
1399
                    }
1400
                    if ($icon = $validator->message_help_icon($message->msgcode)) {
1401
                        if (CLI_SCRIPT) {
1402
                            $this->mtrace(PHP_EOL . '  ^^^ ' . get_string('help') . ': ' .
1403
                                get_string($icon->identifier . '_help', $icon->component), '', $level);
1404
                        } else {
1405
                            $this->mtrace($OUTPUT->render($icon), ' ', $level);
1406
                        }
1407
                    }
1408
                    $this->mtrace(PHP_EOL, '', $level);
1409
                }
1410
            }
1411
            if (!$result) {
1412
                $silent || $this->mtrace(get_string('packagesvalidatingfailed', 'core_plugin'));
1413
                return false;
1414
            }
1415
        }
1416
        $silent || $this->mtrace(PHP_EOL . get_string('packagesvalidatingok', 'core_plugin'));
1417
 
1418
        if (!$confirmed) {
1419
            return true;
1420
        }
1421
 
1422
        // Extract all ZIP packs do the dirroot.
1423
        foreach ($plugins as $plugin) {
1424
            $silent || $this->mtrace(get_string('packagesextracting', 'core_plugin', $plugin->component), ' ... ');
1425
            $zipfile = $zips[$plugin->component];
1426
            [$plugintype, $pluginname] = core_component::normalize_component($plugin->component);
1427
            $target = $this->get_plugintype_root($plugintype);
1428
            if (file_exists($target . '/' . $pluginname)) {
1429
                $this->remove_plugin_folder($this->get_plugin_info($plugin->component));
1430
            }
1431
            if (!$this->unzip_plugin_file($zipfile, $target, $pluginname)) {
1432
                $silent || $this->mtrace(get_string('error'));
1433
                $silent || $this->mtrace('Unable to unzip ' . $zipfile, PHP_EOL, DEBUG_DEVELOPER);
1434
                if (function_exists('opcache_reset')) {
1435
                    opcache_reset();
1436
                }
1437
                return false;
1438
            }
1439
            $silent || $this->mtrace($ok);
1440
        }
1441
        if (function_exists('opcache_reset')) {
1442
            opcache_reset();
1443
        }
1444
 
1445
        return true;
1446
    }
1447
 
1448
    /**
1449
     * Outputs the given message via {@link mtrace()}.
1450
     *
1451
     * If $debug is provided, then the message is displayed only at the given
1452
     * debugging level (e.g. DEBUG_DEVELOPER to display the message only if the
1453
     * site has developer debugging level selected).
1454
     *
1455
     * @param string $msg message
1456
     * @param string $eol end of line
1457
     * @param null|int $debug null to display always, int only on given debug level
1458
     */
1459
    protected function mtrace($msg, $eol = PHP_EOL, $debug = null) {
1460
        global $CFG;
1461
 
1462
        if ($debug !== null && !debugging(null, $debug)) {
1463
            return;
1464
        }
1465
 
1466
        mtrace($msg, $eol);
1467
    }
1468
 
1469
    /**
1470
     * Returns uninstall URL if exists.
1471
     *
1472
     * @param string $component
1473
     * @param string $return either 'overview' or 'manage'
1474
     * @return null|moodle_url uninstall URL, null if uninstall not supported
1475
     */
1476
    public function get_uninstall_url($component, $return = 'overview') {
1477
        if (!$this->can_uninstall_plugin($component)) {
1478
            return null;
1479
        }
1480
 
1481
        $pluginfo = $this->get_plugin_info($component);
1482
 
1483
        if (is_null($pluginfo)) {
1484
            return null;
1485
        }
1486
 
1487
        if (method_exists($pluginfo, 'get_uninstall_url')) {
1488
            debugging(
1489
                'plugininfo method get_uninstall_url() is deprecated, all plugins should be uninstalled via standard URL only.',
1490
                DEBUG_DEVELOPER
1491
            );
1492
            return $pluginfo->get_uninstall_url($return);
1493
        }
1494
 
1495
        return $pluginfo->get_default_uninstall_url($return);
1496
    }
1497
 
1498
    /**
1499
     * Uninstall the given plugin.
1500
     *
1501
     * Automatically cleans-up all remaining configuration data, log records, events,
1502
     * files from the file pool etc.
1503
     *
1504
     * In the future, the functionality of {@link uninstall_plugin()} function may be moved
1505
     * into this method and all the code should be refactored to use it. At the moment, we
1506
     * mimic this future behaviour by wrapping that function call.
1507
     *
1508
     * @param string $component
1509
     * @param progress_trace $progress traces the process
1510
     * @return bool true on success, false on errors/problems
1511
     */
1512
    public function uninstall_plugin($component, progress_trace $progress) {
1513
 
1514
        $pluginfo = $this->get_plugin_info($component);
1515
 
1516
        if (is_null($pluginfo)) {
1517
            return false;
1518
        }
1519
 
1520
        // Give the pluginfo class a chance to execute some steps.
1521
        $result = $pluginfo->uninstall($progress);
1522
        if (!$result) {
1523
            return false;
1524
        }
1525
 
1526
        // Call the legacy core function to uninstall the plugin.
1527
        ob_start();
1528
        uninstall_plugin($pluginfo->type, $pluginfo->name);
1529
        $progress->output(ob_get_clean());
1530
 
1531
        return true;
1532
    }
1533
 
1534
    /**
1535
     * Checks if there are some plugins with a known available update
1536
     *
1537
     * @return bool true if there is at least one available update
1538
     */
1539
    public function some_plugins_updatable() {
1540
        foreach ($this->get_plugins() as $type => $plugins) {
1541
            foreach ($plugins as $plugin) {
1542
                if ($plugin->available_updates()) {
1543
                    return true;
1544
                }
1545
            }
1546
        }
1547
 
1548
        return false;
1549
    }
1550
 
1551
    /**
1552
     * Returns list of available updates for the given component.
1553
     *
1554
     * This method should be considered as internal API and is supposed to be
1555
     * called by {@link \core\plugininfo\base::available_updates()} only
1556
     * to lazy load the data once they are first requested.
1557
     *
1558
     * @param string $component frankenstyle name of the plugin
1559
     * @return null|array array of \core\update\info objects or null
1560
     */
1561
    public function load_available_updates_for_plugin($component) {
1562
        global $CFG;
1563
 
1564
        $provider = \core\update\checker::instance();
1565
 
1566
        if (!$provider->enabled() || $component === '' || during_initial_install()) {
1567
            return null;
1568
        }
1569
 
1570
        if (isset($CFG->updateminmaturity)) {
1571
            $minmaturity = $CFG->updateminmaturity;
1572
        } else {
1573
            // This can happen during the very first upgrade to 2.3.
1574
            $minmaturity = MATURITY_STABLE;
1575
        }
1576
 
1577
        return $provider->get_update_info($component, ['minmaturity' => $minmaturity]);
1578
    }
1579
 
1580
    /**
1581
     * Returns a list of all available updates to be installed.
1582
     *
1583
     * This is used when "update all plugins" action is performed at the
1584
     * administration UI screen.
1585
     *
1586
     * Returns array of remote info objects indexed by the plugin
1587
     * component. If there are multiple updates available (typically a mix of
1588
     * stable and non-stable ones), we pick the most mature most recent one.
1589
     *
1590
     * Plugins without explicit maturity are considered more mature than
1591
     * release candidates but less mature than explicit stable (this should be
1592
     * pretty rare case).
1593
     *
1594
     * @return array (string)component => (\core\update\remote_info)remoteinfo
1595
     */
1596
    public function available_updates() {
1597
 
1598
        $updates = [];
1599
 
1600
        foreach ($this->get_plugins() as $type => $plugins) {
1601
            foreach ($plugins as $plugin) {
1602
                $availableupdates = $plugin->available_updates();
1603
                if (empty($availableupdates)) {
1604
                    continue;
1605
                }
1606
                foreach ($availableupdates as $update) {
1607
                    if (empty($updates[$plugin->component])) {
1608
                        $updates[$plugin->component] = $update;
1609
                        continue;
1610
                    }
1611
                    $maturitycurrent = $updates[$plugin->component]->maturity;
1612
                    if (empty($maturitycurrent)) {
1613
                        $maturitycurrent = MATURITY_STABLE - 25;
1614
                    }
1615
                    $maturityremote = $update->maturity;
1616
                    if (empty($maturityremote)) {
1617
                        $maturityremote = MATURITY_STABLE - 25;
1618
                    }
1619
                    if ($maturityremote < $maturitycurrent) {
1620
                        continue;
1621
                    }
1622
                    if ($maturityremote > $maturitycurrent) {
1623
                        $updates[$plugin->component] = $update;
1624
                        continue;
1625
                    }
1626
                    if ($update->version > $updates[$plugin->component]->version) {
1627
                        $updates[$plugin->component] = $update;
1628
                        continue;
1629
                    }
1630
                }
1631
            }
1632
        }
1633
 
1634
        foreach ($updates as $component => $update) {
1635
            $remoteinfo = $this->get_remote_plugin_info($component, $update->version, true);
1636
            if (empty($remoteinfo) || empty($remoteinfo->version)) {
1637
                unset($updates[$component]);
1638
            } else {
1639
                $updates[$component] = $remoteinfo;
1640
            }
1641
        }
1642
 
1643
        return $updates;
1644
    }
1645
 
1646
    /**
1647
     * Check to see if the given plugin folder can be removed by the web server process.
1648
     *
1649
     * @param string $component full frankenstyle component
1650
     * @return bool
1651
     */
1652
    public function is_plugin_folder_removable($component) {
1653
 
1654
        $pluginfo = $this->get_plugin_info($component);
1655
 
1656
        if (is_null($pluginfo)) {
1657
            return false;
1658
        }
1659
 
1660
        // To be able to remove the plugin folder, its parent must be writable, too.
1661
        if (!isset($pluginfo->rootdir) || !is_writable(dirname($pluginfo->rootdir))) {
1662
            return false;
1663
        }
1664
 
1665
        // Check that the folder and all its content is writable (thence removable).
1666
        return $this->is_directory_removable($pluginfo->rootdir);
1667
    }
1668
 
1669
    /**
1670
     * Is it possible to create a new plugin directory for the given plugin type?
1671
     *
1672
     * @throws coding_exception for invalid plugin types or non-existing plugin type locations
1673
     * @param string $plugintype
1674
     * @return boolean
1675
     */
1676
    public function is_plugintype_writable($plugintype) {
1677
 
1678
        $plugintypepath = $this->get_plugintype_root($plugintype);
1679
 
1680
        if (is_null($plugintypepath)) {
1681
            throw new coding_exception('Unknown plugin type: ' . $plugintype);
1682
        }
1683
 
1684
        if ($plugintypepath === false) {
1685
            throw new coding_exception('Plugin type location does not exist: ' . $plugintype);
1686
        }
1687
 
1688
        return is_writable($plugintypepath);
1689
    }
1690
 
1691
    /**
1692
     * Returns the full path of the root of the given plugin type
1693
     *
1694
     * Null is returned if the plugin type is not known. False is returned if
1695
     * the plugin type root is expected but not found. Otherwise, string is
1696
     * returned.
1697
     *
1698
     * @param string $plugintype
1699
     * @return string|bool|null
1700
     */
1701
    public function get_plugintype_root($plugintype) {
1702
 
1703
        $plugintypepath = null;
1704
        foreach (core_component::get_plugin_types() as $type => $fullpath) {
1705
            if ($type === $plugintype) {
1706
                $plugintypepath = $fullpath;
1707
                break;
1708
            }
1709
        }
1710
        if (is_null($plugintypepath)) {
1711
            return null;
1712
        }
1713
        if (!is_dir($plugintypepath)) {
1714
            return false;
1715
        }
1716
 
1717
        return $plugintypepath;
1718
    }
1719
 
1720
    /**
1721
     * Defines a list of all plugins that were originally shipped in the standard Moodle distribution,
1722
     * but are not anymore and are deleted during upgrades.
1723
     *
1724
     * The main purpose of this list is to hide missing plugins during upgrade.
1725
     *
1726
     * @param string $type plugin type
1727
     * @param string $name plugin name
1728
     * @return bool
1729
     */
1730
    public static function is_deleted_standard_plugin(
1731
        string $type,
1732
        string $name,
1733
    ): bool {
1734
        // Do not include plugins that were removed during upgrades to versions that are
1735
        // not supported as source versions for upgrade any more. For example, at MOODLE_23_STABLE
1736
        // branch, listed should be no plugins that were removed at 1.9.x - 2.1.x versions as
1737
        // Moodle 2.3 supports upgrades from 2.2.x only.
1738
        $plugins = static::load_standard_plugins()->deleted;
1739
 
1740
        if (property_exists($plugins, $type)) {
1741
            return in_array($name, $plugins->$type);
1742
        }
1743
 
1744
        return false;
1745
    }
1746
 
1747
    /**
1748
     * Fetches a list of all plugins shipped in the standard Moodle distribution.
1749
     *
1750
     * If a type is specified but does not exist, a false value is returned.
1751
     * Otherwise an array of the plugins of the specified type is returned.
1752
     *
1753
     * @param null|string $type
1754
     * @return false|array array of standard plugins or false if the type is unknown
1755
     */
1756
    public static function standard_plugins_list(string $type): array|false {
1757
        $plugins = static::load_standard_plugins()->standard;
1758
 
1759
        if (property_exists($plugins, $type)) {
1760
            return (array) $plugins->$type;
1761
        } else {
1762
            return false;
1763
        }
1764
    }
1765
 
1766
    /**
1767
     * Get all standard plugins by their component name.
1768
     *
1769
     * @return array
1770
     */
1771
    public static function get_standard_plugins(): array {
1772
        $plugins = static::load_standard_plugins()->standard;
1773
 
1774
        $result = [];
1775
        foreach ($plugins as $type => $list) {
1776
            foreach ($list as $plugin) {
1777
                $result[] = "{$type}_{$plugin}";
1778
            }
1779
        }
1780
 
1781
        return $result;
1782
    }
1783
 
1784
    /**
1785
     * Get all deleted standard plugins by their component name.
1786
     *
1787
     * @return array
1788
     */
1789
    public static function get_deleted_plugins(): array {
1790
        $plugins = static::load_standard_plugins()->deleted;
1791
 
1792
        $result = [];
1793
        foreach ($plugins as $type => $list) {
1794
            foreach ($list as $plugin) {
1795
                $result[] = "{$type}_{$plugin}";
1796
            }
1797
        }
1798
 
1799
        return $result;
1800
    }
1801
 
1802
    /**
1803
     * Remove the current plugin code from the dirroot.
1804
     *
1805
     * If removing the currently installed version (which happens during
1806
     * updates), we archive the code so that the upgrade can be cancelled.
1807
     *
1808
     * To prevent accidental data-loss, we also archive the existing plugin
1809
     * code if cancelling installation of it, so that the developer does not
1810
     * loose the only version of their work-in-progress.
1811
     *
1812
     * @param \core\plugininfo\base $plugin
1813
     */
1814
    public function remove_plugin_folder(\core\plugininfo\base $plugin) {
1815
 
1816
        if (!$this->is_plugin_folder_removable($plugin->component)) {
1817
            throw new moodle_exception(
1818
                'err_removing_unremovable_folder',
1819
                'core_plugin',
1820
                '',
1821
                ['plugin' => $plugin->component, 'rootdir' => $plugin->rootdir],
1822
                'plugin root folder is not removable as expected'
1823
            );
1824
        }
1825
 
1826
        if ($plugin->get_status() === self::PLUGIN_STATUS_UPTODATE || $plugin->get_status() === self::PLUGIN_STATUS_NEW) {
1827
            $this->archive_plugin_version($plugin);
1828
        }
1829
 
1830
        remove_dir($plugin->rootdir);
1831
        clearstatcache();
1832
        if (function_exists('opcache_reset')) {
1833
            opcache_reset();
1834
        }
1835
    }
1836
 
1837
    /**
1838
     * Can the installation of the new plugin be cancelled?
1839
     *
1840
     * Subplugins can be cancelled only via their parent plugin, not separately
1841
     * (they are considered as implicit requirements if distributed together
1842
     * with the main package).
1843
     *
1844
     * @param \core\plugininfo\base $plugin
1845
     * @return bool
1846
     */
1847
    public function can_cancel_plugin_installation(\core\plugininfo\base $plugin) {
1848
        global $CFG;
1849
 
1850
        if (!empty($CFG->disableupdateautodeploy)) {
1851
            return false;
1852
        }
1853
 
1854
        if (
1855
            empty($plugin)
1856
            || $plugin->is_standard()
1857
            || $plugin->is_subplugin()
1858
            || !$this->is_plugin_folder_removable($plugin->component)
1859
        ) {
1860
            return false;
1861
        }
1862
 
1863
        if ($plugin->get_status() === self::PLUGIN_STATUS_NEW) {
1864
            return true;
1865
        }
1866
 
1867
        return false;
1868
    }
1869
 
1870
    /**
1871
     * Can the upgrade of the existing plugin be cancelled?
1872
     *
1873
     * Subplugins can be cancelled only via their parent plugin, not separately
1874
     * (they are considered as implicit requirements if distributed together
1875
     * with the main package).
1876
     *
1877
     * @param \core\plugininfo\base $plugin
1878
     * @return bool
1879
     */
1880
    public function can_cancel_plugin_upgrade(\core\plugininfo\base $plugin) {
1881
        global $CFG;
1882
 
1883
        if (!empty($CFG->disableupdateautodeploy)) {
1884
            // Cancelling the plugin upgrade is actually installation of the
1885
            // previously archived version.
1886
            return false;
1887
        }
1888
 
1889
        if (
1890
            empty($plugin)
1891
            || $plugin->is_standard()
1892
            || $plugin->is_subplugin()
1893
            || !$this->is_plugin_folder_removable($plugin->component)
1894
        ) {
1895
            return false;
1896
        }
1897
 
1898
        if ($plugin->get_status() === self::PLUGIN_STATUS_UPGRADE) {
1899
            if ($this->get_code_manager()->get_archived_plugin_version($plugin->component, $plugin->versiondb)) {
1900
                return true;
1901
            }
1902
        }
1903
 
1904
        return false;
1905
    }
1906
 
1907
    /**
1908
     * Removes the plugin code directory if it is not installed yet.
1909
     *
1910
     * This is intended for the plugins check screen to give the admin a chance
1911
     * to cancel the installation of just unzipped plugin before the database
1912
     * upgrade happens.
1913
     *
1914
     * @param string $component
1915
     */
1916
    public function cancel_plugin_installation($component) {
1917
        global $CFG;
1918
 
1919
        if (!empty($CFG->disableupdateautodeploy)) {
1920
            return false;
1921
        }
1922
 
1923
        $plugin = $this->get_plugin_info($component);
1924
 
1925
        if ($this->can_cancel_plugin_installation($plugin)) {
1926
            $this->remove_plugin_folder($plugin);
1927
        }
1928
 
1929
        return false;
1930
    }
1931
 
1932
    /**
1933
     * Returns plugins, the installation of which can be cancelled.
1934
     *
1935
     * @return array [(string)component] => (\core\plugininfo\base)plugin
1936
     */
1937
    public function list_cancellable_installations() {
1938
        global $CFG;
1939
 
1940
        if (!empty($CFG->disableupdateautodeploy)) {
1941
            return [];
1942
        }
1943
 
1944
        $cancellable = [];
1945
        foreach ($this->get_plugins() as $type => $plugins) {
1946
            foreach ($plugins as $plugin) {
1947
                if ($this->can_cancel_plugin_installation($plugin)) {
1948
                    $cancellable[$plugin->component] = $plugin;
1949
                }
1950
            }
1951
        }
1952
 
1953
        return $cancellable;
1954
    }
1955
 
1956
    /**
1957
     * Archive the current on-disk plugin code.
1958
     *
1959
     * @param \core\plugininfo\base $plugin
1960
     * @return bool
1961
     */
1962
    public function archive_plugin_version(\core\plugininfo\base $plugin) {
1963
        return $this->get_code_manager()->archive_plugin_version($plugin->rootdir, $plugin->component, $plugin->versiondisk);
1964
    }
1965
 
1966
    /**
1967
     * Returns list of all archives that can be installed to cancel the plugin upgrade.
1968
     *
1969
     * @return array [(string)component] => {(string)->component, (string)->zipfilepath}
1970
     */
1971
    public function list_restorable_archives() {
1972
        global $CFG;
1973
 
1974
        if (!empty($CFG->disableupdateautodeploy)) {
1975
            return false;
1976
        }
1977
 
1978
        $codeman = $this->get_code_manager();
1979
        $restorable = [];
1980
        foreach ($this->get_plugins() as $type => $plugins) {
1981
            foreach ($plugins as $plugin) {
1982
                if ($this->can_cancel_plugin_upgrade($plugin)) {
1983
                    $restorable[$plugin->component] = (object)[
1984
                        'component' => $plugin->component,
1985
                        'zipfilepath' => $codeman->get_archived_plugin_version($plugin->component, $plugin->versiondb),
1986
                    ];
1987
                }
1988
            }
1989
        }
1990
 
1991
        return $restorable;
1992
    }
1993
 
1994
    /**
1995
     * Reorders plugin types into a sequence to be displayed
1996
     *
1997
     * For technical reasons, plugin types returned by {@link core_component::get_plugin_types()} are
1998
     * in a certain order that does not need to fit the expected order for the display.
1999
     * Particularly, activity modules should be displayed first as they represent the
2000
     * real heart of Moodle. They should be followed by other plugin types that are
2001
     * used to build the courses (as that is what one expects from LMS). After that,
2002
     * other supportive plugin types follow.
2003
     *
2004
     * @param array $types associative array
2005
     * @return array same array with altered order of items
2006
     */
2007
    protected function reorder_plugin_types(array $types) {
2008
        $fix = ['mod' => $types['mod']];
2009
        foreach (core_component::get_plugin_list('mod') as $plugin => $fulldir) {
2010
            if (!$subtypes = core_component::get_subplugins('mod_' . $plugin)) {
2011
                continue;
2012
            }
2013
            foreach ($subtypes as $subtype => $ignored) {
2014
                $fix[$subtype] = $types[$subtype];
2015
            }
2016
        }
2017
 
2018
        $fix['mod']        = $types['mod'];
2019
        $fix['block']      = $types['block'];
2020
        $fix['qtype']      = $types['qtype'];
2021
        $fix['qbank']      = $types['qbank'];
2022
        $fix['qbehaviour'] = $types['qbehaviour'];
2023
        $fix['qformat']    = $types['qformat'];
2024
        $fix['filter']     = $types['filter'];
2025
 
2026
        $fix['editor']     = $types['editor'];
2027
        foreach (core_component::get_plugin_list('editor') as $plugin => $fulldir) {
2028
            if (!$subtypes = core_component::get_subplugins('editor_' . $plugin)) {
2029
                continue;
2030
            }
2031
            foreach ($subtypes as $subtype => $ignored) {
2032
                $fix[$subtype] = $types[$subtype];
2033
            }
2034
        }
2035
 
2036
        $fix['enrol'] = $types['enrol'];
2037
        $fix['auth']  = $types['auth'];
2038
        $fix['tool']  = $types['tool'];
2039
        foreach (core_component::get_plugin_list('tool') as $plugin => $fulldir) {
2040
            if (!$subtypes = core_component::get_subplugins('tool_' . $plugin)) {
2041
                continue;
2042
            }
2043
            foreach ($subtypes as $subtype => $ignored) {
2044
                $fix[$subtype] = $types[$subtype];
2045
            }
2046
        }
2047
 
2048
        foreach ($types as $type => $path) {
2049
            if (!isset($fix[$type])) {
2050
                $fix[$type] = $path;
2051
            }
2052
        }
2053
        return $fix;
2054
    }
2055
 
2056
    /**
2057
     * Check if the given directory can be removed by the web server process.
2058
     *
2059
     * This recursively checks that the given directory and all its contents
2060
     * it writable.
2061
     *
2062
     * @param string $fullpath
2063
     * @return boolean
2064
     */
2065
    public function is_directory_removable($fullpath) {
2066
 
2067
        if (!is_writable($fullpath)) {
2068
            return false;
2069
        }
2070
 
2071
        if (is_dir($fullpath)) {
2072
            $handle = opendir($fullpath);
2073
        } else {
2074
            return false;
2075
        }
2076
 
2077
        $result = true;
2078
 
2079
        while ($filename = readdir($handle)) {
2080
            if ($filename === '.' || $filename === '..') {
2081
                continue;
2082
            }
2083
 
2084
            $subfilepath = $fullpath . '/' . $filename;
2085
 
2086
            if (is_dir($subfilepath)) {
2087
                $result = $result && $this->is_directory_removable($subfilepath);
2088
            } else {
2089
                $result = $result && is_writable($subfilepath);
2090
            }
2091
        }
2092
 
2093
        closedir($handle);
2094
 
2095
        return $result;
2096
    }
2097
 
2098
    /**
2099
     * Helper method that implements common uninstall prerequisites
2100
     *
2101
     * @param \core\plugininfo\base $pluginfo
2102
     * @return bool
2103
     */
2104
    protected function common_uninstall_check(\core\plugininfo\base $pluginfo) {
2105
        global $CFG;
2106
        // Check if uninstall is allowed from the GUI.
2107
        if (!empty($CFG->uninstallclionly) && (!CLI_SCRIPT)) {
2108
            return false;
2109
        }
2110
 
2111
        if (!$pluginfo->is_uninstall_allowed()) {
2112
            // The plugin's plugininfo class declares it should not be uninstalled.
2113
            return false;
2114
        }
2115
 
2116
        if ($pluginfo->get_status() === static::PLUGIN_STATUS_NEW) {
2117
            // The plugin is not installed. It should be either installed or removed from the disk.
2118
            // Relying on this temporary state may be tricky.
2119
            return false;
2120
        }
2121
 
2122
        if (method_exists($pluginfo, 'get_uninstall_url') && is_null($pluginfo->get_uninstall_url())) {
2123
            // Backwards compatibility.
2124
            debugging(
2125
                '\core\plugininfo\base subclasses should use is_uninstall_allowed() ' .
2126
                    'instead of returning null in get_uninstall_url()',
2127
                DEBUG_DEVELOPER
2128
            );
2129
            return false;
2130
        }
2131
 
2132
        return true;
2133
    }
2134
 
2135
    /**
2136
     * Returns a code_manager instance to be used for the plugins code operations.
2137
     *
2138
     * @return \core\update\code_manager
2139
     */
2140
    protected function get_code_manager() {
2141
 
2142
        if ($this->codemanager === null) {
2143
            $this->codemanager = new \core\update\code_manager();
2144
        }
2145
 
2146
        return $this->codemanager;
2147
    }
2148
 
2149
    /**
2150
     * Returns a client for https://download.moodle.org/api/
2151
     *
2152
     * @return \core\update\api
2153
     */
2154
    protected function get_update_api_client() {
2155
 
2156
        if ($this->updateapiclient === null) {
2157
            $this->updateapiclient = \core\update\api::client();
2158
        }
2159
 
2160
        return $this->updateapiclient;
2161
    }
2162
}
2163
 
2164
class_alias(plugin_manager::class, 'core_plugin_manager');