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