]> git.mxchange.org Git - friendica.git/blob - src/App/Router.php
c2887b1059c71745f6cb9cda4687c9922af8560e
[friendica.git] / src / App / Router.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2022, the Friendica project
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
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.
11  *
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.
16  *
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/>.
19  *
20  */
21
22 namespace Friendica\App;
23
24 use Dice\Dice;
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 Psr\Log\LoggerInterface;
45
46 /**
47  * Wrapper for FastRoute\Router
48  *
49  * This wrapper only makes use of a subset of the router features, mainly parses a route rule to return the relevant
50  * module class.
51  *
52  * Actual routes are defined in App->collectRoutes.
53  *
54  * @package Friendica\App
55  */
56 class Router
57 {
58         const DELETE  = 'DELETE';
59         const GET     = 'GET';
60         const PATCH   = 'PATCH';
61         const POST    = 'POST';
62         const PUT     = 'PUT';
63         const OPTIONS = 'OPTIONS';
64
65         const ALLOWED_METHODS = [
66                 self::DELETE,
67                 self::GET,
68                 self::PATCH,
69                 self::POST,
70                 self::PUT,
71                 self::OPTIONS
72         ];
73
74         /** @var RouteCollector */
75         protected $routeCollector;
76
77         /**
78          * @var string The HTTP method
79          */
80         private $httpMethod;
81
82         /**
83          * @var array Module parameters
84          */
85         private $parameters = [];
86
87         /** @var L10n */
88         private $l10n;
89
90         /** @var ICanCache */
91         private $cache;
92
93         /** @var ICanLock */
94         private $lock;
95
96         /** @var Arguments */
97         private $args;
98
99         /** @var IManageConfigValues */
100         private $config;
101
102         /** @var LoggerInterface */
103         private $logger;
104
105         /** @var float */
106         private $dice_profiler_threshold;
107
108         /** @var Dice */
109         private $dice;
110
111         /** @var string */
112         private $baseRoutesFilepath;
113
114         /** @var array */
115         private $server;
116
117         /**
118          * @param array               $server             The $_SERVER variable
119          * @param string              $baseRoutesFilepath The path to a base routes file to leverage cache, can be empty
120          * @param L10n                $l10n
121          * @param ICanCache           $cache
122          * @param ICanLock            $lock
123          * @param IManageConfigValues $config
124          * @param Arguments           $args
125          * @param LoggerInterface     $logger
126          * @param Dice                $dice
127          * @param RouteCollector|null $routeCollector
128          */
129         public function __construct(array $server, string $baseRoutesFilepath, L10n $l10n, ICanCache $cache, ICanLock $lock, IManageConfigValues $config, Arguments $args, LoggerInterface $logger, Dice $dice, RouteCollector $routeCollector = null)
130         {
131                 $this->baseRoutesFilepath = $baseRoutesFilepath;
132                 $this->l10n = $l10n;
133                 $this->cache = $cache;
134                 $this->lock = $lock;
135                 $this->args = $args;
136                 $this->config = $config;
137                 $this->dice = $dice;
138                 $this->server = $server;
139                 $this->logger = $logger;
140                 $this->dice_profiler_threshold = $config->get('system', 'dice_profiler_threshold', 0);
141
142                 $httpMethod = $this->server['REQUEST_METHOD'] ?? self::GET;
143
144                 $this->httpMethod = in_array($httpMethod, self::ALLOWED_METHODS) ? $httpMethod : self::GET;
145
146                 $this->routeCollector = isset($routeCollector) ?
147                         $routeCollector :
148                         new RouteCollector(new Std(), new GroupCountBased());
149
150                 if ($this->baseRoutesFilepath && !file_exists($this->baseRoutesFilepath)) {
151                         throw new HTTPException\InternalServerErrorException('Routes file path does\'n exist.');
152                 }
153         }
154
155         /**
156          * This will be called either automatically if a base routes file path was submitted,
157          * or can be called manually with a custom route array.
158          *
159          * @param array $routes The routes to add to the Router
160          *
161          * @return self The router instance with the loaded routes
162          *
163          * @throws HTTPException\InternalServerErrorException In case of invalid configs
164          */
165         public function loadRoutes(array $routes)
166         {
167                 $routeCollector = (isset($this->routeCollector) ?
168                         $this->routeCollector :
169                         new RouteCollector(new Std(), new GroupCountBased()));
170
171                 $this->addRoutes($routeCollector, $routes);
172
173                 $this->routeCollector = $routeCollector;
174
175                 // Add routes from addons
176                 Hook::callAll('route_collection', $this->routeCollector);
177
178                 return $this;
179         }
180
181         private function addRoutes(RouteCollector $routeCollector, array $routes)
182         {
183                 foreach ($routes as $route => $config) {
184                         if ($this->isGroup($config)) {
185                                 $this->addGroup($route, $config, $routeCollector);
186                         } elseif ($this->isRoute($config)) {
187                                 $routeCollector->addRoute($config[1], $route, $config[0]);
188                         } else {
189                                 throw new HTTPException\InternalServerErrorException("Wrong route config for route '" . print_r($route, true) . "'");
190                         }
191                 }
192         }
193
194         /**
195          * Adds a group of routes to a given group
196          *
197          * @param string         $groupRoute     The route of the group
198          * @param array          $routes         The routes of the group
199          * @param RouteCollector $routeCollector The route collector to add this group
200          */
201         private function addGroup(string $groupRoute, array $routes, RouteCollector $routeCollector)
202         {
203                 $routeCollector->addGroup($groupRoute, function (RouteCollector $routeCollector) use ($routes) {
204                         $this->addRoutes($routeCollector, $routes);
205                 });
206         }
207
208         /**
209          * Returns true in case the config is a group config
210          *
211          * @param array $config
212          *
213          * @return bool
214          */
215         private function isGroup(array $config)
216         {
217                 return
218                         is_array($config) &&
219                         is_string(array_keys($config)[0]) &&
220                         // This entry should NOT be a BaseModule
221                         (substr(array_keys($config)[0], 0, strlen('Friendica\Module')) !== 'Friendica\Module') &&
222                         // The second argument is an array (another routes)
223                         is_array(array_values($config)[0]);
224         }
225
226         /**
227          * Returns true in case the config is a route config
228          *
229          * @param array $config
230          *
231          * @return bool
232          */
233         private function isRoute(array $config)
234         {
235                 return
236                         // The config array should at least have one entry
237                         !empty($config[0]) &&
238                         // This entry should be a BaseModule
239                         (substr($config[0], 0, strlen('Friendica\Module')) === 'Friendica\Module') &&
240                         // Either there is no other argument
241                         (empty($config[1]) ||
242                          // Or the second argument is an array (HTTP-Methods)
243                          is_array($config[1]));
244         }
245
246         /**
247          * The current route collector
248          *
249          * @return RouteCollector|null
250          */
251         public function getRouteCollector()
252         {
253                 return $this->routeCollector;
254         }
255
256         /**
257          * Returns the relevant module class name for the given page URI or NULL if no route rule matched.
258          *
259          * @return string A Friendica\BaseModule-extending class name if a route rule matched
260          *
261          * @throws HTTPException\InternalServerErrorException
262          * @throws HTTPException\MethodNotAllowedException    If a rule matched but the method didn't
263          * @throws HTTPException\NotFoundException            If no rule matched
264          */
265         private function getModuleClass()
266         {
267                 $cmd = $this->args->getCommand();
268                 $cmd = '/' . ltrim($cmd, '/');
269
270                 $dispatcher = new Dispatcher\GroupCountBased($this->getCachedDispatchData());
271
272                 $this->parameters = [];
273
274                 $routeInfo  = $dispatcher->dispatch($this->httpMethod, $cmd);
275                 if ($routeInfo[0] === Dispatcher::FOUND) {
276                         $moduleClass = $routeInfo[1];
277                         $this->parameters = $routeInfo[2];
278                 } elseif ($routeInfo[0] === Dispatcher::METHOD_NOT_ALLOWED) {
279                         throw new HTTPException\MethodNotAllowedException($this->l10n->t('Method not allowed for this module. Allowed method(s): %s', implode(', ', $routeInfo[1])));
280                 } elseif ($this->httpMethod === static::OPTIONS) {
281                         // Default response for HTTP OPTIONS requests in case there is no special treatment
282                         $moduleClass = Options::class;
283                 } else {
284                         throw new HTTPException\NotFoundException($this->l10n->t('Page not found.'));
285                 }
286
287                 return $moduleClass;
288         }
289
290         public function getModule(?string $module_class = null): ICanHandleRequests
291         {
292                 $module_parameters = [$this->server];
293                 /**
294                  * ROUTING
295                  *
296                  * From the request URL, routing consists of obtaining the name of a BaseModule-extending class of which the
297                  * post() and/or content() static methods can be respectively called to produce a data change or an output.
298                  **/
299                 try {
300                         $module_class        = $module_class ?? $this->getModuleClass();
301                         $module_parameters[] = $this->parameters;
302                 } catch (MethodNotAllowedException $e) {
303                         $module_class = MethodNotAllowed::class;
304                 } catch (NotFoundException $e) {
305                         $moduleName = $this->args->getModuleName();
306                         // Then we try addon-provided modules that we wrap in the LegacyModule class
307                         if (Addon::isEnabled($moduleName) && file_exists("addon/{$moduleName}/{$moduleName}.php")) {
308                                 //Check if module is an app and if public access to apps is allowed or not
309                                 $privateapps = $this->config->get('config', 'private_addons', false);
310                                 if ((!local_user()) && Hook::isAddonApp($moduleName) && $privateapps) {
311                                         throw new MethodNotAllowedException($this->l10n->t("You must be logged in to use addons. "));
312                                 } else {
313                                         include_once "addon/{$moduleName}/{$moduleName}.php";
314                                         if (function_exists($moduleName . '_module')) {
315                                                 $module_parameters[] = "addon/{$moduleName}/{$moduleName}.php";
316                                                 $module_class        = LegacyModule::class;
317                                         }
318                                 }
319                         }
320
321                         /* Finally, we look for a 'standard' program module in the 'mod' directory
322                          * We emulate a Module class through the LegacyModule class
323                          */
324                         if (!$module_class && file_exists("mod/{$moduleName}.php")) {
325                                 $module_parameters[] = "mod/{$moduleName}.php";
326                                 $module_class        = LegacyModule::class;
327                         }
328
329                         $module_class = $module_class ?: PageNotFound::class;
330                 }
331
332                 $stamp = microtime(true);
333
334                 try {
335                         /** @var ICanHandleRequests $module */
336                         return $this->dice->create($module_class, $module_parameters);
337                 } finally {
338                         if ($this->dice_profiler_threshold > 0) {
339                                 $dur = floatval(microtime(true) - $stamp);
340                                 if ($dur >= $this->dice_profiler_threshold) {
341                                         $this->logger->warning('Dice module creation lasts too long.', ['duration' => round($dur, 3), 'module' => $module_class, 'parameters' => $module_parameters]);
342                                 }
343                         }
344                 }
345         }
346
347         /**
348          * If a base routes file path has been provided, we can load routes from it if the cache misses.
349          *
350          * @return array
351          * @throws HTTPException\InternalServerErrorException
352          */
353         private function getDispatchData()
354         {
355                 $dispatchData = [];
356
357                 if ($this->baseRoutesFilepath) {
358                         $dispatchData = require $this->baseRoutesFilepath;
359                         if (!is_array($dispatchData)) {
360                                 throw new HTTPException\InternalServerErrorException('Invalid base routes file');
361                         }
362                 }
363
364                 $this->loadRoutes($dispatchData);
365
366                 return $this->routeCollector->getData();
367         }
368
369         /**
370          * We cache the dispatch data for speed, as computing the current routes (version 2020.09)
371          * takes about 850ms for each requests.
372          *
373          * The cached "routerDispatchData" lasts for a day, and must be cleared manually when there
374          * is any changes in the enabled addons list.
375          *
376          * Additionally, we check for the base routes file last modification time to automatically
377          * trigger re-computing the dispatch data.
378          *
379          * @return array|mixed
380          * @throws HTTPException\InternalServerErrorException
381          */
382         private function getCachedDispatchData()
383         {
384                 $routerDispatchData = $this->cache->get('routerDispatchData');
385                 $lastRoutesFileModifiedTime = $this->cache->get('lastRoutesFileModifiedTime');
386                 $forceRecompute = false;
387
388                 if ($this->baseRoutesFilepath) {
389                         $routesFileModifiedTime = filemtime($this->baseRoutesFilepath);
390                         $forceRecompute = $lastRoutesFileModifiedTime != $routesFileModifiedTime;
391                 }
392
393                 if (!$forceRecompute && $routerDispatchData) {
394                         return $routerDispatchData;
395                 }
396
397                 if (!$this->lock->acquire('getCachedDispatchData', 0)) {
398                         // Immediately return uncached data when we can't aquire a lock
399                         return $this->getDispatchData();
400                 }
401
402                 $routerDispatchData = $this->getDispatchData();
403
404                 $this->cache->set('routerDispatchData', $routerDispatchData, Duration::DAY);
405                 if (!empty($routesFileModifiedTime)) {
406                         $this->cache->set('lastRoutesFileModifiedTime', $routesFileModifiedTime, Duration::MONTH);
407                 }
408
409                 if ($this->lock->isLocked('getCachedDispatchData')) {
410                         $this->lock->release('getCachedDispatchData');
411                 }
412
413                 return $routerDispatchData;
414         }
415 }