plugin_manager.php 86.2 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

/**
 * Defines classes used for plugins management
 *
 * This library provides a unified interface to various plugin types in
 * Moodle. It is mainly used by the plugins management admin page and the
 * plugins check page during the upgrade.
 *
 * @package    core
 * @copyright  2011 David Mudrak <david@moodle.com>
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */

defined('MOODLE_INTERNAL') || die();

/**
 * Singleton class providing general plugins management functionality.
 */
class core_plugin_manager {

    /** the plugin is shipped with standard Moodle distribution */
    const PLUGIN_SOURCE_STANDARD    = 'std';
    /** the plugin is added extension */
    const PLUGIN_SOURCE_EXTENSION   = 'ext';

    /** the plugin uses neither database nor capabilities, no versions */
    const PLUGIN_STATUS_NODB        = 'nodb';
    /** the plugin is up-to-date */
    const PLUGIN_STATUS_UPTODATE    = 'uptodate';
    /** the plugin is about to be installed */
    const PLUGIN_STATUS_NEW         = 'new';
    /** the plugin is about to be upgraded */
    const PLUGIN_STATUS_UPGRADE     = 'upgrade';
    /** the standard plugin is about to be deleted */
    const PLUGIN_STATUS_DELETE     = 'delete';
    /** the version at the disk is lower than the one already installed */
    const PLUGIN_STATUS_DOWNGRADE   = 'downgrade';
    /** the plugin is installed but missing from disk */
    const PLUGIN_STATUS_MISSING     = 'missing';

56
57
58
59
60
61
    /** the given requirement/dependency is fulfilled */
    const REQUIREMENT_STATUS_OK = 'ok';
    /** the plugin requires higher core/other plugin version than is currently installed */
    const REQUIREMENT_STATUS_OUTDATED = 'outdated';
    /** the required dependency is not installed */
    const REQUIREMENT_STATUS_MISSING = 'missing';
62
63
    /** the current Moodle version is too high for plugin. */
    const REQUIREMENT_STATUS_NEWER = 'newer';
64

65
66
67
68
69
    /** the required dependency is available in the plugins directory */
    const REQUIREMENT_AVAILABLE = 'available';
    /** the required dependency is available in the plugins directory */
    const REQUIREMENT_UNAVAILABLE = 'unavailable';

70
71
72
73
74
75
76
    /** the moodle version is explicitly supported */
    const VERSION_SUPPORTED = 'supported';
    /** the moodle version is not explicitly supported */
    const VERSION_NOT_SUPPORTED = 'notsupported';
    /** the plugin does not specify supports */
    const VERSION_NO_SUPPORTS = 'nosupports';

77
78
79
80
81
82
    /** @var core_plugin_manager holds the singleton instance */
    protected static $singletoninstance;
    /** @var array of raw plugins information */
    protected $pluginsinfo = null;
    /** @var array of raw subplugins information */
    protected $subpluginsinfo = null;
83
84
85
86
    /** @var array cache information about availability in the plugins directory if requesting "at least" version */
    protected $remotepluginsinfoatleast = null;
    /** @var array cache information about availability in the plugins directory if requesting exact version */
    protected $remotepluginsinfoexact = null;
87
88
89
90
91
92
93
94
    /** @var array list of installed plugins $name=>$version */
    protected $installedplugins = null;
    /** @var array list of all enabled plugins $name=>$name */
    protected $enabledplugins = null;
    /** @var array list of all enabled plugins $name=>$diskversion */
    protected $presentplugins = null;
    /** @var array reordered list of plugin types */
    protected $plugintypes = null;
95
96
    /** @var \core\update\code_manager code manager to use for plugins code operations */
    protected $codemanager = null;
97
98
    /** @var \core\update\api client instance to use for accessing download.moodle.org/api/ */
    protected $updateapiclient = null;
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117

    /**
     * Direct initiation not allowed, use the factory method {@link self::instance()}
     */
    protected function __construct() {
    }

    /**
     * Sorry, this is singleton
     */
    protected function __clone() {
    }

    /**
     * Factory method for this class
     *
     * @return core_plugin_manager the singleton instance
     */
    public static function instance() {
118
119
        if (is_null(static::$singletoninstance)) {
            static::$singletoninstance = new static();
120
        }
121
        return static::$singletoninstance;
122
123
124
125
126
127
128
129
    }

    /**
     * Reset all caches.
     * @param bool $phpunitreset
     */
    public static function reset_caches($phpunitreset = false) {
        if ($phpunitreset) {
130
            static::$singletoninstance = null;
131
        } else {
132
133
134
            if (static::$singletoninstance) {
                static::$singletoninstance->pluginsinfo = null;
                static::$singletoninstance->subpluginsinfo = null;
135
136
                static::$singletoninstance->remotepluginsinfoatleast = null;
                static::$singletoninstance->remotepluginsinfoexact = null;
137
138
139
140
                static::$singletoninstance->installedplugins = null;
                static::$singletoninstance->enabledplugins = null;
                static::$singletoninstance->presentplugins = null;
                static::$singletoninstance->plugintypes = null;
141
142
                static::$singletoninstance->codemanager = null;
                static::$singletoninstance->updateapiclient = null;
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
            }
        }
        $cache = cache::make('core', 'plugin_manager');
        $cache->purge();
    }

    /**
     * Returns the result of {@link core_component::get_plugin_types()} ordered for humans
     *
     * @see self::reorder_plugin_types()
     * @return array (string)name => (string)location
     */
    public function get_plugin_types() {
        if (func_num_args() > 0) {
            if (!func_get_arg(0)) {
158
                throw new coding_exception('core_plugin_manager->get_plugin_types() does not support relative paths.');
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
            }
        }
        if ($this->plugintypes) {
            return $this->plugintypes;
        }

        $this->plugintypes = $this->reorder_plugin_types(core_component::get_plugin_types());
        return $this->plugintypes;
    }

    /**
     * Load list of installed plugins,
     * always call before using $this->installedplugins.
     *
     * This method is caching results for all plugins.
     */
    protected function load_installed_plugins() {
        global $DB, $CFG;

        if ($this->installedplugins) {
            return;
        }

        if (empty($CFG->version)) {
            // Nothing installed yet.
            $this->installedplugins = array();
            return;
        }

        $cache = cache::make('core', 'plugin_manager');
        $installed = $cache->get('installed');

        if (is_array($installed)) {
            $this->installedplugins = $installed;
            return;
        }

        $this->installedplugins = array();

        $versions = $DB->get_records('config_plugins', array('name'=>'version'));
        foreach ($versions as $version) {
            $parts = explode('_', $version->plugin, 2);
            if (!isset($parts[1])) {
                // Invalid component, there must be at least one "_".
                continue;
            }
            // Do not verify here if plugin type and name are valid.
            $this->installedplugins[$parts[0]][$parts[1]] = $version->value;
        }

        foreach ($this->installedplugins as $key => $value) {
            ksort($this->installedplugins[$key]);
        }

        $cache->set('installed', $this->installedplugins);
    }

    /**
     * Return list of installed plugins of given type.
     * @param string $type
     * @return array $name=>$version
     */
    public function get_installed_plugins($type) {
        $this->load_installed_plugins();
        if (isset($this->installedplugins[$type])) {
            return $this->installedplugins[$type];
        }
        return array();
    }

    /**
     * Load list of all enabled plugins,
     * call before using $this->enabledplugins.
     *
     * This method is caching results from individual plugin info classes.
     */
    protected function load_enabled_plugins() {
        global $CFG;

        if ($this->enabledplugins) {
            return;
        }

        if (empty($CFG->version)) {
            $this->enabledplugins = array();
            return;
        }

        $cache = cache::make('core', 'plugin_manager');
        $enabled = $cache->get('enabled');

        if (is_array($enabled)) {
            $this->enabledplugins = $enabled;
            return;
        }

        $this->enabledplugins = array();

        require_once($CFG->libdir.'/adminlib.php');

        $plugintypes = core_component::get_plugin_types();
        foreach ($plugintypes as $plugintype => $fulldir) {
261
            $plugininfoclass = static::resolve_plugininfo_class($plugintype);
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
            if (class_exists($plugininfoclass)) {
                $enabled = $plugininfoclass::get_enabled_plugins();
                if (!is_array($enabled)) {
                    continue;
                }
                $this->enabledplugins[$plugintype] = $enabled;
            }
        }

        $cache->set('enabled', $this->enabledplugins);
    }

    /**
     * Get list of enabled plugins of given type,
     * the result may contain missing plugins.
     *
     * @param string $type
     * @return array|null  list of enabled plugins of this type, null if unknown
     */
    public function get_enabled_plugins($type) {
        $this->load_enabled_plugins();
        if (isset($this->enabledplugins[$type])) {
            return $this->enabledplugins[$type];
        }
        return null;
    }

    /**
     * Load list of all present plugins - call before using $this->presentplugins.
     */
    protected function load_present_plugins() {
        if ($this->presentplugins) {
            return;
        }

        $cache = cache::make('core', 'plugin_manager');
        $present = $cache->get('present');

        if (is_array($present)) {
            $this->presentplugins = $present;
            return;
        }

        $this->presentplugins = array();

        $plugintypes = core_component::get_plugin_types();
        foreach ($plugintypes as $type => $typedir) {
            $plugs = core_component::get_plugin_list($type);
            foreach ($plugs as $plug => $fullplug) {
311
                $module = new stdClass();
312
313
                $plugin = new stdClass();
                $plugin->version = null;
314
                include($fullplug.'/version.php');
315
316

                // Check if the legacy $module syntax is still used.
317
                if (!is_object($module) or (count((array)$module) > 0)) {
318
319
320
321
                    debugging('Unsupported $module syntax detected in version.php of the '.$type.'_'.$plug.' plugin.');
                    $skipcache = true;
                }

322
323
324
325
326
327
                // Check if the component is properly declared.
                if (empty($plugin->component) or ($plugin->component !== $type.'_'.$plug)) {
                    debugging('Plugin '.$type.'_'.$plug.' does not declare valid $plugin->component in its version.php.');
                    $skipcache = true;
                }

328
329
330
331
                $this->presentplugins[$type][$plug] = $plugin;
            }
        }

332
333
334
        if (empty($skipcache)) {
            $cache->set('present', $this->presentplugins);
        }
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
    }

    /**
     * Get list of present plugins of given type.
     *
     * @param string $type
     * @return array|null  list of presnet plugins $name=>$diskversion, null if unknown
     */
    public function get_present_plugins($type) {
        $this->load_present_plugins();
        if (isset($this->presentplugins[$type])) {
            return $this->presentplugins[$type];
        }
        return null;
    }

    /**
     * Returns a tree of known plugins and information about them
     *
     * @return array 2D array. The first keys are plugin type names (e.g. qtype);
     *      the second keys are the plugin local name (e.g. multichoice); and
     *      the values are the corresponding objects extending {@link \core\plugininfo\base}
     */
    public function get_plugins() {
        $this->init_pluginsinfo_property();

        // Make sure all types are initialised.
        foreach ($this->pluginsinfo as $plugintype => $list) {
            if ($list === null) {
                $this->get_plugins_of_type($plugintype);
            }
        }

        return $this->pluginsinfo;
    }

    /**
     * Returns list of known plugins of the given type.
     *
     * This method returns the subset of the tree returned by {@link self::get_plugins()}.
     * If the given type is not known, empty array is returned.
     *
     * @param string $type plugin type, e.g. 'mod' or 'workshopallocation'
     * @return \core\plugininfo\base[] (string)plugin name (e.g. 'workshop') => corresponding subclass of {@link \core\plugininfo\base}
     */
    public function get_plugins_of_type($type) {
        global $CFG;

        $this->init_pluginsinfo_property();

        if (!array_key_exists($type, $this->pluginsinfo)) {
            return array();
        }

        if (is_array($this->pluginsinfo[$type])) {
            return $this->pluginsinfo[$type];
        }

        $types = core_component::get_plugin_types();

395
396
        if (!isset($types[$type])) {
            // Orphaned subplugins!
397
            $plugintypeclass = static::resolve_plugininfo_class($type);
398
            $this->pluginsinfo[$type] = $plugintypeclass::get_plugins($type, null, $plugintypeclass, $this);
399
400
401
            return $this->pluginsinfo[$type];
        }

402
        /** @var \core\plugininfo\base $plugintypeclass */
403
        $plugintypeclass = static::resolve_plugininfo_class($type);
404
        $plugins = $plugintypeclass::get_plugins($type, $types[$type], $plugintypeclass, $this);
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
        $this->pluginsinfo[$type] = $plugins;

        return $this->pluginsinfo[$type];
    }

    /**
     * Init placeholder array for plugin infos.
     */
    protected function init_pluginsinfo_property() {
        if (is_array($this->pluginsinfo)) {
            return;
        }
        $this->pluginsinfo = array();

        $plugintypes = $this->get_plugin_types();

        foreach ($plugintypes as $plugintype => $plugintyperootdir) {
            $this->pluginsinfo[$plugintype] = null;
        }
424
425
426
427
428
429
430
431

        // Add orphaned subplugin types.
        $this->load_installed_plugins();
        foreach ($this->installedplugins as $plugintype => $unused) {
            if (!isset($plugintypes[$plugintype])) {
                $this->pluginsinfo[$plugintype] = null;
            }
        }
432
433
434
435
436
437
438
439
440
    }

    /**
     * Find the plugin info class for given type.
     *
     * @param string $type
     * @return string name of pluginfo class for give plugin type
     */
    public static function resolve_plugininfo_class($type) {
441
442
443
444
445
        $plugintypes = core_component::get_plugin_types();
        if (!isset($plugintypes[$type])) {
            return '\core\plugininfo\orphaned';
        }

446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
        $parent = core_component::get_subtype_parent($type);

        if ($parent) {
            $class = '\\'.$parent.'\plugininfo\\' . $type;
            if (class_exists($class)) {
                $plugintypeclass = $class;
            } else {
                if ($dir = core_component::get_component_directory($parent)) {
                    // BC only - use namespace instead!
                    if (file_exists("$dir/adminlib.php")) {
                        global $CFG;
                        include_once("$dir/adminlib.php");
                    }
                    if (class_exists('plugininfo_' . $type)) {
                        $plugintypeclass = 'plugininfo_' . $type;
                        debugging('Class "'.$plugintypeclass.'" is deprecated, migrate to "'.$class.'"', DEBUG_DEVELOPER);
                    } else {
                        debugging('Subplugin type "'.$type.'" should define class "'.$class.'"', DEBUG_DEVELOPER);
                        $plugintypeclass = '\core\plugininfo\general';
                    }
                } else {
                    $plugintypeclass = '\core\plugininfo\general';
                }
            }
        } else {
            $class = '\core\plugininfo\\' . $type;
            if (class_exists($class)) {
                $plugintypeclass = $class;
            } else {
                debugging('All standard types including "'.$type.'" should have plugininfo class!', DEBUG_DEVELOPER);
                $plugintypeclass = '\core\plugininfo\general';
            }
        }

        if (!in_array('core\plugininfo\base', class_parents($plugintypeclass))) {
            throw new coding_exception('Class ' . $plugintypeclass . ' must extend \core\plugininfo\base');
        }

        return $plugintypeclass;
    }

    /**
     * Returns list of all known subplugins of the given plugin.
     *
     * For plugins that do not provide subplugins (i.e. there is no support for it),
     * empty array is returned.
     *
     * @param string $component full component name, e.g. 'mod_workshop'
     * @return array (string) component name (e.g. 'workshopallocation_random') => subclass of {@link \core\plugininfo\base}
     */
    public function get_subplugins_of_plugin($component) {

        $pluginfo = $this->get_plugin_info($component);

        if (is_null($pluginfo)) {
            return array();
        }

        $subplugins = $this->get_subplugins();

        if (!isset($subplugins[$pluginfo->component])) {
            return array();
        }

        $list = array();

        foreach ($subplugins[$pluginfo->component] as $subdata) {
            foreach ($this->get_plugins_of_type($subdata->type) as $subpluginfo) {
                $list[$subpluginfo->component] = $subpluginfo;
            }
        }

        return $list;
    }

    /**
     * Returns list of plugins that define their subplugins and the information
523
     * about them from the db/subplugins.json file.
524
525
     *
     * @return array with keys like 'mod_quiz', and values the data from the
526
     *      corresponding db/subplugins.json file.
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
     */
    public function get_subplugins() {

        if (is_array($this->subpluginsinfo)) {
            return $this->subpluginsinfo;
        }

        $plugintypes = core_component::get_plugin_types();

        $this->subpluginsinfo = array();
        foreach (core_component::get_plugin_types_with_subplugins() as $type => $ignored) {
            foreach (core_component::get_plugin_list($type) as $plugin => $componentdir) {
                $component = $type.'_'.$plugin;
                $subplugins = core_component::get_subplugins($component);
                if (!$subplugins) {
                    continue;
                }
                $this->subpluginsinfo[$component] = array();
                foreach ($subplugins as $subplugintype => $ignored) {
                    $subplugin = new stdClass();
                    $subplugin->type = $subplugintype;
                    $subplugin->typerootdir = $plugintypes[$subplugintype];
                    $this->subpluginsinfo[$component][$subplugintype] = $subplugin;
                }
            }
        }
        return $this->subpluginsinfo;
    }

    /**
     * Returns the name of the plugin that defines the given subplugin type
     *
     * If the given subplugin type is not actually a subplugin, returns false.
     *
     * @param string $subplugintype the name of subplugin type, eg. workshopform or quiz
     * @return false|string the name of the parent plugin, eg. mod_workshop
     */
    public function get_parent_of_subplugin($subplugintype) {
        $parent = core_component::get_subtype_parent($subplugintype);
        if (!$parent) {
            return false;
        }
        return $parent;
    }

    /**
     * Returns a localized name of a given plugin
     *
     * @param string $component name of the plugin, eg mod_workshop or auth_ldap
     * @return string
     */
    public function plugin_name($component) {

        $pluginfo = $this->get_plugin_info($component);

        if (is_null($pluginfo)) {
            throw new moodle_exception('err_unknown_plugin', 'core_plugin', '', array('plugin' => $component));
        }

        return $pluginfo->displayname;
    }

    /**
     * Returns a localized name of a plugin typed in singular form
     *
     * Most plugin types define their names in core_plugin lang file. In case of subplugins,
     * we try to ask the parent plugin for the name. In the worst case, we will return
     * the value of the passed $type parameter.
     *
     * @param string $type the type of the plugin, e.g. mod or workshopform
     * @return string
     */
    public function plugintype_name($type) {

        if (get_string_manager()->string_exists('type_' . $type, 'core_plugin')) {
            // For most plugin types, their names are defined in core_plugin lang file.
            return get_string('type_' . $type, 'core_plugin');

        } else if ($parent = $this->get_parent_of_subplugin($type)) {
            // If this is a subplugin, try to ask the parent plugin for the name.
            if (get_string_manager()->string_exists('subplugintype_' . $type, $parent)) {
                return $this->plugin_name($parent) . ' / ' . get_string('subplugintype_' . $type, $parent);
            } else {
                return $this->plugin_name($parent) . ' / ' . $type;
            }

        } else {
            return $type;
        }
    }

    /**
     * Returns a localized name of a plugin type in plural form
     *
     * Most plugin types define their names in core_plugin lang file. In case of subplugins,
     * we try to ask the parent plugin for the name. In the worst case, we will return
     * the value of the passed $type parameter.
     *
     * @param string $type the type of the plugin, e.g. mod or workshopform
     * @return string
     */
    public function plugintype_name_plural($type) {

        if (get_string_manager()->string_exists('type_' . $type . '_plural', 'core_plugin')) {
            // For most plugin types, their names are defined in core_plugin lang file.
            return get_string('type_' . $type . '_plural', 'core_plugin');

        } else if ($parent = $this->get_parent_of_subplugin($type)) {
            // If this is a subplugin, try to ask the parent plugin for the name.
            if (get_string_manager()->string_exists('subplugintype_' . $type . '_plural', $parent)) {
                return $this->plugin_name($parent) . ' / ' . get_string('subplugintype_' . $type . '_plural', $parent);
            } else {
                return $this->plugin_name($parent) . ' / ' . $type;
            }

        } else {
            return $type;
        }
    }

    /**
     * Returns information about the known plugin, or null
     *
     * @param string $component frankenstyle component name.
     * @return \core\plugininfo\base|null the corresponding plugin information.
     */
    public function get_plugin_info($component) {
        list($type, $name) = core_component::normalize_component($component);
655
656
657
        $plugins = $this->get_plugins_of_type($type);
        if (isset($plugins[$name])) {
            return $plugins[$name];
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
        } else {
            return null;
        }
    }

    /**
     * Check to see if the current version of the plugin seems to be a checkout of an external repository.
     *
     * @param string $component frankenstyle component name
     * @return false|string
     */
    public function plugin_external_source($component) {

        $plugininfo = $this->get_plugin_info($component);

        if (is_null($plugininfo)) {
            return false;
        }

        $pluginroot = $plugininfo->rootdir;

        if (is_dir($pluginroot.'/.git')) {
            return 'git';
        }

683
684
685
686
        if (is_file($pluginroot.'/.git')) {
            return 'git-submodule';
        }

687
688
689
690
691
692
693
694
        if (is_dir($pluginroot.'/CVS')) {
            return 'cvs';
        }

        if (is_dir($pluginroot.'/.svn')) {
            return 'svn';
        }

695
696
697
698
        if (is_dir($pluginroot.'/.hg')) {
            return 'mercurial';
        }

699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
        return false;
    }

    /**
     * Get a list of any other plugins that require this one.
     * @param string $component frankenstyle component name.
     * @return array of frankensyle component names that require this one.
     */
    public function other_plugins_that_require($component) {
        $others = array();
        foreach ($this->get_plugins() as $type => $plugins) {
            foreach ($plugins as $plugin) {
                $required = $plugin->get_other_required_plugins();
                if (isset($required[$component])) {
                    $others[] = $plugin->component;
                }
            }
        }
        return $others;
    }

    /**
     * Check a dependencies list against the list of installed plugins.
     * @param array $dependencies compenent name to required version or ANY_VERSION.
     * @return bool true if all the dependencies are satisfied.
     */
    public function are_dependencies_satisfied($dependencies) {
        foreach ($dependencies as $component => $requiredversion) {
            $otherplugin = $this->get_plugin_info($component);
            if (is_null($otherplugin)) {
                return false;
            }

            if ($requiredversion != ANY_VERSION and $otherplugin->versiondisk < $requiredversion) {
                return false;
            }
        }

        return true;
    }

    /**
     * Checks all dependencies for all installed plugins
     *
     * This is used by install and upgrade. The array passed by reference as the second
     * argument is populated with the list of plugins that have failed dependencies (note that
     * a single plugin can appear multiple times in the $failedplugins).
     *
     * @param int $moodleversion the version from version.php.
     * @param array $failedplugins to return the list of plugins with non-satisfied dependencies
749
     * @param int $branch the current moodle branch, null if not provided
750
751
     * @return bool true if all the dependencies are satisfied for all plugins.
     */
752
753
754
    public function all_plugins_ok($moodleversion, &$failedplugins = array(), $branch = null) {
        global $CFG;
        if (empty($branch)) {
755
            $branch = $CFG->branch ?? '';
756
757
758
759
760
761
762
            if (empty($branch)) {
                // During initial install there is no branch set.
                require($CFG->dirroot . '/version.php');
                $branch = (int)$branch;
                // Force CFG->branch to int value during install.
                $CFG->branch = $branch;
            }
763
        }
764
765
766
767
768
769
770
771
772
773
774
775
776
        $return = true;
        foreach ($this->get_plugins() as $type => $plugins) {
            foreach ($plugins as $plugin) {

                if (!$plugin->is_core_dependency_satisfied($moodleversion)) {
                    $return = false;
                    $failedplugins[] = $plugin->component;
                }

                if (!$this->are_dependencies_satisfied($plugin->get_other_required_plugins())) {
                    $return = false;
                    $failedplugins[] = $plugin->component;
                }
777
778
779
780
781

                if (!$plugin->is_core_compatible_satisfied($branch)) {
                    $return = false;
                    $failedplugins[] = $plugin->component;
                }
782
783
784
785
786
787
            }
        }

        return $return;
    }

788
789
790
791
792
793
794
795
796
797
    /**
     * Resolve requirements and dependencies of a plugin.
     *
     * Returns an array of objects describing the requirement/dependency,
     * indexed by the frankenstyle name of the component. The returned array
     * can be empty. The objects in the array have following properties:
     *
     *  ->(numeric)hasver
     *  ->(numeric)reqver
     *  ->(string)status
798
     *  ->(string)availability
799
800
801
802
803
804
805
806
807
     *
     * @param \core\plugininfo\base $plugin the plugin we are checking
     * @param null|string|int|double $moodleversion explicit moodle core version to check against, defaults to $CFG->version
     * @param null|string|int $moodlebranch explicit moodle core branch to check against, defaults to $CFG->branch
     * @return array of objects
     */
    public function resolve_requirements(\core\plugininfo\base $plugin, $moodleversion=null, $moodlebranch=null) {
        global $CFG;

808
809
810
811
812
        if ($plugin->versiondisk === null) {
            // Missing from disk, we have no version.php to read from.
            return array();
        }

813
814
815
816
817
818
819
820
821
        if ($moodleversion === null) {
            $moodleversion = $CFG->version;
        }

        if ($moodlebranch === null) {
            $moodlebranch = $CFG->branch;
        }

        $reqs = array();
822
        $reqcore = $this->resolve_core_requirements($plugin, $moodleversion, $moodlebranch);
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841

        if (!empty($reqcore)) {
            $reqs['core'] = $reqcore;
        }

        foreach ($plugin->get_other_required_plugins() as $reqplug => $reqver) {
            $reqs[$reqplug] = $this->resolve_dependency_requirements($plugin, $reqplug, $reqver, $moodlebranch);
        }

        return $reqs;
    }

    /**
     * Helper method to resolve plugin's requirements on the moodle core.
     *
     * @param \core\plugininfo\base $plugin the plugin we are checking
     * @param string|int|double $moodleversion moodle core branch to check against
     * @return stdObject
     */
842
    protected function resolve_core_requirements(\core\plugininfo\base $plugin, $moodleversion, $moodlebranch) {
843

844
845
846
847
848
849
        $reqs = (object)array(
            'hasver' => null,
            'reqver' => null,
            'status' => null,
            'availability' => null,
        );
850
851
852
853
854
855
856
857
858
859
860
861
862
863
        $reqs->hasver = $moodleversion;

        if (empty($plugin->versionrequires)) {
            $reqs->reqver = ANY_VERSION;
        } else {
            $reqs->reqver = $plugin->versionrequires;
        }

        if ($plugin->is_core_dependency_satisfied($moodleversion)) {
            $reqs->status = self::REQUIREMENT_STATUS_OK;
        } else {
            $reqs->status = self::REQUIREMENT_STATUS_OUTDATED;
        }

864
865
866
867
868
869
870
871
        // Now check if there is an explicit incompatible, supersedes requires.
        if (isset($plugin->pluginincompatible) && $plugin->pluginincompatible != null) {
            if (!$plugin->is_core_compatible_satisfied($moodlebranch)) {

                $reqs->status = self::REQUIREMENT_STATUS_NEWER;
            }
        }

872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
        return $reqs;
    }

    /**
     * Helper method to resolve plugin's dependecies on other plugins.
     *
     * @param \core\plugininfo\base $plugin the plugin we are checking
     * @param string $otherpluginname
     * @param string|int $requiredversion
     * @param string|int $moodlebranch explicit moodle core branch to check against, defaults to $CFG->branch
     * @return stdClass
     */
    protected function resolve_dependency_requirements(\core\plugininfo\base $plugin, $otherpluginname,
            $requiredversion, $moodlebranch) {

887
888
889
890
891
892
893
        $reqs = (object)array(
            'hasver' => null,
            'reqver' => null,
            'status' => null,
            'availability' => null,
        );

894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
        $otherplugin = $this->get_plugin_info($otherpluginname);

        if ($otherplugin !== null) {
            // The required plugin is installed.
            $reqs->hasver = $otherplugin->versiondisk;
            $reqs->reqver = $requiredversion;
            // Check it has sufficient version.
            if ($requiredversion == ANY_VERSION or $otherplugin->versiondisk >= $requiredversion) {
                $reqs->status = self::REQUIREMENT_STATUS_OK;
            } else {
                $reqs->status = self::REQUIREMENT_STATUS_OUTDATED;
            }

        } else {
            // The required plugin is not installed.
            $reqs->hasver = null;
            $reqs->reqver = $requiredversion;
            $reqs->status = self::REQUIREMENT_STATUS_MISSING;
912
913
914
        }

        if ($reqs->status !== self::REQUIREMENT_STATUS_OK) {
915
            if ($this->is_remote_plugin_available($otherpluginname, $requiredversion, false)) {
916
917
918
919
                $reqs->availability = self::REQUIREMENT_AVAILABLE;
            } else {
                $reqs->availability = self::REQUIREMENT_UNAVAILABLE;
            }
920
921
922
923
924
        }

        return $reqs;
    }

925
926
927
928
929
    /**
     * Helper method to determine whether a moodle version is explicitly supported.
     *
     * @param \core\plugininfo\base $plugin the plugin we are checking
     * @param int $branch the moodle branch to check support for
930
     * @return string
931
     */
932
    public function check_explicitly_supported($plugin, $branch) : string {
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
        // Check for correctly formed supported.
        if (isset($plugin->pluginsupported)) {
            // Broken apart for readability.
            $error = false;
            if (!is_array($plugin->pluginsupported)) {
                $error = true;
            }
            if (!is_int($plugin->pluginsupported[0]) || !is_int($plugin->pluginsupported[1])) {
                $error = true;
            }
            if (count($plugin->pluginsupported) != 2) {
                $error = true;
            }
            if ($error) {
                throw new coding_exception(get_string('err_supported_syntax', 'core_plugin'));
            }
        }

        if (isset($plugin->pluginsupported) && $plugin->pluginsupported != null) {
            if ($plugin->pluginsupported[0] <= $branch && $branch <= $plugin->pluginsupported[1]) {
                return self::VERSION_SUPPORTED;
            } else {
                return self::VERSION_NOT_SUPPORTED;
            }
        } else {
            // If supports aren't specified, but incompatible is, return not supported if not incompatible.
            if (!isset($plugin->pluginsupported) && isset($plugin->pluginincompatible) && !empty($plugin->pluginincompatible)) {
                if (!$plugin->is_core_compatible_satisfied($branch)) {
                    return self::VERSION_NOT_SUPPORTED;
                }
            }
            return self::VERSION_NO_SUPPORTS;
        }
    }

968
969
970
    /**
     * Is the given plugin version available in the plugins directory?
     *
971
972
973
974
975
976
     * See {@link self::get_remote_plugin_info()} for the full explanation of how the $version
     * parameter is interpretted.
     *
     * @param string $component plugin frankenstyle name
     * @param string|int $version ANY_VERSION or the version number
     * @param bool $exactmatch false if "given version or higher" is requested
977
978
     * @return boolean
     */
979
    public function is_remote_plugin_available($component, $version, $exactmatch) {
980

981
        $info = $this->get_remote_plugin_info($component, $version, $exactmatch);
982
983
984
985
986
987
988
989
990
991
992
993
994
995

        if (empty($info)) {
            // There is no available plugin of that name.
            return false;
        }

        if (empty($info->version)) {
            // Plugin is known, but no suitable version was found.
            return false;
        }

        return true;
    }

996
    /**
997
     * Can the given plugin version be installed via the admin UI?
998
     *
999
1000
1001
     * This check should be used whenever attempting to install a plugin from
     * the plugins directory (new install, available update, missing dependency).
     *
1002
     * @param string $component
1003
     * @param int $version version number
1004
     * @param string $reason returned code of the reason why it is not
1005
     * @param bool $checkremote check this version availability on moodle server
1006
1007
     * @return boolean
     */
1008
    public function is_remote_plugin_installable($component, $version, &$reason = null, $checkremote = true) {
1009
1010
1011
        global $CFG;

        // Make sure the feature is not disabled.
1012
        if (!empty($CFG->disableupdateautodeploy)) {
1013
            $reason = 'disabled';
1014
1015
1016
            return false;
        }

1017
        // Make sure the version is available.
1018
        if ($checkremote && !$this->is_remote_plugin_available($component, $version, true)) {
1019
            $reason = 'remoteunavailable';
1020
1021
1022
1023
1024
1025
            return false;
        }

        // Make sure the plugin type root directory is writable.
        list($plugintype, $pluginname) = core_component::normalize_component($component);
        if (!$this->is_plugintype_writable($plugintype)) {
1026
            $reason = 'notwritableplugintype';
1027
1028
1029
            return false;
        }

1030
1031
1032
1033
1034
1035
        if (!$checkremote) {
            $remoteversion = $version;
        } else {
            $remoteinfo = $this->get_remote_plugin_info($component, $version, true);
            $remoteversion = $remoteinfo->version->version;
        }
1036
1037
1038
1039
        $localinfo = $this->get_plugin_info($component);

        if ($localinfo) {
            // If the plugin is already present, prevent downgrade.
1040
            if ($localinfo->versiondb > $remoteversion) {
1041
                $reason = 'cannotdowngrade';
1042
1043
1044
1045
                return false;
            }

            // Make sure we have write access to all the existing code.
1046
1047
1048
1049
1050
            if (is_dir($localinfo->rootdir)) {
                if (!$this->is_plugin_folder_removable($component)) {
                    $reason = 'notwritableplugin';
                    return false;
                }
1051
1052
1053
1054
1055
1056
1057
            }
        }

        // Looks like it could work.
        return true;
    }

1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
    /**
     * Given the list of remote plugin infos, return just those installable.
     *
     * This is typically used on lists returned by
     * {@link self::available_updates()} or {@link self::missing_dependencies()}
     * to perform bulk installation of remote plugins.
     *
     * @param array $remoteinfos list of {@link \core\update\remote_info}
     * @return array
     */
    public function filter_installable($remoteinfos) {
1069
        global $CFG;
1070

1071
1072
1073
        if (!empty($CFG->disableupdateautodeploy)) {
            return array();
        }
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
        if (empty($remoteinfos)) {
            return array();
        }
        $installable = array();
        foreach ($remoteinfos as $index => $remoteinfo) {
            if ($this->is_remote_plugin_installable($remoteinfo->component, $remoteinfo->version->version)) {
                $installable[$index] = $remoteinfo;
            }
        }
        return $installable;
    }

1086
1087
1088
    /**
     * Returns information about a plugin in the plugins directory.
     *
1089
1090
1091
1092
1093
1094
     * This is typically used when checking for available dependencies (in
     * which case the $version represents minimal version we need), or
     * when installing an available update or a new plugin from the plugins
     * directory (in which case the $version is exact version we are
     * interested in). The interpretation of the $version is controlled
     * by the $exactmatch argument.
1095
     *
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
     * If a plugin with the given component name is found, data about the
     * plugin are returned as an object. The ->version property of the object
     * contains the information about the particular plugin version that
     * matches best the given critera. The ->version property is false if no
     * suitable version of the plugin was found (yet the plugin itself is
     * known).
     *
     * See {@link \core\update\api::validate_pluginfo_format()} for the
     * returned data structure.
     *
     * @param string $component plugin frankenstyle name
     * @param string|int $version ANY_VERSION or the version number
     * @param bool $exactmatch false if "given version or higher" is requested
1109
     * @return \core\update\remote_info|bool
1110
     */
1111
    public function get_remote_plugin_info($component, $version, $exactmatch) {
1112

1113
1114
        if ($exactmatch and $version == ANY_VERSION) {
            throw new coding_exception('Invalid request for exactly any version, it does not make sense.');
1115
1116
        }

1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
        $client = $this->get_update_api_client();

        if ($exactmatch) {
            // Use client's get_plugin_info() method.
            if (!isset($this->remotepluginsinfoexact[$component][$version])) {
                $this->remotepluginsinfoexact[$component][$version] = $client->get_plugin_info($component, $version);
            }
            return $this->remotepluginsinfoexact[$component][$version];

        } else {
            // Use client's find_plugin() method.
            if (!isset($this->remotepluginsinfoatleast[$component][$version])) {
                $this->remotepluginsinfoatleast[$component][$version] = $client->find_plugin($component, $version);
            }
            return $this->remotepluginsinfoatleast[$component][$version];
        }
1133
1134
1135
    }

    /**
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
     * Obtain the plugin ZIP file from the given URL
     *
     * The caller is supposed to know both downloads URL and the MD5 hash of
     * the ZIP contents in advance, typically by using the API requests against
     * the plugins directory.
     *
     * @param string $url
     * @param string $md5
     * @return string|bool full path to the file, false on error
     */
    public function get_remote_plugin_zip($url, $md5) {
1147
1148
1149
1150
1151
        global $CFG;

        if (!empty($CFG->disableupdateautodeploy)) {
            return false;
        }
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
        return $this->get_code_manager()->get_remote_plugin_zip($url, $md5);
    }

    /**
     * Extracts the saved plugin ZIP file.
     *
     * Returns the list of files found in the ZIP. The format of that list is
     * array of (string)filerelpath => (bool|string) where the array value is
     * either true or a string describing the problematic file.
     *
     * @see zip_packer::extract_to_pathname()
     * @param string $zipfilepath full path to the saved ZIP file
     * @param string $targetdir full path to the directory to extract the ZIP file to
     * @param string $rootdir explicitly rename the root directory of the ZIP into this non-empty value
1166
     * @return array list of extracted files as returned by {@link zip_packer::extract_to_pathname()}
1167
1168
1169
1170
1171
     */
    public function unzip_plugin_file($zipfilepath, $targetdir, $rootdir = '') {
        return $this->get_code_manager()->unzip_plugin_file($zipfilepath, $targetdir, $rootdir);
    }

1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
    /**
     * Detects the plugin's name from its ZIP file.
     *
     * Plugin ZIP packages are expected to contain a single directory and the
     * directory name would become the plugin name once extracted to the Moodle
     * dirroot.
     *
     * @param string $zipfilepath full path to the ZIP files
     * @return string|bool false on error
     */
    public function get_plugin_zip_root_dir($zipfilepath) {
        return $this->get_code_manager()->get_plugin_zip_root_dir($zipfilepath);
    }

1186
1187
    /**
     * Return a list of missing dependencies.
1188
1189
1190
1191
     *
     * This should provide the full list of plugins that should be installed to
     * fulfill the requirements of all plugins, if possible.
     *
1192
     * @param bool $availableonly return only available missing dependencies
1193
     * @return array of \core\update\remote_info|bool indexed by the component name
1194
     */
1195
    public function missing_dependencies($availableonly=false) {
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206

        $dependencies = array();

        foreach ($this->get_plugins() as $plugintype => $pluginfos) {
            foreach ($pluginfos as $pluginname => $pluginfo) {
                foreach ($this->resolve_requirements($pluginfo) as $reqname => $reqinfo) {
                    if ($reqname === 'core') {
                        continue;
                    }
                    if ($reqinfo->status != self::REQUIREMENT_STATUS_OK) {
                        if ($reqinfo->availability == self::REQUIREMENT_AVAILABLE) {
1207
                            $remoteinfo = $this->get_remote_plugin_info($reqname, $reqinfo->reqver, false);
1208
1209
1210
1211

                            if (empty($dependencies[$reqname])) {
                                $dependencies[$reqname] = $remoteinfo;
                            } else {
1212
1213
1214
1215
                                // If resolving requirements has led to two different versions of the same
                                // remote plugin, pick the higher version. This can happen in cases like one
                                // plugin requiring ANY_VERSION and another plugin requiring specific higher
                                // version with lower maturity of a remote plugin.
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
                                if ($remoteinfo->version->version > $dependencies[$reqname]->version->version) {
                                    $dependencies[$reqname] = $remoteinfo;
                                }
                            }

                        } else {
                            if (!isset($dependencies[$reqname])) {
                                // Unable to find a plugin fulfilling the requirements.
                                $dependencies[$reqname] = false;
                            }
                        }
                    }
                }
            }
        }

1232
1233
1234
1235
1236
1237
1238
1239
        if ($availableonly) {
            foreach ($dependencies as $component => $info) {
                if (empty($info) or empty($info->version)) {
                    unset($dependencies[$component]);
                }
            }
        }

1240
1241
1242
        return $dependencies;
    }

1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
    /**
     * Is it possible to uninstall the given plugin?
     *
     * False is returned if the plugininfo subclass declares the uninstall should
     * not be allowed via {@link \core\plugininfo\base::is_uninstall_allowed()} or if the
     * core vetoes it (e.g. becase the plugin or some of its subplugins is required
     * by some other installed plugin).
     *
     * @param string $component full frankenstyle name, e.g. mod_foobar
     * @return bool
     */
    public function can_uninstall_plugin($component) {

        $pluginfo = $this->get_plugin_info($component);

        if (is_null($pluginfo)) {
            return false;
        }

        if (!$this->common_uninstall_check($pluginfo)) {
            return false;
        }

        // Verify only if something else requires the subplugins, do not verify their common_uninstall_check()!
        $subplugins = $this->get_subplugins_of_plugin($pluginfo->component);
        foreach ($subplugins as $subpluginfo) {
            // Check if there are some other plugins requiring this subplugin
            // (but the parent and siblings).
            foreach ($this->other_plugins_that_require($subpluginfo->component) as $requiresme) {
                $ismyparent = ($pluginfo->component === $requiresme);
                $ismysibling = in_array($requiresme, array_keys($subplugins));
                if (!$ismyparent and !$ismysibling) {
                    return false;
                }
            }
        }

        // Check if there are some other plugins requiring this plugin
        // (but its subplugins).
        foreach ($this->other_plugins_that_require($pluginfo->component) as $requiresme) {
            $ismysubplugin = in_array($requiresme, array_keys($subplugins));
            if (!$ismysubplugin) {
                return false;
            }
        }

        return true;
    }

1292
    /**
1293
1294
1295
1296
1297
1298
     * Perform the installation of plugins.
     *
     * If used for installation of remote plugins from the Moodle Plugins
     * directory, the $plugins must be list of {@link \core\update\remote_info}
     * object that represent installable remote plugins. The caller can use
     * {@link self::filter_installable()} to prepare the list.
1299
     *
1300
1301
1302
     * If used for installation of plugins from locally available ZIP files,
     * the $plugins should be list of objects with properties ->component and
     * ->zipfilepath.
1303
     *
1304
1305
1306
1307
     * The method uses {@link mtrace()} to produce direct output and can be
     * used in both web and cli interfaces.
     *
     * @param array $plugins list of plugins
1308
1309
1310
1311
     * @param bool $confirmed should the files be really deployed into the dirroot?
     * @param bool $silent perform without output
     * @return bool true on success
     */
1312
    public function install_plugins(array $plugins, $confirmed, $silent) {
1313
1314
        global $CFG, $OUTPUT;

1315
1316
1317
1318
        if (!empty($CFG->disableupdateautodeploy)) {
            return false;
        }

1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
        if (empty($plugins)) {
            return false;
        }

        $ok = get_string('ok', 'core');

        // Let admins know they can expect more verbose output.
        $silent or $this->mtrace(get_string('packagesdebug', 'core_plugin'), PHP_EOL, DEBUG_NORMAL);

        // Download all ZIP packages if we do not have them yet.
        $zips = array();
        foreach ($plugins as $plugin) {
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
            if ($plugin instanceof \core\update\remote_info) {
                $zips[$plugin->component] = $this->get_remote_plugin_zip($plugin->version->downloadurl,
                    $plugin->version->downloadmd5);
                $silent or $this->mtrace(get_string('packagesdownloading', 'core_plugin', $plugin->component), ' ... ');
                $silent or $this->mtrace(PHP_EOL.' <- '.$plugin->version->downloadurl, '', DEBUG_DEVELOPER);
                $silent or $this->mtrace(PHP_EOL.' -> '.$zips[$plugin->component], ' ... ', DEBUG_DEVELOPER);
                if (!$zips[$plugin->component]) {
                    $silent or $this->mtrace(get_string('error'));
                    return false;
                }
                $silent or $this->mtrace($ok);
            } else {
                if (empty($plugin->zipfilepath)) {
                    throw new coding_exception('Unexpected data structure provided');
                }
                $zips[$plugin->component] = $plugin->zipfilepath;
                $silent or $this->mtrace('ZIP '.$plugin->zipfilepath, PHP_EOL, DEBUG_DEVELOPER);
1348
1349
1350
1351
1352
1353
            }
        }

        // Validate all downloaded packages.
        foreach ($plugins as $plugin) {
            $zipfile = $zips[$plugin->component];
1354
            $silent or $this->mtrace(get_string('packagesvalidating', 'core_plugin', $plugin->component), ' ... ');
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
            list($plugintype, $pluginname) = core_component::normalize_component($plugin->component);
            $tmp = make_request_directory();
            $zipcontents = $this->unzip_plugin_file($zipfile, $tmp, $pluginname);
            if (empty($zipcontents)) {
                $silent or $this->mtrace(get_string('error'));
                $silent or $this->mtrace('Unable to unzip '.$zipfile, PHP_EOL, DEBUG_DEVELOPER);
                return false;
            }

            $validator = \core\update\validator::instance($tmp, $zipcontents);
            $validator->assert_plugin_type($plugintype);
            $validator->assert_moodle_version($CFG->version);
            // TODO Check for missing dependencies during validation.
            $result = $validator->execute();
            if (!$silent) {
                $result ? $this->mtrace($ok) : $this->mtrace(get_string('error'));
                foreach ($validator->get_messages() as $message) {
                    if ($message->level === $validator::INFO) {
                        // Display [OK] validation messages only if debugging mode is DEBUG_NORMAL.
                        $level = DEBUG_NORMAL;
                    } else if ($message->level === $validator::DEBUG) {
                        // Display [Debug] validation messages only if debugging mode is DEBUG_ALL.
                        $level = DEBUG_ALL;
                    } else {
                        // Display [Warning] and [Error] always.
                        $level = null;
                    }
                    if ($message->level === $validator::WARNING and !CLI_SCRIPT) {
                        $this->mtrace('  <strong>['.$validator->message_level_name($message->level).']</strong>', ' ', $level);
                    } else {
                        $this->mtrace('  ['.$validator->message_level_name($message->level).']', ' ', $level);
                    }
                    $this->mtrace($validator->message_code_name($message->msgcode), ' ', $level);
                    $info = $validator->message_code_info($message->msgcode, $message->addinfo);
                    if ($info) {
                        $this->mtrace('['.s($info).']', ' ', $level);
                    } else if (is_string($message->addinfo)) {
                        $this->mtrace('['.s($message->addinfo, true).']', ' ', $level);
                    } else {
                        $this->mtrace('['.s(json_encode($message->addinfo, true)).']', ' ', $level);
                    }
                    if ($icon = $validator->message_help_icon($message->msgcode)) {
                        if (CLI_SCRIPT) {
                            $this->mtrace(PHP_EOL.'  ^^^ '.get_string('help').': '.
                                get_string($icon->identifier.'_help', $icon->component), '', $level);
                        } else {
                            $this->mtrace($OUTPUT->render($icon), ' ', $level);
                        }
                    }
                    $this->mtrace(PHP_EOL, '', $level);
                }
            }
            if (!$result) {
                $silent or $this->mtrace(get_string('packagesvalidatingfailed', 'core_plugin'));
                return false;
            }
        }
        $silent or $this->mtrace(PHP_EOL.get_string('packagesvalidatingok', 'core_plugin'));

        if (!$confirmed) {
            return true;
        }

        // Extract all ZIP packs do the dirroot.
        foreach ($plugins as $plugin) {
1420
            $silent or $this->mtrace(get_string('packagesextracting', 'core_plugin', $plugin->component), ' ... ');
1421
1422
1423
1424
            $zipfile = $zips[$plugin->component];
            list($plugintype, $pluginname) = core_component::normalize_component($plugin->component);
            $target = $this->get_plugintype_root($plugintype);
            if (file_exists($target.'/'.$pluginname)) {
1425
                $this->remove_plugin_folder($this->get_plugin_info($plugin->component));
1426
1427
1428
1429
            }
            if (!$this->unzip_plugin_file($zipfile, $target, $pluginname)) {
                $silent or $this->mtrace(get_string('error'));
                $silent or $this->mtrace('Unable to unzip '.$zipfile, PHP_EOL, DEBUG_DEVELOPER);
1430
1431
1432
                if (function_exists('opcache_reset')) {
                    opcache_reset();
                }
1433
1434
1435
1436
                return false;
            }
            $silent or $this->mtrace($ok);
        }
1437
1438
1439
        if (function_exists('opcache_reset')) {
            opcache_reset();
        }
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464

        return true;
    }

    /**
     * Outputs the given message via {@link mtrace()}.
     *
     * If $debug is provided, then the message is displayed only at the given
     * debugging level (e.g. DEBUG_DEVELOPER to display the message only if the
     * site has developer debugging level selected).
     *
     * @param string $msg message
     * @param string $eol end of line
     * @param null|int $debug null to display always, int only on given debug level
     */
    protected function mtrace($msg, $eol=PHP_EOL, $debug=null) {
        global $CFG;

        if ($debug !== null and !debugging(null, $debug)) {
            return;
        }

        mtrace($msg, $eol);
    }

1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
    /**
     * Returns uninstall URL if exists.
     *
     * @param string $component
     * @param string $return either 'overview' or 'manage'
     * @return moodle_url uninstall URL, null if uninstall not supported
     */
    public function get_uninstall_url($component, $return = 'overview') {
        if (!$this->can_uninstall_plugin($component)) {
            return null;
        }

        $pluginfo = $this->get_plugin_info($component);

        if (is_null($pluginfo)) {
            return null;
        }

        if (method_exists($pluginfo, 'get_uninstall_url')) {
            debugging('plugininfo method get_uninstall_url() is deprecated, all plugins should be uninstalled via standard URL only.');
            return $pluginfo->get_uninstall_url($return);
        }

        return $pluginfo->get_default_uninstall_url($return);
    }

    /**
     * Uninstall the given plugin.
     *
     * Automatically cleans-up all remaining configuration data, log records, events,
     * files from the file pool etc.
     *
     * In the future, the functionality of {@link uninstall_plugin()} function may be moved
     * into this method and all the code should be refactored to use it. At the moment, we
     * mimic this future behaviour by wrapping that function call.
     *
     * @param string $component
     * @param progress_trace $progress traces the process
     * @return bool true on success, false on errors/problems
     */
    public function uninstall_plugin($component, progress_trace $progress) {

        $pluginfo = $this->get_plugin_info($component);

        if (is_null($pluginfo)) {
            return false;
        }

        // Give the pluginfo class a chance to execute some steps.
        $result = $pluginfo->uninstall($progress);
        if (!$result) {
            return false;
        }

        // Call the legacy core function to uninstall the plugin.
        ob_start();
        uninstall_plugin($pluginfo->type, $pluginfo->name);
        $progress->output(ob_get_clean());

        return true;
    }

    /**
     * Checks if there are some plugins with a known available update
     *
     * @return bool true if there is at least one available update
     */
    public function some_plugins_updatable() {
        foreach ($this->get_plugins() as $type => $plugins) {
            foreach ($plugins as $plugin) {
                if ($plugin->available_updates()) {
                    return true;
                }
            }
        }

        return false;
    }

1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
    /**
     * Returns list of available updates for the given component.
     *
     * This method should be considered as internal API and is supposed to be
     * called by {@link \core\plugininfo\base::available_updates()} only
     * to lazy load the data once they are first requested.
     *
     * @param string $component frankenstyle name of the plugin
     * @return null|array array of \core\update\info objects or null
     */
    public function load_available_updates_for_plugin($component) {
        global $CFG;

        $provider = \core\update\checker::instance();

        if (!$provider->enabled() or during_initial_install()) {
            return null;
        }

        if (isset($CFG->updateminmaturity)) {
            $minmaturity = $CFG->updateminmaturity;
        } else {
            // This can happen during the very first upgrade to 2.3.
            $minmaturity = MATURITY_STABLE;
        }

        return $provider->get_update_info($component, array('minmaturity' => $minmaturity));
    }

1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
    /**
     * Returns a list of all available updates to be installed.
     *
     * This is used when "update all plugins" action is performed at the
     * administration UI screen.
     *
     * Returns array of remote info objects indexed by the plugin
     * component. If there are multiple updates available (typically a mix of
     * stable and non-stable ones), we pick the most mature most recent one.
     *
     * Plugins without explicit maturity are considered more mature than
     * release candidates but less mature than explicit stable (this should be
     * pretty rare case).
     *
1587
     * @return array (string)component => (\core\update\remote_info)remoteinfo
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
     */
    public function available_updates() {

        $updates = array();

        foreach ($this->get_plugins() as $type => $plugins) {
            foreach ($plugins as $plugin) {
                $availableupdates = $plugin->available_updates();
                if (empty($availableupdates)) {
                    continue;
                }
                foreach ($availableupdates as $update) {
                    if (empty($updates[$plugin->component])) {
                        $updates[$plugin->component] = $update;
                        continue;
                    }
                    $maturitycurrent = $updates[$plugin->component]->maturity;
                    if (empty($maturitycurrent)) {
                        $maturitycurrent = MATURITY_STABLE - 25;
                    }
                    $maturityremote = $update->maturity;
                    if (empty($maturityremote)) {
                        $maturityremote = MATURITY_STABLE - 25;
                    }
                    if ($maturityremote < $maturitycurrent) {
                        continue;
                    }
                    if ($maturityremote > $maturitycurrent) {
                        $updates[$plugin->component] = $update;
                        continue;
                    }
                    if ($update->version > $updates[$plugin->component]->version) {
                        $updates[$plugin->component] = $update;
                        continue;
                    }
                }
            }
        }

        foreach ($updates as $component => $update) {
            $remoteinfo = $this->get_remote_plugin_info($component, $update->version, true);
            if (empty($remoteinfo) or empty($remoteinfo->version)) {
                unset($updates[$component]);
            } else {
                $updates[$component] = $remoteinfo;
            }
        }

        return $updates;
    }

1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
    /**
     * Check to see if the given plugin folder can be removed by the web server process.
     *
     * @param string $component full frankenstyle component
     * @return bool
     */
    public function is_plugin_folder_removable($component) {

        $pluginfo = $this->get_plugin_info($component);

        if (is_null($pluginfo)) {
            return false;
        }

        // To be able to remove the plugin folder, its parent must be writable, too.
        if (!is_writable(dirname($pluginfo->rootdir))) {
            return false;
        }

        // Check that the folder and all its content is writable (thence removable).
        return $this->is_directory_removable($pluginfo->rootdir);
    }

1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
    /**
     * Is it possible to create a new plugin directory for the given plugin type?
     *
     * @throws coding_exception for invalid plugin types or non-existing plugin type locations
     * @param string $plugintype
     * @return boolean
     */
    public function is_plugintype_writable($plugintype) {

        $plugintypepath = $this->get_plugintype_root($plugintype);

        if (is_null($plugintypepath)) {
            throw new coding_exception('Unknown plugin type: '.$plugintype);
        }

        if ($plugintypepath === false) {
            throw new coding_exception('Plugin type location does not exist: '.$plugintype);
        }

        return is_writable($plugintypepath);
    }

    /**
     * Returns the full path of the root of the given plugin type
     *
     * Null is returned if the plugin type is not known. False is returned if
     * the plugin type root is expected but not found. Otherwise, string is
     * returned.
     *
     * @param string $plugintype
     * @return string|bool|null
     */
    public function get_plugintype_root($plugintype) {

        $plugintypepath = null;
        foreach (core_component::get_plugin_types() as $type => $fullpath) {
            if ($type === $plugintype) {
                $plugintypepath = $fullpath;
                break;
            }
        }
        if (is_null($plugintypepath)) {
            return null;
        }
        if (!is_dir($plugintypepath)) {
            return false;
        }

        return $plugintypepath;
    }

1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
    /**
     * Defines a list of all plugins that were originally shipped in the standard Moodle distribution,
     * but are not anymore and are deleted during upgrades.
     *
     * The main purpose of this list is to hide missing plugins during upgrade.
     *
     * @param string $type plugin type
     * @param string $name plugin name
     * @return bool
     */
    public static function is_deleted_standard_plugin($type, $name) {
        // Do not include plugins that were removed during upgrades to versions that are
        // not supported as source versions for upgrade any more. For example, at MOODLE_23_STABLE
        // branch, listed should be no plugins that were removed at 1.9.x - 2.1.x versions as
        // Moodle 2.3 supports upgrades from 2.2.x only.
        $plugins = array(
1729
            'qformat' => array('blackboard', 'learnwise', 'examview'),
1730
            'auth' => array('radius', 'fc', 'nntp', 'pam', 'pop3', 'imap'),
1731
            'block' => array('course_overview', 'messages', 'community', 'participants', 'quiz_results'),
1732
            'cachestore' => array('memcache'),
1733
            'enrol' => array('authorize'),
1734
            'filter' => array('censor'),
1735
            'media' => array('swf'),
1736
            'portfolio' => array('picasa', 'boxnet'),
1737
            'qformat' => array('webct'),
1738
            'message' => array('jabber'),
1739
            'quizaccess' => array('safebrowser'),
1740
            'report' => array('search'),
1741
            'repository' => array('alfresco', 'picasa', 'skydrive', 'boxnet'),
1742
            'tinymce' => array('dragmath'),
1743
            'tool' => array('bloglevelupgrade', 'qeupgradehelper', 'timezoneimport', 'assignmentupgrade', 'health'),
1744
1745
1746
1747
            'theme' => array('bootstrapbase', 'clean', 'more', 'afterburner', 'anomaly', 'arialist', 'base',
                'binarius', 'boxxie', 'brick', 'canvas', 'formal_white', 'formfactor', 'fusion', 'leatherbound',
                'magazine', 'mymobile', 'nimble', 'nonzero', 'overlay', 'serenity', 'sky_high', 'splash',
                'standard', 'standardold'),
1748
            'webservice' => array('amf'),
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
        );

        if (!isset($plugins[$type])) {
            return false;
        }
        return in_array($name, $plugins[$type]);
    }

    /**
     * Defines a white list of all plugins shipped in the standard Moodle distribution
     *
     * @param string $type
     * @return false|array array of standard plugins or false if the type is unknown
     */
    public static function standard_plugins_list($type) {

        $standard_plugins = array(

1767
1768
1769
1770
            'antivirus' => array(
                'clamav'
            ),

1771
            'atto' => array(
1772
1773
1774
1775
                'accessibilitychecker', 'accessibilityhelper', 'align',
                'backcolor', 'bold', 'charmap', 'clear', 'collapse', 'emoticon',
                'equation', 'fontcolor', 'html', 'image', 'indent', 'italic',
                'link', 'managefiles', 'media', 'noautolink', 'orderedlist',
1776
                'recordrtc', 'rtl', 'strike', 'subscript', 'superscript', 'table',
1777
                'title', 'underline', 'undo', 'unorderedlist', 'h5p', 'emojipicker',
1778
1779
            ),

1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
            'assignment' => array(
                'offline', 'online', 'upload', 'uploadsingle'
            ),

            'assignsubmission' => array(
                'comments', 'file', 'onlinetext'
            ),

            'assignfeedback' => array(
                'comments', 'file', 'offline', 'editpdf'
            ),

            'auth' => array(
1793
                'cas', 'db', 'email', 'ldap', 'lti', 'manual', 'mnet',
1794
                'nologin', 'none', 'oauth2', 'shibboleth', 'webservice'
1795
1796
            ),

1797
1798
1799
1800
            'availability' => array(
                'completion', 'date', 'grade', 'group', 'grouping', 'profile'
            ),

1801
            'block' => array(
1802
                'accessreview', 'activity_modules', 'activity_results', 'admin_bookmarks', 'badges',
1803
                'blog_menu', 'blog_recent', 'blog_tags', 'calendar_month',
1804
                'calendar_upcoming', 'comments',
1805
1806
                'completionstatus', 'course_list', 'course_summary',
                'feedback', 'globalsearch', 'glossary_random', 'html',
1807
                'login', 'lp', 'mentees', 'mnet_hosts', 'myoverview', 'myprofile',
1808
                'navigation', 'news_items', 'online_users',
1809
                'private_files', 'recent_activity', 'recentlyaccesseditems',
1810
                'recentlyaccessedcourses', 'rss_client', 'search_forums', 'section_links',
1811
                'selfcompletion', 'settings', 'site_main_menu',
1812
                'social_activities', 'starredcourses', 'tag_flickr', 'tag_youtube', 'tags', 'timeline'
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
            ),

            'booktool' => array(
                'exportimscp', 'importhtml', 'print'
            ),

            'cachelock' => array(
                'file'
            ),

            'cachestore' => array(
1824
                'file', 'memcached', 'mongodb', 'session', 'static', 'apcu', 'redis'
1825
1826
1827
1828
1829
1830
            ),

            'calendartype' => array(
                'gregorian'
            ),

1831
1832
1833
1834
            'contenttype' => array(
                'h5p'
            ),

1835
1836
1837
1838
            'customfield' => array(
                'checkbox', 'date', 'select', 'text', 'textarea'
            ),

1839
1840
1841
1842
1843
1844
1845
1846
1847
            'coursereport' => array(
                // Deprecated!
            ),

            'datafield' => array(
                'checkbox', 'date', 'file', 'latlong', 'menu', 'multimenu',
                'number', 'picture', 'radiobutton', 'text', 'textarea', 'url'
            ),

1848
            'dataformat' => array(
1849
                'html', 'csv', 'json', 'excel', 'ods', 'pdf',
1850
1851
            ),

1852
1853
1854
1855
            'datapreset' => array(
                'imagegallery'
            ),

1856
            'fileconverter' => array(
1857
                'unoconv', 'googledrive'
1858
1859
            ),

1860
            'editor' => array(
1861
                'atto', 'textarea', 'tinymce'
1862
1863
1864
1865
            ),

            'enrol' => array(
                'category', 'cohort', 'database', 'flatfile',