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