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