-
Notifications
You must be signed in to change notification settings - Fork 626
/
Elements.php
1459 lines (1254 loc) · 54.4 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\elements\Asset;
use craft\elements\Category;
use craft\elements\db\ElementQuery;
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\events\ElementEvent;
use craft\events\MergeElementsEvent;
use craft\events\RegisterComponentTypesEvent;
use craft\helpers\App;
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\Component;
use yii\base\Exception;
/**
* 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 ElementEvent 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 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 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 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.
* @return ElementInterface|null The matching element, or `null`.
*/
public function getElementById(int $elementId, string $elementType = null, int $siteId = null)
{
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();
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;
}
// 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,
]);
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(['{{%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(['{{%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 The element’s URI, or `null`.
*/
public function getElementUriForSite(int $elementId, int $siteId)
{
return (new Query())
->select(['uri'])
->from(['{{%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(['{{%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
* @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;
// 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.');
}
// 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'])) {
$humanClass = ucfirst(App::humanizeClass(get_class($element)));
if ($isNewElement) {
$element->title = Craft::t('app', 'New {class}', ['class' => $humanClass]);
} else {
$element->title = "{$humanClass} {$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);
}
// Set the attributes
$elementRecord->fieldLayoutId = $element->fieldLayoutId = $element->fieldLayoutId ?? $element->getFieldLayout()->id ?? null;
$elementRecord->enabled = (bool)$element->enabled;
$elementRecord->archived = (bool)$element->archived;
// 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;
$element->uid = $elementRecord->uid;
// 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
Craft::$app->getSearch()->indexElementAttributes($element);
// Update the element across the other sites?
if ($propagate && $element::isLocalized() && Craft::$app->getIsMultiSite()) {
foreach ($supportedSites as $siteInfo) {
// Skip the master site
if ($siteInfo['siteId'] != $element->siteId) {
$this->_propagateElement($element, $isNewElement, $siteInfo);
}
}
}
$transaction->commit();
} catch (\Throwable $e) {
$transaction->rollBack();
throw $e;
}
// Delete the rows that don't need to be there anymore
if (!$isNewElement) {
Db::deleteIfExists(
'{{%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;
}
/**
* 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
{
// Create our first clone for the $element's site
/** @var Element $element */
$element->getFieldValues();
/** @var Element $mainClone */
$mainClone = clone $element;
$mainClone->setAttributes($newAttributes);
$mainClone->duplicateOf = $element;
$mainClone->id = null;
$mainClone->contentId = null;
// 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.');
}
$transaction = Craft::$app->getDb()->beginTransaction();
try {
// Start with $element's site
if (!$this->saveElement($mainClone, false, 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) {
$siteElement = $this->getElementById($element->id, get_class($element), $siteInfo['siteId']);
if ($siteElement === null) {
throw new Exception('Element ' . $element->id . ' doesn’t exist in the site ' . $siteInfo['siteId']);
}
/** @var Element $siteClone */
$siteClone = clone $siteElement;
$siteClone->setAttributes($newAttributes);
$siteClone->duplicateOf = $siteElement;
$siteClone->propagating = true;
$siteClone->id = $mainClone->id;
$siteClone->siteId = $siteInfo['siteId'];
$siteClone->contentId = null;
if (!$this->saveElement($siteClone, false, false)) {
throw new InvalidElementException($siteClone, 'Element ' . $element->id . ' could not be duplicated for site ' . $siteInfo['siteId']);
}
}
}
$transaction->commit();
} catch (\Throwable $e) {
$transaction->rollBack();
throw $e;
}
// Clean up our tracks
$mainClone->duplicateOf = null;
return $mainClone;
}
/**
* Updates an element’s slug and URI, along with any descendants.
*
* @param ElementInterface $element The element to update.
* @param bool $updateOtherSites Whether the element’s other sites should also be updated.
* @param bool $updateDescendants Whether the element’s descendants should also be updated.
* @param bool $queue Whether the element’s slug and URI should be updated via a job in the queue.
*/
public function updateElementSlugAndUri(ElementInterface $element, bool $updateOtherSites = true, bool $updateDescendants = true, bool $queue = false)
{
/** @var Element $element */
if ($queue) {
Craft::$app->getQueue()->push(new UpdateElementSlugsAndUris([
'elementId' => $element->id,
'elementType' => get_class($element),
'siteId' => $element->siteId,
'updateOtherSites' => $updateOtherSites,
'updateDescendants' => $updateDescendants,
]));
return;
}
if ($element::hasUris()) {
ElementHelper::setUniqueUri($element);
}
// Fire a 'beforeUpdateSlugAndUri' event
if ($this->hasEventHandlers(self::EVENT_BEFORE_UPDATE_SLUG_AND_URI)) {
$this->trigger(self::EVENT_BEFORE_UPDATE_SLUG_AND_URI, new ElementEvent([
'element' => $element
]));
}
Craft::$app->getDb()->createCommand()
->update(
'{{%elements_sites}}',
[
'slug' => $element->slug,
'uri' => $element->uri
],
[
'elementId' => $element->id,
'siteId' => $element->siteId
])
->execute();
// Fire a 'afterUpdateSlugAndUri' event
if ($this->hasEventHandlers(self::EVENT_AFTER_UPDATE_SLUG_AND_URI)) {
$this->trigger(self::EVENT_AFTER_UPDATE_SLUG_AND_URI, new ElementEvent([
'element' => $element
]));
}
// Delete any caches involving this element
Craft::$app->getTemplateCaches()->deleteCachesByElement($element);
if ($updateOtherSites) {
$this->updateElementSlugAndUriInOtherSites($element);
}
if ($updateDescendants) {
$this->updateDescendantSlugsAndUris($element, $updateOtherSites);
}
}
/**
* Updates an element’s slug and URI, for any sites besides the given one.
*
* @param ElementInterface $element The element to update.
*/
public function updateElementSlugAndUriInOtherSites(ElementInterface $element)
{
/** @var Element $element */
foreach (Craft::$app->getSites()->getAllSiteIds() as $siteId) {
if ($siteId == $element->siteId) {
continue;
}
$elementInOtherSite = $element::find()
->id($element->id)
->siteId($siteId)
->one();
if ($elementInOtherSite) {
$this->updateElementSlugAndUri($elementInOtherSite, false, false);
}
}
}
/**
* Updates an element’s descendants’ slugs and URIs.
*
* @param ElementInterface $element The element whose descendants should be updated.
* @param bool $updateOtherSites Whether the element’s other sites should also be updated.
* @param bool $queue Whether the descendants’ slugs and URIs should be updated via a job in the queue.
*/
public function updateDescendantSlugsAndUris(ElementInterface $element, bool $updateOtherSites = true, bool $queue = false)
{
/** @var Element $element */
/** @var ElementQuery $query */
$query = $element::find()
->descendantOf($element)
->descendantDist(1)
->anyStatus()
->siteId($element->siteId);
if ($queue) {
$childIds = $query->ids();
if (!empty($childIds)) {
Craft::$app->getQueue()->push(new UpdateElementSlugsAndUris([
'elementId' => $childIds,
'elementType' => get_class($element),
'siteId' => $element->siteId,
'updateOtherSites' => $updateOtherSites,
'updateDescendants' => true,
]));
}
} else {
$children = $query->all();
foreach ($children as $child) {
$this->updateElementSlugAndUri($child, $updateOtherSites, true, false);
}
}
}
/**
* Merges two elements together.
*
* This method will update the following:
* - Any relations involving the merged element
* - Any structures that contain the merged element
* - Any reference tags in textual custom fields referencing the merged element
*
* @param int $mergedElementId The ID of the element that is going away.
* @param int $prevailingElementId The ID of the element that is sticking around.
* @return bool Whether the elements were merged successfully.
* @throws \Throwable if reasons
*/
public function mergeElementsByIds(int $mergedElementId, int $prevailingElementId): bool
{
$transaction = Craft::$app->getDb()->beginTransaction();
try {
// Update any relations that point to the merged element
$relations = (new Query())
->select(['id', 'fieldId', 'sourceId', 'sourceSiteId'])
->from(['{{%relations}}'])
->where(['targetId' => $mergedElementId])
->all();
foreach ($relations as $relation) {
// Make sure the persisting element isn't already selected in the same field
$persistingElementIsRelatedToo = (new Query())
->from(['{{%relations}}'])
->where([
'fieldId' => $relation['fieldId'],
'sourceId' => $relation['sourceId'],
'sourceSiteId' => $relation['sourceSiteId'],
'targetId' => $prevailingElementId
])
->exists();
if (!$persistingElementIsRelatedToo) {
Craft::$app->getDb()->createCommand()
->update(
'{{%relations}}',
[
'targetId' => $prevailingElementId
],
[
'id' => $relation['id']
])
->execute();
}
}
// Update any structures that the merged element is in
$structureElements = (new Query())
->select(['id', 'structureId'])
->from(['{{%structureelements}}'])
->where(['elementId' => $mergedElementId])
->all();
foreach ($structureElements as $structureElement) {
// Make sure the persisting element isn't already a part of that structure
$persistingElementIsInStructureToo = (new Query())
->from(['{{%structureelements}}'])
->where([
'structureId' => $structureElement['structureId'],
'elementId' => $prevailingElementId
])
->exists();
if (!$persistingElementIsInStructureToo) {
Craft::$app->getDb()->createCommand()
->update('{{%relations}}',
[
'elementId' => $prevailingElementId
],
[
'id' => $structureElement['id']
])
->execute();
}
}
// Update any reference tags
/** @var ElementInterface|null $elementType */
$elementType = $this->getElementTypeById($prevailingElementId);
if ($elementType !== null && ($refHandle = $elementType::refHandle()) !== null) {
$refTagPrefix = "{{$refHandle}:";
$queue = Craft::$app->getQueue();
$queue->push(new FindAndReplace([
'description' => Craft::t('app', 'Updating element references'),
'find' => $refTagPrefix . $mergedElementId . ':',
'replace' => $refTagPrefix . $prevailingElementId . ':',
]));
$queue->push(new FindAndReplace([
'description' => Craft::t('app', 'Updating element references'),
'find' => $refTagPrefix . $mergedElementId . '}',
'replace' => $refTagPrefix . $prevailingElementId . '}',
]));
}
// Fire an 'afterMergeElements' event
if ($this->hasEventHandlers(self::EVENT_AFTER_MERGE_ELEMENTS)) {
$this->trigger(self::EVENT_AFTER_MERGE_ELEMENTS, new MergeElementsEvent([
'mergedElementId' => $mergedElementId,
'prevailingElementId' => $prevailingElementId
]));
}
// Now delete the merged element
$success = $this->deleteElementById($mergedElementId);
$transaction->commit();
return $success;
} catch (\Throwable $e) {
$transaction->rollBack();
throw $e;
}
}
/**
* Deletes an element by its ID.
*
* @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.
* @return bool Whether the element was deleted successfully
* @throws \Throwable
*/
public function deleteElementById(int $elementId, string $elementType = null, int $siteId = null): bool
{
if ($elementType === null) {
/** @noinspection CallableParameterUseCaseInTypeContextInspection */
$elementType = $this->getElementTypeById($elementId);
if ($elementType === null) {
return false;
}
}
if ($siteId === null && $elementType::isLocalized() && Craft::$app->getIsMultiSite()) {
// Get a site this element is enabled in
$siteId = (int)(new Query())
->select('siteId')
->from('{{%elements_sites}}')
->where(['elementId' => $elementId])
->scalar();
if ($siteId === 0) {
return false;
}
}
$element = $this->getElementById($elementId, $elementType, $siteId);
if (!$element) {
return false;
}
return $this->deleteElement($element);
}
/**
* Deletes an element.
*
* @param ElementInterface $element The element to be deleted
* @return bool Whether the element was deleted successfully
* @throws \Throwable
*/
public function deleteElement(ElementInterface $element): bool
{
/** @var Element $element */
// Fire a 'beforeDeleteElement' event
if ($this->hasEventHandlers(self::EVENT_BEFORE_DELETE_ELEMENT)) {
$this->trigger(self::EVENT_BEFORE_DELETE_ELEMENT, new ElementEvent([
'element' => $element,
]));
}
if (!$element->beforeDelete()) {
return false;
}
$transaction = Craft::$app->getDb()->beginTransaction();
try {
// First delete any structure nodes with this element, so NestedSetBehavior can do its thing.
/** @var StructureElementRecord[] $records */
$records = StructureElementRecord::findAll([
'elementId' => $element->id
]);
foreach ($records as $record) {
// If this element still has any children, move them up before the one getting deleted.
/** @var StructureElementRecord[] $children */
$children = $record->children()->all();
foreach ($children as $child) {
$child->insertBefore($record);
}
// Delete this element's node
$record->deleteWithChildren();
}
// Delete the caches before they drop their elementId relations (passing `false` because there's no chance
// this element is suddenly going to show up in a new query)
Craft::$app->getTemplateCaches()->deleteCachesByElementId($element->id, false);
// Delete the elements table rows, which will cascade across all other InnoDB tables
Craft::$app->getDb()->createCommand()
->delete('{{%elements}}', ['id' => $element->id])
->execute();
// The searchindex table is probably MyISAM, though
Craft::$app->getDb()->createCommand()
->delete('{{%searchindex}}', ['elementId' => $element->id])
->execute();
$element->afterDelete();
$transaction->commit();
} catch (\Throwable $e) {
$transaction->rollBack();
throw $e;
}
// Fire an 'afterDeleteElement' event
if ($this->hasEventHandlers(self::EVENT_AFTER_DELETE_ELEMENT)) {
$this->trigger(self::EVENT_AFTER_DELETE_ELEMENT, new ElementEvent([
'element' => $element,
]));
}
return true;
}