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