3 * @copyright Copyright (C) 2010-2021, the Friendica project
5 * @license GNU AGPL version 3 or any later version
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.
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.
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/>.
22 namespace Friendica\App;
26 use Friendica\Capabilities\ICanHandleRequests;
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;
40 * Holds the common context of the current, loaded module
42 class ModuleController
44 const DEFAULT = 'home';
45 const DEFAULT_CLASS = Home::class;
47 * A list of modules, which are backend methods
51 const BACKEND_MODULES = [
79 * @var string The module name
84 * @var ?ICanHandleRequests The module object
89 * @var bool true, if the module is a backend module
94 * @var bool true, if the loaded addon is private, so we have to print out not allowed
96 private $printNotAllowedAddon;
101 public function getName()
103 return $this->moduleName;
107 * @return ?ICanHandleRequests The base module object
109 public function getModule(): ?ICanHandleRequests
111 return $this->module;
115 * @return bool True, if the current module is a backend module
116 * @see ModuleController::BACKEND_MODULES for a list
118 public function isBackend()
120 return $this->isBackend;
123 public function __construct(string $moduleName = self::DEFAULT, ?ICanHandleRequests $module = null, bool $isBackend = false, bool $printNotAllowedAddon = false)
125 $this->moduleName = $moduleName;
126 $this->module = $module;
127 $this->isBackend = $isBackend;
128 $this->printNotAllowedAddon = $printNotAllowedAddon;
132 * Determines the current module based on the App arguments and the server variable
134 * @param Arguments $args The Friendica arguments
136 * @return ModuleController The module with the determined module
138 public function determineName(Arguments $args)
140 if ($args->getArgc() > 0) {
141 $module = str_replace('.', '_', $args->get(0));
142 $module = str_replace('-', '_', $module);
144 $module = self::DEFAULT;
147 // Compatibility with the Firefox App
148 if (($module == "users") && ($args->getCommand() == "users/sign_in")) {
152 $isBackend = in_array($module, ModuleController::BACKEND_MODULES);
154 return new ModuleController($module, null, $isBackend, $this->printNotAllowedAddon);
158 * Determine the class of the current module
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
165 * @return ModuleController The determined module of this call
169 public function determineClass(Arguments $args, Router $router, IManageConfigValues $config, Dice $dice)
171 $printNotAllowedAddon = false;
173 $module_class = null;
174 $module_parameters = [];
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.
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;
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;
202 /* Finally, we look for a 'standard' program module in the 'mod' directory
203 * We emulate a Module class through the LegacyModule class
205 if (!$module_class && file_exists("mod/{$this->moduleName}.php")) {
206 $module_parameters[] = "mod/{$this->moduleName}.php";
207 $module_class = LegacyModule::class;
210 $module_class = $module_class ?: PageNotFound::class;
213 /** @var ICanHandleRequests $module */
214 $module = $dice->create($module_class, $module_parameters);
216 return new ModuleController($this->moduleName, $module, $this->isBackend, $printNotAllowedAddon);
220 * Run the determined module class and calls all hooks applied to
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
228 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
230 public function run(Core\L10n $l10n, App\BaseURL $baseUrl, LoggerInterface $logger, Profiler $profiler, array $server, array $post)
232 if ($this->printNotAllowedAddon) {
233 notice($l10n->t("You must be logged in to use addons. "));
236 /* The URL provided does not resolve to a valid module.
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.
243 * Otherwise we are going to emit a 404 not found.
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) {
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']);
257 $logger->debug('index.php: page not found.', ['request_uri' => $server['REQUEST_URI'], 'address' => $server['REMOTE_ADDR'], 'query' => $server['QUERY_STRING']]);
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');
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();
293 $profiler->set(microtime(true), 'ready');
294 $timestamp = microtime(true);
296 Core\Hook::callAll($this->moduleName . '_mod_init', $placeholder);
298 $profiler->set(microtime(true) - $timestamp, 'init');
300 if ($server['REQUEST_METHOD'] === Router::DELETE) {
301 $this->module->delete();
304 if ($server['REQUEST_METHOD'] === Router::PATCH) {
305 $this->module->patch();
308 if ($server['REQUEST_METHOD'] === Router::POST) {
309 Core\Hook::callAll($this->moduleName . '_mod_post', $post);
310 $this->module->post();
313 if ($server['REQUEST_METHOD'] === Router::PUT) {
314 $this->module->put();
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();