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