]> git.mxchange.org Git - friendica.git/blob - boot.php
Merge branch 'master' of https://github.com/friendica/friendica
[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.0.1540' );
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_baseurl($ssl = false) {
524
525                         $scheme = $this->scheme;
526
527                         if((x($this->config,'system')) && (x($this->config['system'],'ssl_policy'))) {
528                                 if(intval($this->config['system']['ssl_policy']) === intval(SSL_POLICY_FULL))
529                                         $scheme = 'https';
530
531                                 //      Basically, we have $ssl = true on any links which can only be seen by a logged in user
532                                 //      (and also the login link). Anything seen by an outsider will have it turned off.
533
534                                 if($this->config['system']['ssl_policy'] == SSL_POLICY_SELFSIGN) {
535                                         if($ssl)
536                                                 $scheme = 'https';
537                                         else
538                                                 $scheme = 'http';
539                                 }
540                         }
541
542                         $this->baseurl = $scheme . "://" . $this->hostname . ((isset($this->path) && strlen($this->path)) ? '/' . $this->path : '' );
543                         return $this->baseurl;
544                 }
545
546                 function set_baseurl($url) {
547                         $parsed = @parse_url($url);
548
549                         $this->baseurl = $url;
550
551                         if($parsed) {
552                                 $this->scheme = $parsed['scheme'];
553
554                                 $this->hostname = $parsed['host'];
555                                 if(x($parsed,'port'))
556                                         $this->hostname .= ':' . $parsed['port'];
557                                 if(x($parsed,'path'))
558                                         $this->path = trim($parsed['path'],'\\/');
559                         }
560
561                 }
562
563                 function get_hostname() {
564                         return $this->hostname;
565                 }
566
567                 function set_hostname($h) {
568                         $this->hostname = $h;
569                 }
570
571                 function set_path($p) {
572                         $this->path = trim(trim($p),'/');
573                 }
574
575                 function get_path() {
576                         return $this->path;
577                 }
578
579                 function set_pager_total($n) {
580                         $this->pager['total'] = intval($n);
581                 }
582
583                 function set_pager_itemspage($n) {
584                         $this->pager['itemspage'] = ((intval($n) > 0) ? intval($n) : 0);
585                         $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
586
587                 }
588
589                 function init_pagehead() {
590                         $interval = ((local_user()) ? get_pconfig(local_user(),'system','update_interval') : 40000);
591                         if($interval < 10000)
592                                 $interval = 40000;
593
594                         $this->page['title'] = $this->config['sitename'];
595
596                         /* put the head template at the beginning of page['htmlhead']
597                          * since the code added by the modules frequently depends on it
598                          * being first
599                          */
600                         if(!isset($this->page['htmlhead']))
601                                 $this->page['htmlhead'] = '';
602                         $tpl = get_markup_template('head.tpl');
603                         $this->page['htmlhead'] = replace_macros($tpl,array(
604                                 '$baseurl' => $this->get_baseurl(), // FIXME for z_path!!!!
605                                 '$local_user' => local_user(),
606                                 '$generator' => 'Friendica' . ' ' . FRIENDICA_VERSION,
607                                 '$delitem' => t('Delete this item?'),
608                                 '$comment' => t('Comment'),
609                                 '$showmore' => t('show more'),
610                                 '$showfewer' => t('show fewer'),
611                                 '$update_interval' => $interval
612                         )) . $this->page['htmlhead'];
613                 }
614
615                 function init_page_end() {
616                         if(!isset($this->page['end']))
617                                 $this->page['end'] = '';
618                         $tpl = get_markup_template('end.tpl');
619                         $this->page['end'] = replace_macros($tpl,array(
620                                 '$baseurl' => $this->get_baseurl() // FIXME for z_path!!!!
621                         )) . $this->page['end'];
622                 }
623
624                 function set_curl_code($code) {
625                         $this->curl_code = $code;
626                 }
627
628                 function get_curl_code() {
629                         return $this->curl_code;
630                 }
631
632                 function set_curl_headers($headers) {
633                         $this->curl_headers = $headers;
634                 }
635
636                 function get_curl_headers() {
637                         return $this->curl_headers;
638                 }
639
640                 function get_cached_avatar_image($avatar_image){
641                         if($this->cached_profile_image[$avatar_image])
642                                 return $this->cached_profile_image[$avatar_image];
643
644                         $path_parts = explode("/",$avatar_image);
645                         $common_filename = $path_parts[count($path_parts)-1];
646
647                         if($this->cached_profile_picdate[$common_filename]){
648                                 $this->cached_profile_image[$avatar_image] = $avatar_image . $this->cached_profile_picdate[$common_filename];
649                         } else {
650                                 $r = q("SELECT `contact`.`avatar-date` AS picdate FROM `contact` WHERE `contact`.`thumb` like \"%%/%s\"",
651                                         $common_filename);
652                                 if(! count($r)){
653                                         $this->cached_profile_image[$avatar_image] = $avatar_image;
654                                 } else {
655                                         $this->cached_profile_picdate[$common_filename] = "?rev=" . urlencode($r[0]['picdate']);
656                                         $this->cached_profile_image[$avatar_image] = $avatar_image . $this->cached_profile_picdate[$common_filename];
657                                 }
658                         }
659                         return $this->cached_profile_image[$avatar_image];
660                 }
661
662
663         }
664 }
665
666 // retrieve the App structure
667 // useful in functions which require it but don't get it passed to them
668
669 if(! function_exists('get_app')) {
670         function get_app() {
671                 global $a;
672                 return $a;
673         }
674 };
675
676
677 // Multi-purpose function to check variable state.
678 // Usage: x($var) or $x($array,'key')
679 // returns false if variable/key is not set
680 // if variable is set, returns 1 if has 'non-zero' value, otherwise returns 0.
681 // e.g. x('') or x(0) returns 0;
682
683 if(! function_exists('x')) {
684         function x($s,$k = NULL) {
685                 if($k != NULL) {
686                         if((is_array($s)) && (array_key_exists($k,$s))) {
687                                 if($s[$k])
688                                         return (int) 1;
689                                 return (int) 0;
690                 }
691                         return false;
692                 }
693                 else {
694                         if(isset($s)) {
695                                 if($s) {
696                                         return (int) 1;
697                                 }
698                                 return (int) 0;
699                         }
700                         return false;
701                 }
702         }
703 }
704
705 // called from db initialisation if db is dead.
706
707 if(! function_exists('system_unavailable')) {
708         function system_unavailable() {
709                 include('system_unavailable.php');
710                 system_down();
711                 killme();
712         }
713 }
714
715
716
717 function clean_urls() {
718         global $a;
719         //      if($a->config['system']['clean_urls'])
720         return true;
721         //      return false;
722 }
723
724 function z_path() {
725         global $a;
726         $base = $a->get_baseurl();
727         if(! clean_urls())
728                 $base .= '/?q=';
729         return $base;
730 }
731
732 function z_root() {
733         global $a;
734         return $a->get_baseurl();
735 }
736
737 function absurl($path) {
738         if(strpos($path,'/') === 0)
739                 return z_path() . $path;
740         return $path;
741 }
742
743 function is_ajax() {
744         return (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');
745 }
746
747
748 // Primarily involved with database upgrade, but also sets the
749 // base url for use in cmdline programs which don't have
750 // $_SERVER variables, and synchronising the state of installed plugins.
751
752
753 if(! function_exists('check_config')) {
754         function check_config(&$a) {
755
756                 $build = get_config('system','build');
757                 if(! x($build))
758                         $build = set_config('system','build',DB_UPDATE_VERSION);
759
760                 $url = get_config('system','url');
761
762                 // if the url isn't set or the stored url is radically different
763                 // than the currently visited url, store the current value accordingly.
764                 // "Radically different" ignores common variations such as http vs https
765                 // and www.example.com vs example.com.
766                 // We will only change the url to an ip address if there is no existing setting
767
768                 if(! x($url))
769                         $url = set_config('system','url',$a->get_baseurl());
770                 if((! link_compare($url,$a->get_baseurl())) && (! preg_match("/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/",$a->get_hostname)))
771                         $url = set_config('system','url',$a->get_baseurl());
772
773
774                 if($build != DB_UPDATE_VERSION) {
775                         $stored = intval($build);
776                         $current = intval(DB_UPDATE_VERSION);
777                         if(($stored < $current) && file_exists('update.php')) {
778
779                                 load_config('database');
780
781                                 // We're reporting a different version than what is currently installed.
782                                 // Run any existing update scripts to bring the database up to current.
783
784                                 require_once('update.php');
785
786                                 // make sure that boot.php and update.php are the same release, we might be
787                                 // updating right this very second and the correct version of the update.php
788                                 // file may not be here yet. This can happen on a very busy site.
789
790                                 if(DB_UPDATE_VERSION == UPDATE_VERSION) {
791
792                                         for($x = $stored; $x < $current; $x ++) {
793                                                 if(function_exists('update_' . $x)) {
794
795                                                         // There could be a lot of processes running or about to run.
796                                                         // We want exactly one process to run the update command.
797                                                         // So store the fact that we're taking responsibility
798                                                         // after first checking to see if somebody else already has.
799
800                                                         // If the update fails or times-out completely you may need to
801                                                         // delete the config entry to try again.
802
803                                                         $t = get_config('database','update_' . $x);
804                                                         if($t !== false)
805                                                                 break;
806                                                         set_config('database','update_' . $x, time());
807
808                                                         // call the specific update
809
810                                                         $func = 'update_' . $x;
811                                                         $retval = $func();
812                                                         if($retval) {
813                                                                 //send the administrator an e-mail
814                                                                 $email_tpl = get_intltext_template("update_fail_eml.tpl");
815                                                                 $email_msg = replace_macros($email_tpl, array(
816                                                                         '$sitename' => $a->config['sitename'],
817                                                                         '$siteurl' =>  $a->get_baseurl(),
818                                                                         '$update' => $x,
819                                                                         '$error' => sprintf( t('Update %s failed. See error logs.'), $x)
820                                                                 ));
821                                                                 $subject=sprintf(t('Update Error at %s'), $a->get_baseurl());
822                                                                         
823                                                                 mail($a->config['admin_email'], $subject, $email_msg,
824                                                                         'From: ' . t('Administrator') . '@' . $_SERVER['SERVER_NAME'] . "\n"
825                                                                         . 'Content-type: text/plain; charset=UTF-8' . "\n"
826                                                                         . 'Content-transfer-encoding: 8bit' );
827                                                                 //try the logger
828                                                                 logger('CRITICAL: Update Failed: '. $x);
829                                                                 break;
830                                                         }
831                                                         else {
832                                                                 set_config('database','update_' . $x, 'success');
833                                                                 set_config('system','build', $x + 1);
834                                                         }                                                               
835                                                 }
836                                         }
837                                 }
838                         }
839                 }
840
841                 /**
842                  *
843                  * Synchronise plugins:
844                  *
845                  * $a->config['system']['addon'] contains a comma-separated list of names
846                  * of plugins/addons which are used on this system.
847                  * Go through the database list of already installed addons, and if we have
848                  * an entry, but it isn't in the config list, call the uninstall procedure
849                  * and mark it uninstalled in the database (for now we'll remove it).
850                  * Then go through the config list and if we have a plugin that isn't installed,
851                  * call the install procedure and add it to the database.
852                  *
853                  */
854
855                 $r = q("SELECT * FROM `addon` WHERE `installed` = 1");
856                 if(count($r))
857                         $installed = $r;
858                 else
859                         $installed = array();
860
861                 $plugins = get_config('system','addon');
862                 $plugins_arr = array();
863
864                 if($plugins)
865                         $plugins_arr = explode(',',str_replace(' ', '',$plugins));
866
867                 $a->plugins = $plugins_arr;
868
869                 $installed_arr = array();
870
871                 if(count($installed)) {
872                         foreach($installed as $i) {
873                                 if(! in_array($i['name'],$plugins_arr)) {
874                                         uninstall_plugin($i['name']);
875                                 }
876                                 else {
877                                         $installed_arr[] = $i['name'];
878                                 }
879                         }
880                 }
881
882                 if(count($plugins_arr)) {
883                         foreach($plugins_arr as $p) {
884                                 if(! in_array($p,$installed_arr)) {
885                                         install_plugin($p);
886                                 }
887                         }
888                 }
889
890
891                 load_hooks();
892
893                 return;
894         }
895 }
896
897
898 function get_guid($size=16) {
899         $exists = true; // assume by default that we don't have a unique guid
900         do {
901                 $s = random_string($size);
902                 $r = q("select id from guid where guid = '%s' limit 1", dbesc($s));
903                 if(! count($r))
904                         $exists = false;
905         } while($exists);
906         q("insert into guid ( guid ) values ( '%s' ) ", dbesc($s));
907         return $s;
908 }
909
910
911 // wrapper for adding a login box. If $register == true provide a registration
912 // link. This will most always depend on the value of $a->config['register_policy'].
913 // returns the complete html for inserting into the page
914
915 if(! function_exists('login')) {
916         function login($register = false, $hiddens=false) {
917                 $a = get_app();
918                 $o = "";
919                 $reg = false;
920                 if ($register) {
921                         $reg = array(
922                                 'title' => t('Create a New Account'),
923                                 'desc' => t('Register')
924                         );
925                 }
926
927                 $noid = get_config('system','no_openid');
928         
929                 $dest_url = $a->get_baseurl(true) . '/' . $a->query_string;
930
931                 if(local_user()) {
932                         $tpl = get_markup_template("logout.tpl");
933                 }
934                 else {
935                         $a->page['htmlhead'] .= replace_macros(get_markup_template("login_head.tpl"),array(
936                                 '$baseurl'              => $a->get_baseurl(true)
937                         ));
938
939                         $tpl = get_markup_template("login.tpl");
940                         $_SESSION['return_url'] = $a->query_string;
941                         $a->module = 'login';
942                 }
943
944
945                 $o .= replace_macros($tpl,array(
946
947                         '$dest_url'     => $dest_url,
948                         '$logout'       => t('Logout'),
949                         '$login'        => t('Login'),
950         
951                         '$lname'                => array('username', t('Nickname or Email address: ') , '', ''),
952                         '$lpassword'    => array('password', t('Password: '), '', ''),
953                         '$lremember'    => array('remember', t('Remember me'), 0, ''),
954         
955                         '$openid'               => !$noid,
956                         '$lopenid'      => array('openid_url', t('Or login using OpenID: '),'',''),
957         
958                         '$hiddens'      => $hiddens,
959         
960                         '$register'     => $reg,
961         
962                         '$lostpass'     => t('Forgot your password?'),
963                         '$lostlink'     => t('Password Reset'),
964                 ));
965
966                 call_hooks('login_hook',$o);
967
968                 return $o;
969         }
970 }
971
972 // Used to end the current process, after saving session state.
973
974 if(! function_exists('killme')) {
975         function killme() {
976                 session_write_close();
977                 exit;
978         }
979 }
980
981 // redirect to another URL and terminate this process.
982
983 if(! function_exists('goaway')) {
984         function goaway($s) {
985                 header("Location: $s");
986                 killme();
987         }
988 }
989
990
991 // Returns the uid of locally logged in user or false.
992
993 if(! function_exists('local_user')) {
994         function local_user() {
995                 if((x($_SESSION,'authenticated')) && (x($_SESSION,'uid')))
996                         return intval($_SESSION['uid']);
997                 return false;
998         }
999 }
1000
1001 // Returns contact id of authenticated site visitor or false
1002
1003 if(! function_exists('remote_user')) {
1004         function remote_user() {
1005                 if((x($_SESSION,'authenticated')) && (x($_SESSION,'visitor_id')))
1006                         return intval($_SESSION['visitor_id']);
1007                 return false;
1008         }
1009 }
1010
1011 // contents of $s are displayed prominently on the page the next time
1012 // a page is loaded. Usually used for errors or alerts.
1013
1014 if(! function_exists('notice')) {
1015         /**
1016          * Show an error message to user.
1017          * 
1018          * This function save text in session, to be shown to the user at next page load
1019          * 
1020          * @param string $s - Text of notice
1021          */
1022         function notice($s) {
1023                 $a = get_app();
1024                 if(! x($_SESSION,'sysmsg'))     $_SESSION['sysmsg'] = array();
1025                 if($a->interactive)
1026                         $_SESSION['sysmsg'][] = $s;
1027         }
1028 }
1029 if(! function_exists('info')) {
1030         /**
1031          * Show an info message to user.
1032          * 
1033          * This function save text in session, to be shown to the user at next page load
1034          * 
1035          * @param string $s - Text of notice
1036          */
1037         function info($s) {
1038                 $a = get_app();
1039                 if(! x($_SESSION,'sysmsg_info')) $_SESSION['sysmsg_info'] = array();
1040                 if($a->interactive)
1041                         $_SESSION['sysmsg_info'][] = $s;
1042         }
1043 }
1044
1045
1046 // wrapper around config to limit the text length of an incoming message
1047
1048 if(! function_exists('get_max_import_size')) {
1049         function get_max_import_size() {
1050                 global $a;
1051                 return ((x($a->config,'max_import_size')) ? $a->config['max_import_size'] : 0 );
1052         }
1053 }
1054
1055
1056
1057 /**
1058  *
1059  * Function : profile_load
1060  * @parameter App    $a
1061  * @parameter string $nickname
1062  * @parameter int    $profile
1063  *
1064  * Summary: Loads a profile into the page sidebar.
1065  * The function requires a writeable copy of the main App structure, and the nickname
1066  * of a registered local account.
1067  *
1068  * If the viewer is an authenticated remote viewer, the profile displayed is the
1069  * one that has been configured for his/her viewing in the Contact manager.
1070  * Passing a non-zero profile ID can also allow a preview of a selected profile
1071  * by the owner.
1072  *
1073  * Profile information is placed in the App structure for later retrieval.
1074  * Honours the owner's chosen theme for display.
1075  *
1076  */
1077
1078 if(! function_exists('profile_load')) {
1079         function profile_load(&$a, $nickname, $profile = 0) {
1080
1081                 $user = q("select uid from user where nickname = '%s' limit 1",
1082                         dbesc($nickname)
1083                 );
1084                 
1085                 if(! ($user && count($user))) {
1086                         logger('profile error: ' . $a->query_string, LOGGER_DEBUG);
1087                         notice( t('Requested account is not available.') . EOL );
1088                         $a->error = 404;
1089                         return;
1090                 }
1091
1092                 if(remote_user() && count($_SESSION['remote'])) {
1093                         foreach($_SESSION['remote'] as $visitor) {
1094                                 if($visitor['uid'] == $user[0]['uid']) {
1095                                         $r = q("SELECT `profile-id` FROM `contact` WHERE `id` = %d LIMIT 1",
1096                                                 intval($visitor['cid'])
1097                                         );
1098                                         if(count($r))
1099                                                 $profile = $r[0]['profile-id'];
1100                                         break;
1101                                 }
1102                         }
1103                 }
1104
1105                 $r = null;
1106                           
1107                 if($profile) {
1108                         $profile_int = intval($profile);
1109                         $r = q("SELECT `profile`.`uid` AS `profile_uid`, `profile`.* , `contact`.`avatar-date` AS picdate, `user`.* FROM `profile`
1110                                         left join `contact` on `contact`.`uid` = `profile`.`uid` LEFT JOIN `user` ON `profile`.`uid` = `user`.`uid`
1111                                         WHERE `user`.`nickname` = '%s' AND `profile`.`id` = %d and `contact`.`self` = 1 LIMIT 1",
1112                                         dbesc($nickname),
1113                                         intval($profile_int)
1114                         );
1115                 }
1116                 if((! $r) && (!  count($r))) {
1117                         $r = q("SELECT `profile`.`uid` AS `profile_uid`, `profile`.* , `contact`.`avatar-date` AS picdate, `user`.* FROM `profile`
1118                                         left join `contact` on `contact`.`uid` = `profile`.`uid` LEFT JOIN `user` ON `profile`.`uid` = `user`.`uid`
1119                                         WHERE `user`.`nickname` = '%s' AND `profile`.`is-default` = 1 and `contact`.`self` = 1 LIMIT 1",
1120                                         dbesc($nickname)
1121                         );
1122                 }
1123
1124                 if(($r === false) || (! count($r))) {
1125                         logger('profile error: ' . $a->query_string, LOGGER_DEBUG);
1126                         notice( t('Requested profile is not available.') . EOL );
1127                         $a->error = 404;
1128                         return;
1129                 }
1130         
1131                 // fetch user tags if this isn't the default profile
1132
1133                 if(! $r[0]['is-default']) {
1134                         $x = q("select `pub_keywords` from `profile` where uid = %d and `is-default` = 1 limit 1",
1135                                         intval($profile_uid)
1136                         );
1137                         if($x && count($x))
1138                                 $r[0]['pub_keywords'] = $x[0]['pub_keywords'];
1139                 }
1140
1141                 $a->profile = $r[0];
1142
1143                 $a->profile['mobile-theme'] = get_pconfig($profile_uid, 'system', 'mobile_theme');
1144
1145
1146                 $a->page['title'] = $a->profile['name'] . " @ " . $a->config['sitename'];
1147                 $_SESSION['theme'] = $a->profile['theme'];
1148                 $_SESSION['mobile-theme'] = $a->profile['mobile-theme'];
1149
1150                 /**
1151                  * load/reload current theme info
1152                  */
1153
1154                 $theme_info_file = "view/theme/".current_theme()."/theme.php";
1155                 if (file_exists($theme_info_file)){
1156                         require_once($theme_info_file);
1157                 }
1158
1159                 if(! (x($a->page,'aside')))
1160                         $a->page['aside'] = '';
1161
1162                 if(local_user() && local_user() == $a->profile['uid']) {
1163                         $a->page['aside'] .= replace_macros(get_markup_template('profile_edlink.tpl'),array(
1164                                 '$editprofile' => t('Edit profile'),
1165                                 '$profid' => $a->profile['id']
1166                         ));
1167                 }
1168
1169                 $block = (((get_config('system','block_public')) && (! local_user()) && (! remote_user())) ? true : false);
1170
1171                 $a->page['aside'] .= profile_sidebar($a->profile, $block);
1172
1173                 /*if(! $block)
1174                  $a->page['aside'] .= contact_block();*/
1175
1176                 return;
1177         }
1178 }
1179
1180
1181 /**
1182  *
1183  * Function: profile_sidebar
1184  *
1185  * Formats a profile for display in the sidebar.
1186  * It is very difficult to templatise the HTML completely
1187  * because of all the conditional logic.
1188  *
1189  * @parameter: array $profile
1190  *
1191  * Returns HTML string stuitable for sidebar inclusion
1192  * Exceptions: Returns empty string if passed $profile is wrong type or not populated
1193  *
1194  */
1195
1196
1197 if(! function_exists('profile_sidebar')) {
1198         function profile_sidebar($profile, $block = 0) {
1199
1200                 $a = get_app();
1201
1202                 $o = '';
1203                 $location = false;
1204                 $address = false;
1205                 $pdesc = true;
1206
1207                 if((! is_array($profile)) && (! count($profile)))
1208                         return $o;
1209
1210                 $profile['picdate'] = urlencode($profile['picdate']);
1211
1212                 call_hooks('profile_sidebar_enter', $profile);
1213
1214         
1215                 // don't show connect link to yourself
1216                 $connect = (($profile['uid'] != local_user()) ? t('Connect')  : False);
1217
1218                 // don't show connect link to authenticated visitors either
1219
1220                 if(remote_user() && count($_SESSION['remote'])) {
1221                         foreach($_SESSION['remote'] as $visitor) {
1222                                 if($visitor['uid'] == $profile['uid']) {
1223                                         $connect = false;
1224                                         break;
1225                                 }
1226                         }
1227                 }
1228
1229                 if(get_my_url() && $profile['unkmail'])
1230                         $wallmessage = t('Message');
1231                 else
1232                         $wallmessage = false;
1233
1234
1235
1236                 // show edit profile to yourself
1237                 if ($profile['uid'] == local_user() && feature_enabled(local_user(),'multi_profiles')) {
1238                         $profile['edit'] = array($a->get_baseurl(). '/profiles', t('Profiles'),"", t('Manage/edit profiles'));
1239                 
1240                         $r = q("SELECT * FROM `profile` WHERE `uid` = %d",
1241                                         local_user());
1242                 
1243                         $profile['menu'] = array(
1244                                 'chg_photo' => t('Change profile photo'),
1245                                 'cr_new' => t('Create New Profile'),
1246                                 'entries' => array(),
1247                         );
1248
1249                         if(count($r)) {
1250
1251                                 foreach($r as $rr) {
1252                                         $profile['menu']['entries'][] = array(
1253                                                 'photo' => $rr['thumb'],
1254                                                 'id' => $rr['id'],
1255                                                 'alt' => t('Profile Image'),
1256                                                 'profile_name' => $rr['profile-name'],
1257                                                 'isdefault' => $rr['is-default'],
1258                                                 'visibile_to_everybody' =>  t('visible to everybody'),
1259                                                 'edit_visibility' => t('Edit visibility'),
1260
1261                                         );
1262                                 }
1263
1264
1265                         }
1266
1267
1268                 }
1269
1270
1271
1272         
1273                 if((x($profile,'address') == 1)
1274                                 || (x($profile,'locality') == 1)
1275                                 || (x($profile,'region') == 1)
1276                                 || (x($profile,'postal-code') == 1)
1277                                 || (x($profile,'country-name') == 1))
1278                         $location = t('Location:');
1279
1280                 $gender = ((x($profile,'gender') == 1) ? t('Gender:') : False);
1281
1282
1283                 $marital = ((x($profile,'marital') == 1) ?  t('Status:') : False);
1284
1285                 $homepage = ((x($profile,'homepage') == 1) ?  t('Homepage:') : False);
1286
1287                 if(($profile['hidewall'] || $block) && (! local_user()) && (! remote_user())) {
1288                         $location = $pdesc = $gender = $marital = $homepage = False;
1289                 }
1290
1291                 $firstname = ((strpos($profile['name'],' '))
1292                                 ? trim(substr($profile['name'],0,strpos($profile['name'],' '))) : $profile['name']);
1293                 $lastname = (($firstname === $profile['name']) ? '' : trim(substr($profile['name'],strlen($firstname))));
1294
1295                 $diaspora = array(
1296                         'podloc' => $a->get_baseurl(),
1297                         'searchable' => (($profile['publish'] && $profile['net-publish']) ? 'true' : 'false' ),
1298                         'nickname' => $profile['nickname'],
1299                         'fullname' => $profile['name'],
1300                         'firstname' => $firstname,
1301                         'lastname' => $lastname,
1302                         'photo300' => $a->get_cached_avatar_image($a->get_baseurl() . '/photo/custom/300/' . $profile['uid'] . '.jpg'),
1303                         'photo100' => $a->get_cached_avatar_image($a->get_baseurl() . '/photo/custom/100/' . $profile['uid'] . '.jpg'),
1304                         'photo50' => $a->get_cached_avatar_image($a->get_baseurl() . '/photo/custom/50/'  . $profile['uid'] . '.jpg'),
1305                 );
1306
1307                 if (!$block){
1308                         $contact_block = contact_block();
1309                 }
1310
1311
1312                 $tpl = get_markup_template('profile_vcard.tpl');
1313
1314                 $o .= replace_macros($tpl, array(
1315                         '$profile' => $profile,
1316                         '$connect'  => $connect,
1317                         '$wallmessage' => $wallmessage,
1318                         '$location' => template_escape($location),
1319                         '$gender'   => $gender,
1320                         '$pdesc'        => $pdesc,
1321                         '$marital'  => $marital,
1322                         '$homepage' => $homepage,
1323                         '$diaspora' => $diaspora,
1324                         '$contact_block' => $contact_block,
1325                 ));
1326
1327
1328                 $arr = array('profile' => &$profile, 'entry' => &$o);
1329
1330                 call_hooks('profile_sidebar', $arr);
1331
1332                 return $o;
1333         }
1334 }
1335
1336
1337 if(! function_exists('get_birthdays')) {
1338         function get_birthdays() {
1339
1340                 $a = get_app();
1341                 $o = '';
1342
1343                 if(! local_user() || $a->is_mobile || $a->is_tablet)
1344                         return $o;
1345
1346 //              $mobile_detect = new Mobile_Detect();
1347 //              $is_mobile = $mobile_detect->isMobile() || $mobile_detect->isTablet();
1348
1349 //              if($is_mobile)
1350 //                      return $o;
1351
1352                 $bd_format = t('g A l F d') ; // 8 AM Friday January 18
1353                 $bd_short = t('F d');
1354
1355                 $r = q("SELECT `event`.*, `event`.`id` AS `eid`, `contact`.* FROM `event`
1356                                 LEFT JOIN `contact` ON `contact`.`id` = `event`.`cid`
1357                                 WHERE `event`.`uid` = %d AND `type` = 'birthday' AND `start` < '%s' AND `finish` > '%s'
1358                                 ORDER BY `start` ASC ",
1359                                 intval(local_user()),
1360                                 dbesc(datetime_convert('UTC','UTC','now + 6 days')),
1361                                 dbesc(datetime_convert('UTC','UTC','now'))
1362                 );
1363
1364                 if($r && count($r)) {
1365                         $total = 0;
1366                         $now = strtotime('now');
1367                         $cids = array();
1368
1369                         $istoday = false;
1370                         foreach($r as $rr) {
1371                                 if(strlen($rr['name']))
1372                                         $total ++;
1373                                 if((strtotime($rr['start'] . ' +00:00') < $now) && (strtotime($rr['finish'] . ' +00:00') > $now))
1374                                         $istoday = true;
1375                         }
1376                         $classtoday = $istoday ? ' birthday-today ' : '';
1377                         if($total) {
1378                                 foreach($r as &$rr) {
1379                                         if(! strlen($rr['name']))
1380                                                 continue;
1381
1382                                         // avoid duplicates
1383
1384                                         if(in_array($rr['cid'],$cids))
1385                                                 continue;
1386                                         $cids[] = $rr['cid'];
1387
1388                                         $today = (((strtotime($rr['start'] . ' +00:00') < $now) && (strtotime($rr['finish'] . ' +00:00') > $now)) ? true : false);
1389                                         $sparkle = '';
1390                                         $url = $rr['url'];
1391                                         if($rr['network'] === NETWORK_DFRN) {
1392                                                 $sparkle = " sparkle";
1393                                                 $url = $a->get_baseurl() . '/redir/'  . $rr['cid'];
1394                                         }
1395         
1396                                         $rr['link'] = $url;
1397                                         $rr['title'] = $rr['name'];
1398                                         $rr['date'] = day_translate(datetime_convert('UTC', $a->timezone, $rr['start'], $rr['adjust'] ? $bd_format : $bd_short)) . (($today) ?  ' ' . t('[today]') : '');
1399                                         $rr['startime'] = Null;
1400                                         $rr['today'] = $today;
1401         
1402                                 }
1403                         }
1404                 }
1405                 $tpl = get_markup_template("birthdays_reminder.tpl");
1406                 return replace_macros($tpl, array(
1407                         '$baseurl' => $a->get_baseurl(),
1408                         '$classtoday' => $classtoday,
1409                         '$count' => $total,
1410                         '$event_reminders' => t('Birthday Reminders'),
1411                         '$event_title' => t('Birthdays this week:'),
1412                         '$events' => $r,
1413                         '$lbr' => '{',  // raw brackets mess up if/endif macro processing
1414                         '$rbr' => '}'
1415
1416                 ));
1417         }
1418 }
1419
1420
1421 if(! function_exists('get_events')) {
1422         function get_events() {
1423
1424                 require_once('include/bbcode.php');
1425
1426                 $a = get_app();
1427
1428                 if(! local_user() || $a->is_mobile || $a->is_tablet)
1429                         return $o;
1430
1431
1432 //              $mobile_detect = new Mobile_Detect();
1433 //              $is_mobile = $mobile_detect->isMobile() || $mobile_detect->isTablet();
1434
1435 //              if($is_mobile)
1436 //                      return $o;
1437
1438                 $bd_format = t('g A l F d') ; // 8 AM Friday January 18
1439                 $bd_short = t('F d');
1440
1441                 $r = q("SELECT `event`.* FROM `event`
1442                                 WHERE `event`.`uid` = %d AND `type` != 'birthday' AND `start` < '%s' AND `start` > '%s'
1443                                 ORDER BY `start` ASC ",
1444                                 intval(local_user()),
1445                                 dbesc(datetime_convert('UTC','UTC','now + 6 days')),
1446                                 dbesc(datetime_convert('UTC','UTC','now - 1 days'))
1447                 );
1448
1449                 if($r && count($r)) {
1450                         $now = strtotime('now');
1451                         $istoday = false;
1452                         foreach($r as $rr) {
1453                                 if(strlen($rr['name']))
1454                                         $total ++;
1455
1456                                 $strt = datetime_convert('UTC',$rr['convert'] ? $a->timezone : 'UTC',$rr['start'],'Y-m-d');
1457                                 if($strt === datetime_convert('UTC',$a->timezone,'now','Y-m-d'))
1458                                         $istoday = true;
1459                         }
1460                         $classtoday = (($istoday) ? 'event-today' : '');
1461
1462
1463                         foreach($r as &$rr) {
1464                                 if($rr['adjust'])
1465                                         $md = datetime_convert('UTC',$a->timezone,$rr['start'],'Y/m');
1466                                 else
1467                                         $md = datetime_convert('UTC','UTC',$rr['start'],'Y/m');
1468                                 $md .= "/#link-".$rr['id'];
1469
1470                                 $title = substr(strip_tags(bbcode($rr['desc'])),0,32) . '... ';
1471                                 if(! $title)
1472                                         $title = t('[No description]');
1473
1474                                 $strt = datetime_convert('UTC',$rr['convert'] ? $a->timezone : 'UTC',$rr['start']);
1475                                 $today = ((substr($strt,0,10) === datetime_convert('UTC',$a->timezone,'now','Y-m-d')) ? true : false);
1476                                 
1477                                 $rr['link'] = $md;
1478                                 $rr['title'] = $title;
1479                                 $rr['date'] = day_translate(datetime_convert('UTC', $rr['adjust'] ? $a->timezone : 'UTC', $rr['start'], $bd_format)) . (($today) ?  ' ' . t('[today]') : '');
1480                                 $rr['startime'] = $strt;
1481                                 $rr['today'] = $today;
1482                         }
1483                 }
1484
1485                 $tpl = get_markup_template("events_reminder.tpl");
1486                 return replace_macros($tpl, array(
1487                         '$baseurl' => $a->get_baseurl(),
1488                         '$classtoday' => $classtoday,
1489                         '$count' => count($r),
1490                         '$event_reminders' => t('Event Reminders'),
1491                         '$event_title' => t('Events this week:'),
1492                         '$events' => $r,
1493                 ));
1494         }
1495 }
1496
1497
1498 /**
1499  *
1500  * Wrap calls to proc_close(proc_open()) and call hook
1501  * so plugins can take part in process :)
1502  *
1503  * args:
1504  * $cmd program to run
1505  *  next args are passed as $cmd command line
1506  *
1507  * e.g.: proc_run("ls","-la","/tmp");
1508  *
1509  * $cmd and string args are surrounded with ""
1510  */
1511
1512 if(! function_exists('proc_run')) {
1513         function proc_run($cmd){
1514
1515                 $a = get_app();
1516
1517                 $args = func_get_args();
1518
1519                 $newargs = array();
1520                 if(! count($args))
1521                         return;
1522
1523                 // expand any arrays
1524
1525                 foreach($args as $arg) {
1526                         if(is_array($arg)) {
1527                                 foreach($arg as $n) {
1528                                         $newargs[] = $n;
1529                                 }
1530                         }
1531                         else
1532                                 $newargs[] = $arg;
1533                 }
1534
1535                 $args = $newargs;
1536                 
1537                 $arr = array('args' => $args, 'run_cmd' => true);
1538
1539                 call_hooks("proc_run", $arr);
1540                 if(! $arr['run_cmd'])
1541                         return;
1542
1543                 if(count($args) && $args[0] === 'php')
1544                         $args[0] = ((x($a->config,'php_path')) && (strlen($a->config['php_path'])) ? $a->config['php_path'] : 'php');
1545         
1546         // add baseurl to args. cli scripts can't construct it
1547         $args[] = $a->get_baseurl();
1548         
1549         for($x = 0; $x < count($args); $x ++)
1550                         $args[$x] = escapeshellarg($args[$x]);
1551
1552         
1553
1554                 $cmdline = implode($args," ");
1555                 if(get_config('system','proc_windows'))
1556                         proc_close(proc_open('cmd /c start /b ' . $cmdline,array(),$foo,dirname(__FILE__)));
1557                 else
1558                         proc_close(proc_open($cmdline." &",array(),$foo,dirname(__FILE__)));
1559         }
1560 }
1561
1562 if(! function_exists('current_theme')) {
1563         function current_theme(){
1564                 $app_base_themes = array('duepuntozero', 'dispy', 'quattro');
1565         
1566                 $a = get_app();
1567         
1568 //              $mobile_detect = new Mobile_Detect();
1569 //              $is_mobile = $mobile_detect->isMobile() || $mobile_detect->isTablet();
1570                 $is_mobile = $a->is_mobile || $a->is_tablet;
1571         
1572                 if($is_mobile) {
1573                         if(isset($_SESSION['show-mobile']) && !$_SESSION['show-mobile']) {
1574                                 $system_theme = '';
1575                                 $theme_name = '';
1576                         }
1577                         else {
1578                                 $system_theme = ((isset($a->config['system']['mobile-theme'])) ? $a->config['system']['mobile-theme'] : '');
1579                                 $theme_name = ((isset($_SESSION) && x($_SESSION,'mobile-theme')) ? $_SESSION['mobile-theme'] : $system_theme);
1580
1581                                 if($theme_name === '---') {
1582                                         // user has selected to have the mobile theme be the same as the normal one
1583                                         $system_theme = '';
1584                                         $theme_name = '';
1585                                 }
1586                         }
1587                 }
1588                 if(!$is_mobile || ($system_theme === '' && $theme_name === '')) {
1589                         $system_theme = ((isset($a->config['system']['theme'])) ? $a->config['system']['theme'] : '');
1590                         $theme_name = ((isset($_SESSION) && x($_SESSION,'theme')) ? $_SESSION['theme'] : $system_theme);
1591                 }
1592
1593                 if($theme_name &&
1594                                 (file_exists('view/theme/' . $theme_name . '/style.css') ||
1595                                                 file_exists('view/theme/' . $theme_name . '/style.php')))
1596                         return($theme_name);
1597         
1598                 foreach($app_base_themes as $t) {
1599                         if(file_exists('view/theme/' . $t . '/style.css')||
1600                                         file_exists('view/theme/' . $t . '/style.php'))
1601                                 return($t);
1602                 }
1603         
1604                 $fallback = array_merge(glob('view/theme/*/style.css'),glob('view/theme/*/style.php'));
1605                 if(count($fallback))
1606                         return (str_replace('view/theme/','', substr($fallback[0],0,-10)));
1607         
1608         }
1609 }
1610
1611 /*
1612  * Return full URL to theme which is currently in effect.
1613 * Provide a sane default if nothing is chosen or the specified theme does not exist.
1614 */
1615 if(! function_exists('current_theme_url')) {
1616         function current_theme_url() {
1617                 global $a;
1618                 $t = current_theme();
1619                 if (file_exists('view/theme/' . $t . '/style.php'))
1620                         return($a->get_baseurl() . '/view/theme/' . $t . '/style.pcss');
1621                 return($a->get_baseurl() . '/view/theme/' . $t . '/style.css');
1622         }
1623 }
1624
1625 if(! function_exists('feed_birthday')) {
1626         function feed_birthday($uid,$tz) {
1627
1628                 /**
1629                  *
1630                  * Determine the next birthday, but only if the birthday is published
1631                  * in the default profile. We _could_ also look for a private profile that the
1632                  * recipient can see, but somebody could get mad at us if they start getting
1633                  * public birthday greetings when they haven't made this info public.
1634                  *
1635                  * Assuming we are able to publish this info, we are then going to convert
1636                  * the start time from the owner's timezone to UTC.
1637                  *
1638                  * This will potentially solve the problem found with some social networks
1639                  * where birthdays are converted to the viewer's timezone and salutations from
1640                  * elsewhere in the world show up on the wrong day. We will convert it to the
1641                  * viewer's timezone also, but first we are going to convert it from the birthday
1642                  * person's timezone to GMT - so the viewer may find the birthday starting at
1643                  * 6:00PM the day before, but that will correspond to midnight to the birthday person.
1644                  *
1645                  */
1646
1647         
1648                 $birthday = '';
1649
1650                 if(! strlen($tz))
1651                         $tz = 'UTC';
1652
1653                 $p = q("SELECT `dob` FROM `profile` WHERE `is-default` = 1 AND `uid` = %d LIMIT 1",
1654                                 intval($uid)
1655                 );
1656
1657                 if($p && count($p)) {
1658                         $tmp_dob = substr($p[0]['dob'],5);
1659                         if(intval($tmp_dob)) {
1660                                 $y = datetime_convert($tz,$tz,'now','Y');
1661                                 $bd = $y . '-' . $tmp_dob . ' 00:00';
1662                                 $t_dob = strtotime($bd);
1663                                 $now = strtotime(datetime_convert($tz,$tz,'now'));
1664                                 if($t_dob < $now)
1665                                         $bd = $y + 1 . '-' . $tmp_dob . ' 00:00';
1666                                 $birthday = datetime_convert($tz,'UTC',$bd,ATOM_TIME);
1667                         }
1668                 }
1669
1670                 return $birthday;
1671         }
1672 }
1673
1674 if(! function_exists('is_site_admin')) {
1675         function is_site_admin() {
1676                 $a = get_app();
1677                 if(local_user() && x($a->user,'email') && x($a->config,'admin_email') && ($a->user['email'] === $a->config['admin_email']))
1678                         return true;
1679                 return false;
1680         }
1681 }
1682
1683
1684 if(! function_exists('load_contact_links')) {
1685         function load_contact_links($uid) {
1686
1687                 $a = get_app();
1688
1689                 $ret = array();
1690
1691                 if(! $uid || x($a->contacts,'empty'))
1692                         return;
1693
1694                 $r = q("SELECT `id`,`network`,`url`,`thumb` FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 ",
1695                                 intval($uid)
1696                 );
1697                 if(count($r)) {
1698                         foreach($r as $rr){
1699                                 $url = normalise_link($rr['url']);
1700                                 $ret[$url] = $rr;
1701                         }
1702                 }
1703                 else
1704                         $ret['empty'] = true;
1705                 $a->contacts = $ret;
1706                 return;
1707         }
1708 }
1709
1710 if(! function_exists('profile_tabs')){
1711         function profile_tabs($a, $is_owner=False, $nickname=Null){
1712                 //echo "<pre>"; var_dump($a->user); killme();
1713         
1714                 if (is_null($nickname))
1715                         $nickname  = $a->user['nickname'];
1716                 
1717                 if(x($_GET,'tab'))
1718                         $tab = notags(trim($_GET['tab']));
1719         
1720                 $url = $a->get_baseurl() . '/profile/' . $nickname;
1721
1722                 $tabs = array(
1723                         array(
1724                                 'label'=>t('Status'),
1725                                 'url' => $url,
1726                                 'sel' => ((!isset($tab)&&$a->argv[0]=='profile')?'active':''),
1727                                 'title' => t('Status Messages and Posts'),
1728                                 'id' => 'status-tab',
1729                         ),
1730                         array(
1731                                 'label' => t('Profile'),
1732                                 'url'   => $url.'/?tab=profile',
1733                                 'sel'   => ((isset($tab) && $tab=='profile')?'active':''),
1734                                 'title' => t('Profile Details'),
1735                                 'id' => 'profile-tab',
1736                         ),
1737                         array(
1738                                 'label' => t('Photos'),
1739                                 'url'   => $a->get_baseurl() . '/photos/' . $nickname,
1740                                 'sel'   => ((!isset($tab)&&$a->argv[0]=='photos')?'active':''),
1741                                 'title' => t('Photo Albums'),
1742                                 'id' => 'photo-tab',
1743                         ),
1744                 );
1745         
1746                 if ($is_owner){
1747                         $tabs[] = array(
1748                                 'label' => t('Events'),
1749                                 'url'   => $a->get_baseurl() . '/events',
1750                                 'sel'   =>((!isset($tab)&&$a->argv[0]=='events')?'active':''),
1751                                 'title' => t('Events and Calendar'),
1752                                 'id' => 'events-tab',
1753                         );
1754                         $tabs[] = array(
1755                                 'label' => t('Personal Notes'),
1756                                 'url'   => $a->get_baseurl() . '/notes',
1757                                 'sel'   =>((!isset($tab)&&$a->argv[0]=='notes')?'active':''),
1758                                 'title' => t('Only You Can See This'),
1759                                 'id' => 'notes-tab',
1760                         );
1761                 }
1762
1763
1764                 $arr = array('is_owner' => $is_owner, 'nickname' => $nickname, 'tab' => (($tab) ? $tab : false), 'tabs' => $tabs);
1765                 call_hooks('profile_tabs', $arr);
1766         
1767                 $tpl = get_markup_template('common_tabs.tpl');
1768
1769                 return replace_macros($tpl,array('$tabs' => $arr['tabs']));
1770         }
1771 }
1772
1773 function get_my_url() {
1774         if(x($_SESSION,'my_url'))
1775                 return $_SESSION['my_url'];
1776         return false;
1777 }
1778
1779 function zrl_init(&$a) {
1780         $tmp_str = get_my_url();
1781         if(validate_url($tmp_str)) {
1782                 proc_run('php','include/gprobe.php',bin2hex($tmp_str));
1783                 $arr = array('zrl' => $tmp_str, 'url' => $a->cmd);
1784                 call_hooks('zrl_init',$arr);
1785         }
1786 }
1787
1788 function zrl($s,$force = false) {
1789         if(! strlen($s))
1790                 return $s;
1791         if((! strpos($s,'/profile/')) && (! $force))
1792                 return $s;
1793         if($force && substr($s,-1,1) !== '/')
1794                 $s = $s . '/';
1795         $achar = strpos($s,'?') ? '&' : '?';
1796         $mine = get_my_url();
1797         if($mine and ! link_compare($mine,$s))
1798                 return $s . $achar . 'zrl=' . urlencode($mine);
1799         return $s;
1800 }
1801
1802 /**
1803 * returns querystring as string from a mapped array
1804 *
1805 * @param params Array 
1806 * @return string
1807 */
1808 function build_querystring($params, $name=null) { 
1809     $ret = ""; 
1810     foreach($params as $key=>$val) {
1811         if(is_array($val)) { 
1812             if($name==null) {
1813                 $ret .= build_querystring($val, $key); 
1814             } else {
1815                 $ret .= build_querystring($val, $name."[$key]");    
1816             }
1817         } else {
1818             $val = urlencode($val);
1819             if($name!=null) {
1820                 $ret.=$name."[$key]"."=$val&"; 
1821             } else {
1822                 $ret.= "$key=$val&"; 
1823             }
1824         } 
1825     } 
1826     return $ret;    
1827 }
1828
1829 /**
1830 * Returns the complete URL of the current page, e.g.: http(s)://something.com/network
1831 *
1832 * Taken from http://webcheatsheet.com/php/get_current_page_url.php
1833 */
1834 function curPageURL() {
1835         $pageURL = 'http';
1836         if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
1837         $pageURL .= "://";
1838         if ($_SERVER["SERVER_PORT"] != "80" && $_SERVER["SERVER_PORT"] != "443") {
1839                 $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
1840         } else {
1841                 $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
1842         }
1843         return $pageURL;
1844 }
1845
1846 function random_digits($digits) {
1847         $rn = '';
1848         for($i = 0; $i < $digits; $i++) {
1849                 $rn .= rand(0,9);
1850         }
1851         return $rn;
1852 }
1853
1854 function get_cachefile($file, $writemode = true) {
1855         $cache = get_config("system","itemcache");
1856
1857         if ($cache == "")
1858                 return("");
1859
1860         if (!is_dir($cache))
1861                 return("");
1862
1863         $subfolder = $cache."/".substr($file, 0, 2);
1864
1865         $cachepath = $subfolder."/".$file;
1866
1867         if ($writemode) {
1868                 if (!is_dir($subfolder)) {
1869                         mkdir($subfolder);
1870                         chmod($subfolder, 0777);
1871                 }
1872         }
1873
1874         return($cachepath);
1875 }
1876
1877 function clear_cache($basepath = "", $path = "") {
1878         if ($path == "") {
1879                 $basepath = get_config('system','itemcache');
1880                 $path = $basepath;
1881         }
1882
1883         if (($path == "") OR (!is_dir($path)))
1884                 return;
1885
1886         if (substr(realpath($path), 0, strlen($basepath)) != $basepath)
1887                 return;
1888
1889         $cachetime = (int)get_config('system','itemcache_duration');
1890         if ($cachetime == 0)
1891                 $cachetime = 86400;
1892
1893         if ($dh = opendir($path)) {
1894                 while (($file = readdir($dh)) !== false) {
1895                         $fullpath = $path."/".$file;
1896                         if ((filetype($fullpath) == "dir") and ($file != ".") and ($file != ".."))
1897                                 clear_cache($basepath, $fullpath);
1898                         if ((filetype($fullpath) == "file") and filectime($fullpath) < (time() - $cachetime))
1899                                 unlink($fullpath);
1900                 }
1901                 closedir($dh);
1902         }
1903 }