3 * @copyright Copyright (C) 2010-2022, 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\Capabilities\ICanHandleRequests;
30 use Friendica\Core\Addon;
31 use Friendica\Core\Cache\Enum\Duration;
32 use Friendica\Core\Cache\Capability\ICanCache;
33 use Friendica\Core\Config\Capability\IManageConfigValues;
34 use Friendica\Core\Hook;
35 use Friendica\Core\L10n;
36 use Friendica\Core\Lock\Capability\ICanLock;
37 use Friendica\LegacyModule;
38 use Friendica\Module\HTTPException\MethodNotAllowed;
39 use Friendica\Module\HTTPException\PageNotFound;
40 use Friendica\Module\Special\Options;
41 use Friendica\Network\HTTPException;
42 use Friendica\Network\HTTPException\MethodNotAllowedException;
43 use Friendica\Network\HTTPException\NotFoundException;
44 use Friendica\Util\Router\FriendicaGroupCountBased;
45 use Psr\Log\LoggerInterface;
48 * Wrapper for FastRoute\Router
50 * This wrapper only makes use of a subset of the router features, mainly parses a route rule to return the relevant
53 * Actual routes are defined in App->collectRoutes.
55 * @package Friendica\App
59 const DELETE = 'DELETE';
61 const PATCH = 'PATCH';
64 const OPTIONS = 'OPTIONS';
66 const ALLOWED_METHODS = [
75 /** @var RouteCollector */
76 protected $routeCollector;
79 * @var array Module parameters
81 private $parameters = [];
95 /** @var IManageConfigValues */
98 /** @var LoggerInterface */
102 private $dice_profiler_threshold;
108 private $baseRoutesFilepath;
114 * @param array $server The $_SERVER variable
115 * @param string $baseRoutesFilepath The path to a base routes file to leverage cache, can be empty
117 * @param ICanCache $cache
118 * @param ICanLock $lock
119 * @param IManageConfigValues $config
120 * @param Arguments $args
121 * @param LoggerInterface $logger
123 * @param RouteCollector|null $routeCollector
125 public function __construct(array $server, string $baseRoutesFilepath, L10n $l10n, ICanCache $cache, ICanLock $lock, IManageConfigValues $config, Arguments $args, LoggerInterface $logger, Dice $dice, RouteCollector $routeCollector = null)
127 $this->baseRoutesFilepath = $baseRoutesFilepath;
129 $this->cache = $cache;
132 $this->config = $config;
134 $this->server = $server;
135 $this->logger = $logger;
136 $this->dice_profiler_threshold = $config->get('system', 'dice_profiler_threshold', 0);
138 $this->routeCollector = $routeCollector ?? new RouteCollector(new Std(), new GroupCountBased());
140 if ($this->baseRoutesFilepath && !file_exists($this->baseRoutesFilepath)) {
141 throw new HTTPException\InternalServerErrorException('Routes file path does\'n exist.');
146 * This will be called either automatically if a base routes file path was submitted,
147 * or can be called manually with a custom route array.
149 * @param array $routes The routes to add to the Router
151 * @return self The router instance with the loaded routes
153 * @throws HTTPException\InternalServerErrorException In case of invalid configs
155 public function loadRoutes(array $routes)
157 $routeCollector = ($this->routeCollector ?? new RouteCollector(new Std(), new GroupCountBased()));
159 $this->addRoutes($routeCollector, $routes);
161 $this->routeCollector = $routeCollector;
163 // Add routes from addons
164 Hook::callAll('route_collection', $this->routeCollector);
169 private function addRoutes(RouteCollector $routeCollector, array $routes)
171 foreach ($routes as $route => $config) {
172 if ($this->isGroup($config)) {
173 $this->addGroup($route, $config, $routeCollector);
174 } elseif ($this->isRoute($config)) {
175 // Always add the OPTIONS endpoint to a route
176 $httpMethods = (array) $config[1];
177 $httpMethods[] = Router::OPTIONS;
178 $routeCollector->addRoute($httpMethods, $route, $config[0]);
180 throw new HTTPException\InternalServerErrorException("Wrong route config for route '" . print_r($route, true) . "'");
186 * Adds a group of routes to a given group
188 * @param string $groupRoute The route of the group
189 * @param array $routes The routes of the group
190 * @param RouteCollector $routeCollector The route collector to add this group
192 private function addGroup(string $groupRoute, array $routes, RouteCollector $routeCollector)
194 $routeCollector->addGroup($groupRoute, function (RouteCollector $routeCollector) use ($routes) {
195 $this->addRoutes($routeCollector, $routes);
200 * Returns true in case the config is a group config
202 * @param array $config
206 private function isGroup(array $config)
210 is_string(array_keys($config)[0]) &&
211 // This entry should NOT be a BaseModule
212 (substr(array_keys($config)[0], 0, strlen('Friendica\Module')) !== 'Friendica\Module') &&
213 // The second argument is an array (another routes)
214 is_array(array_values($config)[0]);
218 * Returns true in case the config is a route config
220 * @param array $config
224 private function isRoute(array $config)
227 // The config array should at least have one entry
228 !empty($config[0]) &&
229 // This entry should be a BaseModule
230 (substr($config[0], 0, strlen('Friendica\Module')) === 'Friendica\Module') &&
231 // Either there is no other argument
232 (empty($config[1]) ||
233 // Or the second argument is an array (HTTP-Methods)
234 is_array($config[1]));
238 * The current route collector
240 * @return RouteCollector|null
242 public function getRouteCollector()
244 return $this->routeCollector;
248 * Returns the relevant module class name for the given page URI or NULL if no route rule matched.
250 * @return string A Friendica\BaseModule-extending class name if a route rule matched
252 * @throws HTTPException\InternalServerErrorException
253 * @throws HTTPException\MethodNotAllowedException If a rule matched but the method didn't
254 * @throws HTTPException\NotFoundException If no rule matched
256 private function getModuleClass()
258 $cmd = $this->args->getCommand();
259 $cmd = '/' . ltrim($cmd, '/');
261 $dispatcher = new FriendicaGroupCountBased($this->getCachedDispatchData());
263 $this->parameters = [];
265 // Check if the HTTP method ist OPTIONS and return the special Options Module with the possible HTTP methods
266 if ($this->args->getMethod() === static::OPTIONS) {
267 $routeOptions = $dispatcher->getOptions($cmd);
269 $moduleClass = Options::class;
270 $this->parameters = ['allowedMethods' => $routeOptions];
272 $routeInfo = $dispatcher->dispatch($this->args->getMethod(), $cmd);
273 if ($routeInfo[0] === Dispatcher::FOUND) {
274 $moduleClass = $routeInfo[1];
275 $this->parameters = $routeInfo[2];
276 } elseif ($routeInfo[0] === Dispatcher::METHOD_NOT_ALLOWED) {
277 throw new HTTPException\MethodNotAllowedException($this->l10n->t('Method not allowed for this module. Allowed method(s): %s', implode(', ', $routeInfo[1])));
279 throw new HTTPException\NotFoundException($this->l10n->t('Page not found.'));
286 public function getModule(?string $module_class = null): ICanHandleRequests
288 $module_parameters = [$this->server];
292 * From the request URL, routing consists of obtaining the name of a BaseModule-extending class of which the
293 * post() and/or content() static methods can be respectively called to produce a data change or an output.
296 $module_class = $module_class ?? $this->getModuleClass();
297 $module_parameters[] = $this->parameters;
298 } catch (MethodNotAllowedException $e) {
299 $module_class = MethodNotAllowed::class;
300 } catch (NotFoundException $e) {
301 $moduleName = $this->args->getModuleName();
302 // Then we try addon-provided modules that we wrap in the LegacyModule class
303 if (Addon::isEnabled($moduleName) && file_exists("addon/{$moduleName}/{$moduleName}.php")) {
304 //Check if module is an app and if public access to apps is allowed or not
305 $privateapps = $this->config->get('config', 'private_addons', false);
306 if ((!local_user()) && Hook::isAddonApp($moduleName) && $privateapps) {
307 throw new MethodNotAllowedException($this->l10n->t("You must be logged in to use addons. "));
309 include_once "addon/{$moduleName}/{$moduleName}.php";
310 if (function_exists($moduleName . '_module')) {
311 $module_parameters[] = "addon/{$moduleName}/{$moduleName}.php";
312 $module_class = LegacyModule::class;
317 /* Finally, we look for a 'standard' program module in the 'mod' directory
318 * We emulate a Module class through the LegacyModule class
320 if (!$module_class && file_exists("mod/{$moduleName}.php")) {
321 $module_parameters[] = "mod/{$moduleName}.php";
322 $module_class = LegacyModule::class;
325 $module_class = $module_class ?: PageNotFound::class;
328 $stamp = microtime(true);
331 /** @var ICanHandleRequests $module */
332 return $this->dice->create($module_class, $module_parameters);
334 if ($this->dice_profiler_threshold > 0) {
335 $dur = floatval(microtime(true) - $stamp);
336 if ($dur >= $this->dice_profiler_threshold) {
337 $this->logger->warning('Dice module creation lasts too long.', ['duration' => round($dur, 3), 'module' => $module_class, 'parameters' => $module_parameters]);
344 * If a base routes file path has been provided, we can load routes from it if the cache misses.
347 * @throws HTTPException\InternalServerErrorException
349 private function getDispatchData()
353 if ($this->baseRoutesFilepath) {
354 $dispatchData = require $this->baseRoutesFilepath;
355 if (!is_array($dispatchData)) {
356 throw new HTTPException\InternalServerErrorException('Invalid base routes file');
360 $this->loadRoutes($dispatchData);
362 return $this->routeCollector->getData();
366 * We cache the dispatch data for speed, as computing the current routes (version 2020.09)
367 * takes about 850ms for each requests.
369 * The cached "routerDispatchData" lasts for a day, and must be cleared manually when there
370 * is any changes in the enabled addons list.
372 * Additionally, we check for the base routes file last modification time to automatically
373 * trigger re-computing the dispatch data.
375 * @return array|mixed
376 * @throws HTTPException\InternalServerErrorException
378 private function getCachedDispatchData()
380 $routerDispatchData = $this->cache->get('routerDispatchData');
381 $lastRoutesFileModifiedTime = $this->cache->get('lastRoutesFileModifiedTime');
382 $forceRecompute = false;
384 if ($this->baseRoutesFilepath) {
385 $routesFileModifiedTime = filemtime($this->baseRoutesFilepath);
386 $forceRecompute = $lastRoutesFileModifiedTime != $routesFileModifiedTime;
389 if (!$forceRecompute && $routerDispatchData) {
390 return $routerDispatchData;
393 if (!$this->lock->acquire('getCachedDispatchData', 0)) {
394 // Immediately return uncached data when we can't aquire a lock
395 return $this->getDispatchData();
398 $routerDispatchData = $this->getDispatchData();
400 $this->cache->set('routerDispatchData', $routerDispatchData, Duration::DAY);
401 if (!empty($routesFileModifiedTime)) {
402 $this->cache->set('lastRoutesFileModifiedTime', $routesFileModifiedTime, Duration::MONTH);
405 if ($this->lock->isLocked('getCachedDispatchData')) {
406 $this->lock->release('getCachedDispatchData');
409 return $routerDispatchData;