]> git.mxchange.org Git - friendica.git/blobdiff - boot.php
don't invoke slap if there's no endpoint configured
[friendica.git] / boot.php
index a264da2e64570942a1e34bb26673d5244db09096..cdb1b35edb8d2bdec0d0f080cd401055cba7d07b 100644 (file)
--- a/boot.php
+++ b/boot.php
@@ -2,14 +2,25 @@
 
 set_time_limit(0);
 
-define ( 'BUILD_ID' , 1003 );
+define ( 'BUILD_ID',               1017   );
+define ( 'DFRN_PROTOCOL_VERSION',  '2.0'  );
 
-define ( 'EOL', "<br />\r\n");
-define ( 'ATOM_TIME',  'Y-m-d\TH:i:s\Z' );
+define ( 'EOL',                    "<br />\r\n"     );
+define ( 'ATOM_TIME',              'Y-m-d\TH:i:s\Z' );
 
-define ( 'REGISTER_CLOSED',  0);
-define ( 'REGISTER_APPROVE', 1);
-define ( 'REGISTER_OPEN',    2);
+// log levels
+
+define ( 'LOGGER_NORMAL',          0 );
+define ( 'LOGGER_TRACE',           1 );
+define ( 'LOGGER_DEBUG',           2 );
+define ( 'LOGGER_DATA',            3 );
+define ( 'LOGGER_ALL',             4 );
+
+// registration policy
+
+define ( 'REGISTER_CLOSED',        0 );
+define ( 'REGISTER_APPROVE',       1 );
+define ( 'REGISTER_OPEN',          2 );
 
 // relationship types
 
@@ -17,25 +28,58 @@ define ( 'REL_VIP',        1);
 define ( 'REL_FAN',        2);
 define ( 'REL_BUD',        3);
 
+
+// page/profile types
+// PAGE_NORMAL is a typical personal profile account
+// PAGE_SOAPBOX automatically approves all friend requests as REL_FAN, (readonly)
+// PAGE_COMMUNITY automatically approves all friend requests as REL_FAN, but with 
+// write access to wall and comments (no email and not included in page owner's ACL lists)
+// PAGE_FREELOVE automatically approves all friend requests as full friends (REL_BUD). 
+
+define ( 'PAGE_NORMAL',            0 );
+define ( 'PAGE_SOAPBOX',           1 );
+define ( 'PAGE_COMMUNITY',         2 );
+define ( 'PAGE_FREELOVE',          3 );
+
+// Maximum number of "people who like (or don't like) this" 
+// that we will list by name
+
+define ( 'MAX_LIKERS',    75);
+
+// email notification options
+
 define ( 'NOTIFY_INTRO',   0x0001 );
 define ( 'NOTIFY_CONFIRM', 0x0002 );
 define ( 'NOTIFY_WALL',    0x0004 );
 define ( 'NOTIFY_COMMENT', 0x0008 );
 define ( 'NOTIFY_MAIL',    0x0010 );
 
+// various namespaces we may need to parse
+
 define ( 'NAMESPACE_DFRN' ,           'http://purl.org/macgirvin/dfrn/1.0' ); 
 define ( 'NAMESPACE_THREAD' ,         'http://purl.org/syndication/thread/1.0' );
 define ( 'NAMESPACE_TOMB' ,           'http://purl.org/atompub/tombstones/1.0' );
 define ( 'NAMESPACE_ACTIVITY',        'http://activitystrea.ms/spec/1.0/' );
-define ( 'NAMESPACE_ACTIVITY_SCHEMA', 'http://activitystrea.ms/schema/1.0/');
+define ( 'NAMESPACE_ACTIVITY_SCHEMA', 'http://activitystrea.ms/schema/1.0/' );
+define ( 'NAMESPACE_MEDIA',           'http://purl.org/syndication/atommedia' );
+define ( 'NAMESPACE_SALMON_ME',       'http://salmon-protocol.org/ns/magic-env' );
+define ( 'NAMESPACE_OSTATUSSUB',      'http://ostatus.org/schema/1.0/subscribe' );
+define ( 'NAMESPACE_GEORSS',          'http://www.georss.org/georss' );
+define ( 'NAMESPACE_POCO',            'http://portablecontacts.net/spec/1.0' );
+define ( 'NAMESPACE_FEED',            'http://schemas.google.com/g/2010#updates-from' );
+
+// activity stream defines
 
 define ( 'ACTIVITY_LIKE',        NAMESPACE_ACTIVITY_SCHEMA . 'like' );
 define ( 'ACTIVITY_DISLIKE',     NAMESPACE_DFRN            . '/dislike' );
 define ( 'ACTIVITY_OBJ_HEART',   NAMESPACE_DFRN            . '/heart' );
 
 define ( 'ACTIVITY_FRIEND',      NAMESPACE_ACTIVITY_SCHEMA . 'make-friend' );
+define ( 'ACTIVITY_FOLLOW',      NAMESPACE_ACTIVITY_SCHEMA . 'follow' );
+define ( 'ACTIVITY_UNFOLLOW',    NAMESPACE_ACTIVITY_SCHEMA . 'unfollow' );
 define ( 'ACTIVITY_POST',        NAMESPACE_ACTIVITY_SCHEMA . 'post' );
 define ( 'ACTIVITY_UPDATE',      NAMESPACE_ACTIVITY_SCHEMA . 'update' );
+define ( 'ACTIVITY_TAG',         NAMESPACE_ACTIVITY_SCHEMA . 'tag' );
 
 define ( 'ACTIVITY_OBJ_COMMENT', NAMESPACE_ACTIVITY_SCHEMA . 'comment' );
 define ( 'ACTIVITY_OBJ_NOTE',    NAMESPACE_ACTIVITY_SCHEMA . 'note' );
@@ -44,6 +88,8 @@ define ( 'ACTIVITY_OBJ_PHOTO',   NAMESPACE_ACTIVITY_SCHEMA . 'photo' );
 define ( 'ACTIVITY_OBJ_P_PHOTO', NAMESPACE_ACTIVITY_SCHEMA . 'profile-photo' );
 define ( 'ACTIVITY_OBJ_ALBUM',   NAMESPACE_ACTIVITY_SCHEMA . 'photo-album' );
 
+// item weight for query ordering
+
 define ( 'GRAVITY_PARENT',       0);
 define ( 'GRAVITY_LIKE',         3);
 define ( 'GRAVITY_COMMENT',      6);
@@ -76,29 +122,33 @@ class App {
        public  $pager;
        public  $strings;   
        public  $path;
+       public  $interactive = true;
 
        private $scheme;
        private $hostname;
        private $baseurl;
        private $db;
 
+       private $curl_code;
+       private $curl_headers;
+
        function __construct() {
 
                $this->config = array();
                $this->page = array();
                $this->pager= array();
 
-               $this->scheme = ((isset($_SERVER['HTTPS']) 
-                               && ($_SERVER['HTTPS'])) ?  'https' : 'http' );
-               $this->hostname = str_replace('www.','',
-                               $_SERVER['SERVER_NAME']);
-               set_include_path("include/$this->hostname" 
-                               . PATH_SEPARATOR . 'include' 
-                               . PATH_SEPARATOR . '.' );
+               $this->scheme = ((isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS']))      ?  'https' : 'http' );
 
-                if(substr($_SERVER['QUERY_STRING'],0,2) == "q=")
+               if(x($_SERVER,'SERVER_NAME'))
+                       $this->hostname = $_SERVER['SERVER_NAME'];
+
+               set_include_path("include/$this->hostname" . PATH_SEPARATOR . 'include' . PATH_SEPARATOR . '.' );
+
+               if((x($_SERVER,'QUERY_STRING')) && substr($_SERVER['QUERY_STRING'],0,2) === "q=")
                        $_SERVER['QUERY_STRING'] = substr($_SERVER['QUERY_STRING'],2);
-               $this->cmd = trim($_GET['q'],'/');
+               if(x($_GET,'q'))
+                       $this->cmd = trim($_GET['q'],'/');
 
 
                $this->argv = explode('/',$this->cmd);
@@ -113,6 +163,7 @@ class App {
                if($this->cmd === '.well-known/host-meta')
                        require_once('include/hostxrd.php');
 
+
                $this->pager['page'] = ((x($_GET,'page')) ? $_GET['page'] : 1);
                $this->pager['itemspage'] = 50;
                $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
@@ -123,9 +174,7 @@ class App {
                if(strlen($this->baseurl))
                        return $this->baseurl;
 
-               $this->baseurl = (($ssl) ? 'https' : $this->scheme) . "://" . $this->hostname
-                       . ((isset($this->path) && strlen($this->path)) 
-                       ? '/' . $this->path : '' );
+               $this->baseurl = (($ssl) ? 'https' : $this->scheme) . "://" . $this->hostname . ((isset($this->path) && strlen($this->path)) ? '/' . $this->path : '' );
                return $this->baseurl;
        }
 
@@ -143,7 +192,7 @@ class App {
        }
 
        function set_path($p) {
-               $this->path = ltrim(trim($p),'/');
+               $this->path = trim(trim($p),'/');
        } 
 
        function get_path() {
@@ -167,8 +216,34 @@ class App {
                ));
        }
 
+       function set_curl_code($code) {
+               $this->curl_code = $code;
+       }
+
+       function get_curl_code() {
+               return $this->curl_code;
+       }
+
+       function set_curl_headers($headers) {
+               $this->curl_headers = $headers;
+       }
+
+       function get_curl_headers() {
+               return $this->curl_headers;
+       }
+
+
 }}
 
+// retrieve the App structure
+// useful in functions which require it but don't get it passed to them
+
+if(! function_exists('get_app')) {
+function get_app() {
+       global $a;
+       return $a;
+}};
+
 
 // Multi-purpose function to check variable state.
 // Usage: x($var) or $x($array,'key')
@@ -226,7 +301,6 @@ function check_config(&$a) {
                $stored = intval($build);
                $current = intval(BUILD_ID);
                if(($stored < $current) && file_exists('update.php')) {
-
                        // We're reporting a different version than what is currently installed.
                        // Run any existing update scripts to bring the database up to current.
 
@@ -248,7 +322,9 @@ function check_config(&$a) {
 // $s is the string requiring macro substitution.
 // $r is an array of key value pairs (search => replace)
 // returns substituted string.
-
+// WARNING: this is pretty basic, and doesn't properly handle search strings that are substrings of each other.
+// For instance if 'test' => "foo" and 'testing' => "bar", testing could become either bar or fooing, 
+// depending on the order in which they were declared in the array.   
 
 if(! function_exists('replace_macros')) {  
 function replace_macros($s,$r) {
@@ -266,22 +342,24 @@ function replace_macros($s,$r) {
 }}
 
 
-// load string tranlsation table for alternate language
-// not yet implemented
+// load string translation table for alternate language
 
 if(! function_exists('load_translation_table')) {
 function load_translation_table($lang) {
        global $a;
 
+       if(file_exists("view/$lang/strings.php"))
+               include("view/$lang/strings.php");
 }}
 
 // translate string if translation exists
 
 if(! function_exists('t')) {
 function t($s) {
-       global $a;
 
-       if($a->strings[$s])
+       $a = get_app();
+
+       if(x($a->strings,$s))
                return $a->strings[$s];
        return $s;
 }}
@@ -290,14 +368,25 @@ function t($s) {
 // results. 
 
 if(! function_exists('fetch_url')) {
-function fetch_url($url,$binary = false) {
+function fetch_url($url,$binary = false, &$redirects = 0) {
        $ch = curl_init($url);
-       if(! $ch) return false;
+       if(($redirects > 8) || (! $ch)) 
+               return false;
 
-        curl_setopt($ch, CURLOPT_HEADER, 0);
-       curl_setopt($ch, CURLOPT_FOLLOWLOCATION,true);
-       curl_setopt($ch, CURLOPT_MAXREDIRS,8);
+       curl_setopt($ch, CURLOPT_HEADER, true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
+
+
+       $curl_time = intval(get_config('system','curl_timeout'));
+       if($curl_time)
+               curl_setopt($ch, CURLOPT_TIMEOUT, $curl_time);
+
+       // by default we will allow self-signed certs
+       // but you can override this
+
+       $check_cert = get_config('system','verifyssl');
+       curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
+
        $prx = get_config('system','proxy');
        if(strlen($prx)) {
                curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
@@ -310,23 +399,55 @@ function fetch_url($url,$binary = false) {
                curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
 
        $s = curl_exec($ch);
+
+       $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
+       $header = substr($s,0,strpos($s,"\r\n\r\n"));
+       if(stristr($header,'100') && (strlen($header) < 30)) {
+               // 100 Continue has two headers, get the real one
+               $s = substr($s,strlen($header)+4);
+               $header = substr($s,0,strpos($s,"\r\n\r\n"));
+       }
+       if($http_code == 301 || $http_code == 302 || $http_code == 303) {
+        $matches = array();
+        preg_match('/(Location:|URI:)(.*?)\n/', $header, $matches);
+        $url = trim(array_pop($matches));
+        $url_parsed = parse_url($url);
+        if (isset($url_parsed)) {
+            $redirects++;
+            return fetch_url($url,$binary,$redirects);
+        }
+    }
+       $a = get_app();
+       $a->set_curl_code($http_code);
+       $body = substr($s,strlen($header)+4);
+       $a->set_curl_headers($header);
+
        curl_close($ch);
-       return($s);
+       return($body);
 }}
 
 // post request to $url. $params is an array of post variables.
 
 if(! function_exists('post_url')) {
-function post_url($url,$params) {
+function post_url($url,$params, $headers = null, &$redirects = 0) {
        $ch = curl_init($url);
-       if(! $ch) return false;
+       if(($redirects > 8) || (! $ch)) 
+               return false;
 
-        curl_setopt($ch, CURLOPT_HEADER, 0);
-       curl_setopt($ch, CURLOPT_FOLLOWLOCATION,true);
-       curl_setopt($ch, CURLOPT_MAXREDIRS,8);
+       curl_setopt($ch, CURLOPT_HEADER, true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
        curl_setopt($ch, CURLOPT_POST,1);
        curl_setopt($ch, CURLOPT_POSTFIELDS,$params);
+
+       $curl_time = intval(get_config('system','curl_timeout'));
+       if($curl_time)
+               curl_setopt($ch, CURLOPT_TIMEOUT, $curl_time);
+
+       if(is_array($headers))
+               curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
+
+       $check_cert = get_config('system','verifyssl');
+       curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
        $prx = get_config('system','proxy');
        if(strlen($prx)) {
                curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
@@ -337,8 +458,31 @@ function post_url($url,$params) {
        }
 
        $s = curl_exec($ch);
+
+       $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
+       $header = substr($s,0,strpos($s,"\r\n\r\n"));
+       if(stristr($header,'100') && (strlen($header) < 30)) {
+               // 100 Continue has two headers, get the real one
+               $s = substr($s,strlen($header)+4);
+               $header = substr($s,0,strpos($s,"\r\n\r\n"));
+       }
+       if($http_code == 301 || $http_code == 302 || $http_code == 303) {
+        $matches = array();
+        preg_match('/(Location:|URI:)(.*?)\n/', $header, $matches);
+        $url = trim(array_pop($matches));
+        $url_parsed = parse_url($url);
+        if (isset($url_parsed)) {
+            $redirects++;
+            return post_url($url,$binary,$headers,$redirects);
+        }
+    }
+       $a = get_app();
+       $a->set_curl_code($http_code);
+       $body = substr($s,strlen($header)+4);
+       $a->set_curl_headers($header);
+
        curl_close($ch);
-       return($s);
+       return($body);
 }}
 
 // random hash, 64 chars
@@ -371,6 +515,7 @@ function escape_tags($string) {
 
 // wrapper for adding a login box. If $register == true provide a registration
 // link. This will most always depend on the value of $a->config['register_policy'].
+// returns the complete html for inserting into the page
 
 if(! function_exists('login')) {
 function login($register = false) {
@@ -477,23 +622,29 @@ function goaway($s) {
 }}
 
 // Generic XML return
-// Outputs a basic XML status structure to STDOUT, with a value variable 
-// of $st and terminates the current process. 
+// Outputs a basic dfrn XML status structure to STDOUT, with a <status> variable 
+// of $st and an optional text <message> of $message and terminates the current process. 
 
 if(! function_exists('xml_status')) {
-function xml_status($st) {
+function xml_status($st, $message = '') {
+
+       $xml_message = ((strlen($message)) ? "\t<message>" . xmlify($message) . "</message>\r\n" : '');
+
+       if($st)
+               logger('xml_status returning non_zero: ' . $st . " message=" . $message);
+
        header( "Content-type: text/xml" );
        echo '<?xml version="1.0" encoding="UTF-8"?>'."\r\n";
-       echo "<result><status>$st</status></result>\r\n";
+       echo "<result>\r\n\t<status>$st</status>\r\n$xml_message</result>\r\n";
        killme();
 }}
 
-// Returns the uid of locally logged on user or false.
+// Returns the uid of locally logged in user or false.
 
 if(! function_exists('local_user')) {
 function local_user() {
        if((x($_SESSION,'authenticated')) && (x($_SESSION,'uid')))
-               return $_SESSION['uid'];
+               return intval($_SESSION['uid']);
        return false;
 }}
 
@@ -502,7 +653,7 @@ function local_user() {
 if(! function_exists('remote_user')) {
 function remote_user() {
        if((x($_SESSION,'authenticated')) && (x($_SESSION,'visitor_id')))
-               return $_SESSION['visitor_id'];
+               return intval($_SESSION['visitor_id']);
        return false;
 }}
 
@@ -511,9 +662,9 @@ function remote_user() {
 
 if(! function_exists('notice')) {
 function notice($s) {
-
-       $_SESSION['sysmsg'] .= $s;
-
+       $a = get_app();
+       if($a->interactive)
+               $_SESSION['sysmsg'] .= $s;
 }}
 
 // wrapper around config to limit the text length of an incoming message
@@ -556,7 +707,7 @@ function xmlify($str) {
                                $buffer .= '&gt;';
                                break;
                        case "\n" :
-                               $buffer .= ' ';
+                               $buffer .= "\n";
                                break;
                        default :
                                $buffer .= $char;
@@ -597,7 +748,7 @@ function hex2bin($s) {
 if(! function_exists('paginate')) {
 function paginate(&$a) {
        $o = '';
-       $stripped = ereg_replace("(&page=[0-9]*)","",$_SERVER['QUERY_STRING']);
+       $stripped = preg_replace('/(&page=[0-9]*)/','',$_SERVER['QUERY_STRING']);
        $stripped = str_replace('q=','',$stripped);
        $stripped = trim($stripped,'/');
        $url = $a->get_baseurl() . '/' . $stripped;
@@ -802,62 +953,153 @@ function convert_xml_element_to_array($xml_element, &$recursion_depth=0) {
 }}
 
 // Given an email style address, perform webfinger lookup and 
-// return the resulting DFRN profile URL.
+// return the resulting DFRN profile URL, or if no DFRN profile URL
+// is located, returns an OStatus subscription template (prefixed 
+// with the string 'stat:' to identify it as on OStatus template).
 // If this isn't an email style address just return $s.
 // Return an empty string if email-style addresses but webfinger fails,
-// or if the resultant personal XRD doesn't contain a DFRN profile.
+// or if the resultant personal XRD doesn't contain a supported 
+// subscription/friend-request attribute.
 
-if(! function_exists('webfinger')) {
-function webfinger($s) {
+if(! function_exists('webfinger_dfrn')) {
+function webfinger_dfrn($s) {
        if(! strstr($s,'@')) {
                return $s;
        }
-       $host = substr($s,strpos($s,'@') + 1);
-       $url = 'http://' . $host . '/.well-known/host-meta' ;
-       $xml = fetch_url($url);
-       if (! $xml)
-               return '';
-       $h = simplexml_load_string($xml);
-       $arr = convert_xml_element_to_array($h);
+       $links = webfinger($s);
+       logger('webfinger_dfrn: ' . $s . ':' . print_r($links,true), LOGGER_DATA);
+       if(count($links)) {
+               foreach($links as $link)
+                       if($link['@attributes']['rel'] === NAMESPACE_DFRN)
+                               return $link['@attributes']['href'];
+               foreach($links as $link)
+                       if($link['@attributes']['rel'] === NAMESPACE_OSTATUSSUB)
+                               return 'stat:' . $link['@attributes']['template'];              
+       }
+       return '';
+}}
 
-       if(! isset($arr['xrd']['link']))
-               return '';
+// Given an email style address, perform webfinger lookup and 
+// return the array of link attributes from the personal XRD file.
+// On error/failure return an empty array.
 
-       $link = $arr['xrd']['link'];
-       if(! isset($link[0]))
-               $links = array($link);
-       else
-               $links = $link;
 
-       foreach($links as $link)
-               if($link['@attributes']['rel'] && $link['@attributes']['rel'] === 'lrdd')
-                       $tpl = $link['@attributes']['template'];
-       if((empty($tpl)) || (! strpos($tpl, '{uri}')))
-               return '';
+if(! function_exists('webfinger')) {
+function webfinger($s) {
+       $host = '';
+       if(strstr($s,'@')) {
+               $host = substr($s,strpos($s,'@') + 1);
+       }
+       if(strlen($host)) {
+               $tpl = fetch_lrdd_template($host);
+               logger('webfinger: lrdd template: ' . $tpl);
+               if(strlen($tpl)) {
+                       $pxrd = str_replace('{uri}', urlencode('acct:'.$s), $tpl);
+                       $links = fetch_xrd_links($pxrd);
+                       if(! count($links)) {
+                               // try with double slashes
+                               $pxrd = str_replace('{uri}', urlencode('acct://'.$s), $tpl);
+                               $links = fetch_xrd_links($pxrd);
+                       }
+                       return $links;
+               }
+       }
+       return array();
+}}
 
-       $pxrd = str_replace('{uri}', urlencode('acct://'.$s), $tpl);
+if(! function_exists('lrdd')) {
+function lrdd($uri) {
 
-       $xml = fetch_url($pxrd);
-       if (! $xml)
-               return '';
-       $h = simplexml_load_string($xml);
-       $arr = convert_xml_element_to_array($h);
+       $a = get_app();
+
+       if(strstr($uri,'@')) {  
+               return(webfinger($uri));
+       }
+       else {
+               $html = fetch_url($uri);
+               $headers = $a->get_curl_headers();
+               $lines = explode("\n",$headers);
+               if(count($lines)) {
+                       foreach($lines as $line) {                              
+                               // TODO alter the following regex to support multiple relations (space separated)
+                               if((stristr($line,'link:')) && preg_match('/<([^>].*)>.*rel\=[\'\"]lrdd[\'\"]/',$line,$matches)) {
+                                       $link = $matches[1];
+                                       break;
+                               }
+                       }
+               }
+               if(! isset($link)) {
+                       // parse the page of the supplied URL looking for rel links
 
-       if(! isset($arr['xrd']['link']))
-               return '';
+                       require_once('library/HTML5/Parser.php');
+                       $dom = HTML5_Parser::parse($html);
 
-       $link = $arr['xrd']['link'];
-       if(! isset($link[0]))
-               $links = array($link);
-       else
-               $links = $link;
+                       if($dom) {
+                               $items = $dom->getElementsByTagName('link');
 
-       foreach($links as $link)
-               if($link['@attributes']['rel'] == NAMESPACE_DFRN)
-                       return $link['@attributes']['href'];
-       return '';
+                               foreach($items as $item) {
+                                       $x = $item->getAttribute('rel');
+                                       if($x == "lrdd") {
+                                               $link = $item->getAttribute('href');
+                                               break;
+                                       }
+                               }
+                       }
+               }
+
+               if(isset($link))
+                       return(fetch_xrd_links($link));
+       }
+       return array();
+}}
+
+
+
+// Given a host name, locate the LRDD template from that
+// host. Returns the LRDD template or an empty string on
+// error/failure.
+
+if(! function_exists('fetch_lrdd_template')) {
+function fetch_lrdd_template($host) {
+       $tpl = '';
+       $url = 'http://' . $host . '/.well-known/host-meta' ;
+       $links = fetch_xrd_links($url);
+       if(count($links)) {
+               foreach($links as $link)
+                       if($link['@attributes']['rel'] && $link['@attributes']['rel'] === 'lrdd')
+                               $tpl = $link['@attributes']['template'];
+       }
+       if(! strpos($tpl,'{uri}'))
+               $tpl = '';
+       return $tpl;
 }}
 
+// Given a URL, retrieve the page as an XRD document.
+// Return an array of links.
+// on error/failure return empty array.
+
+if(! function_exists('fetch_xrd_links')) {
+function fetch_xrd_links($url) {
+
+
+       $xml = fetch_url($url);
+       if (! $xml)
+               return array();
+
+       logger('fetch_xrd_links: ' . $xml, LOGGER_DATA);
+       $h = simplexml_load_string($xml);
+       $arr = convert_xml_element_to_array($h);
+
+       if(isset($arr['xrd']['link'])) {
+               $link = $arr['xrd']['link'];
+               if(! isset($link[0]))
+                       $links = array($link);
+               else
+                       $links = $link;
+               return $links;
+       }
+       return array();
+}}
 
 // Convert an ACL array to a storable string
 
@@ -911,13 +1153,6 @@ function photo_new_resource() {
 }}
 
 
-// Returns logged in user ID
-
-if(! function_exists('get_uid')) {
-function get_uid() {
-       return ((x($_SESSION,'uid')) ? intval($_SESSION['uid']) : 0) ;
-}}
-
 // Take a URL from the wild, prepend http:// if necessary
 // and check DNS to see if it's real
 // return true if it's OK, false if something is wrong with it
@@ -928,13 +1163,25 @@ function validate_url(&$url) {
                $url = 'http://' . $url;
        $h = parse_url($url);
 
-       if(! $h) {
-               return false;
+       if(($h) && (checkdnsrr($h['host'], 'ANY'))) {
+               return true;
        }
-       if(! checkdnsrr($h['host'], 'ANY')) {
+       return false;
+}}
+
+// checks that email is an actual resolvable internet address
+
+if(! function_exists('validate_email')) {
+function validate_email($addr) {
+
+       if(! strpos($addr,'@'))
                return false;
+       $h = substr($addr,strpos($addr,'@') + 1);
+
+       if(($h) && (checkdnsrr($h, 'ANY'))) {
+               return true;
        }
-       return true;
+       return false;
 }}
 
 // Check $url against our list of allowed sites,
@@ -1022,21 +1269,22 @@ function allowed_email($email) {
 
 if(! function_exists('format_like')) {
 function format_like($cnt,$arr,$type,$id) {
+       $o = '';
        if($cnt == 1)
                $o .= $arr[0] . (($type === 'like') ? t(' likes this.') : t(' doesn\'t like this.')) . EOL ;
        else {
                $o .= '<span class="fakelink" onclick="openClose(\'' . $type . 'list-' . $id . '\');" >' 
                        . $cnt . ' ' . t('people') . '</span> ' . (($type === 'like') ? t('like this.') : t('don\'t like this.')) . EOL ;
                $total = count($arr);
-               if($total >= 75)
-                       $arr = array_slice($arr,0,74);
-               if($total < 75)
+               if($total >= MAX_LIKERS)
+                       $arr = array_slice($arr, 0, MAX_LIKERS - 1);
+               if($total < MAX_LIKERS)
                        $arr[count($arr)-1] = t('and') . ' ' . $arr[count($arr)-1];
                $str = implode(', ', $arr);
-               if($total >= 75)
-                       $str .= t(', and ') . $total - 75 . t(' other people');
+               if($total >= MAX_LIKERS)
+                       $str .= t(', and ') . $total - MAX_LIKERS . t(' other people');
                $str .= (($type === 'like') ? t(' like this.') : t(' don\'t like this.'));
-               $o .= '<div id="' . $type . 'list-' . $id . '" style="display: none;" >' . $str . '</div>';
+               $o .= "\t" . '<div id="' . $type . 'list-' . $id . '" style="display: none;" >' . $str . '</div>';
        }
        return $o;
 }}
@@ -1050,7 +1298,197 @@ function load_view_file($s) {
        $b = basename($s);
        $d = dirname($s);
        $lang = get_config('system','language');
-       if($lang && file_exists("$d/$lang/$b"))
+       if($lang === false)
+               $lang = 'en';
+       if(file_exists("$d/$lang/$b"))
                return file_get_contents("$d/$lang/$b");
        return file_get_contents($s);
-}}
\ No newline at end of file
+}}
+
+// for html,xml parsing - let's say you've got
+// an attribute foobar="class1 class2 class3"
+// and you want to find out if it contains 'class3'.
+// you can't use a normal sub string search because you
+// might match 'notclass3' and a regex to do the job is 
+// possible but a bit complicated. 
+// pass the attribute string as $attr and the attribute you 
+// are looking for as $s - returns true if found, otherwise false
+
+if(! function_exists('attribute_contains')) {
+function attribute_contains($attr,$s) {
+       $a = explode(' ', $attr);
+       if(count($a) && in_array($s,$a))
+               return true;
+       return false;
+}}
+
+if(! function_exists('logger')) {
+function logger($msg,$level = 0) {
+
+       $debugging = get_config('system','debugging');
+       $loglevel  = intval(get_config('system','loglevel'));
+       $logfile   = get_config('system','logfile');
+
+       if((! $debugging) || (! $logfile) || ($level > $loglevel))
+               return;
+       
+       @file_put_contents($logfile, datetime_convert() . ':' . session_id() . ' ' . $msg . "\n", FILE_APPEND);
+       return;
+}}
+
+
+if(! function_exists('activity_match')) {
+function activity_match($haystack,$needle) {
+       if(($haystack === $needle) || ((basename($needle) === $haystack) && strstr($needle,NAMESPACE_ACTIVITY_SCHEMA)))
+               return true;
+       return false;
+}}
+
+
+// Pull out all #hashtags and @person tags from $s;
+// We also get @person@domain.com - which would make 
+// the regex quite complicated as tags can also
+// end a sentence. So we'll run through our results
+// and strip the period from any tags which end with one.
+// Returns array of tags found, or empty array.
+
+
+if(! function_exists('get_tags')) {
+function get_tags($s) {
+       $ret = array();
+       if(preg_match_all('/([@#][^ ,:?]*)([ ,:?]|$)/',$s,$match)) {
+               foreach($match[1] as $match) {
+                       if(substr($match,-1,1) === '.')
+                               $ret[] = substr($match,0,-1);
+                       else
+                               $ret[] = $match;
+               }
+       }
+
+       return $ret;
+}}
+
+
+// quick and dirty quoted_printable encoding
+
+if(! function_exists('qp')) {
+function qp($s) {
+return str_replace ("%","=",rawurlencode($s));
+}} 
+
+
+if(! function_exists('like_puller')) {
+function like_puller($a,$item,&$arr,$mode) {
+
+       $url = '';
+       $sparkle = '';
+       $verb = (($mode === 'like') ? ACTIVITY_LIKE : ACTIVITY_DISLIKE);
+
+       if((activity_match($item['verb'],$verb)) && ($item['id'] != $item['parent'])) {
+               $url = $item['author-link'];
+               if(($item['network'] === 'dfrn') && (! $item['self']) && ($item['author-link'] == $item['url'])) {
+                       $url = $a->get_baseurl() . '/redir/' . $item['contact-id'];
+                       $sparkle = ' class="sparkle" ';
+               }
+               if(! ((isset($arr[$item['parent'] . '-l'])) && (is_array($arr[$item['parent'] . '-l']))))
+                       $arr[$item['parent'] . '-l'] = array();
+               if(! isset($arr[$item['parent']]))
+                       $arr[$item['parent']] = 1;
+               else    
+                       $arr[$item['parent']] ++;
+               $arr[$item['parent'] . '-l'][] = '<a href="'. $url . '"'. $sparkle .'>' . $item['author-name'] . '</a>';
+       }
+       return;
+}}
+
+if(! function_exists('get_mentions')) {
+function get_mentions($item) {
+       $o = '';
+       if(! strlen($item['tag']))
+               return $o;
+
+       $arr = explode(',',$item['tag']);
+       foreach($arr as $x) {
+               $matches = null;
+               if(preg_match('/@\[url=([^\]]*)\]/',$x,$matches))
+                       $o .= "\t\t" . '<link rel="mentioned" href="' . $matches[1] . '" />' . "\r\n";
+       }
+       return $o;
+}}
+
+if(! function_exists('contact_block')) {
+function contact_block() {
+       $o = '';
+       $a = get_app();
+       if((! is_array($a->profile)) || ($a->profile['hide-friends']))
+               return $o;
+       $r = q("SELECT COUNT(*) AS `total` FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 and `pending` = 0",
+                       intval($a->profile['uid'])
+       );
+       if(count($r)) {
+               $total = intval($r[0]['total']);
+       }
+       if(! $total) {
+               $o .= '<h4 class="contact-h4">' . t('No contacts') . '</h4>';
+               return $o;
+       }
+       $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 and `pending` = 0 ORDER BY RAND() LIMIT 24",
+                       intval($a->profile['uid'])
+       );
+       if(count($r)) {
+               $o .= '<h4 class="contact-h4">' . $total . ' ' . t('Contacts') . '</h4><div id="contact-block">';
+               foreach($r as $rr) {
+                       $redirect_url = $a->get_baseurl() . '/redir/' . $rr['id'];
+                       if(local_user() && ($rr['uid'] == local_user())
+                               && ($rr['network'] === 'dfrn')) {
+                               $url = $redirect_url;
+                               $sparkle = ' sparkle';
+                       }
+                       else {
+                               $url = $rr['url'];
+                               $sparkle = '';
+                       }
+
+                       $o .= '<div class="contact-block-div"><a class="contact-block-link' . $sparkle . '" href="' . $url . '" ><img class="contact-block-img' . $sparkle . '" src="' . $rr['micro'] . '" title="' . $rr['name'] . ' [' . $rr['url'] . ']" alt="' . $rr['name'] . '" /></a></div>' . "\r\n";
+               }
+               $o .= '</div><div id="contact-block-end"></div>';
+               $o .=  '<div id="viewcontacts"><a id="viewcontacts-link" href="viewcontacts/' . $a->profile['nickname'] . '">' . t('View Contacts') . '</a></div>';
+               
+       }
+       return $o;
+
+}}
+
+if(! function_exists('search')) {
+function search($s) {
+       $a = get_app();
+       $o  = '<div id="search-box">';
+       $o .= '<form action="' . $a->get_baseurl() . '/search' . '" method="get" >';
+       $o .= '<input type="text" name="search" id="search-text" value="' . $s .'" />';
+       $o .= '<input type="submit" name="submit" id="search-submit" value="' . t('Search') . '" />'; 
+       $o .= '</form></div>';
+       return $o;
+}}
+
+if(! function_exists('valid_email')) {
+function valid_email($x){
+       if(preg_match('/^[_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)+$/',$x))
+               return true;
+       return false;
+}}
+
+
+if(! function_exists('gravatar_img')) {
+function gravatar_img($email) {
+       $size = 175;
+       $opt = 'identicon';   // psuedo-random geometric pattern if not found
+       $rating = 'pg';
+       $hash = md5(trim(strtolower($email)));
+       
+       $url = 'http://www.gravatar.com/avatar/' . $hash . '.jpg' 
+               . '?s=' . $size . '&d=' . $opt . '&r=' . $rating;
+
+       logger('gravatar: ' . $email . ' ' . $url);
+       return $url;
+}}
+