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.2.1744' );
16 define ( 'DFRN_PROTOCOL_VERSION', '2.23' );
17 define ( 'DB_UPDATE_VERSION', 1165 );
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
143 define ( 'NETWORK_TWITTER', 'twit'); // Twitter
145 define ( 'NETWORK_PHANTOM', 'unkn'); // Place holder
148 * These numbers are used in stored permissions
149 * and existing allocations MUST NEVER BE CHANGED
150 * OR RE-ASSIGNED! You may only add to them.
153 $netgroup_ids = array(
154 NETWORK_DFRN => (-1),
156 NETWORK_OSTATUS => (-3),
157 NETWORK_FEED => (-4),
158 NETWORK_DIASPORA => (-5),
159 NETWORK_MAIL => (-6),
160 NETWORK_MAIL2 => (-7),
161 NETWORK_FACEBOOK => (-8),
162 NETWORK_LINKEDIN => (-9),
163 NETWORK_XMPP => (-10),
164 NETWORK_MYSPACE => (-11),
165 NETWORK_GPLUS => (-12),
166 NETWORK_PUMPIO => (-13),
167 NETWORK_TWITTER => (-14),
169 NETWORK_PHANTOM => (-127),
174 * Maximum number of "people who like (or don't like) this" that we will list by name
177 define ( 'MAX_LIKERS', 75);
180 * Communication timeout
183 define ( 'ZCURL_TIMEOUT' , (-1));
187 * email notification options
190 define ( 'NOTIFY_INTRO', 0x0001 );
191 define ( 'NOTIFY_CONFIRM', 0x0002 );
192 define ( 'NOTIFY_WALL', 0x0004 );
193 define ( 'NOTIFY_COMMENT', 0x0008 );
194 define ( 'NOTIFY_MAIL', 0x0010 );
195 define ( 'NOTIFY_SUGGEST', 0x0020 );
196 define ( 'NOTIFY_PROFILE', 0x0040 );
197 define ( 'NOTIFY_TAGSELF', 0x0080 );
198 define ( 'NOTIFY_TAGSHARE', 0x0100 );
199 define ( 'NOTIFY_POKE', 0x0200 );
201 define ( 'NOTIFY_SYSTEM', 0x8000 );
208 define ( 'TERM_UNKNOWN', 0 );
209 define ( 'TERM_HASHTAG', 1 );
210 define ( 'TERM_MENTION', 2 );
211 define ( 'TERM_CATEGORY', 3 );
212 define ( 'TERM_PCATEGORY', 4 );
213 define ( 'TERM_FILE', 5 );
214 define ( 'TERM_SAVEDSEARCH', 6 );
215 define ( 'TERM_CONVERSATION', 7 );
217 define ( 'TERM_OBJ_POST', 1 );
218 define ( 'TERM_OBJ_PHOTO', 2 );
223 * various namespaces we may need to parse
226 define ( 'NAMESPACE_ZOT', 'http://purl.org/zot' );
227 define ( 'NAMESPACE_DFRN' , 'http://purl.org/macgirvin/dfrn/1.0' );
228 define ( 'NAMESPACE_THREAD' , 'http://purl.org/syndication/thread/1.0' );
229 define ( 'NAMESPACE_TOMB' , 'http://purl.org/atompub/tombstones/1.0' );
230 define ( 'NAMESPACE_ACTIVITY', 'http://activitystrea.ms/spec/1.0/' );
231 define ( 'NAMESPACE_ACTIVITY_SCHEMA', 'http://activitystrea.ms/schema/1.0/' );
232 define ( 'NAMESPACE_MEDIA', 'http://purl.org/syndication/atommedia' );
233 define ( 'NAMESPACE_SALMON_ME', 'http://salmon-protocol.org/ns/magic-env' );
234 define ( 'NAMESPACE_OSTATUSSUB', 'http://ostatus.org/schema/1.0/subscribe' );
235 define ( 'NAMESPACE_GEORSS', 'http://www.georss.org/georss' );
236 define ( 'NAMESPACE_POCO', 'http://portablecontacts.net/spec/1.0' );
237 define ( 'NAMESPACE_FEED', 'http://schemas.google.com/g/2010#updates-from' );
238 define ( 'NAMESPACE_OSTATUS', 'http://ostatus.org/schema/1.0' );
239 define ( 'NAMESPACE_STATUSNET', 'http://status.net/schema/api/1/' );
240 define ( 'NAMESPACE_ATOM1', 'http://www.w3.org/2005/Atom' );
242 * activity stream defines
245 define ( 'ACTIVITY_LIKE', NAMESPACE_ACTIVITY_SCHEMA . 'like' );
246 define ( 'ACTIVITY_DISLIKE', NAMESPACE_DFRN . '/dislike' );
247 define ( 'ACTIVITY_OBJ_HEART', NAMESPACE_DFRN . '/heart' );
249 define ( 'ACTIVITY_FRIEND', NAMESPACE_ACTIVITY_SCHEMA . 'make-friend' );
250 define ( 'ACTIVITY_REQ_FRIEND', NAMESPACE_ACTIVITY_SCHEMA . 'request-friend' );
251 define ( 'ACTIVITY_UNFRIEND', NAMESPACE_ACTIVITY_SCHEMA . 'remove-friend' );
252 define ( 'ACTIVITY_FOLLOW', NAMESPACE_ACTIVITY_SCHEMA . 'follow' );
253 define ( 'ACTIVITY_UNFOLLOW', NAMESPACE_ACTIVITY_SCHEMA . 'stop-following' );
254 define ( 'ACTIVITY_JOIN', NAMESPACE_ACTIVITY_SCHEMA . 'join' );
256 define ( 'ACTIVITY_POST', NAMESPACE_ACTIVITY_SCHEMA . 'post' );
257 define ( 'ACTIVITY_UPDATE', NAMESPACE_ACTIVITY_SCHEMA . 'update' );
258 define ( 'ACTIVITY_TAG', NAMESPACE_ACTIVITY_SCHEMA . 'tag' );
259 define ( 'ACTIVITY_FAVORITE', NAMESPACE_ACTIVITY_SCHEMA . 'favorite' );
261 define ( 'ACTIVITY_POKE', NAMESPACE_ZOT . '/activity/poke' );
262 define ( 'ACTIVITY_MOOD', NAMESPACE_ZOT . '/activity/mood' );
264 define ( 'ACTIVITY_OBJ_COMMENT', NAMESPACE_ACTIVITY_SCHEMA . 'comment' );
265 define ( 'ACTIVITY_OBJ_NOTE', NAMESPACE_ACTIVITY_SCHEMA . 'note' );
266 define ( 'ACTIVITY_OBJ_PERSON', NAMESPACE_ACTIVITY_SCHEMA . 'person' );
267 define ( 'ACTIVITY_OBJ_PHOTO', NAMESPACE_ACTIVITY_SCHEMA . 'photo' );
268 define ( 'ACTIVITY_OBJ_P_PHOTO', NAMESPACE_ACTIVITY_SCHEMA . 'profile-photo' );
269 define ( 'ACTIVITY_OBJ_ALBUM', NAMESPACE_ACTIVITY_SCHEMA . 'photo-album' );
270 define ( 'ACTIVITY_OBJ_EVENT', NAMESPACE_ACTIVITY_SCHEMA . 'event' );
271 define ( 'ACTIVITY_OBJ_GROUP', NAMESPACE_ACTIVITY_SCHEMA . 'group' );
272 define ( 'ACTIVITY_OBJ_TAGTERM', NAMESPACE_DFRN . '/tagterm' );
273 define ( 'ACTIVITY_OBJ_PROFILE', NAMESPACE_DFRN . '/profile' );
276 * item weight for query ordering
279 define ( 'GRAVITY_PARENT', 0);
280 define ( 'GRAVITY_LIKE', 3);
281 define ( 'GRAVITY_COMMENT', 6);
285 * Reverse the effect of magic_quotes_gpc if it is enabled.
286 * Please disable magic_quotes_gpc so we don't have to do this.
287 * See http://php.net/manual/en/security.magicquotes.disabling.php
293 error_reporting(E_ERROR | E_WARNING | E_PARSE);
297 // This has to be quite large to deal with embedded private photos
298 ini_set('pcre.backtrack_limit', 500000);
301 if (get_magic_quotes_gpc()) {
302 $process = array(&$_GET, &$_POST, &$_COOKIE, &$_REQUEST);
303 while (list($key, $val) = each($process)) {
304 foreach ($val as $k => $v) {
305 unset($process[$key][$k]);
307 $process[$key][stripslashes($k)] = $v;
308 $process[] = &$process[$key][stripslashes($k)];
310 $process[$key][stripslashes($k)] = stripslashes($v);
323 * Our main application structure for the life of this page
324 * Primarily deals with the URL that got us here
325 * and tries to make some sense of it, and
326 * stores our page contents and config storage
327 * and anything else that might need to be passed around
328 * before we spit the page out.
332 if(! class_exists('App')) {
335 public $module_loaded = false;
336 public $query_string;
344 public $page_contact;
346 public $data = array();
347 public $error = false;
357 public $interactive = true;
359 public $apps = array();
363 public $performance = array();
370 // Allow themes to control internal parameters
371 // by changing App values in theme.php
373 public $sourcename = '';
374 public $videowidth = 425;
375 public $videoheight = 350;
376 public $force_max_items = 0;
377 public $theme_thread_allow = true;
379 // An array for all theme-controllable parameters
380 // Mostly unimplemented yet. Only options 'stylesheet' and
383 public $theme = array(
386 'videoheight' => 350,
387 'force_max_items' => 0,
388 'thread_allow' => true,
390 'template_engine' => 'smarty3',
393 // array of registered template engines ('name'=>'class name')
394 public $template_engines = array();
395 // array of instanced template engines ('name'=>'instance')
396 public $template_engine_instance = array();
398 private $ldelim = array(
402 private $rdelim = array(
413 private $curl_content_type;
414 private $curl_headers;
416 private $cached_profile_image;
417 private $cached_profile_picdate;
419 function __construct() {
421 global $default_timezone, $argv, $argc;
423 if (file_exists(".htpreconfig.php"))
424 @include(".htpreconfig.php");
426 $this->timezone = ((x($default_timezone)) ? $default_timezone : 'UTC');
428 date_default_timezone_set($this->timezone);
430 $this->performance["start"] = microtime(true);
431 $this->performance["database"] = 0;
432 $this->performance["network"] = 0;
433 $this->performance["file"] = 0;
434 $this->performance["rendering"] = 0;
435 $this->performance["parser"] = 0;
436 $this->performance["marktime"] = 0;
437 $this->performance["markstart"] = microtime(true);
439 $this->config = array();
440 $this->page = array();
441 $this->pager= array();
443 $this->query_string = '';
448 'include' . PATH_SEPARATOR
449 . 'library' . PATH_SEPARATOR
450 . 'library/phpsec' . PATH_SEPARATOR
451 . 'library/langdet' . PATH_SEPARATOR
455 $this->scheme = 'http';
456 if(x($_SERVER,'HTTPS') && $_SERVER['HTTPS'])
457 $this->scheme = 'https';
458 elseif(x($_SERVER,'SERVER_PORT') && (intval($_SERVER['SERVER_PORT']) == 443))
459 $this->scheme = 'https';
461 if(x($_SERVER,'SERVER_NAME')) {
462 $this->hostname = $_SERVER['SERVER_NAME'];
464 // See bug 437 - this didn't work so disabling it
465 //if(stristr($this->hostname,'xn--')) {
466 // PHP or webserver may have converted idn to punycode, so
467 // convert punycode back to utf-8
468 // require_once('library/simplepie/idn/idna_convert.class.php');
469 // $x = new idna_convert();
470 // $this->hostname = $x->decode($_SERVER['SERVER_NAME']);
473 if(x($_SERVER,'SERVER_PORT') && $_SERVER['SERVER_PORT'] != 80 && $_SERVER['SERVER_PORT'] != 443)
474 $this->hostname .= ':' . $_SERVER['SERVER_PORT'];
476 * Figure out if we are running at the top of a domain
477 * or in a sub-directory and adjust accordingly
480 $path = trim(dirname($_SERVER['SCRIPT_NAME']),'/\\');
481 if(isset($path) && strlen($path) && ($path != $this->path))
486 $this->hostname = $hostname;
488 if (is_array($argv) && $argc>1 && substr(end($argv), 0, 4)=="http" ) {
489 $this->set_baseurl(array_pop($argv) );
493 set_include_path("include/$this->hostname" . PATH_SEPARATOR . get_include_path());
495 if((x($_SERVER,'QUERY_STRING')) && substr($_SERVER['QUERY_STRING'],0,2) === "q=") {
496 $this->query_string = substr($_SERVER['QUERY_STRING'],2);
497 // removing trailing / - maybe a nginx problem
498 if (substr($this->query_string, 0, 1) == "/")
499 $this->query_string = substr($this->query_string, 1);
502 $this->cmd = trim($_GET['q'],'/\\');
504 // unix style "homedir"
506 if(substr($this->cmd,0,1) === '~')
507 $this->cmd = 'profile/' . substr($this->cmd,1);
509 // Diaspora style profile url
511 if(substr($this->cmd,0,2) === 'u/')
512 $this->cmd = 'profile/' . substr($this->cmd,2);
516 * Break the URL path into C style argc/argv style arguments for our
517 * modules. Given "http://example.com/module/arg1/arg2", $this->argc
518 * will be 3 (integer) and $this->argv will contain:
524 * There will always be one argument. If provided a naked domain
525 * URL, $this->argv[0] is set to "home".
529 $this->argv = explode('/',$this->cmd);
530 $this->argc = count($this->argv);
531 if((array_key_exists('0',$this->argv)) && strlen($this->argv[0])) {
532 $this->module = str_replace(".", "_", $this->argv[0]);
533 $this->module = str_replace("-", "_", $this->module);
537 $this->argv = array('home');
538 $this->module = 'home';
542 * See if there is any page number information, and initialise
546 $this->pager['page'] = ((x($_GET,'page') && intval($_GET['page']) > 0) ? intval($_GET['page']) : 1);
547 $this->pager['itemspage'] = 50;
548 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
549 if($this->pager['start'] < 0)
550 $this->pager['start'] = 0;
551 $this->pager['total'] = 0;
554 * Detect mobile devices
557 $mobile_detect = new Mobile_Detect();
558 $this->is_mobile = $mobile_detect->isMobile();
559 $this->is_tablet = $mobile_detect->isTablet();
562 * register template engines
564 $dc = get_declared_classes();
565 foreach ($dc as $k) {
566 if (in_array("ITemplateEngine", class_implements($k))){
567 $this->register_template_engine($k);
573 function get_basepath() {
575 $basepath = get_config("system", "basepath");
578 $basepath = $_SERVER["DOCUMENT_ROOT"];
581 $basepath = $_SERVER["PWD"];
586 function get_baseurl($ssl = false) {
588 $scheme = $this->scheme;
590 if((x($this->config,'system')) && (x($this->config['system'],'ssl_policy'))) {
591 if(intval($this->config['system']['ssl_policy']) === intval(SSL_POLICY_FULL))
594 // Basically, we have $ssl = true on any links which can only be seen by a logged in user
595 // (and also the login link). Anything seen by an outsider will have it turned off.
597 if($this->config['system']['ssl_policy'] == SSL_POLICY_SELFSIGN) {
605 $this->baseurl = $scheme . "://" . $this->hostname . ((isset($this->path) && strlen($this->path)) ? '/' . $this->path : '' );
606 return $this->baseurl;
609 function set_baseurl($url) {
610 $parsed = @parse_url($url);
612 $this->baseurl = $url;
615 $this->scheme = $parsed['scheme'];
617 $this->hostname = $parsed['host'];
618 if(x($parsed,'port'))
619 $this->hostname .= ':' . $parsed['port'];
620 if(x($parsed,'path'))
621 $this->path = trim($parsed['path'],'\\/');
626 function get_hostname() {
627 return $this->hostname;
630 function set_hostname($h) {
631 $this->hostname = $h;
634 function set_path($p) {
635 $this->path = trim(trim($p),'/');
638 function get_path() {
642 function set_pager_total($n) {
643 $this->pager['total'] = intval($n);
646 function set_pager_itemspage($n) {
647 $this->pager['itemspage'] = ((intval($n) > 0) ? intval($n) : 0);
648 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
651 function set_pager_page($n) {
652 $this->pager['page'] = $n;
653 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
656 function init_pagehead() {
657 $interval = ((local_user()) ? get_pconfig(local_user(),'system','update_interval') : 40000);
658 if($interval < 10000)
661 $this->page['title'] = $this->config['sitename'];
663 /* put the head template at the beginning of page['htmlhead']
664 * since the code added by the modules frequently depends on it
667 if(!isset($this->page['htmlhead']))
668 $this->page['htmlhead'] = '';
670 // If we're using Smarty, then doing replace_macros() will replace
671 // any unrecognized variables with a blank string. Since we delay
672 // replacing $stylesheet until later, we need to replace it now
673 // with another variable name
674 if($this->theme['template_engine'] === 'smarty3')
675 $stylesheet = $this->get_template_ldelim('smarty3') . '$stylesheet' . $this->get_template_rdelim('smarty3');
677 $stylesheet = '$stylesheet';
679 $tpl = get_markup_template('head.tpl');
680 $this->page['htmlhead'] = replace_macros($tpl,array(
681 '$baseurl' => $this->get_baseurl(), // FIXME for z_path!!!!
682 '$local_user' => local_user(),
683 '$generator' => 'Friendica' . ' ' . FRIENDICA_VERSION,
684 '$delitem' => t('Delete this item?'),
685 '$comment' => t('Comment'),
686 '$showmore' => t('show more'),
687 '$showfewer' => t('show fewer'),
688 '$update_interval' => $interval,
689 '$stylesheet' => $stylesheet
690 )) . $this->page['htmlhead'];
693 function init_page_end() {
694 if(!isset($this->page['end']))
695 $this->page['end'] = '';
696 $tpl = get_markup_template('end.tpl');
697 $this->page['end'] = replace_macros($tpl,array(
698 '$baseurl' => $this->get_baseurl() // FIXME for z_path!!!!
699 )) . $this->page['end'];
702 function set_curl_code($code) {
703 $this->curl_code = $code;
706 function get_curl_code() {
707 return $this->curl_code;
710 function set_curl_content_type($content_type) {
711 $this->curl_content_type = $content_type;
714 function get_curl_content_type() {
715 return $this->curl_content_type;
718 function set_curl_headers($headers) {
719 $this->curl_headers = $headers;
722 function get_curl_headers() {
723 return $this->curl_headers;
726 function get_cached_avatar_image($avatar_image){
727 if($this->cached_profile_image[$avatar_image])
728 return $this->cached_profile_image[$avatar_image];
730 $path_parts = explode("/",$avatar_image);
731 $common_filename = $path_parts[count($path_parts)-1];
733 if($this->cached_profile_picdate[$common_filename]){
734 $this->cached_profile_image[$avatar_image] = $avatar_image . $this->cached_profile_picdate[$common_filename];
736 $r = q("SELECT `contact`.`avatar-date` AS picdate FROM `contact` WHERE `contact`.`thumb` like \"%%/%s\"",
739 $this->cached_profile_image[$avatar_image] = $avatar_image;
741 $this->cached_profile_picdate[$common_filename] = "?rev=" . urlencode($r[0]['picdate']);
742 $this->cached_profile_image[$avatar_image] = $avatar_image . $this->cached_profile_picdate[$common_filename];
745 return $this->cached_profile_image[$avatar_image];
750 * register template engine class
751 * if $name is "", is used class static property $class::$name
752 * @param string $class
753 * @param string $name
755 function register_template_engine($class, $name = '') {
757 $v = get_class_vars( $class );
758 if(x($v,"name")) $name = $v['name'];
761 echo "template engine <tt>$class</tt> cannot be registered without a name.\n";
764 $this->template_engines[$name] = $class;
768 * return template engine instance. If $name is not defined,
769 * return engine defined by theme, or default
771 * @param strin $name Template engine name
772 * @return object Template Engine instance
774 function template_engine($name = ''){
776 $template_engine = $name;
778 $template_engine = 'smarty3';
779 if (x($this->theme, 'template_engine')) {
780 $template_engine = $this->theme['template_engine'];
784 if (isset($this->template_engines[$template_engine])){
785 if(isset($this->template_engine_instance[$template_engine])){
786 return $this->template_engine_instance[$template_engine];
788 $class = $this->template_engines[$template_engine];
790 $this->template_engine_instance[$template_engine] = $obj;
795 echo "template engine <tt>$template_engine</tt> is not registered!\n"; killme();
798 function get_template_engine() {
799 return $this->theme['template_engine'];
802 function set_template_engine($engine = 'smarty3') {
803 $this->theme['template_engine'] = $engine;
805 $this->theme['template_engine'] = 'smarty3';
809 if(is_writable('view/smarty3/'))
810 $this->theme['template_engine'] = 'smarty3';
818 function get_template_ldelim($engine = 'smarty3') {
819 return $this->ldelim[$engine];
822 function get_template_rdelim($engine = 'smarty3') {
823 return $this->rdelim[$engine];
826 function save_timestamp($stamp, $value) {
827 $duration = (float)(microtime(true)-$stamp);
829 $this->performance[$value] += (float)$duration;
830 $this->performance["marktime"] += (float)$duration;
833 function mark_timestamp($mark) {
834 //$this->performance["markstart"] -= microtime(true) - $this->performance["marktime"];
835 $this->performance["markstart"] = microtime(true) - $this->performance["markstart"] - $this->performance["marktime"];
841 // retrieve the App structure
842 // useful in functions which require it but don't get it passed to them
844 if(! function_exists('get_app')) {
852 // Multi-purpose function to check variable state.
853 // Usage: x($var) or $x($array,'key')
854 // returns false if variable/key is not set
855 // if variable is set, returns 1 if has 'non-zero' value, otherwise returns 0.
856 // e.g. x('') or x(0) returns 0;
858 if(! function_exists('x')) {
859 function x($s,$k = NULL) {
861 if((is_array($s)) && (array_key_exists($k,$s))) {
880 // called from db initialisation if db is dead.
882 if(! function_exists('system_unavailable')) {
883 function system_unavailable() {
884 include('system_unavailable.php');
892 function clean_urls() {
894 // if($a->config['system']['clean_urls'])
901 $base = $a->get_baseurl();
909 return $a->get_baseurl();
912 function absurl($path) {
913 if(strpos($path,'/') === 0)
914 return z_path() . $path;
919 return (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');
922 function check_db() {
924 $build = get_config('system','build');
926 set_config('system','build',DB_UPDATE_VERSION);
927 $build = DB_UPDATE_VERSION;
929 if($build != DB_UPDATE_VERSION)
930 proc_run('php', 'include/dbupdate.php');
937 // Sets the base url for use in cmdline programs which don't have
938 // $_SERVER variables
940 if(! function_exists('check_url')) {
941 function check_url(&$a) {
943 $url = get_config('system','url');
945 // if the url isn't set or the stored url is radically different
946 // than the currently visited url, store the current value accordingly.
947 // "Radically different" ignores common variations such as http vs https
948 // and www.example.com vs example.com.
949 // We will only change the url to an ip address if there is no existing setting
952 $url = set_config('system','url',$a->get_baseurl());
953 if((! link_compare($url,$a->get_baseurl())) && (! preg_match("/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/",$a->get_hostname)))
954 $url = set_config('system','url',$a->get_baseurl());
961 // Automatic database updates
963 if(! function_exists('update_db')) {
964 function update_db(&$a) {
966 $build = get_config('system','build');
968 $build = set_config('system','build',DB_UPDATE_VERSION);
970 if($build != DB_UPDATE_VERSION) {
971 $stored = intval($build);
972 $current = intval(DB_UPDATE_VERSION);
973 if(($stored < $current) && file_exists('update.php')) {
975 load_config('database');
977 // We're reporting a different version than what is currently installed.
978 // Run any existing update scripts to bring the database up to current.
980 require_once('update.php');
982 // make sure that boot.php and update.php are the same release, we might be
983 // updating right this very second and the correct version of the update.php
984 // file may not be here yet. This can happen on a very busy site.
986 if(DB_UPDATE_VERSION == UPDATE_VERSION) {
988 for($x = $stored; $x < $current; $x ++) {
989 if(function_exists('update_' . $x)) {
991 // There could be a lot of processes running or about to run.
992 // We want exactly one process to run the update command.
993 // So store the fact that we're taking responsibility
994 // after first checking to see if somebody else already has.
996 // If the update fails or times-out completely you may need to
997 // delete the config entry to try again.
999 $t = get_config('database','update_' . $x);
1002 set_config('database','update_' . $x, time());
1004 // call the specific update
1006 $func = 'update_' . $x;
1009 //send the administrator an e-mail
1010 $email_tpl = get_intltext_template("update_fail_eml.tpl");
1011 $email_msg = replace_macros($email_tpl, array(
1012 '$sitename' => $a->config['sitename'],
1013 '$siteurl' => $a->get_baseurl(),
1015 '$error' => sprintf( t('Update %s failed. See error logs.'), $x)
1017 $subject=sprintf(t('Update Error at %s'), $a->get_baseurl());
1018 require_once('include/email.php');
1019 $subject = email_header_encode($subject,'UTF-8');
1020 mail($a->config['admin_email'], $subject, $email_msg,
1021 'From: ' . 'Administrator' . '@' . $_SERVER['SERVER_NAME'] . "\n"
1022 . 'Content-type: text/plain; charset=UTF-8' . "\n"
1023 . 'Content-transfer-encoding: 8bit' );
1025 logger('CRITICAL: Update Failed: '. $x);
1029 set_config('database','update_' . $x, 'success');
1030 set_config('system','build', $x + 1);
1043 if(! function_exists('check_plugins')) {
1044 function check_plugins(&$a) {
1048 * Synchronise plugins:
1050 * $a->config['system']['addon'] contains a comma-separated list of names
1051 * of plugins/addons which are used on this system.
1052 * Go through the database list of already installed addons, and if we have
1053 * an entry, but it isn't in the config list, call the uninstall procedure
1054 * and mark it uninstalled in the database (for now we'll remove it).
1055 * Then go through the config list and if we have a plugin that isn't installed,
1056 * call the install procedure and add it to the database.
1060 $r = q("SELECT * FROM `addon` WHERE `installed` = 1");
1064 $installed = array();
1066 $plugins = get_config('system','addon');
1067 $plugins_arr = array();
1070 $plugins_arr = explode(',',str_replace(' ', '',$plugins));
1072 $a->plugins = $plugins_arr;
1074 $installed_arr = array();
1076 if(count($installed)) {
1077 foreach($installed as $i) {
1078 if(! in_array($i['name'],$plugins_arr)) {
1079 uninstall_plugin($i['name']);
1082 $installed_arr[] = $i['name'];
1087 if(count($plugins_arr)) {
1088 foreach($plugins_arr as $p) {
1089 if(! in_array($p,$installed_arr)) {
1103 function get_guid($size=16) {
1104 $exists = true; // assume by default that we don't have a unique guid
1106 $s = random_string($size);
1107 $r = q("select id from guid where guid = '%s' limit 1", dbesc($s));
1111 q("insert into guid ( guid ) values ( '%s' ) ", dbesc($s));
1116 // wrapper for adding a login box. If $register == true provide a registration
1117 // link. This will most always depend on the value of $a->config['register_policy'].
1118 // returns the complete html for inserting into the page
1120 if(! function_exists('login')) {
1121 function login($register = false, $hiddens=false) {
1127 'title' => t('Create a New Account'),
1128 'desc' => t('Register')
1132 $noid = get_config('system','no_openid');
1134 $dest_url = $a->get_baseurl(true) . '/' . $a->query_string;
1137 $tpl = get_markup_template("logout.tpl");
1140 $a->page['htmlhead'] .= replace_macros(get_markup_template("login_head.tpl"),array(
1141 '$baseurl' => $a->get_baseurl(true)
1144 $tpl = get_markup_template("login.tpl");
1145 $_SESSION['return_url'] = $a->query_string;
1146 $a->module = 'login';
1149 $o .= replace_macros($tpl, array(
1151 '$dest_url' => $dest_url,
1152 '$logout' => t('Logout'),
1153 '$login' => t('Login'),
1155 '$lname' => array('username', t('Nickname or Email address: ') , '', ''),
1156 '$lpassword' => array('password', t('Password: '), '', ''),
1157 '$lremember' => array('remember', t('Remember me'), 0, ''),
1159 '$openid' => !$noid,
1160 '$lopenid' => array('openid_url', t('Or login using OpenID: '),'',''),
1162 '$hiddens' => $hiddens,
1164 '$register' => $reg,
1166 '$lostpass' => t('Forgot your password?'),
1167 '$lostlink' => t('Password Reset'),
1169 '$tostitle' => t('Website Terms of Service'),
1170 '$toslink' => t('terms of service'),
1172 '$privacytitle' => t('Website Privacy Policy'),
1173 '$privacylink' => t('privacy policy'),
1177 call_hooks('login_hook',$o);
1183 // Used to end the current process, after saving session state.
1185 if(! function_exists('killme')) {
1187 session_write_close();
1192 // redirect to another URL and terminate this process.
1194 if(! function_exists('goaway')) {
1195 function goaway($s) {
1196 header("Location: $s");
1202 // Returns the uid of locally logged in user or false.
1204 if(! function_exists('local_user')) {
1205 function local_user() {
1206 if((x($_SESSION,'authenticated')) && (x($_SESSION,'uid')))
1207 return intval($_SESSION['uid']);
1212 // Returns contact id of authenticated site visitor or false
1214 if(! function_exists('remote_user')) {
1215 function remote_user() {
1216 if((x($_SESSION,'authenticated')) && (x($_SESSION,'visitor_id')))
1217 return intval($_SESSION['visitor_id']);
1222 // contents of $s are displayed prominently on the page the next time
1223 // a page is loaded. Usually used for errors or alerts.
1225 if(! function_exists('notice')) {
1227 * Show an error message to user.
1229 * This function save text in session, to be shown to the user at next page load
1231 * @param string $s - Text of notice
1233 function notice($s) {
1235 if(! x($_SESSION,'sysmsg')) $_SESSION['sysmsg'] = array();
1237 $_SESSION['sysmsg'][] = $s;
1240 if(! function_exists('info')) {
1242 * Show an info message to user.
1244 * This function save text in session, to be shown to the user at next page load
1246 * @param string $s - Text of notice
1250 if(! x($_SESSION,'sysmsg_info')) $_SESSION['sysmsg_info'] = array();
1252 $_SESSION['sysmsg_info'][] = $s;
1257 // wrapper around config to limit the text length of an incoming message
1259 if(! function_exists('get_max_import_size')) {
1260 function get_max_import_size() {
1262 return ((x($a->config,'max_import_size')) ? $a->config['max_import_size'] : 0 );
1270 * Function : profile_load
1272 * @parameter string $nickname
1273 * @parameter int $profile
1275 * Summary: Loads a profile into the page sidebar.
1276 * The function requires a writeable copy of the main App structure, and the nickname
1277 * of a registered local account.
1279 * If the viewer is an authenticated remote viewer, the profile displayed is the
1280 * one that has been configured for his/her viewing in the Contact manager.
1281 * Passing a non-zero profile ID can also allow a preview of a selected profile
1284 * Profile information is placed in the App structure for later retrieval.
1285 * Honours the owner's chosen theme for display.
1287 * IMPORTANT: Should only be run in the _init() functions of a module. That ensures that
1288 * the theme is chosen before the _init() function of a theme is run, which will usually
1289 * load a lot of theme-specific content
1293 if(! function_exists('profile_load')) {
1294 function profile_load(&$a, $nickname, $profile = 0) {
1296 $user = q("select uid from user where nickname = '%s' limit 1",
1300 if(! ($user && count($user))) {
1301 logger('profile error: ' . $a->query_string, LOGGER_DEBUG);
1302 notice( t('Requested account is not available.') . EOL );
1307 if(remote_user() && count($_SESSION['remote'])) {
1308 foreach($_SESSION['remote'] as $visitor) {
1309 if($visitor['uid'] == $user[0]['uid']) {
1310 $r = q("SELECT `profile-id` FROM `contact` WHERE `id` = %d LIMIT 1",
1311 intval($visitor['cid'])
1314 $profile = $r[0]['profile-id'];
1323 $profile_int = intval($profile);
1324 $r = q("SELECT `profile`.`uid` AS `profile_uid`, `profile`.* , `contact`.`avatar-date` AS picdate, `user`.* FROM `profile`
1325 left join `contact` on `contact`.`uid` = `profile`.`uid` LEFT JOIN `user` ON `profile`.`uid` = `user`.`uid`
1326 WHERE `user`.`nickname` = '%s' AND `profile`.`id` = %d and `contact`.`self` = 1 LIMIT 1",
1328 intval($profile_int)
1331 if((! $r) && (! count($r))) {
1332 $r = q("SELECT `profile`.`uid` AS `profile_uid`, `profile`.* , `contact`.`avatar-date` AS picdate, `user`.* FROM `profile`
1333 left join `contact` on `contact`.`uid` = `profile`.`uid` LEFT JOIN `user` ON `profile`.`uid` = `user`.`uid`
1334 WHERE `user`.`nickname` = '%s' AND `profile`.`is-default` = 1 and `contact`.`self` = 1 LIMIT 1",
1339 if(($r === false) || (! count($r))) {
1340 logger('profile error: ' . $a->query_string, LOGGER_DEBUG);
1341 notice( t('Requested profile is not available.') . EOL );
1346 // fetch user tags if this isn't the default profile
1348 if(! $r[0]['is-default']) {
1349 $x = q("select `pub_keywords` from `profile` where uid = %d and `is-default` = 1 limit 1",
1350 intval($r[0]['profile_uid'])
1353 $r[0]['pub_keywords'] = $x[0]['pub_keywords'];
1356 $a->profile = $r[0];
1358 $a->profile['mobile-theme'] = get_pconfig($a->profile['profile_uid'], 'system', 'mobile_theme');
1361 $a->page['title'] = $a->profile['name'] . " @ " . $a->config['sitename'];
1362 $_SESSION['theme'] = $a->profile['theme'];
1363 $_SESSION['mobile-theme'] = $a->profile['mobile-theme'];
1366 * load/reload current theme info
1369 $a->set_template_engine(); // reset the template engine to the default in case the user's theme doesn't specify one
1371 $theme_info_file = "view/theme/".current_theme()."/theme.php";
1372 if (file_exists($theme_info_file)){
1373 require_once($theme_info_file);
1376 if(! (x($a->page,'aside')))
1377 $a->page['aside'] = '';
1379 if(local_user() && local_user() == $a->profile['uid']) {
1380 $a->page['aside'] .= replace_macros(get_markup_template('profile_edlink.tpl'),array(
1381 '$editprofile' => t('Edit profile'),
1382 '$profid' => $a->profile['id']
1386 $block = (((get_config('system','block_public')) && (! local_user()) && (! remote_user())) ? true : false);
1388 $a->page['aside'] .= profile_sidebar($a->profile, $block);
1391 $a->page['aside'] .= contact_block();*/
1400 * Function: profile_sidebar
1402 * Formats a profile for display in the sidebar.
1403 * It is very difficult to templatise the HTML completely
1404 * because of all the conditional logic.
1406 * @parameter: array $profile
1408 * Returns HTML string stuitable for sidebar inclusion
1409 * Exceptions: Returns empty string if passed $profile is wrong type or not populated
1414 if(! function_exists('profile_sidebar')) {
1415 function profile_sidebar($profile, $block = 0) {
1424 if((! is_array($profile)) && (! count($profile)))
1427 $profile['picdate'] = urlencode($profile['picdate']);
1429 call_hooks('profile_sidebar_enter', $profile);
1432 // don't show connect link to yourself
1433 $connect = (($profile['uid'] != local_user()) ? t('Connect') : False);
1435 // don't show connect link to authenticated visitors either
1437 if(remote_user() && count($_SESSION['remote'])) {
1438 foreach($_SESSION['remote'] as $visitor) {
1439 if($visitor['uid'] == $profile['uid']) {
1446 if( get_my_url() && $profile['unkmail'] && ($profile['uid'] != local_user()) )
1447 $wallmessage = t('Message');
1449 $wallmessage = false;
1453 // show edit profile to yourself
1454 if ($profile['uid'] == local_user() && feature_enabled(local_user(),'multi_profiles')) {
1455 $profile['edit'] = array($a->get_baseurl(). '/profiles', t('Profiles'),"", t('Manage/edit profiles'));
1457 $r = q("SELECT * FROM `profile` WHERE `uid` = %d",
1460 $profile['menu'] = array(
1461 'chg_photo' => t('Change profile photo'),
1462 'cr_new' => t('Create New Profile'),
1463 'entries' => array(),
1468 foreach($r as $rr) {
1469 $profile['menu']['entries'][] = array(
1470 'photo' => $rr['thumb'],
1472 'alt' => t('Profile Image'),
1473 'profile_name' => $rr['profile-name'],
1474 'isdefault' => $rr['is-default'],
1475 'visibile_to_everybody' => t('visible to everybody'),
1476 'edit_visibility' => t('Edit visibility'),
1484 if ($profile['uid'] == local_user() && !feature_enabled(local_user(),'multi_profiles')) {
1485 $profile['edit'] = array($a->get_baseurl(). '/profiles/'.$profile['id'], t('Edit profile'),"", t('Edit profile'));
1486 $profile['menu'] = array(
1487 'chg_photo' => t('Change profile photo'),
1489 'entries' => array(),
1496 if((x($profile,'address') == 1)
1497 || (x($profile,'locality') == 1)
1498 || (x($profile,'region') == 1)
1499 || (x($profile,'postal-code') == 1)
1500 || (x($profile,'country-name') == 1))
1501 $location = t('Location:');
1503 $gender = ((x($profile,'gender') == 1) ? t('Gender:') : False);
1506 $marital = ((x($profile,'marital') == 1) ? t('Status:') : False);
1508 $homepage = ((x($profile,'homepage') == 1) ? t('Homepage:') : False);
1510 if(($profile['hidewall'] || $block) && (! local_user()) && (! remote_user())) {
1511 $location = $pdesc = $gender = $marital = $homepage = False;
1514 $firstname = ((strpos($profile['name'],' '))
1515 ? trim(substr($profile['name'],0,strpos($profile['name'],' '))) : $profile['name']);
1516 $lastname = (($firstname === $profile['name']) ? '' : trim(substr($profile['name'],strlen($firstname))));
1519 'podloc' => $a->get_baseurl(),
1520 'searchable' => (($profile['publish'] && $profile['net-publish']) ? 'true' : 'false' ),
1521 'nickname' => $profile['nickname'],
1522 'fullname' => $profile['name'],
1523 'firstname' => $firstname,
1524 'lastname' => $lastname,
1525 'photo300' => $a->get_cached_avatar_image($a->get_baseurl() . '/photo/custom/300/' . $profile['uid'] . '.jpg'),
1526 'photo100' => $a->get_cached_avatar_image($a->get_baseurl() . '/photo/custom/100/' . $profile['uid'] . '.jpg'),
1527 'photo50' => $a->get_cached_avatar_image($a->get_baseurl() . '/photo/custom/50/' . $profile['uid'] . '.jpg'),
1531 $contact_block = contact_block();
1536 foreach($profile as $k => $v) {
1537 $k = str_replace('-','_',$k);
1541 if($a->theme['template_engine'] === 'internal')
1542 $location = template_escape($location);
1545 $tpl = get_markup_template('profile_vcard.tpl');
1546 $o .= replace_macros($tpl, array(
1548 '$connect' => $connect,
1549 '$wallmessage' => $wallmessage,
1550 '$location' => $location,
1551 '$gender' => $gender,
1553 '$marital' => $marital,
1554 '$homepage' => $homepage,
1555 '$diaspora' => $diaspora,
1556 '$contact_block' => $contact_block,
1560 $arr = array('profile' => &$profile, 'entry' => &$o);
1562 call_hooks('profile_sidebar', $arr);
1569 if(! function_exists('get_birthdays')) {
1570 function get_birthdays() {
1575 if(! local_user() || $a->is_mobile || $a->is_tablet)
1578 // $mobile_detect = new Mobile_Detect();
1579 // $is_mobile = $mobile_detect->isMobile() || $mobile_detect->isTablet();
1584 $bd_format = t('g A l F d') ; // 8 AM Friday January 18
1585 $bd_short = t('F d');
1587 $r = q("SELECT `event`.*, `event`.`id` AS `eid`, `contact`.* FROM `event`
1588 LEFT JOIN `contact` ON `contact`.`id` = `event`.`cid`
1589 WHERE `event`.`uid` = %d AND `type` = 'birthday' AND `start` < '%s' AND `finish` > '%s'
1590 ORDER BY `start` ASC ",
1591 intval(local_user()),
1592 dbesc(datetime_convert('UTC','UTC','now + 6 days')),
1593 dbesc(datetime_convert('UTC','UTC','now'))
1596 if($r && count($r)) {
1598 $now = strtotime('now');
1602 foreach($r as $rr) {
1603 if(strlen($rr['name']))
1605 if((strtotime($rr['start'] . ' +00:00') < $now) && (strtotime($rr['finish'] . ' +00:00') > $now))
1608 $classtoday = $istoday ? ' birthday-today ' : '';
1610 foreach($r as &$rr) {
1611 if(! strlen($rr['name']))
1616 if(in_array($rr['cid'],$cids))
1618 $cids[] = $rr['cid'];
1620 $today = (((strtotime($rr['start'] . ' +00:00') < $now) && (strtotime($rr['finish'] . ' +00:00') > $now)) ? true : false);
1623 if($rr['network'] === NETWORK_DFRN) {
1624 $sparkle = " sparkle";
1625 $url = $a->get_baseurl() . '/redir/' . $rr['cid'];
1629 $rr['title'] = $rr['name'];
1630 $rr['date'] = day_translate(datetime_convert('UTC', $a->timezone, $rr['start'], $rr['adjust'] ? $bd_format : $bd_short)) . (($today) ? ' ' . t('[today]') : '');
1631 $rr['startime'] = Null;
1632 $rr['today'] = $today;
1637 $tpl = get_markup_template("birthdays_reminder.tpl");
1638 return replace_macros($tpl, array(
1639 '$baseurl' => $a->get_baseurl(),
1640 '$classtoday' => $classtoday,
1642 '$event_reminders' => t('Birthday Reminders'),
1643 '$event_title' => t('Birthdays this week:'),
1645 '$lbr' => '{', // raw brackets mess up if/endif macro processing
1653 if(! function_exists('get_events')) {
1654 function get_events() {
1656 require_once('include/bbcode.php');
1660 if(! local_user() || $a->is_mobile || $a->is_tablet)
1664 // $mobile_detect = new Mobile_Detect();
1665 // $is_mobile = $mobile_detect->isMobile() || $mobile_detect->isTablet();
1670 $bd_format = t('g A l F d') ; // 8 AM Friday January 18
1671 $bd_short = t('F d');
1673 $r = q("SELECT `event`.* FROM `event`
1674 WHERE `event`.`uid` = %d AND `type` != 'birthday' AND `start` < '%s' AND `start` > '%s'
1675 ORDER BY `start` ASC ",
1676 intval(local_user()),
1677 dbesc(datetime_convert('UTC','UTC','now + 6 days')),
1678 dbesc(datetime_convert('UTC','UTC','now - 1 days'))
1681 if($r && count($r)) {
1682 $now = strtotime('now');
1684 foreach($r as $rr) {
1685 if(strlen($rr['name']))
1688 $strt = datetime_convert('UTC',$rr['convert'] ? $a->timezone : 'UTC',$rr['start'],'Y-m-d');
1689 if($strt === datetime_convert('UTC',$a->timezone,'now','Y-m-d'))
1692 $classtoday = (($istoday) ? 'event-today' : '');
1695 foreach($r as &$rr) {
1697 $md = datetime_convert('UTC',$a->timezone,$rr['start'],'Y/m');
1699 $md = datetime_convert('UTC','UTC',$rr['start'],'Y/m');
1700 $md .= "/#link-".$rr['id'];
1702 $title = substr(strip_tags(bbcode($rr['desc'])),0,32) . '... ';
1704 $title = t('[No description]');
1706 $strt = datetime_convert('UTC',$rr['convert'] ? $a->timezone : 'UTC',$rr['start']);
1707 $today = ((substr($strt,0,10) === datetime_convert('UTC',$a->timezone,'now','Y-m-d')) ? true : false);
1710 $rr['title'] = $title;
1711 $rr['date'] = day_translate(datetime_convert('UTC', $rr['adjust'] ? $a->timezone : 'UTC', $rr['start'], $bd_format)) . (($today) ? ' ' . t('[today]') : '');
1712 $rr['startime'] = $strt;
1713 $rr['today'] = $today;
1717 $tpl = get_markup_template("events_reminder.tpl");
1718 return replace_macros($tpl, array(
1719 '$baseurl' => $a->get_baseurl(),
1720 '$classtoday' => $classtoday,
1721 '$count' => count($r),
1722 '$event_reminders' => t('Event Reminders'),
1723 '$event_title' => t('Events this week:'),
1732 * Wrap calls to proc_close(proc_open()) and call hook
1733 * so plugins can take part in process :)
1736 * $cmd program to run
1737 * next args are passed as $cmd command line
1739 * e.g.: proc_run("ls","-la","/tmp");
1741 * $cmd and string args are surrounded with ""
1744 if(! function_exists('proc_run')) {
1745 function proc_run($cmd){
1749 $args = func_get_args();
1755 // expand any arrays
1757 foreach($args as $arg) {
1758 if(is_array($arg)) {
1759 foreach($arg as $n) {
1769 $arr = array('args' => $args, 'run_cmd' => true);
1771 call_hooks("proc_run", $arr);
1772 if(! $arr['run_cmd'])
1775 if(count($args) && $args[0] === 'php')
1776 $args[0] = ((x($a->config,'php_path')) && (strlen($a->config['php_path'])) ? $a->config['php_path'] : 'php');
1778 // add baseurl to args. cli scripts can't construct it
1779 $args[] = $a->get_baseurl();
1781 for($x = 0; $x < count($args); $x ++)
1782 $args[$x] = escapeshellarg($args[$x]);
1786 $cmdline = implode($args," ");
1787 if(get_config('system','proc_windows'))
1788 proc_close(proc_open('cmd /c start /b ' . $cmdline,array(),$foo,dirname(__FILE__)));
1790 proc_close(proc_open($cmdline." &",array(),$foo,dirname(__FILE__)));
1794 if(! function_exists('current_theme')) {
1795 function current_theme(){
1796 $app_base_themes = array('duepuntozero', 'dispy', 'quattro');
1800 // $mobile_detect = new Mobile_Detect();
1801 // $is_mobile = $mobile_detect->isMobile() || $mobile_detect->isTablet();
1802 $is_mobile = $a->is_mobile || $a->is_tablet;
1805 if(isset($_SESSION['show-mobile']) && !$_SESSION['show-mobile']) {
1810 $system_theme = ((isset($a->config['system']['mobile-theme'])) ? $a->config['system']['mobile-theme'] : '');
1811 $theme_name = ((isset($_SESSION) && x($_SESSION,'mobile-theme')) ? $_SESSION['mobile-theme'] : $system_theme);
1813 if($theme_name === '---') {
1814 // user has selected to have the mobile theme be the same as the normal one
1820 if(!$is_mobile || ($system_theme === '' && $theme_name === '')) {
1821 $system_theme = ((isset($a->config['system']['theme'])) ? $a->config['system']['theme'] : '');
1822 $theme_name = ((isset($_SESSION) && x($_SESSION,'theme')) ? $_SESSION['theme'] : $system_theme);
1826 (file_exists('view/theme/' . $theme_name . '/style.css') ||
1827 file_exists('view/theme/' . $theme_name . '/style.php')))
1828 return($theme_name);
1830 foreach($app_base_themes as $t) {
1831 if(file_exists('view/theme/' . $t . '/style.css')||
1832 file_exists('view/theme/' . $t . '/style.php'))
1836 $fallback = array_merge(glob('view/theme/*/style.css'),glob('view/theme/*/style.php'));
1837 if(count($fallback))
1838 return (str_replace('view/theme/','', substr($fallback[0],0,-10)));
1844 * Return full URL to theme which is currently in effect.
1845 * Provide a sane default if nothing is chosen or the specified theme does not exist.
1847 if(! function_exists('current_theme_url')) {
1848 function current_theme_url() {
1850 $t = current_theme();
1851 if (file_exists('view/theme/' . $t . '/style.php'))
1852 return($a->get_baseurl() . '/view/theme/' . $t . '/style.pcss');
1853 return($a->get_baseurl() . '/view/theme/' . $t . '/style.css');
1857 if(! function_exists('feed_birthday')) {
1858 function feed_birthday($uid,$tz) {
1862 * Determine the next birthday, but only if the birthday is published
1863 * in the default profile. We _could_ also look for a private profile that the
1864 * recipient can see, but somebody could get mad at us if they start getting
1865 * public birthday greetings when they haven't made this info public.
1867 * Assuming we are able to publish this info, we are then going to convert
1868 * the start time from the owner's timezone to UTC.
1870 * This will potentially solve the problem found with some social networks
1871 * where birthdays are converted to the viewer's timezone and salutations from
1872 * elsewhere in the world show up on the wrong day. We will convert it to the
1873 * viewer's timezone also, but first we are going to convert it from the birthday
1874 * person's timezone to GMT - so the viewer may find the birthday starting at
1875 * 6:00PM the day before, but that will correspond to midnight to the birthday person.
1885 $p = q("SELECT `dob` FROM `profile` WHERE `is-default` = 1 AND `uid` = %d LIMIT 1",
1889 if($p && count($p)) {
1890 $tmp_dob = substr($p[0]['dob'],5);
1891 if(intval($tmp_dob)) {
1892 $y = datetime_convert($tz,$tz,'now','Y');
1893 $bd = $y . '-' . $tmp_dob . ' 00:00';
1894 $t_dob = strtotime($bd);
1895 $now = strtotime(datetime_convert($tz,$tz,'now'));
1897 $bd = $y + 1 . '-' . $tmp_dob . ' 00:00';
1898 $birthday = datetime_convert($tz,'UTC',$bd,ATOM_TIME);
1906 if(! function_exists('is_site_admin')) {
1907 function is_site_admin() {
1910 $adminlist = explode(",", str_replace(" ", "", $a->config['admin_email']));
1912 //if(local_user() && x($a->user,'email') && x($a->config,'admin_email') && ($a->user['email'] === $a->config['admin_email']))
1913 if(local_user() && x($a->user,'email') && x($a->config,'admin_email') && in_array($a->user['email'], $adminlist))
1920 if(! function_exists('load_contact_links')) {
1921 function load_contact_links($uid) {
1927 if(! $uid || x($a->contacts,'empty'))
1930 $r = q("SELECT `id`,`network`,`url`,`thumb` FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 ",
1935 $url = normalise_link($rr['url']);
1940 $ret['empty'] = true;
1941 $a->contacts = $ret;
1946 if(! function_exists('profile_tabs')){
1947 function profile_tabs($a, $is_owner=False, $nickname=Null){
1948 //echo "<pre>"; var_dump($a->user); killme();
1950 if (is_null($nickname))
1951 $nickname = $a->user['nickname'];
1954 $tab = notags(trim($_GET['tab']));
1956 $url = $a->get_baseurl() . '/profile/' . $nickname;
1960 'label'=>t('Status'),
1962 'sel' => ((!isset($tab)&&$a->argv[0]=='profile')?'active':''),
1963 'title' => t('Status Messages and Posts'),
1964 'id' => 'status-tab',
1967 'label' => t('Profile'),
1968 'url' => $url.'/?tab=profile',
1969 'sel' => ((isset($tab) && $tab=='profile')?'active':''),
1970 'title' => t('Profile Details'),
1971 'id' => 'profile-tab',
1974 'label' => t('Photos'),
1975 'url' => $a->get_baseurl() . '/photos/' . $nickname,
1976 'sel' => ((!isset($tab)&&$a->argv[0]=='photos')?'active':''),
1977 'title' => t('Photo Albums'),
1978 'id' => 'photo-tab',
1981 'label' => t('Videos'),
1982 'url' => $a->get_baseurl() . '/videos/' . $nickname,
1983 'sel' => ((!isset($tab)&&$a->argv[0]=='videos')?'active':''),
1984 'title' => t('Videos'),
1985 'id' => 'video-tab',
1991 'label' => t('Events'),
1992 'url' => $a->get_baseurl() . '/events',
1993 'sel' =>((!isset($tab)&&$a->argv[0]=='events')?'active':''),
1994 'title' => t('Events and Calendar'),
1995 'id' => 'events-tab',
1998 'label' => t('Personal Notes'),
1999 'url' => $a->get_baseurl() . '/notes',
2000 'sel' =>((!isset($tab)&&$a->argv[0]=='notes')?'active':''),
2001 'title' => t('Only You Can See This'),
2002 'id' => 'notes-tab',
2007 $arr = array('is_owner' => $is_owner, 'nickname' => $nickname, 'tab' => (($tab) ? $tab : false), 'tabs' => $tabs);
2008 call_hooks('profile_tabs', $arr);
2010 $tpl = get_markup_template('common_tabs.tpl');
2012 return replace_macros($tpl,array('$tabs' => $arr['tabs']));
2016 function get_my_url() {
2017 if(x($_SESSION,'my_url'))
2018 return $_SESSION['my_url'];
2022 function zrl_init(&$a) {
2023 $tmp_str = get_my_url();
2024 if(validate_url($tmp_str)) {
2025 proc_run('php','include/gprobe.php',bin2hex($tmp_str));
2026 $arr = array('zrl' => $tmp_str, 'url' => $a->cmd);
2027 call_hooks('zrl_init',$arr);
2031 function zrl($s,$force = false) {
2034 if((! strpos($s,'/profile/')) && (! $force))
2036 if($force && substr($s,-1,1) !== '/')
2038 $achar = strpos($s,'?') ? '&' : '?';
2039 $mine = get_my_url();
2040 if($mine and ! link_compare($mine,$s))
2041 return $s . $achar . 'zrl=' . urlencode($mine);
2046 * returns querystring as string from a mapped array
2048 * @param params Array
2051 function build_querystring($params, $name=null) {
2053 foreach($params as $key=>$val) {
2054 if(is_array($val)) {
2056 $ret .= build_querystring($val, $key);
2058 $ret .= build_querystring($val, $name."[$key]");
2061 $val = urlencode($val);
2063 $ret.=$name."[$key]"."=$val&";
2065 $ret.= "$key=$val&";
2072 function explode_querystring($query) {
2073 $arg_st = strpos($query, '?');
2074 if($arg_st !== false) {
2075 $base = substr($query, 0, $arg_st);
2083 $args = explode('&', substr($query, $arg_st));
2084 foreach($args as $k=>$arg) {
2088 $args = array_values($args);
2093 $args = array_values($args);
2103 * Returns the complete URL of the current page, e.g.: http(s)://something.com/network
2105 * Taken from http://webcheatsheet.com/php/get_current_page_url.php
2107 function curPageURL() {
2109 if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
2111 if ($_SERVER["SERVER_PORT"] != "80" && $_SERVER["SERVER_PORT"] != "443") {
2112 $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
2114 $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
2119 function random_digits($digits) {
2121 for($i = 0; $i < $digits; $i++) {
2127 function get_cachefile($file, $writemode = true) {
2128 $cache = get_config("system","itemcache");
2130 if ((! $cache) || (! is_dir($cache)))
2133 $subfolder = $cache."/".substr($file, 0, 2);
2135 $cachepath = $subfolder."/".$file;
2138 if (!is_dir($subfolder)) {
2140 chmod($subfolder, 0777);
2147 function clear_cache($basepath = "", $path = "") {
2149 $basepath = get_config('system','itemcache');
2153 if (($path == "") OR (!is_dir($path)))
2156 if (substr(realpath($path), 0, strlen($basepath)) != $basepath)
2159 $cachetime = (int)get_config('system','itemcache_duration');
2160 if ($cachetime == 0)
2163 if (is_writable($path)){
2164 if ($dh = opendir($path)) {
2165 while (($file = readdir($dh)) !== false) {
2166 $fullpath = $path."/".$file;
2167 if ((filetype($fullpath) == "dir") and ($file != ".") and ($file != ".."))
2168 clear_cache($basepath, $fullpath);
2169 if ((filetype($fullpath) == "file") and (filectime($fullpath) < (time() - $cachetime)))
2177 function set_template_engine(&$a, $engine = 'internal') {
2178 // This function is no longer necessary, but keep it as a wrapper to the class method
2179 // to avoid breaking themes again unnecessarily
2181 $a->set_template_engine($engine);
2184 if(!function_exists('exif_imagetype')) {
2185 function exif_imagetype($file) {
2186 $size = getimagesize($file);