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