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