]> git.mxchange.org Git - friendica.git/blob - src/App.php
Remove deprecated App::cmd - replace with DI::args()->getCommand()
[friendica.git] / src / App.php
1 <?php
2 /**
3  * @file src/App.php
4  */
5 namespace Friendica;
6
7 use Exception;
8 use Friendica\App\Arguments;
9 use Friendica\App\BaseURL;
10 use Friendica\App\Page;
11 use Friendica\App\Authentication;
12 use Friendica\Core\Config\Cache\ConfigCache;
13 use Friendica\Core\Config\Configuration;
14 use Friendica\Core\Config\PConfiguration;
15 use Friendica\Core\L10n\L10n;
16 use Friendica\Core\System;
17 use Friendica\Core\Theme;
18 use Friendica\Database\Database;
19 use Friendica\Model\Profile;
20 use Friendica\Module\Special\HTTPException as ModuleHTTPException;
21 use Friendica\Network\HTTPException;
22 use Friendica\Util\ConfigFileLoader;
23 use Friendica\Util\HTTPSignature;
24 use Friendica\Util\Profiler;
25 use Friendica\Util\Strings;
26 use Psr\Log\LoggerInterface;
27
28 /**
29  *
30  * class: App
31  *
32  * @brief Our main application structure for the life of this page.
33  *
34  * Primarily deals with the URL that got us here
35  * and tries to make some sense of it, and
36  * stores our page contents and config storage
37  * and anything else that might need to be passed around
38  * before we spit the page out.
39  *
40  */
41 class App
42 {
43         /**
44          * @var Page The current page environment
45          */
46         public $page;
47         public $profile;
48         public $profile_uid;
49         public $user;
50         public $cid;
51         public $contact;
52         public $contacts;
53         public $page_contact;
54         public $content;
55         public $data = [];
56         /** @deprecated 2019.09 - use App\Arguments->getArgv() or Arguments->get() */
57         public $argv;
58         /** @deprecated 2019.09 - use App\Arguments->getArgc() */
59         public $argc;
60         /** @deprecated 2019.09 - Use App\Module->getName() instead */
61         public $module;
62         public $timezone;
63         public $interactive = true;
64         public $identities;
65         public $theme_info = [];
66         public $category;
67         // Allow themes to control internal parameters
68         // by changing App values in theme.php
69
70         public $sourcename              = '';
71         public $videowidth              = 425;
72         public $videoheight             = 350;
73         public $force_max_items         = 0;
74         public $theme_events_in_profile = true;
75         public $queue;
76
77         /**
78          * @var App\Mode The Mode of the Application
79          */
80         private $mode;
81
82         /**
83          * @var BaseURL
84          */
85         private $baseURL;
86
87         /** @var string The name of the current theme */
88         private $currentTheme;
89         /** @var string The name of the current mobile theme */
90         private $currentMobileTheme;
91
92         /**
93          * @var Configuration The config
94          */
95         private $config;
96
97         /**
98          * @var LoggerInterface The logger
99          */
100         private $logger;
101
102         /**
103          * @var Profiler The profiler of this app
104          */
105         private $profiler;
106
107         /**
108          * @var Database The Friendica database connection
109          */
110         private $database;
111
112         /**
113          * @var L10n The translator
114          */
115         private $l10n;
116
117         /**
118          * @var App\Arguments
119          */
120         private $args;
121
122         /**
123          * @var Core\Process The process methods
124          */
125         private $process;
126
127         /**
128          * Returns the current config cache of this node
129          *
130          * @return ConfigCache
131          */
132         public function getConfigCache()
133         {
134                 return $this->config->getCache();
135         }
136
137         /**
138          * The basepath of this app
139          *
140          * @return string
141          */
142         public function getBasePath()
143         {
144                 // Don't use the basepath of the config table for basepath (it should always be the config-file one)
145                 return $this->config->getCache()->get('system', 'basepath');
146         }
147
148         /**
149          * @param Database        $database The Friendica Database
150          * @param Configuration   $config   The Configuration
151          * @param App\Mode        $mode     The mode of this Friendica app
152          * @param BaseURL         $baseURL  The full base URL of this Friendica app
153          * @param LoggerInterface $logger   The current app logger
154          * @param Profiler        $profiler The profiler of this application
155          * @param L10n            $l10n     The translator instance
156          * @param App\Arguments   $args     The Friendica Arguments of the call
157          * @param Core\Process    $process  The process methods
158          */
159         public function __construct(Database $database, Configuration $config, App\Mode $mode, BaseURL $baseURL, LoggerInterface $logger, Profiler $profiler, L10n $l10n, Arguments $args, App\Module $module, App\Page $page, Core\Process $process)
160         {
161                 $this->database = $database;
162                 $this->config   = $config;
163                 $this->mode     = $mode;
164                 $this->baseURL  = $baseURL;
165                 $this->profiler = $profiler;
166                 $this->logger   = $logger;
167                 $this->l10n     = $l10n;
168                 $this->args     = $args;
169                 $this->process  = $process;
170
171                 $this->argv         = $args->getArgv();
172                 $this->argc         = $args->getArgc();
173                 $this->module       = $module->getName();
174                 $this->page         = $page;
175
176                 $this->load();
177         }
178
179         /**
180          * Load the whole app instance
181          */
182         public function load()
183         {
184                 set_time_limit(0);
185
186                 // This has to be quite large to deal with embedded private photos
187                 ini_set('pcre.backtrack_limit', 500000);
188
189                 set_include_path(
190                         get_include_path() . PATH_SEPARATOR
191                         . $this->getBasePath() . DIRECTORY_SEPARATOR . 'include' . PATH_SEPARATOR
192                         . $this->getBasePath() . DIRECTORY_SEPARATOR . 'library' . PATH_SEPARATOR
193                         . $this->getBasePath());
194
195                 $this->profiler->reset();
196
197                 if ($this->mode->has(App\Mode::DBAVAILABLE)) {
198                         $this->profiler->update($this->config);
199
200                         Core\Hook::loadHooks();
201                         $loader = new ConfigFileLoader($this->getBasePath());
202                         Core\Hook::callAll('load_config', $loader);
203                 }
204
205                 $this->loadDefaultTimezone();
206                 // Register template engines
207                 Core\Renderer::registerTemplateEngine('Friendica\Render\FriendicaSmartyEngine');
208         }
209
210         /**
211          * Loads the default timezone
212          *
213          * Include support for legacy $default_timezone
214          *
215          * @global string $default_timezone
216          */
217         private function loadDefaultTimezone()
218         {
219                 if ($this->config->get('system', 'default_timezone')) {
220                         $this->timezone = $this->config->get('system', 'default_timezone');
221                 } else {
222                         global $default_timezone;
223                         $this->timezone = !empty($default_timezone) ? $default_timezone : 'UTC';
224                 }
225
226                 if ($this->timezone) {
227                         date_default_timezone_set($this->timezone);
228                 }
229         }
230
231         /**
232          * Returns the current UserAgent as a String
233          *
234          * @return string the UserAgent as a String
235          * @throws HTTPException\InternalServerErrorException
236          */
237         public function getUserAgent()
238         {
239                 return
240                         FRIENDICA_PLATFORM . " '" .
241                         FRIENDICA_CODENAME . "' " .
242                         FRIENDICA_VERSION . '-' .
243                         DB_UPDATE_VERSION . '; ' .
244                         $this->baseURL->get();
245         }
246
247         /**
248          * Generates the site's default sender email address
249          *
250          * @return string
251          * @throws HTTPException\InternalServerErrorException
252          */
253         public function getSenderEmailAddress()
254         {
255                 $sender_email = $this->config->get('config', 'sender_email');
256                 if (empty($sender_email)) {
257                         $hostname = $this->baseURL->getHostname();
258                         if (strpos($hostname, ':')) {
259                                 $hostname = substr($hostname, 0, strpos($hostname, ':'));
260                         }
261
262                         $sender_email = 'noreply@' . $hostname;
263                 }
264
265                 return $sender_email;
266         }
267
268         /**
269          * Returns the current theme name. May be overriden by the mobile theme name.
270          *
271          * @return string
272          * @throws Exception
273          */
274         public function getCurrentTheme()
275         {
276                 if ($this->mode->isInstall()) {
277                         return '';
278                 }
279
280                 // Specific mobile theme override
281                 if (($this->mode->isMobile() || $this->mode->isTablet()) && Core\Session::get('show-mobile', true)) {
282                         $user_mobile_theme = $this->getCurrentMobileTheme();
283
284                         // --- means same mobile theme as desktop
285                         if (!empty($user_mobile_theme) && $user_mobile_theme !== '---') {
286                                 return $user_mobile_theme;
287                         }
288                 }
289
290                 if (!$this->currentTheme) {
291                         $this->computeCurrentTheme();
292                 }
293
294                 return $this->currentTheme;
295         }
296
297         /**
298          * Returns the current mobile theme name.
299          *
300          * @return string
301          * @throws Exception
302          */
303         public function getCurrentMobileTheme()
304         {
305                 if ($this->mode->isInstall()) {
306                         return '';
307                 }
308
309                 if (is_null($this->currentMobileTheme)) {
310                         $this->computeCurrentMobileTheme();
311                 }
312
313                 return $this->currentMobileTheme;
314         }
315
316         public function setCurrentTheme($theme)
317         {
318                 $this->currentTheme = $theme;
319         }
320
321         public function setCurrentMobileTheme($theme)
322         {
323                 $this->currentMobileTheme = $theme;
324         }
325
326         /**
327          * Computes the current theme name based on the node settings, the page owner settings and the user settings
328          *
329          * @throws Exception
330          */
331         private function computeCurrentTheme()
332         {
333                 $system_theme = $this->config->get('system', 'theme');
334                 if (!$system_theme) {
335                         throw new Exception($this->l10n->t('No system theme config value set.'));
336                 }
337
338                 // Sane default
339                 $this->setCurrentTheme($system_theme);
340
341                 $page_theme = null;
342                 // Find the theme that belongs to the user whose stuff we are looking at
343                 if ($this->profile_uid && ($this->profile_uid != local_user())) {
344                         // Allow folks to override user themes and always use their own on their own site.
345                         // This works only if the user is on the same server
346                         $user = $this->database->selectFirst('user', ['theme'], ['uid' => $this->profile_uid]);
347                         if ($this->database->isResult($user) && !Core\PConfig::get(local_user(), 'system', 'always_my_theme')) {
348                                 $page_theme = $user['theme'];
349                         }
350                 }
351
352                 $theme_name = $page_theme ?: Core\Session::get('theme', $system_theme);
353
354                 $theme_name = Strings::sanitizeFilePathItem($theme_name);
355                 if ($theme_name
356                     && in_array($theme_name, Theme::getAllowedList())
357                     && (file_exists('view/theme/' . $theme_name . '/style.css')
358                         || file_exists('view/theme/' . $theme_name . '/style.php'))
359                 ) {
360                         $this->setCurrentTheme($theme_name);
361                 }
362         }
363
364         /**
365          * Computes the current mobile theme name based on the node settings, the page owner settings and the user settings
366          */
367         private function computeCurrentMobileTheme()
368         {
369                 $system_mobile_theme = $this->config->get('system', 'mobile-theme', '');
370
371                 // Sane default
372                 $this->setCurrentMobileTheme($system_mobile_theme);
373
374                 $page_mobile_theme = null;
375                 // Find the theme that belongs to the user whose stuff we are looking at
376                 if ($this->profile_uid && ($this->profile_uid != local_user())) {
377                         // Allow folks to override user themes and always use their own on their own site.
378                         // This works only if the user is on the same server
379                         if (!Core\PConfig::get(local_user(), 'system', 'always_my_theme')) {
380                                 $page_mobile_theme = Core\PConfig::get($this->profile_uid, 'system', 'mobile-theme');
381                         }
382                 }
383
384                 $mobile_theme_name = $page_mobile_theme ?: Core\Session::get('mobile-theme', $system_mobile_theme);
385
386                 $mobile_theme_name = Strings::sanitizeFilePathItem($mobile_theme_name);
387                 if ($mobile_theme_name == '---'
388                         ||
389                         in_array($mobile_theme_name, Theme::getAllowedList())
390                         && (file_exists('view/theme/' . $mobile_theme_name . '/style.css')
391                                 || file_exists('view/theme/' . $mobile_theme_name . '/style.php'))
392                 ) {
393                         $this->setCurrentMobileTheme($mobile_theme_name);
394                 }
395         }
396
397         /**
398          * @brief Return full URL to theme which is currently in effect.
399          *
400          * Provide a sane default if nothing is chosen or the specified theme does not exist.
401          *
402          * @return string
403          * @throws Exception
404          */
405         public function getCurrentThemeStylesheetPath()
406         {
407                 return Core\Theme::getStylesheetPath($this->getCurrentTheme());
408         }
409
410         /**
411          * Sets the base url for use in cmdline programs which don't have
412          * $_SERVER variables
413          */
414         public function checkURL()
415         {
416                 $url = $this->config->get('system', 'url');
417
418                 // if the url isn't set or the stored url is radically different
419                 // than the currently visited url, store the current value accordingly.
420                 // "Radically different" ignores common variations such as http vs https
421                 // and www.example.com vs example.com.
422                 // We will only change the url to an ip address if there is no existing setting
423
424                 if (empty($url) || (!Util\Strings::compareLink($url, $this->baseURL->get())) && (!preg_match("/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/", $this->baseURL->getHostname()))) {
425                         $this->config->set('system', 'url', $this->baseURL->get());
426                 }
427         }
428
429         /**
430          * Frontend App script
431          *
432          * The App object behaves like a container and a dispatcher at the same time, including a representation of the
433          * request and a representation of the response.
434          *
435          * This probably should change to limit the size of this monster method.
436          *
437          * @param App\Module     $module The determined module
438          * @param App\Router     $router
439          * @param PConfiguration $pconfig
440          * @param Authentication $auth The Authentication backend of the node
441          * @throws HTTPException\InternalServerErrorException
442          * @throws \ImagickException
443          */
444         public function runFrontend(App\Module $module, App\Router $router, PConfiguration $pconfig, Authentication $auth)
445         {
446                 $moduleName = $module->getName();
447
448                 try {
449                         // Missing DB connection: ERROR
450                         if ($this->mode->has(App\Mode::LOCALCONFIGPRESENT) && !$this->mode->has(App\Mode::DBAVAILABLE)) {
451                                 throw new HTTPException\InternalServerErrorException('Apologies but the website is unavailable at the moment.');
452                         }
453
454                         // Max Load Average reached: ERROR
455                         if ($this->process->isMaxProcessesReached() || $this->process->isMaxLoadReached()) {
456                                 header('Retry-After: 120');
457                                 header('Refresh: 120; url=' . $this->baseURL->get() . "/" . $this->args->getQueryString());
458
459                                 throw new HTTPException\ServiceUnavailableException('The node is currently overloaded. Please try again later.');
460                         }
461
462                         if (!$this->mode->isInstall()) {
463                                 // Force SSL redirection
464                                 if ($this->baseURL->checkRedirectHttps()) {
465                                         System::externalRedirect($this->baseURL->get() . '/' . $this->args->getQueryString());
466                                 }
467
468                                 Core\Hook::callAll('init_1');
469                         }
470
471                         // Exclude the backend processes from the session management
472                         if ($this->mode->isBackend()) {
473                                 Core\Worker::executeIfIdle();
474                         }
475
476                         if ($this->mode->isNormal()) {
477                                 $requester = HTTPSignature::getSigner('', $_SERVER);
478                                 if (!empty($requester)) {
479                                         Profile::addVisitorCookieForHandle($requester);
480                                 }
481                         }
482
483                         // ZRL
484                         if (!empty($_GET['zrl']) && $this->mode->isNormal()) {
485                                 if (!local_user()) {
486                                         // Only continue when the given profile link seems valid
487                                         // Valid profile links contain a path with "/profile/" and no query parameters
488                                         if ((parse_url($_GET['zrl'], PHP_URL_QUERY) == "") &&
489                                             strstr(parse_url($_GET['zrl'], PHP_URL_PATH), "/profile/")) {
490                                                 if (Core\Session::get('visitor_home') != $_GET["zrl"]) {
491                                                         Core\Session::set('my_url', $_GET['zrl']);
492                                                         Core\Session::set('authenticated', 0);
493                                                 }
494
495                                                 Model\Profile::zrlInit($this);
496                                         } else {
497                                                 // Someone came with an invalid parameter, maybe as a DDoS attempt
498                                                 // We simply stop processing here
499                                                 $this->logger->debug('Invalid ZRL parameter.', ['zrl' => $_GET['zrl']]);
500                                                 throw new HTTPException\ForbiddenException();
501                                         }
502                                 }
503                         }
504
505                         if (!empty($_GET['owt']) && $this->mode->isNormal()) {
506                                 $token = $_GET['owt'];
507                                 Model\Profile::openWebAuthInit($token);
508                         }
509
510                         $auth->withSession($this);
511
512                         if (empty($_SESSION['authenticated'])) {
513                                 header('X-Account-Management-Status: none');
514                         }
515
516                         $_SESSION['sysmsg']       = Core\Session::get('sysmsg', []);
517                         $_SESSION['sysmsg_info']  = Core\Session::get('sysmsg_info', []);
518                         $_SESSION['last_updated'] = Core\Session::get('last_updated', []);
519
520                         /*
521                          * check_config() is responsible for running update scripts. These automatically
522                          * update the DB schema whenever we push a new one out. It also checks to see if
523                          * any addons have been added or removed and reacts accordingly.
524                          */
525
526                         // in install mode, any url loads install module
527                         // but we need "view" module for stylesheet
528                         if ($this->mode->isInstall() && $moduleName !== 'install') {
529                                 $this->baseURL->redirect('install');
530                         } elseif (!$this->mode->isInstall() && !$this->mode->has(App\Mode::MAINTENANCEDISABLED) && $moduleName !== 'maintenance') {
531                                 $this->baseURL->redirect('maintenance');
532                         } else {
533                                 $this->checkURL();
534                                 Core\Update::check($this->getBasePath(), false, $this->mode);
535                                 Core\Addon::loadAddons();
536                                 Core\Hook::loadHooks();
537                         }
538
539                         // Compatibility with the Android Diaspora client
540                         if ($moduleName == 'stream') {
541                                 $this->baseURL->redirect('network?order=post');
542                         }
543
544                         if ($moduleName == 'conversations') {
545                                 $this->baseURL->redirect('message');
546                         }
547
548                         if ($moduleName == 'commented') {
549                                 $this->baseURL->redirect('network?order=comment');
550                         }
551
552                         if ($moduleName == 'liked') {
553                                 $this->baseURL->redirect('network?order=comment');
554                         }
555
556                         if ($moduleName == 'activity') {
557                                 $this->baseURL->redirect('network?conv=1');
558                         }
559
560                         if (($moduleName == 'status_messages') && ($this->args->getCommand() == 'status_messages/new')) {
561                                 $this->baseURL->redirect('bookmarklet');
562                         }
563
564                         if (($moduleName == 'user') && ($this->args->getCommand() == 'user/edit')) {
565                                 $this->baseURL->redirect('settings');
566                         }
567
568                         if (($moduleName == 'tag_followings') && ($this->args->getCommand() == 'tag_followings/manage')) {
569                                 $this->baseURL->redirect('search');
570                         }
571
572                         // Initialize module that can set the current theme in the init() method, either directly or via App->profile_uid
573                         $this->page['page_title'] = $moduleName;
574
575                         // determine the module class and save it to the module instance
576                         // @todo there's an implicit dependency due SESSION::start(), so it has to be called here (yet)
577                         $module = $module->determineClass($this->args, $router, $this->config);
578
579                         // Let the module run it's internal process (init, get, post, ...)
580                         $module->run($this->l10n, $this->baseURL, $this->logger, $_SERVER, $_POST);
581                 } catch (HTTPException $e) {
582                         ModuleHTTPException::rawContent($e);
583                 }
584
585                 $this->page->run($this, $this->baseURL, $this->mode, $module, $this->l10n, $this->config, $pconfig);
586         }
587
588         /**
589          * Automatically redirects to relative or absolute URL
590          * Should only be used if it isn't clear if the URL is either internal or external
591          *
592          * @param string $toUrl The target URL
593          *
594          * @throws HTTPException\InternalServerErrorException
595          */
596         public function redirect($toUrl)
597         {
598                 if (!empty(parse_url($toUrl, PHP_URL_SCHEME))) {
599                         Core\System::externalRedirect($toUrl);
600                 } else {
601                         $this->baseURL->redirect($toUrl);
602                 }
603         }
604 }