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