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