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