PathAliasTest.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  1. <?php
  2. namespace Drupal\Tests\path\Functional;
  3. use Drupal\Core\Cache\Cache;
  4. use Drupal\Core\Database\Database;
  5. use Drupal\Core\Url;
  6. /**
  7. * Add, edit, delete, and change alias and verify its consistency in the
  8. * database.
  9. *
  10. * @group path
  11. */
  12. class PathAliasTest extends PathTestBase {
  13. /**
  14. * Modules to enable.
  15. *
  16. * @var array
  17. */
  18. public static $modules = ['path'];
  19. protected function setUp() {
  20. parent::setUp();
  21. // Create test user and log in.
  22. $web_user = $this->drupalCreateUser(['create page content', 'edit own page content', 'administer url aliases', 'create url aliases', 'access content overview']);
  23. $this->drupalLogin($web_user);
  24. }
  25. /**
  26. * Tests the path cache.
  27. */
  28. public function testPathCache() {
  29. // Create test node.
  30. $node1 = $this->drupalCreateNode();
  31. // Create alias.
  32. $edit = [];
  33. $edit['source'] = '/node/' . $node1->id();
  34. $edit['alias'] = '/' . $this->randomMachineName(8);
  35. $this->drupalPostForm('admin/config/search/path/add', $edit, t('Save'));
  36. // Check the path alias whitelist cache.
  37. $whitelist = \Drupal::cache('bootstrap')->get('path_alias_whitelist');
  38. $this->assertTrue($whitelist->data['node']);
  39. $this->assertFalse($whitelist->data['admin']);
  40. // Visit the system path for the node and confirm a cache entry is
  41. // created.
  42. \Drupal::cache('data')->deleteAll();
  43. // Make sure the path is not converted to the alias.
  44. $this->drupalGet(trim($edit['source'], '/'), ['alias' => TRUE]);
  45. $this->assertTrue(\Drupal::cache('data')->get('preload-paths:' . $edit['source']), 'Cache entry was created.');
  46. // Visit the alias for the node and confirm a cache entry is created.
  47. \Drupal::cache('data')->deleteAll();
  48. // @todo Remove this once https://www.drupal.org/node/2480077 lands.
  49. Cache::invalidateTags(['rendered']);
  50. $this->drupalGet(trim($edit['alias'], '/'));
  51. $this->assertTrue(\Drupal::cache('data')->get('preload-paths:' . $edit['source']), 'Cache entry was created.');
  52. }
  53. /**
  54. * Tests alias functionality through the admin interfaces.
  55. */
  56. public function testAdminAlias() {
  57. // Create test node.
  58. $node1 = $this->drupalCreateNode();
  59. // Create alias.
  60. $edit = [];
  61. $edit['source'] = '/node/' . $node1->id();
  62. $edit['alias'] = '/' . $this->getRandomGenerator()->word(8);
  63. $this->drupalPostForm('admin/config/search/path/add', $edit, t('Save'));
  64. // Confirm that the alias works.
  65. $this->drupalGet($edit['alias']);
  66. $this->assertText($node1->label(), 'Alias works.');
  67. $this->assertResponse(200);
  68. // Confirm that the alias works in a case-insensitive way.
  69. $this->assertTrue(ctype_lower(ltrim($edit['alias'], '/')));
  70. $this->drupalGet($edit['alias']);
  71. $this->assertText($node1->label(), 'Alias works lower case.');
  72. $this->assertResponse(200);
  73. $this->drupalGet(mb_strtoupper($edit['alias']));
  74. $this->assertText($node1->label(), 'Alias works upper case.');
  75. $this->assertResponse(200);
  76. // Change alias to one containing "exotic" characters.
  77. $pid = $this->getPID($edit['alias']);
  78. $previous = $edit['alias'];
  79. // Lower-case letters.
  80. $edit['alias'] = '/alias' .
  81. // "Special" ASCII characters.
  82. "- ._~!$'\"()*@[]?&+%#,;=:" .
  83. // Characters that look like a percent-escaped string.
  84. "%23%25%26%2B%2F%3F" .
  85. // Characters from various non-ASCII alphabets.
  86. "中國書۞";
  87. $connection = Database::getConnection();
  88. if ($connection->databaseType() != 'sqlite') {
  89. // When using LIKE for case-insensitivity, the SQLite driver is
  90. // currently unable to find the upper-case versions of non-ASCII
  91. // characters.
  92. // @todo fix this in https://www.drupal.org/node/2607432
  93. $edit['alias'] .= "ïвβéø";
  94. }
  95. $this->drupalPostForm('admin/config/search/path/edit/' . $pid, $edit, t('Save'));
  96. // Confirm that the alias works.
  97. $this->drupalGet(mb_strtoupper($edit['alias']));
  98. $this->assertText($node1->label(), 'Changed alias works.');
  99. $this->assertResponse(200);
  100. $this->container->get('path.alias_manager')->cacheClear();
  101. // Confirm that previous alias no longer works.
  102. $this->drupalGet($previous);
  103. $this->assertNoText($node1->label(), 'Previous alias no longer works.');
  104. $this->assertResponse(404);
  105. // Create second test node.
  106. $node2 = $this->drupalCreateNode();
  107. // Set alias to second test node.
  108. $edit['source'] = '/node/' . $node2->id();
  109. // leave $edit['alias'] the same
  110. $this->drupalPostForm('admin/config/search/path/add', $edit, t('Save'));
  111. // Confirm no duplicate was created.
  112. $this->assertRaw(t('The alias %alias is already in use in this language.', ['%alias' => $edit['alias']]), 'Attempt to move alias was rejected.');
  113. $edit_upper = $edit;
  114. $edit_upper['alias'] = mb_strtoupper($edit['alias']);
  115. $this->drupalPostForm('admin/config/search/path/add', $edit_upper, t('Save'));
  116. $this->assertRaw(t('The alias %alias could not be added because it is already in use in this language with different capitalization: %stored_alias.', [
  117. '%alias' => $edit_upper['alias'],
  118. '%stored_alias' => $edit['alias'],
  119. ]), 'Attempt to move upper-case alias was rejected.');
  120. // Delete alias.
  121. $this->drupalGet('admin/config/search/path/edit/' . $pid);
  122. $this->clickLink(t('Delete'));
  123. $this->assertRaw(t('Are you sure you want to delete path alias %name?', ['%name' => $edit['alias']]));
  124. $this->drupalPostForm(NULL, [], t('Confirm'));
  125. // Confirm that the alias no longer works.
  126. $this->drupalGet($edit['alias']);
  127. $this->assertNoText($node1->label(), 'Alias was successfully deleted.');
  128. $this->assertResponse(404);
  129. // Create a really long alias.
  130. $edit = [];
  131. $edit['source'] = '/node/' . $node1->id();
  132. $alias = '/' . $this->randomMachineName(128);
  133. $edit['alias'] = $alias;
  134. // The alias is shortened to 50 characters counting the ellipsis.
  135. $truncated_alias = substr($alias, 0, 47);
  136. $this->drupalPostForm('admin/config/search/path/add', $edit, t('Save'));
  137. $this->assertNoText($alias, 'The untruncated alias was not found.');
  138. // The 'truncated' alias will always be found.
  139. $this->assertText($truncated_alias, 'The truncated alias was found.');
  140. // Create third test node.
  141. $node3 = $this->drupalCreateNode();
  142. // Create absolute path alias.
  143. $edit = [];
  144. $edit['source'] = '/node/' . $node3->id();
  145. $node3_alias = '/' . $this->randomMachineName(8);
  146. $edit['alias'] = $node3_alias;
  147. $this->drupalPostForm('admin/config/search/path/add', $edit, t('Save'));
  148. // Create fourth test node.
  149. $node4 = $this->drupalCreateNode();
  150. // Create alias with trailing slash.
  151. $edit = [];
  152. $edit['source'] = '/node/' . $node4->id();
  153. $node4_alias = '/' . $this->randomMachineName(8);
  154. $edit['alias'] = $node4_alias . '/';
  155. $this->drupalPostForm('admin/config/search/path/add', $edit, t('Save'));
  156. // Confirm that the alias with trailing slash is not found.
  157. $this->assertNoText($edit['alias'], 'The absolute alias was not found.');
  158. // The alias without trailing flash is found.
  159. $this->assertText(trim($edit['alias'], '/'), 'The alias without trailing slash was found.');
  160. // Update an existing alias to point to a different source.
  161. $pid = $this->getPID($node4_alias);
  162. $edit = [];
  163. $edit['alias'] = $node4_alias;
  164. $edit['source'] = '/node/' . $node2->id();
  165. $this->drupalPostForm('admin/config/search/path/edit/' . $pid, $edit, t('Save'));
  166. $this->assertText('The alias has been saved.');
  167. $this->drupalGet($edit['alias']);
  168. $this->assertNoText($node4->label(), 'Previous alias no longer works.');
  169. $this->assertText($node2->label(), 'Alias works.');
  170. $this->assertResponse(200);
  171. // Update an existing alias to use a duplicate alias.
  172. $pid = $this->getPID($node3_alias);
  173. $edit = [];
  174. $edit['alias'] = $node4_alias;
  175. $edit['source'] = '/node/' . $node3->id();
  176. $this->drupalPostForm('admin/config/search/path/edit/' . $pid, $edit, t('Save'));
  177. $this->assertRaw(t('The alias %alias is already in use in this language.', ['%alias' => $edit['alias']]));
  178. // Create an alias without a starting slash.
  179. $node5 = $this->drupalCreateNode();
  180. $edit = [];
  181. $edit['source'] = 'node/' . $node5->id();
  182. $node5_alias = $this->randomMachineName(8);
  183. $edit['alias'] = $node5_alias . '/';
  184. $this->drupalPostForm('admin/config/search/path/add', $edit, t('Save'));
  185. $this->assertUrl('admin/config/search/path/add');
  186. $this->assertText('The source path has to start with a slash.');
  187. $this->assertText('The alias path has to start with a slash.');
  188. }
  189. /**
  190. * Tests alias functionality through the node interfaces.
  191. */
  192. public function testNodeAlias() {
  193. // Create test node.
  194. $node1 = $this->drupalCreateNode();
  195. // Create alias.
  196. $edit = [];
  197. $edit['path[0][alias]'] = '/' . $this->randomMachineName(8);
  198. $this->drupalPostForm('node/' . $node1->id() . '/edit', $edit, t('Save'));
  199. // Confirm that the alias works.
  200. $this->drupalGet($edit['path[0][alias]']);
  201. $this->assertText($node1->label(), 'Alias works.');
  202. $this->assertResponse(200);
  203. // Confirm the 'canonical' and 'shortlink' URLs.
  204. $elements = $this->xpath("//link[contains(@rel, 'canonical') and contains(@href, '" . $edit['path[0][alias]'] . "')]");
  205. $this->assertTrue(!empty($elements), 'Page contains canonical link URL.');
  206. $elements = $this->xpath("//link[contains(@rel, 'shortlink') and contains(@href, 'node/" . $node1->id() . "')]");
  207. $this->assertTrue(!empty($elements), 'Page contains shortlink URL.');
  208. $previous = $edit['path[0][alias]'];
  209. // Change alias to one containing "exotic" characters.
  210. // Lower-case letters.
  211. $edit['path[0][alias]'] = '/alias' .
  212. // "Special" ASCII characters.
  213. "- ._~!$'\"()*@[]?&+%#,;=:" .
  214. // Characters that look like a percent-escaped string.
  215. "%23%25%26%2B%2F%3F" .
  216. // Characters from various non-ASCII alphabets.
  217. "中國書۞";
  218. $connection = Database::getConnection();
  219. if ($connection->databaseType() != 'sqlite') {
  220. // When using LIKE for case-insensitivity, the SQLite driver is
  221. // currently unable to find the upper-case versions of non-ASCII
  222. // characters.
  223. // @todo fix this in https://www.drupal.org/node/2607432
  224. $edit['path[0][alias]'] .= "ïвβéø";
  225. }
  226. $this->drupalPostForm('node/' . $node1->id() . '/edit', $edit, t('Save'));
  227. // Confirm that the alias works.
  228. $this->drupalGet(mb_strtoupper($edit['path[0][alias]']));
  229. $this->assertText($node1->label(), 'Changed alias works.');
  230. $this->assertResponse(200);
  231. // Make sure that previous alias no longer works.
  232. $this->drupalGet($previous);
  233. $this->assertNoText($node1->label(), 'Previous alias no longer works.');
  234. $this->assertResponse(404);
  235. // Create second test node.
  236. $node2 = $this->drupalCreateNode();
  237. // Set alias to second test node.
  238. // Leave $edit['path[0][alias]'] the same.
  239. $this->drupalPostForm('node/' . $node2->id() . '/edit', $edit, t('Save'));
  240. // Confirm that the alias didn't make a duplicate.
  241. $this->assertText(t('The alias is already in use.'), 'Attempt to moved alias was rejected.');
  242. // Delete alias.
  243. $this->drupalPostForm('node/' . $node1->id() . '/edit', ['path[0][alias]' => ''], t('Save'));
  244. // Confirm that the alias no longer works.
  245. $this->drupalGet($edit['path[0][alias]']);
  246. $this->assertNoText($node1->label(), 'Alias was successfully deleted.');
  247. $this->assertResponse(404);
  248. // Create third test node.
  249. $node3 = $this->drupalCreateNode();
  250. // Set its path alias to an absolute path.
  251. $edit = ['path[0][alias]' => '/' . $this->randomMachineName(8)];
  252. $this->drupalPostForm('node/' . $node3->id() . '/edit', $edit, t('Save'));
  253. // Confirm that the alias was converted to a relative path.
  254. $this->drupalGet(trim($edit['path[0][alias]'], '/'));
  255. $this->assertText($node3->label(), 'Alias became relative.');
  256. $this->assertResponse(200);
  257. // Create fourth test node.
  258. $node4 = $this->drupalCreateNode();
  259. // Set its path alias to have a trailing slash.
  260. $edit = ['path[0][alias]' => '/' . $this->randomMachineName(8) . '/'];
  261. $this->drupalPostForm('node/' . $node4->id() . '/edit', $edit, t('Save'));
  262. // Confirm that the alias was converted to a relative path.
  263. $this->drupalGet(trim($edit['path[0][alias]'], '/'));
  264. $this->assertText($node4->label(), 'Alias trimmed trailing slash.');
  265. $this->assertResponse(200);
  266. // Create fifth test node.
  267. $node5 = $this->drupalCreateNode();
  268. // Set a path alias.
  269. $edit = ['path[0][alias]' => '/' . $this->randomMachineName(8)];
  270. $this->drupalPostForm('node/' . $node5->id() . '/edit', $edit, t('Save'));
  271. // Delete the node and check that the path alias is also deleted.
  272. $node5->delete();
  273. $path_alias = \Drupal::service('path.alias_storage')->lookupPathAlias('/node/' . $node5->id(), $node5->language()->getId());
  274. $this->assertFalse($path_alias, 'Alias was successfully deleted when the referenced node was deleted.');
  275. // Create sixth test node.
  276. $node6 = $this->drupalCreateNode();
  277. // Create an invalid alias with two leading slashes and verify that the
  278. // extra slash is removed when the link is generated. This ensures that URL
  279. // aliases cannot be used to inject external URLs.
  280. // @todo The user interface should either display an error message or
  281. // automatically trim these invalid aliases, rather than allowing them to
  282. // be silently created, at which point the functional aspects of this
  283. // test will need to be moved elsewhere and switch to using a
  284. // programmatically-created alias instead.
  285. $alias = $this->randomMachineName(8);
  286. $edit = ['path[0][alias]' => '//' . $alias];
  287. $this->drupalPostForm($node6->toUrl('edit-form'), $edit, t('Save'));
  288. $this->drupalGet(Url::fromRoute('system.admin_content'));
  289. // This checks the link href before clicking it, rather than using
  290. // \Drupal\Tests\BrowserTestBase::assertSession()->addressEquals() after
  291. // clicking it, because the test browser does not always preserve the
  292. // correct number of slashes in the URL when it visits internal links;
  293. // using \Drupal\Tests\BrowserTestBase::assertSession()->addressEquals()
  294. // would actually make the test pass unconditionally on the testbot (or
  295. // anywhere else where Drupal is installed in a subdirectory).
  296. $link_xpath = $this->xpath('//a[normalize-space(text())=:label]', [':label' => $node6->getTitle()]);
  297. $link_href = $link_xpath[0]->getAttribute('href');
  298. $this->assertEquals($link_href, base_path() . $alias);
  299. $this->clickLink($node6->getTitle());
  300. $this->assertResponse(404);
  301. }
  302. /**
  303. * Returns the path ID.
  304. *
  305. * @param string $alias
  306. * A string containing an aliased path.
  307. *
  308. * @return int
  309. * Integer representing the path ID.
  310. */
  311. public function getPID($alias) {
  312. return db_query("SELECT pid FROM {url_alias} WHERE alias = :alias", [':alias' => $alias])->fetchField();
  313. }
  314. /**
  315. * Tests that duplicate aliases fail validation.
  316. */
  317. public function testDuplicateNodeAlias() {
  318. // Create one node with a random alias.
  319. $node_one = $this->drupalCreateNode();
  320. $edit = [];
  321. $edit['path[0][alias]'] = '/' . $this->randomMachineName();
  322. $this->drupalPostForm('node/' . $node_one->id() . '/edit', $edit, t('Save'));
  323. // Now create another node and try to set the same alias.
  324. $node_two = $this->drupalCreateNode();
  325. $this->drupalPostForm('node/' . $node_two->id() . '/edit', $edit, t('Save'));
  326. $this->assertText(t('The alias is already in use.'));
  327. $this->assertFieldByXPath("//input[@name='path[0][alias]' and contains(@class, 'error')]", $edit['path[0][alias]'], 'Textfield exists and has the error class.');
  328. // Behavior here differs with the inline_form_errors module enabled.
  329. // Enable the inline_form_errors module and try this again. This module
  330. // improves validation with a link in the error message(s) to the fields
  331. // which have invalid input.
  332. $this->assertTrue($this->container->get('module_installer')->install(['inline_form_errors'], TRUE), 'Installed inline_form_errors.');
  333. // Attempt to edit the second node again, as before.
  334. $this->drupalPostForm('node/' . $node_two->id() . '/edit', $edit, t('Preview'));
  335. // This error should still be present next to the field.
  336. $this->assertSession()->pageTextContains(t('The alias is already in use.'), 'Field error found with expected text.');
  337. // The validation error set for the page should include this text.
  338. $this->assertSession()->pageTextContains(t('1 error has been found: URL alias'), 'Form error found with expected text.');
  339. // The text 'URL alias' should be a link.
  340. $this->assertSession()->linkExists('URL alias');
  341. // The link should be to the ID of the URL alias field.
  342. $this->assertSession()->linkByHrefExists('#edit-path-0-alias');
  343. }
  344. }