]> git.mxchange.org Git - friendica.git/blob - src/App/ModuleController.php
Merge remote-tracking branch 'upstream/develop' into api-rework
[friendica.git] / src / App / ModuleController.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 Friendica\App;
26 use Friendica\Capabilities\ICanHandleRequests;
27 use Friendica\Core;
28 use Friendica\Core\Config\Capability\IManageConfigValues;
29 use Friendica\LegacyModule;
30 use Friendica\Module\Home;
31 use Friendica\Module\HTTPException\MethodNotAllowed;
32 use Friendica\Module\HTTPException\PageNotFound;
33 use Friendica\Network\HTTPException\MethodNotAllowedException;
34 use Friendica\Network\HTTPException\NoContentException;
35 use Friendica\Network\HTTPException\NotFoundException;
36 use Friendica\Util\Profiler;
37 use Psr\Log\LoggerInterface;
38
39 /**
40  * Holds the common context of the current, loaded module
41  */
42 class ModuleController
43 {
44         const DEFAULT       = 'home';
45         const DEFAULT_CLASS = Home::class;
46         /**
47          * A list of modules, which are backend methods
48          *
49          * @var array
50          */
51         const BACKEND_MODULES = [
52                 '_well_known',
53                 'api',
54                 'dfrn_notify',
55                 'feed',
56                 'fetch',
57                 'followers',
58                 'following',
59                 'hcard',
60                 'hostxrd',
61                 'inbox',
62                 'manifest',
63                 'nodeinfo',
64                 'noscrape',
65                 'objects',
66                 'outbox',
67                 'poco',
68                 'post',
69                 'pubsub',
70                 'pubsubhubbub',
71                 'receive',
72                 'rsd_xml',
73                 'salmon',
74                 'statistics_json',
75                 'xrd',
76         ];
77
78         /**
79          * @var string The module name
80          */
81         private $moduleName;
82
83         /**
84          * @var ?ICanHandleRequests The module object
85          */
86         private $module;
87
88         /**
89          * @var bool true, if the module is a backend module
90          */
91         private $isBackend;
92
93         /**
94          * @var bool true, if the loaded addon is private, so we have to print out not allowed
95          */
96         private $printNotAllowedAddon;
97
98         /**
99          * @return string
100          */
101         public function getName()
102         {
103                 return $this->moduleName;
104         }
105
106         /**
107          * @return ?ICanHandleRequests The base module object
108          */
109         public function getModule(): ?ICanHandleRequests
110         {
111                 return $this->module;
112         }
113
114         /**
115          * @return bool True, if the current module is a backend module
116          * @see ModuleController::BACKEND_MODULES for a list
117          */
118         public function isBackend()
119         {
120                 return $this->isBackend;
121         }
122
123         public function __construct(string $moduleName = self::DEFAULT, ?ICanHandleRequests $module = null, bool $isBackend = false, bool $printNotAllowedAddon = false)
124         {
125                 $this->moduleName           = $moduleName;
126                 $this->module               = $module;
127                 $this->isBackend            = $isBackend;
128                 $this->printNotAllowedAddon = $printNotAllowedAddon;
129         }
130
131         /**
132          * Determines the current module based on the App arguments and the server variable
133          *
134          * @param Arguments $args   The Friendica arguments
135          *
136          * @return ModuleController The module with the determined module
137          */
138         public function determineName(Arguments $args)
139         {
140                 if ($args->getArgc() > 0) {
141                         $module = str_replace('.', '_', $args->get(0));
142                         $module = str_replace('-', '_', $module);
143                 } else {
144                         $module = self::DEFAULT;
145                 }
146
147                 // Compatibility with the Firefox App
148                 if (($module == "users") && ($args->getCommand() == "users/sign_in")) {
149                         $module = "login";
150                 }
151
152                 $isBackend = in_array($module, ModuleController::BACKEND_MODULES);
153
154                 return new ModuleController($module, null, $isBackend, $this->printNotAllowedAddon);
155         }
156
157         /**
158          * Determine the class of the current module
159          *
160          * @param Arguments           $args   The Friendica execution arguments
161          * @param Router              $router The Friendica routing instance
162          * @param IManageConfigValues $config The Friendica Configuration
163          * @param Dice                $dice   The Dependency Injection container
164          *
165          * @return ModuleController The determined module of this call
166          *
167          * @throws \Exception
168          */
169         public function determineClass(Arguments $args, Router $router, IManageConfigValues $config, Dice $dice)
170         {
171                 $printNotAllowedAddon = false;
172
173                 $module_class      = null;
174                 $module_parameters = [];
175                 /**
176                  * ROUTING
177                  *
178                  * From the request URL, routing consists of obtaining the name of a BaseModule-extending class of which the
179                  * post() and/or content() static methods can be respectively called to produce a data change or an output.
180                  **/
181                 try {
182                         $module_class        = $router->getModuleClass($args->getCommand());
183                         $module_parameters[] = $router->getModuleParameters();
184                 } catch (MethodNotAllowedException $e) {
185                         $module_class = MethodNotAllowed::class;
186                 } catch (NotFoundException $e) {
187                         // Then we try addon-provided modules that we wrap in the LegacyModule class
188                         if (Core\Addon::isEnabled($this->moduleName) && file_exists("addon/{$this->moduleName}/{$this->moduleName}.php")) {
189                                 //Check if module is an app and if public access to apps is allowed or not
190                                 $privateapps = $config->get('config', 'private_addons', false);
191                                 if ((!local_user()) && Core\Hook::isAddonApp($this->moduleName) && $privateapps) {
192                                         $printNotAllowedAddon = true;
193                                 } else {
194                                         include_once "addon/{$this->moduleName}/{$this->moduleName}.php";
195                                         if (function_exists($this->moduleName . '_module')) {
196                                                 $module_parameters[] = "addon/{$this->moduleName}/{$this->moduleName}.php";
197                                                 $module_class        = LegacyModule::class;
198                                         }
199                                 }
200                         }
201
202                         /* Finally, we look for a 'standard' program module in the 'mod' directory
203                          * We emulate a Module class through the LegacyModule class
204                          */
205                         if (!$module_class && file_exists("mod/{$this->moduleName}.php")) {
206                                 $module_parameters[] = "mod/{$this->moduleName}.php";
207                                 $module_class        = LegacyModule::class;
208                         }
209
210                         $module_class = $module_class ?: PageNotFound::class;
211                 }
212
213                 /** @var ICanHandleRequests $module */
214                 $module = $dice->create($module_class, $module_parameters);
215
216                 return new ModuleController($this->moduleName, $module, $this->isBackend, $printNotAllowedAddon);
217         }
218
219         /**
220          * Run the determined module class and calls all hooks applied to
221          *
222          * @param \Friendica\Core\L10n $l10n    The L10n instance
223          * @param App\BaseURL          $baseUrl The Friendica Base URL
224          * @param LoggerInterface      $logger  The Friendica logger
225          * @param array                $server  The $_SERVER variable
226          * @param array                $post    The $_POST variables
227          *
228          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
229          */
230         public function run(Core\L10n $l10n, App\BaseURL $baseUrl, LoggerInterface $logger, Profiler $profiler, array $server, array $post)
231         {
232                 if ($this->printNotAllowedAddon) {
233                         notice($l10n->t("You must be logged in to use addons. "));
234                 }
235
236                 /* The URL provided does not resolve to a valid module.
237                  *
238                  * On Dreamhost sites, quite often things go wrong for no apparent reason and they send us to '/internal_error.html'.
239                  * We don't like doing this, but as it occasionally accounts for 10-20% or more of all site traffic -
240                  * we are going to trap this and redirect back to the requested page. As long as you don't have a critical error on your page
241                  * this will often succeed and eventually do the right thing.
242                  *
243                  * Otherwise we are going to emit a 404 not found.
244                  */
245                 if ($this->module === PageNotFound::class) {
246                         $queryString = $server['QUERY_STRING'];
247                         // Stupid browser tried to pre-fetch our Javascript img template. Don't log the event or return anything - just quietly exit.
248                         if (!empty($queryString) && preg_match('/{[0-9]}/', $queryString) !== 0) {
249                                 exit();
250                         }
251
252                         if (!empty($queryString) && ($queryString === 'q=internal_error.html') && isset($dreamhost_error_hack)) {
253                                 $logger->info('index.php: dreamhost_error_hack invoked.', ['Original URI' => $server['REQUEST_URI']]);
254                                 $baseUrl->redirect($server['REQUEST_URI']);
255                         }
256
257                         $logger->debug('index.php: page not found.', ['request_uri' => $server['REQUEST_URI'], 'address' => $server['REMOTE_ADDR'], 'query' => $server['QUERY_STRING']]);
258                 }
259
260                 // @see https://github.com/tootsuite/mastodon/blob/c3aef491d66aec743a3a53e934a494f653745b61/config/initializers/cors.rb
261                 if (substr($_REQUEST['pagename'] ?? '', 0, 12) == '.well-known/') {
262                         header('Access-Control-Allow-Origin: *');
263                         header('Access-Control-Allow-Headers: *');
264                         header('Access-Control-Allow-Methods: ' . Router::GET);
265                         header('Access-Control-Allow-Credentials: false');
266                 } elseif (substr($_REQUEST['pagename'] ?? '', 0, 8) == 'profile/') {
267                         header('Access-Control-Allow-Origin: *');
268                         header('Access-Control-Allow-Headers: *');
269                         header('Access-Control-Allow-Methods: ' . Router::GET);
270                         header('Access-Control-Allow-Credentials: false');
271                 } elseif (substr($_REQUEST['pagename'] ?? '', 0, 4) == 'api/') {
272                         header('Access-Control-Allow-Origin: *');
273                         header('Access-Control-Allow-Headers: *');
274                         header('Access-Control-Allow-Methods: ' . implode(',', Router::ALLOWED_METHODS));
275                         header('Access-Control-Allow-Credentials: false');
276                         header('Access-Control-Expose-Headers: Link');
277                 } elseif (substr($_REQUEST['pagename'] ?? '', 0, 11) == 'oauth/token') {
278                         header('Access-Control-Allow-Origin: *');
279                         header('Access-Control-Allow-Headers: *');
280                         header('Access-Control-Allow-Methods: ' . Router::POST);
281                         header('Access-Control-Allow-Credentials: false');
282                 }
283
284                 // @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/OPTIONS
285                 // @todo Check allowed methods per requested path
286                 if ($server['REQUEST_METHOD'] === Router::OPTIONS) {
287                         header('Allow: ' . implode(',', Router::ALLOWED_METHODS));
288                         throw new NoContentException();
289                 }
290
291                 $placeholder = '';
292
293                 $profiler->set(microtime(true), 'ready');
294                 $timestamp = microtime(true);
295
296                 Core\Hook::callAll($this->moduleName . '_mod_init', $placeholder);
297
298                 $profiler->set(microtime(true) - $timestamp, 'init');
299
300                 if ($server['REQUEST_METHOD'] === Router::DELETE) {
301                         $this->module->delete();
302                 }
303
304                 if ($server['REQUEST_METHOD'] === Router::PATCH) {
305                         $this->module->patch();
306                 }
307
308                 if ($server['REQUEST_METHOD'] === Router::POST) {
309                         Core\Hook::callAll($this->moduleName . '_mod_post', $post);
310                         $this->module->post();
311                 }
312
313                 if ($server['REQUEST_METHOD'] === Router::PUT) {
314                         $this->module->put();
315                 }
316
317                 // "rawContent" is especially meant for technical endpoints.
318                 // This endpoint doesn't need any theme initialization or other comparable stuff.
319                 $this->module->rawContent();
320         }
321 }