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