/
Elements.php
2046 lines (1777 loc) · 78.3 KB
/
Elements.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
/**
* @link https://craftcms.com/
* @copyright Copyright (c) Pixel & Tonic, Inc.
* @license https://craftcms.github.io/license/
*/
namespace craft\services;
use Craft;
use craft\base\Element;
use craft\base\ElementAction;
use craft\base\ElementActionInterface;
use craft\base\ElementInterface;
use craft\base\Field;
use craft\db\Query;
use craft\db\QueryAbortedException;
use craft\db\Table;
use craft\elements\Asset;
use craft\elements\Category;
use craft\elements\db\ElementQuery;
use craft\elements\db\ElementQueryInterface;
use craft\elements\Entry;
use craft\elements\GlobalSet;
use craft\elements\MatrixBlock;
use craft\elements\Tag;
use craft\elements\User;
use craft\errors\ElementNotFoundException;
use craft\errors\InvalidElementException;
use craft\errors\OperationAbortedException;
use craft\errors\SiteNotFoundException;
use craft\events\BatchElementActionEvent;
use craft\events\DeleteElementEvent;
use craft\events\ElementEvent;
use craft\events\ElementQueryEvent;
use craft\events\MergeElementsEvent;
use craft\events\RegisterComponentTypesEvent;
use craft\helpers\ArrayHelper;
use craft\helpers\Component as ComponentHelper;
use craft\helpers\DateTimeHelper;
use craft\helpers\Db;
use craft\helpers\ElementHelper;
use craft\helpers\StringHelper;
use craft\queue\jobs\FindAndReplace;
use craft\queue\jobs\UpdateElementSlugsAndUris;
use craft\records\Element as ElementRecord;
use craft\records\Element_SiteSettings as Element_SiteSettingsRecord;
use craft\records\StructureElement as StructureElementRecord;
use yii\base\Behavior;
use yii\base\Component;
use yii\base\Exception;
use yii\base\InvalidArgumentException;
use yii\db\Exception as DbException;
/**
* The Elements service provides APIs for managing elements.
* An instance of the Elements service is globally accessible in Craft via [[\craft\base\ApplicationTrait::getElements()|`Craft::$app->elements`]].
*
* @author Pixel & Tonic, Inc. <support@pixelandtonic.com>
* @since 3.0
*/
class Elements extends Component
{
// Constants
// =========================================================================
/**
* @event RegisterComponentTypesEvent The event that is triggered when registering element types.
*
* Element types must implement [[ElementInterface]]. [[Element]] provides a base implementation.
*
* See [Element Types](https://docs.craftcms.com/v3/element-types.html) for documentation on creating element types.
* ---
* ```php
* use craft\events\RegisterComponentTypesEvent;
* use craft\services\Elements;
* use yii\base\Event;
*
* Event::on(Elements::class,
* Elements::EVENT_REGISTER_ELEMENT_TYPES,
* function(RegisterComponentTypesEvent $event) {
* $event->types[] = MyElementType::class;
* }
* );
* ```
*/
const EVENT_REGISTER_ELEMENT_TYPES = 'registerElementTypes';
/**
* @event MergeElementsEvent The event that is triggered after two elements are merged together.
*/
const EVENT_AFTER_MERGE_ELEMENTS = 'afterMergeElements';
/**
* @event DeleteElementEvent The event that is triggered before an element is deleted.
*/
const EVENT_BEFORE_DELETE_ELEMENT = 'beforeDeleteElement';
/**
* @event ElementEvent The event that is triggered after an element is deleted.
*/
const EVENT_AFTER_DELETE_ELEMENT = 'afterDeleteElement';
/**
* @event ElementEvent The event that is triggered before an element is restored.
*/
const EVENT_BEFORE_RESTORE_ELEMENT = 'beforeRestoreElement';
/**
* @event ElementEvent The event that is triggered after an element is restored.
*/
const EVENT_AFTER_RESTORE_ELEMENT = 'afterRestoreElement';
/**
* @event ElementEvent The event that is triggered before an element is saved.
*/
const EVENT_BEFORE_SAVE_ELEMENT = 'beforeSaveElement';
/**
* @event ElementEvent The event that is triggered after an element is saved.
*/
const EVENT_AFTER_SAVE_ELEMENT = 'afterSaveElement';
/**
* @event ElementQueryEvent The event that is triggered before resaving a batch of elements.
*/
const EVENT_BEFORE_RESAVE_ELEMENTS = 'beforeResaveElements';
/**
* @event ElementQueryEvent The event that is triggered after resaving a batch of elements.
*/
const EVENT_AFTER_RESAVE_ELEMENTS = 'afterResaveElements';
/**
* @event BatchElementActionEvent The event that is triggered before an element is resaved.
*/
const EVENT_BEFORE_RESAVE_ELEMENT = 'beforeResaveElement';
/**
* @event BatchElementActionEvent The event that is triggered after an element is resaved.
*/
const EVENT_AFTER_RESAVE_ELEMENT = 'afterResaveElement';
/**
* @event ElementQueryEvent The event that is triggered before propagating a batch of elements.
*/
const EVENT_BEFORE_PROPAGATE_ELEMENTS = 'beforePropagateElements';
/**
* @event ElementQueryEvent The event that is triggered after propagating a batch of elements.
*/
const EVENT_AFTER_PROPAGATE_ELEMENTS = 'afterPropagateElements';
/**
* @event BatchElementActionEvent The event that is triggered before an element is propagated.
*/
const EVENT_BEFORE_PROPAGATE_ELEMENT = 'beforePropagateElement';
/**
* @event BatchElementActionEvent The event that is triggered after an element is propagated.
*/
const EVENT_AFTER_PROPAGATE_ELEMENT = 'afterPropagateElement';
/**
* @event ElementEvent The event that is triggered before an element’s slug and URI are updated, usually following a Structure move.
*/
const EVENT_BEFORE_UPDATE_SLUG_AND_URI = 'beforeUpdateSlugAndUri';
/**
* @event ElementEvent The event that is triggered after an element’s slug and URI are updated, usually following a Structure move.
*/
const EVENT_AFTER_UPDATE_SLUG_AND_URI = 'afterUpdateSlugAndUri';
/**
* @event ElementActionEvent The event that is triggered before an element action is performed.
*
* You may set [[ElementActionEvent::isValid]] to `false` to prevent the action from being performed.
*/
const EVENT_BEFORE_PERFORM_ACTION = 'beforePerformAction';
/**
* @event ElementActionEvent The event that is triggered after an element action is performed.
*/
const EVENT_AFTER_PERFORM_ACTION = 'afterPerformAction';
// Static
// =========================================================================
/**
* @var array Stores a mapping of element IDs to their duplicated element ID(s).
*/
public static $duplicatedElementIds = [];
// Properties
// =========================================================================
/**
* @var array|null
*/
private $_placeholderElements;
/**
* @var array
* @see setPlaceholderElement()
* @see getElementByUri()
*/
private $_placeholderUris;
/**
* @var string[]
*/
private $_elementTypesByRefHandle = [];
// Public Methods
// =========================================================================
/**
* Creates an element with a given config.
*
* @param mixed $config The field’s class name, or its config, with a `type` value and optionally a `settings` value
* @return ElementInterface The element
*/
public function createElement($config): ElementInterface
{
if (is_string($config)) {
$config = ['type' => $config];
}
/** @noinspection PhpIncompatibleReturnTypeInspection */
return ComponentHelper::createComponent($config, ElementInterface::class);
}
// Finding Elements
// -------------------------------------------------------------------------
/**
* Returns an element by its ID.
*
* If no element type is provided, the method will first have to run a DB query to determine what type of element
* the $id is, so you should definitely pass it if it’s known.
* The element’s status will not be a factor when using this method.
*
* @param int $elementId The element’s ID.
* @param string|null $elementType The element class.
* @param int|null $siteId The site to fetch the element in.
* Defaults to the current site.
* @param array $criteria
* @return ElementInterface|null The matching element, or `null`.
*/
public function getElementById(int $elementId, string $elementType = null, int $siteId = null, array $criteria = [])
{
if (!$elementId) {
return null;
}
if ($elementType === null) {
/** @noinspection CallableParameterUseCaseInTypeContextInspection */
$elementType = $this->getElementTypeById($elementId);
if ($elementType === null) {
return null;
}
}
/** @var Element $elementType */
/** @var ElementQuery $query */
$query = $elementType::find();
$query->id = $elementId;
$query->siteId = $siteId;
$query->anyStatus();
// Is this a draft/revision?
try {
$data = (new Query())
->select(['draftId', 'revisionId'])
->from([Table::ELEMENTS])
->where(['id' => $elementId])
->one();
} catch (DbException $e) {
// Not on schema 3.2.6+ yet
}
if (!empty($data['draftId'])) {
$query->draftId($data['draftId']);
} else if (!empty($data['revisionId'])) {
$query->revisionId($data['revisionId']);
}
Craft::configure($query, $criteria);
return $query->one();
}
/**
* Returns an element by its URI.
*
* @param string $uri The element’s URI.
* @param int|null $siteId The site to look for the URI in, and to return the element in.
* Defaults to the current site.
* @param bool $enabledOnly Whether to only look for an enabled element. Defaults to `false`.
* @return ElementInterface|null The matching element, or `null`.
*/
public function getElementByUri(string $uri, int $siteId = null, bool $enabledOnly = false)
{
if ($uri === '') {
$uri = '__home__';
}
if ($siteId === null) {
/** @noinspection PhpUnhandledExceptionInspection */
$siteId = Craft::$app->getSites()->getCurrentSite()->id;
}
// See if we already have a placeholder for this element URI
if (isset($this->_placeholderUris[$uri][$siteId])) {
return $this->_placeholderUris[$uri][$siteId];
}
// First get the element ID and type
$query = (new Query())
->select(['elements.id', 'elements.type'])
->from(['{{%elements}} elements'])
->innerJoin('{{%elements_sites}} elements_sites', '[[elements_sites.elementId]] = [[elements.id]]')
->where([
'elements_sites.siteId' => $siteId,
]);
// todo: remove schema version conditions after next beakpoint
$schemaVersion = Craft::$app->getInstalledSchemaVersion();
if (version_compare($schemaVersion, '3.1.0', '>=')) {
$query->andWhere(['elements.dateDeleted' => null]);
}
if (version_compare($schemaVersion, '3.2.6', '>=')) {
$query->andWhere([
'elements.draftId' => null,
'elements.revisionId' => null,
]);
}
if (Craft::$app->getDb()->getIsMysql()) {
$query->andWhere([
'elements_sites.uri' => $uri,
]);
} else {
$query->andWhere([
'lower([[elements_sites.uri]])' => mb_strtolower($uri),
]);
}
if ($enabledOnly) {
$query->andWhere([
'elements_sites.enabled' => true,
'elements.enabled' => true,
'elements.archived' => false,
]);
}
$result = $query->one();
return $result ? $this->getElementById($result['id'], $result['type'], $siteId) : null;
}
/**
* Returns the class of an element with a given ID.
*
* @param int $elementId The element’s ID
* @return string|null The element’s class, or null if it could not be found
*/
public function getElementTypeById(int $elementId)
{
$class = (new Query())
->select(['type'])
->from([Table::ELEMENTS])
->where(['id' => $elementId])
->scalar();
return $class !== false ? $class : null;
}
/**
* Returns the classes of elements with the given IDs.
*
* @param int[] $elementIds The elements’ IDs
* @return string[]
*/
public function getElementTypesByIds(array $elementIds): array
{
return (new Query())
->select(['type'])
->distinct(true)
->from([Table::ELEMENTS])
->where(['id' => $elementIds])
->column();
}
/**
* Returns an element’s URI for a given site.
*
* @param int $elementId The element’s ID.
* @param int $siteId The site to search for the element’s URI in.
* @return string|null|false The element’s URI or `null`, or `false` if the element doesn’t exist.
*/
public function getElementUriForSite(int $elementId, int $siteId)
{
return (new Query())
->select(['uri'])
->from([Table::ELEMENTS_SITES])
->where(['elementId' => $elementId, 'siteId' => $siteId])
->scalar();
}
/**
* Returns the site IDs that a given element is enabled in.
*
* @param int $elementId The element’s ID.
* @return int[] The site IDs that the element is enabled in. If the element could not be found, an empty array
* will be returned.
*/
public function getEnabledSiteIdsForElement(int $elementId): array
{
return (new Query())
->select(['siteId'])
->from([Table::ELEMENTS_SITES])
->where(['elementId' => $elementId, 'enabled' => 1])
->column();
}
// Saving Elements
// -------------------------------------------------------------------------
/**
* Handles all of the routine tasks that go along with saving elements.
*
* Those tasks include:
*
* - Validating its content (if $validateContent is `true`, or it’s left as `null` and the element is enabled)
* - Ensuring the element has a title if its type [[Element::hasTitles()|has titles]], and giving it a
* default title in the event that $validateContent is set to `false`
* - Saving a row in the `elements` table
* - Assigning the element’s ID on the element model, if it’s a new element
* - Assigning the element’s ID on the element’s content model, if there is one and it’s a new set of content
* - Updating the search index with new keywords from the element’s content
* - Setting a unique URI on the element, if it’s supposed to have one.
* - Saving the element’s row(s) in the `elements_sites` and `content` tables
* - Deleting any rows in the `elements_sites` and `content` tables that no longer need to be there
* - Cleaning any template caches that the element was involved in
*
* The function will fire `beforeElementSave` and `afterElementSave` events, and will call `beforeSave()`
* and `afterSave()` methods on the passed-in element, giving the element opportunities to hook into the
* save process.
*
* Example usage - creating a new entry:
*
* ```php
* $entry = new Entry();
* $entry->sectionId = 10;
* $entry->typeId = 1;
* $entry->authorId = 5;
* $entry->enabled = true;
* $entry->title = "Hello World!";
* $entry->setFieldValues([
* 'body' => "<p>I can’t believe I literally just called this “Hello World!”.</p>",
* ]);
* $success = Craft::$app->elements->saveElement($entry);
* if (!$success) {
* Craft::error('Couldn’t save the entry "'.$entry->title.'"', __METHOD__);
* }
* ```
*
* @param ElementInterface $element The element that is being saved
* @param bool $runValidation Whether the element should be validated
* @param bool $propagate Whether the element should be saved across all of its supported sites
* (this can only be disabled when updating an existing element)
* @return bool
* @throws ElementNotFoundException if $element has an invalid $id
* @throws Exception if the $element doesn’t have any supported sites
* @throws \Throwable if reasons
*/
public function saveElement(ElementInterface $element, bool $runValidation = true, bool $propagate = true): bool
{
/** @var Element $element */
$isNewElement = !$element->id;
if ($isNewElement) {
// Give it a UID right away
if (!$element->uid) {
$element->uid = StringHelper::UUID();
}
// Let Matrix fields, etc., know they should be duplicating their values across all sites.
$element->propagateAll = true;
}
// Fire a 'beforeSaveElement' event
if ($this->hasEventHandlers(self::EVENT_BEFORE_SAVE_ELEMENT)) {
$this->trigger(self::EVENT_BEFORE_SAVE_ELEMENT, new ElementEvent([
'element' => $element,
'isNew' => $isNewElement
]));
}
if (!$element->beforeSave($isNewElement)) {
return false;
}
// Get the sites supported by this element
if (empty($supportedSites = ElementHelper::supportedSitesForElement($element))) {
throw new Exception('All elements must have at least one site associated with them.');
}
// Make sure the element actually supports the site it's being saved in
$supportedSiteIds = ArrayHelper::getColumn($supportedSites, 'siteId');
if (!in_array($element->siteId, $supportedSiteIds, false)) {
throw new Exception('Attempting to save an element in an unsupported site.');
}
// If the element only supports a single site, ensure it's enabled for that site
if (count($supportedSites) === 1) {
$element->enabledForSite = true;
}
// Set a dummy title if there isn't one already and the element type has titles
if (!$runValidation && $element::hasContent() && $element::hasTitles() && !$element->validate(['title'])) {
if ($isNewElement) {
$element->title = Craft::t('app', 'New {type}', ['type' => $element::displayName()]);
} else {
$element->title = $element::displayName() . ' ' . $element->id;
}
}
// Validate
if ($runValidation && !$element->validate()) {
Craft::info('Element not saved due to validation error: ' . print_r($element->errors, true), __METHOD__);
return false;
}
$transaction = Craft::$app->getDb()->beginTransaction();
try {
// Get the element record
if (!$isNewElement) {
$elementRecord = ElementRecord::findOne($element->id);
if (!$elementRecord) {
throw new ElementNotFoundException("No element exists with the ID '{$element->id}'");
}
} else {
$elementRecord = new ElementRecord();
$elementRecord->type = get_class($element);
$elementRecord->uid = $element->uid;
}
// Set the attributes
$elementRecord->uid = $element->uid;
$elementRecord->draftId = $element->draftId;
$elementRecord->revisionId = $element->revisionId;
$elementRecord->fieldLayoutId = $element->fieldLayoutId = $element->fieldLayoutId ?? $element->getFieldLayout()->id ?? null;
$elementRecord->enabled = (bool)$element->enabled;
$elementRecord->archived = (bool)$element->archived;
if ($isNewElement) {
if (isset($element->dateCreated)) {
$elementRecord->dateCreated = Db::prepareValueForDb($element->dateCreated);
}
if (isset($element->dateUpdated)) {
$elementRecord->dateUpdated = Db::prepareValueForDb($element->dateUpdated);
}
} else if ($element->propagating || $element->resaving) {
// Prevent ActiveRecord::prepareForDb() from changing the dateUpdated
$elementRecord->markAttributeDirty('dateUpdated');
} else {
// Force a new dateUpdated value
$elementRecord->dateUpdated = Db::prepareValueForDb(new \DateTime());
}
// Save the element record
$elementRecord->save(false);
$dateCreated = DateTimeHelper::toDateTime($elementRecord->dateCreated);
if ($dateCreated === false) {
throw new Exception('There was a problem calculating dateCreated.');
}
$dateUpdated = DateTimeHelper::toDateTime($elementRecord->dateUpdated);
if ($dateUpdated === false) {
throw new Exception('There was a problem calculating dateUpdated.');
}
// Save the new dateCreated and dateUpdated dates on the model
$element->dateCreated = $dateCreated;
$element->dateUpdated = $dateUpdated;
if ($isNewElement) {
// Save the element ID on the element model
$element->id = $elementRecord->id;
// If there's a temp ID, update the URI
if ($element->tempId && $element->uri) {
$element->uri = str_replace($element->tempId, $element->id, $element->uri);
$element->tempId = null;
}
}
// Save the element's site settings record
if (!$isNewElement) {
$siteSettingsRecord = Element_SiteSettingsRecord::findOne([
'elementId' => $element->id,
'siteId' => $element->siteId,
]);
}
if (empty($siteSettingsRecord)) {
// First time we've saved the element for this site
$siteSettingsRecord = new Element_SiteSettingsRecord();
$siteSettingsRecord->elementId = $element->id;
$siteSettingsRecord->siteId = $element->siteId;
}
$siteSettingsRecord->slug = $element->slug;
$siteSettingsRecord->uri = $element->uri;
$siteSettingsRecord->enabled = (bool)$element->enabledForSite;
if (!$siteSettingsRecord->save(false)) {
throw new Exception('Couldn’t save elements’ site settings record.');
}
// Save the content
if ($element::hasContent()) {
Craft::$app->getContent()->saveContent($element);
}
// It is now officially saved
$element->afterSave($isNewElement);
// Update search index
if (!ElementHelper::isDraftOrRevision($element)) {
Craft::$app->getSearch()->indexElementAttributes($element);
}
// Update the element across the other sites?
if (($isNewElement || $propagate) && $element::isLocalized() && Craft::$app->getIsMultiSite()) {
foreach ($supportedSites as $siteInfo) {
// Skip the master site
if ($siteInfo['siteId'] != $element->siteId) {
$this->_propagateElement($element, $isNewElement, $siteInfo);
}
}
}
// It's now fully saved and propagated
if (!$element->propagating && !$element->duplicateOf) {
$element->afterPropagate($isNewElement);
}
$transaction->commit();
} catch (\Throwable $e) {
$transaction->rollBack();
throw $e;
}
// Delete the rows that don't need to be there anymore
if (!$isNewElement) {
Db::deleteIfExists(
Table::ELEMENTS_SITES,
[
'and',
['elementId' => $element->id],
['not', ['siteId' => $supportedSiteIds]]
]
);
if ($element::hasContent()) {
Db::deleteIfExists(
$element->getContentTable(),
[
'and',
['elementId' => $element->id],
['not', ['siteId' => $supportedSiteIds]]
]
);
}
}
// Delete any caches involving this element. (Even do this for new elements, since they
// might pop up in a cached criteria.)
Craft::$app->getTemplateCaches()->deleteCachesByElement($element);
// Fire an 'afterSaveElement' event
if ($this->hasEventHandlers(self::EVENT_AFTER_SAVE_ELEMENT)) {
$this->trigger(self::EVENT_AFTER_SAVE_ELEMENT, new ElementEvent([
'element' => $element,
'isNew' => $isNewElement,
]));
}
return true;
}
/**
* Resaves all elements that match a given element query.
*
* @param ElementQueryInterface $query The element query to fetch elements with
* @param bool $continueOnError Whether to continue going if an error occurs
* @param bool $skipRevisions Whether elements that are (or belong to) a revision should be skipped
* @throws \Throwable if reasons
* @since 3.2.0
*/
public function resaveElements(ElementQueryInterface $query, bool $continueOnError = false, $skipRevisions = true)
{
// Fire a 'beforeResaveElements' event
if ($this->hasEventHandlers(self::EVENT_BEFORE_RESAVE_ELEMENTS)) {
$this->trigger(self::EVENT_BEFORE_RESAVE_ELEMENTS, new ElementQueryEvent([
'query' => $query,
]));
}
$position = 0;
try {
/** @var ElementQuery $query */
foreach ($query->each() as $element) {
$position++;
/** @var Element $element */
$element->setScenario(Element::SCENARIO_ESSENTIALS);
$element->resaving = true;
// Fire a 'beforeResaveElement' event
if ($this->hasEventHandlers(self::EVENT_BEFORE_RESAVE_ELEMENT)) {
$this->trigger(self::EVENT_BEFORE_RESAVE_ELEMENT, new BatchElementActionEvent([
'query' => $query,
'element' => $element,
'position' => $position,
]));
}
$e = null;
// Make sure this isn't a revision
if ($skipRevisions) {
try {
$root = ElementHelper::rootElement($element);
} catch (\Throwable $rootException) {
$root = null;
$e = new InvalidElementException($element, "Skipped resaving {$element} ({$element->id}) due to an error obtaining its root element: " . $rootException->getMessage());
}
if ($root && $root->getIsRevision()) {
$e = new InvalidElementException($element, "Skipped resaving {$element} ({$element->id}) because it's a revision.");
}
}
if ($e === null) {
try {
$this->saveElement($element);
} catch (\Throwable $e) {
if (!$continueOnError) {
throw $e;
}
Craft::$app->getErrorHandler()->logException($e);
}
}
// Fire an 'afterResaveElement' event
if ($this->hasEventHandlers(self::EVENT_AFTER_RESAVE_ELEMENT)) {
$this->trigger(self::EVENT_AFTER_RESAVE_ELEMENT, new BatchElementActionEvent([
'query' => $query,
'element' => $element,
'position' => $position,
'exception' => $e,
]));
}
}
} catch (QueryAbortedException $e) {
// Fail silently
}
// Fire an 'afterResaveElements' event
if ($this->hasEventHandlers(self::EVENT_AFTER_RESAVE_ELEMENTS)) {
$this->trigger(self::EVENT_AFTER_RESAVE_ELEMENTS, new ElementQueryEvent([
'query' => $query,
]));
}
}
/**
* Propagates all elements that match a given element query to another site(s).
*
* @param ElementQueryInterface $query The element query to fetch elements with
* @param bool $continueOnError Whether to continue going if an error occurs
* @throws \Throwable if reasons
* @var int|int[]|null The site ID(s) that the elements should be propagated to. If null, elements will be
* propagated to all supported sites, except the one they were queried in.
* @since 3.2.0
*/
public function propagateElements(ElementQueryInterface $query, $siteIds = null, bool $continueOnError = false)
{
// Fire a 'beforePropagateElements' event
if ($this->hasEventHandlers(self::EVENT_BEFORE_PROPAGATE_ELEMENTS)) {
$this->trigger(self::EVENT_BEFORE_PROPAGATE_ELEMENTS, new ElementQueryEvent([
'query' => $query,
]));
}
if ($siteIds !== null) {
$siteIds = (array)$siteIds;
}
$position = 0;
try {
/** @var ElementQuery $query */
foreach ($query->each() as $element) {
$position++;
/** @var Element $element */
$element->setScenario(Element::SCENARIO_ESSENTIALS);
$elementSiteIds = $siteIds ?? ArrayHelper::getColumn(ElementHelper::supportedSitesForElement($element), 'siteId');
/** @var ElementInterface|string $elementType */
$elementType = get_class($element);
// Fire a 'beforePropagateElement' event
if ($this->hasEventHandlers(self::EVENT_BEFORE_PROPAGATE_ELEMENT)) {
$this->trigger(self::EVENT_BEFORE_PROPAGATE_ELEMENT, new BatchElementActionEvent([
'query' => $query,
'element' => $element,
'position' => $position,
]));
}
$e = null;
try {
foreach ($elementSiteIds as $siteId) {
if ($siteId != $element->siteId) {
// Make sure the site element wasn't updated more recently than the main one
/** @var Element $siteElement */
$siteElement = $this->getElementById($element->id, $elementType, $siteId);
if ($siteElement === null || $siteElement->dateUpdated < $element->dateUpdated) {
$this->propagateElement($element, $siteId, $siteElement);
}
}
}
} catch (\Throwable $e) {
if (!$continueOnError) {
throw $e;
}
Craft::$app->getErrorHandler()->logException($e);
}
// Fire an 'afterPropagateElement' event
if ($this->hasEventHandlers(self::EVENT_AFTER_PROPAGATE_ELEMENT)) {
$this->trigger(self::EVENT_AFTER_PROPAGATE_ELEMENT, new BatchElementActionEvent([
'query' => $query,
'element' => $element,
'position' => $position,
'exception' => $e,
]));
}
}
} catch (QueryAbortedException $e) {
// Fail silently
}
// Fire an 'afterPropagateElements' event
if ($this->hasEventHandlers(self::EVENT_AFTER_PROPAGATE_ELEMENTS)) {
$this->trigger(self::EVENT_AFTER_PROPAGATE_ELEMENTS, new ElementQueryEvent([
'query' => $query,
]));
}
}
/**
* Duplicates an element.
*
* @param ElementInterface $element the element to duplicate
* @param array $newAttributes any attributes to apply to the duplicate
* @return ElementInterface the duplicated element
* @throws InvalidElementException if saveElement() returns false for any of the sites
* @throws \Throwable if reasons
*/
public function duplicateElement(ElementInterface $element, array $newAttributes = []): ElementInterface
{
// Make sure the element exists
/** @var Element $element */
if (!$element->id) {
throw new Exception('Attempting to duplicate an unsaved element.');
}
// Create our first clone for the $element's site
$element->getFieldValues();
/** @var Element $mainClone */
$mainClone = clone $element;
$mainClone->id = null;
$mainClone->uid = null;
$mainClone->contentId = null;
$mainClone->duplicateOf = $element;
$behaviors = ArrayHelper::remove($newAttributes, 'behaviors', []);
$mainClone->setRevisionNotes(ArrayHelper::remove($newAttributes, 'revisionNotes'));
$mainClone->setAttributes($newAttributes, false);
// Attach behaviors
foreach ($behaviors as $name => $behavior) {
if ($behavior instanceof Behavior) {
$behavior = clone $behavior;
}
$mainClone->attachBehavior($name, $behavior);
}
// Make sure the element actually supports its own site ID
$supportedSites = ElementHelper::supportedSitesForElement($mainClone);
$supportedSiteIds = ArrayHelper::getColumn($supportedSites, 'siteId');
if (!in_array($mainClone->siteId, $supportedSiteIds, false)) {
throw new Exception('Attempting to duplicate an element in an unsupported site.');
}
// Set a unique URI on the clone
try {
ElementHelper::setUniqueUri($mainClone);
} catch (OperationAbortedException $e) {
// Oh well, not worth bailing over
}
$transaction = Craft::$app->getDb()->beginTransaction();
try {
// Start with $element's site
$mainClone->setScenario(Element::SCENARIO_ESSENTIALS);
if (!$this->saveElement($mainClone, true, false)) {
throw new InvalidElementException($mainClone, 'Element ' . $element->id . ' could not be duplicated for site ' . $element->siteId);
}
// Map it
static::$duplicatedElementIds[$element->id] = $mainClone->id;
// Propagate it
foreach ($supportedSites as $siteInfo) {
if ($siteInfo['siteId'] != $mainClone->siteId) {
$siteQuery = $element::find()
->id($element->id ?: false)
->siteId($siteInfo['siteId'])
->anyStatus();
if ($element->getIsDraft()) {
$siteQuery->drafts();
} else if ($element->getIsRevision()) {
$siteQuery->revisions();
}
$siteElement = $siteQuery->one();
if ($siteElement === null) {
Craft::warning('Element ' . $element->id . ' doesn’t exist in the site ' . $siteInfo['siteId']);
continue;
}
/** @var Element $siteClone */
$siteClone = clone $siteElement;
$siteClone->duplicateOf = $siteElement;
$siteClone->propagating = true;
$siteClone->id = $mainClone->id;
$siteClone->uid = $mainClone->uid;
$siteClone->contentId = null;
// Attach behaviors
foreach ($behaviors as $name => $behavior) {
if ($behavior instanceof Behavior) {
$behavior = clone $behavior;
}
$mainClone->attachBehavior($name, $behavior);
}
$siteClone->setAttributes($newAttributes, false);
$siteClone->siteId = $siteInfo['siteId'];
// Set a unique URI on the site clone
try {
ElementHelper::setUniqueUri($siteClone);
} catch (OperationAbortedException $e) {
// Oh well, not worth bailing over
}
if (!$this->saveElement($siteClone, false, false)) {
throw new InvalidElementException($siteClone, 'Element ' . $element->id . ' could not be duplicated for site ' . $siteInfo['siteId']);
}
}
}
// It's now fully duplicated and propagated
$mainClone->afterPropagate(empty($newAttributes['id']));
$transaction->commit();
} catch (\Throwable $e) {
$transaction->rollBack();
throw $e;
}
// Clean up our tracks
$mainClone->duplicateOf = null;
return $mainClone;