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