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