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