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 class
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);
157 return new ModuleController($module, null, $isBackend, $this->printNotAllowedAddon);
161 * Determine the class of the current module
163 * @param Arguments $args The Friendica execution arguments
164 * @param Router $router The Friendica routing instance
165 * @param IManageConfigValues $config The Friendica Configuration
166 * @param Dice $dice The Dependency Injection container
168 * @return ModuleController The determined module of this call
172 public function determineClass(Arguments $args, Router $router, IManageConfigValues $config, Dice $dice)
174 $printNotAllowedAddon = false;
176 $module_class = null;
177 $module_parameters = [];
181 * From the request URL, routing consists of obtaining the name of a BaseModule-extending class of which the
182 * post() and/or content() static methods can be respectively called to produce a data change or an output.
185 $module_class = $router->getModuleClass($args->getCommand());
186 $module_parameters[] = $router->getModuleParameters();
187 } catch (MethodNotAllowedException $e) {
188 $module_class = MethodNotAllowed::class;
189 } catch (NotFoundException $e) {
190 // Then we try addon-provided modules that we wrap in the LegacyModule class
191 if (Core\Addon::isEnabled($this->moduleName) && file_exists("addon/{$this->moduleName}/{$this->moduleName}.php")) {
192 //Check if module is an app and if public access to apps is allowed or not
193 $privateapps = $config->get('config', 'private_addons', false);
194 if ((!local_user()) && Core\Hook::isAddonApp($this->moduleName) && $privateapps) {
195 $printNotAllowedAddon = true;
197 include_once "addon/{$this->moduleName}/{$this->moduleName}.php";
198 if (function_exists($this->moduleName . '_module')) {
199 $module_parameters[] = "addon/{$this->moduleName}/{$this->moduleName}.php";
200 $module_class = LegacyModule::class;
205 /* Finally, we look for a 'standard' program module in the 'mod' directory
206 * We emulate a Module class through the LegacyModule class
208 if (!$module_class && file_exists("mod/{$this->moduleName}.php")) {
209 $module_parameters[] = "mod/{$this->moduleName}.php";
210 $module_class = LegacyModule::class;
213 $module_class = $module_class ?: PageNotFound::class;
216 /** @var ICanHandleRequests $module */
217 $module = $dice->create($module_class, $module_parameters);
219 return new ModuleController($this->moduleName, $module, $this->isBackend, $printNotAllowedAddon);
223 * Run the determined module class and calls all hooks applied to
225 * @param \Friendica\Core\L10n $l10n The L10n instance
226 * @param App\BaseURL $baseUrl The Friendica Base URL
227 * @param LoggerInterface $logger The Friendica logger
228 * @param array $server The $_SERVER variable
229 * @param array $post The $_POST variables
231 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
233 public function run(Core\L10n $l10n, App\BaseURL $baseUrl, LoggerInterface $logger, Profiler $profiler, array $server, array $post)
235 if ($this->printNotAllowedAddon) {
236 notice($l10n->t("You must be logged in to use addons. "));
239 /* The URL provided does not resolve to a valid module.
241 * On Dreamhost sites, quite often things go wrong for no apparent reason and they send us to '/internal_error.html'.
242 * We don't like doing this, but as it occasionally accounts for 10-20% or more of all site traffic -
243 * 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
244 * this will often succeed and eventually do the right thing.
246 * Otherwise we are going to emit a 404 not found.
248 if ($this->module === PageNotFound::class) {
249 $queryString = $server['QUERY_STRING'];
250 // Stupid browser tried to pre-fetch our Javascript img template. Don't log the event or return anything - just quietly exit.
251 if (!empty($queryString) && preg_match('/{[0-9]}/', $queryString) !== 0) {
255 if (!empty($queryString) && ($queryString === 'q=internal_error.html') && isset($dreamhost_error_hack)) {
256 $logger->info('index.php: dreamhost_error_hack invoked.', ['Original URI' => $server['REQUEST_URI']]);
257 $baseUrl->redirect($server['REQUEST_URI']);
260 $logger->debug('index.php: page not found.', ['request_uri' => $server['REQUEST_URI'], 'address' => $server['REMOTE_ADDR'], 'query' => $server['QUERY_STRING']]);
263 // @see https://github.com/tootsuite/mastodon/blob/c3aef491d66aec743a3a53e934a494f653745b61/config/initializers/cors.rb
264 if (substr($_REQUEST['pagename'] ?? '', 0, 12) == '.well-known/') {
265 header('Access-Control-Allow-Origin: *');
266 header('Access-Control-Allow-Headers: *');
267 header('Access-Control-Allow-Methods: ' . Router::GET);
268 header('Access-Control-Allow-Credentials: false');
269 } elseif (substr($_REQUEST['pagename'] ?? '', 0, 8) == 'profile/') {
270 header('Access-Control-Allow-Origin: *');
271 header('Access-Control-Allow-Headers: *');
272 header('Access-Control-Allow-Methods: ' . Router::GET);
273 header('Access-Control-Allow-Credentials: false');
274 } elseif (substr($_REQUEST['pagename'] ?? '', 0, 4) == 'api/') {
275 header('Access-Control-Allow-Origin: *');
276 header('Access-Control-Allow-Headers: *');
277 header('Access-Control-Allow-Methods: ' . implode(',', Router::ALLOWED_METHODS));
278 header('Access-Control-Allow-Credentials: false');
279 header('Access-Control-Expose-Headers: Link');
280 } elseif (substr($_REQUEST['pagename'] ?? '', 0, 11) == 'oauth/token') {
281 header('Access-Control-Allow-Origin: *');
282 header('Access-Control-Allow-Headers: *');
283 header('Access-Control-Allow-Methods: ' . Router::POST);
284 header('Access-Control-Allow-Credentials: false');
287 // @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/OPTIONS
288 // @todo Check allowed methods per requested path
289 if ($server['REQUEST_METHOD'] === Router::OPTIONS) {
290 header('Allow: ' . implode(',', Router::ALLOWED_METHODS));
291 throw new NoContentException();
296 $profiler->set(microtime(true), 'ready');
297 $timestamp = microtime(true);
299 Core\Hook::callAll($this->moduleName . '_mod_init', $placeholder);
301 $this->module->init();
303 $profiler->set(microtime(true) - $timestamp, 'init');
305 if ($server['REQUEST_METHOD'] === Router::DELETE) {
306 $this->module->delete();
309 if ($server['REQUEST_METHOD'] === Router::PATCH) {
310 $this->module->patch();
313 if ($server['REQUEST_METHOD'] === Router::POST) {
314 Core\Hook::callAll($this->moduleName . '_mod_post', $post);
315 $this->module->post();
318 if ($server['REQUEST_METHOD'] === Router::PUT) {
319 $this->module->put();
322 // "rawContent" is especially meant for technical endpoints.
323 // This endpoint doesn't need any theme initialization or other comparable stuff.
324 $this->module->rawContent();