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