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
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
<?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\tests\Integration;

use Piwik\Changes\Model as ChangesModel;
use Piwik\Common;
use Piwik\Config;
use Piwik\Db;
use Piwik\Exception\UnexpectedWebsiteFoundException;
use Piwik\Plugins\CoreAdminHome\CoreAdminHome;
use Piwik\Plugins\CoreAdminHome\Controller;
use Piwik\Plugins\CoreAdminHome\OptOutManager;
use Piwik\Piwik;
use Piwik\Plugins\Login\PasswordVerifier;
use Piwik\Plugins\UsersManager\API as UsersManagerAPI;
use Piwik\Tests\Framework\Fixture;
use Piwik\Tests\Framework\Mock\FakeAccess;
use Piwik\Tests\Framework\TestCase\IntegrationTestCase;
use Piwik\Translation\Loader\DevelopmentLoader;
use Piwik\Translation\Loader\JsonFileLoader;
use Piwik\Translation\Translator;

/**
 * @group CoreAdminHome
 * @group ControllerTest
 * @group Plugins
 */
class ControllerTest extends IntegrationTestCase
{
    /** @var Controller */
    private $controller;
    /** @var array */
    private $backupGet;
    /** @var array */
    private $backupPost;
    /** @var array */
    private $backupRequest;
    /** @var array */
    private $backupServer;
    /** @var array */
    private $backupMail;
    /** @var array */
    private $backupGeneral;
    /** @var bool */
    private $mailSettingsSaved = false;

    public function setUp(): void
    {
        parent::setUp();

        $this->backupGet = $_GET;
        $this->backupPost = $_POST;
        $this->backupRequest = $_REQUEST;
        $this->backupServer = $_SERVER;
        $this->backupMail = Config::getInstance()->mail;
        $this->backupGeneral = Config::getInstance()->General;

        Fixture::createSuperUser();
        if (!Fixture::siteCreated(1)) {
            Fixture::createWebsite('2012-01-01 00:00:00');
        }
        FakeAccess::clearAccess(
            $superUser = true,
            $idSitesAdmin = [1],
            $idSitesView = [1],
            $identity = 'superUserLogin'
        );
        Fixture::resetTranslations();
        Fixture::loadAllTranslations();
        if (!Fixture::siteCreated(2)) {
            Fixture::createWebsite('2012-01-02 00:00:00');
        }
        $_GET = ['idSite' => 1, 'period' => 'day', 'date' => 'today'];
        $_REQUEST = $_GET;

        UsersManagerAPI::getInstance()->setUserPreference(
            'superUserLogin',
            UsersManagerAPI::PREFERENCE_DEFAULT_REPORT,
            2
        );

        $this->controller = new Controller(
            new Translator(new DevelopmentLoader(new JsonFileLoader())),
            new OptOutManager(),
            new PasswordVerifier()
        );
    }

    public function testSetMailSettingsRejectsGetRequests(): void
    {
        $_SERVER['REQUEST_METHOD'] = 'GET';
        $_GET = $this->getMailSettingsRequest('get.example.test');
        $_POST = [];
        $_REQUEST = $_GET;

        $this->expectException(\Exception::class);
        $this->expectExceptionMessage('Invalid HTTP method.');

        $this->controller->setMailSettings();
    }

    public function testSetMailSettingsUsesPostParametersOnly(): void
    {
        $_SERVER['REQUEST_METHOD'] = 'POST';
        $_GET = $this->getMailSettingsRequest('get.example.test');
        $_POST = $this->getMailSettingsRequest('post.example.test');
        $_REQUEST = $_GET + $_POST;

        $controller = $this->getControllerSkippingTokenCheck();

        $controller->setMailSettings();
        $this->mailSettingsSaved = true;

        $this->assertSame('post.example.test', Config::getInstance()->mail['host']);
        $this->assertSame('smtp-user-post', Config::getInstance()->mail['username']);
        $this->assertSame('smtp-password-post', Config::getInstance()->mail['password']);
        $this->assertSame('mail-post@example.test', Config::getInstance()->General['noreply_email_address']);
        $this->assertSame('Acme <Team> & "post"', Config::getInstance()->General['noreply_email_name']);
    }

    public function testSetMailSettingsRejectsIncorrectPasswordConfirmation(): void
    {
        $originalHost = Config::getInstance()->mail['host'];

        $_SERVER['REQUEST_METHOD'] = 'POST';
        $_POST = $this->getMailSettingsRequest('reject.example.test');
        $_REQUEST = $_POST;

        $controller = $this->getControllerSkippingTokenCheck($passwordCorrect = false);

        $response = $controller->setMailSettings();

        $this->assertStringContainsString(Piwik::translate('UsersManager_CurrentPasswordNotCorrect'), $response);
        // nothing must have been persisted
        $this->assertSame($originalHost, Config::getInstance()->mail['host']);
    }

    public function testSetMailSettingsRejectsMissingPasswordConfirmation(): void
    {
        $originalHost = Config::getInstance()->mail['host'];

        $_SERVER['REQUEST_METHOD'] = 'POST';
        $request = $this->getMailSettingsRequest('reject.example.test');
        unset($request['passwordConfirmation']);
        $_POST = $request;
        $_REQUEST = $_POST;

        $controller = $this->getControllerSkippingTokenCheck();

        $response = $controller->setMailSettings();

        $this->assertStringContainsString(Piwik::translate('UsersManager_CurrentPasswordNotCorrect'), $response);
        // nothing must have been persisted
        $this->assertSame($originalHost, Config::getInstance()->mail['host']);
    }

    public function testWhatIsNewDoesNotPrefixBundledPluginsAndPrefixesThirdPartyPlugins(): void
    {
        $this->deleteAllChanges();

        $changesModel = new ChangesModel();
        $changesModel->addChange('CoreHome', [
            'version' => '1.0.0',
            'title' => 'Core bundled change',
            'description' => 'Core bundled description',
        ]);
        $changesModel->addChange('ProfessionalServices', [
            'version' => '1.0.0',
            'title' => 'Professional services bundled change',
            'description' => 'Professional services bundled description',
        ]);
        $changesModel->addChange('ThirdPartyPlugin', [
            'version' => '1.0.0',
            'title' => 'Third party change',
            'description' => 'Third party description',
        ]);

        $html = $this->controller->whatIsNew();

        $this->assertStringContainsString('>Core bundled change<', $html);
        $this->assertStringContainsString('>Professional services bundled change<', $html);
        $this->assertStringContainsString('>ThirdPartyPlugin - Third party change<', $html);

        $this->assertStringNotContainsString('>CoreHome - Core bundled change<', $html);
        $this->assertStringNotContainsString('>ProfessionalServices - Professional services bundled change<', $html);
    }

    public function testModifyErrorPageReplacesInvalidWebsiteMessage(): void
    {
        $_GET = ['idSite' => '999', 'period' => 'day', 'date' => 'today'];
        $_REQUEST = $_GET;

        $output = Piwik_GetErrorMessagePage(
            'Original message',
            false,
            true,
            true,
            'custom-logo.svg',
            'custom-favicon.png',
            false,
            '',
            false,
            'https://example.test/redirect',
            5
        );
        $plugin = new CoreAdminHome();
        $plugin->onModifyErrorPage(
            $output,
            new UnexpectedWebsiteFoundException("The requested website id = 999 couldn't be found")
        );

        $this->assertStringContainsString('This URL is not valid. The content may have been moved, deleted, or is no longer available', $output);
        $this->assertStringContainsString("website id was set to '999' on the URL", $output);
        $this->assertStringContainsString('Please go back to your previous page', $output);
        $this->assertStringContainsString('return to your dashboard', $output);
        $this->assertStringNotContainsString('Original message', $output);
        $this->assertStringContainsString('custom-logo.svg', $output);
        $this->assertStringContainsString('custom-favicon.png', $output);
        $this->assertStringContainsString('https://example.test/redirect', $output);
        $this->assertStringContainsString('setTimeout(function(){window.location.href="https://example.test/redirect"}', $output);
    }

    public function testModifyErrorPageDoesNotReplaceOtherUnexpectedWebsiteExceptions(): void
    {
        $_GET = ['idSite' => '1', 'period' => 'day', 'date' => 'today'];
        $_REQUEST = $_GET;

        $output = Piwik_GetErrorMessagePage('Original message', false, true, true, false, false, false, '', false);
        $plugin = new CoreAdminHome();
        $plugin->onModifyErrorPage(
            $output,
            new UnexpectedWebsiteFoundException("The requested website id = 999 couldn't be found")
        );

        $this->assertStringContainsString('Original message', $output);
        $this->assertStringNotContainsString('This URL is not valid. The content may have been moved, deleted, or is no longer available', $output);
    }

    public function testWhatIsNewRewritesInternalLinksToDefaultReportIdSite(): void
    {
        $this->deleteAllChanges();

        $changesModel = new ChangesModel();
        $changesModel->addChange('UsersManager', [
            'version' => '1.0.0',
            'title' => 'Settings change',
            'description' => 'Description',
            'link_name' => 'Open settings',
            'link' => 'index.php?module=UsersManager&action=userSettings&idSite=1',
        ]);
        $changesModel->addChange('SegmentEditor', [
            'version' => '1.0.0',
            'title' => 'Segment change',
            'description' => 'Description',
            'link_name' => 'Open segments',
            'link' => '/index.php?module=CoreHome&action=index&idSite=1#?idSite=1&category=General_Visitors',
        ]);

        $html = $this->controller->whatIsNew();

        $this->assertStringContainsString('index.php?module=UsersManager&amp;action=userSettings&amp;idSite=2', $html);
        $this->assertStringContainsString('index.php?module=CoreHome&amp;action=index&amp;idSite=2#?idSite=2&amp;category=General_Visitors', $html);
        $this->assertStringNotContainsString('href="/index.php?', $html);
        $this->assertStringNotContainsString('idSite=1', $html);
    }

    public function testWhatIsNewLeavesExternalLinksUnchanged(): void
    {
        $this->deleteAllChanges();

        $changesModel = new ChangesModel();
        $changesModel->addChange('PrivacyManager', [
            'version' => '1.0.0',
            'title' => 'External change',
            'description' => 'Description',
            'link_name' => 'Open docs',
            'link' => 'https://matomo.org/blog/2022/09/improvements-to-matomo-opt-out-form-feature/',
        ]);

        $html = $this->controller->whatIsNew();

        $this->assertStringContainsString(
            'https://matomo.org/blog/2022/09/improvements-to-matomo-opt-out-form-feature/',
            $html
        );
    }

    public function testWhatIsNewFallsBackToDefaultWebsiteIdWhenDefaultReportIsMultiSites(): void
    {
        $this->deleteAllChanges();

        UsersManagerAPI::getInstance()->setUserPreference(
            'superUserLogin',
            UsersManagerAPI::PREFERENCE_DEFAULT_REPORT,
            'MultiSites'
        );

        $changesModel = new ChangesModel();
        $changesModel->addChange('UsersManager', [
            'version' => '1.0.0',
            'title' => 'Settings change',
            'description' => 'Description',
            'link_name' => 'Open settings',
            'link' => 'index.php?module=UsersManager&action=userSettings&idSite=99',
        ]);

        $html = $this->controller->whatIsNew();

        $this->assertStringContainsString('index.php?module=UsersManager&amp;action=userSettings&amp;idSite=1', $html);
    }

    public function testWhatIsNewLeavesInternalLinksUnchangedWhenNoDefaultIdSiteIsAvailable(): void
    {
        FakeAccess::clearAccess(
            $superUser = false,
            $idSitesAdmin = [],
            $idSitesView = [],
            $identity = 'superUserLogin'
        );

        UsersManagerAPI::getInstance()->setUserPreference(
            'superUserLogin',
            UsersManagerAPI::PREFERENCE_DEFAULT_REPORT,
            'MultiSites'
        );

        $changes = [[
            'plugin_name' => 'UsersManager',
            'version' => '1.0.0',
            'title' => 'Settings change',
            'description' => 'Description',
            'link_name' => 'Open settings',
            'link' => 'index.php?module=UsersManager&action=userSettings&idSite=99',
        ]];

        $changes = $this->callEnrichChangesForWhatIsNew($changes);

        $this->assertSame(
            'index.php?module=UsersManager&action=userSettings&idSite=99',
            $changes[0]['link']
        );
    }

    public function tearDown(): void
    {
        $this->deleteAllChanges();
        $_GET = $this->backupGet;
        $_POST = $this->backupPost;
        $_REQUEST = $this->backupRequest;
        $_SERVER = $this->backupServer;
        Config::getInstance()->mail = $this->backupMail;
        Config::getInstance()->General = $this->backupGeneral;
        if ($this->mailSettingsSaved) {
            Config::getInstance()->forceSave();
        }
        parent::tearDown();
    }

    public function provideContainerConfig()
    {
        return [
            'Piwik\Access' => new FakeAccess(),
            'test.vars.loadChanges' => true,
        ];
    }

    private function deleteAllChanges(): void
    {
        Db::query('DELETE FROM `' . Common::prefixTable('changes') . '`');
    }

    private function callEnrichChangesForWhatIsNew(array $changes): array
    {
        $method = new \ReflectionMethod($this->controller, 'enrichChangesForWhatIsNew');
        $method->setAccessible(true);

        return $method->invoke($this->controller, $changes);
    }

    private function getControllerSkippingTokenCheck(bool $passwordCorrect = true): Controller
    {
        $controller = $this->getMockBuilder(Controller::class)
            ->disableOriginalConstructor()
            ->onlyMethods(['checkTokenInUrl'])
            ->getMock();

        $controller->expects($this->once())
            ->method('checkTokenInUrl');

        $passwordVerify = $this->createMock(PasswordVerifier::class);
        $passwordVerify->method('isPasswordCorrect')->willReturn($passwordCorrect);

        $property = new \ReflectionProperty(Controller::class, 'passwordVerify');
        $property->setAccessible(true);
        $property->setValue($controller, $passwordVerify);

        return $controller;
    }

    private function getMailSettingsRequest(string $mailHost): array
    {
        $hostPrefix = explode('.', $mailHost)[0];

        return [
            'mailUseSmtp' => '1',
            'mailPort' => '25',
            'mailHost' => $mailHost,
            'mailType' => '',
            'mailUsername' => 'smtp-user-' . $hostPrefix,
            'mailPassword' => 'smtp-password-' . $hostPrefix,
            'mailEncryption' => 'none',
            'mailFromAddress' => 'mail-' . $hostPrefix . '@example.test',
            'mailFromName' => 'Acme <Team> & "' . $hostPrefix . '"',
            'passwordConfirmation' => 'super-user-password',
        ];
    }
}