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