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