Passed
Push — v3 ( 8fc446...db5cc8 )
by Andrew
20:41 queued 19s
created

DynamicMeta::paginate()   F

Complexity

Conditions 14
Paths 577

Size

Total Lines 55
Code Lines 34

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 210

Importance

Changes 2
Bugs 1 Features 0
Metric Value
eloc 34
c 2
b 1
f 0
dl 0
loc 55
ccs 0
cts 37
cp 0
rs 2.6875
cc 14
nop 1
crap 210
nc 577

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * SEOmatic plugin for Craft CMS 3.x
4
 *
5
 * A turnkey SEO implementation for Craft CMS that is comprehensive, powerful,
6
 * and flexible
7
 *
8
 * @link      https://nystudio107.com
9
 * @copyright Copyright (c) 2017 nystudio107
10
 */
11
12
namespace nystudio107\seomatic\helpers;
13
14
use Craft;
15
use craft\base\Element;
16
use craft\errors\SiteNotFoundException;
17
use craft\helpers\DateTimeHelper;
18
use craft\web\twig\variables\Paginate;
19
use DateTime;
20
use nystudio107\seomatic\events\AddDynamicMetaEvent;
21
use nystudio107\seomatic\fields\SeoSettings;
22
use nystudio107\seomatic\helpers\Field as FieldHelper;
23
use nystudio107\seomatic\helpers\Localization as LocalizationHelper;
24
use nystudio107\seomatic\helpers\Text as TextHelper;
25
use nystudio107\seomatic\models\Entity;
26
use nystudio107\seomatic\models\jsonld\BreadcrumbList;
27
use nystudio107\seomatic\models\jsonld\ContactPoint;
28
use nystudio107\seomatic\models\jsonld\LocalBusiness;
29
use nystudio107\seomatic\models\jsonld\OpeningHoursSpecification;
30
use nystudio107\seomatic\models\jsonld\Organization;
31
use nystudio107\seomatic\models\jsonld\Thing;
32
use nystudio107\seomatic\models\MetaBundle;
33
use nystudio107\seomatic\models\MetaJsonLd;
34
use nystudio107\seomatic\Seomatic;
35
use nystudio107\seomatic\services\Helper as SeomaticHelper;
36
use RecursiveArrayIterator;
37
use RecursiveIteratorIterator;
38
use Throwable;
39
use yii\base\Event;
40
use yii\base\Exception;
41
use yii\base\InvalidConfigException;
42
use function count;
43
use function in_array;
44
use function is_array;
45
use function is_string;
46
47
/**
48
 * @author    nystudio107
49
 * @package   Seomatic
50
 * @since     3.0.0
51
 */
52
class DynamicMeta
53
{
54
    // Constants
55
    // =========================================================================
56
57
    /**
58
     * @event AddDynamicMetaEvent The event that is triggered when SEOmatic has
59
     *        included the standard meta containers, and gives your plugin/module
60
     *        the chance to add whatever custom dynamic meta items you like
61
     *
62
     * ---
63
     * ```php
64
     * use nystudio107\seomatic\events\AddDynamicMetaEvent;
65
     * use nystudio107\seomatic\helpers\DynamicMeta;
66
     * use yii\base\Event;
67
     * Event::on(DynamicMeta::class, DynamicMeta::EVENT_ADD_DYNAMIC_META, function(AddDynamicMetaEvent $e) {
68
     *     // Add whatever dynamic meta items to the containers as you like
69
     * });
70
     * ```
71
     */
72
    const EVENT_ADD_DYNAMIC_META = 'addDynamicMeta';
73
74
    // Static Methods
75
    // =========================================================================
76
77
    /**
78
     * Paginate based on the passed in Paginate variable as returned from the
79
     * Twig {% paginate %} tag:
80
     * https://docs.craftcms.com/v3/templating/tags/paginate.html#the-pageInfo-variable
81
     *
82
     * @param Paginate $pageInfo
83
     */
84
    public static function paginate(Paginate $pageInfo)
85
    {
86
        if ($pageInfo !== null && $pageInfo->currentPage !== null) {
87
            // Let the meta containers know that this page is paginated
88
            Seomatic::$plugin->metaContainers->paginationPage = (string)$pageInfo->currentPage;
89
            // See if we should strip the query params
90
            $stripQueryParams = true;
91
            $pageTrigger = Craft::$app->getConfig()->getGeneral()->pageTrigger;
92
            // Is this query string-based pagination?
93
            if ($pageTrigger[0] === '?') {
94
                $stripQueryParams = false;
95
            }
96
            // Set the canonical URL to be the paginated URL
97
            // see: https://github.com/nystudio107/craft-seomatic/issues/375#issuecomment-488369209
98
            $url = $pageInfo->getPageUrl($pageInfo->currentPage);
99
            if ($stripQueryParams) {
100
                $url = preg_replace('/\?.*/', '', $url);
101
            }
102
            if (!empty($url)) {
103
                $url = UrlHelper::absoluteUrlWithProtocol($url);
104
                Seomatic::$seomaticVariable->meta->canonicalUrl = $url;
105
                $canonical = Seomatic::$seomaticVariable->link->get('canonical');
106
                if ($canonical !== null) {
107
                    $canonical->href = $url;
108
                }
109
            }
110
            // Set the previous URL
111
            $url = $pageInfo->getPrevUrl();
112
            if ($stripQueryParams) {
113
                $url = preg_replace('/\?.*/', '', $url);
114
            }
115
            if (!empty($url)) {
116
                $url = UrlHelper::absoluteUrlWithProtocol($url);
117
                $metaTag = Seomatic::$plugin->link->create([
0 ignored issues
show
Unused Code introduced by
The assignment to $metaTag is dead and can be removed.
Loading history...
118
                    'rel' => 'prev',
119
                    'href' => $url,
120
                ]);
121
            }
122
            // Set the next URL
123
            $url = $pageInfo->getNextUrl();
124
            if ($stripQueryParams) {
125
                $url = preg_replace('/\?.*/', '', $url);
126
            }
127
            if (!empty($url)) {
128
                $url = UrlHelper::absoluteUrlWithProtocol($url);
129
                $metaTag = Seomatic::$plugin->link->create([
130
                    'rel' => 'next',
131
                    'href' => $url,
132
                ]);
133
            }
134
            // If this page is paginated, we need to factor that into the cache key
135
            // We also need to re-add the hreflangs
136
            if (Seomatic::$plugin->metaContainers->paginationPage !== '1') {
137
                if (Seomatic::$settings->addHrefLang && Seomatic::$settings->addPaginatedHreflang) {
138
                    self::addMetaLinkHrefLang();
139
                }
140
            }
141
        }
142
    }
143
144
    /**
145
     * Include any headers for this request
146
     */
147
    public static function includeHttpHeaders()
148
    {
149
        self::addCspHeaders();
150
        // Don't include headers for any response code >= 400
151
        $request = Craft::$app->getRequest();
152
        if (!$request->isConsoleRequest) {
153
            $response = Craft::$app->getResponse();
154
            if ($response->statusCode >= 400 || SeomaticHelper::isPreview()) {
155
                return;
156
            }
157
        }
158
        // Assuming they have headersEnabled, add the response code to the headers
159
        if (Seomatic::$settings->headersEnabled) {
160
            $response = Craft::$app->getResponse();
161
            // X-Robots-Tag header
162
            $robots = Seomatic::$seomaticVariable->tag->get('robots');
163
            if ($robots !== null && $robots->include) {
164
                $robotsArray = $robots->renderAttributes();
165
                $content = $robotsArray['content'] ?? '';
166
                if (!empty($content)) {
167
                    // The content property can be a string or an array
168
                    if (is_array($content)) {
169
                        $headerValue = '';
170
                        foreach ($content as $contentVal) {
171
                            $headerValue .= ($contentVal . ',');
172
                        }
173
                        $headerValue = rtrim($headerValue, ',');
174
                    } else {
175
                        $headerValue = $content;
176
                    }
177
                    $response->headers->set('X-Robots-Tag', $headerValue);
178
                }
179
            }
180
            // Link canonical header
181
            $canonical = Seomatic::$seomaticVariable->link->get('canonical');
182
            if ($canonical !== null && $canonical->include) {
183
                $canonicalArray = $canonical->renderAttributes();
184
                $href = $canonicalArray['href'] ?? '';
185
                if (!empty($href)) {
186
                    // The href property can be a string or an array
187
                    if (is_array($href)) {
188
                        $headerValue = '';
189
                        foreach ($href as $hrefVal) {
190
                            $headerValue .= ('<' . $hrefVal . '>' . ',');
191
                        }
192
                        $headerValue = rtrim($headerValue, ',');
193
                    } else {
194
                        $headerValue = '<' . $href . '>';
195
                    }
196
                    $headerValue .= "; rel='canonical'";
197
                    $response->headers->add('Link', $headerValue);
198
                }
199
            }
200
            // Referrer-Policy header
201
            $referrer = Seomatic::$seomaticVariable->tag->get('referrer');
202
            if ($referrer !== null && $referrer->include) {
203
                $referrerArray = $referrer->renderAttributes();
204
                $content = $referrerArray['content'] ?? '';
205
                if (!empty($content)) {
206
                    // The content property can be a string or an array
207
                    if (is_array($content)) {
208
                        $headerValue = '';
209
                        foreach ($content as $contentVal) {
210
                            $headerValue .= ($contentVal . ',');
211
                        }
212
                        $headerValue = rtrim($headerValue, ',');
213
                    } else {
214
                        $headerValue = $content;
215
                    }
216
                    $response->headers->add('Referrer-Policy', $headerValue);
217
                }
218
            }
219
            // The X-Powered-By tag
220
            if (Seomatic::$settings->generatorEnabled) {
221
                $response->headers->add('X-Powered-By', 'SEOmatic');
222
            }
223
        }
224
    }
225
226
    /**
227
     * Add the Content-Security-Policy script-src headers
228
     */
229
    public static function addCspHeaders()
230
    {
231
        $cspNonces = self::getCspNonces();
232
        $container = Seomatic::$plugin->script->container();
233
        if ($container !== null) {
234
            $container->addNonceHeaders($cspNonces);
235
        }
236
    }
237
238
    /**
239
     * Get all of the CSP Nonces from containers that can have them
240
     *
241
     * @return array
242
     */
243
    public static function getCspNonces(): array
244
    {
245
        $cspNonces = [];
246
        // Add in any fixed policies from Settings
247
        if (!empty(Seomatic::$settings->cspScriptSrcPolicies)) {
248
            $fixedCsps = Seomatic::$settings->cspScriptSrcPolicies;
249
            $iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($fixedCsps));
250
            foreach ($iterator as $value) {
251
                $cspNonces[] = $value;
252
            }
253
        }
254
        // Add in any CSP nonce headers
255
        $container = Seomatic::$plugin->jsonLd->container();
256
        if ($container !== null) {
257
            $cspNonces = array_merge($cspNonces, $container->getCspNonces());
258
        }
259
        $container = Seomatic::$plugin->script->container();
260
        if ($container !== null) {
261
            $cspNonces = array_merge($cspNonces, $container->getCspNonces());
262
        }
263
264
        return $cspNonces;
265
    }
266
267
    /**
268
     * Add the Content-Security-Policy script-src tags
269
     */
270
    public static function addCspTags()
271
    {
272
        $cspNonces = self::getCspNonces();
273
        $container = Seomatic::$plugin->script->container();
274
        if ($container !== null) {
275
            $container->addNonceTags($cspNonces);
276
        }
277
    }
278
279
    /**
280
     * Add any custom/dynamic meta to the containers
281
     *
282
     * @param string|null $uri The URI of the route to add dynamic metadata for
283
     * @param int|null $siteId The siteId of the current site
284
     */
285
    public static function addDynamicMetaToContainers(string $uri = null, int $siteId = null)
286
    {
287
        Craft::beginProfile('DynamicMeta::addDynamicMetaToContainers', __METHOD__);
288
        $request = Craft::$app->getRequest();
289
        // Don't add dynamic meta to console requests, they have no concept of a URI or segments
290
        if (!$request->getIsConsoleRequest()) {
291
            $response = Craft::$app->getResponse();
292
            if ($response->statusCode < 400) {
293
                self::addMetaJsonLdBreadCrumbs($siteId);
294
                if (Seomatic::$settings->addHrefLang) {
295
                    self::addMetaLinkHrefLang($uri, $siteId);
296
                }
297
                self::addSameAsMeta();
298
                $metaSiteVars = Seomatic::$plugin->metaContainers->metaSiteVars;
299
                $jsonLd = Seomatic::$plugin->jsonLd->get('identity');
300
                if ($jsonLd !== null) {
301
                    self::addOpeningHours($jsonLd, $metaSiteVars->identity);
0 ignored issues
show
Bug introduced by
It seems like $metaSiteVars->identity can also be of type array; however, parameter $entity of nystudio107\seomatic\hel...Meta::addOpeningHours() does only seem to accept null|nystudio107\seomatic\models\Entity, maybe add an additional type check? ( Ignorable by Annotation )

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

301
                    self::addOpeningHours($jsonLd, /** @scrutinizer ignore-type */ $metaSiteVars->identity);
Loading history...
302
                    self::addContactPoints($jsonLd, $metaSiteVars->identity);
0 ignored issues
show
Bug introduced by
It seems like $metaSiteVars->identity can also be of type array; however, parameter $entity of nystudio107\seomatic\hel...eta::addContactPoints() does only seem to accept nystudio107\seomatic\models\Entity, maybe add an additional type check? ( Ignorable by Annotation )

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

302
                    self::addContactPoints($jsonLd, /** @scrutinizer ignore-type */ $metaSiteVars->identity);
Loading history...
303
                }
304
                $jsonLd = Seomatic::$plugin->jsonLd->get('creator');
305
                if ($jsonLd !== null) {
306
                    self::addOpeningHours($jsonLd, $metaSiteVars->creator);
307
                    self::addContactPoints($jsonLd, $metaSiteVars->creator);
308
                }
309
                // Allow modules/plugins a chance to add dynamic meta
310
                $event = new AddDynamicMetaEvent([
311
                    'uri' => $uri,
312
                    'siteId' => $siteId,
313
                ]);
314
                Event::trigger(static::class, self::EVENT_ADD_DYNAMIC_META, $event);
315
            }
316
        }
317
        Craft::endProfile('DynamicMeta::addDynamicMetaToContainers', __METHOD__);
318
    }
319
320
    /**
321
     * Add breadcrumbs to the MetaJsonLdContainer
322
     *
323
     * @param int|null $siteId
324
     */
325
    public static function addMetaJsonLdBreadCrumbs(int $siteId = null)
326
    {
327
        Craft::beginProfile('DynamicMeta::addMetaJsonLdBreadCrumbs', __METHOD__);
328
        $position = 0;
329
        if ($siteId === null) {
330
            $siteId = Craft::$app->getSites()->currentSite->id
331
                ?? Craft::$app->getSites()->primarySite->id
332
                ?? 1;
333
        }
334
        $site = Craft::$app->getSites()->getSiteById($siteId);
335
        if ($site === null) {
336
            return;
337
        }
338
        try {
339
            $siteUrl = SiteHelper::siteEnabledWithUrls($siteId) ? $site->baseUrl : Craft::$app->getSites()->getPrimarySite()->baseUrl;
340
        } catch (SiteNotFoundException $e) {
341
            $siteUrl = Craft::$app->getConfig()->getGeneral()->siteUrl;
342
            Craft::error($e->getMessage(), __METHOD__);
343
        }
344
        if (!empty(Seomatic::$settings->siteUrlOverride)) {
345
            try {
346
                $siteUrl = UrlHelper::getSiteUrlOverrideSetting($siteId);
347
            } catch (Throwable $e) {
348
                // That's okay
349
            }
350
        }
351
        $siteUrl = $siteUrl ?: '/';
352
        /** @var BreadcrumbList $crumbs */
353
        $crumbs = Seomatic::$plugin->jsonLd->create([
354
            'type' => 'BreadcrumbList',
355
            'name' => 'Breadcrumbs',
356
            'description' => 'Breadcrumbs list',
357
        ], false);
358
        // Include the Homepage in the breadcrumbs, if includeHomepageInBreadcrumbs is true
359
        $element = null;
360
        if (Seomatic::$settings->includeHomepageInBreadcrumbs) {
361
            /** @var Element $element */
362
            $position++;
363
            $element = Craft::$app->getElements()->getElementByUri('__home__', $siteId, true);
364
            if ($element) {
365
                $uri = $element->uri === '__home__' ? '' : ($element->uri ?? '');
366
                try {
367
                    $id = UrlHelper::siteUrl($uri, null, null, $siteId);
368
                } catch (Exception $e) {
369
                    $id = $siteUrl;
370
                    Craft::error($e->getMessage(), __METHOD__);
371
                }
372
                $item = UrlHelper::stripQueryString($id);
373
                $item = UrlHelper::absoluteUrlWithProtocol($item);
374
                $listItem = MetaJsonLd::create('ListItem', [
375
                    'position' => $position,
376
                    'name' => $element->title,
377
                    'item' => $item,
378
                    '@id' => $id,
379
                ]);
380
                $crumbs->itemListElement[] = $listItem;
381
            } else {
382
                $item = UrlHelper::stripQueryString($siteUrl);
383
                $item = UrlHelper::absoluteUrlWithProtocol($item);
384
                $crumbs->itemListElement[] = MetaJsonLd::create('ListItem', [
385
                    'position' => $position,
386
                    'name' => 'Homepage',
387
                    'item' => $item,
388
                    '@id' => $siteUrl,
389
                ]);
390
            }
391
        }
392
        // Build up the segments, and look for elements that match
393
        $uri = '';
394
        $segments = Craft::$app->getRequest()->getSegments();
395
        /** @var Element|null $lastElement */
396
        $lastElement = Seomatic::$matchedElement;
397
        if ($lastElement && $element) {
398
            if ($lastElement->uri !== '__home__' && $element->uri) {
399
                $path = $lastElement->uri;
400
                $segments = array_values(array_filter(explode('/', $path), function($segment) {
0 ignored issues
show
Bug introduced by
It seems like $path can also be of type null; however, parameter $string of explode() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

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

400
                $segments = array_values(array_filter(explode('/', /** @scrutinizer ignore-type */ $path), function($segment) {
Loading history...
401
                    return $segment !== '';
402
                }));
403
            }
404
        }
405
        // Parse through the segments looking for elements that match
406
        foreach ($segments as $segment) {
407
            $uri .= $segment;
408
            /** @var Element|null $element */
409
            $element = Craft::$app->getElements()->getElementByUri($uri, $siteId, true);
410
            if ($element && $element->uri) {
411
                $position++;
412
                $uri = $element->uri === '__home__' ? '' : $element->uri;
413
                try {
414
                    $id = UrlHelper::siteUrl($uri, null, null, $siteId);
415
                } catch (Exception $e) {
416
                    $id = $siteUrl;
417
                    Craft::error($e->getMessage(), __METHOD__);
418
                }
419
                $item = UrlHelper::stripQueryString($id);
420
                $item = UrlHelper::absoluteUrlWithProtocol($item);
421
                $crumbs->itemListElement[] = MetaJsonLd::create('ListItem', [
422
                    'position' => $position,
423
                    'name' => $element->title,
424
                    'item' => $item,
425
                    '@id' => $id,
426
                ]);
427
            }
428
            $uri .= '/';
429
        }
430
        if (!empty($crumbs->itemListElement)) {
431
            Seomatic::$plugin->jsonLd->add($crumbs);
432
        }
433
        Craft::endProfile('DynamicMeta::addMetaJsonLdBreadCrumbs', __METHOD__);
434
    }
435
436
    /**
437
     * Add meta hreflang tags if there is more than one site
438
     *
439
     * @param string $uri
440
     * @param int|null $siteId
441
     */
442
    public static function addMetaLinkHrefLang(string $uri = null, int $siteId = null)
443
    {
444
        Craft::beginProfile('DynamicMeta::addMetaLinkHrefLang', __METHOD__);
445
        $siteLocalizedUrls = self::getLocalizedUrls($uri, $siteId);
446
        $currentPaginationUrl = null;
447
        if (Seomatic::$plugin->metaContainers->paginationPage !== '1') {
448
            $currentPaginationUrl = Seomatic::$seomaticVariable->meta->canonicalUrl ?? null;
449
        }
450
        if (!empty($siteLocalizedUrls)) {
451
            // Add the rel=alternate tag
452
            $metaTag = Seomatic::$plugin->link->create([
453
                'rel' => 'alternate',
454
                'hreflang' => [],
455
                'href' => [],
456
            ]);
457
            // Add the alternate language link rel's
458
            if (count($siteLocalizedUrls) > 1) {
459
                foreach ($siteLocalizedUrls as $siteLocalizedUrl) {
460
                    $url = $siteLocalizedUrl['url'];
461
                    if ($siteLocalizedUrl['current']) {
462
                        $url = $currentPaginationUrl ?? $siteLocalizedUrl['url'];
463
                    }
464
                    $metaTag->hreflang[] = $siteLocalizedUrl['hreflangLanguage'];
465
                    $metaTag->href[] = $url;
466
                    // Add the x-default hreflang
467
                    if ($siteLocalizedUrl['primary'] && Seomatic::$settings->addXDefaultHrefLang) {
468
                        $metaTag->hreflang[] = 'x-default';
469
                        $metaTag->href[] = $siteLocalizedUrl['url'];
470
                    }
471
                }
472
                Seomatic::$plugin->link->add($metaTag);
473
            }
474
            // Add in the og:locale:alternate tags
475
            $ogLocaleAlternate = Seomatic::$plugin->tag->get('og:locale:alternate');
476
            if (count($siteLocalizedUrls) > 1 && $ogLocaleAlternate) {
477
                $ogContentArray = [];
478
                foreach ($siteLocalizedUrls as $siteLocalizedUrl) {
479
                    if (!in_array($siteLocalizedUrl['ogLanguage'], $ogContentArray, true) &&
480
                        Craft::$app->language !== $siteLocalizedUrl['language']) {
481
                        $ogContentArray[] = $siteLocalizedUrl['ogLanguage'];
482
                    }
483
                }
484
                $ogLocaleAlternate->content = $ogContentArray;
485
            }
486
        }
487
        Craft::endProfile('DynamicMeta::addMetaLinkHrefLang', __METHOD__);
488
    }
489
490
    /**
491
     * Return a list of localized URLs that are in the current site's group
492
     * The current URI is used if $uri is null. Similarly, the current site is
493
     * used if $siteId is null.
494
     * The resulting array of arrays has `id`, `language`, `ogLanguage`,
495
     * `hreflangLanguage`, and `url` as keys.
496
     *
497
     * @param string|null $uri
498
     * @param int|null $siteId
499
     *
500
     * @return array
501
     */
502
    public static function getLocalizedUrls(string $uri = null, int $siteId = null): array
503
    {
504
        Craft::beginProfile('DynamicMeta::getLocalizedUrls', __METHOD__);
505
        $localizedUrls = [];
506
        // No pagination params for URLs
507
        $urlParams = null;
508
        // Get the request URI
509
        if ($uri === null) {
510
            $requestUri = Craft::$app->getRequest()->pathInfo;
511
        } else {
512
            $requestUri = $uri;
513
        }
514
        // Get the site to use
515
        if ($siteId === null) {
516
            try {
517
                $thisSite = Craft::$app->getSites()->getCurrentSite();
518
            } catch (SiteNotFoundException $e) {
519
                $thisSite = null;
520
                Craft::error($e->getMessage(), __METHOD__);
521
            }
522
        } else {
523
            $thisSite = Craft::$app->getSites()->getSiteById($siteId);
524
        }
525
        // Bail if we can't get a site
526
        if ($thisSite === null) {
527
            return $localizedUrls;
528
        }
529
        if (Seomatic::$settings->siteGroupsSeparate) {
530
            // Get only the sites that are in the current site's group
531
            try {
532
                $siteGroup = $thisSite->getGroup();
533
            } catch (InvalidConfigException $e) {
534
                $siteGroup = null;
535
                Craft::error($e->getMessage(), __METHOD__);
536
            }
537
            // Bail if we can't get a site group
538
            if ($siteGroup === null) {
539
                return $localizedUrls;
540
            }
541
            $sites = $siteGroup->getSites();
542
        } else {
543
            $sites = Craft::$app->getSites()->getAllSites();
544
        }
545
        $elements = Craft::$app->getElements();
546
        foreach ($sites as $site) {
547
            $includeUrl = true;
548
            $matchedElement = $elements->getElementByUri($requestUri, $thisSite->id, true);
549
            if ($matchedElement) {
550
                $url = $elements->getElementUriForSite($matchedElement->getId(), $site->id);
551
                // See if they have disabled sitemaps or robots for this entry,
552
                // and if so, don't include it in the hreflang
553
                $element = null;
554
                if ($url) {
555
                    /** @var Element $element */
556
                    $element = $elements->getElementByUri($url, $site->id, false);
557
                }
558
                if ($element !== null) {
559
                    /** @var MetaBundle $metaBundle */
560
                    list($sourceId, $sourceBundleType, $sourceHandle, $sourceSiteId, $typeId)
561
                        = Seomatic::$plugin->metaBundles->getMetaSourceFromElement($element);
562
                    $metaBundle = Seomatic::$plugin->metaBundles->getMetaBundleBySourceId(
563
                        $sourceBundleType,
564
                        $sourceId,
565
                        $sourceSiteId
566
                    );
567
                    if ($metaBundle !== null) {
568
                        // If robots contains 'none' or 'noindex' don't include the URL
569
                        $robotsArray = explode(',', $metaBundle->metaGlobalVars->robots);
570
                        if (in_array('noindex', $robotsArray, true) || in_array('none', $robotsArray, true)) {
571
                            $includeUrl = false;
572
                        }
573
                    }
574
                    $fieldHandles = FieldHelper::fieldsOfTypeFromElement(
575
                        $element,
576
                        FieldHelper::SEO_SETTINGS_CLASS_KEY,
577
                        true
578
                    );
579
                    foreach ($fieldHandles as $fieldHandle) {
580
                        if (!empty($element->$fieldHandle)) {
581
                            /** @var MetaBundle $fieldMetaBundle */
582
                            $fieldMetaBundle = $element->$fieldHandle;
583
                            /** @var SeoSettings $seoSettingsField */
584
                            $seoSettingsField = Craft::$app->getFields()->getFieldByHandle($fieldHandle);
585
                            if ($seoSettingsField !== null) {
586
                                // If robots is set to 'none' don't include the URL
587
                                if ($seoSettingsField->generalTabEnabled
588
                                    && in_array('robots', $seoSettingsField->generalEnabledFields, false)
589
                                    && !Seomatic::$plugin->helper->isInherited($fieldMetaBundle->metaGlobalVars, 'robots')
0 ignored issues
show
Bug introduced by
It seems like $fieldMetaBundle->metaGlobalVars can also be of type array and null; however, parameter $settingCollection of nystudio107\seomatic\ser...s\Helper::isInherited() does only seem to accept nystudio107\seomatic\base\InheritableSettingsModel, maybe add an additional type check? ( Ignorable by Annotation )

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

589
                                    && !Seomatic::$plugin->helper->isInherited(/** @scrutinizer ignore-type */ $fieldMetaBundle->metaGlobalVars, 'robots')
Loading history...
590
                                ) {
591
                                    // If robots contains 'none' or 'noindex' don't include the URL
592
                                    $robotsArray = explode(',', $fieldMetaBundle->metaGlobalVars->robots);
593
                                    if (in_array('noindex', $robotsArray, true) || in_array('none', $robotsArray, true)) {
594
                                        $includeUrl = false;
595
                                    } else {
596
                                        // Otherwise, include the URL
597
                                        $includeUrl = true;
598
                                    }
599
                                }
600
                            }
601
                        }
602
                    }
603
                    // Never include the URL if the element isn't enabled for the site
604
                    if (isset($element->enabledForSite) && !(bool)$element->enabledForSite) {
605
                        $includeUrl = false;
606
                    }
607
                } else {
608
                    $includeUrl = false;
609
                }
610
                $url = ($url === '__home__') ? '' : $url;
611
            } else {
612
                try {
613
                    $url = SiteHelper::siteEnabledWithUrls($site->id) ? UrlHelper::siteUrl($requestUri, $urlParams, null, $site->id)
614
                        : Craft::$app->getSites()->getPrimarySite()->baseUrl;
615
                } catch (SiteNotFoundException $e) {
616
                    $url = '';
617
                    Craft::error($e->getMessage(), __METHOD__);
618
                } catch (Exception $e) {
619
                    $url = '';
620
                    Craft::error($e->getMessage(), __METHOD__);
621
                }
622
            }
623
            $url = $url ?? '';
624
            if (!UrlHelper::isAbsoluteUrl($url)) {
625
                try {
626
                    $url = UrlHelper::siteUrl($url, $urlParams, null, $site->id);
627
                } catch (Exception $e) {
628
                    $url = '';
629
                    Craft::error($e->getMessage(), __METHOD__);
630
                }
631
            }
632
            // Strip any query string params, and make sure we have an absolute URL with protocol
633
            if ($urlParams === null) {
634
                $url = UrlHelper::stripQueryString($url);
635
            }
636
            $url = UrlHelper::absoluteUrlWithProtocol($url);
637
            $url = self::sanitizeUrl($url);
638
            $language = $site->language;
639
            $ogLanguage = LocalizationHelper::normalizeOgLocaleLanguage($language);
640
            $hreflangLanguage = $language;
641
            $hreflangLanguage = strtolower($hreflangLanguage);
642
            $hreflangLanguage = str_replace('_', '-', $hreflangLanguage);
643
            $primary = Seomatic::$settings->xDefaultSite == 0 ? $site->primary : Seomatic::$settings->xDefaultSite == $site->id;
644
            if ($includeUrl) {
645
                $localizedUrls[] = [
646
                    'id' => $site->id,
647
                    'language' => $language,
648
                    'ogLanguage' => $ogLanguage,
649
                    'hreflangLanguage' => $hreflangLanguage,
650
                    'url' => $url,
651
                    'primary' => $primary,
652
                    'current' => $thisSite->id === $site->id,
653
                ];
654
            }
655
        }
656
        Craft::endProfile('DynamicMeta::getLocalizedUrls', __METHOD__);
657
658
        return $localizedUrls;
659
    }
660
661
    /**
662
     * Return a sanitized URL with the query string stripped
663
     *
664
     * @param string $url
665
     * @param bool $checkStatus
666
     *
667
     * @return string
668
     */
669 2
    public static function sanitizeUrl(string $url, bool $checkStatus = true, bool $stripQueryString = true): string
670
    {
671
        // Remove the query string
672 2
        if ($stripQueryString) {
673 2
            $url = UrlHelper::stripQueryString($url);
674
        }
675 2
        $url = UrlHelper::encodeUrlQueryParams(TextHelper::sanitizeUserInput($url));
676
677
        // If this is a >= 400 status code, set the canonical URL to nothing
678 2
        if ($checkStatus && !Craft::$app->getRequest()->getIsConsoleRequest() && Craft::$app->getResponse()->statusCode >= 400) {
679
            $url = '';
680
        }
681
682 2
        return $url;
683
    }
684
685
    /**
686
     * Add the Same As meta tags and JSON-LD
687
     */
688
    public static function addSameAsMeta()
689
    {
690
        Craft::beginProfile('DynamicMeta::addSameAsMeta', __METHOD__);
691
        $metaContainers = Seomatic::$plugin->metaContainers;
692
        $sameAsUrls = [];
693
        if (!empty($metaContainers->metaSiteVars->sameAsLinks)) {
694
            $sameAsUrls = ArrayHelper::getColumn($metaContainers->metaSiteVars->sameAsLinks, 'url', false);
695
            $sameAsUrls = array_values(array_filter($sameAsUrls));
696
        }
697
        // Facebook OpenGraph
698
        $ogSeeAlso = Seomatic::$plugin->tag->get('og:see_also');
699
        if ($ogSeeAlso) {
0 ignored issues
show
introduced by
$ogSeeAlso is of type nystudio107\seomatic\models\MetaTag, thus it always evaluated to true.
Loading history...
700
            $ogSeeAlso->content = $sameAsUrls;
701
        }
702
        // Site Identity JSON-LD
703
        $identity = Seomatic::$plugin->jsonLd->get('identity');
704
        /** @var Thing $identity */
705
        if ($identity !== null && property_exists($identity, 'sameAs')) {
706
            $identity->sameAs = $sameAsUrls;
707
        }
708
        Craft::endProfile('DynamicMeta::addSameAsMeta', __METHOD__);
709
    }
710
711
    /**
712
     * Add the OpeningHoursSpecific to the $jsonLd based on the Entity settings
713
     *
714
     * @param MetaJsonLd|LocalBusiness $jsonLd
715
     * @param Entity|null $entity
716
     */
717
    public static function addOpeningHours(MetaJsonLd $jsonLd, $entity)
718
    {
719
        Craft::beginProfile('DynamicMeta::addOpeningHours', __METHOD__);
720
        if ($jsonLd instanceof LocalBusiness && $entity !== null) {
721
            $openingHours = [];
722
            $days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
723
            $times = $entity->localBusinessOpeningHours;
724
            $index = 0;
725
            foreach ($times as $hours) {
726
                $openTime = '';
727
                $closeTime = '';
728
                if (!empty($hours['open'])) {
729
                    /** @var DateTime $dateTime */
730
                    try {
731
                        $dateTime = DateTimeHelper::toDateTime($hours['open']['date'], false, false);
732
                    } catch (\Exception $e) {
733
                        $dateTime = false;
734
                    }
735
                    if ($dateTime !== false) {
736
                        $openTime = $dateTime->format('H:i:s');
737
                    }
738
                }
739
                if (!empty($hours['close'])) {
740
                    /** @var DateTime $dateTime */
741
                    try {
742
                        $dateTime = DateTimeHelper::toDateTime($hours['close']['date'], false, false);
743
                    } catch (\Exception $e) {
744
                        $dateTime = false;
745
                    }
746
                    if ($dateTime !== false) {
747
                        $closeTime = $dateTime->format('H:i:s');
748
                    }
749
                }
750
                if ($openTime && $closeTime) {
751
                    /** @var OpeningHoursSpecification $hours */
752
                    $hours = Seomatic::$plugin->jsonLd->create([
753
                        'type' => 'OpeningHoursSpecification',
754
                        'opens' => $openTime,
755
                        'closes' => $closeTime,
756
                        'dayOfWeek' => [$days[$index]],
757
                    ], false);
758
                    $openingHours[] = $hours;
759
                }
760
                $index++;
761
            }
762
            $jsonLd->openingHoursSpecification = $openingHours;
763
        }
764
        Craft::endProfile('DynamicMeta::addOpeningHours', __METHOD__);
765
    }
766
767
    /**
768
     * Add the ContactPoint to the $jsonLd based on the Entity settings
769
     *
770
     * @param MetaJsonLd $jsonLd
771
     * @param Entity $entity
772
     */
773
    public static function addContactPoints(MetaJsonLd $jsonLd, Entity $entity)
774
    {
775
        Craft::beginProfile('DynamicMeta::addContactPoints', __METHOD__);
776
        if ($jsonLd instanceof Organization && $entity !== null) {
777
            /** @var Organization $jsonLd */
778
            $contactPoints = [];
779
            if (is_array($entity->organizationContactPoints)) {
780
                foreach ($entity->organizationContactPoints as $contacts) {
781
                    /** @var ContactPoint $contact */
782
                    $contact = Seomatic::$plugin->jsonLd->create([
783
                        'type' => 'ContactPoint',
784
                        'telephone' => $contacts['telephone'],
785
                        'contactType' => $contacts['contactType'],
786
                    ], false);
787
                    $contactPoints[] = $contact;
788
                }
789
            }
790
            $jsonLd->contactPoint = $contactPoints;
791
        }
792
        Craft::endProfile('DynamicMeta::addContactPoints', __METHOD__);
793
    }
794
795
    /**
796
     * Normalize the array of opening hours passed in
797
     *
798
     * @param $value
799
     */
800
    public static function normalizeTimes(&$value)
801
    {
802
        if (is_string($value)) {
803
            $value = Json::decode($value);
804
        }
805
        $normalized = [];
806
        $times = ['open', 'close'];
807
        for ($day = 0; $day <= 6; $day++) {
808
            foreach ($times as $time) {
809
                if (isset($value[$day][$time])
810
                    && ($date = DateTimeHelper::toDateTime($value[$day][$time])) !== false
811
                ) {
812
                    $normalized[$day][$time] = (array)($date);
813
                } else {
814
                    $normalized[$day][$time] = null;
815
                }
816
            }
817
        }
818
819
        $value = $normalized;
820
    }
821
}
822