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