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