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

GeneratePluginBase.php « Commands « CoreConsole « plugins - github.com/matomo-org/matomo.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 38f53b4d1b6eda62e8c9a91e92229744a2bfbcc3 (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
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
<?php
/**
 * Piwik - free/libre analytics platform
 *
 * @link http://piwik.org
 * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
 *
 */

namespace Piwik\Plugins\CoreConsole\Commands;

use Piwik\Common;
use Piwik\Development;
use Piwik\Filesystem;
use Piwik\Plugin\ConsoleCommand;
use Piwik\Plugin\Dependency;
use Piwik\Version;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

abstract class GeneratePluginBase extends ConsoleCommand
{
    public function isEnabled()
    {
        return Development::isEnabled();
    }

    public function getPluginPath($pluginName)
    {
        return PIWIK_INCLUDE_PATH . $this->getRelativePluginPath($pluginName);
    }

    private function getRelativePluginPath($pluginName)
    {
        return '/plugins/' . $pluginName;
    }

    private function createFolderWithinPluginIfNotExists($pluginNameOrCore, $folder)
    {
        if ($pluginNameOrCore === 'core') {
            $pluginPath = $this->getPathToCore();
        } else {
            $pluginPath = $this->getPluginPath($pluginNameOrCore);
        }

        if (!file_exists($pluginPath . $folder)) {
            Filesystem::mkdir($pluginPath . $folder);
        }
    }

    protected function createFileWithinPluginIfNotExists($pluginNameOrCore, $fileName, $content)
    {
        if ($pluginNameOrCore === 'core') {
            $pluginPath = $this->getPathToCore();
        } else {
            $pluginPath = $this->getPluginPath($pluginNameOrCore);
        }

        if (!file_exists($pluginPath . $fileName)) {
            file_put_contents($pluginPath . $fileName, $content);
        }
    }

    /**
     * Creates a lang/en.json within the plugin in case it does not exist yet and adds a translation for the given
     * text.
     *
     * @param $pluginName
     * @param $translatedText
     * @return string  Either the generated translation key or the original text if a different translation for this
     *                 generated translation key already exists.
     */
    protected function makeTranslationIfPossible($pluginName, $translatedText)
    {
        $defaultLang = array($pluginName => array());

        $this->createFolderWithinPluginIfNotExists($pluginName, '/lang');
        $this->createFileWithinPluginIfNotExists($pluginName, '/lang/en.json', $this->toJson($defaultLang));

        $langJsonPath = $this->getPluginPath($pluginName) . '/lang/en.json';
        $translations = file_get_contents($langJsonPath);
        $translations = json_decode($translations, true);

        if (empty($translations[$pluginName])) {
            $translations[$pluginName] = array();
        }

        $key = $this->buildTranslationKey($translatedText);

        if (array_key_exists($key, $translations[$pluginName])) {
            // we do not want to overwrite any existing translations
            if ($translations[$pluginName][$key] === $translatedText) {
                return $pluginName . '_' . $key;
            }

            return $translatedText;
        }

        $translations[$pluginName][$key] = $this->removeNonJsonCompatibleCharacters($translatedText);

        file_put_contents($langJsonPath, $this->toJson($translations));

        return $pluginName . '_' . $key;
    }

    protected function checkAndUpdateRequiredPiwikVersion($pluginName, OutputInterface $output)
    {
        $pluginJsonPath     = $this->getPluginPath($pluginName) . '/plugin.json';
        $relativePluginJson = $this->getRelativePluginPath($pluginName) . '/plugin.json';

        if (!file_exists($pluginJsonPath) || !is_writable($pluginJsonPath)) {
            return;
        }

        $pluginJson = file_get_contents($pluginJsonPath);
        $pluginJson = json_decode($pluginJson, true);

        if (empty($pluginJson)) {
            return;
        }

        if (empty($pluginJson['require'])) {
            $pluginJson['require'] = array();
        }

        $piwikVersion     = Version::VERSION;
        $nextMajorVersion = (int) substr($piwikVersion, 0, strpos($piwikVersion, '.')) + 1;
        $secondPartPiwikVersionRequire = ',<' . $nextMajorVersion . '.0.0-b1';
        if (false === strpos($piwikVersion, '-')) {
            // see https://github.com/composer/composer/issues/4080 we need to specify -stable otherwise it would match
            // $piwikVersion-dev meaning it would also match all pre-released. However, we only want to match a stable
            // release
            $piwikVersion.= '-stable';
        }

        $newRequiredVersion = sprintf('>=%s,<%d.0.0', $piwikVersion, $nextMajorVersion);


        if (!empty($pluginJson['require']['piwik'])) {
            $requiredVersion = trim($pluginJson['require']['piwik']);

            if ($requiredVersion === $newRequiredVersion) {
                // there is nothing to updated
                return;
            }

            // our generated versions look like ">=2.25.4,<3.0.0-b1".
            // We only updated the Piwik version in the first part if the piwik version looks like that or if it has only
            // one piwik version defined. In all other cases, eg user uses || etc we do not update it as user has customized
            // the piwik version.

            foreach (['<>','!=', '<=','==', '^'] as $comparison) {
                if (strpos($requiredVersion, $comparison) === 0) {
                    // user is using custom piwik version require, we do not overwrite anything.
                    return;
                }
            }

            if (strpos($requiredVersion, '||') !== false || strpos($requiredVersion, ' ') !== false) {
                // user is using custom piwik version require, we do not overwrite anything.
                return;
            }

            $requiredPiwikVersions = explode(',', (string) $requiredVersion);
            $numRequiredPiwikVersions = count($requiredPiwikVersions);

            if ($numRequiredPiwikVersions > 2) {
                // user is using custom piwik version require, we do not overwrite anything.
                return;
            }

            if ($numRequiredPiwikVersions === 2 &&
                !Common::stringEndsWith($requiredVersion, $secondPartPiwikVersionRequire)) {
                // user is using custom piwik version require, we do not overwrite anything
                return;
            }

            // if only one piwik version is defined we update it to make sure it does now specify an upper version limit

            $dependency     = new Dependency();
            $missingVersion = $dependency->getMissingVersions($piwikVersion, $requiredVersion);

            if (!empty($missingVersion)) {
                $msg = sprintf('We cannot generate this component as the plugin "%s" requires the Piwik version "%s" in the file "%s". Generating this component requires "%s". If you know your plugin is compatible with your Piwik version remove the required Piwik version in "%s" and try to execute this command again.', $pluginName, $requiredVersion, $relativePluginJson, $newRequiredVersion, $relativePluginJson);

                throw new \Exception($msg);
            }

            $output->writeln('');
            $output->writeln(sprintf('<comment>We have updated the required Piwik version from "%s" to "%s" in "%s".</comment>', $requiredVersion, $newRequiredVersion, $relativePluginJson));
        } else {
            $output->writeln('');
            $output->writeln(sprintf('<comment>We have updated your "%s" to require the Piwik version "%s".</comment>', $relativePluginJson, $newRequiredVersion));
        }

        $pluginJson['require']['piwik'] = $newRequiredVersion;
        file_put_contents($pluginJsonPath, $this->toJson($pluginJson));
    }

    private function toJson($value)
    {
        if (defined('JSON_PRETTY_PRINT')) {

            return json_encode($value, JSON_PRETTY_PRINT);
        }

        return json_encode($value);
    }

    private function buildTranslationKey($translatedText)
    {
        $translatedText = preg_replace('/(\s+)/', '', $translatedText);
        $translatedText = preg_replace("/[^A-Za-z0-9]/", '', $translatedText);
        $translatedText = trim($translatedText);

        return $this->removeNonJsonCompatibleCharacters($translatedText);
    }

    private function removeNonJsonCompatibleCharacters($text)
    {
        return preg_replace('/[^(\x00-\x7F)]*/', '', $text);
    }

    /**
     * Copies the given method and all needed use statements into an existing class. The target class name will be
     * built based on the given $replace argument.
     * @param string $sourceClassName
     * @param string $methodName
     * @param array $replace
     */
    protected function copyTemplateMethodToExisitingClass($sourceClassName, $methodName, $replace)
    {
        $targetClassName = $this->replaceContent($replace, $sourceClassName);

        if (Development::methodExists($targetClassName, $methodName)) {
            // we do not want to add the same method twice
            return;
        }

        Development::checkMethodExists($sourceClassName, $methodName, 'Cannot copy template method: ');

        $targetClass = new \ReflectionClass($targetClassName);
        $file        = new \SplFileObject($targetClass->getFileName());

        $methodCode = Development::getMethodSourceCode($sourceClassName, $methodName);
        $methodCode = $this->replaceContent($replace, $methodCode);
        $methodLine = $targetClass->getEndLine() - 1;

        $sourceUses = Development::getUseStatements($sourceClassName);
        $targetUses = Development::getUseStatements($targetClassName);
        $usesToAdd  = array_diff($sourceUses, $targetUses);
        if (empty($usesToAdd)) {
            $useCode = '';
        } else {
            $useCode = "\nuse " . implode("\nuse ", $usesToAdd) . "\n";
        }

        // search for namespace line before the class starts
        $useLine = 0;
        foreach (new \LimitIterator($file, 0, $targetClass->getStartLine()) as $index => $line) {
            if (0 === strpos(trim($line), 'namespace ')) {
                $useLine = $index + 1;
                break;
            }
        }

        $newClassCode = '';
        foreach(new \LimitIterator($file) as $index => $line) {
            if ($index == $methodLine) {
                $newClassCode .= $methodCode;
            }

            if (0 !== $useLine && $index == $useLine) {
                $newClassCode .= $useCode;
            }

            $newClassCode .= $line;
        }

        file_put_contents($targetClass->getFileName(), $newClassCode);
    }

    /**
     * @param string $templateFolder  full path like /home/...
     * @param string $pluginName
     * @param array $replace         array(key => value) $key will be replaced by $value in all templates
     * @param array $whitelistFiles  If not empty, only given files/directories will be copied.
     *                               For instance array('/Controller.php', '/templates', '/templates/index.twig')
     */
    protected function copyTemplateToPlugin($templateFolder, $pluginName, array $replace = array(), $whitelistFiles = array())
    {
        $replace['PLUGINNAME'] = $pluginName;

        $files = array_merge(
                Filesystem::globr($templateFolder, '*'),
                // Also copy files starting with . such as .gitignore
                Filesystem::globr($templateFolder, '.*')
        );

        foreach ($files as $file) {
            $fileNamePlugin = str_replace($templateFolder, '', $file);

            if (!empty($whitelistFiles) && !in_array($fileNamePlugin, $whitelistFiles)) {
                continue;
            }

            if (is_dir($file)) {
                $fileNamePlugin = $this->replaceContent($replace, $fileNamePlugin);
                $this->createFolderWithinPluginIfNotExists($pluginName, $fileNamePlugin);
            } else {
                $template = file_get_contents($file);
                $template = $this->replaceContent($replace, $template);

                $fileNamePlugin = $this->replaceContent($replace, $fileNamePlugin);

                $this->createFileWithinPluginIfNotExists($pluginName, $fileNamePlugin, $template);
            }

        }
    }

    protected function getPluginNames()
    {
        $pluginDirs = \_glob(PIWIK_INCLUDE_PATH . '/plugins/*', GLOB_ONLYDIR);

        $pluginNames = array();
        foreach ($pluginDirs as $pluginDir) {
            $pluginNames[] = basename($pluginDir);
        }

        return $pluginNames;
    }

    protected function getPluginNamesHavingNotSpecificFile($filename)
    {
        $pluginDirs = \_glob(PIWIK_INCLUDE_PATH . '/plugins/*', GLOB_ONLYDIR);

        $pluginNames = array();
        foreach ($pluginDirs as $pluginDir) {
            if (!file_exists($pluginDir . '/' . $filename)) {
                $pluginNames[] = basename($pluginDir);
            }
        }

        return $pluginNames;
    }

    /**
     * @param InputInterface $input
     * @param OutputInterface $output
     * @return array
     * @throws \RuntimeException
     */
    protected function askPluginNameAndValidate(InputInterface $input, OutputInterface $output, $pluginNames, $invalidArgumentException)
    {
        $validate = function ($pluginName) use ($pluginNames, $invalidArgumentException) {
            if (!in_array($pluginName, $pluginNames)) {
                throw new \InvalidArgumentException($invalidArgumentException);
            }

            return $pluginName;
        };

        $pluginName = $input->getOption('pluginname');

        if (empty($pluginName)) {
            $dialog = $this->getHelperSet()->get('dialog');
            $pluginName = $dialog->askAndValidate($output, 'Enter the name of your plugin: ', $validate, false, null, $pluginNames);
        } else {
            $validate($pluginName);
        }

        return $pluginName;
    }

    private function getPathToCore()
    {
        $path = PIWIK_INCLUDE_PATH . '/core';
        return $path;
    }

    private function replaceContent($replace, $contentToReplace)
    {
        foreach ((array) $replace as $key => $value) {
            $contentToReplace = str_replace($key, $value, $contentToReplace);
        }

        return $contentToReplace;
    }

}