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