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