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