]> git.mxchange.org Git - friendica.git/blob - src/App/ModuleController.php
Refactor App\Module to App\ModuleController and rename properties
[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 class
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                 $defaultClass = static::DEFAULT_CLASS;
126
127                 $this->moduleName           = $moduleName;
128                 $this->module               = $module ?? new $defaultClass();
129                 $this->isBackend            = $isBackend;
130                 $this->printNotAllowedAddon = $printNotAllowedAddon;
131         }
132
133         /**
134          * Determines the current module based on the App arguments and the server variable
135          *
136          * @param Arguments $args   The Friendica arguments
137          *
138          * @return ModuleController The module with the determined module
139          */
140         public function determineName(Arguments $args)
141         {
142                 if ($args->getArgc() > 0) {
143                         $module = str_replace('.', '_', $args->get(0));
144                         $module = str_replace('-', '_', $module);
145                 } else {
146                         $module = self::DEFAULT;
147                 }
148
149                 // Compatibility with the Firefox App
150                 if (($module == "users") && ($args->getCommand() == "users/sign_in")) {
151                         $module = "login";
152                 }
153
154                 $isBackend = in_array($module, ModuleController::BACKEND_MODULES);
155                 ;
156
157                 return new ModuleController($module, null, $isBackend, $this->printNotAllowedAddon);
158         }
159
160         /**
161          * Determine the class of the current module
162          *
163          * @param Arguments           $args   The Friendica execution arguments
164          * @param Router              $router The Friendica routing instance
165          * @param IManageConfigValues $config The Friendica Configuration
166          * @param Dice                $dice   The Dependency Injection container
167          *
168          * @return ModuleController The determined module of this call
169          *
170          * @throws \Exception
171          */
172         public function determineClass(Arguments $args, Router $router, IManageConfigValues $config, Dice $dice)
173         {
174                 $printNotAllowedAddon = false;
175
176                 $module_class      = null;
177                 $module_parameters = [];
178                 /**
179                  * ROUTING
180                  *
181                  * From the request URL, routing consists of obtaining the name of a BaseModule-extending class of which the
182                  * post() and/or content() static methods can be respectively called to produce a data change or an output.
183                  **/
184                 try {
185                         $module_class        = $router->getModuleClass($args->getCommand());
186                         $module_parameters[] = $router->getModuleParameters();
187                 } catch (MethodNotAllowedException $e) {
188                         $module_class = MethodNotAllowed::class;
189                 } catch (NotFoundException $e) {
190                         // Then we try addon-provided modules that we wrap in the LegacyModule class
191                         if (Core\Addon::isEnabled($this->moduleName) && file_exists("addon/{$this->moduleName}/{$this->moduleName}.php")) {
192                                 //Check if module is an app and if public access to apps is allowed or not
193                                 $privateapps = $config->get('config', 'private_addons', false);
194                                 if ((!local_user()) && Core\Hook::isAddonApp($this->moduleName) && $privateapps) {
195                                         $printNotAllowedAddon = true;
196                                 } else {
197                                         include_once "addon/{$this->moduleName}/{$this->moduleName}.php";
198                                         if (function_exists($this->moduleName . '_module')) {
199                                                 $module_parameters[] = "addon/{$this->moduleName}/{$this->moduleName}.php";
200                                                 $module_class        = LegacyModule::class;
201                                         }
202                                 }
203                         }
204
205                         /* Finally, we look for a 'standard' program module in the 'mod' directory
206                          * We emulate a Module class through the LegacyModule class
207                          */
208                         if (!$module_class && file_exists("mod/{$this->moduleName}.php")) {
209                                 $module_parameters[] = "mod/{$this->moduleName}.php";
210                                 $module_class        = LegacyModule::class;
211                         }
212
213                         $module_class = $module_class ?: PageNotFound::class;
214                 }
215
216                 /** @var ICanHandleRequests $module */
217                 $module = $dice->create($module_class, $module_parameters);
218
219                 return new ModuleController($this->moduleName, $module, $this->isBackend, $printNotAllowedAddon);
220         }
221
222         /**
223          * Run the determined module class and calls all hooks applied to
224          *
225          * @param \Friendica\Core\L10n $l10n    The L10n instance
226          * @param App\BaseURL          $baseUrl The Friendica Base URL
227          * @param LoggerInterface      $logger  The Friendica logger
228          * @param array                $server  The $_SERVER variable
229          * @param array                $post    The $_POST variables
230          *
231          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
232          */
233         public function run(Core\L10n $l10n, App\BaseURL $baseUrl, LoggerInterface $logger, Profiler $profiler, array $server, array $post)
234         {
235                 if ($this->printNotAllowedAddon) {
236                         notice($l10n->t("You must be logged in to use addons. "));
237                 }
238
239                 /* The URL provided does not resolve to a valid module.
240                  *
241                  * On Dreamhost sites, quite often things go wrong for no apparent reason and they send us to '/internal_error.html'.
242                  * We don't like doing this, but as it occasionally accounts for 10-20% or more of all site traffic -
243                  * 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
244                  * this will often succeed and eventually do the right thing.
245                  *
246                  * Otherwise we are going to emit a 404 not found.
247                  */
248                 if ($this->module === PageNotFound::class) {
249                         $queryString = $server['QUERY_STRING'];
250                         // Stupid browser tried to pre-fetch our Javascript img template. Don't log the event or return anything - just quietly exit.
251                         if (!empty($queryString) && preg_match('/{[0-9]}/', $queryString) !== 0) {
252                                 exit();
253                         }
254
255                         if (!empty($queryString) && ($queryString === 'q=internal_error.html') && isset($dreamhost_error_hack)) {
256                                 $logger->info('index.php: dreamhost_error_hack invoked.', ['Original URI' => $server['REQUEST_URI']]);
257                                 $baseUrl->redirect($server['REQUEST_URI']);
258                         }
259
260                         $logger->debug('index.php: page not found.', ['request_uri' => $server['REQUEST_URI'], 'address' => $server['REMOTE_ADDR'], 'query' => $server['QUERY_STRING']]);
261                 }
262
263                 // @see https://github.com/tootsuite/mastodon/blob/c3aef491d66aec743a3a53e934a494f653745b61/config/initializers/cors.rb
264                 if (substr($_REQUEST['pagename'] ?? '', 0, 12) == '.well-known/') {
265                         header('Access-Control-Allow-Origin: *');
266                         header('Access-Control-Allow-Headers: *');
267                         header('Access-Control-Allow-Methods: ' . Router::GET);
268                         header('Access-Control-Allow-Credentials: false');
269                 } elseif (substr($_REQUEST['pagename'] ?? '', 0, 8) == 'profile/') {
270                         header('Access-Control-Allow-Origin: *');
271                         header('Access-Control-Allow-Headers: *');
272                         header('Access-Control-Allow-Methods: ' . Router::GET);
273                         header('Access-Control-Allow-Credentials: false');
274                 } elseif (substr($_REQUEST['pagename'] ?? '', 0, 4) == 'api/') {
275                         header('Access-Control-Allow-Origin: *');
276                         header('Access-Control-Allow-Headers: *');
277                         header('Access-Control-Allow-Methods: ' . implode(',', Router::ALLOWED_METHODS));
278                         header('Access-Control-Allow-Credentials: false');
279                         header('Access-Control-Expose-Headers: Link');
280                 } elseif (substr($_REQUEST['pagename'] ?? '', 0, 11) == 'oauth/token') {
281                         header('Access-Control-Allow-Origin: *');
282                         header('Access-Control-Allow-Headers: *');
283                         header('Access-Control-Allow-Methods: ' . Router::POST);
284                         header('Access-Control-Allow-Credentials: false');
285                 }
286
287                 // @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/OPTIONS
288                 // @todo Check allowed methods per requested path
289                 if ($server['REQUEST_METHOD'] === Router::OPTIONS) {
290                         header('Allow: ' . implode(',', Router::ALLOWED_METHODS));
291                         throw new NoContentException();
292                 }
293
294                 $placeholder = '';
295
296                 $profiler->set(microtime(true), 'ready');
297                 $timestamp = microtime(true);
298
299                 Core\Hook::callAll($this->moduleName . '_mod_init', $placeholder);
300
301                 $this->module->init();
302
303                 $profiler->set(microtime(true) - $timestamp, 'init');
304
305                 if ($server['REQUEST_METHOD'] === Router::DELETE) {
306                         $this->module->delete();
307                 }
308
309                 if ($server['REQUEST_METHOD'] === Router::PATCH) {
310                         $this->module->patch();
311                 }
312
313                 if ($server['REQUEST_METHOD'] === Router::POST) {
314                         Core\Hook::callAll($this->moduleName . '_mod_post', $post);
315                         $this->module->post();
316                 }
317
318                 if ($server['REQUEST_METHOD'] === Router::PUT) {
319                         $this->module->put();
320                 }
321
322                 // "rawContent" is especially meant for technical endpoints.
323                 // This endpoint doesn't need any theme initialization or other comparable stuff.
324                 $this->module->rawContent();
325         }
326 }