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