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