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