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');
14 define ( 'FRIENDICA_PLATFORM', 'Friendica');
15 define ( 'FRIENDICA_VERSION', '3.1.1743' );
16 define ( 'DFRN_PROTOCOL_VERSION', '2.23' );
17 define ( 'DB_UPDATE_VERSION', 1163 );
18 define ( 'EOL', "<br />\r\n" );
19 define ( 'ATOM_TIME', 'Y-m-d\TH:i:s\Z' );
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
32 define ( 'JPEG_QUALITY', 100 );
34 * $a->config['system']['png_quality'] from 0 (uncompressed) to 9
36 define ( 'PNG_QUALITY', 8 );
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
46 * $a->config['system']['max_image_length'] = n;
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.
54 define ( 'MAX_IMAGE_LENGTH', -1 );
61 define ( 'DEFAULT_DB_ENGINE', 'MyISAM' );
64 * SSL redirection policies
67 define ( 'SSL_POLICY_NONE', 0 );
68 define ( 'SSL_POLICY_FULL', 1 );
69 define ( 'SSL_POLICY_SELFSIGN', 2 );
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 );
83 * registration policies
86 define ( 'REGISTER_CLOSED', 0 );
87 define ( 'REGISTER_APPROVE', 1 );
88 define ( 'REGISTER_OPEN', 2 );
94 define ( 'CONTACT_IS_FOLLOWER', 1);
95 define ( 'CONTACT_IS_SHARING', 2);
96 define ( 'CONTACT_IS_FRIEND', 3);
100 * DB update return values
103 define ( 'UPDATE_SUCCESS', 0);
104 define ( 'UPDATE_FAILED', 1);
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).
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 );
127 * Network and protocol family types
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 define ( 'NETWORK_PUMPIO', 'pump'); // pump.io
144 define ( 'NETWORK_PHANTOM', 'unkn'); // Place holder
147 * These numbers are used in stored permissions
148 * and existing allocations MUST NEVER BE CHANGED
149 * OR RE-ASSIGNED! You may only add to them.
152 $netgroup_ids = array(
153 NETWORK_DFRN => (-1),
155 NETWORK_OSTATUS => (-3),
156 NETWORK_FEED => (-4),
157 NETWORK_DIASPORA => (-5),
158 NETWORK_MAIL => (-6),
159 NETWORK_MAIL2 => (-7),
160 NETWORK_FACEBOOK => (-8),
161 NETWORK_LINKEDIN => (-9),
162 NETWORK_XMPP => (-10),
163 NETWORK_MYSPACE => (-11),
164 NETWORK_GPLUS => (-12),
165 NETWORK_PUMPIO => (-13),
167 NETWORK_PHANTOM => (-127),
172 * Maximum number of "people who like (or don't like) this" that we will list by name
175 define ( 'MAX_LIKERS', 75);
178 * Communication timeout
181 define ( 'ZCURL_TIMEOUT' , (-1));
185 * email notification options
188 define ( 'NOTIFY_INTRO', 0x0001 );
189 define ( 'NOTIFY_CONFIRM', 0x0002 );
190 define ( 'NOTIFY_WALL', 0x0004 );
191 define ( 'NOTIFY_COMMENT', 0x0008 );
192 define ( 'NOTIFY_MAIL', 0x0010 );
193 define ( 'NOTIFY_SUGGEST', 0x0020 );
194 define ( 'NOTIFY_PROFILE', 0x0040 );
195 define ( 'NOTIFY_TAGSELF', 0x0080 );
196 define ( 'NOTIFY_TAGSHARE', 0x0100 );
197 define ( 'NOTIFY_POKE', 0x0200 );
199 define ( 'NOTIFY_SYSTEM', 0x8000 );
206 define ( 'TERM_UNKNOWN', 0 );
207 define ( 'TERM_HASHTAG', 1 );
208 define ( 'TERM_MENTION', 2 );
209 define ( 'TERM_CATEGORY', 3 );
210 define ( 'TERM_PCATEGORY', 4 );
211 define ( 'TERM_FILE', 5 );
212 define ( 'TERM_SAVEDSEARCH', 6 );
213 define ( 'TERM_CONVERSATION', 7 );
215 define ( 'TERM_OBJ_POST', 1 );
216 define ( 'TERM_OBJ_PHOTO', 2 );
221 * various namespaces we may need to parse
224 define ( 'NAMESPACE_ZOT', 'http://purl.org/zot' );
225 define ( 'NAMESPACE_DFRN' , 'http://purl.org/macgirvin/dfrn/1.0' );
226 define ( 'NAMESPACE_THREAD' , 'http://purl.org/syndication/thread/1.0' );
227 define ( 'NAMESPACE_TOMB' , 'http://purl.org/atompub/tombstones/1.0' );
228 define ( 'NAMESPACE_ACTIVITY', 'http://activitystrea.ms/spec/1.0/' );
229 define ( 'NAMESPACE_ACTIVITY_SCHEMA', 'http://activitystrea.ms/schema/1.0/' );
230 define ( 'NAMESPACE_MEDIA', 'http://purl.org/syndication/atommedia' );
231 define ( 'NAMESPACE_SALMON_ME', 'http://salmon-protocol.org/ns/magic-env' );
232 define ( 'NAMESPACE_OSTATUSSUB', 'http://ostatus.org/schema/1.0/subscribe' );
233 define ( 'NAMESPACE_GEORSS', 'http://www.georss.org/georss' );
234 define ( 'NAMESPACE_POCO', 'http://portablecontacts.net/spec/1.0' );
235 define ( 'NAMESPACE_FEED', 'http://schemas.google.com/g/2010#updates-from' );
236 define ( 'NAMESPACE_OSTATUS', 'http://ostatus.org/schema/1.0' );
237 define ( 'NAMESPACE_STATUSNET', 'http://status.net/schema/api/1/' );
238 define ( 'NAMESPACE_ATOM1', 'http://www.w3.org/2005/Atom' );
240 * activity stream defines
243 define ( 'ACTIVITY_LIKE', NAMESPACE_ACTIVITY_SCHEMA . 'like' );
244 define ( 'ACTIVITY_DISLIKE', NAMESPACE_DFRN . '/dislike' );
245 define ( 'ACTIVITY_OBJ_HEART', NAMESPACE_DFRN . '/heart' );
247 define ( 'ACTIVITY_FRIEND', NAMESPACE_ACTIVITY_SCHEMA . 'make-friend' );
248 define ( 'ACTIVITY_REQ_FRIEND', NAMESPACE_ACTIVITY_SCHEMA . 'request-friend' );
249 define ( 'ACTIVITY_UNFRIEND', NAMESPACE_ACTIVITY_SCHEMA . 'remove-friend' );
250 define ( 'ACTIVITY_FOLLOW', NAMESPACE_ACTIVITY_SCHEMA . 'follow' );
251 define ( 'ACTIVITY_UNFOLLOW', NAMESPACE_ACTIVITY_SCHEMA . 'stop-following' );
252 define ( 'ACTIVITY_JOIN', NAMESPACE_ACTIVITY_SCHEMA . 'join' );
254 define ( 'ACTIVITY_POST', NAMESPACE_ACTIVITY_SCHEMA . 'post' );
255 define ( 'ACTIVITY_UPDATE', NAMESPACE_ACTIVITY_SCHEMA . 'update' );
256 define ( 'ACTIVITY_TAG', NAMESPACE_ACTIVITY_SCHEMA . 'tag' );
257 define ( 'ACTIVITY_FAVORITE', NAMESPACE_ACTIVITY_SCHEMA . 'favorite' );
259 define ( 'ACTIVITY_POKE', NAMESPACE_ZOT . '/activity/poke' );
260 define ( 'ACTIVITY_MOOD', NAMESPACE_ZOT . '/activity/mood' );
262 define ( 'ACTIVITY_OBJ_COMMENT', NAMESPACE_ACTIVITY_SCHEMA . 'comment' );
263 define ( 'ACTIVITY_OBJ_NOTE', NAMESPACE_ACTIVITY_SCHEMA . 'note' );
264 define ( 'ACTIVITY_OBJ_PERSON', NAMESPACE_ACTIVITY_SCHEMA . 'person' );
265 define ( 'ACTIVITY_OBJ_PHOTO', NAMESPACE_ACTIVITY_SCHEMA . 'photo' );
266 define ( 'ACTIVITY_OBJ_P_PHOTO', NAMESPACE_ACTIVITY_SCHEMA . 'profile-photo' );
267 define ( 'ACTIVITY_OBJ_ALBUM', NAMESPACE_ACTIVITY_SCHEMA . 'photo-album' );
268 define ( 'ACTIVITY_OBJ_EVENT', NAMESPACE_ACTIVITY_SCHEMA . 'event' );
269 define ( 'ACTIVITY_OBJ_GROUP', NAMESPACE_ACTIVITY_SCHEMA . 'group' );
270 define ( 'ACTIVITY_OBJ_TAGTERM', NAMESPACE_DFRN . '/tagterm' );
271 define ( 'ACTIVITY_OBJ_PROFILE', NAMESPACE_DFRN . '/profile' );
274 * item weight for query ordering
277 define ( 'GRAVITY_PARENT', 0);
278 define ( 'GRAVITY_LIKE', 3);
279 define ( 'GRAVITY_COMMENT', 6);
283 * Reverse the effect of magic_quotes_gpc if it is enabled.
284 * Please disable magic_quotes_gpc so we don't have to do this.
285 * See http://php.net/manual/en/security.magicquotes.disabling.php
291 error_reporting(E_ERROR | E_WARNING | E_PARSE);
295 // This has to be quite large to deal with embedded private photos
296 ini_set('pcre.backtrack_limit', 500000);
299 if (get_magic_quotes_gpc()) {
300 $process = array(&$_GET, &$_POST, &$_COOKIE, &$_REQUEST);
301 while (list($key, $val) = each($process)) {
302 foreach ($val as $k => $v) {
303 unset($process[$key][$k]);
305 $process[$key][stripslashes($k)] = $v;
306 $process[] = &$process[$key][stripslashes($k)];
308 $process[$key][stripslashes($k)] = stripslashes($v);
321 * Our main application structure for the life of this page
322 * Primarily deals with the URL that got us here
323 * and tries to make some sense of it, and
324 * stores our page contents and config storage
325 * and anything else that might need to be passed around
326 * before we spit the page out.
330 if(! class_exists('App')) {
333 public $module_loaded = false;
334 public $query_string;
342 public $page_contact;
344 public $data = array();
345 public $error = false;
355 public $interactive = true;
357 public $apps = array();
361 public $performance = array();
368 // Allow themes to control internal parameters
369 // by changing App values in theme.php
371 public $sourcename = '';
372 public $videowidth = 425;
373 public $videoheight = 350;
374 public $force_max_items = 0;
375 public $theme_thread_allow = true;
377 // An array for all theme-controllable parameters
378 // Mostly unimplemented yet. Only options 'stylesheet' and
381 public $theme = array(
384 'videoheight' => 350,
385 'force_max_items' => 0,
386 'thread_allow' => true,
388 'template_engine' => 'smarty3',
391 // array of registered template engines ('name'=>'class name')
392 public $template_engines = array();
393 // array of instanced template engines ('name'=>'instance')
394 public $template_engine_instance = array();
396 private $ldelim = array(
400 private $rdelim = array(
411 private $curl_content_type;
412 private $curl_headers;
414 private $cached_profile_image;
415 private $cached_profile_picdate;
417 function __construct() {
419 global $default_timezone, $argv, $argc;
421 $this->timezone = ((x($default_timezone)) ? $default_timezone : 'UTC');
423 date_default_timezone_set($this->timezone);
425 $this->performance["start"] = microtime(true);
426 $this->performance["database"] = 0;
427 $this->performance["network"] = 0;
428 $this->performance["file"] = 0;
429 $this->performance["rendering"] = 0;
430 $this->performance["parser"] = 0;
431 $this->performance["marktime"] = 0;
432 $this->performance["markstart"] = microtime(true);
434 $this->config = array();
435 $this->page = array();
436 $this->pager= array();
438 $this->query_string = '';
443 'include' . PATH_SEPARATOR
444 . 'library' . PATH_SEPARATOR
445 . 'library/phpsec' . PATH_SEPARATOR
446 . 'library/langdet' . PATH_SEPARATOR
450 $this->scheme = 'http';
451 if(x($_SERVER,'HTTPS') && $_SERVER['HTTPS'])
452 $this->scheme = 'https';
453 elseif(x($_SERVER,'SERVER_PORT') && (intval($_SERVER['SERVER_PORT']) == 443))
454 $this->scheme = 'https';
456 if(x($_SERVER,'SERVER_NAME')) {
457 $this->hostname = $_SERVER['SERVER_NAME'];
459 // See bug 437 - this didn't work so disabling it
460 //if(stristr($this->hostname,'xn--')) {
461 // PHP or webserver may have converted idn to punycode, so
462 // convert punycode back to utf-8
463 // require_once('library/simplepie/idn/idna_convert.class.php');
464 // $x = new idna_convert();
465 // $this->hostname = $x->decode($_SERVER['SERVER_NAME']);
468 if(x($_SERVER,'SERVER_PORT') && $_SERVER['SERVER_PORT'] != 80 && $_SERVER['SERVER_PORT'] != 443)
469 $this->hostname .= ':' . $_SERVER['SERVER_PORT'];
471 * Figure out if we are running at the top of a domain
472 * or in a sub-directory and adjust accordingly
475 $path = trim(dirname($_SERVER['SCRIPT_NAME']),'/\\');
476 if(isset($path) && strlen($path) && ($path != $this->path))
479 if (is_array($argv) && $argc>1 && substr(end($argv), 0, 4)=="http" ) {
480 $this->set_baseurl(array_pop($argv) );
484 set_include_path("include/$this->hostname" . PATH_SEPARATOR . get_include_path());
486 if((x($_SERVER,'QUERY_STRING')) && substr($_SERVER['QUERY_STRING'],0,2) === "q=") {
487 $this->query_string = substr($_SERVER['QUERY_STRING'],2);
488 // removing trailing / - maybe a nginx problem
489 if (substr($this->query_string, 0, 1) == "/")
490 $this->query_string = substr($this->query_string, 1);
493 $this->cmd = trim($_GET['q'],'/\\');
495 // unix style "homedir"
497 if(substr($this->cmd,0,1) === '~')
498 $this->cmd = 'profile/' . substr($this->cmd,1);
500 // Diaspora style profile url
502 if(substr($this->cmd,0,2) === 'u/')
503 $this->cmd = 'profile/' . substr($this->cmd,2);
507 * Break the URL path into C style argc/argv style arguments for our
508 * modules. Given "http://example.com/module/arg1/arg2", $this->argc
509 * will be 3 (integer) and $this->argv will contain:
515 * There will always be one argument. If provided a naked domain
516 * URL, $this->argv[0] is set to "home".
520 $this->argv = explode('/',$this->cmd);
521 $this->argc = count($this->argv);
522 if((array_key_exists('0',$this->argv)) && strlen($this->argv[0])) {
523 $this->module = str_replace(".", "_", $this->argv[0]);
524 $this->module = str_replace("-", "_", $this->module);
528 $this->argv = array('home');
529 $this->module = 'home';
533 * See if there is any page number information, and initialise
537 $this->pager['page'] = ((x($_GET,'page') && intval($_GET['page']) > 0) ? intval($_GET['page']) : 1);
538 $this->pager['itemspage'] = 50;
539 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
540 if($this->pager['start'] < 0)
541 $this->pager['start'] = 0;
542 $this->pager['total'] = 0;
545 * Detect mobile devices
548 $mobile_detect = new Mobile_Detect();
549 $this->is_mobile = $mobile_detect->isMobile();
550 $this->is_tablet = $mobile_detect->isTablet();
553 * register template engines
555 $dc = get_declared_classes();
556 foreach ($dc as $k) {
557 if (in_array("ITemplateEngine", class_implements($k))){
558 $this->register_template_engine($k);
564 function get_basepath() {
566 $basepath = get_config("system", "basepath");
569 $basepath = $_SERVER["DOCUMENT_ROOT"];
572 $basepath = $_SERVER["PWD"];
577 function get_baseurl($ssl = false) {
579 $scheme = $this->scheme;
581 if((x($this->config,'system')) && (x($this->config['system'],'ssl_policy'))) {
582 if(intval($this->config['system']['ssl_policy']) === intval(SSL_POLICY_FULL))
585 // Basically, we have $ssl = true on any links which can only be seen by a logged in user
586 // (and also the login link). Anything seen by an outsider will have it turned off.
588 if($this->config['system']['ssl_policy'] == SSL_POLICY_SELFSIGN) {
596 $this->baseurl = $scheme . "://" . $this->hostname . ((isset($this->path) && strlen($this->path)) ? '/' . $this->path : '' );
597 return $this->baseurl;
600 function set_baseurl($url) {
601 $parsed = @parse_url($url);
603 $this->baseurl = $url;
606 $this->scheme = $parsed['scheme'];
608 $this->hostname = $parsed['host'];
609 if(x($parsed,'port'))
610 $this->hostname .= ':' . $parsed['port'];
611 if(x($parsed,'path'))
612 $this->path = trim($parsed['path'],'\\/');
617 function get_hostname() {
618 return $this->hostname;
621 function set_hostname($h) {
622 $this->hostname = $h;
625 function set_path($p) {
626 $this->path = trim(trim($p),'/');
629 function get_path() {
633 function set_pager_total($n) {
634 $this->pager['total'] = intval($n);
637 function set_pager_itemspage($n) {
638 $this->pager['itemspage'] = ((intval($n) > 0) ? intval($n) : 0);
639 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
642 function set_pager_page($n) {
643 $this->pager['page'] = $n;
644 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
647 function init_pagehead() {
648 $interval = ((local_user()) ? get_pconfig(local_user(),'system','update_interval') : 40000);
649 if($interval < 10000)
652 $this->page['title'] = $this->config['sitename'];
654 /* put the head template at the beginning of page['htmlhead']
655 * since the code added by the modules frequently depends on it
658 if(!isset($this->page['htmlhead']))
659 $this->page['htmlhead'] = '';
661 // If we're using Smarty, then doing replace_macros() will replace
662 // any unrecognized variables with a blank string. Since we delay
663 // replacing $stylesheet until later, we need to replace it now
664 // with another variable name
665 if($this->theme['template_engine'] === 'smarty3')
666 $stylesheet = $this->get_template_ldelim('smarty3') . '$stylesheet' . $this->get_template_rdelim('smarty3');
668 $stylesheet = '$stylesheet';
670 $tpl = get_markup_template('head.tpl');
671 $this->page['htmlhead'] = replace_macros($tpl,array(
672 '$baseurl' => $this->get_baseurl(), // FIXME for z_path!!!!
673 '$local_user' => local_user(),
674 '$generator' => 'Friendica' . ' ' . FRIENDICA_VERSION,
675 '$delitem' => t('Delete this item?'),
676 '$comment' => t('Comment'),
677 '$showmore' => t('show more'),
678 '$showfewer' => t('show fewer'),
679 '$update_interval' => $interval,
680 '$stylesheet' => $stylesheet
681 )) . $this->page['htmlhead'];
684 function init_page_end() {
685 if(!isset($this->page['end']))
686 $this->page['end'] = '';
687 $tpl = get_markup_template('end.tpl');
688 $this->page['end'] = replace_macros($tpl,array(
689 '$baseurl' => $this->get_baseurl() // FIXME for z_path!!!!
690 )) . $this->page['end'];
693 function set_curl_code($code) {
694 $this->curl_code = $code;
697 function get_curl_code() {
698 return $this->curl_code;
701 function set_curl_content_type($content_type) {
702 $this->curl_content_type = $content_type;
705 function get_curl_content_type() {
706 return $this->curl_content_type;
709 function set_curl_headers($headers) {
710 $this->curl_headers = $headers;
713 function get_curl_headers() {
714 return $this->curl_headers;
717 function get_cached_avatar_image($avatar_image){
718 if($this->cached_profile_image[$avatar_image])
719 return $this->cached_profile_image[$avatar_image];
721 $path_parts = explode("/",$avatar_image);
722 $common_filename = $path_parts[count($path_parts)-1];
724 if($this->cached_profile_picdate[$common_filename]){
725 $this->cached_profile_image[$avatar_image] = $avatar_image . $this->cached_profile_picdate[$common_filename];
727 $r = q("SELECT `contact`.`avatar-date` AS picdate FROM `contact` WHERE `contact`.`thumb` like \"%%/%s\"",
730 $this->cached_profile_image[$avatar_image] = $avatar_image;
732 $this->cached_profile_picdate[$common_filename] = "?rev=" . urlencode($r[0]['picdate']);
733 $this->cached_profile_image[$avatar_image] = $avatar_image . $this->cached_profile_picdate[$common_filename];
736 return $this->cached_profile_image[$avatar_image];
741 * register template engine class
742 * if $name is "", is used class static property $class::$name
743 * @param string $class
744 * @param string $name
746 function register_template_engine($class, $name = '') {
748 $v = get_class_vars( $class );
749 if(x($v,"name")) $name = $v['name'];
752 echo "template engine <tt>$class</tt> cannot be registered without a name.\n";
755 $this->template_engines[$name] = $class;
759 * return template engine instance. If $name is not defined,
760 * return engine defined by theme, or default
762 * @param strin $name Template engine name
763 * @return object Template Engine instance
765 function template_engine($name = ''){
767 $template_engine = $name;
769 $template_engine = 'smarty3';
770 if (x($this->theme, 'template_engine')) {
771 $template_engine = $this->theme['template_engine'];
775 if (isset($this->template_engines[$template_engine])){
776 if(isset($this->template_engine_instance[$template_engine])){
777 return $this->template_engine_instance[$template_engine];
779 $class = $this->template_engines[$template_engine];
781 $this->template_engine_instance[$template_engine] = $obj;
786 echo "template engine <tt>$template_engine</tt> is not registered!\n"; killme();
789 function get_template_engine() {
790 return $this->theme['template_engine'];
793 function set_template_engine($engine = 'smarty3') {
794 $this->theme['template_engine'] = $engine;
796 $this->theme['template_engine'] = 'smarty3';
800 if(is_writable('view/smarty3/'))
801 $this->theme['template_engine'] = 'smarty3';
809 function get_template_ldelim($engine = 'smarty3') {
810 return $this->ldelim[$engine];
813 function get_template_rdelim($engine = 'smarty3') {
814 return $this->rdelim[$engine];
817 function save_timestamp($stamp, $value) {
818 $duration = (float)(microtime(true)-$stamp);
820 $this->performance[$value] += (float)$duration;
821 $this->performance["marktime"] += (float)$duration;
824 function mark_timestamp($mark) {
825 //$this->performance["markstart"] -= microtime(true) - $this->performance["marktime"];
826 $this->performance["markstart"] = microtime(true) - $this->performance["markstart"] - $this->performance["marktime"];
831 // retrieve the App structure
832 // useful in functions which require it but don't get it passed to them
834 if(! function_exists('get_app')) {
842 // Multi-purpose function to check variable state.
843 // Usage: x($var) or $x($array,'key')
844 // returns false if variable/key is not set
845 // if variable is set, returns 1 if has 'non-zero' value, otherwise returns 0.
846 // e.g. x('') or x(0) returns 0;
848 if(! function_exists('x')) {
849 function x($s,$k = NULL) {
851 if((is_array($s)) && (array_key_exists($k,$s))) {
870 // called from db initialisation if db is dead.
872 if(! function_exists('system_unavailable')) {
873 function system_unavailable() {
874 include('system_unavailable.php');
882 function clean_urls() {
884 // if($a->config['system']['clean_urls'])
891 $base = $a->get_baseurl();
899 return $a->get_baseurl();
902 function absurl($path) {
903 if(strpos($path,'/') === 0)
904 return z_path() . $path;
909 return (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');
912 function check_db() {
914 $build = get_config('system','build');
916 set_config('system','build',DB_UPDATE_VERSION);
917 $build = DB_UPDATE_VERSION;
919 if($build != DB_UPDATE_VERSION)
920 proc_run('php', 'include/dbupdate.php');
927 // Sets the base url for use in cmdline programs which don't have
928 // $_SERVER variables
930 if(! function_exists('check_url')) {
931 function check_url(&$a) {
933 $url = get_config('system','url');
935 // if the url isn't set or the stored url is radically different
936 // than the currently visited url, store the current value accordingly.
937 // "Radically different" ignores common variations such as http vs https
938 // and www.example.com vs example.com.
939 // We will only change the url to an ip address if there is no existing setting
942 $url = set_config('system','url',$a->get_baseurl());
943 if((! link_compare($url,$a->get_baseurl())) && (! preg_match("/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/",$a->get_hostname)))
944 $url = set_config('system','url',$a->get_baseurl());
951 // Automatic database updates
953 if(! function_exists('update_db')) {
954 function update_db(&$a) {
956 $build = get_config('system','build');
958 $build = set_config('system','build',DB_UPDATE_VERSION);
960 if($build != DB_UPDATE_VERSION) {
961 $stored = intval($build);
962 $current = intval(DB_UPDATE_VERSION);
963 if(($stored < $current) && file_exists('update.php')) {
965 load_config('database');
967 // We're reporting a different version than what is currently installed.
968 // Run any existing update scripts to bring the database up to current.
970 require_once('update.php');
972 // make sure that boot.php and update.php are the same release, we might be
973 // updating right this very second and the correct version of the update.php
974 // file may not be here yet. This can happen on a very busy site.
976 if(DB_UPDATE_VERSION == UPDATE_VERSION) {
978 for($x = $stored; $x < $current; $x ++) {
979 if(function_exists('update_' . $x)) {
981 // There could be a lot of processes running or about to run.
982 // We want exactly one process to run the update command.
983 // So store the fact that we're taking responsibility
984 // after first checking to see if somebody else already has.
986 // If the update fails or times-out completely you may need to
987 // delete the config entry to try again.
989 $t = get_config('database','update_' . $x);
992 set_config('database','update_' . $x, time());
994 // call the specific update
996 $func = 'update_' . $x;
999 //send the administrator an e-mail
1000 $email_tpl = get_intltext_template("update_fail_eml.tpl");
1001 $email_msg = replace_macros($email_tpl, array(
1002 '$sitename' => $a->config['sitename'],
1003 '$siteurl' => $a->get_baseurl(),
1005 '$error' => sprintf( t('Update %s failed. See error logs.'), $x)
1007 $subject=sprintf(t('Update Error at %s'), $a->get_baseurl());
1008 require_once('include/email.php');
1009 $subject = email_header_encode($subject,'UTF-8');
1010 mail($a->config['admin_email'], $subject, $email_msg,
1011 'From: ' . 'Administrator' . '@' . $_SERVER['SERVER_NAME'] . "\n"
1012 . 'Content-type: text/plain; charset=UTF-8' . "\n"
1013 . 'Content-transfer-encoding: 8bit' );
1015 logger('CRITICAL: Update Failed: '. $x);
1019 set_config('database','update_' . $x, 'success');
1020 set_config('system','build', $x + 1);
1033 if(! function_exists('check_plugins')) {
1034 function check_plugins(&$a) {
1038 * Synchronise plugins:
1040 * $a->config['system']['addon'] contains a comma-separated list of names
1041 * of plugins/addons which are used on this system.
1042 * Go through the database list of already installed addons, and if we have
1043 * an entry, but it isn't in the config list, call the uninstall procedure
1044 * and mark it uninstalled in the database (for now we'll remove it).
1045 * Then go through the config list and if we have a plugin that isn't installed,
1046 * call the install procedure and add it to the database.
1050 $r = q("SELECT * FROM `addon` WHERE `installed` = 1");
1054 $installed = array();
1056 $plugins = get_config('system','addon');
1057 $plugins_arr = array();
1060 $plugins_arr = explode(',',str_replace(' ', '',$plugins));
1062 $a->plugins = $plugins_arr;
1064 $installed_arr = array();
1066 if(count($installed)) {
1067 foreach($installed as $i) {
1068 if(! in_array($i['name'],$plugins_arr)) {
1069 uninstall_plugin($i['name']);
1072 $installed_arr[] = $i['name'];
1077 if(count($plugins_arr)) {
1078 foreach($plugins_arr as $p) {
1079 if(! in_array($p,$installed_arr)) {
1093 function get_guid($size=16) {
1094 $exists = true; // assume by default that we don't have a unique guid
1096 $s = random_string($size);
1097 $r = q("select id from guid where guid = '%s' limit 1", dbesc($s));
1101 q("insert into guid ( guid ) values ( '%s' ) ", dbesc($s));
1106 // wrapper for adding a login box. If $register == true provide a registration
1107 // link. This will most always depend on the value of $a->config['register_policy'].
1108 // returns the complete html for inserting into the page
1110 if(! function_exists('login')) {
1111 function login($register = false, $hiddens=false) {
1117 'title' => t('Create a New Account'),
1118 'desc' => t('Register')
1122 $noid = get_config('system','no_openid');
1124 $dest_url = $a->get_baseurl(true) . '/' . $a->query_string;
1127 $tpl = get_markup_template("logout.tpl");
1130 $a->page['htmlhead'] .= replace_macros(get_markup_template("login_head.tpl"),array(
1131 '$baseurl' => $a->get_baseurl(true)
1134 $tpl = get_markup_template("login.tpl");
1135 $_SESSION['return_url'] = $a->query_string;
1136 $a->module = 'login';
1139 $o .= replace_macros($tpl, array(
1141 '$dest_url' => $dest_url,
1142 '$logout' => t('Logout'),
1143 '$login' => t('Login'),
1145 '$lname' => array('username', t('Nickname or Email address: ') , '', ''),
1146 '$lpassword' => array('password', t('Password: '), '', ''),
1147 '$lremember' => array('remember', t('Remember me'), 0, ''),
1149 '$openid' => !$noid,
1150 '$lopenid' => array('openid_url', t('Or login using OpenID: '),'',''),
1152 '$hiddens' => $hiddens,
1154 '$register' => $reg,
1156 '$lostpass' => t('Forgot your password?'),
1157 '$lostlink' => t('Password Reset'),
1159 '$tostitle' => t('Website Terms of Service'),
1160 '$toslink' => t('terms of service'),
1162 '$privacytitle' => t('Website Privacy Policy'),
1163 '$privacylink' => t('privacy policy'),
1167 call_hooks('login_hook',$o);
1173 // Used to end the current process, after saving session state.
1175 if(! function_exists('killme')) {
1177 session_write_close();
1182 // redirect to another URL and terminate this process.
1184 if(! function_exists('goaway')) {
1185 function goaway($s) {
1186 header("Location: $s");
1192 // Returns the uid of locally logged in user or false.
1194 if(! function_exists('local_user')) {
1195 function local_user() {
1196 if((x($_SESSION,'authenticated')) && (x($_SESSION,'uid')))
1197 return intval($_SESSION['uid']);
1202 // Returns contact id of authenticated site visitor or false
1204 if(! function_exists('remote_user')) {
1205 function remote_user() {
1206 if((x($_SESSION,'authenticated')) && (x($_SESSION,'visitor_id')))
1207 return intval($_SESSION['visitor_id']);
1212 // contents of $s are displayed prominently on the page the next time
1213 // a page is loaded. Usually used for errors or alerts.
1215 if(! function_exists('notice')) {
1217 * Show an error message to user.
1219 * This function save text in session, to be shown to the user at next page load
1221 * @param string $s - Text of notice
1223 function notice($s) {
1225 if(! x($_SESSION,'sysmsg')) $_SESSION['sysmsg'] = array();
1227 $_SESSION['sysmsg'][] = $s;
1230 if(! function_exists('info')) {
1232 * Show an info message to user.
1234 * This function save text in session, to be shown to the user at next page load
1236 * @param string $s - Text of notice
1240 if(! x($_SESSION,'sysmsg_info')) $_SESSION['sysmsg_info'] = array();
1242 $_SESSION['sysmsg_info'][] = $s;
1247 // wrapper around config to limit the text length of an incoming message
1249 if(! function_exists('get_max_import_size')) {
1250 function get_max_import_size() {
1252 return ((x($a->config,'max_import_size')) ? $a->config['max_import_size'] : 0 );
1260 * Function : profile_load
1262 * @parameter string $nickname
1263 * @parameter int $profile
1265 * Summary: Loads a profile into the page sidebar.
1266 * The function requires a writeable copy of the main App structure, and the nickname
1267 * of a registered local account.
1269 * If the viewer is an authenticated remote viewer, the profile displayed is the
1270 * one that has been configured for his/her viewing in the Contact manager.
1271 * Passing a non-zero profile ID can also allow a preview of a selected profile
1274 * Profile information is placed in the App structure for later retrieval.
1275 * Honours the owner's chosen theme for display.
1277 * IMPORTANT: Should only be run in the _init() functions of a module. That ensures that
1278 * the theme is chosen before the _init() function of a theme is run, which will usually
1279 * load a lot of theme-specific content
1283 if(! function_exists('profile_load')) {
1284 function profile_load(&$a, $nickname, $profile = 0) {
1286 $user = q("select uid from user where nickname = '%s' limit 1",
1290 if(! ($user && count($user))) {
1291 logger('profile error: ' . $a->query_string, LOGGER_DEBUG);
1292 notice( t('Requested account is not available.') . EOL );
1297 if(remote_user() && count($_SESSION['remote'])) {
1298 foreach($_SESSION['remote'] as $visitor) {
1299 if($visitor['uid'] == $user[0]['uid']) {
1300 $r = q("SELECT `profile-id` FROM `contact` WHERE `id` = %d LIMIT 1",
1301 intval($visitor['cid'])
1304 $profile = $r[0]['profile-id'];
1313 $profile_int = intval($profile);
1314 $r = q("SELECT `profile`.`uid` AS `profile_uid`, `profile`.* , `contact`.`avatar-date` AS picdate, `user`.* FROM `profile`
1315 left join `contact` on `contact`.`uid` = `profile`.`uid` LEFT JOIN `user` ON `profile`.`uid` = `user`.`uid`
1316 WHERE `user`.`nickname` = '%s' AND `profile`.`id` = %d and `contact`.`self` = 1 LIMIT 1",
1318 intval($profile_int)
1321 if((! $r) && (! count($r))) {
1322 $r = q("SELECT `profile`.`uid` AS `profile_uid`, `profile`.* , `contact`.`avatar-date` AS picdate, `user`.* FROM `profile`
1323 left join `contact` on `contact`.`uid` = `profile`.`uid` LEFT JOIN `user` ON `profile`.`uid` = `user`.`uid`
1324 WHERE `user`.`nickname` = '%s' AND `profile`.`is-default` = 1 and `contact`.`self` = 1 LIMIT 1",
1329 if(($r === false) || (! count($r))) {
1330 logger('profile error: ' . $a->query_string, LOGGER_DEBUG);
1331 notice( t('Requested profile is not available.') . EOL );
1336 // fetch user tags if this isn't the default profile
1338 if(! $r[0]['is-default']) {
1339 $x = q("select `pub_keywords` from `profile` where uid = %d and `is-default` = 1 limit 1",
1340 intval($r[0]['profile_uid'])
1343 $r[0]['pub_keywords'] = $x[0]['pub_keywords'];
1346 $a->profile = $r[0];
1348 $a->profile['mobile-theme'] = get_pconfig($a->profile['profile_uid'], 'system', 'mobile_theme');
1351 $a->page['title'] = $a->profile['name'] . " @ " . $a->config['sitename'];
1352 $_SESSION['theme'] = $a->profile['theme'];
1353 $_SESSION['mobile-theme'] = $a->profile['mobile-theme'];
1356 * load/reload current theme info
1359 $a->set_template_engine(); // reset the template engine to the default in case the user's theme doesn't specify one
1361 $theme_info_file = "view/theme/".current_theme()."/theme.php";
1362 if (file_exists($theme_info_file)){
1363 require_once($theme_info_file);
1366 if(! (x($a->page,'aside')))
1367 $a->page['aside'] = '';
1369 if(local_user() && local_user() == $a->profile['uid']) {
1370 $a->page['aside'] .= replace_macros(get_markup_template('profile_edlink.tpl'),array(
1371 '$editprofile' => t('Edit profile'),
1372 '$profid' => $a->profile['id']
1376 $block = (((get_config('system','block_public')) && (! local_user()) && (! remote_user())) ? true : false);
1378 $a->page['aside'] .= profile_sidebar($a->profile, $block);
1381 $a->page['aside'] .= contact_block();*/
1390 * Function: profile_sidebar
1392 * Formats a profile for display in the sidebar.
1393 * It is very difficult to templatise the HTML completely
1394 * because of all the conditional logic.
1396 * @parameter: array $profile
1398 * Returns HTML string stuitable for sidebar inclusion
1399 * Exceptions: Returns empty string if passed $profile is wrong type or not populated
1404 if(! function_exists('profile_sidebar')) {
1405 function profile_sidebar($profile, $block = 0) {
1414 if((! is_array($profile)) && (! count($profile)))
1417 $profile['picdate'] = urlencode($profile['picdate']);
1419 call_hooks('profile_sidebar_enter', $profile);
1422 // don't show connect link to yourself
1423 $connect = (($profile['uid'] != local_user()) ? t('Connect') : False);
1425 // don't show connect link to authenticated visitors either
1427 if(remote_user() && count($_SESSION['remote'])) {
1428 foreach($_SESSION['remote'] as $visitor) {
1429 if($visitor['uid'] == $profile['uid']) {
1436 if( get_my_url() && $profile['unkmail'] && ($profile['uid'] != local_user()) )
1437 $wallmessage = t('Message');
1439 $wallmessage = false;
1443 // show edit profile to yourself
1444 if ($profile['uid'] == local_user() && feature_enabled(local_user(),'multi_profiles')) {
1445 $profile['edit'] = array($a->get_baseurl(). '/profiles', t('Profiles'),"", t('Manage/edit profiles'));
1447 $r = q("SELECT * FROM `profile` WHERE `uid` = %d",
1450 $profile['menu'] = array(
1451 'chg_photo' => t('Change profile photo'),
1452 'cr_new' => t('Create New Profile'),
1453 'entries' => array(),
1458 foreach($r as $rr) {
1459 $profile['menu']['entries'][] = array(
1460 'photo' => $rr['thumb'],
1462 'alt' => t('Profile Image'),
1463 'profile_name' => $rr['profile-name'],
1464 'isdefault' => $rr['is-default'],
1465 'visibile_to_everybody' => t('visible to everybody'),
1466 'edit_visibility' => t('Edit visibility'),
1474 if ($profile['uid'] == local_user() && !feature_enabled(local_user(),'multi_profiles')) {
1475 $profile['edit'] = array($a->get_baseurl(). '/profiles/'.$profile['id'], t('Edit profile'),"", t('Edit profile'));
1476 $profile['menu'] = array(
1477 'chg_photo' => t('Change profile photo'),
1479 'entries' => array(),
1486 if((x($profile,'address') == 1)
1487 || (x($profile,'locality') == 1)
1488 || (x($profile,'region') == 1)
1489 || (x($profile,'postal-code') == 1)
1490 || (x($profile,'country-name') == 1))
1491 $location = t('Location:');
1493 $gender = ((x($profile,'gender') == 1) ? t('Gender:') : False);
1496 $marital = ((x($profile,'marital') == 1) ? t('Status:') : False);
1498 $homepage = ((x($profile,'homepage') == 1) ? t('Homepage:') : False);
1500 if(($profile['hidewall'] || $block) && (! local_user()) && (! remote_user())) {
1501 $location = $pdesc = $gender = $marital = $homepage = False;
1504 $firstname = ((strpos($profile['name'],' '))
1505 ? trim(substr($profile['name'],0,strpos($profile['name'],' '))) : $profile['name']);
1506 $lastname = (($firstname === $profile['name']) ? '' : trim(substr($profile['name'],strlen($firstname))));
1509 'podloc' => $a->get_baseurl(),
1510 'searchable' => (($profile['publish'] && $profile['net-publish']) ? 'true' : 'false' ),
1511 'nickname' => $profile['nickname'],
1512 'fullname' => $profile['name'],
1513 'firstname' => $firstname,
1514 'lastname' => $lastname,
1515 'photo300' => $a->get_cached_avatar_image($a->get_baseurl() . '/photo/custom/300/' . $profile['uid'] . '.jpg'),
1516 'photo100' => $a->get_cached_avatar_image($a->get_baseurl() . '/photo/custom/100/' . $profile['uid'] . '.jpg'),
1517 'photo50' => $a->get_cached_avatar_image($a->get_baseurl() . '/photo/custom/50/' . $profile['uid'] . '.jpg'),
1521 $contact_block = contact_block();
1526 foreach($profile as $k => $v) {
1527 $k = str_replace('-','_',$k);
1531 if($a->theme['template_engine'] === 'internal')
1532 $location = template_escape($location);
1535 $tpl = get_markup_template('profile_vcard.tpl');
1536 $o .= replace_macros($tpl, array(
1538 '$connect' => $connect,
1539 '$wallmessage' => $wallmessage,
1540 '$location' => $location,
1541 '$gender' => $gender,
1543 '$marital' => $marital,
1544 '$homepage' => $homepage,
1545 '$diaspora' => $diaspora,
1546 '$contact_block' => $contact_block,
1550 $arr = array('profile' => &$profile, 'entry' => &$o);
1552 call_hooks('profile_sidebar', $arr);
1559 if(! function_exists('get_birthdays')) {
1560 function get_birthdays() {
1565 if(! local_user() || $a->is_mobile || $a->is_tablet)
1568 // $mobile_detect = new Mobile_Detect();
1569 // $is_mobile = $mobile_detect->isMobile() || $mobile_detect->isTablet();
1574 $bd_format = t('g A l F d') ; // 8 AM Friday January 18
1575 $bd_short = t('F d');
1577 $r = q("SELECT `event`.*, `event`.`id` AS `eid`, `contact`.* FROM `event`
1578 LEFT JOIN `contact` ON `contact`.`id` = `event`.`cid`
1579 WHERE `event`.`uid` = %d AND `type` = 'birthday' AND `start` < '%s' AND `finish` > '%s'
1580 ORDER BY `start` ASC ",
1581 intval(local_user()),
1582 dbesc(datetime_convert('UTC','UTC','now + 6 days')),
1583 dbesc(datetime_convert('UTC','UTC','now'))
1586 if($r && count($r)) {
1588 $now = strtotime('now');
1592 foreach($r as $rr) {
1593 if(strlen($rr['name']))
1595 if((strtotime($rr['start'] . ' +00:00') < $now) && (strtotime($rr['finish'] . ' +00:00') > $now))
1598 $classtoday = $istoday ? ' birthday-today ' : '';
1600 foreach($r as &$rr) {
1601 if(! strlen($rr['name']))
1606 if(in_array($rr['cid'],$cids))
1608 $cids[] = $rr['cid'];
1610 $today = (((strtotime($rr['start'] . ' +00:00') < $now) && (strtotime($rr['finish'] . ' +00:00') > $now)) ? true : false);
1613 if($rr['network'] === NETWORK_DFRN) {
1614 $sparkle = " sparkle";
1615 $url = $a->get_baseurl() . '/redir/' . $rr['cid'];
1619 $rr['title'] = $rr['name'];
1620 $rr['date'] = day_translate(datetime_convert('UTC', $a->timezone, $rr['start'], $rr['adjust'] ? $bd_format : $bd_short)) . (($today) ? ' ' . t('[today]') : '');
1621 $rr['startime'] = Null;
1622 $rr['today'] = $today;
1627 $tpl = get_markup_template("birthdays_reminder.tpl");
1628 return replace_macros($tpl, array(
1629 '$baseurl' => $a->get_baseurl(),
1630 '$classtoday' => $classtoday,
1632 '$event_reminders' => t('Birthday Reminders'),
1633 '$event_title' => t('Birthdays this week:'),
1635 '$lbr' => '{', // raw brackets mess up if/endif macro processing
1643 if(! function_exists('get_events')) {
1644 function get_events() {
1646 require_once('include/bbcode.php');
1650 if(! local_user() || $a->is_mobile || $a->is_tablet)
1654 // $mobile_detect = new Mobile_Detect();
1655 // $is_mobile = $mobile_detect->isMobile() || $mobile_detect->isTablet();
1660 $bd_format = t('g A l F d') ; // 8 AM Friday January 18
1661 $bd_short = t('F d');
1663 $r = q("SELECT `event`.* FROM `event`
1664 WHERE `event`.`uid` = %d AND `type` != 'birthday' AND `start` < '%s' AND `start` > '%s'
1665 ORDER BY `start` ASC ",
1666 intval(local_user()),
1667 dbesc(datetime_convert('UTC','UTC','now + 6 days')),
1668 dbesc(datetime_convert('UTC','UTC','now - 1 days'))
1671 if($r && count($r)) {
1672 $now = strtotime('now');
1674 foreach($r as $rr) {
1675 if(strlen($rr['name']))
1678 $strt = datetime_convert('UTC',$rr['convert'] ? $a->timezone : 'UTC',$rr['start'],'Y-m-d');
1679 if($strt === datetime_convert('UTC',$a->timezone,'now','Y-m-d'))
1682 $classtoday = (($istoday) ? 'event-today' : '');
1685 foreach($r as &$rr) {
1687 $md = datetime_convert('UTC',$a->timezone,$rr['start'],'Y/m');
1689 $md = datetime_convert('UTC','UTC',$rr['start'],'Y/m');
1690 $md .= "/#link-".$rr['id'];
1692 $title = substr(strip_tags(bbcode($rr['desc'])),0,32) . '... ';
1694 $title = t('[No description]');
1696 $strt = datetime_convert('UTC',$rr['convert'] ? $a->timezone : 'UTC',$rr['start']);
1697 $today = ((substr($strt,0,10) === datetime_convert('UTC',$a->timezone,'now','Y-m-d')) ? true : false);
1700 $rr['title'] = $title;
1701 $rr['date'] = day_translate(datetime_convert('UTC', $rr['adjust'] ? $a->timezone : 'UTC', $rr['start'], $bd_format)) . (($today) ? ' ' . t('[today]') : '');
1702 $rr['startime'] = $strt;
1703 $rr['today'] = $today;
1707 $tpl = get_markup_template("events_reminder.tpl");
1708 return replace_macros($tpl, array(
1709 '$baseurl' => $a->get_baseurl(),
1710 '$classtoday' => $classtoday,
1711 '$count' => count($r),
1712 '$event_reminders' => t('Event Reminders'),
1713 '$event_title' => t('Events this week:'),
1722 * Wrap calls to proc_close(proc_open()) and call hook
1723 * so plugins can take part in process :)
1726 * $cmd program to run
1727 * next args are passed as $cmd command line
1729 * e.g.: proc_run("ls","-la","/tmp");
1731 * $cmd and string args are surrounded with ""
1734 if(! function_exists('proc_run')) {
1735 function proc_run($cmd){
1739 $args = func_get_args();
1745 // expand any arrays
1747 foreach($args as $arg) {
1748 if(is_array($arg)) {
1749 foreach($arg as $n) {
1759 $arr = array('args' => $args, 'run_cmd' => true);
1761 call_hooks("proc_run", $arr);
1762 if(! $arr['run_cmd'])
1765 if(count($args) && $args[0] === 'php')
1766 $args[0] = ((x($a->config,'php_path')) && (strlen($a->config['php_path'])) ? $a->config['php_path'] : 'php');
1768 // add baseurl to args. cli scripts can't construct it
1769 $args[] = $a->get_baseurl();
1771 for($x = 0; $x < count($args); $x ++)
1772 $args[$x] = escapeshellarg($args[$x]);
1776 $cmdline = implode($args," ");
1777 if(get_config('system','proc_windows'))
1778 proc_close(proc_open('cmd /c start /b ' . $cmdline,array(),$foo,dirname(__FILE__)));
1780 proc_close(proc_open($cmdline." &",array(),$foo,dirname(__FILE__)));
1784 if(! function_exists('current_theme')) {
1785 function current_theme(){
1786 $app_base_themes = array('duepuntozero', 'dispy', 'quattro');
1790 // $mobile_detect = new Mobile_Detect();
1791 // $is_mobile = $mobile_detect->isMobile() || $mobile_detect->isTablet();
1792 $is_mobile = $a->is_mobile || $a->is_tablet;
1795 if(isset($_SESSION['show-mobile']) && !$_SESSION['show-mobile']) {
1800 $system_theme = ((isset($a->config['system']['mobile-theme'])) ? $a->config['system']['mobile-theme'] : '');
1801 $theme_name = ((isset($_SESSION) && x($_SESSION,'mobile-theme')) ? $_SESSION['mobile-theme'] : $system_theme);
1803 if($theme_name === '---') {
1804 // user has selected to have the mobile theme be the same as the normal one
1810 if(!$is_mobile || ($system_theme === '' && $theme_name === '')) {
1811 $system_theme = ((isset($a->config['system']['theme'])) ? $a->config['system']['theme'] : '');
1812 $theme_name = ((isset($_SESSION) && x($_SESSION,'theme')) ? $_SESSION['theme'] : $system_theme);
1816 (file_exists('view/theme/' . $theme_name . '/style.css') ||
1817 file_exists('view/theme/' . $theme_name . '/style.php')))
1818 return($theme_name);
1820 foreach($app_base_themes as $t) {
1821 if(file_exists('view/theme/' . $t . '/style.css')||
1822 file_exists('view/theme/' . $t . '/style.php'))
1826 $fallback = array_merge(glob('view/theme/*/style.css'),glob('view/theme/*/style.php'));
1827 if(count($fallback))
1828 return (str_replace('view/theme/','', substr($fallback[0],0,-10)));
1834 * Return full URL to theme which is currently in effect.
1835 * Provide a sane default if nothing is chosen or the specified theme does not exist.
1837 if(! function_exists('current_theme_url')) {
1838 function current_theme_url() {
1840 $t = current_theme();
1841 if (file_exists('view/theme/' . $t . '/style.php'))
1842 return($a->get_baseurl() . '/view/theme/' . $t . '/style.pcss');
1843 return($a->get_baseurl() . '/view/theme/' . $t . '/style.css');
1847 if(! function_exists('feed_birthday')) {
1848 function feed_birthday($uid,$tz) {
1852 * Determine the next birthday, but only if the birthday is published
1853 * in the default profile. We _could_ also look for a private profile that the
1854 * recipient can see, but somebody could get mad at us if they start getting
1855 * public birthday greetings when they haven't made this info public.
1857 * Assuming we are able to publish this info, we are then going to convert
1858 * the start time from the owner's timezone to UTC.
1860 * This will potentially solve the problem found with some social networks
1861 * where birthdays are converted to the viewer's timezone and salutations from
1862 * elsewhere in the world show up on the wrong day. We will convert it to the
1863 * viewer's timezone also, but first we are going to convert it from the birthday
1864 * person's timezone to GMT - so the viewer may find the birthday starting at
1865 * 6:00PM the day before, but that will correspond to midnight to the birthday person.
1875 $p = q("SELECT `dob` FROM `profile` WHERE `is-default` = 1 AND `uid` = %d LIMIT 1",
1879 if($p && count($p)) {
1880 $tmp_dob = substr($p[0]['dob'],5);
1881 if(intval($tmp_dob)) {
1882 $y = datetime_convert($tz,$tz,'now','Y');
1883 $bd = $y . '-' . $tmp_dob . ' 00:00';
1884 $t_dob = strtotime($bd);
1885 $now = strtotime(datetime_convert($tz,$tz,'now'));
1887 $bd = $y + 1 . '-' . $tmp_dob . ' 00:00';
1888 $birthday = datetime_convert($tz,'UTC',$bd,ATOM_TIME);
1896 if(! function_exists('is_site_admin')) {
1897 function is_site_admin() {
1899 if(local_user() && x($a->user,'email') && x($a->config,'admin_email') && ($a->user['email'] === $a->config['admin_email']))
1906 if(! function_exists('load_contact_links')) {
1907 function load_contact_links($uid) {
1913 if(! $uid || x($a->contacts,'empty'))
1916 $r = q("SELECT `id`,`network`,`url`,`thumb` FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 ",
1921 $url = normalise_link($rr['url']);
1926 $ret['empty'] = true;
1927 $a->contacts = $ret;
1932 if(! function_exists('profile_tabs')){
1933 function profile_tabs($a, $is_owner=False, $nickname=Null){
1934 //echo "<pre>"; var_dump($a->user); killme();
1936 if (is_null($nickname))
1937 $nickname = $a->user['nickname'];
1940 $tab = notags(trim($_GET['tab']));
1942 $url = $a->get_baseurl() . '/profile/' . $nickname;
1946 'label'=>t('Status'),
1948 'sel' => ((!isset($tab)&&$a->argv[0]=='profile')?'active':''),
1949 'title' => t('Status Messages and Posts'),
1950 'id' => 'status-tab',
1953 'label' => t('Profile'),
1954 'url' => $url.'/?tab=profile',
1955 'sel' => ((isset($tab) && $tab=='profile')?'active':''),
1956 'title' => t('Profile Details'),
1957 'id' => 'profile-tab',
1960 'label' => t('Photos'),
1961 'url' => $a->get_baseurl() . '/photos/' . $nickname,
1962 'sel' => ((!isset($tab)&&$a->argv[0]=='photos')?'active':''),
1963 'title' => t('Photo Albums'),
1964 'id' => 'photo-tab',
1967 'label' => t('Videos'),
1968 'url' => $a->get_baseurl() . '/videos/' . $nickname,
1969 'sel' => ((!isset($tab)&&$a->argv[0]=='videos')?'active':''),
1970 'title' => t('Videos'),
1971 'id' => 'video-tab',
1977 'label' => t('Events'),
1978 'url' => $a->get_baseurl() . '/events',
1979 'sel' =>((!isset($tab)&&$a->argv[0]=='events')?'active':''),
1980 'title' => t('Events and Calendar'),
1981 'id' => 'events-tab',
1984 'label' => t('Personal Notes'),
1985 'url' => $a->get_baseurl() . '/notes',
1986 'sel' =>((!isset($tab)&&$a->argv[0]=='notes')?'active':''),
1987 'title' => t('Only You Can See This'),
1988 'id' => 'notes-tab',
1993 $arr = array('is_owner' => $is_owner, 'nickname' => $nickname, 'tab' => (($tab) ? $tab : false), 'tabs' => $tabs);
1994 call_hooks('profile_tabs', $arr);
1996 $tpl = get_markup_template('common_tabs.tpl');
1998 return replace_macros($tpl,array('$tabs' => $arr['tabs']));
2002 function get_my_url() {
2003 if(x($_SESSION,'my_url'))
2004 return $_SESSION['my_url'];
2008 function zrl_init(&$a) {
2009 $tmp_str = get_my_url();
2010 if(validate_url($tmp_str)) {
2011 proc_run('php','include/gprobe.php',bin2hex($tmp_str));
2012 $arr = array('zrl' => $tmp_str, 'url' => $a->cmd);
2013 call_hooks('zrl_init',$arr);
2017 function zrl($s,$force = false) {
2020 if((! strpos($s,'/profile/')) && (! $force))
2022 if($force && substr($s,-1,1) !== '/')
2024 $achar = strpos($s,'?') ? '&' : '?';
2025 $mine = get_my_url();
2026 if($mine and ! link_compare($mine,$s))
2027 return $s . $achar . 'zrl=' . urlencode($mine);
2032 * returns querystring as string from a mapped array
2034 * @param params Array
2037 function build_querystring($params, $name=null) {
2039 foreach($params as $key=>$val) {
2040 if(is_array($val)) {
2042 $ret .= build_querystring($val, $key);
2044 $ret .= build_querystring($val, $name."[$key]");
2047 $val = urlencode($val);
2049 $ret.=$name."[$key]"."=$val&";
2051 $ret.= "$key=$val&";
2058 function explode_querystring($query) {
2059 $arg_st = strpos($query, '?');
2060 if($arg_st !== false) {
2061 $base = substr($query, 0, $arg_st);
2069 $args = explode('&', substr($query, $arg_st));
2070 foreach($args as $k=>$arg) {
2074 $args = array_values($args);
2079 $args = array_values($args);
2089 * Returns the complete URL of the current page, e.g.: http(s)://something.com/network
2091 * Taken from http://webcheatsheet.com/php/get_current_page_url.php
2093 function curPageURL() {
2095 if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
2097 if ($_SERVER["SERVER_PORT"] != "80" && $_SERVER["SERVER_PORT"] != "443") {
2098 $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
2100 $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
2105 function random_digits($digits) {
2107 for($i = 0; $i < $digits; $i++) {
2113 function get_cachefile($file, $writemode = true) {
2114 $cache = get_config("system","itemcache");
2116 if ((! $cache) || (! is_dir($cache)))
2119 $subfolder = $cache."/".substr($file, 0, 2);
2121 $cachepath = $subfolder."/".$file;
2124 if (!is_dir($subfolder)) {
2126 chmod($subfolder, 0777);
2133 function clear_cache($basepath = "", $path = "") {
2135 $basepath = get_config('system','itemcache');
2139 if (($path == "") OR (!is_dir($path)))
2142 if (substr(realpath($path), 0, strlen($basepath)) != $basepath)
2145 $cachetime = (int)get_config('system','itemcache_duration');
2146 if ($cachetime == 0)
2149 if ($dh = opendir($path)) {
2150 while (($file = readdir($dh)) !== false) {
2151 $fullpath = $path."/".$file;
2152 if ((filetype($fullpath) == "dir") and ($file != ".") and ($file != ".."))
2153 clear_cache($basepath, $fullpath);
2154 if ((filetype($fullpath) == "file") and (filectime($fullpath) < (time() - $cachetime)))
2161 function set_template_engine(&$a, $engine = 'internal') {
2162 // This function is no longer necessary, but keep it as a wrapper to the class method
2163 // to avoid breaking themes again unnecessarily
2165 $a->set_template_engine($engine);