]> git.mxchange.org Git - friendica.git/blob - src/App/Router.php
Merge pull request #9602 from AndyHee/patch-20201125
[friendica.git] / src / App / Router.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2020, Friendica
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
25 use FastRoute\DataGenerator\GroupCountBased;
26 use FastRoute\Dispatcher;
27 use FastRoute\RouteCollector;
28 use FastRoute\RouteParser\Std;
29 use Friendica\Core\Cache\Duration;
30 use Friendica\Core\Cache\ICache;
31 use Friendica\Core\Hook;
32 use Friendica\Core\L10n;
33 use Friendica\Network\HTTPException;
34
35 /**
36  * Wrapper for FastRoute\Router
37  *
38  * This wrapper only makes use of a subset of the router features, mainly parses a route rule to return the relevant
39  * module class.
40  *
41  * Actual routes are defined in App->collectRoutes.
42  *
43  * @package Friendica\App
44  */
45 class Router
46 {
47         const DELETE = 'DELETE';
48         const GET    = 'GET';
49         const PATCH  = 'PATCH';
50         const POST   = 'POST';
51         const PUT    = 'PUT';
52
53         const ALLOWED_METHODS = [
54                 self::DELETE,
55                 self::GET,
56                 self::PATCH,
57                 self::POST,
58                 self::PUT,
59         ];
60
61         /** @var RouteCollector */
62         protected $routeCollector;
63
64         /**
65          * @var string The HTTP method
66          */
67         private $httpMethod;
68
69         /**
70          * @var array Module parameters
71          */
72         private $parameters = [];
73
74         /** @var L10n */
75         private $l10n;
76
77         /** @var ICache */
78         private $cache;
79
80         /** @var string */
81         private $baseRoutesFilepath;
82
83         /**
84          * @param array               $server             The $_SERVER variable
85          * @param string              $baseRoutesFilepath The path to a base routes file to leverage cache, can be empty
86          * @param L10n                $l10n
87          * @param ICache              $cache
88          * @param RouteCollector|null $routeCollector
89          */
90         public function __construct(array $server, string $baseRoutesFilepath, L10n $l10n, ICache $cache, RouteCollector $routeCollector = null)
91         {
92                 $this->baseRoutesFilepath = $baseRoutesFilepath;
93                 $this->l10n = $l10n;
94                 $this->cache = $cache;
95
96                 $httpMethod = $server['REQUEST_METHOD'] ?? self::GET;
97                 $this->httpMethod = in_array($httpMethod, self::ALLOWED_METHODS) ? $httpMethod : self::GET;
98
99                 $this->routeCollector = isset($routeCollector) ?
100                         $routeCollector :
101                         new RouteCollector(new Std(), new GroupCountBased());
102
103                 if ($this->baseRoutesFilepath && !file_exists($this->baseRoutesFilepath)) {
104                         throw new HTTPException\InternalServerErrorException('Routes file path does\'n exist.');
105                 }
106         }
107
108         /**
109          * This will be called either automatically if a base routes file path was submitted,
110          * or can be called manually with a custom route array.
111          *
112          * @param array $routes The routes to add to the Router
113          *
114          * @return self The router instance with the loaded routes
115          *
116          * @throws HTTPException\InternalServerErrorException In case of invalid configs
117          */
118         public function loadRoutes(array $routes)
119         {
120                 $routeCollector = (isset($this->routeCollector) ?
121                         $this->routeCollector :
122                         new RouteCollector(new Std(), new GroupCountBased()));
123
124                 $this->addRoutes($routeCollector, $routes);
125
126                 $this->routeCollector = $routeCollector;
127
128                 // Add routes from addons
129                 Hook::callAll('route_collection', $this->routeCollector);
130
131                 return $this;
132         }
133
134         private function addRoutes(RouteCollector $routeCollector, array $routes)
135         {
136                 foreach ($routes as $route => $config) {
137                         if ($this->isGroup($config)) {
138                                 $this->addGroup($route, $config, $routeCollector);
139                         } elseif ($this->isRoute($config)) {
140                                 $routeCollector->addRoute($config[1], $route, $config[0]);
141                         } else {
142                                 throw new HTTPException\InternalServerErrorException("Wrong route config for route '" . print_r($route, true) . "'");
143                         }
144                 }
145         }
146
147         /**
148          * Adds a group of routes to a given group
149          *
150          * @param string         $groupRoute     The route of the group
151          * @param array          $routes         The routes of the group
152          * @param RouteCollector $routeCollector The route collector to add this group
153          */
154         private function addGroup(string $groupRoute, array $routes, RouteCollector $routeCollector)
155         {
156                 $routeCollector->addGroup($groupRoute, function (RouteCollector $routeCollector) use ($routes) {
157                         $this->addRoutes($routeCollector, $routes);
158                 });
159         }
160
161         /**
162          * Returns true in case the config is a group config
163          *
164          * @param array $config
165          *
166          * @return bool
167          */
168         private function isGroup(array $config)
169         {
170                 return
171                         is_array($config) &&
172                         is_string(array_keys($config)[0]) &&
173                         // This entry should NOT be a BaseModule
174                         (substr(array_keys($config)[0], 0, strlen('Friendica\Module')) !== 'Friendica\Module') &&
175                         // The second argument is an array (another routes)
176                         is_array(array_values($config)[0]);
177         }
178
179         /**
180          * Returns true in case the config is a route config
181          *
182          * @param array $config
183          *
184          * @return bool
185          */
186         private function isRoute(array $config)
187         {
188                 return
189                         // The config array should at least have one entry
190                         !empty($config[0]) &&
191                         // This entry should be a BaseModule
192                         (substr($config[0], 0, strlen('Friendica\Module')) === 'Friendica\Module') &&
193                         // Either there is no other argument
194                         (empty($config[1]) ||
195                          // Or the second argument is an array (HTTP-Methods)
196                          is_array($config[1]));
197         }
198
199         /**
200          * The current route collector
201          *
202          * @return RouteCollector|null
203          */
204         public function getRouteCollector()
205         {
206                 return $this->routeCollector;
207         }
208
209         /**
210          * Returns the relevant module class name for the given page URI or NULL if no route rule matched.
211          *
212          * @param string $cmd The path component of the request URL without the query string
213          *
214          * @return string A Friendica\BaseModule-extending class name if a route rule matched
215          *
216          * @throws HTTPException\InternalServerErrorException
217          * @throws HTTPException\MethodNotAllowedException    If a rule matched but the method didn't
218          * @throws HTTPException\NotFoundException            If no rule matched
219          */
220         public function getModuleClass($cmd)
221         {
222                 $cmd = '/' . ltrim($cmd, '/');
223
224                 $dispatcher = new Dispatcher\GroupCountBased($this->getCachedDispatchData());
225
226                 $moduleClass = null;
227                 $this->parameters = [];
228
229                 $routeInfo  = $dispatcher->dispatch($this->httpMethod, $cmd);
230                 if ($routeInfo[0] === Dispatcher::FOUND) {
231                         $moduleClass = $routeInfo[1];
232                         $this->parameters = $routeInfo[2];
233                 } elseif ($routeInfo[0] === Dispatcher::METHOD_NOT_ALLOWED) {
234                         throw new HTTPException\MethodNotAllowedException($this->l10n->t('Method not allowed for this module. Allowed method(s): %s', implode(', ', $routeInfo[1])));
235                 } else {
236                         throw new HTTPException\NotFoundException($this->l10n->t('Page not found.'));
237                 }
238
239                 return $moduleClass;
240         }
241
242         /**
243          * Returns the module parameters.
244          *
245          * @return array parameters
246          */
247         public function getModuleParameters()
248         {
249                 return $this->parameters;
250         }
251
252         /**
253          * If a base routes file path has been provided, we can load routes from it if the cache misses.
254          *
255          * @return array
256          * @throws HTTPException\InternalServerErrorException
257          */
258         private function getDispatchData()
259         {
260                 $dispatchData = [];
261
262                 if ($this->baseRoutesFilepath) {
263                         $dispatchData = require $this->baseRoutesFilepath;
264                         if (!is_array($dispatchData)) {
265                                 throw new HTTPException\InternalServerErrorException('Invalid base routes file');
266                         }
267                 }
268
269                 $this->loadRoutes($dispatchData);
270
271                 return $this->routeCollector->getData();
272         }
273
274         /**
275          * We cache the dispatch data for speed, as computing the current routes (version 2020.09)
276          * takes about 850ms for each requests.
277          *
278          * The cached "routerDispatchData" lasts for a day, and must be cleared manually when there
279          * is any changes in the enabled addons list.
280          *
281          * Additionally, we check for the base routes file last modification time to automatically
282          * trigger re-computing the dispatch data.
283          *
284          * @return array|mixed
285          * @throws HTTPException\InternalServerErrorException
286          */
287         private function getCachedDispatchData()
288         {
289                 $routerDispatchData = $this->cache->get('routerDispatchData');
290                 $lastRoutesFileModifiedTime = $this->cache->get('lastRoutesFileModifiedTime');
291                 $forceRecompute = false;
292
293                 if ($this->baseRoutesFilepath) {
294                         $routesFileModifiedTime = filemtime($this->baseRoutesFilepath);
295                         $forceRecompute = $lastRoutesFileModifiedTime != $routesFileModifiedTime;
296                 }
297
298                 if (!$forceRecompute && $routerDispatchData) {
299                         return $routerDispatchData;
300                 }
301
302                 $routerDispatchData = $this->getDispatchData();
303
304                 $this->cache->set('routerDispatchData', $routerDispatchData, Duration::DAY);
305                 if (!empty($routesFileModifiedTime)) {
306                         $this->cache->set('lastRoutesFileMtime', $routesFileModifiedTime, Duration::MONTH);
307                 }
308
309                 return $routerDispatchData;
310         }
311 }