File: CustomLogo.php

package info (click to toggle)
matomo 5.5.1%2Bdfsg-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 73,596 kB
  • sloc: php: 231,041; javascript: 102,286; python: 202; xml: 189; sh: 172; makefile: 20; sql: 10
file content (488 lines) | stat: -rw-r--r-- 14,393 bytes parent folder | download
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
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
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
<?php

/**
 * Matomo - free/libre analytics platform
 *
 * @link    https://matomo.org
 * @license https://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
 */

namespace Piwik\Plugins\CoreAdminHome;

use Piwik\Exception\DI\NotFoundException;
use Piwik\Config;
use Piwik\Container\StaticContainer;
use Piwik\Exception\Exception;
use Piwik\Filesystem;
use Piwik\Option;
use Piwik\Piwik;
use Piwik\Plugin\Manager;
use Piwik\SettingsPiwik;

class CustomLogo
{
    public const LOGO_HEIGHT = 300;
    public const LOGO_SMALL_HEIGHT = 100;
    public const FAVICON_HEIGHT = 32;

    public const FILENAME_LOGO = 'logo.png';
    public const FILENAME_LOGO_HEADER = 'logo-header.png';
    public const FILENAME_LOGO_SVG = 'logo.svg';
    public const FILENAME_FAVICON = 'favicon.png';

    public function getLogoUrl($pathOnly = false)
    {
        $defaultLogo = 'plugins/Morpheus/images/logo.png';
        $themeLogo = 'plugins/%s/images/logo.png';
        $userLogo = static::getPathUserLogo();
        return $this->getPathToLogo($pathOnly, $defaultLogo, $themeLogo, $userLogo);
    }

    public function getHeaderLogoUrl($pathOnly = false)
    {
        $defaultLogo = 'plugins/Morpheus/images/logo.svg';
        $themeLogo = 'plugins/%s/images/logo-header.png';
        $customLogo = static::getPathUserLogoSmall();
        return $this->getPathToLogo($pathOnly, $defaultLogo, $themeLogo, $customLogo);
    }

    public function getSVGLogoUrl($pathOnly = false)
    {
        $defaultLogo = 'plugins/Morpheus/images/logo.svg';
        $themeLogo = 'plugins/%s/images/logo.svg';
        $customLogo = static::getPathUserSvgLogo();
        $svg = $this->getPathToLogo($pathOnly, $defaultLogo, $themeLogo, $customLogo);
        return $svg;
    }

    public function isEnabled(): bool
    {
        return $this->isCustomLogoFeatureEnabled() && Option::get('branding_use_custom_logo');
    }

    public function enable()
    {
        Option::set('branding_use_custom_logo', '1', true);
    }

    public function disable()
    {
        Option::set('branding_use_custom_logo', '0', true);
    }

    public function hasSVGLogo()
    {
        if (!$this->isEnabled()) {
            /* We always have our application logo */
            return true;
        }

        if ($this->isEnabled() && static::logoExists(static::getPathUserSvgLogo())) {
            return true;
        }

        return false;
    }

    /**
     * @return bool
     */
    public function isFileUploadEnabled()
    {
        return ini_get('file_uploads') == 1;
    }

    public function isCustomLogoFeatureEnabled()
    {
        return Config::getInstance()->General['enable_custom_logo'] != 0;
    }

    /**
     * @return bool
     */
    public function isCustomLogoWritable()
    {
        if (Config::getInstance()->General['enable_custom_logo_check'] == 0) {
            return true;
        }
        $pathUserLogo = $this->getPathUserLogo();

        $directoryWritingTo = PIWIK_DOCUMENT_ROOT . '/' . dirname($pathUserLogo);

        // Create directory if not already created
        Filesystem::mkdir($directoryWritingTo);

        $directoryWritable = is_writable($directoryWritingTo);
        $logoFilesWriteable = is_writeable(PIWIK_DOCUMENT_ROOT . '/' . $pathUserLogo)
            && is_writeable(PIWIK_DOCUMENT_ROOT . '/' . $this->getPathUserSvgLogo())
            && is_writeable(PIWIK_DOCUMENT_ROOT . '/' . $this->getPathUserLogoSmall());

        $isCustomLogoWritable = ($logoFilesWriteable || $directoryWritable) && $this->isFileUploadEnabled();

        return $isCustomLogoWritable;
    }

    protected function getPathToLogo($pathOnly, $defaultLogo, $themeLogo, $customLogo)
    {
        $logo = $defaultLogo;

        $theme = \Piwik\Plugin\Manager::getInstance()->getThemeEnabled();
        if (!$theme) {
            $themeName = Manager::DEFAULT_THEME;
        } else {
            $themeName = $theme->getPluginName();
        }
        $themeLogo = sprintf($themeLogo, $themeName);

        if (static::logoExists($themeLogo)) {
            $logo = $themeLogo;
        }
        if ($this->isEnabled() && static::logoExists($customLogo)) {
            $logo = $customLogo;
        }

        if (!$pathOnly) {
            return SettingsPiwik::getPiwikUrl() . $logo;
        }

        return Filesystem::getPathToPiwikRoot() . '/' . $logo;
    }

    private static function getBasePath()
    {
        try {
            $basePath = StaticContainer::get('path.misc.user');
            return $basePath;
        } catch (NotFoundException $e) {
            // happens when upgrading from an older version which didn't have that global config entry yet
            // to a newer version of Matomo when this value is being requested while the update happens
            // basically request starts... the old global.php is loaded, then we update all PHP files, then after the
            // update within the same request a newer version of CustomLogo.php is loaded and they are not compatible.
            // In this case we return the default value
            return 'misc/user/';
        }
    }

    public static function getTempPathUserLogoUploads(): string
    {
        // use sha1 of the username to prevent usage of unsafe characters in the path
        $path = StaticContainer::get('path.tmp') . '/logos/' . sha1(Piwik::getCurrentUserLogin()) . '/';

        if (!is_dir($path)) {
            Filesystem::mkdir($path);
        }

        return $path;
    }

    public static function getPathUserLogo(): string
    {
        return static::rewritePath(self::getBasePath() . self::FILENAME_LOGO);
    }

    public static function getTempPathUserLogo(): string
    {
        return static::getTempPathUserLogoUploads()  . self::FILENAME_LOGO;
    }

    public static function getPathUserFavicon(): string
    {
        return static::rewritePath(self::getBasePath() . self::FILENAME_FAVICON);
    }

    public static function getTempPathUserFavicon(): string
    {
        return static::getTempPathUserLogoUploads()  . self::FILENAME_FAVICON;
    }

    public static function getPathUserSvgLogo(): string
    {
        return static::rewritePath(self::getBasePath() . self::FILENAME_LOGO_SVG);
    }

    public static function getPathUserLogoSmall(): string
    {
        return static::rewritePath(self::getBasePath() . self::FILENAME_LOGO_HEADER);
    }

    public static function getTempPathUserLogoSmall(): string
    {
        return static::getTempPathUserLogoUploads() . self::FILENAME_LOGO_HEADER;
    }

    protected static function rewritePath(string $path): string
    {
        return SettingsPiwik::rewriteMiscUserPathWithInstanceId($path);
    }

    public static function hasTempLogo(): bool
    {
        $logoTempPath = static::getTempPathUserLogo();
        $smallLogoTempPath = static::getTempPathUserLogoSmall();

        return (file_exists($logoTempPath) && file_exists($smallLogoTempPath));
    }

    public static function hasTempFavicon(): bool
    {
        $faviconTempPath = static::getTempPathUserFavicon();

        return file_exists($faviconTempPath);
    }

    /**
     * @return bool
     */
    public static function hasUserLogo()
    {
        return static::logoExists(static::getPathUserLogo());
    }

    /**
     * @return bool
     */
    public static function hasUserFavicon()
    {
        return static::logoExists(static::getPathUserFavicon());
    }

    private function postLogoChangeEvent($imagePath): void
    {
        $rootPath = Filesystem::getPathToPiwikRoot();
        $absolutePath = $rootPath . '/' . $imagePath;

        /**
         * Triggered when a user uploads a custom logo. This event is triggered for
         * the large logo, for the smaller logo-header.png file, and for the favicon.
         *
         * @param string $absolutePath The absolute path to the logo file on the Piwik server.
         */
        Piwik::postEvent('CoreAdminHome.customLogoChanged', [$absolutePath]);
    }

    public function uploadFaviconToTempFolder(): bool
    {
        $uploadFieldName = 'customFavicon';

        $faviconTempPath = static::getTempPathUserFavicon();

        return $this->uploadImage($uploadFieldName, self::FAVICON_HEIGHT, $faviconTempPath);
    }

    public function uploadLogoToTempFolder(): bool
    {
        $uploadFieldName = 'customLogo';

        $logoTempPath = static::getTempPathUserLogo();
        $smallLogoTempPath = static::getTempPathUserLogoSmall();

        $success = $this->uploadImage($uploadFieldName, self::LOGO_SMALL_HEIGHT, $smallLogoTempPath);
        if (!$success) {
            return false;
        }

        $success = $this->uploadImage($uploadFieldName, self::LOGO_HEIGHT, $logoTempPath);
        if (!$success) {
            return false;
        }

        return true;
    }

    /**
     * Publish logo and small logo from tmp folder to user folder
     *
     * @return bool
     */
    public function publishUserLogo(): bool
    {
        $logoTempPath = static::getTempPathUserLogo();
        $logoUserPath = static::getPathUserLogo();

        $smallLogoTempPath = static::getTempPathUserLogoSmall();
        $smallLogoUserPath = static::getPathUserLogoSmall();

        try {
            if (file_exists($logoTempPath) && file_exists($smallLogoTempPath)) {
                Filesystem::copy($logoTempPath, $logoUserPath);
                Filesystem::copy($smallLogoTempPath, $smallLogoUserPath);

                $this->postLogoChangeEvent($logoUserPath);
                $this->postLogoChangeEvent($smallLogoUserPath);

                // remove temp files
                Filesystem::remove($logoTempPath);
                Filesystem::remove($smallLogoTempPath);

                return true;
            }
        } catch (Exception $e) {
            // nop
        }

        return false;
    }

    /**
     * Publish favicon from tmp folder to user folder
     *
     * @return bool
     */
    public function publishUserFavicon(): bool
    {
        $faviconTempPath = static::getTempPathUserFavicon();
        $faviconUserPath = static::getPathUserFavicon();

        try {
            if (file_exists($faviconTempPath)) {
                Filesystem::copy($faviconTempPath, $faviconUserPath);

                $this->postLogoChangeEvent($faviconUserPath);

                // remove temp file
                Filesystem::remove($faviconTempPath);

                return true;
            }
        } catch (Exception $e) {
            // nop
        }

        return false;
    }

    /**
     * Remove any uploaded logos from tmp and user folders
     *
     * @return void
     */
    public function removeLogos(): void
    {
        static::removePublishedLogos();
        static::removeLogosFromTempFolder();
    }

    /**
     * Remove publicly accessible logos and favicons from the misc/user folder
     *
     * @return void
     */
    public function removePublishedLogos(): void
    {
        $logoUserPath = static::getPathUserLogo();
        $smallLogoUserPath = static::getPathUserLogoSmall();
        $faviconUserPath = static::getPathUserFavicon();

        Filesystem::deleteFileIfExists($logoUserPath);
        Filesystem::deleteFileIfExists($smallLogoUserPath);
        Filesystem::deleteFileIfExists($faviconUserPath);
    }

    /**
     * Remove all uploaded logos and favicons from the temp folder
     *
     * @return void
     */
    public function removeLogosFromTempFolder(): void
    {
        $logosUploadTempFolder = static::getTempPathUserLogoUploads();
        Filesystem::unlinkRecursive($logosUploadTempFolder, true);
    }

    /**
     * Process logo/favicon uploads from the request and store in a given path
     * @param $uploadFieldName
     * @param $targetHeight
     * @param $path
     * @return bool
     */
    private function uploadImage($uploadFieldName, $targetHeight, $path): bool
    {
        if (
            empty($_FILES[$uploadFieldName])
            || !empty($_FILES[$uploadFieldName]['error'])
        ) {
            return false;
        }

        $file = $_FILES[$uploadFieldName]['tmp_name'];
        if (!file_exists($file)) {
            return false;
        }

        list($width, $height) = getimagesize($file);
        switch ($_FILES[$uploadFieldName]['type']) {
            case 'image/jpeg':
                $image = @imagecreatefromjpeg($file);
                break;
            case 'image/png':
                $image = @imagecreatefrompng($file);
                break;
            case 'image/gif':
                $image = @imagecreatefromgif($file);
                break;
            default:
                return false;
        }

        // @phpstan-ignore class.notFound
        if (!is_resource($image) && !($image instanceof \GdImage)) {
            return false;
        }

        $targetWidth = round($width * $targetHeight / $height);

        $newImage = imagecreatetruecolor($targetWidth, $targetHeight);

        if ($_FILES[$uploadFieldName]['type'] == 'image/png') {
            imagealphablending($newImage, false);
            imagesavealpha($newImage, true);
        }

        $backgroundColor = imagecolorallocate($newImage, 0, 0, 0);
        imagecolortransparent($newImage, $backgroundColor);

        imagecopyresampled($newImage, $image, 0, 0, 0, 0, $targetWidth, $targetHeight, $width, $height);
        return imagepng($newImage, $path, 3);
    }

    /**
     * @return bool
     */
    private static function logoExists($relativePath)
    {
        return file_exists(Filesystem::getPathToPiwikRoot() . '/' . $relativePath);
    }

    /**
     * If tmp logo exists, return it as base64 encoded string for preview in branding settings
     *
     * @return string|null
     */
    public function getTempUserLogoBase64(): ?string
    {
        $img = static::getTempPathUserLogo();

        if (file_exists($img)) {
            return base64_encode(file_get_contents($img));
        }

        return null;
    }

    /**
     * If tmp favicon exists, return it as base64 encoded string for preview in branding settings
     *
     * @return string|null
     */
    public function getTempUserFaviconBase64(): ?string
    {
        $img = static::getTempPathUserFavicon();

        if (file_exists($img)) {
            return base64_encode(file_get_contents($img));
        }

        return null;
    }
}