3 * @copyright Copyright (C) 2010-2021, the Friendica project
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\App;
25 use FastRoute\DataGenerator\GroupCountBased;
26 use FastRoute\Dispatcher;
27 use FastRoute\RouteCollector;
28 use FastRoute\RouteParser\Std;
29 use Friendica\Core\Cache\Duration;
30 use Friendica\Core\Cache\ICache;
31 use Friendica\Core\Hook;
32 use Friendica\Core\L10n;
33 use Friendica\Network\HTTPException;
36 * Wrapper for FastRoute\Router
38 * This wrapper only makes use of a subset of the router features, mainly parses a route rule to return the relevant
41 * Actual routes are defined in App->collectRoutes.
43 * @package Friendica\App
47 const DELETE = 'DELETE';
49 const PATCH = 'PATCH';
53 const ALLOWED_METHODS = [
61 /** @var RouteCollector */
62 protected $routeCollector;
65 * @var string The HTTP method
70 * @var array Module parameters
72 private $parameters = [];
81 private $baseRoutesFilepath;
84 * @param array $server The $_SERVER variable
85 * @param string $baseRoutesFilepath The path to a base routes file to leverage cache, can be empty
87 * @param ICache $cache
88 * @param RouteCollector|null $routeCollector
90 public function __construct(array $server, string $baseRoutesFilepath, L10n $l10n, ICache $cache, RouteCollector $routeCollector = null)
92 $this->baseRoutesFilepath = $baseRoutesFilepath;
94 $this->cache = $cache;
96 $httpMethod = $server['REQUEST_METHOD'] ?? self::GET;
97 $this->httpMethod = in_array($httpMethod, self::ALLOWED_METHODS) ? $httpMethod : self::GET;
99 $this->routeCollector = isset($routeCollector) ?
101 new RouteCollector(new Std(), new GroupCountBased());
103 if ($this->baseRoutesFilepath && !file_exists($this->baseRoutesFilepath)) {
104 throw new HTTPException\InternalServerErrorException('Routes file path does\'n exist.');
109 * This will be called either automatically if a base routes file path was submitted,
110 * or can be called manually with a custom route array.
112 * @param array $routes The routes to add to the Router
114 * @return self The router instance with the loaded routes
116 * @throws HTTPException\InternalServerErrorException In case of invalid configs
118 public function loadRoutes(array $routes)
120 $routeCollector = (isset($this->routeCollector) ?
121 $this->routeCollector :
122 new RouteCollector(new Std(), new GroupCountBased()));
124 $this->addRoutes($routeCollector, $routes);
126 $this->routeCollector = $routeCollector;
128 // Add routes from addons
129 Hook::callAll('route_collection', $this->routeCollector);
134 private function addRoutes(RouteCollector $routeCollector, array $routes)
136 foreach ($routes as $route => $config) {
137 if ($this->isGroup($config)) {
138 $this->addGroup($route, $config, $routeCollector);
139 } elseif ($this->isRoute($config)) {
140 $routeCollector->addRoute($config[1], $route, $config[0]);
142 throw new HTTPException\InternalServerErrorException("Wrong route config for route '" . print_r($route, true) . "'");
148 * Adds a group of routes to a given group
150 * @param string $groupRoute The route of the group
151 * @param array $routes The routes of the group
152 * @param RouteCollector $routeCollector The route collector to add this group
154 private function addGroup(string $groupRoute, array $routes, RouteCollector $routeCollector)
156 $routeCollector->addGroup($groupRoute, function (RouteCollector $routeCollector) use ($routes) {
157 $this->addRoutes($routeCollector, $routes);
162 * Returns true in case the config is a group config
164 * @param array $config
168 private function isGroup(array $config)
172 is_string(array_keys($config)[0]) &&
173 // This entry should NOT be a BaseModule
174 (substr(array_keys($config)[0], 0, strlen('Friendica\Module')) !== 'Friendica\Module') &&
175 // The second argument is an array (another routes)
176 is_array(array_values($config)[0]);
180 * Returns true in case the config is a route config
182 * @param array $config
186 private function isRoute(array $config)
189 // The config array should at least have one entry
190 !empty($config[0]) &&
191 // This entry should be a BaseModule
192 (substr($config[0], 0, strlen('Friendica\Module')) === 'Friendica\Module') &&
193 // Either there is no other argument
194 (empty($config[1]) ||
195 // Or the second argument is an array (HTTP-Methods)
196 is_array($config[1]));
200 * The current route collector
202 * @return RouteCollector|null
204 public function getRouteCollector()
206 return $this->routeCollector;
210 * Returns the relevant module class name for the given page URI or NULL if no route rule matched.
212 * @param string $cmd The path component of the request URL without the query string
214 * @return string A Friendica\BaseModule-extending class name if a route rule matched
216 * @throws HTTPException\InternalServerErrorException
217 * @throws HTTPException\MethodNotAllowedException If a rule matched but the method didn't
218 * @throws HTTPException\NotFoundException If no rule matched
220 public function getModuleClass($cmd)
222 $cmd = '/' . ltrim($cmd, '/');
224 $dispatcher = new Dispatcher\GroupCountBased($this->getCachedDispatchData());
227 $this->parameters = [];
229 $routeInfo = $dispatcher->dispatch($this->httpMethod, $cmd);
230 if ($routeInfo[0] === Dispatcher::FOUND) {
231 $moduleClass = $routeInfo[1];
232 $this->parameters = $routeInfo[2];
233 } elseif ($routeInfo[0] === Dispatcher::METHOD_NOT_ALLOWED) {
234 throw new HTTPException\MethodNotAllowedException($this->l10n->t('Method not allowed for this module. Allowed method(s): %s', implode(', ', $routeInfo[1])));
236 throw new HTTPException\NotFoundException($this->l10n->t('Page not found.'));
243 * Returns the module parameters.
245 * @return array parameters
247 public function getModuleParameters()
249 return $this->parameters;
253 * If a base routes file path has been provided, we can load routes from it if the cache misses.
256 * @throws HTTPException\InternalServerErrorException
258 private function getDispatchData()
262 if ($this->baseRoutesFilepath) {
263 $dispatchData = require $this->baseRoutesFilepath;
264 if (!is_array($dispatchData)) {
265 throw new HTTPException\InternalServerErrorException('Invalid base routes file');
269 $this->loadRoutes($dispatchData);
271 return $this->routeCollector->getData();
275 * We cache the dispatch data for speed, as computing the current routes (version 2020.09)
276 * takes about 850ms for each requests.
278 * The cached "routerDispatchData" lasts for a day, and must be cleared manually when there
279 * is any changes in the enabled addons list.
281 * Additionally, we check for the base routes file last modification time to automatically
282 * trigger re-computing the dispatch data.
284 * @return array|mixed
285 * @throws HTTPException\InternalServerErrorException
287 private function getCachedDispatchData()
289 $routerDispatchData = $this->cache->get('routerDispatchData');
290 $lastRoutesFileModifiedTime = $this->cache->get('lastRoutesFileModifiedTime');
291 $forceRecompute = false;
293 if ($this->baseRoutesFilepath) {
294 $routesFileModifiedTime = filemtime($this->baseRoutesFilepath);
295 $forceRecompute = $lastRoutesFileModifiedTime != $routesFileModifiedTime;
298 if (!$forceRecompute && $routerDispatchData) {
299 return $routerDispatchData;
302 $routerDispatchData = $this->getDispatchData();
304 $this->cache->set('routerDispatchData', $routerDispatchData, Duration::DAY);
305 if (!empty($routesFileModifiedTime)) {
306 $this->cache->set('lastRoutesFileMtime', $routesFileModifiedTime, Duration::MONTH);
309 return $routerDispatchData;