Welcome to mirror list, hosted at ThFree Co, Russian Federation.

PluginInstaller.php « CorePluginsAdmin « plugins - github.com/matomo-org/matomo.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 4619ecca9f2237e0eceaf16ceba9fb1a149e79ce (plain)
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
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
261
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
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
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
<?php
/**
 * Matomo - free/libre analytics platform
 *
 * @link https://matomo.org
 * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
 *
 */
namespace Piwik\Plugins\CorePluginsAdmin;

use Piwik\Common;
use Piwik\Container\StaticContainer;
use Piwik\Filechecks;
use Piwik\Filesystem;
use Piwik\Piwik;
use Piwik\Plugin\Manager as PluginManager;
use Piwik\Plugin\Dependency as PluginDependency;
use Piwik\Plugin\Manager;
use Piwik\Plugins\Marketplace\Environment;
use Piwik\Plugins\Marketplace\Marketplace;
use Piwik\Unzip;
use Piwik\Plugins\Marketplace\Api\Client;

/**
 *
 */
class PluginInstaller
{
    const PATH_TO_DOWNLOAD = '/latest/plugins/';

    private $pluginName;

    /**
     * Null if Marketplace Plugin is not installed
     * @var Client|null
     */
    private $marketplaceClient;

    /**
     * PluginInstaller constructor.
     * @param Client|null $client
     */
    public function __construct($client = null)
    {
        if (!empty($client)) {
            $this->marketplaceClient = $client;
        } elseif (Marketplace::isMarketplaceEnabled()) {
            // we load it manually as marketplace might not be loaded
            $this->marketplaceClient = StaticContainer::get('Piwik\Plugins\Marketplace\Api\Client');
        }
    }

    public function installOrUpdatePluginFromMarketplace($pluginName)
    {
        $this->checkMarketplaceIsEnabled();

        $this->pluginName = $pluginName;

        try {
            $this->makeSureFoldersAreWritable();
            $this->makeSurePluginNameIsValid();

            $tmpPluginZip = $this->downloadPluginFromMarketplace();
            $tmpPluginFolder = dirname($tmpPluginZip) . '/' . basename($tmpPluginZip, '.zip') .  '/';
            $this->extractPluginFiles($tmpPluginZip, $tmpPluginFolder);
            $this->makeSurePluginJsonExists($tmpPluginFolder);
            $metadata = $this->getPluginMetadataIfValid($tmpPluginFolder);
            $this->makeSureThereAreNoMissingRequirements($metadata);
            $this->copyPluginToDestination($tmpPluginFolder);

            Filesystem::deleteAllCacheOnUpdate($this->pluginName);

            $pluginManager = PluginManager::getInstance();
            if ($pluginManager->isPluginLoaded($this->pluginName)) {
                $plugin = PluginManager::getInstance()->getLoadedPlugin($this->pluginName);
                if (!empty($plugin)) {
                    $plugin->reloadPluginInformation();
                }
            }

        } catch (\Exception $e) {

            if (!empty($tmpPluginZip)) {
                Filesystem::deleteFileIfExists($tmpPluginZip);
            }
            if (!empty($tmpPluginFolder)) {
                $this->removeFolderIfExists($tmpPluginFolder);
            }

            throw $e;
        }

        $this->removeFileIfExists($tmpPluginZip);
        $this->removeFolderIfExists($tmpPluginFolder);
    }

    public function installOrUpdatePluginFromFile($pathToZip)
    {
        $tmpPluginName = 'uploaded' . Common::generateUniqId();
        $tmpPluginFolder = StaticContainer::get('path.tmp') . self::PATH_TO_DOWNLOAD . $tmpPluginName;

        try {
            $this->makeSureFoldersAreWritable();
            $this->extractPluginFiles($pathToZip, $tmpPluginFolder);

            $this->makeSurePluginJsonExists($tmpPluginFolder);
            $metadata = $this->getPluginMetadataIfValid($tmpPluginFolder);
            $this->makeSureThereAreNoMissingRequirements($metadata);

            $this->pluginName = $metadata->name;

            $this->fixPluginFolderIfNeeded($tmpPluginFolder);
            $this->copyPluginToDestination($tmpPluginFolder);

            Filesystem::deleteAllCacheOnUpdate($this->pluginName);

        } catch (\Exception $e) {

            $this->removeFileIfExists($pathToZip);
            $this->removeFolderIfExists($tmpPluginFolder);

            throw $e;
        }

        $this->removeFileIfExists($pathToZip);
        $this->removeFolderIfExists($tmpPluginFolder);

        return $metadata;
    }

    private function makeSureFoldersAreWritable()
    {
        $dirs = array(
            StaticContainer::get('path.tmp') . self::PATH_TO_DOWNLOAD,
            Manager::getPluginsDirectory()
        );
        // we do not require additional plugin directories to be writeable ({@link Manager::getPluginsDirectories()})
        // as we only upload to core plugins directory anyway
        Filechecks::dieIfDirectoriesNotWritable($dirs);
    }

    /**
     * @return false|string   false on failed download, or a path to the downloaded zip file
     * @throws PluginInstallerException
     */
    private function downloadPluginFromMarketplace()
    {
        try {
            return $this->marketplaceClient->download($this->pluginName);
        } catch (\Exception $e) {

            try {
                $downloadUrl = $this->marketplaceClient->getDownloadUrl($this->pluginName);
                $errorMessage = sprintf('Failed to download plugin from %s: %s', $downloadUrl, $e->getMessage());

            } catch (\Exception $ex) {
                $errorMessage = sprintf('Failed to download plugin: %s', $e->getMessage());
            }

            throw new PluginInstallerException($errorMessage);
        }
    }

    /**
     * @param $pluginZipFile
     * @param $pathExtracted
     * @throws \Exception
     */
    private function extractPluginFiles($pluginZipFile, $pathExtracted)
    {
        $archive = Unzip::factory('PclZip', $pluginZipFile);

        $this->removeFolderIfExists($pathExtracted);

        if (0 == ($pluginFiles = $archive->extract($pathExtracted))) {
            throw new PluginInstallerException(Piwik::translate('CoreUpdater_ExceptionArchiveIncompatible', $archive->errorInfo()));
        }

        if (0 == count($pluginFiles)) {
            throw new PluginInstallerException(Piwik::translate('Plugin Zip File Is Empty'));
        }
    }

    private function makeSurePluginJsonExists($tmpPluginFolder)
    {
        $pluginJsonPath = $this->getPathToPluginJson($tmpPluginFolder);

        if (!file_exists($pluginJsonPath)) {
            throw new PluginInstallerException('Plugin is not valid, it is missing the plugin.json file.');
        }
    }

    private function makeSureThereAreNoMissingRequirements($metadata)
    {
        $requires = array();
        if (!empty($metadata->require)) {
            $requires = (array) $metadata->require;
        }

        $dependency = new PluginDependency();
        $dependency->setEnvironment($this->getEnvironment());
        $missingDependencies = $dependency->getMissingDependencies($requires);

        if (!empty($missingDependencies)) {
            $message = '';
            foreach ($missingDependencies as $dep) {
                if (empty($dep['actualVersion'])) {
                    $params   = array(ucfirst($dep['requirement']), $dep['requiredVersion'], $metadata->name);
                    $message .= Piwik::translate('CorePluginsAdmin_MissingRequirementsPleaseInstallNotice', $params);
                } else {
                    $params   = array(ucfirst($dep['requirement']), $dep['actualVersion'], $dep['requiredVersion']);
                    $message .= Piwik::translate('CorePluginsAdmin_MissingRequirementsNotice', $params);
                }

            }

            throw new PluginInstallerException($message);
        }
    }

    private function getPluginMetadataIfValid($tmpPluginFolder)
    {
        $pluginJsonPath = $this->getPathToPluginJson($tmpPluginFolder);

        $metadata = file_get_contents($pluginJsonPath);
        $metadata = json_decode($metadata);

        if (empty($metadata)) {
            throw new PluginInstallerException('Plugin is not valid, plugin.json is empty or does not contain valid JSON.');
        }

        if (empty($metadata->name)) {
            throw new PluginInstallerException('Plugin is not valid, the plugin.json file does not specify the plugin name.');
        }

        if (!preg_match('/^[a-zA-Z0-9_-]+$/', $metadata->name)) {
            throw new PluginInstallerException('The plugin name specified in plugin.json contains illegal characters. ' .
                'Plugin name can only contain following characters: [a-zA-Z0-9-_].');
        }

        if (empty($metadata->version)) {
            throw new PluginInstallerException('Plugin is not valid, the plugin.json file does not specify the plugin version.');
        }

        if (empty($metadata->description)) {
            throw new PluginInstallerException('Plugin is not valid, the plugin.json file does not specify a description.');
        }

        return $metadata;
    }

    private function getPathToPluginJson($tmpPluginFolder)
    {
        $firstSubFolder = $this->getNameOfFirstSubfolder($tmpPluginFolder);
        $path = $tmpPluginFolder . DIRECTORY_SEPARATOR . $firstSubFolder . DIRECTORY_SEPARATOR . 'plugin.json';

        return $path;
    }

    /**
     * @param $pluginDir
     * @throws PluginInstallerException
     * @return string
     */
    private function getNameOfFirstSubfolder($pluginDir)
    {
        if (!($dir = opendir($pluginDir))) {
            return false;
        }
        $firstSubFolder = '';

        while ($file = readdir($dir)) {
            if ($file[0] != '.' && is_dir($pluginDir . DIRECTORY_SEPARATOR . $file)) {
                $firstSubFolder = $file;
                break;
            }
        }

        if (empty($firstSubFolder)) {
            throw new PluginInstallerException('The plugin ZIP file does not contain a subfolder, but Piwik expects plugin files to be within a subfolder in the Zip archive.');
        }

        return $firstSubFolder;
    }

    private function fixPluginFolderIfNeeded($tmpPluginFolder)
    {
        $firstSubFolder = $this->getNameOfFirstSubfolder($tmpPluginFolder);

        if ($firstSubFolder === $this->pluginName) {
            return;
        }

        $from = $tmpPluginFolder . DIRECTORY_SEPARATOR . $firstSubFolder;
        $to = $tmpPluginFolder . DIRECTORY_SEPARATOR . $this->pluginName;
        rename($from, $to);
    }

    private function copyPluginToDestination($tmpPluginFolder)
    {
        $pluginsDir = Manager::getPluginsDirectory();

        if (!empty($GLOBALS['MATOMO_PLUGIN_COPY_DIR'])) {
            $pluginsDir = $GLOBALS['MATOMO_PLUGIN_COPY_DIR'];
        }
        $pluginTargetPath = $pluginsDir . $this->pluginName;

        $this->removeFolderIfExists($pluginTargetPath);

        Filesystem::copyRecursive($tmpPluginFolder, $pluginsDir);
    }

    /**
     * @param $pathExtracted
     */
    private function removeFolderIfExists($pathExtracted)
    {
        Filesystem::unlinkRecursive($pathExtracted, true);
    }

    /**
     * @param $targetTmpFile
     */
    private function removeFileIfExists($targetTmpFile)
    {
        Filesystem::deleteFileIfExists($targetTmpFile);
    }

    /**
     * @throws PluginInstallerException
     */
    private function makeSurePluginNameIsValid()
    {
        try {
            $pluginDetails = $this->marketplaceClient->getPluginInfo($this->pluginName);
        } catch (\Exception $e) {
            throw new PluginInstallerException($e->getMessage());
        }

        if (empty($pluginDetails)) {
            throw new PluginInstallerException('This plugin was not found in the Marketplace.');
        }
    }

    private function checkMarketplaceIsEnabled()
    {
        if (!isset($this->marketplaceClient)) {
            throw new PluginInstallerException('Marketplace plugin needs to be enabled to perform this action.');
        }
    }

    private function getEnvironment()
    {
        if ($this->marketplaceClient) {
            return $this->marketplaceClient->getEnvironment();
        } else {
            return StaticContainer::get(Environment::class);
        }
    }

}