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\Core\Session;
38 use Friendica\LegacyModule;
39 use Friendica\Module\HTTPException\MethodNotAllowed;
40 use Friendica\Module\HTTPException\PageNotFound;
41 use Friendica\Module\Special\Options;
42 use Friendica\Network\HTTPException;
43 use Friendica\Network\HTTPException\MethodNotAllowedException;
44 use Friendica\Network\HTTPException\NotFoundException;
45 use Friendica\Util\Router\FriendicaGroupCountBased;
46 use Psr\Log\LoggerInterface;
49 * Wrapper for FastRoute\Router
51 * This wrapper only makes use of a subset of the router features, mainly parses a route rule to return the relevant
54 * Actual routes are defined in App->collectRoutes.
56 * @package Friendica\App
60 const DELETE = 'DELETE';
62 const PATCH = 'PATCH';
65 const OPTIONS = 'OPTIONS';
67 const ALLOWED_METHODS = [
76 /** @var RouteCollector */
77 protected $routeCollector;
80 * @var array Module parameters
82 private $parameters = [];
96 /** @var IManageConfigValues */
99 /** @var LoggerInterface */
103 private $dice_profiler_threshold;
109 private $baseRoutesFilepath;
115 * @param array $server The $_SERVER variable
116 * @param string $baseRoutesFilepath The path to a base routes file to leverage cache, can be empty
118 * @param ICanCache $cache
119 * @param ICanLock $lock
120 * @param IManageConfigValues $config
121 * @param Arguments $args
122 * @param LoggerInterface $logger
124 * @param RouteCollector|null $routeCollector
126 public function __construct(array $server, string $baseRoutesFilepath, L10n $l10n, ICanCache $cache, ICanLock $lock, IManageConfigValues $config, Arguments $args, LoggerInterface $logger, Dice $dice, RouteCollector $routeCollector = null)
128 $this->baseRoutesFilepath = $baseRoutesFilepath;
130 $this->cache = $cache;
133 $this->config = $config;
135 $this->server = $server;
136 $this->logger = $logger;
137 $this->dice_profiler_threshold = $config->get('system', 'dice_profiler_threshold', 0);
139 $this->routeCollector = $routeCollector ?? new RouteCollector(new Std(), new GroupCountBased());
141 if ($this->baseRoutesFilepath && !file_exists($this->baseRoutesFilepath)) {
142 throw new HTTPException\InternalServerErrorException('Routes file path does\'n exist.');
147 * This will be called either automatically if a base routes file path was submitted,
148 * or can be called manually with a custom route array.
150 * @param array $routes The routes to add to the Router
152 * @return self The router instance with the loaded routes
154 * @throws HTTPException\InternalServerErrorException In case of invalid configs
156 public function loadRoutes(array $routes): Router
158 $routeCollector = ($this->routeCollector ?? new RouteCollector(new Std(), new GroupCountBased()));
160 $this->addRoutes($routeCollector, $routes);
162 $this->routeCollector = $routeCollector;
164 // Add routes from addons
165 Hook::callAll('route_collection', $this->routeCollector);
171 * Adds multiple routes to a route collector
173 * @param RouteCollector $routeCollector Route collector instance
174 * @param array $routes Multiple routes to be added
175 * @throws HTTPException\InternalServerErrorException If route was wrong (somehow)
177 private function addRoutes(RouteCollector $routeCollector, array $routes)
179 foreach ($routes as $route => $config) {
180 if ($this->isGroup($config)) {
181 $this->addGroup($route, $config, $routeCollector);
182 } elseif ($this->isRoute($config)) {
183 // Always add the OPTIONS endpoint to a route
184 $httpMethods = (array) $config[1];
185 $httpMethods[] = Router::OPTIONS;
186 $routeCollector->addRoute($httpMethods, $route, $config[0]);
188 throw new HTTPException\InternalServerErrorException("Wrong route config for route '" . print_r($route, true) . "'");
194 * Adds a group of routes to a given group
196 * @param string $groupRoute The route of the group
197 * @param array $routes The routes of the group
198 * @param RouteCollector $routeCollector The route collector to add this group
200 private function addGroup(string $groupRoute, array $routes, RouteCollector $routeCollector)
202 $routeCollector->addGroup($groupRoute, function (RouteCollector $routeCollector) use ($routes) {
203 $this->addRoutes($routeCollector, $routes);
208 * Returns true in case the config is a group config
210 * @param array $config
214 private function isGroup(array $config)
218 is_string(array_keys($config)[0]) &&
219 // This entry should NOT be a BaseModule
220 (substr(array_keys($config)[0], 0, strlen('Friendica\Module')) !== 'Friendica\Module') &&
221 // The second argument is an array (another routes)
222 is_array(array_values($config)[0]);
226 * Returns true in case the config is a route config
228 * @param array $config
232 private function isRoute(array $config): bool
235 // The config array should at least have one entry
236 !empty($config[0]) &&
237 // This entry should be a BaseModule
238 (substr($config[0], 0, strlen('Friendica\Module')) === 'Friendica\Module') &&
239 // Either there is no other argument
240 (empty($config[1]) ||
241 // Or the second argument is an array (HTTP-Methods)
242 is_array($config[1]));
246 * The current route collector
248 * @return RouteCollector|null
250 public function getRouteCollector()
252 return $this->routeCollector;
256 * Returns the relevant module class name for the given page URI or NULL if no route rule matched.
258 * @return string A Friendica\BaseModule-extending class name if a route rule matched
260 * @throws HTTPException\InternalServerErrorException
261 * @throws HTTPException\MethodNotAllowedException If a rule matched but the method didn't
262 * @throws HTTPException\NotFoundException If no rule matched
264 private function getModuleClass(): string
266 $cmd = $this->args->getCommand();
267 $cmd = '/' . ltrim($cmd, '/');
269 $dispatcher = new FriendicaGroupCountBased($this->getCachedDispatchData());
271 $this->parameters = [];
273 // Check if the HTTP method is OPTIONS and return the special Options Module with the possible HTTP methods
274 if ($this->args->getMethod() === static::OPTIONS) {
275 $moduleClass = Options::class;
276 $this->parameters = ['allowedMethods' => $dispatcher->getOptions($cmd)];
278 $routeInfo = $dispatcher->dispatch($this->args->getMethod(), $cmd);
279 if ($routeInfo[0] === Dispatcher::FOUND) {
280 $moduleClass = $routeInfo[1];
281 $this->parameters = $routeInfo[2];
282 } elseif ($routeInfo[0] === Dispatcher::METHOD_NOT_ALLOWED) {
283 throw new HTTPException\MethodNotAllowedException($this->l10n->t('Method not allowed for this module. Allowed method(s): %s', implode(', ', $routeInfo[1])));
285 throw new HTTPException\NotFoundException($this->l10n->t('Page not found.'));
292 public function getModule(?string $module_class = null): ICanHandleRequests
294 $module_parameters = [$this->server];
298 * From the request URL, routing consists of obtaining the name of a BaseModule-extending class of which the
299 * post() and/or content() static methods can be respectively called to produce a data change or an output.
302 $module_class = $module_class ?? $this->getModuleClass();
303 $module_parameters[] = $this->parameters;
304 } catch (MethodNotAllowedException $e) {
305 $module_class = MethodNotAllowed::class;
306 } catch (NotFoundException $e) {
307 $moduleName = $this->args->getModuleName();
308 // Then we try addon-provided modules that we wrap in the LegacyModule class
309 if (Addon::isEnabled($moduleName) && file_exists("addon/{$moduleName}/{$moduleName}.php")) {
310 //Check if module is an app and if public access to apps is allowed or not
311 $privateapps = $this->config->get('config', 'private_addons', false);
312 if (!Session::getLocalUser() && Hook::isAddonApp($moduleName) && $privateapps) {
313 throw new MethodNotAllowedException($this->l10n->t("You must be logged in to use addons. "));
315 include_once "addon/{$moduleName}/{$moduleName}.php";
316 if (function_exists($moduleName . '_module')) {
317 $module_parameters[] = "addon/{$moduleName}/{$moduleName}.php";
318 $module_class = LegacyModule::class;
323 /* Finally, we look for a 'standard' program module in the 'mod' directory
324 * We emulate a Module class through the LegacyModule class
326 if (!$module_class && file_exists("mod/{$moduleName}.php")) {
327 $module_parameters[] = "mod/{$moduleName}.php";
328 $module_class = LegacyModule::class;
331 $module_class = $module_class ?: PageNotFound::class;
334 $stamp = microtime(true);
337 /** @var ICanHandleRequests $module */
338 return $this->dice->create($module_class, $module_parameters);
340 if ($this->dice_profiler_threshold > 0) {
341 $dur = floatval(microtime(true) - $stamp);
342 if ($dur >= $this->dice_profiler_threshold) {
343 $this->logger->notice('Dice module creation lasts too long.', ['duration' => round($dur, 3), 'module' => $module_class, 'parameters' => $module_parameters]);
350 * If a base routes file path has been provided, we can load routes from it if the cache misses.
353 * @throws HTTPException\InternalServerErrorException
355 private function getDispatchData()
359 if ($this->baseRoutesFilepath) {
360 $dispatchData = require $this->baseRoutesFilepath;
361 if (!is_array($dispatchData)) {
362 throw new HTTPException\InternalServerErrorException('Invalid base routes file');
366 $this->loadRoutes($dispatchData);
368 return $this->routeCollector->getData();
372 * We cache the dispatch data for speed, as computing the current routes (version 2020.09)
373 * takes about 850ms for each requests.
375 * The cached "routerDispatchData" lasts for a day, and must be cleared manually when there
376 * is any changes in the enabled addons list.
378 * Additionally, we check for the base routes file last modification time to automatically
379 * trigger re-computing the dispatch data.
381 * @return array|mixed
382 * @throws HTTPException\InternalServerErrorException
384 private function getCachedDispatchData()
386 $routerDispatchData = $this->cache->get('routerDispatchData');
387 $lastRoutesFileModifiedTime = $this->cache->get('lastRoutesFileModifiedTime');
388 $forceRecompute = false;
390 if ($this->baseRoutesFilepath) {
391 $routesFileModifiedTime = filemtime($this->baseRoutesFilepath);
392 $forceRecompute = $lastRoutesFileModifiedTime != $routesFileModifiedTime;
395 if (!$forceRecompute && $routerDispatchData) {
396 return $routerDispatchData;
399 if (!$this->lock->acquire('getCachedDispatchData', 0)) {
400 // Immediately return uncached data when we can't aquire a lock
401 return $this->getDispatchData();
404 $routerDispatchData = $this->getDispatchData();
406 $this->cache->set('routerDispatchData', $routerDispatchData, Duration::DAY);
407 if (!empty($routesFileModifiedTime)) {
408 $this->cache->set('lastRoutesFileModifiedTime', $routesFileModifiedTime, Duration::MONTH);
411 if ($this->lock->isLocked('getCachedDispatchData')) {
412 $this->lock->release('getCachedDispatchData');
415 return $routerDispatchData;