From 734eb3921fe71b4d90a9b7ac0fd321bb731bfec1 Mon Sep 17 00:00:00 2001 From: GuySartorelli <36352093+GuySartorelli@users.noreply.github.com> Date: Tue, 21 Sep 2021 17:09:48 +1200 Subject: [PATCH 1/2] FIX: Treat absolute links in a consistent manner in get_by_link. Fixes #2580 The call to `Director::makeRelative` transforms absolute links into relative links. Previously, this meant that you could pass in "https://example.co.nz/about-us" or "about-us" and get the same result, but passing in "https://example.co.nz/" and "/" would give _different_ results. This commit performs the transformation to a relative link _before_ checking if the path should be for the home page, which leads to more consistent results. --- code/Model/SiteTree.php | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/code/Model/SiteTree.php b/code/Model/SiteTree.php index d0be2288..4eae1034 100755 --- a/code/Model/SiteTree.php +++ b/code/Model/SiteTree.php @@ -415,9 +415,8 @@ class SiteTree extends DataObject implements PermissionProvider, i18nEntityProvi $urlSegmentExpr = sprintf('"%s"."URLSegment"', $tableName); $parentIDExpr = sprintf('"%s"."ParentID"', $tableName); - if (trim($link, '/')) { - $link = trim(Director::makeRelative($link), '/'); - } else { + $link = trim(Director::makeRelative($link), '/'); + if (!$link) { $link = RootURLController::get_homepage_link(); } From 1db69ee91ad8ed7a9c34a8e37b1d9338d1472dcb Mon Sep 17 00:00:00 2001 From: Guy Sartorelli Date: Mon, 15 Nov 2021 14:30:44 +1300 Subject: [PATCH 2/2] ENH: Add tests for absolute URLs in get_by_link --- tests/php/Model/SiteTreeTest.php | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/tests/php/Model/SiteTreeTest.php b/tests/php/Model/SiteTreeTest.php index aa37f24a..00a139ed 100644 --- a/tests/php/Model/SiteTreeTest.php +++ b/tests/php/Model/SiteTreeTest.php @@ -467,6 +467,21 @@ class SiteTreeTest extends SapphireTest ); } + public function testGetByLinkAbsolute() + { + $home = $this->objFromFixture('Page', 'home'); + $about = $this->objFromFixture('Page', 'about'); + $staff = $this->objFromFixture('Page', 'staff'); + $product = $this->objFromFixture('Page', 'product1'); + + $base = 'https://example.test/'; + $this->assertEquals($home->ID, SiteTree::get_by_link(Controller::join_links($base, '/'), false)->ID); + $this->assertEquals($home->ID, SiteTree::get_by_link(Controller::join_links($base, '/home/'), false)->ID); + $this->assertEquals($about->ID, SiteTree::get_by_link(Controller::join_links($base, $about->Link()), false)->ID); + $this->assertEquals($staff->ID, SiteTree::get_by_link(Controller::join_links($base, $staff->Link()), false)->ID); + $this->assertEquals($product->ID, SiteTree::get_by_link(Controller::join_links($base, $product->Link()), false)->ID); + } + public function testRelativeLink() { $about = $this->objFromFixture('Page', 'about');