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