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