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