]> git.mxchange.org Git - friendica.git/blob - boot.php
diaspora admin toggle, update install guide
[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
9
10 define ( 'FRIENDIKA_VERSION',      '2.2.1080' );
11 define ( 'DFRN_PROTOCOL_VERSION',  '2.21'    );
12 define ( 'DB_UPDATE_VERSION',      1081      );
13
14 define ( 'EOL',                    "<br />\r\n"     );
15 define ( 'ATOM_TIME',              'Y-m-d\TH:i:s\Z' );
16
17
18 /**
19  *
20  * Image storage quality. Lower numbers save space at cost of image detail.
21  * For ease of upgrade, please do not change here. Change jpeg quality with 
22  * set_config('system','jpeg_quality',n) in .htconfig.php
23  * where n is netween 1 and 100, and with very poor results below about 50 
24  *
25  */
26
27 define ( 'JPEG_QUALITY',            100  );         
28
29 /**
30  * SSL redirection policies
31  */
32
33 define ( 'SSL_POLICY_NONE',         0 );
34 define ( 'SSL_POLICY_FULL',         1 );
35 define ( 'SSL_POLICY_SELFSIGN',     2 );
36
37
38 /**
39  * log levels
40  */
41
42 define ( 'LOGGER_NORMAL',          0 );
43 define ( 'LOGGER_TRACE',           1 );
44 define ( 'LOGGER_DEBUG',           2 );
45 define ( 'LOGGER_DATA',            3 );
46 define ( 'LOGGER_ALL',             4 );
47
48 /**
49  * registration policies
50  */
51
52 define ( 'REGISTER_CLOSED',        0 );
53 define ( 'REGISTER_APPROVE',       1 );
54 define ( 'REGISTER_OPEN',          2 );
55
56 /**
57  * relationship types
58  */
59
60 define ( 'CONTACT_IS_FOLLOWER', 1);
61 define ( 'CONTACT_IS_SHARING',  2);
62 define ( 'CONTACT_IS_FRIEND',   3);
63
64
65 /**
66  * Hook array order
67  */
68  
69 define ( 'HOOK_HOOK',      0);
70 define ( 'HOOK_FILE',      1);
71 define ( 'HOOK_FUNCTION',  2);
72
73 /**
74  *
75  * page/profile types
76  *
77  * PAGE_NORMAL is a typical personal profile account
78  * PAGE_SOAPBOX automatically approves all friend requests as CONTACT_IS_SHARING, (readonly)
79  * PAGE_COMMUNITY automatically approves all friend requests as CONTACT_IS_SHARING, but with 
80  *      write access to wall and comments (no email and not included in page owner's ACL lists)
81  * PAGE_FREELOVE automatically approves all friend requests as full friends (CONTACT_IS_FRIEND). 
82  *
83  */
84
85 define ( 'PAGE_NORMAL',            0 );
86 define ( 'PAGE_SOAPBOX',           1 );
87 define ( 'PAGE_COMMUNITY',         2 );
88 define ( 'PAGE_FREELOVE',          3 );
89
90 /**
91  * Network and protocol family types 
92  */
93
94 define ( 'NETWORK_ZOT',              'zot!');    // Zot!
95 define ( 'NETWORK_DFRN',             'dfrn');    // Friendika, Mistpark, other DFRN implementations
96 define ( 'NETWORK_OSTATUS',          'stat');    // status.net, identi.ca, GNU-social, other OStatus implementations
97 define ( 'NETWORK_FEED',             'feed');    // RSS/Atom feeds with no known "post/notify" protocol
98 define ( 'NETWORK_DIASPORA',         'dspr');    // Diaspora
99 define ( 'NETWORK_MAIL',             'mail');    // IMAP/POP
100 define ( 'NETWORK_FACEBOOK',         'face');    // Facebook API     
101
102
103 /**
104  * Maximum number of "people who like (or don't like) this"  that we will list by name
105  */
106
107 define ( 'MAX_LIKERS',    75);
108
109 /**
110  * Communication timeout
111  */
112
113 define ( 'ZCURL_TIMEOUT' , (-1));
114
115
116 /**
117  * email notification options
118  */
119
120 define ( 'NOTIFY_INTRO',   0x0001 );
121 define ( 'NOTIFY_CONFIRM', 0x0002 );
122 define ( 'NOTIFY_WALL',    0x0004 );
123 define ( 'NOTIFY_COMMENT', 0x0008 );
124 define ( 'NOTIFY_MAIL',    0x0010 );
125
126 /**
127  * various namespaces we may need to parse
128  */
129
130 define ( 'NAMESPACE_ZOT',             'http://purl.org/macgirvin/zot' );
131 define ( 'NAMESPACE_DFRN' ,           'http://purl.org/macgirvin/dfrn/1.0' ); 
132 define ( 'NAMESPACE_THREAD' ,         'http://purl.org/syndication/thread/1.0' );
133 define ( 'NAMESPACE_TOMB' ,           'http://purl.org/atompub/tombstones/1.0' );
134 define ( 'NAMESPACE_ACTIVITY',        'http://activitystrea.ms/spec/1.0/' );
135 define ( 'NAMESPACE_ACTIVITY_SCHEMA', 'http://activitystrea.ms/schema/1.0/' );
136 define ( 'NAMESPACE_MEDIA',           'http://purl.org/syndication/atommedia' );
137 define ( 'NAMESPACE_SALMON_ME',       'http://salmon-protocol.org/ns/magic-env' );
138 define ( 'NAMESPACE_OSTATUSSUB',      'http://ostatus.org/schema/1.0/subscribe' );
139 define ( 'NAMESPACE_GEORSS',          'http://www.georss.org/georss' );
140 define ( 'NAMESPACE_POCO',            'http://portablecontacts.net/spec/1.0' );
141 define ( 'NAMESPACE_FEED',            'http://schemas.google.com/g/2010#updates-from' );
142 define ( 'NAMESPACE_OSTATUS',         'http://ostatus.org/schema/1.0' );
143 define ( 'NAMESPACE_STATUSNET',       'http://status.net/schema/api/1/' );
144 define ( 'NAMESPACE_ATOM1',           'http://www.w3.org/2005/Atom' );
145 /**
146  * activity stream defines
147  */
148
149 define ( 'ACTIVITY_LIKE',        NAMESPACE_ACTIVITY_SCHEMA . 'like' );
150 define ( 'ACTIVITY_DISLIKE',     NAMESPACE_DFRN            . '/dislike' );
151 define ( 'ACTIVITY_OBJ_HEART',   NAMESPACE_DFRN            . '/heart' );
152
153 define ( 'ACTIVITY_FRIEND',      NAMESPACE_ACTIVITY_SCHEMA . 'make-friend' );
154 define ( 'ACTIVITY_FOLLOW',      NAMESPACE_ACTIVITY_SCHEMA . 'follow' );
155 define ( 'ACTIVITY_UNFOLLOW',    NAMESPACE_ACTIVITY_SCHEMA . 'stop-following' );
156 define ( 'ACTIVITY_POST',        NAMESPACE_ACTIVITY_SCHEMA . 'post' );
157 define ( 'ACTIVITY_UPDATE',      NAMESPACE_ACTIVITY_SCHEMA . 'update' );
158 define ( 'ACTIVITY_TAG',         NAMESPACE_ACTIVITY_SCHEMA . 'tag' );
159
160 define ( 'ACTIVITY_OBJ_COMMENT', NAMESPACE_ACTIVITY_SCHEMA . 'comment' );
161 define ( 'ACTIVITY_OBJ_NOTE',    NAMESPACE_ACTIVITY_SCHEMA . 'note' );
162 define ( 'ACTIVITY_OBJ_PERSON',  NAMESPACE_ACTIVITY_SCHEMA . 'person' );
163 define ( 'ACTIVITY_OBJ_PHOTO',   NAMESPACE_ACTIVITY_SCHEMA . 'photo' );
164 define ( 'ACTIVITY_OBJ_P_PHOTO', NAMESPACE_ACTIVITY_SCHEMA . 'profile-photo' );
165 define ( 'ACTIVITY_OBJ_ALBUM',   NAMESPACE_ACTIVITY_SCHEMA . 'photo-album' );
166 define ( 'ACTIVITY_OBJ_EVENT',   NAMESPACE_ACTIVITY_SCHEMA . 'event' );
167
168 /**
169  * item weight for query ordering
170  */
171
172 define ( 'GRAVITY_PARENT',       0);
173 define ( 'GRAVITY_LIKE',         3);
174 define ( 'GRAVITY_COMMENT',      6);
175
176 /**
177  *
178  * Reverse the effect of magic_quotes_gpc if it is enabled.
179  * Please disable magic_quotes_gpc so we don't have to do this.
180  * See http://php.net/manual/en/security.magicquotes.disabling.php
181  *
182  */
183
184 function startup() {
185         error_reporting(E_ERROR | E_WARNING | E_PARSE);
186         set_time_limit(0);
187         ini_set('pcre.backtrack_limit', 250000);
188
189
190         if (get_magic_quotes_gpc()) {
191         $process = array(&$_GET, &$_POST, &$_COOKIE, &$_REQUEST);
192             while (list($key, $val) = each($process)) {
193             foreach ($val as $k => $v) {
194                     unset($process[$key][$k]);
195                 if (is_array($v)) {
196                         $process[$key][stripslashes($k)] = $v;
197                         $process[] = &$process[$key][stripslashes($k)];
198                 } else {
199                         $process[$key][stripslashes($k)] = stripslashes($v);
200                 }
201                 }
202         }
203             unset($process);
204         }
205
206 }
207
208 /**
209  *
210  * class: App
211  *
212  * Our main application structure for the life of this page
213  * Primarily deals with the URL that got us here
214  * and tries to make some sense of it, and 
215  * stores our page contents and config storage
216  * and anything else that might need to be passed around 
217  * before we spit the page out. 
218  *
219  */
220
221 if(! class_exists('App')) {
222 class App {
223
224         public  $module_loaded = false;
225         public  $query_string;
226         public  $config;
227         public  $page;
228         public  $profile;
229         public  $user;
230         public  $cid;
231         public  $contact;
232         public  $contacts;
233         public  $page_contact;
234         public  $content;
235         public  $data;
236         public  $error = false;
237         public  $cmd;
238         public  $argv;
239         public  $argc;
240         public  $module;
241         public  $pager;
242         public  $strings;   
243         public  $path;
244         public  $hooks;
245         public  $timezone;
246         public  $interactive = true;
247         public  $plugins;
248         public  $apps;
249         public  $identities;
250
251         private $scheme;
252         private $hostname;
253         private $baseurl;
254         private $db;
255
256         private $curl_code;
257         private $curl_headers;
258
259         function __construct() {
260
261                 $this->config = array();
262                 $this->page = array();
263                 $this->pager= array();
264
265                 $this->query_string = '';
266
267                 startup();
268
269                 $this->scheme = ((isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS']))      ?  'https' : 'http' );
270
271                 if(x($_SERVER,'SERVER_NAME')) {
272                         $this->hostname = $_SERVER['SERVER_NAME'];
273                         if(x($_SERVER,'SERVER_PORT') && $_SERVER['SERVER_PORT'] != 80 && $_SERVER['SERVER_PORT'] != 443)
274                                 $this->hostname .= ':' . $_SERVER['SERVER_PORT'];
275                         /** 
276                          * Figure out if we are running at the top of a domain
277                          * or in a sub-directory and adjust accordingly
278                          */
279
280                         $path = trim(dirname($_SERVER['SCRIPT_NAME']),'/\\');
281                         if(isset($path) && strlen($path) && ($path != $this->path))
282                                 $this->path = $path;
283                 }
284
285                 set_include_path(
286                         "include/$this->hostname" . PATH_SEPARATOR 
287                         . 'include' . PATH_SEPARATOR 
288                         . 'library' . PATH_SEPARATOR 
289                         . 'library/phpsec' . PATH_SEPARATOR 
290                         . '.' );
291
292                 if((x($_SERVER,'QUERY_STRING')) && substr($_SERVER['QUERY_STRING'],0,2) === "q=")
293                         $this->query_string = substr($_SERVER['QUERY_STRING'],2);
294                 if(x($_GET,'q'))
295                         $this->cmd = trim($_GET['q'],'/\\');
296
297
298
299                 /**
300                  *
301                  * Break the URL path into C style argc/argv style arguments for our
302                  * modules. Given "http://example.com/module/arg1/arg2", $this->argc
303                  * will be 3 (integer) and $this->argv will contain:
304                  *   [0] => 'module'
305                  *   [1] => 'arg1'
306                  *   [2] => 'arg2'
307                  *
308                  *
309                  * There will always be one argument. If provided a naked domain
310                  * URL, $this->argv[0] is set to "home".
311                  *
312                  */
313
314                 $this->argv = explode('/',$this->cmd);
315                 $this->argc = count($this->argv);
316                 if((array_key_exists('0',$this->argv)) && strlen($this->argv[0])) {
317                         $this->module = str_replace(".", "_", $this->argv[0]);
318                 }
319                 else {
320                         $this->argc = 1;
321                         $this->argv = array('home');
322                         $this->module = 'home';
323                 }
324
325                 /**
326                  * Special handling for the webfinger/lrdd host XRD file
327                  */
328
329                 if($this->cmd === '.well-known/host-meta') {
330                         $this->argc = 1;
331                         $this->argv = array('hostxrd');
332                         $this->module = 'hostxrd';
333                 }
334
335                 /**
336                  * See if there is any page number information, and initialise 
337                  * pagination
338                  */
339
340                 $this->pager['page'] = ((x($_GET,'page')) ? $_GET['page'] : 1);
341                 $this->pager['itemspage'] = 50;
342                 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
343                 $this->pager['total'] = 0;
344         }
345
346         function get_baseurl($ssl = false) {
347
348                 $scheme = $this->scheme;
349
350                 if(x($this->config,'ssl_policy')) {
351                         if(($ssl) || ($this->config['ssl_policy'] == SSL_POLICY_FULL)) 
352                                 $scheme = 'https';
353                         if(($this->config['ssl_policy'] == SSL_POLICY_SELFSIGN) && (local_user() || x($_POST,'auth-params')))
354                                 $scheme = 'https';
355                 }
356
357                 $this->baseurl = $scheme . "://" . $this->hostname . ((isset($this->path) && strlen($this->path)) ? '/' . $this->path : '' );
358                 return $this->baseurl;
359         }
360
361         function set_baseurl($url) {
362                 $parsed = @parse_url($url);
363
364                 $this->baseurl = $url;
365
366                 if($parsed) {           
367                         $this->scheme = $parsed['scheme'];
368
369                         $this->hostname = $parsed['host'];
370                         if(x($parsed,'port'))
371                                 $this->hostname .= ':' . $parsed['port'];
372                         if(x($parsed,'path'))
373                                 $this->path = trim($parsed['path'],'\\/');
374                 }
375
376         }
377
378         function get_hostname() {
379                 return $this->hostname;
380         }
381
382         function set_hostname($h) {
383                 $this->hostname = $h;
384         }
385
386         function set_path($p) {
387                 $this->path = trim(trim($p),'/');
388         } 
389
390         function get_path() {
391                 return $this->path;
392         }
393
394         function set_pager_total($n) {
395                 $this->pager['total'] = intval($n);
396         }
397
398         function set_pager_itemspage($n) {
399                 $this->pager['itemspage'] = intval($n);
400                 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
401
402         } 
403
404         function init_pagehead() {
405                 $this->page['title'] = $this->config['sitename'];
406                 $tpl = file_get_contents('view/head.tpl');
407                 $this->page['htmlhead'] = replace_macros($tpl,array(
408                         '$baseurl' => $this->get_baseurl(), // FIXME for z_path!!!!
409                         '$generator' => 'Friendika' . ' ' . FRIENDIKA_VERSION,
410                         '$delitem' => t('Delete this item?'),
411                         '$comment' => t('Comment')
412                 ));
413         }
414
415         function set_curl_code($code) {
416                 $this->curl_code = $code;
417         }
418
419         function get_curl_code() {
420                 return $this->curl_code;
421         }
422
423         function set_curl_headers($headers) {
424                 $this->curl_headers = $headers;
425         }
426
427         function get_curl_headers() {
428                 return $this->curl_headers;
429         }
430
431
432 }}
433
434 // retrieve the App structure
435 // useful in functions which require it but don't get it passed to them
436
437 if(! function_exists('get_app')) {
438 function get_app() {
439         global $a;
440         return $a;
441 }};
442
443
444 // Multi-purpose function to check variable state.
445 // Usage: x($var) or $x($array,'key')
446 // returns false if variable/key is not set
447 // if variable is set, returns 1 if has 'non-zero' value, otherwise returns 0.
448 // e.g. x('') or x(0) returns 0;
449
450 if(! function_exists('x')) {
451 function x($s,$k = NULL) {
452         if($k != NULL) {
453                 if((is_array($s)) && (array_key_exists($k,$s))) {
454                         if($s[$k])
455                                 return (int) 1;
456                         return (int) 0;
457                 }
458                 return false;
459         }
460         else {          
461                 if(isset($s)) {
462                         if($s) {
463                                 return (int) 1;
464                         }
465                         return (int) 0;
466                 }
467                 return false;
468         }
469 }}
470
471 // called from db initialisation if db is dead.
472
473 if(! function_exists('system_unavailable')) {
474 function system_unavailable() {
475         include('system_unavailable.php');
476         system_down();
477         killme();
478 }}
479
480
481
482 function clean_urls() {
483         global $a;
484 //      if($a->config['system']['clean_urls'])
485                 return true;
486 //      return false;
487 }
488
489 function z_path() {
490         global $a;
491         $base = $a->get_baseurl();
492         if(! clean_urls())
493                 $base .= '/?q=';
494         return $base;
495 }
496
497 function z_root() {
498         global $a;
499         return $a->get_baseurl();
500 }
501
502 function absurl($path) {
503         if(strpos($path,'/') === 0)
504                 return z_path() . $path;
505         return $path;
506 }
507
508
509 // Primarily involved with database upgrade, but also sets the 
510 // base url for use in cmdline programs which don't have
511 // $_SERVER variables, and synchronising the state of installed plugins.
512
513
514 if(! function_exists('check_config')) {
515 function check_config(&$a) {
516
517         $build = get_config('system','build');
518         if(! x($build))
519                 $build = set_config('system','build',DB_UPDATE_VERSION);
520
521         $url = get_config('system','url');
522
523         // if the url isn't set or the stored url is radically different 
524         // than the currently visited url, store the current value accordingly.
525         // "Radically different" ignores common variations such as http vs https 
526         // and www.example.com vs example.com.
527
528         if((! x($url)) || (! link_compare($url,$a->get_baseurl())))
529                 $url = set_config('system','url',$a->get_baseurl());
530
531         if($build != DB_UPDATE_VERSION) {
532                 $stored = intval($build);
533                 $current = intval(DB_UPDATE_VERSION);
534                 if(($stored < $current) && file_exists('update.php')) {
535
536                         // We're reporting a different version than what is currently installed.
537                         // Run any existing update scripts to bring the database up to current.
538
539                         require_once('update.php');
540
541                         // make sure that boot.php and update.php are the same release, we might be
542                         // updating right this very second and the correct version of the update.php
543                         // file may not be here yet. This can happen on a very busy site.
544
545                         if(DB_UPDATE_VERSION == UPDATE_VERSION) {
546
547                                 for($x = $stored; $x < $current; $x ++) {
548                                         if(function_exists('update_' . $x)) {
549                                                 $func = 'update_' . $x;
550                                                 $func($a);
551                                         }
552                                 }
553                                 set_config('system','build', DB_UPDATE_VERSION);
554                         }
555                 }
556         }
557
558         /**
559          *
560          * Synchronise plugins:
561          *
562          * $a->config['system']['addon'] contains a comma-separated list of names
563          * of plugins/addons which are used on this system. 
564          * Go through the database list of already installed addons, and if we have
565          * an entry, but it isn't in the config list, call the uninstall procedure
566          * and mark it uninstalled in the database (for now we'll remove it).
567          * Then go through the config list and if we have a plugin that isn't installed,
568          * call the install procedure and add it to the database.
569          *
570          */
571
572         $r = q("SELECT * FROM `addon` WHERE `installed` = 1");
573         if(count($r))
574                 $installed = $r;
575         else
576                 $installed = array();
577
578         $plugins = get_config('system','addon');
579         $plugins_arr = array();
580
581         if($plugins)
582                 $plugins_arr = explode(',',str_replace(' ', '',$plugins));
583
584         $a->plugins = $plugins_arr;
585
586         $installed_arr = array();
587
588         if(count($installed)) {
589                 foreach($installed as $i) {
590                         if(! in_array($i['name'],$plugins_arr)) {
591                                 uninstall_plugin($i['name']);
592                         }
593                         else
594                                 $installed_arr[] = $i['name'];
595                 }
596         }
597
598         if(count($plugins_arr)) {
599                 foreach($plugins_arr as $p) {
600                         if(! in_array($p,$installed_arr)) {
601                                 install_plugin($p);
602                         }
603                 }
604         }
605
606
607         load_hooks();
608
609         return;
610 }}
611
612
613 function get_guid($size=16) {
614         $exists = true; // assume by default that we don't have a unique guid
615         do {
616                 $s = random_string($size);
617                 $r = q("select id from guid where guid = '%s' limit 1", dbesc($s));
618                 if(! count($r))
619                         $exists = false;
620         } while($exists);
621         q("insert into guid ( guid ) values ( '%s' ) ", dbesc($s));
622         return $s;
623 }
624
625
626 // wrapper for adding a login box. If $register == true provide a registration
627 // link. This will most always depend on the value of $a->config['register_policy'].
628 // returns the complete html for inserting into the page
629
630 if(! function_exists('login')) {
631 function login($register = false) {
632         $o = "";
633         $register_tpl = (($register) ? get_markup_template("register-link.tpl") : "");
634         
635         $register_html = replace_macros($register_tpl,array(
636                 '$title' => t('Create a New Account'),
637                 '$desc' => t('Register')
638         ));
639
640         $noid = get_config('system','no_openid');
641         if($noid) {
642                 $classname = 'no-openid';
643                 $namelabel = t('Nickname or Email address: ');
644                 $passlabel = t('Password: ');
645                 $login     = t('Login');
646         }
647         else {
648                 $classname = 'openid';
649                 $namelabel = t('Nickname/Email/OpenID: ');
650                 $passlabel = t("Password \x28if not OpenID\x29: ");
651                 $login     = t('Login');
652         }
653         $lostpass = t('Forgot your password?');
654         $lostlink = t('Password Reset');
655
656         if(local_user()) {
657                 $tpl = get_markup_template("logout.tpl");
658         }
659         else {
660                 $tpl = get_markup_template("login.tpl");
661
662         }
663
664         $o = '<script type="text/javascript"> $(document).ready(function() { $("#login-name").focus();} );</script>';   
665
666         $o .= replace_macros($tpl,array(
667                 '$logout'        => t('Logout'),
668                 '$register_html' => $register_html, 
669                 '$classname'     => $classname,
670                 '$namelabel'     => $namelabel,
671                 '$passlabel'     => $passlabel,
672                 '$login'         => $login,
673                 '$lostpass'      => $lostpass,
674                 '$lostlink'      => $lostlink 
675         ));
676
677         return $o;
678 }}
679
680 // Used to end the current process, after saving session state. 
681
682 if(! function_exists('killme')) {
683 function killme() {
684         session_write_close();
685         exit;
686 }}
687
688 // redirect to another URL and terminate this process.
689
690 if(! function_exists('goaway')) {
691 function goaway($s) {
692         header("Location: $s");
693         killme();
694 }}
695
696
697 // Returns the uid of locally logged in user or false.
698
699 if(! function_exists('local_user')) {
700 function local_user() {
701         if((x($_SESSION,'authenticated')) && (x($_SESSION,'uid')))
702                 return intval($_SESSION['uid']);
703         return false;
704 }}
705
706 // Returns contact id of authenticated site visitor or false
707
708 if(! function_exists('remote_user')) {
709 function remote_user() {
710         if((x($_SESSION,'authenticated')) && (x($_SESSION,'visitor_id')))
711                 return intval($_SESSION['visitor_id']);
712         return false;
713 }}
714
715 // contents of $s are displayed prominently on the page the next time
716 // a page is loaded. Usually used for errors or alerts.
717
718 if(! function_exists('notice')) {
719 function notice($s) {
720         $a = get_app();
721         if($a->interactive)
722                 $_SESSION['sysmsg'] .= $s;
723 }}
724 if(! function_exists('info')) {
725 function info($s) {
726         $a = get_app();
727         if($a->interactive)
728                 $_SESSION['sysmsg_info'] .= $s;
729 }}
730
731
732 // wrapper around config to limit the text length of an incoming message
733
734 if(! function_exists('get_max_import_size')) {
735 function get_max_import_size() {
736         global $a;
737         return ((x($a->config,'max_import_size')) ? $a->config['max_import_size'] : 0 );
738 }}
739
740
741
742 /**
743  *
744  * Function : profile_load
745  * @parameter App    $a
746  * @parameter string $nickname
747  * @parameter int    $profile
748  *
749  * Summary: Loads a profile into the page sidebar. 
750  * The function requires a writeable copy of the main App structure, and the nickname
751  * of a registered local account.
752  *
753  * If the viewer is an authenticated remote viewer, the profile displayed is the
754  * one that has been configured for his/her viewing in the Contact manager.
755  * Passing a non-zero profile ID can also allow a preview of a selected profile
756  * by the owner.
757  *
758  * Profile information is placed in the App structure for later retrieval.
759  * Honours the owner's chosen theme for display. 
760  *
761  */
762
763 if(! function_exists('profile_load')) {
764 function profile_load(&$a, $nickname, $profile = 0) {
765         if(remote_user()) {
766                 $r = q("SELECT `profile-id` FROM `contact` WHERE `id` = %d LIMIT 1",
767                         intval($_SESSION['visitor_id']));
768                 if(count($r))
769                         $profile = $r[0]['profile-id'];
770         } 
771
772         $r = null;
773
774         if($profile) {
775                 $profile_int = intval($profile);
776                 $r = q("SELECT `profile`.`uid` AS `profile_uid`, `profile`.* , `user`.* FROM `profile` 
777                         LEFT JOIN `user` ON `profile`.`uid` = `user`.`uid`
778                         WHERE `user`.`nickname` = '%s' AND `profile`.`id` = %d LIMIT 1",
779                         dbesc($nickname),
780                         intval($profile_int)
781                 );
782         }
783         if(! count($r)) {       
784                 $r = q("SELECT `profile`.`uid` AS `profile_uid`, `profile`.* , `user`.* FROM `profile` 
785                         LEFT JOIN `user` ON `profile`.`uid` = `user`.`uid`
786                         WHERE `user`.`nickname` = '%s' AND `profile`.`is-default` = 1 LIMIT 1",
787                         dbesc($nickname)
788                 );
789         }
790
791         if(($r === false) || (! count($r))) {
792                 notice( t('No profile') . EOL );
793                 $a->error = 404;
794                 return;
795         }
796
797         $a->profile = $r[0];
798
799
800         $a->page['title'] = $a->profile['name'] . " @ " . $a->config['sitename'];
801         $_SESSION['theme'] = $a->profile['theme'];
802
803         if(! (x($a->page,'aside')))
804                 $a->page['aside'] = '';
805
806         $block = (((get_config('system','block_public')) && (! local_user()) && (! remote_user())) ? true : false);
807
808         $a->page['aside'] .= profile_sidebar($a->profile, $block);
809
810         if(! $block)
811                 $a->page['aside'] .= contact_block();
812
813         return;
814 }}
815
816
817 /**
818  *
819  * Function: profile_sidebar
820  *
821  * Formats a profile for display in the sidebar.
822  * It is very difficult to templatise the HTML completely
823  * because of all the conditional logic.
824  *
825  * @parameter: array $profile
826  *
827  * Returns HTML string stuitable for sidebar inclusion
828  * Exceptions: Returns empty string if passed $profile is wrong type or not populated
829  *
830  */
831
832
833 if(! function_exists('profile_sidebar')) {
834 function profile_sidebar($profile, $block = 0) {
835
836         $a = get_app();
837
838         $o = '';
839         $location = '';
840         $address = false;
841
842         if((! is_array($profile)) && (! count($profile)))
843                 return $o;
844
845         call_hooks('profile_sidebar_enter', $profile);
846
847         $fullname = '<div class="fn">' . $profile['name'] . '</div>';
848
849         $pdesc = '<div class="title">' . $profile['pdesc'] . '</div>';
850
851         $tabs = '';
852
853         $photo = '<div id="profile-photo-wrapper"><img class="photo" width="175" height="175" src="' . $profile['photo'] . '" alt="' . $profile['name'] . '" /></div>';
854
855         // don't show connect link to yourself
856         $connect = (($profile['uid'] != local_user()) ? '<li><a id="dfrn-request-link" href="dfrn_request/' . $profile['nickname'] . '">' . t('Connect') . '</a></li>' : '');
857
858         // don't show connect link to authenticated visitors either
859
860         if((remote_user()) && ($_SESSION['visitor_visiting'] == $profile['uid']))
861                 $connect = ''; 
862
863         if((x($profile,'address') == 1) 
864                 || (x($profile,'locality') == 1) 
865                 || (x($profile,'region') == 1) 
866                 || (x($profile,'postal-code') == 1) 
867                 || (x($profile,'country-name') == 1))
868                 $address = true;
869
870         if($address) {
871                 $location .= '<div class="location"><span class="location-label">' . t('Location:') . '</span> <div class="adr">';
872                 $location .= ((x($profile,'address') == 1) ? '<div class="street-address">' . $profile['address'] . '</div>' : '');
873                 $location .= (((x($profile,'locality') == 1) || (x($profile,'region') == 1) || (x($profile,'postal-code') == 1)) 
874                         ? '<span class="city-state-zip"><span class="locality">' . $profile['locality'] . '</span>' 
875                         . ((x($profile['locality']) == 1) ? t(', ') : '') 
876                         . '<span class="region">' . $profile['region'] . '</span>'
877                         . ' <span class="postal-code">' . $profile['postal-code'] . '</span></span>' : '');
878                 $location .= ((x($profile,'country-name') == 1) ? ' <span class="country-name">' . $profile['country-name'] . '</span>' : '');  
879                 $location .= '</div></div><div class="profile-clear"></div>';
880
881         }
882
883
884         $gender = ((x($profile,'gender') == 1) ? '<div class="mf"><span class="gender-label">' . t('Gender:') . '</span> <span class="x-gender">' . $profile['gender'] . '</span></div><div class="profile-clear"></div>' : '');
885
886         $pubkey = ((x($profile,'pubkey') == 1) ? '<div class="key" style="display:none;">' . $profile['pubkey'] . '</div>' : '');
887
888         $marital = ((x($profile,'marital') == 1) ? '<div class="marital"><span class="marital-label"><span class="heart">&hearts;</span> ' . t('Status:') . ' </span><span class="marital-text">' . $profile['marital'] . '</span></div><div class="profile-clear"></div>' : '');
889
890         $homepage = ((x($profile,'homepage') == 1) ? '<div class="homepage"><span class="homepage-label">' . t('Homepage:') . ' </span><span class="homepage-url">' . linkify($profile['homepage']) . '</span></div><div class="profile-clear"></div>' : '');
891
892         if(($profile['hidewall'] || $block) && (! local_user()) && (! remote_user())) {
893                 $location = $pdesc = $connect = $gender = $marital = $homepage = '';
894         }
895
896         $podloc = $a->get_baseurl();
897         $searchable = (($profile['publish'] && $profile['net-publish']) ? 'true' : 'false' );
898         $nickname = $profile['nickname'];
899         $photo300 = $a->get_baseurl() . '/photo/custom/300/' . $profile['uid'] . '.jpg';
900         $photo100 = $a->get_baseurl() . '/photo/custom/100/' . $profile['uid'] . '.jpg';
901         $photo50  = $a->get_baseurl() . '/photo/custom/50/'  . $profile['uid'] . '.jpg';
902
903         $diaspora_vcard = <<< EOT
904
905 <div style="display:none;">
906 <dl class='entity_nickname'>
907 <dt>Nickname</dt>
908 <dd>
909 <a class="nickname url uid" href="$podloc/" rel="me">$nickname</a>
910 </dd>
911 </dl>
912 <dl class='entity_fn'>
913 <dt>Full name</dt>
914 <dd>
915 <span class='fn'>$fullname</span>
916 </dd>
917 </dl>
918 <dl class="entity_url">
919 <dt>URL</dt>
920 <dd>
921 <a class="url" href="$podloc/" id="pod_location" rel="me">$podloc/</a>
922 </dd>
923 </dl>
924 <dl class="entity_photo">
925 <dt>Photo</dt>
926 <dd>
927 <img class="photo avatar" height="300px" width="300px" src="$photo300">
928 </dd>
929 </dl>
930 <dl class="entity_photo_medium">
931 <dt>Photo</dt>
932 <dd> 
933 <img class="photo avatar" height="100px" width="100px" src="$photo100">
934 </dd>
935 </dl>
936 <dl class="entity_photo_small">
937 <dt>Photo</dt>
938 <dd>
939 <img class="photo avatar" height="50px" width="50px" src="$photo50">
940 </dd>
941 </dl>
942 <dl class="entity_searchable">
943 <dt>Searchable</dt>
944 <dd>
945 <span class="searchable">$searchable</span>
946 </dd>
947 </dl>
948 </div>
949 EOT;
950
951         $tpl = get_markup_template('profile_vcard.tpl');
952
953         $o .= replace_macros($tpl, array(
954                 '$fullname' => $fullname,
955                 '$pdesc'    => $pdesc,
956                 '$tabs'     => $tabs,
957                 '$photo'    => $photo,
958                 '$connect'  => $connect,                
959                 '$location' => $location,
960                 '$gender'   => $gender,
961                 '$pubkey'   => $pubkey,
962                 '$marital'  => $marital,
963                 '$homepage' => $homepage,
964                 '$diaspora' => $diaspora_vcard
965         ));
966
967
968         $arr = array('profile' => &$profile, 'entry' => &$o);
969
970         call_hooks('profile_sidebar', $arr);
971
972         return $o;
973 }}
974
975
976 if(! function_exists('get_birthdays')) {
977 function get_birthdays() {
978
979         $a = get_app();
980         $o = '';
981
982         if(! local_user())
983                 return $o;
984
985         $bd_format = t('g A l F d') ; // 8 AM Friday January 18
986
987         $r = q("SELECT `event`.*, `event`.`id` AS `eid`, `contact`.* FROM `event` 
988                 LEFT JOIN `contact` ON `contact`.`id` = `event`.`cid` 
989                 WHERE `event`.`uid` = %d AND `type` = 'birthday' AND `start` < '%s' AND `finish` > '%s' 
990                 ORDER BY `start` DESC ",
991                 intval(local_user()),
992                 dbesc(datetime_convert('UTC','UTC','now + 6 days')),
993                 dbesc(datetime_convert('UTC','UTC','now'))
994         );
995
996         if($r && count($r)) {
997                 $total = 0;
998                 foreach($r as $rr)
999                         if(strlen($rr['name']))
1000                                 $total ++;
1001
1002                 if($total) {
1003                         $o .= '<div id="birthday-notice" class="birthday-notice fakelink" onclick=openClose(\'birthday-wrapper\'); >' . t('Birthday Reminders') . ' ' . '(' . $total . ')' . '</div>'; 
1004                         $o .= '<div id="birthday-wrapper" style="display: none;" ><div id="birthday-title">' . t('Birthdays this week:') . '</div>'; 
1005                         $o .= '<div id="birthday-adjust">' . t("\x28Adjusted for local time\x29") . '</div>';
1006                         $o .= '<div id="birthday-title-end"></div>';
1007
1008                         foreach($r as $rr) {
1009                                 if(! strlen($rr['name']))
1010                                         continue;
1011                                 $now = strtotime('now');
1012                                 $today = (((strtotime($rr['start'] . ' +00:00') < $now) && (strtotime($rr['finish'] . ' +00:00') > $now)) ? true : false); 
1013         
1014                                 $o .= '<div class="birthday-list" id="birthday-' . $rr['eid'] . '"><a class="sparkle" href="' 
1015                                 . $a->get_baseurl() . '/redir/'  . $rr['cid'] . '">' . $rr['name'] . '</a> ' 
1016                                 . day_translate(datetime_convert('UTC', $a->timezone, $rr['start'], $bd_format)) . (($today) ?  ' ' . t('[today]') : '')
1017                                 . '</div>' ;
1018                         }
1019                         $o .= '</div></div>';
1020                 }
1021         }
1022         return $o;
1023 }}
1024
1025
1026 /**
1027  * 
1028  * Wrap calls to proc_close(proc_open()) and call hook
1029  * so plugins can take part in process :)
1030  * 
1031  * args:
1032  * $cmd program to run
1033  *  next args are passed as $cmd command line
1034  * 
1035  * e.g.: proc_run("ls","-la","/tmp");
1036  * 
1037  * $cmd and string args are surrounded with ""
1038  */
1039
1040 if(! function_exists('proc_run')) {
1041 function proc_run($cmd){
1042
1043         $a = get_app();
1044
1045         $args = func_get_args();
1046         $arr = array('args' => $args, 'run_cmd' => true);
1047
1048         call_hooks("proc_run", $arr);
1049         if(! $arr['run_cmd'])
1050                 return;
1051
1052         if(count($args) && $args[0] === 'php')
1053         $args[0] = ((x($a->config,'php_path')) && (strlen($a->config['php_path'])) ? $a->config['php_path'] : 'php');
1054         foreach ($args as $arg){
1055                 $arg = escapeshellarg($arg);
1056         }
1057         $cmdline = implode($args," ");
1058         proc_close(proc_open($cmdline." &",array(),$foo));
1059 }}
1060
1061 if(! function_exists('current_theme')) {
1062 function current_theme(){
1063         $app_base_themes = array('duepuntozero', 'loozah');
1064         
1065         $a = get_app();
1066         
1067         $system_theme = ((isset($a->config['system']['theme'])) ? $a->config['system']['theme'] : '');
1068         $theme_name = ((is_array($_SESSION) && x($_SESSION,'theme')) ? $_SESSION['theme'] : $system_theme);
1069         
1070         if($theme_name && file_exists('view/theme/' . $theme_name . '/style.css'))
1071                 return($theme_name);
1072         
1073         foreach($app_base_themes as $t) {
1074                 if(file_exists('view/theme/' . $t . '/style.css'))
1075                         return($t);
1076         }
1077         
1078         $fallback = glob('view/theme/*/style.css');
1079         if(count($fallback))
1080                 return (str_replace('view/theme/','', str_replace("/style.css","",$fallback[0])));
1081
1082 }}
1083
1084 /*
1085 * Return full URL to theme which is currently in effect.
1086 * Provide a sane default if nothing is chosen or the specified theme does not exist.
1087 */
1088 if(! function_exists('current_theme_url')) {
1089 function current_theme_url() {
1090         global $a;
1091         $t = current_theme();
1092         return($a->get_baseurl() . '/view/theme/' . $t . '/style.css');
1093 }}
1094
1095 if(! function_exists('feed_birthday')) {
1096 function feed_birthday($uid,$tz) {
1097
1098         /**
1099          *
1100          * Determine the next birthday, but only if the birthday is published
1101          * in the default profile. We _could_ also look for a private profile that the
1102          * recipient can see, but somebody could get mad at us if they start getting
1103          * public birthday greetings when they haven't made this info public. 
1104          *
1105          * Assuming we are able to publish this info, we are then going to convert
1106          * the start time from the owner's timezone to UTC. 
1107          *
1108          * This will potentially solve the problem found with some social networks
1109          * where birthdays are converted to the viewer's timezone and salutations from
1110          * elsewhere in the world show up on the wrong day. We will convert it to the
1111          * viewer's timezone also, but first we are going to convert it from the birthday
1112          * person's timezone to GMT - so the viewer may find the birthday starting at
1113          * 6:00PM the day before, but that will correspond to midnight to the birthday person.
1114          *
1115          */
1116
1117         $birthday = '';
1118
1119         $p = q("SELECT `dob` FROM `profile` WHERE `is-default` = 1 AND `uid` = %d LIMIT 1",
1120                 intval($uid)
1121         );
1122
1123         if($p && count($p)) {
1124                 $tmp_dob = substr($p[0]['dob'],5);
1125                 if(intval($tmp_dob)) {
1126                         $y = datetime_convert($tz,$tz,'now','Y');
1127                         $bd = $y . '-' . $tmp_dob . ' 00:00';
1128                         $t_dob = strtotime($bd);
1129                         $now = strtotime(datetime_convert($tz,$tz,'now'));
1130                         if($t_dob < $now)
1131                                 $bd = $y + 1 . '-' . $tmp_dob . ' 00:00';
1132                         $birthday = datetime_convert($tz,'UTC',$bd,ATOM_TIME); 
1133                 }
1134         }
1135
1136         return $birthday;
1137 }}
1138
1139 if(! function_exists('is_site_admin')) {
1140 function is_site_admin() {
1141         $a = get_app();
1142         if(local_user() && x($a->user,'email') && x($a->config,'admin_email') && ($a->user['email'] === $a->config['admin_email']))
1143                 return true;
1144         return false;
1145 }}
1146
1147
1148 if(! function_exists('load_contact_links')) {
1149 function load_contact_links($uid) {
1150
1151         $a = get_app();
1152
1153         $ret = array();
1154
1155         if(! $uid || x($a->contacts,'empty'))
1156                 return;
1157
1158         $r = q("SELECT `id`,`network`,`url`,`thumb` FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 ",
1159                         intval($uid)
1160         );
1161         if(count($r)) {
1162                 foreach($r as $rr){
1163                         $url = normalise_link($rr['url']);
1164                         $ret[$url] = $rr;
1165                 }
1166         }
1167         else 
1168                 $ret['empty'] = true;   
1169         $a->contacts = $ret;
1170         return;         
1171 }}