Routing.php 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  1. <?php
  2. declare(strict_types=1);
  3. namespace PhpMyAdmin;
  4. use FastRoute\DataGenerator\GroupCountBased as DataGeneratorGroupCountBased;
  5. use FastRoute\Dispatcher;
  6. use FastRoute\Dispatcher\GroupCountBased as DispatcherGroupCountBased;
  7. use FastRoute\RouteCollector;
  8. use FastRoute\RouteParser\Std as RouteParserStd;
  9. use PhpMyAdmin\Http\ServerRequest;
  10. use Psr\Container\ContainerInterface;
  11. use function __;
  12. use function file_exists;
  13. use function file_put_contents;
  14. use function htmlspecialchars;
  15. use function is_readable;
  16. use function is_string;
  17. use function is_writable;
  18. use function rawurldecode;
  19. use function sprintf;
  20. use function trigger_error;
  21. use function var_export;
  22. use const CACHE_DIR;
  23. use const E_USER_WARNING;
  24. use const ROOT_PATH;
  25. /**
  26. * Class used to warm up the routing cache and manage routing.
  27. */
  28. class Routing
  29. {
  30. public const ROUTES_CACHE_FILE = CACHE_DIR . 'routes.cache.php';
  31. public static function getDispatcher(): Dispatcher
  32. {
  33. $routes = require ROOT_PATH . 'libraries/routes.php';
  34. return self::routesCachedDispatcher($routes);
  35. }
  36. public static function skipCache(): bool
  37. {
  38. global $cfg;
  39. return ($cfg['environment'] ?? '') === 'development';
  40. }
  41. public static function canWriteCache(): bool
  42. {
  43. $cacheFileExists = file_exists(self::ROUTES_CACHE_FILE);
  44. $canWriteFile = is_writable(self::ROUTES_CACHE_FILE);
  45. if ($cacheFileExists && $canWriteFile) {
  46. return true;
  47. }
  48. // Write without read does not work, chmod 200 for example
  49. if (! $cacheFileExists && is_writable(CACHE_DIR) && is_readable(CACHE_DIR)) {
  50. return true;
  51. }
  52. return $canWriteFile;
  53. }
  54. private static function routesCachedDispatcher(callable $routeDefinitionCallback): Dispatcher
  55. {
  56. $skipCache = self::skipCache();
  57. // If skip cache is enabled, do not try to read the file
  58. // If no cache skipping then read it and use it
  59. if (
  60. ! $skipCache
  61. && file_exists(self::ROUTES_CACHE_FILE)
  62. && isset($_SESSION['isRoutesCacheFileValid'])
  63. && $_SESSION['isRoutesCacheFileValid']
  64. ) {
  65. /** @psalm-suppress MissingFile, UnresolvableInclude, MixedAssignment */
  66. $dispatchData = require self::ROUTES_CACHE_FILE;
  67. return new DispatcherGroupCountBased($dispatchData);
  68. }
  69. $routeCollector = new RouteCollector(
  70. new RouteParserStd(),
  71. new DataGeneratorGroupCountBased()
  72. );
  73. $routeDefinitionCallback($routeCollector);
  74. $dispatchData = $routeCollector->getData();
  75. $canWriteCache = self::canWriteCache();
  76. // If skip cache is enabled, do not try to write it
  77. // If no skip cache then try to write if write is possible
  78. if (! $skipCache && $canWriteCache) {
  79. /** @psalm-suppress MissingFile, UnresolvableInclude, MixedAssignment */
  80. $cachedDispatchData = file_exists(self::ROUTES_CACHE_FILE) ? require self::ROUTES_CACHE_FILE : [];
  81. $_SESSION['isRoutesCacheFileValid'] = $dispatchData === $cachedDispatchData;
  82. if (
  83. ! $_SESSION['isRoutesCacheFileValid']
  84. && ! self::writeCache(sprintf('<?php return %s;', var_export($dispatchData, true)))
  85. ) {
  86. $_SESSION['isRoutesCacheFileValid'] = false;
  87. trigger_error(
  88. sprintf(
  89. __(
  90. 'The routing cache could not be written, '
  91. . 'you need to adjust permissions on the folder/file "%s"'
  92. ),
  93. self::ROUTES_CACHE_FILE
  94. ),
  95. E_USER_WARNING
  96. );
  97. }
  98. }
  99. return new DispatcherGroupCountBased($dispatchData);
  100. }
  101. public static function writeCache(string $cacheContents): bool
  102. {
  103. return @file_put_contents(self::ROUTES_CACHE_FILE, $cacheContents) !== false;
  104. }
  105. /**
  106. * @psalm-return non-empty-string
  107. */
  108. public static function getCurrentRoute(): string
  109. {
  110. /** @var mixed $route */
  111. $route = $_GET['route'] ?? $_POST['route'] ?? '/';
  112. if (! is_string($route) || $route === '') {
  113. $route = '/';
  114. }
  115. /**
  116. * See FAQ 1.34.
  117. *
  118. * @see https://docs.phpmyadmin.net/en/latest/faq.html#faq1-34
  119. */
  120. $db = isset($_GET['db']) && is_string($_GET['db']) ? $_GET['db'] : '';
  121. if ($route === '/' && $db !== '') {
  122. $table = isset($_GET['table']) && is_string($_GET['table']) ? $_GET['table'] : '';
  123. $route = $table === '' ? '/database/structure' : '/sql';
  124. }
  125. return $route;
  126. }
  127. /**
  128. * Call associated controller for a route using the dispatcher
  129. */
  130. public static function callControllerForRoute(
  131. ServerRequest $request,
  132. string $route,
  133. Dispatcher $dispatcher,
  134. ContainerInterface $container
  135. ): void {
  136. $routeInfo = $dispatcher->dispatch($request->getMethod(), rawurldecode($route));
  137. if ($routeInfo[0] === Dispatcher::NOT_FOUND) {
  138. /** @var ResponseRenderer $response */
  139. $response = $container->get(ResponseRenderer::class);
  140. $response->setHttpResponseCode(404);
  141. echo Message::error(sprintf(
  142. __('Error 404! The page %s was not found.'),
  143. '<code>' . htmlspecialchars($route) . '</code>'
  144. ))->getDisplay();
  145. return;
  146. }
  147. if ($routeInfo[0] === Dispatcher::METHOD_NOT_ALLOWED) {
  148. /** @var ResponseRenderer $response */
  149. $response = $container->get(ResponseRenderer::class);
  150. $response->setHttpResponseCode(405);
  151. echo Message::error(__('Error 405! Request method not allowed.'))->getDisplay();
  152. return;
  153. }
  154. if ($routeInfo[0] !== Dispatcher::FOUND) {
  155. return;
  156. }
  157. /** @psalm-var class-string $controllerName */
  158. $controllerName = $routeInfo[1];
  159. /** @var array<string, string> $vars */
  160. $vars = $routeInfo[2];
  161. /**
  162. * @psalm-var callable(ServerRequest=, array<string, string>=):void $controller
  163. */
  164. $controller = $container->get($controllerName);
  165. $controller($request, $vars);
  166. }
  167. }