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