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