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