Passed
Push — v3 ( 646bcf...7f2a90 )
by Andrew
14:12 queued 24s
created

DynamicMeta::sanitizeUrl()   A

Complexity

Conditions 5
Paths 4

Size

Total Lines 14
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 5.0729

Importance

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

304
                    self::addOpeningHours($jsonLd, /** @scrutinizer ignore-type */ $metaSiteVars->identity);
Loading history...
305
                    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

305
                    self::addContactPoints($jsonLd, /** @scrutinizer ignore-type */ $metaSiteVars->identity);
Loading history...
306
                }
307
                $jsonLd = Seomatic::$plugin->jsonLd->get('creator');
308
                if ($jsonLd !== null) {
309
                    self::addOpeningHours($jsonLd, $metaSiteVars->creator);
310
                    self::addContactPoints($jsonLd, $metaSiteVars->creator);
311
                }
312
                // Allow modules/plugins a chance to add dynamic meta
313
                $event = new AddDynamicMetaEvent([
314
                    'uri' => $uri,
315
                    'siteId' => $siteId,
316
                ]);
317
                Event::trigger(static::class, self::EVENT_ADD_DYNAMIC_META, $event);
318
            }
319
        }
320
        Craft::endProfile('DynamicMeta::addDynamicMetaToContainers', __METHOD__);
321
    }
322
323
    /**
324
     * If this is the homepage, and the MainEntityOfPage is WebPage or a WebSite, set the name
325
     * and alternateName so it shows up in SERP as per:
326
     * https://developers.google.com/search/docs/appearance/site-names
327
     *
328
     * @return void
329
     */
330
    public static function handleHomepage()
331
    {
332
        if (Seomatic::$matchedElement && Seomatic::$matchedElement->uri === '__home__') {
0 ignored issues
show
Bug introduced by
Accessing uri on the interface craft\base\ElementInterface suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
333
            $mainEntity = Seomatic::$plugin->jsonLd->get('mainEntityOfPage');
334
            if ($mainEntity instanceof WebPage || $mainEntity instanceof WebSite) {
335
                /** WebPage $mainEntity */
336
                $mainEntity->name = "{{ seomatic.site.siteName }}";
337
                $mainEntity->alternateName = "{{ seomatic.site.siteAlternateName }}";
338
            }
339
        }
340
    }
341
342
    /**
343
     * Add breadcrumbs to the MetaJsonLdContainer
344
     *
345
     * @param int|null $siteId
346
     */
347
    public static function addMetaJsonLdBreadCrumbs(int $siteId = null)
348
    {
349
        Craft::beginProfile('DynamicMeta::addMetaJsonLdBreadCrumbs', __METHOD__);
350
        $position = 0;
351
        if ($siteId === null) {
352
            $siteId = Craft::$app->getSites()->currentSite->id
353
                ?? Craft::$app->getSites()->primarySite->id
354
                ?? 1;
355
        }
356
        $site = Craft::$app->getSites()->getSiteById($siteId);
357
        if ($site === null) {
358
            return;
359
        }
360
        try {
361
            $siteUrl = SiteHelper::siteEnabledWithUrls($siteId) ? $site->baseUrl : Craft::$app->getSites()->getPrimarySite()->baseUrl;
362
        } catch (SiteNotFoundException $e) {
363
            $siteUrl = Craft::$app->getConfig()->getGeneral()->siteUrl;
364
            Craft::error($e->getMessage(), __METHOD__);
365
        }
366
        if (!empty(Seomatic::$settings->siteUrlOverride)) {
367
            try {
368
                $siteUrl = UrlHelper::getSiteUrlOverrideSetting($siteId);
369
            } catch (Throwable $e) {
370
                // That's okay
371
            }
372
        }
373
        $siteUrl = $siteUrl ?: '/';
374
        /** @var BreadcrumbList $crumbs */
375
        $crumbs = Seomatic::$plugin->jsonLd->create([
376
            'type' => 'BreadcrumbList',
377
            'name' => 'Breadcrumbs',
378
            'description' => 'Breadcrumbs list',
379
        ], false);
380
        // Include the Homepage in the breadcrumbs, if includeHomepageInBreadcrumbs is true
381
        $element = null;
382
        if (Seomatic::$settings->includeHomepageInBreadcrumbs) {
383
            /** @var Element $element */
384
            $position++;
385
            $element = Craft::$app->getElements()->getElementByUri('__home__', $siteId, true);
386
            if ($element) {
387
                $uri = $element->uri === '__home__' ? '' : ($element->uri ?? '');
388
                try {
389
                    $id = UrlHelper::siteUrl($uri, null, null, $siteId);
390
                } catch (Exception $e) {
391
                    $id = $siteUrl;
392
                    Craft::error($e->getMessage(), __METHOD__);
393
                }
394
                $item = UrlHelper::stripQueryString($id);
395
                $item = UrlHelper::absoluteUrlWithProtocol($item);
396
                $listItem = MetaJsonLd::create('ListItem', [
397
                    'position' => $position,
398
                    'name' => $element->title,
399
                    'item' => $item,
400
                    '@id' => $id,
401
                ]);
402
                $crumbs->itemListElement[] = $listItem;
403
            } else {
404
                $item = UrlHelper::stripQueryString($siteUrl);
405
                $item = UrlHelper::absoluteUrlWithProtocol($item);
406
                $crumbs->itemListElement[] = MetaJsonLd::create('ListItem', [
407
                    'position' => $position,
408
                    'name' => 'Homepage',
409
                    'item' => $item,
410
                    '@id' => $siteUrl,
411
                ]);
412
            }
413
        }
414
        // Build up the segments, and look for elements that match
415
        $uri = '';
416
        $segments = Craft::$app->getRequest()->getSegments();
417
        /** @var Element|null $lastElement */
418
        $lastElement = Seomatic::$matchedElement;
419
        if ($lastElement && $element) {
420
            if ($lastElement->uri !== '__home__' && $element->uri) {
421
                $path = $lastElement->uri;
422
                $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

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

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