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