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