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