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