]> git.mxchange.org Git - friendica.git/blob - boot.php
Merge pull request #1678 from annando/1506-ostatus-completion
[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
14 require_once('update.php');
15 require_once('include/dbstructure.php');
16
17 define ( 'FRIENDICA_PLATFORM',     'Friendica');
18 define ( 'FRIENDICA_CODENAME',     'Lily of the valley');
19 define ( 'FRIENDICA_VERSION',      '3.4.0' );
20 define ( 'DFRN_PROTOCOL_VERSION',  '2.23'    );
21 define ( 'DB_UPDATE_VERSION',      1185      );
22 define ( 'EOL',                    "<br />\r\n"     );
23 define ( 'ATOM_TIME',              'Y-m-d\TH:i:s\Z' );
24
25
26 /**
27  *
28  * Image storage quality. Lower numbers save space at cost of image detail.
29  * For ease of upgrade, please do not change here. Change jpeg quality with
30  * $a->config['system']['jpeg_quality'] = n;
31  * in .htconfig.php, where n is netween 1 and 100, and with very poor results
32  * below about 50
33  *
34  */
35
36 define ( 'JPEG_QUALITY',            100  );
37 /**
38  * $a->config['system']['png_quality'] from 0 (uncompressed) to 9
39  */
40 define ( 'PNG_QUALITY',             8  );
41
42 /**
43  *
44  * An alternate way of limiting picture upload sizes. Specify the maximum pixel
45  * length that pictures are allowed to be (for non-square pictures, it will apply
46  * to the longest side). Pictures longer than this length will be resized to be
47  * this length (on the longest side, the other side will be scaled appropriately).
48  * Modify this value using
49  *
50  *    $a->config['system']['max_image_length'] = n;
51  *
52  * in .htconfig.php
53  *
54  * If you don't want to set a maximum length, set to -1. The default value is
55  * defined by 'MAX_IMAGE_LENGTH' below.
56  *
57  */
58 define ( 'MAX_IMAGE_LENGTH',        -1  );
59
60
61 /**
62  * Not yet used
63  */
64
65 define ( 'DEFAULT_DB_ENGINE',  'MyISAM'  );
66
67 /**
68  * SSL redirection policies
69  */
70
71 define ( 'SSL_POLICY_NONE',         0 );
72 define ( 'SSL_POLICY_FULL',         1 );
73 define ( 'SSL_POLICY_SELFSIGN',     2 );
74
75
76 /**
77  * log levels
78  */
79
80 define ( 'LOGGER_NORMAL',          0 );
81 define ( 'LOGGER_TRACE',           1 );
82 define ( 'LOGGER_DEBUG',           2 );
83 define ( 'LOGGER_DATA',            3 );
84 define ( 'LOGGER_ALL',             4 );
85
86 /**
87  * registration policies
88  */
89
90 define ( 'REGISTER_CLOSED',        0 );
91 define ( 'REGISTER_APPROVE',       1 );
92 define ( 'REGISTER_OPEN',          2 );
93
94 /**
95  * relationship types
96  */
97
98 define ( 'CONTACT_IS_FOLLOWER', 1);
99 define ( 'CONTACT_IS_SHARING',  2);
100 define ( 'CONTACT_IS_FRIEND',   3);
101
102
103 /**
104  * DB update return values
105  */
106
107 define ( 'UPDATE_SUCCESS', 0);
108 define ( 'UPDATE_FAILED',  1);
109
110
111 /**
112  *
113  * page/profile types
114  *
115  * PAGE_NORMAL is a typical personal profile account
116  * PAGE_SOAPBOX automatically approves all friend requests as CONTACT_IS_SHARING, (readonly)
117  * PAGE_COMMUNITY automatically approves all friend requests as CONTACT_IS_SHARING, but with
118  *      write access to wall and comments (no email and not included in page owner's ACL lists)
119  * PAGE_FREELOVE automatically approves all friend requests as full friends (CONTACT_IS_FRIEND).
120  *
121  */
122
123 define ( 'PAGE_NORMAL',            0 );
124 define ( 'PAGE_SOAPBOX',           1 );
125 define ( 'PAGE_COMMUNITY',         2 );
126 define ( 'PAGE_FREELOVE',          3 );
127 define ( 'PAGE_BLOG',              4 );
128 define ( 'PAGE_PRVGROUP',          5 );
129
130 // Type of the community page
131 define ( 'CP_NO_COMMUNITY_PAGE',   -1 );
132 define ( 'CP_USERS_ON_SERVER',     0 );
133 define ( 'CP_GLOBAL_COMMUNITY',    1 );
134
135 /**
136  * Network and protocol family types
137  */
138
139 define ( 'NETWORK_DFRN',             'dfrn');    // Friendica, Mistpark, other DFRN implementations
140 define ( 'NETWORK_ZOT',              'zot!');    // Zot!
141 define ( 'NETWORK_OSTATUS',          'stat');    // status.net, identi.ca, GNU-social, other OStatus implementations
142 define ( 'NETWORK_FEED',             'feed');    // RSS/Atom feeds with no known "post/notify" protocol
143 define ( 'NETWORK_DIASPORA',         'dspr');    // Diaspora
144 define ( 'NETWORK_MAIL',             'mail');    // IMAP/POP
145 define ( 'NETWORK_MAIL2',            'mai2');    // extended IMAP/POP
146 define ( 'NETWORK_FACEBOOK',         'face');    // Facebook API
147 define ( 'NETWORK_LINKEDIN',         'lnkd');    // LinkedIn
148 define ( 'NETWORK_XMPP',             'xmpp');    // XMPP
149 define ( 'NETWORK_MYSPACE',          'mysp');    // MySpace
150 define ( 'NETWORK_GPLUS',            'goog');    // Google+
151 define ( 'NETWORK_PUMPIO',           'pump');    // pump.io
152 define ( 'NETWORK_TWITTER',          'twit');    // Twitter
153 define ( 'NETWORK_DIASPORA2',        'dspc');    // Diaspora connector
154 define ( 'NETWORK_STATUSNET',        'stac');    // Statusnet connector
155 define ( 'NETWORK_APPNET',           'apdn');    // app.net
156
157 define ( 'NETWORK_PHANTOM',          'unkn');    // Place holder
158
159 /**
160  * These numbers are used in stored permissions
161  * and existing allocations MUST NEVER BE CHANGED
162  * OR RE-ASSIGNED! You may only add to them.
163  */
164
165 $netgroup_ids = array(
166         NETWORK_DFRN     => (-1),
167         NETWORK_ZOT      => (-2),
168         NETWORK_OSTATUS  => (-3),
169         NETWORK_FEED     => (-4),
170         NETWORK_DIASPORA => (-5),
171         NETWORK_MAIL     => (-6),
172         NETWORK_MAIL2    => (-7),
173         NETWORK_FACEBOOK => (-8),
174         NETWORK_LINKEDIN => (-9),
175         NETWORK_XMPP     => (-10),
176         NETWORK_MYSPACE  => (-11),
177         NETWORK_GPLUS    => (-12),
178         NETWORK_PUMPIO   => (-13),
179         NETWORK_TWITTER  => (-14),
180         NETWORK_DIASPORA2 => (-15),
181         NETWORK_STATUSNET => (-16),
182         NETWORK_APPNET => (-17),
183
184         NETWORK_PHANTOM  => (-127),
185 );
186
187
188 /**
189  * Maximum number of "people who like (or don't like) this"  that we will list by name
190  */
191
192 define ( 'MAX_LIKERS',    75);
193
194 /**
195  * Communication timeout
196  */
197
198 define ( 'ZCURL_TIMEOUT' , (-1));
199
200
201 /**
202  * email notification options
203  */
204
205 define ( 'NOTIFY_INTRO',    0x0001 );
206 define ( 'NOTIFY_CONFIRM',  0x0002 );
207 define ( 'NOTIFY_WALL',     0x0004 );
208 define ( 'NOTIFY_COMMENT',  0x0008 );
209 define ( 'NOTIFY_MAIL',     0x0010 );
210 define ( 'NOTIFY_SUGGEST',  0x0020 );
211 define ( 'NOTIFY_PROFILE',  0x0040 );
212 define ( 'NOTIFY_TAGSELF',  0x0080 );
213 define ( 'NOTIFY_TAGSHARE', 0x0100 );
214 define ( 'NOTIFY_POKE',     0x0200 );
215 define ( 'NOTIFY_SHARE',    0x0400 );
216
217 define ( 'NOTIFY_SYSTEM',   0x8000 );
218
219
220 /**
221  * Tag/term types
222  */
223
224 define ( 'TERM_UNKNOWN',   0 );
225 define ( 'TERM_HASHTAG',   1 );
226 define ( 'TERM_MENTION',   2 );
227 define ( 'TERM_CATEGORY',  3 );
228 define ( 'TERM_PCATEGORY', 4 );
229 define ( 'TERM_FILE',      5 );
230 define ( 'TERM_SAVEDSEARCH', 6 );
231 define ( 'TERM_CONVERSATION', 7 );
232
233 define ( 'TERM_OBJ_POST',  1 );
234 define ( 'TERM_OBJ_PHOTO', 2 );
235
236
237
238 /**
239  * various namespaces we may need to parse
240  */
241
242 define ( 'NAMESPACE_ZOT',             'http://purl.org/zot' );
243 define ( 'NAMESPACE_DFRN' ,           'http://purl.org/macgirvin/dfrn/1.0' );
244 define ( 'NAMESPACE_THREAD' ,         'http://purl.org/syndication/thread/1.0' );
245 define ( 'NAMESPACE_TOMB' ,           'http://purl.org/atompub/tombstones/1.0' );
246 define ( 'NAMESPACE_ACTIVITY',        'http://activitystrea.ms/spec/1.0/' );
247 define ( 'NAMESPACE_ACTIVITY_SCHEMA', 'http://activitystrea.ms/schema/1.0/' );
248 define ( 'NAMESPACE_MEDIA',           'http://purl.org/syndication/atommedia' );
249 define ( 'NAMESPACE_SALMON_ME',       'http://salmon-protocol.org/ns/magic-env' );
250 define ( 'NAMESPACE_OSTATUSSUB',      'http://ostatus.org/schema/1.0/subscribe' );
251 define ( 'NAMESPACE_GEORSS',          'http://www.georss.org/georss' );
252 define ( 'NAMESPACE_POCO',            'http://portablecontacts.net/spec/1.0' );
253 define ( 'NAMESPACE_FEED',            'http://schemas.google.com/g/2010#updates-from' );
254 define ( 'NAMESPACE_OSTATUS',         'http://ostatus.org/schema/1.0' );
255 define ( 'NAMESPACE_STATUSNET',       'http://status.net/schema/api/1/' );
256 define ( 'NAMESPACE_ATOM1',           'http://www.w3.org/2005/Atom' );
257 /**
258  * activity stream defines
259  */
260
261 define ( 'ACTIVITY_LIKE',        NAMESPACE_ACTIVITY_SCHEMA . 'like' );
262 define ( 'ACTIVITY_DISLIKE',     NAMESPACE_DFRN            . '/dislike' );
263 define ( 'ACTIVITY_OBJ_HEART',   NAMESPACE_DFRN            . '/heart' );
264
265 define ( 'ACTIVITY_FRIEND',      NAMESPACE_ACTIVITY_SCHEMA . 'make-friend' );
266 define ( 'ACTIVITY_REQ_FRIEND',  NAMESPACE_ACTIVITY_SCHEMA . 'request-friend' );
267 define ( 'ACTIVITY_UNFRIEND',    NAMESPACE_ACTIVITY_SCHEMA . 'remove-friend' );
268 define ( 'ACTIVITY_FOLLOW',      NAMESPACE_ACTIVITY_SCHEMA . 'follow' );
269 define ( 'ACTIVITY_UNFOLLOW',    NAMESPACE_ACTIVITY_SCHEMA . 'stop-following' );
270 define ( 'ACTIVITY_JOIN',        NAMESPACE_ACTIVITY_SCHEMA . 'join' );
271
272 define ( 'ACTIVITY_POST',        NAMESPACE_ACTIVITY_SCHEMA . 'post' );
273 define ( 'ACTIVITY_UPDATE',      NAMESPACE_ACTIVITY_SCHEMA . 'update' );
274 define ( 'ACTIVITY_TAG',         NAMESPACE_ACTIVITY_SCHEMA . 'tag' );
275 define ( 'ACTIVITY_FAVORITE',    NAMESPACE_ACTIVITY_SCHEMA . 'favorite' );
276
277 define ( 'ACTIVITY_POKE',        NAMESPACE_ZOT . '/activity/poke' );
278 define ( 'ACTIVITY_MOOD',        NAMESPACE_ZOT . '/activity/mood' );
279
280 define ( 'ACTIVITY_OBJ_BOOKMARK', NAMESPACE_ACTIVITY_SCHEMA . 'bookmark' );
281 define ( 'ACTIVITY_OBJ_COMMENT', NAMESPACE_ACTIVITY_SCHEMA . 'comment' );
282 define ( 'ACTIVITY_OBJ_NOTE',    NAMESPACE_ACTIVITY_SCHEMA . 'note' );
283 define ( 'ACTIVITY_OBJ_PERSON',  NAMESPACE_ACTIVITY_SCHEMA . 'person' );
284 define ( 'ACTIVITY_OBJ_IMAGE',   NAMESPACE_ACTIVITY_SCHEMA . 'image' );
285 define ( 'ACTIVITY_OBJ_PHOTO',   NAMESPACE_ACTIVITY_SCHEMA . 'photo' );
286 define ( 'ACTIVITY_OBJ_VIDEO',   NAMESPACE_ACTIVITY_SCHEMA . 'video' );
287 define ( 'ACTIVITY_OBJ_P_PHOTO', NAMESPACE_ACTIVITY_SCHEMA . 'profile-photo' );
288 define ( 'ACTIVITY_OBJ_ALBUM',   NAMESPACE_ACTIVITY_SCHEMA . 'photo-album' );
289 define ( 'ACTIVITY_OBJ_EVENT',   NAMESPACE_ACTIVITY_SCHEMA . 'event' );
290 define ( 'ACTIVITY_OBJ_GROUP',   NAMESPACE_ACTIVITY_SCHEMA . 'group' );
291 define ( 'ACTIVITY_OBJ_TAGTERM', NAMESPACE_DFRN            . '/tagterm' );
292 define ( 'ACTIVITY_OBJ_PROFILE', NAMESPACE_DFRN            . '/profile' );
293 define ( 'ACTIVITY_OBJ_QUESTION', 'http://activityschema.org/object/question' );
294
295 /**
296  * item weight for query ordering
297  */
298
299 define ( 'GRAVITY_PARENT',       0);
300 define ( 'GRAVITY_LIKE',         3);
301 define ( 'GRAVITY_COMMENT',      6);
302
303 /**
304  *
305  * Reverse the effect of magic_quotes_gpc if it is enabled.
306  * Please disable magic_quotes_gpc so we don't have to do this.
307  * See http://php.net/manual/en/security.magicquotes.disabling.php
308  *
309  */
310
311 function startup() {
312
313         error_reporting(E_ERROR | E_WARNING | E_PARSE);
314
315         set_time_limit(0);
316
317         // This has to be quite large to deal with embedded private photos
318         ini_set('pcre.backtrack_limit', 500000);
319
320
321         if (get_magic_quotes_gpc()) {
322                 $process = array(&$_GET, &$_POST, &$_COOKIE, &$_REQUEST);
323                 while (list($key, $val) = each($process)) {
324                         foreach ($val as $k => $v) {
325                                 unset($process[$key][$k]);
326                                 if (is_array($v)) {
327                                         $process[$key][stripslashes($k)] = $v;
328                                         $process[] = &$process[$key][stripslashes($k)];
329                                 } else {
330                                         $process[$key][stripslashes($k)] = stripslashes($v);
331                                 }
332                         }
333                 }
334                 unset($process);
335         }
336
337 }
338
339 /**
340  *
341  * class: App
342  *
343  * Our main application structure for the life of this page
344  * Primarily deals with the URL that got us here
345  * and tries to make some sense of it, and
346  * stores our page contents and config storage
347  * and anything else that might need to be passed around
348  * before we spit the page out.
349  *
350  */
351
352 if(! class_exists('App')) {
353         class App {
354
355                 public  $module_loaded = false;
356                 public  $query_string;
357                 public  $config;
358                 public  $page;
359                 public  $profile;
360                 public  $user;
361                 public  $cid;
362                 public  $contact;
363                 public  $contacts;
364                 public  $page_contact;
365                 public  $content;
366                 public  $data = array();
367                 public  $error = false;
368                 public  $cmd;
369                 public  $argv;
370                 public  $argc;
371                 public  $module;
372                 public  $pager;
373                 public  $strings;
374                 public  $path;
375                 public  $hooks;
376                 public  $timezone;
377                 public  $interactive = true;
378                 public  $plugins;
379                 public  $apps = array();
380                 public  $identities;
381                 public  $is_mobile;
382                 public  $is_tablet;
383                 public  $is_friendica_app;
384                 public  $performance = array();
385
386                 public $nav_sel;
387
388                 public $category;
389
390
391                 // Allow themes to control internal parameters
392                 // by changing App values in theme.php
393
394                 public  $sourcename = '';
395                 public  $videowidth = 425;
396                 public  $videoheight = 350;
397                 public  $force_max_items = 0;
398                 public  $theme_thread_allow = true;
399
400                 // An array for all theme-controllable parameters
401                 // Mostly unimplemented yet. Only options 'stylesheet' and
402                 // beyond are used.
403
404                 public  $theme = array(
405                         'sourcename' => '',
406                         'videowidth' => 425,
407                         'videoheight' => 350,
408                         'force_max_items' => 0,
409                         'thread_allow' => true,
410                         'stylesheet' => '',
411                         'template_engine' => 'smarty3',
412                 );
413
414                 // array of registered template engines ('name'=>'class name')
415                 public $template_engines = array();
416                 // array of instanced template engines ('name'=>'instance')
417                 public $template_engine_instance = array();
418
419                 private $ldelim = array(
420                         'internal' => '',
421                         'smarty3' => '{{'
422                 );
423                 private $rdelim = array(
424                         'internal' => '',
425                         'smarty3' => '}}'
426                 );
427
428                 private $scheme;
429                 private $hostname;
430                 private $baseurl;
431                 private $db;
432
433                 private $curl_code;
434                 private $curl_content_type;
435                 private $curl_headers;
436
437                 private $cached_profile_image;
438                 private $cached_profile_picdate;
439
440                 function __construct() {
441
442                         global $default_timezone;
443
444                         $hostname = "";
445
446                         if (file_exists(".htpreconfig.php"))
447                                 @include(".htpreconfig.php");
448
449                         $this->timezone = ((x($default_timezone)) ? $default_timezone : 'UTC');
450
451                         date_default_timezone_set($this->timezone);
452
453                         $this->performance["start"] = microtime(true);
454                         $this->performance["database"] = 0;
455                         $this->performance["network"] = 0;
456                         $this->performance["file"] = 0;
457                         $this->performance["rendering"] = 0;
458                         $this->performance["parser"] = 0;
459                         $this->performance["marktime"] = 0;
460                         $this->performance["markstart"] = microtime(true);
461
462                         $this->config = array();
463                         $this->page = array();
464                         $this->pager= array();
465
466                         $this->query_string = '';
467
468                         startup();
469
470                         set_include_path(
471                                         'include' . PATH_SEPARATOR
472                                         . 'library' . PATH_SEPARATOR
473                                         . 'library/phpsec' . PATH_SEPARATOR
474                                         . 'library/langdet' . PATH_SEPARATOR
475                                         . '.' );
476
477
478                         $this->scheme = 'http';
479                         if(x($_SERVER,'HTTPS') && $_SERVER['HTTPS'])
480                                 $this->scheme = 'https';
481                         elseif(x($_SERVER,'SERVER_PORT') && (intval($_SERVER['SERVER_PORT']) == 443))
482                                 $this->scheme = 'https';
483
484                         if(x($_SERVER,'SERVER_NAME')) {
485                                 $this->hostname = $_SERVER['SERVER_NAME'];
486
487                                 // See bug 437 - this didn't work so disabling it
488                                 //if(stristr($this->hostname,'xn--')) {
489                                         // PHP or webserver may have converted idn to punycode, so
490                                         // convert punycode back to utf-8
491                                 //      require_once('library/simplepie/idn/idna_convert.class.php');
492                                 //      $x = new idna_convert();
493                                 //      $this->hostname = $x->decode($_SERVER['SERVER_NAME']);
494                                 //}
495
496                                 if(x($_SERVER,'SERVER_PORT') && $_SERVER['SERVER_PORT'] != 80 && $_SERVER['SERVER_PORT'] != 443)
497                                         $this->hostname .= ':' . $_SERVER['SERVER_PORT'];
498                                 /**
499                                  * Figure out if we are running at the top of a domain
500                                  * or in a sub-directory and adjust accordingly
501                                  */
502
503                                 $path = trim(dirname($_SERVER['SCRIPT_NAME']),'/\\');
504                                 if(isset($path) && strlen($path) && ($path != $this->path))
505                                         $this->path = $path;
506                         }
507
508                         if ($hostname != "")
509                                 $this->hostname = $hostname;
510
511                         if (is_array($_SERVER["argv"]) && $_SERVER["argc"]>1 && substr(end($_SERVER["argv"]), 0, 4)=="http" ) {
512                                 $this->set_baseurl(array_pop($_SERVER["argv"]) );
513                                 $_SERVER["argc"] --;
514                         }
515
516                         #set_include_path("include/$this->hostname" . PATH_SEPARATOR . get_include_path());
517
518                         if((x($_SERVER,'QUERY_STRING')) && substr($_SERVER['QUERY_STRING'],0,9) === "pagename=") {
519                                 $this->query_string = substr($_SERVER['QUERY_STRING'],9);
520                                 // removing trailing / - maybe a nginx problem
521                                 if (substr($this->query_string, 0, 1) == "/")
522                                         $this->query_string = substr($this->query_string, 1);
523                         } elseif((x($_SERVER,'QUERY_STRING')) && substr($_SERVER['QUERY_STRING'],0,2) === "q=") {
524                                 $this->query_string = substr($_SERVER['QUERY_STRING'],2);
525                                 // removing trailing / - maybe a nginx problem
526                                 if (substr($this->query_string, 0, 1) == "/")
527                                         $this->query_string = substr($this->query_string, 1);
528                         }
529
530                         if (x($_GET,'pagename'))
531                                 $this->cmd = trim($_GET['pagename'],'/\\');
532                         elseif (x($_GET,'q'))
533                                 $this->cmd = trim($_GET['q'],'/\\');
534
535
536                         // fix query_string
537                         $this->query_string = str_replace($this->cmd."&",$this->cmd."?", $this->query_string);
538
539
540                         // unix style "homedir"
541
542                         if(substr($this->cmd,0,1) === '~')
543                                 $this->cmd = 'profile/' . substr($this->cmd,1);
544
545                         // Diaspora style profile url
546
547                         if(substr($this->cmd,0,2) === 'u/')
548                                 $this->cmd = 'profile/' . substr($this->cmd,2);
549
550
551                         /**
552                          *
553                          * Break the URL path into C style argc/argv style arguments for our
554                          * modules. Given "http://example.com/module/arg1/arg2", $this->argc
555                          * will be 3 (integer) and $this->argv will contain:
556                          *   [0] => 'module'
557                          *   [1] => 'arg1'
558                          *   [2] => 'arg2'
559                          *
560                          *
561                          * There will always be one argument. If provided a naked domain
562                          * URL, $this->argv[0] is set to "home".
563                          *
564                          */
565
566                         $this->argv = explode('/',$this->cmd);
567                         $this->argc = count($this->argv);
568                         if((array_key_exists('0',$this->argv)) && strlen($this->argv[0])) {
569                                 $this->module = str_replace(".", "_", $this->argv[0]);
570                                 $this->module = str_replace("-", "_", $this->module);
571                         }
572                         else {
573                                 $this->argc = 1;
574                                 $this->argv = array('home');
575                                 $this->module = 'home';
576                         }
577
578                         /**
579                          * See if there is any page number information, and initialise
580                          * pagination
581                          */
582
583                         $this->pager['page'] = ((x($_GET,'page') && intval($_GET['page']) > 0) ? intval($_GET['page']) : 1);
584                         $this->pager['itemspage'] = 50;
585                         $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
586                         if($this->pager['start'] < 0)
587                                 $this->pager['start'] = 0;
588                         $this->pager['total'] = 0;
589
590                         /**
591                          * Detect mobile devices
592                          */
593
594                         $mobile_detect = new Mobile_Detect();
595                         $this->is_mobile = $mobile_detect->isMobile();
596                         $this->is_tablet = $mobile_detect->isTablet();
597
598                         // Friendica-Client
599                         $this->is_friendica_app = ($_SERVER['HTTP_USER_AGENT'] == "Apache-HttpClient/UNAVAILABLE (java 1.4)");
600
601                         /**
602                          * register template engines
603                          */
604                         $dc = get_declared_classes();
605                         foreach ($dc as $k) {
606                                 if (in_array("ITemplateEngine", class_implements($k))){
607                                         $this->register_template_engine($k);
608                                 }
609                         }
610
611                 }
612
613                 function get_basepath() {
614
615                         $basepath = get_config("system", "basepath");
616
617                         if ($basepath == "")
618                                 $basepath = $_SERVER["DOCUMENT_ROOT"];
619
620                         if ($basepath == "")
621                                 $basepath = $_SERVER["PWD"];
622
623                         return($basepath);
624                 }
625
626                 function get_scheme() {
627                         return($this->scheme);
628                 }
629
630                 function get_baseurl($ssl = false) {
631
632                         $scheme = $this->scheme;
633
634                         if((x($this->config,'system')) && (x($this->config['system'],'ssl_policy'))) {
635                                 if(intval($this->config['system']['ssl_policy']) === intval(SSL_POLICY_FULL))
636                                         $scheme = 'https';
637
638                                 //      Basically, we have $ssl = true on any links which can only be seen by a logged in user
639                                 //      (and also the login link). Anything seen by an outsider will have it turned off.
640
641                                 if($this->config['system']['ssl_policy'] == SSL_POLICY_SELFSIGN) {
642                                         if($ssl)
643                                                 $scheme = 'https';
644                                         else
645                                                 $scheme = 'http';
646                                 }
647                         }
648
649                         if (get_config('config','hostname') != "")
650                                 $this->hostname = get_config('config','hostname');
651
652                         $this->baseurl = $scheme . "://" . $this->hostname . ((isset($this->path) && strlen($this->path)) ? '/' . $this->path : '' );
653                         return $this->baseurl;
654                 }
655
656                 function set_baseurl($url) {
657                         $parsed = @parse_url($url);
658
659                         $this->baseurl = $url;
660
661                         if($parsed) {
662                                 $this->scheme = $parsed['scheme'];
663
664                                 $hostname = $parsed['host'];
665                                 if(x($parsed,'port'))
666                                         $hostname .= ':' . $parsed['port'];
667                                 if(x($parsed,'path'))
668                                         $this->path = trim($parsed['path'],'\\/');
669
670                                 if (file_exists(".htpreconfig.php"))
671                                         @include(".htpreconfig.php");
672
673                                 if (get_config('config','hostname') != "")
674                                         $this->hostname = get_config('config','hostname');
675
676                                 if (!isset($this->hostname) OR ($this->hostname == ""))
677                                         $this->hostname = $hostname;
678                         }
679
680                 }
681
682                 function get_hostname() {
683                         if (get_config('config','hostname') != "")
684                                 $this->hostname = get_config('config','hostname');
685
686                         return $this->hostname;
687                 }
688
689                 function set_hostname($h) {
690                         $this->hostname = $h;
691                 }
692
693                 function set_path($p) {
694                         $this->path = trim(trim($p),'/');
695                 }
696
697                 function get_path() {
698                         return $this->path;
699                 }
700
701                 function set_pager_total($n) {
702                         $this->pager['total'] = intval($n);
703                 }
704
705                 function set_pager_itemspage($n) {
706                         $this->pager['itemspage'] = ((intval($n) > 0) ? intval($n) : 0);
707                         $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
708                 }
709
710                 function set_pager_page($n) {
711                         $this->pager['page'] = $n;
712                         $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
713                 }
714
715                 function init_pagehead() {
716                         $interval = ((local_user()) ? get_pconfig(local_user(),'system','update_interval') : 40000);
717                         if($interval < 10000)
718                                 $interval = 40000;
719
720                         $this->page['title'] = $this->config['sitename'];
721
722                         /* put the head template at the beginning of page['htmlhead']
723                          * since the code added by the modules frequently depends on it
724                          * being first
725                          */
726                         if(!isset($this->page['htmlhead']))
727                                 $this->page['htmlhead'] = '';
728
729                         // If we're using Smarty, then doing replace_macros() will replace
730                         // any unrecognized variables with a blank string. Since we delay
731                         // replacing $stylesheet until later, we need to replace it now
732                         // with another variable name
733                         if($this->theme['template_engine'] === 'smarty3')
734                                 $stylesheet = $this->get_template_ldelim('smarty3') . '$stylesheet' . $this->get_template_rdelim('smarty3');
735                         else
736                                 $stylesheet = '$stylesheet';
737
738                         $shortcut_icon = get_config("system", "shortcut_icon");
739                         if ($shortcut_icon == "")
740                                 $shortcut_icon = $this->get_baseurl()."/images/friendica-32.png";
741
742                         $touch_icon = get_config("system", "touch_icon");
743                         if ($touch_icon == "")
744                                 $touch_icon = $this->get_baseurl()."/images/friendica-128.png";
745
746                         $tpl = get_markup_template('head.tpl');
747                         $this->page['htmlhead'] = replace_macros($tpl,array(
748                                 '$baseurl' => $this->get_baseurl(), // FIXME for z_path!!!!
749                                 '$local_user' => local_user(),
750                                 '$generator' => 'Friendica' . ' ' . FRIENDICA_VERSION,
751                                 '$delitem' => t('Delete this item?'),
752                                 '$comment' => t('Comment'),
753                                 '$showmore' => t('show more'),
754                                 '$showfewer' => t('show fewer'),
755                                 '$update_interval' => $interval,
756                                 '$shortcut_icon' => $shortcut_icon,
757                                 '$touch_icon' => $touch_icon,
758                                 '$stylesheet' => $stylesheet
759                         )) . $this->page['htmlhead'];
760                 }
761
762                 function init_page_end() {
763                         if(!isset($this->page['end']))
764                                 $this->page['end'] = '';
765                         $tpl = get_markup_template('end.tpl');
766                         $this->page['end'] = replace_macros($tpl,array(
767                                 '$baseurl' => $this->get_baseurl() // FIXME for z_path!!!!
768                         )) . $this->page['end'];
769                 }
770
771                 function set_curl_code($code) {
772                         $this->curl_code = $code;
773                 }
774
775                 function get_curl_code() {
776                         return $this->curl_code;
777                 }
778
779                 function set_curl_content_type($content_type) {
780                         $this->curl_content_type = $content_type;
781                 }
782
783                 function get_curl_content_type() {
784                         return $this->curl_content_type;
785                 }
786
787                 function set_curl_headers($headers) {
788                         $this->curl_headers = $headers;
789                 }
790
791                 function get_curl_headers() {
792                         return $this->curl_headers;
793                 }
794
795                 function get_cached_avatar_image($avatar_image){
796                         if($this->cached_profile_image[$avatar_image])
797                                 return $this->cached_profile_image[$avatar_image];
798
799                         $path_parts = explode("/",$avatar_image);
800                         $common_filename = $path_parts[count($path_parts)-1];
801
802                         if($this->cached_profile_picdate[$common_filename]){
803                                 $this->cached_profile_image[$avatar_image] = $avatar_image . $this->cached_profile_picdate[$common_filename];
804                         } else {
805                                 $r = q("SELECT `contact`.`avatar-date` AS picdate FROM `contact` WHERE `contact`.`thumb` like '%%/%s'",
806                                         $common_filename);
807                                 if(! count($r)){
808                                         $this->cached_profile_image[$avatar_image] = $avatar_image;
809                                 } else {
810                                         $this->cached_profile_picdate[$common_filename] = "?rev=".urlencode($r[0]['picdate']);
811                                         $this->cached_profile_image[$avatar_image] = $avatar_image.$this->cached_profile_picdate[$common_filename];
812                                 }
813                         }
814                         return $this->cached_profile_image[$avatar_image];
815                 }
816
817
818                 /**
819                  * register template engine class
820                  * if $name is "", is used class static property $class::$name
821                  * @param string $class
822                  * @param string $name
823                  */
824                 function register_template_engine($class, $name = '') {
825                         if ($name===""){
826                                 $v = get_class_vars( $class );
827                                 if(x($v,"name")) $name = $v['name'];
828                         }
829                         if ($name===""){
830                                 echo "template engine <tt>$class</tt> cannot be registered without a name.\n";
831                                 killme();
832                         }
833                         $this->template_engines[$name] = $class;
834                 }
835
836                 /**
837                  * return template engine instance. If $name is not defined,
838                  * return engine defined by theme, or default
839                  *
840                  * @param strin $name Template engine name
841                  * @return object Template Engine instance
842                  */
843                 function template_engine($name = ''){
844                         if ($name!=="") {
845                                 $template_engine = $name;
846                         } else {
847                                 $template_engine = 'smarty3';
848                                 if (x($this->theme, 'template_engine')) {
849                                         $template_engine = $this->theme['template_engine'];
850                                 }
851                         }
852
853                         if (isset($this->template_engines[$template_engine])){
854                                 if(isset($this->template_engine_instance[$template_engine])){
855                                         return $this->template_engine_instance[$template_engine];
856                                 } else {
857                                         $class = $this->template_engines[$template_engine];
858                                         $obj = new $class;
859                                         $this->template_engine_instance[$template_engine] = $obj;
860                                         return $obj;
861                                 }
862                         }
863
864                         echo "template engine <tt>$template_engine</tt> is not registered!\n"; killme();
865                 }
866
867                 function get_template_engine() {
868                         return $this->theme['template_engine'];
869                 }
870
871                 function set_template_engine($engine = 'smarty3') {
872                         $this->theme['template_engine'] = $engine;
873                         /*
874                         $this->theme['template_engine'] = 'smarty3';
875
876                         switch($engine) {
877                                 case 'smarty3':
878                                         if(is_writable('view/smarty3/'))
879                                                 $this->theme['template_engine'] = 'smarty3';
880                                         break;
881                                 default:
882                                         break;
883                         }
884                         */
885                 }
886
887                 function get_template_ldelim($engine = 'smarty3') {
888                         return $this->ldelim[$engine];
889                 }
890
891                 function get_template_rdelim($engine = 'smarty3') {
892                         return $this->rdelim[$engine];
893                 }
894
895                 function save_timestamp($stamp, $value) {
896                         $duration = (float)(microtime(true)-$stamp);
897
898                         $this->performance[$value] += (float)$duration;
899                         $this->performance["marktime"] += (float)$duration;
900                 }
901
902                 function mark_timestamp($mark) {
903                         //$this->performance["markstart"] -= microtime(true) - $this->performance["marktime"];
904                         $this->performance["markstart"] = microtime(true) - $this->performance["markstart"] - $this->performance["marktime"];
905                 }
906
907                 function get_useragent() {
908                         return(FRIENDICA_PLATFORM." '".FRIENDICA_CODENAME."' ".FRIENDICA_VERSION."-".DB_UPDATE_VERSION."; ".$this->get_baseurl());
909                 }
910
911                 function is_friendica_app() {
912                         return($this->is_friendica_app);
913                 }
914
915         }
916 }
917
918 // retrieve the App structure
919 // useful in functions which require it but don't get it passed to them
920
921 if(! function_exists('get_app')) {
922         function get_app() {
923                 global $a;
924                 return $a;
925         }
926 };
927
928
929 // Multi-purpose function to check variable state.
930 // Usage: x($var) or $x($array,'key')
931 // returns false if variable/key is not set
932 // if variable is set, returns 1 if has 'non-zero' value, otherwise returns 0.
933 // e.g. x('') or x(0) returns 0;
934
935 if(! function_exists('x')) {
936         function x($s,$k = NULL) {
937                 if($k != NULL) {
938                         if((is_array($s)) && (array_key_exists($k,$s))) {
939                                 if($s[$k])
940                                         return (int) 1;
941                                 return (int) 0;
942                 }
943                         return false;
944                 }
945                 else {
946                         if(isset($s)) {
947                                 if($s) {
948                                         return (int) 1;
949                                 }
950                                 return (int) 0;
951                         }
952                         return false;
953                 }
954         }
955 }
956
957 // called from db initialisation if db is dead.
958
959 if(! function_exists('system_unavailable')) {
960         function system_unavailable() {
961                 include('system_unavailable.php');
962                 system_down();
963                 killme();
964         }
965 }
966
967
968
969 function clean_urls() {
970         global $a;
971         //      if($a->config['system']['clean_urls'])
972         return true;
973         //      return false;
974 }
975
976 function z_path() {
977         global $a;
978         $base = $a->get_baseurl();
979         if(! clean_urls())
980                 $base .= '/?q=';
981         return $base;
982 }
983
984 function z_root() {
985         global $a;
986         return $a->get_baseurl();
987 }
988
989 function absurl($path) {
990         if(strpos($path,'/') === 0)
991                 return z_path() . $path;
992         return $path;
993 }
994
995 function is_ajax() {
996         return (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');
997 }
998
999 function check_db() {
1000
1001         $build = get_config('system','build');
1002         if(! x($build)) {
1003                 set_config('system','build',DB_UPDATE_VERSION);
1004                 $build = DB_UPDATE_VERSION;
1005         }
1006         if($build != DB_UPDATE_VERSION)
1007                 proc_run('php', 'include/dbupdate.php');
1008
1009 }
1010
1011
1012
1013
1014 // Sets the base url for use in cmdline programs which don't have
1015 // $_SERVER variables
1016
1017 if(! function_exists('check_url')) {
1018         function check_url(&$a) {
1019
1020                 $url = get_config('system','url');
1021
1022                 // if the url isn't set or the stored url is radically different
1023                 // than the currently visited url, store the current value accordingly.
1024                 // "Radically different" ignores common variations such as http vs https
1025                 // and www.example.com vs example.com.
1026                 // We will only change the url to an ip address if there is no existing setting
1027
1028                 if(! x($url))
1029                         $url = set_config('system','url',$a->get_baseurl());
1030                 if((! link_compare($url,$a->get_baseurl())) && (! preg_match("/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/",$a->get_hostname)))
1031                         $url = set_config('system','url',$a->get_baseurl());
1032
1033                 return;
1034         }
1035 }
1036
1037
1038 // Automatic database updates
1039
1040 if(! function_exists('update_db')) {
1041         function update_db(&$a) {
1042                 $build = get_config('system','build');
1043                 if(! x($build))
1044                         $build = set_config('system','build',DB_UPDATE_VERSION);
1045
1046                 if($build != DB_UPDATE_VERSION) {
1047                         $stored = intval($build);
1048                         $current = intval(DB_UPDATE_VERSION);
1049                         if($stored < $current) {
1050                                 load_config('database');
1051
1052                                 // We're reporting a different version than what is currently installed.
1053                                 // Run any existing update scripts to bring the database up to current.
1054
1055                                 // make sure that boot.php and update.php are the same release, we might be
1056                                 // updating right this very second and the correct version of the update.php
1057                                 // file may not be here yet. This can happen on a very busy site.
1058
1059                                 if(DB_UPDATE_VERSION == UPDATE_VERSION) {
1060                                         // Compare the current structure with the defined structure
1061
1062                                         $t = get_config('database','dbupdate_'.DB_UPDATE_VERSION);
1063                                         if($t !== false)
1064                                                 return;
1065
1066                                         set_config('database','dbupdate_'.DB_UPDATE_VERSION, time());
1067
1068                                         // run old update routine (wich could modify the schema and
1069                                         // conflits with new routine)
1070                                         for ($x = $stored; $x < NEW_UPDATE_ROUTINE_VERSION; $x++) {
1071                                                 $r = run_update_function($x);
1072                                                 if (!$r) break;
1073                                         }
1074                                         if ($stored < NEW_UPDATE_ROUTINE_VERSION) $stored = NEW_UPDATE_ROUTINE_VERSION;
1075
1076
1077                                         // run new update routine
1078                                         // it update the structure in one call
1079                                         $retval = update_structure(false, true);
1080                                         if($retval) {
1081                                                 update_fail(
1082                                                         DB_UPDATE_VERSION,
1083                                                         $retval
1084                                                 );
1085                                                 return;
1086                                         } else {
1087                                                 set_config('database','dbupdate_'.DB_UPDATE_VERSION, 'success');
1088                                         }
1089
1090                                         // run any left update_nnnn functions in update.php
1091                                         for($x = $stored; $x < $current; $x ++) {
1092                                                 $r = run_update_function($x);
1093                                                 if (!$r) break;
1094                                         }
1095                                 }
1096                         }
1097                 }
1098
1099                 return;
1100         }
1101 }
1102 if(!function_exists('run_update_function')){
1103         function run_update_function($x) {
1104                 if(function_exists('update_' . $x)) {
1105
1106                         // There could be a lot of processes running or about to run.
1107                         // We want exactly one process to run the update command.
1108                         // So store the fact that we're taking responsibility
1109                         // after first checking to see if somebody else already has.
1110
1111                         // If the update fails or times-out completely you may need to
1112                         // delete the config entry to try again.
1113
1114                         $t = get_config('database','update_' . $x);
1115                         if($t !== false)
1116                                 return false;
1117                         set_config('database','update_' . $x, time());
1118
1119                         // call the specific update
1120
1121                         $func = 'update_' . $x;
1122                         $retval = $func();
1123
1124                         if($retval) {
1125                                 //send the administrator an e-mail
1126                                 update_fail(
1127                                         $x,
1128                                         sprintf(t('Update %s failed. See error logs.'), $x)
1129                                 );
1130                                 return false;
1131                         } else {
1132                                 set_config('database','update_' . $x, 'success');
1133                                 set_config('system','build', $x + 1);
1134                                 return true;
1135                         }
1136                 } else {
1137                         set_config('database','update_' . $x, 'success');
1138                         set_config('system','build', $x + 1);
1139                         return true;
1140                 }
1141                 return true;
1142         }
1143 }
1144
1145
1146 if(! function_exists('check_plugins')) {
1147         function check_plugins(&$a) {
1148
1149                 /**
1150                  *
1151                  * Synchronise plugins:
1152                  *
1153                  * $a->config['system']['addon'] contains a comma-separated list of names
1154                  * of plugins/addons which are used on this system.
1155                  * Go through the database list of already installed addons, and if we have
1156                  * an entry, but it isn't in the config list, call the uninstall procedure
1157                  * and mark it uninstalled in the database (for now we'll remove it).
1158                  * Then go through the config list and if we have a plugin that isn't installed,
1159                  * call the install procedure and add it to the database.
1160                  *
1161                  */
1162
1163                 $r = q("SELECT * FROM `addon` WHERE `installed` = 1");
1164                 if(count($r))
1165                         $installed = $r;
1166                 else
1167                         $installed = array();
1168
1169                 $plugins = get_config('system','addon');
1170                 $plugins_arr = array();
1171
1172                 if($plugins)
1173                         $plugins_arr = explode(',',str_replace(' ', '',$plugins));
1174
1175                 $a->plugins = $plugins_arr;
1176
1177                 $installed_arr = array();
1178
1179                 if(count($installed)) {
1180                         foreach($installed as $i) {
1181                                 if(! in_array($i['name'],$plugins_arr)) {
1182                                         uninstall_plugin($i['name']);
1183                                 }
1184                                 else {
1185                                         $installed_arr[] = $i['name'];
1186                                 }
1187                         }
1188                 }
1189
1190                 if(count($plugins_arr)) {
1191                         foreach($plugins_arr as $p) {
1192                                 if(! in_array($p,$installed_arr)) {
1193                                         install_plugin($p);
1194                                 }
1195                         }
1196                 }
1197
1198
1199                 load_hooks();
1200
1201                 return;
1202         }
1203 }
1204
1205 function get_guid($size=16, $prefix = "") {
1206
1207         if ($prefix == "") {
1208                 $a = get_app();
1209                 $prefix = hash("crc32", $a->get_hostname());
1210         }
1211
1212         while (strlen($prefix) < ($size - 13))
1213                 $prefix .= mt_rand();
1214
1215         if ($size >= 24) {
1216                 $prefix = substr($prefix, 0, $size - 22);
1217                 return(str_replace(".", "", uniqid($prefix, true)));
1218         } else {
1219                 $prefix = substr($prefix, 0, $size - 13);
1220                 return(uniqid($prefix));
1221         }
1222 }
1223
1224 // wrapper for adding a login box. If $register == true provide a registration
1225 // link. This will most always depend on the value of $a->config['register_policy'].
1226 // returns the complete html for inserting into the page
1227
1228 if(! function_exists('login')) {
1229         function login($register = false, $hiddens=false) {
1230                 $a = get_app();
1231                 $o = "";
1232                 $reg = false;
1233                 if ($register) {
1234                         $reg = array(
1235                                 'title' => t('Create a New Account'),
1236                                 'desc' => t('Register')
1237                         );
1238                 }
1239
1240                 $noid = get_config('system','no_openid');
1241
1242                 $dest_url = $a->get_baseurl(true) . '/' . $a->query_string;
1243
1244                 if(local_user()) {
1245                         $tpl = get_markup_template("logout.tpl");
1246                 }
1247                 else {
1248                         $a->page['htmlhead'] .= replace_macros(get_markup_template("login_head.tpl"),array(
1249                                 '$baseurl'              => $a->get_baseurl(true)
1250                         ));
1251
1252                         $tpl = get_markup_template("login.tpl");
1253                         $_SESSION['return_url'] = $a->query_string;
1254                         $a->module = 'login';
1255                 }
1256
1257                 $o .= replace_macros($tpl, array(
1258
1259                         '$dest_url'     => $dest_url,
1260                         '$logout'       => t('Logout'),
1261                         '$login'        => t('Login'),
1262
1263                         '$lname'                => array('username', t('Nickname or Email address: ') , '', ''),
1264                         '$lpassword'    => array('password', t('Password: '), '', ''),
1265                         '$lremember'    => array('remember', t('Remember me'), 0,  ''),
1266
1267                         '$openid'               => !$noid,
1268                         '$lopenid'      => array('openid_url', t('Or login using OpenID: '),'',''),
1269
1270                         '$hiddens'      => $hiddens,
1271
1272                         '$register'     => $reg,
1273
1274                         '$lostpass'     => t('Forgot your password?'),
1275                         '$lostlink'     => t('Password Reset'),
1276
1277                         '$tostitle'     => t('Website Terms of Service'),
1278                         '$toslink'      => t('terms of service'),
1279
1280                         '$privacytitle' => t('Website Privacy Policy'),
1281                         '$privacylink'  => t('privacy policy'),
1282
1283                 ));
1284
1285                 call_hooks('login_hook',$o);
1286
1287                 return $o;
1288         }
1289 }
1290
1291 // Used to end the current process, after saving session state.
1292
1293 if(! function_exists('killme')) {
1294         function killme() {
1295                 session_write_close();
1296                 exit;
1297         }
1298 }
1299
1300 // redirect to another URL and terminate this process.
1301
1302 if(! function_exists('goaway')) {
1303         function goaway($s) {
1304                 header("Location: $s");
1305                 killme();
1306         }
1307 }
1308
1309
1310 // Returns the uid of locally logged in user or false.
1311
1312 if(! function_exists('local_user')) {
1313         function local_user() {
1314                 if((x($_SESSION,'authenticated')) && (x($_SESSION,'uid')))
1315                         return intval($_SESSION['uid']);
1316                 return false;
1317         }
1318 }
1319
1320 // Returns contact id of authenticated site visitor or false
1321
1322 if(! function_exists('remote_user')) {
1323         function remote_user() {
1324                 if((x($_SESSION,'authenticated')) && (x($_SESSION,'visitor_id')))
1325                         return intval($_SESSION['visitor_id']);
1326                 return false;
1327         }
1328 }
1329
1330 // contents of $s are displayed prominently on the page the next time
1331 // a page is loaded. Usually used for errors or alerts.
1332
1333 if(! function_exists('notice')) {
1334         /**
1335          * Show an error message to user.
1336          *
1337          * This function save text in session, to be shown to the user at next page load
1338          *
1339          * @param string $s - Text of notice
1340          */
1341         function notice($s) {
1342                 $a = get_app();
1343                 if(! x($_SESSION,'sysmsg'))     $_SESSION['sysmsg'] = array();
1344                 if($a->interactive)
1345                         $_SESSION['sysmsg'][] = $s;
1346         }
1347 }
1348 if(! function_exists('info')) {
1349         /**
1350          * Show an info message to user.
1351          *
1352          * This function save text in session, to be shown to the user at next page load
1353          *
1354          * @param string $s - Text of notice
1355          */
1356         function info($s) {
1357                 $a = get_app();
1358
1359                 if (local_user() AND get_pconfig(local_user(),'system','ignore_info'))
1360                         return;
1361
1362                 if(! x($_SESSION,'sysmsg_info')) $_SESSION['sysmsg_info'] = array();
1363                 if($a->interactive)
1364                         $_SESSION['sysmsg_info'][] = $s;
1365         }
1366 }
1367
1368
1369 // wrapper around config to limit the text length of an incoming message
1370
1371 if(! function_exists('get_max_import_size')) {
1372         function get_max_import_size() {
1373                 global $a;
1374                 return ((x($a->config,'max_import_size')) ? $a->config['max_import_size'] : 0 );
1375         }
1376 }
1377
1378
1379
1380 /**
1381  *
1382  * Function : profile_load
1383  * @parameter App    $a
1384  * @parameter string $nickname
1385  * @parameter int    $profile
1386  *
1387  * Summary: Loads a profile into the page sidebar.
1388  * The function requires a writeable copy of the main App structure, and the nickname
1389  * of a registered local account.
1390  *
1391  * If the viewer is an authenticated remote viewer, the profile displayed is the
1392  * one that has been configured for his/her viewing in the Contact manager.
1393  * Passing a non-zero profile ID can also allow a preview of a selected profile
1394  * by the owner.
1395  *
1396  * Profile information is placed in the App structure for later retrieval.
1397  * Honours the owner's chosen theme for display.
1398  *
1399  * IMPORTANT: Should only be run in the _init() functions of a module. That ensures that
1400  * the theme is chosen before the _init() function of a theme is run, which will usually
1401  * load a lot of theme-specific content
1402  *
1403  */
1404
1405 if(! function_exists('profile_load')) {
1406         function profile_load(&$a, $nickname, $profile = 0, $profiledata = array()) {
1407
1408                 $user = q("SELECT `uid` FROM `user` WHERE `nickname` = '%s' LIMIT 1",
1409                         dbesc($nickname)
1410                 );
1411
1412                 if(!$user && count($user) && !count($profiledata)) {
1413                         logger('profile error: ' . $a->query_string, LOGGER_DEBUG);
1414                         notice( t('Requested account is not available.') . EOL );
1415                         $a->error = 404;
1416                         return;
1417                 }
1418
1419                 if(remote_user() && count($_SESSION['remote'])) {
1420                         foreach($_SESSION['remote'] as $visitor) {
1421                                 if($visitor['uid'] == $user[0]['uid']) {
1422                                         $r = q("SELECT `profile-id` FROM `contact` WHERE `id` = %d LIMIT 1",
1423                                                 intval($visitor['cid'])
1424                                         );
1425                                         if(count($r))
1426                                                 $profile = $r[0]['profile-id'];
1427                                         break;
1428                                 }
1429                         }
1430                 }
1431
1432                 $r = null;
1433
1434                 if($profile) {
1435                         $profile_int = intval($profile);
1436                         $r = q("SELECT `profile`.`uid` AS `profile_uid`, `profile`.* , `contact`.`avatar-date` AS picdate, `user`.* FROM `profile`
1437                                         INNER JOIN `contact` on `contact`.`uid` = `profile`.`uid` INNER JOIN `user` ON `profile`.`uid` = `user`.`uid`
1438                                         WHERE `user`.`nickname` = '%s' AND `profile`.`id` = %d and `contact`.`self` = 1 LIMIT 1",
1439                                         dbesc($nickname),
1440                                         intval($profile_int)
1441                         );
1442                 }
1443                 if((!$r) && (!count($r))) {
1444                         $r = q("SELECT `profile`.`uid` AS `profile_uid`, `profile`.* , `contact`.`avatar-date` AS picdate, `user`.* FROM `profile`
1445                                         INNER JOIN `contact` on `contact`.`uid` = `profile`.`uid` INNER JOIN `user` ON `profile`.`uid` = `user`.`uid`
1446                                         WHERE `user`.`nickname` = '%s' AND `profile`.`is-default` = 1 and `contact`.`self` = 1 LIMIT 1",
1447                                         dbesc($nickname)
1448                         );
1449                 }
1450
1451                 if(($r === false) || (!count($r)) && !count($profiledata)) {
1452                         logger('profile error: ' . $a->query_string, LOGGER_DEBUG);
1453                         notice( t('Requested profile is not available.') . EOL );
1454                         $a->error = 404;
1455                         return;
1456                 }
1457
1458                 // fetch user tags if this isn't the default profile
1459
1460                 if(!$r[0]['is-default']) {
1461                         $x = q("select `pub_keywords` from `profile` where uid = %d and `is-default` = 1 limit 1",
1462                                         intval($r[0]['profile_uid'])
1463                         );
1464                         if($x && count($x))
1465                                 $r[0]['pub_keywords'] = $x[0]['pub_keywords'];
1466                 }
1467
1468                 $a->profile = $r[0];
1469
1470                 $a->profile['mobile-theme'] = get_pconfig($a->profile['profile_uid'], 'system', 'mobile_theme');
1471                 $a->profile['network'] = NETWORK_DFRN;
1472
1473                 $a->page['title'] = $a->profile['name'] . " @ " . $a->config['sitename'];
1474
1475                 if (!$profiledata)
1476                         $_SESSION['theme'] = $a->profile['theme'];
1477
1478                 $_SESSION['mobile-theme'] = $a->profile['mobile-theme'];
1479
1480                 /**
1481                  * load/reload current theme info
1482                  */
1483
1484                 $a->set_template_engine(); // reset the template engine to the default in case the user's theme doesn't specify one
1485
1486                 $theme_info_file = "view/theme/".current_theme()."/theme.php";
1487                 if (file_exists($theme_info_file)){
1488                         require_once($theme_info_file);
1489                 }
1490
1491                 if(! (x($a->page,'aside')))
1492                         $a->page['aside'] = '';
1493
1494                 if(local_user() && local_user() == $a->profile['uid'] && $profiledata) {
1495                         $a->page['aside'] .= replace_macros(get_markup_template('profile_edlink.tpl'),array(
1496                                 '$editprofile' => t('Edit profile'),
1497                                 '$profid' => $a->profile['id']
1498                         ));
1499                 }
1500
1501                 $block = (((get_config('system','block_public')) && (! local_user()) && (! remote_user())) ? true : false);
1502
1503                 // To-Do:
1504                 // By now, the contact block isn't shown, when a different profile is given
1505                 // But: When this profile was on the same server, then we could display the contacts
1506                 if ($profiledata)
1507                         $a->page['aside'] .= profile_sidebar($profiledata, true);
1508                 else
1509                         $a->page['aside'] .= profile_sidebar($a->profile, $block);
1510
1511
1512                 /*if(! $block)
1513                  $a->page['aside'] .= contact_block();*/
1514
1515                 return;
1516         }
1517 }
1518
1519
1520 /**
1521  *
1522  * Function: profile_sidebar
1523  *
1524  * Formats a profile for display in the sidebar.
1525  * It is very difficult to templatise the HTML completely
1526  * because of all the conditional logic.
1527  *
1528  * @parameter: array $profile
1529  *
1530  * Returns HTML string stuitable for sidebar inclusion
1531  * Exceptions: Returns empty string if passed $profile is wrong type or not populated
1532  *
1533  */
1534
1535
1536 if(! function_exists('profile_sidebar')) {
1537         function profile_sidebar($profile, $block = 0) {
1538                 $a = get_app();
1539
1540                 $o = '';
1541                 $location = false;
1542                 $address = false;
1543                 $pdesc = true;
1544
1545                 if((! is_array($profile)) && (! count($profile)))
1546                         return $o;
1547
1548                 $profile['picdate'] = urlencode($profile['picdate']);
1549
1550                 if (($profile['network'] != "") AND ($profile['network'] != NETWORK_DFRN)) {
1551                         require_once('include/contact_selectors.php');
1552                         if ($profile['url'] != "")
1553                                 $profile['network_name'] = '<a href="'.$profile['url'].'">'.network_to_name($profile['network'])."</a>";
1554                         else
1555                                 $profile['network_name'] = network_to_name($profile['network']);
1556                 } else
1557                         $profile['network_name'] = "";
1558
1559                 call_hooks('profile_sidebar_enter', $profile);
1560
1561
1562                 // don't show connect link to yourself
1563                 $connect = (($profile['uid'] != local_user()) ? t('Connect')  : False);
1564
1565                 // don't show connect link to authenticated visitors either
1566                 if(remote_user() && count($_SESSION['remote'])) {
1567                         foreach($_SESSION['remote'] as $visitor) {
1568                                 if($visitor['uid'] == $profile['uid']) {
1569                                         $connect = false;
1570                                         break;
1571                                 }
1572                         }
1573                 }
1574
1575                 // Is the local user already connected to that user?
1576                 if ($connect AND local_user()) {
1577                         if (isset($profile["url"]))
1578                                 $profile_url = normalise_link($profile["url"]);
1579                         else
1580                                 $profile_url = normalise_link($a->get_baseurl()."/profile/".$profile["nickname"]);
1581
1582                         $r = q("SELECT * FROM `contact` WHERE NOT `pending` AND `uid` = %d AND `nurl` = '%s'",
1583                                 local_user(), $profile_url);
1584                         if (count($r))
1585                                 $connect = false;
1586                 }
1587
1588                 if ($connect AND ($profile['network'] != NETWORK_DFRN) AND !isset($profile['remoteconnect']))
1589                                 $connect = false;
1590
1591                 if (isset($profile['remoteconnect']))
1592                         $remoteconnect = $profile['remoteconnect'];
1593
1594                 if( get_my_url() && $profile['unkmail'] && ($profile['uid'] != local_user()) )
1595                         $wallmessage = t('Message');
1596                 else
1597                         $wallmessage = false;
1598
1599                 // show edit profile to yourself
1600                 if ($profile['uid'] == local_user() && feature_enabled(local_user(),'multi_profiles')) {
1601                         $profile['edit'] = array($a->get_baseurl(). '/profiles', t('Profiles'),"", t('Manage/edit profiles'));
1602                         $r = q("SELECT * FROM `profile` WHERE `uid` = %d",
1603                                         local_user());
1604
1605                         $profile['menu'] = array(
1606                                 'chg_photo' => t('Change profile photo'),
1607                                 'cr_new' => t('Create New Profile'),
1608                                 'entries' => array(),
1609                         );
1610
1611                         if(count($r)) {
1612
1613                                 foreach($r as $rr) {
1614                                         $profile['menu']['entries'][] = array(
1615                                                 'photo' => $rr['thumb'],
1616                                                 'id' => $rr['id'],
1617                                                 'alt' => t('Profile Image'),
1618                                                 'profile_name' => $rr['profile-name'],
1619                                                 'isdefault' => $rr['is-default'],
1620                                                 'visibile_to_everybody' =>  t('visible to everybody'),
1621                                                 'edit_visibility' => t('Edit visibility'),
1622
1623                                         );
1624                                 }
1625
1626
1627                         }
1628                 }
1629                 if ($profile['uid'] == local_user() && !feature_enabled(local_user(),'multi_profiles')) {
1630                         $profile['edit'] = array($a->get_baseurl(). '/profiles/'.$profile['id'], t('Edit profile'),"", t('Edit profile'));
1631                         $profile['menu'] = array(
1632                                 'chg_photo' => t('Change profile photo'),
1633                                 'cr_new' => null,
1634                                 'entries' => array(),
1635                         );
1636                 }
1637
1638                 if((x($profile,'address') == 1)
1639                                 || (x($profile,'locality') == 1)
1640                                 || (x($profile,'region') == 1)
1641                                 || (x($profile,'postal-code') == 1)
1642                                 || (x($profile,'country-name') == 1))
1643                         $location = t('Location:');
1644
1645                 $gender = ((x($profile,'gender') == 1) ? t('Gender:') : False);
1646
1647
1648                 $marital = ((x($profile,'marital') == 1) ?  t('Status:') : False);
1649
1650                 $homepage = ((x($profile,'homepage') == 1) ?  t('Homepage:') : False);
1651
1652                 $about = ((x($profile,'about') == 1) ?  t('About:') : False);
1653
1654                 if(($profile['hidewall'] || $block) && (! local_user()) && (! remote_user())) {
1655                         $location = $pdesc = $gender = $marital = $homepage = $about = False;
1656                 }
1657
1658                 $firstname = ((strpos($profile['name'],' '))
1659                                 ? trim(substr($profile['name'],0,strpos($profile['name'],' '))) : $profile['name']);
1660                 $lastname = (($firstname === $profile['name']) ? '' : trim(substr($profile['name'],strlen($firstname))));
1661
1662                 $diaspora = array(
1663                         'podloc' => $a->get_baseurl(),
1664                         'searchable' => (($profile['publish'] && $profile['net-publish']) ? 'true' : 'false' ),
1665                         'nickname' => $profile['nickname'],
1666                         'fullname' => $profile['name'],
1667                         'firstname' => $firstname,
1668                         'lastname' => $lastname,
1669                         'photo300' => $a->get_cached_avatar_image($a->get_baseurl() . '/photo/custom/300/' . $profile['uid'] . '.jpg'),
1670                         'photo100' => $a->get_cached_avatar_image($a->get_baseurl() . '/photo/custom/100/' . $profile['uid'] . '.jpg'),
1671                         'photo50' => $a->get_cached_avatar_image($a->get_baseurl() . '/photo/custom/50/'  . $profile['uid'] . '.jpg'),
1672                 );
1673
1674                 if (!$block){
1675                         $contact_block = contact_block();
1676
1677                         if(is_array($a->profile) AND !$a->profile['hide-friends']) {
1678                                 $r = q("SELECT `gcontact`.`updated` FROM `contact` INNER JOIN `gcontact` WHERE `gcontact`.`nurl` = `contact`.`nurl` AND `self` AND `uid` = %d LIMIT 1",
1679                                         intval($a->profile['uid']));
1680                                 if(count($r))
1681                                         $updated =  date("c", strtotime($r[0]['updated']));
1682
1683                                 $r = q("SELECT COUNT(*) AS `total` FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 and `pending` = 0 AND `hidden` = 0 AND `archive` = 0
1684                                                 AND `network` IN ('%s', '%s', '%s', '')",
1685                                         intval($profile['uid']),
1686                                         dbesc(NETWORK_DFRN),
1687                                         dbesc(NETWORK_DIASPORA),
1688                                         dbesc(NETWORK_OSTATUS)
1689                                 );
1690                                 if(count($r))
1691                                         $contacts = intval($r[0]['total']);
1692                         }
1693                 }
1694
1695                 $p = array();
1696                 foreach($profile as $k => $v) {
1697                         $k = str_replace('-','_',$k);
1698                         $p[$k] = $v;
1699                 }
1700
1701                 if($a->theme['template_engine'] === 'internal')
1702                         $location = template_escape($location);
1703
1704                 $tpl = get_markup_template('profile_vcard.tpl');
1705                 $o .= replace_macros($tpl, array(
1706                         '$profile' => $p,
1707                         '$connect'  => $connect,
1708                         '$remoteconnect'  => $remoteconnect,
1709                         '$wallmessage' => $wallmessage,
1710                         '$location' => $location,
1711                         '$gender'   => $gender,
1712                         '$pdesc'        => $pdesc,
1713                         '$marital'  => $marital,
1714                         '$homepage' => $homepage,
1715                         '$about' => $about,
1716                         '$network' =>  t('Network:'),
1717                         '$contacts' => $contacts,
1718                         '$updated' => $updated,
1719                         '$diaspora' => $diaspora,
1720                         '$contact_block' => $contact_block,
1721                 ));
1722
1723
1724                 $arr = array('profile' => &$profile, 'entry' => &$o);
1725
1726                 call_hooks('profile_sidebar', $arr);
1727
1728                 return $o;
1729         }
1730 }
1731
1732
1733 if(! function_exists('get_birthdays')) {
1734         function get_birthdays() {
1735
1736                 $a = get_app();
1737                 $o = '';
1738
1739                 if(! local_user() || $a->is_mobile || $a->is_tablet)
1740                         return $o;
1741
1742 //              $mobile_detect = new Mobile_Detect();
1743 //              $is_mobile = $mobile_detect->isMobile() || $mobile_detect->isTablet();
1744
1745 //              if($is_mobile)
1746 //                      return $o;
1747
1748                 $bd_format = t('g A l F d') ; // 8 AM Friday January 18
1749                 $bd_short = t('F d');
1750
1751                 $r = q("SELECT `event`.*, `event`.`id` AS `eid`, `contact`.* FROM `event`
1752                                 INNER JOIN `contact` ON `contact`.`id` = `event`.`cid`
1753                                 WHERE `event`.`uid` = %d AND `type` = 'birthday' AND `start` < '%s' AND `finish` > '%s'
1754                                 ORDER BY `start` ASC ",
1755                                 intval(local_user()),
1756                                 dbesc(datetime_convert('UTC','UTC','now + 6 days')),
1757                                 dbesc(datetime_convert('UTC','UTC','now'))
1758                 );
1759
1760                 if($r && count($r)) {
1761                         $total = 0;
1762                         $now = strtotime('now');
1763                         $cids = array();
1764
1765                         $istoday = false;
1766                         foreach($r as $rr) {
1767                                 if(strlen($rr['name']))
1768                                         $total ++;
1769                                 if((strtotime($rr['start'] . ' +00:00') < $now) && (strtotime($rr['finish'] . ' +00:00') > $now))
1770                                         $istoday = true;
1771                         }
1772                         $classtoday = $istoday ? ' birthday-today ' : '';
1773                         if($total) {
1774                                 foreach($r as &$rr) {
1775                                         if(! strlen($rr['name']))
1776                                                 continue;
1777
1778                                         // avoid duplicates
1779
1780                                         if(in_array($rr['cid'],$cids))
1781                                                 continue;
1782                                         $cids[] = $rr['cid'];
1783
1784                                         $today = (((strtotime($rr['start'] . ' +00:00') < $now) && (strtotime($rr['finish'] . ' +00:00') > $now)) ? true : false);
1785                                         $sparkle = '';
1786                                         $url = $rr['url'];
1787                                         if($rr['network'] === NETWORK_DFRN) {
1788                                                 $sparkle = " sparkle";
1789                                                 $url = $a->get_baseurl() . '/redir/'  . $rr['cid'];
1790                                         }
1791
1792                                         $rr['link'] = $url;
1793                                         $rr['title'] = $rr['name'];
1794                                         $rr['date'] = day_translate(datetime_convert('UTC', $a->timezone, $rr['start'], $rr['adjust'] ? $bd_format : $bd_short)) . (($today) ?  ' ' . t('[today]') : '');
1795                                         $rr['startime'] = Null;
1796                                         $rr['today'] = $today;
1797
1798                                 }
1799                         }
1800                 }
1801                 $tpl = get_markup_template("birthdays_reminder.tpl");
1802                 return replace_macros($tpl, array(
1803                         '$baseurl' => $a->get_baseurl(),
1804                         '$classtoday' => $classtoday,
1805                         '$count' => $total,
1806                         '$event_reminders' => t('Birthday Reminders'),
1807                         '$event_title' => t('Birthdays this week:'),
1808                         '$events' => $r,
1809                         '$lbr' => '{',  // raw brackets mess up if/endif macro processing
1810                         '$rbr' => '}'
1811
1812                 ));
1813         }
1814 }
1815
1816
1817 if(! function_exists('get_events')) {
1818         function get_events() {
1819
1820                 require_once('include/bbcode.php');
1821
1822                 $a = get_app();
1823
1824                 if(! local_user() || $a->is_mobile || $a->is_tablet)
1825                         return $o;
1826
1827
1828 //              $mobile_detect = new Mobile_Detect();
1829 //              $is_mobile = $mobile_detect->isMobile() || $mobile_detect->isTablet();
1830
1831 //              if($is_mobile)
1832 //                      return $o;
1833
1834                 $bd_format = t('g A l F d') ; // 8 AM Friday January 18
1835                 $bd_short = t('F d');
1836
1837                 $r = q("SELECT `event`.* FROM `event`
1838                                 WHERE `event`.`uid` = %d AND `type` != 'birthday' AND `start` < '%s' AND `start` >= '%s'
1839                                 ORDER BY `start` ASC ",
1840                                 intval(local_user()),
1841                                 dbesc(datetime_convert('UTC','UTC','now + 7 days')),
1842                                 dbesc(datetime_convert('UTC','UTC','now - 1 days'))
1843                 );
1844
1845                 if($r && count($r)) {
1846                         $now = strtotime('now');
1847                         $istoday = false;
1848                         foreach($r as $rr) {
1849                                 if(strlen($rr['name']))
1850                                         $total ++;
1851
1852                                 $strt = datetime_convert('UTC',$rr['convert'] ? $a->timezone : 'UTC',$rr['start'],'Y-m-d');
1853                                 if($strt === datetime_convert('UTC',$a->timezone,'now','Y-m-d'))
1854                                         $istoday = true;
1855                         }
1856                         $classtoday = (($istoday) ? 'event-today' : '');
1857
1858                         $skip = 0;
1859
1860                         foreach($r as &$rr) {
1861                                 if($rr['adjust'])
1862                                         $md = datetime_convert('UTC',$a->timezone,$rr['start'],'Y/m');
1863                                 else
1864                                         $md = datetime_convert('UTC','UTC',$rr['start'],'Y/m');
1865                                 $md .= "/#link-".$rr['id'];
1866
1867                                 $title = substr(strip_tags(bbcode($rr['desc'])),0,32) . '... ';
1868                                 if(! $title)
1869                                         $title = t('[No description]');
1870
1871                                 $strt = datetime_convert('UTC',$rr['convert'] ? $a->timezone : 'UTC',$rr['start']);
1872
1873                                 if(substr($strt,0,10) < datetime_convert('UTC',$a->timezone,'now','Y-m-d')) {
1874                                         $skip++;
1875                                         continue;
1876                                 }
1877
1878                                 $today = ((substr($strt,0,10) === datetime_convert('UTC',$a->timezone,'now','Y-m-d')) ? true : false);
1879
1880                                 $rr['link'] = $md;
1881                                 $rr['title'] = $title;
1882                                 $rr['date'] = day_translate(datetime_convert('UTC', $rr['adjust'] ? $a->timezone : 'UTC', $rr['start'], $bd_format)) . (($today) ?  ' ' . t('[today]') : '');
1883                                 $rr['startime'] = $strt;
1884                                 $rr['today'] = $today;
1885                         }
1886                 }
1887
1888                 $tpl = get_markup_template("events_reminder.tpl");
1889                 return replace_macros($tpl, array(
1890                         '$baseurl' => $a->get_baseurl(),
1891                         '$classtoday' => $classtoday,
1892                         '$count' => count($r) - $skip,
1893                         '$event_reminders' => t('Event Reminders'),
1894                         '$event_title' => t('Events this week:'),
1895                         '$events' => $r,
1896                 ));
1897         }
1898 }
1899
1900
1901 /**
1902  *
1903  * Wrap calls to proc_close(proc_open()) and call hook
1904  * so plugins can take part in process :)
1905  *
1906  * args:
1907  * $cmd program to run
1908  *  next args are passed as $cmd command line
1909  *
1910  * e.g.: proc_run("ls","-la","/tmp");
1911  *
1912  * $cmd and string args are surrounded with ""
1913  */
1914
1915 if(! function_exists('proc_run')) {
1916         function proc_run($cmd){
1917
1918                 $a = get_app();
1919
1920                 $args = func_get_args();
1921
1922                 $newargs = array();
1923                 if(! count($args))
1924                         return;
1925
1926                 // expand any arrays
1927
1928                 foreach($args as $arg) {
1929                         if(is_array($arg)) {
1930                                 foreach($arg as $n) {
1931                                         $newargs[] = $n;
1932                                 }
1933                         }
1934                         else
1935                                 $newargs[] = $arg;
1936                 }
1937
1938                 $args = $newargs;
1939
1940                 $arr = array('args' => $args, 'run_cmd' => true);
1941
1942                 call_hooks("proc_run", $arr);
1943                 if(! $arr['run_cmd'])
1944                         return;
1945
1946                 if(count($args) && $args[0] === 'php')
1947                         $args[0] = ((x($a->config,'php_path')) && (strlen($a->config['php_path'])) ? $a->config['php_path'] : 'php');
1948
1949         // add baseurl to args. cli scripts can't construct it
1950         $args[] = $a->get_baseurl();
1951
1952         for($x = 0; $x < count($args); $x ++)
1953                         $args[$x] = escapeshellarg($args[$x]);
1954
1955
1956
1957                 $cmdline = implode($args," ");
1958                 if(get_config('system','proc_windows'))
1959                         proc_close(proc_open('cmd /c start /b ' . $cmdline,array(),$foo,dirname(__FILE__)));
1960                 else
1961                         proc_close(proc_open($cmdline." &",array(),$foo,dirname(__FILE__)));
1962         }
1963 }
1964
1965 if(! function_exists('current_theme')) {
1966         function current_theme(){
1967                 $app_base_themes = array('duepuntozero', 'dispy', 'quattro');
1968
1969                 $a = get_app();
1970
1971 //              $mobile_detect = new Mobile_Detect();
1972 //              $is_mobile = $mobile_detect->isMobile() || $mobile_detect->isTablet();
1973                 $is_mobile = $a->is_mobile || $a->is_tablet;
1974
1975                 if($is_mobile) {
1976                         if(isset($_SESSION['show-mobile']) && !$_SESSION['show-mobile']) {
1977                                 $system_theme = '';
1978                                 $theme_name = '';
1979                         }
1980                         else {
1981                                 $system_theme = ((isset($a->config['system']['mobile-theme'])) ? $a->config['system']['mobile-theme'] : '');
1982                                 $theme_name = ((isset($_SESSION) && x($_SESSION,'mobile-theme')) ? $_SESSION['mobile-theme'] : $system_theme);
1983
1984                                 if($theme_name === '---') {
1985                                         // user has selected to have the mobile theme be the same as the normal one
1986                                         $system_theme = '';
1987                                         $theme_name = '';
1988                                 }
1989                         }
1990                 }
1991                 if(!$is_mobile || ($system_theme === '' && $theme_name === '')) {
1992                         $system_theme = ((isset($a->config['system']['theme'])) ? $a->config['system']['theme'] : '');
1993                         $theme_name = ((isset($_SESSION) && x($_SESSION,'theme')) ? $_SESSION['theme'] : $system_theme);
1994                 }
1995
1996                 if($theme_name &&
1997                                 (file_exists('view/theme/' . $theme_name . '/style.css') ||
1998                                                 file_exists('view/theme/' . $theme_name . '/style.php')))
1999                         return($theme_name);
2000
2001                 foreach($app_base_themes as $t) {
2002                         if(file_exists('view/theme/' . $t . '/style.css')||
2003                                         file_exists('view/theme/' . $t . '/style.php'))
2004                                 return($t);
2005                 }
2006
2007                 $fallback = array_merge(glob('view/theme/*/style.css'),glob('view/theme/*/style.php'));
2008                 if(count($fallback))
2009                         return (str_replace('view/theme/','', substr($fallback[0],0,-10)));
2010
2011         }
2012 }
2013
2014 /*
2015  * Return full URL to theme which is currently in effect.
2016 * Provide a sane default if nothing is chosen or the specified theme does not exist.
2017 */
2018 if(! function_exists('current_theme_url')) {
2019         function current_theme_url() {
2020                 global $a;
2021                 $t = current_theme();
2022                 if (file_exists('view/theme/' . $t . '/style.php'))
2023                         return($a->get_baseurl() . '/view/theme/' . $t . '/style.pcss');
2024                 return($a->get_baseurl() . '/view/theme/' . $t . '/style.css');
2025         }
2026 }
2027
2028 if(! function_exists('feed_birthday')) {
2029         function feed_birthday($uid,$tz) {
2030
2031                 /**
2032                  *
2033                  * Determine the next birthday, but only if the birthday is published
2034                  * in the default profile. We _could_ also look for a private profile that the
2035                  * recipient can see, but somebody could get mad at us if they start getting
2036                  * public birthday greetings when they haven't made this info public.
2037                  *
2038                  * Assuming we are able to publish this info, we are then going to convert
2039                  * the start time from the owner's timezone to UTC.
2040                  *
2041                  * This will potentially solve the problem found with some social networks
2042                  * where birthdays are converted to the viewer's timezone and salutations from
2043                  * elsewhere in the world show up on the wrong day. We will convert it to the
2044                  * viewer's timezone also, but first we are going to convert it from the birthday
2045                  * person's timezone to GMT - so the viewer may find the birthday starting at
2046                  * 6:00PM the day before, but that will correspond to midnight to the birthday person.
2047                  *
2048                  */
2049
2050
2051                 $birthday = '';
2052
2053                 if(! strlen($tz))
2054                         $tz = 'UTC';
2055
2056                 $p = q("SELECT `dob` FROM `profile` WHERE `is-default` = 1 AND `uid` = %d LIMIT 1",
2057                                 intval($uid)
2058                 );
2059
2060                 if($p && count($p)) {
2061                         $tmp_dob = substr($p[0]['dob'],5);
2062                         if(intval($tmp_dob)) {
2063                                 $y = datetime_convert($tz,$tz,'now','Y');
2064                                 $bd = $y . '-' . $tmp_dob . ' 00:00';
2065                                 $t_dob = strtotime($bd);
2066                                 $now = strtotime(datetime_convert($tz,$tz,'now'));
2067                                 if($t_dob < $now)
2068                                         $bd = $y + 1 . '-' . $tmp_dob . ' 00:00';
2069                                 $birthday = datetime_convert($tz,'UTC',$bd,ATOM_TIME);
2070                         }
2071                 }
2072
2073                 return $birthday;
2074         }
2075 }
2076
2077 if(! function_exists('is_site_admin')) {
2078         function is_site_admin() {
2079                 $a = get_app();
2080
2081                 $adminlist = explode(",", str_replace(" ", "", $a->config['admin_email']));
2082
2083                 //if(local_user() && x($a->user,'email') && x($a->config,'admin_email') && ($a->user['email'] === $a->config['admin_email']))
2084                 if(local_user() && x($a->user,'email') && x($a->config,'admin_email') && in_array($a->user['email'], $adminlist))
2085                         return true;
2086                 return false;
2087         }
2088 }
2089
2090
2091 if(! function_exists('load_contact_links')) {
2092         function load_contact_links($uid) {
2093
2094                 $a = get_app();
2095
2096                 $ret = array();
2097
2098                 if(! $uid || x($a->contacts,'empty'))
2099                         return;
2100
2101                 $r = q("SELECT `id`,`network`,`url`,`thumb` FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 AND `thumb` != ''",
2102                                 intval($uid)
2103                 );
2104                 if(count($r)) {
2105                         foreach($r as $rr){
2106                                 $url = normalise_link($rr['url']);
2107                                 $ret[$url] = $rr;
2108                         }
2109                 }
2110                 else
2111                         $ret['empty'] = true;
2112                 $a->contacts = $ret;
2113                 return;
2114         }
2115 }
2116
2117 if(! function_exists('profile_tabs')){
2118         function profile_tabs($a, $is_owner=False, $nickname=Null){
2119                 //echo "<pre>"; var_dump($a->user); killme();
2120
2121                 if (is_null($nickname))
2122                         $nickname  = $a->user['nickname'];
2123
2124                 if(x($_GET,'tab'))
2125                         $tab = notags(trim($_GET['tab']));
2126
2127                 $url = $a->get_baseurl() . '/profile/' . $nickname;
2128
2129                 $tabs = array(
2130                         array(
2131                                 'label'=>t('Status'),
2132                                 'url' => $url,
2133                                 'sel' => ((!isset($tab)&&$a->argv[0]=='profile')?'active':''),
2134                                 'title' => t('Status Messages and Posts'),
2135                                 'id' => 'status-tab',
2136                         ),
2137                         array(
2138                                 'label' => t('Profile'),
2139                                 'url'   => $url.'/?tab=profile',
2140                                 'sel'   => ((isset($tab) && $tab=='profile')?'active':''),
2141                                 'title' => t('Profile Details'),
2142                                 'id' => 'profile-tab',
2143                         ),
2144                         array(
2145                                 'label' => t('Photos'),
2146                                 'url'   => $a->get_baseurl() . '/photos/' . $nickname,
2147                                 'sel'   => ((!isset($tab)&&$a->argv[0]=='photos')?'active':''),
2148                                 'title' => t('Photo Albums'),
2149                                 'id' => 'photo-tab',
2150                         ),
2151                         array(
2152                                 'label' => t('Videos'),
2153                                 'url'   => $a->get_baseurl() . '/videos/' . $nickname,
2154                                 'sel'   => ((!isset($tab)&&$a->argv[0]=='videos')?'active':''),
2155                                 'title' => t('Videos'),
2156                                 'id' => 'video-tab',
2157                         ),
2158                 );
2159
2160                 if ($is_owner){
2161                         $tabs[] = array(
2162                                 'label' => t('Events'),
2163                                 'url'   => $a->get_baseurl() . '/events',
2164                                 'sel'   =>((!isset($tab)&&$a->argv[0]=='events')?'active':''),
2165                                 'title' => t('Events and Calendar'),
2166                                 'id' => 'events-tab',
2167                         );
2168                         $tabs[] = array(
2169                                 'label' => t('Personal Notes'),
2170                                 'url'   => $a->get_baseurl() . '/notes',
2171                                 'sel'   =>((!isset($tab)&&$a->argv[0]=='notes')?'active':''),
2172                                 'title' => t('Only You Can See This'),
2173                                 'id' => 'notes-tab',
2174                         );
2175                 }
2176
2177
2178                 $arr = array('is_owner' => $is_owner, 'nickname' => $nickname, 'tab' => (($tab) ? $tab : false), 'tabs' => $tabs);
2179                 call_hooks('profile_tabs', $arr);
2180
2181                 $tpl = get_markup_template('common_tabs.tpl');
2182
2183                 return replace_macros($tpl,array('$tabs' => $arr['tabs']));
2184         }
2185 }
2186
2187 function get_my_url() {
2188         if(x($_SESSION,'my_url'))
2189                 return $_SESSION['my_url'];
2190         return false;
2191 }
2192
2193 function zrl_init(&$a) {
2194         $tmp_str = get_my_url();
2195         if(validate_url($tmp_str)) {
2196
2197                 // Is it a DDoS attempt?
2198                 // The check fetches the cached value from gprobe to reduce the load for this system
2199                 $urlparts = parse_url($tmp_str);
2200
2201                 $result = Cache::get("gprobe:".$urlparts["host"]);
2202                 if (!is_null($result)) {
2203                         $result = unserialize($result);
2204                         if ($result["network"] == NETWORK_FEED) {
2205                                 logger("DDoS attempt detected for ".$urlparts["host"]." by ".$_SERVER["REMOTE_ADDR"].". server data: ".print_r($_SERVER, true), LOGGER_DEBUG);
2206                                 return;
2207                         }
2208                 }
2209
2210                 proc_run('php','include/gprobe.php',bin2hex($tmp_str));
2211                 $arr = array('zrl' => $tmp_str, 'url' => $a->cmd);
2212                 call_hooks('zrl_init',$arr);
2213         }
2214 }
2215
2216 function zrl($s,$force = false) {
2217         if(! strlen($s))
2218                 return $s;
2219         if((! strpos($s,'/profile/')) && (! $force))
2220                 return $s;
2221         if($force && substr($s,-1,1) !== '/')
2222                 $s = $s . '/';
2223         $achar = strpos($s,'?') ? '&' : '?';
2224         $mine = get_my_url();
2225         if($mine and ! link_compare($mine,$s))
2226                 return $s . $achar . 'zrl=' . urlencode($mine);
2227         return $s;
2228 }
2229
2230 /**
2231 * returns querystring as string from a mapped array
2232 *
2233 * @param params Array
2234 * @return string
2235 */
2236 function build_querystring($params, $name=null) {
2237     $ret = "";
2238     foreach($params as $key=>$val) {
2239         if(is_array($val)) {
2240             if($name==null) {
2241                 $ret .= build_querystring($val, $key);
2242             } else {
2243                 $ret .= build_querystring($val, $name."[$key]");
2244             }
2245         } else {
2246             $val = urlencode($val);
2247             if($name!=null) {
2248                 $ret.=$name."[$key]"."=$val&";
2249             } else {
2250                 $ret.= "$key=$val&";
2251             }
2252         }
2253     }
2254     return $ret;
2255 }
2256
2257 function explode_querystring($query) {
2258         $arg_st = strpos($query, '?');
2259         if($arg_st !== false) {
2260                 $base = substr($query, 0, $arg_st);
2261                 $arg_st += 1;
2262         }
2263         else {
2264                 $base = '';
2265                 $arg_st = 0;
2266         }
2267
2268         $args = explode('&', substr($query, $arg_st));
2269         foreach($args as $k=>$arg) {
2270                 if($arg === '')
2271                         unset($args[$k]);
2272         }
2273         $args = array_values($args);
2274
2275         if(!$base) {
2276                 $base = $args[0];
2277                 unset($args[0]);
2278                 $args = array_values($args);
2279         }
2280
2281         return array(
2282                 'base' => $base,
2283                 'args' => $args,
2284         );
2285 }
2286
2287 /**
2288 * Returns the complete URL of the current page, e.g.: http(s)://something.com/network
2289 *
2290 * Taken from http://webcheatsheet.com/php/get_current_page_url.php
2291 */
2292 function curPageURL() {
2293         $pageURL = 'http';
2294         if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
2295         $pageURL .= "://";
2296         if ($_SERVER["SERVER_PORT"] != "80" && $_SERVER["SERVER_PORT"] != "443") {
2297                 $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
2298         } else {
2299                 $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
2300         }
2301         return $pageURL;
2302 }
2303
2304 function random_digits($digits) {
2305         $rn = '';
2306         for($i = 0; $i < $digits; $i++) {
2307                 $rn .= rand(0,9);
2308         }
2309         return $rn;
2310 }
2311
2312 function get_cachefile($file, $writemode = true) {
2313         $cache = get_itemcachepath();
2314
2315         if ((! $cache) || (! is_dir($cache)))
2316                 return("");
2317
2318         $subfolder = $cache."/".substr($file, 0, 2);
2319
2320         $cachepath = $subfolder."/".$file;
2321
2322         if ($writemode) {
2323                 if (!is_dir($subfolder)) {
2324                         mkdir($subfolder);
2325                         chmod($subfolder, 0777);
2326                 }
2327         }
2328
2329         return($cachepath);
2330 }
2331
2332 function clear_cache($basepath = "", $path = "") {
2333         if ($path == "") {
2334                 $basepath = get_itemcachepath();
2335                 $path = $basepath;
2336         }
2337
2338         if (($path == "") OR (!is_dir($path)))
2339                 return;
2340
2341         if (substr(realpath($path), 0, strlen($basepath)) != $basepath)
2342                 return;
2343
2344         $cachetime = (int)get_config('system','itemcache_duration');
2345         if ($cachetime == 0)
2346                 $cachetime = 86400;
2347
2348         if (is_writable($path)){
2349         if ($dh = opendir($path)) {
2350                 while (($file = readdir($dh)) !== false) {
2351                         $fullpath = $path."/".$file;
2352                         if ((filetype($fullpath) == "dir") and ($file != ".") and ($file != ".."))
2353                                 clear_cache($basepath, $fullpath);
2354                         if ((filetype($fullpath) == "file") and (filectime($fullpath) < (time() - $cachetime)))
2355                                 unlink($fullpath);
2356                 }
2357                 closedir($dh);
2358         }
2359         }
2360 }
2361
2362 function get_itemcachepath() {
2363         // Checking, if the cache is deactivated
2364         $cachetime = (int)get_config('system','itemcache_duration');
2365         if ($cachetime < 0)
2366                 return "";
2367
2368         $itemcache = get_config('system','itemcache');
2369         if (($itemcache != "") AND is_dir($itemcache) AND is_writable($itemcache))
2370                 return($itemcache);
2371
2372         $temppath = get_temppath();
2373
2374         if ($temppath != "") {
2375                 $itemcache = $temppath."/itemcache";
2376                 if(!file_exists($itemcache) && !is_dir($itemcache)) {
2377                         mkdir($itemcache);
2378                 }
2379
2380                 if (is_dir($itemcache) AND is_writable($itemcache)) {
2381                         set_config("system", "itemcache", $itemcache);
2382                         return($itemcache);
2383                 }
2384         }
2385         return "";
2386 }
2387
2388 function get_lockpath() {
2389         $lockpath = get_config('system','lockpath');
2390         if (($lockpath != "") AND is_dir($lockpath) AND is_writable($lockpath))
2391                 return($lockpath);
2392
2393         $temppath = get_temppath();
2394
2395         if ($temppath != "") {
2396                 $lockpath = $temppath."/lock";
2397                 mkdir($lockpath);
2398
2399                 if (is_dir($lockpath) AND is_writable($lockpath)) {
2400                         set_config("system", "lockpath", $lockpath);
2401                         return($lockpath);
2402                 }
2403         }
2404         return "";
2405 }
2406
2407 function get_temppath() {
2408         $temppath = get_config("system","temppath");
2409         if (($temppath != "") AND is_dir($temppath) AND is_writable($temppath))
2410                 return($temppath);
2411
2412         $temppath = sys_get_temp_dir();
2413         if (($temppath != "") AND is_dir($temppath) AND is_writable($temppath)) {
2414                 set_config("system", "temppath", $temppath);
2415                 return($temppath);
2416         }
2417
2418         return("");
2419 }
2420
2421 function set_template_engine(&$a, $engine = 'internal') {
2422 // This function is no longer necessary, but keep it as a wrapper to the class method
2423 // to avoid breaking themes again unnecessarily
2424
2425         $a->set_template_engine($engine);
2426 }
2427
2428 if(!function_exists('exif_imagetype')) {
2429         function exif_imagetype($file) {
2430                 $size = getimagesize($file);
2431                 return($size[2]);
2432         }
2433 }