]> git.mxchange.org Git - friendica.git/blob - boot.php
Merge remote-tracking branch 'upstream/develop' into 1502-poco-generation-counter
[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-RC' );
20 define ( 'DFRN_PROTOCOL_VERSION',  '2.23'    );
21 define ( 'DB_UPDATE_VERSION',      1180      );
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
1683
1684                 $p = array();
1685                 foreach($profile as $k => $v) {
1686                         $k = str_replace('-','_',$k);
1687                         $p[$k] = $v;
1688                 }
1689
1690                 if($a->theme['template_engine'] === 'internal')
1691                         $location = template_escape($location);
1692
1693
1694                 $tpl = get_markup_template('profile_vcard.tpl');
1695                 $o .= replace_macros($tpl, array(
1696                         '$profile' => $p,
1697                         '$connect'  => $connect,
1698                         '$remoteconnect'  => $remoteconnect,
1699                         '$wallmessage' => $wallmessage,
1700                         '$location' => $location,
1701                         '$gender'   => $gender,
1702                         '$pdesc'        => $pdesc,
1703                         '$marital'  => $marital,
1704                         '$homepage' => $homepage,
1705                         '$about' => $about,
1706                         '$network' =>  t('Network:'),
1707                         '$diaspora' => $diaspora,
1708                         '$contact_block' => $contact_block,
1709                 ));
1710
1711
1712                 $arr = array('profile' => &$profile, 'entry' => &$o);
1713
1714                 call_hooks('profile_sidebar', $arr);
1715
1716                 return $o;
1717         }
1718 }
1719
1720
1721 if(! function_exists('get_birthdays')) {
1722         function get_birthdays() {
1723
1724                 $a = get_app();
1725                 $o = '';
1726
1727                 if(! local_user() || $a->is_mobile || $a->is_tablet)
1728                         return $o;
1729
1730 //              $mobile_detect = new Mobile_Detect();
1731 //              $is_mobile = $mobile_detect->isMobile() || $mobile_detect->isTablet();
1732
1733 //              if($is_mobile)
1734 //                      return $o;
1735
1736                 $bd_format = t('g A l F d') ; // 8 AM Friday January 18
1737                 $bd_short = t('F d');
1738
1739                 $r = q("SELECT `event`.*, `event`.`id` AS `eid`, `contact`.* FROM `event`
1740                                 INNER JOIN `contact` ON `contact`.`id` = `event`.`cid`
1741                                 WHERE `event`.`uid` = %d AND `type` = 'birthday' AND `start` < '%s' AND `finish` > '%s'
1742                                 ORDER BY `start` ASC ",
1743                                 intval(local_user()),
1744                                 dbesc(datetime_convert('UTC','UTC','now + 6 days')),
1745                                 dbesc(datetime_convert('UTC','UTC','now'))
1746                 );
1747
1748                 if($r && count($r)) {
1749                         $total = 0;
1750                         $now = strtotime('now');
1751                         $cids = array();
1752
1753                         $istoday = false;
1754                         foreach($r as $rr) {
1755                                 if(strlen($rr['name']))
1756                                         $total ++;
1757                                 if((strtotime($rr['start'] . ' +00:00') < $now) && (strtotime($rr['finish'] . ' +00:00') > $now))
1758                                         $istoday = true;
1759                         }
1760                         $classtoday = $istoday ? ' birthday-today ' : '';
1761                         if($total) {
1762                                 foreach($r as &$rr) {
1763                                         if(! strlen($rr['name']))
1764                                                 continue;
1765
1766                                         // avoid duplicates
1767
1768                                         if(in_array($rr['cid'],$cids))
1769                                                 continue;
1770                                         $cids[] = $rr['cid'];
1771
1772                                         $today = (((strtotime($rr['start'] . ' +00:00') < $now) && (strtotime($rr['finish'] . ' +00:00') > $now)) ? true : false);
1773                                         $sparkle = '';
1774                                         $url = $rr['url'];
1775                                         if($rr['network'] === NETWORK_DFRN) {
1776                                                 $sparkle = " sparkle";
1777                                                 $url = $a->get_baseurl() . '/redir/'  . $rr['cid'];
1778                                         }
1779
1780                                         $rr['link'] = $url;
1781                                         $rr['title'] = $rr['name'];
1782                                         $rr['date'] = day_translate(datetime_convert('UTC', $a->timezone, $rr['start'], $rr['adjust'] ? $bd_format : $bd_short)) . (($today) ?  ' ' . t('[today]') : '');
1783                                         $rr['startime'] = Null;
1784                                         $rr['today'] = $today;
1785
1786                                 }
1787                         }
1788                 }
1789                 $tpl = get_markup_template("birthdays_reminder.tpl");
1790                 return replace_macros($tpl, array(
1791                         '$baseurl' => $a->get_baseurl(),
1792                         '$classtoday' => $classtoday,
1793                         '$count' => $total,
1794                         '$event_reminders' => t('Birthday Reminders'),
1795                         '$event_title' => t('Birthdays this week:'),
1796                         '$events' => $r,
1797                         '$lbr' => '{',  // raw brackets mess up if/endif macro processing
1798                         '$rbr' => '}'
1799
1800                 ));
1801         }
1802 }
1803
1804
1805 if(! function_exists('get_events')) {
1806         function get_events() {
1807
1808                 require_once('include/bbcode.php');
1809
1810                 $a = get_app();
1811
1812                 if(! local_user() || $a->is_mobile || $a->is_tablet)
1813                         return $o;
1814
1815
1816 //              $mobile_detect = new Mobile_Detect();
1817 //              $is_mobile = $mobile_detect->isMobile() || $mobile_detect->isTablet();
1818
1819 //              if($is_mobile)
1820 //                      return $o;
1821
1822                 $bd_format = t('g A l F d') ; // 8 AM Friday January 18
1823                 $bd_short = t('F d');
1824
1825                 $r = q("SELECT `event`.* FROM `event`
1826                                 WHERE `event`.`uid` = %d AND `type` != 'birthday' AND `start` < '%s' AND `start` > '%s'
1827                                 ORDER BY `start` ASC ",
1828                                 intval(local_user()),
1829                                 dbesc(datetime_convert('UTC','UTC','now + 6 days')),
1830                                 dbesc(datetime_convert('UTC','UTC','now - 1 days'))
1831                 );
1832
1833                 if($r && count($r)) {
1834                         $now = strtotime('now');
1835                         $istoday = false;
1836                         foreach($r as $rr) {
1837                                 if(strlen($rr['name']))
1838                                         $total ++;
1839
1840                                 $strt = datetime_convert('UTC',$rr['convert'] ? $a->timezone : 'UTC',$rr['start'],'Y-m-d');
1841                                 if($strt === datetime_convert('UTC',$a->timezone,'now','Y-m-d'))
1842                                         $istoday = true;
1843                         }
1844                         $classtoday = (($istoday) ? 'event-today' : '');
1845
1846
1847                         foreach($r as &$rr) {
1848                                 if($rr['adjust'])
1849                                         $md = datetime_convert('UTC',$a->timezone,$rr['start'],'Y/m');
1850                                 else
1851                                         $md = datetime_convert('UTC','UTC',$rr['start'],'Y/m');
1852                                 $md .= "/#link-".$rr['id'];
1853
1854                                 $title = substr(strip_tags(bbcode($rr['desc'])),0,32) . '... ';
1855                                 if(! $title)
1856                                         $title = t('[No description]');
1857
1858                                 $strt = datetime_convert('UTC',$rr['convert'] ? $a->timezone : 'UTC',$rr['start']);
1859                                 $today = ((substr($strt,0,10) === datetime_convert('UTC',$a->timezone,'now','Y-m-d')) ? true : false);
1860
1861                                 $rr['link'] = $md;
1862                                 $rr['title'] = $title;
1863                                 $rr['date'] = day_translate(datetime_convert('UTC', $rr['adjust'] ? $a->timezone : 'UTC', $rr['start'], $bd_format)) . (($today) ?  ' ' . t('[today]') : '');
1864                                 $rr['startime'] = $strt;
1865                                 $rr['today'] = $today;
1866                         }
1867                 }
1868
1869                 $tpl = get_markup_template("events_reminder.tpl");
1870                 return replace_macros($tpl, array(
1871                         '$baseurl' => $a->get_baseurl(),
1872                         '$classtoday' => $classtoday,
1873                         '$count' => count($r),
1874                         '$event_reminders' => t('Event Reminders'),
1875                         '$event_title' => t('Events this week:'),
1876                         '$events' => $r,
1877                 ));
1878         }
1879 }
1880
1881
1882 /**
1883  *
1884  * Wrap calls to proc_close(proc_open()) and call hook
1885  * so plugins can take part in process :)
1886  *
1887  * args:
1888  * $cmd program to run
1889  *  next args are passed as $cmd command line
1890  *
1891  * e.g.: proc_run("ls","-la","/tmp");
1892  *
1893  * $cmd and string args are surrounded with ""
1894  */
1895
1896 if(! function_exists('proc_run')) {
1897         function proc_run($cmd){
1898
1899                 $a = get_app();
1900
1901                 $args = func_get_args();
1902
1903                 $newargs = array();
1904                 if(! count($args))
1905                         return;
1906
1907                 // expand any arrays
1908
1909                 foreach($args as $arg) {
1910                         if(is_array($arg)) {
1911                                 foreach($arg as $n) {
1912                                         $newargs[] = $n;
1913                                 }
1914                         }
1915                         else
1916                                 $newargs[] = $arg;
1917                 }
1918
1919                 $args = $newargs;
1920
1921                 $arr = array('args' => $args, 'run_cmd' => true);
1922
1923                 call_hooks("proc_run", $arr);
1924                 if(! $arr['run_cmd'])
1925                         return;
1926
1927                 if(count($args) && $args[0] === 'php')
1928                         $args[0] = ((x($a->config,'php_path')) && (strlen($a->config['php_path'])) ? $a->config['php_path'] : 'php');
1929
1930         // add baseurl to args. cli scripts can't construct it
1931         $args[] = $a->get_baseurl();
1932
1933         for($x = 0; $x < count($args); $x ++)
1934                         $args[$x] = escapeshellarg($args[$x]);
1935
1936
1937
1938                 $cmdline = implode($args," ");
1939                 if(get_config('system','proc_windows'))
1940                         proc_close(proc_open('cmd /c start /b ' . $cmdline,array(),$foo,dirname(__FILE__)));
1941                 else
1942                         proc_close(proc_open($cmdline." &",array(),$foo,dirname(__FILE__)));
1943         }
1944 }
1945
1946 if(! function_exists('current_theme')) {
1947         function current_theme(){
1948                 $app_base_themes = array('duepuntozero', 'dispy', 'quattro');
1949
1950                 $a = get_app();
1951
1952 //              $mobile_detect = new Mobile_Detect();
1953 //              $is_mobile = $mobile_detect->isMobile() || $mobile_detect->isTablet();
1954                 $is_mobile = $a->is_mobile || $a->is_tablet;
1955
1956                 if($is_mobile) {
1957                         if(isset($_SESSION['show-mobile']) && !$_SESSION['show-mobile']) {
1958                                 $system_theme = '';
1959                                 $theme_name = '';
1960                         }
1961                         else {
1962                                 $system_theme = ((isset($a->config['system']['mobile-theme'])) ? $a->config['system']['mobile-theme'] : '');
1963                                 $theme_name = ((isset($_SESSION) && x($_SESSION,'mobile-theme')) ? $_SESSION['mobile-theme'] : $system_theme);
1964
1965                                 if($theme_name === '---') {
1966                                         // user has selected to have the mobile theme be the same as the normal one
1967                                         $system_theme = '';
1968                                         $theme_name = '';
1969                                 }
1970                         }
1971                 }
1972                 if(!$is_mobile || ($system_theme === '' && $theme_name === '')) {
1973                         $system_theme = ((isset($a->config['system']['theme'])) ? $a->config['system']['theme'] : '');
1974                         $theme_name = ((isset($_SESSION) && x($_SESSION,'theme')) ? $_SESSION['theme'] : $system_theme);
1975                 }
1976
1977                 if($theme_name &&
1978                                 (file_exists('view/theme/' . $theme_name . '/style.css') ||
1979                                                 file_exists('view/theme/' . $theme_name . '/style.php')))
1980                         return($theme_name);
1981
1982                 foreach($app_base_themes as $t) {
1983                         if(file_exists('view/theme/' . $t . '/style.css')||
1984                                         file_exists('view/theme/' . $t . '/style.php'))
1985                                 return($t);
1986                 }
1987
1988                 $fallback = array_merge(glob('view/theme/*/style.css'),glob('view/theme/*/style.php'));
1989                 if(count($fallback))
1990                         return (str_replace('view/theme/','', substr($fallback[0],0,-10)));
1991
1992         }
1993 }
1994
1995 /*
1996  * Return full URL to theme which is currently in effect.
1997 * Provide a sane default if nothing is chosen or the specified theme does not exist.
1998 */
1999 if(! function_exists('current_theme_url')) {
2000         function current_theme_url() {
2001                 global $a;
2002                 $t = current_theme();
2003                 if (file_exists('view/theme/' . $t . '/style.php'))
2004                         return($a->get_baseurl() . '/view/theme/' . $t . '/style.pcss');
2005                 return($a->get_baseurl() . '/view/theme/' . $t . '/style.css');
2006         }
2007 }
2008
2009 if(! function_exists('feed_birthday')) {
2010         function feed_birthday($uid,$tz) {
2011
2012                 /**
2013                  *
2014                  * Determine the next birthday, but only if the birthday is published
2015                  * in the default profile. We _could_ also look for a private profile that the
2016                  * recipient can see, but somebody could get mad at us if they start getting
2017                  * public birthday greetings when they haven't made this info public.
2018                  *
2019                  * Assuming we are able to publish this info, we are then going to convert
2020                  * the start time from the owner's timezone to UTC.
2021                  *
2022                  * This will potentially solve the problem found with some social networks
2023                  * where birthdays are converted to the viewer's timezone and salutations from
2024                  * elsewhere in the world show up on the wrong day. We will convert it to the
2025                  * viewer's timezone also, but first we are going to convert it from the birthday
2026                  * person's timezone to GMT - so the viewer may find the birthday starting at
2027                  * 6:00PM the day before, but that will correspond to midnight to the birthday person.
2028                  *
2029                  */
2030
2031
2032                 $birthday = '';
2033
2034                 if(! strlen($tz))
2035                         $tz = 'UTC';
2036
2037                 $p = q("SELECT `dob` FROM `profile` WHERE `is-default` = 1 AND `uid` = %d LIMIT 1",
2038                                 intval($uid)
2039                 );
2040
2041                 if($p && count($p)) {
2042                         $tmp_dob = substr($p[0]['dob'],5);
2043                         if(intval($tmp_dob)) {
2044                                 $y = datetime_convert($tz,$tz,'now','Y');
2045                                 $bd = $y . '-' . $tmp_dob . ' 00:00';
2046                                 $t_dob = strtotime($bd);
2047                                 $now = strtotime(datetime_convert($tz,$tz,'now'));
2048                                 if($t_dob < $now)
2049                                         $bd = $y + 1 . '-' . $tmp_dob . ' 00:00';
2050                                 $birthday = datetime_convert($tz,'UTC',$bd,ATOM_TIME);
2051                         }
2052                 }
2053
2054                 return $birthday;
2055         }
2056 }
2057
2058 if(! function_exists('is_site_admin')) {
2059         function is_site_admin() {
2060                 $a = get_app();
2061
2062                 $adminlist = explode(",", str_replace(" ", "", $a->config['admin_email']));
2063
2064                 //if(local_user() && x($a->user,'email') && x($a->config,'admin_email') && ($a->user['email'] === $a->config['admin_email']))
2065                 if(local_user() && x($a->user,'email') && x($a->config,'admin_email') && in_array($a->user['email'], $adminlist))
2066                         return true;
2067                 return false;
2068         }
2069 }
2070
2071
2072 if(! function_exists('load_contact_links')) {
2073         function load_contact_links($uid) {
2074
2075                 $a = get_app();
2076
2077                 $ret = array();
2078
2079                 if(! $uid || x($a->contacts,'empty'))
2080                         return;
2081
2082                 $r = q("SELECT `id`,`network`,`url`,`thumb` FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 AND `thumb` != ''",
2083                                 intval($uid)
2084                 );
2085                 if(count($r)) {
2086                         foreach($r as $rr){
2087                                 $url = normalise_link($rr['url']);
2088                                 $ret[$url] = $rr;
2089                         }
2090                 }
2091                 else
2092                         $ret['empty'] = true;
2093                 $a->contacts = $ret;
2094                 return;
2095         }
2096 }
2097
2098 if(! function_exists('profile_tabs')){
2099         function profile_tabs($a, $is_owner=False, $nickname=Null){
2100                 //echo "<pre>"; var_dump($a->user); killme();
2101
2102                 if (is_null($nickname))
2103                         $nickname  = $a->user['nickname'];
2104
2105                 if(x($_GET,'tab'))
2106                         $tab = notags(trim($_GET['tab']));
2107
2108                 $url = $a->get_baseurl() . '/profile/' . $nickname;
2109
2110                 $tabs = array(
2111                         array(
2112                                 'label'=>t('Status'),
2113                                 'url' => $url,
2114                                 'sel' => ((!isset($tab)&&$a->argv[0]=='profile')?'active':''),
2115                                 'title' => t('Status Messages and Posts'),
2116                                 'id' => 'status-tab',
2117                         ),
2118                         array(
2119                                 'label' => t('Profile'),
2120                                 'url'   => $url.'/?tab=profile',
2121                                 'sel'   => ((isset($tab) && $tab=='profile')?'active':''),
2122                                 'title' => t('Profile Details'),
2123                                 'id' => 'profile-tab',
2124                         ),
2125                         array(
2126                                 'label' => t('Photos'),
2127                                 'url'   => $a->get_baseurl() . '/photos/' . $nickname,
2128                                 'sel'   => ((!isset($tab)&&$a->argv[0]=='photos')?'active':''),
2129                                 'title' => t('Photo Albums'),
2130                                 'id' => 'photo-tab',
2131                         ),
2132                         array(
2133                                 'label' => t('Videos'),
2134                                 'url'   => $a->get_baseurl() . '/videos/' . $nickname,
2135                                 'sel'   => ((!isset($tab)&&$a->argv[0]=='videos')?'active':''),
2136                                 'title' => t('Videos'),
2137                                 'id' => 'video-tab',
2138                         ),
2139                 );
2140
2141                 if ($is_owner){
2142                         $tabs[] = array(
2143                                 'label' => t('Events'),
2144                                 'url'   => $a->get_baseurl() . '/events',
2145                                 'sel'   =>((!isset($tab)&&$a->argv[0]=='events')?'active':''),
2146                                 'title' => t('Events and Calendar'),
2147                                 'id' => 'events-tab',
2148                         );
2149                         $tabs[] = array(
2150                                 'label' => t('Personal Notes'),
2151                                 'url'   => $a->get_baseurl() . '/notes',
2152                                 'sel'   =>((!isset($tab)&&$a->argv[0]=='notes')?'active':''),
2153                                 'title' => t('Only You Can See This'),
2154                                 'id' => 'notes-tab',
2155                         );
2156                 }
2157
2158
2159                 $arr = array('is_owner' => $is_owner, 'nickname' => $nickname, 'tab' => (($tab) ? $tab : false), 'tabs' => $tabs);
2160                 call_hooks('profile_tabs', $arr);
2161
2162                 $tpl = get_markup_template('common_tabs.tpl');
2163
2164                 return replace_macros($tpl,array('$tabs' => $arr['tabs']));
2165         }
2166 }
2167
2168 function get_my_url() {
2169         if(x($_SESSION,'my_url'))
2170                 return $_SESSION['my_url'];
2171         return false;
2172 }
2173
2174 function zrl_init(&$a) {
2175         $tmp_str = get_my_url();
2176         if(validate_url($tmp_str)) {
2177                 proc_run('php','include/gprobe.php',bin2hex($tmp_str));
2178                 $arr = array('zrl' => $tmp_str, 'url' => $a->cmd);
2179                 call_hooks('zrl_init',$arr);
2180         }
2181 }
2182
2183 function zrl($s,$force = false) {
2184         if(! strlen($s))
2185                 return $s;
2186         if((! strpos($s,'/profile/')) && (! $force))
2187                 return $s;
2188         if($force && substr($s,-1,1) !== '/')
2189                 $s = $s . '/';
2190         $achar = strpos($s,'?') ? '&' : '?';
2191         $mine = get_my_url();
2192         if($mine and ! link_compare($mine,$s))
2193                 return $s . $achar . 'zrl=' . urlencode($mine);
2194         return $s;
2195 }
2196
2197 /**
2198 * returns querystring as string from a mapped array
2199 *
2200 * @param params Array
2201 * @return string
2202 */
2203 function build_querystring($params, $name=null) {
2204     $ret = "";
2205     foreach($params as $key=>$val) {
2206         if(is_array($val)) {
2207             if($name==null) {
2208                 $ret .= build_querystring($val, $key);
2209             } else {
2210                 $ret .= build_querystring($val, $name."[$key]");
2211             }
2212         } else {
2213             $val = urlencode($val);
2214             if($name!=null) {
2215                 $ret.=$name."[$key]"."=$val&";
2216             } else {
2217                 $ret.= "$key=$val&";
2218             }
2219         }
2220     }
2221     return $ret;
2222 }
2223
2224 function explode_querystring($query) {
2225         $arg_st = strpos($query, '?');
2226         if($arg_st !== false) {
2227                 $base = substr($query, 0, $arg_st);
2228                 $arg_st += 1;
2229         }
2230         else {
2231                 $base = '';
2232                 $arg_st = 0;
2233         }
2234
2235         $args = explode('&', substr($query, $arg_st));
2236         foreach($args as $k=>$arg) {
2237                 if($arg === '')
2238                         unset($args[$k]);
2239         }
2240         $args = array_values($args);
2241
2242         if(!$base) {
2243                 $base = $args[0];
2244                 unset($args[0]);
2245                 $args = array_values($args);
2246         }
2247
2248         return array(
2249                 'base' => $base,
2250                 'args' => $args,
2251         );
2252 }
2253
2254 /**
2255 * Returns the complete URL of the current page, e.g.: http(s)://something.com/network
2256 *
2257 * Taken from http://webcheatsheet.com/php/get_current_page_url.php
2258 */
2259 function curPageURL() {
2260         $pageURL = 'http';
2261         if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
2262         $pageURL .= "://";
2263         if ($_SERVER["SERVER_PORT"] != "80" && $_SERVER["SERVER_PORT"] != "443") {
2264                 $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
2265         } else {
2266                 $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
2267         }
2268         return $pageURL;
2269 }
2270
2271 function random_digits($digits) {
2272         $rn = '';
2273         for($i = 0; $i < $digits; $i++) {
2274                 $rn .= rand(0,9);
2275         }
2276         return $rn;
2277 }
2278
2279 function get_cachefile($file, $writemode = true) {
2280         $cache = get_itemcachepath();
2281
2282         if ((! $cache) || (! is_dir($cache)))
2283                 return("");
2284
2285         $subfolder = $cache."/".substr($file, 0, 2);
2286
2287         $cachepath = $subfolder."/".$file;
2288
2289         if ($writemode) {
2290                 if (!is_dir($subfolder)) {
2291                         mkdir($subfolder);
2292                         chmod($subfolder, 0777);
2293                 }
2294         }
2295
2296         return($cachepath);
2297 }
2298
2299 function clear_cache($basepath = "", $path = "") {
2300         if ($path == "") {
2301                 $basepath = get_itemcachepath();
2302                 $path = $basepath;
2303         }
2304
2305         if (($path == "") OR (!is_dir($path)))
2306                 return;
2307
2308         if (substr(realpath($path), 0, strlen($basepath)) != $basepath)
2309                 return;
2310
2311         $cachetime = (int)get_config('system','itemcache_duration');
2312         if ($cachetime == 0)
2313                 $cachetime = 86400;
2314
2315         if (is_writable($path)){
2316         if ($dh = opendir($path)) {
2317                 while (($file = readdir($dh)) !== false) {
2318                         $fullpath = $path."/".$file;
2319                         if ((filetype($fullpath) == "dir") and ($file != ".") and ($file != ".."))
2320                                 clear_cache($basepath, $fullpath);
2321                         if ((filetype($fullpath) == "file") and (filectime($fullpath) < (time() - $cachetime)))
2322                                 unlink($fullpath);
2323                 }
2324                 closedir($dh);
2325         }
2326         }
2327 }
2328
2329 function get_itemcachepath() {
2330         // Checking, if the cache is deactivated
2331         $cachetime = (int)get_config('system','itemcache_duration');
2332         if ($cachetime < 0)
2333                 return "";
2334
2335         $itemcache = get_config('system','itemcache');
2336         if (($itemcache != "") AND is_dir($itemcache) AND is_writable($itemcache))
2337                 return($itemcache);
2338
2339         $temppath = get_temppath();
2340
2341         if ($temppath != "") {
2342                 $itemcache = $temppath."/itemcache";
2343                 mkdir($itemcache);
2344
2345                 if (is_dir($itemcache) AND is_writable($itemcache)) {
2346                         set_config("system", "itemcache", $itemcache);
2347                         return($itemcache);
2348                 }
2349         }
2350         return "";
2351 }
2352
2353 function get_lockpath() {
2354         $lockpath = get_config('system','lockpath');
2355         if (($lockpath != "") AND is_dir($lockpath) AND is_writable($lockpath))
2356                 return($lockpath);
2357
2358         $temppath = get_temppath();
2359
2360         if ($temppath != "") {
2361                 $lockpath = $temppath."/lock";
2362                 mkdir($lockpath);
2363
2364                 if (is_dir($lockpath) AND is_writable($lockpath)) {
2365                         set_config("system", "lockpath", $lockpath);
2366                         return($lockpath);
2367                 }
2368         }
2369         return "";
2370 }
2371
2372 function get_temppath() {
2373         $temppath = get_config("system","temppath");
2374         if (($temppath != "") AND is_dir($temppath) AND is_writable($temppath))
2375                 return($temppath);
2376
2377         $temppath = sys_get_temp_dir();
2378         if (($temppath != "") AND is_dir($temppath) AND is_writable($temppath)) {
2379                 set_config("system", "temppath", $temppath);
2380                 return($temppath);
2381         }
2382
2383         return("");
2384 }
2385
2386 function set_template_engine(&$a, $engine = 'internal') {
2387 // This function is no longer necessary, but keep it as a wrapper to the class method
2388 // to avoid breaking themes again unnecessarily
2389
2390         $a->set_template_engine($engine);
2391 }
2392
2393 if(!function_exists('exif_imagetype')) {
2394         function exif_imagetype($file) {
2395                 $size = getimagesize($file);
2396                 return($size[2]);
2397         }
2398 }