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