]> git.mxchange.org Git - friendica.git/blob - src/App/Module.php
Merge pull request #9963 from mexon/mat/support-cid-scheme
[friendica.git] / src / App / Module.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 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                 'proxy',
67                 'pubsub',
68                 'pubsubhubbub',
69                 'receive',
70                 'rsd_xml',
71                 'salmon',
72                 'statistics_json',
73                 'xrd',
74         ];
75
76         /**
77          * @var string The module name
78          */
79         private $module;
80
81         /**
82          * @var BaseModule The module class
83          */
84         private $module_class;
85
86         /**
87          * @var array The module parameters
88          */
89         private $module_parameters;
90
91         /**
92          * @var bool true, if the module is a backend module
93          */
94         private $isBackend;
95
96         /**
97          * @var bool true, if the loaded addon is private, so we have to print out not allowed
98          */
99         private $printNotAllowedAddon;
100
101         /**
102          * @return string
103          */
104         public function getName()
105         {
106                 return $this->module;
107         }
108
109         /**
110          * @return string The base class name
111          */
112         public function getClassName()
113         {
114                 return $this->module_class;
115         }
116
117         /**
118          * @return array The module parameters extracted from the route
119          */
120         public function getParameters()
121         {
122                 return $this->module_parameters;
123         }
124
125         /**
126          * @return bool True, if the current module is a backend module
127          * @see Module::BACKEND_MODULES for a list
128          */
129         public function isBackend()
130         {
131                 return $this->isBackend;
132         }
133
134         public function __construct(string $module = self::DEFAULT, string $moduleClass = self::DEFAULT_CLASS, array $moduleParameters = [], bool $isBackend = false, bool $printNotAllowedAddon = false)
135         {
136                 $this->module               = $module;
137                 $this->module_class         = $moduleClass;
138                 $this->module_parameters    = $moduleParameters;
139                 $this->isBackend            = $isBackend;
140                 $this->printNotAllowedAddon = $printNotAllowedAddon;
141         }
142
143         /**
144          * Determines the current module based on the App arguments and the server variable
145          *
146          * @param Arguments $args   The Friendica arguments
147          *
148          * @return Module The module with the determined module
149          */
150         public function determineModule(Arguments $args)
151         {
152                 if ($args->getArgc() > 0) {
153                         $module = str_replace('.', '_', $args->get(0));
154                         $module = str_replace('-', '_', $module);
155                 } else {
156                         $module = self::DEFAULT;
157                 }
158
159                 // Compatibility with the Firefox App
160                 if (($module == "users") && ($args->getCommand() == "users/sign_in")) {
161                         $module = "login";
162                 }
163
164                 $isBackend = in_array($module, Module::BACKEND_MODULES);;
165
166                 return new Module($module, $this->module_class, [], $isBackend, $this->printNotAllowedAddon);
167         }
168
169         /**
170          * Determine the class of the current module
171          *
172          * @param Arguments           $args   The Friendica execution arguments
173          * @param Router              $router The Friendica routing instance
174          * @param Core\Config\IConfig $config The Friendica Configuration
175          *
176          * @return Module The determined module of this call
177          *
178          * @throws \Exception
179          */
180         public function determineClass(Arguments $args, Router $router, Core\Config\IConfig $config)
181         {
182                 $printNotAllowedAddon = false;
183
184                 $module_class = null;
185                 $module_parameters = [];
186                 /**
187                  * ROUTING
188                  *
189                  * From the request URL, routing consists of obtaining the name of a BaseModule-extending class of which the
190                  * post() and/or content() static methods can be respectively called to produce a data change or an output.
191                  **/
192                 try {
193                         $module_class = $router->getModuleClass($args->getCommand());
194                         $module_parameters = $router->getModuleParameters();
195                 } catch (MethodNotAllowedException $e) {
196                         $module_class = MethodNotAllowed::class;
197                 } catch (NotFoundException $e) {
198                         // Then we try addon-provided modules that we wrap in the LegacyModule class
199                         if (Core\Addon::isEnabled($this->module) && file_exists("addon/{$this->module}/{$this->module}.php")) {
200                                 //Check if module is an app and if public access to apps is allowed or not
201                                 $privateapps = $config->get('config', 'private_addons', false);
202                                 if ((!local_user()) && Core\Hook::isAddonApp($this->module) && $privateapps) {
203                                         $printNotAllowedAddon = true;
204                                 } else {
205                                         include_once "addon/{$this->module}/{$this->module}.php";
206                                         if (function_exists($this->module . '_module')) {
207                                                 LegacyModule::setModuleFile("addon/{$this->module}/{$this->module}.php");
208                                                 $module_class = LegacyModule::class;
209                                         }
210                                 }
211                         }
212
213                         /* Finally, we look for a 'standard' program module in the 'mod' directory
214                          * We emulate a Module class through the LegacyModule class
215                          */
216                         if (!$module_class && file_exists("mod/{$this->module}.php")) {
217                                 LegacyModule::setModuleFile("mod/{$this->module}.php");
218                                 $module_class = LegacyModule::class;
219                         }
220
221                         $module_class = $module_class ?: PageNotFound::class;
222                 }
223
224                 return new Module($this->module, $module_class, $module_parameters, $this->isBackend, $printNotAllowedAddon);
225         }
226
227         /**
228          * Run the determined module class and calls all hooks applied to
229          *
230          * @param \Friendica\Core\L10n $l10n    The L10n instance
231          * @param App\BaseURL          $baseUrl The Friendica Base URL
232          * @param LoggerInterface      $logger  The Friendica logger
233          * @param array                $server  The $_SERVER variable
234          * @param array                $post    The $_POST variables
235          *
236          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
237          */
238         public function run(Core\L10n $l10n, App\BaseURL $baseUrl, LoggerInterface $logger, Profiler $profiler, array $server, array $post)
239         {
240                 if ($this->printNotAllowedAddon) {
241                         notice($l10n->t("You must be logged in to use addons. "));
242                 }
243
244                 /* The URL provided does not resolve to a valid module.
245                  *
246                  * On Dreamhost sites, quite often things go wrong for no apparent reason and they send us to '/internal_error.html'.
247                  * We don't like doing this, but as it occasionally accounts for 10-20% or more of all site traffic -
248                  * 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
249                  * this will often succeed and eventually do the right thing.
250                  *
251                  * Otherwise we are going to emit a 404 not found.
252                  */
253                 if ($this->module_class === PageNotFound::class) {
254                         $queryString = $server['QUERY_STRING'];
255                         // Stupid browser tried to pre-fetch our Javascript img template. Don't log the event or return anything - just quietly exit.
256                         if (!empty($queryString) && preg_match('/{[0-9]}/', $queryString) !== 0) {
257                                 exit();
258                         }
259
260                         if (!empty($queryString) && ($queryString === 'q=internal_error.html') && isset($dreamhost_error_hack)) {
261                                 $logger->info('index.php: dreamhost_error_hack invoked.', ['Original URI' => $server['REQUEST_URI']]);
262                                 $baseUrl->redirect($server['REQUEST_URI']);
263                         }
264
265                         $logger->debug('index.php: page not found.', ['request_uri' => $server['REQUEST_URI'], 'address' => $server['REMOTE_ADDR'], 'query' => $server['QUERY_STRING']]);
266                 }
267
268                 $placeholder = '';
269
270                 $profiler->set(microtime(true), 'ready');
271                 $timestamp = microtime(true);
272
273                 Core\Hook::callAll($this->module . '_mod_init', $placeholder);
274
275                 call_user_func([$this->module_class, 'init'], $this->module_parameters);
276
277                 $profiler->set(microtime(true) - $timestamp, 'init');
278
279                 if ($server['REQUEST_METHOD'] === 'POST') {
280                         Core\Hook::callAll($this->module . '_mod_post', $post);
281                         call_user_func([$this->module_class, 'post'], $this->module_parameters);
282                 }
283
284                 Core\Hook::callAll($this->module . '_mod_afterpost', $placeholder);
285                 call_user_func([$this->module_class, 'afterpost'], $this->module_parameters);
286
287                 // "rawContent" is especially meant for technical endpoints.
288                 // This endpoint doesn't need any theme initialization or other comparable stuff.
289                 call_user_func([$this->module_class, 'rawContent'], $this->module_parameters);
290         }
291 }