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