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