Merge pull request #2190 from annando/1512-getload
[friendica.git] / index.php
1 <?php
2
3
4 /**
5  *
6  * Friendica
7  *
8  */
9
10 /**
11  *
12  * bootstrap the application
13  *
14  */
15
16 require_once('boot.php');
17 require_once('object/BaseObject.php');
18
19 $a = new App;
20 BaseObject::set_app($a);
21
22 /**
23  *
24  * Load the configuration file which contains our DB credentials.
25  * Ignore errors. If the file doesn't exist or is empty, we are running in installation mode.
26  *
27  */
28
29 $install = ((file_exists('.htconfig.php') && filesize('.htconfig.php')) ? false : true);
30
31 @include(".htconfig.php");
32
33
34
35
36
37 /**
38  *
39  * Try to open the database;
40  *
41  */
42
43 require_once("include/dba.php");
44
45 if(!$install) {
46         $db = new dba($db_host, $db_user, $db_pass, $db_data, $install);
47             unset($db_host, $db_user, $db_pass, $db_data);
48
49         /**
50          * Load configs from db. Overwrite configs from .htconfig.php
51          */
52
53         load_config('config');
54         load_config('system');
55
56         $maxsysload_frontend = intval(get_config('system','maxloadavg_frontend'));
57         if($maxsysload_frontend < 1)
58                 $maxsysload_frontend = 50;
59
60         $load = current_load();
61         if($load) {
62                 if($load > $maxsysload_frontend) {
63                         logger('system: load ' . $load . ' too high. Service Temporarily Unavailable.');
64                         header($_SERVER["SERVER_PROTOCOL"].' 503 Service Temporarily Unavailable');
65                         header('Retry-After: 300');
66                         die("System is currently unavailable. Please try again later");
67                 }
68         }
69
70
71         if (get_config('system','force_ssl') AND ($a->get_scheme() == "http") AND
72                 (intval(get_config('system','ssl_policy')) == SSL_POLICY_FULL) AND
73                 (substr($a->get_baseurl(), 0, 8) == "https://")) {
74                 header("HTTP/1.1 302 Moved Temporarily");
75                 header("location: ".$a->get_baseurl()."/".$a->query_string);
76         }
77
78         require_once("include/session.php");
79         load_hooks();
80         call_hooks('init_1');
81
82         $maintenance = get_config('system', 'maintenance');
83 }
84
85 $lang = get_browser_language();
86
87 load_translation_table($lang);
88
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
100 session_start();
101
102 /**
103  * Language was set earlier, but we can over-ride it in the session.
104  * We have to do it here because the session was just now opened.
105  */
106 if (x($_SESSION,'authenticated') && !x($_SESSION,'language')) {
107         // we didn't loaded user data yet, but we need user language
108         $r = q("SELECT language FROM user WHERE uid=%d", intval($_SESSION['uid']));
109         $_SESSION['language'] = $lang;
110         if (count($r)>0) $_SESSION['language'] = $r[0]['language'];
111 }
112
113 if((x($_SESSION,'language')) && ($_SESSION['language'] !== $lang)) {
114         $lang = $_SESSION['language'];
115         load_translation_table($lang);
116 }
117
118 if((x($_GET,'zrl')) && (!$install && !$maintenance)) {
119         $_SESSION['my_url'] = $_GET['zrl'];
120         $a->query_string = preg_replace('/[\?&]zrl=(.*?)([\?&]|$)/is','',$a->query_string);
121         zrl_init($a);
122 }
123
124 /**
125  *
126  * For Mozilla auth manager - still needs sorting, and this might conflict with LRDD header.
127  * Apache/PHP lumps the Link: headers into one - and other services might not be able to parse it
128  * this way. There's a PHP flag to link the headers because by default this will over-write any other
129  * link header.
130  *
131  * What we really need to do is output the raw headers ourselves so we can keep them separate.
132  *
133  */
134
135 // header('Link: <' . $a->get_baseurl() . '/amcd>; rel="acct-mgmt";');
136
137 if((x($_SESSION,'authenticated')) || (x($_POST,'auth-params')) || ($a->module === 'login'))
138         require("include/auth.php");
139
140 if(! x($_SESSION,'authenticated'))
141         header('X-Account-Management-Status: none');
142
143 /* set up page['htmlhead'] and page['end'] for the modules to use */
144 $a->page['htmlhead'] = '';
145 $a->page['end'] = '';
146
147
148 if(! x($_SESSION,'sysmsg'))
149         $_SESSION['sysmsg'] = array();
150
151 if(! x($_SESSION,'sysmsg_info'))
152         $_SESSION['sysmsg_info'] = array();
153
154 /*
155  * check_config() is responsible for running update scripts. These automatically
156  * update the DB schema whenever we push a new one out. It also checks to see if
157  * any plugins have been added or removed and reacts accordingly.
158  */
159
160 // in install mode, any url loads install module
161 // but we need "view" module for stylesheet
162 if($install && $a->module!="view")
163         $a->module = 'install';
164 elseif($maintenance && $a->module!="view")
165         $a->module = 'maintenance';
166 else {
167         check_url($a);
168         check_db();
169         check_plugins($a);
170 }
171
172 nav_set_selected('nothing');
173
174 //Don't populate apps_menu if apps are private
175 $privateapps = get_config('config','private_addons');
176 if((local_user()) || (! $privateapps === "1"))
177 {
178         $arr = array('app_menu' => $a->apps);
179
180         call_hooks('app_menu', $arr);
181
182         $a->apps = $arr['app_menu'];
183 }
184
185 /**
186  *
187  * We have already parsed the server path into $a->argc and $a->argv
188  *
189  * $a->argv[0] is our module name. We will load the file mod/{$a->argv[0]}.php
190  * and use it for handling our URL request.
191  * The module file contains a few functions that we call in various circumstances
192  * and in the following order:
193  *
194  * "module"_init
195  * "module"_post (only called if there are $_POST variables)
196  * "module"_afterpost
197  * "module"_content - the string return of this function contains our page body
198  *
199  * Modules which emit other serialisations besides HTML (XML,JSON, etc.) should do
200  * so within the module init and/or post functions and then invoke killme() to terminate
201  * further processing.
202  */
203
204 if(strlen($a->module)) {
205
206         /**
207          *
208          * We will always have a module name.
209          * First see if we have a plugin which is masquerading as a module.
210          *
211          */
212
213         // Compatibility with the Android Diaspora client
214         if ($a->module == "stream")
215                 $a->module = "network";
216
217         // Compatibility with the Firefox App
218         if (($a->module == "users") AND ($a->cmd == "users/sign_in"))
219                 $a->module = "login";
220
221         $privateapps = get_config('config','private_addons');
222
223         if(is_array($a->plugins) && in_array($a->module,$a->plugins) && file_exists("addon/{$a->module}/{$a->module}.php")) {
224                 //Check if module is an app and if public access to apps is allowed or not
225                 if((!local_user()) && plugin_is_app($a->module) && $privateapps === "1") {
226                         info( t("You must be logged in to use addons. "));
227                 }
228                 else {
229                         include_once("addon/{$a->module}/{$a->module}.php");
230                         if(function_exists($a->module . '_module'))
231                                 $a->module_loaded = true;
232                 }
233         }
234
235         /**
236          * If not, next look for a 'standard' program module in the 'mod' directory
237          */
238
239         if((! $a->module_loaded) && (file_exists("mod/{$a->module}.php"))) {
240                 include_once("mod/{$a->module}.php");
241                 $a->module_loaded = true;
242         }
243
244         /**
245          *
246          * The URL provided does not resolve to a valid module.
247          *
248          * On Dreamhost sites, quite often things go wrong for no apparent reason and they send us to '/internal_error.html'.
249          * We don't like doing this, but as it occasionally accounts for 10-20% or more of all site traffic -
250          * 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
251          * this will often succeed and eventually do the right thing.
252          *
253          * Otherwise we are going to emit a 404 not found.
254          *
255          */
256
257         if(! $a->module_loaded) {
258
259                 // Stupid browser tried to pre-fetch our Javascript img template. Don't log the event or return anything - just quietly exit.
260                 if((x($_SERVER,'QUERY_STRING')) && preg_match('/{[0-9]}/',$_SERVER['QUERY_STRING']) !== 0) {
261                         killme();
262                 }
263
264                 if((x($_SERVER,'QUERY_STRING')) && ($_SERVER['QUERY_STRING'] === 'q=internal_error.html') && isset($dreamhost_error_hack)) {
265                         logger('index.php: dreamhost_error_hack invoked. Original URI =' . $_SERVER['REQUEST_URI']);
266                         goaway($a->get_baseurl() . $_SERVER['REQUEST_URI']);
267                 }
268
269                 logger('index.php: page not found: ' . $_SERVER['REQUEST_URI'] . ' ADDRESS: ' . $_SERVER['REMOTE_ADDR'] . ' QUERY: ' . $_SERVER['QUERY_STRING'], LOGGER_DEBUG);
270                 header($_SERVER["SERVER_PROTOCOL"] . ' 404 ' . t('Not Found'));
271                 $tpl = get_markup_template("404.tpl");
272                 $a->page['content'] = replace_macros($tpl, array(
273                         '$message' =>  t('Page not found.' )
274                 ));
275         }
276 }
277
278 /**
279  * load current theme info
280  */
281 $theme_info_file = "view/theme/".current_theme()."/theme.php";
282 if (file_exists($theme_info_file)){
283         require_once($theme_info_file);
284 }
285
286
287 /* initialise content region */
288
289 if(! x($a->page,'content'))
290         $a->page['content'] = '';
291
292 if(!$install && !$maintenance)
293         call_hooks('page_content_top',$a->page['content']);
294
295 /**
296  * Call module functions
297  */
298
299 if($a->module_loaded) {
300         $a->page['page_title'] = $a->module;
301         $placeholder = '';
302
303         if(function_exists($a->module . '_init')) {
304                 call_hooks($a->module . '_mod_init', $placeholder);
305                 $func = $a->module . '_init';
306                 $func($a);
307         }
308
309         if(function_exists(str_replace('-','_',current_theme()) . '_init')) {
310                 $func = str_replace('-','_',current_theme()) . '_init';
311                 $func($a);
312         }
313 //      elseif (x($a->theme_info,"extends") && file_exists("view/theme/".$a->theme_info["extends"]."/theme.php")) {
314 //              require_once("view/theme/".$a->theme_info["extends"]."/theme.php");
315 //              if(function_exists(str_replace('-','_',$a->theme_info["extends"]) . '_init')) {
316 //                      $func = str_replace('-','_',$a->theme_info["extends"]) . '_init';
317 //                      $func($a);
318 //              }
319 //      }
320
321         if(($_SERVER['REQUEST_METHOD'] === 'POST') && (! $a->error)
322                 && (function_exists($a->module . '_post'))
323                 && (! x($_POST,'auth-params'))) {
324                 call_hooks($a->module . '_mod_post', $_POST);
325                 $func = $a->module . '_post';
326                 $func($a);
327         }
328
329         if((! $a->error) && (function_exists($a->module . '_afterpost'))) {
330                 call_hooks($a->module . '_mod_afterpost',$placeholder);
331                 $func = $a->module . '_afterpost';
332                 $func($a);
333         }
334
335         if((! $a->error) && (function_exists($a->module . '_content'))) {
336                 $arr = array('content' => $a->page['content']);
337                 call_hooks($a->module . '_mod_content', $arr);
338                 $a->page['content'] = $arr['content'];
339                 $func = $a->module . '_content';
340                 $arr = array('content' => $func($a));
341                 call_hooks($a->module . '_mod_aftercontent', $arr);
342                 $a->page['content'] .= $arr['content'];
343         }
344
345         if(function_exists(str_replace('-','_',current_theme()) . '_content_loaded')) {
346                 $func = str_replace('-','_',current_theme()) . '_content_loaded';
347                 $func($a);
348         }
349 }
350
351 /*
352  * Create the page head after setting the language
353  * and getting any auth credentials
354  *
355  * Moved init_pagehead() and init_page_end() to after
356  * all the module functions have executed so that all
357  * theme choices made by the modules can take effect
358  */
359
360 $a->init_pagehead();
361
362 /**
363  * Build the page ending -- this is stuff that goes right before
364  * the closing </body> tag
365  */
366
367 $a->init_page_end();
368
369 // If you're just visiting, let javascript take you home
370
371 if(x($_SESSION,'visitor_home'))
372         $homebase = $_SESSION['visitor_home'];
373 elseif(local_user())
374         $homebase = $a->get_baseurl() . '/profile/' . $a->user['nickname'];
375
376 if(isset($homebase))
377         $a->page['content'] .= '<script>var homebase="' . $homebase . '" ; </script>';
378
379 // now that we've been through the module content, see if the page reported
380 // a permission problem and if so, a 403 response would seem to be in order.
381
382 if(stristr( implode("",$_SESSION['sysmsg']), t('Permission denied'))) {
383         header($_SERVER["SERVER_PROTOCOL"] . ' 403 ' . t('Permission denied.'));
384 }
385
386 /**
387  *
388  * Report anything which needs to be communicated in the notification area (before the main body)
389  *
390  */
391
392 /*if(x($_SESSION,'sysmsg')) {
393         $a->page['content'] = "<div id=\"sysmsg\" class=\"error-message\">{$_SESSION['sysmsg']}</div>\r\n"
394                 . ((x($a->page,'content')) ? $a->page['content'] : '');
395         $_SESSION['sysmsg']="";
396         unset($_SESSION['sysmsg']);
397 }
398 if(x($_SESSION,'sysmsg_info')) {
399         $a->page['content'] = "<div id=\"sysmsg_info\" class=\"info-message\">{$_SESSION['sysmsg_info']}</div>\r\n"
400                 . ((x($a->page,'content')) ? $a->page['content'] : '');
401         $_SESSION['sysmsg_info']="";
402         unset($_SESSION['sysmsg_info']);
403 }*/
404
405
406
407 call_hooks('page_end', $a->page['content']);
408
409
410 /**
411  *
412  * Add a place for the pause/resume Ajax indicator
413  *
414  */
415
416 $a->page['content'] .=  '<div id="pause"></div>';
417
418
419 /**
420  *
421  * Add the navigation (menu) template
422  *
423  */
424
425 if($a->module != 'install' && $a->module != 'maintenance') {
426         nav($a);
427 }
428
429 /**
430  * Add a "toggle mobile" link if we're using a mobile device
431  */
432
433 if($a->is_mobile || $a->is_tablet) {
434         if(isset($_SESSION['show-mobile']) && !$_SESSION['show-mobile']) {
435                 $link = $a->get_baseurl() . '/toggle_mobile?address=' . curPageURL();
436         }
437         else {
438                 $link = $a->get_baseurl() . '/toggle_mobile?off=1&address=' . curPageURL();
439         }
440         $a->page['footer'] = replace_macros(get_markup_template("toggle_mobile_footer.tpl"), array(
441                                 '$toggle_link' => $link,
442                                 '$toggle_text' => t('toggle mobile')
443                          ));
444 }
445
446 /**
447  * Build the page - now that we have all the components
448  */
449
450 if(!$a->theme['stylesheet'])
451         $stylesheet = current_theme_url();
452 else
453         $stylesheet = $a->theme['stylesheet'];
454
455 $a->page['htmlhead'] = str_replace('{{$stylesheet}}',$stylesheet,$a->page['htmlhead']);
456 //$a->page['htmlhead'] = replace_macros($a->page['htmlhead'], array('$stylesheet' => $stylesheet));
457
458 if (isset($_GET["mode"]) AND (($_GET["mode"] == "raw") OR ($_GET["mode"] == "minimal"))) {
459         $doc = new DOMDocument();
460
461         $target = new DOMDocument();
462         $target->loadXML("<root></root>");
463
464         $content = mb_convert_encoding($a->page["content"], 'HTML-ENTITIES', "UTF-8");
465
466         @$doc->loadHTML($content);
467
468         $xpath = new DomXPath($doc);
469
470         $list = $xpath->query("//*[contains(@id,'tread-wrapper-')]");  /* */
471
472         foreach ($list as $item) {
473
474                 $item = $target->importNode($item, true);
475
476                 // And then append it to the target
477                 $target->documentElement->appendChild($item);
478         }
479 }
480
481 if (isset($_GET["mode"]) AND ($_GET["mode"] == "raw")) {
482
483         header("Content-type: text/html; charset=utf-8");
484
485         echo substr($target->saveHTML(), 6, -8);
486
487         session_write_close();
488         exit;
489
490 } elseif (get_pconfig(local_user(),'system','infinite_scroll')
491           AND ($a->module == "network") AND ($_GET["mode"] != "minimal")) {
492         if (is_string($_GET["page"]))
493                 $pageno = $_GET["page"];
494         else
495                 $pageno = 1;
496
497         $reload_uri = "";
498
499         foreach ($_GET AS $param => $value)
500                 if (($param != "page") AND ($param != "q"))
501                         $reload_uri .= "&".$param."=".urlencode($value);
502
503         if (($a->page_offset != "") AND !strstr($reload_uri, "&offset="))
504                 $reload_uri .= "&offset=".urlencode($a->page_offset);
505
506
507 $a->page['htmlhead'] .= <<< EOT
508 <script type="text/javascript">
509
510 $(document).ready(function() {
511     num = $pageno;
512 });
513
514 function loadcontent() {
515         if (lockLoadContent) return;
516         lockLoadContent = true;
517
518         $("#scroll-loader").fadeIn('normal');
519
520         num+=1;
521
522         console.log('Loading page ' + num);
523
524         $.get('/network?mode=raw$reload_uri&page=' + num, function(data) {
525                 $("#scroll-loader").hide();
526                 if ($(data).length > 0) {
527                         $(data).insertBefore('#conversation-end');
528                         lockLoadContent = false;
529                 } else {
530                         $("#scroll-end").fadeIn('normal');
531                 }
532         });
533 }
534
535 var num = $pageno;
536 var lockLoadContent = false;
537
538 $(window).scroll(function(e){
539
540         if ($(document).height() != $(window).height()) {
541                 // First method that is expected to work - but has problems with Chrome
542                 if ($(window).scrollTop() > ($(document).height() - $(window).height() * 1.5))
543                         loadcontent();
544         } else {
545                 // This method works with Chrome - but seems to be much slower in Firefox
546                 if ($(window).scrollTop() > (($("section").height() + $("header").height() + $("footer").height()) - $(window).height() * 1.5))
547                         loadcontent();
548         }
549 });
550 </script>
551
552 EOT;
553
554 }
555
556 $page    = $a->page;
557 $profile = $a->profile;
558
559 header("Content-type: text/html; charset=utf-8");
560
561
562 if (isset($_GET["mode"]) AND ($_GET["mode"] == "minimal")) {
563         //$page['content'] = substr($target->saveHTML(), 6, -8)."\n\n".
564         //                      '<div id="conversation-end"></div>'."\n\n";
565
566         require "view/minimal.php";
567 } else {
568         $template = 'view/theme/' . current_theme() . '/'
569                 . ((x($a->page,'template')) ? $a->page['template'] : 'default' ) . '.php';
570
571         if(file_exists($template))
572                 require_once($template);
573         else
574                 require_once(str_replace('theme/' . current_theme() . '/', '', $template));
575 }
576
577 session_write_close();
578 exit;