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 require_once('update.php');
15 require_once('include/dbstructure.php');
17 define ( 'FRIENDICA_PLATFORM', 'Friendica');
18 define ( 'FRIENDICA_CODENAME', 'Ginger');
19 define ( 'FRIENDICA_VERSION', '3.3.3-RC' );
20 define ( 'DFRN_PROTOCOL_VERSION', '2.23' );
21 define ( 'DB_UPDATE_VERSION', 1180 );
22 define ( 'EOL', "<br />\r\n" );
23 define ( 'ATOM_TIME', 'Y-m-d\TH:i:s\Z' );
28 * Image storage quality. Lower numbers save space at cost of image detail.
29 * For ease of upgrade, please do not change here. Change jpeg quality with
30 * $a->config['system']['jpeg_quality'] = n;
31 * in .htconfig.php, where n is netween 1 and 100, and with very poor results
36 define ( 'JPEG_QUALITY', 100 );
38 * $a->config['system']['png_quality'] from 0 (uncompressed) to 9
40 define ( 'PNG_QUALITY', 8 );
44 * An alternate way of limiting picture upload sizes. Specify the maximum pixel
45 * length that pictures are allowed to be (for non-square pictures, it will apply
46 * to the longest side). Pictures longer than this length will be resized to be
47 * this length (on the longest side, the other side will be scaled appropriately).
48 * Modify this value using
50 * $a->config['system']['max_image_length'] = n;
54 * If you don't want to set a maximum length, set to -1. The default value is
55 * defined by 'MAX_IMAGE_LENGTH' below.
58 define ( 'MAX_IMAGE_LENGTH', -1 );
65 define ( 'DEFAULT_DB_ENGINE', 'MyISAM' );
68 * SSL redirection policies
71 define ( 'SSL_POLICY_NONE', 0 );
72 define ( 'SSL_POLICY_FULL', 1 );
73 define ( 'SSL_POLICY_SELFSIGN', 2 );
80 define ( 'LOGGER_NORMAL', 0 );
81 define ( 'LOGGER_TRACE', 1 );
82 define ( 'LOGGER_DEBUG', 2 );
83 define ( 'LOGGER_DATA', 3 );
84 define ( 'LOGGER_ALL', 4 );
87 * registration policies
90 define ( 'REGISTER_CLOSED', 0 );
91 define ( 'REGISTER_APPROVE', 1 );
92 define ( 'REGISTER_OPEN', 2 );
98 define ( 'CONTACT_IS_FOLLOWER', 1);
99 define ( 'CONTACT_IS_SHARING', 2);
100 define ( 'CONTACT_IS_FRIEND', 3);
104 * DB update return values
107 define ( 'UPDATE_SUCCESS', 0);
108 define ( 'UPDATE_FAILED', 1);
115 * PAGE_NORMAL is a typical personal profile account
116 * PAGE_SOAPBOX automatically approves all friend requests as CONTACT_IS_SHARING, (readonly)
117 * PAGE_COMMUNITY automatically approves all friend requests as CONTACT_IS_SHARING, but with
118 * write access to wall and comments (no email and not included in page owner's ACL lists)
119 * PAGE_FREELOVE automatically approves all friend requests as full friends (CONTACT_IS_FRIEND).
123 define ( 'PAGE_NORMAL', 0 );
124 define ( 'PAGE_SOAPBOX', 1 );
125 define ( 'PAGE_COMMUNITY', 2 );
126 define ( 'PAGE_FREELOVE', 3 );
127 define ( 'PAGE_BLOG', 4 );
128 define ( 'PAGE_PRVGROUP', 5 );
130 // Type of the community page
131 define ( 'CP_NO_COMMUNITY_PAGE', -1 );
132 define ( 'CP_USERS_ON_SERVER', 0 );
133 define ( 'CP_GLOBAL_COMMUNITY', 1 );
136 * Network and protocol family types
139 define ( 'NETWORK_DFRN', 'dfrn'); // Friendica, Mistpark, other DFRN implementations
140 define ( 'NETWORK_ZOT', 'zot!'); // Zot!
141 define ( 'NETWORK_OSTATUS', 'stat'); // status.net, identi.ca, GNU-social, other OStatus implementations
142 define ( 'NETWORK_FEED', 'feed'); // RSS/Atom feeds with no known "post/notify" protocol
143 define ( 'NETWORK_DIASPORA', 'dspr'); // Diaspora
144 define ( 'NETWORK_MAIL', 'mail'); // IMAP/POP
145 define ( 'NETWORK_MAIL2', 'mai2'); // extended IMAP/POP
146 define ( 'NETWORK_FACEBOOK', 'face'); // Facebook API
147 define ( 'NETWORK_LINKEDIN', 'lnkd'); // LinkedIn
148 define ( 'NETWORK_XMPP', 'xmpp'); // XMPP
149 define ( 'NETWORK_MYSPACE', 'mysp'); // MySpace
150 define ( 'NETWORK_GPLUS', 'goog'); // Google+
151 define ( 'NETWORK_PUMPIO', 'pump'); // pump.io
152 define ( 'NETWORK_TWITTER', 'twit'); // Twitter
153 define ( 'NETWORK_DIASPORA2', 'dspc'); // Diaspora connector
154 define ( 'NETWORK_STATUSNET', 'stac'); // Statusnet connector
155 define ( 'NETWORK_APPNET', 'apdn'); // app.net
157 define ( 'NETWORK_PHANTOM', 'unkn'); // Place holder
160 * These numbers are used in stored permissions
161 * and existing allocations MUST NEVER BE CHANGED
162 * OR RE-ASSIGNED! You may only add to them.
165 $netgroup_ids = array(
166 NETWORK_DFRN => (-1),
168 NETWORK_OSTATUS => (-3),
169 NETWORK_FEED => (-4),
170 NETWORK_DIASPORA => (-5),
171 NETWORK_MAIL => (-6),
172 NETWORK_MAIL2 => (-7),
173 NETWORK_FACEBOOK => (-8),
174 NETWORK_LINKEDIN => (-9),
175 NETWORK_XMPP => (-10),
176 NETWORK_MYSPACE => (-11),
177 NETWORK_GPLUS => (-12),
178 NETWORK_PUMPIO => (-13),
179 NETWORK_TWITTER => (-14),
180 NETWORK_DIASPORA2 => (-15),
181 NETWORK_STATUSNET => (-16),
182 NETWORK_APPNET => (-17),
184 NETWORK_PHANTOM => (-127),
189 * Maximum number of "people who like (or don't like) this" that we will list by name
192 define ( 'MAX_LIKERS', 75);
195 * Communication timeout
198 define ( 'ZCURL_TIMEOUT' , (-1));
202 * email notification options
205 define ( 'NOTIFY_INTRO', 0x0001 );
206 define ( 'NOTIFY_CONFIRM', 0x0002 );
207 define ( 'NOTIFY_WALL', 0x0004 );
208 define ( 'NOTIFY_COMMENT', 0x0008 );
209 define ( 'NOTIFY_MAIL', 0x0010 );
210 define ( 'NOTIFY_SUGGEST', 0x0020 );
211 define ( 'NOTIFY_PROFILE', 0x0040 );
212 define ( 'NOTIFY_TAGSELF', 0x0080 );
213 define ( 'NOTIFY_TAGSHARE', 0x0100 );
214 define ( 'NOTIFY_POKE', 0x0200 );
215 define ( 'NOTIFY_SHARE', 0x0400 );
217 define ( 'NOTIFY_SYSTEM', 0x8000 );
224 define ( 'TERM_UNKNOWN', 0 );
225 define ( 'TERM_HASHTAG', 1 );
226 define ( 'TERM_MENTION', 2 );
227 define ( 'TERM_CATEGORY', 3 );
228 define ( 'TERM_PCATEGORY', 4 );
229 define ( 'TERM_FILE', 5 );
230 define ( 'TERM_SAVEDSEARCH', 6 );
231 define ( 'TERM_CONVERSATION', 7 );
233 define ( 'TERM_OBJ_POST', 1 );
234 define ( 'TERM_OBJ_PHOTO', 2 );
239 * various namespaces we may need to parse
242 define ( 'NAMESPACE_ZOT', 'http://purl.org/zot' );
243 define ( 'NAMESPACE_DFRN' , 'http://purl.org/macgirvin/dfrn/1.0' );
244 define ( 'NAMESPACE_THREAD' , 'http://purl.org/syndication/thread/1.0' );
245 define ( 'NAMESPACE_TOMB' , 'http://purl.org/atompub/tombstones/1.0' );
246 define ( 'NAMESPACE_ACTIVITY', 'http://activitystrea.ms/spec/1.0/' );
247 define ( 'NAMESPACE_ACTIVITY_SCHEMA', 'http://activitystrea.ms/schema/1.0/' );
248 define ( 'NAMESPACE_MEDIA', 'http://purl.org/syndication/atommedia' );
249 define ( 'NAMESPACE_SALMON_ME', 'http://salmon-protocol.org/ns/magic-env' );
250 define ( 'NAMESPACE_OSTATUSSUB', 'http://ostatus.org/schema/1.0/subscribe' );
251 define ( 'NAMESPACE_GEORSS', 'http://www.georss.org/georss' );
252 define ( 'NAMESPACE_POCO', 'http://portablecontacts.net/spec/1.0' );
253 define ( 'NAMESPACE_FEED', 'http://schemas.google.com/g/2010#updates-from' );
254 define ( 'NAMESPACE_OSTATUS', 'http://ostatus.org/schema/1.0' );
255 define ( 'NAMESPACE_STATUSNET', 'http://status.net/schema/api/1/' );
256 define ( 'NAMESPACE_ATOM1', 'http://www.w3.org/2005/Atom' );
258 * activity stream defines
261 define ( 'ACTIVITY_LIKE', NAMESPACE_ACTIVITY_SCHEMA . 'like' );
262 define ( 'ACTIVITY_DISLIKE', NAMESPACE_DFRN . '/dislike' );
263 define ( 'ACTIVITY_OBJ_HEART', NAMESPACE_DFRN . '/heart' );
265 define ( 'ACTIVITY_FRIEND', NAMESPACE_ACTIVITY_SCHEMA . 'make-friend' );
266 define ( 'ACTIVITY_REQ_FRIEND', NAMESPACE_ACTIVITY_SCHEMA . 'request-friend' );
267 define ( 'ACTIVITY_UNFRIEND', NAMESPACE_ACTIVITY_SCHEMA . 'remove-friend' );
268 define ( 'ACTIVITY_FOLLOW', NAMESPACE_ACTIVITY_SCHEMA . 'follow' );
269 define ( 'ACTIVITY_UNFOLLOW', NAMESPACE_ACTIVITY_SCHEMA . 'stop-following' );
270 define ( 'ACTIVITY_JOIN', NAMESPACE_ACTIVITY_SCHEMA . 'join' );
272 define ( 'ACTIVITY_POST', NAMESPACE_ACTIVITY_SCHEMA . 'post' );
273 define ( 'ACTIVITY_UPDATE', NAMESPACE_ACTIVITY_SCHEMA . 'update' );
274 define ( 'ACTIVITY_TAG', NAMESPACE_ACTIVITY_SCHEMA . 'tag' );
275 define ( 'ACTIVITY_FAVORITE', NAMESPACE_ACTIVITY_SCHEMA . 'favorite' );
277 define ( 'ACTIVITY_POKE', NAMESPACE_ZOT . '/activity/poke' );
278 define ( 'ACTIVITY_MOOD', NAMESPACE_ZOT . '/activity/mood' );
280 define ( 'ACTIVITY_OBJ_BOOKMARK', NAMESPACE_ACTIVITY_SCHEMA . 'bookmark' );
281 define ( 'ACTIVITY_OBJ_COMMENT', NAMESPACE_ACTIVITY_SCHEMA . 'comment' );
282 define ( 'ACTIVITY_OBJ_NOTE', NAMESPACE_ACTIVITY_SCHEMA . 'note' );
283 define ( 'ACTIVITY_OBJ_PERSON', NAMESPACE_ACTIVITY_SCHEMA . 'person' );
284 define ( 'ACTIVITY_OBJ_IMAGE', NAMESPACE_ACTIVITY_SCHEMA . 'image' );
285 define ( 'ACTIVITY_OBJ_PHOTO', NAMESPACE_ACTIVITY_SCHEMA . 'photo' );
286 define ( 'ACTIVITY_OBJ_VIDEO', NAMESPACE_ACTIVITY_SCHEMA . 'video' );
287 define ( 'ACTIVITY_OBJ_P_PHOTO', NAMESPACE_ACTIVITY_SCHEMA . 'profile-photo' );
288 define ( 'ACTIVITY_OBJ_ALBUM', NAMESPACE_ACTIVITY_SCHEMA . 'photo-album' );
289 define ( 'ACTIVITY_OBJ_EVENT', NAMESPACE_ACTIVITY_SCHEMA . 'event' );
290 define ( 'ACTIVITY_OBJ_GROUP', NAMESPACE_ACTIVITY_SCHEMA . 'group' );
291 define ( 'ACTIVITY_OBJ_TAGTERM', NAMESPACE_DFRN . '/tagterm' );
292 define ( 'ACTIVITY_OBJ_PROFILE', NAMESPACE_DFRN . '/profile' );
295 * item weight for query ordering
298 define ( 'GRAVITY_PARENT', 0);
299 define ( 'GRAVITY_LIKE', 3);
300 define ( 'GRAVITY_COMMENT', 6);
304 * Reverse the effect of magic_quotes_gpc if it is enabled.
305 * Please disable magic_quotes_gpc so we don't have to do this.
306 * See http://php.net/manual/en/security.magicquotes.disabling.php
312 error_reporting(E_ERROR | E_WARNING | E_PARSE);
316 // This has to be quite large to deal with embedded private photos
317 ini_set('pcre.backtrack_limit', 500000);
320 if (get_magic_quotes_gpc()) {
321 $process = array(&$_GET, &$_POST, &$_COOKIE, &$_REQUEST);
322 while (list($key, $val) = each($process)) {
323 foreach ($val as $k => $v) {
324 unset($process[$key][$k]);
326 $process[$key][stripslashes($k)] = $v;
327 $process[] = &$process[$key][stripslashes($k)];
329 $process[$key][stripslashes($k)] = stripslashes($v);
342 * Our main application structure for the life of this page
343 * Primarily deals with the URL that got us here
344 * and tries to make some sense of it, and
345 * stores our page contents and config storage
346 * and anything else that might need to be passed around
347 * before we spit the page out.
351 if(! class_exists('App')) {
354 public $module_loaded = false;
355 public $query_string;
363 public $page_contact;
365 public $data = array();
366 public $error = false;
376 public $interactive = true;
378 public $apps = array();
382 public $performance = array();
389 // Allow themes to control internal parameters
390 // by changing App values in theme.php
392 public $sourcename = '';
393 public $videowidth = 425;
394 public $videoheight = 350;
395 public $force_max_items = 0;
396 public $theme_thread_allow = true;
398 // An array for all theme-controllable parameters
399 // Mostly unimplemented yet. Only options 'stylesheet' and
402 public $theme = array(
405 'videoheight' => 350,
406 'force_max_items' => 0,
407 'thread_allow' => true,
409 'template_engine' => 'smarty3',
412 // array of registered template engines ('name'=>'class name')
413 public $template_engines = array();
414 // array of instanced template engines ('name'=>'instance')
415 public $template_engine_instance = array();
417 // Used for reducing load to the ostatus completion
418 public $last_ostatus_conversation_url;
420 private $ldelim = array(
424 private $rdelim = array(
435 private $curl_content_type;
436 private $curl_headers;
438 private $cached_profile_image;
439 private $cached_profile_picdate;
441 function __construct() {
443 global $default_timezone;
447 if (file_exists(".htpreconfig.php"))
448 @include(".htpreconfig.php");
450 $this->timezone = ((x($default_timezone)) ? $default_timezone : 'UTC');
452 date_default_timezone_set($this->timezone);
454 $this->performance["start"] = microtime(true);
455 $this->performance["database"] = 0;
456 $this->performance["network"] = 0;
457 $this->performance["file"] = 0;
458 $this->performance["rendering"] = 0;
459 $this->performance["parser"] = 0;
460 $this->performance["marktime"] = 0;
461 $this->performance["markstart"] = microtime(true);
463 $this->config = array();
464 $this->page = array();
465 $this->pager= array();
467 $this->query_string = '';
472 'include' . PATH_SEPARATOR
473 . 'library' . PATH_SEPARATOR
474 . 'library/phpsec' . PATH_SEPARATOR
475 . 'library/langdet' . PATH_SEPARATOR
479 $this->scheme = 'http';
480 if(x($_SERVER,'HTTPS') && $_SERVER['HTTPS'])
481 $this->scheme = 'https';
482 elseif(x($_SERVER,'SERVER_PORT') && (intval($_SERVER['SERVER_PORT']) == 443))
483 $this->scheme = 'https';
485 if(x($_SERVER,'SERVER_NAME')) {
486 $this->hostname = $_SERVER['SERVER_NAME'];
488 // See bug 437 - this didn't work so disabling it
489 //if(stristr($this->hostname,'xn--')) {
490 // PHP or webserver may have converted idn to punycode, so
491 // convert punycode back to utf-8
492 // require_once('library/simplepie/idn/idna_convert.class.php');
493 // $x = new idna_convert();
494 // $this->hostname = $x->decode($_SERVER['SERVER_NAME']);
497 if(x($_SERVER,'SERVER_PORT') && $_SERVER['SERVER_PORT'] != 80 && $_SERVER['SERVER_PORT'] != 443)
498 $this->hostname .= ':' . $_SERVER['SERVER_PORT'];
500 * Figure out if we are running at the top of a domain
501 * or in a sub-directory and adjust accordingly
504 $path = trim(dirname($_SERVER['SCRIPT_NAME']),'/\\');
505 if(isset($path) && strlen($path) && ($path != $this->path))
510 $this->hostname = $hostname;
512 if (is_array($_SERVER["argv"]) && $_SERVER["argc"]>1 && substr(end($_SERVER["argv"]), 0, 4)=="http" ) {
513 $this->set_baseurl(array_pop($_SERVER["argv"]) );
517 #set_include_path("include/$this->hostname" . PATH_SEPARATOR . get_include_path());
519 if((x($_SERVER,'QUERY_STRING')) && substr($_SERVER['QUERY_STRING'],0,9) === "pagename=") {
520 $this->query_string = substr($_SERVER['QUERY_STRING'],9);
521 // removing trailing / - maybe a nginx problem
522 if (substr($this->query_string, 0, 1) == "/")
523 $this->query_string = substr($this->query_string, 1);
524 } elseif((x($_SERVER,'QUERY_STRING')) && substr($_SERVER['QUERY_STRING'],0,2) === "q=") {
525 $this->query_string = substr($_SERVER['QUERY_STRING'],2);
526 // removing trailing / - maybe a nginx problem
527 if (substr($this->query_string, 0, 1) == "/")
528 $this->query_string = substr($this->query_string, 1);
531 if (x($_GET,'pagename'))
532 $this->cmd = trim($_GET['pagename'],'/\\');
533 elseif (x($_GET,'q'))
534 $this->cmd = trim($_GET['q'],'/\\');
538 $this->query_string = str_replace($this->cmd."&",$this->cmd."?", $this->query_string);
541 // unix style "homedir"
543 if(substr($this->cmd,0,1) === '~')
544 $this->cmd = 'profile/' . substr($this->cmd,1);
546 // Diaspora style profile url
548 if(substr($this->cmd,0,2) === 'u/')
549 $this->cmd = 'profile/' . substr($this->cmd,2);
554 * Break the URL path into C style argc/argv style arguments for our
555 * modules. Given "http://example.com/module/arg1/arg2", $this->argc
556 * will be 3 (integer) and $this->argv will contain:
562 * There will always be one argument. If provided a naked domain
563 * URL, $this->argv[0] is set to "home".
567 $this->argv = explode('/',$this->cmd);
568 $this->argc = count($this->argv);
569 if((array_key_exists('0',$this->argv)) && strlen($this->argv[0])) {
570 $this->module = str_replace(".", "_", $this->argv[0]);
571 $this->module = str_replace("-", "_", $this->module);
575 $this->argv = array('home');
576 $this->module = 'home';
580 * See if there is any page number information, and initialise
584 $this->pager['page'] = ((x($_GET,'page') && intval($_GET['page']) > 0) ? intval($_GET['page']) : 1);
585 $this->pager['itemspage'] = 50;
586 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
587 if($this->pager['start'] < 0)
588 $this->pager['start'] = 0;
589 $this->pager['total'] = 0;
592 * Detect mobile devices
595 $mobile_detect = new Mobile_Detect();
596 $this->is_mobile = $mobile_detect->isMobile();
597 $this->is_tablet = $mobile_detect->isTablet();
600 * register template engines
602 $dc = get_declared_classes();
603 foreach ($dc as $k) {
604 if (in_array("ITemplateEngine", class_implements($k))){
605 $this->register_template_engine($k);
611 function get_basepath() {
613 $basepath = get_config("system", "basepath");
616 $basepath = $_SERVER["DOCUMENT_ROOT"];
619 $basepath = $_SERVER["PWD"];
624 function get_scheme() {
625 return($this->scheme);
628 function get_baseurl($ssl = false) {
630 $scheme = $this->scheme;
632 if((x($this->config,'system')) && (x($this->config['system'],'ssl_policy'))) {
633 if(intval($this->config['system']['ssl_policy']) === intval(SSL_POLICY_FULL))
636 // Basically, we have $ssl = true on any links which can only be seen by a logged in user
637 // (and also the login link). Anything seen by an outsider will have it turned off.
639 if($this->config['system']['ssl_policy'] == SSL_POLICY_SELFSIGN) {
647 if (get_config('config','hostname') != "")
648 $this->hostname = get_config('config','hostname');
650 $this->baseurl = $scheme . "://" . $this->hostname . ((isset($this->path) && strlen($this->path)) ? '/' . $this->path : '' );
651 return $this->baseurl;
654 function set_baseurl($url) {
655 $parsed = @parse_url($url);
657 $this->baseurl = $url;
660 $this->scheme = $parsed['scheme'];
662 $hostname = $parsed['host'];
663 if(x($parsed,'port'))
664 $hostname .= ':' . $parsed['port'];
665 if(x($parsed,'path'))
666 $this->path = trim($parsed['path'],'\\/');
668 if (file_exists(".htpreconfig.php"))
669 @include(".htpreconfig.php");
671 if (get_config('config','hostname') != "")
672 $this->hostname = get_config('config','hostname');
674 if (!isset($this->hostname) OR ($this->hostname == ""))
675 $this->hostname = $hostname;
680 function get_hostname() {
681 if (get_config('config','hostname') != "")
682 $this->hostname = get_config('config','hostname');
684 return $this->hostname;
687 function set_hostname($h) {
688 $this->hostname = $h;
691 function set_path($p) {
692 $this->path = trim(trim($p),'/');
695 function get_path() {
699 function set_pager_total($n) {
700 $this->pager['total'] = intval($n);
703 function set_pager_itemspage($n) {
704 $this->pager['itemspage'] = ((intval($n) > 0) ? intval($n) : 0);
705 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
708 function set_pager_page($n) {
709 $this->pager['page'] = $n;
710 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
713 function init_pagehead() {
714 $interval = ((local_user()) ? get_pconfig(local_user(),'system','update_interval') : 40000);
715 if($interval < 10000)
718 $this->page['title'] = $this->config['sitename'];
720 /* put the head template at the beginning of page['htmlhead']
721 * since the code added by the modules frequently depends on it
724 if(!isset($this->page['htmlhead']))
725 $this->page['htmlhead'] = '';
727 // If we're using Smarty, then doing replace_macros() will replace
728 // any unrecognized variables with a blank string. Since we delay
729 // replacing $stylesheet until later, we need to replace it now
730 // with another variable name
731 if($this->theme['template_engine'] === 'smarty3')
732 $stylesheet = $this->get_template_ldelim('smarty3') . '$stylesheet' . $this->get_template_rdelim('smarty3');
734 $stylesheet = '$stylesheet';
736 $shortcut_icon = get_config("system", "shortcut_icon");
737 if ($shortcut_icon == "")
738 $shortcut_icon = $this->get_baseurl()."/images/friendica-32.png";
740 $touch_icon = get_config("system", "touch_icon");
741 if ($touch_icon == "")
742 $touch_icon = $this->get_baseurl()."/images/friendica-128.png";
744 $tpl = get_markup_template('head.tpl');
745 $this->page['htmlhead'] = replace_macros($tpl,array(
746 '$baseurl' => $this->get_baseurl(), // FIXME for z_path!!!!
747 '$local_user' => local_user(),
748 '$generator' => 'Friendica' . ' ' . FRIENDICA_VERSION,
749 '$delitem' => t('Delete this item?'),
750 '$comment' => t('Comment'),
751 '$showmore' => t('show more'),
752 '$showfewer' => t('show fewer'),
753 '$update_interval' => $interval,
754 '$shortcut_icon' => $shortcut_icon,
755 '$touch_icon' => $touch_icon,
756 '$stylesheet' => $stylesheet
757 )) . $this->page['htmlhead'];
760 function init_page_end() {
761 if(!isset($this->page['end']))
762 $this->page['end'] = '';
763 $tpl = get_markup_template('end.tpl');
764 $this->page['end'] = replace_macros($tpl,array(
765 '$baseurl' => $this->get_baseurl() // FIXME for z_path!!!!
766 )) . $this->page['end'];
769 function set_curl_code($code) {
770 $this->curl_code = $code;
773 function get_curl_code() {
774 return $this->curl_code;
777 function set_curl_content_type($content_type) {
778 $this->curl_content_type = $content_type;
781 function get_curl_content_type() {
782 return $this->curl_content_type;
785 function set_curl_headers($headers) {
786 $this->curl_headers = $headers;
789 function get_curl_headers() {
790 return $this->curl_headers;
793 function get_cached_avatar_image($avatar_image){
794 if($this->cached_profile_image[$avatar_image])
795 return $this->cached_profile_image[$avatar_image];
797 $path_parts = explode("/",$avatar_image);
798 $common_filename = $path_parts[count($path_parts)-1];
800 if($this->cached_profile_picdate[$common_filename]){
801 $this->cached_profile_image[$avatar_image] = $avatar_image . $this->cached_profile_picdate[$common_filename];
803 $r = q("SELECT `contact`.`avatar-date` AS picdate FROM `contact` WHERE `contact`.`thumb` like '%%/%s'",
806 $this->cached_profile_image[$avatar_image] = $avatar_image;
808 $this->cached_profile_picdate[$common_filename] = "?rev=".urlencode($r[0]['picdate']);
809 $this->cached_profile_image[$avatar_image] = $avatar_image.$this->cached_profile_picdate[$common_filename];
812 return $this->cached_profile_image[$avatar_image];
817 * register template engine class
818 * if $name is "", is used class static property $class::$name
819 * @param string $class
820 * @param string $name
822 function register_template_engine($class, $name = '') {
824 $v = get_class_vars( $class );
825 if(x($v,"name")) $name = $v['name'];
828 echo "template engine <tt>$class</tt> cannot be registered without a name.\n";
831 $this->template_engines[$name] = $class;
835 * return template engine instance. If $name is not defined,
836 * return engine defined by theme, or default
838 * @param strin $name Template engine name
839 * @return object Template Engine instance
841 function template_engine($name = ''){
843 $template_engine = $name;
845 $template_engine = 'smarty3';
846 if (x($this->theme, 'template_engine')) {
847 $template_engine = $this->theme['template_engine'];
851 if (isset($this->template_engines[$template_engine])){
852 if(isset($this->template_engine_instance[$template_engine])){
853 return $this->template_engine_instance[$template_engine];
855 $class = $this->template_engines[$template_engine];
857 $this->template_engine_instance[$template_engine] = $obj;
862 echo "template engine <tt>$template_engine</tt> is not registered!\n"; killme();
865 function get_template_engine() {
866 return $this->theme['template_engine'];
869 function set_template_engine($engine = 'smarty3') {
870 $this->theme['template_engine'] = $engine;
872 $this->theme['template_engine'] = 'smarty3';
876 if(is_writable('view/smarty3/'))
877 $this->theme['template_engine'] = 'smarty3';
885 function get_template_ldelim($engine = 'smarty3') {
886 return $this->ldelim[$engine];
889 function get_template_rdelim($engine = 'smarty3') {
890 return $this->rdelim[$engine];
893 function save_timestamp($stamp, $value) {
894 $duration = (float)(microtime(true)-$stamp);
896 $this->performance[$value] += (float)$duration;
897 $this->performance["marktime"] += (float)$duration;
900 function mark_timestamp($mark) {
901 //$this->performance["markstart"] -= microtime(true) - $this->performance["marktime"];
902 $this->performance["markstart"] = microtime(true) - $this->performance["markstart"] - $this->performance["marktime"];
905 function get_useragent() {
906 return(FRIENDICA_PLATFORM." '".FRIENDICA_CODENAME."' ".FRIENDICA_VERSION."-".DB_UPDATE_VERSION."; ".$this->get_baseurl());
912 // retrieve the App structure
913 // useful in functions which require it but don't get it passed to them
915 if(! function_exists('get_app')) {
923 // Multi-purpose function to check variable state.
924 // Usage: x($var) or $x($array,'key')
925 // returns false if variable/key is not set
926 // if variable is set, returns 1 if has 'non-zero' value, otherwise returns 0.
927 // e.g. x('') or x(0) returns 0;
929 if(! function_exists('x')) {
930 function x($s,$k = NULL) {
932 if((is_array($s)) && (array_key_exists($k,$s))) {
951 // called from db initialisation if db is dead.
953 if(! function_exists('system_unavailable')) {
954 function system_unavailable() {
955 include('system_unavailable.php');
963 function clean_urls() {
965 // if($a->config['system']['clean_urls'])
972 $base = $a->get_baseurl();
980 return $a->get_baseurl();
983 function absurl($path) {
984 if(strpos($path,'/') === 0)
985 return z_path() . $path;
990 return (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');
993 function check_db() {
995 $build = get_config('system','build');
997 set_config('system','build',DB_UPDATE_VERSION);
998 $build = DB_UPDATE_VERSION;
1000 if($build != DB_UPDATE_VERSION)
1001 proc_run('php', 'include/dbupdate.php');
1008 // Sets the base url for use in cmdline programs which don't have
1009 // $_SERVER variables
1011 if(! function_exists('check_url')) {
1012 function check_url(&$a) {
1014 $url = get_config('system','url');
1016 // if the url isn't set or the stored url is radically different
1017 // than the currently visited url, store the current value accordingly.
1018 // "Radically different" ignores common variations such as http vs https
1019 // and www.example.com vs example.com.
1020 // We will only change the url to an ip address if there is no existing setting
1023 $url = set_config('system','url',$a->get_baseurl());
1024 if((! link_compare($url,$a->get_baseurl())) && (! preg_match("/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/",$a->get_hostname)))
1025 $url = set_config('system','url',$a->get_baseurl());
1032 // Automatic database updates
1034 if(! function_exists('update_db')) {
1035 function update_db(&$a) {
1036 $build = get_config('system','build');
1038 $build = set_config('system','build',DB_UPDATE_VERSION);
1040 if($build != DB_UPDATE_VERSION) {
1041 $stored = intval($build);
1042 $current = intval(DB_UPDATE_VERSION);
1043 if($stored < $current) {
1044 load_config('database');
1046 // We're reporting a different version than what is currently installed.
1047 // Run any existing update scripts to bring the database up to current.
1049 // make sure that boot.php and update.php are the same release, we might be
1050 // updating right this very second and the correct version of the update.php
1051 // file may not be here yet. This can happen on a very busy site.
1053 if(DB_UPDATE_VERSION == UPDATE_VERSION) {
1054 // Compare the current structure with the defined structure
1056 $t = get_config('database','dbupdate_'.DB_UPDATE_VERSION);
1060 set_config('database','dbupdate_'.DB_UPDATE_VERSION, time());
1062 // run old update routine (wich could modify the schema and
1063 // conflits with new routine)
1064 for ($x = $stored; $x < NEW_UPDATE_ROUTINE_VERSION; $x++) {
1065 $r = run_update_function($x);
1068 if ($stored < NEW_UPDATE_ROUTINE_VERSION) $stored = NEW_UPDATE_ROUTINE_VERSION;
1071 // run new update routine
1072 // it update the structure in one call
1073 $retval = update_structure(false, true);
1081 set_config('database','dbupdate_'.DB_UPDATE_VERSION, 'success');
1084 // run any left update_nnnn functions in update.php
1085 for($x = $stored; $x < $current; $x ++) {
1086 $r = run_update_function($x);
1096 if(!function_exists('run_update_function')){
1097 function run_update_function($x) {
1098 if(function_exists('update_' . $x)) {
1100 // There could be a lot of processes running or about to run.
1101 // We want exactly one process to run the update command.
1102 // So store the fact that we're taking responsibility
1103 // after first checking to see if somebody else already has.
1105 // If the update fails or times-out completely you may need to
1106 // delete the config entry to try again.
1108 $t = get_config('database','update_' . $x);
1111 set_config('database','update_' . $x, time());
1113 // call the specific update
1115 $func = 'update_' . $x;
1119 //send the administrator an e-mail
1122 sprintf(t('Update %s failed. See error logs.'), $x)
1126 set_config('database','update_' . $x, 'success');
1127 set_config('system','build', $x + 1);
1131 set_config('database','update_' . $x, 'success');
1132 set_config('system','build', $x + 1);
1140 if(! function_exists('check_plugins')) {
1141 function check_plugins(&$a) {
1145 * Synchronise plugins:
1147 * $a->config['system']['addon'] contains a comma-separated list of names
1148 * of plugins/addons which are used on this system.
1149 * Go through the database list of already installed addons, and if we have
1150 * an entry, but it isn't in the config list, call the uninstall procedure
1151 * and mark it uninstalled in the database (for now we'll remove it).
1152 * Then go through the config list and if we have a plugin that isn't installed,
1153 * call the install procedure and add it to the database.
1157 $r = q("SELECT * FROM `addon` WHERE `installed` = 1");
1161 $installed = array();
1163 $plugins = get_config('system','addon');
1164 $plugins_arr = array();
1167 $plugins_arr = explode(',',str_replace(' ', '',$plugins));
1169 $a->plugins = $plugins_arr;
1171 $installed_arr = array();
1173 if(count($installed)) {
1174 foreach($installed as $i) {
1175 if(! in_array($i['name'],$plugins_arr)) {
1176 uninstall_plugin($i['name']);
1179 $installed_arr[] = $i['name'];
1184 if(count($plugins_arr)) {
1185 foreach($plugins_arr as $p) {
1186 if(! in_array($p,$installed_arr)) {
1199 function get_guid($size=16) {
1200 $exists = true; // assume by default that we don't have a unique guid
1203 while (strlen($prefix) < ($size - 13))
1204 $prefix .= mt_rand();
1206 $s = substr(uniqid($prefix), -$size);
1208 $r = q("select id from guid where guid = '%s' limit 1", dbesc($s));
1212 q("insert into guid (guid) values ('%s') ", dbesc($s));
1216 /*function get_guid($size=16) {
1217 $exists = true; // assume by default that we don't have a unique guid
1219 $s = random_string($size);
1220 $r = q("select id from guid where guid = '%s' limit 1", dbesc($s));
1224 q("insert into guid ( guid ) values ( '%s' ) ", dbesc($s));
1229 // wrapper for adding a login box. If $register == true provide a registration
1230 // link. This will most always depend on the value of $a->config['register_policy'].
1231 // returns the complete html for inserting into the page
1233 if(! function_exists('login')) {
1234 function login($register = false, $hiddens=false) {
1240 'title' => t('Create a New Account'),
1241 'desc' => t('Register')
1245 $noid = get_config('system','no_openid');
1247 $dest_url = $a->get_baseurl(true) . '/' . $a->query_string;
1250 $tpl = get_markup_template("logout.tpl");
1253 $a->page['htmlhead'] .= replace_macros(get_markup_template("login_head.tpl"),array(
1254 '$baseurl' => $a->get_baseurl(true)
1257 $tpl = get_markup_template("login.tpl");
1258 $_SESSION['return_url'] = $a->query_string;
1259 $a->module = 'login';
1262 $o .= replace_macros($tpl, array(
1264 '$dest_url' => $dest_url,
1265 '$logout' => t('Logout'),
1266 '$login' => t('Login'),
1268 '$lname' => array('username', t('Nickname or Email address: ') , '', ''),
1269 '$lpassword' => array('password', t('Password: '), '', ''),
1270 '$lremember' => array('remember', t('Remember me'), 0, ''),
1272 '$openid' => !$noid,
1273 '$lopenid' => array('openid_url', t('Or login using OpenID: '),'',''),
1275 '$hiddens' => $hiddens,
1277 '$register' => $reg,
1279 '$lostpass' => t('Forgot your password?'),
1280 '$lostlink' => t('Password Reset'),
1282 '$tostitle' => t('Website Terms of Service'),
1283 '$toslink' => t('terms of service'),
1285 '$privacytitle' => t('Website Privacy Policy'),
1286 '$privacylink' => t('privacy policy'),
1290 call_hooks('login_hook',$o);
1296 // Used to end the current process, after saving session state.
1298 if(! function_exists('killme')) {
1300 session_write_close();
1305 // redirect to another URL and terminate this process.
1307 if(! function_exists('goaway')) {
1308 function goaway($s) {
1309 header("Location: $s");
1315 // Returns the uid of locally logged in user or false.
1317 if(! function_exists('local_user')) {
1318 function local_user() {
1319 if((x($_SESSION,'authenticated')) && (x($_SESSION,'uid')))
1320 return intval($_SESSION['uid']);
1325 // Returns contact id of authenticated site visitor or false
1327 if(! function_exists('remote_user')) {
1328 function remote_user() {
1329 if((x($_SESSION,'authenticated')) && (x($_SESSION,'visitor_id')))
1330 return intval($_SESSION['visitor_id']);
1335 // contents of $s are displayed prominently on the page the next time
1336 // a page is loaded. Usually used for errors or alerts.
1338 if(! function_exists('notice')) {
1340 * Show an error message to user.
1342 * This function save text in session, to be shown to the user at next page load
1344 * @param string $s - Text of notice
1346 function notice($s) {
1348 if(! x($_SESSION,'sysmsg')) $_SESSION['sysmsg'] = array();
1350 $_SESSION['sysmsg'][] = $s;
1353 if(! function_exists('info')) {
1355 * Show an info message to user.
1357 * This function save text in session, to be shown to the user at next page load
1359 * @param string $s - Text of notice
1364 if (local_user() AND get_pconfig(local_user(),'system','ignore_info'))
1367 if(! x($_SESSION,'sysmsg_info')) $_SESSION['sysmsg_info'] = array();
1369 $_SESSION['sysmsg_info'][] = $s;
1374 // wrapper around config to limit the text length of an incoming message
1376 if(! function_exists('get_max_import_size')) {
1377 function get_max_import_size() {
1379 return ((x($a->config,'max_import_size')) ? $a->config['max_import_size'] : 0 );
1387 * Function : profile_load
1389 * @parameter string $nickname
1390 * @parameter int $profile
1392 * Summary: Loads a profile into the page sidebar.
1393 * The function requires a writeable copy of the main App structure, and the nickname
1394 * of a registered local account.
1396 * If the viewer is an authenticated remote viewer, the profile displayed is the
1397 * one that has been configured for his/her viewing in the Contact manager.
1398 * Passing a non-zero profile ID can also allow a preview of a selected profile
1401 * Profile information is placed in the App structure for later retrieval.
1402 * Honours the owner's chosen theme for display.
1404 * IMPORTANT: Should only be run in the _init() functions of a module. That ensures that
1405 * the theme is chosen before the _init() function of a theme is run, which will usually
1406 * load a lot of theme-specific content
1410 if(! function_exists('profile_load')) {
1411 function profile_load(&$a, $nickname, $profile = 0, $profiledata = array()) {
1413 $user = q("SELECT `uid` FROM `user` WHERE `nickname` = '%s' LIMIT 1",
1417 if(!$user && count($user) && !count($profiledata)) {
1418 logger('profile error: ' . $a->query_string, LOGGER_DEBUG);
1419 notice( t('Requested account is not available.') . EOL );
1424 if(remote_user() && count($_SESSION['remote'])) {
1425 foreach($_SESSION['remote'] as $visitor) {
1426 if($visitor['uid'] == $user[0]['uid']) {
1427 $r = q("SELECT `profile-id` FROM `contact` WHERE `id` = %d LIMIT 1",
1428 intval($visitor['cid'])
1431 $profile = $r[0]['profile-id'];
1440 $profile_int = intval($profile);
1441 $r = q("SELECT `profile`.`uid` AS `profile_uid`, `profile`.* , `contact`.`avatar-date` AS picdate, `user`.* FROM `profile`
1442 INNER JOIN `contact` on `contact`.`uid` = `profile`.`uid` INNER JOIN `user` ON `profile`.`uid` = `user`.`uid`
1443 WHERE `user`.`nickname` = '%s' AND `profile`.`id` = %d and `contact`.`self` = 1 LIMIT 1",
1445 intval($profile_int)
1448 if((!$r) && (!count($r))) {
1449 $r = q("SELECT `profile`.`uid` AS `profile_uid`, `profile`.* , `contact`.`avatar-date` AS picdate, `user`.* FROM `profile`
1450 INNER JOIN `contact` on `contact`.`uid` = `profile`.`uid` INNER JOIN `user` ON `profile`.`uid` = `user`.`uid`
1451 WHERE `user`.`nickname` = '%s' AND `profile`.`is-default` = 1 and `contact`.`self` = 1 LIMIT 1",
1456 if(($r === false) || (!count($r)) && !count($profiledata)) {
1457 logger('profile error: ' . $a->query_string, LOGGER_DEBUG);
1458 notice( t('Requested profile is not available.') . EOL );
1463 // fetch user tags if this isn't the default profile
1465 if(!$r[0]['is-default']) {
1466 $x = q("select `pub_keywords` from `profile` where uid = %d and `is-default` = 1 limit 1",
1467 intval($r[0]['profile_uid'])
1470 $r[0]['pub_keywords'] = $x[0]['pub_keywords'];
1473 $a->profile = $r[0];
1475 $a->profile['mobile-theme'] = get_pconfig($a->profile['profile_uid'], 'system', 'mobile_theme');
1476 $a->profile['network'] = NETWORK_DFRN;
1478 $a->page['title'] = $a->profile['name'] . " @ " . $a->config['sitename'];
1481 $_SESSION['theme'] = $a->profile['theme'];
1483 $_SESSION['mobile-theme'] = $a->profile['mobile-theme'];
1486 * load/reload current theme info
1489 $a->set_template_engine(); // reset the template engine to the default in case the user's theme doesn't specify one
1491 $theme_info_file = "view/theme/".current_theme()."/theme.php";
1492 if (file_exists($theme_info_file)){
1493 require_once($theme_info_file);
1496 if(! (x($a->page,'aside')))
1497 $a->page['aside'] = '';
1499 if(local_user() && local_user() == $a->profile['uid'] && $profiledata) {
1500 $a->page['aside'] .= replace_macros(get_markup_template('profile_edlink.tpl'),array(
1501 '$editprofile' => t('Edit profile'),
1502 '$profid' => $a->profile['id']
1506 $block = (((get_config('system','block_public')) && (! local_user()) && (! remote_user())) ? true : false);
1509 // By now, the contact block isn't shown, when a different profile is given
1510 // But: When this profile was on the same server, then we could display the contacts
1512 $a->page['aside'] .= profile_sidebar($profiledata, true);
1514 $a->page['aside'] .= profile_sidebar($a->profile, $block);
1518 $a->page['aside'] .= contact_block();*/
1527 * Function: profile_sidebar
1529 * Formats a profile for display in the sidebar.
1530 * It is very difficult to templatise the HTML completely
1531 * because of all the conditional logic.
1533 * @parameter: array $profile
1535 * Returns HTML string stuitable for sidebar inclusion
1536 * Exceptions: Returns empty string if passed $profile is wrong type or not populated
1541 if(! function_exists('profile_sidebar')) {
1542 function profile_sidebar($profile, $block = 0) {
1550 if((! is_array($profile)) && (! count($profile)))
1553 $profile['picdate'] = urlencode($profile['picdate']);
1555 if (($profile['network'] != "") AND ($profile['network'] != NETWORK_DFRN)) {
1556 require_once('include/contact_selectors.php');
1557 if ($profile['url'] != "")
1558 $profile['network_name'] = '<a href="'.$profile['url'].'">'.network_to_name($profile['network'])."</a>";
1560 $profile['network_name'] = network_to_name($profile['network']);
1562 $profile['network_name'] = "";
1564 call_hooks('profile_sidebar_enter', $profile);
1567 // don't show connect link to yourself
1568 $connect = (($profile['uid'] != local_user()) ? t('Connect') : False);
1570 // don't show connect link to authenticated visitors either
1571 if(remote_user() && count($_SESSION['remote'])) {
1572 foreach($_SESSION['remote'] as $visitor) {
1573 if($visitor['uid'] == $profile['uid']) {
1580 // Is the local user already connected to that user?
1581 if ($connect AND local_user()) {
1582 if (isset($profile["url"]))
1583 $profile_url = normalise_link($profile["url"]);
1585 $profile_url = normalise_link($a->get_baseurl()."/profile/".$profile["nickname"]);
1587 $r = q("SELECT * FROM `contact` WHERE NOT `pending` AND `uid` = %d AND `nurl` = '%s'",
1588 local_user(), $profile_url);
1593 if ($connect AND ($profile['network'] != NETWORK_DFRN) AND !isset($profile['remoteconnect']))
1596 if (isset($profile['remoteconnect']))
1597 $remoteconnect = $profile['remoteconnect'];
1599 if( get_my_url() && $profile['unkmail'] && ($profile['uid'] != local_user()) )
1600 $wallmessage = t('Message');
1602 $wallmessage = false;
1604 // show edit profile to yourself
1605 if ($profile['uid'] == local_user() && feature_enabled(local_user(),'multi_profiles')) {
1606 $profile['edit'] = array($a->get_baseurl(). '/profiles', t('Profiles'),"", t('Manage/edit profiles'));
1607 $r = q("SELECT * FROM `profile` WHERE `uid` = %d",
1610 $profile['menu'] = array(
1611 'chg_photo' => t('Change profile photo'),
1612 'cr_new' => t('Create New Profile'),
1613 'entries' => array(),
1618 foreach($r as $rr) {
1619 $profile['menu']['entries'][] = array(
1620 'photo' => $rr['thumb'],
1622 'alt' => t('Profile Image'),
1623 'profile_name' => $rr['profile-name'],
1624 'isdefault' => $rr['is-default'],
1625 'visibile_to_everybody' => t('visible to everybody'),
1626 'edit_visibility' => t('Edit visibility'),
1634 if ($profile['uid'] == local_user() && !feature_enabled(local_user(),'multi_profiles')) {
1635 $profile['edit'] = array($a->get_baseurl(). '/profiles/'.$profile['id'], t('Edit profile'),"", t('Edit profile'));
1636 $profile['menu'] = array(
1637 'chg_photo' => t('Change profile photo'),
1639 'entries' => array(),
1643 if((x($profile,'address') == 1)
1644 || (x($profile,'locality') == 1)
1645 || (x($profile,'region') == 1)
1646 || (x($profile,'postal-code') == 1)
1647 || (x($profile,'country-name') == 1))
1648 $location = t('Location:');
1650 $gender = ((x($profile,'gender') == 1) ? t('Gender:') : False);
1653 $marital = ((x($profile,'marital') == 1) ? t('Status:') : False);
1655 $homepage = ((x($profile,'homepage') == 1) ? t('Homepage:') : False);
1657 $about = ((x($profile,'about') == 1) ? t('About:') : False);
1659 if(($profile['hidewall'] || $block) && (! local_user()) && (! remote_user())) {
1660 $location = $pdesc = $gender = $marital = $homepage = $about = False;
1663 $firstname = ((strpos($profile['name'],' '))
1664 ? trim(substr($profile['name'],0,strpos($profile['name'],' '))) : $profile['name']);
1665 $lastname = (($firstname === $profile['name']) ? '' : trim(substr($profile['name'],strlen($firstname))));
1668 'podloc' => $a->get_baseurl(),
1669 'searchable' => (($profile['publish'] && $profile['net-publish']) ? 'true' : 'false' ),
1670 'nickname' => $profile['nickname'],
1671 'fullname' => $profile['name'],
1672 'firstname' => $firstname,
1673 'lastname' => $lastname,
1674 'photo300' => $a->get_cached_avatar_image($a->get_baseurl() . '/photo/custom/300/' . $profile['uid'] . '.jpg'),
1675 'photo100' => $a->get_cached_avatar_image($a->get_baseurl() . '/photo/custom/100/' . $profile['uid'] . '.jpg'),
1676 'photo50' => $a->get_cached_avatar_image($a->get_baseurl() . '/photo/custom/50/' . $profile['uid'] . '.jpg'),
1680 $contact_block = contact_block();
1682 if(is_array($a->profile) AND !$a->profile['hide-friends']) {
1683 $r = q("SELECT COUNT(*) AS `total` FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 and `pending` = 0 AND `hidden` = 0 AND `archive` = 0
1684 AND `network` IN ('%s', '%s', '%s', '')",
1685 intval($profile['uid']),
1686 dbesc(NETWORK_DFRN),
1687 dbesc(NETWORK_DIASPORA),
1688 dbesc(NETWORK_OSTATUS)
1691 $contacts = intval($r[0]['total']);
1696 foreach($profile as $k => $v) {
1697 $k = str_replace('-','_',$k);
1701 if($a->theme['template_engine'] === 'internal')
1702 $location = template_escape($location);
1705 $tpl = get_markup_template('profile_vcard.tpl');
1706 $o .= replace_macros($tpl, array(
1708 '$connect' => $connect,
1709 '$remoteconnect' => $remoteconnect,
1710 '$wallmessage' => $wallmessage,
1711 '$location' => $location,
1712 '$gender' => $gender,
1714 '$marital' => $marital,
1715 '$homepage' => $homepage,
1717 '$network' => t('Network:'),
1718 '$contacts' => $contacts,
1719 '$diaspora' => $diaspora,
1720 '$contact_block' => $contact_block,
1724 $arr = array('profile' => &$profile, 'entry' => &$o);
1726 call_hooks('profile_sidebar', $arr);
1733 if(! function_exists('get_birthdays')) {
1734 function get_birthdays() {
1739 if(! local_user() || $a->is_mobile || $a->is_tablet)
1742 // $mobile_detect = new Mobile_Detect();
1743 // $is_mobile = $mobile_detect->isMobile() || $mobile_detect->isTablet();
1748 $bd_format = t('g A l F d') ; // 8 AM Friday January 18
1749 $bd_short = t('F d');
1751 $r = q("SELECT `event`.*, `event`.`id` AS `eid`, `contact`.* FROM `event`
1752 INNER JOIN `contact` ON `contact`.`id` = `event`.`cid`
1753 WHERE `event`.`uid` = %d AND `type` = 'birthday' AND `start` < '%s' AND `finish` > '%s'
1754 ORDER BY `start` ASC ",
1755 intval(local_user()),
1756 dbesc(datetime_convert('UTC','UTC','now + 6 days')),
1757 dbesc(datetime_convert('UTC','UTC','now'))
1760 if($r && count($r)) {
1762 $now = strtotime('now');
1766 foreach($r as $rr) {
1767 if(strlen($rr['name']))
1769 if((strtotime($rr['start'] . ' +00:00') < $now) && (strtotime($rr['finish'] . ' +00:00') > $now))
1772 $classtoday = $istoday ? ' birthday-today ' : '';
1774 foreach($r as &$rr) {
1775 if(! strlen($rr['name']))
1780 if(in_array($rr['cid'],$cids))
1782 $cids[] = $rr['cid'];
1784 $today = (((strtotime($rr['start'] . ' +00:00') < $now) && (strtotime($rr['finish'] . ' +00:00') > $now)) ? true : false);
1787 if($rr['network'] === NETWORK_DFRN) {
1788 $sparkle = " sparkle";
1789 $url = $a->get_baseurl() . '/redir/' . $rr['cid'];
1793 $rr['title'] = $rr['name'];
1794 $rr['date'] = day_translate(datetime_convert('UTC', $a->timezone, $rr['start'], $rr['adjust'] ? $bd_format : $bd_short)) . (($today) ? ' ' . t('[today]') : '');
1795 $rr['startime'] = Null;
1796 $rr['today'] = $today;
1801 $tpl = get_markup_template("birthdays_reminder.tpl");
1802 return replace_macros($tpl, array(
1803 '$baseurl' => $a->get_baseurl(),
1804 '$classtoday' => $classtoday,
1806 '$event_reminders' => t('Birthday Reminders'),
1807 '$event_title' => t('Birthdays this week:'),
1809 '$lbr' => '{', // raw brackets mess up if/endif macro processing
1817 if(! function_exists('get_events')) {
1818 function get_events() {
1820 require_once('include/bbcode.php');
1824 if(! local_user() || $a->is_mobile || $a->is_tablet)
1828 // $mobile_detect = new Mobile_Detect();
1829 // $is_mobile = $mobile_detect->isMobile() || $mobile_detect->isTablet();
1834 $bd_format = t('g A l F d') ; // 8 AM Friday January 18
1835 $bd_short = t('F d');
1837 $r = q("SELECT `event`.* FROM `event`
1838 WHERE `event`.`uid` = %d AND `type` != 'birthday' AND `start` < '%s' AND `start` > '%s'
1839 ORDER BY `start` ASC ",
1840 intval(local_user()),
1841 dbesc(datetime_convert('UTC','UTC','now + 6 days')),
1842 dbesc(datetime_convert('UTC','UTC','now - 1 days'))
1845 if($r && count($r)) {
1846 $now = strtotime('now');
1848 foreach($r as $rr) {
1849 if(strlen($rr['name']))
1852 $strt = datetime_convert('UTC',$rr['convert'] ? $a->timezone : 'UTC',$rr['start'],'Y-m-d');
1853 if($strt === datetime_convert('UTC',$a->timezone,'now','Y-m-d'))
1856 $classtoday = (($istoday) ? 'event-today' : '');
1859 foreach($r as &$rr) {
1861 $md = datetime_convert('UTC',$a->timezone,$rr['start'],'Y/m');
1863 $md = datetime_convert('UTC','UTC',$rr['start'],'Y/m');
1864 $md .= "/#link-".$rr['id'];
1866 $title = substr(strip_tags(bbcode($rr['desc'])),0,32) . '... ';
1868 $title = t('[No description]');
1870 $strt = datetime_convert('UTC',$rr['convert'] ? $a->timezone : 'UTC',$rr['start']);
1871 $today = ((substr($strt,0,10) === datetime_convert('UTC',$a->timezone,'now','Y-m-d')) ? true : false);
1874 $rr['title'] = $title;
1875 $rr['date'] = day_translate(datetime_convert('UTC', $rr['adjust'] ? $a->timezone : 'UTC', $rr['start'], $bd_format)) . (($today) ? ' ' . t('[today]') : '');
1876 $rr['startime'] = $strt;
1877 $rr['today'] = $today;
1881 $tpl = get_markup_template("events_reminder.tpl");
1882 return replace_macros($tpl, array(
1883 '$baseurl' => $a->get_baseurl(),
1884 '$classtoday' => $classtoday,
1885 '$count' => count($r),
1886 '$event_reminders' => t('Event Reminders'),
1887 '$event_title' => t('Events this week:'),
1896 * Wrap calls to proc_close(proc_open()) and call hook
1897 * so plugins can take part in process :)
1900 * $cmd program to run
1901 * next args are passed as $cmd command line
1903 * e.g.: proc_run("ls","-la","/tmp");
1905 * $cmd and string args are surrounded with ""
1908 if(! function_exists('proc_run')) {
1909 function proc_run($cmd){
1913 $args = func_get_args();
1919 // expand any arrays
1921 foreach($args as $arg) {
1922 if(is_array($arg)) {
1923 foreach($arg as $n) {
1933 $arr = array('args' => $args, 'run_cmd' => true);
1935 call_hooks("proc_run", $arr);
1936 if(! $arr['run_cmd'])
1939 if(count($args) && $args[0] === 'php')
1940 $args[0] = ((x($a->config,'php_path')) && (strlen($a->config['php_path'])) ? $a->config['php_path'] : 'php');
1942 // add baseurl to args. cli scripts can't construct it
1943 $args[] = $a->get_baseurl();
1945 for($x = 0; $x < count($args); $x ++)
1946 $args[$x] = escapeshellarg($args[$x]);
1950 $cmdline = implode($args," ");
1951 if(get_config('system','proc_windows'))
1952 proc_close(proc_open('cmd /c start /b ' . $cmdline,array(),$foo,dirname(__FILE__)));
1954 proc_close(proc_open($cmdline." &",array(),$foo,dirname(__FILE__)));
1958 if(! function_exists('current_theme')) {
1959 function current_theme(){
1960 $app_base_themes = array('duepuntozero', 'dispy', 'quattro');
1964 // $mobile_detect = new Mobile_Detect();
1965 // $is_mobile = $mobile_detect->isMobile() || $mobile_detect->isTablet();
1966 $is_mobile = $a->is_mobile || $a->is_tablet;
1969 if(isset($_SESSION['show-mobile']) && !$_SESSION['show-mobile']) {
1974 $system_theme = ((isset($a->config['system']['mobile-theme'])) ? $a->config['system']['mobile-theme'] : '');
1975 $theme_name = ((isset($_SESSION) && x($_SESSION,'mobile-theme')) ? $_SESSION['mobile-theme'] : $system_theme);
1977 if($theme_name === '---') {
1978 // user has selected to have the mobile theme be the same as the normal one
1984 if(!$is_mobile || ($system_theme === '' && $theme_name === '')) {
1985 $system_theme = ((isset($a->config['system']['theme'])) ? $a->config['system']['theme'] : '');
1986 $theme_name = ((isset($_SESSION) && x($_SESSION,'theme')) ? $_SESSION['theme'] : $system_theme);
1990 (file_exists('view/theme/' . $theme_name . '/style.css') ||
1991 file_exists('view/theme/' . $theme_name . '/style.php')))
1992 return($theme_name);
1994 foreach($app_base_themes as $t) {
1995 if(file_exists('view/theme/' . $t . '/style.css')||
1996 file_exists('view/theme/' . $t . '/style.php'))
2000 $fallback = array_merge(glob('view/theme/*/style.css'),glob('view/theme/*/style.php'));
2001 if(count($fallback))
2002 return (str_replace('view/theme/','', substr($fallback[0],0,-10)));
2008 * Return full URL to theme which is currently in effect.
2009 * Provide a sane default if nothing is chosen or the specified theme does not exist.
2011 if(! function_exists('current_theme_url')) {
2012 function current_theme_url() {
2014 $t = current_theme();
2015 if (file_exists('view/theme/' . $t . '/style.php'))
2016 return($a->get_baseurl() . '/view/theme/' . $t . '/style.pcss');
2017 return($a->get_baseurl() . '/view/theme/' . $t . '/style.css');
2021 if(! function_exists('feed_birthday')) {
2022 function feed_birthday($uid,$tz) {
2026 * Determine the next birthday, but only if the birthday is published
2027 * in the default profile. We _could_ also look for a private profile that the
2028 * recipient can see, but somebody could get mad at us if they start getting
2029 * public birthday greetings when they haven't made this info public.
2031 * Assuming we are able to publish this info, we are then going to convert
2032 * the start time from the owner's timezone to UTC.
2034 * This will potentially solve the problem found with some social networks
2035 * where birthdays are converted to the viewer's timezone and salutations from
2036 * elsewhere in the world show up on the wrong day. We will convert it to the
2037 * viewer's timezone also, but first we are going to convert it from the birthday
2038 * person's timezone to GMT - so the viewer may find the birthday starting at
2039 * 6:00PM the day before, but that will correspond to midnight to the birthday person.
2049 $p = q("SELECT `dob` FROM `profile` WHERE `is-default` = 1 AND `uid` = %d LIMIT 1",
2053 if($p && count($p)) {
2054 $tmp_dob = substr($p[0]['dob'],5);
2055 if(intval($tmp_dob)) {
2056 $y = datetime_convert($tz,$tz,'now','Y');
2057 $bd = $y . '-' . $tmp_dob . ' 00:00';
2058 $t_dob = strtotime($bd);
2059 $now = strtotime(datetime_convert($tz,$tz,'now'));
2061 $bd = $y + 1 . '-' . $tmp_dob . ' 00:00';
2062 $birthday = datetime_convert($tz,'UTC',$bd,ATOM_TIME);
2070 if(! function_exists('is_site_admin')) {
2071 function is_site_admin() {
2074 $adminlist = explode(",", str_replace(" ", "", $a->config['admin_email']));
2076 //if(local_user() && x($a->user,'email') && x($a->config,'admin_email') && ($a->user['email'] === $a->config['admin_email']))
2077 if(local_user() && x($a->user,'email') && x($a->config,'admin_email') && in_array($a->user['email'], $adminlist))
2084 if(! function_exists('load_contact_links')) {
2085 function load_contact_links($uid) {
2091 if(! $uid || x($a->contacts,'empty'))
2094 $r = q("SELECT `id`,`network`,`url`,`thumb` FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 AND `thumb` != ''",
2099 $url = normalise_link($rr['url']);
2104 $ret['empty'] = true;
2105 $a->contacts = $ret;
2110 if(! function_exists('profile_tabs')){
2111 function profile_tabs($a, $is_owner=False, $nickname=Null){
2112 //echo "<pre>"; var_dump($a->user); killme();
2114 if (is_null($nickname))
2115 $nickname = $a->user['nickname'];
2118 $tab = notags(trim($_GET['tab']));
2120 $url = $a->get_baseurl() . '/profile/' . $nickname;
2124 'label'=>t('Status'),
2126 'sel' => ((!isset($tab)&&$a->argv[0]=='profile')?'active':''),
2127 'title' => t('Status Messages and Posts'),
2128 'id' => 'status-tab',
2131 'label' => t('Profile'),
2132 'url' => $url.'/?tab=profile',
2133 'sel' => ((isset($tab) && $tab=='profile')?'active':''),
2134 'title' => t('Profile Details'),
2135 'id' => 'profile-tab',
2138 'label' => t('Photos'),
2139 'url' => $a->get_baseurl() . '/photos/' . $nickname,
2140 'sel' => ((!isset($tab)&&$a->argv[0]=='photos')?'active':''),
2141 'title' => t('Photo Albums'),
2142 'id' => 'photo-tab',
2145 'label' => t('Videos'),
2146 'url' => $a->get_baseurl() . '/videos/' . $nickname,
2147 'sel' => ((!isset($tab)&&$a->argv[0]=='videos')?'active':''),
2148 'title' => t('Videos'),
2149 'id' => 'video-tab',
2155 'label' => t('Events'),
2156 'url' => $a->get_baseurl() . '/events',
2157 'sel' =>((!isset($tab)&&$a->argv[0]=='events')?'active':''),
2158 'title' => t('Events and Calendar'),
2159 'id' => 'events-tab',
2162 'label' => t('Personal Notes'),
2163 'url' => $a->get_baseurl() . '/notes',
2164 'sel' =>((!isset($tab)&&$a->argv[0]=='notes')?'active':''),
2165 'title' => t('Only You Can See This'),
2166 'id' => 'notes-tab',
2171 $arr = array('is_owner' => $is_owner, 'nickname' => $nickname, 'tab' => (($tab) ? $tab : false), 'tabs' => $tabs);
2172 call_hooks('profile_tabs', $arr);
2174 $tpl = get_markup_template('common_tabs.tpl');
2176 return replace_macros($tpl,array('$tabs' => $arr['tabs']));
2180 function get_my_url() {
2181 if(x($_SESSION,'my_url'))
2182 return $_SESSION['my_url'];
2186 function zrl_init(&$a) {
2187 $tmp_str = get_my_url();
2188 if(validate_url($tmp_str)) {
2189 proc_run('php','include/gprobe.php',bin2hex($tmp_str));
2190 $arr = array('zrl' => $tmp_str, 'url' => $a->cmd);
2191 call_hooks('zrl_init',$arr);
2195 function zrl($s,$force = false) {
2198 if((! strpos($s,'/profile/')) && (! $force))
2200 if($force && substr($s,-1,1) !== '/')
2202 $achar = strpos($s,'?') ? '&' : '?';
2203 $mine = get_my_url();
2204 if($mine and ! link_compare($mine,$s))
2205 return $s . $achar . 'zrl=' . urlencode($mine);
2210 * returns querystring as string from a mapped array
2212 * @param params Array
2215 function build_querystring($params, $name=null) {
2217 foreach($params as $key=>$val) {
2218 if(is_array($val)) {
2220 $ret .= build_querystring($val, $key);
2222 $ret .= build_querystring($val, $name."[$key]");
2225 $val = urlencode($val);
2227 $ret.=$name."[$key]"."=$val&";
2229 $ret.= "$key=$val&";
2236 function explode_querystring($query) {
2237 $arg_st = strpos($query, '?');
2238 if($arg_st !== false) {
2239 $base = substr($query, 0, $arg_st);
2247 $args = explode('&', substr($query, $arg_st));
2248 foreach($args as $k=>$arg) {
2252 $args = array_values($args);
2257 $args = array_values($args);
2267 * Returns the complete URL of the current page, e.g.: http(s)://something.com/network
2269 * Taken from http://webcheatsheet.com/php/get_current_page_url.php
2271 function curPageURL() {
2273 if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
2275 if ($_SERVER["SERVER_PORT"] != "80" && $_SERVER["SERVER_PORT"] != "443") {
2276 $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
2278 $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
2283 function random_digits($digits) {
2285 for($i = 0; $i < $digits; $i++) {
2291 function get_cachefile($file, $writemode = true) {
2292 $cache = get_itemcachepath();
2294 if ((! $cache) || (! is_dir($cache)))
2297 $subfolder = $cache."/".substr($file, 0, 2);
2299 $cachepath = $subfolder."/".$file;
2302 if (!is_dir($subfolder)) {
2304 chmod($subfolder, 0777);
2311 function clear_cache($basepath = "", $path = "") {
2313 $basepath = get_itemcachepath();
2317 if (($path == "") OR (!is_dir($path)))
2320 if (substr(realpath($path), 0, strlen($basepath)) != $basepath)
2323 $cachetime = (int)get_config('system','itemcache_duration');
2324 if ($cachetime == 0)
2327 if (is_writable($path)){
2328 if ($dh = opendir($path)) {
2329 while (($file = readdir($dh)) !== false) {
2330 $fullpath = $path."/".$file;
2331 if ((filetype($fullpath) == "dir") and ($file != ".") and ($file != ".."))
2332 clear_cache($basepath, $fullpath);
2333 if ((filetype($fullpath) == "file") and (filectime($fullpath) < (time() - $cachetime)))
2341 function get_itemcachepath() {
2342 // Checking, if the cache is deactivated
2343 $cachetime = (int)get_config('system','itemcache_duration');
2347 $itemcache = get_config('system','itemcache');
2348 if (($itemcache != "") AND is_dir($itemcache) AND is_writable($itemcache))
2351 $temppath = get_temppath();
2353 if ($temppath != "") {
2354 $itemcache = $temppath."/itemcache";
2357 if (is_dir($itemcache) AND is_writable($itemcache)) {
2358 set_config("system", "itemcache", $itemcache);
2365 function get_lockpath() {
2366 $lockpath = get_config('system','lockpath');
2367 if (($lockpath != "") AND is_dir($lockpath) AND is_writable($lockpath))
2370 $temppath = get_temppath();
2372 if ($temppath != "") {
2373 $lockpath = $temppath."/lock";
2376 if (is_dir($lockpath) AND is_writable($lockpath)) {
2377 set_config("system", "lockpath", $lockpath);
2384 function get_temppath() {
2385 $temppath = get_config("system","temppath");
2386 if (($temppath != "") AND is_dir($temppath) AND is_writable($temppath))
2389 $temppath = sys_get_temp_dir();
2390 if (($temppath != "") AND is_dir($temppath) AND is_writable($temppath)) {
2391 set_config("system", "temppath", $temppath);
2398 function set_template_engine(&$a, $engine = 'internal') {
2399 // This function is no longer necessary, but keep it as a wrapper to the class method
2400 // to avoid breaking themes again unnecessarily
2402 $a->set_template_engine($engine);
2405 if(!function_exists('exif_imagetype')) {
2406 function exif_imagetype($file) {
2407 $size = getimagesize($file);