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