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