1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* SEOmatic plugin for Craft CMS |
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\models\MetaLink; |
35
|
|
|
use nystudio107\seomatic\Seomatic; |
36
|
|
|
use nystudio107\seomatic\services\Helper as SeomaticHelper; |
37
|
|
|
use RecursiveArrayIterator; |
38
|
|
|
use RecursiveIteratorIterator; |
39
|
|
|
use Throwable; |
40
|
|
|
use yii\base\Event; |
41
|
|
|
use yii\base\Exception; |
42
|
|
|
use yii\base\InvalidConfigException; |
43
|
|
|
use function count; |
44
|
|
|
use function in_array; |
45
|
|
|
use function is_array; |
46
|
|
|
use function is_string; |
47
|
|
|
|
48
|
|
|
/** |
49
|
|
|
* @author nystudio107 |
50
|
|
|
* @package Seomatic |
51
|
|
|
* @since 3.0.0 |
52
|
|
|
*/ |
53
|
|
|
class DynamicMeta |
54
|
|
|
{ |
55
|
|
|
// Constants |
56
|
|
|
// ========================================================================= |
57
|
|
|
|
58
|
|
|
/** |
59
|
|
|
* @event AddDynamicMetaEvent The event that is triggered when SEOmatic has |
60
|
|
|
* included the standard meta containers, and gives your plugin/module |
61
|
|
|
* the chance to add whatever custom dynamic meta items you like |
62
|
|
|
* |
63
|
|
|
* --- |
64
|
|
|
* ```php |
65
|
|
|
* use nystudio107\seomatic\events\AddDynamicMetaEvent; |
66
|
|
|
* use nystudio107\seomatic\helpers\DynamicMeta; |
67
|
|
|
* use yii\base\Event; |
68
|
|
|
* Event::on(DynamicMeta::class, DynamicMeta::EVENT_ADD_DYNAMIC_META, function(AddDynamicMetaEvent $e) { |
69
|
|
|
* // Add whatever dynamic meta items to the containers as you like |
70
|
|
|
* }); |
71
|
|
|
* ``` |
72
|
|
|
*/ |
73
|
|
|
public const EVENT_ADD_DYNAMIC_META = 'addDynamicMeta'; |
74
|
|
|
|
75
|
|
|
// Static Methods |
76
|
|
|
// ========================================================================= |
77
|
|
|
|
78
|
|
|
/** |
79
|
|
|
* Paginate based on the passed in Paginate variable as returned from the |
80
|
|
|
* Twig {% paginate %} tag: |
81
|
|
|
* https://docs.craftcms.com/v3/templating/tags/paginate.html#the-pageInfo-variable |
82
|
|
|
* |
83
|
|
|
* @param ?Paginate $pageInfo |
84
|
|
|
*/ |
85
|
|
|
public static function paginate(?Paginate $pageInfo) |
86
|
|
|
{ |
87
|
|
|
if ($pageInfo !== null && $pageInfo->currentPage !== null) { |
88
|
|
|
// Let the meta containers know that this page is paginated |
89
|
|
|
Seomatic::$plugin->metaContainers->paginationPage = (string)$pageInfo->currentPage; |
90
|
|
|
// See if we should strip the query params |
91
|
|
|
$stripQueryParams = true; |
92
|
|
|
$pageTrigger = Craft::$app->getConfig()->getGeneral()->pageTrigger; |
93
|
|
|
// Is this query string-based pagination? |
94
|
|
|
if ($pageTrigger[0] === '?') { |
95
|
|
|
$stripQueryParams = false; |
96
|
|
|
} |
97
|
|
|
// Set the canonical URL to be the paginated URL |
98
|
|
|
// see: https://github.com/nystudio107/craft-seomatic/issues/375#issuecomment-488369209 |
99
|
|
|
$url = $pageInfo->getPageUrl($pageInfo->currentPage); |
100
|
|
|
if ($stripQueryParams) { |
101
|
|
|
$url = preg_replace('/\?.*/', '', $url); |
102
|
|
|
} |
103
|
|
|
if (!empty($url)) { |
104
|
|
|
$url = UrlHelper::absoluteUrlWithProtocol($url); |
105
|
|
|
Seomatic::$seomaticVariable->meta->canonicalUrl = $url; |
106
|
|
|
$canonical = Seomatic::$seomaticVariable->link->get('canonical'); |
107
|
|
|
if ($canonical !== null) { |
108
|
|
|
$canonical->href = $url; |
109
|
|
|
} |
110
|
|
|
} |
111
|
|
|
// Set the previous URL |
112
|
|
|
$url = $pageInfo->getPrevUrl(); |
113
|
|
|
if ($stripQueryParams) { |
114
|
|
|
$url = preg_replace('/\?.*/', '', $url); |
115
|
|
|
} |
116
|
|
|
if (!empty($url)) { |
117
|
|
|
$url = UrlHelper::absoluteUrlWithProtocol($url); |
118
|
|
|
$metaTag = Seomatic::$plugin->link->create([ |
|
|
|
|
119
|
|
|
'rel' => 'prev', |
120
|
|
|
'href' => $url, |
121
|
|
|
]); |
122
|
|
|
} |
123
|
|
|
// Set the next URL |
124
|
|
|
$url = $pageInfo->getNextUrl(); |
125
|
|
|
if ($stripQueryParams) { |
126
|
|
|
$url = preg_replace('/\?.*/', '', $url); |
127
|
|
|
} |
128
|
|
|
if (!empty($url)) { |
129
|
|
|
$url = UrlHelper::absoluteUrlWithProtocol($url); |
130
|
|
|
$metaTag = Seomatic::$plugin->link->create([ |
131
|
|
|
'rel' => 'next', |
132
|
|
|
'href' => $url, |
133
|
|
|
]); |
134
|
|
|
} |
135
|
|
|
// If this page is paginated, we need to factor that into the cache key |
136
|
|
|
// We also need to re-add the hreflangs |
137
|
|
|
if (Seomatic::$plugin->metaContainers->paginationPage !== '1') { |
138
|
|
|
if (Seomatic::$settings->addHrefLang && Seomatic::$settings->addPaginatedHreflang) { |
139
|
|
|
self::addMetaLinkHrefLang(); |
140
|
|
|
} |
141
|
|
|
} |
142
|
|
|
} |
143
|
|
|
} |
144
|
|
|
|
145
|
|
|
/** |
146
|
|
|
* Include any headers for this request |
147
|
|
|
*/ |
148
|
|
|
public static function includeHttpHeaders() |
149
|
|
|
{ |
150
|
|
|
self::addCspHeaders(); |
151
|
|
|
// Don't include headers for any response code >= 400 |
152
|
|
|
$request = Craft::$app->getRequest(); |
153
|
|
|
if (!$request->isConsoleRequest) { |
154
|
|
|
$response = Craft::$app->getResponse(); |
155
|
|
|
if ($response->statusCode >= 400 || SeomaticHelper::isPreview()) { |
156
|
|
|
return; |
157
|
|
|
} |
158
|
|
|
} |
159
|
|
|
// Assuming they have headersEnabled, add the response code to the headers |
160
|
|
|
if (Seomatic::$settings->headersEnabled) { |
161
|
|
|
$response = Craft::$app->getResponse(); |
162
|
|
|
// X-Robots-Tag header |
163
|
|
|
$robots = Seomatic::$seomaticVariable->tag->get('robots'); |
164
|
|
|
if ($robots !== null && $robots->include) { |
165
|
|
|
$robotsArray = $robots->renderAttributes(); |
166
|
|
|
$content = $robotsArray['content'] ?? ''; |
167
|
|
|
if (!empty($content)) { |
168
|
|
|
// The content property can be a string or an array |
169
|
|
|
if (is_array($content)) { |
170
|
|
|
$headerValue = ''; |
171
|
|
|
foreach ($content as $contentVal) { |
172
|
|
|
$headerValue .= ($contentVal . ','); |
173
|
|
|
} |
174
|
|
|
$headerValue = rtrim($headerValue, ','); |
175
|
|
|
} else { |
176
|
|
|
$headerValue = $content; |
177
|
|
|
} |
178
|
|
|
$response->headers->set('X-Robots-Tag', $headerValue); |
179
|
|
|
} |
180
|
|
|
} |
181
|
|
|
// Link canonical header |
182
|
|
|
$canonical = Seomatic::$seomaticVariable->link->get('canonical'); |
183
|
|
|
if ($canonical !== null && $canonical->include) { |
184
|
|
|
$canonicalArray = $canonical->renderAttributes(); |
185
|
|
|
$href = $canonicalArray['href'] ?? ''; |
186
|
|
|
if (!empty($href)) { |
187
|
|
|
// The href property can be a string or an array |
188
|
|
|
if (is_array($href)) { |
189
|
|
|
$headerValue = ''; |
190
|
|
|
foreach ($href as $hrefVal) { |
191
|
|
|
$headerValue .= ('<' . $hrefVal . '>' . ','); |
192
|
|
|
} |
193
|
|
|
$headerValue = rtrim($headerValue, ','); |
194
|
|
|
} else { |
195
|
|
|
$headerValue = '<' . $href . '>'; |
196
|
|
|
} |
197
|
|
|
$headerValue .= "; rel='canonical'"; |
198
|
|
|
$response->headers->add('Link', $headerValue); |
199
|
|
|
} |
200
|
|
|
} |
201
|
|
|
// Referrer-Policy header |
202
|
|
|
$referrer = Seomatic::$seomaticVariable->tag->get('referrer'); |
203
|
|
|
if ($referrer !== null && $referrer->include) { |
204
|
|
|
$referrerArray = $referrer->renderAttributes(); |
205
|
|
|
$content = $referrerArray['content'] ?? ''; |
206
|
|
|
if (!empty($content)) { |
207
|
|
|
// The content property can be a string or an array |
208
|
|
|
if (is_array($content)) { |
209
|
|
|
$headerValue = ''; |
210
|
|
|
foreach ($content as $contentVal) { |
211
|
|
|
$headerValue .= ($contentVal . ','); |
212
|
|
|
} |
213
|
|
|
$headerValue = rtrim($headerValue, ','); |
214
|
|
|
} else { |
215
|
|
|
$headerValue = $content; |
216
|
|
|
} |
217
|
|
|
$response->headers->add('Referrer-Policy', $headerValue); |
218
|
|
|
} |
219
|
|
|
} |
220
|
|
|
// The X-Powered-By tag |
221
|
|
|
if (Seomatic::$settings->generatorEnabled) { |
222
|
|
|
$response->headers->add('X-Powered-By', 'SEOmatic'); |
223
|
|
|
} |
224
|
|
|
} |
225
|
|
|
} |
226
|
|
|
|
227
|
|
|
/** |
228
|
|
|
* Add the Content-Security-Policy script-src headers |
229
|
|
|
*/ |
230
|
|
|
public static function addCspHeaders() |
231
|
|
|
{ |
232
|
|
|
$cspNonces = self::getCspNonces(); |
233
|
|
|
$container = Seomatic::$plugin->script->container(); |
234
|
|
|
if ($container !== null) { |
235
|
|
|
$container->addNonceHeaders($cspNonces); |
236
|
|
|
} |
237
|
|
|
} |
238
|
|
|
|
239
|
|
|
/** |
240
|
|
|
* Get all of the CSP Nonces from containers that can have them |
241
|
|
|
* |
242
|
|
|
* @return array |
243
|
|
|
*/ |
244
|
|
|
public static function getCspNonces(): array |
245
|
|
|
{ |
246
|
|
|
$cspNonces = []; |
247
|
|
|
// Add in any fixed policies from Settings |
248
|
|
|
if (!empty(Seomatic::$settings->cspScriptSrcPolicies)) { |
249
|
|
|
$fixedCsps = Seomatic::$settings->cspScriptSrcPolicies; |
250
|
|
|
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($fixedCsps)); |
251
|
|
|
foreach ($iterator as $value) { |
252
|
|
|
$cspNonces[] = $value; |
253
|
|
|
} |
254
|
|
|
} |
255
|
|
|
// Add in any CSP nonce headers |
256
|
|
|
$container = Seomatic::$plugin->jsonLd->container(); |
257
|
|
|
if ($container !== null) { |
258
|
|
|
$cspNonces = array_merge($cspNonces, $container->getCspNonces()); |
259
|
|
|
} |
260
|
|
|
$container = Seomatic::$plugin->script->container(); |
261
|
|
|
if ($container !== null) { |
262
|
|
|
$cspNonces = array_merge($cspNonces, $container->getCspNonces()); |
263
|
|
|
} |
264
|
|
|
|
265
|
|
|
return $cspNonces; |
266
|
|
|
} |
267
|
|
|
|
268
|
|
|
/** |
269
|
|
|
* Add the Content-Security-Policy script-src tags |
270
|
|
|
*/ |
271
|
|
|
public static function addCspTags() |
272
|
|
|
{ |
273
|
|
|
$cspNonces = self::getCspNonces(); |
274
|
|
|
$container = Seomatic::$plugin->script->container(); |
275
|
|
|
if ($container !== null) { |
276
|
|
|
$container->addNonceTags($cspNonces); |
277
|
|
|
} |
278
|
|
|
} |
279
|
|
|
|
280
|
|
|
/** |
281
|
|
|
* Add any custom/dynamic meta to the containers |
282
|
|
|
* |
283
|
|
|
* @param string|null $uri The URI of the route to add dynamic metadata for |
284
|
|
|
* @param int|null $siteId The siteId of the current site |
285
|
|
|
*/ |
286
|
|
|
public static function addDynamicMetaToContainers(string $uri = null, int $siteId = null) |
287
|
|
|
{ |
288
|
|
|
Craft::beginProfile('DynamicMeta::addDynamicMetaToContainers', __METHOD__); |
289
|
|
|
$request = Craft::$app->getRequest(); |
290
|
|
|
// Don't add dynamic meta to console requests, they have no concept of a URI or segments |
291
|
|
|
if (!$request->getIsConsoleRequest()) { |
292
|
|
|
$response = Craft::$app->getResponse(); |
293
|
|
|
if ($response->statusCode < 400) { |
294
|
|
|
self::addMetaJsonLdBreadCrumbs($siteId); |
295
|
|
|
if (Seomatic::$settings->addHrefLang) { |
296
|
|
|
self::addMetaLinkHrefLang($uri, $siteId); |
297
|
|
|
} |
298
|
|
|
self::addSameAsMeta(); |
299
|
|
|
$metaSiteVars = Seomatic::$plugin->metaContainers->metaSiteVars; |
300
|
|
|
$jsonLd = Seomatic::$plugin->jsonLd->get('identity'); |
301
|
|
|
if ($jsonLd !== null) { |
302
|
|
|
self::addOpeningHours($jsonLd, $metaSiteVars->identity); |
|
|
|
|
303
|
|
|
self::addContactPoints($jsonLd, $metaSiteVars->identity); |
|
|
|
|
304
|
|
|
} |
305
|
|
|
$jsonLd = Seomatic::$plugin->jsonLd->get('creator'); |
306
|
|
|
if ($jsonLd !== null) { |
307
|
|
|
self::addOpeningHours($jsonLd, $metaSiteVars->creator); |
308
|
|
|
self::addContactPoints($jsonLd, $metaSiteVars->creator); |
309
|
|
|
} |
310
|
|
|
// Allow modules/plugins a chance to add dynamic meta |
311
|
|
|
$event = new AddDynamicMetaEvent([ |
312
|
|
|
'uri' => $uri, |
313
|
|
|
'siteId' => $siteId, |
314
|
|
|
]); |
315
|
|
|
Event::trigger(static::class, self::EVENT_ADD_DYNAMIC_META, $event); |
316
|
|
|
} |
317
|
|
|
} |
318
|
|
|
Craft::endProfile('DynamicMeta::addDynamicMetaToContainers', __METHOD__); |
319
|
|
|
} |
320
|
|
|
|
321
|
|
|
/** |
322
|
|
|
* Add breadcrumbs to the MetaJsonLdContainer |
323
|
|
|
* |
324
|
|
|
* @param int|null $siteId |
325
|
|
|
*/ |
326
|
|
|
public static function addMetaJsonLdBreadCrumbs(int $siteId = null) |
327
|
|
|
{ |
328
|
|
|
Craft::beginProfile('DynamicMeta::addMetaJsonLdBreadCrumbs', __METHOD__); |
329
|
|
|
$position = 0; |
330
|
|
|
if ($siteId === null) { |
331
|
|
|
$siteId = Craft::$app->getSites()->currentSite->id |
332
|
|
|
?? Craft::$app->getSites()->primarySite->id |
333
|
|
|
?? 1; |
334
|
|
|
} |
335
|
|
|
$site = Craft::$app->getSites()->getSiteById($siteId); |
336
|
|
|
if ($site === null) { |
337
|
|
|
return; |
338
|
|
|
} |
339
|
|
|
$siteUrl = '/'; |
|
|
|
|
340
|
|
|
try { |
341
|
|
|
$siteUrl = SiteHelper::siteEnabledWithUrls($siteId) ? $site->baseUrl : Craft::$app->getSites()->getPrimarySite()->baseUrl; |
342
|
|
|
} catch (SiteNotFoundException $e) { |
343
|
|
|
Craft::error($e->getMessage(), __METHOD__); |
344
|
|
|
} |
345
|
|
|
if (!empty(Seomatic::$settings->siteUrlOverride)) { |
346
|
|
|
try { |
347
|
|
|
$siteUrl = UrlHelper::getSiteUrlOverrideSetting($siteId); |
348
|
|
|
} catch (Throwable $e) { |
349
|
|
|
// That's okay |
350
|
|
|
} |
351
|
|
|
} |
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) { |
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|null $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
|
|
|
/** @var MetaLink $metaTag */ |
453
|
|
|
$metaTag = Seomatic::$plugin->link->create([ |
454
|
|
|
'rel' => 'alternate', |
455
|
|
|
'hreflang' => [], |
456
|
|
|
'href' => [], |
457
|
|
|
]); |
458
|
|
|
// Add the alternate language link rel's |
459
|
|
|
if (count($siteLocalizedUrls) > 1) { |
460
|
|
|
foreach ($siteLocalizedUrls as $siteLocalizedUrl) { |
461
|
|
|
$url = $siteLocalizedUrl['url']; |
462
|
|
|
if ($siteLocalizedUrl['current']) { |
463
|
|
|
$url = $currentPaginationUrl ?? $siteLocalizedUrl['url']; |
464
|
|
|
} |
465
|
|
|
$metaTag->hreflang[] = $siteLocalizedUrl['hreflangLanguage']; |
466
|
|
|
$metaTag->href[] = $url; |
467
|
|
|
// Add the x-default hreflang |
468
|
|
|
if ($siteLocalizedUrl['primary'] && Seomatic::$settings->addXDefaultHrefLang) { |
469
|
|
|
$metaTag->hreflang[] = 'x-default'; |
470
|
|
|
$metaTag->href[] = $siteLocalizedUrl['url']; |
471
|
|
|
} |
472
|
|
|
} |
473
|
|
|
Seomatic::$plugin->link->add($metaTag); |
474
|
|
|
} |
475
|
|
|
// Add in the og:locale:alternate tags |
476
|
|
|
$ogLocaleAlternate = Seomatic::$plugin->tag->get('og:locale:alternate'); |
477
|
|
|
if (count($siteLocalizedUrls) > 1 && $ogLocaleAlternate) { |
478
|
|
|
$ogContentArray = []; |
479
|
|
|
foreach ($siteLocalizedUrls as $siteLocalizedUrl) { |
480
|
|
|
if (!in_array($siteLocalizedUrl['ogLanguage'], $ogContentArray, true) && |
481
|
|
|
Craft::$app->language !== $siteLocalizedUrl['language']) { |
482
|
|
|
$ogContentArray[] = $siteLocalizedUrl['ogLanguage']; |
483
|
|
|
} |
484
|
|
|
} |
485
|
|
|
$ogLocaleAlternate->content = $ogContentArray; |
486
|
|
|
} |
487
|
|
|
} |
488
|
|
|
Craft::endProfile('DynamicMeta::addMetaLinkHrefLang', __METHOD__); |
489
|
|
|
} |
490
|
|
|
|
491
|
|
|
/** |
492
|
|
|
* Return a list of localized URLs that are in the current site's group |
493
|
|
|
* The current URI is used if $uri is null. Similarly, the current site is |
494
|
|
|
* used if $siteId is null. |
495
|
|
|
* The resulting array of arrays has `id`, `language`, `ogLanguage`, |
496
|
|
|
* `hreflangLanguage`, and `url` as keys. |
497
|
|
|
* |
498
|
|
|
* @param string|null $uri |
499
|
|
|
* @param int|null $siteId |
500
|
|
|
* |
501
|
|
|
* @return array |
502
|
|
|
*/ |
503
|
|
|
public static function getLocalizedUrls(string $uri = null, int $siteId = null): array |
504
|
|
|
{ |
505
|
|
|
Craft::beginProfile('DynamicMeta::getLocalizedUrls', __METHOD__); |
506
|
|
|
$localizedUrls = []; |
507
|
|
|
// No pagination params for URLs |
508
|
|
|
$urlParams = null; |
509
|
|
|
// Get the request URI |
510
|
|
|
if ($uri === null) { |
511
|
|
|
$requestUri = Craft::$app->getRequest()->pathInfo; |
512
|
|
|
} else { |
513
|
|
|
$requestUri = $uri; |
514
|
|
|
} |
515
|
|
|
// Get the site to use |
516
|
|
|
if ($siteId === null) { |
517
|
|
|
try { |
518
|
|
|
$thisSite = Craft::$app->getSites()->getCurrentSite(); |
519
|
|
|
} catch (SiteNotFoundException $e) { |
520
|
|
|
$thisSite = null; |
521
|
|
|
Craft::error($e->getMessage(), __METHOD__); |
522
|
|
|
} |
523
|
|
|
} else { |
524
|
|
|
$thisSite = Craft::$app->getSites()->getSiteById($siteId); |
525
|
|
|
} |
526
|
|
|
// Bail if we can't get a site |
527
|
|
|
if ($thisSite === null) { |
528
|
|
|
return $localizedUrls; |
529
|
|
|
} |
530
|
|
|
if (Seomatic::$settings->siteGroupsSeparate) { |
531
|
|
|
// Get only the sites that are in the current site's group |
532
|
|
|
try { |
533
|
|
|
$siteGroup = $thisSite->getGroup(); |
534
|
|
|
} catch (InvalidConfigException $e) { |
535
|
|
|
$siteGroup = null; |
536
|
|
|
Craft::error($e->getMessage(), __METHOD__); |
537
|
|
|
} |
538
|
|
|
// Bail if we can't get a site group |
539
|
|
|
if ($siteGroup === null) { |
540
|
|
|
return $localizedUrls; |
541
|
|
|
} |
542
|
|
|
$sites = $siteGroup->getSites(); |
543
|
|
|
} else { |
544
|
|
|
$sites = Craft::$app->getSites()->getAllSites(); |
545
|
|
|
} |
546
|
|
|
$elements = Craft::$app->getElements(); |
547
|
|
|
foreach ($sites as $site) { |
548
|
|
|
$includeUrl = true; |
549
|
|
|
$matchedElement = $elements->getElementByUri($requestUri, $thisSite->id, true); |
550
|
|
|
if ($matchedElement) { |
551
|
|
|
$url = $elements->getElementUriForSite($matchedElement->getId(), $site->id); |
552
|
|
|
// See if they have disabled sitemaps or robots for this entry, |
553
|
|
|
// and if so, don't include it in the hreflang |
554
|
|
|
$element = null; |
555
|
|
|
if ($url) { |
556
|
|
|
/** @var Element $element */ |
557
|
|
|
$element = $elements->getElementByUri($url, $site->id, false); |
558
|
|
|
} |
559
|
|
|
if ($element !== null) { |
560
|
|
|
/** @var MetaBundle $metaBundle */ |
561
|
|
|
list($sourceId, $sourceBundleType, $sourceHandle, $sourceSiteId, $typeId) |
562
|
|
|
= Seomatic::$plugin->metaBundles->getMetaSourceFromElement($element); |
563
|
|
|
$metaBundle = Seomatic::$plugin->metaBundles->getMetaBundleBySourceId( |
564
|
|
|
$sourceBundleType, |
565
|
|
|
$sourceId, |
566
|
|
|
$sourceSiteId |
567
|
|
|
); |
568
|
|
|
if ($metaBundle !== null) { |
569
|
|
|
// If robots contains 'none' or 'noindex' don't include the URL |
570
|
|
|
$robotsArray = explode(',', $metaBundle->metaGlobalVars->robots); |
571
|
|
|
if (in_array('noindex', $robotsArray, true) || in_array('none', $robotsArray, true)) { |
572
|
|
|
$includeUrl = false; |
573
|
|
|
} |
574
|
|
|
} |
575
|
|
|
$fieldHandles = FieldHelper::fieldsOfTypeFromElement( |
576
|
|
|
$element, |
577
|
|
|
FieldHelper::SEO_SETTINGS_CLASS_KEY, |
578
|
|
|
true |
579
|
|
|
); |
580
|
|
|
foreach ($fieldHandles as $fieldHandle) { |
581
|
|
|
if (!empty($element->$fieldHandle)) { |
582
|
|
|
/** @var MetaBundle $fieldMetaBundle */ |
583
|
|
|
$fieldMetaBundle = $element->$fieldHandle; |
584
|
|
|
/** @var SeoSettings $seoSettingsField */ |
585
|
|
|
$seoSettingsField = Craft::$app->getFields()->getFieldByHandle($fieldHandle); |
586
|
|
|
if ($seoSettingsField !== null) { |
587
|
|
|
// If robots is set to 'none' don't include the URL |
588
|
|
|
if ($seoSettingsField->generalTabEnabled |
589
|
|
|
&& in_array('robots', $seoSettingsField->generalEnabledFields, false) |
590
|
|
|
&& !Seomatic::$plugin->helper->isInherited($fieldMetaBundle->metaGlobalVars, 'robots') |
|
|
|
|
591
|
|
|
) { |
592
|
|
|
// If robots contains 'none' or 'noindex' don't include the URL |
593
|
|
|
$robotsArray = explode(',', $fieldMetaBundle->metaGlobalVars->robots); |
594
|
|
|
if (in_array('noindex', $robotsArray, true) || in_array('none', $robotsArray, true)) { |
595
|
|
|
$includeUrl = false; |
596
|
|
|
} else { |
597
|
|
|
// Otherwise, include the URL |
598
|
|
|
$includeUrl = true; |
599
|
|
|
} |
600
|
|
|
} |
601
|
|
|
} |
602
|
|
|
} |
603
|
|
|
} |
604
|
|
|
// Never include the URL if the element isn't enabled for the site |
605
|
|
|
if (isset($element->enabledForSite) && !(bool)$element->enabledForSite) { |
606
|
|
|
$includeUrl = false; |
607
|
|
|
} |
608
|
|
|
} else { |
609
|
|
|
$includeUrl = false; |
610
|
|
|
} |
611
|
|
|
$url = ($url === '__home__') ? '' : $url; |
612
|
|
|
} else { |
613
|
|
|
try { |
614
|
|
|
$url = SiteHelper::siteEnabledWithUrls($site->id) ? UrlHelper::siteUrl($requestUri, $urlParams, null, $site->id) |
615
|
|
|
: Craft::$app->getSites()->getPrimarySite()->baseUrl; |
616
|
|
|
} catch (SiteNotFoundException $e) { |
617
|
|
|
$url = ''; |
618
|
|
|
Craft::error($e->getMessage(), __METHOD__); |
619
|
|
|
} catch (Exception $e) { |
620
|
|
|
$url = ''; |
621
|
|
|
Craft::error($e->getMessage(), __METHOD__); |
622
|
|
|
} |
623
|
|
|
} |
624
|
|
|
$url = $url ?? ''; |
625
|
|
|
if (!UrlHelper::isAbsoluteUrl($url)) { |
626
|
|
|
try { |
627
|
|
|
$url = UrlHelper::siteUrl($url, $urlParams, null, $site->id); |
628
|
|
|
} catch (Exception $e) { |
629
|
|
|
$url = ''; |
630
|
|
|
Craft::error($e->getMessage(), __METHOD__); |
631
|
|
|
} |
632
|
|
|
} |
633
|
|
|
// Strip any query string params, and make sure we have an absolute URL with protocol |
634
|
|
|
if ($urlParams === null) { |
635
|
|
|
$url = UrlHelper::stripQueryString($url); |
636
|
|
|
} |
637
|
|
|
$url = UrlHelper::absoluteUrlWithProtocol($url); |
638
|
|
|
|
639
|
|
|
$url = self::sanitizeUrl($url); |
640
|
|
|
$language = $site->language; |
641
|
|
|
$ogLanguage = LocalizationHelper::normalizeOgLocaleLanguage($language); |
642
|
|
|
$hreflangLanguage = $language; |
643
|
|
|
$hreflangLanguage = strtolower($hreflangLanguage); |
644
|
|
|
$hreflangLanguage = str_replace('_', '-', $hreflangLanguage); |
645
|
|
|
$primary = Seomatic::$settings->xDefaultSite == 0 ? $site->primary : Seomatic::$settings->xDefaultSite == $site->id; |
646
|
|
|
if ($includeUrl) { |
647
|
|
|
$localizedUrls[] = [ |
648
|
|
|
'id' => $site->id, |
649
|
|
|
'language' => $language, |
650
|
|
|
'ogLanguage' => $ogLanguage, |
651
|
|
|
'hreflangLanguage' => $hreflangLanguage, |
652
|
|
|
'url' => $url, |
653
|
|
|
'primary' => $primary, |
654
|
|
|
'current' => $thisSite->id === $site->id, |
655
|
|
|
]; |
656
|
|
|
} |
657
|
|
|
} |
658
|
|
|
Craft::endProfile('DynamicMeta::getLocalizedUrls', __METHOD__); |
659
|
|
|
|
660
|
|
|
return $localizedUrls; |
661
|
|
|
} |
662
|
|
|
|
663
|
|
|
/** |
664
|
|
|
* Return a sanitized URL with the query string stripped |
665
|
|
|
* |
666
|
|
|
* @param string $url |
667
|
|
|
* @param bool $checkStatus |
668
|
|
|
* |
669
|
|
|
* @return string |
670
|
|
|
*/ |
671
|
|
|
public static function sanitizeUrl(string $url, bool $checkStatus = true, bool $stripQueryString = true): string |
672
|
|
|
{ |
673
|
|
|
// Remove the query string |
674
|
|
|
if ($stripQueryString) { |
675
|
|
|
$url = UrlHelper::stripQueryString($url); |
676
|
|
|
} |
677
|
|
|
$url = UrlHelper::encodeUrlQueryParams(TextHelper::sanitizeUserInput($url)); |
678
|
|
|
|
679
|
|
|
// If this is a >= 400 status code, set the canonical URL to nothing |
680
|
|
|
if ($checkStatus && !Craft::$app->getRequest()->getIsConsoleRequest() && Craft::$app->getResponse()->statusCode >= 400) { |
681
|
|
|
$url = ''; |
682
|
|
|
} |
683
|
|
|
|
684
|
|
|
return $url; |
685
|
|
|
} |
686
|
|
|
|
687
|
|
|
/** |
688
|
|
|
* Add the Same As meta tags and JSON-LD |
689
|
|
|
*/ |
690
|
|
|
public static function addSameAsMeta() |
691
|
|
|
{ |
692
|
|
|
Craft::beginProfile('DynamicMeta::addSameAsMeta', __METHOD__); |
693
|
|
|
$metaContainers = Seomatic::$plugin->metaContainers; |
694
|
|
|
$sameAsUrls = []; |
695
|
|
|
if (!empty($metaContainers->metaSiteVars->sameAsLinks)) { |
696
|
|
|
$sameAsUrls = ArrayHelper::getColumn($metaContainers->metaSiteVars->sameAsLinks, 'url', false); |
697
|
|
|
$sameAsUrls = array_values(array_filter($sameAsUrls)); |
698
|
|
|
} |
699
|
|
|
// Facebook OpenGraph |
700
|
|
|
$ogSeeAlso = Seomatic::$plugin->tag->get('og:see_also'); |
701
|
|
|
if ($ogSeeAlso) { |
|
|
|
|
702
|
|
|
$ogSeeAlso->content = $sameAsUrls; |
703
|
|
|
} |
704
|
|
|
// Site Identity JSON-LD |
705
|
|
|
$identity = Seomatic::$plugin->jsonLd->get('identity'); |
706
|
|
|
/** @var Thing|null $identity */ |
707
|
|
|
if ($identity !== null && property_exists($identity, 'sameAs')) { |
708
|
|
|
$identity->sameAs = $sameAsUrls; |
709
|
|
|
} |
710
|
|
|
Craft::endProfile('DynamicMeta::addSameAsMeta', __METHOD__); |
711
|
|
|
} |
712
|
|
|
|
713
|
|
|
/** |
714
|
|
|
* Add the OpeningHoursSpecific to the $jsonLd based on the Entity settings |
715
|
|
|
* |
716
|
|
|
* @param MetaJsonLd $jsonLd |
717
|
|
|
* @param ?Entity $entity |
718
|
|
|
*/ |
719
|
|
|
public static function addOpeningHours(MetaJsonLd $jsonLd, ?Entity $entity) |
720
|
|
|
{ |
721
|
|
|
Craft::beginProfile('DynamicMeta::addOpeningHours', __METHOD__); |
722
|
|
|
if ($jsonLd instanceof LocalBusiness && $entity !== null) { |
723
|
|
|
/** @var LocalBusiness $jsonLd */ |
724
|
|
|
$openingHours = []; |
725
|
|
|
$days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']; |
726
|
|
|
$times = $entity->localBusinessOpeningHours; |
727
|
|
|
$index = 0; |
728
|
|
|
foreach ($times as $hours) { |
729
|
|
|
$openTime = ''; |
730
|
|
|
$closeTime = ''; |
731
|
|
|
if (!empty($hours['open'])) { |
732
|
|
|
/** @var DateTime $dateTime */ |
733
|
|
|
try { |
734
|
|
|
$dateTime = DateTimeHelper::toDateTime($hours['open']['date'], false, false); |
735
|
|
|
} catch (\Exception $e) { |
736
|
|
|
$dateTime = false; |
737
|
|
|
} |
738
|
|
|
if ($dateTime !== false) { |
739
|
|
|
$openTime = $dateTime->format('H:i:s'); |
740
|
|
|
} |
741
|
|
|
} |
742
|
|
|
if (!empty($hours['close'])) { |
743
|
|
|
/** @var DateTime $dateTime */ |
744
|
|
|
try { |
745
|
|
|
$dateTime = DateTimeHelper::toDateTime($hours['close']['date'], false, false); |
746
|
|
|
} catch (\Exception $e) { |
747
|
|
|
$dateTime = false; |
748
|
|
|
} |
749
|
|
|
if ($dateTime !== false) { |
750
|
|
|
$closeTime = $dateTime->format('H:i:s'); |
751
|
|
|
} |
752
|
|
|
} |
753
|
|
|
if ($openTime && $closeTime) { |
754
|
|
|
/** @var OpeningHoursSpecification $hours */ |
755
|
|
|
$hours = Seomatic::$plugin->jsonLd->create([ |
756
|
|
|
'type' => 'OpeningHoursSpecification', |
757
|
|
|
'opens' => $openTime, |
758
|
|
|
'closes' => $closeTime, |
759
|
|
|
'dayOfWeek' => [$days[$index]], |
760
|
|
|
], false); |
761
|
|
|
$openingHours[] = $hours; |
762
|
|
|
} |
763
|
|
|
$index++; |
764
|
|
|
} |
765
|
|
|
$jsonLd->openingHoursSpecification = $openingHours; |
766
|
|
|
} |
767
|
|
|
Craft::endProfile('DynamicMeta::addOpeningHours', __METHOD__); |
768
|
|
|
} |
769
|
|
|
|
770
|
|
|
/** |
771
|
|
|
* Add the ContactPoint to the $jsonLd based on the Entity settings |
772
|
|
|
* |
773
|
|
|
* @param MetaJsonLd $jsonLd |
774
|
|
|
* @param Entity|null $entity |
775
|
|
|
*/ |
776
|
|
|
public static function addContactPoints(MetaJsonLd $jsonLd, ?Entity $entity) |
777
|
|
|
{ |
778
|
|
|
Craft::beginProfile('DynamicMeta::addContactPoints', __METHOD__); |
779
|
|
|
if ($jsonLd instanceof Organization && $entity !== null) { |
780
|
|
|
/** @var Organization $jsonLd */ |
781
|
|
|
$contactPoints = []; |
782
|
|
|
if (is_array($entity->organizationContactPoints)) { |
|
|
|
|
783
|
|
|
foreach ($entity->organizationContactPoints as $contacts) { |
784
|
|
|
/** @var ContactPoint $contact */ |
785
|
|
|
$contact = Seomatic::$plugin->jsonLd->create([ |
786
|
|
|
'type' => 'ContactPoint', |
787
|
|
|
'telephone' => $contacts['telephone'], |
788
|
|
|
'contactType' => $contacts['contactType'], |
789
|
|
|
], false); |
790
|
|
|
$contactPoints[] = $contact; |
791
|
|
|
} |
792
|
|
|
} |
793
|
|
|
$jsonLd->contactPoint = $contactPoints; |
794
|
|
|
} |
795
|
|
|
Craft::endProfile('DynamicMeta::addContactPoints', __METHOD__); |
796
|
|
|
} |
797
|
|
|
|
798
|
|
|
/** |
799
|
|
|
* Normalize the array of opening hours passed in |
800
|
|
|
* |
801
|
|
|
* @param $value |
802
|
|
|
*/ |
803
|
|
|
public static function normalizeTimes(&$value) |
804
|
|
|
{ |
805
|
|
|
if (is_string($value)) { |
806
|
|
|
$value = Json::decode($value); |
807
|
|
|
} |
808
|
|
|
$normalized = []; |
809
|
|
|
$times = ['open', 'close']; |
810
|
|
|
for ($day = 0; $day <= 6; $day++) { |
811
|
|
|
foreach ($times as $time) { |
812
|
|
|
if (isset($value[$day][$time]) |
813
|
|
|
&& ($date = DateTimeHelper::toDateTime($value[$day][$time])) !== false |
814
|
|
|
) { |
815
|
|
|
$normalized[$day][$time] = (array)($date); |
816
|
|
|
} else { |
817
|
|
|
$normalized[$day][$time] = null; |
818
|
|
|
} |
819
|
|
|
} |
820
|
|
|
} |
821
|
|
|
|
822
|
|
|
$value = $normalized; |
823
|
|
|
} |
824
|
|
|
} |
825
|
|
|
|