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