AliasStorage.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  1. <?php
  2. namespace Drupal\Core\Path;
  3. use Drupal\Core\Cache\Cache;
  4. use Drupal\Core\Database\Connection;
  5. use Drupal\Core\Database\SchemaObjectExistsException;
  6. use Drupal\Core\Extension\ModuleHandlerInterface;
  7. use Drupal\Core\Language\LanguageInterface;
  8. use Drupal\Core\Database\Query\Condition;
  9. /**
  10. * Provides a class for CRUD operations on path aliases.
  11. *
  12. * All queries perform case-insensitive matching on the 'source' and 'alias'
  13. * fields, so the aliases '/test-alias' and '/test-Alias' are considered to be
  14. * the same, and will both refer to the same internal system path.
  15. */
  16. class AliasStorage implements AliasStorageInterface {
  17. /**
  18. * The table for the url_alias storage.
  19. */
  20. const TABLE = 'url_alias';
  21. /**
  22. * The database connection.
  23. *
  24. * @var \Drupal\Core\Database\Connection
  25. */
  26. protected $connection;
  27. /**
  28. * The module handler.
  29. *
  30. * @var \Drupal\Core\Extension\ModuleHandlerInterface
  31. */
  32. protected $moduleHandler;
  33. /**
  34. * Constructs a Path CRUD object.
  35. *
  36. * @param \Drupal\Core\Database\Connection $connection
  37. * A database connection for reading and writing path aliases.
  38. * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
  39. * The module handler.
  40. */
  41. public function __construct(Connection $connection, ModuleHandlerInterface $module_handler) {
  42. $this->connection = $connection;
  43. $this->moduleHandler = $module_handler;
  44. }
  45. /**
  46. * {@inheritdoc}
  47. */
  48. public function save($source, $alias, $langcode = LanguageInterface::LANGCODE_NOT_SPECIFIED, $pid = NULL) {
  49. if ($source[0] !== '/') {
  50. throw new \InvalidArgumentException(sprintf('Source path %s has to start with a slash.', $source));
  51. }
  52. if ($alias[0] !== '/') {
  53. throw new \InvalidArgumentException(sprintf('Alias path %s has to start with a slash.', $alias));
  54. }
  55. $fields = [
  56. 'source' => $source,
  57. 'alias' => $alias,
  58. 'langcode' => $langcode,
  59. ];
  60. // Insert or update the alias.
  61. if (empty($pid)) {
  62. $try_again = FALSE;
  63. try {
  64. $query = $this->connection->insert(static::TABLE)
  65. ->fields($fields);
  66. $pid = $query->execute();
  67. }
  68. catch (\Exception $e) {
  69. // If there was an exception, try to create the table.
  70. if (!$try_again = $this->ensureTableExists()) {
  71. // If the exception happened for other reason than the missing table,
  72. // propagate the exception.
  73. throw $e;
  74. }
  75. }
  76. // Now that the table has been created, try again if necessary.
  77. if ($try_again) {
  78. $query = $this->connection->insert(static::TABLE)
  79. ->fields($fields);
  80. $pid = $query->execute();
  81. }
  82. $fields['pid'] = $pid;
  83. $operation = 'insert';
  84. }
  85. else {
  86. // Fetch the current values so that an update hook can identify what
  87. // exactly changed.
  88. try {
  89. $original = $this->connection->query('SELECT source, alias, langcode FROM {url_alias} WHERE pid = :pid', [':pid' => $pid])
  90. ->fetchAssoc();
  91. }
  92. catch (\Exception $e) {
  93. $this->catchException($e);
  94. $original = FALSE;
  95. }
  96. $fields['pid'] = $pid;
  97. $query = $this->connection->update(static::TABLE)
  98. ->fields($fields)
  99. ->condition('pid', $pid);
  100. $pid = $query->execute();
  101. $fields['original'] = $original;
  102. $operation = 'update';
  103. }
  104. if ($pid) {
  105. // @todo Switch to using an event for this instead of a hook.
  106. $this->moduleHandler->invokeAll('path_' . $operation, [$fields]);
  107. Cache::invalidateTags(['route_match']);
  108. return $fields;
  109. }
  110. return FALSE;
  111. }
  112. /**
  113. * {@inheritdoc}
  114. */
  115. public function load($conditions) {
  116. $select = $this->connection->select(static::TABLE);
  117. foreach ($conditions as $field => $value) {
  118. if ($field == 'source' || $field == 'alias') {
  119. // Use LIKE for case-insensitive matching.
  120. $select->condition($field, $this->connection->escapeLike($value), 'LIKE');
  121. }
  122. else {
  123. $select->condition($field, $value);
  124. }
  125. }
  126. try {
  127. return $select
  128. ->fields(static::TABLE)
  129. ->orderBy('pid', 'DESC')
  130. ->range(0, 1)
  131. ->execute()
  132. ->fetchAssoc();
  133. }
  134. catch (\Exception $e) {
  135. $this->catchException($e);
  136. return FALSE;
  137. }
  138. }
  139. /**
  140. * {@inheritdoc}
  141. */
  142. public function delete($conditions) {
  143. $path = $this->load($conditions);
  144. $query = $this->connection->delete(static::TABLE);
  145. foreach ($conditions as $field => $value) {
  146. if ($field == 'source' || $field == 'alias') {
  147. // Use LIKE for case-insensitive matching.
  148. $query->condition($field, $this->connection->escapeLike($value), 'LIKE');
  149. }
  150. else {
  151. $query->condition($field, $value);
  152. }
  153. }
  154. try {
  155. $deleted = $query->execute();
  156. }
  157. catch (\Exception $e) {
  158. $this->catchException($e);
  159. $deleted = FALSE;
  160. }
  161. // @todo Switch to using an event for this instead of a hook.
  162. $this->moduleHandler->invokeAll('path_delete', [$path]);
  163. Cache::invalidateTags(['route_match']);
  164. return $deleted;
  165. }
  166. /**
  167. * {@inheritdoc}
  168. */
  169. public function preloadPathAlias($preloaded, $langcode) {
  170. $langcode_list = [$langcode, LanguageInterface::LANGCODE_NOT_SPECIFIED];
  171. $select = $this->connection->select(static::TABLE)
  172. ->fields(static::TABLE, ['source', 'alias']);
  173. if (!empty($preloaded)) {
  174. $conditions = new Condition('OR');
  175. foreach ($preloaded as $preloaded_item) {
  176. $conditions->condition('source', $this->connection->escapeLike($preloaded_item), 'LIKE');
  177. }
  178. $select->condition($conditions);
  179. }
  180. // Always get the language-specific alias before the language-neutral one.
  181. // For example 'de' is less than 'und' so the order needs to be ASC, while
  182. // 'xx-lolspeak' is more than 'und' so the order needs to be DESC. We also
  183. // order by pid ASC so that fetchAllKeyed() returns the most recently
  184. // created alias for each source. Subsequent queries using fetchField() must
  185. // use pid DESC to have the same effect.
  186. if ($langcode == LanguageInterface::LANGCODE_NOT_SPECIFIED) {
  187. array_pop($langcode_list);
  188. }
  189. elseif ($langcode < LanguageInterface::LANGCODE_NOT_SPECIFIED) {
  190. $select->orderBy('langcode', 'ASC');
  191. }
  192. else {
  193. $select->orderBy('langcode', 'DESC');
  194. }
  195. $select->orderBy('pid', 'ASC');
  196. $select->condition('langcode', $langcode_list, 'IN');
  197. try {
  198. return $select->execute()->fetchAllKeyed();
  199. }
  200. catch (\Exception $e) {
  201. $this->catchException($e);
  202. return FALSE;
  203. }
  204. }
  205. /**
  206. * {@inheritdoc}
  207. */
  208. public function lookupPathAlias($path, $langcode) {
  209. $source = $this->connection->escapeLike($path);
  210. $langcode_list = [$langcode, LanguageInterface::LANGCODE_NOT_SPECIFIED];
  211. // See the queries above. Use LIKE for case-insensitive matching.
  212. $select = $this->connection->select(static::TABLE)
  213. ->fields(static::TABLE, ['alias'])
  214. ->condition('source', $source, 'LIKE');
  215. if ($langcode == LanguageInterface::LANGCODE_NOT_SPECIFIED) {
  216. array_pop($langcode_list);
  217. }
  218. elseif ($langcode > LanguageInterface::LANGCODE_NOT_SPECIFIED) {
  219. $select->orderBy('langcode', 'DESC');
  220. }
  221. else {
  222. $select->orderBy('langcode', 'ASC');
  223. }
  224. $select->orderBy('pid', 'DESC');
  225. $select->condition('langcode', $langcode_list, 'IN');
  226. try {
  227. return $select->execute()->fetchField();
  228. }
  229. catch (\Exception $e) {
  230. $this->catchException($e);
  231. return FALSE;
  232. }
  233. }
  234. /**
  235. * {@inheritdoc}
  236. */
  237. public function lookupPathSource($path, $langcode) {
  238. $alias = $this->connection->escapeLike($path);
  239. $langcode_list = [$langcode, LanguageInterface::LANGCODE_NOT_SPECIFIED];
  240. // See the queries above. Use LIKE for case-insensitive matching.
  241. $select = $this->connection->select(static::TABLE)
  242. ->fields(static::TABLE, ['source'])
  243. ->condition('alias', $alias, 'LIKE');
  244. if ($langcode == LanguageInterface::LANGCODE_NOT_SPECIFIED) {
  245. array_pop($langcode_list);
  246. }
  247. elseif ($langcode > LanguageInterface::LANGCODE_NOT_SPECIFIED) {
  248. $select->orderBy('langcode', 'DESC');
  249. }
  250. else {
  251. $select->orderBy('langcode', 'ASC');
  252. }
  253. $select->orderBy('pid', 'DESC');
  254. $select->condition('langcode', $langcode_list, 'IN');
  255. try {
  256. return $select->execute()->fetchField();
  257. }
  258. catch (\Exception $e) {
  259. $this->catchException($e);
  260. return FALSE;
  261. }
  262. }
  263. /**
  264. * {@inheritdoc}
  265. */
  266. public function aliasExists($alias, $langcode, $source = NULL) {
  267. // Use LIKE and NOT LIKE for case-insensitive matching.
  268. $query = $this->connection->select(static::TABLE)
  269. ->condition('alias', $this->connection->escapeLike($alias), 'LIKE')
  270. ->condition('langcode', $langcode);
  271. if (!empty($source)) {
  272. $query->condition('source', $this->connection->escapeLike($source), 'NOT LIKE');
  273. }
  274. $query->addExpression('1');
  275. $query->range(0, 1);
  276. try {
  277. return (bool) $query->execute()->fetchField();
  278. }
  279. catch (\Exception $e) {
  280. $this->catchException($e);
  281. return FALSE;
  282. }
  283. }
  284. /**
  285. * {@inheritdoc}
  286. */
  287. public function languageAliasExists() {
  288. try {
  289. return (bool) $this->connection->queryRange('SELECT 1 FROM {url_alias} WHERE langcode <> :langcode', 0, 1, [':langcode' => LanguageInterface::LANGCODE_NOT_SPECIFIED])->fetchField();
  290. }
  291. catch (\Exception $e) {
  292. $this->catchException($e);
  293. return FALSE;
  294. }
  295. }
  296. /**
  297. * {@inheritdoc}
  298. */
  299. public function getAliasesForAdminListing($header, $keys = NULL) {
  300. $query = $this->connection->select(static::TABLE)
  301. ->extend('Drupal\Core\Database\Query\PagerSelectExtender')
  302. ->extend('Drupal\Core\Database\Query\TableSortExtender');
  303. if ($keys) {
  304. // Replace wildcards with PDO wildcards.
  305. $query->condition('alias', '%' . preg_replace('!\*+!', '%', $keys) . '%', 'LIKE');
  306. }
  307. try {
  308. return $query
  309. ->fields(static::TABLE)
  310. ->orderByHeader($header)
  311. ->limit(50)
  312. ->execute()
  313. ->fetchAll();
  314. }
  315. catch (\Exception $e) {
  316. $this->catchException($e);
  317. return [];
  318. }
  319. }
  320. /**
  321. * {@inheritdoc}
  322. */
  323. public function pathHasMatchingAlias($initial_substring) {
  324. $query = $this->connection->select(static::TABLE, 'u');
  325. $query->addExpression(1);
  326. try {
  327. return (bool) $query
  328. ->condition('u.source', $this->connection->escapeLike($initial_substring) . '%', 'LIKE')
  329. ->range(0, 1)
  330. ->execute()
  331. ->fetchField();
  332. }
  333. catch (\Exception $e) {
  334. $this->catchException($e);
  335. return FALSE;
  336. }
  337. }
  338. /**
  339. * Check if the table exists and create it if not.
  340. */
  341. protected function ensureTableExists() {
  342. try {
  343. $database_schema = $this->connection->schema();
  344. if (!$database_schema->tableExists(static::TABLE)) {
  345. $schema_definition = $this->schemaDefinition();
  346. $database_schema->createTable(static::TABLE, $schema_definition);
  347. return TRUE;
  348. }
  349. }
  350. // If another process has already created the table, attempting to recreate
  351. // it will throw an exception. In this case just catch the exception and do
  352. // nothing.
  353. catch (SchemaObjectExistsException $e) {
  354. return TRUE;
  355. }
  356. return FALSE;
  357. }
  358. /**
  359. * Act on an exception when url_alias might be stale.
  360. *
  361. * If the table does not yet exist, that's fine, but if the table exists and
  362. * yet the query failed, then the url_alias is stale and the exception needs
  363. * to propagate.
  364. *
  365. * @param $e
  366. * The exception.
  367. *
  368. * @throws \Exception
  369. */
  370. protected function catchException(\Exception $e) {
  371. if ($this->connection->schema()->tableExists(static::TABLE)) {
  372. throw $e;
  373. }
  374. }
  375. /**
  376. * Defines the schema for the {url_alias} table.
  377. *
  378. * @internal
  379. */
  380. public static function schemaDefinition() {
  381. return [
  382. 'description' => 'A list of URL aliases for Drupal paths; a user may visit either the source or destination path.',
  383. 'fields' => [
  384. 'pid' => [
  385. 'description' => 'A unique path alias identifier.',
  386. 'type' => 'serial',
  387. 'unsigned' => TRUE,
  388. 'not null' => TRUE,
  389. ],
  390. 'source' => [
  391. 'description' => 'The Drupal path this alias is for; e.g. node/12.',
  392. 'type' => 'varchar',
  393. 'length' => 255,
  394. 'not null' => TRUE,
  395. 'default' => '',
  396. ],
  397. 'alias' => [
  398. 'description' => 'The alias for this path; e.g. title-of-the-story.',
  399. 'type' => 'varchar',
  400. 'length' => 255,
  401. 'not null' => TRUE,
  402. 'default' => '',
  403. ],
  404. 'langcode' => [
  405. 'description' => "The language code this alias is for; if 'und', the alias will be used for unknown languages. Each Drupal path can have an alias for each supported language.",
  406. 'type' => 'varchar_ascii',
  407. 'length' => 12,
  408. 'not null' => TRUE,
  409. 'default' => '',
  410. ],
  411. ],
  412. 'primary key' => ['pid'],
  413. 'indexes' => [
  414. 'alias_langcode_pid' => ['alias', 'langcode', 'pid'],
  415. 'source_langcode_pid' => ['source', 'langcode', 'pid'],
  416. ],
  417. ];
  418. }
  419. }