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