-
-
Notifications
You must be signed in to change notification settings - Fork 71
/
MetaBundles.php
1088 lines (1021 loc) · 42.3 KB
/
MetaBundles.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
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* SEOmatic plugin for Craft CMS 3.x
*
* A turnkey SEO implementation for Craft CMS that is comprehensive, powerful,
* and flexible
*
* @link https://nystudio107.com
* @copyright Copyright (c) 2017 nystudio107
*/
namespace nystudio107\seomatic\services;
use Craft;
use craft\base\Component;
use craft\base\Element;
use craft\base\Model;
use craft\commerce\models\ProductType;
use craft\db\Query;
use craft\models\CategoryGroup;
use craft\models\Section;
use craft\models\Section_SiteSettings;
use craft\models\Site;
use DateTime;
use nystudio107\seomatic\base\SeoElementInterface;
use nystudio107\seomatic\fields\SeoSettings;
use nystudio107\seomatic\helpers\ArrayHelper;
use nystudio107\seomatic\helpers\Config as ConfigHelper;
use nystudio107\seomatic\helpers\MetaValue as MetaValueHelper;
use nystudio107\seomatic\helpers\Migration as MigrationHelper;
use nystudio107\seomatic\helpers\SiteHelper;
use nystudio107\seomatic\models\MetaBundle;
use nystudio107\seomatic\models\MetaScriptContainer;
use nystudio107\seomatic\models\metatag\RobotsTag;
use nystudio107\seomatic\models\MetaTagContainer;
use nystudio107\seomatic\records\MetaBundle as MetaBundleRecord;
use nystudio107\seomatic\Seomatic;
use nystudio107\seomatic\services\Tag as TagService;
use Throwable;
use yii\base\InvalidConfigException;
use function in_array;
/**
* Meta bundle functions for SEOmatic
* An instance of the service is available via [[`Seomatic::$plugin->metaBundles`|`seomatic.bundles`]]
*
* @author nystudio107Meta bundle failed validation
* @package Seomatic
* @since 3.0.0
*/
class MetaBundles extends Component
{
// Constants
// =========================================================================
const GLOBAL_META_BUNDLE = '__GLOBAL_BUNDLE__';
const FIELD_META_BUNDLE = 'field';
const IGNORE_DB_ATTRIBUTES = [
'id',
'dateCreated',
'dateUpdated',
'uid',
];
const ALWAYS_INCLUDED_SEO_SETTINGS_FIELDS = [
'twitterTitle',
'twitterDescription',
'twitterImage',
'twitterImageDescription',
'ogTitle',
'ogDescription',
'ogImage',
'ogImageDescription',
];
const COMPOSITE_INHERITANCE_CHILDREN = [
'seoImage' => [
'metaBundleSettings.seoImageTransformMode',
'metaBundleSettings.seoImageTransform',
'metaBundleSettings.seoImageSource',
'metaBundleSettings.seoImageField',
'metaBundleSettings.seoImageIds',
],
'ogImage' => [
'metaBundleSettings.ogImageTransformMode',
'metaBundleSettings.ogImageTransform',
'metaBundleSettings.ogImageSource',
'metaBundleSettings.ogImageField',
'metaBundleSettings.ogImageIds',
],
'twitterImage' => [
'metaBundleSettings.twitterImageTransformMode',
'metaBundleSettings.twitterImageTransform',
'metaBundleSettings.twitterImageSource',
'metaBundleSettings.twitterImageField',
'metaBundleSettings.twitterImageIds',
],
];
const PRESERVE_SCRIPT_SETTINGS = [
'include',
'tagAttrs',
'templateString',
'position',
'bodyTemplateString',
'bodyPosition',
'vars',
];
const PRESERVE_FRONTEND_TEMPLATE_SETTINGS = [
'include',
'templateString',
];
// Protected Properties
// =========================================================================
/**
* @var MetaBundle[] indexed by [id]
*/
protected $metaBundles = [];
/**
* @var array indexed by [sourceId][sourceSiteId] = id
*/
protected $metaBundlesBySourceId = [];
/**
* @var array indexed by [sourceHandle][sourceSiteId] = id
*/
protected $metaBundlesBySourceHandle = [];
/**
* @var array indexed by [sourceSiteId] = id
*/
protected $globalMetaBundles = [];
/**
* @var array parent meta bundles for elements
*/
protected $elementContentMetaBundles = [];
// Public Methods
// =========================================================================
/**
* Get the global meta bundle for the site
*
* @param int $sourceSiteId
* @param bool $parse Whether the resulting metabundle should be parsed
*
* @return null|MetaBundle
*/
public function getGlobalMetaBundle(int $sourceSiteId, $parse = true)
{
$metaBundle = null;
// See if we have the meta bundle cached
if (!empty($this->globalMetaBundles[$sourceSiteId])) {
return $this->globalMetaBundles[$sourceSiteId];
}
$metaBundleArray = (new Query())
->from(['{{%seomatic_metabundles}}'])
->where([
'sourceBundleType' => self::GLOBAL_META_BUNDLE,
'sourceSiteId' => $sourceSiteId,
])
->one();
if (!empty($metaBundleArray)) {
// Get the attributes from the db
$metaBundleArray = array_diff_key($metaBundleArray, array_flip(self::IGNORE_DB_ATTRIBUTES));
$metaBundle = MetaBundle::create($metaBundleArray, $parse);
if ($parse) {
$this->syncBundleWithConfig($metaBundle);
}
} else {
// If it doesn't exist, create it
$metaBundle = $this->createGlobalMetaBundleForSite($sourceSiteId);
}
if ($parse) {
// Cache it for future accesses
$this->globalMetaBundles[$sourceSiteId] = $metaBundle;
}
return $metaBundle;
}
/**
* Synchronize the passed in metaBundle with the seomatic-config files if
* there is a newer version of the MetaBundle bundleVersion in the config
* file
*
* @param MetaBundle $metaBundle
* @param bool $forceUpdate
*/
public function syncBundleWithConfig(MetaBundle &$metaBundle, bool $forceUpdate = false)
{
$prevMetaBundle = $metaBundle;
$config = [];
$sourceBundleType = $metaBundle->sourceBundleType;
if ($sourceBundleType === self::GLOBAL_META_BUNDLE) {
$config = ConfigHelper::getConfigFromFile('globalmeta/Bundle');
}
$seoElement = Seomatic::$plugin->seoElements->getSeoElementByMetaBundleType($sourceBundleType);
if ($seoElement) {
$configPath = $seoElement::configFilePath();
$config = ConfigHelper::getConfigFromFile($configPath);
}
// If the config file has a newer version than the $metaBundleArray, merge them
$shouldUpdate = !empty($config) && version_compare($config['bundleVersion'], $metaBundle->bundleVersion, '>');
if ($shouldUpdate || $forceUpdate) {
// Create a new meta bundle
if ($sourceBundleType === self::GLOBAL_META_BUNDLE) {
$metaBundle = $this->createGlobalMetaBundleForSite(
$metaBundle->sourceSiteId,
$metaBundle
);
} else {
$sourceModel = $seoElement::sourceModelFromId($metaBundle->sourceId);
if ($sourceModel) {
$metaBundle = $this->createMetaBundleFromSeoElement(
$seoElement,
$sourceModel,
$metaBundle->sourceSiteId,
$metaBundle
);
}
}
}
// If for some reason we were unable to sync this meta bundle, return the old one
if ($metaBundle === null) {
$metaBundle = $prevMetaBundle;
}
}
/**
* @param int $siteId
* @param MetaBundle|null $baseConfig
*
* @return MetaBundle
*/
public function createGlobalMetaBundleForSite(int $siteId, $baseConfig = null): MetaBundle
{
// Create a new meta bundle with propagated defaults
$metaBundleDefaults = ArrayHelper::merge(
ConfigHelper::getConfigFromFile('globalmeta/Bundle'),
[
'sourceSiteId' => $siteId,
]
);
// The computedType must be set before creating the bundle
if ($baseConfig !== null) {
$metaBundleDefaults['metaGlobalVars']['mainEntityOfPage'] = $baseConfig->metaGlobalVars->mainEntityOfPage;
$metaBundleDefaults['metaSiteVars']['identity']['computedType'] =
$baseConfig->metaSiteVars->identity->computedType;
$metaBundleDefaults['metaSiteVars']['creator']['computedType'] =
$baseConfig->metaSiteVars->creator->computedType;
}
$metaBundle = MetaBundle::create($metaBundleDefaults);
if ($metaBundle !== null) {
if ($baseConfig !== null) {
$this->mergeMetaBundleSettings($metaBundle, $baseConfig);
}
$this->updateMetaBundle($metaBundle, $siteId);
}
return $metaBundle;
}
/**
* @param MetaBundle $metaBundle
* @param int $siteId
*/
public function updateMetaBundle(MetaBundle $metaBundle, int $siteId)
{
$metaBundle->sourceName = (string)$metaBundle->sourceName;
$metaBundle->sourceTemplate = (string)$metaBundle->sourceTemplate;
// Make sure it validates
if ($metaBundle->validate(null, true)) {
// Save it out to a record
$params = [
'sourceBundleType' => $metaBundle->sourceBundleType,
'sourceId' => $metaBundle->sourceId,
'sourceSiteId' => $siteId,
];
if ($metaBundle->typeId !== null) {
$metaBundle->typeId = (int)$metaBundle->typeId;
}
if (!empty($metaBundle->typeId)) {
$params['typeId'] = $metaBundle->typeId;
} else {
$metaBundle->typeId = null;
}
$metaBundleRecord = MetaBundleRecord::findOne($params);
if (!$metaBundleRecord) {
$metaBundleRecord = new MetaBundleRecord();
}
// @TODO remove this hack that doesn't allow environment-transformed settings to be saved in a meta bundle with a proper system to address it
// The issue was that the containers were getting saved to the db with a hard-coded setting in them, because they'd
// been set that way by the environment, whereas to be changeable via the GUI, it needs to be set to {seomatic.meta.robots}
/** @var RobotsTag|null $robotsTag */
$robotsTag = $metaBundle->metaContainers[MetaTagContainer::CONTAINER_TYPE . TagService::GENERAL_HANDLE]->data['robots'] ?? null;
if (!empty($robotsTag)) {
$robotsTag->content = $robotsTag->environment['live']['content'] ?? '{seomatic.meta.robots}';
}
$metaBundleRecord->setAttributes($metaBundle->getAttributes(), false);
if ($metaBundleRecord->save()) {
Craft::info(
'Meta bundle updated: '
. $metaBundle->sourceBundleType
. ' id: '
. $metaBundle->sourceId
. ' from siteId: '
. $metaBundle->sourceSiteId,
__METHOD__
);
}
} else {
Craft::error(
'Meta bundle failed validation: '
. print_r($metaBundle->getErrors(), true)
. ' type: '
. $metaBundle->sourceType
. ' id: '
. $metaBundle->sourceId
. ' from siteId: '
. $metaBundle->sourceSiteId,
__METHOD__
);
}
}
/**
* @param class-string<SeoElementInterface> $seoElement
* @param Model $sourceModel
* @param int $sourceSiteId
* @param ?MetaBundle $baseConfig
* @param bool $syncConfig
* @return MetaBundle|null
* @throws InvalidConfigException
*/
public function createMetaBundleFromSeoElement(
$seoElement,
$sourceModel,
int $sourceSiteId,
$baseConfig = null,
$syncConfig = false
) {
$metaBundle = null;
// Get the site settings and turn them into arrays
/** @var Section|CategoryGroup|ProductType $sourceModel */
$siteSettings = $sourceModel->getSiteSettings();
if (!empty($siteSettings[$sourceSiteId])) {
$siteSettingsArray = [];
/** @var Section_SiteSettings $siteSetting */
foreach ($siteSettings as $siteSetting) {
if ($siteSetting->hasUrls && SiteHelper::siteEnabledWithUrls($sourceSiteId)) {
$siteSettingArray = $siteSetting->toArray();
// Get the site language
$siteSettingArray['language'] = MetaValueHelper::getSiteLanguage($siteSetting->siteId);
$siteSettingsArray[] = $siteSettingArray;
}
}
$siteSettingsArray = ArrayHelper::index($siteSettingsArray, 'siteId');
// Create a MetaBundle for this site
$siteSetting = $siteSettings[$sourceSiteId];
if ($siteSetting->hasUrls && SiteHelper::siteEnabledWithUrls($sourceSiteId)) {
if ($syncConfig) {
// Get the most recent dateUpdated
$element = $seoElement::mostRecentElement($sourceModel, $sourceSiteId);
/** @var Element|null $element */
if ($element) {
$dateUpdated = $element->dateUpdated ?? $element->dateCreated;
} else {
$dateUpdated = new DateTime();
}
// Create a new meta bundle with propagated defaults
$metaBundleDefaults = ArrayHelper::merge(
$seoElement::metaBundleConfig($sourceModel),
[
'sourceTemplate' => (string)$siteSetting->template,
'sourceSiteId' => $siteSetting->siteId,
'sourceAltSiteSettings' => $siteSettingsArray,
'sourceDateUpdated' => $dateUpdated,
]
);
// The mainEntityOfPage computedType must be set before creating the bundle
if ($baseConfig !== null && !empty($baseConfig->metaGlobalVars->mainEntityOfPage)) {
$metaBundleDefaults['metaGlobalVars']['mainEntityOfPage'] =
$baseConfig->metaGlobalVars->mainEntityOfPage;
}
// Merge in any migrated settings from an old Seomatic_Meta Field
if ($element !== null) {
/** @var Element $elementFromSite */
$elementFromSite = Craft::$app->getElements()->getElementById($element->id, null, $sourceSiteId);
if ($element instanceof Element) {
$config = MigrationHelper::configFromSeomaticMeta(
$elementFromSite,
MigrationHelper::SECTION_MIGRATION_CONTEXT
);
$metaBundleDefaults = ArrayHelper::merge(
$metaBundleDefaults,
$config
);
}
}
$metaBundle = MetaBundle::create($metaBundleDefaults);
if ($baseConfig !== null) {
$this->mergeMetaBundleSettings($metaBundle, $baseConfig);
}
$this->updateMetaBundle($metaBundle, $sourceSiteId);
}
}
}
return $metaBundle;
}
/**
* @param string $sourceBundleType
* @param string $sourceHandle
* @param int $sourceSiteId
* @param int|null $typeId
*
* @return null|MetaBundle
*/
public function getMetaBundleBySourceHandle(string $sourceBundleType, string $sourceHandle, int $sourceSiteId, $typeId = null)
{
$metaBundle = null;
$typeId = (int)$typeId;
// See if we have the meta bundle cached
if (!empty($this->metaBundlesBySourceHandle[$sourceBundleType][$sourceHandle][$sourceSiteId][$typeId])) {
$id = $this->metaBundlesBySourceHandle[$sourceBundleType][$sourceHandle][$sourceSiteId][$typeId];
if (!empty($this->metaBundles[$id])) {
return $this->metaBundles[$id];
}
}
// Look for a matching meta bundle in the db
$query = (new Query())
->from(['{{%seomatic_metabundles}}'])
->where([
'sourceBundleType' => $sourceBundleType,
'sourceHandle' => $sourceHandle,
'sourceSiteId' => $sourceSiteId,
]);
if (!empty($typeId)) {
$query
->andWhere([
'typeId' => $typeId,
]);
}
$metaBundleArray = $query
->one();
// If the specific query with a `typeId` returned nothing, try a more general query without `typeId`
if (empty($metaBundleArray)) {
$metaBundleArray = (new Query())
->from(['{{%seomatic_metabundles}}'])
->where([
'sourceBundleType' => $sourceBundleType,
'sourceHandle' => $sourceHandle,
'sourceSiteId' => $sourceSiteId,
])
->one();
}
if (!empty($metaBundleArray)) {
$metaBundleArray = array_diff_key($metaBundleArray, array_flip(self::IGNORE_DB_ATTRIBUTES));
$metaBundle = MetaBundle::create($metaBundleArray);
$id = count($this->metaBundles);
$this->metaBundles[$id] = $metaBundle;
$this->metaBundlesBySourceHandle[$sourceBundleType][$sourceHandle][$sourceSiteId][$typeId] = $id;
} else {
// If it doesn't exist, create it
$seoElement = Seomatic::$plugin->seoElements->getSeoElementByMetaBundleType($sourceBundleType);
if ($seoElement !== null) {
$sourceModel = $seoElement::sourceModelFromHandle($sourceHandle);
if ($sourceModel) {
$metaBundle = $this->createMetaBundleFromSeoElement($seoElement, $sourceModel, $sourceSiteId, null, true);
}
}
}
return $metaBundle;
}
/**
* Invalidate the caches and data structures associated with this MetaBundle
*
* @param string $sourceBundleType
* @param int|null $sourceId
* @param bool $isNew
*/
public function invalidateMetaBundleById(string $sourceBundleType, ?int $sourceId, bool $isNew = false)
{
$metaBundleInvalidated = false;
$sites = Craft::$app->getSites()->getAllSites();
foreach ($sites as $site) {
// See if this is a section we are tracking
$metaBundle = $this->getMetaBundleBySourceId($sourceBundleType, $sourceId, $site->id);
if ($metaBundle) {
Craft::info(
'Invalidating meta bundle: '
. $metaBundle->sourceHandle
. ' from siteId: '
. $site->id,
__METHOD__
);
// Is this a new source?
if (!$isNew) {
$metaBundleInvalidated = true;
// Handle syncing up the sourceHandle
if ($sourceBundleType !== self::GLOBAL_META_BUNDLE) {
$seoElement = Seomatic::$plugin->seoElements->getSeoElementByMetaBundleType($sourceBundleType);
if ($seoElement !== null) {
/** @var Section|CategoryGroup|ProductType $sourceModel */
$sourceModel = $seoElement::sourceModelFromId($sourceId);
if ($sourceModel !== null) {
$metaBundle->sourceName = (string)$sourceModel->name;
$metaBundle->sourceHandle = $sourceModel->handle;
}
}
}
// Invalidate caches after an existing section is saved
Seomatic::$plugin->metaContainers->invalidateContainerCacheById(
$sourceId,
$sourceBundleType,
$metaBundle->sourceSiteId
);
Seomatic::$plugin->sitemaps->invalidateSitemapCache(
$metaBundle->sourceHandle,
$metaBundle->sourceSiteId,
$metaBundle->sourceBundleType,
false
);
// Update the meta bundle data
$this->updateMetaBundle($metaBundle, $site->id);
}
}
}
// If we've invalidated a meta bundle, we need to invalidate the sitemap index, too
if ($metaBundleInvalidated) {
Seomatic::$plugin->sitemaps->invalidateSitemapIndexCache();
}
}
/**
* @param string $sourceBundleType
* @param int $sourceId
* @param int|null $sourceSiteId
* @param int|null $typeId
*
* @return null|MetaBundle
*/
public function getMetaBundleBySourceId(string $sourceBundleType, int $sourceId, ?int $sourceSiteId, $typeId = null)
{
$metaBundle = null;
$typeId = (int)$typeId;
// See if we have the meta bundle cached
if (!empty($this->metaBundlesBySourceId[$sourceBundleType][$sourceId][$sourceSiteId][$typeId])) {
$id = $this->metaBundlesBySourceId[$sourceBundleType][$sourceId][$sourceSiteId][$typeId];
if (!empty($this->metaBundles[$id])) {
return $this->metaBundles[$id];
}
}
// Look for a matching meta bundle in the db
$query = (new Query())
->from(['{{%seomatic_metabundles}}'])
->where([
'sourceBundleType' => $sourceBundleType,
'sourceId' => $sourceId,
'sourceSiteId' => $sourceSiteId,
]);
if (!empty($typeId)) {
$query
->andWhere([
'typeId' => $typeId,
]);
}
$metaBundleArray = $query
->one();
// If the specific query with a `typeId` returned nothing, try a more general query without `typeId`
if (empty($metaBundleArray)) {
$metaBundleArray = (new Query())
->from(['{{%seomatic_metabundles}}'])
->where([
'sourceBundleType' => $sourceBundleType,
'sourceId' => $sourceId,
'sourceSiteId' => $sourceSiteId,
])
->one();
}
if (!empty($metaBundleArray)) {
// Get the attributes from the db
$metaBundleArray = array_diff_key($metaBundleArray, array_flip(self::IGNORE_DB_ATTRIBUTES));
$metaBundle = MetaBundle::create($metaBundleArray);
$this->syncBundleWithConfig($metaBundle);
$id = count($this->metaBundles);
$this->metaBundles[$id] = $metaBundle;
$this->metaBundlesBySourceId[$sourceBundleType][$sourceId][$sourceSiteId][$typeId] = $id;
} else {
// If it doesn't exist, create it
$seoElement = Seomatic::$plugin->seoElements->getSeoElementByMetaBundleType($sourceBundleType);
if ($seoElement !== null) {
$sourceModel = $seoElement::sourceModelFromId($sourceId);
if ($sourceModel) {
$metaBundle = $this->createMetaBundleFromSeoElement($seoElement, $sourceModel, $sourceSiteId, null, true);
}
}
}
return $metaBundle;
}
/**
* Resave all the meta bundles of a given type.
*
* @param string $metaBundleType
*/
public function resaveMetaBundles(string $metaBundleType)
{
// For all meta bundles of a given type
$metaBundleRows = (new Query())
->from(['{{%seomatic_metabundles}}'])
->where(['sourceBundleType' => $metaBundleType])
->all();
foreach ($metaBundleRows as $metaBundleRow) {
// Create it from the DB data
$metaBundleData = array_diff_key($metaBundleRow, array_flip(self::IGNORE_DB_ATTRIBUTES));
$metaBundle = MetaBundle::create($metaBundleData);
if (!$metaBundle) {
continue;
}
// Sync it and update it.
Seomatic::$plugin->metaBundles->syncBundleWithConfig($metaBundle, true);
Seomatic::$plugin->metaBundles->updateMetaBundle($metaBundle, $metaBundle->sourceSiteId);
}
}
/**
* Invalidate the caches and data structures associated with this MetaBundle
*
* @param Element|null $element
* @param bool $isNew
*/
public function invalidateMetaBundleByElement($element, bool $isNew = false)
{
$metaBundleInvalidated = false;
$invalidateMetaBundle = true;
$sitemapInvalidated = false;
if (Seomatic::$craft32) {
if ($element->getIsDraft() || $element->getIsRevision()) {
$invalidateMetaBundle = false;
}
}
if ($element && $invalidateMetaBundle) {
$uri = $element->uri ?? '';
// Normalize the incoming URI to account for `__home__`
if ($element->uri) {
$uri = ($element->uri === '__home__') ? '' : $uri;
}
// Invalidate sitemap caches after an existing element is saved
list($sourceId, $sourceBundleType, $sourceHandle, $sourceSiteId, $typeId)
= $this->getMetaSourceFromElement($element);
if ($sourceId) {
Craft::info(
'Invalidating meta bundle: '
. $uri
. '/'
. $sourceSiteId,
__METHOD__
);
$metaBundleInvalidated = true;
Seomatic::$plugin->metaContainers->invalidateContainerCacheByPath($uri, $sourceSiteId);
// Invalidate the sitemap cache
$metaBundle = $this->getMetaBundleBySourceId($sourceBundleType, $sourceId, $sourceSiteId);
if ($metaBundle) {
$dateUpdated = $element->dateUpdated ?? $element->dateCreated;
$metaBundle->sourceDateUpdated = $dateUpdated;
// Update the meta bundle data
$this->updateMetaBundle($metaBundle, $sourceSiteId);
if (
$metaBundle->metaSitemapVars->sitemapUrls
&& !$element->resaving) {
$sitemapInvalidated = true;
Seomatic::$plugin->sitemaps->invalidateSitemapCache(
$metaBundle->sourceHandle,
$metaBundle->sourceSiteId,
$metaBundle->sourceBundleType,
false
);
}
}
}
// If we've invalidated a meta bundle, we need to invalidate the sitemap index, too
if ($metaBundleInvalidated
&& $sitemapInvalidated
&& !$element->resaving) {
Seomatic::$plugin->sitemaps->invalidateSitemapIndexCache();
}
}
}
/**
* @param Element $element
*
* @return array
*/
public function getMetaSourceFromElement(Element $element): array
{
$sourceId = 0;
$typeId = null;
$sourceSiteId = 0;
$sourceHandle = '';
// See if this is a section we are tracking
$sourceBundleType = Seomatic::$plugin->seoElements->getMetaBundleTypeFromElement($element);
if ($sourceBundleType) {
$seoElement = Seomatic::$plugin->seoElements->getSeoElementByMetaBundleType($sourceBundleType);
if ($seoElement) {
$sourceId = $seoElement::sourceIdFromElement($element);
$typeId = $seoElement::typeIdFromElement($element);
$sourceHandle = $seoElement::sourceHandleFromElement($element);
$sourceSiteId = $element->siteId;
}
} else {
$sourceBundleType = '';
}
return [$sourceId, $sourceBundleType, $sourceHandle, $sourceSiteId, $typeId];
}
/**
* Get all of the meta bundles for a given $sourceSiteId
*
* @param int|null $sourceSiteId
*
* @return array
*/
public function getContentMetaBundlesForSiteId($sourceSiteId, $filter = ''): array
{
$metaBundles = [];
$bundles = [];
// Since sectionIds, CategoryIds, etc. are not unique, we need to do separate queries and combine them
$seoElements = Seomatic::$plugin->seoElements->getAllSeoElementTypes();
foreach ($seoElements as $seoElement) {
$subQuery = (new Query())
->from(['{{%seomatic_metabundles}}'])
->where(['=', 'sourceBundleType', $seoElement::META_BUNDLE_TYPE]);
if ((int)$sourceSiteId !== 0) {
$subQuery->andWhere(['sourceSiteId' => $sourceSiteId]);
}
if ($filter !== '') {
$subQuery->andWhere(['like', 'sourceName', $filter]);
}
$bundleQuery = (new Query())
->select(['mb.*'])
->from(['mb' => $subQuery])
->leftJoin(['mb2' => $subQuery], [
'and',
'[[mb.sourceId]] = [[mb2.sourceId]]',
'[[mb.id]] < [[mb2.id]]',
])
->where(['mb2.id' => null]);
$bundles = array_merge($bundles, $bundleQuery->all());
}
foreach ($bundles as $bundle) {
$bundle = array_diff_key($bundle, array_flip(self::IGNORE_DB_ATTRIBUTES));
$metaBundle = MetaBundle::create($bundle);
if ($metaBundle) {
$metaBundles[] = $metaBundle;
}
}
return $metaBundles;
}
/**
* Get the parent content meta bundle for a given element.
*
* @param Element $element
* @return mixed|MetaBundle|null
*/
public function getContentMetaBundleForElement(Element $element)
{
$source = $this->getMetaSourceFromElement($element);
$key = implode(".", $source) . '.' . $element->siteId;
if (empty($this->elementContentMetaBundles[$key])) {
$this->elementContentMetaBundles[$key] = $this->getMetaBundleBySourceId($source[1], $source[0], $element->siteId, $source[4]);
}
return $this->elementContentMetaBundles[$key];
}
/**
* Set fields the user is unable to edit to an empty string, so they are
* filtered out when meta containers are combined
*
* @param MetaBundle $metaBundle
* @param string $fieldHandle
*/
public function pruneFieldMetaBundleSettings(MetaBundle $metaBundle, string $fieldHandle)
{
/** @var SeoSettings|null $seoSettingsField */
$seoSettingsField = Craft::$app->getFields()->getFieldByHandle($fieldHandle);
if ($seoSettingsField) {
$seoSettingsEnabledFields = array_flip(array_merge(
$seoSettingsField->generalEnabledFields,
$seoSettingsField->twitterEnabledFields,
$seoSettingsField->facebookEnabledFields,
$seoSettingsField->sitemapEnabledFields
));
// Always include some fields, as they are calculated even if not explicitly included
$seoSettingsEnabledFields = array_merge(
$seoSettingsEnabledFields,
array_flip(self::ALWAYS_INCLUDED_SEO_SETTINGS_FIELDS)
);
// metaGlobalVars
$attributes = $metaBundle->metaGlobalVars->getAttributes();
// Get a list of explicitly inherited values
$inherited = array_keys(ArrayHelper::remove($attributes, 'inherited', []));
$emptyValues = array_fill_keys(array_keys(array_diff_key($attributes, $seoSettingsEnabledFields)), '');
// Nullify the inherited values
$emptyValues = array_merge($emptyValues, array_fill_keys($inherited, ''));
foreach ($inherited as $inheritedAttribute) {
foreach (self::COMPOSITE_INHERITANCE_CHILDREN[$inheritedAttribute] ?? [] as $child) {
list($model, $attribute) = explode('.', $child);
$metaBundle->{$model}->$attribute = '';
}
}
$attributes = array_merge($attributes, $emptyValues);
$metaBundle->metaGlobalVars->setAttributes($attributes, false);
// Handle the mainEntityOfPage
if (!in_array('mainEntityOfPage', $seoSettingsField->generalEnabledFields, false)) {
$metaBundle->metaGlobalVars->mainEntityOfPage = '';
}
// metaSiteVars
$attributes = $metaBundle->metaSiteVars->getAttributes();
$emptyValues = array_fill_keys(array_keys(array_diff_key($attributes, $seoSettingsEnabledFields)), '');
$attributes = array_merge($attributes, $emptyValues);
$metaBundle->metaSiteVars->setAttributes($attributes, false);
// metaSitemapVars
$attributes = $metaBundle->metaSitemapVars->getAttributes();
// Get a list of explicitly inherited values
$inherited = array_keys(ArrayHelper::remove($attributes, 'inherited', []));
$emptyValues = array_fill_keys(array_keys(array_diff_key($attributes, $seoSettingsEnabledFields)), '');
// Nullify the inherited values
$emptyValues = array_merge($emptyValues, array_fill_keys($inherited, ''));
$attributes = array_merge($attributes, $emptyValues);
$metaBundle->metaSitemapVars->setAttributes($attributes, false);
}
}
/**
* Remove any meta bundles from the $metaBundles array that no longer
* correspond with an SeoElement
*
* @param array $metaBundles
*/
public function pruneVestigialMetaBundles(array &$metaBundles)
{
foreach ($metaBundles as $key => $metaBundle) {
$prune = $this->pruneVestigialMetaBundle($metaBundle);
/** @var MetaBundle $metaBundle */
if ($prune) {
unset($metaBundles[$key]);
}
}
ArrayHelper::multisort($metaBundles, 'sourceName');
}
/**
* Determine whether a given MetaBundle is vestigial or not
*
* @param $metaBundle
*
* @return bool
*/
public function pruneVestigialMetaBundle($metaBundle): bool
{
$prune = false;
$sourceBundleType = $metaBundle->sourceBundleType;
if ($sourceBundleType && $sourceBundleType !== self::GLOBAL_META_BUNDLE) {
$seoElement = Seomatic::$plugin->seoElements->getSeoElementByMetaBundleType($sourceBundleType);
if ($seoElement) {
$sourceModel = $seoElement::sourceModelFromId($metaBundle->sourceId);
/** @var Section|CategoryGroup|ProductType|null $sourceModel */
if ($sourceModel === null) {
$prune = true;
} else {
$prune = true;
$siteSettings = $sourceModel->getSiteSettings();
if (!empty($siteSettings)) {
/** @var Section_SiteSettings $siteSetting */
foreach ($siteSettings as $siteSetting) {
if ($siteSetting->siteId == $metaBundle->sourceSiteId && $siteSetting->hasUrls && SiteHelper::siteEnabledWithUrls($siteSetting->siteId)) {
$prune = false;
}
}
}
}
} else {
$prune = true;
}
}
return $prune;
}
/**
* Delete any meta bundles from the $metaBundles array that no longer
* correspond with an SeoElement
*
* @param array $metaBundles
*/
public function deleteVestigialMetaBundles(array $metaBundles)
{
foreach ($metaBundles as $key => $metaBundle) {
$prune = $this->pruneVestigialMetaBundle($metaBundle);
/** @var MetaBundle $metaBundle */
if ($prune) {
$this->deleteMetaBundleBySourceId(
$metaBundle->sourceBundleType,
$metaBundle->sourceId,
$metaBundle->sourceSiteId
);
}
}
}
/**
* Delete a meta bundle by $sourceId
*
* @param string $sourceBundleType
* @param int $sourceId
* @param int|null $siteId
*/
public function deleteMetaBundleBySourceId(string $sourceBundleType, int $sourceId, ?int $siteId = null)
{
$sites = [];
if ($siteId === null) {
$sites = Craft::$app->getSites()->getAllSites();
} else {
$sites[] = Craft::$app->getSites()->getSiteById($siteId);
}
/** @var Site $site */
foreach ($sites as $site) {
// Look for a matching meta bundle in the db
$metaBundleRecord = MetaBundleRecord::findOne([
'sourceBundleType' => $sourceBundleType,
'sourceId' => $sourceId,
'sourceSiteId' => $site->id,
]);
if ($metaBundleRecord) {
try {
$metaBundleRecord->delete();
} catch (Throwable $e) {
Craft::error($e->getMessage(), __METHOD__);
}
Craft::info(
'Meta bundle deleted: '
. $sourceId
. ' from siteId: '
. $site->id,
__METHOD__
);
}
}
}
/**
* Get all of the data from $bundle in containers of $type
*
* @param MetaBundle $bundle
* @param string $type
*
* @return array
*/
public function getContainerDataFromBundle(MetaBundle $bundle, string $type): array
{
$containerData = [];
foreach ($bundle->metaContainers as $metaContainer) {
if ($metaContainer::CONTAINER_TYPE === $type) {
foreach ($metaContainer->data as $dataHandle => $data) {
$containerData[$dataHandle] = $data;