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([ |
|
|
|
|
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
|
|
|
$hrefVal = UrlHelper::encodeUrl($hrefVal); |
193
|
|
|
$headerValue .= ('<' . $hrefVal . '>' . ','); |
194
|
|
|
} |
195
|
|
|
$headerValue = rtrim($headerValue, ','); |
196
|
|
|
} else { |
197
|
|
|
$href = UrlHelper::encodeUrl($href); |
198
|
|
|
$headerValue = '<' . $href . '>'; |
199
|
|
|
} |
200
|
|
|
$headerValue .= "; rel='canonical'"; |
201
|
|
|
$response->headers->add('Link', $headerValue); |
202
|
|
|
} |
203
|
|
|
} |
204
|
|
|
// Referrer-Policy header |
205
|
|
|
$referrer = Seomatic::$seomaticVariable->tag->get('referrer'); |
206
|
|
|
if ($referrer !== null && $referrer->include) { |
207
|
|
|
$referrerArray = $referrer->renderAttributes(); |
208
|
|
|
$content = $referrerArray['content'] ?? ''; |
209
|
|
|
if (!empty($content)) { |
210
|
|
|
// The content property can be a string or an array |
211
|
|
|
if (is_array($content)) { |
212
|
|
|
$headerValue = ''; |
213
|
|
|
foreach ($content as $contentVal) { |
214
|
|
|
$headerValue .= ($contentVal . ','); |
215
|
|
|
} |
216
|
|
|
$headerValue = rtrim($headerValue, ','); |
217
|
|
|
} else { |
218
|
|
|
$headerValue = $content; |
219
|
|
|
} |
220
|
|
|
$response->headers->add('Referrer-Policy', $headerValue); |
221
|
|
|
} |
222
|
|
|
} |
223
|
|
|
// The X-Powered-By tag |
224
|
|
|
if (Seomatic::$settings->generatorEnabled) { |
225
|
|
|
$response->headers->add('X-Powered-By', 'SEOmatic'); |
226
|
|
|
} |
227
|
|
|
} |
228
|
|
|
} |
229
|
|
|
|
230
|
|
|
/** |
231
|
|
|
* Add the Content-Security-Policy script-src headers |
232
|
|
|
*/ |
233
|
|
|
public static function addCspHeaders() |
234
|
|
|
{ |
235
|
|
|
$cspNonces = self::getCspNonces(); |
236
|
|
|
$container = Seomatic::$plugin->script->container(); |
237
|
|
|
if ($container !== null) { |
238
|
|
|
$container->addNonceHeaders($cspNonces); |
239
|
|
|
} |
240
|
|
|
} |
241
|
|
|
|
242
|
|
|
/** |
243
|
|
|
* Get all of the CSP Nonces from containers that can have them |
244
|
|
|
* |
245
|
|
|
* @return array |
246
|
|
|
*/ |
247
|
|
|
public static function getCspNonces(): array |
248
|
|
|
{ |
249
|
|
|
$cspNonces = []; |
250
|
|
|
// Add in any fixed policies from Settings |
251
|
|
|
if (!empty(Seomatic::$settings->cspScriptSrcPolicies)) { |
252
|
|
|
$fixedCsps = Seomatic::$settings->cspScriptSrcPolicies; |
253
|
|
|
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($fixedCsps)); |
254
|
|
|
foreach ($iterator as $value) { |
255
|
|
|
$cspNonces[] = $value; |
256
|
|
|
} |
257
|
|
|
} |
258
|
|
|
// Add in any CSP nonce headers |
259
|
|
|
$container = Seomatic::$plugin->jsonLd->container(); |
260
|
|
|
if ($container !== null) { |
261
|
|
|
$cspNonces = array_merge($cspNonces, $container->getCspNonces()); |
262
|
|
|
} |
263
|
|
|
$container = Seomatic::$plugin->script->container(); |
264
|
|
|
if ($container !== null) { |
265
|
|
|
$cspNonces = array_merge($cspNonces, $container->getCspNonces()); |
266
|
|
|
} |
267
|
|
|
|
268
|
|
|
return $cspNonces; |
269
|
|
|
} |
270
|
|
|
|
271
|
|
|
/** |
272
|
|
|
* Add the Content-Security-Policy script-src tags |
273
|
|
|
*/ |
274
|
|
|
public static function addCspTags() |
275
|
|
|
{ |
276
|
|
|
$cspNonces = self::getCspNonces(); |
277
|
|
|
$container = Seomatic::$plugin->script->container(); |
278
|
|
|
if ($container !== null) { |
279
|
|
|
$container->addNonceTags($cspNonces); |
280
|
|
|
} |
281
|
|
|
} |
282
|
|
|
|
283
|
|
|
/** |
284
|
|
|
* Add any custom/dynamic meta to the containers |
285
|
|
|
* |
286
|
|
|
* @param string|null $uri The URI of the route to add dynamic metadata for |
287
|
|
|
* @param int|null $siteId The siteId of the current site |
288
|
|
|
*/ |
289
|
|
|
public static function addDynamicMetaToContainers(string $uri = null, int $siteId = null) |
290
|
|
|
{ |
291
|
|
|
Craft::beginProfile('DynamicMeta::addDynamicMetaToContainers', __METHOD__); |
292
|
|
|
$request = Craft::$app->getRequest(); |
293
|
|
|
// Don't add dynamic meta to console requests, they have no concept of a URI or segments |
294
|
|
|
if (!$request->getIsConsoleRequest()) { |
295
|
|
|
$response = Craft::$app->getResponse(); |
296
|
|
|
if ($response->statusCode < 400) { |
297
|
|
|
self::handleHomepage(); |
298
|
|
|
self::addMetaJsonLdBreadCrumbs($siteId); |
299
|
|
|
if (Seomatic::$settings->addHrefLang) { |
300
|
|
|
self::addMetaLinkHrefLang($uri, $siteId); |
301
|
|
|
} |
302
|
|
|
self::addSameAsMeta(); |
303
|
|
|
$metaSiteVars = Seomatic::$plugin->metaContainers->metaSiteVars; |
304
|
|
|
$jsonLd = Seomatic::$plugin->jsonLd->get('identity'); |
305
|
|
|
if ($jsonLd !== null) { |
306
|
|
|
self::addOpeningHours($jsonLd, $metaSiteVars->identity); |
|
|
|
|
307
|
|
|
self::addContactPoints($jsonLd, $metaSiteVars->identity); |
|
|
|
|
308
|
|
|
} |
309
|
|
|
$jsonLd = Seomatic::$plugin->jsonLd->get('creator'); |
310
|
|
|
if ($jsonLd !== null) { |
311
|
|
|
self::addOpeningHours($jsonLd, $metaSiteVars->creator); |
312
|
|
|
self::addContactPoints($jsonLd, $metaSiteVars->creator); |
313
|
|
|
} |
314
|
|
|
// Allow modules/plugins a chance to add dynamic meta |
315
|
|
|
$event = new AddDynamicMetaEvent([ |
316
|
|
|
'uri' => $uri, |
317
|
|
|
'siteId' => $siteId, |
318
|
|
|
]); |
319
|
|
|
Event::trigger(static::class, self::EVENT_ADD_DYNAMIC_META, $event); |
320
|
|
|
} |
321
|
|
|
} |
322
|
|
|
Craft::endProfile('DynamicMeta::addDynamicMetaToContainers', __METHOD__); |
323
|
|
|
} |
324
|
|
|
|
325
|
|
|
/** |
326
|
|
|
* If this is the homepage, and the MainEntityOfPage is WebPage or a WebSite, set the name |
327
|
|
|
* and alternateName so it shows up in SERP as per: |
328
|
|
|
* https://developers.google.com/search/docs/appearance/site-names |
329
|
|
|
* |
330
|
|
|
* @return void |
331
|
|
|
*/ |
332
|
|
|
public static function handleHomepage() |
333
|
|
|
{ |
334
|
|
|
if (Seomatic::$matchedElement && Seomatic::$matchedElement->uri === '__home__') { |
|
|
|
|
335
|
|
|
$mainEntity = Seomatic::$plugin->jsonLd->get('mainEntityOfPage'); |
336
|
|
|
if ($mainEntity instanceof WebPage || $mainEntity instanceof WebSite) { |
337
|
|
|
/** WebPage $mainEntity */ |
338
|
|
|
$mainEntity->name = "{{ seomatic.site.siteName }}"; |
339
|
|
|
$mainEntity->alternateName = "{{ seomatic.site.siteAlternateName }}"; |
340
|
|
|
} |
341
|
|
|
} |
342
|
|
|
} |
343
|
|
|
|
344
|
|
|
/** |
345
|
|
|
* Add breadcrumbs to the MetaJsonLdContainer |
346
|
|
|
* |
347
|
|
|
* @param int|null $siteId |
348
|
|
|
*/ |
349
|
|
|
public static function addMetaJsonLdBreadCrumbs(int $siteId = null) |
350
|
|
|
{ |
351
|
|
|
Craft::beginProfile('DynamicMeta::addMetaJsonLdBreadCrumbs', __METHOD__); |
352
|
|
|
$position = 0; |
353
|
|
|
if ($siteId === null) { |
354
|
|
|
$siteId = Craft::$app->getSites()->currentSite->id |
355
|
|
|
?? Craft::$app->getSites()->primarySite->id |
356
|
|
|
?? 1; |
357
|
|
|
} |
358
|
|
|
$site = Craft::$app->getSites()->getSiteById($siteId); |
359
|
|
|
if ($site === null) { |
360
|
|
|
return; |
361
|
|
|
} |
362
|
|
|
try { |
363
|
|
|
$siteUrl = SiteHelper::siteEnabledWithUrls($siteId) ? $site->baseUrl : Craft::$app->getSites()->getPrimarySite()->baseUrl; |
364
|
|
|
} catch (SiteNotFoundException $e) { |
365
|
|
|
$siteUrl = Craft::$app->getConfig()->getGeneral()->siteUrl; |
366
|
|
|
Craft::error($e->getMessage(), __METHOD__); |
367
|
|
|
} |
368
|
|
|
if (!empty(Seomatic::$settings->siteUrlOverride)) { |
369
|
|
|
try { |
370
|
|
|
$siteUrl = UrlHelper::getSiteUrlOverrideSetting($siteId); |
371
|
|
|
} catch (Throwable $e) { |
372
|
|
|
// That's okay |
373
|
|
|
} |
374
|
|
|
} |
375
|
|
|
$siteUrl = $siteUrl ?: '/'; |
376
|
|
|
/** @var BreadcrumbList $crumbs */ |
377
|
|
|
$crumbs = Seomatic::$plugin->jsonLd->create([ |
378
|
|
|
'type' => 'BreadcrumbList', |
379
|
|
|
'name' => 'Breadcrumbs', |
380
|
|
|
'description' => 'Breadcrumbs list', |
381
|
|
|
], false); |
382
|
|
|
// Include the Homepage in the breadcrumbs, if includeHomepageInBreadcrumbs is true |
383
|
|
|
$element = null; |
384
|
|
|
if (Seomatic::$settings->includeHomepageInBreadcrumbs) { |
385
|
|
|
/** @var Element $element */ |
386
|
|
|
$position++; |
387
|
|
|
$element = Craft::$app->getElements()->getElementByUri('__home__', $siteId, true); |
388
|
|
|
if ($element) { |
389
|
|
|
$uri = $element->uri === '__home__' ? '' : ($element->uri ?? ''); |
390
|
|
|
try { |
391
|
|
|
$id = UrlHelper::siteUrl($uri, null, null, $siteId); |
392
|
|
|
} catch (Exception $e) { |
393
|
|
|
$id = $siteUrl; |
394
|
|
|
Craft::error($e->getMessage(), __METHOD__); |
395
|
|
|
} |
396
|
|
|
$item = UrlHelper::stripQueryString($id); |
397
|
|
|
$item = UrlHelper::absoluteUrlWithProtocol($item); |
398
|
|
|
$listItem = MetaJsonLd::create('ListItem', [ |
399
|
|
|
'position' => $position, |
400
|
|
|
'name' => $element->title, |
401
|
|
|
'item' => $item, |
402
|
|
|
'@id' => $id, |
403
|
|
|
]); |
404
|
|
|
$crumbs->itemListElement[] = $listItem; |
405
|
|
|
} else { |
406
|
|
|
$item = UrlHelper::stripQueryString($siteUrl); |
407
|
|
|
$item = UrlHelper::absoluteUrlWithProtocol($item); |
408
|
|
|
$crumbs->itemListElement[] = MetaJsonLd::create('ListItem', [ |
409
|
|
|
'position' => $position, |
410
|
|
|
'name' => 'Homepage', |
411
|
|
|
'item' => $item, |
412
|
|
|
'@id' => $siteUrl, |
413
|
|
|
]); |
414
|
|
|
} |
415
|
|
|
} |
416
|
|
|
// Build up the segments, and look for elements that match |
417
|
|
|
$uri = ''; |
418
|
|
|
$segments = Craft::$app->getRequest()->getSegments(); |
419
|
|
|
/** @var Element|null $lastElement */ |
420
|
|
|
$lastElement = Seomatic::$matchedElement; |
421
|
|
|
if ($lastElement && $element) { |
422
|
|
|
if ($lastElement->uri !== '__home__' && $element->uri) { |
423
|
|
|
$path = $lastElement->uri; |
424
|
|
|
$segments = array_values(array_filter(explode('/', $path), function($segment) { |
|
|
|
|
425
|
|
|
return $segment !== ''; |
426
|
|
|
})); |
427
|
|
|
} |
428
|
|
|
} |
429
|
|
|
// Parse through the segments looking for elements that match |
430
|
|
|
foreach ($segments as $segment) { |
431
|
|
|
$uri .= $segment; |
432
|
|
|
/** @var Element|null $element */ |
433
|
|
|
$element = Craft::$app->getElements()->getElementByUri($uri, $siteId, true); |
434
|
|
|
if ($element && $element->uri) { |
435
|
|
|
$position++; |
436
|
|
|
$uri = $element->uri === '__home__' ? '' : $element->uri; |
437
|
|
|
try { |
438
|
|
|
$id = UrlHelper::siteUrl($uri, null, null, $siteId); |
439
|
|
|
} catch (Exception $e) { |
440
|
|
|
$id = $siteUrl; |
441
|
|
|
Craft::error($e->getMessage(), __METHOD__); |
442
|
|
|
} |
443
|
|
|
$item = UrlHelper::stripQueryString($id); |
444
|
|
|
$item = UrlHelper::absoluteUrlWithProtocol($item); |
445
|
|
|
$crumbs->itemListElement[] = MetaJsonLd::create('ListItem', [ |
446
|
|
|
'position' => $position, |
447
|
|
|
'name' => $element->title, |
448
|
|
|
'item' => $item, |
449
|
|
|
'@id' => $id, |
450
|
|
|
]); |
451
|
|
|
} |
452
|
|
|
$uri .= '/'; |
453
|
|
|
} |
454
|
|
|
if (!empty($crumbs->itemListElement)) { |
455
|
|
|
Seomatic::$plugin->jsonLd->add($crumbs); |
456
|
|
|
} |
457
|
|
|
Craft::endProfile('DynamicMeta::addMetaJsonLdBreadCrumbs', __METHOD__); |
458
|
|
|
} |
459
|
|
|
|
460
|
|
|
/** |
461
|
|
|
* Add meta hreflang tags if there is more than one site |
462
|
|
|
* |
463
|
|
|
* @param string $uri |
464
|
|
|
* @param int|null $siteId |
465
|
|
|
*/ |
466
|
|
|
public static function addMetaLinkHrefLang(string $uri = null, int $siteId = null) |
467
|
|
|
{ |
468
|
|
|
Craft::beginProfile('DynamicMeta::addMetaLinkHrefLang', __METHOD__); |
469
|
|
|
$siteLocalizedUrls = self::getLocalizedUrls($uri, $siteId); |
470
|
|
|
$currentPaginationUrl = null; |
471
|
|
|
if (Seomatic::$plugin->metaContainers->paginationPage !== '1') { |
472
|
|
|
$currentPaginationUrl = Seomatic::$seomaticVariable->meta->canonicalUrl ?? null; |
473
|
|
|
} |
474
|
|
|
if (!empty($siteLocalizedUrls)) { |
475
|
|
|
// Add the rel=alternate tag |
476
|
|
|
$metaTag = Seomatic::$plugin->link->create([ |
477
|
|
|
'rel' => 'alternate', |
478
|
|
|
'hreflang' => [], |
479
|
|
|
'href' => [], |
480
|
|
|
]); |
481
|
|
|
// Add the alternate language link rel's |
482
|
|
|
if (count($siteLocalizedUrls) > 1) { |
483
|
|
|
foreach ($siteLocalizedUrls as $siteLocalizedUrl) { |
484
|
|
|
$url = $siteLocalizedUrl['url']; |
485
|
|
|
if ($siteLocalizedUrl['current']) { |
486
|
|
|
$url = $currentPaginationUrl ?? $siteLocalizedUrl['url']; |
487
|
|
|
} |
488
|
|
|
$metaTag->hreflang[] = $siteLocalizedUrl['hreflangLanguage']; |
489
|
|
|
$metaTag->href[] = $url; |
490
|
|
|
// Add the x-default hreflang |
491
|
|
|
if ($siteLocalizedUrl['primary'] && Seomatic::$settings->addXDefaultHrefLang) { |
492
|
|
|
$metaTag->hreflang[] = 'x-default'; |
493
|
|
|
$metaTag->href[] = $siteLocalizedUrl['url']; |
494
|
|
|
} |
495
|
|
|
} |
496
|
|
|
Seomatic::$plugin->link->add($metaTag); |
497
|
|
|
} |
498
|
|
|
// Add in the og:locale:alternate tags |
499
|
|
|
$ogLocaleAlternate = Seomatic::$plugin->tag->get('og:locale:alternate'); |
500
|
|
|
if (count($siteLocalizedUrls) > 1 && $ogLocaleAlternate) { |
501
|
|
|
$ogContentArray = []; |
502
|
|
|
foreach ($siteLocalizedUrls as $siteLocalizedUrl) { |
503
|
|
|
if (!in_array($siteLocalizedUrl['ogLanguage'], $ogContentArray, true) && |
504
|
|
|
Craft::$app->language !== $siteLocalizedUrl['language']) { |
505
|
|
|
$ogContentArray[] = $siteLocalizedUrl['ogLanguage']; |
506
|
|
|
} |
507
|
|
|
} |
508
|
|
|
$ogLocaleAlternate->content = $ogContentArray; |
509
|
|
|
} |
510
|
|
|
} |
511
|
|
|
Craft::endProfile('DynamicMeta::addMetaLinkHrefLang', __METHOD__); |
512
|
|
|
} |
513
|
|
|
|
514
|
|
|
/** |
515
|
|
|
* Return a list of localized URLs that are in the current site's group |
516
|
|
|
* The current URI is used if $uri is null. Similarly, the current site is |
517
|
|
|
* used if $siteId is null. |
518
|
|
|
* The resulting array of arrays has `id`, `language`, `ogLanguage`, |
519
|
|
|
* `hreflangLanguage`, and `url` as keys. |
520
|
|
|
* |
521
|
|
|
* @param string|null $uri |
522
|
|
|
* @param int|null $siteId |
523
|
|
|
* |
524
|
|
|
* @return array |
525
|
|
|
*/ |
526
|
|
|
public static function getLocalizedUrls(string $uri = null, int $siteId = null): array |
527
|
|
|
{ |
528
|
|
|
Craft::beginProfile('DynamicMeta::getLocalizedUrls', __METHOD__); |
529
|
|
|
$localizedUrls = []; |
530
|
|
|
// No pagination params for URLs |
531
|
|
|
$urlParams = null; |
532
|
|
|
// Get the request URI |
533
|
|
|
if ($uri === null) { |
534
|
|
|
$requestUri = Craft::$app->getRequest()->pathInfo; |
535
|
|
|
} else { |
536
|
|
|
$requestUri = $uri; |
537
|
|
|
} |
538
|
|
|
// Get the site to use |
539
|
|
|
if ($siteId === null) { |
540
|
|
|
try { |
541
|
|
|
$thisSite = Craft::$app->getSites()->getCurrentSite(); |
542
|
|
|
} catch (SiteNotFoundException $e) { |
543
|
|
|
$thisSite = null; |
544
|
|
|
Craft::error($e->getMessage(), __METHOD__); |
545
|
|
|
} |
546
|
|
|
} else { |
547
|
|
|
$thisSite = Craft::$app->getSites()->getSiteById($siteId); |
548
|
|
|
} |
549
|
|
|
// Bail if we can't get a site |
550
|
|
|
if ($thisSite === null) { |
551
|
|
|
return $localizedUrls; |
552
|
|
|
} |
553
|
|
|
if (Seomatic::$settings->siteGroupsSeparate) { |
554
|
|
|
// Get only the sites that are in the current site's group |
555
|
|
|
try { |
556
|
|
|
$siteGroup = $thisSite->getGroup(); |
557
|
|
|
} catch (InvalidConfigException $e) { |
558
|
|
|
$siteGroup = null; |
559
|
|
|
Craft::error($e->getMessage(), __METHOD__); |
560
|
|
|
} |
561
|
|
|
// Bail if we can't get a site group |
562
|
|
|
if ($siteGroup === null) { |
563
|
|
|
return $localizedUrls; |
564
|
|
|
} |
565
|
|
|
$sites = $siteGroup->getSites(); |
566
|
|
|
} else { |
567
|
|
|
$sites = Craft::$app->getSites()->getAllSites(); |
568
|
|
|
} |
569
|
|
|
$elements = Craft::$app->getElements(); |
570
|
|
|
foreach ($sites as $site) { |
571
|
|
|
$includeUrl = true; |
572
|
|
|
$matchedElement = $elements->getElementByUri($requestUri, $thisSite->id, true); |
573
|
|
|
if ($matchedElement) { |
574
|
|
|
$url = $elements->getElementUriForSite($matchedElement->getId(), $site->id); |
575
|
|
|
// See if they have disabled sitemaps or robots for this entry, |
576
|
|
|
// and if so, don't include it in the hreflang |
577
|
|
|
$element = null; |
578
|
|
|
if ($url) { |
579
|
|
|
/** @var Element $element */ |
580
|
|
|
$element = $elements->getElementByUri($url, $site->id, false); |
581
|
|
|
} |
582
|
|
|
if ($element !== null) { |
583
|
|
|
/** @var MetaBundle $metaBundle */ |
584
|
|
|
list($sourceId, $sourceBundleType, $sourceHandle, $sourceSiteId, $typeId) |
585
|
|
|
= Seomatic::$plugin->metaBundles->getMetaSourceFromElement($element); |
586
|
|
|
$metaBundle = Seomatic::$plugin->metaBundles->getMetaBundleBySourceId( |
587
|
|
|
$sourceBundleType, |
588
|
|
|
$sourceId, |
589
|
|
|
$sourceSiteId |
590
|
|
|
); |
591
|
|
|
if ($metaBundle !== null) { |
592
|
|
|
// If robots contains 'none' or 'noindex' don't include the URL |
593
|
|
|
$robotsArray = explode(',', $metaBundle->metaGlobalVars->robots); |
594
|
|
|
if (in_array('noindex', $robotsArray, true) || in_array('none', $robotsArray, true)) { |
595
|
|
|
$includeUrl = false; |
596
|
|
|
} |
597
|
|
|
} |
598
|
|
|
$fieldHandles = FieldHelper::fieldsOfTypeFromElement( |
599
|
|
|
$element, |
600
|
|
|
FieldHelper::SEO_SETTINGS_CLASS_KEY, |
601
|
|
|
true |
602
|
|
|
); |
603
|
|
|
foreach ($fieldHandles as $fieldHandle) { |
604
|
|
|
if (!empty($element->$fieldHandle)) { |
605
|
|
|
/** @var MetaBundle $fieldMetaBundle */ |
606
|
|
|
$fieldMetaBundle = $element->$fieldHandle; |
607
|
|
|
/** @var SeoSettings $seoSettingsField */ |
608
|
|
|
$seoSettingsField = Craft::$app->getFields()->getFieldByHandle($fieldHandle); |
609
|
|
|
if ($seoSettingsField !== null) { |
610
|
|
|
// If robots is set to 'none' don't include the URL |
611
|
|
|
if ($seoSettingsField->generalTabEnabled |
612
|
|
|
&& in_array('robots', $seoSettingsField->generalEnabledFields, false) |
613
|
|
|
&& !Seomatic::$plugin->helper->isInherited($fieldMetaBundle->metaGlobalVars, 'robots') |
|
|
|
|
614
|
|
|
) { |
615
|
|
|
// If robots contains 'none' or 'noindex' don't include the URL |
616
|
|
|
$robotsArray = explode(',', $fieldMetaBundle->metaGlobalVars->robots); |
617
|
|
|
if (in_array('noindex', $robotsArray, true) || in_array('none', $robotsArray, true)) { |
618
|
|
|
$includeUrl = false; |
619
|
|
|
} else { |
620
|
|
|
// Otherwise, include the URL |
621
|
|
|
$includeUrl = true; |
622
|
|
|
} |
623
|
|
|
} |
624
|
|
|
} |
625
|
|
|
} |
626
|
|
|
} |
627
|
|
|
// Never include the URL if the element isn't enabled for the site |
628
|
|
|
if (isset($element->enabledForSite) && !(bool)$element->enabledForSite) { |
629
|
|
|
$includeUrl = false; |
630
|
|
|
} |
631
|
|
|
} else { |
632
|
|
|
$includeUrl = false; |
633
|
|
|
} |
634
|
|
|
$url = ($url === '__home__') ? '' : $url; |
635
|
|
|
} else { |
636
|
|
|
try { |
637
|
|
|
$url = SiteHelper::siteEnabledWithUrls($site->id) ? UrlHelper::siteUrl($requestUri, $urlParams, null, $site->id) |
638
|
|
|
: Craft::$app->getSites()->getPrimarySite()->baseUrl; |
639
|
|
|
} catch (SiteNotFoundException $e) { |
640
|
|
|
$url = ''; |
641
|
|
|
Craft::error($e->getMessage(), __METHOD__); |
642
|
|
|
} catch (Exception $e) { |
643
|
|
|
$url = ''; |
644
|
|
|
Craft::error($e->getMessage(), __METHOD__); |
645
|
|
|
} |
646
|
|
|
} |
647
|
|
|
$url = $url ?? ''; |
648
|
|
|
if (!UrlHelper::isAbsoluteUrl($url)) { |
649
|
|
|
try { |
650
|
|
|
$url = UrlHelper::siteUrl($url, $urlParams, null, $site->id); |
651
|
|
|
} catch (Exception $e) { |
652
|
|
|
$url = ''; |
653
|
|
|
Craft::error($e->getMessage(), __METHOD__); |
654
|
|
|
} |
655
|
|
|
} |
656
|
|
|
// Strip any query string params, and make sure we have an absolute URL with protocol |
657
|
|
|
if ($urlParams === null) { |
658
|
|
|
$url = UrlHelper::stripQueryString($url); |
659
|
|
|
} |
660
|
|
|
$url = UrlHelper::absoluteUrlWithProtocol($url); |
661
|
|
|
$url = self::sanitizeUrl($url); |
662
|
|
|
$language = $site->language; |
663
|
|
|
$ogLanguage = LocalizationHelper::normalizeOgLocaleLanguage($language); |
664
|
|
|
$hreflangLanguage = $language; |
665
|
|
|
$hreflangLanguage = strtolower($hreflangLanguage); |
666
|
|
|
$hreflangLanguage = str_replace('_', '-', $hreflangLanguage); |
667
|
|
|
$primary = Seomatic::$settings->xDefaultSite == 0 ? $site->primary : Seomatic::$settings->xDefaultSite == $site->id; |
668
|
|
|
if ($includeUrl) { |
669
|
|
|
$localizedUrls[] = [ |
670
|
|
|
'id' => $site->id, |
671
|
|
|
'language' => $language, |
672
|
|
|
'ogLanguage' => $ogLanguage, |
673
|
|
|
'hreflangLanguage' => $hreflangLanguage, |
674
|
|
|
'url' => $url, |
675
|
|
|
'primary' => $primary, |
676
|
|
|
'current' => $thisSite->id === $site->id, |
677
|
|
|
]; |
678
|
|
|
} |
679
|
|
|
} |
680
|
|
|
Craft::endProfile('DynamicMeta::getLocalizedUrls', __METHOD__); |
681
|
|
|
|
682
|
|
|
return $localizedUrls; |
683
|
|
|
} |
684
|
|
|
|
685
|
|
|
/** |
686
|
|
|
* Return a sanitized URL with the query string stripped |
687
|
|
|
* |
688
|
|
|
* @param string $url |
689
|
|
|
* @param bool $checkStatus |
690
|
|
|
* |
691
|
|
|
* @return string |
692
|
|
|
*/ |
693
|
2 |
|
public static function sanitizeUrl(string $url, bool $checkStatus = true, bool $stripQueryString = true): string |
694
|
|
|
{ |
695
|
|
|
// Remove the query string |
696
|
2 |
|
if ($stripQueryString) { |
697
|
2 |
|
$url = UrlHelper::stripQueryString($url); |
698
|
|
|
} |
699
|
2 |
|
$url = UrlHelper::encodeUrlQueryParams(TextHelper::sanitizeUserInput($url)); |
700
|
|
|
|
701
|
|
|
// If this is a >= 400 status code, set the canonical URL to nothing |
702
|
2 |
|
if ($checkStatus && !Craft::$app->getRequest()->getIsConsoleRequest() && Craft::$app->getResponse()->statusCode >= 400) { |
703
|
|
|
$url = ''; |
704
|
|
|
} |
705
|
|
|
|
706
|
2 |
|
return $url; |
707
|
|
|
} |
708
|
|
|
|
709
|
|
|
/** |
710
|
|
|
* Add the Same As meta tags and JSON-LD |
711
|
|
|
*/ |
712
|
|
|
public static function addSameAsMeta() |
713
|
|
|
{ |
714
|
|
|
Craft::beginProfile('DynamicMeta::addSameAsMeta', __METHOD__); |
715
|
|
|
$metaContainers = Seomatic::$plugin->metaContainers; |
716
|
|
|
$sameAsUrls = []; |
717
|
|
|
if (!empty($metaContainers->metaSiteVars->sameAsLinks)) { |
718
|
|
|
$sameAsUrls = ArrayHelper::getColumn($metaContainers->metaSiteVars->sameAsLinks, 'url', false); |
719
|
|
|
$sameAsUrls = array_values(array_filter($sameAsUrls)); |
720
|
|
|
} |
721
|
|
|
// Facebook OpenGraph |
722
|
|
|
$ogSeeAlso = Seomatic::$plugin->tag->get('og:see_also'); |
723
|
|
|
if ($ogSeeAlso) { |
|
|
|
|
724
|
|
|
$ogSeeAlso->content = $sameAsUrls; |
725
|
|
|
} |
726
|
|
|
// Site Identity JSON-LD |
727
|
|
|
$identity = Seomatic::$plugin->jsonLd->get('identity'); |
728
|
|
|
/** @var Thing $identity */ |
729
|
|
|
if ($identity !== null && property_exists($identity, 'sameAs')) { |
730
|
|
|
$identity->sameAs = $sameAsUrls; |
731
|
|
|
} |
732
|
|
|
Craft::endProfile('DynamicMeta::addSameAsMeta', __METHOD__); |
733
|
|
|
} |
734
|
|
|
|
735
|
|
|
/** |
736
|
|
|
* Add the OpeningHoursSpecific to the $jsonLd based on the Entity settings |
737
|
|
|
* |
738
|
|
|
* @param MetaJsonLd|LocalBusiness $jsonLd |
739
|
|
|
* @param Entity|null $entity |
740
|
|
|
*/ |
741
|
|
|
public static function addOpeningHours(MetaJsonLd $jsonLd, $entity) |
742
|
|
|
{ |
743
|
|
|
Craft::beginProfile('DynamicMeta::addOpeningHours', __METHOD__); |
744
|
|
|
if ($jsonLd instanceof LocalBusiness && $entity !== null) { |
745
|
|
|
$openingHours = []; |
746
|
|
|
$days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']; |
747
|
|
|
$times = $entity->localBusinessOpeningHours; |
748
|
|
|
$index = 0; |
749
|
|
|
foreach ($times as $hours) { |
750
|
|
|
$openTime = ''; |
751
|
|
|
$closeTime = ''; |
752
|
|
|
if (!empty($hours['open'])) { |
753
|
|
|
/** @var DateTime $dateTime */ |
754
|
|
|
try { |
755
|
|
|
$dateTime = DateTimeHelper::toDateTime($hours['open']['date'], false, false); |
756
|
|
|
} catch (\Exception $e) { |
757
|
|
|
$dateTime = false; |
758
|
|
|
} |
759
|
|
|
if ($dateTime !== false) { |
760
|
|
|
$openTime = $dateTime->format('H:i:s'); |
761
|
|
|
} |
762
|
|
|
} |
763
|
|
|
if (!empty($hours['close'])) { |
764
|
|
|
/** @var DateTime $dateTime */ |
765
|
|
|
try { |
766
|
|
|
$dateTime = DateTimeHelper::toDateTime($hours['close']['date'], false, false); |
767
|
|
|
} catch (\Exception $e) { |
768
|
|
|
$dateTime = false; |
769
|
|
|
} |
770
|
|
|
if ($dateTime !== false) { |
771
|
|
|
$closeTime = $dateTime->format('H:i:s'); |
772
|
|
|
} |
773
|
|
|
} |
774
|
|
|
if ($openTime && $closeTime) { |
775
|
|
|
/** @var OpeningHoursSpecification $hours */ |
776
|
|
|
$hours = Seomatic::$plugin->jsonLd->create([ |
777
|
|
|
'type' => 'OpeningHoursSpecification', |
778
|
|
|
'opens' => $openTime, |
779
|
|
|
'closes' => $closeTime, |
780
|
|
|
'dayOfWeek' => [$days[$index]], |
781
|
|
|
], false); |
782
|
|
|
$openingHours[] = $hours; |
783
|
|
|
} |
784
|
|
|
$index++; |
785
|
|
|
} |
786
|
|
|
$jsonLd->openingHoursSpecification = $openingHours; |
787
|
|
|
} |
788
|
|
|
Craft::endProfile('DynamicMeta::addOpeningHours', __METHOD__); |
789
|
|
|
} |
790
|
|
|
|
791
|
|
|
/** |
792
|
|
|
* Add the ContactPoint to the $jsonLd based on the Entity settings |
793
|
|
|
* |
794
|
|
|
* @param MetaJsonLd $jsonLd |
795
|
|
|
* @param Entity $entity |
796
|
|
|
*/ |
797
|
|
|
public static function addContactPoints(MetaJsonLd $jsonLd, Entity $entity) |
798
|
|
|
{ |
799
|
|
|
Craft::beginProfile('DynamicMeta::addContactPoints', __METHOD__); |
800
|
|
|
if ($jsonLd instanceof Organization && $entity !== null) { |
801
|
|
|
/** @var Organization $jsonLd */ |
802
|
|
|
$contactPoints = []; |
803
|
|
|
if (is_array($entity->organizationContactPoints)) { |
804
|
|
|
foreach ($entity->organizationContactPoints as $contacts) { |
805
|
|
|
/** @var ContactPoint $contact */ |
806
|
|
|
$contact = Seomatic::$plugin->jsonLd->create([ |
807
|
|
|
'type' => 'ContactPoint', |
808
|
|
|
'telephone' => $contacts['telephone'], |
809
|
|
|
'contactType' => $contacts['contactType'], |
810
|
|
|
], false); |
811
|
|
|
$contactPoints[] = $contact; |
812
|
|
|
} |
813
|
|
|
} |
814
|
|
|
$jsonLd->contactPoint = $contactPoints; |
815
|
|
|
} |
816
|
|
|
Craft::endProfile('DynamicMeta::addContactPoints', __METHOD__); |
817
|
|
|
} |
818
|
|
|
|
819
|
|
|
/** |
820
|
|
|
* Normalize the array of opening hours passed in |
821
|
|
|
* |
822
|
|
|
* @param $value |
823
|
|
|
*/ |
824
|
|
|
public static function normalizeTimes(&$value) |
825
|
|
|
{ |
826
|
|
|
if (is_string($value)) { |
827
|
|
|
$value = Json::decode($value); |
828
|
|
|
} |
829
|
|
|
$normalized = []; |
830
|
|
|
$times = ['open', 'close']; |
831
|
|
|
for ($day = 0; $day <= 6; $day++) { |
832
|
|
|
foreach ($times as $time) { |
833
|
|
|
if (isset($value[$day][$time]) |
834
|
|
|
&& ($date = DateTimeHelper::toDateTime($value[$day][$time])) !== false |
835
|
|
|
) { |
836
|
|
|
$normalized[$day][$time] = (array)($date); |
837
|
|
|
} else { |
838
|
|
|
$normalized[$day][$time] = null; |
839
|
|
|
} |
840
|
|
|
} |
841
|
|
|
} |
842
|
|
|
|
843
|
|
|
$value = $normalized; |
844
|
|
|
} |
845
|
|
|
} |
846
|
|
|
|