plugin_manager.php 81 KB
Newer Older
1001
1002
1003
1004
        }
        return $installable;
    }

1005
1006
1007
    /**
     * Returns information about a plugin in the plugins directory.
     *
1008
1009
1010
1011
1012
1013
     * 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.
1014
     *
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
     * 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
1028
     * @return \core\update\remote_info|bool
1029
     */
1030
    public function get_remote_plugin_info($component, $version, $exactmatch) {
1031

1032
1033
        if ($exactmatch and $version == ANY_VERSION) {
            throw new coding_exception('Invalid request for exactly any version, it does not make sense.');
1034
1035
        }

1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
        $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];
        }
1052
1053
1054
    }

    /**
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
     * 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) {
1066
1067
1068
1069
1070
        global $CFG;

        if (!empty($CFG->disableupdateautodeploy)) {
            return false;
        }
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
        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
1085
     * @return array list of extracted files as returned by {@link zip_packer::extract_to_pathname()}
1086
1087
1088
1089
1090
     */
    public function unzip_plugin_file($zipfilepath, $targetdir, $rootdir = '') {
        return $this->get_code_manager()->unzip_plugin_file($zipfilepath, $targetdir, $rootdir);
    }

1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
    /**
     * 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);
    }

1105
1106
    /**
     * Return a list of missing dependencies.
1107
1108
1109
1110
     *
     * This should provide the full list of plugins that should be installed to
     * fulfill the requirements of all plugins, if possible.
     *
1111
     * @param bool $availableonly return only available missing dependencies
1112
     * @return array of \core\update\remote_info|bool indexed by the component name
1113
     */
1114
    public function missing_dependencies($availableonly=false) {
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125

        $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) {
1126
                            $remoteinfo = $this->get_remote_plugin_info($reqname, $reqinfo->reqver, false);
1127
1128
1129
1130

                            if (empty($dependencies[$reqname])) {
                                $dependencies[$reqname] = $remoteinfo;
                            } else {
1131
1132
1133
1134
                                // 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.
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
                                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;
                            }
                        }
                    }
                }
            }
        }

1151
1152
1153
1154
1155
1156
1157
1158
        if ($availableonly) {
            foreach ($dependencies as $component => $info) {
                if (empty($info) or empty($info->version)) {
                    unset($dependencies[$component]);
                }
            }
        }

1159
1160
1161
        return $dependencies;
    }

1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
    /**
     * 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;
    }

1211
    /**
1212
1213
1214
1215
1216
1217
     * 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.
1218
     *
1219
1220
1221
     * If used for installation of plugins from locally available ZIP files,
     * the $plugins should be list of objects with properties ->component and
     * ->zipfilepath.
1222
     *
1223
1224
1225
1226
     * 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
1227
1228
1229
1230
     * @param bool $confirmed should the files be really deployed into the dirroot?
     * @param bool $silent perform without output
     * @return bool true on success
     */
1231
    public function install_plugins(array $plugins, $confirmed, $silent) {
1232
1233
        global $CFG, $OUTPUT;

1234
1235
1236
1237
        if (!empty($CFG->disableupdateautodeploy)) {
            return false;
        }

1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
        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) {
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
            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);
1267
1268
1269
1270
1271
1272
            }
        }

        // Validate all downloaded packages.
        foreach ($plugins as $plugin) {
            $zipfile = $zips[$plugin->component];
1273
            $silent or $this->mtrace(get_string('packagesvalidating', 'core_plugin', $plugin->component), ' ... ');
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
            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) {
1339
            $silent or $this->mtrace(get_string('packagesextracting', 'core_plugin', $plugin->component), ' ... ');
1340
1341
1342
1343
            $zipfile = $zips[$plugin->component];
            list($plugintype, $pluginname) = core_component::normalize_component($plugin->component);
            $target = $this->get_plugintype_root($plugintype);
            if (file_exists($target.'/'.$pluginname)) {
1344
                $this->remove_plugin_folder($this->get_plugin_info($plugin->component));
1345
1346
1347
1348
            }
            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);
1349
1350
1351
                if (function_exists('opcache_reset')) {
                    opcache_reset();
                }
1352
1353
1354
1355
                return false;
            }
            $silent or $this->mtrace($ok);
        }
1356
1357
1358
        if (function_exists('opcache_reset')) {
            opcache_reset();
        }
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

        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);
    }

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
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
    /**
     * 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;
    }

1463
1464
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
    /**
     * 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));
    }

1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
    /**
     * 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).
     *
1506
     * @return array (string)component => (\core\update\remote_info)remoteinfo
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
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
     */
    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;
    }

1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
    /**
     * 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);
    }

1581
1582
1583
1584
1585
1586
1587
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
    /**
     * 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;
    }

1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
    /**
     * 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(
1648
            'qformat' => array('blackboard', 'learnwise'),
1649
            'auth' => array('radius', 'fc', 'nntp', 'pam', 'pop3', 'imap'),
1650
            'block' => array('course_overview', 'messages'),
1651
            'enrol' => array('authorize'),
1652
            'report' => array('search'),
1653
            'repository' => array('alfresco'),
1654
            'tinymce' => array('dragmath'),
1655
            'tool' => array('bloglevelupgrade', 'qeupgradehelper', 'timezoneimport', 'assignmentupgrade'),
1656
1657
1658
            'theme' => array('afterburner', 'anomaly', 'arialist', 'base', 'binarius', 'boxxie', 'brick', 'canvas',
                'formal_white', 'formfactor', 'fusion', 'leatherbound', 'magazine', 'mymobile', 'nimble', 'nonzero',
                'overlay', 'serenity', 'sky_high', 'splash', 'standard', 'standardold'),
1659
            'webservice' => array('amf'),
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
        );

        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(

1678
1679
1680
1681
            'antivirus' => array(
                'clamav'
            ),

1682
            'atto' => array(
1683
1684
1685
1686
                'accessibilitychecker', 'accessibilityhelper', 'align',
                'backcolor', 'bold', 'charmap', 'clear', 'collapse', 'emoticon',
                'equation', 'fontcolor', 'html', 'image', 'indent', 'italic',
                'link', 'managefiles', 'media', 'noautolink', 'orderedlist',
1687
1688
                'recordrtc', 'rtl', 'strike', 'subscript', 'superscript', 'table',
                'title', 'underline', 'undo', 'unorderedlist'
1689
1690
            ),

1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
            'assignment' => array(
                'offline', 'online', 'upload', 'uploadsingle'
            ),

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

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

            'auth' => array(
1704
                'cas', 'db', 'email', 'ldap', 'lti', 'manual', 'mnet',
1705
                'nologin', 'none', 'oauth2', 'shibboleth', 'webservice'
1706
1707
            ),

1708
1709
1710
1711
            'availability' => array(
                'completion', 'date', 'grade', 'group', 'grouping', 'profile'
            ),

1712
            'block' => array(
1713
1714
                'activity_modules', 'activity_results', 'admin_bookmarks', 'badges',
                'blog_menu', 'blog_recent', 'blog_tags', 'calendar_month',
1715
                'calendar_upcoming', 'comments', 'community',
1716
1717
                'completionstatus', 'course_list', 'course_summary',
                'feedback', 'globalsearch', 'glossary_random', 'html',
1718
                'login', 'lp', 'mentees', 'mnet_hosts', 'myoverview', 'myprofile',
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
                'navigation', 'news_items', 'online_users', 'participants',
                'private_files', 'quiz_results', 'recent_activity',
                'rss_client', 'search_forums', 'section_links',
                'selfcompletion', 'settings', 'site_main_menu',
                'social_activities', 'tag_flickr', 'tag_youtube', 'tags'
            ),

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

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

            'cachestore' => array(
1735
                'file', 'memcache', 'memcached', 'mongodb', 'session', 'static', 'apcu', 'redis'
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
            ),

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

            'coursereport' => array(
                // Deprecated!
            ),

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

1751
1752
1753
1754
            'dataformat' => array(
                'html', 'csv', 'json', 'excel', 'ods',
            ),

1755
1756
1757
1758
            'datapreset' => array(
                'imagegallery'
            ),

1759
            'fileconverter' => array(
1760
                'unoconv', 'googledrive'
1761
1762
            ),

1763
            'editor' => array(
1764
                'atto', 'textarea', 'tinymce'
1765
1766
1767
1768
            ),

            'enrol' => array(
                'category', 'cohort', 'database', 'flatfile',
1769
                'guest', 'imsenterprise', 'ldap', 'lti', 'manual', 'meta', 'mnet',
1770
1771
1772
1773
1774
                'paypal', 'self'
            ),

            'filter' => array(
                'activitynames', 'algebra', 'censor', 'emailprotect',
1775
                'emoticon', 'mathjaxloader', 'mediaplugin', 'multilang', 'tex', 'tidy',
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
                'urltolink', 'data', 'glossary'
            ),

            'format' => array(
                'singleactivity', 'social', 'topics', 'weeks'
            ),

            'gradeexport' => array(
                'ods', 'txt', 'xls', 'xml'
            ),

            'gradeimport' => array(
1788
                'csv', 'direct', 'xml'
1789
1790
1791
            ),

            'gradereport' => array(
1792
                'grader', 'history', 'outcomes', 'overview', 'user', 'singleview'
1793
1794
1795
1796
1797
1798
1799
1800
1801
            ),

            'gradingform' => array(
                'rubric', 'guide'
            ),

            'local' => array(
            ),

1802
1803
1804
1805
            'logstore' => array(
                'database', 'legacy', 'standard',
            ),

1806
            'ltiservice' => array(
1807
                'gradebookservices', 'memberships', 'profile', 'toolproxy', 'toolsettings'
1808
1809
            ),

1810
1811
1812
1813
            'mlbackend' => array(
                'php', 'python'
            ),

1814
1815
1816
1817
            'media' => array(
                'html5audio', 'html5video', 'swf', 'videojs', 'vimeo', 'youtube'
            ),

1818
            'message' => array(
1819
                'airnotifier', 'email', 'jabber', 'popup'
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
            ),

            'mnetservice' => array(
                'enrol'
            ),

            'mod' => array(
                'assign', 'assignment', 'book', 'chat', 'choice', 'data', 'feedback', 'folder',
                'forum', 'glossary', 'imscp', 'label', 'lesson', 'lti', 'page',
                'quiz', 'resource', 'scorm', 'survey', 'url', 'wiki', 'workshop'
            ),

            'plagiarism' => array(
            ),

            'portfolio' => array(
                'boxnet', 'download', 'flickr', 'googledocs', 'mahara', 'picasa'
            ),

            'profilefield' => array(
                'checkbox', 'datetime', 'menu', 'text', 'textarea'
            ),

            'qbehaviour' => array(
                'adaptive', 'adaptivenopenalty', 'deferredcbm',
                'deferredfeedback', 'immediatecbm', 'immediatefeedback',
                'informationitem', 'interactive', 'interactivecountback',
                'manualgraded', 'missing'
            ),

            'qformat' => array(
                'aiken', 'blackboard_six', 'examview', 'gift',
1852
                'missingword', 'multianswer', 'webct',
1853
1854
1855
1856
1857
                'xhtml', 'xml'
            ),

            'qtype' => array(
                'calculated', 'calculatedmulti', 'calculatedsimple',
1858
1859
                'ddimageortext', 'ddmarker', 'ddwtos', 'description',
                'essay', 'gapselect', 'match', 'missingtype', 'multianswer',
1860
1861
1862
1863
1864
1865
1866
1867
1868
                'multichoice', 'numerical', 'random', 'randomsamatch',
                'shortanswer', 'truefalse'
            ),

            'quiz' => array(
                'grading', 'overview', 'responses', 'statistics'
            ),

            'quizaccess' => array(
1869
                'delaybetweenattempts', 'ipaddress', 'numattempts', 'offlineattempts', 'openclosedate',
1870
1871
1872
1873
                'password', 'safebrowser', 'securewindow', 'timelimit'
            ),

            'report' => array(
1874
                'backups', 'competency', 'completion', 'configlog', 'courseoverview', 'eventlist',
1875
                'insights', 'log', 'loglive', 'outline', 'participation', 'progress', 'questioninstances',
1876
                'security', 'stats', 'performance', 'usersessions'
1877
1878
1879
            ),

            'repository' => array(
1880
                'areafiles', 'boxnet', 'coursefiles', 'dropbox', 'equella', 'filesystem',
1881
                'flickr', 'flickr_public', 'googledocs', 'local', 'merlot',
1882
                'onedrive', 'picasa', 'recent', 'skydrive', 's3', 'upload', 'url', 'user', 'webdav',
1883
1884
1885
                'wikimedia', 'youtube'
            ),

1886
            'search' => array(
1887
                'simpledb', 'solr'
1888
1889
            ),

1890
1891
1892
1893
1894
1895
1896
1897
            'scormreport' => array(
                'basic',
                'interactions',
                'graphs',
                'objectives'
            ),

            'tinymce' => array(
1898
                'ctrlhelp', 'managefiles', 'moodleemoticon', 'moodleimage',
1899
1900
1901
1902
                'moodlemedia', 'moodlenolink', 'pdw', 'spellchecker', 'wrap'
            ),

            'theme' => array(
1903
                'boost', 'bootstrapbase', 'clean', 'more'
1904
1905
1906
            ),

            'tool' => array(
1907
                'analytics', 'availabilityconditions', 'behat', 'capability', 'cohortroles', 'customlang',
1908
                'dataprivacy', 'dbtransfer', 'filetypes', 'generator', 'health', 'httpsreplace', 'innodb', 'installaddon',
1909
                'langimport', 'log', 'lp', 'lpimportcsv', 'lpmigrate', 'messageinbound', 'mobile', 'multilangupgrade',
1910
1911
                'monitor', 'oauth2', 'phpunit', 'policy', 'profiling', 'recyclebin', 'replace', 'spamcleaner', 'task',
                'templatelibrary', 'uploadcourse', 'uploaduser', 'unsuproles', 'usertours', 'xmldb'
1912
1913
1914
            ),

            'webservice' => array(
1915
                'rest', 'soap', 'xmlrpc'
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
            ),

            'workshopallocation' => array(
                'manual', 'random', 'scheduled'
            ),

            'workshopeval' => array(
                'best'
            ),

            'workshopform' => array(
                'accumulative', 'comments', 'numerrors', 'rubric'
            )
        );

        if (isset($standard_plugins[$type])) {
            return $standard_plugins[$type];
        } else {
            return false;
        }
    }

1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
    /**
     * Remove the current plugin code from the dirroot.
     *
     * If removing the currently installed version (which happens during
     * updates), we archive the code so that the upgrade can be cancelled.
     *
     * To prevent accidental data-loss, we also archive the existing plugin
     * code if cancelling installation of it, so that the developer does not
     * loose the only version of their work-in-progress.
     *
     * @param \core\plugininfo\base $plugin
     */
    public function remove_plugin_folder(\core\plugininfo\base $plugin) {

        if (!$this->is_plugin_folder_removable($plugin->component)) {
            throw new moodle_exception('err_removing_unremovable_folder', 'core_plugin', '',
1954
                array('plugin' => $plugin->component, 'rootdir' => $plugin->rootdir),
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
                'plugin root folder is not removable as expected');
        }

        if ($plugin->get_status() === self::PLUGIN_STATUS_UPTODATE or $plugin->get_status() === self::PLUGIN_STATUS_NEW) {
            $this->archive_plugin_version($plugin);
        }

        remove_dir($plugin->rootdir);
        clearstatcache();
        if (function_exists('opcache_reset')) {
            opcache_reset();
        }
    }

1969
1970
1971
    /**
     * Can the installation of the new plugin be cancelled?
     *
1972
1973
1974
1975
     * Subplugins can be cancelled only via their parent plugin, not separately
     * (they are considered as implicit requirements if distributed together
     * with the main package).
     *
1976
1977
1978
1979
     * @param \core\plugininfo\base $plugin
     * @return bool
     */
    public function can_cancel_plugin_installation(\core\plugininfo\base $plugin) {
1980
1981
1982
1983
1984
        global $CFG;

        if (!empty($CFG->disableupdateautodeploy)) {
            return false;
        }
1985

1986
1987
        if (empty($plugin) or $plugin->is_standard() or $plugin->is_subplugin()
                or !$this->is_plugin_folder_removable($plugin->component)) {
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
            return false;
        }

        if ($plugin->get_status() === self::PLUGIN_STATUS_NEW) {
            return true;
        }

        return false;
    }

1998
1999
2000
    /**
     * Can the upgrade of the existing plugin be cancelled?
     *
For faster browsing, not all history is shown. View entire blame