]> git.mxchange.org Git - friendica.git/blob - boot.php
Merge pull request #2356 from annando/1602-redmatrix-name
[friendica.git] / boot.php
1 <?php
2 /** @file boot.php
3  *
4  * This file defines some global constants and includes the central App class.
5  */
6
7 /**
8  * Friendica
9  * 
10  * Friendica is a communications platform for integrated social communications
11  * utilising decentralised communications and linkage to several indie social
12  * projects - as well as popular mainstream providers.
13  * 
14  * Our mission is to free our friends and families from the clutches of
15  * data-harvesting corporations, and pave the way to a future where social
16  * communications are free and open and flow between alternate providers as
17  * easily as email does today.
18  */
19
20 require_once('include/autoloader.php');
21  
22 require_once('include/config.php');
23 require_once('include/network.php');
24 require_once('include/plugin.php');
25 require_once('include/text.php');
26 require_once('include/datetime.php');
27 require_once('include/pgettext.php');
28 require_once('include/nav.php');
29 require_once('include/cache.php');
30 require_once('library/Mobile_Detect/Mobile_Detect.php');
31 require_once('include/features.php');
32 require_once('include/identity.php');
33
34 require_once('update.php');
35 require_once('include/dbstructure.php');
36
37 define ( 'FRIENDICA_PLATFORM',     'Friendica');
38 define ( 'FRIENDICA_CODENAME',     'Asparagus');
39 define ( 'FRIENDICA_VERSION',      '3.5-dev' );
40 define ( 'DFRN_PROTOCOL_VERSION',  '2.23'    );
41 define ( 'DB_UPDATE_VERSION',      1194      );
42
43 /**
44  * @brief Constant with a HTML line break.
45  *
46  * Contains a HTML line break (br) element and a real carriage return with line
47  * feed for the source.
48  * This can be used in HTML and JavaScript where needed a line break.
49  */
50 define ( 'EOL',                    "<br />\r\n"     );
51 define ( 'ATOM_TIME',              'Y-m-d\TH:i:s\Z' );
52
53
54 /**
55  * @brief Image storage quality.
56  * 
57  * Lower numbers save space at cost of image detail.
58  * For ease of upgrade, please do not change here. Change jpeg quality with
59  * $a->config['system']['jpeg_quality'] = n;
60  * in .htconfig.php, where n is netween 1 and 100, and with very poor results
61  * below about 50
62  *
63  */
64
65 define ( 'JPEG_QUALITY',            100  );
66 /**
67  * $a->config['system']['png_quality'] from 0 (uncompressed) to 9
68  */
69 define ( 'PNG_QUALITY',             8  );
70
71 /**
72  *
73  * An alternate way of limiting picture upload sizes. Specify the maximum pixel
74  * length that pictures are allowed to be (for non-square pictures, it will apply
75  * to the longest side). Pictures longer than this length will be resized to be
76  * this length (on the longest side, the other side will be scaled appropriately).
77  * Modify this value using
78  *
79  *    $a->config['system']['max_image_length'] = n;
80  *
81  * in .htconfig.php
82  *
83  * If you don't want to set a maximum length, set to -1. The default value is
84  * defined by 'MAX_IMAGE_LENGTH' below.
85  *
86  */
87 define ( 'MAX_IMAGE_LENGTH',        -1  );
88
89
90 /**
91  * Not yet used
92  */
93
94 define ( 'DEFAULT_DB_ENGINE',  'MyISAM'  );
95
96 /**
97  * @name SSL Policy
98  * 
99  * SSL redirection policies
100  * @{
101  */
102 define ( 'SSL_POLICY_NONE',         0 );
103 define ( 'SSL_POLICY_FULL',         1 );
104 define ( 'SSL_POLICY_SELFSIGN',     2 );
105 /* @}*/
106
107 /**
108  * @name Logger
109  * 
110  * log levels
111  * @{
112  */
113 define ( 'LOGGER_NORMAL',          0 );
114 define ( 'LOGGER_TRACE',           1 );
115 define ( 'LOGGER_DEBUG',           2 );
116 define ( 'LOGGER_DATA',            3 );
117 define ( 'LOGGER_ALL',             4 );
118 /* @}*/
119
120 /**
121  * @name Cache
122  * 
123  * Cache levels
124  * @{
125  */
126 define ( 'CACHE_MONTH',            0 );
127 define ( 'CACHE_WEEK',             1 );
128 define ( 'CACHE_DAY',              2 );
129 define ( 'CACHE_HOUR',             3 );
130 /* @}*/
131
132 /**
133  * @name Register
134  * 
135  * Registration policies
136  * @{
137  */
138 define ( 'REGISTER_CLOSED',        0 );
139 define ( 'REGISTER_APPROVE',       1 );
140 define ( 'REGISTER_OPEN',          2 );
141 /** @}*/
142
143 /**
144  * @name Contact_is
145  * 
146  * Relationship types
147  * @{
148  */
149 define ( 'CONTACT_IS_FOLLOWER', 1);
150 define ( 'CONTACT_IS_SHARING',  2);
151 define ( 'CONTACT_IS_FRIEND',   3);
152 /** @}*/
153
154 /**
155  * @name Update
156  * 
157  * DB update return values
158  * @{
159  */
160 define ( 'UPDATE_SUCCESS', 0);
161 define ( 'UPDATE_FAILED',  1);
162 /** @}*/
163
164
165 /**
166  * @name page/profile types
167  *
168  * PAGE_NORMAL is a typical personal profile account
169  * PAGE_SOAPBOX automatically approves all friend requests as CONTACT_IS_SHARING, (readonly)
170  * PAGE_COMMUNITY automatically approves all friend requests as CONTACT_IS_SHARING, but with
171  *      write access to wall and comments (no email and not included in page owner's ACL lists)
172  * PAGE_FREELOVE automatically approves all friend requests as full friends (CONTACT_IS_FRIEND).
173  *
174  * @{
175  */
176 define ( 'PAGE_NORMAL',            0 );
177 define ( 'PAGE_SOAPBOX',           1 );
178 define ( 'PAGE_COMMUNITY',         2 );
179 define ( 'PAGE_FREELOVE',          3 );
180 define ( 'PAGE_BLOG',              4 );
181 define ( 'PAGE_PRVGROUP',          5 );
182 /** @}*/
183
184 /**
185  * @name CP
186  * 
187  * Type of the community page
188  * @{
189  */
190 define ( 'CP_NO_COMMUNITY_PAGE',   -1 );
191 define ( 'CP_USERS_ON_SERVER',     0 );
192 define ( 'CP_GLOBAL_COMMUNITY',    1 );
193 /** @}*/
194
195 /**
196  * @name Network
197  * 
198  * Network and protocol family types
199  * @{
200  */
201 define ( 'NETWORK_DFRN',             'dfrn');    // Friendica, Mistpark, other DFRN implementations
202 define ( 'NETWORK_ZOT',              'zot!');    // Zot!
203 define ( 'NETWORK_OSTATUS',          'stat');    // status.net, identi.ca, GNU-social, other OStatus implementations
204 define ( 'NETWORK_FEED',             'feed');    // RSS/Atom feeds with no known "post/notify" protocol
205 define ( 'NETWORK_DIASPORA',         'dspr');    // Diaspora
206 define ( 'NETWORK_MAIL',             'mail');    // IMAP/POP
207 define ( 'NETWORK_MAIL2',            'mai2');    // extended IMAP/POP
208 define ( 'NETWORK_FACEBOOK',         'face');    // Facebook API
209 define ( 'NETWORK_LINKEDIN',         'lnkd');    // LinkedIn
210 define ( 'NETWORK_XMPP',             'xmpp');    // XMPP
211 define ( 'NETWORK_MYSPACE',          'mysp');    // MySpace
212 define ( 'NETWORK_GPLUS',            'goog');    // Google+
213 define ( 'NETWORK_PUMPIO',           'pump');    // pump.io
214 define ( 'NETWORK_TWITTER',          'twit');    // Twitter
215 define ( 'NETWORK_DIASPORA2',        'dspc');    // Diaspora connector
216 define ( 'NETWORK_STATUSNET',        'stac');    // Statusnet connector
217 define ( 'NETWORK_APPNET',           'apdn');    // app.net
218 define ( 'NETWORK_NEWS',             'nntp');    // Network News Transfer Protocol
219 define ( 'NETWORK_ICALENDAR',        'ical');    // iCalendar
220 define ( 'NETWORK_PHANTOM',          'unkn');    // Place holder
221 /** @}*/
222
223 /**
224  * These numbers are used in stored permissions
225  * and existing allocations MUST NEVER BE CHANGED
226  * OR RE-ASSIGNED! You may only add to them.
227  */
228
229 $netgroup_ids = array(
230         NETWORK_DFRN     => (-1),
231         NETWORK_ZOT      => (-2),
232         NETWORK_OSTATUS  => (-3),
233         NETWORK_FEED     => (-4),
234         NETWORK_DIASPORA => (-5),
235         NETWORK_MAIL     => (-6),
236         NETWORK_MAIL2    => (-7),
237         NETWORK_FACEBOOK => (-8),
238         NETWORK_LINKEDIN => (-9),
239         NETWORK_XMPP     => (-10),
240         NETWORK_MYSPACE  => (-11),
241         NETWORK_GPLUS    => (-12),
242         NETWORK_PUMPIO   => (-13),
243         NETWORK_TWITTER  => (-14),
244         NETWORK_DIASPORA2 => (-15),
245         NETWORK_STATUSNET => (-16),
246         NETWORK_APPNET    => (-17),
247         NETWORK_NEWS      => (-18),
248         NETWORK_ICALENDAR => (-19),
249
250         NETWORK_PHANTOM  => (-127),
251 );
252
253
254 /**
255  * Maximum number of "people who like (or don't like) this"  that we will list by name
256  */
257
258 define ( 'MAX_LIKERS',    75);
259
260 /**
261  * Communication timeout
262  */
263
264 define ( 'ZCURL_TIMEOUT' , (-1));
265
266
267 /**
268  * @name Notify
269  * 
270  * Email notification options
271  * @{
272  */
273 define ( 'NOTIFY_INTRO',    0x0001 );
274 define ( 'NOTIFY_CONFIRM',  0x0002 );
275 define ( 'NOTIFY_WALL',     0x0004 );
276 define ( 'NOTIFY_COMMENT',  0x0008 );
277 define ( 'NOTIFY_MAIL',     0x0010 );
278 define ( 'NOTIFY_SUGGEST',  0x0020 );
279 define ( 'NOTIFY_PROFILE',  0x0040 );
280 define ( 'NOTIFY_TAGSELF',  0x0080 );
281 define ( 'NOTIFY_TAGSHARE', 0x0100 );
282 define ( 'NOTIFY_POKE',     0x0200 );
283 define ( 'NOTIFY_SHARE',    0x0400 );
284
285 define ( 'NOTIFY_SYSTEM',   0x8000 );
286 /* @}*/
287
288
289 /**
290  * @name Term
291  * 
292  * Tag/term types
293  * @{
294  */
295 define ( 'TERM_UNKNOWN',   0 );
296 define ( 'TERM_HASHTAG',   1 );
297 define ( 'TERM_MENTION',   2 );
298 define ( 'TERM_CATEGORY',  3 );
299 define ( 'TERM_PCATEGORY', 4 );
300 define ( 'TERM_FILE',      5 );
301 define ( 'TERM_SAVEDSEARCH', 6 );
302 define ( 'TERM_CONVERSATION', 7 );
303
304 define ( 'TERM_OBJ_POST',  1 );
305 define ( 'TERM_OBJ_PHOTO', 2 );
306
307
308
309 /**
310  * @name Namespaces
311  * 
312  * Various namespaces we may need to parse
313  * @{
314  */
315 define ( 'NAMESPACE_ZOT',             'http://purl.org/zot' );
316 define ( 'NAMESPACE_DFRN' ,           'http://purl.org/macgirvin/dfrn/1.0' );
317 define ( 'NAMESPACE_THREAD' ,         'http://purl.org/syndication/thread/1.0' );
318 define ( 'NAMESPACE_TOMB' ,           'http://purl.org/atompub/tombstones/1.0' );
319 define ( 'NAMESPACE_ACTIVITY',        'http://activitystrea.ms/spec/1.0/' );
320 define ( 'NAMESPACE_ACTIVITY_SCHEMA', 'http://activitystrea.ms/schema/1.0/' );
321 define ( 'NAMESPACE_MEDIA',           'http://purl.org/syndication/atommedia' );
322 define ( 'NAMESPACE_SALMON_ME',       'http://salmon-protocol.org/ns/magic-env' );
323 define ( 'NAMESPACE_OSTATUSSUB',      'http://ostatus.org/schema/1.0/subscribe' );
324 define ( 'NAMESPACE_GEORSS',          'http://www.georss.org/georss' );
325 define ( 'NAMESPACE_POCO',            'http://portablecontacts.net/spec/1.0' );
326 define ( 'NAMESPACE_FEED',            'http://schemas.google.com/g/2010#updates-from' );
327 define ( 'NAMESPACE_OSTATUS',         'http://ostatus.org/schema/1.0' );
328 define ( 'NAMESPACE_STATUSNET',       'http://status.net/schema/api/1/' );
329 define ( 'NAMESPACE_ATOM1',           'http://www.w3.org/2005/Atom' );
330 /* @}*/
331
332 /**
333  * @name Activity
334  * 
335  * Activity stream defines
336  * @{
337  */
338 define ( 'ACTIVITY_LIKE',        NAMESPACE_ACTIVITY_SCHEMA . 'like' );
339 define ( 'ACTIVITY_DISLIKE',     NAMESPACE_DFRN            . '/dislike' );
340 define ( 'ACTIVITY_ATTEND',      NAMESPACE_ZOT             . '/activity/attendyes' );
341 define ( 'ACTIVITY_ATTENDNO',    NAMESPACE_ZOT             . '/activity/attendno' );
342 define ( 'ACTIVITY_ATTENDMAYBE', NAMESPACE_ZOT             . '/activity/attendmaybe' );
343
344 define ( 'ACTIVITY_OBJ_HEART',   NAMESPACE_DFRN            . '/heart' );
345
346 define ( 'ACTIVITY_FRIEND',      NAMESPACE_ACTIVITY_SCHEMA . 'make-friend' );
347 define ( 'ACTIVITY_REQ_FRIEND',  NAMESPACE_ACTIVITY_SCHEMA . 'request-friend' );
348 define ( 'ACTIVITY_UNFRIEND',    NAMESPACE_ACTIVITY_SCHEMA . 'remove-friend' );
349 define ( 'ACTIVITY_FOLLOW',      NAMESPACE_ACTIVITY_SCHEMA . 'follow' );
350 define ( 'ACTIVITY_UNFOLLOW',    NAMESPACE_ACTIVITY_SCHEMA . 'stop-following' );
351 define ( 'ACTIVITY_JOIN',        NAMESPACE_ACTIVITY_SCHEMA . 'join' );
352
353 define ( 'ACTIVITY_POST',        NAMESPACE_ACTIVITY_SCHEMA . 'post' );
354 define ( 'ACTIVITY_UPDATE',      NAMESPACE_ACTIVITY_SCHEMA . 'update' );
355 define ( 'ACTIVITY_TAG',         NAMESPACE_ACTIVITY_SCHEMA . 'tag' );
356 define ( 'ACTIVITY_FAVORITE',    NAMESPACE_ACTIVITY_SCHEMA . 'favorite' );
357 define ( 'ACTIVITY_SHARE',       NAMESPACE_ACTIVITY_SCHEMA . 'share' );
358
359 define ( 'ACTIVITY_POKE',        NAMESPACE_ZOT . '/activity/poke' );
360 define ( 'ACTIVITY_MOOD',        NAMESPACE_ZOT . '/activity/mood' );
361
362 define ( 'ACTIVITY_OBJ_BOOKMARK', NAMESPACE_ACTIVITY_SCHEMA . 'bookmark' );
363 define ( 'ACTIVITY_OBJ_COMMENT', NAMESPACE_ACTIVITY_SCHEMA . 'comment' );
364 define ( 'ACTIVITY_OBJ_NOTE',    NAMESPACE_ACTIVITY_SCHEMA . 'note' );
365 define ( 'ACTIVITY_OBJ_PERSON',  NAMESPACE_ACTIVITY_SCHEMA . 'person' );
366 define ( 'ACTIVITY_OBJ_IMAGE',   NAMESPACE_ACTIVITY_SCHEMA . 'image' );
367 define ( 'ACTIVITY_OBJ_PHOTO',   NAMESPACE_ACTIVITY_SCHEMA . 'photo' );
368 define ( 'ACTIVITY_OBJ_VIDEO',   NAMESPACE_ACTIVITY_SCHEMA . 'video' );
369 define ( 'ACTIVITY_OBJ_P_PHOTO', NAMESPACE_ACTIVITY_SCHEMA . 'profile-photo' );
370 define ( 'ACTIVITY_OBJ_ALBUM',   NAMESPACE_ACTIVITY_SCHEMA . 'photo-album' );
371 define ( 'ACTIVITY_OBJ_EVENT',   NAMESPACE_ACTIVITY_SCHEMA . 'event' );
372 define ( 'ACTIVITY_OBJ_GROUP',   NAMESPACE_ACTIVITY_SCHEMA . 'group' );
373 define ( 'ACTIVITY_OBJ_TAGTERM', NAMESPACE_DFRN            . '/tagterm' );
374 define ( 'ACTIVITY_OBJ_PROFILE', NAMESPACE_DFRN            . '/profile' );
375 define ( 'ACTIVITY_OBJ_QUESTION', 'http://activityschema.org/object/question' );
376 /* @}*/
377
378 /**
379  * @name Gravity
380  * 
381  * Item weight for query ordering
382  * @{
383  */
384 define ( 'GRAVITY_PARENT',       0);
385 define ( 'GRAVITY_LIKE',         3);
386 define ( 'GRAVITY_COMMENT',      6);
387 /* @}*/
388
389
390 /**
391  *
392  * Reverse the effect of magic_quotes_gpc if it is enabled.
393  * Please disable magic_quotes_gpc so we don't have to do this.
394  * See http://php.net/manual/en/security.magicquotes.disabling.php
395  *
396  */
397
398 function startup() {
399
400         error_reporting(E_ERROR | E_WARNING | E_PARSE);
401
402         set_time_limit(0);
403
404         // This has to be quite large to deal with embedded private photos
405         ini_set('pcre.backtrack_limit', 500000);
406
407
408         if (get_magic_quotes_gpc()) {
409                 $process = array(&$_GET, &$_POST, &$_COOKIE, &$_REQUEST);
410                 while (list($key, $val) = each($process)) {
411                         foreach ($val as $k => $v) {
412                                 unset($process[$key][$k]);
413                                 if (is_array($v)) {
414                                         $process[$key][stripslashes($k)] = $v;
415                                         $process[] = &$process[$key][stripslashes($k)];
416                                 } else {
417                                         $process[$key][stripslashes($k)] = stripslashes($v);
418                                 }
419                         }
420                 }
421                 unset($process);
422         }
423
424 }
425
426 /**
427  *
428  * class: App
429  * 
430  * @brief Our main application structure for the life of this page.
431  * 
432  * Primarily deals with the URL that got us here
433  * and tries to make some sense of it, and
434  * stores our page contents and config storage
435  * and anything else that might need to be passed around
436  * before we spit the page out.
437  *
438  */
439 class App {
440
441         public  $module_loaded = false;
442         public  $query_string;
443         public  $config;
444         public  $page;
445         public  $profile;
446         public  $profile_uid;
447         public  $user;
448         public  $cid;
449         public  $contact;
450         public  $contacts;
451         public  $page_contact;
452         public  $content;
453         public  $data = array();
454         public  $error = false;
455         public  $cmd;
456         public  $argv;
457         public  $argc;
458         public  $module;
459         public  $pager;
460         public  $strings;
461         public  $path;
462         public  $hooks;
463         public  $timezone;
464         public  $interactive = true;
465         public  $plugins;
466         public  $apps = array();
467         public  $identities;
468         public  $is_mobile;
469         public  $is_tablet;
470         public  $is_friendica_app;
471         public  $performance = array();
472         public  $callstack = array();
473
474         public $nav_sel;
475
476         public $category;
477
478
479         // Allow themes to control internal parameters
480         // by changing App values in theme.php
481
482         public  $sourcename = '';
483         public  $videowidth = 425;
484         public  $videoheight = 350;
485         public  $force_max_items = 0;
486         public  $theme_thread_allow = true;
487         public  $theme_events_in_profile = true;
488
489         /**
490          * @brief An array for all theme-controllable parameters
491          *
492          * Mostly unimplemented yet. Only options 'template_engine' and
493          * beyond are used.
494          */
495         public  $theme = array(
496                 'sourcename' => '',
497                 'videowidth' => 425,
498                 'videoheight' => 350,
499                 'force_max_items' => 0,
500                 'thread_allow' => true,
501                 'stylesheet' => '',
502                 'template_engine' => 'smarty3',
503         );
504
505         /**
506          * @brief An array of registered template engines ('name'=>'class name')
507          */
508         public $template_engines = array();
509         /**
510          * @brief An array of instanced template engines ('name'=>'instance')
511          */
512         public $template_engine_instance = array();
513
514         private $ldelim = array(
515                 'internal' => '',
516                 'smarty3' => '{{'
517         );
518         private $rdelim = array(
519                 'internal' => '',
520                 'smarty3' => '}}'
521         );
522
523         private $scheme;
524         private $hostname;
525         private $baseurl;
526         private $db;
527
528         private $curl_code;
529         private $curl_content_type;
530         private $curl_headers;
531
532         private $cached_profile_image;
533         private $cached_profile_picdate;
534
535         private static $a;
536
537         /**
538          * @brief App constructor.
539          */
540         function __construct() {
541
542                 global $default_timezone;
543
544                 $hostname = "";
545
546                 if (file_exists(".htpreconfig.php"))
547                         @include(".htpreconfig.php");
548
549                 $this->timezone = ((x($default_timezone)) ? $default_timezone : 'UTC');
550
551                 date_default_timezone_set($this->timezone);
552
553                 $this->performance["start"] = microtime(true);
554                 $this->performance["database"] = 0;
555                 $this->performance["network"] = 0;
556                 $this->performance["file"] = 0;
557                 $this->performance["rendering"] = 0;
558                 $this->performance["parser"] = 0;
559                 $this->performance["marktime"] = 0;
560                 $this->performance["markstart"] = microtime(true);
561
562                 $this->callstack["database"] = array();
563                 $this->callstack["network"] = array();
564                 $this->callstack["file"] = array();
565                 $this->callstack["rendering"] = array();
566                 $this->callstack["parser"] = array();
567
568                 $this->config = array();
569                 $this->page = array();
570                 $this->pager= array();
571
572                 $this->query_string = '';
573
574                 startup();
575
576                 set_include_path(
577                                 'include' . PATH_SEPARATOR
578                                 . 'library' . PATH_SEPARATOR
579                                 . 'library/phpsec' . PATH_SEPARATOR
580                                 . 'library/langdet' . PATH_SEPARATOR
581                                 . '.' );
582
583
584                 $this->scheme = 'http';
585                 if(x($_SERVER,'HTTPS') && $_SERVER['HTTPS'])
586                         $this->scheme = 'https';
587                 elseif(x($_SERVER,'SERVER_PORT') && (intval($_SERVER['SERVER_PORT']) == 443))
588                         $this->scheme = 'https';
589
590                 if(x($_SERVER,'SERVER_NAME')) {
591                         $this->hostname = $_SERVER['SERVER_NAME'];
592
593                         // See bug 437 - this didn't work so disabling it
594                         //if(stristr($this->hostname,'xn--')) {
595                                 // PHP or webserver may have converted idn to punycode, so
596                                 // convert punycode back to utf-8
597                         //      require_once('library/simplepie/idn/idna_convert.class.php');
598                         //      $x = new idna_convert();
599                         //      $this->hostname = $x->decode($_SERVER['SERVER_NAME']);
600                         //}
601
602                         if(x($_SERVER,'SERVER_PORT') && $_SERVER['SERVER_PORT'] != 80 && $_SERVER['SERVER_PORT'] != 443)
603                                 $this->hostname .= ':' . $_SERVER['SERVER_PORT'];
604                         /*
605                          * Figure out if we are running at the top of a domain
606                          * or in a sub-directory and adjust accordingly
607                          */
608
609                         $path = trim(dirname($_SERVER['SCRIPT_NAME']),'/\\');
610                         if(isset($path) && strlen($path) && ($path != $this->path))
611                                 $this->path = $path;
612                 }
613
614                 if ($hostname != "")
615                         $this->hostname = $hostname;
616
617                 if (is_array($_SERVER["argv"]) && $_SERVER["argc"]>1 && substr(end($_SERVER["argv"]), 0, 4)=="http" ) {
618                         $this->set_baseurl(array_pop($_SERVER["argv"]) );
619                         $_SERVER["argc"] --;
620                 }
621
622                 #set_include_path("include/$this->hostname" . PATH_SEPARATOR . get_include_path());
623
624                 if((x($_SERVER,'QUERY_STRING')) && substr($_SERVER['QUERY_STRING'],0,9) === "pagename=") {
625                         $this->query_string = substr($_SERVER['QUERY_STRING'],9);
626                         // removing trailing / - maybe a nginx problem
627                         if (substr($this->query_string, 0, 1) == "/")
628                                 $this->query_string = substr($this->query_string, 1);
629                 } elseif((x($_SERVER,'QUERY_STRING')) && substr($_SERVER['QUERY_STRING'],0,2) === "q=") {
630                         $this->query_string = substr($_SERVER['QUERY_STRING'],2);
631                         // removing trailing / - maybe a nginx problem
632                         if (substr($this->query_string, 0, 1) == "/")
633                                 $this->query_string = substr($this->query_string, 1);
634                 }
635
636                 if (x($_GET,'pagename'))
637                         $this->cmd = trim($_GET['pagename'],'/\\');
638                 elseif (x($_GET,'q'))
639                         $this->cmd = trim($_GET['q'],'/\\');
640
641
642                 // fix query_string
643                 $this->query_string = str_replace($this->cmd."&",$this->cmd."?", $this->query_string);
644
645
646                 // unix style "homedir"
647
648                 if(substr($this->cmd,0,1) === '~')
649                         $this->cmd = 'profile/' . substr($this->cmd,1);
650
651                 // Diaspora style profile url
652
653                 if(substr($this->cmd,0,2) === 'u/')
654                         $this->cmd = 'profile/' . substr($this->cmd,2);
655
656
657                 /*
658                  *
659                  * Break the URL path into C style argc/argv style arguments for our
660                  * modules. Given "http://example.com/module/arg1/arg2", $this->argc
661                  * will be 3 (integer) and $this->argv will contain:
662                  *   [0] => 'module'
663                  *   [1] => 'arg1'
664                  *   [2] => 'arg2'
665                  *
666                  *
667                  * There will always be one argument. If provided a naked domain
668                  * URL, $this->argv[0] is set to "home".
669                  *
670                  */
671
672                 $this->argv = explode('/',$this->cmd);
673                 $this->argc = count($this->argv);
674                 if((array_key_exists('0',$this->argv)) && strlen($this->argv[0])) {
675                         $this->module = str_replace(".", "_", $this->argv[0]);
676                         $this->module = str_replace("-", "_", $this->module);
677                 }
678                 else {
679                         $this->argc = 1;
680                         $this->argv = array('home');
681                         $this->module = 'home';
682                 }
683
684                 /*
685                  * See if there is any page number information, and initialise
686                  * pagination
687                  */
688
689                 $this->pager['page'] = ((x($_GET,'page') && intval($_GET['page']) > 0) ? intval($_GET['page']) : 1);
690                 $this->pager['itemspage'] = 50;
691                 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
692                 if($this->pager['start'] < 0)
693                         $this->pager['start'] = 0;
694                 $this->pager['total'] = 0;
695
696                 /*
697                  * Detect mobile devices
698                  */
699
700                 $mobile_detect = new Mobile_Detect();
701                 $this->is_mobile = $mobile_detect->isMobile();
702                 $this->is_tablet = $mobile_detect->isTablet();
703
704                 // Friendica-Client
705                 $this->is_friendica_app = ($_SERVER['HTTP_USER_AGENT'] == "Apache-HttpClient/UNAVAILABLE (java 1.4)");
706
707                 /*
708                  * register template engines
709                  */
710                 $dc = get_declared_classes();
711                 foreach ($dc as $k) {
712                         if (in_array("ITemplateEngine", class_implements($k))){
713                                 $this->register_template_engine($k);
714                         }
715                 }
716
717                 self::$a = $this;
718
719         }
720
721         function get_basepath() {
722
723                 $basepath = get_config("system", "basepath");
724
725                 if ($basepath == "")
726                         $basepath = dirname(__FILE__);
727
728                 if ($basepath == "")
729                         $basepath = $_SERVER["DOCUMENT_ROOT"];
730
731                 if ($basepath == "")
732                         $basepath = $_SERVER["PWD"];
733
734                 return($basepath);
735         }
736
737         function get_scheme() {
738                 return($this->scheme);
739         }
740
741         function get_baseurl($ssl = false) {
742
743                 // Is the function called statically?
744                 if (!is_object($this))
745                         return(self::$a->get_baseurl($ssl));
746
747                 $scheme = $this->scheme;
748
749                 if((x($this->config,'system')) && (x($this->config['system'],'ssl_policy'))) {
750                         if(intval($this->config['system']['ssl_policy']) === intval(SSL_POLICY_FULL))
751                                 $scheme = 'https';
752
753                         //      Basically, we have $ssl = true on any links which can only be seen by a logged in user
754                         //      (and also the login link). Anything seen by an outsider will have it turned off.
755
756                         if($this->config['system']['ssl_policy'] == SSL_POLICY_SELFSIGN) {
757                                 if($ssl)
758                                         $scheme = 'https';
759                                 else
760                                         $scheme = 'http';
761                         }
762                 }
763
764                 if (get_config('config','hostname') != "")
765                         $this->hostname = get_config('config','hostname');
766
767                 $this->baseurl = $scheme . "://" . $this->hostname . ((isset($this->path) && strlen($this->path)) ? '/' . $this->path : '' );
768                 return $this->baseurl;
769         }
770
771         function set_baseurl($url) {
772                 $parsed = @parse_url($url);
773
774                 $this->baseurl = $url;
775
776                 if($parsed) {
777                         $this->scheme = $parsed['scheme'];
778
779                         $hostname = $parsed['host'];
780                         if(x($parsed,'port'))
781                                 $hostname .= ':' . $parsed['port'];
782                         if(x($parsed,'path'))
783                                 $this->path = trim($parsed['path'],'\\/');
784
785                         if (file_exists(".htpreconfig.php"))
786                                 @include(".htpreconfig.php");
787
788                         if (get_config('config','hostname') != "")
789                                 $this->hostname = get_config('config','hostname');
790
791                         if (!isset($this->hostname) OR ($this->hostname == ""))
792                                 $this->hostname = $hostname;
793                 }
794
795         }
796
797         function get_hostname() {
798                 if (get_config('config','hostname') != "")
799                         $this->hostname = get_config('config','hostname');
800
801                 return $this->hostname;
802         }
803
804         function set_hostname($h) {
805                 $this->hostname = $h;
806         }
807
808         function set_path($p) {
809                 $this->path = trim(trim($p),'/');
810         }
811
812         function get_path() {
813                 return $this->path;
814         }
815
816         function set_pager_total($n) {
817                 $this->pager['total'] = intval($n);
818         }
819
820         function set_pager_itemspage($n) {
821                 $this->pager['itemspage'] = ((intval($n) > 0) ? intval($n) : 0);
822                 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
823         }
824
825         function set_pager_page($n) {
826                 $this->pager['page'] = $n;
827                 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
828         }
829
830         function init_pagehead() {
831                 $interval = ((local_user()) ? get_pconfig(local_user(),'system','update_interval') : 40000);
832
833                 // If the update is "deactivated" set it to the highest integer number (~24 days)
834                 if ($interval < 0)
835                         $interval = 2147483647;
836
837                 if($interval < 10000)
838                         $interval = 40000;
839
840                 // compose the page title from the sitename and the
841                 // current module called
842                 if (!$this->module=='')
843                 {
844                     $this->page['title'] = $this->config['sitename'].' ('.$this->module.')';
845                 } else {
846                     $this->page['title'] = $this->config['sitename'];
847                 }
848
849                 /* put the head template at the beginning of page['htmlhead']
850                  * since the code added by the modules frequently depends on it
851                  * being first
852                  */
853                 if(!isset($this->page['htmlhead']))
854                         $this->page['htmlhead'] = '';
855
856                 // If we're using Smarty, then doing replace_macros() will replace
857                 // any unrecognized variables with a blank string. Since we delay
858                 // replacing $stylesheet until later, we need to replace it now
859                 // with another variable name
860                 if($this->theme['template_engine'] === 'smarty3')
861                         $stylesheet = $this->get_template_ldelim('smarty3') . '$stylesheet' . $this->get_template_rdelim('smarty3');
862                 else
863                         $stylesheet = '$stylesheet';
864
865                 $shortcut_icon = get_config("system", "shortcut_icon");
866                 if ($shortcut_icon == "")
867                         $shortcut_icon = $this->get_baseurl()."/images/friendica-32.png";
868
869                 $touch_icon = get_config("system", "touch_icon");
870                 if ($touch_icon == "")
871                         $touch_icon = $this->get_baseurl()."/images/friendica-128.png";
872
873                 $tpl = get_markup_template('head.tpl');
874                 $this->page['htmlhead'] = replace_macros($tpl,array(
875                         '$baseurl' => $this->get_baseurl(), // FIXME for z_path!!!!
876                         '$local_user' => local_user(),
877                         '$generator' => 'Friendica' . ' ' . FRIENDICA_VERSION,
878                         '$delitem' => t('Delete this item?'),
879                         '$comment' => t('Comment'),
880                         '$showmore' => t('show more'),
881                         '$showfewer' => t('show fewer'),
882                         '$update_interval' => $interval,
883                         '$shortcut_icon' => $shortcut_icon,
884                         '$touch_icon' => $touch_icon,
885                         '$stylesheet' => $stylesheet
886                 )) . $this->page['htmlhead'];
887         }
888
889         function init_page_end() {
890                 if(!isset($this->page['end']))
891                         $this->page['end'] = '';
892                 $tpl = get_markup_template('end.tpl');
893                 $this->page['end'] = replace_macros($tpl,array(
894                         '$baseurl' => $this->get_baseurl() // FIXME for z_path!!!!
895                 )) . $this->page['end'];
896         }
897
898         function set_curl_code($code) {
899                 $this->curl_code = $code;
900         }
901
902         function get_curl_code() {
903                 return $this->curl_code;
904         }
905
906         function set_curl_content_type($content_type) {
907                 $this->curl_content_type = $content_type;
908         }
909
910         function get_curl_content_type() {
911                 return $this->curl_content_type;
912         }
913
914         function set_curl_headers($headers) {
915                 $this->curl_headers = $headers;
916         }
917
918         function get_curl_headers() {
919                 return $this->curl_headers;
920         }
921
922         function get_cached_avatar_image($avatar_image){
923                 return $avatar_image;
924
925                 // The following code is deactivated. It doesn't seem to make any sense and it slows down the system.
926                 /*
927                 if($this->cached_profile_image[$avatar_image])
928                         return $this->cached_profile_image[$avatar_image];
929
930                 $path_parts = explode("/",$avatar_image);
931                 $common_filename = $path_parts[count($path_parts)-1];
932
933                 if($this->cached_profile_picdate[$common_filename]){
934                         $this->cached_profile_image[$avatar_image] = $avatar_image . $this->cached_profile_picdate[$common_filename];
935                 } else {
936                         $r = q("SELECT `contact`.`avatar-date` AS picdate FROM `contact` WHERE `contact`.`thumb` like '%%/%s'",
937                                 $common_filename);
938                         if(! count($r)){
939                                 $this->cached_profile_image[$avatar_image] = $avatar_image;
940                         } else {
941                                 $this->cached_profile_picdate[$common_filename] = "?rev=".urlencode($r[0]['picdate']);
942                                 $this->cached_profile_image[$avatar_image] = $avatar_image.$this->cached_profile_picdate[$common_filename];
943                         }
944                 }
945                 return $this->cached_profile_image[$avatar_image];
946                 */
947         }
948
949
950         /**
951          * @brief Register template engine class
952          * 
953          * If $name is "", is used class static property $class::$name
954          * 
955          * @param string $class
956          * @param string $name
957          */
958         function register_template_engine($class, $name = '') {
959                 if ($name===""){
960                         $v = get_class_vars( $class );
961                         if(x($v,"name")) $name = $v['name'];
962                 }
963                 if ($name===""){
964                         echo "template engine <tt>$class</tt> cannot be registered without a name.\n";
965                         killme();
966                 }
967                 $this->template_engines[$name] = $class;
968         }
969
970         /**
971          * @brief Return template engine instance.
972          * 
973          * If $name is not defined, return engine defined by theme,
974          * or default
975          *
976          * @param strin $name Template engine name
977          * @return object Template Engine instance
978          */
979         function template_engine($name = ''){
980                 if ($name!=="") {
981                         $template_engine = $name;
982                 } else {
983                         $template_engine = 'smarty3';
984                         if (x($this->theme, 'template_engine')) {
985                                 $template_engine = $this->theme['template_engine'];
986                         }
987                 }
988
989                 if (isset($this->template_engines[$template_engine])){
990                         if(isset($this->template_engine_instance[$template_engine])){
991                                 return $this->template_engine_instance[$template_engine];
992                         } else {
993                                 $class = $this->template_engines[$template_engine];
994                                 $obj = new $class;
995                                 $this->template_engine_instance[$template_engine] = $obj;
996                                 return $obj;
997                         }
998                 }
999
1000                 echo "template engine <tt>$template_engine</tt> is not registered!\n"; killme();
1001         }
1002
1003         /**
1004          * @brief Returns the active template engine.
1005          *
1006          * @return string
1007          */
1008         function get_template_engine() {
1009                 return $this->theme['template_engine'];
1010         }
1011
1012         function set_template_engine($engine = 'smarty3') {
1013                 $this->theme['template_engine'] = $engine;
1014                 /*
1015                 $this->theme['template_engine'] = 'smarty3';
1016
1017                 switch($engine) {
1018                         case 'smarty3':
1019                                 if(is_writable('view/smarty3/'))
1020                                         $this->theme['template_engine'] = 'smarty3';
1021                                 break;
1022                         default:
1023                                 break;
1024                 }
1025                 */
1026         }
1027
1028         function get_template_ldelim($engine = 'smarty3') {
1029                 return $this->ldelim[$engine];
1030         }
1031
1032         function get_template_rdelim($engine = 'smarty3') {
1033                 return $this->rdelim[$engine];
1034         }
1035
1036         function save_timestamp($stamp, $value) {
1037                 $duration = (float)(microtime(true)-$stamp);
1038
1039                 $this->performance[$value] += (float)$duration;
1040                 $this->performance["marktime"] += (float)$duration;
1041
1042                 $callstack = $this->callstack();
1043
1044                 $this->callstack[$value][$callstack] += (float)$duration;
1045
1046         }
1047
1048         /**
1049          * @brief Returns a string with a callstack. Can be used for logging.
1050          *
1051          * @return string
1052          */
1053         function callstack() {
1054                 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 6);
1055
1056                 // We remove the first two items from the list since they contain data that we don't need.
1057                 array_shift($trace);
1058                 array_shift($trace);
1059
1060                 $callstack = array();
1061                 foreach ($trace AS $func)
1062                         $callstack[] = $func["function"];
1063
1064                 return implode(", ", $callstack);
1065         }
1066
1067         function mark_timestamp($mark) {
1068                 //$this->performance["markstart"] -= microtime(true) - $this->performance["marktime"];
1069                 $this->performance["markstart"] = microtime(true) - $this->performance["markstart"] - $this->performance["marktime"];
1070         }
1071
1072         function get_useragent() {
1073                 return(FRIENDICA_PLATFORM." '".FRIENDICA_CODENAME."' ".FRIENDICA_VERSION."-".DB_UPDATE_VERSION."; ".$this->get_baseurl());
1074         }
1075
1076         function is_friendica_app() {
1077                 return($this->is_friendica_app);
1078         }
1079
1080 }
1081
1082 /**
1083  * @brief Retrieve the App structure
1084  * 
1085  * Useful in functions which require it but don't get it passed to them
1086  */
1087 function get_app() {
1088         global $a;
1089         return $a;
1090 }
1091
1092
1093 /**
1094  * @brief Multi-purpose function to check variable state.
1095  *
1096  * Usage: x($var) or $x($array, 'key')
1097  *
1098  * returns false if variable/key is not set
1099  * if variable is set, returns 1 if has 'non-zero' value, otherwise returns 0.
1100  * e.g. x('') or x(0) returns 0;
1101  *
1102  * @param string|array $s variable to check
1103  * @param string $k key inside the array to check
1104  *
1105  * @return bool|int
1106  */
1107 function x($s,$k = NULL) {
1108         if($k != NULL) {
1109                 if((is_array($s)) && (array_key_exists($k,$s))) {
1110                         if($s[$k])
1111                                 return (int) 1;
1112                         return (int) 0;
1113         }
1114                 return false;
1115         }
1116         else {
1117                 if(isset($s)) {
1118                         if($s) {
1119                                 return (int) 1;
1120                         }
1121                         return (int) 0;
1122                 }
1123                 return false;
1124         }
1125 }
1126
1127
1128 /**
1129  * @brief Called from db initialisation if db is dead.
1130  */
1131 function system_unavailable() {
1132         include('system_unavailable.php');
1133         system_down();
1134         killme();
1135 }
1136
1137
1138 function clean_urls() {
1139         global $a;
1140         //      if($a->config['system']['clean_urls'])
1141         return true;
1142         //      return false;
1143 }
1144
1145 function z_path() {
1146         global $a;
1147         $base = $a->get_baseurl();
1148         if(! clean_urls())
1149                 $base .= '/?q=';
1150         return $base;
1151 }
1152
1153 /**
1154  * @brief Returns the baseurl.
1155  *
1156  * @see App::get_baseurl()
1157  *
1158  * @return string
1159  */
1160 function z_root() {
1161         global $a;
1162         return $a->get_baseurl();
1163 }
1164
1165 /**
1166  * @brief Return absolut URL for given $path.
1167  *
1168  * @param string $path
1169  *
1170  * @return string
1171  */
1172 function absurl($path) {
1173         if(strpos($path,'/') === 0)
1174                 return z_path() . $path;
1175         return $path;
1176 }
1177
1178 /**
1179  * @brief Function to check if request was an AJAX (xmlhttprequest) request.
1180  *
1181  * @return boolean
1182  */
1183 function is_ajax() {
1184         return (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');
1185 }
1186
1187 function check_db() {
1188
1189         $build = get_config('system','build');
1190         if(! x($build)) {
1191                 set_config('system','build',DB_UPDATE_VERSION);
1192                 $build = DB_UPDATE_VERSION;
1193         }
1194         if($build != DB_UPDATE_VERSION)
1195                 proc_run('php', 'include/dbupdate.php');
1196
1197 }
1198
1199
1200 /**
1201  * Sets the base url for use in cmdline programs which don't have
1202  * $_SERVER variables
1203  */
1204 function check_url(&$a) {
1205
1206         $url = get_config('system','url');
1207
1208         // if the url isn't set or the stored url is radically different
1209         // than the currently visited url, store the current value accordingly.
1210         // "Radically different" ignores common variations such as http vs https
1211         // and www.example.com vs example.com.
1212         // We will only change the url to an ip address if there is no existing setting
1213
1214         if(! x($url))
1215                 $url = set_config('system','url',$a->get_baseurl());
1216         if((! link_compare($url,$a->get_baseurl())) && (! preg_match("/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/",$a->get_hostname)))
1217                 $url = set_config('system','url',$a->get_baseurl());
1218
1219         return;
1220 }
1221
1222
1223 /**
1224  * @brief Automatic database updates
1225  */
1226 function update_db(&$a) {
1227         $build = get_config('system','build');
1228         if(! x($build))
1229                 $build = set_config('system','build',DB_UPDATE_VERSION);
1230
1231         if($build != DB_UPDATE_VERSION) {
1232                 $stored = intval($build);
1233                 $current = intval(DB_UPDATE_VERSION);
1234                 if($stored < $current) {
1235                         load_config('database');
1236
1237                         // We're reporting a different version than what is currently installed.
1238                         // Run any existing update scripts to bring the database up to current.
1239
1240                         // make sure that boot.php and update.php are the same release, we might be
1241                         // updating right this very second and the correct version of the update.php
1242                         // file may not be here yet. This can happen on a very busy site.
1243
1244                         if(DB_UPDATE_VERSION == UPDATE_VERSION) {
1245                                 // Compare the current structure with the defined structure
1246
1247                                 $t = get_config('database','dbupdate_'.DB_UPDATE_VERSION);
1248                                 if($t !== false)
1249                                         return;
1250
1251                                 set_config('database','dbupdate_'.DB_UPDATE_VERSION, time());
1252
1253                                 // run old update routine (wich could modify the schema and
1254                                 // conflits with new routine)
1255                                 for ($x = $stored; $x < NEW_UPDATE_ROUTINE_VERSION; $x++) {
1256                                         $r = run_update_function($x);
1257                                         if (!$r) break;
1258                                 }
1259                                 if ($stored < NEW_UPDATE_ROUTINE_VERSION) $stored = NEW_UPDATE_ROUTINE_VERSION;
1260
1261
1262                                 // run new update routine
1263                                 // it update the structure in one call
1264                                 $retval = update_structure(false, true);
1265                                 if($retval) {
1266                                         update_fail(
1267                                                 DB_UPDATE_VERSION,
1268                                                 $retval
1269                                         );
1270                                         return;
1271                                 } else {
1272                                         set_config('database','dbupdate_'.DB_UPDATE_VERSION, 'success');
1273                                 }
1274
1275                                 // run any left update_nnnn functions in update.php
1276                                 for($x = $stored; $x < $current; $x ++) {
1277                                         $r = run_update_function($x);
1278                                         if (!$r) break;
1279                                 }
1280                         }
1281                 }
1282         }
1283
1284         return;
1285 }
1286
1287 function run_update_function($x) {
1288         if(function_exists('update_' . $x)) {
1289
1290                 // There could be a lot of processes running or about to run.
1291                 // We want exactly one process to run the update command.
1292                 // So store the fact that we're taking responsibility
1293                 // after first checking to see if somebody else already has.
1294
1295                 // If the update fails or times-out completely you may need to
1296                 // delete the config entry to try again.
1297
1298                 $t = get_config('database','update_' . $x);
1299                 if($t !== false)
1300                         return false;
1301                 set_config('database','update_' . $x, time());
1302
1303                 // call the specific update
1304
1305                 $func = 'update_' . $x;
1306                 $retval = $func();
1307
1308                 if($retval) {
1309                         //send the administrator an e-mail
1310                         update_fail(
1311                                 $x,
1312                                 sprintf(t('Update %s failed. See error logs.'), $x)
1313                         );
1314                         return false;
1315                 } else {
1316                         set_config('database','update_' . $x, 'success');
1317                         set_config('system','build', $x + 1);
1318                         return true;
1319                 }
1320         } else {
1321                 set_config('database','update_' . $x, 'success');
1322                 set_config('system','build', $x + 1);
1323                 return true;
1324         }
1325         return true;
1326 }
1327
1328 /**
1329  * @brief Synchronise plugins:
1330  *
1331  * $a->config['system']['addon'] contains a comma-separated list of names
1332  * of plugins/addons which are used on this system.
1333  * Go through the database list of already installed addons, and if we have
1334  * an entry, but it isn't in the config list, call the uninstall procedure
1335  * and mark it uninstalled in the database (for now we'll remove it).
1336  * Then go through the config list and if we have a plugin that isn't installed,
1337  * call the install procedure and add it to the database.
1338  * 
1339  * @param App $a
1340  *
1341          */
1342 function check_plugins(&$a) {
1343
1344         $r = q("SELECT * FROM `addon` WHERE `installed` = 1");
1345         if(count($r))
1346                 $installed = $r;
1347         else
1348                 $installed = array();
1349
1350         $plugins = get_config('system','addon');
1351         $plugins_arr = array();
1352
1353         if($plugins)
1354                 $plugins_arr = explode(',',str_replace(' ', '',$plugins));
1355
1356         $a->plugins = $plugins_arr;
1357
1358         $installed_arr = array();
1359
1360         if(count($installed)) {
1361                 foreach($installed as $i) {
1362                         if(! in_array($i['name'],$plugins_arr)) {
1363                                 uninstall_plugin($i['name']);
1364                         }
1365                         else {
1366                                 $installed_arr[] = $i['name'];
1367                         }
1368                 }
1369         }
1370
1371         if(count($plugins_arr)) {
1372                 foreach($plugins_arr as $p) {
1373                         if(! in_array($p,$installed_arr)) {
1374                                 install_plugin($p);
1375                         }
1376                 }
1377         }
1378
1379
1380         load_hooks();
1381
1382         return;
1383 }
1384
1385 function get_guid($size=16, $prefix = "") {
1386
1387         if ($prefix == "") {
1388                 $a = get_app();
1389                 $prefix = hash("crc32", $a->get_hostname());
1390         }
1391
1392         while (strlen($prefix) < ($size - 13))
1393                 $prefix .= mt_rand();
1394
1395         if ($size >= 24) {
1396                 $prefix = substr($prefix, 0, $size - 22);
1397                 return(str_replace(".", "", uniqid($prefix, true)));
1398         } else {
1399                 $prefix = substr($prefix, 0, max($size - 13, 0));
1400                 return(uniqid($prefix));
1401         }
1402 }
1403
1404 /** 
1405  * @brief Wrapper for adding a login box.
1406  * 
1407  * @param bool $register
1408  *      If $register == true provide a registration link.
1409  *      This will most always depend on the value of $a->config['register_policy'].
1410  * @param bool $hiddens
1411  * 
1412  * @return string
1413  *      Returns the complete html for inserting into the page
1414  * 
1415  * @hooks 'login_hook'
1416  *      string $o
1417  */
1418 function login($register = false, $hiddens=false) {
1419         $a = get_app();
1420         $o = "";
1421         $reg = false;
1422         if ($register) {
1423                 $reg = array(
1424                         'title' => t('Create a New Account'),
1425                         'desc' => t('Register')
1426                 );
1427         }
1428
1429         $noid = get_config('system','no_openid');
1430
1431         $dest_url = $a->get_baseurl(true) . '/' . $a->query_string;
1432
1433         if(local_user()) {
1434                 $tpl = get_markup_template("logout.tpl");
1435         }
1436         else {
1437                 $a->page['htmlhead'] .= replace_macros(get_markup_template("login_head.tpl"),array(
1438                         '$baseurl'              => $a->get_baseurl(true)
1439                 ));
1440
1441                 $tpl = get_markup_template("login.tpl");
1442                 $_SESSION['return_url'] = $a->query_string;
1443                 $a->module = 'login';
1444         }
1445
1446         $o .= replace_macros($tpl, array(
1447
1448                 '$dest_url'     => $dest_url,
1449                 '$logout'       => t('Logout'),
1450                 '$login'        => t('Login'),
1451
1452                 '$lname'                => array('username', t('Nickname or Email address: ') , '', ''),
1453                 '$lpassword'    => array('password', t('Password: '), '', ''),
1454                 '$lremember'    => array('remember', t('Remember me'), 0,  ''),
1455
1456                 '$openid'               => !$noid,
1457                 '$lopenid'      => array('openid_url', t('Or login using OpenID: '),'',''),
1458
1459                 '$hiddens'      => $hiddens,
1460
1461                 '$register'     => $reg,
1462
1463                 '$lostpass'     => t('Forgot your password?'),
1464                 '$lostlink'     => t('Password Reset'),
1465
1466                 '$tostitle'     => t('Website Terms of Service'),
1467                 '$toslink'      => t('terms of service'),
1468
1469                 '$privacytitle' => t('Website Privacy Policy'),
1470                 '$privacylink'  => t('privacy policy'),
1471
1472         ));
1473
1474         call_hooks('login_hook',$o);
1475
1476         return $o;
1477 }
1478
1479 /**
1480  * @brief Used to end the current process, after saving session state.
1481  */
1482 function killme() {
1483         session_write_close();
1484         exit;
1485 }
1486
1487 /**
1488  * @brief Redirect to another URL and terminate this process.
1489  */
1490 function goaway($s) {
1491         header("Location: $s");
1492         killme();
1493 }
1494
1495
1496 /**
1497  * @brief Returns the user id of locally logged in user or false.
1498  * 
1499  * @return int|bool user id or false
1500  */
1501 function local_user() {
1502         if((x($_SESSION,'authenticated')) && (x($_SESSION,'uid')))
1503                 return intval($_SESSION['uid']);
1504         return false;
1505 }
1506
1507 /**
1508  * @brief Returns contact id of authenticated site visitor or false
1509  * 
1510  * @return int|bool visitor_id or false
1511  */
1512 function remote_user() {
1513         if((x($_SESSION,'authenticated')) && (x($_SESSION,'visitor_id')))
1514                 return intval($_SESSION['visitor_id']);
1515         return false;
1516 }
1517
1518 /**
1519  * @brief Show an error message to user.
1520  *
1521  * This function save text in session, to be shown to the user at next page load
1522  *
1523  * @param string $s - Text of notice
1524  */
1525 function notice($s) {
1526         $a = get_app();
1527         if(! x($_SESSION,'sysmsg'))     $_SESSION['sysmsg'] = array();
1528         if($a->interactive)
1529                 $_SESSION['sysmsg'][] = $s;
1530 }
1531
1532 /**
1533  * @brief Show an info message to user.
1534  *
1535  * This function save text in session, to be shown to the user at next page load
1536  *
1537  * @param string $s - Text of notice
1538  */
1539 function info($s) {
1540         $a = get_app();
1541
1542         if (local_user() AND get_pconfig(local_user(),'system','ignore_info'))
1543                 return;
1544
1545         if(! x($_SESSION,'sysmsg_info')) $_SESSION['sysmsg_info'] = array();
1546         if($a->interactive)
1547                 $_SESSION['sysmsg_info'][] = $s;
1548 }
1549
1550
1551 /**
1552  * @brief Wrapper around config to limit the text length of an incoming message
1553  *
1554  * @return int
1555  */
1556 function get_max_import_size() {
1557         global $a;
1558         return ((x($a->config,'max_import_size')) ? $a->config['max_import_size'] : 0 );
1559 }
1560
1561 /**
1562  * @brief Wrap calls to proc_close(proc_open()) and call hook
1563  *      so plugins can take part in process :)
1564  *
1565  * @param string $cmd program to run
1566  * 
1567  * next args are passed as $cmd command line
1568  * e.g.: proc_run("ls","-la","/tmp");
1569  *
1570  * @note $cmd and string args are surrounded with ""
1571  * 
1572  * @hooks 'proc_run'
1573  *      array $arr
1574  */
1575 function proc_run($cmd){
1576
1577         $a = get_app();
1578
1579         $args = func_get_args();
1580
1581         $newargs = array();
1582         if(! count($args))
1583                 return;
1584
1585         // expand any arrays
1586
1587         foreach($args as $arg) {
1588                 if(is_array($arg)) {
1589                         foreach($arg as $n) {
1590                                 $newargs[] = $n;
1591                         }
1592                 }
1593                 else
1594                         $newargs[] = $arg;
1595         }
1596
1597         $args = $newargs;
1598
1599         $arr = array('args' => $args, 'run_cmd' => true);
1600
1601         call_hooks("proc_run", $arr);
1602         if(! $arr['run_cmd'])
1603                 return;
1604
1605         if(count($args) && $args[0] === 'php') {
1606
1607                 if (get_config("system", "worker")) {
1608                         $argv = $args;
1609                         array_shift($argv);
1610
1611                         $parameters = json_encode($argv);
1612                         $found = q("SELECT `id` FROM `workerqueue` WHERE `parameter` = '%s'",
1613                                         dbesc($parameters));
1614
1615                         if (!$found)
1616                                 q("INSERT INTO `workerqueue` (`parameter`, `created`, `priority`)
1617                                                         VALUES ('%s', '%s', %d)",
1618                                         dbesc($parameters),
1619                                         dbesc(datetime_convert()),
1620                                         intval(0));
1621
1622                         // Should we quit and wait for the poller to be called as a cronjob?
1623                         if (get_config("system", "worker_dont_fork"))
1624                                 return;
1625
1626                         // Checking number of workers
1627                         $workers = q("SELECT COUNT(*) AS `workers` FROM `workerqueue` WHERE `executed` != '0000-00-00 00:00:00'");
1628
1629                         // Get number of allowed number of worker threads
1630                         $queues = intval(get_config("system", "worker_queues"));
1631
1632                         if ($queues == 0)
1633                                 $queues = 4;
1634
1635                         // If there are already enough workers running, don't fork another one
1636                         if ($workers[0]["workers"] >= $queues)
1637                                 return;
1638
1639                         // Now call the poller to execute the jobs that we just added to the queue
1640                         $args = array("php", "include/poller.php", "no_cron");
1641                 }
1642
1643                 $args[0] = ((x($a->config,'php_path')) && (strlen($a->config['php_path'])) ? $a->config['php_path'] : 'php');
1644         }
1645
1646         // add baseurl to args. cli scripts can't construct it
1647         $args[] = $a->get_baseurl();
1648
1649         for($x = 0; $x < count($args); $x ++)
1650                 $args[$x] = escapeshellarg($args[$x]);
1651
1652         $cmdline = implode($args," ");
1653
1654         if(get_config('system','proc_windows'))
1655                 proc_close(proc_open('cmd /c start /b ' . $cmdline,array(),$foo,dirname(__FILE__)));
1656         else
1657                 proc_close(proc_open($cmdline." &",array(),$foo,dirname(__FILE__)));
1658 }
1659
1660 function current_theme(){
1661         $app_base_themes = array('duepuntozero', 'dispy', 'quattro');
1662
1663         $a = get_app();
1664
1665         $page_theme = null;
1666
1667         // Find the theme that belongs to the user whose stuff we are looking at
1668
1669         if($a->profile_uid && ($a->profile_uid != local_user())) {
1670                 $r = q("select theme from user where uid = %d limit 1",
1671                         intval($a->profile_uid)
1672                 );
1673                 if($r)
1674                         $page_theme = $r[0]['theme'];
1675         }
1676
1677         // Allow folks to over-rule user themes and always use their own on their own site.
1678         // This works only if the user is on the same server
1679
1680         if($page_theme && local_user() && (local_user() != $a->profile_uid)) {
1681                 if(get_pconfig(local_user(),'system','always_my_theme'))
1682                         $page_theme = null;
1683         }
1684
1685 //              $mobile_detect = new Mobile_Detect();
1686 //              $is_mobile = $mobile_detect->isMobile() || $mobile_detect->isTablet();
1687         $is_mobile = $a->is_mobile || $a->is_tablet;
1688
1689         $standard_system_theme = ((isset($a->config['system']['theme'])) ? $a->config['system']['theme'] : '');
1690         $standard_theme_name = ((isset($_SESSION) && x($_SESSION,'theme')) ? $_SESSION['theme'] : $standard_system_theme);
1691
1692         if($is_mobile) {
1693                 if(isset($_SESSION['show-mobile']) && !$_SESSION['show-mobile']) {
1694                         $system_theme = $standard_system_theme;
1695                         $theme_name = $standard_theme_name;
1696                 }
1697                 else {
1698                         $system_theme = ((isset($a->config['system']['mobile-theme'])) ? $a->config['system']['mobile-theme'] : $standard_system_theme);
1699                         $theme_name = ((isset($_SESSION) && x($_SESSION,'mobile-theme')) ? $_SESSION['mobile-theme'] : $system_theme);
1700
1701                         if($theme_name === '---') {
1702                                 // user has selected to have the mobile theme be the same as the normal one
1703                                 $system_theme = $standard_system_theme;
1704                                 $theme_name = $standard_theme_name;
1705
1706                                 if($page_theme)
1707                                         $theme_name = $page_theme;
1708                         }
1709                 }
1710         }
1711         else {
1712                 $system_theme = $standard_system_theme;
1713                 $theme_name = $standard_theme_name;
1714
1715                 if($page_theme)
1716                         $theme_name = $page_theme;
1717         }
1718
1719         if($theme_name &&
1720                         (file_exists('view/theme/' . $theme_name . '/style.css') ||
1721                                         file_exists('view/theme/' . $theme_name . '/style.php')))
1722                 return($theme_name);
1723
1724         foreach($app_base_themes as $t) {
1725                 if(file_exists('view/theme/' . $t . '/style.css')||
1726                                 file_exists('view/theme/' . $t . '/style.php'))
1727                         return($t);
1728         }
1729
1730         $fallback = array_merge(glob('view/theme/*/style.css'),glob('view/theme/*/style.php'));
1731         if(count($fallback))
1732                 return (str_replace('view/theme/','', substr($fallback[0],0,-10)));
1733
1734 }
1735
1736 /**
1737  * @brief Return full URL to theme which is currently in effect.
1738  * 
1739  * Provide a sane default if nothing is chosen or the specified theme does not exist.
1740  * 
1741  * @return string
1742  */
1743 function current_theme_url() {
1744         global $a;
1745
1746         $t = current_theme();
1747
1748         $opts = (($a->profile_uid) ? '?f=&puid=' . $a->profile_uid : '');
1749         if (file_exists('view/theme/' . $t . '/style.php'))
1750                 return($a->get_baseurl() . '/view/theme/' . $t . '/style.pcss' . $opts);
1751
1752         return($a->get_baseurl() . '/view/theme/' . $t . '/style.css');
1753 }
1754
1755 function feed_birthday($uid,$tz) {
1756
1757         /**
1758          *
1759          * Determine the next birthday, but only if the birthday is published
1760          * in the default profile. We _could_ also look for a private profile that the
1761          * recipient can see, but somebody could get mad at us if they start getting
1762          * public birthday greetings when they haven't made this info public.
1763          *
1764          * Assuming we are able to publish this info, we are then going to convert
1765          * the start time from the owner's timezone to UTC.
1766          *
1767          * This will potentially solve the problem found with some social networks
1768          * where birthdays are converted to the viewer's timezone and salutations from
1769          * elsewhere in the world show up on the wrong day. We will convert it to the
1770          * viewer's timezone also, but first we are going to convert it from the birthday
1771          * person's timezone to GMT - so the viewer may find the birthday starting at
1772          * 6:00PM the day before, but that will correspond to midnight to the birthday person.
1773          *
1774          */
1775
1776
1777         $birthday = '';
1778
1779         if(! strlen($tz))
1780                 $tz = 'UTC';
1781
1782         $p = q("SELECT `dob` FROM `profile` WHERE `is-default` = 1 AND `uid` = %d LIMIT 1",
1783                         intval($uid)
1784         );
1785
1786         if($p && count($p)) {
1787                 $tmp_dob = substr($p[0]['dob'],5);
1788                 if(intval($tmp_dob)) {
1789                         $y = datetime_convert($tz,$tz,'now','Y');
1790                         $bd = $y . '-' . $tmp_dob . ' 00:00';
1791                         $t_dob = strtotime($bd);
1792                         $now = strtotime(datetime_convert($tz,$tz,'now'));
1793                         if($t_dob < $now)
1794                                 $bd = $y + 1 . '-' . $tmp_dob . ' 00:00';
1795                         $birthday = datetime_convert($tz,'UTC',$bd,ATOM_TIME);
1796                 }
1797         }
1798
1799         return $birthday;
1800 }
1801
1802 /**
1803  * @brief Check if current user has admin role.
1804  *
1805  * @return bool true if user is an admin
1806  */
1807 function is_site_admin() {
1808         $a = get_app();
1809
1810         $adminlist = explode(",", str_replace(" ", "", $a->config['admin_email']));
1811
1812         //if(local_user() && x($a->user,'email') && x($a->config,'admin_email') && ($a->user['email'] === $a->config['admin_email']))
1813         if(local_user() && x($a->user,'email') && x($a->config,'admin_email') && in_array($a->user['email'], $adminlist))
1814                 return true;
1815         return false;
1816 }
1817
1818
1819 function load_contact_links($uid) {
1820
1821         $a = get_app();
1822
1823         $ret = array();
1824
1825         if(! $uid || x($a->contacts,'empty'))
1826                 return;
1827
1828         $r = q("SELECT `id`,`network`,`url`,`thumb`, `rel` FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 AND `thumb` != ''",
1829                         intval($uid)
1830         );
1831         if(count($r)) {
1832                 foreach($r as $rr){
1833                         $url = normalise_link($rr['url']);
1834                         $ret[$url] = $rr;
1835                 }
1836         } else
1837                 $ret['empty'] = true;
1838
1839         $a->contacts = $ret;
1840         return;
1841 }
1842
1843 /**
1844  * @brief Returns querystring as string from a mapped array.
1845  *
1846  * @param array $params mapped array with query parameters
1847  * @param string $name of parameter, default null
1848  *
1849  * @return string
1850  */
1851 function build_querystring($params, $name=null) {
1852         $ret = "";
1853         foreach($params as $key=>$val) {
1854                 if(is_array($val)) {
1855                         if($name==null) {
1856                                 $ret .= build_querystring($val, $key);
1857                         } else {
1858                                 $ret .= build_querystring($val, $name."[$key]");
1859                         }
1860                 } else {
1861                         $val = urlencode($val);
1862                         if($name!=null) {
1863                                 $ret.=$name."[$key]"."=$val&";
1864                         } else {
1865                                 $ret.= "$key=$val&";
1866                         }
1867                 }
1868         }
1869         return $ret;
1870 }
1871
1872 function explode_querystring($query) {
1873         $arg_st = strpos($query, '?');
1874         if($arg_st !== false) {
1875                 $base = substr($query, 0, $arg_st);
1876                 $arg_st += 1;
1877         } else {
1878                 $base = '';
1879                 $arg_st = 0;
1880         }
1881
1882         $args = explode('&', substr($query, $arg_st));
1883         foreach($args as $k=>$arg) {
1884                 if($arg === '')
1885                         unset($args[$k]);
1886         }
1887         $args = array_values($args);
1888
1889         if(!$base) {
1890                 $base = $args[0];
1891                 unset($args[0]);
1892                 $args = array_values($args);
1893         }
1894
1895         return array(
1896                 'base' => $base,
1897                 'args' => $args,
1898         );
1899 }
1900
1901 /**
1902 * Returns the complete URL of the current page, e.g.: http(s)://something.com/network
1903 *
1904 * Taken from http://webcheatsheet.com/php/get_current_page_url.php
1905 */
1906 function curPageURL() {
1907         $pageURL = 'http';
1908         if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
1909         $pageURL .= "://";
1910         if ($_SERVER["SERVER_PORT"] != "80" && $_SERVER["SERVER_PORT"] != "443") {
1911                 $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
1912         } else {
1913                 $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
1914         }
1915         return $pageURL;
1916 }
1917
1918 function random_digits($digits) {
1919         $rn = '';
1920         for($i = 0; $i < $digits; $i++) {
1921                 $rn .= rand(0,9);
1922         }
1923         return $rn;
1924 }
1925
1926 function get_server() {
1927         $server = get_config("system", "directory");
1928
1929         if ($server == "")
1930                 $server = "http://dir.friendi.ca";
1931
1932         return($server);
1933 }
1934
1935 function get_cachefile($file, $writemode = true) {
1936         $cache = get_itemcachepath();
1937
1938         if ((! $cache) || (! is_dir($cache)))
1939                 return("");
1940
1941         $subfolder = $cache."/".substr($file, 0, 2);
1942
1943         $cachepath = $subfolder."/".$file;
1944
1945         if ($writemode) {
1946                 if (!is_dir($subfolder)) {
1947                         mkdir($subfolder);
1948                         chmod($subfolder, 0777);
1949                 }
1950         }
1951
1952         return($cachepath);
1953 }
1954
1955 function clear_cache($basepath = "", $path = "") {
1956         if ($path == "") {
1957                 $basepath = get_itemcachepath();
1958                 $path = $basepath;
1959         }
1960
1961         if (($path == "") OR (!is_dir($path)))
1962                 return;
1963
1964         if (substr(realpath($path), 0, strlen($basepath)) != $basepath)
1965                 return;
1966
1967         $cachetime = (int)get_config('system','itemcache_duration');
1968         if ($cachetime == 0)
1969                 $cachetime = 86400;
1970
1971         if (is_writable($path)){
1972                 if ($dh = opendir($path)) {
1973                         while (($file = readdir($dh)) !== false) {
1974                                 $fullpath = $path."/".$file;
1975                                 if ((filetype($fullpath) == "dir") and ($file != ".") and ($file != ".."))
1976                                         clear_cache($basepath, $fullpath);
1977                                 if ((filetype($fullpath) == "file") and (filectime($fullpath) < (time() - $cachetime)))
1978                                         unlink($fullpath);
1979                         }
1980                         closedir($dh);
1981                 }
1982         }
1983 }
1984
1985 function get_itemcachepath() {
1986         // Checking, if the cache is deactivated
1987         $cachetime = (int)get_config('system','itemcache_duration');
1988         if ($cachetime < 0)
1989                 return "";
1990
1991         $itemcache = get_config('system','itemcache');
1992         if (($itemcache != "") AND is_dir($itemcache) AND is_writable($itemcache))
1993                 return($itemcache);
1994
1995         $temppath = get_temppath();
1996
1997         if ($temppath != "") {
1998                 $itemcache = $temppath."/itemcache";
1999                 if(!file_exists($itemcache) && !is_dir($itemcache)) {
2000                         mkdir($itemcache);
2001                 }
2002
2003                 if (is_dir($itemcache) AND is_writable($itemcache)) {
2004                         set_config("system", "itemcache", $itemcache);
2005                         return($itemcache);
2006                 }
2007         }
2008         return "";
2009 }
2010
2011 function get_lockpath() {
2012         $lockpath = get_config('system','lockpath');
2013         if (($lockpath != "") AND is_dir($lockpath) AND is_writable($lockpath))
2014                 return($lockpath);
2015
2016         $temppath = get_temppath();
2017
2018         if ($temppath != "") {
2019                 $lockpath = $temppath."/lock";
2020
2021                 if (!is_dir($lockpath))
2022                         mkdir($lockpath);
2023                 elseif (!is_writable($lockpath))
2024                         $lockpath = $temppath;
2025
2026                 if (is_dir($lockpath) AND is_writable($lockpath)) {
2027                         set_config("system", "lockpath", $lockpath);
2028                         return($lockpath);
2029                 }
2030         }
2031         return "";
2032 }
2033
2034 function get_temppath() {
2035         $a = get_app();
2036
2037         $temppath = get_config("system","temppath");
2038         if (($temppath != "") AND is_dir($temppath) AND is_writable($temppath))
2039                 return($temppath);
2040
2041         $temppath = sys_get_temp_dir();
2042         if (($temppath != "") AND is_dir($temppath) AND is_writable($temppath)) {
2043                 $temppath .= "/".$a->get_hostname();
2044                 if (!is_dir($temppath))
2045                         mkdir($temppath);
2046
2047                 if (is_dir($temppath) AND is_writable($temppath)) {
2048                         set_config("system", "temppath", $temppath);
2049                         return($temppath);
2050                 }
2051         }
2052
2053         return("");
2054 }
2055
2056 function set_template_engine(&$a, $engine = 'internal') {
2057 /// @note This function is no longer necessary, but keep it as a wrapper to the class method
2058 /// to avoid breaking themes again unnecessarily
2059
2060         $a->set_template_engine($engine);
2061 }
2062
2063 if(!function_exists('exif_imagetype')) {
2064         function exif_imagetype($file) {
2065                 $size = getimagesize($file);
2066                 return($size[2]);
2067         }
2068 }
2069
2070 function validate_include(&$file) {
2071         $orig_file = $file;
2072
2073         $file = realpath($file);
2074
2075         if (strpos($file, getcwd()) !== 0)
2076                 return false;
2077
2078         $file = str_replace(getcwd()."/", "", $file, $count);
2079         if ($count != 1)
2080                 return false;
2081
2082         if ($orig_file !== $file)
2083                 return false;
2084
2085         $valid = false;
2086         if (strpos($file, "include/") === 0)
2087                 $valid = true;
2088
2089         if (strpos($file, "addon/") === 0)
2090                 $valid = true;
2091
2092         if (!$valid)
2093                 return false;
2094
2095         return true;
2096 }
2097
2098 function current_load() {
2099         if (!function_exists('sys_getloadavg'))
2100                 return false;
2101
2102         $load_arr = sys_getloadavg();
2103
2104         if (!is_array($load_arr))
2105                 return false;
2106
2107         return max($load_arr);
2108 }
2109
2110 /**
2111  * @brief get c-style args
2112  * 
2113  * @return int
2114  */
2115 function argc() {
2116         return get_app()->argc;
2117 }
2118
2119 /**
2120  * @brief Returns the value of a argv key
2121  * 
2122  * @param int $x argv key
2123  * @return string Value of the argv key
2124  */
2125 function argv($x) {
2126         if(array_key_exists($x,get_app()->argv))
2127                 return get_app()->argv[$x];
2128
2129         return '';
2130 }