3 * @copyright Copyright (C) 2020, Friendica
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
50 const ALLOWED_METHODS = [
55 /** @var RouteCollector */
56 protected $routeCollector;
59 * @var string The HTTP method
64 * @var array Module parameters
66 private $parameters = [];
75 private $baseRoutesFilepath;
78 * @param array $server The $_SERVER variable
79 * @param string $baseRoutesFilepath The path to a base routes file to leverage cache, can be empty
81 * @param ICache $cache
82 * @param RouteCollector|null $routeCollector
84 public function __construct(array $server, string $baseRoutesFilepath, L10n $l10n, ICache $cache, RouteCollector $routeCollector = null)
86 $this->baseRoutesFilepath = $baseRoutesFilepath;
88 $this->cache = $cache;
90 $httpMethod = $server['REQUEST_METHOD'] ?? self::GET;
91 $this->httpMethod = in_array($httpMethod, self::ALLOWED_METHODS) ? $httpMethod : self::GET;
93 $this->routeCollector = isset($routeCollector) ?
95 new RouteCollector(new Std(), new GroupCountBased());
99 * This will be called either automatically if a base routes file path was submitted,
100 * or can be called manually with a custom route array.
102 * @param array $routes The routes to add to the Router
104 * @return self The router instance with the loaded routes
106 * @throws HTTPException\InternalServerErrorException In case of invalid configs
108 public function loadRoutes(array $routes)
110 $routeCollector = (isset($this->routeCollector) ?
111 $this->routeCollector :
112 new RouteCollector(new Std(), new GroupCountBased()));
114 $this->addRoutes($routeCollector, $routes);
116 $this->routeCollector = $routeCollector;
118 // Add routes from addons
119 Hook::callAll('route_collection', $this->routeCollector);
124 private function addRoutes(RouteCollector $routeCollector, array $routes)
126 foreach ($routes as $route => $config) {
127 if ($this->isGroup($config)) {
128 $this->addGroup($route, $config, $routeCollector);
129 } elseif ($this->isRoute($config)) {
130 $routeCollector->addRoute($config[1], $route, $config[0]);
132 throw new HTTPException\InternalServerErrorException("Wrong route config for route '" . print_r($route, true) . "'");
138 * Adds a group of routes to a given group
140 * @param string $groupRoute The route of the group
141 * @param array $routes The routes of the group
142 * @param RouteCollector $routeCollector The route collector to add this group
144 private function addGroup(string $groupRoute, array $routes, RouteCollector $routeCollector)
146 $routeCollector->addGroup($groupRoute, function (RouteCollector $routeCollector) use ($routes) {
147 $this->addRoutes($routeCollector, $routes);
152 * Returns true in case the config is a group config
154 * @param array $config
158 private function isGroup(array $config)
162 is_string(array_keys($config)[0]) &&
163 // This entry should NOT be a BaseModule
164 (substr(array_keys($config)[0], 0, strlen('Friendica\Module')) !== 'Friendica\Module') &&
165 // The second argument is an array (another routes)
166 is_array(array_values($config)[0]);
170 * Returns true in case the config is a route config
172 * @param array $config
176 private function isRoute(array $config)
179 // The config array should at least have one entry
180 !empty($config[0]) &&
181 // This entry should be a BaseModule
182 (substr($config[0], 0, strlen('Friendica\Module')) === 'Friendica\Module') &&
183 // Either there is no other argument
184 (empty($config[1]) ||
185 // Or the second argument is an array (HTTP-Methods)
186 is_array($config[1]));
190 * The current route collector
192 * @return RouteCollector|null
194 public function getRouteCollector()
196 return $this->routeCollector;
200 * Returns the relevant module class name for the given page URI or NULL if no route rule matched.
202 * @param string $cmd The path component of the request URL without the query string
204 * @return string A Friendica\BaseModule-extending class name if a route rule matched
206 * @throws HTTPException\InternalServerErrorException
207 * @throws HTTPException\MethodNotAllowedException If a rule matched but the method didn't
208 * @throws HTTPException\NotFoundException If no rule matched
210 public function getModuleClass($cmd)
212 $cmd = '/' . ltrim($cmd, '/');
214 $dispatcher = new Dispatcher\GroupCountBased($this->getCachedDispatchData());
217 $this->parameters = [];
219 $routeInfo = $dispatcher->dispatch($this->httpMethod, $cmd);
220 if ($routeInfo[0] === Dispatcher::FOUND) {
221 $moduleClass = $routeInfo[1];
222 $this->parameters = $routeInfo[2];
223 } elseif ($routeInfo[0] === Dispatcher::METHOD_NOT_ALLOWED) {
224 throw new HTTPException\MethodNotAllowedException($this->l10n->t('Method not allowed for this module. Allowed method(s): %s', implode(', ', $routeInfo[1])));
226 throw new HTTPException\NotFoundException($this->l10n->t('Page not found.'));
233 * Returns the module parameters.
235 * @return array parameters
237 public function getModuleParameters()
239 return $this->parameters;
243 * If a base routes file path has been provided, we can load routes from it if the cache misses.
246 * @throws HTTPException\InternalServerErrorException
248 private function getDispatchData()
252 if ($this->baseRoutesFilepath && file_exists($this->baseRoutesFilepath)) {
253 $dispatchData = require $this->baseRoutesFilepath;
254 if (!is_array($dispatchData)) {
255 throw new HTTPException\InternalServerErrorException('Invalid base routes file');
259 $this->loadRoutes($dispatchData);
261 return $this->routeCollector->getData();
265 * We cache the dispatch data for speed, as computing the current routes (version 2020.09)
266 * takes about 850ms for each requests.
268 * The cached "routerDispatchData" lasts for a day, and must be cleared manually when there
269 * is any changes in the enabled addons list.
271 * @return array|mixed
272 * @throws HTTPException\InternalServerErrorException
274 private function getCachedDispatchData()
276 $routerDispatchData = $this->cache->get('routerDispatchData');
278 if ($routerDispatchData) {
279 return $routerDispatchData;
282 $routerDispatchData = $this->getDispatchData();
284 $this->cache->set('routerDispatchData', $routerDispatchData, Duration::DAY);
286 return $routerDispatchData;