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