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