]> git.mxchange.org Git - friendica.git/blob - boot.php
Merge pull request #1119 from annando/1409-issue-881
[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,9) === "pagename=") {
511                                 $this->query_string = substr($_SERVER['QUERY_STRING'],9);
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                         } elseif((x($_SERVER,'QUERY_STRING')) && substr($_SERVER['QUERY_STRING'],0,2) === "q=") {
516                                 $this->query_string = substr($_SERVER['QUERY_STRING'],2);
517                                 // removing trailing / - maybe a nginx problem
518                                 if (substr($this->query_string, 0, 1) == "/")
519                                         $this->query_string = substr($this->query_string, 1);
520                         }
521                         if (x($_GET,'pagename'))
522                                 $this->cmd = trim($_GET['pagename'],'/\\');
523                         elseif (x($_GET,'q'))
524                                 $this->cmd = trim($_GET['q'],'/\\');
525
526                         // unix style "homedir"
527
528                         if(substr($this->cmd,0,1) === '~')
529                                 $this->cmd = 'profile/' . substr($this->cmd,1);
530
531                         // Diaspora style profile url
532
533                         if(substr($this->cmd,0,2) === 'u/')
534                                 $this->cmd = 'profile/' . substr($this->cmd,2);
535
536                         /**
537                          *
538                          * Break the URL path into C style argc/argv style arguments for our
539                          * modules. Given "http://example.com/module/arg1/arg2", $this->argc
540                          * will be 3 (integer) and $this->argv will contain:
541                          *   [0] => 'module'
542                          *   [1] => 'arg1'
543                          *   [2] => 'arg2'
544                          *
545                          *
546                          * There will always be one argument. If provided a naked domain
547                          * URL, $this->argv[0] is set to "home".
548                          *
549                          */
550
551                         $this->argv = explode('/',$this->cmd);
552                         $this->argc = count($this->argv);
553                         if((array_key_exists('0',$this->argv)) && strlen($this->argv[0])) {
554                                 $this->module = str_replace(".", "_", $this->argv[0]);
555                                 $this->module = str_replace("-", "_", $this->module);
556                         }
557                         else {
558                                 $this->argc = 1;
559                                 $this->argv = array('home');
560                                 $this->module = 'home';
561                         }
562
563                         /**
564                          * See if there is any page number information, and initialise
565                          * pagination
566                          */
567
568                         $this->pager['page'] = ((x($_GET,'page') && intval($_GET['page']) > 0) ? intval($_GET['page']) : 1);
569                         $this->pager['itemspage'] = 50;
570                         $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
571                         if($this->pager['start'] < 0)
572                                 $this->pager['start'] = 0;
573                         $this->pager['total'] = 0;
574
575                         /**
576                          * Detect mobile devices
577                          */
578
579                         $mobile_detect = new Mobile_Detect();
580                         $this->is_mobile = $mobile_detect->isMobile();
581                         $this->is_tablet = $mobile_detect->isTablet();
582
583                         /**
584                          * register template engines
585                          */
586                         $dc = get_declared_classes();
587                         foreach ($dc as $k) {
588                                 if (in_array("ITemplateEngine", class_implements($k))){
589                                         $this->register_template_engine($k);
590                                 }
591                         }
592
593                 }
594
595                 function get_basepath() {
596
597                         $basepath = get_config("system", "basepath");
598
599                         if ($basepath == "")
600                                 $basepath = $_SERVER["DOCUMENT_ROOT"];
601
602                         if ($basepath == "")
603                                 $basepath = $_SERVER["PWD"];
604
605                         return($basepath);
606                 }
607
608                 function get_baseurl($ssl = false) {
609
610                         $scheme = $this->scheme;
611
612                         if((x($this->config,'system')) && (x($this->config['system'],'ssl_policy'))) {
613                                 if(intval($this->config['system']['ssl_policy']) === intval(SSL_POLICY_FULL))
614                                         $scheme = 'https';
615
616                                 //      Basically, we have $ssl = true on any links which can only be seen by a logged in user
617                                 //      (and also the login link). Anything seen by an outsider will have it turned off.
618
619                                 if($this->config['system']['ssl_policy'] == SSL_POLICY_SELFSIGN) {
620                                         if($ssl)
621                                                 $scheme = 'https';
622                                         else
623                                                 $scheme = 'http';
624                                 }
625                         }
626
627                         $this->baseurl = $scheme . "://" . $this->hostname . ((isset($this->path) && strlen($this->path)) ? '/' . $this->path : '' );
628                         return $this->baseurl;
629                 }
630
631                 function set_baseurl($url) {
632                         $parsed = @parse_url($url);
633
634                         $this->baseurl = $url;
635
636                         if($parsed) {
637                                 $this->scheme = $parsed['scheme'];
638
639                                 $hostname = $parsed['host'];
640                                 if(x($parsed,'port'))
641                                         $hostname .= ':' . $parsed['port'];
642                                 if(x($parsed,'path'))
643                                         $this->path = trim($parsed['path'],'\\/');
644
645                                 if (file_exists(".htpreconfig.php"))
646                                         @include(".htpreconfig.php");
647
648                                 $this->hostname = $hostname;
649                         }
650
651                 }
652
653                 function get_hostname() {
654                         return $this->hostname;
655                 }
656
657                 function set_hostname($h) {
658                         $this->hostname = $h;
659                 }
660
661                 function set_path($p) {
662                         $this->path = trim(trim($p),'/');
663                 }
664
665                 function get_path() {
666                         return $this->path;
667                 }
668
669                 function set_pager_total($n) {
670                         $this->pager['total'] = intval($n);
671                 }
672
673                 function set_pager_itemspage($n) {
674                         $this->pager['itemspage'] = ((intval($n) > 0) ? intval($n) : 0);
675                         $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
676                 }
677
678                 function set_pager_page($n) {
679                         $this->pager['page'] = $n;
680                         $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
681                 }
682
683                 function init_pagehead() {
684                         $interval = ((local_user()) ? get_pconfig(local_user(),'system','update_interval') : 40000);
685                         if($interval < 10000)
686                                 $interval = 40000;
687
688                         $this->page['title'] = $this->config['sitename'];
689
690                         /* put the head template at the beginning of page['htmlhead']
691                          * since the code added by the modules frequently depends on it
692                          * being first
693                          */
694                         if(!isset($this->page['htmlhead']))
695                                 $this->page['htmlhead'] = '';
696
697                         // If we're using Smarty, then doing replace_macros() will replace
698                         // any unrecognized variables with a blank string. Since we delay
699                         // replacing $stylesheet until later, we need to replace it now
700                         // with another variable name
701                         if($this->theme['template_engine'] === 'smarty3')
702                                 $stylesheet = $this->get_template_ldelim('smarty3') . '$stylesheet' . $this->get_template_rdelim('smarty3');
703                         else
704                                 $stylesheet = '$stylesheet';
705
706                         $shortcut_icon = get_config("system", "shortcut_icon");
707                         if ($shortcut_icon == "")
708                                 $shortcut_icon = $this->get_baseurl()."/images/friendica-32.png";
709
710                         $touch_icon = get_config("system", "touch_icon");
711                         if ($touch_icon == "")
712                                 $touch_icon = $this->get_baseurl()."/images/friendica-128.png";
713
714                         $tpl = get_markup_template('head.tpl');
715                         $this->page['htmlhead'] = replace_macros($tpl,array(
716                                 '$baseurl' => $this->get_baseurl(), // FIXME for z_path!!!!
717                                 '$local_user' => local_user(),
718                                 '$generator' => 'Friendica' . ' ' . FRIENDICA_VERSION,
719                                 '$delitem' => t('Delete this item?'),
720                                 '$comment' => t('Comment'),
721                                 '$showmore' => t('show more'),
722                                 '$showfewer' => t('show fewer'),
723                                 '$update_interval' => $interval,
724                                 '$shortcut_icon' => $shortcut_icon,
725                                 '$touch_icon' => $touch_icon,
726                                 '$stylesheet' => $stylesheet
727                         )) . $this->page['htmlhead'];
728                 }
729
730                 function init_page_end() {
731                         if(!isset($this->page['end']))
732                                 $this->page['end'] = '';
733                         $tpl = get_markup_template('end.tpl');
734                         $this->page['end'] = replace_macros($tpl,array(
735                                 '$baseurl' => $this->get_baseurl() // FIXME for z_path!!!!
736                         )) . $this->page['end'];
737                 }
738
739                 function set_curl_code($code) {
740                         $this->curl_code = $code;
741                 }
742
743                 function get_curl_code() {
744                         return $this->curl_code;
745                 }
746
747                 function set_curl_content_type($content_type) {
748                         $this->curl_content_type = $content_type;
749                 }
750
751                 function get_curl_content_type() {
752                         return $this->curl_content_type;
753                 }
754
755                 function set_curl_headers($headers) {
756                         $this->curl_headers = $headers;
757                 }
758
759                 function get_curl_headers() {
760                         return $this->curl_headers;
761                 }
762
763                 function get_cached_avatar_image($avatar_image){
764                         if($this->cached_profile_image[$avatar_image])
765                                 return $this->cached_profile_image[$avatar_image];
766
767                         $path_parts = explode("/",$avatar_image);
768                         $common_filename = $path_parts[count($path_parts)-1];
769
770                         if($this->cached_profile_picdate[$common_filename]){
771                                 $this->cached_profile_image[$avatar_image] = $avatar_image . $this->cached_profile_picdate[$common_filename];
772                         } else {
773                                 $r = q("SELECT `contact`.`avatar-date` AS picdate FROM `contact` WHERE `contact`.`thumb` like '%%/%s'",
774                                         $common_filename);
775                                 if(! count($r)){
776                                         $this->cached_profile_image[$avatar_image] = $avatar_image;
777                                 } else {
778                                         $this->cached_profile_picdate[$common_filename] = "?rev=".urlencode($r[0]['picdate']);
779                                         $this->cached_profile_image[$avatar_image] = $avatar_image.$this->cached_profile_picdate[$common_filename];
780                                 }
781                         }
782                         return $this->cached_profile_image[$avatar_image];
783                 }
784
785
786                 /**
787                  * register template engine class
788                  * if $name is "", is used class static property $class::$name
789                  * @param string $class
790                  * @param string $name
791                  */
792                 function register_template_engine($class, $name = '') {
793                         if ($name===""){
794                                 $v = get_class_vars( $class );
795                                 if(x($v,"name")) $name = $v['name'];
796                         }
797                         if ($name===""){
798                                 echo "template engine <tt>$class</tt> cannot be registered without a name.\n";
799                                 killme(); 
800                         }
801                         $this->template_engines[$name] = $class;
802                 }
803
804                 /**
805                  * return template engine instance. If $name is not defined,
806                  * return engine defined by theme, or default
807                  * 
808                  * @param strin $name Template engine name
809                  * @return object Template Engine instance
810                  */
811                 function template_engine($name = ''){
812                         if ($name!=="") {
813                                 $template_engine = $name;
814                         } else {
815                                 $template_engine = 'smarty3';
816                                 if (x($this->theme, 'template_engine')) {
817                                         $template_engine = $this->theme['template_engine'];
818                                 }
819                         }
820
821                         if (isset($this->template_engines[$template_engine])){
822                                 if(isset($this->template_engine_instance[$template_engine])){
823                                         return $this->template_engine_instance[$template_engine];
824                                 } else {
825                                         $class = $this->template_engines[$template_engine];
826                                         $obj = new $class;
827                                         $this->template_engine_instance[$template_engine] = $obj;
828                                         return $obj;
829                                 }
830                         }
831
832                         echo "template engine <tt>$template_engine</tt> is not registered!\n"; killme();
833                 }
834
835                 function get_template_engine() {
836                         return $this->theme['template_engine'];
837                 }
838
839                 function set_template_engine($engine = 'smarty3') {
840                         $this->theme['template_engine'] = $engine;
841                         /*
842                         $this->theme['template_engine'] = 'smarty3';
843
844                         switch($engine) {
845                                 case 'smarty3':
846                                         if(is_writable('view/smarty3/'))
847                                                 $this->theme['template_engine'] = 'smarty3';
848                                         break;
849                                 default:
850                                         break;
851                         }
852                         */
853                 }
854
855                 function get_template_ldelim($engine = 'smarty3') {
856                         return $this->ldelim[$engine];
857                 }
858
859                 function get_template_rdelim($engine = 'smarty3') {
860                         return $this->rdelim[$engine];
861                 }
862
863                 function save_timestamp($stamp, $value) {
864                         $duration = (float)(microtime(true)-$stamp);
865
866                         $this->performance[$value] += (float)$duration;
867                         $this->performance["marktime"] += (float)$duration;
868                 }
869
870                 function mark_timestamp($mark) {
871                         //$this->performance["markstart"] -= microtime(true) - $this->performance["marktime"];
872                         $this->performance["markstart"] = microtime(true) - $this->performance["markstart"] - $this->performance["marktime"];
873                 }
874
875                 function get_useragent() {
876                         return(FRIENDICA_PLATFORM." ".FRIENDICA_VERSION."-".DB_UPDATE_VERSION."; ".$this->get_baseurl());
877                 }
878
879         }
880 }
881
882 // retrieve the App structure
883 // useful in functions which require it but don't get it passed to them
884
885 if(! function_exists('get_app')) {
886         function get_app() {
887                 global $a;
888                 return $a;
889         }
890 };
891
892
893 // Multi-purpose function to check variable state.
894 // Usage: x($var) or $x($array,'key')
895 // returns false if variable/key is not set
896 // if variable is set, returns 1 if has 'non-zero' value, otherwise returns 0.
897 // e.g. x('') or x(0) returns 0;
898
899 if(! function_exists('x')) {
900         function x($s,$k = NULL) {
901                 if($k != NULL) {
902                         if((is_array($s)) && (array_key_exists($k,$s))) {
903                                 if($s[$k])
904                                         return (int) 1;
905                                 return (int) 0;
906                 }
907                         return false;
908                 }
909                 else {
910                         if(isset($s)) {
911                                 if($s) {
912                                         return (int) 1;
913                                 }
914                                 return (int) 0;
915                         }
916                         return false;
917                 }
918         }
919 }
920
921 // called from db initialisation if db is dead.
922
923 if(! function_exists('system_unavailable')) {
924         function system_unavailable() {
925                 include('system_unavailable.php');
926                 system_down();
927                 killme();
928         }
929 }
930
931
932
933 function clean_urls() {
934         global $a;
935         //      if($a->config['system']['clean_urls'])
936         return true;
937         //      return false;
938 }
939
940 function z_path() {
941         global $a;
942         $base = $a->get_baseurl();
943         if(! clean_urls())
944                 $base .= '/?q=';
945         return $base;
946 }
947
948 function z_root() {
949         global $a;
950         return $a->get_baseurl();
951 }
952
953 function absurl($path) {
954         if(strpos($path,'/') === 0)
955                 return z_path() . $path;
956         return $path;
957 }
958
959 function is_ajax() {
960         return (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');
961 }
962
963 function check_db() {
964
965         $build = get_config('system','build');
966         if(! x($build)) {
967                 set_config('system','build',DB_UPDATE_VERSION);
968                 $build = DB_UPDATE_VERSION;
969         }
970         if($build != DB_UPDATE_VERSION)
971                 proc_run('php', 'include/dbupdate.php');
972
973 }
974
975
976
977
978 // Sets the base url for use in cmdline programs which don't have
979 // $_SERVER variables
980
981 if(! function_exists('check_url')) {
982         function check_url(&$a) {
983
984                 $url = get_config('system','url');
985
986                 // if the url isn't set or the stored url is radically different
987                 // than the currently visited url, store the current value accordingly.
988                 // "Radically different" ignores common variations such as http vs https
989                 // and www.example.com vs example.com.
990                 // We will only change the url to an ip address if there is no existing setting
991
992                 if(! x($url))
993                         $url = set_config('system','url',$a->get_baseurl());
994                 if((! link_compare($url,$a->get_baseurl())) && (! preg_match("/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/",$a->get_hostname)))
995                         $url = set_config('system','url',$a->get_baseurl());
996
997                 return;
998         }
999 }
1000
1001
1002 // Automatic database updates
1003
1004 if(! function_exists('update_db')) {
1005         function update_db(&$a) {
1006
1007                 $build = get_config('system','build');
1008                 if(! x($build))
1009                         $build = set_config('system','build',DB_UPDATE_VERSION);
1010
1011                 if($build != DB_UPDATE_VERSION) {
1012                         $stored = intval($build);
1013                         $current = intval(DB_UPDATE_VERSION);
1014                         if(($stored < $current) && file_exists('update.php')) {
1015
1016                                 load_config('database');
1017
1018                                 // We're reporting a different version than what is currently installed.
1019                                 // Run any existing update scripts to bring the database up to current.
1020
1021                                 require_once('update.php');
1022
1023                                 // make sure that boot.php and update.php are the same release, we might be
1024                                 // updating right this very second and the correct version of the update.php
1025                                 // file may not be here yet. This can happen on a very busy site.
1026
1027                                 if(DB_UPDATE_VERSION == UPDATE_VERSION) {
1028
1029                                         // Compare the current structure with the defined structure
1030
1031                                         $t = get_config('database','dbupdate_'.DB_UPDATE_VERSION);
1032                                         if($t !== false)
1033                                                 return;
1034
1035                                         set_config('database','dbupdate_'.DB_UPDATE_VERSION, time());
1036
1037                                         require_once("include/dbstructure.php");
1038                                         $retval = update_structure(false, true);
1039                                         if($retval) {
1040                                                 //send the administrator an e-mail
1041                                                 $email_tpl = get_intltext_template("update_fail_eml.tpl");
1042                                                 $email_msg = replace_macros($email_tpl, array(
1043                                                         '$sitename' => $a->config['sitename'],
1044                                                         '$siteurl' =>  $a->get_baseurl(),
1045                                                         '$update' => DB_UPDATE_VERSION,
1046                                                         '$error' => sprintf(t('Update %s failed. See error logs.'), DB_UPDATE_VERSION)
1047                                                 ));
1048                                                 $subject=sprintf(t('Update Error at %s'), $a->get_baseurl());
1049                                                 require_once('include/email.php');
1050                                                 $subject = email_header_encode($subject,'UTF-8');
1051                                                 mail($a->config['admin_email'], $subject, $email_msg,
1052                                                         'From: ' . 'Administrator' . '@' . $_SERVER['SERVER_NAME']."\n"
1053                                                         .'Content-type: text/plain; charset=UTF-8'."\n"
1054                                                         .'Content-transfer-encoding: 8bit');
1055                                                 //try the logger
1056                                                 logger("CRITICAL: Database structure update failed: ".$retval);
1057                                                 break;
1058                                         } else
1059                                                 set_config('database','dbupdate_'.DB_UPDATE_VERSION, 'success');
1060
1061                                         for($x = $stored; $x < $current; $x ++) {
1062                                                 if(function_exists('update_' . $x)) {
1063
1064                                                         // There could be a lot of processes running or about to run.
1065                                                         // We want exactly one process to run the update command.
1066                                                         // So store the fact that we're taking responsibility
1067                                                         // after first checking to see if somebody else already has.
1068
1069                                                         // If the update fails or times-out completely you may need to
1070                                                         // delete the config entry to try again.
1071
1072                                                         $t = get_config('database','update_' . $x);
1073                                                         if($t !== false)
1074                                                                 break;
1075                                                         set_config('database','update_' . $x, time());
1076
1077                                                         // call the specific update
1078
1079                                                         $func = 'update_' . $x;
1080                                                         $retval = $func();
1081                                                         if($retval) {
1082                                                                 //send the administrator an e-mail
1083                                                                 $email_tpl = get_intltext_template("update_fail_eml.tpl");
1084                                                                 $email_msg = replace_macros($email_tpl, array(
1085                                                                         '$sitename' => $a->config['sitename'],
1086                                                                         '$siteurl' =>  $a->get_baseurl(),
1087                                                                         '$update' => $x,
1088                                                                         '$error' => sprintf( t('Update %s failed. See error logs.'), $x)
1089                                                                 ));
1090                                                                 $subject=sprintf(t('Update Error at %s'), $a->get_baseurl());
1091                                                                 require_once('include/email.php');
1092                                                                 $subject = email_header_encode($subject,'UTF-8');
1093                                                                 mail($a->config['admin_email'], $subject, $email_msg,
1094                                                                         'From: ' . 'Administrator' . '@' . $_SERVER['SERVER_NAME'] . "\n"
1095                                                                         . 'Content-type: text/plain; charset=UTF-8' . "\n"
1096                                                                         . 'Content-transfer-encoding: 8bit' );
1097                                                                 //try the logger
1098                                                                 logger('CRITICAL: Update Failed: '. $x);
1099                                                                 break;
1100                                                         } else {
1101                                                                 set_config('database','update_' . $x, 'success');
1102                                                                 set_config('system','build', $x + 1);
1103                                                         }
1104                                                 } else {
1105                                                         set_config('database','update_' . $x, 'success');
1106                                                         set_config('system','build', $x + 1);
1107                                                 }
1108                                         }
1109                                 }
1110                         }
1111                 }
1112
1113                 return;
1114         }
1115 }
1116
1117
1118 if(! function_exists('check_plugins')) {
1119         function check_plugins(&$a) {
1120
1121                 /**
1122                  *
1123                  * Synchronise plugins:
1124                  *
1125                  * $a->config['system']['addon'] contains a comma-separated list of names
1126                  * of plugins/addons which are used on this system.
1127                  * Go through the database list of already installed addons, and if we have
1128                  * an entry, but it isn't in the config list, call the uninstall procedure
1129                  * and mark it uninstalled in the database (for now we'll remove it).
1130                  * Then go through the config list and if we have a plugin that isn't installed,
1131                  * call the install procedure and add it to the database.
1132                  *
1133                  */
1134
1135                 $r = q("SELECT * FROM `addon` WHERE `installed` = 1");
1136                 if(count($r))
1137                         $installed = $r;
1138                 else
1139                         $installed = array();
1140
1141                 $plugins = get_config('system','addon');
1142                 $plugins_arr = array();
1143
1144                 if($plugins)
1145                         $plugins_arr = explode(',',str_replace(' ', '',$plugins));
1146
1147                 $a->plugins = $plugins_arr;
1148
1149                 $installed_arr = array();
1150
1151                 if(count($installed)) {
1152                         foreach($installed as $i) {
1153                                 if(! in_array($i['name'],$plugins_arr)) {
1154                                         uninstall_plugin($i['name']);
1155                                 }
1156                                 else {
1157                                         $installed_arr[] = $i['name'];
1158                                 }
1159                         }
1160                 }
1161
1162                 if(count($plugins_arr)) {
1163                         foreach($plugins_arr as $p) {
1164                                 if(! in_array($p,$installed_arr)) {
1165                                         install_plugin($p);
1166                                 }
1167                         }
1168                 }
1169
1170
1171                 load_hooks();
1172
1173                 return;
1174         }
1175 }
1176
1177 function get_guid($size=16) {
1178         $exists = true; // assume by default that we don't have a unique guid
1179         do {
1180                 $prefix = "";
1181                 while (strlen($prefix) < ($size - 13))
1182                         $prefix .= mt_rand();
1183
1184                 $s = substr(uniqid($prefix), -$size);
1185
1186                 $r = q("select id from guid where guid = '%s' limit 1", dbesc($s));
1187                 if(! count($r))
1188                         $exists = false;
1189         } while($exists);
1190         q("insert into guid (guid) values ('%s') ", dbesc($s));
1191         return $s;
1192 }
1193
1194 /*function get_guid($size=16) {
1195         $exists = true; // assume by default that we don't have a unique guid
1196         do {
1197                 $s = random_string($size);
1198                 $r = q("select id from guid where guid = '%s' limit 1", dbesc($s));
1199                 if(! count($r))
1200                         $exists = false;
1201         } while($exists);
1202         q("insert into guid ( guid ) values ( '%s' ) ", dbesc($s));
1203         return $s;
1204 }*/
1205
1206
1207 // wrapper for adding a login box. If $register == true provide a registration
1208 // link. This will most always depend on the value of $a->config['register_policy'].
1209 // returns the complete html for inserting into the page
1210
1211 if(! function_exists('login')) {
1212         function login($register = false, $hiddens=false) {
1213                 $a = get_app();
1214                 $o = "";
1215                 $reg = false;
1216                 if ($register) {
1217                         $reg = array(
1218                                 'title' => t('Create a New Account'),
1219                                 'desc' => t('Register')
1220                         );
1221                 }
1222
1223                 $noid = get_config('system','no_openid');
1224         
1225                 $dest_url = $a->get_baseurl(true) . '/' . $a->query_string;
1226
1227                 if(local_user()) {
1228                         $tpl = get_markup_template("logout.tpl");
1229                 }
1230                 else {
1231                         $a->page['htmlhead'] .= replace_macros(get_markup_template("login_head.tpl"),array(
1232                                 '$baseurl'              => $a->get_baseurl(true)
1233                         ));
1234
1235                         $tpl = get_markup_template("login.tpl");
1236                         $_SESSION['return_url'] = $a->query_string;
1237                         $a->module = 'login';
1238                 }
1239
1240                 $o .= replace_macros($tpl, array(
1241
1242                         '$dest_url'     => $dest_url,
1243                         '$logout'       => t('Logout'),
1244                         '$login'        => t('Login'),
1245         
1246                         '$lname'                => array('username', t('Nickname or Email address: ') , '', ''),
1247                         '$lpassword'    => array('password', t('Password: '), '', ''),
1248                         '$lremember'    => array('remember', t('Remember me'), 0,  ''),
1249         
1250                         '$openid'               => !$noid,
1251                         '$lopenid'      => array('openid_url', t('Or login using OpenID: '),'',''),
1252         
1253                         '$hiddens'      => $hiddens,
1254         
1255                         '$register'     => $reg,
1256         
1257                         '$lostpass'     => t('Forgot your password?'),
1258                         '$lostlink'     => t('Password Reset'),
1259
1260                         '$tostitle'     => t('Website Terms of Service'),
1261                         '$toslink'      => t('terms of service'),
1262
1263                         '$privacytitle' => t('Website Privacy Policy'),
1264                         '$privacylink'  => t('privacy policy'),
1265
1266                 ));
1267
1268                 call_hooks('login_hook',$o);
1269
1270                 return $o;
1271         }
1272 }
1273
1274 // Used to end the current process, after saving session state.
1275
1276 if(! function_exists('killme')) {
1277         function killme() {
1278                 session_write_close();
1279                 exit;
1280         }
1281 }
1282
1283 // redirect to another URL and terminate this process.
1284
1285 if(! function_exists('goaway')) {
1286         function goaway($s) {
1287                 header("Location: $s");
1288                 killme();
1289         }
1290 }
1291
1292
1293 // Returns the uid of locally logged in user or false.
1294
1295 if(! function_exists('local_user')) {
1296         function local_user() {
1297                 if((x($_SESSION,'authenticated')) && (x($_SESSION,'uid')))
1298                         return intval($_SESSION['uid']);
1299                 return false;
1300         }
1301 }
1302
1303 // Returns contact id of authenticated site visitor or false
1304
1305 if(! function_exists('remote_user')) {
1306         function remote_user() {
1307                 if((x($_SESSION,'authenticated')) && (x($_SESSION,'visitor_id')))
1308                         return intval($_SESSION['visitor_id']);
1309                 return false;
1310         }
1311 }
1312
1313 // contents of $s are displayed prominently on the page the next time
1314 // a page is loaded. Usually used for errors or alerts.
1315
1316 if(! function_exists('notice')) {
1317         /**
1318          * Show an error message to user.
1319          * 
1320          * This function save text in session, to be shown to the user at next page load
1321          * 
1322          * @param string $s - Text of notice
1323          */
1324         function notice($s) {
1325                 $a = get_app();
1326                 if(! x($_SESSION,'sysmsg'))     $_SESSION['sysmsg'] = array();
1327                 if($a->interactive)
1328                         $_SESSION['sysmsg'][] = $s;
1329         }
1330 }
1331 if(! function_exists('info')) {
1332         /**
1333          * Show an info message to user.
1334          * 
1335          * This function save text in session, to be shown to the user at next page load
1336          * 
1337          * @param string $s - Text of notice
1338          */
1339         function info($s) {
1340                 $a = get_app();
1341
1342                 if (local_user() AND get_pconfig(local_user(),'system','ignore_info'))
1343                         return;
1344
1345                 if(! x($_SESSION,'sysmsg_info')) $_SESSION['sysmsg_info'] = array();
1346                 if($a->interactive)
1347                         $_SESSION['sysmsg_info'][] = $s;
1348         }
1349 }
1350
1351
1352 // wrapper around config to limit the text length of an incoming message
1353
1354 if(! function_exists('get_max_import_size')) {
1355         function get_max_import_size() {
1356                 global $a;
1357                 return ((x($a->config,'max_import_size')) ? $a->config['max_import_size'] : 0 );
1358         }
1359 }
1360
1361
1362
1363 /**
1364  *
1365  * Function : profile_load
1366  * @parameter App    $a
1367  * @parameter string $nickname
1368  * @parameter int    $profile
1369  *
1370  * Summary: Loads a profile into the page sidebar.
1371  * The function requires a writeable copy of the main App structure, and the nickname
1372  * of a registered local account.
1373  *
1374  * If the viewer is an authenticated remote viewer, the profile displayed is the
1375  * one that has been configured for his/her viewing in the Contact manager.
1376  * Passing a non-zero profile ID can also allow a preview of a selected profile
1377  * by the owner.
1378  *
1379  * Profile information is placed in the App structure for later retrieval.
1380  * Honours the owner's chosen theme for display.
1381  *
1382  * IMPORTANT: Should only be run in the _init() functions of a module. That ensures that
1383  * the theme is chosen before the _init() function of a theme is run, which will usually
1384  * load a lot of theme-specific content
1385  *
1386  */
1387
1388 if(! function_exists('profile_load')) {
1389         function profile_load(&$a, $nickname, $profile = 0, $profiledata = array()) {
1390
1391                 $user = q("select uid from user where nickname = '%s' limit 1",
1392                         dbesc($nickname)
1393                 );
1394
1395                 if(! ($user && count($user))) {
1396                         logger('profile error: ' . $a->query_string, LOGGER_DEBUG);
1397                         notice( t('Requested account is not available.') . EOL );
1398                         $a->error = 404;
1399                         return;
1400                 }
1401
1402                 if(remote_user() && count($_SESSION['remote'])) {
1403                         foreach($_SESSION['remote'] as $visitor) {
1404                                 if($visitor['uid'] == $user[0]['uid']) {
1405                                         $r = q("SELECT `profile-id` FROM `contact` WHERE `id` = %d LIMIT 1",
1406                                                 intval($visitor['cid'])
1407                                         );
1408                                         if(count($r))
1409                                                 $profile = $r[0]['profile-id'];
1410                                         break;
1411                                 }
1412                         }
1413                 }
1414
1415                 $r = null;
1416
1417                 if($profile) {
1418                         $profile_int = intval($profile);
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`.`id` = %d and `contact`.`self` = 1 LIMIT 1",
1422                                         dbesc($nickname),
1423                                         intval($profile_int)
1424                         );
1425                 }
1426                 if((! $r) && (!  count($r))) {
1427                         $r = q("SELECT `profile`.`uid` AS `profile_uid`, `profile`.* , `contact`.`avatar-date` AS picdate, `user`.* FROM `profile`
1428                                         INNER JOIN `contact` on `contact`.`uid` = `profile`.`uid` INNER JOIN `user` ON `profile`.`uid` = `user`.`uid`
1429                                         WHERE `user`.`nickname` = '%s' AND `profile`.`is-default` = 1 and `contact`.`self` = 1 LIMIT 1",
1430                                         dbesc($nickname)
1431                         );
1432                 }
1433
1434                 if(($r === false) || (! count($r))) {
1435                         logger('profile error: ' . $a->query_string, LOGGER_DEBUG);
1436                         notice( t('Requested profile is not available.') . EOL );
1437                         $a->error = 404;
1438                         return;
1439                 }
1440
1441                 // fetch user tags if this isn't the default profile
1442
1443                 if(! $r[0]['is-default']) {
1444                         $x = q("select `pub_keywords` from `profile` where uid = %d and `is-default` = 1 limit 1",
1445                                         intval($r[0]['profile_uid'])
1446                         );
1447                         if($x && count($x))
1448                                 $r[0]['pub_keywords'] = $x[0]['pub_keywords'];
1449                 }
1450
1451                 $a->profile = $r[0];
1452
1453                 $a->profile['mobile-theme'] = get_pconfig($a->profile['profile_uid'], 'system', 'mobile_theme');
1454                 $a->profile['network'] = NETWORK_DFRN;
1455
1456                 $a->page['title'] = $a->profile['name'] . " @ " . $a->config['sitename'];
1457
1458                 if (!$profiledata)
1459                         $_SESSION['theme'] = $a->profile['theme'];
1460
1461                 $_SESSION['mobile-theme'] = $a->profile['mobile-theme'];
1462
1463                 /**
1464                  * load/reload current theme info
1465                  */
1466
1467                 $a->set_template_engine(); // reset the template engine to the default in case the user's theme doesn't specify one
1468
1469                 $theme_info_file = "view/theme/".current_theme()."/theme.php";
1470                 if (file_exists($theme_info_file)){
1471                         require_once($theme_info_file);
1472                 }
1473
1474                 if(! (x($a->page,'aside')))
1475                         $a->page['aside'] = '';
1476
1477                 if(local_user() && local_user() == $a->profile['uid'] && $profiledata) {
1478                         $a->page['aside'] .= replace_macros(get_markup_template('profile_edlink.tpl'),array(
1479                                 '$editprofile' => t('Edit profile'),
1480                                 '$profid' => $a->profile['id']
1481                         ));
1482                 }
1483
1484                 $block = (((get_config('system','block_public')) && (! local_user()) && (! remote_user())) ? true : false);
1485
1486                 // To-Do:
1487                 // By now, the contact block isn't shown, when a different profile is given
1488                 // But: When this profile was on the same server, then we could display the contacts
1489                 if ($profiledata)
1490                         $a->page['aside'] .= profile_sidebar($profiledata, true);
1491                 else
1492                         $a->page['aside'] .= profile_sidebar($a->profile, $block);
1493
1494
1495                 /*if(! $block)
1496                  $a->page['aside'] .= contact_block();*/
1497
1498                 return;
1499         }
1500 }
1501
1502
1503 /**
1504  *
1505  * Function: profile_sidebar
1506  *
1507  * Formats a profile for display in the sidebar.
1508  * It is very difficult to templatise the HTML completely
1509  * because of all the conditional logic.
1510  *
1511  * @parameter: array $profile
1512  *
1513  * Returns HTML string stuitable for sidebar inclusion
1514  * Exceptions: Returns empty string if passed $profile is wrong type or not populated
1515  *
1516  */
1517
1518
1519 if(! function_exists('profile_sidebar')) {
1520         function profile_sidebar($profile, $block = 0) {
1521                 $a = get_app();
1522
1523                 $o = '';
1524                 $location = false;
1525                 $address = false;
1526                 $pdesc = true;
1527
1528                 if((! is_array($profile)) && (! count($profile)))
1529                         return $o;
1530
1531                 $profile['picdate'] = urlencode($profile['picdate']);
1532
1533                 if (($profile['network'] != "") AND ($profile['network'] != NETWORK_DFRN)) {
1534                         require_once('include/contact_selectors.php');
1535                         if ($profile['url'] != "")
1536                                 $profile['network_name'] = '<a href="'.$profile['url'].'">'.network_to_name($profile['network'])."</a>";
1537                         else
1538                                 $profile['network_name'] = network_to_name($profile['network']);
1539                 } else
1540                         $profile['network_name'] = "";
1541
1542                 call_hooks('profile_sidebar_enter', $profile);
1543
1544
1545                 // don't show connect link to yourself
1546                 $connect = (($profile['uid'] != local_user()) ? t('Connect')  : False);
1547
1548                 // don't show connect link to authenticated visitors either
1549                 if(remote_user() && count($_SESSION['remote'])) {
1550                         foreach($_SESSION['remote'] as $visitor) {
1551                                 if($visitor['uid'] == $profile['uid']) {
1552                                         $connect = false;
1553                                         break;
1554                                 }
1555                         }
1556                 }
1557
1558                 // Is the local user already connected to that user?
1559                 if ($connect AND local_user()) {
1560                         if (isset($profile["url"]))
1561                                 $profile_url = normalise_link($profile["url"]);
1562                         else
1563                                 $profile_url = normalise_link($a->get_baseurl()."/profile/".$profile["nickname"]);
1564
1565                         $r = q("SELECT * FROM `contact` WHERE NOT `pending` AND `uid` = %d AND `nurl` = '%s'",
1566                                 local_user(), $profile_url);
1567                         if (count($r))
1568                                 $connect = false;
1569                 }
1570
1571                 if ($connect AND ($profile['network'] != NETWORK_DFRN) AND !isset($profile['remoteconnect']))
1572                                 $connect = false;
1573
1574                 if (isset($profile['remoteconnect']))
1575                         $remoteconnect = $profile['remoteconnect'];
1576
1577                 if( get_my_url() && $profile['unkmail'] && ($profile['uid'] != local_user()) )
1578                         $wallmessage = t('Message');
1579                 else
1580                         $wallmessage = false;
1581
1582                 // show edit profile to yourself
1583                 if ($profile['uid'] == local_user() && feature_enabled(local_user(),'multi_profiles')) {
1584                         $profile['edit'] = array($a->get_baseurl(). '/profiles', t('Profiles'),"", t('Manage/edit profiles'));
1585                         $r = q("SELECT * FROM `profile` WHERE `uid` = %d",
1586                                         local_user());
1587
1588                         $profile['menu'] = array(
1589                                 'chg_photo' => t('Change profile photo'),
1590                                 'cr_new' => t('Create New Profile'),
1591                                 'entries' => array(),
1592                         );
1593
1594                         if(count($r)) {
1595
1596                                 foreach($r as $rr) {
1597                                         $profile['menu']['entries'][] = array(
1598                                                 'photo' => $rr['thumb'],
1599                                                 'id' => $rr['id'],
1600                                                 'alt' => t('Profile Image'),
1601                                                 'profile_name' => $rr['profile-name'],
1602                                                 'isdefault' => $rr['is-default'],
1603                                                 'visibile_to_everybody' =>  t('visible to everybody'),
1604                                                 'edit_visibility' => t('Edit visibility'),
1605
1606                                         );
1607                                 }
1608
1609
1610                         }
1611                 }
1612                 if ($profile['uid'] == local_user() && !feature_enabled(local_user(),'multi_profiles')) {
1613                         $profile['edit'] = array($a->get_baseurl(). '/profiles/'.$profile['id'], t('Edit profile'),"", t('Edit profile'));
1614                         $profile['menu'] = array(
1615                                 'chg_photo' => t('Change profile photo'),
1616                                 'cr_new' => null,
1617                                 'entries' => array(),
1618                         );
1619                 }
1620
1621                 if((x($profile,'address') == 1)
1622                                 || (x($profile,'locality') == 1)
1623                                 || (x($profile,'region') == 1)
1624                                 || (x($profile,'postal-code') == 1)
1625                                 || (x($profile,'country-name') == 1))
1626                         $location = t('Location:');
1627
1628                 $gender = ((x($profile,'gender') == 1) ? t('Gender:') : False);
1629
1630
1631                 $marital = ((x($profile,'marital') == 1) ?  t('Status:') : False);
1632
1633                 $homepage = ((x($profile,'homepage') == 1) ?  t('Homepage:') : False);
1634
1635                 if(($profile['hidewall'] || $block) && (! local_user()) && (! remote_user())) {
1636                         $location = $pdesc = $gender = $marital = $homepage = False;
1637                 }
1638
1639                 $firstname = ((strpos($profile['name'],' '))
1640                                 ? trim(substr($profile['name'],0,strpos($profile['name'],' '))) : $profile['name']);
1641                 $lastname = (($firstname === $profile['name']) ? '' : trim(substr($profile['name'],strlen($firstname))));
1642
1643                 $diaspora = array(
1644                         'podloc' => $a->get_baseurl(),
1645                         'searchable' => (($profile['publish'] && $profile['net-publish']) ? 'true' : 'false' ),
1646                         'nickname' => $profile['nickname'],
1647                         'fullname' => $profile['name'],
1648                         'firstname' => $firstname,
1649                         'lastname' => $lastname,
1650                         'photo300' => $a->get_cached_avatar_image($a->get_baseurl() . '/photo/custom/300/' . $profile['uid'] . '.jpg'),
1651                         'photo100' => $a->get_cached_avatar_image($a->get_baseurl() . '/photo/custom/100/' . $profile['uid'] . '.jpg'),
1652                         'photo50' => $a->get_cached_avatar_image($a->get_baseurl() . '/photo/custom/50/'  . $profile['uid'] . '.jpg'),
1653                 );
1654
1655                 if (!$block){
1656                         $contact_block = contact_block();
1657                 }
1658
1659
1660                 $p = array();
1661                 foreach($profile as $k => $v) {
1662                         $k = str_replace('-','_',$k);
1663                         $p[$k] = $v;
1664                 }
1665
1666                 if($a->theme['template_engine'] === 'internal')
1667                         $location = template_escape($location);
1668
1669
1670                 $tpl = get_markup_template('profile_vcard.tpl');
1671                 $o .= replace_macros($tpl, array(
1672                         '$profile' => $p,
1673                         '$connect'  => $connect,
1674                         '$remoteconnect'  => $remoteconnect,
1675                         '$wallmessage' => $wallmessage,
1676                         '$location' => $location,
1677                         '$gender'   => $gender,
1678                         '$pdesc'        => $pdesc,
1679                         '$marital'  => $marital,
1680                         '$homepage' => $homepage,
1681                         '$network' =>  t('Network:'),
1682                         '$diaspora' => $diaspora,
1683                         '$contact_block' => $contact_block,
1684                 ));
1685
1686
1687                 $arr = array('profile' => &$profile, 'entry' => &$o);
1688
1689                 call_hooks('profile_sidebar', $arr);
1690
1691                 return $o;
1692         }
1693 }
1694
1695
1696 if(! function_exists('get_birthdays')) {
1697         function get_birthdays() {
1698
1699                 $a = get_app();
1700                 $o = '';
1701
1702                 if(! local_user() || $a->is_mobile || $a->is_tablet)
1703                         return $o;
1704
1705 //              $mobile_detect = new Mobile_Detect();
1706 //              $is_mobile = $mobile_detect->isMobile() || $mobile_detect->isTablet();
1707
1708 //              if($is_mobile)
1709 //                      return $o;
1710
1711                 $bd_format = t('g A l F d') ; // 8 AM Friday January 18
1712                 $bd_short = t('F d');
1713
1714                 $r = q("SELECT `event`.*, `event`.`id` AS `eid`, `contact`.* FROM `event`
1715                                 INNER JOIN `contact` ON `contact`.`id` = `event`.`cid`
1716                                 WHERE `event`.`uid` = %d AND `type` = 'birthday' AND `start` < '%s' AND `finish` > '%s'
1717                                 ORDER BY `start` ASC ",
1718                                 intval(local_user()),
1719                                 dbesc(datetime_convert('UTC','UTC','now + 6 days')),
1720                                 dbesc(datetime_convert('UTC','UTC','now'))
1721                 );
1722
1723                 if($r && count($r)) {
1724                         $total = 0;
1725                         $now = strtotime('now');
1726                         $cids = array();
1727
1728                         $istoday = false;
1729                         foreach($r as $rr) {
1730                                 if(strlen($rr['name']))
1731                                         $total ++;
1732                                 if((strtotime($rr['start'] . ' +00:00') < $now) && (strtotime($rr['finish'] . ' +00:00') > $now))
1733                                         $istoday = true;
1734                         }
1735                         $classtoday = $istoday ? ' birthday-today ' : '';
1736                         if($total) {
1737                                 foreach($r as &$rr) {
1738                                         if(! strlen($rr['name']))
1739                                                 continue;
1740
1741                                         // avoid duplicates
1742
1743                                         if(in_array($rr['cid'],$cids))
1744                                                 continue;
1745                                         $cids[] = $rr['cid'];
1746
1747                                         $today = (((strtotime($rr['start'] . ' +00:00') < $now) && (strtotime($rr['finish'] . ' +00:00') > $now)) ? true : false);
1748                                         $sparkle = '';
1749                                         $url = $rr['url'];
1750                                         if($rr['network'] === NETWORK_DFRN) {
1751                                                 $sparkle = " sparkle";
1752                                                 $url = $a->get_baseurl() . '/redir/'  . $rr['cid'];
1753                                         }
1754
1755                                         $rr['link'] = $url;
1756                                         $rr['title'] = $rr['name'];
1757                                         $rr['date'] = day_translate(datetime_convert('UTC', $a->timezone, $rr['start'], $rr['adjust'] ? $bd_format : $bd_short)) . (($today) ?  ' ' . t('[today]') : '');
1758                                         $rr['startime'] = Null;
1759                                         $rr['today'] = $today;
1760         
1761                                 }
1762                         }
1763                 }
1764                 $tpl = get_markup_template("birthdays_reminder.tpl");
1765                 return replace_macros($tpl, array(
1766                         '$baseurl' => $a->get_baseurl(),
1767                         '$classtoday' => $classtoday,
1768                         '$count' => $total,
1769                         '$event_reminders' => t('Birthday Reminders'),
1770                         '$event_title' => t('Birthdays this week:'),
1771                         '$events' => $r,
1772                         '$lbr' => '{',  // raw brackets mess up if/endif macro processing
1773                         '$rbr' => '}'
1774
1775                 ));
1776         }
1777 }
1778
1779
1780 if(! function_exists('get_events')) {
1781         function get_events() {
1782
1783                 require_once('include/bbcode.php');
1784
1785                 $a = get_app();
1786
1787                 if(! local_user() || $a->is_mobile || $a->is_tablet)
1788                         return $o;
1789
1790
1791 //              $mobile_detect = new Mobile_Detect();
1792 //              $is_mobile = $mobile_detect->isMobile() || $mobile_detect->isTablet();
1793
1794 //              if($is_mobile)
1795 //                      return $o;
1796
1797                 $bd_format = t('g A l F d') ; // 8 AM Friday January 18
1798                 $bd_short = t('F d');
1799
1800                 $r = q("SELECT `event`.* FROM `event`
1801                                 WHERE `event`.`uid` = %d AND `type` != 'birthday' AND `start` < '%s' AND `start` > '%s'
1802                                 ORDER BY `start` ASC ",
1803                                 intval(local_user()),
1804                                 dbesc(datetime_convert('UTC','UTC','now + 6 days')),
1805                                 dbesc(datetime_convert('UTC','UTC','now - 1 days'))
1806                 );
1807
1808                 if($r && count($r)) {
1809                         $now = strtotime('now');
1810                         $istoday = false;
1811                         foreach($r as $rr) {
1812                                 if(strlen($rr['name']))
1813                                         $total ++;
1814
1815                                 $strt = datetime_convert('UTC',$rr['convert'] ? $a->timezone : 'UTC',$rr['start'],'Y-m-d');
1816                                 if($strt === datetime_convert('UTC',$a->timezone,'now','Y-m-d'))
1817                                         $istoday = true;
1818                         }
1819                         $classtoday = (($istoday) ? 'event-today' : '');
1820
1821
1822                         foreach($r as &$rr) {
1823                                 if($rr['adjust'])
1824                                         $md = datetime_convert('UTC',$a->timezone,$rr['start'],'Y/m');
1825                                 else
1826                                         $md = datetime_convert('UTC','UTC',$rr['start'],'Y/m');
1827                                 $md .= "/#link-".$rr['id'];
1828
1829                                 $title = substr(strip_tags(bbcode($rr['desc'])),0,32) . '... ';
1830                                 if(! $title)
1831                                         $title = t('[No description]');
1832
1833                                 $strt = datetime_convert('UTC',$rr['convert'] ? $a->timezone : 'UTC',$rr['start']);
1834                                 $today = ((substr($strt,0,10) === datetime_convert('UTC',$a->timezone,'now','Y-m-d')) ? true : false);
1835                                 
1836                                 $rr['link'] = $md;
1837                                 $rr['title'] = $title;
1838                                 $rr['date'] = day_translate(datetime_convert('UTC', $rr['adjust'] ? $a->timezone : 'UTC', $rr['start'], $bd_format)) . (($today) ?  ' ' . t('[today]') : '');
1839                                 $rr['startime'] = $strt;
1840                                 $rr['today'] = $today;
1841                         }
1842                 }
1843
1844                 $tpl = get_markup_template("events_reminder.tpl");
1845                 return replace_macros($tpl, array(
1846                         '$baseurl' => $a->get_baseurl(),
1847                         '$classtoday' => $classtoday,
1848                         '$count' => count($r),
1849                         '$event_reminders' => t('Event Reminders'),
1850                         '$event_title' => t('Events this week:'),
1851                         '$events' => $r,
1852                 ));
1853         }
1854 }
1855
1856
1857 /**
1858  *
1859  * Wrap calls to proc_close(proc_open()) and call hook
1860  * so plugins can take part in process :)
1861  *
1862  * args:
1863  * $cmd program to run
1864  *  next args are passed as $cmd command line
1865  *
1866  * e.g.: proc_run("ls","-la","/tmp");
1867  *
1868  * $cmd and string args are surrounded with ""
1869  */
1870
1871 if(! function_exists('proc_run')) {
1872         function proc_run($cmd){
1873
1874                 $a = get_app();
1875
1876                 $args = func_get_args();
1877
1878                 $newargs = array();
1879                 if(! count($args))
1880                         return;
1881
1882                 // expand any arrays
1883
1884                 foreach($args as $arg) {
1885                         if(is_array($arg)) {
1886                                 foreach($arg as $n) {
1887                                         $newargs[] = $n;
1888                                 }
1889                         }
1890                         else
1891                                 $newargs[] = $arg;
1892                 }
1893
1894                 $args = $newargs;
1895                 
1896                 $arr = array('args' => $args, 'run_cmd' => true);
1897
1898                 call_hooks("proc_run", $arr);
1899                 if(! $arr['run_cmd'])
1900                         return;
1901
1902                 if(count($args) && $args[0] === 'php')
1903                         $args[0] = ((x($a->config,'php_path')) && (strlen($a->config['php_path'])) ? $a->config['php_path'] : 'php');
1904         
1905         // add baseurl to args. cli scripts can't construct it
1906         $args[] = $a->get_baseurl();
1907         
1908         for($x = 0; $x < count($args); $x ++)
1909                         $args[$x] = escapeshellarg($args[$x]);
1910
1911         
1912
1913                 $cmdline = implode($args," ");
1914                 if(get_config('system','proc_windows'))
1915                         proc_close(proc_open('cmd /c start /b ' . $cmdline,array(),$foo,dirname(__FILE__)));
1916                 else
1917                         proc_close(proc_open($cmdline." &",array(),$foo,dirname(__FILE__)));
1918         }
1919 }
1920
1921 if(! function_exists('current_theme')) {
1922         function current_theme(){
1923                 $app_base_themes = array('duepuntozero', 'dispy', 'quattro');
1924         
1925                 $a = get_app();
1926         
1927 //              $mobile_detect = new Mobile_Detect();
1928 //              $is_mobile = $mobile_detect->isMobile() || $mobile_detect->isTablet();
1929                 $is_mobile = $a->is_mobile || $a->is_tablet;
1930
1931                 if($is_mobile) {
1932                         if(isset($_SESSION['show-mobile']) && !$_SESSION['show-mobile']) {
1933                                 $system_theme = '';
1934                                 $theme_name = '';
1935                         }
1936                         else {
1937                                 $system_theme = ((isset($a->config['system']['mobile-theme'])) ? $a->config['system']['mobile-theme'] : '');
1938                                 $theme_name = ((isset($_SESSION) && x($_SESSION,'mobile-theme')) ? $_SESSION['mobile-theme'] : $system_theme);
1939
1940                                 if($theme_name === '---') {
1941                                         // user has selected to have the mobile theme be the same as the normal one
1942                                         $system_theme = '';
1943                                         $theme_name = '';
1944                                 }
1945                         }
1946                 }
1947                 if(!$is_mobile || ($system_theme === '' && $theme_name === '')) {
1948                         $system_theme = ((isset($a->config['system']['theme'])) ? $a->config['system']['theme'] : '');
1949                         $theme_name = ((isset($_SESSION) && x($_SESSION,'theme')) ? $_SESSION['theme'] : $system_theme);
1950                 }
1951
1952                 if($theme_name &&
1953                                 (file_exists('view/theme/' . $theme_name . '/style.css') ||
1954                                                 file_exists('view/theme/' . $theme_name . '/style.php')))
1955                         return($theme_name);
1956         
1957                 foreach($app_base_themes as $t) {
1958                         if(file_exists('view/theme/' . $t . '/style.css')||
1959                                         file_exists('view/theme/' . $t . '/style.php'))
1960                                 return($t);
1961                 }
1962         
1963                 $fallback = array_merge(glob('view/theme/*/style.css'),glob('view/theme/*/style.php'));
1964                 if(count($fallback))
1965                         return (str_replace('view/theme/','', substr($fallback[0],0,-10)));
1966         
1967         }
1968 }
1969
1970 /*
1971  * Return full URL to theme which is currently in effect.
1972 * Provide a sane default if nothing is chosen or the specified theme does not exist.
1973 */
1974 if(! function_exists('current_theme_url')) {
1975         function current_theme_url() {
1976                 global $a;
1977                 $t = current_theme();
1978                 if (file_exists('view/theme/' . $t . '/style.php'))
1979                         return($a->get_baseurl() . '/view/theme/' . $t . '/style.pcss');
1980                 return($a->get_baseurl() . '/view/theme/' . $t . '/style.css');
1981         }
1982 }
1983
1984 if(! function_exists('feed_birthday')) {
1985         function feed_birthday($uid,$tz) {
1986
1987                 /**
1988                  *
1989                  * Determine the next birthday, but only if the birthday is published
1990                  * in the default profile. We _could_ also look for a private profile that the
1991                  * recipient can see, but somebody could get mad at us if they start getting
1992                  * public birthday greetings when they haven't made this info public.
1993                  *
1994                  * Assuming we are able to publish this info, we are then going to convert
1995                  * the start time from the owner's timezone to UTC.
1996                  *
1997                  * This will potentially solve the problem found with some social networks
1998                  * where birthdays are converted to the viewer's timezone and salutations from
1999                  * elsewhere in the world show up on the wrong day. We will convert it to the
2000                  * viewer's timezone also, but first we are going to convert it from the birthday
2001                  * person's timezone to GMT - so the viewer may find the birthday starting at
2002                  * 6:00PM the day before, but that will correspond to midnight to the birthday person.
2003                  *
2004                  */
2005
2006         
2007                 $birthday = '';
2008
2009                 if(! strlen($tz))
2010                         $tz = 'UTC';
2011
2012                 $p = q("SELECT `dob` FROM `profile` WHERE `is-default` = 1 AND `uid` = %d LIMIT 1",
2013                                 intval($uid)
2014                 );
2015
2016                 if($p && count($p)) {
2017                         $tmp_dob = substr($p[0]['dob'],5);
2018                         if(intval($tmp_dob)) {
2019                                 $y = datetime_convert($tz,$tz,'now','Y');
2020                                 $bd = $y . '-' . $tmp_dob . ' 00:00';
2021                                 $t_dob = strtotime($bd);
2022                                 $now = strtotime(datetime_convert($tz,$tz,'now'));
2023                                 if($t_dob < $now)
2024                                         $bd = $y + 1 . '-' . $tmp_dob . ' 00:00';
2025                                 $birthday = datetime_convert($tz,'UTC',$bd,ATOM_TIME);
2026                         }
2027                 }
2028
2029                 return $birthday;
2030         }
2031 }
2032
2033 if(! function_exists('is_site_admin')) {
2034         function is_site_admin() {
2035                 $a = get_app();
2036
2037                 $adminlist = explode(",", str_replace(" ", "", $a->config['admin_email']));
2038
2039                 //if(local_user() && x($a->user,'email') && x($a->config,'admin_email') && ($a->user['email'] === $a->config['admin_email']))
2040                 if(local_user() && x($a->user,'email') && x($a->config,'admin_email') && in_array($a->user['email'], $adminlist))
2041                         return true;
2042                 return false;
2043         }
2044 }
2045
2046
2047 if(! function_exists('load_contact_links')) {
2048         function load_contact_links($uid) {
2049
2050                 $a = get_app();
2051
2052                 $ret = array();
2053
2054                 if(! $uid || x($a->contacts,'empty'))
2055                         return;
2056
2057                 $r = q("SELECT `id`,`network`,`url`,`thumb` FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 ",
2058                                 intval($uid)
2059                 );
2060                 if(count($r)) {
2061                         foreach($r as $rr){
2062                                 $url = normalise_link($rr['url']);
2063                                 $ret[$url] = $rr;
2064                         }
2065                 }
2066                 else
2067                         $ret['empty'] = true;
2068                 $a->contacts = $ret;
2069                 return;
2070         }
2071 }
2072
2073 if(! function_exists('profile_tabs')){
2074         function profile_tabs($a, $is_owner=False, $nickname=Null){
2075                 //echo "<pre>"; var_dump($a->user); killme();
2076         
2077                 if (is_null($nickname))
2078                         $nickname  = $a->user['nickname'];
2079                 
2080                 if(x($_GET,'tab'))
2081                         $tab = notags(trim($_GET['tab']));
2082         
2083                 $url = $a->get_baseurl() . '/profile/' . $nickname;
2084
2085                 $tabs = array(
2086                         array(
2087                                 'label'=>t('Status'),
2088                                 'url' => $url,
2089                                 'sel' => ((!isset($tab)&&$a->argv[0]=='profile')?'active':''),
2090                                 'title' => t('Status Messages and Posts'),
2091                                 'id' => 'status-tab',
2092                         ),
2093                         array(
2094                                 'label' => t('Profile'),
2095                                 'url'   => $url.'/?tab=profile',
2096                                 'sel'   => ((isset($tab) && $tab=='profile')?'active':''),
2097                                 'title' => t('Profile Details'),
2098                                 'id' => 'profile-tab',
2099                         ),
2100                         array(
2101                                 'label' => t('Photos'),
2102                                 'url'   => $a->get_baseurl() . '/photos/' . $nickname,
2103                                 'sel'   => ((!isset($tab)&&$a->argv[0]=='photos')?'active':''),
2104                                 'title' => t('Photo Albums'),
2105                                 'id' => 'photo-tab',
2106                         ),
2107                         array(
2108                                 'label' => t('Videos'),
2109                                 'url'   => $a->get_baseurl() . '/videos/' . $nickname,
2110                                 'sel'   => ((!isset($tab)&&$a->argv[0]=='videos')?'active':''),
2111                                 'title' => t('Videos'),
2112                                 'id' => 'video-tab',
2113                         ),
2114                 );
2115         
2116                 if ($is_owner){
2117                         $tabs[] = array(
2118                                 'label' => t('Events'),
2119                                 'url'   => $a->get_baseurl() . '/events',
2120                                 'sel'   =>((!isset($tab)&&$a->argv[0]=='events')?'active':''),
2121                                 'title' => t('Events and Calendar'),
2122                                 'id' => 'events-tab',
2123                         );
2124                         $tabs[] = array(
2125                                 'label' => t('Personal Notes'),
2126                                 'url'   => $a->get_baseurl() . '/notes',
2127                                 'sel'   =>((!isset($tab)&&$a->argv[0]=='notes')?'active':''),
2128                                 'title' => t('Only You Can See This'),
2129                                 'id' => 'notes-tab',
2130                         );
2131                 }
2132
2133
2134                 $arr = array('is_owner' => $is_owner, 'nickname' => $nickname, 'tab' => (($tab) ? $tab : false), 'tabs' => $tabs);
2135                 call_hooks('profile_tabs', $arr);
2136         
2137                 $tpl = get_markup_template('common_tabs.tpl');
2138
2139                 return replace_macros($tpl,array('$tabs' => $arr['tabs']));
2140         }
2141 }
2142
2143 function get_my_url() {
2144         if(x($_SESSION,'my_url'))
2145                 return $_SESSION['my_url'];
2146         return false;
2147 }
2148
2149 function zrl_init(&$a) {
2150         $tmp_str = get_my_url();
2151         if(validate_url($tmp_str)) {
2152                 proc_run('php','include/gprobe.php',bin2hex($tmp_str));
2153                 $arr = array('zrl' => $tmp_str, 'url' => $a->cmd);
2154                 call_hooks('zrl_init',$arr);
2155         }
2156 }
2157
2158 function zrl($s,$force = false) {
2159         if(! strlen($s))
2160                 return $s;
2161         if((! strpos($s,'/profile/')) && (! $force))
2162                 return $s;
2163         if($force && substr($s,-1,1) !== '/')
2164                 $s = $s . '/';
2165         $achar = strpos($s,'?') ? '&' : '?';
2166         $mine = get_my_url();
2167         if($mine and ! link_compare($mine,$s))
2168                 return $s . $achar . 'zrl=' . urlencode($mine);
2169         return $s;
2170 }
2171
2172 /**
2173 * returns querystring as string from a mapped array
2174 *
2175 * @param params Array 
2176 * @return string
2177 */
2178 function build_querystring($params, $name=null) { 
2179     $ret = ""; 
2180     foreach($params as $key=>$val) {
2181         if(is_array($val)) { 
2182             if($name==null) {
2183                 $ret .= build_querystring($val, $key); 
2184             } else {
2185                 $ret .= build_querystring($val, $name."[$key]");    
2186             }
2187         } else {
2188             $val = urlencode($val);
2189             if($name!=null) {
2190                 $ret.=$name."[$key]"."=$val&"; 
2191             } else {
2192                 $ret.= "$key=$val&"; 
2193             }
2194         } 
2195     } 
2196     return $ret;    
2197 }
2198
2199 function explode_querystring($query) {
2200         $arg_st = strpos($query, '?');
2201         if($arg_st !== false) {
2202                 $base = substr($query, 0, $arg_st);
2203                 $arg_st += 1;
2204         }
2205         else {
2206                 $base = '';
2207                 $arg_st = 0;
2208         }
2209
2210         $args = explode('&', substr($query, $arg_st));
2211         foreach($args as $k=>$arg) {
2212                 if($arg === '')
2213                         unset($args[$k]);
2214         }
2215         $args = array_values($args);
2216
2217         if(!$base) {
2218                 $base = $args[0];
2219                 unset($args[0]);
2220                 $args = array_values($args);
2221         }
2222
2223         return array(
2224                 'base' => $base,
2225                 'args' => $args,
2226         );
2227 }
2228
2229 /**
2230 * Returns the complete URL of the current page, e.g.: http(s)://something.com/network
2231 *
2232 * Taken from http://webcheatsheet.com/php/get_current_page_url.php
2233 */
2234 function curPageURL() {
2235         $pageURL = 'http';
2236         if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
2237         $pageURL .= "://";
2238         if ($_SERVER["SERVER_PORT"] != "80" && $_SERVER["SERVER_PORT"] != "443") {
2239                 $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
2240         } else {
2241                 $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
2242         }
2243         return $pageURL;
2244 }
2245
2246 function random_digits($digits) {
2247         $rn = '';
2248         for($i = 0; $i < $digits; $i++) {
2249                 $rn .= rand(0,9);
2250         }
2251         return $rn;
2252 }
2253
2254 function get_cachefile($file, $writemode = true) {
2255         $cache = get_itemcachepath();
2256
2257         if ((! $cache) || (! is_dir($cache)))
2258                 return("");
2259
2260         $subfolder = $cache."/".substr($file, 0, 2);
2261
2262         $cachepath = $subfolder."/".$file;
2263
2264         if ($writemode) {
2265                 if (!is_dir($subfolder)) {
2266                         mkdir($subfolder);
2267                         chmod($subfolder, 0777);
2268                 }
2269         }
2270
2271         return($cachepath);
2272 }
2273
2274 function clear_cache($basepath = "", $path = "") {
2275         if ($path == "") {
2276                 $basepath = get_itemcachepath();
2277                 $path = $basepath;
2278         }
2279
2280         if (($path == "") OR (!is_dir($path)))
2281                 return;
2282
2283         if (substr(realpath($path), 0, strlen($basepath)) != $basepath)
2284                 return;
2285
2286         $cachetime = (int)get_config('system','itemcache_duration');
2287         if ($cachetime == 0)
2288                 $cachetime = 86400;
2289
2290         if (is_writable($path)){
2291         if ($dh = opendir($path)) {
2292                 while (($file = readdir($dh)) !== false) {
2293                         $fullpath = $path."/".$file;
2294                         if ((filetype($fullpath) == "dir") and ($file != ".") and ($file != ".."))
2295                                 clear_cache($basepath, $fullpath);
2296                         if ((filetype($fullpath) == "file") and (filectime($fullpath) < (time() - $cachetime)))
2297                                 unlink($fullpath);
2298                 }
2299                 closedir($dh);
2300         }
2301         }
2302 }
2303
2304 function get_itemcachepath() {
2305         // Checking, if the cache is deactivated
2306         $cachetime = (int)get_config('system','itemcache_duration');
2307         if ($cachetime < 0)
2308                 return "";
2309
2310         $itemcache = get_config('system','itemcache');
2311         if (($itemcache != "") AND is_dir($itemcache) AND is_writable($itemcache))
2312                 return($itemcache);
2313
2314         $temppath = get_temppath();
2315
2316         if ($temppath != "") {
2317                 $itemcache = $temppath."/itemcache";
2318                 mkdir($itemcache);
2319
2320                 if (is_dir($itemcache) AND is_writable($itemcache)) {
2321                         set_config("system", "itemcache", $itemcache);
2322                         return($itemcache);
2323                 }
2324         }
2325         return "";
2326 }
2327
2328 function get_lockpath() {
2329         $lockpath = get_config('system','lockpath');
2330         if (($lockpath != "") AND is_dir($lockpath) AND is_writable($lockpath))
2331                 return($lockpath);
2332
2333         $temppath = get_temppath();
2334
2335         if ($temppath != "") {
2336                 $lockpath = $temppath."/lock";
2337                 mkdir($lockpath);
2338
2339                 if (is_dir($lockpath) AND is_writable($lockpath)) {
2340                         set_config("system", "lockpath", $lockpath);
2341                         return($lockpath);
2342                 }
2343         }
2344         return "";
2345 }
2346
2347 function get_temppath() {
2348         $temppath = get_config("system","temppath");
2349         if (($temppath != "") AND is_dir($temppath) AND is_writable($temppath))
2350                 return($temppath);
2351
2352         $temppath = sys_get_temp_dir();
2353         if (($temppath != "") AND is_dir($temppath) AND is_writable($temppath)) {
2354                 set_config("system", "temppath", $temppath);
2355                 return($temppath);
2356         }
2357
2358         return("");
2359 }
2360
2361 function set_template_engine(&$a, $engine = 'internal') {
2362 // This function is no longer necessary, but keep it as a wrapper to the class method
2363 // to avoid breaking themes again unnecessarily
2364
2365         $a->set_template_engine($engine);
2366 }
2367
2368 if(!function_exists('exif_imagetype')) {
2369         function exif_imagetype($file) {
2370                 $size = getimagesize($file);
2371                 return($size[2]);
2372         }
2373 }