-
Notifications
You must be signed in to change notification settings - Fork 669
/
ElggEntity.php
1349 lines (1170 loc) · 36.7 KB
/
ElggEntity.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
use Elgg\Database\QueryBuilder;
use Elgg\Exceptions\DatabaseException;
use Elgg\Exceptions\Filesystem\IOException;
use Elgg\Exceptions\DomainException as ElggDomainException;
use Elgg\Exceptions\InvalidArgumentException as ElggInvalidArgumentException;
use Elgg\Traits\Entity\AccessCollections;
use Elgg\Traits\Entity\Annotations;
use Elgg\Traits\Entity\Icons;
use Elgg\Traits\Entity\Metadata;
use Elgg\Traits\Entity\Relationships;
use Elgg\Traits\Entity\Subscriptions;
/**
* The parent class for all Elgg Entities.
*
* An \ElggEntity is one of the basic data models in Elgg.
* It is the primary means of storing and retrieving data from the database.
* An \ElggEntity represents one row of the entities table.
*
* The \ElggEntity class handles CRUD operations for the entities table.
* \ElggEntity should always be extended by another class to handle CRUD
* operations on the type-specific table.
*
* \ElggEntity uses magic methods for get and set, so any property that isn't
* declared will be assumed to be metadata and written to the database
* as metadata on the object. All children classes must declare which
* properties are columns of the type table or they will be assumed
* to be metadata. See \ElggObject::initializeAttributes() for examples.
*
* Core supports 4 types of entities: \ElggObject, \ElggUser, \ElggGroup, and \ElggSite.
*
* @tip Plugin authors will want to extend the \ElggObject class, not this class.
*
* @property-read string $type object, user, group, or site (read-only after save)
* @property-read string $subtype Further clarifies the nature of the entity
* @property-read int $guid The unique identifier for this entity (read only)
* @property int $owner_guid The GUID of the owner of this entity (usually the creator)
* @property int $container_guid The GUID of the entity containing this entity
* @property int $access_id Specifies the visibility level of this entity
* @property int $time_created A UNIX timestamp of when the entity was created
* @property-read int $time_updated A UNIX timestamp of when the entity was last updated (automatically updated on save)
* @property-read int $last_action A UNIX timestamp of when the entity was last acted upon
* @property-read int $time_deleted A UNIX timestamp of when the entity was deleted
* @property-read string $deleted Is this entity deleted ('yes' or 'no')
* @property-read string $enabled Is this entity enabled ('yes' or 'no')
*
* Metadata (the above are attributes)
* @property string $location A location of the entity
*/
abstract class ElggEntity extends \ElggData {
use AccessCollections;
use Annotations;
use Icons;
use Metadata;
use Relationships;
use Subscriptions;
public const PRIMARY_ATTR_NAMES = [
'guid',
'type',
'subtype',
'owner_guid',
'container_guid',
'access_id',
'time_created',
'time_updated',
'last_action',
'enabled',
'deleted',
'time_deleted',
];
/**
* @var string[] attributes that are integers
*/
protected const INTEGER_ATTR_NAMES = [
'guid',
'owner_guid',
'container_guid',
'access_id',
'time_created',
'time_updated',
'last_action',
'time_deleted',
];
/**
* Volatile data structure for this object, allows for storage of data
* in-memory that isn't synced back to the metadata table.
* @var array
*/
protected $volatile = [];
/**
* Holds the original (persisted) attribute values that have been changed but not yet saved.
* @var array
*/
protected $orig_attributes = [];
/**
* @var bool
*/
protected $_is_cacheable = true;
/**
* Create a new entity.
*
* Plugin developers should only use the constructor to create a new entity.
* To retrieve entities, use get_entity() and the elgg_get_entities* functions.
*
* If no arguments are passed, it creates a new entity.
* If a database result is passed as a \stdClass instance, it instantiates
* that entity.
*
* @param stdClass $row Database row result. Default is null to create a new object.
*
* @throws IOException If cannot load remaining data from db
*/
public function __construct(stdClass $row = null) {
$this->initializeAttributes();
if (!empty($row) && !$this->load($row)) {
throw new IOException('Failed to load new ' . get_class() . " for GUID: {$row->guid}");
}
}
/**
* Initialize the attributes array.
*
* This is vital to distinguish between metadata and base parameters.
*
* @return void
*/
protected function initializeAttributes() {
parent::initializeAttributes();
$this->attributes['guid'] = null;
$this->attributes['type'] = null;
$this->attributes['subtype'] = null;
$this->attributes['owner_guid'] = _elgg_services()->session_manager->getLoggedInUserGuid();
$this->attributes['container_guid'] = _elgg_services()->session_manager->getLoggedInUserGuid();
$this->attributes['access_id'] = ACCESS_PRIVATE;
$this->attributes['time_updated'] = null;
$this->attributes['last_action'] = null;
$this->attributes['enabled'] = 'yes';
$this->attributes['deleted'] = 'no';
$this->attributes['time_deleted'] = null;
}
/**
* Clone an entity
*
* Resets the guid so that the entity can be saved as a distinct entity from
* the original. Creation time will be set when this new entity is saved.
* The owner and container guids come from the original entity. The clone
* method copies metadata but does not copy annotations.
*
* @return void
*/
public function __clone() {
$orig_entity = get_entity($this->guid);
if (!$orig_entity) {
_elgg_services()->logger->error("Failed to clone entity with GUID $this->guid");
return;
}
$metadata_array = elgg_get_metadata([
'guid' => $this->guid,
'limit' => false,
]);
$this->attributes['guid'] = null;
$this->attributes['time_created'] = null;
$this->attributes['time_updated'] = null;
$this->attributes['last_action'] = null;
$this->attributes['subtype'] = $orig_entity->getSubtype();
// copy metadata over to new entity - slightly convoluted due to
// handling of metadata arrays
if (is_array($metadata_array)) {
// create list of metadata names
$metadata_names = [];
foreach ($metadata_array as $metadata) {
$metadata_names[] = $metadata->name;
}
// arrays are stored with multiple entries per name
$metadata_names = array_unique($metadata_names);
// move the metadata over
foreach ($metadata_names as $name) {
$this->__set($name, $orig_entity->$name);
}
}
}
/**
* Set an attribute or metadata value for this entity
*
* Anything that is not an attribute is saved as metadata.
*
* Be advised that metadata values are cast to integer or string.
* You can save booleans, but they will be stored and returned as integers.
*
* @param string $name Name of the attribute or metadata
* @param mixed $value The value to be set
*
* @return void
* @throws \Elgg\Exceptions\InvalidArgumentException
* @see \ElggEntity::setMetadata()
*/
public function __set($name, $value) {
if ($this->$name === $value) {
// quick return if value is not changing
return;
}
if (array_key_exists($name, $this->attributes)) {
// if an attribute is 1 (integer) and it's set to "1" (string), don't consider that a change.
if (is_int($this->attributes[$name])
&& is_string($value)
&& ((string) $this->attributes[$name] === $value)) {
return;
}
// keep original values
if ($this->guid && !array_key_exists($name, $this->orig_attributes)) {
$this->orig_attributes[$name] = $this->attributes[$name];
}
// Certain properties should not be manually changed!
switch ($name) {
case 'guid':
case 'last_action':
case 'time_deleted':
case 'time_updated':
case 'type':
return;
case 'subtype':
throw new ElggInvalidArgumentException(elgg_echo('ElggEntity:Error:SetSubtype', ['setSubtype()']));
case 'enabled':
throw new ElggInvalidArgumentException(elgg_echo('ElggEntity:Error:SetEnabled', ['enable() / disable()']));
case 'deleted':
throw new ElggInvalidArgumentException(elgg_echo('ElggEntity:Error:SetDeleted', ['delete() / restore()']));
case 'access_id':
case 'owner_guid':
case 'container_guid':
if ($value !== null) {
$this->attributes[$name] = (int) $value;
} else {
$this->attributes[$name] = null;
}
break;
default:
$this->attributes[$name] = $value;
break;
}
return;
}
$this->setMetadata($name, $value);
}
/**
* Get the original values of attribute(s) that have been modified since the entity was persisted.
*
* @return array
*/
public function getOriginalAttributes(): array {
return $this->orig_attributes;
}
/**
* Get an attribute or metadata value
*
* If the name matches an attribute, the attribute is returned. If metadata
* does not exist with that name, a null is returned.
*
* This only returns an array if there are multiple values for a particular
* $name key.
*
* @param string $name Name of the attribute or metadata
*
* @return mixed
*/
public function __get($name) {
if (array_key_exists($name, $this->attributes)) {
return $this->attributes[$name];
}
return $this->getMetadata($name);
}
/**
* Get the entity's display name
*
* @return string The title or name of this entity.
*/
public function getDisplayName(): string {
return (string) $this->name;
}
/**
* Sets the title or name of this entity.
*
* @param string $display_name The title or name of this entity.
*
* @return void
*/
public function setDisplayName(string $display_name): void {
$this->name = $display_name;
}
/**
* Get a piece of volatile (non-persisted) data on this entity.
*
* @param string $name The name of the volatile data
*
* @return mixed The value or null if not found.
*/
public function getVolatileData(string $name) {
return array_key_exists($name, $this->volatile) ? $this->volatile[$name] : null;
}
/**
* Set a piece of volatile (non-persisted) data on this entity
*
* @param string $name Name
* @param mixed $value Value
*
* @return void
*/
public function setVolatileData(string $name, $value): void {
$this->volatile[$name] = $value;
}
/**
* Removes all river items related to this entity
*
* @return void
*/
public function removeAllRelatedRiverItems(): void {
elgg_delete_river(['subject_guid' => $this->guid, 'limit' => false]);
elgg_delete_river(['object_guid' => $this->guid, 'limit' => false]);
elgg_delete_river(['target_guid' => $this->guid, 'limit' => false]);
}
/**
* Count the number of comments attached to this entity.
*
* @return int Number of comments
* @since 1.8.0
*/
public function countComments(): int {
if (!$this->hasCapability('commentable')) {
return 0;
}
$params = ['entity' => $this];
$num = _elgg_services()->events->triggerResults('comments:count', $this->getType(), $params);
if (is_int($num)) {
return $num;
}
return \Elgg\Comments\DataService::instance()->getCommentsCount($this);
}
/**
* Check if the given user has access to this entity
*
* @param int $user_guid the GUID of the user to check access for (default: logged in user_guid)
*
* @return bool
* @since 4.3
*/
public function hasAccess(int $user_guid = 0): bool {
return _elgg_services()->accessCollections->hasAccessToEntity($this, $user_guid);
}
/**
* Can a user edit this entity?
*
* @tip Can be overridden by registering for the permissions_check event.
*
* @param int $user_guid The user GUID, optionally (default: logged in user)
*
* @return bool Whether this entity is editable by the given user.
*/
public function canEdit(int $user_guid = 0): bool {
return _elgg_services()->userCapabilities->canEdit($this, $user_guid);
}
/**
* Can a user delete this entity?
*
* @tip Can be overridden by registering for the permissions_check:delete event.
*
* @param int $user_guid The user GUID, optionally (default: logged in user)
*
* @return bool Whether this entity is deletable by the given user.
* @since 1.11
*/
public function canDelete(int $user_guid = 0): bool {
return _elgg_services()->userCapabilities->canDelete($this, $user_guid);
}
/**
* Can a user add an entity to this container
*
* @param int $user_guid The GUID of the user creating the entity (0 for logged in user).
* @param string $type The type of entity we're looking to write
* @param string $subtype The subtype of the entity we're looking to write
*
* @return bool
* @throws \Elgg\Exceptions\InvalidArgumentException
*/
public function canWriteToContainer(int $user_guid = 0, string $type = '', string $subtype = ''): bool {
if (empty($type) || empty($subtype)) {
throw new ElggInvalidArgumentException(__METHOD__ . ' requires $type and $subtype to be set');
}
return _elgg_services()->userCapabilities->canWriteToContainer($this, $type, $subtype, $user_guid);
}
/**
* Can a user comment on an entity?
*
* @tip Can be overridden by registering for the 'permissions_check:comment', '<entity type>' event.
*
* @param int $user_guid User guid (default is logged in user)
*
* @return bool
*/
public function canComment(int $user_guid = 0): bool {
return _elgg_services()->userCapabilities->canComment($this, $user_guid);
}
/**
* Can a user annotate an entity?
*
* @tip Can be overridden by registering for the event [permissions_check:annotate:<name>,
* <entity type>] or [permissions_check:annotate, <entity type>]. The events are called in that order.
*
* @tip If you want logged out users to annotate an object, do not call
* canAnnotate(). It's easier than using the event.
*
* @param int $user_guid User guid (default is logged in user)
* @param string $annotation_name The name of the annotation (default is unspecified)
*
* @return bool
*/
public function canAnnotate(int $user_guid = 0, string $annotation_name = ''): bool {
return _elgg_services()->userCapabilities->canAnnotate($this, $user_guid, $annotation_name);
}
/**
* Returns the guid.
*
* @return int|null GUID
*/
public function getGUID(): ?int {
return $this->guid;
}
/**
* Returns the entity type
*
* @return string The entity type
*/
public function getType(): string {
return (string) $this->attributes['type'];
}
/**
* Set the subtype of the entity
*
* @param string $subtype the new type
*
* @return void
* @see self::initializeAttributes()
*/
public function setSubtype(string $subtype): void {
// keep original values
if ($this->guid && !array_key_exists('subtype', $this->orig_attributes)) {
$this->orig_attributes['subtype'] = $this->attributes['subtype'];
}
$this->attributes['subtype'] = $subtype;
}
/**
* Get the entity subtype
*
* @return string The entity subtype
*/
public function getSubtype(): string {
return (string) $this->attributes['subtype'];
}
/**
* Get the guid of the entity's owner.
*
* @return int The owner GUID
*/
public function getOwnerGUID(): int {
return (int) $this->owner_guid;
}
/**
* Gets the \ElggEntity that owns this entity.
*
* @return \ElggEntity|null
*/
public function getOwnerEntity(): ?\ElggEntity {
return $this->owner_guid ? get_entity($this->owner_guid) : null;
}
/**
* Set the container for this object.
*
* @param int $container_guid The ID of the container.
*
* @return void
*/
public function setContainerGUID(int $container_guid): void {
$this->container_guid = $container_guid;
}
/**
* Gets the container GUID for this entity.
*
* @return int
*/
public function getContainerGUID(): int {
return (int) $this->container_guid;
}
/**
* Get the container entity for this object.
*
* @return \ElggEntity|null
* @since 1.8.0
*/
public function getContainerEntity(): ?\ElggEntity {
return $this->container_guid ? get_entity($this->getContainerGUID()) : null;
}
/**
* Returns the UNIX epoch time that this entity was last updated
*
* @return int UNIX epoch time
*/
public function getTimeUpdated(): int {
return (int) $this->time_updated;
}
/**
* Gets the URL for this entity.
*
* Plugins can register for the 'entity:url', '<type>' event to
* customize the url for an entity.
*
* @return string The URL of the entity
*/
public function getURL(): string {
$url = elgg_generate_entity_url($this, 'view');
$url = _elgg_services()->events->triggerResults('entity:url', "{$this->getType()}:{$this->getSubtype()}", ['entity' => $this], $url);
$url = _elgg_services()->events->triggerResults('entity:url', $this->getType(), ['entity' => $this], $url);
if (empty($url)) {
return '';
}
return elgg_normalize_url($url);
}
/**
* {@inheritDoc}
*/
public function save(): bool {
if ($this->guid > 0) {
$result = $this->update();
} else {
$result = $this->create() !== false;
}
if ($result) {
$this->cache();
}
return $result;
}
/**
* Create a new entry in the entities table.
*
* Saves the base information in the entities table for the entity. Saving
* the type-specific information is handled in the calling class method.
*
* @return int|false The new entity's GUID or false if prevented by an event handler
*
* @throws \Elgg\Exceptions\DomainException If the entity's type has not been set.
* @throws \Elgg\Exceptions\InvalidArgumentException If the entity's subtype has not been set, access_id is invalid or something is wrong with the owner or container
* @throws \Elgg\Exceptions\Filesystem\IOException If the new row fails to write to the DB.
*/
protected function create() {
$type = $this->attributes['type'];
if (!in_array($type, \Elgg\Config::ENTITY_TYPES)) {
throw new ElggDomainException('Entity type must be one of the allowed types: ' . implode(', ', \Elgg\Config::ENTITY_TYPES));
}
$subtype = $this->attributes['subtype'];
if (!$subtype) {
throw new ElggInvalidArgumentException('All entities must have a subtype');
}
$owner_guid = (int) $this->attributes['owner_guid'];
$access_id = (int) $this->attributes['access_id'];
$now = $this->getCurrentTime()->getTimestamp();
$time_created = isset($this->attributes['time_created']) ? (int) $this->attributes['time_created'] : $now;
$deleted = $this->attributes['deleted'];
$time_deleted = (int) $this->attributes['time_deleted'];
$container_guid = $this->attributes['container_guid'];
if ($container_guid == 0) {
$container_guid = $owner_guid;
$this->attributes['container_guid'] = $container_guid;
}
$container_guid = (int) $container_guid;
if ($access_id === ACCESS_DEFAULT) {
throw new ElggInvalidArgumentException('ACCESS_DEFAULT is not a valid access level. See its documentation in constants.php');
}
if ($access_id === ACCESS_FRIENDS) {
throw new ElggInvalidArgumentException('ACCESS_FRIENDS is not a valid access level. See its documentation in constants.php');
}
$user_guid = _elgg_services()->session_manager->getLoggedInUserGuid();
// If given an owner, verify it can be loaded
if (!empty($owner_guid)) {
$owner = $this->getOwnerEntity();
if (!$owner instanceof \ElggEntity) {
$error = "User {$user_guid} tried to create a ({$type}, {$subtype}),";
$error .= " but the given owner {$owner_guid} could not be loaded.";
throw new ElggInvalidArgumentException($error);
}
// If different owner than logged in, verify can write to container.
if ($user_guid !== $owner_guid && !$owner->canEdit() && !$owner->canWriteToContainer($user_guid, $type, $subtype)) {
$error = "User {$user_guid} tried to create a ({$type}, {$subtype}) with owner {$owner_guid},";
$error .= " but the user wasn't permitted to write to the owner's container.";
throw new ElggInvalidArgumentException($error);
}
}
// If given a container, verify it can be loaded and that the current user can write to it
if (!empty($container_guid)) {
$container = $this->getContainerEntity();
if (!$container instanceof \ElggEntity) {
$error = "User {$user_guid} tried to create a ({$type}, {$subtype}),";
$error .= " but the given container {$container_guid} could not be loaded.";
throw new ElggInvalidArgumentException($error);
}
if (!$container->canWriteToContainer($user_guid, $type, $subtype)) {
$error = "User {$user_guid} tried to create a ({$type}, {$subtype}),";
$error .= " but was not permitted to write to container {$container_guid}.";
throw new ElggInvalidArgumentException($error);
}
}
if (!_elgg_services()->events->triggerBefore('create', $this->type, $this)) {
return false;
}
// Create primary table row
$guid = _elgg_services()->entityTable->insertRow((object) [
'type' => $type,
'subtype' => $subtype,
'owner_guid' => $owner_guid,
'container_guid' => $container_guid,
'access_id' => $access_id,
'time_created' => $time_created,
'time_updated' => $now,
'last_action' => $now,
'deleted' => $deleted,
'time_deleted' => $time_deleted
], $this->attributes);
if (!$guid) {
throw new IOException("Unable to save new object's base entity information!");
}
$this->attributes['subtype'] = $subtype;
$this->attributes['guid'] = (int) $guid;
$this->attributes['time_created'] = (int) $time_created;
$this->attributes['time_updated'] = (int) $now;
$this->attributes['last_action'] = (int) $now;
$this->attributes['container_guid'] = (int) $container_guid;
$this->attributes['deleted'] = $deleted;
$this->attributes['time_deleted'] = (int) $time_deleted;
// We are writing this new entity to cache to make sure subsequent calls
// to get_entity() load the entity from cache and not from the DB. This
// MUST come before the metadata and annotation writes below!
$this->cache();
// Save any unsaved metadata
if (count($this->temp_metadata) > 0) {
foreach ($this->temp_metadata as $name => $value) {
// temp metadata is always an array, but if there is only one value return just the value
$this->setMetadata($name, $value, '', count($value) > 1);
}
$this->temp_metadata = [];
}
// Save any unsaved annotations.
if (count($this->temp_annotations) > 0) {
foreach ($this->temp_annotations as $name => $value) {
$this->annotate($name, $value);
}
$this->temp_annotations = [];
}
if (isset($container) && !$container instanceof \ElggUser) {
// users have their own logic for setting last action
$container->updateLastAction();
}
// for BC reasons this event is still needed (for example for notifications)
_elgg_services()->events->trigger('create', $this->type, $this);
_elgg_services()->events->triggerAfter('create', $this->type, $this);
return $guid;
}
/**
* Update the entity in the database.
*
* @return bool Whether the update was successful.
*
* @throws \Elgg\Exceptions\InvalidArgumentException
*/
protected function update(): bool {
if (!$this->canEdit()) {
return false;
}
// give old update event a chance to stop the update
if (!_elgg_services()->events->trigger('update', $this->type, $this)) {
return false;
}
$this->invalidateCache();
// See #6225. We copy these after the update event in case a handler changed one of them.
$guid = (int) $this->guid;
$owner_guid = (int) $this->owner_guid;
$access_id = (int) $this->access_id;
$container_guid = (int) $this->container_guid;
$time_created = (int) $this->time_created;
$time = $this->getCurrentTime()->getTimestamp();
$deleted = $this->deleted;
$time_deleted = (int) $this->time_deleted;
if ($access_id == ACCESS_DEFAULT) {
throw new ElggInvalidArgumentException('ACCESS_DEFAULT is not a valid access level. See its documentation in constants.php');
}
if ($access_id == ACCESS_FRIENDS) {
throw new ElggInvalidArgumentException('ACCESS_FRIENDS is not a valid access level. See its documentation in constants.php');
}
// Update primary table
$ret = _elgg_services()->entityTable->updateRow($guid, (object) [
'owner_guid' => $owner_guid,
'container_guid' => $container_guid,
'access_id' => $access_id,
'time_created' => $time_created,
'time_updated' => $time,
'guid' => $guid,
'deleted' => $deleted,
'time_deleted' => $time_deleted
]);
if ($ret === false) {
return false;
}
$this->attributes['time_updated'] = $time;
_elgg_services()->events->triggerAfter('update', $this->type, $this);
$this->orig_attributes = [];
$this->cache();
// Handle cases where there was no error BUT no rows were updated!
return true;
}
/**
* Loads attributes from the entities table into the object.
*
* @param stdClass $row Object of properties from database row(s)
*
* @return bool
*/
protected function load(stdClass $row): bool {
$attributes = array_merge($this->attributes, (array) $row);
if (array_diff(self::PRIMARY_ATTR_NAMES, array_keys($attributes)) !== []) {
// Some primary attributes are missing
return false;
}
foreach ($attributes as $name => $value) {
if (!in_array($name, self::PRIMARY_ATTR_NAMES)) {
$this->setVolatileData("select:{$name}", $value);
unset($attributes[$name]);
continue;
}
if (in_array($name, static::INTEGER_ATTR_NAMES)) {
$attributes[$name] = (int) $value;
}
}
$this->attributes = $attributes;
$this->cache();
return true;
}
/**
* Disable this entity.
*
* Disabled entities are not returned by getter functions.
* To enable an entity, use {@link \ElggEntity::enable()}.
*
* Recursively disabling an entity will disable all entities
* owned or contained by the parent entity.
*
* @note Internal: Disabling an entity sets the 'enabled' column to 'no'.
*
* @param string $reason Optional reason
* @param bool $recursive Recursively disable all contained entities?
*
* @return bool
* @see \ElggEntity::enable()
*/
public function disable(string $reason = '', bool $recursive = true): bool {
if (!$this->guid) {
return false;
}
if (!_elgg_services()->events->trigger('disable', $this->type, $this)) {
return false;
}
if (!$this->canEdit()) {
return false;
}
if ($this instanceof ElggUser && !$this->isBanned()) {
// temporarily ban to prevent using the site during disable
// not using ban function to bypass events
$this->setMetadata('banned', 'yes');
$unban_after = true;
} else {
$unban_after = false;
}
if (!empty($reason)) {
$this->disable_reason = $reason;
}
$guid = (int) $this->guid;
if ($recursive) {
elgg_call(ELGG_IGNORE_ACCESS | ELGG_HIDE_DISABLED_ENTITIES | ELGG_SHOW_DELETED_ENTITIES, function () use ($guid, $reason) {
$base_options = [
'wheres' => [
function(QueryBuilder $qb, $main_alias) use ($guid) {
return $qb->compare("{$main_alias}.guid", '!=', $guid, ELGG_VALUE_GUID);
},
],
'limit' => false,
'batch' => true,
'batch_inc_offset' => false,
];
foreach (['owner_guid', 'container_guid'] as $db_column) {
$options = $base_options;
$options[$db_column] = $guid;
$subentities = elgg_get_entities($options);
/* @var $subentity \ElggEntity */
foreach ($subentities as $subentity) {
if (!$subentity->isEnabled()) {
continue;
}
$subentity->addRelationship($guid, 'disabled_with');
$subentity->disable($reason, true);
}
}
});
}
$disabled = _elgg_services()->entityTable->disable($this);
if ($unban_after) {
$this->setMetadata('banned', 'no');
}
if ($disabled) {
$this->invalidateCache();
$this->attributes['enabled'] = 'no';
_elgg_services()->events->triggerAfter('disable', $this->type, $this);
}
return $disabled;
}
/**
* Enable the entity
*
* @param bool $recursive Recursively enable all entities disabled with the entity?
*
* @return bool
*/
public function enable(bool $recursive = true): bool {
if (empty($this->guid)) {
return false;
}
if (!_elgg_services()->events->trigger('enable', $this->type, $this)) {
return false;
}
if (!$this->canEdit()) {
return false;
}
$result = elgg_call(ELGG_IGNORE_ACCESS | ELGG_SHOW_DISABLED_ENTITIES | ELGG_SHOW_DELETED_ENTITIES, function() use ($recursive) {
$result = _elgg_services()->entityTable->enable($this);
$this->deleteMetadata('disable_reason');
if ($recursive) {
$disabled_with_it = elgg_get_entities([
'relationship' => 'disabled_with',
'relationship_guid' => $this->guid,
'inverse_relationship' => true,
'limit' => false,
'batch' => true,
'batch_inc_offset' => false,
]);
foreach ($disabled_with_it as $e) {
$e->enable($recursive);
$e->removeRelationship($this->guid, 'disabled_with');
}
}
return $result;
});
if ($result) {
$this->attributes['enabled'] = 'yes';
_elgg_services()->events->triggerAfter('enable', $this->type, $this);
}
return $result;
}
/**
* Is this entity enabled?
*
* @return boolean Whether this entity is enabled.
*/
public function isEnabled(): bool {