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