-
-
Notifications
You must be signed in to change notification settings - Fork 7
/
Meta.php
670 lines (576 loc) 路 16.7 KB
/
Meta.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
<?php
namespace tobimori\Seo;
use Kirby\Cms\App;
use Kirby\Cms\Page;
use Kirby\Content\Field;
use Kirby\Exception\InvalidArgumentException;
use Kirby\Toolkit\A;
use Kirby\Toolkit\Str;
/**
* The Meta class is responsible for handling the meta data & cascading
*/
class Meta
{
/**
* These values will be handled as 'field is empty'
*/
public const DEFAULT_VALUES = ['[]', 'default'];
protected Page $page;
protected ?string $lang;
protected array $consumed = [];
protected array $metaDefaults = [];
protected array $metaArray = [];
/**
* Creates a new Meta instance
*/
public function __construct(Page $page, ?string $lang = null)
{
$this->page = $page;
$this->lang = $lang;
if (method_exists($this->page, 'metaDefaults')) {
$this->metaDefaults = $this->page->metaDefaults($this->lang);
}
}
/**
* Returns the meta array which maps meta tags to their fieldnames
*/
protected function metaArray(): array
{
if ($this->metaArray) {
return $this->metaArray;
}
/**
* We have to specify field names and resolve them later, so we can use this
* function to resolve meta tags from field names in the programmatic function
*/
$meta =
[
'title' => 'metaTitle',
'description' => 'metaDescription',
'date' => fn () => $this->page->modified($this->dateFormat()),
'og:title' => 'ogTitle',
'og:description' => 'ogDescription',
'og:site_name' => 'ogSiteName',
'og:image' => 'ogImage',
'og:image:width' => fn () => $this->ogImage() ? $this->get('ogImage')->toFile()?->width() : null,
'og:image:height' => fn () => $this->ogImage() ? $this->get('ogImage')->toFile()?->height() : null,
'og:image:alt' => fn () => $this->get('ogImage')->toFile()?->alt(),
'og:type' => 'ogType',
];
// Robots
if ($robotsActive = option('tobimori.seo.robots.active')) {
$meta['robots'] = fn () => $this->robots();
}
// only add canonical and alternate tags if the page is indexable
// we have to resolve this lazily (using a callable) to avoid an infinite loop
$allowsIndexFn = fn () => !$robotsActive || !Str::contains($this->robots(), 'noindex');
// canonical
$canonicalFn = fn () => $allowsIndexFn() ? $this->canonicalUrl() : null;
$meta['canonical'] = $canonicalFn;
$meta['og:url'] = $canonicalFn;
// Multi-lang alternate tags
if (kirby()->languages()->count() > 1 && kirby()->language() !== null) {
foreach (kirby()->languages() as $lang) {
// only add alternate tags if the page is indexable
$meta['alternate'][] = fn () => $allowsIndexFn() ? [
'hreflang' => $lang->code(),
'href' => $this->page->url($lang->code()),
] : null;
if ($lang !== kirby()->language()) {
$meta['og:locale:alternate'][] = fn () => $lang->code();
}
}
// only add alternate tags if the page is indexable
$meta['alternate'][] = fn () => $allowsIndexFn() ? [
'hreflang' => 'x-default',
'href' => $this->page->url(kirby()->language()->code()),
] : null;
$meta['og:locale'] = fn () => kirby()->language()->locale(LC_ALL);
} else {
$meta['og:locale'] = fn () => $this->locale(LC_ALL);
}
// Twitter tags "opt-in" - TODO: wip
if (option('tobimori.seo.twitter', true)) {
$meta = array_merge($meta, [
'twitter:card' => 'twitterCardType',
'twitter:title' => 'ogTitle',
'twitter:description' => 'ogDescription',
'twitter:image' => 'ogImage',
'twitter:site' => 'twitterSite',
'twitter:creator' => 'twitterCreator',
]);
}
// This array will be normalized for use in the snippet in $this->snippetData()
return $this->metaArray = $meta;
}
/**
* This array defines what HTML tag the corresponding meta tags are using including the attributes,
* so everything is a bit more elegant when defining programmatic content (supports regex)
*/
public const TAG_TYPE_MAP = [
[
'tag' => 'title',
'tags' => [
'title'
]
],
[
'tag' => 'link',
'attributes' => [
'name' => 'rel',
'content' => 'href',
],
'tags' => [
'canonical',
'alternate',
]
],
[
'tag' => 'meta',
'attributes' => [
'name' => 'property',
'content' => 'content',
],
'tags' => [
'/og:.+/'
]
]
];
/**
* Normalize the meta array and remaining meta defaults to be used in the snippet,
* also resolve the content, if necessary
*/
public function snippetData(array $raw = null): array
{
$mergeWithDefaults = !isset($raw);
$raw ??= $this->metaArray();
$tags = [];
foreach ($raw as $name => $value) {
// if the key is numeric, it is already normalized to the correct array syntax
if (is_numeric($name)) {
// but we still check if the array is valid
if (!is_array($value) || count(array_intersect(['tag', 'content', 'attributes'], array_keys($value))) !== count($value)) {
throw new InvalidArgumentException("[kirby-seo] Invalid array structure found in programmatic content for page {$this->slug()}. Please check your metaDefaults method for template {$this->template()->name()}.");
}
$tags[] = $value;
continue;
}
// allow overrides from metaDefaults for keys that are a callable or array by default
// (all fields from meta array that are not part of the regular cascade)
if ((is_callable($value) || is_array($value)) && $mergeWithDefaults && array_key_exists($name, $this->metaDefaults)) {
$this->consumed[] = $name;
$value = $this->metaDefaults[$name];
}
// if the value is a string, we know it's a field name
if (is_string($value)) {
$value = $this->$value($name);
}
// if the value is a callable, we resolve it
if (is_callable($value)) {
$value = $value($this->page);
}
// if the value is empty, we don't want to output it
if ((is_a($value, 'Kirby\Content\Field') && $value->isEmpty()) || !$value) {
continue;
}
// resolve the tag type from the meta array
// so we can use the correct attributes to normalize it
$tag = $this->resolveTag($name);
// if the value is an associative array now, all of them are attributes
// and we don't look for what the TAG_TYPE_MAP says
// or there should be multiple tags with the same name (non-associative array)
if (is_array($value)) {
if (!A::isAssociative($value)) {
foreach ($value as $val) {
$tags = array_merge($tags, $this->snippetData([$name => $val]));
}
continue;
}
// array is associative, so it's an array of attributes
// we resolve the values, if they are callable
array_walk($value, function (&$item) {
if (is_callable($item)) {
$item = $item($this->page);
}
});
// add the tag to the array
$tags[] = [
'tag' => $tag['tag'],
'attributes' => $value,
'content' => null,
];
continue;
}
// if the value is a string, we use the TAG_TYPE_MAP
// to correctly map the attributes
$tags[] = [
'tag' => $tag['tag'],
'attributes' => isset($tag['attributes']) ? [
$tag['attributes']['name'] => $name,
$tag['attributes']['content'] => $value,
] : null,
'content' => !isset($tag['attributes']) ? $value : null,
];
}
if ($mergeWithDefaults) {
// merge the remaining meta defaults
$tags = array_merge($tags, $this->snippetData(array_diff_key($this->metaDefaults, array_flip($this->consumed))));
}
return $tags;
}
/**
* Resolves the tag type from the meta array
*/
protected function resolveTag(string $tag): array
{
foreach (self::TAG_TYPE_MAP as $type) {
foreach ($type['tags'] as $regexOrString) {
// Check if the supplied tag is a regex or a normal tag name
if (Str::startsWith($regexOrString, '/') && Str::endsWith($regexOrString, '/') ?
Str::match($tag, $regexOrString) : $tag === $regexOrString
) {
return $type;
}
}
}
return [
'tag' => 'meta',
'attributes' => [
'name' => 'name',
'content' => 'content',
]
];
}
/**
* Magic method to get a meta value by calling the method name
*/
public function __call($name, $args = null): mixed
{
if (method_exists($this, $name)) {
return $this->$name($args);
}
return $this->get($name);
}
/**
* Get the meta value for a given key
*/
public function get(string $key, array $exclude = []): Field
{
$cascade = option('tobimori.seo.cascade');
if (count(array_intersect(get_class_methods($this), $cascade)) !== count($cascade)) {
throw new InvalidArgumentException('[kirby-seo] Invalid cascade method in config. Please check your options for `tobimori.seo.cascade`.');
}
// Track consumed keys, so we don't output legacy field values
$toBeConsumed = $key;
if (
(array_key_exists($toBeConsumed, $this->metaDefaults)
|| array_key_exists($toBeConsumed = $this->findTagForField($toBeConsumed), $this->metaDefaults))
&& !in_array($toBeConsumed, $this->consumed)
) {
$this->consumed[] = $toBeConsumed;
}
foreach (array_diff($cascade, $exclude) as $method) {
if ($field = $this->$method($key)) {
return $field;
}
}
return new Field($this->page, $key, '');
}
/**
* Get the meta value for a given key from the page's fields
*/
protected function fields(string $key): Field|null
{
if (($field = $this->page->content($this->lang)->get($key))) {
if (Str::contains($key, 'robots') && !option('tobimori.seo.robots.pageSettings')) {
return null;
}
if ($field->isNotEmpty() && !A::has(self::DEFAULT_VALUES, $field->value())) {
return $field;
}
}
return null;
}
/**
* Maps Open Graph fields to Meta fields for fallbackFields
* cascade method
*/
public const FALLBACK_MAP = [
'ogTitle' => 'metaTitle',
'ogDescription' => 'metaDescription',
'ogTemplate' => 'metaTemplate',
];
/**
* We only allow the following cascade methods for fallbacks,
* because we don't want to fallback to the config defaults for
* Meta fields, because we most likely already have those set
* for the Open Graph fields
*/
public const FALLBACK_CASCADE = [
'fields',
'programmatic',
'parent',
'site'
];
/**
* Get the meta value for a given key using the fallback fields
* defined above (usually Open Graph > Meta Fields)
*/
protected function fallbackFields(string $key): Field|null
{
if (array_key_exists($key, self::FALLBACK_MAP)) {
$fallback = self::FALLBACK_MAP[$key];
$cascade = option('tobimori.seo.cascade');
foreach (array_intersect($cascade, self::FALLBACK_CASCADE) as $method) {
if ($field = $this->$method($fallback)) {
return $field;
}
}
}
return null;
}
protected function findTagForField(string $fieldName): string|null
{
return array_search($fieldName, $this->metaArray());
}
/**
* Get the meta value for a given key from the page's meta
* array, which can be set in the page's model metaDefaults method
*/
protected function programmatic(string $key): Field|null
{
if (!$this->metaDefaults) {
return null;
}
// Check if the key (field name) is in the array syntax
if (array_key_exists($key, $this->metaDefaults)) {
$val = $this->metaDefaults[$key];
}
/* If there is no programmatic value for the key,
* try looking it up in the meta array
* maybe it is a meta tag and not a field name?
*/
if (!isset($val) && ($key = $this->findTagForField($key)) && array_key_exists($key, $this->metaDefaults)) {
$val = $this->metaDefaults[$key];
}
if (isset($val)) {
if (is_callable($val)) {
$val = $val($this->page);
}
if (is_array($val)) {
$val = $val['content'] ?? $val['href'] ?? null;
// Last sanity check, if the array syntax doesn't have a supported key
if ($val === null) {
// Remove the key from the consumed array, so it doesn't get filtered out
// (we can assume the entry is a custom meta tag that uses different attributes)
$this->consumed = array_filter($this->consumed, fn ($item) => $item !== $key);
return null;
}
}
if (is_a($val, 'Kirby\Content\Field')) {
return new Field($this->page, $key, $val->value());
}
return new Field($this->page, $key, $val);
}
return null;
}
/**
* Get the meta value for a given key from the page's parent,
* if the page is allowed to inherit the value
*/
protected function parent(string $key): Field|null
{
if ($this->canInherit($key)) {
$parent = $this->page->parent();
$parentMeta = new Meta($parent, $this->lang);
if ($value = $parentMeta->get($key)) {
return $value;
}
}
return null;
}
/**
* Get the meta value for a given key from the
* site's meta blueprint & content
*/
protected function site(string $key): Field|null
{
if (($site = $this->page->site()->content($this->lang)->get($key)) && ($site->isNotEmpty() && !A::has(self::DEFAULT_VALUES, $site->value))) {
return $site;
}
return null;
}
/**
* Get the meta value for a given key from the
* config.php options
*/
protected function options(string $key): Field|null
{
if ($option = option("tobimori.seo.default.{$key}")) {
if (is_callable($option)) {
$option = $option($this->page);
}
if (is_a($option, 'Kirby\Content\Field')) {
return $option;
}
return new Field($this->page, $key, $option);
}
return null;
}
/**
* Checks if the page can inherit a meta value from its parent
*/
private function canInherit(string $key): bool
{
$parent = $this->page->parent();
if (!$parent) {
return false;
}
$inherit = $parent->metaInherit()->split();
if (Str::contains($key, 'robots') && A::has($inherit, 'robots')) {
return true;
}
return A::has($inherit, $key);
}
/**
* Applies the title template, and returns the correct title
*/
public function metaTitle()
{
$title = $this->get('metaTitle');
$template = $this->get('metaTemplate');
$useTemplate = $this->page->useTitleTemplate();
$useTemplate = $useTemplate->isEmpty() ? true : $useTemplate->toBool();
$string = $title->value();
if ($useTemplate) {
$string = $this->page->toString(
$template,
['title' => $title]
);
}
return new Field(
$this->page,
'metaTitle',
$string
);
}
/**
* Applies the OG title template, and returns the OG Title
*/
public function ogTitle()
{
$title = $this->get('metaTitle');
$template = $this->get('ogTemplate');
$useTemplate = $this->page->useOgTemplate();
$useTemplate = $useTemplate->isEmpty() ? true : $useTemplate->toBool();
$string = $title->value();
if ($useTemplate) {
$string = $this->page->toString(
$template,
['title' => $title]
);
}
return new Field(
$this->page,
'ogTitle',
$string
);
}
/**
* Gets the canonical url for the page
*/
public function canonicalUrl()
{
return $this->page->site()->canonicalFor($this->page->url());
}
/**
* Get the Twitter username from an account url set in the site options
*/
public function twitterSite()
{
$accs = $this->page->site()->socialMediaAccounts()->toObject();
$username = '';
if ($accs->twitter()->isNotEmpty()) {
// tries to match all twitter urls, and extract the username
$matches = [];
preg_match('/^(https?:\/\/)?(www\.)?twitter\.com\/(#!\/)?@?(?<name>[^\/\?]*)$/', $accs->twitter()->value(), $matches);
if (isset($matches['name'])) {
$username = $matches['name'];
}
}
return new Field($this->page, 'twitter', $username);
}
/**
* Gets the date format for modified meta tags, based on the registered date handler
*/
public function dateFormat(): string
{
if ($custom = option('tobimori.seo.dateFormat')) {
if (is_callable($custom)) {
return $custom($this->page);
}
return $custom;
}
switch (option('date.handler')) {
case 'strftime':
return '%Y-%m-%d';
case 'intl':
return 'yyyy-MM-dd';
case 'date':
default:
return 'Y-m-d';
}
}
/**
* Get the pages' robots rules as string
*/
public function robots()
{
$robots = [];
foreach (option('tobimori.seo.robots.types') as $type) {
if (!$this->get('robots' . Str::ucfirst($type))->toBool()) {
$robots[] = 'no' . Str::lower($type);
}
}
if (A::count($robots) === 0) {
$robots = ['all'];
}
return A::join($robots, ',');
}
/**
* Get the og:image url
*/
public function ogImage(): string|null
{
$field = $this->get('ogImage');
if ($ogImage = $field->toFile()?->thumb([
'width' => 1200,
'height' => 630,
'crop' => true,
])) {
return $ogImage->url();
}
if ($field->isNotEmpty()) {
return $field->value();
}
return null;
}
/**
* Helper method the get the current page from the URL path,
* for use in programmatic blueprints
*/
public static function currentPage(): Page|null
{
$path = App::instance()->request()->url()->toString();
$matches = Str::match($path, "/pages\/([a-zA-Z0-9-_+]+)\/?/m");
$segments = Str::split($matches[1], '+');
$page = App::instance()->site();
foreach ($segments as $segment) {
if ($page = $page->findPageOrDraft($segment)) {
continue;
}
return null;
}
return $page;
}
}