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