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