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