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