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