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