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';
52 const OPTIONS = 'OPTIONS';
54 const ALLOWED_METHODS = [
63 /** @var RouteCollector */
64 protected $routeCollector;
67 * @var string The HTTP method
72 * @var array Module parameters
74 private $parameters = [];
83 private $baseRoutesFilepath;
86 * @param array $server The $_SERVER variable
87 * @param string $baseRoutesFilepath The path to a base routes file to leverage cache, can be empty
89 * @param ICache $cache
90 * @param RouteCollector|null $routeCollector
92 public function __construct(array $server, string $baseRoutesFilepath, L10n $l10n, ICache $cache, RouteCollector $routeCollector = null)
94 $this->baseRoutesFilepath = $baseRoutesFilepath;
96 $this->cache = $cache;
98 $httpMethod = $server['REQUEST_METHOD'] ?? self::GET;
99 $this->httpMethod = in_array($httpMethod, self::ALLOWED_METHODS) ? $httpMethod : self::GET;
101 $this->routeCollector = isset($routeCollector) ?
103 new RouteCollector(new Std(), new GroupCountBased());
105 if ($this->baseRoutesFilepath && !file_exists($this->baseRoutesFilepath)) {
106 throw new HTTPException\InternalServerErrorException('Routes file path does\'n exist.');
111 * This will be called either automatically if a base routes file path was submitted,
112 * or can be called manually with a custom route array.
114 * @param array $routes The routes to add to the Router
116 * @return self The router instance with the loaded routes
118 * @throws HTTPException\InternalServerErrorException In case of invalid configs
120 public function loadRoutes(array $routes)
122 $routeCollector = (isset($this->routeCollector) ?
123 $this->routeCollector :
124 new RouteCollector(new Std(), new GroupCountBased()));
126 $this->addRoutes($routeCollector, $routes);
128 $this->routeCollector = $routeCollector;
130 // Add routes from addons
131 Hook::callAll('route_collection', $this->routeCollector);
136 private function addRoutes(RouteCollector $routeCollector, array $routes)
138 foreach ($routes as $route => $config) {
139 if ($this->isGroup($config)) {
140 $this->addGroup($route, $config, $routeCollector);
141 } elseif ($this->isRoute($config)) {
142 $routeCollector->addRoute($config[1], $route, $config[0]);
144 throw new HTTPException\InternalServerErrorException("Wrong route config for route '" . print_r($route, true) . "'");
150 * Adds a group of routes to a given group
152 * @param string $groupRoute The route of the group
153 * @param array $routes The routes of the group
154 * @param RouteCollector $routeCollector The route collector to add this group
156 private function addGroup(string $groupRoute, array $routes, RouteCollector $routeCollector)
158 $routeCollector->addGroup($groupRoute, function (RouteCollector $routeCollector) use ($routes) {
159 $this->addRoutes($routeCollector, $routes);
164 * Returns true in case the config is a group config
166 * @param array $config
170 private function isGroup(array $config)
174 is_string(array_keys($config)[0]) &&
175 // This entry should NOT be a BaseModule
176 (substr(array_keys($config)[0], 0, strlen('Friendica\Module')) !== 'Friendica\Module') &&
177 // The second argument is an array (another routes)
178 is_array(array_values($config)[0]);
182 * Returns true in case the config is a route config
184 * @param array $config
188 private function isRoute(array $config)
191 // The config array should at least have one entry
192 !empty($config[0]) &&
193 // This entry should be a BaseModule
194 (substr($config[0], 0, strlen('Friendica\Module')) === 'Friendica\Module') &&
195 // Either there is no other argument
196 (empty($config[1]) ||
197 // Or the second argument is an array (HTTP-Methods)
198 is_array($config[1]));
202 * The current route collector
204 * @return RouteCollector|null
206 public function getRouteCollector()
208 return $this->routeCollector;
212 * Returns the relevant module class name for the given page URI or NULL if no route rule matched.
214 * @param string $cmd The path component of the request URL without the query string
216 * @return string A Friendica\BaseModule-extending class name if a route rule matched
218 * @throws HTTPException\InternalServerErrorException
219 * @throws HTTPException\MethodNotAllowedException If a rule matched but the method didn't
220 * @throws HTTPException\NotFoundException If no rule matched
222 public function getModuleClass($cmd)
224 $cmd = '/' . ltrim($cmd, '/');
226 $dispatcher = new Dispatcher\GroupCountBased($this->getCachedDispatchData());
229 $this->parameters = [];
231 $routeInfo = $dispatcher->dispatch($this->httpMethod, $cmd);
232 if ($routeInfo[0] === Dispatcher::FOUND) {
233 $moduleClass = $routeInfo[1];
234 $this->parameters = $routeInfo[2];
235 } elseif ($routeInfo[0] === Dispatcher::METHOD_NOT_ALLOWED) {
236 throw new HTTPException\MethodNotAllowedException($this->l10n->t('Method not allowed for this module. Allowed method(s): %s', implode(', ', $routeInfo[1])));
238 throw new HTTPException\NotFoundException($this->l10n->t('Page not found.'));
245 * Returns the module parameters.
247 * @return array parameters
249 public function getModuleParameters()
251 return $this->parameters;
255 * If a base routes file path has been provided, we can load routes from it if the cache misses.
258 * @throws HTTPException\InternalServerErrorException
260 private function getDispatchData()
264 if ($this->baseRoutesFilepath) {
265 $dispatchData = require $this->baseRoutesFilepath;
266 if (!is_array($dispatchData)) {
267 throw new HTTPException\InternalServerErrorException('Invalid base routes file');
271 $this->loadRoutes($dispatchData);
273 return $this->routeCollector->getData();
277 * We cache the dispatch data for speed, as computing the current routes (version 2020.09)
278 * takes about 850ms for each requests.
280 * The cached "routerDispatchData" lasts for a day, and must be cleared manually when there
281 * is any changes in the enabled addons list.
283 * Additionally, we check for the base routes file last modification time to automatically
284 * trigger re-computing the dispatch data.
286 * @return array|mixed
287 * @throws HTTPException\InternalServerErrorException
289 private function getCachedDispatchData()
291 $routerDispatchData = $this->cache->get('routerDispatchData');
292 $lastRoutesFileModifiedTime = $this->cache->get('lastRoutesFileModifiedTime');
293 $forceRecompute = false;
295 if ($this->baseRoutesFilepath) {
296 $routesFileModifiedTime = filemtime($this->baseRoutesFilepath);
297 $forceRecompute = $lastRoutesFileModifiedTime != $routesFileModifiedTime;
300 if (!$forceRecompute && $routerDispatchData) {
301 return $routerDispatchData;
304 $routerDispatchData = $this->getDispatchData();
306 $this->cache->set('routerDispatchData', $routerDispatchData, Duration::DAY);
307 if (!empty($routesFileModifiedTime)) {
308 $this->cache->set('lastRoutesFileMtime', $routesFileModifiedTime, Duration::MONTH);
311 return $routerDispatchData;