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