]> git.mxchange.org Git - friendica.git/blob - boot.php
Merge pull request #2264 from tobiasd/20160118-admin2
[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',      1193      );
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         public  $callstack = array();
471
472         public $nav_sel;
473
474         public $category;
475
476
477         // Allow themes to control internal parameters
478         // by changing App values in theme.php
479
480         public  $sourcename = '';
481         public  $videowidth = 425;
482         public  $videoheight = 350;
483         public  $force_max_items = 0;
484         public  $theme_thread_allow = true;
485         public  $theme_events_in_profile = true;
486
487         /**
488          * @brief An array for all theme-controllable parameters
489          *
490          * Mostly unimplemented yet. Only options 'template_engine' and
491          * beyond are used.
492          */
493         public  $theme = array(
494                 'sourcename' => '',
495                 'videowidth' => 425,
496                 'videoheight' => 350,
497                 'force_max_items' => 0,
498                 'thread_allow' => true,
499                 'stylesheet' => '',
500                 'template_engine' => 'smarty3',
501         );
502
503         /**
504          * @brief An array of registered template engines ('name'=>'class name')
505          */
506         public $template_engines = array();
507         /**
508          * @brief An array of instanced template engines ('name'=>'instance')
509          */
510         public $template_engine_instance = array();
511
512         private $ldelim = array(
513                 'internal' => '',
514                 'smarty3' => '{{'
515         );
516         private $rdelim = array(
517                 'internal' => '',
518                 'smarty3' => '}}'
519         );
520
521         private $scheme;
522         private $hostname;
523         private $baseurl;
524         private $db;
525
526         private $curl_code;
527         private $curl_content_type;
528         private $curl_headers;
529
530         private $cached_profile_image;
531         private $cached_profile_picdate;
532
533         /**
534          * @brief App constructor.
535          */
536         function __construct() {
537
538                 global $default_timezone;
539
540                 $hostname = "";
541
542                 if (file_exists(".htpreconfig.php"))
543                         @include(".htpreconfig.php");
544
545                 $this->timezone = ((x($default_timezone)) ? $default_timezone : 'UTC');
546
547                 date_default_timezone_set($this->timezone);
548
549                 $this->performance["start"] = microtime(true);
550                 $this->performance["database"] = 0;
551                 $this->performance["network"] = 0;
552                 $this->performance["file"] = 0;
553                 $this->performance["rendering"] = 0;
554                 $this->performance["parser"] = 0;
555                 $this->performance["marktime"] = 0;
556                 $this->performance["markstart"] = microtime(true);
557
558                 $this->callstack["database"] = array();
559                 $this->callstack["network"] = array();
560                 $this->callstack["file"] = array();
561                 $this->callstack["rendering"] = array();
562                 $this->callstack["parser"] = array();
563
564                 $this->config = array();
565                 $this->page = array();
566                 $this->pager= array();
567
568                 $this->query_string = '';
569
570                 startup();
571
572                 set_include_path(
573                                 'include' . PATH_SEPARATOR
574                                 . 'library' . PATH_SEPARATOR
575                                 . 'library/phpsec' . PATH_SEPARATOR
576                                 . 'library/langdet' . PATH_SEPARATOR
577                                 . '.' );
578
579
580                 $this->scheme = 'http';
581                 if(x($_SERVER,'HTTPS') && $_SERVER['HTTPS'])
582                         $this->scheme = 'https';
583                 elseif(x($_SERVER,'SERVER_PORT') && (intval($_SERVER['SERVER_PORT']) == 443))
584                         $this->scheme = 'https';
585
586                 if(x($_SERVER,'SERVER_NAME')) {
587                         $this->hostname = $_SERVER['SERVER_NAME'];
588
589                         // See bug 437 - this didn't work so disabling it
590                         //if(stristr($this->hostname,'xn--')) {
591                                 // PHP or webserver may have converted idn to punycode, so
592                                 // convert punycode back to utf-8
593                         //      require_once('library/simplepie/idn/idna_convert.class.php');
594                         //      $x = new idna_convert();
595                         //      $this->hostname = $x->decode($_SERVER['SERVER_NAME']);
596                         //}
597
598                         if(x($_SERVER,'SERVER_PORT') && $_SERVER['SERVER_PORT'] != 80 && $_SERVER['SERVER_PORT'] != 443)
599                                 $this->hostname .= ':' . $_SERVER['SERVER_PORT'];
600                         /*
601                          * Figure out if we are running at the top of a domain
602                          * or in a sub-directory and adjust accordingly
603                          */
604
605                         $path = trim(dirname($_SERVER['SCRIPT_NAME']),'/\\');
606                         if(isset($path) && strlen($path) && ($path != $this->path))
607                                 $this->path = $path;
608                 }
609
610                 if ($hostname != "")
611                         $this->hostname = $hostname;
612
613                 if (is_array($_SERVER["argv"]) && $_SERVER["argc"]>1 && substr(end($_SERVER["argv"]), 0, 4)=="http" ) {
614                         $this->set_baseurl(array_pop($_SERVER["argv"]) );
615                         $_SERVER["argc"] --;
616                 }
617
618                 #set_include_path("include/$this->hostname" . PATH_SEPARATOR . get_include_path());
619
620                 if((x($_SERVER,'QUERY_STRING')) && substr($_SERVER['QUERY_STRING'],0,9) === "pagename=") {
621                         $this->query_string = substr($_SERVER['QUERY_STRING'],9);
622                         // removing trailing / - maybe a nginx problem
623                         if (substr($this->query_string, 0, 1) == "/")
624                                 $this->query_string = substr($this->query_string, 1);
625                 } elseif((x($_SERVER,'QUERY_STRING')) && substr($_SERVER['QUERY_STRING'],0,2) === "q=") {
626                         $this->query_string = substr($_SERVER['QUERY_STRING'],2);
627                         // removing trailing / - maybe a nginx problem
628                         if (substr($this->query_string, 0, 1) == "/")
629                                 $this->query_string = substr($this->query_string, 1);
630                 }
631
632                 if (x($_GET,'pagename'))
633                         $this->cmd = trim($_GET['pagename'],'/\\');
634                 elseif (x($_GET,'q'))
635                         $this->cmd = trim($_GET['q'],'/\\');
636
637
638                 // fix query_string
639                 $this->query_string = str_replace($this->cmd."&",$this->cmd."?", $this->query_string);
640
641
642                 // unix style "homedir"
643
644                 if(substr($this->cmd,0,1) === '~')
645                         $this->cmd = 'profile/' . substr($this->cmd,1);
646
647                 // Diaspora style profile url
648
649                 if(substr($this->cmd,0,2) === 'u/')
650                         $this->cmd = 'profile/' . substr($this->cmd,2);
651
652
653                 /*
654                  *
655                  * Break the URL path into C style argc/argv style arguments for our
656                  * modules. Given "http://example.com/module/arg1/arg2", $this->argc
657                  * will be 3 (integer) and $this->argv will contain:
658                  *   [0] => 'module'
659                  *   [1] => 'arg1'
660                  *   [2] => 'arg2'
661                  *
662                  *
663                  * There will always be one argument. If provided a naked domain
664                  * URL, $this->argv[0] is set to "home".
665                  *
666                  */
667
668                 $this->argv = explode('/',$this->cmd);
669                 $this->argc = count($this->argv);
670                 if((array_key_exists('0',$this->argv)) && strlen($this->argv[0])) {
671                         $this->module = str_replace(".", "_", $this->argv[0]);
672                         $this->module = str_replace("-", "_", $this->module);
673                 }
674                 else {
675                         $this->argc = 1;
676                         $this->argv = array('home');
677                         $this->module = 'home';
678                 }
679
680                 /*
681                  * See if there is any page number information, and initialise
682                  * pagination
683                  */
684
685                 $this->pager['page'] = ((x($_GET,'page') && intval($_GET['page']) > 0) ? intval($_GET['page']) : 1);
686                 $this->pager['itemspage'] = 50;
687                 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
688                 if($this->pager['start'] < 0)
689                         $this->pager['start'] = 0;
690                 $this->pager['total'] = 0;
691
692                 /*
693                  * Detect mobile devices
694                  */
695
696                 $mobile_detect = new Mobile_Detect();
697                 $this->is_mobile = $mobile_detect->isMobile();
698                 $this->is_tablet = $mobile_detect->isTablet();
699
700                 // Friendica-Client
701                 $this->is_friendica_app = ($_SERVER['HTTP_USER_AGENT'] == "Apache-HttpClient/UNAVAILABLE (java 1.4)");
702
703                 /*
704                  * register template engines
705                  */
706                 $dc = get_declared_classes();
707                 foreach ($dc as $k) {
708                         if (in_array("ITemplateEngine", class_implements($k))){
709                                 $this->register_template_engine($k);
710                         }
711                 }
712
713         }
714
715         function get_basepath() {
716
717                 $basepath = get_config("system", "basepath");
718
719                 if ($basepath == "")
720                         $basepath = dirname(__FILE__);
721
722                 if ($basepath == "")
723                         $basepath = $_SERVER["DOCUMENT_ROOT"];
724
725                 if ($basepath == "")
726                         $basepath = $_SERVER["PWD"];
727
728                 return($basepath);
729         }
730
731         function get_scheme() {
732                 return($this->scheme);
733         }
734
735         function get_baseurl($ssl = false) {
736
737                 $scheme = $this->scheme;
738
739                 if((x($this->config,'system')) && (x($this->config['system'],'ssl_policy'))) {
740                         if(intval($this->config['system']['ssl_policy']) === intval(SSL_POLICY_FULL))
741                                 $scheme = 'https';
742
743                         //      Basically, we have $ssl = true on any links which can only be seen by a logged in user
744                         //      (and also the login link). Anything seen by an outsider will have it turned off.
745
746                         if($this->config['system']['ssl_policy'] == SSL_POLICY_SELFSIGN) {
747                                 if($ssl)
748                                         $scheme = 'https';
749                                 else
750                                         $scheme = 'http';
751                         }
752                 }
753
754                 if (get_config('config','hostname') != "")
755                         $this->hostname = get_config('config','hostname');
756
757                 $this->baseurl = $scheme . "://" . $this->hostname . ((isset($this->path) && strlen($this->path)) ? '/' . $this->path : '' );
758                 return $this->baseurl;
759         }
760
761         function set_baseurl($url) {
762                 $parsed = @parse_url($url);
763
764                 $this->baseurl = $url;
765
766                 if($parsed) {
767                         $this->scheme = $parsed['scheme'];
768
769                         $hostname = $parsed['host'];
770                         if(x($parsed,'port'))
771                                 $hostname .= ':' . $parsed['port'];
772                         if(x($parsed,'path'))
773                                 $this->path = trim($parsed['path'],'\\/');
774
775                         if (file_exists(".htpreconfig.php"))
776                                 @include(".htpreconfig.php");
777
778                         if (get_config('config','hostname') != "")
779                                 $this->hostname = get_config('config','hostname');
780
781                         if (!isset($this->hostname) OR ($this->hostname == ""))
782                                 $this->hostname = $hostname;
783                 }
784
785         }
786
787         function get_hostname() {
788                 if (get_config('config','hostname') != "")
789                         $this->hostname = get_config('config','hostname');
790
791                 return $this->hostname;
792         }
793
794         function set_hostname($h) {
795                 $this->hostname = $h;
796         }
797
798         function set_path($p) {
799                 $this->path = trim(trim($p),'/');
800         }
801
802         function get_path() {
803                 return $this->path;
804         }
805
806         function set_pager_total($n) {
807                 $this->pager['total'] = intval($n);
808         }
809
810         function set_pager_itemspage($n) {
811                 $this->pager['itemspage'] = ((intval($n) > 0) ? intval($n) : 0);
812                 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
813         }
814
815         function set_pager_page($n) {
816                 $this->pager['page'] = $n;
817                 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
818         }
819
820         function init_pagehead() {
821                 $interval = ((local_user()) ? get_pconfig(local_user(),'system','update_interval') : 40000);
822
823                 // If the update is "deactivated" set it to the highest integer number (~24 days)
824                 if ($interval < 0)
825                         $interval = 2147483647;
826
827                 if($interval < 10000)
828                         $interval = 40000;
829
830                 // compose the page title from the sitename and the
831                 // current module called
832                 if (!$this->module=='')
833                 {
834                     $this->page['title'] = $this->config['sitename'].' ('.$this->module.')';
835                 } else {
836                     $this->page['title'] = $this->config['sitename'];
837                 }
838
839                 /* put the head template at the beginning of page['htmlhead']
840                  * since the code added by the modules frequently depends on it
841                  * being first
842                  */
843                 if(!isset($this->page['htmlhead']))
844                         $this->page['htmlhead'] = '';
845
846                 // If we're using Smarty, then doing replace_macros() will replace
847                 // any unrecognized variables with a blank string. Since we delay
848                 // replacing $stylesheet until later, we need to replace it now
849                 // with another variable name
850                 if($this->theme['template_engine'] === 'smarty3')
851                         $stylesheet = $this->get_template_ldelim('smarty3') . '$stylesheet' . $this->get_template_rdelim('smarty3');
852                 else
853                         $stylesheet = '$stylesheet';
854
855                 $shortcut_icon = get_config("system", "shortcut_icon");
856                 if ($shortcut_icon == "")
857                         $shortcut_icon = $this->get_baseurl()."/images/friendica-32.png";
858
859                 $touch_icon = get_config("system", "touch_icon");
860                 if ($touch_icon == "")
861                         $touch_icon = $this->get_baseurl()."/images/friendica-128.png";
862
863                 $tpl = get_markup_template('head.tpl');
864                 $this->page['htmlhead'] = replace_macros($tpl,array(
865                         '$baseurl' => $this->get_baseurl(), // FIXME for z_path!!!!
866                         '$local_user' => local_user(),
867                         '$generator' => 'Friendica' . ' ' . FRIENDICA_VERSION,
868                         '$delitem' => t('Delete this item?'),
869                         '$comment' => t('Comment'),
870                         '$showmore' => t('show more'),
871                         '$showfewer' => t('show fewer'),
872                         '$update_interval' => $interval,
873                         '$shortcut_icon' => $shortcut_icon,
874                         '$touch_icon' => $touch_icon,
875                         '$stylesheet' => $stylesheet
876                 )) . $this->page['htmlhead'];
877         }
878
879         function init_page_end() {
880                 if(!isset($this->page['end']))
881                         $this->page['end'] = '';
882                 $tpl = get_markup_template('end.tpl');
883                 $this->page['end'] = replace_macros($tpl,array(
884                         '$baseurl' => $this->get_baseurl() // FIXME for z_path!!!!
885                 )) . $this->page['end'];
886         }
887
888         function set_curl_code($code) {
889                 $this->curl_code = $code;
890         }
891
892         function get_curl_code() {
893                 return $this->curl_code;
894         }
895
896         function set_curl_content_type($content_type) {
897                 $this->curl_content_type = $content_type;
898         }
899
900         function get_curl_content_type() {
901                 return $this->curl_content_type;
902         }
903
904         function set_curl_headers($headers) {
905                 $this->curl_headers = $headers;
906         }
907
908         function get_curl_headers() {
909                 return $this->curl_headers;
910         }
911
912         function get_cached_avatar_image($avatar_image){
913                 return $avatar_image;
914
915                 // The following code is deactivated. It doesn't seem to make any sense and it slows down the system.
916                 /*
917                 if($this->cached_profile_image[$avatar_image])
918                         return $this->cached_profile_image[$avatar_image];
919
920                 $path_parts = explode("/",$avatar_image);
921                 $common_filename = $path_parts[count($path_parts)-1];
922
923                 if($this->cached_profile_picdate[$common_filename]){
924                         $this->cached_profile_image[$avatar_image] = $avatar_image . $this->cached_profile_picdate[$common_filename];
925                 } else {
926                         $r = q("SELECT `contact`.`avatar-date` AS picdate FROM `contact` WHERE `contact`.`thumb` like '%%/%s'",
927                                 $common_filename);
928                         if(! count($r)){
929                                 $this->cached_profile_image[$avatar_image] = $avatar_image;
930                         } else {
931                                 $this->cached_profile_picdate[$common_filename] = "?rev=".urlencode($r[0]['picdate']);
932                                 $this->cached_profile_image[$avatar_image] = $avatar_image.$this->cached_profile_picdate[$common_filename];
933                         }
934                 }
935                 return $this->cached_profile_image[$avatar_image];
936                 */
937         }
938
939
940         /**
941          * @brief Register template engine class
942          * 
943          * If $name is "", is used class static property $class::$name
944          * 
945          * @param string $class
946          * @param string $name
947          */
948         function register_template_engine($class, $name = '') {
949                 if ($name===""){
950                         $v = get_class_vars( $class );
951                         if(x($v,"name")) $name = $v['name'];
952                 }
953                 if ($name===""){
954                         echo "template engine <tt>$class</tt> cannot be registered without a name.\n";
955                         killme();
956                 }
957                 $this->template_engines[$name] = $class;
958         }
959
960         /**
961          * @brief Return template engine instance.
962          * 
963          * If $name is not defined, return engine defined by theme,
964          * or default
965          *
966          * @param strin $name Template engine name
967          * @return object Template Engine instance
968          */
969         function template_engine($name = ''){
970                 if ($name!=="") {
971                         $template_engine = $name;
972                 } else {
973                         $template_engine = 'smarty3';
974                         if (x($this->theme, 'template_engine')) {
975                                 $template_engine = $this->theme['template_engine'];
976                         }
977                 }
978
979                 if (isset($this->template_engines[$template_engine])){
980                         if(isset($this->template_engine_instance[$template_engine])){
981                                 return $this->template_engine_instance[$template_engine];
982                         } else {
983                                 $class = $this->template_engines[$template_engine];
984                                 $obj = new $class;
985                                 $this->template_engine_instance[$template_engine] = $obj;
986                                 return $obj;
987                         }
988                 }
989
990                 echo "template engine <tt>$template_engine</tt> is not registered!\n"; killme();
991         }
992
993         /**
994          * @brief Returns the active template engine.
995          *
996          * @return string
997          */
998         function get_template_engine() {
999                 return $this->theme['template_engine'];
1000         }
1001
1002         function set_template_engine($engine = 'smarty3') {
1003                 $this->theme['template_engine'] = $engine;
1004                 /*
1005                 $this->theme['template_engine'] = 'smarty3';
1006
1007                 switch($engine) {
1008                         case 'smarty3':
1009                                 if(is_writable('view/smarty3/'))
1010                                         $this->theme['template_engine'] = 'smarty3';
1011                                 break;
1012                         default:
1013                                 break;
1014                 }
1015                 */
1016         }
1017
1018         function get_template_ldelim($engine = 'smarty3') {
1019                 return $this->ldelim[$engine];
1020         }
1021
1022         function get_template_rdelim($engine = 'smarty3') {
1023                 return $this->rdelim[$engine];
1024         }
1025
1026         function save_timestamp($stamp, $value) {
1027                 $duration = (float)(microtime(true)-$stamp);
1028
1029                 $this->performance[$value] += (float)$duration;
1030                 $this->performance["marktime"] += (float)$duration;
1031
1032                 // Trace the different functions with their timestamps
1033                 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 5);
1034
1035                 array_shift($trace);
1036
1037                 $function = array();
1038                 foreach ($trace AS $func)
1039                         $function[] = $func["function"];
1040
1041                 $function = implode(", ", $function);
1042
1043                 $this->callstack[$value][$function] += (float)$duration;
1044
1045         }
1046
1047         function mark_timestamp($mark) {
1048                 //$this->performance["markstart"] -= microtime(true) - $this->performance["marktime"];
1049                 $this->performance["markstart"] = microtime(true) - $this->performance["markstart"] - $this->performance["marktime"];
1050         }
1051
1052         function get_useragent() {
1053                 return(FRIENDICA_PLATFORM." '".FRIENDICA_CODENAME."' ".FRIENDICA_VERSION."-".DB_UPDATE_VERSION."; ".$this->get_baseurl());
1054         }
1055
1056         function is_friendica_app() {
1057                 return($this->is_friendica_app);
1058         }
1059
1060 }
1061
1062 /**
1063  * @brief Retrieve the App structure
1064  * 
1065  * Useful in functions which require it but don't get it passed to them
1066  */
1067 function get_app() {
1068         global $a;
1069         return $a;
1070 }
1071
1072
1073 /**
1074  * @brief Multi-purpose function to check variable state.
1075  *
1076  * Usage: x($var) or $x($array, 'key')
1077  *
1078  * returns false if variable/key is not set
1079  * if variable is set, returns 1 if has 'non-zero' value, otherwise returns 0.
1080  * e.g. x('') or x(0) returns 0;
1081  *
1082  * @param string|array $s variable to check
1083  * @param string $k key inside the array to check
1084  *
1085  * @return bool|int
1086  */
1087 function x($s,$k = NULL) {
1088         if($k != NULL) {
1089                 if((is_array($s)) && (array_key_exists($k,$s))) {
1090                         if($s[$k])
1091                                 return (int) 1;
1092                         return (int) 0;
1093         }
1094                 return false;
1095         }
1096         else {
1097                 if(isset($s)) {
1098                         if($s) {
1099                                 return (int) 1;
1100                         }
1101                         return (int) 0;
1102                 }
1103                 return false;
1104         }
1105 }
1106
1107
1108 /**
1109  * @brief Called from db initialisation if db is dead.
1110  */
1111 function system_unavailable() {
1112         include('system_unavailable.php');
1113         system_down();
1114         killme();
1115 }
1116
1117
1118 function clean_urls() {
1119         global $a;
1120         //      if($a->config['system']['clean_urls'])
1121         return true;
1122         //      return false;
1123 }
1124
1125 function z_path() {
1126         global $a;
1127         $base = $a->get_baseurl();
1128         if(! clean_urls())
1129                 $base .= '/?q=';
1130         return $base;
1131 }
1132
1133 /**
1134  * @brief Returns the baseurl.
1135  *
1136  * @see App::get_baseurl()
1137  *
1138  * @return string
1139  */
1140 function z_root() {
1141         global $a;
1142         return $a->get_baseurl();
1143 }
1144
1145 /**
1146  * @brief Return absolut URL for given $path.
1147  *
1148  * @param string $path
1149  *
1150  * @return string
1151  */
1152 function absurl($path) {
1153         if(strpos($path,'/') === 0)
1154                 return z_path() . $path;
1155         return $path;
1156 }
1157
1158 /**
1159  * @brief Function to check if request was an AJAX (xmlhttprequest) request.
1160  *
1161  * @return boolean
1162  */
1163 function is_ajax() {
1164         return (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');
1165 }
1166
1167 function check_db() {
1168
1169         $build = get_config('system','build');
1170         if(! x($build)) {
1171                 set_config('system','build',DB_UPDATE_VERSION);
1172                 $build = DB_UPDATE_VERSION;
1173         }
1174         if($build != DB_UPDATE_VERSION)
1175                 proc_run('php', 'include/dbupdate.php');
1176
1177 }
1178
1179
1180 /**
1181  * Sets the base url for use in cmdline programs which don't have
1182  * $_SERVER variables
1183  */
1184 function check_url(&$a) {
1185
1186         $url = get_config('system','url');
1187
1188         // if the url isn't set or the stored url is radically different
1189         // than the currently visited url, store the current value accordingly.
1190         // "Radically different" ignores common variations such as http vs https
1191         // and www.example.com vs example.com.
1192         // We will only change the url to an ip address if there is no existing setting
1193
1194         if(! x($url))
1195                 $url = set_config('system','url',$a->get_baseurl());
1196         if((! link_compare($url,$a->get_baseurl())) && (! preg_match("/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/",$a->get_hostname)))
1197                 $url = set_config('system','url',$a->get_baseurl());
1198
1199         return;
1200 }
1201
1202
1203 /**
1204  * @brief Automatic database updates
1205  */
1206 function update_db(&$a) {
1207         $build = get_config('system','build');
1208         if(! x($build))
1209                 $build = set_config('system','build',DB_UPDATE_VERSION);
1210
1211         if($build != DB_UPDATE_VERSION) {
1212                 $stored = intval($build);
1213                 $current = intval(DB_UPDATE_VERSION);
1214                 if($stored < $current) {
1215                         load_config('database');
1216
1217                         // We're reporting a different version than what is currently installed.
1218                         // Run any existing update scripts to bring the database up to current.
1219
1220                         // make sure that boot.php and update.php are the same release, we might be
1221                         // updating right this very second and the correct version of the update.php
1222                         // file may not be here yet. This can happen on a very busy site.
1223
1224                         if(DB_UPDATE_VERSION == UPDATE_VERSION) {
1225                                 // Compare the current structure with the defined structure
1226
1227                                 $t = get_config('database','dbupdate_'.DB_UPDATE_VERSION);
1228                                 if($t !== false)
1229                                         return;
1230
1231                                 set_config('database','dbupdate_'.DB_UPDATE_VERSION, time());
1232
1233                                 // run old update routine (wich could modify the schema and
1234                                 // conflits with new routine)
1235                                 for ($x = $stored; $x < NEW_UPDATE_ROUTINE_VERSION; $x++) {
1236                                         $r = run_update_function($x);
1237                                         if (!$r) break;
1238                                 }
1239                                 if ($stored < NEW_UPDATE_ROUTINE_VERSION) $stored = NEW_UPDATE_ROUTINE_VERSION;
1240
1241
1242                                 // run new update routine
1243                                 // it update the structure in one call
1244                                 $retval = update_structure(false, true);
1245                                 if($retval) {
1246                                         update_fail(
1247                                                 DB_UPDATE_VERSION,
1248                                                 $retval
1249                                         );
1250                                         return;
1251                                 } else {
1252                                         set_config('database','dbupdate_'.DB_UPDATE_VERSION, 'success');
1253                                 }
1254
1255                                 // run any left update_nnnn functions in update.php
1256                                 for($x = $stored; $x < $current; $x ++) {
1257                                         $r = run_update_function($x);
1258                                         if (!$r) break;
1259                                 }
1260                         }
1261                 }
1262         }
1263
1264         return;
1265 }
1266
1267 function run_update_function($x) {
1268         if(function_exists('update_' . $x)) {
1269
1270                 // There could be a lot of processes running or about to run.
1271                 // We want exactly one process to run the update command.
1272                 // So store the fact that we're taking responsibility
1273                 // after first checking to see if somebody else already has.
1274
1275                 // If the update fails or times-out completely you may need to
1276                 // delete the config entry to try again.
1277
1278                 $t = get_config('database','update_' . $x);
1279                 if($t !== false)
1280                         return false;
1281                 set_config('database','update_' . $x, time());
1282
1283                 // call the specific update
1284
1285                 $func = 'update_' . $x;
1286                 $retval = $func();
1287
1288                 if($retval) {
1289                         //send the administrator an e-mail
1290                         update_fail(
1291                                 $x,
1292                                 sprintf(t('Update %s failed. See error logs.'), $x)
1293                         );
1294                         return false;
1295                 } else {
1296                         set_config('database','update_' . $x, 'success');
1297                         set_config('system','build', $x + 1);
1298                         return true;
1299                 }
1300         } else {
1301                 set_config('database','update_' . $x, 'success');
1302                 set_config('system','build', $x + 1);
1303                 return true;
1304         }
1305         return true;
1306 }
1307
1308 /**
1309  * @brief Synchronise plugins:
1310  *
1311  * $a->config['system']['addon'] contains a comma-separated list of names
1312  * of plugins/addons which are used on this system.
1313  * Go through the database list of already installed addons, and if we have
1314  * an entry, but it isn't in the config list, call the uninstall procedure
1315  * and mark it uninstalled in the database (for now we'll remove it).
1316  * Then go through the config list and if we have a plugin that isn't installed,
1317  * call the install procedure and add it to the database.
1318  * 
1319  * @param App $a
1320  *
1321          */
1322 function check_plugins(&$a) {
1323
1324         $r = q("SELECT * FROM `addon` WHERE `installed` = 1");
1325         if(count($r))
1326                 $installed = $r;
1327         else
1328                 $installed = array();
1329
1330         $plugins = get_config('system','addon');
1331         $plugins_arr = array();
1332
1333         if($plugins)
1334                 $plugins_arr = explode(',',str_replace(' ', '',$plugins));
1335
1336         $a->plugins = $plugins_arr;
1337
1338         $installed_arr = array();
1339
1340         if(count($installed)) {
1341                 foreach($installed as $i) {
1342                         if(! in_array($i['name'],$plugins_arr)) {
1343                                 uninstall_plugin($i['name']);
1344                         }
1345                         else {
1346                                 $installed_arr[] = $i['name'];
1347                         }
1348                 }
1349         }
1350
1351         if(count($plugins_arr)) {
1352                 foreach($plugins_arr as $p) {
1353                         if(! in_array($p,$installed_arr)) {
1354                                 install_plugin($p);
1355                         }
1356                 }
1357         }
1358
1359
1360         load_hooks();
1361
1362         return;
1363 }
1364
1365 function get_guid($size=16, $prefix = "") {
1366
1367         if ($prefix == "") {
1368                 $a = get_app();
1369                 $prefix = hash("crc32", $a->get_hostname());
1370         }
1371
1372         while (strlen($prefix) < ($size - 13))
1373                 $prefix .= mt_rand();
1374
1375         if ($size >= 24) {
1376                 $prefix = substr($prefix, 0, $size - 22);
1377                 return(str_replace(".", "", uniqid($prefix, true)));
1378         } else {
1379                 $prefix = substr($prefix, 0, max($size - 13, 0));
1380                 return(uniqid($prefix));
1381         }
1382 }
1383
1384 /** 
1385  * @brief Wrapper for adding a login box.
1386  * 
1387  * @param bool $register
1388  *      If $register == true provide a registration link.
1389  *      This will most always depend on the value of $a->config['register_policy'].
1390  * @param bool $hiddens
1391  * 
1392  * @return string
1393  *      Returns the complete html for inserting into the page
1394  * 
1395  * @hooks 'login_hook'
1396  *      string $o
1397  */
1398 function login($register = false, $hiddens=false) {
1399         $a = get_app();
1400         $o = "";
1401         $reg = false;
1402         if ($register) {
1403                 $reg = array(
1404                         'title' => t('Create a New Account'),
1405                         'desc' => t('Register')
1406                 );
1407         }
1408
1409         $noid = get_config('system','no_openid');
1410
1411         $dest_url = $a->get_baseurl(true) . '/' . $a->query_string;
1412
1413         if(local_user()) {
1414                 $tpl = get_markup_template("logout.tpl");
1415         }
1416         else {
1417                 $a->page['htmlhead'] .= replace_macros(get_markup_template("login_head.tpl"),array(
1418                         '$baseurl'              => $a->get_baseurl(true)
1419                 ));
1420
1421                 $tpl = get_markup_template("login.tpl");
1422                 $_SESSION['return_url'] = $a->query_string;
1423                 $a->module = 'login';
1424         }
1425
1426         $o .= replace_macros($tpl, array(
1427
1428                 '$dest_url'     => $dest_url,
1429                 '$logout'       => t('Logout'),
1430                 '$login'        => t('Login'),
1431
1432                 '$lname'                => array('username', t('Nickname or Email address: ') , '', ''),
1433                 '$lpassword'    => array('password', t('Password: '), '', ''),
1434                 '$lremember'    => array('remember', t('Remember me'), 0,  ''),
1435
1436                 '$openid'               => !$noid,
1437                 '$lopenid'      => array('openid_url', t('Or login using OpenID: '),'',''),
1438
1439                 '$hiddens'      => $hiddens,
1440
1441                 '$register'     => $reg,
1442
1443                 '$lostpass'     => t('Forgot your password?'),
1444                 '$lostlink'     => t('Password Reset'),
1445
1446                 '$tostitle'     => t('Website Terms of Service'),
1447                 '$toslink'      => t('terms of service'),
1448
1449                 '$privacytitle' => t('Website Privacy Policy'),
1450                 '$privacylink'  => t('privacy policy'),
1451
1452         ));
1453
1454         call_hooks('login_hook',$o);
1455
1456         return $o;
1457 }
1458
1459 /**
1460  * @brief Used to end the current process, after saving session state.
1461  */
1462 function killme() {
1463         session_write_close();
1464         exit;
1465 }
1466
1467 /**
1468  * @brief Redirect to another URL and terminate this process.
1469  */
1470 function goaway($s) {
1471         header("Location: $s");
1472         killme();
1473 }
1474
1475
1476 /**
1477  * @brief Returns the user id of locally logged in user or false.
1478  * 
1479  * @return int|bool user id or false
1480  */
1481 function local_user() {
1482         if((x($_SESSION,'authenticated')) && (x($_SESSION,'uid')))
1483                 return intval($_SESSION['uid']);
1484         return false;
1485 }
1486
1487 /**
1488  * @brief Returns contact id of authenticated site visitor or false
1489  * 
1490  * @return int|bool visitor_id or false
1491  */
1492 function remote_user() {
1493         if((x($_SESSION,'authenticated')) && (x($_SESSION,'visitor_id')))
1494                 return intval($_SESSION['visitor_id']);
1495         return false;
1496 }
1497
1498 /**
1499  * @brief Show an error message to user.
1500  *
1501  * This function save text in session, to be shown to the user at next page load
1502  *
1503  * @param string $s - Text of notice
1504  */
1505 function notice($s) {
1506         $a = get_app();
1507         if(! x($_SESSION,'sysmsg'))     $_SESSION['sysmsg'] = array();
1508         if($a->interactive)
1509                 $_SESSION['sysmsg'][] = $s;
1510 }
1511
1512 /**
1513  * @brief Show an info message to user.
1514  *
1515  * This function save text in session, to be shown to the user at next page load
1516  *
1517  * @param string $s - Text of notice
1518  */
1519 function info($s) {
1520         $a = get_app();
1521
1522         if (local_user() AND get_pconfig(local_user(),'system','ignore_info'))
1523                 return;
1524
1525         if(! x($_SESSION,'sysmsg_info')) $_SESSION['sysmsg_info'] = array();
1526         if($a->interactive)
1527                 $_SESSION['sysmsg_info'][] = $s;
1528 }
1529
1530
1531 /**
1532  * @brief Wrapper around config to limit the text length of an incoming message
1533  *
1534  * @return int
1535  */
1536 function get_max_import_size() {
1537         global $a;
1538         return ((x($a->config,'max_import_size')) ? $a->config['max_import_size'] : 0 );
1539 }
1540
1541 /**
1542  * @brief Wrap calls to proc_close(proc_open()) and call hook
1543  *      so plugins can take part in process :)
1544  *
1545  * @param string $cmd program to run
1546  * 
1547  * next args are passed as $cmd command line
1548  * e.g.: proc_run("ls","-la","/tmp");
1549  *
1550  * @note $cmd and string args are surrounded with ""
1551  * 
1552  * @hooks 'proc_run'
1553  *      array $arr
1554  */
1555 function proc_run($cmd){
1556
1557         $a = get_app();
1558
1559         $args = func_get_args();
1560
1561         $newargs = array();
1562         if(! count($args))
1563                 return;
1564
1565         // expand any arrays
1566
1567         foreach($args as $arg) {
1568                 if(is_array($arg)) {
1569                         foreach($arg as $n) {
1570                                 $newargs[] = $n;
1571                         }
1572                 }
1573                 else
1574                         $newargs[] = $arg;
1575         }
1576
1577         $args = $newargs;
1578
1579         $arr = array('args' => $args, 'run_cmd' => true);
1580
1581         call_hooks("proc_run", $arr);
1582         if(! $arr['run_cmd'])
1583                 return;
1584
1585         if(count($args) && $args[0] === 'php') {
1586
1587                 if (get_config("system", "worker")) {
1588                         $argv = $args;
1589                         array_shift($argv);
1590
1591                         $parameters = json_encode($argv);
1592                         $found = q("SELECT `id` FROM `workerqueue` WHERE `parameter` = '%s'",
1593                                         dbesc($parameters));
1594
1595                         if (!$found)
1596                                 q("INSERT INTO `workerqueue` (`parameter`, `created`, `priority`)
1597                                                         VALUES ('%s', '%s', %d)",
1598                                         dbesc($parameters),
1599                                         dbesc(datetime_convert()),
1600                                         intval(0));
1601
1602                         // Should we quit and wait for the poller to be called as a cronjob?
1603                         if (get_config("system", "worker_dont_fork"))
1604                                 return;
1605
1606                         // Checking number of workers
1607                         $workers = q("SELECT COUNT(*) AS `workers` FROM `workerqueue` WHERE `executed` != '0000-00-00 00:00:00'");
1608
1609                         // Get number of allowed number of worker threads
1610                         $queues = intval(get_config("system", "worker_queues"));
1611
1612                         if ($queues == 0)
1613                                 $queues = 4;
1614
1615                         // If there are already enough workers running, don't fork another one
1616                         if ($workers[0]["workers"] >= $queues)
1617                                 return;
1618
1619                         // Now call the poller to execute the jobs that we just added to the queue
1620                         $args = array("php", "include/poller.php", "no_cron");
1621                 }
1622
1623                 $args[0] = ((x($a->config,'php_path')) && (strlen($a->config['php_path'])) ? $a->config['php_path'] : 'php');
1624         }
1625
1626         // add baseurl to args. cli scripts can't construct it
1627         $args[] = $a->get_baseurl();
1628
1629         for($x = 0; $x < count($args); $x ++)
1630                 $args[$x] = escapeshellarg($args[$x]);
1631
1632         $cmdline = implode($args," ");
1633
1634         if(get_config('system','proc_windows'))
1635                 proc_close(proc_open('cmd /c start /b ' . $cmdline,array(),$foo,dirname(__FILE__)));
1636         else
1637                 proc_close(proc_open($cmdline." &",array(),$foo,dirname(__FILE__)));
1638 }
1639
1640 function current_theme(){
1641         $app_base_themes = array('duepuntozero', 'dispy', 'quattro');
1642
1643         $a = get_app();
1644
1645         $page_theme = null;
1646
1647         // Find the theme that belongs to the user whose stuff we are looking at
1648
1649         if($a->profile_uid && ($a->profile_uid != local_user())) {
1650                 $r = q("select theme from user where uid = %d limit 1",
1651                         intval($a->profile_uid)
1652                 );
1653                 if($r)
1654                         $page_theme = $r[0]['theme'];
1655         }
1656
1657         // Allow folks to over-rule user themes and always use their own on their own site.
1658         // This works only if the user is on the same server
1659
1660         if($page_theme && local_user() && (local_user() != $a->profile_uid)) {
1661                 if(get_pconfig(local_user(),'system','always_my_theme'))
1662                         $page_theme = null;
1663         }
1664
1665 //              $mobile_detect = new Mobile_Detect();
1666 //              $is_mobile = $mobile_detect->isMobile() || $mobile_detect->isTablet();
1667         $is_mobile = $a->is_mobile || $a->is_tablet;
1668
1669         $standard_system_theme = ((isset($a->config['system']['theme'])) ? $a->config['system']['theme'] : '');
1670         $standard_theme_name = ((isset($_SESSION) && x($_SESSION,'theme')) ? $_SESSION['theme'] : $standard_system_theme);
1671
1672         if($is_mobile) {
1673                 if(isset($_SESSION['show-mobile']) && !$_SESSION['show-mobile']) {
1674                         $system_theme = $standard_system_theme;
1675                         $theme_name = $standard_theme_name;
1676                 }
1677                 else {
1678                         $system_theme = ((isset($a->config['system']['mobile-theme'])) ? $a->config['system']['mobile-theme'] : $standard_system_theme);
1679                         $theme_name = ((isset($_SESSION) && x($_SESSION,'mobile-theme')) ? $_SESSION['mobile-theme'] : $system_theme);
1680
1681                         if($theme_name === '---') {
1682                                 // user has selected to have the mobile theme be the same as the normal one
1683                                 $system_theme = $standard_system_theme;
1684                                 $theme_name = $standard_theme_name;
1685
1686                                 if($page_theme)
1687                                         $theme_name = $page_theme;
1688                         }
1689                 }
1690         }
1691         else {
1692                 $system_theme = $standard_system_theme;
1693                 $theme_name = $standard_theme_name;
1694
1695                 if($page_theme)
1696                         $theme_name = $page_theme;
1697         }
1698
1699         if($theme_name &&
1700                         (file_exists('view/theme/' . $theme_name . '/style.css') ||
1701                                         file_exists('view/theme/' . $theme_name . '/style.php')))
1702                 return($theme_name);
1703
1704         foreach($app_base_themes as $t) {
1705                 if(file_exists('view/theme/' . $t . '/style.css')||
1706                                 file_exists('view/theme/' . $t . '/style.php'))
1707                         return($t);
1708         }
1709
1710         $fallback = array_merge(glob('view/theme/*/style.css'),glob('view/theme/*/style.php'));
1711         if(count($fallback))
1712                 return (str_replace('view/theme/','', substr($fallback[0],0,-10)));
1713
1714 }
1715
1716 /**
1717  * @brief Return full URL to theme which is currently in effect.
1718  * 
1719  * Provide a sane default if nothing is chosen or the specified theme does not exist.
1720  * 
1721  * @return string
1722  */
1723 function current_theme_url() {
1724         global $a;
1725
1726         $t = current_theme();
1727
1728         $opts = (($a->profile_uid) ? '?f=&puid=' . $a->profile_uid : '');
1729         if (file_exists('view/theme/' . $t . '/style.php'))
1730                 return($a->get_baseurl() . '/view/theme/' . $t . '/style.pcss' . $opts);
1731
1732         return($a->get_baseurl() . '/view/theme/' . $t . '/style.css');
1733 }
1734
1735 function feed_birthday($uid,$tz) {
1736
1737         /**
1738          *
1739          * Determine the next birthday, but only if the birthday is published
1740          * in the default profile. We _could_ also look for a private profile that the
1741          * recipient can see, but somebody could get mad at us if they start getting
1742          * public birthday greetings when they haven't made this info public.
1743          *
1744          * Assuming we are able to publish this info, we are then going to convert
1745          * the start time from the owner's timezone to UTC.
1746          *
1747          * This will potentially solve the problem found with some social networks
1748          * where birthdays are converted to the viewer's timezone and salutations from
1749          * elsewhere in the world show up on the wrong day. We will convert it to the
1750          * viewer's timezone also, but first we are going to convert it from the birthday
1751          * person's timezone to GMT - so the viewer may find the birthday starting at
1752          * 6:00PM the day before, but that will correspond to midnight to the birthday person.
1753          *
1754          */
1755
1756
1757         $birthday = '';
1758
1759         if(! strlen($tz))
1760                 $tz = 'UTC';
1761
1762         $p = q("SELECT `dob` FROM `profile` WHERE `is-default` = 1 AND `uid` = %d LIMIT 1",
1763                         intval($uid)
1764         );
1765
1766         if($p && count($p)) {
1767                 $tmp_dob = substr($p[0]['dob'],5);
1768                 if(intval($tmp_dob)) {
1769                         $y = datetime_convert($tz,$tz,'now','Y');
1770                         $bd = $y . '-' . $tmp_dob . ' 00:00';
1771                         $t_dob = strtotime($bd);
1772                         $now = strtotime(datetime_convert($tz,$tz,'now'));
1773                         if($t_dob < $now)
1774                                 $bd = $y + 1 . '-' . $tmp_dob . ' 00:00';
1775                         $birthday = datetime_convert($tz,'UTC',$bd,ATOM_TIME);
1776                 }
1777         }
1778
1779         return $birthday;
1780 }
1781
1782 /**
1783  * @brief Check if current user has admin role.
1784  *
1785  * @return bool true if user is an admin
1786  */
1787 function is_site_admin() {
1788         $a = get_app();
1789
1790         $adminlist = explode(",", str_replace(" ", "", $a->config['admin_email']));
1791
1792         //if(local_user() && x($a->user,'email') && x($a->config,'admin_email') && ($a->user['email'] === $a->config['admin_email']))
1793         if(local_user() && x($a->user,'email') && x($a->config,'admin_email') && in_array($a->user['email'], $adminlist))
1794                 return true;
1795         return false;
1796 }
1797
1798
1799 function load_contact_links($uid) {
1800
1801         $a = get_app();
1802
1803         $ret = array();
1804
1805         if(! $uid || x($a->contacts,'empty'))
1806                 return;
1807
1808         $r = q("SELECT `id`,`network`,`url`,`thumb`, `rel` FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 AND `thumb` != ''",
1809                         intval($uid)
1810         );
1811         if(count($r)) {
1812                 foreach($r as $rr){
1813                         $url = normalise_link($rr['url']);
1814                         $ret[$url] = $rr;
1815                 }
1816         } else
1817                 $ret['empty'] = true;
1818
1819         $a->contacts = $ret;
1820         return;
1821 }
1822
1823 /**
1824  * @brief Returns querystring as string from a mapped array.
1825  *
1826  * @param array $params mapped array with query parameters
1827  * @param string $name of parameter, default null
1828  *
1829  * @return string
1830  */
1831 function build_querystring($params, $name=null) {
1832         $ret = "";
1833         foreach($params as $key=>$val) {
1834                 if(is_array($val)) {
1835                         if($name==null) {
1836                                 $ret .= build_querystring($val, $key);
1837                         } else {
1838                                 $ret .= build_querystring($val, $name."[$key]");
1839                         }
1840                 } else {
1841                         $val = urlencode($val);
1842                         if($name!=null) {
1843                                 $ret.=$name."[$key]"."=$val&";
1844                         } else {
1845                                 $ret.= "$key=$val&";
1846                         }
1847                 }
1848         }
1849         return $ret;
1850 }
1851
1852 function explode_querystring($query) {
1853         $arg_st = strpos($query, '?');
1854         if($arg_st !== false) {
1855                 $base = substr($query, 0, $arg_st);
1856                 $arg_st += 1;
1857         } else {
1858                 $base = '';
1859                 $arg_st = 0;
1860         }
1861
1862         $args = explode('&', substr($query, $arg_st));
1863         foreach($args as $k=>$arg) {
1864                 if($arg === '')
1865                         unset($args[$k]);
1866         }
1867         $args = array_values($args);
1868
1869         if(!$base) {
1870                 $base = $args[0];
1871                 unset($args[0]);
1872                 $args = array_values($args);
1873         }
1874
1875         return array(
1876                 'base' => $base,
1877                 'args' => $args,
1878         );
1879 }
1880
1881 /**
1882 * Returns the complete URL of the current page, e.g.: http(s)://something.com/network
1883 *
1884 * Taken from http://webcheatsheet.com/php/get_current_page_url.php
1885 */
1886 function curPageURL() {
1887         $pageURL = 'http';
1888         if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
1889         $pageURL .= "://";
1890         if ($_SERVER["SERVER_PORT"] != "80" && $_SERVER["SERVER_PORT"] != "443") {
1891                 $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
1892         } else {
1893                 $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
1894         }
1895         return $pageURL;
1896 }
1897
1898 function random_digits($digits) {
1899         $rn = '';
1900         for($i = 0; $i < $digits; $i++) {
1901                 $rn .= rand(0,9);
1902         }
1903         return $rn;
1904 }
1905
1906 function get_server() {
1907         $server = get_config("system", "directory");
1908
1909         if ($server == "")
1910                 $server = "http://dir.friendi.ca";
1911
1912         return($server);
1913 }
1914
1915 function get_cachefile($file, $writemode = true) {
1916         $cache = get_itemcachepath();
1917
1918         if ((! $cache) || (! is_dir($cache)))
1919                 return("");
1920
1921         $subfolder = $cache."/".substr($file, 0, 2);
1922
1923         $cachepath = $subfolder."/".$file;
1924
1925         if ($writemode) {
1926                 if (!is_dir($subfolder)) {
1927                         mkdir($subfolder);
1928                         chmod($subfolder, 0777);
1929                 }
1930         }
1931
1932         return($cachepath);
1933 }
1934
1935 function clear_cache($basepath = "", $path = "") {
1936         if ($path == "") {
1937                 $basepath = get_itemcachepath();
1938                 $path = $basepath;
1939         }
1940
1941         if (($path == "") OR (!is_dir($path)))
1942                 return;
1943
1944         if (substr(realpath($path), 0, strlen($basepath)) != $basepath)
1945                 return;
1946
1947         $cachetime = (int)get_config('system','itemcache_duration');
1948         if ($cachetime == 0)
1949                 $cachetime = 86400;
1950
1951         if (is_writable($path)){
1952                 if ($dh = opendir($path)) {
1953                         while (($file = readdir($dh)) !== false) {
1954                                 $fullpath = $path."/".$file;
1955                                 if ((filetype($fullpath) == "dir") and ($file != ".") and ($file != ".."))
1956                                         clear_cache($basepath, $fullpath);
1957                                 if ((filetype($fullpath) == "file") and (filectime($fullpath) < (time() - $cachetime)))
1958                                         unlink($fullpath);
1959                         }
1960                         closedir($dh);
1961                 }
1962         }
1963 }
1964
1965 function get_itemcachepath() {
1966         // Checking, if the cache is deactivated
1967         $cachetime = (int)get_config('system','itemcache_duration');
1968         if ($cachetime < 0)
1969                 return "";
1970
1971         $itemcache = get_config('system','itemcache');
1972         if (($itemcache != "") AND is_dir($itemcache) AND is_writable($itemcache))
1973                 return($itemcache);
1974
1975         $temppath = get_temppath();
1976
1977         if ($temppath != "") {
1978                 $itemcache = $temppath."/itemcache";
1979                 if(!file_exists($itemcache) && !is_dir($itemcache)) {
1980                         mkdir($itemcache);
1981                 }
1982
1983                 if (is_dir($itemcache) AND is_writable($itemcache)) {
1984                         set_config("system", "itemcache", $itemcache);
1985                         return($itemcache);
1986                 }
1987         }
1988         return "";
1989 }
1990
1991 function get_lockpath() {
1992         $lockpath = get_config('system','lockpath');
1993         if (($lockpath != "") AND is_dir($lockpath) AND is_writable($lockpath))
1994                 return($lockpath);
1995
1996         $temppath = get_temppath();
1997
1998         if ($temppath != "") {
1999                 $lockpath = $temppath."/lock";
2000
2001                 if (!is_dir($lockpath))
2002                         mkdir($lockpath);
2003                 elseif (!is_writable($lockpath))
2004                         $lockpath = $temppath;
2005
2006                 if (is_dir($lockpath) AND is_writable($lockpath)) {
2007                         set_config("system", "lockpath", $lockpath);
2008                         return($lockpath);
2009                 }
2010         }
2011         return "";
2012 }
2013
2014 function get_temppath() {
2015         $a = get_app();
2016
2017         $temppath = get_config("system","temppath");
2018         if (($temppath != "") AND is_dir($temppath) AND is_writable($temppath))
2019                 return($temppath);
2020
2021         $temppath = sys_get_temp_dir();
2022         if (($temppath != "") AND is_dir($temppath) AND is_writable($temppath)) {
2023                 $temppath .= "/".$a->get_hostname();
2024                 if (!is_dir($temppath))
2025                         mkdir($temppath);
2026
2027                 if (is_dir($temppath) AND is_writable($temppath)) {
2028                         set_config("system", "temppath", $temppath);
2029                         return($temppath);
2030                 }
2031         }
2032
2033         return("");
2034 }
2035
2036 function set_template_engine(&$a, $engine = 'internal') {
2037 /// @note This function is no longer necessary, but keep it as a wrapper to the class method
2038 /// to avoid breaking themes again unnecessarily
2039
2040         $a->set_template_engine($engine);
2041 }
2042
2043 if(!function_exists('exif_imagetype')) {
2044         function exif_imagetype($file) {
2045                 $size = getimagesize($file);
2046                 return($size[2]);
2047         }
2048 }
2049
2050 function validate_include(&$file) {
2051         $orig_file = $file;
2052
2053         $file = realpath($file);
2054
2055         if (strpos($file, getcwd()) !== 0)
2056                 return false;
2057
2058         $file = str_replace(getcwd()."/", "", $file, $count);
2059         if ($count != 1)
2060                 return false;
2061
2062         if ($orig_file !== $file)
2063                 return false;
2064
2065         $valid = false;
2066         if (strpos($file, "include/") === 0)
2067                 $valid = true;
2068
2069         if (strpos($file, "addon/") === 0)
2070                 $valid = true;
2071
2072         if (!$valid)
2073                 return false;
2074
2075         return true;
2076 }
2077
2078 function current_load() {
2079         if (!function_exists('sys_getloadavg'))
2080                 return false;
2081
2082         $load_arr = sys_getloadavg();
2083
2084         if (!is_array($load_arr))
2085                 return false;
2086
2087         return max($load_arr);
2088 }
2089
2090 /**
2091  * @brief get c-style args
2092  * 
2093  * @return int
2094  */
2095 function argc() {
2096         return get_app()->argc;
2097 }
2098
2099 /**
2100  * @brief Returns the value of a argv key
2101  * 
2102  * @param int $x argv key
2103  * @return string Value of the argv key
2104  */
2105 function argv($x) {
2106         if(array_key_exists($x,get_app()->argv))
2107                 return get_app()->argv[$x];
2108
2109         return '';
2110 }