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