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', 1178 );
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 );
131 * Network and protocol family types
134 define ( 'NETWORK_DFRN', 'dfrn'); // Friendica, Mistpark, other DFRN implementations
135 define ( 'NETWORK_ZOT', 'zot!'); // Zot!
136 define ( 'NETWORK_OSTATUS', 'stat'); // status.net, identi.ca, GNU-social, other OStatus implementations
137 define ( 'NETWORK_FEED', 'feed'); // RSS/Atom feeds with no known "post/notify" protocol
138 define ( 'NETWORK_DIASPORA', 'dspr'); // Diaspora
139 define ( 'NETWORK_MAIL', 'mail'); // IMAP/POP
140 define ( 'NETWORK_MAIL2', 'mai2'); // extended IMAP/POP
141 define ( 'NETWORK_FACEBOOK', 'face'); // Facebook API
142 define ( 'NETWORK_LINKEDIN', 'lnkd'); // LinkedIn
143 define ( 'NETWORK_XMPP', 'xmpp'); // XMPP
144 define ( 'NETWORK_MYSPACE', 'mysp'); // MySpace
145 define ( 'NETWORK_GPLUS', 'goog'); // Google+
146 define ( 'NETWORK_PUMPIO', 'pump'); // pump.io
147 define ( 'NETWORK_TWITTER', 'twit'); // Twitter
148 define ( 'NETWORK_DIASPORA2', 'dspc'); // Diaspora connector
149 define ( 'NETWORK_STATUSNET', 'stac'); // Statusnet connector
150 define ( 'NETWORK_APPNET', 'apdn'); // app.net
152 define ( 'NETWORK_PHANTOM', 'unkn'); // Place holder
155 * These numbers are used in stored permissions
156 * and existing allocations MUST NEVER BE CHANGED
157 * OR RE-ASSIGNED! You may only add to them.
160 $netgroup_ids = array(
161 NETWORK_DFRN => (-1),
163 NETWORK_OSTATUS => (-3),
164 NETWORK_FEED => (-4),
165 NETWORK_DIASPORA => (-5),
166 NETWORK_MAIL => (-6),
167 NETWORK_MAIL2 => (-7),
168 NETWORK_FACEBOOK => (-8),
169 NETWORK_LINKEDIN => (-9),
170 NETWORK_XMPP => (-10),
171 NETWORK_MYSPACE => (-11),
172 NETWORK_GPLUS => (-12),
173 NETWORK_PUMPIO => (-13),
174 NETWORK_TWITTER => (-14),
175 NETWORK_DIASPORA2 => (-15),
176 NETWORK_STATUSNET => (-16),
177 NETWORK_APPNET => (-17),
179 NETWORK_PHANTOM => (-127),
184 * Maximum number of "people who like (or don't like) this" that we will list by name
187 define ( 'MAX_LIKERS', 75);
190 * Communication timeout
193 define ( 'ZCURL_TIMEOUT' , (-1));
197 * email notification options
200 define ( 'NOTIFY_INTRO', 0x0001 );
201 define ( 'NOTIFY_CONFIRM', 0x0002 );
202 define ( 'NOTIFY_WALL', 0x0004 );
203 define ( 'NOTIFY_COMMENT', 0x0008 );
204 define ( 'NOTIFY_MAIL', 0x0010 );
205 define ( 'NOTIFY_SUGGEST', 0x0020 );
206 define ( 'NOTIFY_PROFILE', 0x0040 );
207 define ( 'NOTIFY_TAGSELF', 0x0080 );
208 define ( 'NOTIFY_TAGSHARE', 0x0100 );
209 define ( 'NOTIFY_POKE', 0x0200 );
210 define ( 'NOTIFY_SHARE', 0x0400 );
212 define ( 'NOTIFY_SYSTEM', 0x8000 );
219 define ( 'TERM_UNKNOWN', 0 );
220 define ( 'TERM_HASHTAG', 1 );
221 define ( 'TERM_MENTION', 2 );
222 define ( 'TERM_CATEGORY', 3 );
223 define ( 'TERM_PCATEGORY', 4 );
224 define ( 'TERM_FILE', 5 );
225 define ( 'TERM_SAVEDSEARCH', 6 );
226 define ( 'TERM_CONVERSATION', 7 );
228 define ( 'TERM_OBJ_POST', 1 );
229 define ( 'TERM_OBJ_PHOTO', 2 );
234 * various namespaces we may need to parse
237 define ( 'NAMESPACE_ZOT', 'http://purl.org/zot' );
238 define ( 'NAMESPACE_DFRN' , 'http://purl.org/macgirvin/dfrn/1.0' );
239 define ( 'NAMESPACE_THREAD' , 'http://purl.org/syndication/thread/1.0' );
240 define ( 'NAMESPACE_TOMB' , 'http://purl.org/atompub/tombstones/1.0' );
241 define ( 'NAMESPACE_ACTIVITY', 'http://activitystrea.ms/spec/1.0/' );
242 define ( 'NAMESPACE_ACTIVITY_SCHEMA', 'http://activitystrea.ms/schema/1.0/' );
243 define ( 'NAMESPACE_MEDIA', 'http://purl.org/syndication/atommedia' );
244 define ( 'NAMESPACE_SALMON_ME', 'http://salmon-protocol.org/ns/magic-env' );
245 define ( 'NAMESPACE_OSTATUSSUB', 'http://ostatus.org/schema/1.0/subscribe' );
246 define ( 'NAMESPACE_GEORSS', 'http://www.georss.org/georss' );
247 define ( 'NAMESPACE_POCO', 'http://portablecontacts.net/spec/1.0' );
248 define ( 'NAMESPACE_FEED', 'http://schemas.google.com/g/2010#updates-from' );
249 define ( 'NAMESPACE_OSTATUS', 'http://ostatus.org/schema/1.0' );
250 define ( 'NAMESPACE_STATUSNET', 'http://status.net/schema/api/1/' );
251 define ( 'NAMESPACE_ATOM1', 'http://www.w3.org/2005/Atom' );
253 * activity stream defines
256 define ( 'ACTIVITY_LIKE', NAMESPACE_ACTIVITY_SCHEMA . 'like' );
257 define ( 'ACTIVITY_DISLIKE', NAMESPACE_DFRN . '/dislike' );
258 define ( 'ACTIVITY_OBJ_HEART', NAMESPACE_DFRN . '/heart' );
260 define ( 'ACTIVITY_FRIEND', NAMESPACE_ACTIVITY_SCHEMA . 'make-friend' );
261 define ( 'ACTIVITY_REQ_FRIEND', NAMESPACE_ACTIVITY_SCHEMA . 'request-friend' );
262 define ( 'ACTIVITY_UNFRIEND', NAMESPACE_ACTIVITY_SCHEMA . 'remove-friend' );
263 define ( 'ACTIVITY_FOLLOW', NAMESPACE_ACTIVITY_SCHEMA . 'follow' );
264 define ( 'ACTIVITY_UNFOLLOW', NAMESPACE_ACTIVITY_SCHEMA . 'stop-following' );
265 define ( 'ACTIVITY_JOIN', NAMESPACE_ACTIVITY_SCHEMA . 'join' );
267 define ( 'ACTIVITY_POST', NAMESPACE_ACTIVITY_SCHEMA . 'post' );
268 define ( 'ACTIVITY_UPDATE', NAMESPACE_ACTIVITY_SCHEMA . 'update' );
269 define ( 'ACTIVITY_TAG', NAMESPACE_ACTIVITY_SCHEMA . 'tag' );
270 define ( 'ACTIVITY_FAVORITE', NAMESPACE_ACTIVITY_SCHEMA . 'favorite' );
272 define ( 'ACTIVITY_POKE', NAMESPACE_ZOT . '/activity/poke' );
273 define ( 'ACTIVITY_MOOD', NAMESPACE_ZOT . '/activity/mood' );
275 define ( 'ACTIVITY_OBJ_BOOKMARK', NAMESPACE_ACTIVITY_SCHEMA . 'bookmark' );
276 define ( 'ACTIVITY_OBJ_COMMENT', NAMESPACE_ACTIVITY_SCHEMA . 'comment' );
277 define ( 'ACTIVITY_OBJ_NOTE', NAMESPACE_ACTIVITY_SCHEMA . 'note' );
278 define ( 'ACTIVITY_OBJ_PERSON', NAMESPACE_ACTIVITY_SCHEMA . 'person' );
279 define ( 'ACTIVITY_OBJ_IMAGE', NAMESPACE_ACTIVITY_SCHEMA . 'image' );
280 define ( 'ACTIVITY_OBJ_PHOTO', NAMESPACE_ACTIVITY_SCHEMA . 'photo' );
281 define ( 'ACTIVITY_OBJ_VIDEO', NAMESPACE_ACTIVITY_SCHEMA . 'video' );
282 define ( 'ACTIVITY_OBJ_P_PHOTO', NAMESPACE_ACTIVITY_SCHEMA . 'profile-photo' );
283 define ( 'ACTIVITY_OBJ_ALBUM', NAMESPACE_ACTIVITY_SCHEMA . 'photo-album' );
284 define ( 'ACTIVITY_OBJ_EVENT', NAMESPACE_ACTIVITY_SCHEMA . 'event' );
285 define ( 'ACTIVITY_OBJ_GROUP', NAMESPACE_ACTIVITY_SCHEMA . 'group' );
286 define ( 'ACTIVITY_OBJ_TAGTERM', NAMESPACE_DFRN . '/tagterm' );
287 define ( 'ACTIVITY_OBJ_PROFILE', NAMESPACE_DFRN . '/profile' );
290 * item weight for query ordering
293 define ( 'GRAVITY_PARENT', 0);
294 define ( 'GRAVITY_LIKE', 3);
295 define ( 'GRAVITY_COMMENT', 6);
299 * Reverse the effect of magic_quotes_gpc if it is enabled.
300 * Please disable magic_quotes_gpc so we don't have to do this.
301 * See http://php.net/manual/en/security.magicquotes.disabling.php
307 error_reporting(E_ERROR | E_WARNING | E_PARSE);
311 // This has to be quite large to deal with embedded private photos
312 ini_set('pcre.backtrack_limit', 500000);
315 if (get_magic_quotes_gpc()) {
316 $process = array(&$_GET, &$_POST, &$_COOKIE, &$_REQUEST);
317 while (list($key, $val) = each($process)) {
318 foreach ($val as $k => $v) {
319 unset($process[$key][$k]);
321 $process[$key][stripslashes($k)] = $v;
322 $process[] = &$process[$key][stripslashes($k)];
324 $process[$key][stripslashes($k)] = stripslashes($v);
337 * Our main application structure for the life of this page
338 * Primarily deals with the URL that got us here
339 * and tries to make some sense of it, and
340 * stores our page contents and config storage
341 * and anything else that might need to be passed around
342 * before we spit the page out.
346 if(! class_exists('App')) {
349 public $module_loaded = false;
350 public $query_string;
358 public $page_contact;
360 public $data = array();
361 public $error = false;
371 public $interactive = true;
373 public $apps = array();
377 public $performance = array();
384 // Allow themes to control internal parameters
385 // by changing App values in theme.php
387 public $sourcename = '';
388 public $videowidth = 425;
389 public $videoheight = 350;
390 public $force_max_items = 0;
391 public $theme_thread_allow = true;
393 // An array for all theme-controllable parameters
394 // Mostly unimplemented yet. Only options 'stylesheet' and
397 public $theme = array(
400 'videoheight' => 350,
401 'force_max_items' => 0,
402 'thread_allow' => true,
404 'template_engine' => 'smarty3',
407 // array of registered template engines ('name'=>'class name')
408 public $template_engines = array();
409 // array of instanced template engines ('name'=>'instance')
410 public $template_engine_instance = array();
412 // Used for reducing load to the ostatus completion
413 public $last_ostatus_conversation_url;
415 private $ldelim = array(
419 private $rdelim = array(
430 private $curl_content_type;
431 private $curl_headers;
433 private $cached_profile_image;
434 private $cached_profile_picdate;
436 function __construct() {
438 global $default_timezone;
442 if (file_exists(".htpreconfig.php"))
443 @include(".htpreconfig.php");
445 $this->timezone = ((x($default_timezone)) ? $default_timezone : 'UTC');
447 date_default_timezone_set($this->timezone);
449 $this->performance["start"] = microtime(true);
450 $this->performance["database"] = 0;
451 $this->performance["network"] = 0;
452 $this->performance["file"] = 0;
453 $this->performance["rendering"] = 0;
454 $this->performance["parser"] = 0;
455 $this->performance["marktime"] = 0;
456 $this->performance["markstart"] = microtime(true);
458 $this->config = array();
459 $this->page = array();
460 $this->pager= array();
462 $this->query_string = '';
467 'include' . PATH_SEPARATOR
468 . 'library' . PATH_SEPARATOR
469 . 'library/phpsec' . PATH_SEPARATOR
470 . 'library/langdet' . PATH_SEPARATOR
474 $this->scheme = 'http';
475 if(x($_SERVER,'HTTPS') && $_SERVER['HTTPS'])
476 $this->scheme = 'https';
477 elseif(x($_SERVER,'SERVER_PORT') && (intval($_SERVER['SERVER_PORT']) == 443))
478 $this->scheme = 'https';
480 if(x($_SERVER,'SERVER_NAME')) {
481 $this->hostname = $_SERVER['SERVER_NAME'];
483 // See bug 437 - this didn't work so disabling it
484 //if(stristr($this->hostname,'xn--')) {
485 // PHP or webserver may have converted idn to punycode, so
486 // convert punycode back to utf-8
487 // require_once('library/simplepie/idn/idna_convert.class.php');
488 // $x = new idna_convert();
489 // $this->hostname = $x->decode($_SERVER['SERVER_NAME']);
492 if(x($_SERVER,'SERVER_PORT') && $_SERVER['SERVER_PORT'] != 80 && $_SERVER['SERVER_PORT'] != 443)
493 $this->hostname .= ':' . $_SERVER['SERVER_PORT'];
495 * Figure out if we are running at the top of a domain
496 * or in a sub-directory and adjust accordingly
499 $path = trim(dirname($_SERVER['SCRIPT_NAME']),'/\\');
500 if(isset($path) && strlen($path) && ($path != $this->path))
505 $this->hostname = $hostname;
507 if (is_array($_SERVER["argv"]) && $_SERVER["argc"]>1 && substr(end($_SERVER["argv"]), 0, 4)=="http" ) {
508 $this->set_baseurl(array_pop($_SERVER["argv"]) );
512 #set_include_path("include/$this->hostname" . PATH_SEPARATOR . get_include_path());
514 if((x($_SERVER,'QUERY_STRING')) && substr($_SERVER['QUERY_STRING'],0,9) === "pagename=") {
515 $this->query_string = substr($_SERVER['QUERY_STRING'],9);
516 // removing trailing / - maybe a nginx problem
517 if (substr($this->query_string, 0, 1) == "/")
518 $this->query_string = substr($this->query_string, 1);
519 } elseif((x($_SERVER,'QUERY_STRING')) && substr($_SERVER['QUERY_STRING'],0,2) === "q=") {
520 $this->query_string = substr($_SERVER['QUERY_STRING'],2);
521 // removing trailing / - maybe a nginx problem
522 if (substr($this->query_string, 0, 1) == "/")
523 $this->query_string = substr($this->query_string, 1);
526 if (x($_GET,'pagename'))
527 $this->cmd = trim($_GET['pagename'],'/\\');
528 elseif (x($_GET,'q'))
529 $this->cmd = trim($_GET['q'],'/\\');
533 $this->query_string = str_replace($this->cmd."&",$this->cmd."?", $this->query_string);
536 // unix style "homedir"
538 if(substr($this->cmd,0,1) === '~')
539 $this->cmd = 'profile/' . substr($this->cmd,1);
541 // Diaspora style profile url
543 if(substr($this->cmd,0,2) === 'u/')
544 $this->cmd = 'profile/' . substr($this->cmd,2);
549 * Break the URL path into C style argc/argv style arguments for our
550 * modules. Given "http://example.com/module/arg1/arg2", $this->argc
551 * will be 3 (integer) and $this->argv will contain:
557 * There will always be one argument. If provided a naked domain
558 * URL, $this->argv[0] is set to "home".
562 $this->argv = explode('/',$this->cmd);
563 $this->argc = count($this->argv);
564 if((array_key_exists('0',$this->argv)) && strlen($this->argv[0])) {
565 $this->module = str_replace(".", "_", $this->argv[0]);
566 $this->module = str_replace("-", "_", $this->module);
570 $this->argv = array('home');
571 $this->module = 'home';
575 * See if there is any page number information, and initialise
579 $this->pager['page'] = ((x($_GET,'page') && intval($_GET['page']) > 0) ? intval($_GET['page']) : 1);
580 $this->pager['itemspage'] = 50;
581 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
582 if($this->pager['start'] < 0)
583 $this->pager['start'] = 0;
584 $this->pager['total'] = 0;
587 * Detect mobile devices
590 $mobile_detect = new Mobile_Detect();
591 $this->is_mobile = $mobile_detect->isMobile();
592 $this->is_tablet = $mobile_detect->isTablet();
595 * register template engines
597 $dc = get_declared_classes();
598 foreach ($dc as $k) {
599 if (in_array("ITemplateEngine", class_implements($k))){
600 $this->register_template_engine($k);
606 function get_basepath() {
608 $basepath = get_config("system", "basepath");
611 $basepath = $_SERVER["DOCUMENT_ROOT"];
614 $basepath = $_SERVER["PWD"];
619 function get_scheme() {
620 return($this->scheme);
623 function get_baseurl($ssl = false) {
625 $scheme = $this->scheme;
627 if((x($this->config,'system')) && (x($this->config['system'],'ssl_policy'))) {
628 if(intval($this->config['system']['ssl_policy']) === intval(SSL_POLICY_FULL))
631 // Basically, we have $ssl = true on any links which can only be seen by a logged in user
632 // (and also the login link). Anything seen by an outsider will have it turned off.
634 if($this->config['system']['ssl_policy'] == SSL_POLICY_SELFSIGN) {
642 if (get_config('config','hostname') != "")
643 $this->hostname = get_config('config','hostname');
645 $this->baseurl = $scheme . "://" . $this->hostname . ((isset($this->path) && strlen($this->path)) ? '/' . $this->path : '' );
646 return $this->baseurl;
649 function set_baseurl($url) {
650 $parsed = @parse_url($url);
652 $this->baseurl = $url;
655 $this->scheme = $parsed['scheme'];
657 $hostname = $parsed['host'];
658 if(x($parsed,'port'))
659 $hostname .= ':' . $parsed['port'];
660 if(x($parsed,'path'))
661 $this->path = trim($parsed['path'],'\\/');
663 if (file_exists(".htpreconfig.php"))
664 @include(".htpreconfig.php");
666 if (get_config('config','hostname') != "")
667 $this->hostname = get_config('config','hostname');
669 if (!isset($this->hostname) OR ($this->hostname == ""))
670 $this->hostname = $hostname;
675 function get_hostname() {
676 if (get_config('config','hostname') != "")
677 $this->hostname = get_config('config','hostname');
679 return $this->hostname;
682 function set_hostname($h) {
683 $this->hostname = $h;
686 function set_path($p) {
687 $this->path = trim(trim($p),'/');
690 function get_path() {
694 function set_pager_total($n) {
695 $this->pager['total'] = intval($n);
698 function set_pager_itemspage($n) {
699 $this->pager['itemspage'] = ((intval($n) > 0) ? intval($n) : 0);
700 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
703 function set_pager_page($n) {
704 $this->pager['page'] = $n;
705 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
708 function init_pagehead() {
709 $interval = ((local_user()) ? get_pconfig(local_user(),'system','update_interval') : 40000);
710 if($interval < 10000)
713 $this->page['title'] = $this->config['sitename'];
715 /* put the head template at the beginning of page['htmlhead']
716 * since the code added by the modules frequently depends on it
719 if(!isset($this->page['htmlhead']))
720 $this->page['htmlhead'] = '';
722 // If we're using Smarty, then doing replace_macros() will replace
723 // any unrecognized variables with a blank string. Since we delay
724 // replacing $stylesheet until later, we need to replace it now
725 // with another variable name
726 if($this->theme['template_engine'] === 'smarty3')
727 $stylesheet = $this->get_template_ldelim('smarty3') . '$stylesheet' . $this->get_template_rdelim('smarty3');
729 $stylesheet = '$stylesheet';
731 $shortcut_icon = get_config("system", "shortcut_icon");
732 if ($shortcut_icon == "")
733 $shortcut_icon = $this->get_baseurl()."/images/friendica-32.png";
735 $touch_icon = get_config("system", "touch_icon");
736 if ($touch_icon == "")
737 $touch_icon = $this->get_baseurl()."/images/friendica-128.png";
739 $tpl = get_markup_template('head.tpl');
740 $this->page['htmlhead'] = replace_macros($tpl,array(
741 '$baseurl' => $this->get_baseurl(), // FIXME for z_path!!!!
742 '$local_user' => local_user(),
743 '$generator' => 'Friendica' . ' ' . FRIENDICA_VERSION,
744 '$delitem' => t('Delete this item?'),
745 '$comment' => t('Comment'),
746 '$showmore' => t('show more'),
747 '$showfewer' => t('show fewer'),
748 '$update_interval' => $interval,
749 '$shortcut_icon' => $shortcut_icon,
750 '$touch_icon' => $touch_icon,
751 '$stylesheet' => $stylesheet
752 )) . $this->page['htmlhead'];
755 function init_page_end() {
756 if(!isset($this->page['end']))
757 $this->page['end'] = '';
758 $tpl = get_markup_template('end.tpl');
759 $this->page['end'] = replace_macros($tpl,array(
760 '$baseurl' => $this->get_baseurl() // FIXME for z_path!!!!
761 )) . $this->page['end'];
764 function set_curl_code($code) {
765 $this->curl_code = $code;
768 function get_curl_code() {
769 return $this->curl_code;
772 function set_curl_content_type($content_type) {
773 $this->curl_content_type = $content_type;
776 function get_curl_content_type() {
777 return $this->curl_content_type;
780 function set_curl_headers($headers) {
781 $this->curl_headers = $headers;
784 function get_curl_headers() {
785 return $this->curl_headers;
788 function get_cached_avatar_image($avatar_image){
789 if($this->cached_profile_image[$avatar_image])
790 return $this->cached_profile_image[$avatar_image];
792 $path_parts = explode("/",$avatar_image);
793 $common_filename = $path_parts[count($path_parts)-1];
795 if($this->cached_profile_picdate[$common_filename]){
796 $this->cached_profile_image[$avatar_image] = $avatar_image . $this->cached_profile_picdate[$common_filename];
798 $r = q("SELECT `contact`.`avatar-date` AS picdate FROM `contact` WHERE `contact`.`thumb` like '%%/%s'",
801 $this->cached_profile_image[$avatar_image] = $avatar_image;
803 $this->cached_profile_picdate[$common_filename] = "?rev=".urlencode($r[0]['picdate']);
804 $this->cached_profile_image[$avatar_image] = $avatar_image.$this->cached_profile_picdate[$common_filename];
807 return $this->cached_profile_image[$avatar_image];
812 * register template engine class
813 * if $name is "", is used class static property $class::$name
814 * @param string $class
815 * @param string $name
817 function register_template_engine($class, $name = '') {
819 $v = get_class_vars( $class );
820 if(x($v,"name")) $name = $v['name'];
823 echo "template engine <tt>$class</tt> cannot be registered without a name.\n";
826 $this->template_engines[$name] = $class;
830 * return template engine instance. If $name is not defined,
831 * return engine defined by theme, or default
833 * @param strin $name Template engine name
834 * @return object Template Engine instance
836 function template_engine($name = ''){
838 $template_engine = $name;
840 $template_engine = 'smarty3';
841 if (x($this->theme, 'template_engine')) {
842 $template_engine = $this->theme['template_engine'];
846 if (isset($this->template_engines[$template_engine])){
847 if(isset($this->template_engine_instance[$template_engine])){
848 return $this->template_engine_instance[$template_engine];
850 $class = $this->template_engines[$template_engine];
852 $this->template_engine_instance[$template_engine] = $obj;
857 echo "template engine <tt>$template_engine</tt> is not registered!\n"; killme();
860 function get_template_engine() {
861 return $this->theme['template_engine'];
864 function set_template_engine($engine = 'smarty3') {
865 $this->theme['template_engine'] = $engine;
867 $this->theme['template_engine'] = 'smarty3';
871 if(is_writable('view/smarty3/'))
872 $this->theme['template_engine'] = 'smarty3';
880 function get_template_ldelim($engine = 'smarty3') {
881 return $this->ldelim[$engine];
884 function get_template_rdelim($engine = 'smarty3') {
885 return $this->rdelim[$engine];
888 function save_timestamp($stamp, $value) {
889 $duration = (float)(microtime(true)-$stamp);
891 $this->performance[$value] += (float)$duration;
892 $this->performance["marktime"] += (float)$duration;
895 function mark_timestamp($mark) {
896 //$this->performance["markstart"] -= microtime(true) - $this->performance["marktime"];
897 $this->performance["markstart"] = microtime(true) - $this->performance["markstart"] - $this->performance["marktime"];
900 function get_useragent() {
901 return(FRIENDICA_PLATFORM." '".FRIENDICA_CODENAME."' ".FRIENDICA_VERSION."-".DB_UPDATE_VERSION."; ".$this->get_baseurl());
907 // retrieve the App structure
908 // useful in functions which require it but don't get it passed to them
910 if(! function_exists('get_app')) {
918 // Multi-purpose function to check variable state.
919 // Usage: x($var) or $x($array,'key')
920 // returns false if variable/key is not set
921 // if variable is set, returns 1 if has 'non-zero' value, otherwise returns 0.
922 // e.g. x('') or x(0) returns 0;
924 if(! function_exists('x')) {
925 function x($s,$k = NULL) {
927 if((is_array($s)) && (array_key_exists($k,$s))) {
946 // called from db initialisation if db is dead.
948 if(! function_exists('system_unavailable')) {
949 function system_unavailable() {
950 include('system_unavailable.php');
958 function clean_urls() {
960 // if($a->config['system']['clean_urls'])
967 $base = $a->get_baseurl();
975 return $a->get_baseurl();
978 function absurl($path) {
979 if(strpos($path,'/') === 0)
980 return z_path() . $path;
985 return (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');
988 function check_db() {
990 $build = get_config('system','build');
992 set_config('system','build',DB_UPDATE_VERSION);
993 $build = DB_UPDATE_VERSION;
995 if($build != DB_UPDATE_VERSION)
996 proc_run('php', 'include/dbupdate.php');
1003 // Sets the base url for use in cmdline programs which don't have
1004 // $_SERVER variables
1006 if(! function_exists('check_url')) {
1007 function check_url(&$a) {
1009 $url = get_config('system','url');
1011 // if the url isn't set or the stored url is radically different
1012 // than the currently visited url, store the current value accordingly.
1013 // "Radically different" ignores common variations such as http vs https
1014 // and www.example.com vs example.com.
1015 // We will only change the url to an ip address if there is no existing setting
1018 $url = set_config('system','url',$a->get_baseurl());
1019 if((! link_compare($url,$a->get_baseurl())) && (! preg_match("/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/",$a->get_hostname)))
1020 $url = set_config('system','url',$a->get_baseurl());
1027 // Automatic database updates
1029 if(! function_exists('update_db')) {
1030 function update_db(&$a) {
1031 $build = get_config('system','build');
1033 $build = set_config('system','build',DB_UPDATE_VERSION);
1035 if($build != DB_UPDATE_VERSION) {
1036 $stored = intval($build);
1037 $current = intval(DB_UPDATE_VERSION);
1038 if($stored < $current) {
1039 load_config('database');
1041 // We're reporting a different version than what is currently installed.
1042 // Run any existing update scripts to bring the database up to current.
1044 // make sure that boot.php and update.php are the same release, we might be
1045 // updating right this very second and the correct version of the update.php
1046 // file may not be here yet. This can happen on a very busy site.
1048 if(DB_UPDATE_VERSION == UPDATE_VERSION) {
1049 // Compare the current structure with the defined structure
1051 $t = get_config('database','dbupdate_'.DB_UPDATE_VERSION);
1055 set_config('database','dbupdate_'.DB_UPDATE_VERSION, time());
1057 // run old update routine (wich could modify the schema and
1058 // conflits with new routine)
1059 for ($x = $stored; $x < NEW_UPDATE_ROUTINE_VERSION; $x++) {
1060 $r = run_update_function($x);
1063 if ($stored < NEW_UPDATE_ROUTINE_VERSION) $stored = NEW_UPDATE_ROUTINE_VERSION;
1066 // run new update routine
1067 // it update the structure in one call
1068 $retval = update_structure(false, true);
1076 set_config('database','dbupdate_'.DB_UPDATE_VERSION, 'success');
1079 // run any left update_nnnn functions in update.php
1080 for($x = $stored; $x < $current; $x ++) {
1081 $r = run_update_function($x);
1091 if(!function_exists('run_update_function')){
1092 function run_update_function($x) {
1093 if(function_exists('update_' . $x)) {
1095 // There could be a lot of processes running or about to run.
1096 // We want exactly one process to run the update command.
1097 // So store the fact that we're taking responsibility
1098 // after first checking to see if somebody else already has.
1100 // If the update fails or times-out completely you may need to
1101 // delete the config entry to try again.
1103 $t = get_config('database','update_' . $x);
1106 set_config('database','update_' . $x, time());
1108 // call the specific update
1110 $func = 'update_' . $x;
1114 //send the administrator an e-mail
1117 sprintf(t('Update %s failed. See error logs.'), $x)
1121 set_config('database','update_' . $x, 'success');
1122 set_config('system','build', $x + 1);
1126 set_config('database','update_' . $x, 'success');
1127 set_config('system','build', $x + 1);
1135 if(! function_exists('check_plugins')) {
1136 function check_plugins(&$a) {
1140 * Synchronise plugins:
1142 * $a->config['system']['addon'] contains a comma-separated list of names
1143 * of plugins/addons which are used on this system.
1144 * Go through the database list of already installed addons, and if we have
1145 * an entry, but it isn't in the config list, call the uninstall procedure
1146 * and mark it uninstalled in the database (for now we'll remove it).
1147 * Then go through the config list and if we have a plugin that isn't installed,
1148 * call the install procedure and add it to the database.
1152 $r = q("SELECT * FROM `addon` WHERE `installed` = 1");
1156 $installed = array();
1158 $plugins = get_config('system','addon');
1159 $plugins_arr = array();
1162 $plugins_arr = explode(',',str_replace(' ', '',$plugins));
1164 $a->plugins = $plugins_arr;
1166 $installed_arr = array();
1168 if(count($installed)) {
1169 foreach($installed as $i) {
1170 if(! in_array($i['name'],$plugins_arr)) {
1171 uninstall_plugin($i['name']);
1174 $installed_arr[] = $i['name'];
1179 if(count($plugins_arr)) {
1180 foreach($plugins_arr as $p) {
1181 if(! in_array($p,$installed_arr)) {
1194 function get_guid($size=16) {
1195 $exists = true; // assume by default that we don't have a unique guid
1198 while (strlen($prefix) < ($size - 13))
1199 $prefix .= mt_rand();
1201 $s = substr(uniqid($prefix), -$size);
1203 $r = q("select id from guid where guid = '%s' limit 1", dbesc($s));
1207 q("insert into guid (guid) values ('%s') ", dbesc($s));
1211 /*function get_guid($size=16) {
1212 $exists = true; // assume by default that we don't have a unique guid
1214 $s = random_string($size);
1215 $r = q("select id from guid where guid = '%s' limit 1", dbesc($s));
1219 q("insert into guid ( guid ) values ( '%s' ) ", dbesc($s));
1224 // wrapper for adding a login box. If $register == true provide a registration
1225 // link. This will most always depend on the value of $a->config['register_policy'].
1226 // returns the complete html for inserting into the page
1228 if(! function_exists('login')) {
1229 function login($register = false, $hiddens=false) {
1235 'title' => t('Create a New Account'),
1236 'desc' => t('Register')
1240 $noid = get_config('system','no_openid');
1242 $dest_url = $a->get_baseurl(true) . '/' . $a->query_string;
1245 $tpl = get_markup_template("logout.tpl");
1248 $a->page['htmlhead'] .= replace_macros(get_markup_template("login_head.tpl"),array(
1249 '$baseurl' => $a->get_baseurl(true)
1252 $tpl = get_markup_template("login.tpl");
1253 $_SESSION['return_url'] = $a->query_string;
1254 $a->module = 'login';
1257 $o .= replace_macros($tpl, array(
1259 '$dest_url' => $dest_url,
1260 '$logout' => t('Logout'),
1261 '$login' => t('Login'),
1263 '$lname' => array('username', t('Nickname or Email address: ') , '', ''),
1264 '$lpassword' => array('password', t('Password: '), '', ''),
1265 '$lremember' => array('remember', t('Remember me'), 0, ''),
1267 '$openid' => !$noid,
1268 '$lopenid' => array('openid_url', t('Or login using OpenID: '),'',''),
1270 '$hiddens' => $hiddens,
1272 '$register' => $reg,
1274 '$lostpass' => t('Forgot your password?'),
1275 '$lostlink' => t('Password Reset'),
1277 '$tostitle' => t('Website Terms of Service'),
1278 '$toslink' => t('terms of service'),
1280 '$privacytitle' => t('Website Privacy Policy'),
1281 '$privacylink' => t('privacy policy'),
1285 call_hooks('login_hook',$o);
1291 // Used to end the current process, after saving session state.
1293 if(! function_exists('killme')) {
1295 session_write_close();
1300 // redirect to another URL and terminate this process.
1302 if(! function_exists('goaway')) {
1303 function goaway($s) {
1304 header("Location: $s");
1310 // Returns the uid of locally logged in user or false.
1312 if(! function_exists('local_user')) {
1313 function local_user() {
1314 if((x($_SESSION,'authenticated')) && (x($_SESSION,'uid')))
1315 return intval($_SESSION['uid']);
1320 // Returns contact id of authenticated site visitor or false
1322 if(! function_exists('remote_user')) {
1323 function remote_user() {
1324 if((x($_SESSION,'authenticated')) && (x($_SESSION,'visitor_id')))
1325 return intval($_SESSION['visitor_id']);
1330 // contents of $s are displayed prominently on the page the next time
1331 // a page is loaded. Usually used for errors or alerts.
1333 if(! function_exists('notice')) {
1335 * Show an error message to user.
1337 * This function save text in session, to be shown to the user at next page load
1339 * @param string $s - Text of notice
1341 function notice($s) {
1343 if(! x($_SESSION,'sysmsg')) $_SESSION['sysmsg'] = array();
1345 $_SESSION['sysmsg'][] = $s;
1348 if(! function_exists('info')) {
1350 * Show an info message to user.
1352 * This function save text in session, to be shown to the user at next page load
1354 * @param string $s - Text of notice
1359 if (local_user() AND get_pconfig(local_user(),'system','ignore_info'))
1362 if(! x($_SESSION,'sysmsg_info')) $_SESSION['sysmsg_info'] = array();
1364 $_SESSION['sysmsg_info'][] = $s;
1369 // wrapper around config to limit the text length of an incoming message
1371 if(! function_exists('get_max_import_size')) {
1372 function get_max_import_size() {
1374 return ((x($a->config,'max_import_size')) ? $a->config['max_import_size'] : 0 );
1382 * Function : profile_load
1384 * @parameter string $nickname
1385 * @parameter int $profile
1387 * Summary: Loads a profile into the page sidebar.
1388 * The function requires a writeable copy of the main App structure, and the nickname
1389 * of a registered local account.
1391 * If the viewer is an authenticated remote viewer, the profile displayed is the
1392 * one that has been configured for his/her viewing in the Contact manager.
1393 * Passing a non-zero profile ID can also allow a preview of a selected profile
1396 * Profile information is placed in the App structure for later retrieval.
1397 * Honours the owner's chosen theme for display.
1399 * IMPORTANT: Should only be run in the _init() functions of a module. That ensures that
1400 * the theme is chosen before the _init() function of a theme is run, which will usually
1401 * load a lot of theme-specific content
1405 if(! function_exists('profile_load')) {
1406 function profile_load(&$a, $nickname, $profile = 0, $profiledata = array()) {
1408 $user = q("SELECT `uid` FROM `user` WHERE `nickname` = '%s' LIMIT 1",
1412 if(!$user && count($user) && !count($profiledata)) {
1413 logger('profile error: ' . $a->query_string, LOGGER_DEBUG);
1414 notice( t('Requested account is not available.') . EOL );
1419 if(remote_user() && count($_SESSION['remote'])) {
1420 foreach($_SESSION['remote'] as $visitor) {
1421 if($visitor['uid'] == $user[0]['uid']) {
1422 $r = q("SELECT `profile-id` FROM `contact` WHERE `id` = %d LIMIT 1",
1423 intval($visitor['cid'])
1426 $profile = $r[0]['profile-id'];
1435 $profile_int = intval($profile);
1436 $r = q("SELECT `profile`.`uid` AS `profile_uid`, `profile`.* , `contact`.`avatar-date` AS picdate, `user`.* FROM `profile`
1437 INNER JOIN `contact` on `contact`.`uid` = `profile`.`uid` INNER JOIN `user` ON `profile`.`uid` = `user`.`uid`
1438 WHERE `user`.`nickname` = '%s' AND `profile`.`id` = %d and `contact`.`self` = 1 LIMIT 1",
1440 intval($profile_int)
1443 if((!$r) && (!count($r))) {
1444 $r = q("SELECT `profile`.`uid` AS `profile_uid`, `profile`.* , `contact`.`avatar-date` AS picdate, `user`.* FROM `profile`
1445 INNER JOIN `contact` on `contact`.`uid` = `profile`.`uid` INNER JOIN `user` ON `profile`.`uid` = `user`.`uid`
1446 WHERE `user`.`nickname` = '%s' AND `profile`.`is-default` = 1 and `contact`.`self` = 1 LIMIT 1",
1451 if(($r === false) || (!count($r)) && !count($profiledata)) {
1452 logger('profile error: ' . $a->query_string, LOGGER_DEBUG);
1453 notice( t('Requested profile is not available.') . EOL );
1458 // fetch user tags if this isn't the default profile
1460 if(!$r[0]['is-default']) {
1461 $x = q("select `pub_keywords` from `profile` where uid = %d and `is-default` = 1 limit 1",
1462 intval($r[0]['profile_uid'])
1465 $r[0]['pub_keywords'] = $x[0]['pub_keywords'];
1468 $a->profile = $r[0];
1470 $a->profile['mobile-theme'] = get_pconfig($a->profile['profile_uid'], 'system', 'mobile_theme');
1471 $a->profile['network'] = NETWORK_DFRN;
1473 $a->page['title'] = $a->profile['name'] . " @ " . $a->config['sitename'];
1476 $_SESSION['theme'] = $a->profile['theme'];
1478 $_SESSION['mobile-theme'] = $a->profile['mobile-theme'];
1481 * load/reload current theme info
1484 $a->set_template_engine(); // reset the template engine to the default in case the user's theme doesn't specify one
1486 $theme_info_file = "view/theme/".current_theme()."/theme.php";
1487 if (file_exists($theme_info_file)){
1488 require_once($theme_info_file);
1491 if(! (x($a->page,'aside')))
1492 $a->page['aside'] = '';
1494 if(local_user() && local_user() == $a->profile['uid'] && $profiledata) {
1495 $a->page['aside'] .= replace_macros(get_markup_template('profile_edlink.tpl'),array(
1496 '$editprofile' => t('Edit profile'),
1497 '$profid' => $a->profile['id']
1501 $block = (((get_config('system','block_public')) && (! local_user()) && (! remote_user())) ? true : false);
1504 // By now, the contact block isn't shown, when a different profile is given
1505 // But: When this profile was on the same server, then we could display the contacts
1507 $a->page['aside'] .= profile_sidebar($profiledata, true);
1509 $a->page['aside'] .= profile_sidebar($a->profile, $block);
1513 $a->page['aside'] .= contact_block();*/
1522 * Function: profile_sidebar
1524 * Formats a profile for display in the sidebar.
1525 * It is very difficult to templatise the HTML completely
1526 * because of all the conditional logic.
1528 * @parameter: array $profile
1530 * Returns HTML string stuitable for sidebar inclusion
1531 * Exceptions: Returns empty string if passed $profile is wrong type or not populated
1536 if(! function_exists('profile_sidebar')) {
1537 function profile_sidebar($profile, $block = 0) {
1545 if((! is_array($profile)) && (! count($profile)))
1548 $profile['picdate'] = urlencode($profile['picdate']);
1550 if (($profile['network'] != "") AND ($profile['network'] != NETWORK_DFRN)) {
1551 require_once('include/contact_selectors.php');
1552 if ($profile['url'] != "")
1553 $profile['network_name'] = '<a href="'.$profile['url'].'">'.network_to_name($profile['network'])."</a>";
1555 $profile['network_name'] = network_to_name($profile['network']);
1557 $profile['network_name'] = "";
1559 call_hooks('profile_sidebar_enter', $profile);
1562 // don't show connect link to yourself
1563 $connect = (($profile['uid'] != local_user()) ? t('Connect') : False);
1565 // don't show connect link to authenticated visitors either
1566 if(remote_user() && count($_SESSION['remote'])) {
1567 foreach($_SESSION['remote'] as $visitor) {
1568 if($visitor['uid'] == $profile['uid']) {
1575 // Is the local user already connected to that user?
1576 if ($connect AND local_user()) {
1577 if (isset($profile["url"]))
1578 $profile_url = normalise_link($profile["url"]);
1580 $profile_url = normalise_link($a->get_baseurl()."/profile/".$profile["nickname"]);
1582 $r = q("SELECT * FROM `contact` WHERE NOT `pending` AND `uid` = %d AND `nurl` = '%s'",
1583 local_user(), $profile_url);
1588 if ($connect AND ($profile['network'] != NETWORK_DFRN) AND !isset($profile['remoteconnect']))
1591 if (isset($profile['remoteconnect']))
1592 $remoteconnect = $profile['remoteconnect'];
1594 if( get_my_url() && $profile['unkmail'] && ($profile['uid'] != local_user()) )
1595 $wallmessage = t('Message');
1597 $wallmessage = false;
1599 // show edit profile to yourself
1600 if ($profile['uid'] == local_user() && feature_enabled(local_user(),'multi_profiles')) {
1601 $profile['edit'] = array($a->get_baseurl(). '/profiles', t('Profiles'),"", t('Manage/edit profiles'));
1602 $r = q("SELECT * FROM `profile` WHERE `uid` = %d",
1605 $profile['menu'] = array(
1606 'chg_photo' => t('Change profile photo'),
1607 'cr_new' => t('Create New Profile'),
1608 'entries' => array(),
1613 foreach($r as $rr) {
1614 $profile['menu']['entries'][] = array(
1615 'photo' => $rr['thumb'],
1617 'alt' => t('Profile Image'),
1618 'profile_name' => $rr['profile-name'],
1619 'isdefault' => $rr['is-default'],
1620 'visibile_to_everybody' => t('visible to everybody'),
1621 'edit_visibility' => t('Edit visibility'),
1629 if ($profile['uid'] == local_user() && !feature_enabled(local_user(),'multi_profiles')) {
1630 $profile['edit'] = array($a->get_baseurl(). '/profiles/'.$profile['id'], t('Edit profile'),"", t('Edit profile'));
1631 $profile['menu'] = array(
1632 'chg_photo' => t('Change profile photo'),
1634 'entries' => array(),
1638 if((x($profile,'address') == 1)
1639 || (x($profile,'locality') == 1)
1640 || (x($profile,'region') == 1)
1641 || (x($profile,'postal-code') == 1)
1642 || (x($profile,'country-name') == 1))
1643 $location = t('Location:');
1645 $gender = ((x($profile,'gender') == 1) ? t('Gender:') : False);
1648 $marital = ((x($profile,'marital') == 1) ? t('Status:') : False);
1650 $homepage = ((x($profile,'homepage') == 1) ? t('Homepage:') : False);
1652 $about = ((x($profile,'about') == 1) ? t('About:') : False);
1654 if(($profile['hidewall'] || $block) && (! local_user()) && (! remote_user())) {
1655 $location = $pdesc = $gender = $marital = $homepage = $about = False;
1658 $firstname = ((strpos($profile['name'],' '))
1659 ? trim(substr($profile['name'],0,strpos($profile['name'],' '))) : $profile['name']);
1660 $lastname = (($firstname === $profile['name']) ? '' : trim(substr($profile['name'],strlen($firstname))));
1663 'podloc' => $a->get_baseurl(),
1664 'searchable' => (($profile['publish'] && $profile['net-publish']) ? 'true' : 'false' ),
1665 'nickname' => $profile['nickname'],
1666 'fullname' => $profile['name'],
1667 'firstname' => $firstname,
1668 'lastname' => $lastname,
1669 'photo300' => $a->get_cached_avatar_image($a->get_baseurl() . '/photo/custom/300/' . $profile['uid'] . '.jpg'),
1670 'photo100' => $a->get_cached_avatar_image($a->get_baseurl() . '/photo/custom/100/' . $profile['uid'] . '.jpg'),
1671 'photo50' => $a->get_cached_avatar_image($a->get_baseurl() . '/photo/custom/50/' . $profile['uid'] . '.jpg'),
1675 $contact_block = contact_block();
1680 foreach($profile as $k => $v) {
1681 $k = str_replace('-','_',$k);
1685 if($a->theme['template_engine'] === 'internal')
1686 $location = template_escape($location);
1689 $tpl = get_markup_template('profile_vcard.tpl');
1690 $o .= replace_macros($tpl, array(
1692 '$connect' => $connect,
1693 '$remoteconnect' => $remoteconnect,
1694 '$wallmessage' => $wallmessage,
1695 '$location' => $location,
1696 '$gender' => $gender,
1698 '$marital' => $marital,
1699 '$homepage' => $homepage,
1701 '$network' => t('Network:'),
1702 '$diaspora' => $diaspora,
1703 '$contact_block' => $contact_block,
1707 $arr = array('profile' => &$profile, 'entry' => &$o);
1709 call_hooks('profile_sidebar', $arr);
1716 if(! function_exists('get_birthdays')) {
1717 function get_birthdays() {
1722 if(! local_user() || $a->is_mobile || $a->is_tablet)
1725 // $mobile_detect = new Mobile_Detect();
1726 // $is_mobile = $mobile_detect->isMobile() || $mobile_detect->isTablet();
1731 $bd_format = t('g A l F d') ; // 8 AM Friday January 18
1732 $bd_short = t('F d');
1734 $r = q("SELECT `event`.*, `event`.`id` AS `eid`, `contact`.* FROM `event`
1735 INNER JOIN `contact` ON `contact`.`id` = `event`.`cid`
1736 WHERE `event`.`uid` = %d AND `type` = 'birthday' AND `start` < '%s' AND `finish` > '%s'
1737 ORDER BY `start` ASC ",
1738 intval(local_user()),
1739 dbesc(datetime_convert('UTC','UTC','now + 6 days')),
1740 dbesc(datetime_convert('UTC','UTC','now'))
1743 if($r && count($r)) {
1745 $now = strtotime('now');
1749 foreach($r as $rr) {
1750 if(strlen($rr['name']))
1752 if((strtotime($rr['start'] . ' +00:00') < $now) && (strtotime($rr['finish'] . ' +00:00') > $now))
1755 $classtoday = $istoday ? ' birthday-today ' : '';
1757 foreach($r as &$rr) {
1758 if(! strlen($rr['name']))
1763 if(in_array($rr['cid'],$cids))
1765 $cids[] = $rr['cid'];
1767 $today = (((strtotime($rr['start'] . ' +00:00') < $now) && (strtotime($rr['finish'] . ' +00:00') > $now)) ? true : false);
1770 if($rr['network'] === NETWORK_DFRN) {
1771 $sparkle = " sparkle";
1772 $url = $a->get_baseurl() . '/redir/' . $rr['cid'];
1776 $rr['title'] = $rr['name'];
1777 $rr['date'] = day_translate(datetime_convert('UTC', $a->timezone, $rr['start'], $rr['adjust'] ? $bd_format : $bd_short)) . (($today) ? ' ' . t('[today]') : '');
1778 $rr['startime'] = Null;
1779 $rr['today'] = $today;
1784 $tpl = get_markup_template("birthdays_reminder.tpl");
1785 return replace_macros($tpl, array(
1786 '$baseurl' => $a->get_baseurl(),
1787 '$classtoday' => $classtoday,
1789 '$event_reminders' => t('Birthday Reminders'),
1790 '$event_title' => t('Birthdays this week:'),
1792 '$lbr' => '{', // raw brackets mess up if/endif macro processing
1800 if(! function_exists('get_events')) {
1801 function get_events() {
1803 require_once('include/bbcode.php');
1807 if(! local_user() || $a->is_mobile || $a->is_tablet)
1811 // $mobile_detect = new Mobile_Detect();
1812 // $is_mobile = $mobile_detect->isMobile() || $mobile_detect->isTablet();
1817 $bd_format = t('g A l F d') ; // 8 AM Friday January 18
1818 $bd_short = t('F d');
1820 $r = q("SELECT `event`.* FROM `event`
1821 WHERE `event`.`uid` = %d AND `type` != 'birthday' AND `start` < '%s' AND `start` > '%s'
1822 ORDER BY `start` ASC ",
1823 intval(local_user()),
1824 dbesc(datetime_convert('UTC','UTC','now + 6 days')),
1825 dbesc(datetime_convert('UTC','UTC','now - 1 days'))
1828 if($r && count($r)) {
1829 $now = strtotime('now');
1831 foreach($r as $rr) {
1832 if(strlen($rr['name']))
1835 $strt = datetime_convert('UTC',$rr['convert'] ? $a->timezone : 'UTC',$rr['start'],'Y-m-d');
1836 if($strt === datetime_convert('UTC',$a->timezone,'now','Y-m-d'))
1839 $classtoday = (($istoday) ? 'event-today' : '');
1842 foreach($r as &$rr) {
1844 $md = datetime_convert('UTC',$a->timezone,$rr['start'],'Y/m');
1846 $md = datetime_convert('UTC','UTC',$rr['start'],'Y/m');
1847 $md .= "/#link-".$rr['id'];
1849 $title = substr(strip_tags(bbcode($rr['desc'])),0,32) . '... ';
1851 $title = t('[No description]');
1853 $strt = datetime_convert('UTC',$rr['convert'] ? $a->timezone : 'UTC',$rr['start']);
1854 $today = ((substr($strt,0,10) === datetime_convert('UTC',$a->timezone,'now','Y-m-d')) ? true : false);
1857 $rr['title'] = $title;
1858 $rr['date'] = day_translate(datetime_convert('UTC', $rr['adjust'] ? $a->timezone : 'UTC', $rr['start'], $bd_format)) . (($today) ? ' ' . t('[today]') : '');
1859 $rr['startime'] = $strt;
1860 $rr['today'] = $today;
1864 $tpl = get_markup_template("events_reminder.tpl");
1865 return replace_macros($tpl, array(
1866 '$baseurl' => $a->get_baseurl(),
1867 '$classtoday' => $classtoday,
1868 '$count' => count($r),
1869 '$event_reminders' => t('Event Reminders'),
1870 '$event_title' => t('Events this week:'),
1879 * Wrap calls to proc_close(proc_open()) and call hook
1880 * so plugins can take part in process :)
1883 * $cmd program to run
1884 * next args are passed as $cmd command line
1886 * e.g.: proc_run("ls","-la","/tmp");
1888 * $cmd and string args are surrounded with ""
1891 if(! function_exists('proc_run')) {
1892 function proc_run($cmd){
1896 $args = func_get_args();
1902 // expand any arrays
1904 foreach($args as $arg) {
1905 if(is_array($arg)) {
1906 foreach($arg as $n) {
1916 $arr = array('args' => $args, 'run_cmd' => true);
1918 call_hooks("proc_run", $arr);
1919 if(! $arr['run_cmd'])
1922 if(count($args) && $args[0] === 'php')
1923 $args[0] = ((x($a->config,'php_path')) && (strlen($a->config['php_path'])) ? $a->config['php_path'] : 'php');
1925 // add baseurl to args. cli scripts can't construct it
1926 $args[] = $a->get_baseurl();
1928 for($x = 0; $x < count($args); $x ++)
1929 $args[$x] = escapeshellarg($args[$x]);
1933 $cmdline = implode($args," ");
1934 if(get_config('system','proc_windows'))
1935 proc_close(proc_open('cmd /c start /b ' . $cmdline,array(),$foo,dirname(__FILE__)));
1937 proc_close(proc_open($cmdline." &",array(),$foo,dirname(__FILE__)));
1941 if(! function_exists('current_theme')) {
1942 function current_theme(){
1943 $app_base_themes = array('duepuntozero', 'dispy', 'quattro');
1947 // $mobile_detect = new Mobile_Detect();
1948 // $is_mobile = $mobile_detect->isMobile() || $mobile_detect->isTablet();
1949 $is_mobile = $a->is_mobile || $a->is_tablet;
1952 if(isset($_SESSION['show-mobile']) && !$_SESSION['show-mobile']) {
1957 $system_theme = ((isset($a->config['system']['mobile-theme'])) ? $a->config['system']['mobile-theme'] : '');
1958 $theme_name = ((isset($_SESSION) && x($_SESSION,'mobile-theme')) ? $_SESSION['mobile-theme'] : $system_theme);
1960 if($theme_name === '---') {
1961 // user has selected to have the mobile theme be the same as the normal one
1967 if(!$is_mobile || ($system_theme === '' && $theme_name === '')) {
1968 $system_theme = ((isset($a->config['system']['theme'])) ? $a->config['system']['theme'] : '');
1969 $theme_name = ((isset($_SESSION) && x($_SESSION,'theme')) ? $_SESSION['theme'] : $system_theme);
1973 (file_exists('view/theme/' . $theme_name . '/style.css') ||
1974 file_exists('view/theme/' . $theme_name . '/style.php')))
1975 return($theme_name);
1977 foreach($app_base_themes as $t) {
1978 if(file_exists('view/theme/' . $t . '/style.css')||
1979 file_exists('view/theme/' . $t . '/style.php'))
1983 $fallback = array_merge(glob('view/theme/*/style.css'),glob('view/theme/*/style.php'));
1984 if(count($fallback))
1985 return (str_replace('view/theme/','', substr($fallback[0],0,-10)));
1991 * Return full URL to theme which is currently in effect.
1992 * Provide a sane default if nothing is chosen or the specified theme does not exist.
1994 if(! function_exists('current_theme_url')) {
1995 function current_theme_url() {
1997 $t = current_theme();
1998 if (file_exists('view/theme/' . $t . '/style.php'))
1999 return($a->get_baseurl() . '/view/theme/' . $t . '/style.pcss');
2000 return($a->get_baseurl() . '/view/theme/' . $t . '/style.css');
2004 if(! function_exists('feed_birthday')) {
2005 function feed_birthday($uid,$tz) {
2009 * Determine the next birthday, but only if the birthday is published
2010 * in the default profile. We _could_ also look for a private profile that the
2011 * recipient can see, but somebody could get mad at us if they start getting
2012 * public birthday greetings when they haven't made this info public.
2014 * Assuming we are able to publish this info, we are then going to convert
2015 * the start time from the owner's timezone to UTC.
2017 * This will potentially solve the problem found with some social networks
2018 * where birthdays are converted to the viewer's timezone and salutations from
2019 * elsewhere in the world show up on the wrong day. We will convert it to the
2020 * viewer's timezone also, but first we are going to convert it from the birthday
2021 * person's timezone to GMT - so the viewer may find the birthday starting at
2022 * 6:00PM the day before, but that will correspond to midnight to the birthday person.
2032 $p = q("SELECT `dob` FROM `profile` WHERE `is-default` = 1 AND `uid` = %d LIMIT 1",
2036 if($p && count($p)) {
2037 $tmp_dob = substr($p[0]['dob'],5);
2038 if(intval($tmp_dob)) {
2039 $y = datetime_convert($tz,$tz,'now','Y');
2040 $bd = $y . '-' . $tmp_dob . ' 00:00';
2041 $t_dob = strtotime($bd);
2042 $now = strtotime(datetime_convert($tz,$tz,'now'));
2044 $bd = $y + 1 . '-' . $tmp_dob . ' 00:00';
2045 $birthday = datetime_convert($tz,'UTC',$bd,ATOM_TIME);
2053 if(! function_exists('is_site_admin')) {
2054 function is_site_admin() {
2057 $adminlist = explode(",", str_replace(" ", "", $a->config['admin_email']));
2059 //if(local_user() && x($a->user,'email') && x($a->config,'admin_email') && ($a->user['email'] === $a->config['admin_email']))
2060 if(local_user() && x($a->user,'email') && x($a->config,'admin_email') && in_array($a->user['email'], $adminlist))
2067 if(! function_exists('load_contact_links')) {
2068 function load_contact_links($uid) {
2074 if(! $uid || x($a->contacts,'empty'))
2077 $r = q("SELECT `id`,`network`,`url`,`thumb` FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 AND `thumb` != ''",
2082 $url = normalise_link($rr['url']);
2087 $ret['empty'] = true;
2088 $a->contacts = $ret;
2093 if(! function_exists('profile_tabs')){
2094 function profile_tabs($a, $is_owner=False, $nickname=Null){
2095 //echo "<pre>"; var_dump($a->user); killme();
2097 if (is_null($nickname))
2098 $nickname = $a->user['nickname'];
2101 $tab = notags(trim($_GET['tab']));
2103 $url = $a->get_baseurl() . '/profile/' . $nickname;
2107 'label'=>t('Status'),
2109 'sel' => ((!isset($tab)&&$a->argv[0]=='profile')?'active':''),
2110 'title' => t('Status Messages and Posts'),
2111 'id' => 'status-tab',
2114 'label' => t('Profile'),
2115 'url' => $url.'/?tab=profile',
2116 'sel' => ((isset($tab) && $tab=='profile')?'active':''),
2117 'title' => t('Profile Details'),
2118 'id' => 'profile-tab',
2121 'label' => t('Photos'),
2122 'url' => $a->get_baseurl() . '/photos/' . $nickname,
2123 'sel' => ((!isset($tab)&&$a->argv[0]=='photos')?'active':''),
2124 'title' => t('Photo Albums'),
2125 'id' => 'photo-tab',
2128 'label' => t('Videos'),
2129 'url' => $a->get_baseurl() . '/videos/' . $nickname,
2130 'sel' => ((!isset($tab)&&$a->argv[0]=='videos')?'active':''),
2131 'title' => t('Videos'),
2132 'id' => 'video-tab',
2138 'label' => t('Events'),
2139 'url' => $a->get_baseurl() . '/events',
2140 'sel' =>((!isset($tab)&&$a->argv[0]=='events')?'active':''),
2141 'title' => t('Events and Calendar'),
2142 'id' => 'events-tab',
2145 'label' => t('Personal Notes'),
2146 'url' => $a->get_baseurl() . '/notes',
2147 'sel' =>((!isset($tab)&&$a->argv[0]=='notes')?'active':''),
2148 'title' => t('Only You Can See This'),
2149 'id' => 'notes-tab',
2154 $arr = array('is_owner' => $is_owner, 'nickname' => $nickname, 'tab' => (($tab) ? $tab : false), 'tabs' => $tabs);
2155 call_hooks('profile_tabs', $arr);
2157 $tpl = get_markup_template('common_tabs.tpl');
2159 return replace_macros($tpl,array('$tabs' => $arr['tabs']));
2163 function get_my_url() {
2164 if(x($_SESSION,'my_url'))
2165 return $_SESSION['my_url'];
2169 function zrl_init(&$a) {
2170 $tmp_str = get_my_url();
2171 if(validate_url($tmp_str)) {
2172 proc_run('php','include/gprobe.php',bin2hex($tmp_str));
2173 $arr = array('zrl' => $tmp_str, 'url' => $a->cmd);
2174 call_hooks('zrl_init',$arr);
2178 function zrl($s,$force = false) {
2181 if((! strpos($s,'/profile/')) && (! $force))
2183 if($force && substr($s,-1,1) !== '/')
2185 $achar = strpos($s,'?') ? '&' : '?';
2186 $mine = get_my_url();
2187 if($mine and ! link_compare($mine,$s))
2188 return $s . $achar . 'zrl=' . urlencode($mine);
2193 * returns querystring as string from a mapped array
2195 * @param params Array
2198 function build_querystring($params, $name=null) {
2200 foreach($params as $key=>$val) {
2201 if(is_array($val)) {
2203 $ret .= build_querystring($val, $key);
2205 $ret .= build_querystring($val, $name."[$key]");
2208 $val = urlencode($val);
2210 $ret.=$name."[$key]"."=$val&";
2212 $ret.= "$key=$val&";
2219 function explode_querystring($query) {
2220 $arg_st = strpos($query, '?');
2221 if($arg_st !== false) {
2222 $base = substr($query, 0, $arg_st);
2230 $args = explode('&', substr($query, $arg_st));
2231 foreach($args as $k=>$arg) {
2235 $args = array_values($args);
2240 $args = array_values($args);
2250 * Returns the complete URL of the current page, e.g.: http(s)://something.com/network
2252 * Taken from http://webcheatsheet.com/php/get_current_page_url.php
2254 function curPageURL() {
2256 if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
2258 if ($_SERVER["SERVER_PORT"] != "80" && $_SERVER["SERVER_PORT"] != "443") {
2259 $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
2261 $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
2266 function random_digits($digits) {
2268 for($i = 0; $i < $digits; $i++) {
2274 function get_cachefile($file, $writemode = true) {
2275 $cache = get_itemcachepath();
2277 if ((! $cache) || (! is_dir($cache)))
2280 $subfolder = $cache."/".substr($file, 0, 2);
2282 $cachepath = $subfolder."/".$file;
2285 if (!is_dir($subfolder)) {
2287 chmod($subfolder, 0777);
2294 function clear_cache($basepath = "", $path = "") {
2296 $basepath = get_itemcachepath();
2300 if (($path == "") OR (!is_dir($path)))
2303 if (substr(realpath($path), 0, strlen($basepath)) != $basepath)
2306 $cachetime = (int)get_config('system','itemcache_duration');
2307 if ($cachetime == 0)
2310 if (is_writable($path)){
2311 if ($dh = opendir($path)) {
2312 while (($file = readdir($dh)) !== false) {
2313 $fullpath = $path."/".$file;
2314 if ((filetype($fullpath) == "dir") and ($file != ".") and ($file != ".."))
2315 clear_cache($basepath, $fullpath);
2316 if ((filetype($fullpath) == "file") and (filectime($fullpath) < (time() - $cachetime)))
2324 function get_itemcachepath() {
2325 // Checking, if the cache is deactivated
2326 $cachetime = (int)get_config('system','itemcache_duration');
2330 $itemcache = get_config('system','itemcache');
2331 if (($itemcache != "") AND is_dir($itemcache) AND is_writable($itemcache))
2334 $temppath = get_temppath();
2336 if ($temppath != "") {
2337 $itemcache = $temppath."/itemcache";
2340 if (is_dir($itemcache) AND is_writable($itemcache)) {
2341 set_config("system", "itemcache", $itemcache);
2348 function get_lockpath() {
2349 $lockpath = get_config('system','lockpath');
2350 if (($lockpath != "") AND is_dir($lockpath) AND is_writable($lockpath))
2353 $temppath = get_temppath();
2355 if ($temppath != "") {
2356 $lockpath = $temppath."/lock";
2359 if (is_dir($lockpath) AND is_writable($lockpath)) {
2360 set_config("system", "lockpath", $lockpath);
2367 function get_temppath() {
2368 $temppath = get_config("system","temppath");
2369 if (($temppath != "") AND is_dir($temppath) AND is_writable($temppath))
2372 $temppath = sys_get_temp_dir();
2373 if (($temppath != "") AND is_dir($temppath) AND is_writable($temppath)) {
2374 set_config("system", "temppath", $temppath);
2381 function set_template_engine(&$a, $engine = 'internal') {
2382 // This function is no longer necessary, but keep it as a wrapper to the class method
2383 // to avoid breaking themes again unnecessarily
2385 $a->set_template_engine($engine);
2388 if(!function_exists('exif_imagetype')) {
2389 function exif_imagetype($file) {
2390 $size = getimagesize($file);