]> git.mxchange.org Git - friendica.git/blob - src/App/Router.php
[frio] Add Mute Author Server button to post actions
[friendica.git] / src / App / Router.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2023, 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         protected $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                 $this->parameters = [$this->server];
155         }
156
157         /**
158          * This will be called either automatically if a base routes file path was submitted,
159          * or can be called manually with a custom route array.
160          *
161          * @param array $routes The routes to add to the Router
162          *
163          * @return self The router instance with the loaded routes
164          *
165          * @throws HTTPException\InternalServerErrorException In case of invalid configs
166          */
167         public function loadRoutes(array $routes): Router
168         {
169                 $routeCollector = ($this->routeCollector ?? 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         /**
182          * Adds multiple routes to a route collector
183          *
184          * @param RouteCollector $routeCollector Route collector instance
185          * @param array $routes Multiple routes to be added
186          * @throws HTTPException\InternalServerErrorException If route was wrong (somehow)
187          */
188         private function addRoutes(RouteCollector $routeCollector, array $routes)
189         {
190                 foreach ($routes as $route => $config) {
191                         if ($this->isGroup($config)) {
192                                 $this->addGroup($route, $config, $routeCollector);
193                         } elseif ($this->isRoute($config)) {
194                                 // Always add the OPTIONS endpoint to a route
195                                 $httpMethods   = (array) $config[1];
196                                 $httpMethods[] = Router::OPTIONS;
197                                 $routeCollector->addRoute($httpMethods, $route, $config[0]);
198                         } else {
199                                 throw new HTTPException\InternalServerErrorException("Wrong route config for route '" . print_r($route, true) . "'");
200                         }
201                 }
202         }
203
204         /**
205          * Adds a group of routes to a given group
206          *
207          * @param string         $groupRoute     The route of the group
208          * @param array          $routes         The routes of the group
209          * @param RouteCollector $routeCollector The route collector to add this group
210          */
211         private function addGroup(string $groupRoute, array $routes, RouteCollector $routeCollector)
212         {
213                 $routeCollector->addGroup($groupRoute, function (RouteCollector $routeCollector) use ($routes) {
214                         $this->addRoutes($routeCollector, $routes);
215                 });
216         }
217
218         /**
219          * Returns true in case the config is a group config
220          *
221          * @param array $config
222          *
223          * @return bool
224          */
225         private function isGroup(array $config): bool
226         {
227                 return
228                         is_array($config) &&
229                         is_string(array_keys($config)[0]) &&
230                         // This entry should NOT be a BaseModule
231                         (substr(array_keys($config)[0], 0, strlen('Friendica\Module')) !== 'Friendica\Module') &&
232                         // The second argument is an array (another routes)
233                         is_array(array_values($config)[0]);
234         }
235
236         /**
237          * Returns true in case the config is a route config
238          *
239          * @param array $config
240          *
241          * @return bool
242          */
243         private function isRoute(array $config): bool
244         {
245                 return
246                         // The config array should at least have one entry
247                         !empty($config[0]) &&
248                         // This entry should be a BaseModule
249                         (substr($config[0], 0, strlen('Friendica\Module')) === 'Friendica\Module') &&
250                         // Either there is no other argument
251                         (empty($config[1]) ||
252                          // Or the second argument is an array (HTTP-Methods)
253                          is_array($config[1]));
254         }
255
256         /**
257          * The current route collector
258          *
259          * @return RouteCollector|null
260          */
261         public function getRouteCollector(): ?RouteCollector
262         {
263                 return $this->routeCollector;
264         }
265
266         /**
267          * Returns the Friendica\BaseModule-extending class name if a route rule matched
268          *
269          * @return string
270          *
271          * @throws InternalServerErrorException
272          * @throws MethodNotAllowedException
273          */
274         public function getModuleClass(): string
275         {
276                 if (empty($this->moduleClass)) {
277                         $this->determineModuleClass();
278                 }
279
280                 return $this->moduleClass;
281         }
282
283         /**
284          * Returns the relevant module class name for the given page URI or NULL if no route rule matched.
285          *
286          * @return void
287          *
288          * @throws HTTPException\InternalServerErrorException Unexpected exceptions
289          * @throws HTTPException\MethodNotAllowedException    If a rule is private only
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                 try {
299                         // Check if the HTTP method is OPTIONS and return the special Options Module with the possible HTTP methods
300                         if ($this->args->getMethod() === static::OPTIONS) {
301                                 $this->moduleClass = Options::class;
302                                 $this->parameters[] = ['AllowedMethods' => $dispatcher->getOptions($cmd)];
303                         } else {
304                                 $routeInfo = $dispatcher->dispatch($this->args->getMethod(), $cmd);
305                                 if ($routeInfo[0] === Dispatcher::FOUND) {
306                                         $this->moduleClass = $routeInfo[1];
307                                         $this->parameters[] = $routeInfo[2];
308                                 } else if ($routeInfo[0] === Dispatcher::METHOD_NOT_ALLOWED) {
309                                         throw new HTTPException\MethodNotAllowedException($this->l10n->t('Method not allowed for this module. Allowed method(s): %s', implode(', ', $routeInfo[1])));
310                                 } else {
311                                         throw new HTTPException\NotFoundException($this->l10n->t('Page not found.'));
312                                 }
313                         }
314                 } catch (MethodNotAllowedException $e) {
315                         $this->moduleClass = MethodNotAllowed::class;
316                 } catch (NotFoundException $e) {
317                         $moduleName = $this->args->getModuleName();
318                         // Then we try addon-provided modules that we wrap in the LegacyModule class
319                         if (Addon::isEnabled($moduleName) && file_exists("addon/{$moduleName}/{$moduleName}.php")) {
320                                 //Check if module is an app and if public access to apps is allowed or not
321                                 $privateapps = $this->config->get('config', 'private_addons', false);
322                                 if (!$this->isLocalUser && Hook::isAddonApp($moduleName) && $privateapps) {
323                                         throw new MethodNotAllowedException($this->l10n->t("You must be logged in to use addons. "));
324                                 } else {
325                                         include_once "addon/{$moduleName}/{$moduleName}.php";
326                                         if (function_exists($moduleName . '_module')) {
327                                                 $this->parameters[] = "addon/{$moduleName}/{$moduleName}.php";
328                                                 $this->moduleClass  = LegacyModule::class;
329                                         }
330                                 }
331                         }
332
333                         /* Finally, we look for a 'standard' program module in the 'mod' directory
334                          * We emulate a Module class through the LegacyModule class
335                          */
336                         if (!$this->moduleClass && file_exists("mod/{$moduleName}.php")) {
337                                 $this->parameters[] = "mod/{$moduleName}.php";
338                                 $this->moduleClass  = LegacyModule::class;
339                         }
340
341                         $this->moduleClass = $this->moduleClass ?: PageNotFound::class;
342                 }
343         }
344
345         public function getModule(?string $module_class = null): ICanHandleRequests
346         {
347                 $moduleClass = $module_class ?? $this->getModuleClass();
348
349                 $stamp = microtime(true);
350
351                 try {
352                         /** @var ICanHandleRequests $module */
353                         return $this->dice->create($moduleClass, $this->parameters);
354                 } finally {
355                         if ($this->dice_profiler_threshold > 0) {
356                                 $dur = floatval(microtime(true) - $stamp);
357                                 if ($dur >= $this->dice_profiler_threshold) {
358                                         $this->logger->notice('Dice module creation lasts too long.', ['duration' => round($dur, 3), 'module' => $moduleClass, 'parameters' => $this->parameters]);
359                                 }
360                         }
361                 }
362         }
363
364         /**
365          * If a base routes file path has been provided, we can load routes from it if the cache misses.
366          *
367          * @return array
368          * @throws HTTPException\InternalServerErrorException
369          */
370         private function getDispatchData()
371         {
372                 $dispatchData = [];
373
374                 if ($this->baseRoutesFilepath) {
375                         $dispatchData = require $this->baseRoutesFilepath;
376                         if (!is_array($dispatchData)) {
377                                 throw new HTTPException\InternalServerErrorException('Invalid base routes file');
378                         }
379                 }
380
381                 $this->loadRoutes($dispatchData);
382
383                 return $this->routeCollector->getData();
384         }
385
386         /**
387          * We cache the dispatch data for speed, as computing the current routes (version 2020.09)
388          * takes about 850ms for each requests.
389          *
390          * The cached "routerDispatchData" lasts for a day, and must be cleared manually when there
391          * is any changes in the enabled addons list.
392          *
393          * Additionally, we check for the base routes file last modification time to automatically
394          * trigger re-computing the dispatch data.
395          *
396          * @return array|mixed
397          * @throws HTTPException\InternalServerErrorException
398          */
399         private function getCachedDispatchData()
400         {
401                 $routerDispatchData         = $this->cache->get('routerDispatchData');
402                 $lastRoutesFileModifiedTime = $this->cache->get('lastRoutesFileModifiedTime');
403                 $forceRecompute             = false;
404
405                 if ($this->baseRoutesFilepath) {
406                         $routesFileModifiedTime = filemtime($this->baseRoutesFilepath);
407                         $forceRecompute         = $lastRoutesFileModifiedTime != $routesFileModifiedTime;
408                 }
409
410                 if (!$forceRecompute && $routerDispatchData) {
411                         return $routerDispatchData;
412                 }
413
414                 if (!$this->lock->acquire('getCachedDispatchData', 0)) {
415                         // Immediately return uncached data when we can't acquire a lock
416                         return $this->getDispatchData();
417                 }
418
419                 $routerDispatchData = $this->getDispatchData();
420
421                 $this->cache->set('routerDispatchData', $routerDispatchData, Duration::DAY);
422                 if (!empty($routesFileModifiedTime)) {
423                         $this->cache->set('lastRoutesFileModifiedTime', $routesFileModifiedTime, Duration::MONTH);
424                 }
425
426                 if ($this->lock->isLocked('getCachedDispatchData')) {
427                         $this->lock->release('getCachedDispatchData');
428                 }
429
430                 return $routerDispatchData;
431         }
432 }