Merge remote-tracking branch 'upstream/develop' into item-permissions
[friendica.git/.git] / index.php
1 <?php
2 /**
3  * @file index.php
4  * Friendica
5  */
6
7 /**
8  * Bootstrap the application
9  */
10
11 use Friendica\App;
12 use Friendica\BaseObject;
13 use Friendica\Content\Nav;
14 use Friendica\Core\Addon;
15 use Friendica\Core\System;
16 use Friendica\Core\Theme;
17 use Friendica\Core\Config;
18 use Friendica\Core\Worker;
19 use Friendica\Database\DBM;
20 use Friendica\Model\Profile;
21 use Friendica\Module\Login;
22
23 require_once 'boot.php';
24
25 if (empty($a)) {
26         $a = new App(__DIR__);
27 }
28 BaseObject::setApp($a);
29
30 // We assume that the index.php is called by a frontend process
31 // The value is set to "true" by default in boot.php
32 $a->backend = false;
33
34 /**
35  * Load the configuration file which contains our DB credentials.
36  * Ignore errors. If the file doesn't exist or is empty, we are running in
37  * installation mode.
38  */
39
40 $install = ((file_exists('.htconfig.php') && filesize('.htconfig.php')) ? false : true);
41
42 // Only load config if found, don't surpress errors
43 if (!$install) {
44         include ".htconfig.php";
45 }
46
47 /**
48  * Try to open the database;
49  */
50
51 require_once "include/dba.php";
52
53 if (!$install) {
54         dba::connect($db_host, $db_user, $db_pass, $db_data, $install);
55         unset($db_host, $db_user, $db_pass, $db_data);
56
57         /**
58          * Load configs from db. Overwrite configs from .htconfig.php
59          */
60
61         Config::load();
62
63         if ($a->max_processes_reached() || $a->maxload_reached()) {
64                 header($_SERVER["SERVER_PROTOCOL"] . ' 503 Service Temporarily Unavailable');
65                 header('Retry-After: 120');
66                 header('Refresh: 120; url=' . System::baseUrl() . "/" . $a->query_string);
67                 die("System is currently unavailable. Please try again later");
68         }
69
70         if (Config::get('system', 'force_ssl') && ($a->get_scheme() == "http")
71                 && (intval(Config::get('system', 'ssl_policy')) == SSL_POLICY_FULL)
72                 && (substr(System::baseUrl(), 0, 8) == "https://")
73         ) {
74                 header("HTTP/1.1 302 Moved Temporarily");
75                 header("Location: " . System::baseUrl() . "/" . $a->query_string);
76                 exit();
77         }
78
79         require_once 'include/session.php';
80         Addon::loadHooks();
81         Addon::callHooks('init_1');
82
83         $maintenance = Config::get('system', 'maintenance');
84 }
85
86 $lang = get_browser_language();
87
88 load_translation_table($lang);
89
90 /**
91  * Important stuff we always need to do.
92  *
93  * The order of these may be important so use caution if you think they're all
94  * intertwingled with no logical order and decide to sort it out. Some of the
95  * dependencies have changed, but at least at one time in the recent past - the
96  * order was critical to everything working properly
97  */
98
99 // Exclude the backend processes from the session management
100 if (!$a->is_backend()) {
101         $stamp1 = microtime(true);
102         session_start();
103         $a->save_timestamp($stamp1, "parser");
104 } else {
105         $_SESSION = [];
106         Worker::executeIfIdle();
107 }
108
109 /**
110  * Language was set earlier, but we can over-ride it in the session.
111  * We have to do it here because the session was just now opened.
112  */
113 if (x($_SESSION, 'authenticated') && !x($_SESSION, 'language')) {
114         // we haven't loaded user data yet, but we need user language
115         $user = dba::selectFirst('user', ['language'], ['uid' => $_SESSION['uid']]);
116         $_SESSION['language'] = $lang;
117         if (DBM::is_result($user)) {
118                 $_SESSION['language'] = $user['language'];
119         }
120 }
121
122 if ((x($_SESSION, 'language')) && ($_SESSION['language'] !== $lang)) {
123         $lang = $_SESSION['language'];
124         load_translation_table($lang);
125 }
126
127 if ((x($_GET, 'zrl')) && (!$install && !$maintenance)) {
128         // Only continue when the given profile link seems valid
129         // Valid profile links contain a path with "/profile/" and no query parameters
130         if ((parse_url($_GET['zrl'], PHP_URL_QUERY) == "")
131                 && strstr(parse_url($_GET['zrl'], PHP_URL_PATH), "/profile/")
132         ) {
133                 $_SESSION['my_url'] = $_GET['zrl'];
134                 $a->query_string = preg_replace('/[\?&]zrl=(.*?)([\?&]|$)/is', '', $a->query_string);
135                 Profile::zrlInit($a);
136         } else {
137                 // Someone came with an invalid parameter, maybe as a DDoS attempt
138                 // We simply stop processing here
139                 logger("Invalid ZRL parameter ".$_GET['zrl'], LOGGER_DEBUG);
140                 header('HTTP/1.1 403 Forbidden');
141                 echo "<h1>403 Forbidden</h1>";
142                 killme();
143         }
144 }
145
146 /**
147  * For Mozilla auth manager - still needs sorting, and this might conflict with LRDD header.
148  * Apache/PHP lumps the Link: headers into one - and other services might not be able to parse it
149  * this way. There's a PHP flag to link the headers because by default this will over-write any other
150  * link header.
151  *
152  * What we really need to do is output the raw headers ourselves so we can keep them separate.
153  */
154
155 // header('Link: <' . System::baseUrl() . '/amcd>; rel="acct-mgmt";');
156
157 Login::sessionAuth();
158
159 if (! x($_SESSION, 'authenticated')) {
160         header('X-Account-Management-Status: none');
161 }
162
163 /* set up page['htmlhead'] and page['end'] for the modules to use */
164 $a->page['htmlhead'] = '';
165 $a->page['end'] = '';
166
167
168 if (! x($_SESSION, 'sysmsg')) {
169         $_SESSION['sysmsg'] = [];
170 }
171
172 if (! x($_SESSION, 'sysmsg_info')) {
173         $_SESSION['sysmsg_info'] = [];
174 }
175
176 // Array for informations about last received items
177 if (! x($_SESSION, 'last_updated')) {
178         $_SESSION['last_updated'] = [];
179 }
180 /*
181  * check_config() is responsible for running update scripts. These automatically
182  * update the DB schema whenever we push a new one out. It also checks to see if
183  * any addons have been added or removed and reacts accordingly.
184  */
185
186 // in install mode, any url loads install module
187 // but we need "view" module for stylesheet
188 if ($install && $a->module!="view") {
189         $a->module = 'install';
190 } elseif ($maintenance && $a->module!="view") {
191         $a->module = 'maintenance';
192 } else {
193         check_url($a);
194         check_db(false);
195         check_addons($a);
196 }
197
198 Nav::setSelected('nothing');
199
200 //Don't populate apps_menu if apps are private
201 $privateapps = Config::get('config', 'private_addons');
202 if ((local_user()) || (! $privateapps === "1")) {
203         $arr = ['app_menu' => $a->apps];
204
205         Addon::callHooks('app_menu', $arr);
206
207         $a->apps = $arr['app_menu'];
208 }
209
210 /**
211  * We have already parsed the server path into $a->argc and $a->argv
212  *
213  * $a->argv[0] is our module name. We will load the file mod/{$a->argv[0]}.php
214  * and use it for handling our URL request.
215  * The module file contains a few functions that we call in various circumstances
216  * and in the following order:
217  *
218  * "module"_init
219  * "module"_post (only called if there are $_POST variables)
220  * "module"_afterpost
221  * "module"_content - the string return of this function contains our page body
222  *
223  * Modules which emit other serialisations besides HTML (XML,JSON, etc.) should do
224  * so within the module init and/or post functions and then invoke killme() to terminate
225  * further processing.
226  */
227 if (strlen($a->module)) {
228
229         /**
230          * We will always have a module name.
231          * First see if we have an addon which is masquerading as a module.
232          */
233
234         // Compatibility with the Android Diaspora client
235         if ($a->module == "stream") {
236                 $a->module = "network";
237         }
238
239         // Compatibility with the Firefox App
240         if (($a->module == "users") && ($a->cmd == "users/sign_in")) {
241                 $a->module = "login";
242         }
243
244         $privateapps = Config::get('config', 'private_addons');
245
246         if (is_array($a->addons) && in_array($a->module, $a->addons) && file_exists("addon/{$a->module}/{$a->module}.php")) {
247                 //Check if module is an app and if public access to apps is allowed or not
248                 if ((!local_user()) && Addon::isApp($a->module) && $privateapps === "1") {
249                         info(t("You must be logged in to use addons. "));
250                 } else {
251                         include_once "addon/{$a->module}/{$a->module}.php";
252                         if (function_exists($a->module . '_module')) {
253                                 $a->module_loaded = true;
254                         }
255                 }
256         }
257
258         // Controller class routing
259         if (! $a->module_loaded && class_exists('Friendica\\Module\\' . ucfirst($a->module))) {
260                 $a->module_class = 'Friendica\\Module\\' . ucfirst($a->module);
261                 $a->module_loaded = true;
262         }
263
264         /**
265          * If not, next look for a 'standard' program module in the 'mod' directory
266          */
267
268         if (! $a->module_loaded && file_exists("mod/{$a->module}.php")) {
269                 include_once "mod/{$a->module}.php";
270                 $a->module_loaded = true;
271         }
272
273         /**
274          * The URL provided does not resolve to a valid module.
275          *
276          * On Dreamhost sites, quite often things go wrong for no apparent reason and they send us to '/internal_error.html'.
277          * We don't like doing this, but as it occasionally accounts for 10-20% or more of all site traffic -
278          * 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
279          * this will often succeed and eventually do the right thing.
280          *
281          * Otherwise we are going to emit a 404 not found.
282          */
283
284         if (! $a->module_loaded) {
285                 // Stupid browser tried to pre-fetch our Javascript img template. Don't log the event or return anything - just quietly exit.
286                 if ((x($_SERVER, 'QUERY_STRING')) && preg_match('/{[0-9]}/', $_SERVER['QUERY_STRING']) !== 0) {
287                         killme();
288                 }
289
290                 if ((x($_SERVER, 'QUERY_STRING')) && ($_SERVER['QUERY_STRING'] === 'q=internal_error.html') && isset($dreamhost_error_hack)) {
291                         logger('index.php: dreamhost_error_hack invoked. Original URI =' . $_SERVER['REQUEST_URI']);
292                         goaway(System::baseUrl() . $_SERVER['REQUEST_URI']);
293                 }
294
295                 logger('index.php: page not found: ' . $_SERVER['REQUEST_URI'] . ' ADDRESS: ' . $_SERVER['REMOTE_ADDR'] . ' QUERY: ' . $_SERVER['QUERY_STRING'], LOGGER_DEBUG);
296                 header($_SERVER["SERVER_PROTOCOL"] . ' 404 ' . t('Not Found'));
297                 $tpl = get_markup_template("404.tpl");
298                 $a->page['content'] = replace_macros(
299                         $tpl,
300                         [
301                         '$message' =>  t('Page not found.')]
302                 );
303         }
304 }
305
306 /**
307  * Load current theme info
308  */
309 $theme_info_file = "view/theme/".current_theme()."/theme.php";
310 if (file_exists($theme_info_file)) {
311         require_once $theme_info_file;
312 }
313
314
315 /* initialise content region */
316
317 if (! x($a->page, 'content')) {
318         $a->page['content'] = '';
319 }
320
321 if (!$install && !$maintenance) {
322         Addon::callHooks('page_content_top', $a->page['content']);
323 }
324
325 /**
326  * Call module functions
327  */
328
329 if ($a->module_loaded) {
330         $a->page['page_title'] = $a->module;
331         $placeholder = '';
332
333         if ($a->module_class) {
334                 Addon::callHooks($a->module . '_mod_init', $placeholder);
335                 call_user_func([$a->module_class, 'init']);
336         } else if (function_exists($a->module . '_init')) {
337                 Addon::callHooks($a->module . '_mod_init', $placeholder);
338                 $func = $a->module . '_init';
339                 $func($a);
340         }
341
342         if (function_exists(str_replace('-', '_', current_theme()) . '_init')) {
343                 $func = str_replace('-', '_', current_theme()) . '_init';
344                 $func($a);
345         }
346
347         if (! $a->error && $_SERVER['REQUEST_METHOD'] === 'POST') {
348                 Addon::callHooks($a->module . '_mod_post', $_POST);
349                 if ($a->module_class) {
350                         call_user_func([$a->module_class, 'post']);
351                 } else if (function_exists($a->module . '_post')) {
352                         $func = $a->module . '_post';
353                         $func($a);
354                 }
355         }
356
357         if (! $a->error) {
358                 Addon::callHooks($a->module . '_mod_afterpost', $placeholder);
359                 if ($a->module_class) {
360                         call_user_func([$a->module_class, 'afterpost']);
361                 } else if (function_exists($a->module . '_afterpost')) {
362                         $func = $a->module . '_afterpost';
363                         $func($a);
364                 }
365         }
366
367         if (! $a->error) {
368                 $arr = ['content' => $a->page['content']];
369                 Addon::callHooks($a->module . '_mod_content', $arr);
370                 $a->page['content'] = $arr['content'];
371                 if ($a->module_class) {
372                         $arr = ['content' => call_user_func([$a->module_class, 'content'])];
373                 } else if (function_exists($a->module . '_content')) {
374                         $func = $a->module . '_content';
375                         $arr = ['content' => $func($a)];
376                 }
377                 Addon::callHooks($a->module . '_mod_aftercontent', $arr);
378                 $a->page['content'] .= $arr['content'];
379         }
380
381         if (function_exists(str_replace('-', '_', current_theme()) . '_content_loaded')) {
382                 $func = str_replace('-', '_', current_theme()) . '_content_loaded';
383                 $func($a);
384         }
385 }
386
387 /*
388  * Create the page head after setting the language
389  * and getting any auth credentials.
390  *
391  * Moved init_pagehead() and init_page_end() to after
392  * all the module functions have executed so that all
393  * theme choices made by the modules can take effect.
394  */
395
396 $a->init_pagehead();
397
398 /*
399  * Build the page ending -- this is stuff that goes right before
400  * the closing </body> tag
401  */
402 $a->init_page_end();
403
404 // If you're just visiting, let javascript take you home
405 if (x($_SESSION, 'visitor_home')) {
406         $homebase = $_SESSION['visitor_home'];
407 } elseif (local_user()) {
408         $homebase = 'profile/' . $a->user['nickname'];
409 }
410
411 if (isset($homebase)) {
412         $a->page['content'] .= '<script>var homebase="' . $homebase . '" ; </script>';
413 }
414
415 /*
416  * now that we've been through the module content, see if the page reported
417  * a permission problem and if so, a 403 response would seem to be in order.
418  */
419 if (stristr(implode("", $_SESSION['sysmsg']), t('Permission denied'))) {
420         header($_SERVER["SERVER_PROTOCOL"] . ' 403 ' . t('Permission denied.'));
421 }
422
423 /*
424  * Report anything which needs to be communicated in the notification area (before the main body)
425  */
426 Addon::callHooks('page_end', $a->page['content']);
427
428 /*
429  * Add the navigation (menu) template
430  */
431 if ($a->module != 'install' && $a->module != 'maintenance') {
432         Nav::build($a);
433 }
434
435 /*
436  * Add a "toggle mobile" link if we're using a mobile device
437  */
438 if ($a->is_mobile || $a->is_tablet) {
439         if (isset($_SESSION['show-mobile']) && !$_SESSION['show-mobile']) {
440                 $link = 'toggle_mobile?address=' . curPageURL();
441         } else {
442                 $link = 'toggle_mobile?off=1&address=' . curPageURL();
443         }
444         $a->page['footer'] = replace_macros(
445                 get_markup_template("toggle_mobile_footer.tpl"),
446                 [
447                         '$toggle_link' => $link,
448                         '$toggle_text' => t('toggle mobile')]
449         );
450 }
451
452 /**
453  * Build the page - now that we have all the components
454  */
455
456 if (!$a->theme['stylesheet']) {
457         $stylesheet = current_theme_url();
458 } else {
459         $stylesheet = $a->theme['stylesheet'];
460 }
461
462 $a->page['htmlhead'] = str_replace('{{$stylesheet}}', $stylesheet, $a->page['htmlhead']);
463 //$a->page['htmlhead'] = replace_macros($a->page['htmlhead'], array('$stylesheet' => $stylesheet));
464
465 if (isset($_GET["mode"]) && (($_GET["mode"] == "raw") || ($_GET["mode"] == "minimal"))) {
466         $doc = new DOMDocument();
467
468         $target = new DOMDocument();
469         $target->loadXML("<root></root>");
470
471         $content = mb_convert_encoding($a->page["content"], 'HTML-ENTITIES', "UTF-8");
472
473         /// @TODO one day, kill those error-surpressing @ stuff, or PHP should ban it
474         @$doc->loadHTML($content);
475
476         $xpath = new DomXPath($doc);
477
478         $list = $xpath->query("//*[contains(@id,'tread-wrapper-')]");  /* */
479
480         foreach ($list as $item) {
481                 $item = $target->importNode($item, true);
482
483                 // And then append it to the target
484                 $target->documentElement->appendChild($item);
485         }
486 }
487
488 if (isset($_GET["mode"]) && ($_GET["mode"] == "raw")) {
489         header("Content-type: text/html; charset=utf-8");
490
491         echo substr($target->saveHTML(), 6, -8);
492
493         killme();
494 }
495
496 $page    = $a->page;
497 $profile = $a->profile;
498
499 header("X-Friendica-Version: " . FRIENDICA_VERSION);
500 header("Content-type: text/html; charset=utf-8");
501
502 if (Config::get('system', 'hsts') && (Config::get('system', 'ssl_policy') == SSL_POLICY_FULL)) {
503         header("Strict-Transport-Security: max-age=31536000");
504 }
505
506 // Some security stuff
507 header('X-Content-Type-Options: nosniff');
508 header('X-XSS-Protection: 1; mode=block');
509 header('X-Permitted-Cross-Domain-Policies: none');
510 header('X-Frame-Options: sameorigin');
511
512 // Things like embedded OSM maps don't work, when this is enabled
513 // header("Content-Security-Policy: default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; connect-src 'self'; style-src 'self' 'unsafe-inline'; font-src 'self'; img-src 'self' https: data:; media-src 'self' https:; child-src 'self' https:; object-src 'none'");
514
515 /*
516  * We use $_GET["mode"] for special page templates. So we will check if we have
517  * to load another page template than the default one.
518  * The page templates are located in /view/php/ or in the theme directory.
519  */
520 if (isset($_GET["mode"])) {
521         $template = Theme::getPathForFile($_GET["mode"] . '.php');
522 }
523
524 // If there is no page template use the default page template
525 if (empty($template)) {
526         $template = Theme::getPathForFile("default.php");
527 }
528
529 /// @TODO Looks unsafe (remote-inclusion), is maybe not but Theme::getPathForFile() uses file_exists() but does not escape anything
530 require_once $template;
531
532 killme();