]> git.mxchange.org Git - friendica.git/blob - boot.php
Merge branch 'pull'
[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.1097' );
11 define ( 'DFRN_PROTOCOL_VERSION',  '2.21'    );
12 define ( 'DB_UPDATE_VERSION',      1087      );
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         call_hooks('login_hook',$o);
678
679         return $o;
680 }}
681
682 // Used to end the current process, after saving session state. 
683
684 if(! function_exists('killme')) {
685 function killme() {
686         session_write_close();
687         exit;
688 }}
689
690 // redirect to another URL and terminate this process.
691
692 if(! function_exists('goaway')) {
693 function goaway($s) {
694         header("Location: $s");
695         killme();
696 }}
697
698
699 // Returns the uid of locally logged in user or false.
700
701 if(! function_exists('local_user')) {
702 function local_user() {
703         if((x($_SESSION,'authenticated')) && (x($_SESSION,'uid')))
704                 return intval($_SESSION['uid']);
705         return false;
706 }}
707
708 // Returns contact id of authenticated site visitor or false
709
710 if(! function_exists('remote_user')) {
711 function remote_user() {
712         if((x($_SESSION,'authenticated')) && (x($_SESSION,'visitor_id')))
713                 return intval($_SESSION['visitor_id']);
714         return false;
715 }}
716
717 // contents of $s are displayed prominently on the page the next time
718 // a page is loaded. Usually used for errors or alerts.
719
720 if(! function_exists('notice')) {
721 function notice($s) {
722         $a = get_app();
723         if($a->interactive)
724                 $_SESSION['sysmsg'] .= $s;
725 }}
726 if(! function_exists('info')) {
727 function info($s) {
728         $a = get_app();
729         if($a->interactive)
730                 $_SESSION['sysmsg_info'] .= $s;
731 }}
732
733
734 // wrapper around config to limit the text length of an incoming message
735
736 if(! function_exists('get_max_import_size')) {
737 function get_max_import_size() {
738         global $a;
739         return ((x($a->config,'max_import_size')) ? $a->config['max_import_size'] : 0 );
740 }}
741
742
743
744 /**
745  *
746  * Function : profile_load
747  * @parameter App    $a
748  * @parameter string $nickname
749  * @parameter int    $profile
750  *
751  * Summary: Loads a profile into the page sidebar. 
752  * The function requires a writeable copy of the main App structure, and the nickname
753  * of a registered local account.
754  *
755  * If the viewer is an authenticated remote viewer, the profile displayed is the
756  * one that has been configured for his/her viewing in the Contact manager.
757  * Passing a non-zero profile ID can also allow a preview of a selected profile
758  * by the owner.
759  *
760  * Profile information is placed in the App structure for later retrieval.
761  * Honours the owner's chosen theme for display. 
762  *
763  */
764
765 if(! function_exists('profile_load')) {
766 function profile_load(&$a, $nickname, $profile = 0) {
767         if(remote_user()) {
768                 $r = q("SELECT `profile-id` FROM `contact` WHERE `id` = %d LIMIT 1",
769                         intval($_SESSION['visitor_id']));
770                 if(count($r))
771                         $profile = $r[0]['profile-id'];
772         } 
773
774         $r = null;
775
776         if($profile) {
777                 $profile_int = intval($profile);
778                 $r = q("SELECT `profile`.`uid` AS `profile_uid`, `profile`.* , `user`.* FROM `profile` 
779                         LEFT JOIN `user` ON `profile`.`uid` = `user`.`uid`
780                         WHERE `user`.`nickname` = '%s' AND `profile`.`id` = %d LIMIT 1",
781                         dbesc($nickname),
782                         intval($profile_int)
783                 );
784         }
785         if(! count($r)) {       
786                 $r = q("SELECT `profile`.`uid` AS `profile_uid`, `profile`.* , `user`.* FROM `profile` 
787                         LEFT JOIN `user` ON `profile`.`uid` = `user`.`uid`
788                         WHERE `user`.`nickname` = '%s' AND `profile`.`is-default` = 1 LIMIT 1",
789                         dbesc($nickname)
790                 );
791         }
792
793         if(($r === false) || (! count($r))) {
794                 notice( t('No profile') . EOL );
795                 $a->error = 404;
796                 return;
797         }
798
799         $a->profile = $r[0];
800
801
802         $a->page['title'] = $a->profile['name'] . " @ " . $a->config['sitename'];
803         $_SESSION['theme'] = $a->profile['theme'];
804
805         if(! (x($a->page,'aside')))
806                 $a->page['aside'] = '';
807
808         $block = (((get_config('system','block_public')) && (! local_user()) && (! remote_user())) ? true : false);
809
810         $a->page['aside'] .= profile_sidebar($a->profile, $block);
811
812         if(! $block)
813                 $a->page['aside'] .= contact_block();
814
815         return;
816 }}
817
818
819 /**
820  *
821  * Function: profile_sidebar
822  *
823  * Formats a profile for display in the sidebar.
824  * It is very difficult to templatise the HTML completely
825  * because of all the conditional logic.
826  *
827  * @parameter: array $profile
828  *
829  * Returns HTML string stuitable for sidebar inclusion
830  * Exceptions: Returns empty string if passed $profile is wrong type or not populated
831  *
832  */
833
834
835 if(! function_exists('profile_sidebar')) {
836 function profile_sidebar($profile, $block = 0) {
837
838         $a = get_app();
839
840         $o = '';
841         $location = '';
842         $address = false;
843
844         if((! is_array($profile)) && (! count($profile)))
845                 return $o;
846
847         call_hooks('profile_sidebar_enter', $profile);
848
849         $fullname = '<div class="fn">' . $profile['name'] . '</div>';
850
851         $pdesc = '<div class="title">' . $profile['pdesc'] . '</div>';
852
853         $tabs = '';
854
855         $photo = '<div id="profile-photo-wrapper"><img class="photo" width="175" height="175" src="' . $profile['photo'] . '" alt="' . $profile['name'] . '" /></div>';
856
857         // don't show connect link to yourself
858         $connect = (($profile['uid'] != local_user()) ? '<li><a id="dfrn-request-link" href="dfrn_request/' . $profile['nickname'] . '">' . t('Connect') . '</a></li>' : '');
859
860         // don't show connect link to authenticated visitors either
861
862         if((remote_user()) && ($_SESSION['visitor_visiting'] == $profile['uid']))
863                 $connect = ''; 
864
865         if((x($profile,'address') == 1) 
866                 || (x($profile,'locality') == 1) 
867                 || (x($profile,'region') == 1) 
868                 || (x($profile,'postal-code') == 1) 
869                 || (x($profile,'country-name') == 1))
870                 $address = true;
871
872         if($address) {
873                 $location .= '<div class="location"><span class="location-label">' . t('Location:') . '</span> <div class="adr">';
874                 $location .= ((x($profile,'address') == 1) ? '<div class="street-address">' . $profile['address'] . '</div>' : '');
875                 $location .= (((x($profile,'locality') == 1) || (x($profile,'region') == 1) || (x($profile,'postal-code') == 1)) 
876                         ? '<span class="city-state-zip"><span class="locality">' . $profile['locality'] . '</span>' 
877                         . ((x($profile['locality']) == 1) ? t(', ') : '') 
878                         . '<span class="region">' . $profile['region'] . '</span>'
879                         . ' <span class="postal-code">' . $profile['postal-code'] . '</span></span>' : '');
880                 $location .= ((x($profile,'country-name') == 1) ? ' <span class="country-name">' . $profile['country-name'] . '</span>' : '');  
881                 $location .= '</div></div><div class="profile-clear"></div>';
882
883         }
884
885
886         $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>' : '');
887
888         $pubkey = ((x($profile,'pubkey') == 1) ? '<div class="key" style="display:none;">' . $profile['pubkey'] . '</div>' : '');
889
890         $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>' : '');
891
892         $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>' : '');
893
894         if(($profile['hidewall'] || $block) && (! local_user()) && (! remote_user())) {
895                 $location = $pdesc = $connect = $gender = $marital = $homepage = '';
896         }
897
898         $podloc = $a->get_baseurl();
899         $searchable = (($profile['publish'] && $profile['net-publish']) ? 'true' : 'false' );
900         $nickname = $profile['nickname'];
901         $photo300 = $a->get_baseurl() . '/photo/custom/300/' . $profile['uid'] . '.jpg';
902         $photo100 = $a->get_baseurl() . '/photo/custom/100/' . $profile['uid'] . '.jpg';
903         $photo50  = $a->get_baseurl() . '/photo/custom/50/'  . $profile['uid'] . '.jpg';
904
905         $diaspora_vcard = <<< EOT
906
907 <div style="display:none;">
908 <dl class='entity_nickname'>
909 <dt>Nickname</dt>
910 <dd>
911 <a class="nickname url uid" href="$podloc/" rel="me">$nickname</a>
912 </dd>
913 </dl>
914 <dl class='entity_fn'>
915 <dt>Full name</dt>
916 <dd>
917 <span class='fn'>$fullname</span>
918 </dd>
919 </dl>
920 <dl class="entity_url">
921 <dt>URL</dt>
922 <dd>
923 <a class="url" href="$podloc/" id="pod_location" rel="me">$podloc/</a>
924 </dd>
925 </dl>
926 <dl class="entity_photo">
927 <dt>Photo</dt>
928 <dd>
929 <img class="photo avatar" height="300px" width="300px" src="$photo300">
930 </dd>
931 </dl>
932 <dl class="entity_photo_medium">
933 <dt>Photo</dt>
934 <dd> 
935 <img class="photo avatar" height="100px" width="100px" src="$photo100">
936 </dd>
937 </dl>
938 <dl class="entity_photo_small">
939 <dt>Photo</dt>
940 <dd>
941 <img class="photo avatar" height="50px" width="50px" src="$photo50">
942 </dd>
943 </dl>
944 <dl class="entity_searchable">
945 <dt>Searchable</dt>
946 <dd>
947 <span class="searchable">$searchable</span>
948 </dd>
949 </dl>
950 </div>
951 EOT;
952
953         $tpl = get_markup_template('profile_vcard.tpl');
954
955         $o .= replace_macros($tpl, array(
956                 '$fullname' => $fullname,
957                 '$pdesc'    => $pdesc,
958                 '$tabs'     => $tabs,
959                 '$photo'    => $photo,
960                 '$connect'  => $connect,                
961                 '$location' => $location,
962                 '$gender'   => $gender,
963                 '$pubkey'   => $pubkey,
964                 '$marital'  => $marital,
965                 '$homepage' => $homepage,
966                 '$diaspora' => $diaspora_vcard
967         ));
968
969
970         $arr = array('profile' => &$profile, 'entry' => &$o);
971
972         call_hooks('profile_sidebar', $arr);
973
974         return $o;
975 }}
976
977
978 if(! function_exists('get_birthdays')) {
979 function get_birthdays() {
980
981         $a = get_app();
982         $o = '';
983
984         if(! local_user())
985                 return $o;
986
987         $bd_format = t('g A l F d') ; // 8 AM Friday January 18
988
989         $r = q("SELECT `event`.*, `event`.`id` AS `eid`, `contact`.* FROM `event` 
990                 LEFT JOIN `contact` ON `contact`.`id` = `event`.`cid` 
991                 WHERE `event`.`uid` = %d AND `type` = 'birthday' AND `start` < '%s' AND `finish` > '%s' 
992                 ORDER BY `start` DESC ",
993                 intval(local_user()),
994                 dbesc(datetime_convert('UTC','UTC','now + 6 days')),
995                 dbesc(datetime_convert('UTC','UTC','now'))
996         );
997
998         if($r && count($r)) {
999                 $total = 0;
1000                 foreach($r as $rr)
1001                         if(strlen($rr['name']))
1002                                 $total ++;
1003
1004                 if($total) {
1005                         $o .= '<div id="birthday-notice" class="birthday-notice fakelink" onclick=openClose(\'birthday-wrapper\'); >' . t('Birthday Reminders') . ' ' . '(' . $total . ')' . '</div>'; 
1006                         $o .= '<div id="birthday-wrapper" style="display: none;" ><div id="birthday-title">' . t('Birthdays this week:') . '</div>'; 
1007                         $o .= '<div id="birthday-adjust">' . t("\x28Adjusted for local time\x29") . '</div>';
1008                         $o .= '<div id="birthday-title-end"></div>';
1009
1010                         foreach($r as $rr) {
1011                                 if(! strlen($rr['name']))
1012                                         continue;
1013                                 $now = strtotime('now');
1014                                 $today = (((strtotime($rr['start'] . ' +00:00') < $now) && (strtotime($rr['finish'] . ' +00:00') > $now)) ? true : false); 
1015         
1016                                 $o .= '<div class="birthday-list" id="birthday-' . $rr['eid'] . '"><a class="sparkle" href="' 
1017                                 . $a->get_baseurl() . '/redir/'  . $rr['cid'] . '">' . $rr['name'] . '</a> ' 
1018                                 . day_translate(datetime_convert('UTC', $a->timezone, $rr['start'], $bd_format)) . (($today) ?  ' ' . t('[today]') : '')
1019                                 . '</div>' ;
1020                         }
1021                         $o .= '</div></div>';
1022                 }
1023         }
1024         return $o;
1025 }}
1026
1027
1028 /**
1029  * 
1030  * Wrap calls to proc_close(proc_open()) and call hook
1031  * so plugins can take part in process :)
1032  * 
1033  * args:
1034  * $cmd program to run
1035  *  next args are passed as $cmd command line
1036  * 
1037  * e.g.: proc_run("ls","-la","/tmp");
1038  * 
1039  * $cmd and string args are surrounded with ""
1040  */
1041
1042 if(! function_exists('proc_run')) {
1043 function proc_run($cmd){
1044
1045         $a = get_app();
1046
1047         $args = func_get_args();
1048         $arr = array('args' => $args, 'run_cmd' => true);
1049
1050         call_hooks("proc_run", $arr);
1051         if(! $arr['run_cmd'])
1052                 return;
1053
1054         if(count($args) && $args[0] === 'php')
1055         $args[0] = ((x($a->config,'php_path')) && (strlen($a->config['php_path'])) ? $a->config['php_path'] : 'php');
1056         foreach ($args as $arg){
1057                 $arg = escapeshellarg($arg);
1058         }
1059         $cmdline = implode($args," ");
1060         proc_close(proc_open($cmdline." &",array(),$foo));
1061 }}
1062
1063 if(! function_exists('current_theme')) {
1064 function current_theme(){
1065         $app_base_themes = array('duepuntozero', 'loozah');
1066         
1067         $a = get_app();
1068         
1069         $system_theme = ((isset($a->config['system']['theme'])) ? $a->config['system']['theme'] : '');
1070         $theme_name = ((is_array($_SESSION) && x($_SESSION,'theme')) ? $_SESSION['theme'] : $system_theme);
1071         
1072         if($theme_name && file_exists('view/theme/' . $theme_name . '/style.css'))
1073                 return($theme_name);
1074         
1075         foreach($app_base_themes as $t) {
1076                 if(file_exists('view/theme/' . $t . '/style.css'))
1077                         return($t);
1078         }
1079         
1080         $fallback = glob('view/theme/*/style.css');
1081         if(count($fallback))
1082                 return (str_replace('view/theme/','', str_replace("/style.css","",$fallback[0])));
1083
1084 }}
1085
1086 /*
1087 * Return full URL to theme which is currently in effect.
1088 * Provide a sane default if nothing is chosen or the specified theme does not exist.
1089 */
1090 if(! function_exists('current_theme_url')) {
1091 function current_theme_url() {
1092         global $a;
1093         $t = current_theme();
1094         return($a->get_baseurl() . '/view/theme/' . $t . '/style.css');
1095 }}
1096
1097 if(! function_exists('feed_birthday')) {
1098 function feed_birthday($uid,$tz) {
1099
1100         /**
1101          *
1102          * Determine the next birthday, but only if the birthday is published
1103          * in the default profile. We _could_ also look for a private profile that the
1104          * recipient can see, but somebody could get mad at us if they start getting
1105          * public birthday greetings when they haven't made this info public. 
1106          *
1107          * Assuming we are able to publish this info, we are then going to convert
1108          * the start time from the owner's timezone to UTC. 
1109          *
1110          * This will potentially solve the problem found with some social networks
1111          * where birthdays are converted to the viewer's timezone and salutations from
1112          * elsewhere in the world show up on the wrong day. We will convert it to the
1113          * viewer's timezone also, but first we are going to convert it from the birthday
1114          * person's timezone to GMT - so the viewer may find the birthday starting at
1115          * 6:00PM the day before, but that will correspond to midnight to the birthday person.
1116          *
1117          */
1118
1119         $birthday = '';
1120
1121         $p = q("SELECT `dob` FROM `profile` WHERE `is-default` = 1 AND `uid` = %d LIMIT 1",
1122                 intval($uid)
1123         );
1124
1125         if($p && count($p)) {
1126                 $tmp_dob = substr($p[0]['dob'],5);
1127                 if(intval($tmp_dob)) {
1128                         $y = datetime_convert($tz,$tz,'now','Y');
1129                         $bd = $y . '-' . $tmp_dob . ' 00:00';
1130                         $t_dob = strtotime($bd);
1131                         $now = strtotime(datetime_convert($tz,$tz,'now'));
1132                         if($t_dob < $now)
1133                                 $bd = $y + 1 . '-' . $tmp_dob . ' 00:00';
1134                         $birthday = datetime_convert($tz,'UTC',$bd,ATOM_TIME); 
1135                 }
1136         }
1137
1138         return $birthday;
1139 }}
1140
1141 if(! function_exists('is_site_admin')) {
1142 function is_site_admin() {
1143         $a = get_app();
1144         if(local_user() && x($a->user,'email') && x($a->config,'admin_email') && ($a->user['email'] === $a->config['admin_email']))
1145                 return true;
1146         return false;
1147 }}
1148
1149
1150 if(! function_exists('load_contact_links')) {
1151 function load_contact_links($uid) {
1152
1153         $a = get_app();
1154
1155         $ret = array();
1156
1157         if(! $uid || x($a->contacts,'empty'))
1158                 return;
1159
1160         $r = q("SELECT `id`,`network`,`url`,`thumb` FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 ",
1161                         intval($uid)
1162         );
1163         if(count($r)) {
1164                 foreach($r as $rr){
1165                         $url = normalise_link($rr['url']);
1166                         $ret[$url] = $rr;
1167                 }
1168         }
1169         else 
1170                 $ret['empty'] = true;   
1171         $a->contacts = $ret;
1172         return;         
1173 }}