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.1753' );
16 define ( 'DFRN_PROTOCOL_VERSION', '2.23' );
17 define ( 'DB_UPDATE_VERSION', 1173 );
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
144 define ( 'NETWORK_DIASPORA2', 'dspc'); // Diaspora connector
145 define ( 'NETWORK_STATUSNET', 'stac'); // Statusnet connector
146 define ( 'NETWORK_APPNET', 'apdn'); // app.net
148 define ( 'NETWORK_PHANTOM', 'unkn'); // Place holder
151 * These numbers are used in stored permissions
152 * and existing allocations MUST NEVER BE CHANGED
153 * OR RE-ASSIGNED! You may only add to them.
156 $netgroup_ids = array(
157 NETWORK_DFRN => (-1),
159 NETWORK_OSTATUS => (-3),
160 NETWORK_FEED => (-4),
161 NETWORK_DIASPORA => (-5),
162 NETWORK_MAIL => (-6),
163 NETWORK_MAIL2 => (-7),
164 NETWORK_FACEBOOK => (-8),
165 NETWORK_LINKEDIN => (-9),
166 NETWORK_XMPP => (-10),
167 NETWORK_MYSPACE => (-11),
168 NETWORK_GPLUS => (-12),
169 NETWORK_PUMPIO => (-13),
170 NETWORK_TWITTER => (-14),
171 NETWORK_DIASPORA2 => (-15),
172 NETWORK_STATUSNET => (-16),
173 NETWORK_APPNET => (-17),
175 NETWORK_PHANTOM => (-127),
180 * Maximum number of "people who like (or don't like) this" that we will list by name
183 define ( 'MAX_LIKERS', 75);
186 * Communication timeout
189 define ( 'ZCURL_TIMEOUT' , (-1));
193 * email notification options
196 define ( 'NOTIFY_INTRO', 0x0001 );
197 define ( 'NOTIFY_CONFIRM', 0x0002 );
198 define ( 'NOTIFY_WALL', 0x0004 );
199 define ( 'NOTIFY_COMMENT', 0x0008 );
200 define ( 'NOTIFY_MAIL', 0x0010 );
201 define ( 'NOTIFY_SUGGEST', 0x0020 );
202 define ( 'NOTIFY_PROFILE', 0x0040 );
203 define ( 'NOTIFY_TAGSELF', 0x0080 );
204 define ( 'NOTIFY_TAGSHARE', 0x0100 );
205 define ( 'NOTIFY_POKE', 0x0200 );
206 define ( 'NOTIFY_SHARE', 0x0400 );
208 define ( 'NOTIFY_SYSTEM', 0x8000 );
215 define ( 'TERM_UNKNOWN', 0 );
216 define ( 'TERM_HASHTAG', 1 );
217 define ( 'TERM_MENTION', 2 );
218 define ( 'TERM_CATEGORY', 3 );
219 define ( 'TERM_PCATEGORY', 4 );
220 define ( 'TERM_FILE', 5 );
221 define ( 'TERM_SAVEDSEARCH', 6 );
222 define ( 'TERM_CONVERSATION', 7 );
224 define ( 'TERM_OBJ_POST', 1 );
225 define ( 'TERM_OBJ_PHOTO', 2 );
230 * various namespaces we may need to parse
233 define ( 'NAMESPACE_ZOT', 'http://purl.org/zot' );
234 define ( 'NAMESPACE_DFRN' , 'http://purl.org/macgirvin/dfrn/1.0' );
235 define ( 'NAMESPACE_THREAD' , 'http://purl.org/syndication/thread/1.0' );
236 define ( 'NAMESPACE_TOMB' , 'http://purl.org/atompub/tombstones/1.0' );
237 define ( 'NAMESPACE_ACTIVITY', 'http://activitystrea.ms/spec/1.0/' );
238 define ( 'NAMESPACE_ACTIVITY_SCHEMA', 'http://activitystrea.ms/schema/1.0/' );
239 define ( 'NAMESPACE_MEDIA', 'http://purl.org/syndication/atommedia' );
240 define ( 'NAMESPACE_SALMON_ME', 'http://salmon-protocol.org/ns/magic-env' );
241 define ( 'NAMESPACE_OSTATUSSUB', 'http://ostatus.org/schema/1.0/subscribe' );
242 define ( 'NAMESPACE_GEORSS', 'http://www.georss.org/georss' );
243 define ( 'NAMESPACE_POCO', 'http://portablecontacts.net/spec/1.0' );
244 define ( 'NAMESPACE_FEED', 'http://schemas.google.com/g/2010#updates-from' );
245 define ( 'NAMESPACE_OSTATUS', 'http://ostatus.org/schema/1.0' );
246 define ( 'NAMESPACE_STATUSNET', 'http://status.net/schema/api/1/' );
247 define ( 'NAMESPACE_ATOM1', 'http://www.w3.org/2005/Atom' );
249 * activity stream defines
252 define ( 'ACTIVITY_LIKE', NAMESPACE_ACTIVITY_SCHEMA . 'like' );
253 define ( 'ACTIVITY_DISLIKE', NAMESPACE_DFRN . '/dislike' );
254 define ( 'ACTIVITY_OBJ_HEART', NAMESPACE_DFRN . '/heart' );
256 define ( 'ACTIVITY_FRIEND', NAMESPACE_ACTIVITY_SCHEMA . 'make-friend' );
257 define ( 'ACTIVITY_REQ_FRIEND', NAMESPACE_ACTIVITY_SCHEMA . 'request-friend' );
258 define ( 'ACTIVITY_UNFRIEND', NAMESPACE_ACTIVITY_SCHEMA . 'remove-friend' );
259 define ( 'ACTIVITY_FOLLOW', NAMESPACE_ACTIVITY_SCHEMA . 'follow' );
260 define ( 'ACTIVITY_UNFOLLOW', NAMESPACE_ACTIVITY_SCHEMA . 'stop-following' );
261 define ( 'ACTIVITY_JOIN', NAMESPACE_ACTIVITY_SCHEMA . 'join' );
263 define ( 'ACTIVITY_POST', NAMESPACE_ACTIVITY_SCHEMA . 'post' );
264 define ( 'ACTIVITY_UPDATE', NAMESPACE_ACTIVITY_SCHEMA . 'update' );
265 define ( 'ACTIVITY_TAG', NAMESPACE_ACTIVITY_SCHEMA . 'tag' );
266 define ( 'ACTIVITY_FAVORITE', NAMESPACE_ACTIVITY_SCHEMA . 'favorite' );
268 define ( 'ACTIVITY_POKE', NAMESPACE_ZOT . '/activity/poke' );
269 define ( 'ACTIVITY_MOOD', NAMESPACE_ZOT . '/activity/mood' );
271 define ( 'ACTIVITY_OBJ_BOOKMARK', NAMESPACE_ACTIVITY_SCHEMA . 'bookmark' );
272 define ( 'ACTIVITY_OBJ_COMMENT', NAMESPACE_ACTIVITY_SCHEMA . 'comment' );
273 define ( 'ACTIVITY_OBJ_NOTE', NAMESPACE_ACTIVITY_SCHEMA . 'note' );
274 define ( 'ACTIVITY_OBJ_PERSON', NAMESPACE_ACTIVITY_SCHEMA . 'person' );
275 define ( 'ACTIVITY_OBJ_IMAGE', NAMESPACE_ACTIVITY_SCHEMA . 'image' );
276 define ( 'ACTIVITY_OBJ_PHOTO', NAMESPACE_ACTIVITY_SCHEMA . 'photo' );
277 define ( 'ACTIVITY_OBJ_VIDEO', NAMESPACE_ACTIVITY_SCHEMA . 'video' );
278 define ( 'ACTIVITY_OBJ_P_PHOTO', NAMESPACE_ACTIVITY_SCHEMA . 'profile-photo' );
279 define ( 'ACTIVITY_OBJ_ALBUM', NAMESPACE_ACTIVITY_SCHEMA . 'photo-album' );
280 define ( 'ACTIVITY_OBJ_EVENT', NAMESPACE_ACTIVITY_SCHEMA . 'event' );
281 define ( 'ACTIVITY_OBJ_GROUP', NAMESPACE_ACTIVITY_SCHEMA . 'group' );
282 define ( 'ACTIVITY_OBJ_TAGTERM', NAMESPACE_DFRN . '/tagterm' );
283 define ( 'ACTIVITY_OBJ_PROFILE', NAMESPACE_DFRN . '/profile' );
286 * item weight for query ordering
289 define ( 'GRAVITY_PARENT', 0);
290 define ( 'GRAVITY_LIKE', 3);
291 define ( 'GRAVITY_COMMENT', 6);
295 * Reverse the effect of magic_quotes_gpc if it is enabled.
296 * Please disable magic_quotes_gpc so we don't have to do this.
297 * See http://php.net/manual/en/security.magicquotes.disabling.php
303 error_reporting(E_ERROR | E_WARNING | E_PARSE);
307 // This has to be quite large to deal with embedded private photos
308 ini_set('pcre.backtrack_limit', 500000);
311 if (get_magic_quotes_gpc()) {
312 $process = array(&$_GET, &$_POST, &$_COOKIE, &$_REQUEST);
313 while (list($key, $val) = each($process)) {
314 foreach ($val as $k => $v) {
315 unset($process[$key][$k]);
317 $process[$key][stripslashes($k)] = $v;
318 $process[] = &$process[$key][stripslashes($k)];
320 $process[$key][stripslashes($k)] = stripslashes($v);
333 * Our main application structure for the life of this page
334 * Primarily deals with the URL that got us here
335 * and tries to make some sense of it, and
336 * stores our page contents and config storage
337 * and anything else that might need to be passed around
338 * before we spit the page out.
342 if(! class_exists('App')) {
345 public $module_loaded = false;
346 public $query_string;
354 public $page_contact;
356 public $data = array();
357 public $error = false;
367 public $interactive = true;
369 public $apps = array();
373 public $performance = array();
380 // Allow themes to control internal parameters
381 // by changing App values in theme.php
383 public $sourcename = '';
384 public $videowidth = 425;
385 public $videoheight = 350;
386 public $force_max_items = 0;
387 public $theme_thread_allow = true;
389 // An array for all theme-controllable parameters
390 // Mostly unimplemented yet. Only options 'stylesheet' and
393 public $theme = array(
396 'videoheight' => 350,
397 'force_max_items' => 0,
398 'thread_allow' => true,
400 'template_engine' => 'smarty3',
403 // array of registered template engines ('name'=>'class name')
404 public $template_engines = array();
405 // array of instanced template engines ('name'=>'instance')
406 public $template_engine_instance = array();
408 // Used for reducing load to the ostatus completion
409 public $last_ostatus_conversation_url;
411 private $ldelim = array(
415 private $rdelim = array(
426 private $curl_content_type;
427 private $curl_headers;
429 private $cached_profile_image;
430 private $cached_profile_picdate;
432 function __construct() {
434 global $default_timezone, $argv, $argc;
438 if (file_exists(".htpreconfig.php"))
439 @include(".htpreconfig.php");
441 $this->timezone = ((x($default_timezone)) ? $default_timezone : 'UTC');
443 date_default_timezone_set($this->timezone);
445 $this->performance["start"] = microtime(true);
446 $this->performance["database"] = 0;
447 $this->performance["network"] = 0;
448 $this->performance["file"] = 0;
449 $this->performance["rendering"] = 0;
450 $this->performance["parser"] = 0;
451 $this->performance["marktime"] = 0;
452 $this->performance["markstart"] = microtime(true);
454 $this->config = array();
455 $this->page = array();
456 $this->pager= array();
458 $this->query_string = '';
463 'include' . PATH_SEPARATOR
464 . 'library' . PATH_SEPARATOR
465 . 'library/phpsec' . PATH_SEPARATOR
466 . 'library/langdet' . PATH_SEPARATOR
470 $this->scheme = 'http';
471 if(x($_SERVER,'HTTPS') && $_SERVER['HTTPS'])
472 $this->scheme = 'https';
473 elseif(x($_SERVER,'SERVER_PORT') && (intval($_SERVER['SERVER_PORT']) == 443))
474 $this->scheme = 'https';
476 if(x($_SERVER,'SERVER_NAME')) {
477 $this->hostname = $_SERVER['SERVER_NAME'];
479 // See bug 437 - this didn't work so disabling it
480 //if(stristr($this->hostname,'xn--')) {
481 // PHP or webserver may have converted idn to punycode, so
482 // convert punycode back to utf-8
483 // require_once('library/simplepie/idn/idna_convert.class.php');
484 // $x = new idna_convert();
485 // $this->hostname = $x->decode($_SERVER['SERVER_NAME']);
488 if(x($_SERVER,'SERVER_PORT') && $_SERVER['SERVER_PORT'] != 80 && $_SERVER['SERVER_PORT'] != 443)
489 $this->hostname .= ':' . $_SERVER['SERVER_PORT'];
491 * Figure out if we are running at the top of a domain
492 * or in a sub-directory and adjust accordingly
495 $path = trim(dirname($_SERVER['SCRIPT_NAME']),'/\\');
496 if(isset($path) && strlen($path) && ($path != $this->path))
501 $this->hostname = $hostname;
503 if (is_array($argv) && $argc>1 && substr(end($argv), 0, 4)=="http" ) {
504 $this->set_baseurl(array_pop($argv) );
508 set_include_path("include/$this->hostname" . PATH_SEPARATOR . get_include_path());
510 if((x($_SERVER,'QUERY_STRING')) && substr($_SERVER['QUERY_STRING'],0,9) === "pagename=") {
511 $this->query_string = substr($_SERVER['QUERY_STRING'],9);
512 // removing trailing / - maybe a nginx problem
513 if (substr($this->query_string, 0, 1) == "/")
514 $this->query_string = substr($this->query_string, 1);
515 } elseif((x($_SERVER,'QUERY_STRING')) && substr($_SERVER['QUERY_STRING'],0,2) === "q=") {
516 $this->query_string = substr($_SERVER['QUERY_STRING'],2);
517 // removing trailing / - maybe a nginx problem
518 if (substr($this->query_string, 0, 1) == "/")
519 $this->query_string = substr($this->query_string, 1);
521 if (x($_GET,'pagename'))
522 $this->cmd = trim($_GET['pagename'],'/\\');
523 elseif (x($_GET,'q'))
524 $this->cmd = trim($_GET['q'],'/\\');
526 // unix style "homedir"
528 if(substr($this->cmd,0,1) === '~')
529 $this->cmd = 'profile/' . substr($this->cmd,1);
531 // Diaspora style profile url
533 if(substr($this->cmd,0,2) === 'u/')
534 $this->cmd = 'profile/' . substr($this->cmd,2);
538 * Break the URL path into C style argc/argv style arguments for our
539 * modules. Given "http://example.com/module/arg1/arg2", $this->argc
540 * will be 3 (integer) and $this->argv will contain:
546 * There will always be one argument. If provided a naked domain
547 * URL, $this->argv[0] is set to "home".
551 $this->argv = explode('/',$this->cmd);
552 $this->argc = count($this->argv);
553 if((array_key_exists('0',$this->argv)) && strlen($this->argv[0])) {
554 $this->module = str_replace(".", "_", $this->argv[0]);
555 $this->module = str_replace("-", "_", $this->module);
559 $this->argv = array('home');
560 $this->module = 'home';
564 * See if there is any page number information, and initialise
568 $this->pager['page'] = ((x($_GET,'page') && intval($_GET['page']) > 0) ? intval($_GET['page']) : 1);
569 $this->pager['itemspage'] = 50;
570 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
571 if($this->pager['start'] < 0)
572 $this->pager['start'] = 0;
573 $this->pager['total'] = 0;
576 * Detect mobile devices
579 $mobile_detect = new Mobile_Detect();
580 $this->is_mobile = $mobile_detect->isMobile();
581 $this->is_tablet = $mobile_detect->isTablet();
584 * register template engines
586 $dc = get_declared_classes();
587 foreach ($dc as $k) {
588 if (in_array("ITemplateEngine", class_implements($k))){
589 $this->register_template_engine($k);
595 function get_basepath() {
597 $basepath = get_config("system", "basepath");
600 $basepath = $_SERVER["DOCUMENT_ROOT"];
603 $basepath = $_SERVER["PWD"];
608 function get_baseurl($ssl = false) {
610 $scheme = $this->scheme;
612 if((x($this->config,'system')) && (x($this->config['system'],'ssl_policy'))) {
613 if(intval($this->config['system']['ssl_policy']) === intval(SSL_POLICY_FULL))
616 // Basically, we have $ssl = true on any links which can only be seen by a logged in user
617 // (and also the login link). Anything seen by an outsider will have it turned off.
619 if($this->config['system']['ssl_policy'] == SSL_POLICY_SELFSIGN) {
627 $this->baseurl = $scheme . "://" . $this->hostname . ((isset($this->path) && strlen($this->path)) ? '/' . $this->path : '' );
628 return $this->baseurl;
631 function set_baseurl($url) {
632 $parsed = @parse_url($url);
634 $this->baseurl = $url;
637 $this->scheme = $parsed['scheme'];
639 $hostname = $parsed['host'];
640 if(x($parsed,'port'))
641 $hostname .= ':' . $parsed['port'];
642 if(x($parsed,'path'))
643 $this->path = trim($parsed['path'],'\\/');
645 if (file_exists(".htpreconfig.php"))
646 @include(".htpreconfig.php");
648 $this->hostname = $hostname;
653 function get_hostname() {
654 return $this->hostname;
657 function set_hostname($h) {
658 $this->hostname = $h;
661 function set_path($p) {
662 $this->path = trim(trim($p),'/');
665 function get_path() {
669 function set_pager_total($n) {
670 $this->pager['total'] = intval($n);
673 function set_pager_itemspage($n) {
674 $this->pager['itemspage'] = ((intval($n) > 0) ? intval($n) : 0);
675 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
678 function set_pager_page($n) {
679 $this->pager['page'] = $n;
680 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
683 function init_pagehead() {
684 $interval = ((local_user()) ? get_pconfig(local_user(),'system','update_interval') : 40000);
685 if($interval < 10000)
688 $this->page['title'] = $this->config['sitename'];
690 /* put the head template at the beginning of page['htmlhead']
691 * since the code added by the modules frequently depends on it
694 if(!isset($this->page['htmlhead']))
695 $this->page['htmlhead'] = '';
697 // If we're using Smarty, then doing replace_macros() will replace
698 // any unrecognized variables with a blank string. Since we delay
699 // replacing $stylesheet until later, we need to replace it now
700 // with another variable name
701 if($this->theme['template_engine'] === 'smarty3')
702 $stylesheet = $this->get_template_ldelim('smarty3') . '$stylesheet' . $this->get_template_rdelim('smarty3');
704 $stylesheet = '$stylesheet';
706 $shortcut_icon = get_config("system", "shortcut_icon");
707 if ($shortcut_icon == "")
708 $shortcut_icon = $this->get_baseurl()."/images/friendica-32.png";
710 $touch_icon = get_config("system", "touch_icon");
711 if ($touch_icon == "")
712 $touch_icon = $this->get_baseurl()."/images/friendica-128.png";
714 $tpl = get_markup_template('head.tpl');
715 $this->page['htmlhead'] = replace_macros($tpl,array(
716 '$baseurl' => $this->get_baseurl(), // FIXME for z_path!!!!
717 '$local_user' => local_user(),
718 '$generator' => 'Friendica' . ' ' . FRIENDICA_VERSION,
719 '$delitem' => t('Delete this item?'),
720 '$comment' => t('Comment'),
721 '$showmore' => t('show more'),
722 '$showfewer' => t('show fewer'),
723 '$update_interval' => $interval,
724 '$shortcut_icon' => $shortcut_icon,
725 '$touch_icon' => $touch_icon,
726 '$stylesheet' => $stylesheet
727 )) . $this->page['htmlhead'];
730 function init_page_end() {
731 if(!isset($this->page['end']))
732 $this->page['end'] = '';
733 $tpl = get_markup_template('end.tpl');
734 $this->page['end'] = replace_macros($tpl,array(
735 '$baseurl' => $this->get_baseurl() // FIXME for z_path!!!!
736 )) . $this->page['end'];
739 function set_curl_code($code) {
740 $this->curl_code = $code;
743 function get_curl_code() {
744 return $this->curl_code;
747 function set_curl_content_type($content_type) {
748 $this->curl_content_type = $content_type;
751 function get_curl_content_type() {
752 return $this->curl_content_type;
755 function set_curl_headers($headers) {
756 $this->curl_headers = $headers;
759 function get_curl_headers() {
760 return $this->curl_headers;
763 function get_cached_avatar_image($avatar_image){
764 if($this->cached_profile_image[$avatar_image])
765 return $this->cached_profile_image[$avatar_image];
767 $path_parts = explode("/",$avatar_image);
768 $common_filename = $path_parts[count($path_parts)-1];
770 if($this->cached_profile_picdate[$common_filename]){
771 $this->cached_profile_image[$avatar_image] = $avatar_image . $this->cached_profile_picdate[$common_filename];
773 $r = q("SELECT `contact`.`avatar-date` AS picdate FROM `contact` WHERE `contact`.`thumb` like '%%/%s'",
776 $this->cached_profile_image[$avatar_image] = $avatar_image;
778 $this->cached_profile_picdate[$common_filename] = "?rev=".urlencode($r[0]['picdate']);
779 $this->cached_profile_image[$avatar_image] = $avatar_image.$this->cached_profile_picdate[$common_filename];
782 return $this->cached_profile_image[$avatar_image];
787 * register template engine class
788 * if $name is "", is used class static property $class::$name
789 * @param string $class
790 * @param string $name
792 function register_template_engine($class, $name = '') {
794 $v = get_class_vars( $class );
795 if(x($v,"name")) $name = $v['name'];
798 echo "template engine <tt>$class</tt> cannot be registered without a name.\n";
801 $this->template_engines[$name] = $class;
805 * return template engine instance. If $name is not defined,
806 * return engine defined by theme, or default
808 * @param strin $name Template engine name
809 * @return object Template Engine instance
811 function template_engine($name = ''){
813 $template_engine = $name;
815 $template_engine = 'smarty3';
816 if (x($this->theme, 'template_engine')) {
817 $template_engine = $this->theme['template_engine'];
821 if (isset($this->template_engines[$template_engine])){
822 if(isset($this->template_engine_instance[$template_engine])){
823 return $this->template_engine_instance[$template_engine];
825 $class = $this->template_engines[$template_engine];
827 $this->template_engine_instance[$template_engine] = $obj;
832 echo "template engine <tt>$template_engine</tt> is not registered!\n"; killme();
835 function get_template_engine() {
836 return $this->theme['template_engine'];
839 function set_template_engine($engine = 'smarty3') {
840 $this->theme['template_engine'] = $engine;
842 $this->theme['template_engine'] = 'smarty3';
846 if(is_writable('view/smarty3/'))
847 $this->theme['template_engine'] = 'smarty3';
855 function get_template_ldelim($engine = 'smarty3') {
856 return $this->ldelim[$engine];
859 function get_template_rdelim($engine = 'smarty3') {
860 return $this->rdelim[$engine];
863 function save_timestamp($stamp, $value) {
864 $duration = (float)(microtime(true)-$stamp);
866 $this->performance[$value] += (float)$duration;
867 $this->performance["marktime"] += (float)$duration;
870 function mark_timestamp($mark) {
871 //$this->performance["markstart"] -= microtime(true) - $this->performance["marktime"];
872 $this->performance["markstart"] = microtime(true) - $this->performance["markstart"] - $this->performance["marktime"];
878 // retrieve the App structure
879 // useful in functions which require it but don't get it passed to them
881 if(! function_exists('get_app')) {
889 // Multi-purpose function to check variable state.
890 // Usage: x($var) or $x($array,'key')
891 // returns false if variable/key is not set
892 // if variable is set, returns 1 if has 'non-zero' value, otherwise returns 0.
893 // e.g. x('') or x(0) returns 0;
895 if(! function_exists('x')) {
896 function x($s,$k = NULL) {
898 if((is_array($s)) && (array_key_exists($k,$s))) {
917 // called from db initialisation if db is dead.
919 if(! function_exists('system_unavailable')) {
920 function system_unavailable() {
921 include('system_unavailable.php');
929 function clean_urls() {
931 // if($a->config['system']['clean_urls'])
938 $base = $a->get_baseurl();
946 return $a->get_baseurl();
949 function absurl($path) {
950 if(strpos($path,'/') === 0)
951 return z_path() . $path;
956 return (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');
959 function check_db() {
961 $build = get_config('system','build');
963 set_config('system','build',DB_UPDATE_VERSION);
964 $build = DB_UPDATE_VERSION;
966 if($build != DB_UPDATE_VERSION)
967 proc_run('php', 'include/dbupdate.php');
974 // Sets the base url for use in cmdline programs which don't have
975 // $_SERVER variables
977 if(! function_exists('check_url')) {
978 function check_url(&$a) {
980 $url = get_config('system','url');
982 // if the url isn't set or the stored url is radically different
983 // than the currently visited url, store the current value accordingly.
984 // "Radically different" ignores common variations such as http vs https
985 // and www.example.com vs example.com.
986 // We will only change the url to an ip address if there is no existing setting
989 $url = set_config('system','url',$a->get_baseurl());
990 if((! link_compare($url,$a->get_baseurl())) && (! preg_match("/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/",$a->get_hostname)))
991 $url = set_config('system','url',$a->get_baseurl());
998 // Automatic database updates
1000 if(! function_exists('update_db')) {
1001 function update_db(&$a) {
1003 $build = get_config('system','build');
1005 $build = set_config('system','build',DB_UPDATE_VERSION);
1007 if($build != DB_UPDATE_VERSION) {
1008 $stored = intval($build);
1009 $current = intval(DB_UPDATE_VERSION);
1010 if(($stored < $current) && file_exists('update.php')) {
1012 load_config('database');
1014 // We're reporting a different version than what is currently installed.
1015 // Run any existing update scripts to bring the database up to current.
1017 require_once('update.php');
1019 // make sure that boot.php and update.php are the same release, we might be
1020 // updating right this very second and the correct version of the update.php
1021 // file may not be here yet. This can happen on a very busy site.
1023 if(DB_UPDATE_VERSION == UPDATE_VERSION) {
1025 // Compare the current structure with the defined structure
1027 $t = get_config('database','dbupdate_'.DB_UPDATE_VERSION);
1031 set_config('database','dbupdate_'.DB_UPDATE_VERSION, time());
1033 require_once("include/dbstructure.php");
1034 $retval = update_structure(false, true);
1036 //send the administrator an e-mail
1037 $email_tpl = get_intltext_template("update_fail_eml.tpl");
1038 $email_msg = replace_macros($email_tpl, array(
1039 '$sitename' => $a->config['sitename'],
1040 '$siteurl' => $a->get_baseurl(),
1041 '$update' => DB_UPDATE_VERSION,
1042 '$error' => sprintf(t('Update %s failed. See error logs.'), DB_UPDATE_VERSION)
1044 $subject=sprintf(t('Update Error at %s'), $a->get_baseurl());
1045 require_once('include/email.php');
1046 $subject = email_header_encode($subject,'UTF-8');
1047 mail($a->config['admin_email'], $subject, $email_msg,
1048 'From: ' . 'Administrator' . '@' . $_SERVER['SERVER_NAME']."\n"
1049 .'Content-type: text/plain; charset=UTF-8'."\n"
1050 .'Content-transfer-encoding: 8bit');
1052 logger("CRITICAL: Database structure update failed: ".$retval);
1055 set_config('database','dbupdate_'.DB_UPDATE_VERSION, 'success');
1057 for($x = $stored; $x < $current; $x ++) {
1058 if(function_exists('update_' . $x)) {
1060 // There could be a lot of processes running or about to run.
1061 // We want exactly one process to run the update command.
1062 // So store the fact that we're taking responsibility
1063 // after first checking to see if somebody else already has.
1065 // If the update fails or times-out completely you may need to
1066 // delete the config entry to try again.
1068 $t = get_config('database','update_' . $x);
1071 set_config('database','update_' . $x, time());
1073 // call the specific update
1075 $func = 'update_' . $x;
1078 //send the administrator an e-mail
1079 $email_tpl = get_intltext_template("update_fail_eml.tpl");
1080 $email_msg = replace_macros($email_tpl, array(
1081 '$sitename' => $a->config['sitename'],
1082 '$siteurl' => $a->get_baseurl(),
1084 '$error' => sprintf( t('Update %s failed. See error logs.'), $x)
1086 $subject=sprintf(t('Update Error at %s'), $a->get_baseurl());
1087 require_once('include/email.php');
1088 $subject = email_header_encode($subject,'UTF-8');
1089 mail($a->config['admin_email'], $subject, $email_msg,
1090 'From: ' . 'Administrator' . '@' . $_SERVER['SERVER_NAME'] . "\n"
1091 . 'Content-type: text/plain; charset=UTF-8' . "\n"
1092 . 'Content-transfer-encoding: 8bit' );
1094 logger('CRITICAL: Update Failed: '. $x);
1097 set_config('database','update_' . $x, 'success');
1098 set_config('system','build', $x + 1);
1101 set_config('database','update_' . $x, 'success');
1102 set_config('system','build', $x + 1);
1114 if(! function_exists('check_plugins')) {
1115 function check_plugins(&$a) {
1119 * Synchronise plugins:
1121 * $a->config['system']['addon'] contains a comma-separated list of names
1122 * of plugins/addons which are used on this system.
1123 * Go through the database list of already installed addons, and if we have
1124 * an entry, but it isn't in the config list, call the uninstall procedure
1125 * and mark it uninstalled in the database (for now we'll remove it).
1126 * Then go through the config list and if we have a plugin that isn't installed,
1127 * call the install procedure and add it to the database.
1131 $r = q("SELECT * FROM `addon` WHERE `installed` = 1");
1135 $installed = array();
1137 $plugins = get_config('system','addon');
1138 $plugins_arr = array();
1141 $plugins_arr = explode(',',str_replace(' ', '',$plugins));
1143 $a->plugins = $plugins_arr;
1145 $installed_arr = array();
1147 if(count($installed)) {
1148 foreach($installed as $i) {
1149 if(! in_array($i['name'],$plugins_arr)) {
1150 uninstall_plugin($i['name']);
1153 $installed_arr[] = $i['name'];
1158 if(count($plugins_arr)) {
1159 foreach($plugins_arr as $p) {
1160 if(! in_array($p,$installed_arr)) {
1173 function get_guid($size=16) {
1174 $exists = true; // assume by default that we don't have a unique guid
1177 while (strlen($prefix) < ($size - 13))
1178 $prefix .= mt_rand();
1180 $s = substr(uniqid($prefix), -$size);
1182 $r = q("select id from guid where guid = '%s' limit 1", dbesc($s));
1186 q("insert into guid (guid) values ('%s') ", dbesc($s));
1190 /*function get_guid($size=16) {
1191 $exists = true; // assume by default that we don't have a unique guid
1193 $s = random_string($size);
1194 $r = q("select id from guid where guid = '%s' limit 1", dbesc($s));
1198 q("insert into guid ( guid ) values ( '%s' ) ", dbesc($s));
1203 // wrapper for adding a login box. If $register == true provide a registration
1204 // link. This will most always depend on the value of $a->config['register_policy'].
1205 // returns the complete html for inserting into the page
1207 if(! function_exists('login')) {
1208 function login($register = false, $hiddens=false) {
1214 'title' => t('Create a New Account'),
1215 'desc' => t('Register')
1219 $noid = get_config('system','no_openid');
1221 $dest_url = $a->get_baseurl(true) . '/' . $a->query_string;
1224 $tpl = get_markup_template("logout.tpl");
1227 $a->page['htmlhead'] .= replace_macros(get_markup_template("login_head.tpl"),array(
1228 '$baseurl' => $a->get_baseurl(true)
1231 $tpl = get_markup_template("login.tpl");
1232 $_SESSION['return_url'] = $a->query_string;
1233 $a->module = 'login';
1236 $o .= replace_macros($tpl, array(
1238 '$dest_url' => $dest_url,
1239 '$logout' => t('Logout'),
1240 '$login' => t('Login'),
1242 '$lname' => array('username', t('Nickname or Email address: ') , '', ''),
1243 '$lpassword' => array('password', t('Password: '), '', ''),
1244 '$lremember' => array('remember', t('Remember me'), 0, ''),
1246 '$openid' => !$noid,
1247 '$lopenid' => array('openid_url', t('Or login using OpenID: '),'',''),
1249 '$hiddens' => $hiddens,
1251 '$register' => $reg,
1253 '$lostpass' => t('Forgot your password?'),
1254 '$lostlink' => t('Password Reset'),
1256 '$tostitle' => t('Website Terms of Service'),
1257 '$toslink' => t('terms of service'),
1259 '$privacytitle' => t('Website Privacy Policy'),
1260 '$privacylink' => t('privacy policy'),
1264 call_hooks('login_hook',$o);
1270 // Used to end the current process, after saving session state.
1272 if(! function_exists('killme')) {
1274 session_write_close();
1279 // redirect to another URL and terminate this process.
1281 if(! function_exists('goaway')) {
1282 function goaway($s) {
1283 header("Location: $s");
1289 // Returns the uid of locally logged in user or false.
1291 if(! function_exists('local_user')) {
1292 function local_user() {
1293 if((x($_SESSION,'authenticated')) && (x($_SESSION,'uid')))
1294 return intval($_SESSION['uid']);
1299 // Returns contact id of authenticated site visitor or false
1301 if(! function_exists('remote_user')) {
1302 function remote_user() {
1303 if((x($_SESSION,'authenticated')) && (x($_SESSION,'visitor_id')))
1304 return intval($_SESSION['visitor_id']);
1309 // contents of $s are displayed prominently on the page the next time
1310 // a page is loaded. Usually used for errors or alerts.
1312 if(! function_exists('notice')) {
1314 * Show an error message to user.
1316 * This function save text in session, to be shown to the user at next page load
1318 * @param string $s - Text of notice
1320 function notice($s) {
1322 if(! x($_SESSION,'sysmsg')) $_SESSION['sysmsg'] = array();
1324 $_SESSION['sysmsg'][] = $s;
1327 if(! function_exists('info')) {
1329 * Show an info message to user.
1331 * This function save text in session, to be shown to the user at next page load
1333 * @param string $s - Text of notice
1338 if (local_user() AND get_pconfig(local_user(),'system','ignore_info'))
1341 if(! x($_SESSION,'sysmsg_info')) $_SESSION['sysmsg_info'] = array();
1343 $_SESSION['sysmsg_info'][] = $s;
1348 // wrapper around config to limit the text length of an incoming message
1350 if(! function_exists('get_max_import_size')) {
1351 function get_max_import_size() {
1353 return ((x($a->config,'max_import_size')) ? $a->config['max_import_size'] : 0 );
1361 * Function : profile_load
1363 * @parameter string $nickname
1364 * @parameter int $profile
1366 * Summary: Loads a profile into the page sidebar.
1367 * The function requires a writeable copy of the main App structure, and the nickname
1368 * of a registered local account.
1370 * If the viewer is an authenticated remote viewer, the profile displayed is the
1371 * one that has been configured for his/her viewing in the Contact manager.
1372 * Passing a non-zero profile ID can also allow a preview of a selected profile
1375 * Profile information is placed in the App structure for later retrieval.
1376 * Honours the owner's chosen theme for display.
1378 * IMPORTANT: Should only be run in the _init() functions of a module. That ensures that
1379 * the theme is chosen before the _init() function of a theme is run, which will usually
1380 * load a lot of theme-specific content
1384 if(! function_exists('profile_load')) {
1385 function profile_load(&$a, $nickname, $profile = 0, $profiledata = array()) {
1387 $user = q("select uid from user where nickname = '%s' limit 1",
1391 if(! ($user && count($user))) {
1392 logger('profile error: ' . $a->query_string, LOGGER_DEBUG);
1393 notice( t('Requested account is not available.') . EOL );
1398 if(remote_user() && count($_SESSION['remote'])) {
1399 foreach($_SESSION['remote'] as $visitor) {
1400 if($visitor['uid'] == $user[0]['uid']) {
1401 $r = q("SELECT `profile-id` FROM `contact` WHERE `id` = %d LIMIT 1",
1402 intval($visitor['cid'])
1405 $profile = $r[0]['profile-id'];
1414 $profile_int = intval($profile);
1415 $r = q("SELECT `profile`.`uid` AS `profile_uid`, `profile`.* , `contact`.`avatar-date` AS picdate, `user`.* FROM `profile`
1416 INNER JOIN `contact` on `contact`.`uid` = `profile`.`uid` INNER JOIN `user` ON `profile`.`uid` = `user`.`uid`
1417 WHERE `user`.`nickname` = '%s' AND `profile`.`id` = %d and `contact`.`self` = 1 LIMIT 1",
1419 intval($profile_int)
1422 if((! $r) && (! count($r))) {
1423 $r = q("SELECT `profile`.`uid` AS `profile_uid`, `profile`.* , `contact`.`avatar-date` AS picdate, `user`.* FROM `profile`
1424 INNER JOIN `contact` on `contact`.`uid` = `profile`.`uid` INNER JOIN `user` ON `profile`.`uid` = `user`.`uid`
1425 WHERE `user`.`nickname` = '%s' AND `profile`.`is-default` = 1 and `contact`.`self` = 1 LIMIT 1",
1430 if(($r === false) || (! count($r))) {
1431 logger('profile error: ' . $a->query_string, LOGGER_DEBUG);
1432 notice( t('Requested profile is not available.') . EOL );
1437 // fetch user tags if this isn't the default profile
1439 if(! $r[0]['is-default']) {
1440 $x = q("select `pub_keywords` from `profile` where uid = %d and `is-default` = 1 limit 1",
1441 intval($r[0]['profile_uid'])
1444 $r[0]['pub_keywords'] = $x[0]['pub_keywords'];
1447 $a->profile = $r[0];
1449 $a->profile['mobile-theme'] = get_pconfig($a->profile['profile_uid'], 'system', 'mobile_theme');
1450 $a->profile['network'] = NETWORK_DFRN;
1452 $a->page['title'] = $a->profile['name'] . " @ " . $a->config['sitename'];
1455 $_SESSION['theme'] = $a->profile['theme'];
1457 $_SESSION['mobile-theme'] = $a->profile['mobile-theme'];
1460 * load/reload current theme info
1463 $a->set_template_engine(); // reset the template engine to the default in case the user's theme doesn't specify one
1465 $theme_info_file = "view/theme/".current_theme()."/theme.php";
1466 if (file_exists($theme_info_file)){
1467 require_once($theme_info_file);
1470 if(! (x($a->page,'aside')))
1471 $a->page['aside'] = '';
1473 if(local_user() && local_user() == $a->profile['uid'] && $profiledata) {
1474 $a->page['aside'] .= replace_macros(get_markup_template('profile_edlink.tpl'),array(
1475 '$editprofile' => t('Edit profile'),
1476 '$profid' => $a->profile['id']
1480 $block = (((get_config('system','block_public')) && (! local_user()) && (! remote_user())) ? true : false);
1483 // By now, the contact block isn't shown, when a different profile is given
1484 // But: When this profile was on the same server, then we could display the contacts
1486 $a->page['aside'] .= profile_sidebar($profiledata, true);
1488 $a->page['aside'] .= profile_sidebar($a->profile, $block);
1492 $a->page['aside'] .= contact_block();*/
1501 * Function: profile_sidebar
1503 * Formats a profile for display in the sidebar.
1504 * It is very difficult to templatise the HTML completely
1505 * because of all the conditional logic.
1507 * @parameter: array $profile
1509 * Returns HTML string stuitable for sidebar inclusion
1510 * Exceptions: Returns empty string if passed $profile is wrong type or not populated
1515 if(! function_exists('profile_sidebar')) {
1516 function profile_sidebar($profile, $block = 0) {
1524 if((! is_array($profile)) && (! count($profile)))
1527 $profile['picdate'] = urlencode($profile['picdate']);
1529 if (($profile['network'] != "") AND ($profile['network'] != NETWORK_DFRN)) {
1530 require_once('include/contact_selectors.php');
1531 if ($profile['url'] != "")
1532 $profile['network_name'] = '<a href="'.$profile['url'].'">'.network_to_name($profile['network'])."</a>";
1534 $profile['network_name'] = network_to_name($profile['network']);
1536 $profile['network_name'] = "";
1538 call_hooks('profile_sidebar_enter', $profile);
1541 // don't show connect link to yourself
1542 $connect = (($profile['uid'] != local_user()) ? t('Connect') : False);
1544 // don't show connect link to authenticated visitors either
1545 if(remote_user() && count($_SESSION['remote'])) {
1546 foreach($_SESSION['remote'] as $visitor) {
1547 if($visitor['uid'] == $profile['uid']) {
1554 // Is the local user already connected to that user?
1555 if ($connect AND local_user()) {
1556 if (isset($profile["url"]))
1557 $profile_url = normalise_link($profile["url"]);
1559 $profile_url = normalise_link($a->get_baseurl()."/profile/".$profile["nickname"]);
1561 $r = q("SELECT * FROM `contact` WHERE NOT `pending` AND `uid` = %d AND `nurl` = '%s'",
1562 local_user(), $profile_url);
1567 if ($connect AND ($profile['network'] != NETWORK_DFRN) AND !isset($profile['remoteconnect']))
1570 if (isset($profile['remoteconnect']))
1571 $remoteconnect = $profile['remoteconnect'];
1573 if( get_my_url() && $profile['unkmail'] && ($profile['uid'] != local_user()) )
1574 $wallmessage = t('Message');
1576 $wallmessage = false;
1578 // show edit profile to yourself
1579 if ($profile['uid'] == local_user() && feature_enabled(local_user(),'multi_profiles')) {
1580 $profile['edit'] = array($a->get_baseurl(). '/profiles', t('Profiles'),"", t('Manage/edit profiles'));
1581 $r = q("SELECT * FROM `profile` WHERE `uid` = %d",
1584 $profile['menu'] = array(
1585 'chg_photo' => t('Change profile photo'),
1586 'cr_new' => t('Create New Profile'),
1587 'entries' => array(),
1592 foreach($r as $rr) {
1593 $profile['menu']['entries'][] = array(
1594 'photo' => $rr['thumb'],
1596 'alt' => t('Profile Image'),
1597 'profile_name' => $rr['profile-name'],
1598 'isdefault' => $rr['is-default'],
1599 'visibile_to_everybody' => t('visible to everybody'),
1600 'edit_visibility' => t('Edit visibility'),
1608 if ($profile['uid'] == local_user() && !feature_enabled(local_user(),'multi_profiles')) {
1609 $profile['edit'] = array($a->get_baseurl(). '/profiles/'.$profile['id'], t('Edit profile'),"", t('Edit profile'));
1610 $profile['menu'] = array(
1611 'chg_photo' => t('Change profile photo'),
1613 'entries' => array(),
1617 if((x($profile,'address') == 1)
1618 || (x($profile,'locality') == 1)
1619 || (x($profile,'region') == 1)
1620 || (x($profile,'postal-code') == 1)
1621 || (x($profile,'country-name') == 1))
1622 $location = t('Location:');
1624 $gender = ((x($profile,'gender') == 1) ? t('Gender:') : False);
1627 $marital = ((x($profile,'marital') == 1) ? t('Status:') : False);
1629 $homepage = ((x($profile,'homepage') == 1) ? t('Homepage:') : False);
1631 if(($profile['hidewall'] || $block) && (! local_user()) && (! remote_user())) {
1632 $location = $pdesc = $gender = $marital = $homepage = False;
1635 $firstname = ((strpos($profile['name'],' '))
1636 ? trim(substr($profile['name'],0,strpos($profile['name'],' '))) : $profile['name']);
1637 $lastname = (($firstname === $profile['name']) ? '' : trim(substr($profile['name'],strlen($firstname))));
1640 'podloc' => $a->get_baseurl(),
1641 'searchable' => (($profile['publish'] && $profile['net-publish']) ? 'true' : 'false' ),
1642 'nickname' => $profile['nickname'],
1643 'fullname' => $profile['name'],
1644 'firstname' => $firstname,
1645 'lastname' => $lastname,
1646 'photo300' => $a->get_cached_avatar_image($a->get_baseurl() . '/photo/custom/300/' . $profile['uid'] . '.jpg'),
1647 'photo100' => $a->get_cached_avatar_image($a->get_baseurl() . '/photo/custom/100/' . $profile['uid'] . '.jpg'),
1648 'photo50' => $a->get_cached_avatar_image($a->get_baseurl() . '/photo/custom/50/' . $profile['uid'] . '.jpg'),
1652 $contact_block = contact_block();
1657 foreach($profile as $k => $v) {
1658 $k = str_replace('-','_',$k);
1662 if($a->theme['template_engine'] === 'internal')
1663 $location = template_escape($location);
1666 $tpl = get_markup_template('profile_vcard.tpl');
1667 $o .= replace_macros($tpl, array(
1669 '$connect' => $connect,
1670 '$remoteconnect' => $remoteconnect,
1671 '$wallmessage' => $wallmessage,
1672 '$location' => $location,
1673 '$gender' => $gender,
1675 '$marital' => $marital,
1676 '$homepage' => $homepage,
1677 '$network' => t('Network:'),
1678 '$diaspora' => $diaspora,
1679 '$contact_block' => $contact_block,
1683 $arr = array('profile' => &$profile, 'entry' => &$o);
1685 call_hooks('profile_sidebar', $arr);
1692 if(! function_exists('get_birthdays')) {
1693 function get_birthdays() {
1698 if(! local_user() || $a->is_mobile || $a->is_tablet)
1701 // $mobile_detect = new Mobile_Detect();
1702 // $is_mobile = $mobile_detect->isMobile() || $mobile_detect->isTablet();
1707 $bd_format = t('g A l F d') ; // 8 AM Friday January 18
1708 $bd_short = t('F d');
1710 $r = q("SELECT `event`.*, `event`.`id` AS `eid`, `contact`.* FROM `event`
1711 INNER JOIN `contact` ON `contact`.`id` = `event`.`cid`
1712 WHERE `event`.`uid` = %d AND `type` = 'birthday' AND `start` < '%s' AND `finish` > '%s'
1713 ORDER BY `start` ASC ",
1714 intval(local_user()),
1715 dbesc(datetime_convert('UTC','UTC','now + 6 days')),
1716 dbesc(datetime_convert('UTC','UTC','now'))
1719 if($r && count($r)) {
1721 $now = strtotime('now');
1725 foreach($r as $rr) {
1726 if(strlen($rr['name']))
1728 if((strtotime($rr['start'] . ' +00:00') < $now) && (strtotime($rr['finish'] . ' +00:00') > $now))
1731 $classtoday = $istoday ? ' birthday-today ' : '';
1733 foreach($r as &$rr) {
1734 if(! strlen($rr['name']))
1739 if(in_array($rr['cid'],$cids))
1741 $cids[] = $rr['cid'];
1743 $today = (((strtotime($rr['start'] . ' +00:00') < $now) && (strtotime($rr['finish'] . ' +00:00') > $now)) ? true : false);
1746 if($rr['network'] === NETWORK_DFRN) {
1747 $sparkle = " sparkle";
1748 $url = $a->get_baseurl() . '/redir/' . $rr['cid'];
1752 $rr['title'] = $rr['name'];
1753 $rr['date'] = day_translate(datetime_convert('UTC', $a->timezone, $rr['start'], $rr['adjust'] ? $bd_format : $bd_short)) . (($today) ? ' ' . t('[today]') : '');
1754 $rr['startime'] = Null;
1755 $rr['today'] = $today;
1760 $tpl = get_markup_template("birthdays_reminder.tpl");
1761 return replace_macros($tpl, array(
1762 '$baseurl' => $a->get_baseurl(),
1763 '$classtoday' => $classtoday,
1765 '$event_reminders' => t('Birthday Reminders'),
1766 '$event_title' => t('Birthdays this week:'),
1768 '$lbr' => '{', // raw brackets mess up if/endif macro processing
1776 if(! function_exists('get_events')) {
1777 function get_events() {
1779 require_once('include/bbcode.php');
1783 if(! local_user() || $a->is_mobile || $a->is_tablet)
1787 // $mobile_detect = new Mobile_Detect();
1788 // $is_mobile = $mobile_detect->isMobile() || $mobile_detect->isTablet();
1793 $bd_format = t('g A l F d') ; // 8 AM Friday January 18
1794 $bd_short = t('F d');
1796 $r = q("SELECT `event`.* FROM `event`
1797 WHERE `event`.`uid` = %d AND `type` != 'birthday' AND `start` < '%s' AND `start` > '%s'
1798 ORDER BY `start` ASC ",
1799 intval(local_user()),
1800 dbesc(datetime_convert('UTC','UTC','now + 6 days')),
1801 dbesc(datetime_convert('UTC','UTC','now - 1 days'))
1804 if($r && count($r)) {
1805 $now = strtotime('now');
1807 foreach($r as $rr) {
1808 if(strlen($rr['name']))
1811 $strt = datetime_convert('UTC',$rr['convert'] ? $a->timezone : 'UTC',$rr['start'],'Y-m-d');
1812 if($strt === datetime_convert('UTC',$a->timezone,'now','Y-m-d'))
1815 $classtoday = (($istoday) ? 'event-today' : '');
1818 foreach($r as &$rr) {
1820 $md = datetime_convert('UTC',$a->timezone,$rr['start'],'Y/m');
1822 $md = datetime_convert('UTC','UTC',$rr['start'],'Y/m');
1823 $md .= "/#link-".$rr['id'];
1825 $title = substr(strip_tags(bbcode($rr['desc'])),0,32) . '... ';
1827 $title = t('[No description]');
1829 $strt = datetime_convert('UTC',$rr['convert'] ? $a->timezone : 'UTC',$rr['start']);
1830 $today = ((substr($strt,0,10) === datetime_convert('UTC',$a->timezone,'now','Y-m-d')) ? true : false);
1833 $rr['title'] = $title;
1834 $rr['date'] = day_translate(datetime_convert('UTC', $rr['adjust'] ? $a->timezone : 'UTC', $rr['start'], $bd_format)) . (($today) ? ' ' . t('[today]') : '');
1835 $rr['startime'] = $strt;
1836 $rr['today'] = $today;
1840 $tpl = get_markup_template("events_reminder.tpl");
1841 return replace_macros($tpl, array(
1842 '$baseurl' => $a->get_baseurl(),
1843 '$classtoday' => $classtoday,
1844 '$count' => count($r),
1845 '$event_reminders' => t('Event Reminders'),
1846 '$event_title' => t('Events this week:'),
1855 * Wrap calls to proc_close(proc_open()) and call hook
1856 * so plugins can take part in process :)
1859 * $cmd program to run
1860 * next args are passed as $cmd command line
1862 * e.g.: proc_run("ls","-la","/tmp");
1864 * $cmd and string args are surrounded with ""
1867 if(! function_exists('proc_run')) {
1868 function proc_run($cmd){
1872 $args = func_get_args();
1878 // expand any arrays
1880 foreach($args as $arg) {
1881 if(is_array($arg)) {
1882 foreach($arg as $n) {
1892 $arr = array('args' => $args, 'run_cmd' => true);
1894 call_hooks("proc_run", $arr);
1895 if(! $arr['run_cmd'])
1898 if(count($args) && $args[0] === 'php')
1899 $args[0] = ((x($a->config,'php_path')) && (strlen($a->config['php_path'])) ? $a->config['php_path'] : 'php');
1901 // add baseurl to args. cli scripts can't construct it
1902 $args[] = $a->get_baseurl();
1904 for($x = 0; $x < count($args); $x ++)
1905 $args[$x] = escapeshellarg($args[$x]);
1909 $cmdline = implode($args," ");
1910 if(get_config('system','proc_windows'))
1911 proc_close(proc_open('cmd /c start /b ' . $cmdline,array(),$foo,dirname(__FILE__)));
1913 proc_close(proc_open($cmdline." &",array(),$foo,dirname(__FILE__)));
1917 if(! function_exists('current_theme')) {
1918 function current_theme(){
1919 $app_base_themes = array('duepuntozero', 'dispy', 'quattro');
1923 // $mobile_detect = new Mobile_Detect();
1924 // $is_mobile = $mobile_detect->isMobile() || $mobile_detect->isTablet();
1925 $is_mobile = $a->is_mobile || $a->is_tablet;
1928 if(isset($_SESSION['show-mobile']) && !$_SESSION['show-mobile']) {
1933 $system_theme = ((isset($a->config['system']['mobile-theme'])) ? $a->config['system']['mobile-theme'] : '');
1934 $theme_name = ((isset($_SESSION) && x($_SESSION,'mobile-theme')) ? $_SESSION['mobile-theme'] : $system_theme);
1936 if($theme_name === '---') {
1937 // user has selected to have the mobile theme be the same as the normal one
1943 if(!$is_mobile || ($system_theme === '' && $theme_name === '')) {
1944 $system_theme = ((isset($a->config['system']['theme'])) ? $a->config['system']['theme'] : '');
1945 $theme_name = ((isset($_SESSION) && x($_SESSION,'theme')) ? $_SESSION['theme'] : $system_theme);
1949 (file_exists('view/theme/' . $theme_name . '/style.css') ||
1950 file_exists('view/theme/' . $theme_name . '/style.php')))
1951 return($theme_name);
1953 foreach($app_base_themes as $t) {
1954 if(file_exists('view/theme/' . $t . '/style.css')||
1955 file_exists('view/theme/' . $t . '/style.php'))
1959 $fallback = array_merge(glob('view/theme/*/style.css'),glob('view/theme/*/style.php'));
1960 if(count($fallback))
1961 return (str_replace('view/theme/','', substr($fallback[0],0,-10)));
1967 * Return full URL to theme which is currently in effect.
1968 * Provide a sane default if nothing is chosen or the specified theme does not exist.
1970 if(! function_exists('current_theme_url')) {
1971 function current_theme_url() {
1973 $t = current_theme();
1974 if (file_exists('view/theme/' . $t . '/style.php'))
1975 return($a->get_baseurl() . '/view/theme/' . $t . '/style.pcss');
1976 return($a->get_baseurl() . '/view/theme/' . $t . '/style.css');
1980 if(! function_exists('feed_birthday')) {
1981 function feed_birthday($uid,$tz) {
1985 * Determine the next birthday, but only if the birthday is published
1986 * in the default profile. We _could_ also look for a private profile that the
1987 * recipient can see, but somebody could get mad at us if they start getting
1988 * public birthday greetings when they haven't made this info public.
1990 * Assuming we are able to publish this info, we are then going to convert
1991 * the start time from the owner's timezone to UTC.
1993 * This will potentially solve the problem found with some social networks
1994 * where birthdays are converted to the viewer's timezone and salutations from
1995 * elsewhere in the world show up on the wrong day. We will convert it to the
1996 * viewer's timezone also, but first we are going to convert it from the birthday
1997 * person's timezone to GMT - so the viewer may find the birthday starting at
1998 * 6:00PM the day before, but that will correspond to midnight to the birthday person.
2008 $p = q("SELECT `dob` FROM `profile` WHERE `is-default` = 1 AND `uid` = %d LIMIT 1",
2012 if($p && count($p)) {
2013 $tmp_dob = substr($p[0]['dob'],5);
2014 if(intval($tmp_dob)) {
2015 $y = datetime_convert($tz,$tz,'now','Y');
2016 $bd = $y . '-' . $tmp_dob . ' 00:00';
2017 $t_dob = strtotime($bd);
2018 $now = strtotime(datetime_convert($tz,$tz,'now'));
2020 $bd = $y + 1 . '-' . $tmp_dob . ' 00:00';
2021 $birthday = datetime_convert($tz,'UTC',$bd,ATOM_TIME);
2029 if(! function_exists('is_site_admin')) {
2030 function is_site_admin() {
2033 $adminlist = explode(",", str_replace(" ", "", $a->config['admin_email']));
2035 //if(local_user() && x($a->user,'email') && x($a->config,'admin_email') && ($a->user['email'] === $a->config['admin_email']))
2036 if(local_user() && x($a->user,'email') && x($a->config,'admin_email') && in_array($a->user['email'], $adminlist))
2043 if(! function_exists('load_contact_links')) {
2044 function load_contact_links($uid) {
2050 if(! $uid || x($a->contacts,'empty'))
2053 $r = q("SELECT `id`,`network`,`url`,`thumb` FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 ",
2058 $url = normalise_link($rr['url']);
2063 $ret['empty'] = true;
2064 $a->contacts = $ret;
2069 if(! function_exists('profile_tabs')){
2070 function profile_tabs($a, $is_owner=False, $nickname=Null){
2071 //echo "<pre>"; var_dump($a->user); killme();
2073 if (is_null($nickname))
2074 $nickname = $a->user['nickname'];
2077 $tab = notags(trim($_GET['tab']));
2079 $url = $a->get_baseurl() . '/profile/' . $nickname;
2083 'label'=>t('Status'),
2085 'sel' => ((!isset($tab)&&$a->argv[0]=='profile')?'active':''),
2086 'title' => t('Status Messages and Posts'),
2087 'id' => 'status-tab',
2090 'label' => t('Profile'),
2091 'url' => $url.'/?tab=profile',
2092 'sel' => ((isset($tab) && $tab=='profile')?'active':''),
2093 'title' => t('Profile Details'),
2094 'id' => 'profile-tab',
2097 'label' => t('Photos'),
2098 'url' => $a->get_baseurl() . '/photos/' . $nickname,
2099 'sel' => ((!isset($tab)&&$a->argv[0]=='photos')?'active':''),
2100 'title' => t('Photo Albums'),
2101 'id' => 'photo-tab',
2104 'label' => t('Videos'),
2105 'url' => $a->get_baseurl() . '/videos/' . $nickname,
2106 'sel' => ((!isset($tab)&&$a->argv[0]=='videos')?'active':''),
2107 'title' => t('Videos'),
2108 'id' => 'video-tab',
2114 'label' => t('Events'),
2115 'url' => $a->get_baseurl() . '/events',
2116 'sel' =>((!isset($tab)&&$a->argv[0]=='events')?'active':''),
2117 'title' => t('Events and Calendar'),
2118 'id' => 'events-tab',
2121 'label' => t('Personal Notes'),
2122 'url' => $a->get_baseurl() . '/notes',
2123 'sel' =>((!isset($tab)&&$a->argv[0]=='notes')?'active':''),
2124 'title' => t('Only You Can See This'),
2125 'id' => 'notes-tab',
2130 $arr = array('is_owner' => $is_owner, 'nickname' => $nickname, 'tab' => (($tab) ? $tab : false), 'tabs' => $tabs);
2131 call_hooks('profile_tabs', $arr);
2133 $tpl = get_markup_template('common_tabs.tpl');
2135 return replace_macros($tpl,array('$tabs' => $arr['tabs']));
2139 function get_my_url() {
2140 if(x($_SESSION,'my_url'))
2141 return $_SESSION['my_url'];
2145 function zrl_init(&$a) {
2146 $tmp_str = get_my_url();
2147 if(validate_url($tmp_str)) {
2148 proc_run('php','include/gprobe.php',bin2hex($tmp_str));
2149 $arr = array('zrl' => $tmp_str, 'url' => $a->cmd);
2150 call_hooks('zrl_init',$arr);
2154 function zrl($s,$force = false) {
2157 if((! strpos($s,'/profile/')) && (! $force))
2159 if($force && substr($s,-1,1) !== '/')
2161 $achar = strpos($s,'?') ? '&' : '?';
2162 $mine = get_my_url();
2163 if($mine and ! link_compare($mine,$s))
2164 return $s . $achar . 'zrl=' . urlencode($mine);
2169 * returns querystring as string from a mapped array
2171 * @param params Array
2174 function build_querystring($params, $name=null) {
2176 foreach($params as $key=>$val) {
2177 if(is_array($val)) {
2179 $ret .= build_querystring($val, $key);
2181 $ret .= build_querystring($val, $name."[$key]");
2184 $val = urlencode($val);
2186 $ret.=$name."[$key]"."=$val&";
2188 $ret.= "$key=$val&";
2195 function explode_querystring($query) {
2196 $arg_st = strpos($query, '?');
2197 if($arg_st !== false) {
2198 $base = substr($query, 0, $arg_st);
2206 $args = explode('&', substr($query, $arg_st));
2207 foreach($args as $k=>$arg) {
2211 $args = array_values($args);
2216 $args = array_values($args);
2226 * Returns the complete URL of the current page, e.g.: http(s)://something.com/network
2228 * Taken from http://webcheatsheet.com/php/get_current_page_url.php
2230 function curPageURL() {
2232 if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
2234 if ($_SERVER["SERVER_PORT"] != "80" && $_SERVER["SERVER_PORT"] != "443") {
2235 $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
2237 $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
2242 function random_digits($digits) {
2244 for($i = 0; $i < $digits; $i++) {
2250 function get_cachefile($file, $writemode = true) {
2251 $cache = get_itemcachepath();
2253 if ((! $cache) || (! is_dir($cache)))
2256 $subfolder = $cache."/".substr($file, 0, 2);
2258 $cachepath = $subfolder."/".$file;
2261 if (!is_dir($subfolder)) {
2263 chmod($subfolder, 0777);
2270 function clear_cache($basepath = "", $path = "") {
2272 $basepath = get_itemcachepath();
2276 if (($path == "") OR (!is_dir($path)))
2279 if (substr(realpath($path), 0, strlen($basepath)) != $basepath)
2282 $cachetime = (int)get_config('system','itemcache_duration');
2283 if ($cachetime == 0)
2286 if (is_writable($path)){
2287 if ($dh = opendir($path)) {
2288 while (($file = readdir($dh)) !== false) {
2289 $fullpath = $path."/".$file;
2290 if ((filetype($fullpath) == "dir") and ($file != ".") and ($file != ".."))
2291 clear_cache($basepath, $fullpath);
2292 if ((filetype($fullpath) == "file") and (filectime($fullpath) < (time() - $cachetime)))
2300 function get_itemcachepath() {
2301 // Checking, if the cache is deactivated
2302 $cachetime = (int)get_config('system','itemcache_duration');
2306 $itemcache = get_config('system','itemcache');
2307 if (($itemcache != "") AND is_dir($itemcache) AND is_writable($itemcache))
2310 $temppath = get_temppath();
2312 if ($temppath != "") {
2313 $itemcache = $temppath."/itemcache";
2316 if (is_dir($itemcache) AND is_writable($itemcache)) {
2317 set_config("system", "itemcache", $itemcache);
2324 function get_lockpath() {
2325 $lockpath = get_config('system','lockpath');
2326 if (($lockpath != "") AND is_dir($lockpath) AND is_writable($lockpath))
2329 $temppath = get_temppath();
2331 if ($temppath != "") {
2332 $lockpath = $temppath."/lock";
2335 if (is_dir($lockpath) AND is_writable($lockpath)) {
2336 set_config("system", "lockpath", $lockpath);
2343 function get_temppath() {
2344 $temppath = get_config("system","temppath");
2345 if (($temppath != "") AND is_dir($temppath) AND is_writable($temppath))
2348 $temppath = sys_get_temp_dir();
2349 if (($temppath != "") AND is_dir($temppath) AND is_writable($temppath)) {
2350 set_config("system", "temppath", $temppath);
2357 function set_template_engine(&$a, $engine = 'internal') {
2358 // This function is no longer necessary, but keep it as a wrapper to the class method
2359 // to avoid breaking themes again unnecessarily
2361 $a->set_template_engine($engine);
2364 if(!function_exists('exif_imagetype')) {
2365 function exif_imagetype($file) {
2366 $size = getimagesize($file);