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