]> git.mxchange.org Git - friendica.git/blob - boot.php
Merge pull request #1698 from rabuzarus/identity
[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.0' );
21 define ( 'DFRN_PROTOCOL_VERSION',  '2.23'    );
22 define ( 'DB_UPDATE_VERSION',      1185      );
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
278 define ( 'ACTIVITY_POKE',        NAMESPACE_ZOT . '/activity/poke' );
279 define ( 'ACTIVITY_MOOD',        NAMESPACE_ZOT . '/activity/mood' );
280
281 define ( 'ACTIVITY_OBJ_BOOKMARK', NAMESPACE_ACTIVITY_SCHEMA . 'bookmark' );
282 define ( 'ACTIVITY_OBJ_COMMENT', NAMESPACE_ACTIVITY_SCHEMA . 'comment' );
283 define ( 'ACTIVITY_OBJ_NOTE',    NAMESPACE_ACTIVITY_SCHEMA . 'note' );
284 define ( 'ACTIVITY_OBJ_PERSON',  NAMESPACE_ACTIVITY_SCHEMA . 'person' );
285 define ( 'ACTIVITY_OBJ_IMAGE',   NAMESPACE_ACTIVITY_SCHEMA . 'image' );
286 define ( 'ACTIVITY_OBJ_PHOTO',   NAMESPACE_ACTIVITY_SCHEMA . 'photo' );
287 define ( 'ACTIVITY_OBJ_VIDEO',   NAMESPACE_ACTIVITY_SCHEMA . 'video' );
288 define ( 'ACTIVITY_OBJ_P_PHOTO', NAMESPACE_ACTIVITY_SCHEMA . 'profile-photo' );
289 define ( 'ACTIVITY_OBJ_ALBUM',   NAMESPACE_ACTIVITY_SCHEMA . 'photo-album' );
290 define ( 'ACTIVITY_OBJ_EVENT',   NAMESPACE_ACTIVITY_SCHEMA . 'event' );
291 define ( 'ACTIVITY_OBJ_GROUP',   NAMESPACE_ACTIVITY_SCHEMA . 'group' );
292 define ( 'ACTIVITY_OBJ_TAGTERM', NAMESPACE_DFRN            . '/tagterm' );
293 define ( 'ACTIVITY_OBJ_PROFILE', NAMESPACE_DFRN            . '/profile' );
294 define ( 'ACTIVITY_OBJ_QUESTION', 'http://activityschema.org/object/question' );
295
296 /**
297  * item weight for query ordering
298  */
299
300 define ( 'GRAVITY_PARENT',       0);
301 define ( 'GRAVITY_LIKE',         3);
302 define ( 'GRAVITY_COMMENT',      6);
303
304 /**
305  *
306  * Reverse the effect of magic_quotes_gpc if it is enabled.
307  * Please disable magic_quotes_gpc so we don't have to do this.
308  * See http://php.net/manual/en/security.magicquotes.disabling.php
309  *
310  */
311
312 function startup() {
313
314         error_reporting(E_ERROR | E_WARNING | E_PARSE);
315
316         set_time_limit(0);
317
318         // This has to be quite large to deal with embedded private photos
319         ini_set('pcre.backtrack_limit', 500000);
320
321
322         if (get_magic_quotes_gpc()) {
323                 $process = array(&$_GET, &$_POST, &$_COOKIE, &$_REQUEST);
324                 while (list($key, $val) = each($process)) {
325                         foreach ($val as $k => $v) {
326                                 unset($process[$key][$k]);
327                                 if (is_array($v)) {
328                                         $process[$key][stripslashes($k)] = $v;
329                                         $process[] = &$process[$key][stripslashes($k)];
330                                 } else {
331                                         $process[$key][stripslashes($k)] = stripslashes($v);
332                                 }
333                         }
334                 }
335                 unset($process);
336         }
337
338 }
339
340 /**
341  *
342  * class: App
343  *
344  * Our main application structure for the life of this page
345  * Primarily deals with the URL that got us here
346  * and tries to make some sense of it, and
347  * stores our page contents and config storage
348  * and anything else that might need to be passed around
349  * before we spit the page out.
350  *
351  */
352
353 if(! class_exists('App')) {
354         class App {
355
356                 public  $module_loaded = false;
357                 public  $query_string;
358                 public  $config;
359                 public  $page;
360                 public  $profile;
361                 public  $user;
362                 public  $cid;
363                 public  $contact;
364                 public  $contacts;
365                 public  $page_contact;
366                 public  $content;
367                 public  $data = array();
368                 public  $error = false;
369                 public  $cmd;
370                 public  $argv;
371                 public  $argc;
372                 public  $module;
373                 public  $pager;
374                 public  $strings;
375                 public  $path;
376                 public  $hooks;
377                 public  $timezone;
378                 public  $interactive = true;
379                 public  $plugins;
380                 public  $apps = array();
381                 public  $identities;
382                 public  $is_mobile;
383                 public  $is_tablet;
384                 public  $is_friendica_app;
385                 public  $performance = array();
386
387                 public $nav_sel;
388
389                 public $category;
390
391
392                 // Allow themes to control internal parameters
393                 // by changing App values in theme.php
394
395                 public  $sourcename = '';
396                 public  $videowidth = 425;
397                 public  $videoheight = 350;
398                 public  $force_max_items = 0;
399                 public  $theme_thread_allow = true;
400
401                 // An array for all theme-controllable parameters
402                 // Mostly unimplemented yet. Only options 'stylesheet' and
403                 // beyond are used.
404
405                 public  $theme = array(
406                         'sourcename' => '',
407                         'videowidth' => 425,
408                         'videoheight' => 350,
409                         'force_max_items' => 0,
410                         'thread_allow' => true,
411                         'stylesheet' => '',
412                         'template_engine' => 'smarty3',
413                 );
414
415                 // array of registered template engines ('name'=>'class name')
416                 public $template_engines = array();
417                 // array of instanced template engines ('name'=>'instance')
418                 public $template_engine_instance = array();
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                         // Friendica-Client
600                         $this->is_friendica_app = ($_SERVER['HTTP_USER_AGENT'] == "Apache-HttpClient/UNAVAILABLE (java 1.4)");
601
602                         /**
603                          * register template engines
604                          */
605                         $dc = get_declared_classes();
606                         foreach ($dc as $k) {
607                                 if (in_array("ITemplateEngine", class_implements($k))){
608                                         $this->register_template_engine($k);
609                                 }
610                         }
611
612                 }
613
614                 function get_basepath() {
615
616                         $basepath = get_config("system", "basepath");
617
618                         if ($basepath == "")
619                                 $basepath = $_SERVER["DOCUMENT_ROOT"];
620
621                         if ($basepath == "")
622                                 $basepath = $_SERVER["PWD"];
623
624                         return($basepath);
625                 }
626
627                 function get_scheme() {
628                         return($this->scheme);
629                 }
630
631                 function get_baseurl($ssl = false) {
632
633                         $scheme = $this->scheme;
634
635                         if((x($this->config,'system')) && (x($this->config['system'],'ssl_policy'))) {
636                                 if(intval($this->config['system']['ssl_policy']) === intval(SSL_POLICY_FULL))
637                                         $scheme = 'https';
638
639                                 //      Basically, we have $ssl = true on any links which can only be seen by a logged in user
640                                 //      (and also the login link). Anything seen by an outsider will have it turned off.
641
642                                 if($this->config['system']['ssl_policy'] == SSL_POLICY_SELFSIGN) {
643                                         if($ssl)
644                                                 $scheme = 'https';
645                                         else
646                                                 $scheme = 'http';
647                                 }
648                         }
649
650                         if (get_config('config','hostname') != "")
651                                 $this->hostname = get_config('config','hostname');
652
653                         $this->baseurl = $scheme . "://" . $this->hostname . ((isset($this->path) && strlen($this->path)) ? '/' . $this->path : '' );
654                         return $this->baseurl;
655                 }
656
657                 function set_baseurl($url) {
658                         $parsed = @parse_url($url);
659
660                         $this->baseurl = $url;
661
662                         if($parsed) {
663                                 $this->scheme = $parsed['scheme'];
664
665                                 $hostname = $parsed['host'];
666                                 if(x($parsed,'port'))
667                                         $hostname .= ':' . $parsed['port'];
668                                 if(x($parsed,'path'))
669                                         $this->path = trim($parsed['path'],'\\/');
670
671                                 if (file_exists(".htpreconfig.php"))
672                                         @include(".htpreconfig.php");
673
674                                 if (get_config('config','hostname') != "")
675                                         $this->hostname = get_config('config','hostname');
676
677                                 if (!isset($this->hostname) OR ($this->hostname == ""))
678                                         $this->hostname = $hostname;
679                         }
680
681                 }
682
683                 function get_hostname() {
684                         if (get_config('config','hostname') != "")
685                                 $this->hostname = get_config('config','hostname');
686
687                         return $this->hostname;
688                 }
689
690                 function set_hostname($h) {
691                         $this->hostname = $h;
692                 }
693
694                 function set_path($p) {
695                         $this->path = trim(trim($p),'/');
696                 }
697
698                 function get_path() {
699                         return $this->path;
700                 }
701
702                 function set_pager_total($n) {
703                         $this->pager['total'] = intval($n);
704                 }
705
706                 function set_pager_itemspage($n) {
707                         $this->pager['itemspage'] = ((intval($n) > 0) ? intval($n) : 0);
708                         $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
709                 }
710
711                 function set_pager_page($n) {
712                         $this->pager['page'] = $n;
713                         $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
714                 }
715
716                 function init_pagehead() {
717                         $interval = ((local_user()) ? get_pconfig(local_user(),'system','update_interval') : 40000);
718                         if($interval < 10000)
719                                 $interval = 40000;
720
721                         $this->page['title'] = $this->config['sitename'];
722
723                         /* put the head template at the beginning of page['htmlhead']
724                          * since the code added by the modules frequently depends on it
725                          * being first
726                          */
727                         if(!isset($this->page['htmlhead']))
728                                 $this->page['htmlhead'] = '';
729
730                         // If we're using Smarty, then doing replace_macros() will replace
731                         // any unrecognized variables with a blank string. Since we delay
732                         // replacing $stylesheet until later, we need to replace it now
733                         // with another variable name
734                         if($this->theme['template_engine'] === 'smarty3')
735                                 $stylesheet = $this->get_template_ldelim('smarty3') . '$stylesheet' . $this->get_template_rdelim('smarty3');
736                         else
737                                 $stylesheet = '$stylesheet';
738
739                         $shortcut_icon = get_config("system", "shortcut_icon");
740                         if ($shortcut_icon == "")
741                                 $shortcut_icon = $this->get_baseurl()."/images/friendica-32.png";
742
743                         $touch_icon = get_config("system", "touch_icon");
744                         if ($touch_icon == "")
745                                 $touch_icon = $this->get_baseurl()."/images/friendica-128.png";
746
747                         $tpl = get_markup_template('head.tpl');
748                         $this->page['htmlhead'] = replace_macros($tpl,array(
749                                 '$baseurl' => $this->get_baseurl(), // FIXME for z_path!!!!
750                                 '$local_user' => local_user(),
751                                 '$generator' => 'Friendica' . ' ' . FRIENDICA_VERSION,
752                                 '$delitem' => t('Delete this item?'),
753                                 '$comment' => t('Comment'),
754                                 '$showmore' => t('show more'),
755                                 '$showfewer' => t('show fewer'),
756                                 '$update_interval' => $interval,
757                                 '$shortcut_icon' => $shortcut_icon,
758                                 '$touch_icon' => $touch_icon,
759                                 '$stylesheet' => $stylesheet
760                         )) . $this->page['htmlhead'];
761                 }
762
763                 function init_page_end() {
764                         if(!isset($this->page['end']))
765                                 $this->page['end'] = '';
766                         $tpl = get_markup_template('end.tpl');
767                         $this->page['end'] = replace_macros($tpl,array(
768                                 '$baseurl' => $this->get_baseurl() // FIXME for z_path!!!!
769                         )) . $this->page['end'];
770                 }
771
772                 function set_curl_code($code) {
773                         $this->curl_code = $code;
774                 }
775
776                 function get_curl_code() {
777                         return $this->curl_code;
778                 }
779
780                 function set_curl_content_type($content_type) {
781                         $this->curl_content_type = $content_type;
782                 }
783
784                 function get_curl_content_type() {
785                         return $this->curl_content_type;
786                 }
787
788                 function set_curl_headers($headers) {
789                         $this->curl_headers = $headers;
790                 }
791
792                 function get_curl_headers() {
793                         return $this->curl_headers;
794                 }
795
796                 function get_cached_avatar_image($avatar_image){
797                         if($this->cached_profile_image[$avatar_image])
798                                 return $this->cached_profile_image[$avatar_image];
799
800                         $path_parts = explode("/",$avatar_image);
801                         $common_filename = $path_parts[count($path_parts)-1];
802
803                         if($this->cached_profile_picdate[$common_filename]){
804                                 $this->cached_profile_image[$avatar_image] = $avatar_image . $this->cached_profile_picdate[$common_filename];
805                         } else {
806                                 $r = q("SELECT `contact`.`avatar-date` AS picdate FROM `contact` WHERE `contact`.`thumb` like '%%/%s'",
807                                         $common_filename);
808                                 if(! count($r)){
809                                         $this->cached_profile_image[$avatar_image] = $avatar_image;
810                                 } else {
811                                         $this->cached_profile_picdate[$common_filename] = "?rev=".urlencode($r[0]['picdate']);
812                                         $this->cached_profile_image[$avatar_image] = $avatar_image.$this->cached_profile_picdate[$common_filename];
813                                 }
814                         }
815                         return $this->cached_profile_image[$avatar_image];
816                 }
817
818
819                 /**
820                  * register template engine class
821                  * if $name is "", is used class static property $class::$name
822                  * @param string $class
823                  * @param string $name
824                  */
825                 function register_template_engine($class, $name = '') {
826                         if ($name===""){
827                                 $v = get_class_vars( $class );
828                                 if(x($v,"name")) $name = $v['name'];
829                         }
830                         if ($name===""){
831                                 echo "template engine <tt>$class</tt> cannot be registered without a name.\n";
832                                 killme();
833                         }
834                         $this->template_engines[$name] = $class;
835                 }
836
837                 /**
838                  * return template engine instance. If $name is not defined,
839                  * return engine defined by theme, or default
840                  *
841                  * @param strin $name Template engine name
842                  * @return object Template Engine instance
843                  */
844                 function template_engine($name = ''){
845                         if ($name!=="") {
846                                 $template_engine = $name;
847                         } else {
848                                 $template_engine = 'smarty3';
849                                 if (x($this->theme, 'template_engine')) {
850                                         $template_engine = $this->theme['template_engine'];
851                                 }
852                         }
853
854                         if (isset($this->template_engines[$template_engine])){
855                                 if(isset($this->template_engine_instance[$template_engine])){
856                                         return $this->template_engine_instance[$template_engine];
857                                 } else {
858                                         $class = $this->template_engines[$template_engine];
859                                         $obj = new $class;
860                                         $this->template_engine_instance[$template_engine] = $obj;
861                                         return $obj;
862                                 }
863                         }
864
865                         echo "template engine <tt>$template_engine</tt> is not registered!\n"; killme();
866                 }
867
868                 function get_template_engine() {
869                         return $this->theme['template_engine'];
870                 }
871
872                 function set_template_engine($engine = 'smarty3') {
873                         $this->theme['template_engine'] = $engine;
874                         /*
875                         $this->theme['template_engine'] = 'smarty3';
876
877                         switch($engine) {
878                                 case 'smarty3':
879                                         if(is_writable('view/smarty3/'))
880                                                 $this->theme['template_engine'] = 'smarty3';
881                                         break;
882                                 default:
883                                         break;
884                         }
885                         */
886                 }
887
888                 function get_template_ldelim($engine = 'smarty3') {
889                         return $this->ldelim[$engine];
890                 }
891
892                 function get_template_rdelim($engine = 'smarty3') {
893                         return $this->rdelim[$engine];
894                 }
895
896                 function save_timestamp($stamp, $value) {
897                         $duration = (float)(microtime(true)-$stamp);
898
899                         $this->performance[$value] += (float)$duration;
900                         $this->performance["marktime"] += (float)$duration;
901                 }
902
903                 function mark_timestamp($mark) {
904                         //$this->performance["markstart"] -= microtime(true) - $this->performance["marktime"];
905                         $this->performance["markstart"] = microtime(true) - $this->performance["markstart"] - $this->performance["marktime"];
906                 }
907
908                 function get_useragent() {
909                         return(FRIENDICA_PLATFORM." '".FRIENDICA_CODENAME."' ".FRIENDICA_VERSION."-".DB_UPDATE_VERSION."; ".$this->get_baseurl());
910                 }
911
912                 function is_friendica_app() {
913                         return($this->is_friendica_app);
914                 }
915
916         }
917 }
918
919 // retrieve the App structure
920 // useful in functions which require it but don't get it passed to them
921
922 if(! function_exists('get_app')) {
923         function get_app() {
924                 global $a;
925                 return $a;
926         }
927 };
928
929
930 // Multi-purpose function to check variable state.
931 // Usage: x($var) or $x($array,'key')
932 // returns false if variable/key is not set
933 // if variable is set, returns 1 if has 'non-zero' value, otherwise returns 0.
934 // e.g. x('') or x(0) returns 0;
935
936 if(! function_exists('x')) {
937         function x($s,$k = NULL) {
938                 if($k != NULL) {
939                         if((is_array($s)) && (array_key_exists($k,$s))) {
940                                 if($s[$k])
941                                         return (int) 1;
942                                 return (int) 0;
943                 }
944                         return false;
945                 }
946                 else {
947                         if(isset($s)) {
948                                 if($s) {
949                                         return (int) 1;
950                                 }
951                                 return (int) 0;
952                         }
953                         return false;
954                 }
955         }
956 }
957
958 // called from db initialisation if db is dead.
959
960 if(! function_exists('system_unavailable')) {
961         function system_unavailable() {
962                 include('system_unavailable.php');
963                 system_down();
964                 killme();
965         }
966 }
967
968
969
970 function clean_urls() {
971         global $a;
972         //      if($a->config['system']['clean_urls'])
973         return true;
974         //      return false;
975 }
976
977 function z_path() {
978         global $a;
979         $base = $a->get_baseurl();
980         if(! clean_urls())
981                 $base .= '/?q=';
982         return $base;
983 }
984
985 function z_root() {
986         global $a;
987         return $a->get_baseurl();
988 }
989
990 function absurl($path) {
991         if(strpos($path,'/') === 0)
992                 return z_path() . $path;
993         return $path;
994 }
995
996 function is_ajax() {
997         return (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');
998 }
999
1000 function check_db() {
1001
1002         $build = get_config('system','build');
1003         if(! x($build)) {
1004                 set_config('system','build',DB_UPDATE_VERSION);
1005                 $build = DB_UPDATE_VERSION;
1006         }
1007         if($build != DB_UPDATE_VERSION)
1008                 proc_run('php', 'include/dbupdate.php');
1009
1010 }
1011
1012
1013
1014
1015 // Sets the base url for use in cmdline programs which don't have
1016 // $_SERVER variables
1017
1018 if(! function_exists('check_url')) {
1019         function check_url(&$a) {
1020
1021                 $url = get_config('system','url');
1022
1023                 // if the url isn't set or the stored url is radically different
1024                 // than the currently visited url, store the current value accordingly.
1025                 // "Radically different" ignores common variations such as http vs https
1026                 // and www.example.com vs example.com.
1027                 // We will only change the url to an ip address if there is no existing setting
1028
1029                 if(! x($url))
1030                         $url = set_config('system','url',$a->get_baseurl());
1031                 if((! link_compare($url,$a->get_baseurl())) && (! preg_match("/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/",$a->get_hostname)))
1032                         $url = set_config('system','url',$a->get_baseurl());
1033
1034                 return;
1035         }
1036 }
1037
1038
1039 // Automatic database updates
1040
1041 if(! function_exists('update_db')) {
1042         function update_db(&$a) {
1043                 $build = get_config('system','build');
1044                 if(! x($build))
1045                         $build = set_config('system','build',DB_UPDATE_VERSION);
1046
1047                 if($build != DB_UPDATE_VERSION) {
1048                         $stored = intval($build);
1049                         $current = intval(DB_UPDATE_VERSION);
1050                         if($stored < $current) {
1051                                 load_config('database');
1052
1053                                 // We're reporting a different version than what is currently installed.
1054                                 // Run any existing update scripts to bring the database up to current.
1055
1056                                 // make sure that boot.php and update.php are the same release, we might be
1057                                 // updating right this very second and the correct version of the update.php
1058                                 // file may not be here yet. This can happen on a very busy site.
1059
1060                                 if(DB_UPDATE_VERSION == UPDATE_VERSION) {
1061                                         // Compare the current structure with the defined structure
1062
1063                                         $t = get_config('database','dbupdate_'.DB_UPDATE_VERSION);
1064                                         if($t !== false)
1065                                                 return;
1066
1067                                         set_config('database','dbupdate_'.DB_UPDATE_VERSION, time());
1068
1069                                         // run old update routine (wich could modify the schema and
1070                                         // conflits with new routine)
1071                                         for ($x = $stored; $x < NEW_UPDATE_ROUTINE_VERSION; $x++) {
1072                                                 $r = run_update_function($x);
1073                                                 if (!$r) break;
1074                                         }
1075                                         if ($stored < NEW_UPDATE_ROUTINE_VERSION) $stored = NEW_UPDATE_ROUTINE_VERSION;
1076
1077
1078                                         // run new update routine
1079                                         // it update the structure in one call
1080                                         $retval = update_structure(false, true);
1081                                         if($retval) {
1082                                                 update_fail(
1083                                                         DB_UPDATE_VERSION,
1084                                                         $retval
1085                                                 );
1086                                                 return;
1087                                         } else {
1088                                                 set_config('database','dbupdate_'.DB_UPDATE_VERSION, 'success');
1089                                         }
1090
1091                                         // run any left update_nnnn functions in update.php
1092                                         for($x = $stored; $x < $current; $x ++) {
1093                                                 $r = run_update_function($x);
1094                                                 if (!$r) break;
1095                                         }
1096                                 }
1097                         }
1098                 }
1099
1100                 return;
1101         }
1102 }
1103 if(!function_exists('run_update_function')){
1104         function run_update_function($x) {
1105                 if(function_exists('update_' . $x)) {
1106
1107                         // There could be a lot of processes running or about to run.
1108                         // We want exactly one process to run the update command.
1109                         // So store the fact that we're taking responsibility
1110                         // after first checking to see if somebody else already has.
1111
1112                         // If the update fails or times-out completely you may need to
1113                         // delete the config entry to try again.
1114
1115                         $t = get_config('database','update_' . $x);
1116                         if($t !== false)
1117                                 return false;
1118                         set_config('database','update_' . $x, time());
1119
1120                         // call the specific update
1121
1122                         $func = 'update_' . $x;
1123                         $retval = $func();
1124
1125                         if($retval) {
1126                                 //send the administrator an e-mail
1127                                 update_fail(
1128                                         $x,
1129                                         sprintf(t('Update %s failed. See error logs.'), $x)
1130                                 );
1131                                 return false;
1132                         } else {
1133                                 set_config('database','update_' . $x, 'success');
1134                                 set_config('system','build', $x + 1);
1135                                 return true;
1136                         }
1137                 } else {
1138                         set_config('database','update_' . $x, 'success');
1139                         set_config('system','build', $x + 1);
1140                         return true;
1141                 }
1142                 return true;
1143         }
1144 }
1145
1146
1147 if(! function_exists('check_plugins')) {
1148         function check_plugins(&$a) {
1149
1150                 /**
1151                  *
1152                  * Synchronise plugins:
1153                  *
1154                  * $a->config['system']['addon'] contains a comma-separated list of names
1155                  * of plugins/addons which are used on this system.
1156                  * Go through the database list of already installed addons, and if we have
1157                  * an entry, but it isn't in the config list, call the uninstall procedure
1158                  * and mark it uninstalled in the database (for now we'll remove it).
1159                  * Then go through the config list and if we have a plugin that isn't installed,
1160                  * call the install procedure and add it to the database.
1161                  *
1162                  */
1163
1164                 $r = q("SELECT * FROM `addon` WHERE `installed` = 1");
1165                 if(count($r))
1166                         $installed = $r;
1167                 else
1168                         $installed = array();
1169
1170                 $plugins = get_config('system','addon');
1171                 $plugins_arr = array();
1172
1173                 if($plugins)
1174                         $plugins_arr = explode(',',str_replace(' ', '',$plugins));
1175
1176                 $a->plugins = $plugins_arr;
1177
1178                 $installed_arr = array();
1179
1180                 if(count($installed)) {
1181                         foreach($installed as $i) {
1182                                 if(! in_array($i['name'],$plugins_arr)) {
1183                                         uninstall_plugin($i['name']);
1184                                 }
1185                                 else {
1186                                         $installed_arr[] = $i['name'];
1187                                 }
1188                         }
1189                 }
1190
1191                 if(count($plugins_arr)) {
1192                         foreach($plugins_arr as $p) {
1193                                 if(! in_array($p,$installed_arr)) {
1194                                         install_plugin($p);
1195                                 }
1196                         }
1197                 }
1198
1199
1200                 load_hooks();
1201
1202                 return;
1203         }
1204 }
1205
1206 function get_guid($size=16, $prefix = "") {
1207
1208         if ($prefix == "") {
1209                 $a = get_app();
1210                 $prefix = hash("crc32", $a->get_hostname());
1211         }
1212
1213         while (strlen($prefix) < ($size - 13))
1214                 $prefix .= mt_rand();
1215
1216         if ($size >= 24) {
1217                 $prefix = substr($prefix, 0, $size - 22);
1218                 return(str_replace(".", "", uniqid($prefix, true)));
1219         } else {
1220                 $prefix = substr($prefix, 0, $size - 13);
1221                 return(uniqid($prefix));
1222         }
1223 }
1224
1225 // wrapper for adding a login box. If $register == true provide a registration
1226 // link. This will most always depend on the value of $a->config['register_policy'].
1227 // returns the complete html for inserting into the page
1228
1229 if(! function_exists('login')) {
1230         function login($register = false, $hiddens=false) {
1231                 $a = get_app();
1232                 $o = "";
1233                 $reg = false;
1234                 if ($register) {
1235                         $reg = array(
1236                                 'title' => t('Create a New Account'),
1237                                 'desc' => t('Register')
1238                         );
1239                 }
1240
1241                 $noid = get_config('system','no_openid');
1242
1243                 $dest_url = $a->get_baseurl(true) . '/' . $a->query_string;
1244
1245                 if(local_user()) {
1246                         $tpl = get_markup_template("logout.tpl");
1247                 }
1248                 else {
1249                         $a->page['htmlhead'] .= replace_macros(get_markup_template("login_head.tpl"),array(
1250                                 '$baseurl'              => $a->get_baseurl(true)
1251                         ));
1252
1253                         $tpl = get_markup_template("login.tpl");
1254                         $_SESSION['return_url'] = $a->query_string;
1255                         $a->module = 'login';
1256                 }
1257
1258                 $o .= replace_macros($tpl, array(
1259
1260                         '$dest_url'     => $dest_url,
1261                         '$logout'       => t('Logout'),
1262                         '$login'        => t('Login'),
1263
1264                         '$lname'                => array('username', t('Nickname or Email address: ') , '', ''),
1265                         '$lpassword'    => array('password', t('Password: '), '', ''),
1266                         '$lremember'    => array('remember', t('Remember me'), 0,  ''),
1267
1268                         '$openid'               => !$noid,
1269                         '$lopenid'      => array('openid_url', t('Or login using OpenID: '),'',''),
1270
1271                         '$hiddens'      => $hiddens,
1272
1273                         '$register'     => $reg,
1274
1275                         '$lostpass'     => t('Forgot your password?'),
1276                         '$lostlink'     => t('Password Reset'),
1277
1278                         '$tostitle'     => t('Website Terms of Service'),
1279                         '$toslink'      => t('terms of service'),
1280
1281                         '$privacytitle' => t('Website Privacy Policy'),
1282                         '$privacylink'  => t('privacy policy'),
1283
1284                 ));
1285
1286                 call_hooks('login_hook',$o);
1287
1288                 return $o;
1289         }
1290 }
1291
1292 // Used to end the current process, after saving session state.
1293
1294 if(! function_exists('killme')) {
1295         function killme() {
1296                 session_write_close();
1297                 exit;
1298         }
1299 }
1300
1301 // redirect to another URL and terminate this process.
1302
1303 if(! function_exists('goaway')) {
1304         function goaway($s) {
1305                 header("Location: $s");
1306                 killme();
1307         }
1308 }
1309
1310
1311 // Returns the uid of locally logged in user or false.
1312
1313 if(! function_exists('local_user')) {
1314         function local_user() {
1315                 if((x($_SESSION,'authenticated')) && (x($_SESSION,'uid')))
1316                         return intval($_SESSION['uid']);
1317                 return false;
1318         }
1319 }
1320
1321 // Returns contact id of authenticated site visitor or false
1322
1323 if(! function_exists('remote_user')) {
1324         function remote_user() {
1325                 if((x($_SESSION,'authenticated')) && (x($_SESSION,'visitor_id')))
1326                         return intval($_SESSION['visitor_id']);
1327                 return false;
1328         }
1329 }
1330
1331 // contents of $s are displayed prominently on the page the next time
1332 // a page is loaded. Usually used for errors or alerts.
1333
1334 if(! function_exists('notice')) {
1335         /**
1336          * Show an error message to user.
1337          *
1338          * This function save text in session, to be shown to the user at next page load
1339          *
1340          * @param string $s - Text of notice
1341          */
1342         function notice($s) {
1343                 $a = get_app();
1344                 if(! x($_SESSION,'sysmsg'))     $_SESSION['sysmsg'] = array();
1345                 if($a->interactive)
1346                         $_SESSION['sysmsg'][] = $s;
1347         }
1348 }
1349 if(! function_exists('info')) {
1350         /**
1351          * Show an info message to user.
1352          *
1353          * This function save text in session, to be shown to the user at next page load
1354          *
1355          * @param string $s - Text of notice
1356          */
1357         function info($s) {
1358                 $a = get_app();
1359
1360                 if (local_user() AND get_pconfig(local_user(),'system','ignore_info'))
1361                         return;
1362
1363                 if(! x($_SESSION,'sysmsg_info')) $_SESSION['sysmsg_info'] = array();
1364                 if($a->interactive)
1365                         $_SESSION['sysmsg_info'][] = $s;
1366         }
1367 }
1368
1369
1370 // wrapper around config to limit the text length of an incoming message
1371
1372 if(! function_exists('get_max_import_size')) {
1373         function get_max_import_size() {
1374                 global $a;
1375                 return ((x($a->config,'max_import_size')) ? $a->config['max_import_size'] : 0 );
1376         }
1377 }
1378
1379 /**
1380  *
1381  * Wrap calls to proc_close(proc_open()) and call hook
1382  * so plugins can take part in process :)
1383  *
1384  * args:
1385  * $cmd program to run
1386  *  next args are passed as $cmd command line
1387  *
1388  * e.g.: proc_run("ls","-la","/tmp");
1389  *
1390  * $cmd and string args are surrounded with ""
1391  */
1392
1393 if(! function_exists('proc_run')) {
1394         function proc_run($cmd){
1395
1396                 $a = get_app();
1397
1398                 $args = func_get_args();
1399
1400                 $newargs = array();
1401                 if(! count($args))
1402                         return;
1403
1404                 // expand any arrays
1405
1406                 foreach($args as $arg) {
1407                         if(is_array($arg)) {
1408                                 foreach($arg as $n) {
1409                                         $newargs[] = $n;
1410                                 }
1411                         }
1412                         else
1413                                 $newargs[] = $arg;
1414                 }
1415
1416                 $args = $newargs;
1417
1418                 $arr = array('args' => $args, 'run_cmd' => true);
1419
1420                 call_hooks("proc_run", $arr);
1421                 if(! $arr['run_cmd'])
1422                         return;
1423
1424                 if(count($args) && $args[0] === 'php')
1425                         $args[0] = ((x($a->config,'php_path')) && (strlen($a->config['php_path'])) ? $a->config['php_path'] : 'php');
1426
1427                 // add baseurl to args. cli scripts can't construct it
1428                 $args[] = $a->get_baseurl();
1429
1430                 for($x = 0; $x < count($args); $x ++)
1431                         $args[$x] = escapeshellarg($args[$x]);
1432
1433
1434
1435                 $cmdline = implode($args," ");
1436                 if(get_config('system','proc_windows'))
1437                         proc_close(proc_open('cmd /c start /b ' . $cmdline,array(),$foo,dirname(__FILE__)));
1438                 else
1439                         proc_close(proc_open($cmdline." &",array(),$foo,dirname(__FILE__)));
1440         }
1441 }
1442
1443 if(! function_exists('current_theme')) {
1444         function current_theme(){
1445                 $app_base_themes = array('duepuntozero', 'dispy', 'quattro');
1446
1447                 $a = get_app();
1448
1449 //              $mobile_detect = new Mobile_Detect();
1450 //              $is_mobile = $mobile_detect->isMobile() || $mobile_detect->isTablet();
1451                 $is_mobile = $a->is_mobile || $a->is_tablet;
1452
1453                 if($is_mobile) {
1454                         if(isset($_SESSION['show-mobile']) && !$_SESSION['show-mobile']) {
1455                                 $system_theme = '';
1456                                 $theme_name = '';
1457                         }
1458                         else {
1459                                 $system_theme = ((isset($a->config['system']['mobile-theme'])) ? $a->config['system']['mobile-theme'] : '');
1460                                 $theme_name = ((isset($_SESSION) && x($_SESSION,'mobile-theme')) ? $_SESSION['mobile-theme'] : $system_theme);
1461
1462                                 if($theme_name === '---') {
1463                                         // user has selected to have the mobile theme be the same as the normal one
1464                                         $system_theme = '';
1465                                         $theme_name = '';
1466                                 }
1467                         }
1468                 }
1469                 if(!$is_mobile || ($system_theme === '' && $theme_name === '')) {
1470                         $system_theme = ((isset($a->config['system']['theme'])) ? $a->config['system']['theme'] : '');
1471                         $theme_name = ((isset($_SESSION) && x($_SESSION,'theme')) ? $_SESSION['theme'] : $system_theme);
1472                 }
1473
1474                 if($theme_name &&
1475                                 (file_exists('view/theme/' . $theme_name . '/style.css') ||
1476                                                 file_exists('view/theme/' . $theme_name . '/style.php')))
1477                         return($theme_name);
1478
1479                 foreach($app_base_themes as $t) {
1480                         if(file_exists('view/theme/' . $t . '/style.css')||
1481                                         file_exists('view/theme/' . $t . '/style.php'))
1482                                 return($t);
1483                 }
1484
1485                 $fallback = array_merge(glob('view/theme/*/style.css'),glob('view/theme/*/style.php'));
1486                 if(count($fallback))
1487                         return (str_replace('view/theme/','', substr($fallback[0],0,-10)));
1488
1489         }
1490 }
1491
1492 /*
1493  * Return full URL to theme which is currently in effect.
1494 * Provide a sane default if nothing is chosen or the specified theme does not exist.
1495 */
1496 if(! function_exists('current_theme_url')) {
1497         function current_theme_url() {
1498                 global $a;
1499                 $t = current_theme();
1500                 if (file_exists('view/theme/' . $t . '/style.php'))
1501                         return($a->get_baseurl() . '/view/theme/' . $t . '/style.pcss');
1502                 return($a->get_baseurl() . '/view/theme/' . $t . '/style.css');
1503         }
1504 }
1505
1506 if(! function_exists('feed_birthday')) {
1507         function feed_birthday($uid,$tz) {
1508
1509                 /**
1510                  *
1511                  * Determine the next birthday, but only if the birthday is published
1512                  * in the default profile. We _could_ also look for a private profile that the
1513                  * recipient can see, but somebody could get mad at us if they start getting
1514                  * public birthday greetings when they haven't made this info public.
1515                  *
1516                  * Assuming we are able to publish this info, we are then going to convert
1517                  * the start time from the owner's timezone to UTC.
1518                  *
1519                  * This will potentially solve the problem found with some social networks
1520                  * where birthdays are converted to the viewer's timezone and salutations from
1521                  * elsewhere in the world show up on the wrong day. We will convert it to the
1522                  * viewer's timezone also, but first we are going to convert it from the birthday
1523                  * person's timezone to GMT - so the viewer may find the birthday starting at
1524                  * 6:00PM the day before, but that will correspond to midnight to the birthday person.
1525                  *
1526                  */
1527
1528
1529                 $birthday = '';
1530
1531                 if(! strlen($tz))
1532                         $tz = 'UTC';
1533
1534                 $p = q("SELECT `dob` FROM `profile` WHERE `is-default` = 1 AND `uid` = %d LIMIT 1",
1535                                 intval($uid)
1536                 );
1537
1538                 if($p && count($p)) {
1539                         $tmp_dob = substr($p[0]['dob'],5);
1540                         if(intval($tmp_dob)) {
1541                                 $y = datetime_convert($tz,$tz,'now','Y');
1542                                 $bd = $y . '-' . $tmp_dob . ' 00:00';
1543                                 $t_dob = strtotime($bd);
1544                                 $now = strtotime(datetime_convert($tz,$tz,'now'));
1545                                 if($t_dob < $now)
1546                                         $bd = $y + 1 . '-' . $tmp_dob . ' 00:00';
1547                                 $birthday = datetime_convert($tz,'UTC',$bd,ATOM_TIME);
1548                         }
1549                 }
1550
1551                 return $birthday;
1552         }
1553 }
1554
1555 if(! function_exists('is_site_admin')) {
1556         function is_site_admin() {
1557                 $a = get_app();
1558
1559                 $adminlist = explode(",", str_replace(" ", "", $a->config['admin_email']));
1560
1561                 //if(local_user() && x($a->user,'email') && x($a->config,'admin_email') && ($a->user['email'] === $a->config['admin_email']))
1562                 if(local_user() && x($a->user,'email') && x($a->config,'admin_email') && in_array($a->user['email'], $adminlist))
1563                         return true;
1564                 return false;
1565         }
1566 }
1567
1568
1569 if(! function_exists('load_contact_links')) {
1570         function load_contact_links($uid) {
1571
1572                 $a = get_app();
1573
1574                 $ret = array();
1575
1576                 if(! $uid || x($a->contacts,'empty'))
1577                         return;
1578
1579                 $r = q("SELECT `id`,`network`,`url`,`thumb` FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 AND `thumb` != ''",
1580                                 intval($uid)
1581                 );
1582                 if(count($r)) {
1583                         foreach($r as $rr){
1584                                 $url = normalise_link($rr['url']);
1585                                 $ret[$url] = $rr;
1586                         }
1587                 }
1588                 else
1589                         $ret['empty'] = true;
1590                 $a->contacts = $ret;
1591                 return;
1592         }
1593 }
1594
1595 /**
1596 * returns querystring as string from a mapped array
1597 *
1598 * @param params Array
1599 * @return string
1600 */
1601 function build_querystring($params, $name=null) {
1602     $ret = "";
1603     foreach($params as $key=>$val) {
1604         if(is_array($val)) {
1605             if($name==null) {
1606                 $ret .= build_querystring($val, $key);
1607             } else {
1608                 $ret .= build_querystring($val, $name."[$key]");
1609             }
1610         } else {
1611             $val = urlencode($val);
1612             if($name!=null) {
1613                 $ret.=$name."[$key]"."=$val&";
1614             } else {
1615                 $ret.= "$key=$val&";
1616             }
1617         }
1618     }
1619     return $ret;
1620 }
1621
1622 function explode_querystring($query) {
1623         $arg_st = strpos($query, '?');
1624         if($arg_st !== false) {
1625                 $base = substr($query, 0, $arg_st);
1626                 $arg_st += 1;
1627         }
1628         else {
1629                 $base = '';
1630                 $arg_st = 0;
1631         }
1632
1633         $args = explode('&', substr($query, $arg_st));
1634         foreach($args as $k=>$arg) {
1635                 if($arg === '')
1636                         unset($args[$k]);
1637         }
1638         $args = array_values($args);
1639
1640         if(!$base) {
1641                 $base = $args[0];
1642                 unset($args[0]);
1643                 $args = array_values($args);
1644         }
1645
1646         return array(
1647                 'base' => $base,
1648                 'args' => $args,
1649         );
1650 }
1651
1652 /**
1653 * Returns the complete URL of the current page, e.g.: http(s)://something.com/network
1654 *
1655 * Taken from http://webcheatsheet.com/php/get_current_page_url.php
1656 */
1657 function curPageURL() {
1658         $pageURL = 'http';
1659         if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
1660         $pageURL .= "://";
1661         if ($_SERVER["SERVER_PORT"] != "80" && $_SERVER["SERVER_PORT"] != "443") {
1662                 $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
1663         } else {
1664                 $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
1665         }
1666         return $pageURL;
1667 }
1668
1669 function random_digits($digits) {
1670         $rn = '';
1671         for($i = 0; $i < $digits; $i++) {
1672                 $rn .= rand(0,9);
1673         }
1674         return $rn;
1675 }
1676
1677 function get_cachefile($file, $writemode = true) {
1678         $cache = get_itemcachepath();
1679
1680         if ((! $cache) || (! is_dir($cache)))
1681                 return("");
1682
1683         $subfolder = $cache."/".substr($file, 0, 2);
1684
1685         $cachepath = $subfolder."/".$file;
1686
1687         if ($writemode) {
1688                 if (!is_dir($subfolder)) {
1689                         mkdir($subfolder);
1690                         chmod($subfolder, 0777);
1691                 }
1692         }
1693
1694         return($cachepath);
1695 }
1696
1697 function clear_cache($basepath = "", $path = "") {
1698         if ($path == "") {
1699                 $basepath = get_itemcachepath();
1700                 $path = $basepath;
1701         }
1702
1703         if (($path == "") OR (!is_dir($path)))
1704                 return;
1705
1706         if (substr(realpath($path), 0, strlen($basepath)) != $basepath)
1707                 return;
1708
1709         $cachetime = (int)get_config('system','itemcache_duration');
1710         if ($cachetime == 0)
1711                 $cachetime = 86400;
1712
1713         if (is_writable($path)){
1714         if ($dh = opendir($path)) {
1715                 while (($file = readdir($dh)) !== false) {
1716                         $fullpath = $path."/".$file;
1717                         if ((filetype($fullpath) == "dir") and ($file != ".") and ($file != ".."))
1718                                 clear_cache($basepath, $fullpath);
1719                         if ((filetype($fullpath) == "file") and (filectime($fullpath) < (time() - $cachetime)))
1720                                 unlink($fullpath);
1721                 }
1722                 closedir($dh);
1723         }
1724         }
1725 }
1726
1727 function get_itemcachepath() {
1728         // Checking, if the cache is deactivated
1729         $cachetime = (int)get_config('system','itemcache_duration');
1730         if ($cachetime < 0)
1731                 return "";
1732
1733         $itemcache = get_config('system','itemcache');
1734         if (($itemcache != "") AND is_dir($itemcache) AND is_writable($itemcache))
1735                 return($itemcache);
1736
1737         $temppath = get_temppath();
1738
1739         if ($temppath != "") {
1740                 $itemcache = $temppath."/itemcache";
1741                 if(!file_exists($itemcache) && !is_dir($itemcache)) {
1742                         mkdir($itemcache);
1743                 }
1744
1745                 if (is_dir($itemcache) AND is_writable($itemcache)) {
1746                         set_config("system", "itemcache", $itemcache);
1747                         return($itemcache);
1748                 }
1749         }
1750         return "";
1751 }
1752
1753 function get_lockpath() {
1754         $lockpath = get_config('system','lockpath');
1755         if (($lockpath != "") AND is_dir($lockpath) AND is_writable($lockpath))
1756                 return($lockpath);
1757
1758         $temppath = get_temppath();
1759
1760         if ($temppath != "") {
1761                 $lockpath = $temppath."/lock";
1762                 mkdir($lockpath);
1763
1764                 if (is_dir($lockpath) AND is_writable($lockpath)) {
1765                         set_config("system", "lockpath", $lockpath);
1766                         return($lockpath);
1767                 }
1768         }
1769         return "";
1770 }
1771
1772 function get_temppath() {
1773         $temppath = get_config("system","temppath");
1774         if (($temppath != "") AND is_dir($temppath) AND is_writable($temppath))
1775                 return($temppath);
1776
1777         $temppath = sys_get_temp_dir();
1778         if (($temppath != "") AND is_dir($temppath) AND is_writable($temppath)) {
1779                 set_config("system", "temppath", $temppath);
1780                 return($temppath);
1781         }
1782
1783         return("");
1784 }
1785
1786 function set_template_engine(&$a, $engine = 'internal') {
1787 // This function is no longer necessary, but keep it as a wrapper to the class method
1788 // to avoid breaking themes again unnecessarily
1789
1790         $a->set_template_engine($engine);
1791 }
1792
1793 if(!function_exists('exif_imagetype')) {
1794         function exif_imagetype($file) {
1795                 $size = getimagesize($file);
1796                 return($size[2]);
1797         }
1798 }