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