]> git.mxchange.org Git - friendica.git/blob - boot.php
Merge pull request #834 from tobiasd/issue775
[friendica.git] / boot.php
1 <?php
2
3 require_once('include/config.php');
4 require_once('include/network.php');
5 require_once('include/plugin.php');
6 require_once('include/text.php');
7 require_once('include/datetime.php');
8 require_once('include/pgettext.php');
9 require_once('include/nav.php');
10 require_once('include/cache.php');
11 require_once('library/Mobile_Detect/Mobile_Detect.php');
12 require_once('include/features.php');
13
14 define ( 'FRIENDICA_PLATFORM',     'Friendica');
15 define ( 'FRIENDICA_VERSION',      '3.2.1745' );
16 define ( 'DFRN_PROTOCOL_VERSION',  '2.23'    );
17 define ( 'DB_UPDATE_VERSION',      1165      );
18 define ( 'EOL',                    "<br />\r\n"     );
19 define ( 'ATOM_TIME',              'Y-m-d\TH:i:s\Z' );
20
21
22 /**
23  *
24  * Image storage quality. Lower numbers save space at cost of image detail.
25  * For ease of upgrade, please do not change here. Change jpeg quality with
26  * $a->config['system']['jpeg_quality'] = n;
27  * in .htconfig.php, where n is netween 1 and 100, and with very poor results
28  * below about 50
29  *
30  */
31
32 define ( 'JPEG_QUALITY',            100  );
33 /**
34  * $a->config['system']['png_quality'] from 0 (uncompressed) to 9
35  */
36 define ( 'PNG_QUALITY',             8  );
37
38 /**
39  *
40  * An alternate way of limiting picture upload sizes. Specify the maximum pixel
41  * length that pictures are allowed to be (for non-square pictures, it will apply
42  * to the longest side). Pictures longer than this length will be resized to be
43  * this length (on the longest side, the other side will be scaled appropriately).
44  * Modify this value using
45  *
46  *    $a->config['system']['max_image_length'] = n;
47  *
48  * in .htconfig.php
49  *
50  * If you don't want to set a maximum length, set to -1. The default value is
51  * defined by 'MAX_IMAGE_LENGTH' below.
52  *
53  */
54 define ( 'MAX_IMAGE_LENGTH',        -1  );
55
56
57 /**
58  * Not yet used
59  */
60
61 define ( 'DEFAULT_DB_ENGINE',  'MyISAM'  );
62
63 /**
64  * SSL redirection policies
65  */
66
67 define ( 'SSL_POLICY_NONE',         0 );
68 define ( 'SSL_POLICY_FULL',         1 );
69 define ( 'SSL_POLICY_SELFSIGN',     2 );
70
71
72 /**
73  * log levels
74  */
75
76 define ( 'LOGGER_NORMAL',          0 );
77 define ( 'LOGGER_TRACE',           1 );
78 define ( 'LOGGER_DEBUG',           2 );
79 define ( 'LOGGER_DATA',            3 );
80 define ( 'LOGGER_ALL',             4 );
81
82 /**
83  * registration policies
84  */
85
86 define ( 'REGISTER_CLOSED',        0 );
87 define ( 'REGISTER_APPROVE',       1 );
88 define ( 'REGISTER_OPEN',          2 );
89
90 /**
91  * relationship types
92  */
93
94 define ( 'CONTACT_IS_FOLLOWER', 1);
95 define ( 'CONTACT_IS_SHARING',  2);
96 define ( 'CONTACT_IS_FRIEND',   3);
97
98
99 /**
100  * DB update return values
101  */
102
103 define ( 'UPDATE_SUCCESS', 0);
104 define ( 'UPDATE_FAILED',  1);
105
106
107 /**
108  *
109  * page/profile types
110  *
111  * PAGE_NORMAL is a typical personal profile account
112  * PAGE_SOAPBOX automatically approves all friend requests as CONTACT_IS_SHARING, (readonly)
113  * PAGE_COMMUNITY automatically approves all friend requests as CONTACT_IS_SHARING, but with
114  *      write access to wall and comments (no email and not included in page owner's ACL lists)
115  * PAGE_FREELOVE automatically approves all friend requests as full friends (CONTACT_IS_FRIEND).
116  *
117  */
118
119 define ( 'PAGE_NORMAL',            0 );
120 define ( 'PAGE_SOAPBOX',           1 );
121 define ( 'PAGE_COMMUNITY',         2 );
122 define ( 'PAGE_FREELOVE',          3 );
123 define ( 'PAGE_BLOG',              4 );
124 define ( 'PAGE_PRVGROUP',          5 );
125
126 /**
127  * Network and protocol family types
128  */
129
130 define ( 'NETWORK_DFRN',             'dfrn');    // Friendica, Mistpark, other DFRN implementations
131 define ( 'NETWORK_ZOT',              'zot!');    // Zot!
132 define ( 'NETWORK_OSTATUS',          'stat');    // status.net, identi.ca, GNU-social, other OStatus implementations
133 define ( 'NETWORK_FEED',             'feed');    // RSS/Atom feeds with no known "post/notify" protocol
134 define ( 'NETWORK_DIASPORA',         'dspr');    // Diaspora
135 define ( 'NETWORK_MAIL',             'mail');    // IMAP/POP
136 define ( 'NETWORK_MAIL2',            'mai2');    // extended IMAP/POP
137 define ( 'NETWORK_FACEBOOK',         'face');    // Facebook API
138 define ( 'NETWORK_LINKEDIN',         'lnkd');    // LinkedIn
139 define ( 'NETWORK_XMPP',             'xmpp');    // XMPP
140 define ( 'NETWORK_MYSPACE',          'mysp');    // MySpace
141 define ( 'NETWORK_GPLUS',            'goog');    // Google+
142 define ( 'NETWORK_PUMPIO',           'pump');    // pump.io
143 define ( 'NETWORK_TWITTER',          'twit');    // Twitter
144
145 define ( 'NETWORK_PHANTOM',          'unkn');    // Place holder
146
147 /**
148  * These numbers are used in stored permissions
149  * and existing allocations MUST NEVER BE CHANGED
150  * OR RE-ASSIGNED! You may only add to them.
151  */
152
153 $netgroup_ids = array(
154         NETWORK_DFRN     => (-1),
155         NETWORK_ZOT      => (-2),
156         NETWORK_OSTATUS  => (-3),
157         NETWORK_FEED     => (-4),
158         NETWORK_DIASPORA => (-5),
159         NETWORK_MAIL     => (-6),
160         NETWORK_MAIL2    => (-7),
161         NETWORK_FACEBOOK => (-8),
162         NETWORK_LINKEDIN => (-9),
163         NETWORK_XMPP     => (-10),
164         NETWORK_MYSPACE  => (-11),
165         NETWORK_GPLUS    => (-12),
166         NETWORK_PUMPIO   => (-13),
167         NETWORK_TWITTER  => (-14),
168
169         NETWORK_PHANTOM  => (-127),
170 );
171
172
173 /**
174  * Maximum number of "people who like (or don't like) this"  that we will list by name
175  */
176
177 define ( 'MAX_LIKERS',    75);
178
179 /**
180  * Communication timeout
181  */
182
183 define ( 'ZCURL_TIMEOUT' , (-1));
184
185
186 /**
187  * email notification options
188  */
189
190 define ( 'NOTIFY_INTRO',    0x0001 );
191 define ( 'NOTIFY_CONFIRM',  0x0002 );
192 define ( 'NOTIFY_WALL',     0x0004 );
193 define ( 'NOTIFY_COMMENT',  0x0008 );
194 define ( 'NOTIFY_MAIL',     0x0010 );
195 define ( 'NOTIFY_SUGGEST',  0x0020 );
196 define ( 'NOTIFY_PROFILE',  0x0040 );
197 define ( 'NOTIFY_TAGSELF',  0x0080 );
198 define ( 'NOTIFY_TAGSHARE', 0x0100 );
199 define ( 'NOTIFY_POKE',     0x0200 );
200
201 define ( 'NOTIFY_SYSTEM',   0x8000 );
202
203
204 /**
205  * Tag/term types
206  */
207
208 define ( 'TERM_UNKNOWN',   0 );
209 define ( 'TERM_HASHTAG',   1 );
210 define ( 'TERM_MENTION',   2 );
211 define ( 'TERM_CATEGORY',  3 );
212 define ( 'TERM_PCATEGORY', 4 );
213 define ( 'TERM_FILE',      5 );
214 define ( 'TERM_SAVEDSEARCH', 6 );
215 define ( 'TERM_CONVERSATION', 7 );
216
217 define ( 'TERM_OBJ_POST',  1 );
218 define ( 'TERM_OBJ_PHOTO', 2 );
219
220
221
222 /**
223  * various namespaces we may need to parse
224  */
225
226 define ( 'NAMESPACE_ZOT',             'http://purl.org/zot' );
227 define ( 'NAMESPACE_DFRN' ,           'http://purl.org/macgirvin/dfrn/1.0' );
228 define ( 'NAMESPACE_THREAD' ,         'http://purl.org/syndication/thread/1.0' );
229 define ( 'NAMESPACE_TOMB' ,           'http://purl.org/atompub/tombstones/1.0' );
230 define ( 'NAMESPACE_ACTIVITY',        'http://activitystrea.ms/spec/1.0/' );
231 define ( 'NAMESPACE_ACTIVITY_SCHEMA', 'http://activitystrea.ms/schema/1.0/' );
232 define ( 'NAMESPACE_MEDIA',           'http://purl.org/syndication/atommedia' );
233 define ( 'NAMESPACE_SALMON_ME',       'http://salmon-protocol.org/ns/magic-env' );
234 define ( 'NAMESPACE_OSTATUSSUB',      'http://ostatus.org/schema/1.0/subscribe' );
235 define ( 'NAMESPACE_GEORSS',          'http://www.georss.org/georss' );
236 define ( 'NAMESPACE_POCO',            'http://portablecontacts.net/spec/1.0' );
237 define ( 'NAMESPACE_FEED',            'http://schemas.google.com/g/2010#updates-from' );
238 define ( 'NAMESPACE_OSTATUS',         'http://ostatus.org/schema/1.0' );
239 define ( 'NAMESPACE_STATUSNET',       'http://status.net/schema/api/1/' );
240 define ( 'NAMESPACE_ATOM1',           'http://www.w3.org/2005/Atom' );
241 /**
242  * activity stream defines
243  */
244
245 define ( 'ACTIVITY_LIKE',        NAMESPACE_ACTIVITY_SCHEMA . 'like' );
246 define ( 'ACTIVITY_DISLIKE',     NAMESPACE_DFRN            . '/dislike' );
247 define ( 'ACTIVITY_OBJ_HEART',   NAMESPACE_DFRN            . '/heart' );
248
249 define ( 'ACTIVITY_FRIEND',      NAMESPACE_ACTIVITY_SCHEMA . 'make-friend' );
250 define ( 'ACTIVITY_REQ_FRIEND',  NAMESPACE_ACTIVITY_SCHEMA . 'request-friend' );
251 define ( 'ACTIVITY_UNFRIEND',    NAMESPACE_ACTIVITY_SCHEMA . 'remove-friend' );
252 define ( 'ACTIVITY_FOLLOW',      NAMESPACE_ACTIVITY_SCHEMA . 'follow' );
253 define ( 'ACTIVITY_UNFOLLOW',    NAMESPACE_ACTIVITY_SCHEMA . 'stop-following' );
254 define ( 'ACTIVITY_JOIN',        NAMESPACE_ACTIVITY_SCHEMA . 'join' );
255
256 define ( 'ACTIVITY_POST',        NAMESPACE_ACTIVITY_SCHEMA . 'post' );
257 define ( 'ACTIVITY_UPDATE',      NAMESPACE_ACTIVITY_SCHEMA . 'update' );
258 define ( 'ACTIVITY_TAG',         NAMESPACE_ACTIVITY_SCHEMA . 'tag' );
259 define ( 'ACTIVITY_FAVORITE',    NAMESPACE_ACTIVITY_SCHEMA . 'favorite' );
260
261 define ( 'ACTIVITY_POKE',        NAMESPACE_ZOT . '/activity/poke' );
262 define ( 'ACTIVITY_MOOD',        NAMESPACE_ZOT . '/activity/mood' );
263
264 define ( 'ACTIVITY_OBJ_COMMENT', NAMESPACE_ACTIVITY_SCHEMA . 'comment' );
265 define ( 'ACTIVITY_OBJ_NOTE',    NAMESPACE_ACTIVITY_SCHEMA . 'note' );
266 define ( 'ACTIVITY_OBJ_PERSON',  NAMESPACE_ACTIVITY_SCHEMA . 'person' );
267 define ( 'ACTIVITY_OBJ_PHOTO',   NAMESPACE_ACTIVITY_SCHEMA . 'photo' );
268 define ( 'ACTIVITY_OBJ_P_PHOTO', NAMESPACE_ACTIVITY_SCHEMA . 'profile-photo' );
269 define ( 'ACTIVITY_OBJ_ALBUM',   NAMESPACE_ACTIVITY_SCHEMA . 'photo-album' );
270 define ( 'ACTIVITY_OBJ_EVENT',   NAMESPACE_ACTIVITY_SCHEMA . 'event' );
271 define ( 'ACTIVITY_OBJ_GROUP',   NAMESPACE_ACTIVITY_SCHEMA . 'group' );
272 define ( 'ACTIVITY_OBJ_TAGTERM', NAMESPACE_DFRN            . '/tagterm' );
273 define ( 'ACTIVITY_OBJ_PROFILE', NAMESPACE_DFRN            . '/profile' );
274
275 /**
276  * item weight for query ordering
277  */
278
279 define ( 'GRAVITY_PARENT',       0);
280 define ( 'GRAVITY_LIKE',         3);
281 define ( 'GRAVITY_COMMENT',      6);
282
283 /**
284  *
285  * Reverse the effect of magic_quotes_gpc if it is enabled.
286  * Please disable magic_quotes_gpc so we don't have to do this.
287  * See http://php.net/manual/en/security.magicquotes.disabling.php
288  *
289  */
290
291 function startup() {
292
293         error_reporting(E_ERROR | E_WARNING | E_PARSE);
294
295         set_time_limit(0);
296
297         // This has to be quite large to deal with embedded private photos
298         ini_set('pcre.backtrack_limit', 500000);
299
300
301         if (get_magic_quotes_gpc()) {
302                 $process = array(&$_GET, &$_POST, &$_COOKIE, &$_REQUEST);
303                 while (list($key, $val) = each($process)) {
304                         foreach ($val as $k => $v) {
305                                 unset($process[$key][$k]);
306                                 if (is_array($v)) {
307                                         $process[$key][stripslashes($k)] = $v;
308                                         $process[] = &$process[$key][stripslashes($k)];
309                                 } else {
310                                         $process[$key][stripslashes($k)] = stripslashes($v);
311                                 }
312                         }
313                 }
314                 unset($process);
315         }
316
317 }
318
319 /**
320  *
321  * class: App
322  *
323  * Our main application structure for the life of this page
324  * Primarily deals with the URL that got us here
325  * and tries to make some sense of it, and
326  * stores our page contents and config storage
327  * and anything else that might need to be passed around
328  * before we spit the page out.
329  *
330  */
331
332 if(! class_exists('App')) {
333         class App {
334
335                 public  $module_loaded = false;
336                 public  $query_string;
337                 public  $config;
338                 public  $page;
339                 public  $profile;
340                 public  $user;
341                 public  $cid;
342                 public  $contact;
343                 public  $contacts;
344                 public  $page_contact;
345                 public  $content;
346                 public  $data = array();
347                 public  $error = false;
348                 public  $cmd;
349                 public  $argv;
350                 public  $argc;
351                 public  $module;
352                 public  $pager;
353                 public  $strings;
354                 public  $path;
355                 public  $hooks;
356                 public  $timezone;
357                 public  $interactive = true;
358                 public  $plugins;
359                 public  $apps = array();
360                 public  $identities;
361                 public  $is_mobile;
362                 public  $is_tablet;
363                 public  $performance = array();
364
365                 public $nav_sel;
366
367                 public $category;
368
369
370                 // Allow themes to control internal parameters
371                 // by changing App values in theme.php
372
373                 public  $sourcename = '';
374                 public  $videowidth = 425;
375                 public  $videoheight = 350;
376                 public  $force_max_items = 0;
377                 public  $theme_thread_allow = true;
378
379                 // An array for all theme-controllable parameters
380                 // Mostly unimplemented yet. Only options 'stylesheet' and
381                 // beyond are used.
382
383                 public  $theme = array(
384                         'sourcename' => '',
385                         'videowidth' => 425,
386                         'videoheight' => 350,
387                         'force_max_items' => 0,
388                         'thread_allow' => true,
389                         'stylesheet' => '',
390                         'template_engine' => 'smarty3',
391                 );
392
393                 // array of registered template engines ('name'=>'class name')
394                 public $template_engines = array();
395                 // array of instanced template engines ('name'=>'instance')
396                 public $template_engine_instance = array();
397
398                 private $ldelim = array(
399                         'internal' => '',
400                         'smarty3' => '{{'
401                 );
402                 private $rdelim = array(
403                         'internal' => '',
404                         'smarty3' => '}}'
405                 );
406
407                 private $scheme;
408                 private $hostname;
409                 private $baseurl;
410                 private $db;
411
412                 private $curl_code;
413                 private $curl_content_type;
414                 private $curl_headers;
415
416                 private $cached_profile_image;
417                 private $cached_profile_picdate;
418
419                 function __construct() {
420
421                         global $default_timezone, $argv, $argc;
422
423                         if (file_exists(".htpreconfig.php"))
424                                 @include(".htpreconfig.php");
425
426                         $this->timezone = ((x($default_timezone)) ? $default_timezone : 'UTC');
427
428                         date_default_timezone_set($this->timezone);
429
430                         $this->performance["start"] = microtime(true);
431                         $this->performance["database"] = 0;
432                         $this->performance["network"] = 0;
433                         $this->performance["file"] = 0;
434                         $this->performance["rendering"] = 0;
435                         $this->performance["parser"] = 0;
436                         $this->performance["marktime"] = 0;
437                         $this->performance["markstart"] = microtime(true);
438
439                         $this->config = array();
440                         $this->page = array();
441                         $this->pager= array();
442
443                         $this->query_string = '';
444
445                         startup();
446
447                         set_include_path(
448                                         'include' . PATH_SEPARATOR
449                                         . 'library' . PATH_SEPARATOR
450                                         . 'library/phpsec' . PATH_SEPARATOR
451                                         . 'library/langdet' . PATH_SEPARATOR
452                                         . '.' );
453
454
455                         $this->scheme = 'http';
456                         if(x($_SERVER,'HTTPS') && $_SERVER['HTTPS'])
457                                 $this->scheme = 'https';
458                         elseif(x($_SERVER,'SERVER_PORT') && (intval($_SERVER['SERVER_PORT']) == 443))
459                                 $this->scheme = 'https';
460
461                         if(x($_SERVER,'SERVER_NAME')) {
462                                 $this->hostname = $_SERVER['SERVER_NAME'];
463
464                                 // See bug 437 - this didn't work so disabling it
465                                 //if(stristr($this->hostname,'xn--')) {
466                                         // PHP or webserver may have converted idn to punycode, so
467                                         // convert punycode back to utf-8
468                                 //      require_once('library/simplepie/idn/idna_convert.class.php');
469                                 //      $x = new idna_convert();
470                                 //      $this->hostname = $x->decode($_SERVER['SERVER_NAME']);
471                                 //}
472
473                                 if(x($_SERVER,'SERVER_PORT') && $_SERVER['SERVER_PORT'] != 80 && $_SERVER['SERVER_PORT'] != 443)
474                                         $this->hostname .= ':' . $_SERVER['SERVER_PORT'];
475                                 /**
476                                  * Figure out if we are running at the top of a domain
477                                  * or in a sub-directory and adjust accordingly
478                                  */
479
480                                 $path = trim(dirname($_SERVER['SCRIPT_NAME']),'/\\');
481                                 if(isset($path) && strlen($path) && ($path != $this->path))
482                                         $this->path = $path;
483                         }
484
485                         if ($hostname != "")
486                                 $this->hostname = $hostname;
487
488                         if (is_array($argv) && $argc>1 && substr(end($argv), 0, 4)=="http" ) {
489                                 $this->set_baseurl(array_pop($argv) );
490                                 $argc --;
491                         }
492
493                         set_include_path("include/$this->hostname" . PATH_SEPARATOR . get_include_path());
494
495                         if((x($_SERVER,'QUERY_STRING')) && substr($_SERVER['QUERY_STRING'],0,2) === "q=") {
496                                 $this->query_string = substr($_SERVER['QUERY_STRING'],2);
497                                 // removing trailing / - maybe a nginx problem
498                                 if (substr($this->query_string, 0, 1) == "/")
499                                         $this->query_string = substr($this->query_string, 1);
500                         }
501                         if(x($_GET,'q'))
502                                 $this->cmd = trim($_GET['q'],'/\\');
503
504                         // unix style "homedir"
505
506                         if(substr($this->cmd,0,1) === '~')
507                                 $this->cmd = 'profile/' . substr($this->cmd,1);
508
509                         // Diaspora style profile url
510
511                         if(substr($this->cmd,0,2) === 'u/')
512                                 $this->cmd = 'profile/' . substr($this->cmd,2);
513
514                         /**
515                          *
516                          * Break the URL path into C style argc/argv style arguments for our
517                          * modules. Given "http://example.com/module/arg1/arg2", $this->argc
518                          * will be 3 (integer) and $this->argv will contain:
519                          *   [0] => 'module'
520                          *   [1] => 'arg1'
521                          *   [2] => 'arg2'
522                          *
523                          *
524                          * There will always be one argument. If provided a naked domain
525                          * URL, $this->argv[0] is set to "home".
526                          *
527                          */
528
529                         $this->argv = explode('/',$this->cmd);
530                         $this->argc = count($this->argv);
531                         if((array_key_exists('0',$this->argv)) && strlen($this->argv[0])) {
532                                 $this->module = str_replace(".", "_", $this->argv[0]);
533                                 $this->module = str_replace("-", "_", $this->module);
534                         }
535                         else {
536                                 $this->argc = 1;
537                                 $this->argv = array('home');
538                                 $this->module = 'home';
539                         }
540
541                         /**
542                          * See if there is any page number information, and initialise
543                          * pagination
544                          */
545
546                         $this->pager['page'] = ((x($_GET,'page') && intval($_GET['page']) > 0) ? intval($_GET['page']) : 1);
547                         $this->pager['itemspage'] = 50;
548                         $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
549                         if($this->pager['start'] < 0)
550                                 $this->pager['start'] = 0;
551                         $this->pager['total'] = 0;
552
553                         /**
554                          * Detect mobile devices
555                          */
556
557                         $mobile_detect = new Mobile_Detect();
558                         $this->is_mobile = $mobile_detect->isMobile();
559                         $this->is_tablet = $mobile_detect->isTablet();
560
561                         /**
562                          * register template engines
563                          */
564                         $dc = get_declared_classes();
565                         foreach ($dc as $k) {
566                                 if (in_array("ITemplateEngine", class_implements($k))){
567                                         $this->register_template_engine($k);
568                                 }
569                         }
570
571                 }
572
573                 function get_basepath() {
574
575                         $basepath = get_config("system", "basepath");
576
577                         if ($basepath == "")
578                                 $basepath = $_SERVER["DOCUMENT_ROOT"];
579
580                         if ($basepath == "")
581                                 $basepath = $_SERVER["PWD"];
582
583                         return($basepath);
584                 }
585
586                 function get_baseurl($ssl = false) {
587
588                         $scheme = $this->scheme;
589
590                         if((x($this->config,'system')) && (x($this->config['system'],'ssl_policy'))) {
591                                 if(intval($this->config['system']['ssl_policy']) === intval(SSL_POLICY_FULL))
592                                         $scheme = 'https';
593
594                                 //      Basically, we have $ssl = true on any links which can only be seen by a logged in user
595                                 //      (and also the login link). Anything seen by an outsider will have it turned off.
596
597                                 if($this->config['system']['ssl_policy'] == SSL_POLICY_SELFSIGN) {
598                                         if($ssl)
599                                                 $scheme = 'https';
600                                         else
601                                                 $scheme = 'http';
602                                 }
603                         }
604
605                         $this->baseurl = $scheme . "://" . $this->hostname . ((isset($this->path) && strlen($this->path)) ? '/' . $this->path : '' );
606                         return $this->baseurl;
607                 }
608
609                 function set_baseurl($url) {
610                         $parsed = @parse_url($url);
611
612                         $this->baseurl = $url;
613
614                         if($parsed) {
615                                 $this->scheme = $parsed['scheme'];
616
617                                 $this->hostname = $parsed['host'];
618                                 if(x($parsed,'port'))
619                                         $this->hostname .= ':' . $parsed['port'];
620                                 if(x($parsed,'path'))
621                                         $this->path = trim($parsed['path'],'\\/');
622                         }
623
624                 }
625
626                 function get_hostname() {
627                         return $this->hostname;
628                 }
629
630                 function set_hostname($h) {
631                         $this->hostname = $h;
632                 }
633
634                 function set_path($p) {
635                         $this->path = trim(trim($p),'/');
636                 }
637
638                 function get_path() {
639                         return $this->path;
640                 }
641
642                 function set_pager_total($n) {
643                         $this->pager['total'] = intval($n);
644                 }
645
646                 function set_pager_itemspage($n) {
647                         $this->pager['itemspage'] = ((intval($n) > 0) ? intval($n) : 0);
648                         $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
649                 }
650
651                 function set_pager_page($n) {
652                         $this->pager['page'] = $n;
653                         $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
654                 }
655
656                 function init_pagehead() {
657                         $interval = ((local_user()) ? get_pconfig(local_user(),'system','update_interval') : 40000);
658                         if($interval < 10000)
659                                 $interval = 40000;
660
661                         $this->page['title'] = $this->config['sitename'];
662
663                         /* put the head template at the beginning of page['htmlhead']
664                          * since the code added by the modules frequently depends on it
665                          * being first
666                          */
667                         if(!isset($this->page['htmlhead']))
668                                 $this->page['htmlhead'] = '';
669
670                         // If we're using Smarty, then doing replace_macros() will replace
671                         // any unrecognized variables with a blank string. Since we delay
672                         // replacing $stylesheet until later, we need to replace it now
673                         // with another variable name
674                         if($this->theme['template_engine'] === 'smarty3')
675                                 $stylesheet = $this->get_template_ldelim('smarty3') . '$stylesheet' . $this->get_template_rdelim('smarty3');
676                         else
677                                 $stylesheet = '$stylesheet';
678
679                         $tpl = get_markup_template('head.tpl');
680                         $this->page['htmlhead'] = replace_macros($tpl,array(
681                                 '$baseurl' => $this->get_baseurl(), // FIXME for z_path!!!!
682                                 '$local_user' => local_user(),
683                                 '$generator' => 'Friendica' . ' ' . FRIENDICA_VERSION,
684                                 '$delitem' => t('Delete this item?'),
685                                 '$comment' => t('Comment'),
686                                 '$showmore' => t('show more'),
687                                 '$showfewer' => t('show fewer'),
688                                 '$update_interval' => $interval,
689                                 '$stylesheet' => $stylesheet
690                         )) . $this->page['htmlhead'];
691                 }
692
693                 function init_page_end() {
694                         if(!isset($this->page['end']))
695                                 $this->page['end'] = '';
696                         $tpl = get_markup_template('end.tpl');
697                         $this->page['end'] = replace_macros($tpl,array(
698                                 '$baseurl' => $this->get_baseurl() // FIXME for z_path!!!!
699                         )) . $this->page['end'];
700                 }
701
702                 function set_curl_code($code) {
703                         $this->curl_code = $code;
704                 }
705
706                 function get_curl_code() {
707                         return $this->curl_code;
708                 }
709
710                 function set_curl_content_type($content_type) {
711                         $this->curl_content_type = $content_type;
712                 }
713
714                 function get_curl_content_type() {
715                         return $this->curl_content_type;
716                 }
717
718                 function set_curl_headers($headers) {
719                         $this->curl_headers = $headers;
720                 }
721
722                 function get_curl_headers() {
723                         return $this->curl_headers;
724                 }
725
726                 function get_cached_avatar_image($avatar_image){
727                         if($this->cached_profile_image[$avatar_image])
728                                 return $this->cached_profile_image[$avatar_image];
729
730                         $path_parts = explode("/",$avatar_image);
731                         $common_filename = $path_parts[count($path_parts)-1];
732
733                         if($this->cached_profile_picdate[$common_filename]){
734                                 $this->cached_profile_image[$avatar_image] = $avatar_image . $this->cached_profile_picdate[$common_filename];
735                         } else {
736                                 $r = q("SELECT `contact`.`avatar-date` AS picdate FROM `contact` WHERE `contact`.`thumb` like \"%%/%s\"",
737                                         $common_filename);
738                                 if(! count($r)){
739                                         $this->cached_profile_image[$avatar_image] = $avatar_image;
740                                 } else {
741                                         $this->cached_profile_picdate[$common_filename] = "?rev=" . urlencode($r[0]['picdate']);
742                                         $this->cached_profile_image[$avatar_image] = $avatar_image . $this->cached_profile_picdate[$common_filename];
743                                 }
744                         }
745                         return $this->cached_profile_image[$avatar_image];
746                 }
747
748
749                 /**
750                  * register template engine class
751                  * if $name is "", is used class static property $class::$name
752                  * @param string $class
753                  * @param string $name
754                  */
755                 function register_template_engine($class, $name = '') {
756                         if ($name===""){
757                                 $v = get_class_vars( $class );
758                                 if(x($v,"name")) $name = $v['name'];
759                         }
760                         if ($name===""){
761                                 echo "template engine <tt>$class</tt> cannot be registered without a name.\n";
762                                 killme(); 
763                         }
764                         $this->template_engines[$name] = $class;
765                 }
766
767                 /**
768                  * return template engine instance. If $name is not defined,
769                  * return engine defined by theme, or default
770                  * 
771                  * @param strin $name Template engine name
772                  * @return object Template Engine instance
773                  */
774                 function template_engine($name = ''){
775                         if ($name!=="") {
776                                 $template_engine = $name;
777                         } else {
778                                 $template_engine = 'smarty3';
779                                 if (x($this->theme, 'template_engine')) {
780                                         $template_engine = $this->theme['template_engine'];
781                                 }
782                         }
783
784                         if (isset($this->template_engines[$template_engine])){
785                                 if(isset($this->template_engine_instance[$template_engine])){
786                                         return $this->template_engine_instance[$template_engine];
787                                 } else {
788                                         $class = $this->template_engines[$template_engine];
789                                         $obj = new $class;
790                                         $this->template_engine_instance[$template_engine] = $obj;
791                                         return $obj;
792                                 }
793                         }
794
795                         echo "template engine <tt>$template_engine</tt> is not registered!\n"; killme();
796                 }
797
798                 function get_template_engine() {
799                         return $this->theme['template_engine'];
800                 }
801
802                 function set_template_engine($engine = 'smarty3') {
803                         $this->theme['template_engine'] = $engine;
804                         /*
805                         $this->theme['template_engine'] = 'smarty3';
806
807                         switch($engine) {
808                                 case 'smarty3':
809                                         if(is_writable('view/smarty3/'))
810                                                 $this->theme['template_engine'] = 'smarty3';
811                                         break;
812                                 default:
813                                         break;
814                         }
815                         */
816                 }
817
818                 function get_template_ldelim($engine = 'smarty3') {
819                         return $this->ldelim[$engine];
820                 }
821
822                 function get_template_rdelim($engine = 'smarty3') {
823                         return $this->rdelim[$engine];
824                 }
825
826                 function save_timestamp($stamp, $value) {
827                         $duration = (float)(microtime(true)-$stamp);
828
829                         $this->performance[$value] += (float)$duration;
830                         $this->performance["marktime"] += (float)$duration;
831                 }
832
833                 function mark_timestamp($mark) {
834                         //$this->performance["markstart"] -= microtime(true) - $this->performance["marktime"];
835                         $this->performance["markstart"] = microtime(true) - $this->performance["markstart"] - $this->performance["marktime"];
836                 }
837
838         }
839 }
840
841 // retrieve the App structure
842 // useful in functions which require it but don't get it passed to them
843
844 if(! function_exists('get_app')) {
845         function get_app() {
846                 global $a;
847                 return $a;
848         }
849 };
850
851
852 // Multi-purpose function to check variable state.
853 // Usage: x($var) or $x($array,'key')
854 // returns false if variable/key is not set
855 // if variable is set, returns 1 if has 'non-zero' value, otherwise returns 0.
856 // e.g. x('') or x(0) returns 0;
857
858 if(! function_exists('x')) {
859         function x($s,$k = NULL) {
860                 if($k != NULL) {
861                         if((is_array($s)) && (array_key_exists($k,$s))) {
862                                 if($s[$k])
863                                         return (int) 1;
864                                 return (int) 0;
865                 }
866                         return false;
867                 }
868                 else {
869                         if(isset($s)) {
870                                 if($s) {
871                                         return (int) 1;
872                                 }
873                                 return (int) 0;
874                         }
875                         return false;
876                 }
877         }
878 }
879
880 // called from db initialisation if db is dead.
881
882 if(! function_exists('system_unavailable')) {
883         function system_unavailable() {
884                 include('system_unavailable.php');
885                 system_down();
886                 killme();
887         }
888 }
889
890
891
892 function clean_urls() {
893         global $a;
894         //      if($a->config['system']['clean_urls'])
895         return true;
896         //      return false;
897 }
898
899 function z_path() {
900         global $a;
901         $base = $a->get_baseurl();
902         if(! clean_urls())
903                 $base .= '/?q=';
904         return $base;
905 }
906
907 function z_root() {
908         global $a;
909         return $a->get_baseurl();
910 }
911
912 function absurl($path) {
913         if(strpos($path,'/') === 0)
914                 return z_path() . $path;
915         return $path;
916 }
917
918 function is_ajax() {
919         return (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');
920 }
921
922 function check_db() {
923
924         $build = get_config('system','build');
925         if(! x($build)) {
926                 set_config('system','build',DB_UPDATE_VERSION);
927                 $build = DB_UPDATE_VERSION;
928         }
929         if($build != DB_UPDATE_VERSION)
930                 proc_run('php', 'include/dbupdate.php');
931
932 }
933
934
935
936
937 // Sets the base url for use in cmdline programs which don't have
938 // $_SERVER variables
939
940 if(! function_exists('check_url')) {
941         function check_url(&$a) {
942
943                 $url = get_config('system','url');
944
945                 // if the url isn't set or the stored url is radically different
946                 // than the currently visited url, store the current value accordingly.
947                 // "Radically different" ignores common variations such as http vs https
948                 // and www.example.com vs example.com.
949                 // We will only change the url to an ip address if there is no existing setting
950
951                 if(! x($url))
952                         $url = set_config('system','url',$a->get_baseurl());
953                 if((! link_compare($url,$a->get_baseurl())) && (! preg_match("/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/",$a->get_hostname)))
954                         $url = set_config('system','url',$a->get_baseurl());
955
956                 return;
957         }
958 }
959
960
961 // Automatic database updates
962
963 if(! function_exists('update_db')) {
964         function update_db(&$a) {
965
966                 $build = get_config('system','build');
967                 if(! x($build))
968                         $build = set_config('system','build',DB_UPDATE_VERSION);
969
970                 if($build != DB_UPDATE_VERSION) {
971                         $stored = intval($build);
972                         $current = intval(DB_UPDATE_VERSION);
973                         if(($stored < $current) && file_exists('update.php')) {
974
975                                 load_config('database');
976
977                                 // We're reporting a different version than what is currently installed.
978                                 // Run any existing update scripts to bring the database up to current.
979
980                                 require_once('update.php');
981
982                                 // make sure that boot.php and update.php are the same release, we might be
983                                 // updating right this very second and the correct version of the update.php
984                                 // file may not be here yet. This can happen on a very busy site.
985
986                                 if(DB_UPDATE_VERSION == UPDATE_VERSION) {
987
988                                         for($x = $stored; $x < $current; $x ++) {
989                                                 if(function_exists('update_' . $x)) {
990
991                                                         // There could be a lot of processes running or about to run.
992                                                         // We want exactly one process to run the update command.
993                                                         // So store the fact that we're taking responsibility
994                                                         // after first checking to see if somebody else already has.
995
996                                                         // If the update fails or times-out completely you may need to
997                                                         // delete the config entry to try again.
998
999                                                         $t = get_config('database','update_' . $x);
1000                                                         if($t !== false)
1001                                                                 break;
1002                                                         set_config('database','update_' . $x, time());
1003
1004                                                         // call the specific update
1005
1006                                                         $func = 'update_' . $x;
1007                                                         $retval = $func();
1008                                                         if($retval) {
1009                                                                 //send the administrator an e-mail
1010                                                                 $email_tpl = get_intltext_template("update_fail_eml.tpl");
1011                                                                 $email_msg = replace_macros($email_tpl, array(
1012                                                                         '$sitename' => $a->config['sitename'],
1013                                                                         '$siteurl' =>  $a->get_baseurl(),
1014                                                                         '$update' => $x,
1015                                                                         '$error' => sprintf( t('Update %s failed. See error logs.'), $x)
1016                                                                 ));
1017                                                                 $subject=sprintf(t('Update Error at %s'), $a->get_baseurl());
1018                                                                 require_once('include/email.php');
1019                                                                 $subject = email_header_encode($subject,'UTF-8');
1020                                                                 mail($a->config['admin_email'], $subject, $email_msg,
1021                                                                         'From: ' . 'Administrator' . '@' . $_SERVER['SERVER_NAME'] . "\n"
1022                                                                         . 'Content-type: text/plain; charset=UTF-8' . "\n"
1023                                                                         . 'Content-transfer-encoding: 8bit' );
1024                                                                 //try the logger
1025                                                                 logger('CRITICAL: Update Failed: '. $x);
1026                                                                 break;
1027                                                         }
1028                                                         else {
1029                                                                 set_config('database','update_' . $x, 'success');
1030                                                                 set_config('system','build', $x + 1);
1031                                                         }
1032                                                 }
1033                                         }
1034                                 }
1035                         }
1036                 }
1037
1038                 return;
1039         }
1040 }
1041
1042
1043 if(! function_exists('check_plugins')) {
1044         function check_plugins(&$a) {
1045
1046                 /**
1047                  *
1048                  * Synchronise plugins:
1049                  *
1050                  * $a->config['system']['addon'] contains a comma-separated list of names
1051                  * of plugins/addons which are used on this system.
1052                  * Go through the database list of already installed addons, and if we have
1053                  * an entry, but it isn't in the config list, call the uninstall procedure
1054                  * and mark it uninstalled in the database (for now we'll remove it).
1055                  * Then go through the config list and if we have a plugin that isn't installed,
1056                  * call the install procedure and add it to the database.
1057                  *
1058                  */
1059
1060                 $r = q("SELECT * FROM `addon` WHERE `installed` = 1");
1061                 if(count($r))
1062                         $installed = $r;
1063                 else
1064                         $installed = array();
1065
1066                 $plugins = get_config('system','addon');
1067                 $plugins_arr = array();
1068
1069                 if($plugins)
1070                         $plugins_arr = explode(',',str_replace(' ', '',$plugins));
1071
1072                 $a->plugins = $plugins_arr;
1073
1074                 $installed_arr = array();
1075
1076                 if(count($installed)) {
1077                         foreach($installed as $i) {
1078                                 if(! in_array($i['name'],$plugins_arr)) {
1079                                         uninstall_plugin($i['name']);
1080                                 }
1081                                 else {
1082                                         $installed_arr[] = $i['name'];
1083                                 }
1084                         }
1085                 }
1086
1087                 if(count($plugins_arr)) {
1088                         foreach($plugins_arr as $p) {
1089                                 if(! in_array($p,$installed_arr)) {
1090                                         install_plugin($p);
1091                                 }
1092                         }
1093                 }
1094
1095
1096                 load_hooks();
1097
1098                 return;
1099         }
1100 }
1101
1102
1103 function get_guid($size=16) {
1104         $exists = true; // assume by default that we don't have a unique guid
1105         do {
1106                 $s = random_string($size);
1107                 $r = q("select id from guid where guid = '%s' limit 1", dbesc($s));
1108                 if(! count($r))
1109                         $exists = false;
1110         } while($exists);
1111         q("insert into guid ( guid ) values ( '%s' ) ", dbesc($s));
1112         return $s;
1113 }
1114
1115
1116 // wrapper for adding a login box. If $register == true provide a registration
1117 // link. This will most always depend on the value of $a->config['register_policy'].
1118 // returns the complete html for inserting into the page
1119
1120 if(! function_exists('login')) {
1121         function login($register = false, $hiddens=false) {
1122                 $a = get_app();
1123                 $o = "";
1124                 $reg = false;
1125                 if ($register) {
1126                         $reg = array(
1127                                 'title' => t('Create a New Account'),
1128                                 'desc' => t('Register')
1129                         );
1130                 }
1131
1132                 $noid = get_config('system','no_openid');
1133         
1134                 $dest_url = $a->get_baseurl(true) . '/' . $a->query_string;
1135
1136                 if(local_user()) {
1137                         $tpl = get_markup_template("logout.tpl");
1138                 }
1139                 else {
1140                         $a->page['htmlhead'] .= replace_macros(get_markup_template("login_head.tpl"),array(
1141                                 '$baseurl'              => $a->get_baseurl(true)
1142                         ));
1143
1144                         $tpl = get_markup_template("login.tpl");
1145                         $_SESSION['return_url'] = $a->query_string;
1146                         $a->module = 'login';
1147                 }
1148
1149                 $o .= replace_macros($tpl, array(
1150
1151                         '$dest_url'     => $dest_url,
1152                         '$logout'       => t('Logout'),
1153                         '$login'        => t('Login'),
1154         
1155                         '$lname'                => array('username', t('Nickname or Email address: ') , '', ''),
1156                         '$lpassword'    => array('password', t('Password: '), '', ''),
1157                         '$lremember'    => array('remember', t('Remember me'), 0,  ''),
1158         
1159                         '$openid'               => !$noid,
1160                         '$lopenid'      => array('openid_url', t('Or login using OpenID: '),'',''),
1161         
1162                         '$hiddens'      => $hiddens,
1163         
1164                         '$register'     => $reg,
1165         
1166                         '$lostpass'     => t('Forgot your password?'),
1167                         '$lostlink'     => t('Password Reset'),
1168
1169                         '$tostitle'     => t('Website Terms of Service'),
1170                         '$toslink'      => t('terms of service'),
1171
1172                         '$privacytitle' => t('Website Privacy Policy'),
1173                         '$privacylink'  => t('privacy policy'),
1174
1175                 ));
1176
1177                 call_hooks('login_hook',$o);
1178
1179                 return $o;
1180         }
1181 }
1182
1183 // Used to end the current process, after saving session state.
1184
1185 if(! function_exists('killme')) {
1186         function killme() {
1187                 session_write_close();
1188                 exit;
1189         }
1190 }
1191
1192 // redirect to another URL and terminate this process.
1193
1194 if(! function_exists('goaway')) {
1195         function goaway($s) {
1196                 header("Location: $s");
1197                 killme();
1198         }
1199 }
1200
1201
1202 // Returns the uid of locally logged in user or false.
1203
1204 if(! function_exists('local_user')) {
1205         function local_user() {
1206                 if((x($_SESSION,'authenticated')) && (x($_SESSION,'uid')))
1207                         return intval($_SESSION['uid']);
1208                 return false;
1209         }
1210 }
1211
1212 // Returns contact id of authenticated site visitor or false
1213
1214 if(! function_exists('remote_user')) {
1215         function remote_user() {
1216                 if((x($_SESSION,'authenticated')) && (x($_SESSION,'visitor_id')))
1217                         return intval($_SESSION['visitor_id']);
1218                 return false;
1219         }
1220 }
1221
1222 // contents of $s are displayed prominently on the page the next time
1223 // a page is loaded. Usually used for errors or alerts.
1224
1225 if(! function_exists('notice')) {
1226         /**
1227          * Show an error message to user.
1228          * 
1229          * This function save text in session, to be shown to the user at next page load
1230          * 
1231          * @param string $s - Text of notice
1232          */
1233         function notice($s) {
1234                 $a = get_app();
1235                 if(! x($_SESSION,'sysmsg'))     $_SESSION['sysmsg'] = array();
1236                 if($a->interactive)
1237                         $_SESSION['sysmsg'][] = $s;
1238         }
1239 }
1240 if(! function_exists('info')) {
1241         /**
1242          * Show an info message to user.
1243          * 
1244          * This function save text in session, to be shown to the user at next page load
1245          * 
1246          * @param string $s - Text of notice
1247          */
1248         function info($s) {
1249                 $a = get_app();
1250                 if(! x($_SESSION,'sysmsg_info')) $_SESSION['sysmsg_info'] = array();
1251                 if($a->interactive)
1252                         $_SESSION['sysmsg_info'][] = $s;
1253         }
1254 }
1255
1256
1257 // wrapper around config to limit the text length of an incoming message
1258
1259 if(! function_exists('get_max_import_size')) {
1260         function get_max_import_size() {
1261                 global $a;
1262                 return ((x($a->config,'max_import_size')) ? $a->config['max_import_size'] : 0 );
1263         }
1264 }
1265
1266
1267
1268 /**
1269  *
1270  * Function : profile_load
1271  * @parameter App    $a
1272  * @parameter string $nickname
1273  * @parameter int    $profile
1274  *
1275  * Summary: Loads a profile into the page sidebar.
1276  * The function requires a writeable copy of the main App structure, and the nickname
1277  * of a registered local account.
1278  *
1279  * If the viewer is an authenticated remote viewer, the profile displayed is the
1280  * one that has been configured for his/her viewing in the Contact manager.
1281  * Passing a non-zero profile ID can also allow a preview of a selected profile
1282  * by the owner.
1283  *
1284  * Profile information is placed in the App structure for later retrieval.
1285  * Honours the owner's chosen theme for display.
1286  *
1287  * IMPORTANT: Should only be run in the _init() functions of a module. That ensures that
1288  * the theme is chosen before the _init() function of a theme is run, which will usually
1289  * load a lot of theme-specific content
1290  *
1291  */
1292
1293 if(! function_exists('profile_load')) {
1294         function profile_load(&$a, $nickname, $profile = 0) {
1295
1296                 $user = q("select uid from user where nickname = '%s' limit 1",
1297                         dbesc($nickname)
1298                 );
1299
1300                 if(! ($user && count($user))) {
1301                         logger('profile error: ' . $a->query_string, LOGGER_DEBUG);
1302                         notice( t('Requested account is not available.') . EOL );
1303                         $a->error = 404;
1304                         return;
1305                 }
1306
1307                 if(remote_user() && count($_SESSION['remote'])) {
1308                         foreach($_SESSION['remote'] as $visitor) {
1309                                 if($visitor['uid'] == $user[0]['uid']) {
1310                                         $r = q("SELECT `profile-id` FROM `contact` WHERE `id` = %d LIMIT 1",
1311                                                 intval($visitor['cid'])
1312                                         );
1313                                         if(count($r))
1314                                                 $profile = $r[0]['profile-id'];
1315                                         break;
1316                                 }
1317                         }
1318                 }
1319
1320                 $r = null;
1321
1322                 if($profile) {
1323                         $profile_int = intval($profile);
1324                         $r = q("SELECT `profile`.`uid` AS `profile_uid`, `profile`.* , `contact`.`avatar-date` AS picdate, `user`.* FROM `profile`
1325                                         left join `contact` on `contact`.`uid` = `profile`.`uid` LEFT JOIN `user` ON `profile`.`uid` = `user`.`uid`
1326                                         WHERE `user`.`nickname` = '%s' AND `profile`.`id` = %d and `contact`.`self` = 1 LIMIT 1",
1327                                         dbesc($nickname),
1328                                         intval($profile_int)
1329                         );
1330                 }
1331                 if((! $r) && (!  count($r))) {
1332                         $r = q("SELECT `profile`.`uid` AS `profile_uid`, `profile`.* , `contact`.`avatar-date` AS picdate, `user`.* FROM `profile`
1333                                         left join `contact` on `contact`.`uid` = `profile`.`uid` LEFT JOIN `user` ON `profile`.`uid` = `user`.`uid`
1334                                         WHERE `user`.`nickname` = '%s' AND `profile`.`is-default` = 1 and `contact`.`self` = 1 LIMIT 1",
1335                                         dbesc($nickname)
1336                         );
1337                 }
1338
1339                 if(($r === false) || (! count($r))) {
1340                         logger('profile error: ' . $a->query_string, LOGGER_DEBUG);
1341                         notice( t('Requested profile is not available.') . EOL );
1342                         $a->error = 404;
1343                         return;
1344                 }
1345
1346                 // fetch user tags if this isn't the default profile
1347
1348                 if(! $r[0]['is-default']) {
1349                         $x = q("select `pub_keywords` from `profile` where uid = %d and `is-default` = 1 limit 1",
1350                                         intval($r[0]['profile_uid'])
1351                         );
1352                         if($x && count($x))
1353                                 $r[0]['pub_keywords'] = $x[0]['pub_keywords'];
1354                 }
1355
1356                 $a->profile = $r[0];
1357
1358                 $a->profile['mobile-theme'] = get_pconfig($a->profile['profile_uid'], 'system', 'mobile_theme');
1359
1360
1361                 $a->page['title'] = $a->profile['name'] . " @ " . $a->config['sitename'];
1362                 $_SESSION['theme'] = $a->profile['theme'];
1363                 $_SESSION['mobile-theme'] = $a->profile['mobile-theme'];
1364
1365                 /**
1366                  * load/reload current theme info
1367                  */
1368
1369                 $a->set_template_engine(); // reset the template engine to the default in case the user's theme doesn't specify one
1370
1371                 $theme_info_file = "view/theme/".current_theme()."/theme.php";
1372                 if (file_exists($theme_info_file)){
1373                         require_once($theme_info_file);
1374                 }
1375
1376                 if(! (x($a->page,'aside')))
1377                         $a->page['aside'] = '';
1378
1379                 if(local_user() && local_user() == $a->profile['uid']) {
1380                         $a->page['aside'] .= replace_macros(get_markup_template('profile_edlink.tpl'),array(
1381                                 '$editprofile' => t('Edit profile'),
1382                                 '$profid' => $a->profile['id']
1383                         ));
1384                 }
1385
1386                 $block = (((get_config('system','block_public')) && (! local_user()) && (! remote_user())) ? true : false);
1387
1388                 $a->page['aside'] .= profile_sidebar($a->profile, $block);
1389
1390                 /*if(! $block)
1391                  $a->page['aside'] .= contact_block();*/
1392
1393                 return;
1394         }
1395 }
1396
1397
1398 /**
1399  *
1400  * Function: profile_sidebar
1401  *
1402  * Formats a profile for display in the sidebar.
1403  * It is very difficult to templatise the HTML completely
1404  * because of all the conditional logic.
1405  *
1406  * @parameter: array $profile
1407  *
1408  * Returns HTML string stuitable for sidebar inclusion
1409  * Exceptions: Returns empty string if passed $profile is wrong type or not populated
1410  *
1411  */
1412
1413
1414 if(! function_exists('profile_sidebar')) {
1415         function profile_sidebar($profile, $block = 0) {
1416
1417                 $a = get_app();
1418
1419                 $o = '';
1420                 $location = false;
1421                 $address = false;
1422                 $pdesc = true;
1423
1424                 if((! is_array($profile)) && (! count($profile)))
1425                         return $o;
1426
1427                 $profile['picdate'] = urlencode($profile['picdate']);
1428
1429                 call_hooks('profile_sidebar_enter', $profile);
1430
1431         
1432                 // don't show connect link to yourself
1433                 $connect = (($profile['uid'] != local_user()) ? t('Connect')  : False);
1434
1435                 // don't show connect link to authenticated visitors either
1436
1437                 if(remote_user() && count($_SESSION['remote'])) {
1438                         foreach($_SESSION['remote'] as $visitor) {
1439                                 if($visitor['uid'] == $profile['uid']) {
1440                                         $connect = false;
1441                                         break;
1442                                 }
1443                         }
1444                 }
1445
1446                 if( get_my_url() && $profile['unkmail'] && ($profile['uid'] != local_user()) )
1447                         $wallmessage = t('Message');
1448                 else
1449                         $wallmessage = false;
1450
1451
1452
1453                 // show edit profile to yourself
1454                 if ($profile['uid'] == local_user() && feature_enabled(local_user(),'multi_profiles')) {
1455                         $profile['edit'] = array($a->get_baseurl(). '/profiles', t('Profiles'),"", t('Manage/edit profiles'));
1456                 
1457                         $r = q("SELECT * FROM `profile` WHERE `uid` = %d",
1458                                         local_user());
1459                 
1460                         $profile['menu'] = array(
1461                                 'chg_photo' => t('Change profile photo'),
1462                                 'cr_new' => t('Create New Profile'),
1463                                 'entries' => array(),
1464                         );
1465
1466                         if(count($r)) {
1467
1468                                 foreach($r as $rr) {
1469                                         $profile['menu']['entries'][] = array(
1470                                                 'photo' => $rr['thumb'],
1471                                                 'id' => $rr['id'],
1472                                                 'alt' => t('Profile Image'),
1473                                                 'profile_name' => $rr['profile-name'],
1474                                                 'isdefault' => $rr['is-default'],
1475                                                 'visibile_to_everybody' =>  t('visible to everybody'),
1476                                                 'edit_visibility' => t('Edit visibility'),
1477
1478                                         );
1479                                 }
1480
1481
1482                         }
1483                 }
1484         if ($profile['uid'] == local_user() && !feature_enabled(local_user(),'multi_profiles')) {
1485             $profile['edit'] = array($a->get_baseurl(). '/profiles/'.$profile['id'], t('Edit profile'),"", t('Edit profile'));
1486                 $profile['menu'] = array(
1487                                 'chg_photo' => t('Change profile photo'),
1488                                 'cr_new' => null,
1489                                 'entries' => array(),
1490                         );
1491         }
1492
1493
1494
1495         
1496                 if((x($profile,'address') == 1)
1497                                 || (x($profile,'locality') == 1)
1498                                 || (x($profile,'region') == 1)
1499                                 || (x($profile,'postal-code') == 1)
1500                                 || (x($profile,'country-name') == 1))
1501                         $location = t('Location:');
1502
1503                 $gender = ((x($profile,'gender') == 1) ? t('Gender:') : False);
1504
1505
1506                 $marital = ((x($profile,'marital') == 1) ?  t('Status:') : False);
1507
1508                 $homepage = ((x($profile,'homepage') == 1) ?  t('Homepage:') : False);
1509
1510                 if(($profile['hidewall'] || $block) && (! local_user()) && (! remote_user())) {
1511                         $location = $pdesc = $gender = $marital = $homepage = False;
1512                 }
1513
1514                 $firstname = ((strpos($profile['name'],' '))
1515                                 ? trim(substr($profile['name'],0,strpos($profile['name'],' '))) : $profile['name']);
1516                 $lastname = (($firstname === $profile['name']) ? '' : trim(substr($profile['name'],strlen($firstname))));
1517
1518                 $diaspora = array(
1519                         'podloc' => $a->get_baseurl(),
1520                         'searchable' => (($profile['publish'] && $profile['net-publish']) ? 'true' : 'false' ),
1521                         'nickname' => $profile['nickname'],
1522                         'fullname' => $profile['name'],
1523                         'firstname' => $firstname,
1524                         'lastname' => $lastname,
1525                         'photo300' => $a->get_cached_avatar_image($a->get_baseurl() . '/photo/custom/300/' . $profile['uid'] . '.jpg'),
1526                         'photo100' => $a->get_cached_avatar_image($a->get_baseurl() . '/photo/custom/100/' . $profile['uid'] . '.jpg'),
1527                         'photo50' => $a->get_cached_avatar_image($a->get_baseurl() . '/photo/custom/50/'  . $profile['uid'] . '.jpg'),
1528                 );
1529
1530                 if (!$block){
1531                         $contact_block = contact_block();
1532                 }
1533
1534
1535                 $p = array();
1536                 foreach($profile as $k => $v) {
1537                         $k = str_replace('-','_',$k);
1538                         $p[$k] = $v;
1539                 }
1540
1541                 if($a->theme['template_engine'] === 'internal')
1542                         $location = template_escape($location);
1543
1544
1545                 $tpl = get_markup_template('profile_vcard.tpl');
1546                 $o .= replace_macros($tpl, array(
1547                         '$profile' => $p,
1548                         '$connect'  => $connect,
1549                         '$wallmessage' => $wallmessage,
1550                         '$location' => $location,
1551                         '$gender'   => $gender,
1552                         '$pdesc'        => $pdesc,
1553                         '$marital'  => $marital,
1554                         '$homepage' => $homepage,
1555                         '$diaspora' => $diaspora,
1556                         '$contact_block' => $contact_block,
1557                 ));
1558
1559
1560                 $arr = array('profile' => &$profile, 'entry' => &$o);
1561
1562                 call_hooks('profile_sidebar', $arr);
1563
1564                 return $o;
1565         }
1566 }
1567
1568
1569 if(! function_exists('get_birthdays')) {
1570         function get_birthdays() {
1571
1572                 $a = get_app();
1573                 $o = '';
1574
1575                 if(! local_user() || $a->is_mobile || $a->is_tablet)
1576                         return $o;
1577
1578 //              $mobile_detect = new Mobile_Detect();
1579 //              $is_mobile = $mobile_detect->isMobile() || $mobile_detect->isTablet();
1580
1581 //              if($is_mobile)
1582 //                      return $o;
1583
1584                 $bd_format = t('g A l F d') ; // 8 AM Friday January 18
1585                 $bd_short = t('F d');
1586
1587                 $r = q("SELECT `event`.*, `event`.`id` AS `eid`, `contact`.* FROM `event`
1588                                 LEFT JOIN `contact` ON `contact`.`id` = `event`.`cid`
1589                                 WHERE `event`.`uid` = %d AND `type` = 'birthday' AND `start` < '%s' AND `finish` > '%s'
1590                                 ORDER BY `start` ASC ",
1591                                 intval(local_user()),
1592                                 dbesc(datetime_convert('UTC','UTC','now + 6 days')),
1593                                 dbesc(datetime_convert('UTC','UTC','now'))
1594                 );
1595
1596                 if($r && count($r)) {
1597                         $total = 0;
1598                         $now = strtotime('now');
1599                         $cids = array();
1600
1601                         $istoday = false;
1602                         foreach($r as $rr) {
1603                                 if(strlen($rr['name']))
1604                                         $total ++;
1605                                 if((strtotime($rr['start'] . ' +00:00') < $now) && (strtotime($rr['finish'] . ' +00:00') > $now))
1606                                         $istoday = true;
1607                         }
1608                         $classtoday = $istoday ? ' birthday-today ' : '';
1609                         if($total) {
1610                                 foreach($r as &$rr) {
1611                                         if(! strlen($rr['name']))
1612                                                 continue;
1613
1614                                         // avoid duplicates
1615
1616                                         if(in_array($rr['cid'],$cids))
1617                                                 continue;
1618                                         $cids[] = $rr['cid'];
1619
1620                                         $today = (((strtotime($rr['start'] . ' +00:00') < $now) && (strtotime($rr['finish'] . ' +00:00') > $now)) ? true : false);
1621                                         $sparkle = '';
1622                                         $url = $rr['url'];
1623                                         if($rr['network'] === NETWORK_DFRN) {
1624                                                 $sparkle = " sparkle";
1625                                                 $url = $a->get_baseurl() . '/redir/'  . $rr['cid'];
1626                                         }
1627         
1628                                         $rr['link'] = $url;
1629                                         $rr['title'] = $rr['name'];
1630                                         $rr['date'] = day_translate(datetime_convert('UTC', $a->timezone, $rr['start'], $rr['adjust'] ? $bd_format : $bd_short)) . (($today) ?  ' ' . t('[today]') : '');
1631                                         $rr['startime'] = Null;
1632                                         $rr['today'] = $today;
1633         
1634                                 }
1635                         }
1636                 }
1637                 $tpl = get_markup_template("birthdays_reminder.tpl");
1638                 return replace_macros($tpl, array(
1639                         '$baseurl' => $a->get_baseurl(),
1640                         '$classtoday' => $classtoday,
1641                         '$count' => $total,
1642                         '$event_reminders' => t('Birthday Reminders'),
1643                         '$event_title' => t('Birthdays this week:'),
1644                         '$events' => $r,
1645                         '$lbr' => '{',  // raw brackets mess up if/endif macro processing
1646                         '$rbr' => '}'
1647
1648                 ));
1649         }
1650 }
1651
1652
1653 if(! function_exists('get_events')) {
1654         function get_events() {
1655
1656                 require_once('include/bbcode.php');
1657
1658                 $a = get_app();
1659
1660                 if(! local_user() || $a->is_mobile || $a->is_tablet)
1661                         return $o;
1662
1663
1664 //              $mobile_detect = new Mobile_Detect();
1665 //              $is_mobile = $mobile_detect->isMobile() || $mobile_detect->isTablet();
1666
1667 //              if($is_mobile)
1668 //                      return $o;
1669
1670                 $bd_format = t('g A l F d') ; // 8 AM Friday January 18
1671                 $bd_short = t('F d');
1672
1673                 $r = q("SELECT `event`.* FROM `event`
1674                                 WHERE `event`.`uid` = %d AND `type` != 'birthday' AND `start` < '%s' AND `start` > '%s'
1675                                 ORDER BY `start` ASC ",
1676                                 intval(local_user()),
1677                                 dbesc(datetime_convert('UTC','UTC','now + 6 days')),
1678                                 dbesc(datetime_convert('UTC','UTC','now - 1 days'))
1679                 );
1680
1681                 if($r && count($r)) {
1682                         $now = strtotime('now');
1683                         $istoday = false;
1684                         foreach($r as $rr) {
1685                                 if(strlen($rr['name']))
1686                                         $total ++;
1687
1688                                 $strt = datetime_convert('UTC',$rr['convert'] ? $a->timezone : 'UTC',$rr['start'],'Y-m-d');
1689                                 if($strt === datetime_convert('UTC',$a->timezone,'now','Y-m-d'))
1690                                         $istoday = true;
1691                         }
1692                         $classtoday = (($istoday) ? 'event-today' : '');
1693
1694
1695                         foreach($r as &$rr) {
1696                                 if($rr['adjust'])
1697                                         $md = datetime_convert('UTC',$a->timezone,$rr['start'],'Y/m');
1698                                 else
1699                                         $md = datetime_convert('UTC','UTC',$rr['start'],'Y/m');
1700                                 $md .= "/#link-".$rr['id'];
1701
1702                                 $title = substr(strip_tags(bbcode($rr['desc'])),0,32) . '... ';
1703                                 if(! $title)
1704                                         $title = t('[No description]');
1705
1706                                 $strt = datetime_convert('UTC',$rr['convert'] ? $a->timezone : 'UTC',$rr['start']);
1707                                 $today = ((substr($strt,0,10) === datetime_convert('UTC',$a->timezone,'now','Y-m-d')) ? true : false);
1708                                 
1709                                 $rr['link'] = $md;
1710                                 $rr['title'] = $title;
1711                                 $rr['date'] = day_translate(datetime_convert('UTC', $rr['adjust'] ? $a->timezone : 'UTC', $rr['start'], $bd_format)) . (($today) ?  ' ' . t('[today]') : '');
1712                                 $rr['startime'] = $strt;
1713                                 $rr['today'] = $today;
1714                         }
1715                 }
1716
1717                 $tpl = get_markup_template("events_reminder.tpl");
1718                 return replace_macros($tpl, array(
1719                         '$baseurl' => $a->get_baseurl(),
1720                         '$classtoday' => $classtoday,
1721                         '$count' => count($r),
1722                         '$event_reminders' => t('Event Reminders'),
1723                         '$event_title' => t('Events this week:'),
1724                         '$events' => $r,
1725                 ));
1726         }
1727 }
1728
1729
1730 /**
1731  *
1732  * Wrap calls to proc_close(proc_open()) and call hook
1733  * so plugins can take part in process :)
1734  *
1735  * args:
1736  * $cmd program to run
1737  *  next args are passed as $cmd command line
1738  *
1739  * e.g.: proc_run("ls","-la","/tmp");
1740  *
1741  * $cmd and string args are surrounded with ""
1742  */
1743
1744 if(! function_exists('proc_run')) {
1745         function proc_run($cmd){
1746
1747                 $a = get_app();
1748
1749                 $args = func_get_args();
1750
1751                 $newargs = array();
1752                 if(! count($args))
1753                         return;
1754
1755                 // expand any arrays
1756
1757                 foreach($args as $arg) {
1758                         if(is_array($arg)) {
1759                                 foreach($arg as $n) {
1760                                         $newargs[] = $n;
1761                                 }
1762                         }
1763                         else
1764                                 $newargs[] = $arg;
1765                 }
1766
1767                 $args = $newargs;
1768                 
1769                 $arr = array('args' => $args, 'run_cmd' => true);
1770
1771                 call_hooks("proc_run", $arr);
1772                 if(! $arr['run_cmd'])
1773                         return;
1774
1775                 if(count($args) && $args[0] === 'php')
1776                         $args[0] = ((x($a->config,'php_path')) && (strlen($a->config['php_path'])) ? $a->config['php_path'] : 'php');
1777         
1778         // add baseurl to args. cli scripts can't construct it
1779         $args[] = $a->get_baseurl();
1780         
1781         for($x = 0; $x < count($args); $x ++)
1782                         $args[$x] = escapeshellarg($args[$x]);
1783
1784         
1785
1786                 $cmdline = implode($args," ");
1787                 if(get_config('system','proc_windows'))
1788                         proc_close(proc_open('cmd /c start /b ' . $cmdline,array(),$foo,dirname(__FILE__)));
1789                 else
1790                         proc_close(proc_open($cmdline." &",array(),$foo,dirname(__FILE__)));
1791         }
1792 }
1793
1794 if(! function_exists('current_theme')) {
1795         function current_theme(){
1796                 $app_base_themes = array('duepuntozero', 'dispy', 'quattro');
1797         
1798                 $a = get_app();
1799         
1800 //              $mobile_detect = new Mobile_Detect();
1801 //              $is_mobile = $mobile_detect->isMobile() || $mobile_detect->isTablet();
1802                 $is_mobile = $a->is_mobile || $a->is_tablet;
1803
1804                 if($is_mobile) {
1805                         if(isset($_SESSION['show-mobile']) && !$_SESSION['show-mobile']) {
1806                                 $system_theme = '';
1807                                 $theme_name = '';
1808                         }
1809                         else {
1810                                 $system_theme = ((isset($a->config['system']['mobile-theme'])) ? $a->config['system']['mobile-theme'] : '');
1811                                 $theme_name = ((isset($_SESSION) && x($_SESSION,'mobile-theme')) ? $_SESSION['mobile-theme'] : $system_theme);
1812
1813                                 if($theme_name === '---') {
1814                                         // user has selected to have the mobile theme be the same as the normal one
1815                                         $system_theme = '';
1816                                         $theme_name = '';
1817                                 }
1818                         }
1819                 }
1820                 if(!$is_mobile || ($system_theme === '' && $theme_name === '')) {
1821                         $system_theme = ((isset($a->config['system']['theme'])) ? $a->config['system']['theme'] : '');
1822                         $theme_name = ((isset($_SESSION) && x($_SESSION,'theme')) ? $_SESSION['theme'] : $system_theme);
1823                 }
1824
1825                 if($theme_name &&
1826                                 (file_exists('view/theme/' . $theme_name . '/style.css') ||
1827                                                 file_exists('view/theme/' . $theme_name . '/style.php')))
1828                         return($theme_name);
1829         
1830                 foreach($app_base_themes as $t) {
1831                         if(file_exists('view/theme/' . $t . '/style.css')||
1832                                         file_exists('view/theme/' . $t . '/style.php'))
1833                                 return($t);
1834                 }
1835         
1836                 $fallback = array_merge(glob('view/theme/*/style.css'),glob('view/theme/*/style.php'));
1837                 if(count($fallback))
1838                         return (str_replace('view/theme/','', substr($fallback[0],0,-10)));
1839         
1840         }
1841 }
1842
1843 /*
1844  * Return full URL to theme which is currently in effect.
1845 * Provide a sane default if nothing is chosen or the specified theme does not exist.
1846 */
1847 if(! function_exists('current_theme_url')) {
1848         function current_theme_url() {
1849                 global $a;
1850                 $t = current_theme();
1851                 if (file_exists('view/theme/' . $t . '/style.php'))
1852                         return($a->get_baseurl() . '/view/theme/' . $t . '/style.pcss');
1853                 return($a->get_baseurl() . '/view/theme/' . $t . '/style.css');
1854         }
1855 }
1856
1857 if(! function_exists('feed_birthday')) {
1858         function feed_birthday($uid,$tz) {
1859
1860                 /**
1861                  *
1862                  * Determine the next birthday, but only if the birthday is published
1863                  * in the default profile. We _could_ also look for a private profile that the
1864                  * recipient can see, but somebody could get mad at us if they start getting
1865                  * public birthday greetings when they haven't made this info public.
1866                  *
1867                  * Assuming we are able to publish this info, we are then going to convert
1868                  * the start time from the owner's timezone to UTC.
1869                  *
1870                  * This will potentially solve the problem found with some social networks
1871                  * where birthdays are converted to the viewer's timezone and salutations from
1872                  * elsewhere in the world show up on the wrong day. We will convert it to the
1873                  * viewer's timezone also, but first we are going to convert it from the birthday
1874                  * person's timezone to GMT - so the viewer may find the birthday starting at
1875                  * 6:00PM the day before, but that will correspond to midnight to the birthday person.
1876                  *
1877                  */
1878
1879         
1880                 $birthday = '';
1881
1882                 if(! strlen($tz))
1883                         $tz = 'UTC';
1884
1885                 $p = q("SELECT `dob` FROM `profile` WHERE `is-default` = 1 AND `uid` = %d LIMIT 1",
1886                                 intval($uid)
1887                 );
1888
1889                 if($p && count($p)) {
1890                         $tmp_dob = substr($p[0]['dob'],5);
1891                         if(intval($tmp_dob)) {
1892                                 $y = datetime_convert($tz,$tz,'now','Y');
1893                                 $bd = $y . '-' . $tmp_dob . ' 00:00';
1894                                 $t_dob = strtotime($bd);
1895                                 $now = strtotime(datetime_convert($tz,$tz,'now'));
1896                                 if($t_dob < $now)
1897                                         $bd = $y + 1 . '-' . $tmp_dob . ' 00:00';
1898                                 $birthday = datetime_convert($tz,'UTC',$bd,ATOM_TIME);
1899                         }
1900                 }
1901
1902                 return $birthday;
1903         }
1904 }
1905
1906 if(! function_exists('is_site_admin')) {
1907         function is_site_admin() {
1908                 $a = get_app();
1909                 if(local_user() && x($a->user,'email') && x($a->config,'admin_email') && ($a->user['email'] === $a->config['admin_email']))
1910                         return true;
1911                 return false;
1912         }
1913 }
1914
1915
1916 if(! function_exists('load_contact_links')) {
1917         function load_contact_links($uid) {
1918
1919                 $a = get_app();
1920
1921                 $ret = array();
1922
1923                 if(! $uid || x($a->contacts,'empty'))
1924                         return;
1925
1926                 $r = q("SELECT `id`,`network`,`url`,`thumb` FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 ",
1927                                 intval($uid)
1928                 );
1929                 if(count($r)) {
1930                         foreach($r as $rr){
1931                                 $url = normalise_link($rr['url']);
1932                                 $ret[$url] = $rr;
1933                         }
1934                 }
1935                 else
1936                         $ret['empty'] = true;
1937                 $a->contacts = $ret;
1938                 return;
1939         }
1940 }
1941
1942 if(! function_exists('profile_tabs')){
1943         function profile_tabs($a, $is_owner=False, $nickname=Null){
1944                 //echo "<pre>"; var_dump($a->user); killme();
1945         
1946                 if (is_null($nickname))
1947                         $nickname  = $a->user['nickname'];
1948                 
1949                 if(x($_GET,'tab'))
1950                         $tab = notags(trim($_GET['tab']));
1951         
1952                 $url = $a->get_baseurl() . '/profile/' . $nickname;
1953
1954                 $tabs = array(
1955                         array(
1956                                 'label'=>t('Status'),
1957                                 'url' => $url,
1958                                 'sel' => ((!isset($tab)&&$a->argv[0]=='profile')?'active':''),
1959                                 'title' => t('Status Messages and Posts'),
1960                                 'id' => 'status-tab',
1961                         ),
1962                         array(
1963                                 'label' => t('Profile'),
1964                                 'url'   => $url.'/?tab=profile',
1965                                 'sel'   => ((isset($tab) && $tab=='profile')?'active':''),
1966                                 'title' => t('Profile Details'),
1967                                 'id' => 'profile-tab',
1968                         ),
1969                         array(
1970                                 'label' => t('Photos'),
1971                                 'url'   => $a->get_baseurl() . '/photos/' . $nickname,
1972                                 'sel'   => ((!isset($tab)&&$a->argv[0]=='photos')?'active':''),
1973                                 'title' => t('Photo Albums'),
1974                                 'id' => 'photo-tab',
1975                         ),
1976                         array(
1977                                 'label' => t('Videos'),
1978                                 'url'   => $a->get_baseurl() . '/videos/' . $nickname,
1979                                 'sel'   => ((!isset($tab)&&$a->argv[0]=='videos')?'active':''),
1980                                 'title' => t('Videos'),
1981                                 'id' => 'video-tab',
1982                         ),
1983                 );
1984         
1985                 if ($is_owner){
1986                         $tabs[] = array(
1987                                 'label' => t('Events'),
1988                                 'url'   => $a->get_baseurl() . '/events',
1989                                 'sel'   =>((!isset($tab)&&$a->argv[0]=='events')?'active':''),
1990                                 'title' => t('Events and Calendar'),
1991                                 'id' => 'events-tab',
1992                         );
1993                         $tabs[] = array(
1994                                 'label' => t('Personal Notes'),
1995                                 'url'   => $a->get_baseurl() . '/notes',
1996                                 'sel'   =>((!isset($tab)&&$a->argv[0]=='notes')?'active':''),
1997                                 'title' => t('Only You Can See This'),
1998                                 'id' => 'notes-tab',
1999                         );
2000                 }
2001
2002
2003                 $arr = array('is_owner' => $is_owner, 'nickname' => $nickname, 'tab' => (($tab) ? $tab : false), 'tabs' => $tabs);
2004                 call_hooks('profile_tabs', $arr);
2005         
2006                 $tpl = get_markup_template('common_tabs.tpl');
2007
2008                 return replace_macros($tpl,array('$tabs' => $arr['tabs']));
2009         }
2010 }
2011
2012 function get_my_url() {
2013         if(x($_SESSION,'my_url'))
2014                 return $_SESSION['my_url'];
2015         return false;
2016 }
2017
2018 function zrl_init(&$a) {
2019         $tmp_str = get_my_url();
2020         if(validate_url($tmp_str)) {
2021                 proc_run('php','include/gprobe.php',bin2hex($tmp_str));
2022                 $arr = array('zrl' => $tmp_str, 'url' => $a->cmd);
2023                 call_hooks('zrl_init',$arr);
2024         }
2025 }
2026
2027 function zrl($s,$force = false) {
2028         if(! strlen($s))
2029                 return $s;
2030         if((! strpos($s,'/profile/')) && (! $force))
2031                 return $s;
2032         if($force && substr($s,-1,1) !== '/')
2033                 $s = $s . '/';
2034         $achar = strpos($s,'?') ? '&' : '?';
2035         $mine = get_my_url();
2036         if($mine and ! link_compare($mine,$s))
2037                 return $s . $achar . 'zrl=' . urlencode($mine);
2038         return $s;
2039 }
2040
2041 /**
2042 * returns querystring as string from a mapped array
2043 *
2044 * @param params Array 
2045 * @return string
2046 */
2047 function build_querystring($params, $name=null) { 
2048     $ret = ""; 
2049     foreach($params as $key=>$val) {
2050         if(is_array($val)) { 
2051             if($name==null) {
2052                 $ret .= build_querystring($val, $key); 
2053             } else {
2054                 $ret .= build_querystring($val, $name."[$key]");    
2055             }
2056         } else {
2057             $val = urlencode($val);
2058             if($name!=null) {
2059                 $ret.=$name."[$key]"."=$val&"; 
2060             } else {
2061                 $ret.= "$key=$val&"; 
2062             }
2063         } 
2064     } 
2065     return $ret;    
2066 }
2067
2068 function explode_querystring($query) {
2069         $arg_st = strpos($query, '?');
2070         if($arg_st !== false) {
2071                 $base = substr($query, 0, $arg_st);
2072                 $arg_st += 1;
2073         }
2074         else {
2075                 $base = '';
2076                 $arg_st = 0;
2077         }
2078
2079         $args = explode('&', substr($query, $arg_st));
2080         foreach($args as $k=>$arg) {
2081                 if($arg === '')
2082                         unset($args[$k]);
2083         }
2084         $args = array_values($args);
2085
2086         if(!$base) {
2087                 $base = $args[0];
2088                 unset($args[0]);
2089                 $args = array_values($args);
2090         }
2091
2092         return array(
2093                 'base' => $base,
2094                 'args' => $args,
2095         );
2096 }
2097
2098 /**
2099 * Returns the complete URL of the current page, e.g.: http(s)://something.com/network
2100 *
2101 * Taken from http://webcheatsheet.com/php/get_current_page_url.php
2102 */
2103 function curPageURL() {
2104         $pageURL = 'http';
2105         if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
2106         $pageURL .= "://";
2107         if ($_SERVER["SERVER_PORT"] != "80" && $_SERVER["SERVER_PORT"] != "443") {
2108                 $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
2109         } else {
2110                 $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
2111         }
2112         return $pageURL;
2113 }
2114
2115 function random_digits($digits) {
2116         $rn = '';
2117         for($i = 0; $i < $digits; $i++) {
2118                 $rn .= rand(0,9);
2119         }
2120         return $rn;
2121 }
2122
2123 function get_cachefile($file, $writemode = true) {
2124         $cache = get_config("system","itemcache");
2125
2126         if ((! $cache) || (! is_dir($cache)))
2127                 return("");
2128
2129         $subfolder = $cache."/".substr($file, 0, 2);
2130
2131         $cachepath = $subfolder."/".$file;
2132
2133         if ($writemode) {
2134                 if (!is_dir($subfolder)) {
2135                         mkdir($subfolder);
2136                         chmod($subfolder, 0777);
2137                 }
2138         }
2139
2140         return($cachepath);
2141 }
2142
2143 function clear_cache($basepath = "", $path = "") {
2144         if ($path == "") {
2145                 $basepath = get_config('system','itemcache');
2146                 $path = $basepath;
2147         }
2148
2149         if (($path == "") OR (!is_dir($path)))
2150                 return;
2151
2152         if (substr(realpath($path), 0, strlen($basepath)) != $basepath)
2153                 return;
2154
2155         $cachetime = (int)get_config('system','itemcache_duration');
2156         if ($cachetime == 0)
2157                 $cachetime = 86400;
2158
2159         if (is_writable($path)){
2160         if ($dh = opendir($path)) {
2161                 while (($file = readdir($dh)) !== false) {
2162                         $fullpath = $path."/".$file;
2163                         if ((filetype($fullpath) == "dir") and ($file != ".") and ($file != ".."))
2164                                 clear_cache($basepath, $fullpath);
2165                         if ((filetype($fullpath) == "file") and (filectime($fullpath) < (time() - $cachetime)))
2166                                 unlink($fullpath);
2167                 }
2168                 closedir($dh);
2169         }
2170         }
2171 }
2172
2173 function set_template_engine(&$a, $engine = 'internal') {
2174 // This function is no longer necessary, but keep it as a wrapper to the class method
2175 // to avoid breaking themes again unnecessarily
2176
2177         $a->set_template_engine($engine);
2178 }
2179
2180 if(!function_exists('exif_imagetype')) {
2181         function exif_imagetype($file) {
2182                 $size = getimagesize($file);
2183                 return($size[2]);
2184         }
2185 }