Skip to content

Commit

Permalink
fix(db): check for entity existence during relationship creation
Browse files Browse the repository at this point in the history
fixes #12059
  • Loading branch information
jeabakker committed Jan 13, 2021
1 parent 549ee02 commit d23e735
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 4 deletions.
9 changes: 7 additions & 2 deletions engine/classes/Elgg/Database/RelationshipsTable.php
Expand Up @@ -117,8 +117,7 @@ public function delete($id, $call_event = true) {
*/
public function add($guid_one, $relationship, $guid_two, $return_id = false) {
if (strlen($relationship) > \ElggRelationship::RELATIONSHIP_LIMIT) {
$msg = "relationship name cannot be longer than " . \ElggRelationship::RELATIONSHIP_LIMIT;
throw new InvalidArgumentException($msg);
throw new InvalidArgumentException('Relationship name cannot be longer than ' . \ElggRelationship::RELATIONSHIP_LIMIT);
}

// Check for duplicates
Expand All @@ -127,6 +126,12 @@ public function add($guid_one, $relationship, $guid_two, $return_id = false) {
return false;
}

// Check if the related entities exist
if (!$this->entities->exists($guid_one) || !$this->entities->exists($guid_two)) {
// one or both of the guids doesn't exist
return false;
}

$insert = Insert::intoTable('entity_relationships');
$insert->values([
'guid_one' => $insert->param($guid_one, ELGG_VALUE_GUID),
Expand Down
11 changes: 9 additions & 2 deletions engine/tests/classes/Elgg/Mocks/Database/RelationshipsTable.php
Expand Up @@ -39,8 +39,15 @@ class RelationshipsTable extends DbRelationshipsTable {
* {@inheritdoc}
*/
public function add($guid_one, $relationship, $guid_two, $return_id = false) {
$rel = $this->check($guid_one, $relationship, $guid_two);
if ($rel) {
// Check for duplicates
// note: escape $relationship after this call, we don't want to double-escape
if ($this->check($guid_one, $relationship, $guid_two)) {
return false;
}

// Check if the related entities exist
if (!$this->entities->exists($guid_one) || !$this->entities->exists($guid_two)) {
// one or both of the guids doesn't exist
return false;
}

Expand Down
Expand Up @@ -80,6 +80,23 @@ public function testAddDuplicateRelationshipFailure() {
$object2->delete();
}

public function testAddNonExistingEntityRelationshipFailure() {
$object1 = $this->createObject();
$object2 = $this->createObject();

$failure = $this->service->add($object1->guid, 'testRelationship', 123456789);
$this->assertFalse($failure);

$failure = $this->service->add(123456789, 'testRelationship', $object2->guid);
$this->assertFalse($failure);

$failure = $this->service->add(123456789, 'testRelationship', 987654321);
$this->assertFalse($failure);

$object1->delete();
$object2->delete();
}

public function testAddRelationshipPreventByEvent() {

elgg()->events->backup();
Expand Down

0 comments on commit d23e735

Please sign in to comment.