Passed
Push — develop ( 23539e...9d4d3e )
by Andrew
12:19
created

Redirects::getAllRegExRedirects()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 13
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 5
c 1
b 0
f 0
dl 0
loc 13
ccs 0
cts 6
cp 0
rs 10
cc 2
nc 2
nop 2
crap 6
1
<?php
2
/**
3
 * Retour plugin for Craft CMS 3.x
4
 *
5
 * Retour allows you to intelligently redirect legacy URLs, so that you don't
6
 * lose SEO value when rebuilding & restructuring a website
7
 *
8
 * @link      https://nystudio107.com/
0 ignored issues
show
Coding Style introduced by
The tag in position 1 should be the @copyright tag
Loading history...
9
 * @copyright Copyright (c) 2018 nystudio107
0 ignored issues
show
Coding Style introduced by
@copyright tag must contain a year and the name of the copyright holder
Loading history...
10
 */
0 ignored issues
show
Coding Style introduced by
PHP version not specified
Loading history...
Coding Style introduced by
Missing @category tag in file comment
Loading history...
Coding Style introduced by
Missing @package tag in file comment
Loading history...
Coding Style introduced by
Missing @author tag in file comment
Loading history...
Coding Style introduced by
Missing @license tag in file comment
Loading history...
11
12
namespace nystudio107\retour\services;
13
14
use craft\base\ElementInterface;
15
use nystudio107\retour\Retour;
16
use nystudio107\retour\events\RedirectEvent;
17
use nystudio107\retour\events\ResolveRedirectEvent;
18
use nystudio107\retour\events\RedirectResolvedEvent;
19
use nystudio107\retour\helpers\UrlHelper;
20
use nystudio107\retour\models\StaticRedirects as StaticRedirectsModel;
21
22
use Craft;
23
use craft\base\Component;
24
use craft\base\Plugin;
25
use craft\db\Query;
26
use craft\errors\SiteNotFoundException;
27
use craft\helpers\Db;
28
29
use yii\base\ExitException;
30
use yii\base\InvalidConfigException;
31
use yii\base\InvalidRouteException;
32
use yii\caching\TagDependency;
33
use yii\db\Exception;
34
35
/** @noinspection MissingPropertyAnnotationsInspection */
0 ignored issues
show
Coding Style introduced by
The open comment tag must be the only content on the line
Loading history...
Coding Style introduced by
Missing short description in doc comment
Loading history...
Coding Style introduced by
The close comment tag must be the only content on the line
Loading history...
36
37
/**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
38
 * @author    nystudio107
0 ignored issues
show
Coding Style introduced by
The tag in position 1 should be the @package tag
Loading history...
Coding Style introduced by
Content of the @author tag must be in the form "Display Name <[email protected]>"
Loading history...
Coding Style introduced by
Tag value for @author tag indented incorrectly; expected 2 spaces but found 4
Loading history...
39
 * @package   Retour
0 ignored issues
show
Coding Style introduced by
Tag value for @package tag indented incorrectly; expected 1 spaces but found 3
Loading history...
40
 * @since     3.0.0
0 ignored issues
show
Coding Style introduced by
The tag in position 3 should be the @author tag
Loading history...
Coding Style introduced by
Tag value for @since tag indented incorrectly; expected 3 spaces but found 5
Loading history...
41
 */
0 ignored issues
show
Coding Style introduced by
Missing @category tag in class comment
Loading history...
Coding Style introduced by
Missing @license tag in class comment
Loading history...
Coding Style introduced by
Missing @link tag in class comment
Loading history...
42
class Redirects extends Component
43
{
44
    // Constants
45
    // =========================================================================
46
47
    const CACHE_KEY = 'retour_redirect_';
48
49
    const GLOBAL_REDIRECTS_CACHE_TAG = 'retour_redirects';
50
51
    const EVENT_REDIRECT_ID = 0;
52
53
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
54
     * @event RedirectEvent The event that is triggered before the redirect is saved
55
     * You may set [[RedirectEvent::isValid]] to `false` to prevent the redirect from getting saved.
56
     *
57
     * ```php
58
     * use nystudio107\retour\services\Redirects;
59
     * use nystudio107\retour\events\RedirectEvent;
60
     *
61
     * Event::on(Redirects::class,
62
     *     Redirects::EVENT_BEFORE_SAVE_REDIRECT,
63
     *     function(RedirectEvent $event) {
64
     *         // potentially set $event->isValid;
65
     *     }
66
     * );
67
     * ```
68
     */
69
    const EVENT_BEFORE_SAVE_REDIRECT = 'beforeSaveRedirect';
70
71
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
72
     * @event RedirectEvent The event that is triggered after the redirect is saved
73
     *
74
     * ```php
75
     * use nystudio107\retour\services\Redirects;
76
     * use nystudio107\retour\events\RedirectEvent;
77
     *
78
     * Event::on(Redirects::class,
79
     *     Redirects::EVENT_AFTER_SAVE_REDIRECT,
80
     *     function(RedirectEvent $event) {
81
     *         // the redirect was saved
82
     *     }
83
     * );
84
     * ```
85
     */
86
    const EVENT_AFTER_SAVE_REDIRECT = 'afterSaveRedirect';
87
88
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
89
     * @event ResolveRedirectEvent The event that is triggered before Retour has attempted
90
     *        to resolve redirects. You may set [[ResolveRedirectEvent::redirectDestUrl]] to
91
     *        to the URL that it should redirect to, or null if no redirect should happen
92
     *
93
     * ```php
94
     * use nystudio107\retour\services\Redirects;
95
     * use nystudio107\retour\events\ResolveRedirectEvent;
96
     *
97
     * Event::on(Redirects::class,
98
     *     Redirects::EVENT_AFTER_SAVE_REDIRECT,
99
     *     function(ResolveRedirectEvent $event) {
100
     *         // potentially set $event->redirectDestUrl;
101
     *     }
102
     * );
103
     * ```
104
     */
105
    const EVENT_BEFORE_RESOLVE_REDIRECT = 'beforeResolveRedirect';
106
107
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
108
     * @event ResolveRedirectEvent The event that is triggered after Retour has attempted
109
     *        to resolve redirects. You may set [[ResolveRedirectEvent::redirectDestUrl]] to
110
     *        to the URL that it should redirect to, or null if no redirect should happen
111
     *
112
     * ```php
113
     * use nystudio107\retour\services\Redirects;
114
     * use nystudio107\retour\events\ResolveRedirectEvent;
115
     *
116
     * Event::on(Redirects::class,
117
     *     Redirects::EVENT_AFTER_RESOLVE_REDIRECT,
118
     *     function(ResolveRedirectEvent $event) {
119
     *         // potentially set $event->redirectDestUrl;
120
     *     }
121
     * );
122
     * ```
123
     */
124
    const EVENT_AFTER_RESOLVE_REDIRECT = 'afterResolveRedirect';
125
126
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
127
     * @event RedirectResolvedEvent The event that is triggered once Retour has resolved
128
     *        a redirect. [[RedirectResolvedEvent::redirect]] will be set to the redirect
129
     *        that was resolved. You may set [[RedirectResolvedEvent::redirectDestUrl]] to
130
     *        to a different URL that it should redirect to, or leave it null if the
131
     *        redirect should happen as resolved.
132
     *
133
     * ```php
134
     * use nystudio107\retour\services\Redirects;
135
     * use nystudio107\retour\events\RedirectResolvedEvent;
136
     *
137
     * Event::on(Redirects::class,
138
     *     Redirects::EVENT_REDIRECT_RESOLVED,
139
     *     function(RedirectResolvedEvent $event) {
140
     *         // potentially set $event->redirectDestUrl;
141
     *     }
142
     * );
143
     * ```
144
     */
145
    const EVENT_REDIRECT_RESOLVED = 'redirectResolved';
146
147
    // Protected Properties
148
    // =========================================================================
149
150
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
151
     * @var null|array
152
     */
153
    protected $cachedStaticRedirects;
154
155
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
156
     * @var null|array
157
     */
158
    protected $cachedRegExRedirects;
159
160
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
161
     * @var null|array
162
     */
163
    protected $cachedExactMatchRedirects;
164
165
    // Public Methods
166
    // =========================================================================
167
168
    /**
169
     * Handle 404s by looking for redirects
170
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
171
    public function handle404()
172
    {
173
        Craft::info(
174
            Craft::t(
175
                'retour',
176
                'A 404 exception occurred'
177
            ),
178
            __METHOD__
179
        );
180
        $request = Craft::$app->getRequest();
181
        // We only want site requests that are not live preview or console requests
182
        if ($request->getIsSiteRequest() && !$this->isPreview($request) && !$request->getIsConsoleRequest()) {
183
            // See if we should redirect
184
            try {
185
                $fullUrl = urldecode($request->getAbsoluteUrl());
186
                $pathOnly = urldecode($request->getUrl());
187
            } catch (InvalidConfigException $e) {
188
                Craft::error(
189
                    $e->getMessage(),
190
                    __METHOD__
191
                );
192
                $pathOnly = '';
193
                $fullUrl = '';
194
            }
195
            // Strip the query string if `alwaysStripQueryString` is set
196
            if (Retour::$settings->alwaysStripQueryString) {
197
                $fullUrl = UrlHelper::stripQueryString($fullUrl);
198
                $pathOnly = UrlHelper::stripQueryString($pathOnly);
199
            }
200
            // Stash the $pathOnly for use when incrementing the statistics
201
            $originalPathOnly = $pathOnly;
202
            Craft::info(
203
                Craft::t(
204
                    'retour',
205
                    '404 full URL: {fullUrl}, 404 path only: {pathOnly}',
206
                    ['fullUrl' => $fullUrl, 'pathOnly' => $pathOnly]
207
                ),
208
                __METHOD__
209
            );
210
            if (!$this->excludeUri($pathOnly)) {
211
                // Redirect if we find a match, otherwise let Craft handle it
212
                $redirect = $this->findRedirectMatch($fullUrl, $pathOnly);
213
                if (!$this->doRedirect($fullUrl, $pathOnly, $redirect) && !Retour::$settings->alwaysStripQueryString) {
214
                    // Try it again without the query string
215
                    $fullUrl = UrlHelper::stripQueryString($fullUrl);
216
                    $pathOnly = UrlHelper::stripQueryString($pathOnly);
217
                    $redirect = $this->findRedirectMatch($fullUrl, $pathOnly);
218
                    $this->doRedirect($fullUrl, $pathOnly, $redirect);
219
                }
220
                // Increment the stats
221
                Retour::$plugin->statistics->incrementStatistics($originalPathOnly, false);
222
            }
223
        }
224
    }
225
226
    /**
227
     * Do the redirect
228
     *
229
     * @param string     $fullUrl
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
230
     * @param string     $pathOnly
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
231
     * @param null|array $redirect
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
232
     *
233
     * @return bool false if not redirected
234
     */
235
    public function doRedirect(string $fullUrl, string $pathOnly, $redirect): bool
236
    {
237
        $response = Craft::$app->getResponse();
238
        if ($redirect !== null) {
239
            // Figure out what type of source matching was done
240
            $redirectSrcMatch = $redirect['redirectSrcMatch'] ?? 'pathonly';
241
            switch ($redirectSrcMatch) {
242
                case 'pathonly':
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 12 spaces, found 16
Loading history...
243
                    $url = $pathOnly;
244
                    break;
245
                case 'fullurl':
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 12 spaces, found 16
Loading history...
246
                    $url = $fullUrl;
247
                    break;
248
                default:
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 12 spaces, found 16
Loading history...
249
                    $url = $pathOnly;
250
                    break;
251
            }
252
            $dest = $redirect['redirectDestUrl'];
253
            // If this isn't a full URL, make it one based on the appropriate site
254
            if (!UrlHelper::isFullUrl($dest)) {
255
                try {
256
                    $siteId = $redirect['siteId'] ?? null;
257
                    if ($siteId !== null) {
258
                        $siteId = (int)$siteId;
259
                    }
260
                    $dest = UrlHelper::siteUrl($dest, null, null, $siteId);
261
                } catch (\yii\base\Exception $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
262
                }
263
            }
264
            if (Retour::$settings->preserveQueryString) {
265
                $request = Craft::$app->getRequest();
266
                if (!empty($request->getQueryStringWithoutPath())) {
267
                    $dest .= '?' . $request->getQueryStringWithoutPath();
268
                }
269
            }
270
            $redirectMatchType = $redirect['redirectMatchType'] ?? 'notfound';
271
            // Parse reference tags for exact matches
272
            if ($redirectMatchType === 'exactmatch') {
273
                $dest = Craft::$app->elements->parseRefs($dest, $redirect['siteId'] ?? null);
0 ignored issues
show
Bug introduced by
The method parseRefs() does not exist on null. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

273
                /** @scrutinizer ignore-call */ 
274
                $dest = Craft::$app->elements->parseRefs($dest, $redirect['siteId'] ?? null);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
274
            }
275
            $status = $redirect['redirectHttpCode'];
276
            Craft::info(
277
                Craft::t(
278
                    'retour',
279
                    'Redirecting {url} to {dest} with status {status}',
280
                    ['url' => $url, 'dest' => $dest, 'status' => $status]
281
                ),
282
                __METHOD__
283
            );
284
            // Increment the stats
285
            Retour::$plugin->statistics->incrementStatistics($url, true);
286
            // Handle a Retour return status > 400 to render the actual error template
287
            if ($status >= 400) {
288
                Retour::$currentException->statusCode = $status;
289
                $errorHandler = Craft::$app->getErrorHandler();
290
                $errorHandler->exception = Retour::$currentException;
291
                try {
292
                    $response = Craft::$app->runAction('templates/render-error');
293
                } catch (InvalidRouteException $e) {
294
                    Craft::error($e->getMessage(), __METHOD__);
295
                } catch (\yii\console\Exception $e) {
296
                    Craft::error($e->getMessage(), __METHOD__);
297
                }
298
            }
299
            // Sanitize the URL
300
            $dest = UrlHelper::sanitizeUrl($dest);
301
            // Add any additional headers (existing ones will be replaced)
302
            if (!empty(Retour::$settings->additionalHeaders)) {
303
                foreach (Retour::$settings->additionalHeaders as $additionalHeader) {
304
                    $response->headers->set($additionalHeader['name'], $additionalHeader['value']);
305
                }
306
            }
307
            // Redirect the request away;
308
            $response->redirect($dest, $status)->send();
309
            try {
310
                Craft::$app->end();
311
            } catch (ExitException $e) {
312
                Craft::error($e->getMessage(), __METHOD__);
313
            }
314
        }
315
316
        return false;
317
    }
318
319
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
320
     * @param string $fullUrl
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
321
     * @param string $pathOnly
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
322
     * @param null   $siteId
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $siteId is correct as it would always require null to be passed?
Loading history...
Coding Style introduced by
Missing parameter comment
Loading history...
323
     *
324
     * @return array|null
325
     */
326
    public function findRedirectMatch(string $fullUrl, string $pathOnly, $siteId = null)
327
    {
328
        // Get the current site
329
        if ($siteId === null) {
0 ignored issues
show
introduced by
The condition $siteId === null is always true.
Loading history...
330
            $currentSite = Craft::$app->getSites()->currentSite;
331
            if ($currentSite) {
332
                $siteId = $currentSite->id;
333
            } else {
334
                $primarySite = Craft::$app->getSites()->primarySite;
335
                if ($currentSite) {
336
                    $siteId = $primarySite->id;
337
                }
338
            }
339
        }
340
        // Try getting the full URL redirect from the cache
341
        $redirect = $this->getRedirectFromCache($fullUrl, $siteId);
342
        if ($redirect) {
343
            $this->incrementRedirectHitCount($redirect);
344
            $this->saveRedirectToCache($fullUrl, $redirect);
345
346
            return $redirect;
347
        }
348
        // Try getting the path only redirect from the cache
349
        $redirect = $this->getRedirectFromCache($pathOnly, $siteId);
350
        if ($redirect) {
351
            $this->incrementRedirectHitCount($redirect);
352
            $this->saveRedirectToCache($pathOnly, $redirect);
353
354
            return $redirect;
355
        }
356
357
        $redirect = $this->getStaticRedirect($fullUrl, $pathOnly, $siteId);
358
        if ($redirect) {
359
            $this->incrementRedirectHitCount($redirect);
360
            $this->saveRedirectToCache($pathOnly, $redirect);
361
362
            return $redirect;
363
        }
364
365
        // Resolve static redirects
366
        $redirects = $this->getAllRegExRedirects(null, $siteId);
367
        $redirect = $this->resolveRedirect($fullUrl, $pathOnly, $redirects, $siteId);
368
        if ($redirect) {
369
            return $redirect;
370
        }
371
372
        return null;
373
    }
374
375
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
376
     * @param          $url
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 1 spaces but found 10
Loading history...
377
     * @param int|null $siteId
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
378
     *
379
     * @return bool|array
380
     */
381
    public function getRedirectFromCache($url, int $siteId = 0)
382
    {
383
        $cache = Craft::$app->getCache();
384
        $cacheKey = $this::CACHE_KEY.md5($url).$siteId;
385
        $redirect = $cache->get($cacheKey);
386
        Craft::info(
387
            Craft::t(
388
                'retour',
389
                'Cached redirect hit for {url}',
390
                ['url' => $url]
391
            ),
392
            __METHOD__
393
        );
394
395
        return $redirect;
396
    }
397
398
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
399
     * @param  string $url
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 1 spaces but found 2
Loading history...
400
     * @param  array  $redirect
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 1 spaces but found 2
Loading history...
401
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
402
    public function saveRedirectToCache($url, $redirect)
403
    {
404
        $cache = Craft::$app->getCache();
405
        // Get the current site id
406
        $sites = Craft::$app->getSites();
407
        try {
408
            $siteId = $sites->getCurrentSite()->id;
409
        } catch (SiteNotFoundException $e) {
410
            $siteId = 1;
411
        }
412
        $cacheKey = $this::CACHE_KEY.md5($url).$siteId;
413
        // Create the dependency tags
414
        $dependency = new TagDependency([
0 ignored issues
show
Coding Style introduced by
The opening parenthesis of a multi-line function call should be the last content on the line.
Loading history...
415
            'tags' => [
416
                $this::GLOBAL_REDIRECTS_CACHE_TAG,
417
                $this::GLOBAL_REDIRECTS_CACHE_TAG.$siteId,
418
            ],
419
        ]);
0 ignored issues
show
Coding Style introduced by
For multi-line function calls, the closing parenthesis should be on a new line.

If a function call spawns multiple lines, the coding standard suggests to move the closing parenthesis to a new line:

someFunctionCall(
    $firstArgument,
    $secondArgument,
    $thirdArgument
); // Closing parenthesis on a new line.
Loading history...
420
        $cache->set($cacheKey, $redirect, Retour::$cacheDuration, $dependency);
421
        Craft::info(
422
            Craft::t(
423
                'retour',
424
                'Cached redirect saved for {url}',
425
                ['url' => $url]
426
            ),
427
            __METHOD__
428
        );
429
    }
430
431
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
Coding Style introduced by
Parameter $siteId should have a doc-comment as per coding-style.
Loading history...
432
     * @param string $fullUrl
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
433
     * @param string $pathOnly
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
434
     * @param array  $redirects
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
435
     *
436
     * @return array|null
437
     */
438
    public function resolveRedirect(string $fullUrl, string $pathOnly, array $redirects, $siteId)
439
    {
440
        $result = null;
441
        // Throw the Redirects::EVENT_BEFORE_RESOLVE_REDIRECT event
442
        $event = new ResolveRedirectEvent([
0 ignored issues
show
Coding Style introduced by
The opening parenthesis of a multi-line function call should be the last content on the line.
Loading history...
443
            'fullUrl' => $fullUrl,
444
            'pathOnly' => $pathOnly,
445
            'redirectDestUrl' => null,
446
            'redirectHttpCode' => 301,
447
            'siteId' => $siteId,
448
        ]);
0 ignored issues
show
Coding Style introduced by
For multi-line function calls, the closing parenthesis should be on a new line.

If a function call spawns multiple lines, the coding standard suggests to move the closing parenthesis to a new line:

someFunctionCall(
    $firstArgument,
    $secondArgument,
    $thirdArgument
); // Closing parenthesis on a new line.
Loading history...
449
        $this->trigger(self::EVENT_BEFORE_RESOLVE_REDIRECT, $event);
450
        if ($event->redirectDestUrl !== null) {
451
            return $this->resolveEventRedirect($event);
452
        }
453
        // Iterate through the redirects
454
        foreach ($redirects as $redirect) {
455
            // Figure out what type of source matching to do
456
            $redirectSrcMatch = $redirect['redirectSrcMatch'] ?? 'pathonly';
457
            $redirectEnabled = (bool)$redirect['enabled'];
458
            if ($redirectEnabled === true) {
459
                switch ($redirectSrcMatch) {
460
                    case 'pathonly':
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 16 spaces, found 20
Loading history...
461
                        $url = $pathOnly;
462
                        break;
463
                    case 'fullurl':
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 16 spaces, found 20
Loading history...
464
                        $url = $fullUrl;
465
                        break;
466
                    default:
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 16 spaces, found 20
Loading history...
467
                        $url = $pathOnly;
468
                        break;
469
                }
470
                $redirectMatchType = $redirect['redirectMatchType'] ?? 'notfound';
471
                switch ($redirectMatchType) {
472
                    // Do a straight up match
473
                    case 'exactmatch':
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 16 spaces, found 20
Loading history...
474
                        if (strcasecmp($redirect['redirectSrcUrlParsed'], $url) === 0) {
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 20 spaces, found 24
Loading history...
475
                            $this->incrementRedirectHitCount($redirect);
476
                            $this->saveRedirectToCache($url, $redirect);
477
478
                            // Throw the Redirects::EVENT_REDIRECT_RESOLVED event
479
                            $event = new RedirectResolvedEvent([
0 ignored issues
show
Coding Style introduced by
The opening parenthesis of a multi-line function call should be the last content on the line.
Loading history...
480
                                'fullUrl' => $fullUrl,
481
                                'pathOnly' => $pathOnly,
482
                                'redirectDestUrl' => null,
483
                                'redirectHttpCode' => 301,
484
                                'redirect' => $redirect,
485
                                'siteId' => $siteId,
486
                            ]);
0 ignored issues
show
Coding Style introduced by
For multi-line function calls, the closing parenthesis should be on a new line.

If a function call spawns multiple lines, the coding standard suggests to move the closing parenthesis to a new line:

someFunctionCall(
    $firstArgument,
    $secondArgument,
    $thirdArgument
); // Closing parenthesis on a new line.
Loading history...
487
                            $this->trigger(self::EVENT_REDIRECT_RESOLVED, $event);
488
                            if ($event->redirectDestUrl !== null) {
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 20 spaces, found 28
Loading history...
489
                                return $this->resolveEventRedirect($event, $url, $redirect);
490
                            }
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 20 spaces, found 28
Loading history...
491
492
                            return $redirect;
493
                        }
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 20 spaces, found 24
Loading history...
494
                        break;
495
496
                    // Do a regex match
497
                    case 'regexmatch':
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 16 spaces, found 20
Loading history...
498
                        $matchRegEx = '`'.$redirect['redirectSrcUrlParsed'].'`i';
499
                        try {
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 20 spaces, found 24
Loading history...
500
                            if (preg_match($matchRegEx, $url) === 1) {
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 24 spaces, found 28
Loading history...
501
                                $this->incrementRedirectHitCount($redirect);
502
                                // If we're not associated with an EntryID, handle capture group replacement
503
                                if ((int)$redirect['associatedElementId'] === 0) {
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 28 spaces, found 32
Loading history...
504
                                    $redirect['redirectDestUrl'] = preg_replace(
505
                                        $matchRegEx,
506
                                        $redirect['redirectDestUrl'],
507
                                        $url
508
                                    );
509
                                }
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 28 spaces, found 32
Loading history...
510
                                $url = preg_replace('/([^:])(\/{2,})/', '$1/', $url);
511
                                $this->saveRedirectToCache($url, $redirect);
512
513
                                // Throw the Redirects::EVENT_REDIRECT_RESOLVED event
514
                                $event = new RedirectResolvedEvent([
0 ignored issues
show
Coding Style introduced by
The opening parenthesis of a multi-line function call should be the last content on the line.
Loading history...
515
                                    'fullUrl' => $fullUrl,
516
                                    'pathOnly' => $pathOnly,
517
                                    'redirectDestUrl' => null,
518
                                    'redirectHttpCode' => 301,
519
                                    'redirect' => $redirect,
520
                                    'siteId' => $siteId,
521
                                ]);
0 ignored issues
show
Coding Style introduced by
For multi-line function calls, the closing parenthesis should be on a new line.

If a function call spawns multiple lines, the coding standard suggests to move the closing parenthesis to a new line:

someFunctionCall(
    $firstArgument,
    $secondArgument,
    $thirdArgument
); // Closing parenthesis on a new line.
Loading history...
522
                                $this->trigger(self::EVENT_REDIRECT_RESOLVED, $event);
523
                                if ($event->redirectDestUrl !== null) {
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 24 spaces, found 32
Loading history...
524
                                    return $this->resolveEventRedirect($event, $url, $redirect);
525
                                }
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 24 spaces, found 32
Loading history...
526
527
                                return $redirect;
528
                            }
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 24 spaces, found 28
Loading history...
529
                        } catch (\Exception $e) {
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 20 spaces, found 24
Loading history...
530
                            // That's fine
531
                            Craft::error('Invalid Redirect Regex: '.$matchRegEx, __METHOD__);
532
                        }
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 20 spaces, found 24
Loading history...
533
534
                        break;
535
536
                    // Otherwise try to look up a plugin's method by and call it for the match
537
                    default:
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 16 spaces, found 20
Loading history...
538
                        $plugin = $redirectMatchType ? Craft::$app->getPlugins()->getPlugin($redirectMatchType) : null;
539
                        if ($plugin && method_exists($plugin, 'retourMatch')) {
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 20 spaces, found 24
Loading history...
540
                            $args = [
541
                                [
542
                                    'redirect' => &$redirect,
543
                                ],
544
                            ];
545
                            $result = \call_user_func_array([$plugin, 'retourMatch'], $args);
546
                            if ($result) {
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 24 spaces, found 28
Loading history...
547
                                $this->incrementRedirectHitCount($redirect);
548
                                $this->saveRedirectToCache($url, $redirect);
549
550
                                // Throw the Redirects::EVENT_REDIRECT_RESOLVED event
551
                                $event = new RedirectResolvedEvent([
0 ignored issues
show
Coding Style introduced by
The opening parenthesis of a multi-line function call should be the last content on the line.
Loading history...
552
                                    'fullUrl' => $fullUrl,
553
                                    'pathOnly' => $pathOnly,
554
                                    'redirectDestUrl' => null,
555
                                    'redirectHttpCode' => 301,
556
                                    'redirect' => $redirect,
557
                                    'siteId' => $siteId,
558
                                ]);
0 ignored issues
show
Coding Style introduced by
For multi-line function calls, the closing parenthesis should be on a new line.

If a function call spawns multiple lines, the coding standard suggests to move the closing parenthesis to a new line:

someFunctionCall(
    $firstArgument,
    $secondArgument,
    $thirdArgument
); // Closing parenthesis on a new line.
Loading history...
559
                                $this->trigger(self::EVENT_REDIRECT_RESOLVED, $event);
560
                                if ($event->redirectDestUrl !== null) {
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 24 spaces, found 32
Loading history...
561
                                    return $this->resolveEventRedirect($event, $url, $redirect);
562
                                }
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 24 spaces, found 32
Loading history...
563
564
                                return $redirect;
565
                            }
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 24 spaces, found 28
Loading history...
566
                        }
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 20 spaces, found 24
Loading history...
567
                        break;
568
                }
569
            }
570
        }
571
        // Throw the Redirects::EVENT_AFTER_RESOLVE_REDIRECT event
572
        $event = new ResolveRedirectEvent([
0 ignored issues
show
Coding Style introduced by
The opening parenthesis of a multi-line function call should be the last content on the line.
Loading history...
573
            'fullUrl' => $fullUrl,
574
            'pathOnly' => $pathOnly,
575
            'redirectDestUrl' => null,
576
            'redirectHttpCode' => 301,
577
            'siteId' => $siteId,
578
        ]);
0 ignored issues
show
Coding Style introduced by
For multi-line function calls, the closing parenthesis should be on a new line.

If a function call spawns multiple lines, the coding standard suggests to move the closing parenthesis to a new line:

someFunctionCall(
    $firstArgument,
    $secondArgument,
    $thirdArgument
); // Closing parenthesis on a new line.
Loading history...
579
        $this->trigger(self::EVENT_AFTER_RESOLVE_REDIRECT, $event);
580
        if ($event->redirectDestUrl !== null) {
581
            return $this->resolveEventRedirect($event);
582
        }
583
        Craft::info(
584
            Craft::t(
585
                'retour',
586
                'Not handled-> full URL: {fullUrl}, path only: {pathOnly}',
587
                ['fullUrl' => $fullUrl, 'pathOnly' => $pathOnly]
588
            ),
589
            __METHOD__
590
        );
591
592
        return $result;
593
    }
594
595
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
Coding Style introduced by
Parameter $url should have a doc-comment as per coding-style.
Loading history...
Coding Style introduced by
Parameter $redirect should have a doc-comment as per coding-style.
Loading history...
596
     * @param ResolveRedirectEvent $event
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
597
     *
598
     * @return null|array
599
     */
600
    public function resolveEventRedirect(ResolveRedirectEvent $event, $url = null, $redirect = null)
601
    {
602
        $result = null;
603
604
        if ($event->redirectDestUrl !== null) {
605
            $resolvedRedirect = new StaticRedirectsModel([
0 ignored issues
show
Coding Style introduced by
The opening parenthesis of a multi-line function call should be the last content on the line.
Loading history...
606
                'id' => self::EVENT_REDIRECT_ID,
607
                'redirectDestUrl' => $event->redirectDestUrl,
608
                'redirectHttpCode' => $event->redirectHttpCode,
609
            ]);
0 ignored issues
show
Coding Style introduced by
For multi-line function calls, the closing parenthesis should be on a new line.

If a function call spawns multiple lines, the coding standard suggests to move the closing parenthesis to a new line:

someFunctionCall(
    $firstArgument,
    $secondArgument,
    $thirdArgument
); // Closing parenthesis on a new line.
Loading history...
610
            $result = $resolvedRedirect->toArray();
611
612
            if ($url !== null && $redirect !== null) {
613
                // Save the modified redirect to the cache
614
                $redirect['redirectDestUrl'] = $event->redirectDestUrl;
615
                $redirect['redirectHttpCode'] = $event->redirectHttpCode;
616
                $this->saveRedirectToCache($url, $redirect);
617
            }
618
        }
619
620
        return $result;
621
    }
622
623
    /**
624
     * Returns the list of matching schemes
625
     *
626
     * @return  array
0 ignored issues
show
Coding Style introduced by
Tag value for @return tag indented incorrectly; expected 1 spaces but found 2
Loading history...
627
     */
628
    public function getMatchesList(): array
629
    {
630
        $result = [
631
            'exactmatch' => Craft::t('retour', 'Exact Match'),
632
            'regexmatch' => Craft::t('retour', 'RegEx Match'),
633
        ];
634
635
        // Add any plugins that offer the retourMatch() method
636
        foreach (Craft::$app->getPlugins()->getAllPlugins() as $plugin) {
637
            /** @var Plugin $plugin */
0 ignored issues
show
Coding Style introduced by
The open comment tag must be the only content on the line
Loading history...
Coding Style introduced by
Missing short description in doc comment
Loading history...
Coding Style introduced by
The close comment tag must be the only content on the line
Loading history...
638
            if (method_exists($plugin, 'retourMatch')) {
639
                $result[$plugin->getHandle()] = $plugin->name.Craft::t('retour', ' Match');
640
            }
641
        }
642
643
        return $result;
644
    }
645
646
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
647
     * @param string $fullUrl
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
648
     * @param string $pathOnly
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
649
     * @param $siteId
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
650
     * @return mixed|null
0 ignored issues
show
Coding Style introduced by
Tag @return cannot be grouped with parameter tags in a doc comment
Loading history...
651
     */
652
    public function getStaticRedirect(string $fullUrl, string $pathOnly, $siteId)
653
    {
654
        $staticCondition = ['redirectMatchType' => 'exactmatch'];
655
        $siteCondition = [
656
            'or',
657
            ['siteId' => $siteId],
658
            ['siteId' => null]
659
        ];
660
        $pathCondition = [
661
            'or',
662
            ['and',
663
                ['redirectSrcMatch' => 'pathonly'],
664
                ['redirectSrcUrlParsed' => $pathOnly]
665
            ],
666
            ['and',
667
                ['redirectSrcMatch' => 'fullurl'],
668
                ['redirectSrcUrlParsed' => $fullUrl]
669
            ],
670
        ];
671
672
        $query = (new Query)
673
            ->from('{{%retour_static_redirects}}')
674
            ->where(['and',
0 ignored issues
show
Coding Style introduced by
The opening parenthesis of a multi-line function call should be the last content on the line.
Loading history...
675
                $staticCondition,
676
                $pathCondition,
677
                $siteCondition
678
            ])
0 ignored issues
show
Coding Style introduced by
For multi-line function calls, the closing parenthesis should be on a new line.

If a function call spawns multiple lines, the coding standard suggests to move the closing parenthesis to a new line:

someFunctionCall(
    $firstArgument,
    $secondArgument,
    $thirdArgument
); // Closing parenthesis on a new line.
Loading history...
679
            ->limit(1);
680
681
        return $query->one();
682
    }
683
684
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
685
     * @param null|int $limit
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
686
     * @param int|null $siteId
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
687
     *
688
     * @return array All of the regex match redirects
689
     */
690
    public function getAllRegExRedirects(int $limit = null, int $siteId = null): array
691
    {
692
        // Cache it in our class; no need to fetch it more than once
693
        if ($this->cachedRegExRedirects !== null) {
694
            return $this->cachedRegExRedirects;
695
        }
696
697
        $redirects = $this->getRedirectsByMatchType($limit, $siteId, 'regexmatch');
698
699
        // Cache for future accesses
700
        $this->cachedRegExRedirects = $redirects;
701
702
        return $redirects;
703
    }
704
705
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
706
     * @param null|int $limit
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
707
     * @param int|null $siteId
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
708
     *
709
     * @return array All of the regex match redirects
710
     */
711
    public function getAllExactMatchRedirects(int $limit = null, int $siteId = null): array
712
    {
713
        // Cache it in our class; no need to fetch it more than once
714
        if ($this->cachedExactMatchRedirects !== null) {
715
            return $this->cachedExactMatchRedirects;
716
        }
717
718
        $redirects = $this->getRedirectsByMatchType($limit, $siteId, 'exactmatch');
719
720
        // Cache for future accesses
721
        $this->cachedExactMatchRedirects = $redirects;
722
723
        return $redirects;
724
    }
725
726
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
727
     * @param int|null $limit
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
728
     * @param int|null $siteId
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
729
     * @param string $type
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
Coding Style introduced by
Expected 3 spaces after parameter type; 1 found
Loading history...
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
730
     * @return array
0 ignored issues
show
Coding Style introduced by
Tag @return cannot be grouped with parameter tags in a doc comment
Loading history...
731
     */
732
    protected function getRedirectsByMatchType(int $limit = null, int $siteId = null, string $type): array
733
    {
734
        // Query the db table
735
        $query = (new Query())
736
            ->from(['{{%retour_static_redirects}}'])
737
            ->orderBy('redirectMatchType ASC, redirectSrcMatch ASC, hitCount DESC');
738
739
        if ($siteId) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $siteId of type integer|null is loosely compared to true; this is ambiguous if the integer can be 0. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
740
            $query
741
                ->where(['siteId' => $siteId])
742
                ->orWhere(['siteId' => null]);
743
        }
744
745
        if ($limit) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $limit of type integer|null is loosely compared to true; this is ambiguous if the integer can be 0. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
746
            $query->limit($limit);
747
        }
748
749
        $query->andWhere(['redirectMatchType' => $type]);
750
751
        return $query->all();
752
    }
753
754
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
755
     * @param null|int $limit
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
756
     * @param int|null $siteId
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
757
     *
758
     * @return array All of the statistics
759
     */
760
    public function getAllStaticRedirects($limit = null, int $siteId = null): array
761
    {
762
        // Cache it in our class; no need to fetch it more than once
763
        if ($this->cachedStaticRedirects !== null) {
764
            return $this->cachedStaticRedirects;
765
        }
766
        // Query the db table
767
        $query = (new Query())
768
            ->from(['{{%retour_static_redirects}}'])
769
            ->orderBy('redirectMatchType ASC, redirectSrcMatch ASC, hitCount DESC');
770
        if ($siteId) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $siteId of type integer|null is loosely compared to true; this is ambiguous if the integer can be 0. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
771
            $query
772
                ->where(['siteId' => $siteId])
773
                ->orWhere(['siteId' => null]);
774
        }
775
        if ($limit) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $limit of type integer|null is loosely compared to true; this is ambiguous if the integer can be 0. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
776
            $query->limit($limit);
777
        }
778
        $redirects = $query->all();
779
        // Cache for future accesses
780
        $this->cachedStaticRedirects = $redirects;
781
782
        return $redirects;
783
    }
784
785
    /**
786
     * Return a redirect by id
787
     *
788
     * @param int $id
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
789
     *
790
     * @return null|array The static redirect
791
     */
792
    public function getRedirectById(int $id)
793
    {
794
        // Query the db table
795
        $redirect = (new Query())
796
            ->from(['{{%retour_static_redirects}}'])
797
            ->where(['id' => $id])
798
            ->one();
799
800
        return $redirect;
801
    }
802
803
    /**
804
     * Return a redirect by redirectSrcUrl
805
     *
806
     * @param string   $redirectSrcUrl
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
807
     * @param int|null $siteId
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
808
     *
809
     * @return null|array
810
     */
811
    public function getRedirectByRedirectSrcUrl(string $redirectSrcUrl, int $siteId = null)
812
    {
813
        // Query the db table
814
        $query = (new Query())
815
            ->from(['{{%retour_static_redirects}}'])
816
            ->where(['redirectSrcUrl' => $redirectSrcUrl])
0 ignored issues
show
Coding Style introduced by
Space after closing parenthesis of function call prohibited
Loading history...
817
        ;
818
        if ($siteId) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $siteId of type integer|null is loosely compared to true; this is ambiguous if the integer can be 0. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
819
            $query
820
                ->andWhere(['or', [
0 ignored issues
show
Coding Style introduced by
The opening parenthesis of a multi-line function call should be the last content on the line.
Loading history...
821
                    'siteId' => $siteId,
822
                ], [
0 ignored issues
show
Coding Style introduced by
This line of the multi-line function call does not seem to be indented correctly. Expected 20 spaces, but found 16.
Loading history...
823
                    'siteId' => null,
824
                ]]);
0 ignored issues
show
Coding Style introduced by
For multi-line function calls, the closing parenthesis should be on a new line.

If a function call spawns multiple lines, the coding standard suggests to move the closing parenthesis to a new line:

someFunctionCall(
    $firstArgument,
    $secondArgument,
    $thirdArgument
); // Closing parenthesis on a new line.
Loading history...
825
        }
826
        $redirect = $query->one();
827
828
        return $redirect;
829
    }
830
831
    /**
832
     * Return redirects for a given element.
833
     *
834
     * @param int $elementId
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
Coding Style introduced by
Expected 6 spaces after parameter type; 1 found
Loading history...
835
     * @param int|null $siteId
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
836
     *
837
     * @return null|array
838
     */
839
    public function getRedirectsByElementId(int $elementId, int $siteId = null)
840
    {
841
        // Query the db table
842
        $query = (new Query())
843
            ->from(['{{%retour_static_redirects}}'])
844
            ->where(['associatedElementId' => $elementId])
0 ignored issues
show
Coding Style introduced by
Space after closing parenthesis of function call prohibited
Loading history...
845
        ;
846
        if ($siteId !== null) {
847
            $query->andWhere(['siteId' => $siteId]);
848
        }
849
850
        return $query->all();
851
    }
852
853
    /**
854
     * Delete a redirect by id
855
     *
856
     * @param int $id
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
857
     *
858
     * @return int The result
859
     */
860
    public function deleteRedirectById(int $id): int
861
    {
862
        $db = Craft::$app->getDb();
863
        // Delete a row from the db table
864
        try {
865
            $result = $db->createCommand()->delete(
866
                '{{%retour_static_redirects}}',
867
                [
868
                    'id' => $id,
869
                ]
870
            )->execute();
871
        } catch (Exception $e) {
872
            Craft::error($e->getMessage(), __METHOD__);
873
            $result = 0;
874
        }
875
876
        return $result;
877
    }
878
879
    /**
880
     * Increment the retour_static_redirects record
881
     *
882
     * @param $redirectConfig
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
883
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
884
    public function incrementRedirectHitCount(&$redirectConfig)
885
    {
886
        if ($redirectConfig !== null) {
887
            $db = Craft::$app->getDb();
888
            $redirectConfig['hitCount']++;
889
            $redirectConfig['hitLastTime'] = Db::prepareDateForDb(new \DateTime());
890
            Craft::debug(
891
                Craft::t(
892
                    'retour',
893
                    'Incrementing statistics for: {redirect}',
894
                    ['redirect' => print_r($redirectConfig, true)]
895
                ),
896
                __METHOD__
897
            );
898
            // Update the existing record
899
            try {
900
                $rowsAffected = $db->createCommand()->update(
901
                    '{{%retour_static_redirects}}',
902
                    [
903
                        'hitCount' => $redirectConfig['hitCount'],
904
                        'hitLastTime' => $redirectConfig['hitLastTime'],
905
                    ],
906
                    [
907
                        'id' => $redirectConfig['id'],
908
                    ]
909
                )->execute();
910
                Craft::debug('Rows affected: '.$rowsAffected, __METHOD__);
911
            } catch (\Exception $e) {
912
                Craft::error($e->getMessage(), __METHOD__);
913
            }
914
        }
915
    }
916
917
    /**
918
     * Save an element redirect.
919
     *
920
     * @param ElementInterface $element
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
921
     * @param string $sourceUrl
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
Coding Style introduced by
Expected 11 spaces after parameter type; 1 found
Loading history...
922
     * @param string $redirectSrcMatch
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
Coding Style introduced by
Expected 11 spaces after parameter type; 1 found
Loading history...
923
     * @param int $redirectHttpCode
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
Coding Style introduced by
Expected 14 spaces after parameter type; 1 found
Loading history...
924
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
925
    public function enableElementRedirect(ElementInterface $element, string $sourceUrl, string $redirectSrcMatch = 'pathonly', int $redirectHttpCode = 301)
926
    {
927
        $redirectConfig = [
928
            'redirectMatchType' => 'exactmatch',
929
            'redirectSrcUrl' => $sourceUrl,
930
            'siteId' => $element->siteId,
0 ignored issues
show
Bug introduced by
Accessing siteId on the interface craft\base\ElementInterface suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
931
            'associatedElementId' => $element->getCanonicalId(),
932
            'enabled' => true,
933
            'redirectSrcMatch' => $redirectSrcMatch,
934
            'redirectDestUrl' => $element->getUrl(),
935
            'redirectHttpCode' => $redirectHttpCode,
936
        ];
937
938
        $this->saveRedirect($redirectConfig);
939
    }
940
941
    /**
0 ignored issues
show
Coding Style introduced by
Parameter $allSites should have a doc-comment as per coding-style.
Loading history...
942
     * Delete an element redirect.
943
     *
944
     * @param ElementInterface $element
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
945
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
946
    public function removeElementRedirect(ElementInterface $element, bool $allSites = false)
947
    {
948
        $redirects = $this->getRedirectsByElementId($element->getCanonicalId(), $allSites ? null : $element->siteId);
0 ignored issues
show
Bug introduced by
Accessing siteId on the interface craft\base\ElementInterface suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
949
950
        if (!empty($redirects)) {
951
            foreach ($redirects as $redirect) {
952
                $this->deleteRedirectById($redirect['id']);
953
            }
954
        }
955
    }
956
957
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
958
     * @param array $redirectConfig
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
959
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
960
    public function saveRedirect(array $redirectConfig)
961
    {
962
        // Handle URL encoded URLs by decoding them before saving them
963
        if (isset($redirectConfig['redirectMatchType']) && $redirectConfig['redirectMatchType'] === 'exactmatch') {
964
            $redirectConfig['redirectSrcUrl'] = urldecode($redirectConfig['redirectSrcUrl'] ?? '');
965
            $redirectConfig['redirectSrcUrlParsed'] = urldecode($redirectConfig['redirectSrcUrlParsed'] ?? '');
966
        }
967
        // Validate the model before saving it to the db
968
        $redirect = new StaticRedirectsModel($redirectConfig);
969
        if ($redirect->validate() === false) {
970
            Craft::error(
971
                Craft::t(
972
                    'retour',
973
                    'Error validating redirect {id}: {errors}',
974
                    ['id' => $redirect->id, 'errors' => print_r($redirect->getErrors(), true)]
975
                ),
976
                __METHOD__
977
            );
978
979
            return;
980
        }
981
        // Get the validated model attributes and save them to the db
982
        $redirectConfig = $redirect->getAttributes();
983
        // 0 for a siteId needs to be converted to null
984
        if (empty($redirectConfig['siteId']) || (int)$redirectConfig['siteId'] === 0) {
985
            $redirectConfig['siteId'] = null;
986
        }
987
        // Throw an event to before saving the redirect
988
        $db = Craft::$app->getDb();
989
        // See if a redirect exists with this source URL already
990
        if ((int)$redirectConfig['id'] === 0) {
991
            // Query the db table
992
            $redirect = (new Query())
993
                ->from(['{{%retour_static_redirects}}'])
994
                ->where(['redirectSrcUrlParsed' => $redirectConfig['redirectSrcUrlParsed']])
995
                ->andWhere(['siteId' => $redirectConfig['siteId']])
996
                ->one();
997
            // If it exists, update it rather than having duplicates
998
            if (!empty($redirect)) {
999
                $redirectConfig['id'] = $redirect['id'];
1000
            }
1001
        }
1002
        // Trigger a 'beforeSaveRedirect' event
1003
        $isNew = (int)$redirectConfig['id'] === 0;
1004
        $event = new RedirectEvent([
0 ignored issues
show
Coding Style introduced by
The opening parenthesis of a multi-line function call should be the last content on the line.
Loading history...
1005
            'isNew' => $isNew,
1006
            'legacyUrl' => $redirectConfig['redirectSrcUrlParsed'],
1007
            'destinationUrl' => $redirectConfig['redirectDestUrl'],
1008
            'matchType' => $redirectConfig['redirectSrcMatch'],
1009
            'redirectType' => $redirectConfig['redirectHttpCode'],
1010
            'siteId' => $redirectConfig['siteId'],
1011
        ]);
0 ignored issues
show
Coding Style introduced by
For multi-line function calls, the closing parenthesis should be on a new line.

If a function call spawns multiple lines, the coding standard suggests to move the closing parenthesis to a new line:

someFunctionCall(
    $firstArgument,
    $secondArgument,
    $thirdArgument
); // Closing parenthesis on a new line.
Loading history...
1012
        $this->trigger(self::EVENT_BEFORE_SAVE_REDIRECT, $event);
1013
        if (!$event->isValid) {
1014
            return;
1015
        }
1016
        // See if this is an existing redirect
1017
        if (!$isNew) {
1018
            Craft::debug(
1019
                Craft::t(
1020
                    'retour',
1021
                    'Updating existing redirect: {redirect}',
1022
                    ['redirect' => print_r($redirectConfig, true)]
1023
                ),
1024
                __METHOD__
1025
            );
1026
            // Update the existing record
1027
            try {
1028
                $db->createCommand()->update(
1029
                    '{{%retour_static_redirects}}',
1030
                    $redirectConfig,
1031
                    [
1032
                        'id' => $redirectConfig['id'],
1033
                    ]
1034
                )->execute();
1035
            } catch (Exception $e) {
1036
                Craft::error($e->getMessage(), __METHOD__);
1037
            }
1038
        } else {
1039
            Craft::debug(
1040
                Craft::t(
1041
                    'retour',
1042
                    'Creating new redirect: {redirect}',
1043
                    ['redirect' => print_r($redirectConfig, true)]
1044
                ),
1045
                __METHOD__
1046
            );
1047
            unset($redirectConfig['id']);
1048
            // Create a new record
1049
            try {
1050
                $db->createCommand()->insert(
1051
                    '{{%retour_static_redirects}}',
1052
                    $redirectConfig
1053
                )->execute();
1054
            } catch (Exception $e) {
1055
                Craft::error($e->getMessage(), __METHOD__);
1056
            }
1057
        }
1058
        // To prevent redirect loops, see if any static redirects have our redirectDestUrl as their redirectSrcUrl
1059
        $testRedirectConfig = $this->getRedirectByRedirectSrcUrl(
1060
            $redirectConfig['redirectDestUrl'],
1061
            $redirectConfig['siteId']
1062
        );
1063
        if ($testRedirectConfig !== null) {
1064
            Craft::debug(
1065
                Craft::t(
1066
                    'retour',
1067
                    'Deleting redirect to prevent a loop: {redirect}',
1068
                    ['redirect' => print_r($testRedirectConfig, true)]
1069
                ),
1070
                __METHOD__
1071
            );
1072
            // Delete the redirect that has a redirectSrcUrl the same as this record's redirectDestUrl
1073
            try {
1074
                $db->createCommand()->delete(
1075
                    '{{%retour_static_redirects}}',
1076
                    ['id' => $testRedirectConfig['id']]
1077
                )->execute();
1078
            } catch (Exception $e) {
1079
                Craft::error($e->getMessage(), __METHOD__);
1080
            }
1081
        }
1082
        // Trigger a 'afterSaveRedirect' event
1083
        $this->trigger(self::EVENT_AFTER_SAVE_REDIRECT, $event);
1084
1085
        // Invalidate caches after saving a redirect
1086
        $this->invalidateCaches();
1087
    }
1088
1089
    /**
1090
     * Invalidate all of the redirects caches
1091
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
1092
    public function invalidateCaches()
1093
    {
1094
        $cache = Craft::$app->getCache();
1095
        TagDependency::invalidate($cache, $this::GLOBAL_REDIRECTS_CACHE_TAG);
1096
        // If they are using Craft 3.3 or later, clear the GraphQL caches too
1097
        if (Retour::$craft33) {
1098
            $gql = Craft::$app->getGql();
1099
            if (method_exists($gql, 'invalidateCaches')) {
1100
                $gql->invalidateCaches();
1101
            }
1102
        }
1103
        Craft::info(
1104
            Craft::t(
1105
                'retour',
1106
                'All redirect caches cleared'
1107
            ),
1108
            __METHOD__
1109
        );
1110
    }
1111
1112
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
1113
     * @param $uri
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
1114
     *
1115
     * @return bool
1116
     */
1117
    public function excludeUri($uri): bool
1118
    {
1119
        $uri = '/'.ltrim($uri, '/');
1120
        if (!empty(Retour::$settings->excludePatterns)) {
1121
            foreach (Retour::$settings->excludePatterns as $excludePattern) {
1122
                $pattern = '`'.$excludePattern['pattern'].'`i';
1123
                try {
1124
                    if (preg_match($pattern, $uri) === 1) {
1125
                        return true;
1126
                    }
1127
                } catch (\Exception $e) {
1128
                    // That's fine
1129
                    Craft::error('Invalid exclude URI Regex: '.$pattern, __METHOD__);
1130
                }
1131
            }
1132
        }
1133
1134
        return false;
1135
    }
1136
1137
    /**
0 ignored issues
show
Coding Style introduced by
Parameter $request should have a doc-comment as per coding-style.
Loading history...
1138
     * Return whether this is a preview request of any kind
1139
     *
1140
     * @return bool
1141
     */
1142
    public function isPreview($request): bool
1143
    {
1144
        $isPreview = false;
1145
        if (Retour::$craft32) {
1146
            $isPreview = $request->getIsPreview();
1147
        }
1148
        $isLivePreview = $request->getIsLivePreview();
1149
1150
        return ($isPreview || $isLivePreview);
1151
    }
1152
}
1153