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