5 define ( 'BUILD_ID', 1008 );
6 define ( 'DFRN_PROTOCOL_VERSION', '2.0' );
8 define ( 'EOL', "<br />\r\n" );
9 define ( 'ATOM_TIME', 'Y-m-d\TH:i:s\Z' );
11 // registration policy
13 define ( 'REGISTER_CLOSED', 0 );
14 define ( 'REGISTER_APPROVE', 1 );
15 define ( 'REGISTER_OPEN', 2 );
19 define ( 'REL_VIP', 1);
20 define ( 'REL_FAN', 2);
21 define ( 'REL_BUD', 3);
25 // PAGE_NORMAL is a typical personal profile account
26 // PAGE_SOAPBOX automatically approves all friend requests as REL_FAN, (readonly)
27 // PAGE_COMMUNITY automatically approves all friend requests as REL_FAN, but with
28 // write access to wall and comments (no email and not included in page owner's ACL lists)
29 // PAGE_FREELOVE automatically approves all friend requests as full friends (REL_BUD).
31 define ( 'PAGE_NORMAL', 0 );
32 define ( 'PAGE_SOAPBOX', 1 );
33 define ( 'PAGE_COMMUNITY', 2 );
34 define ( 'PAGE_FREELOVE', 3 );
36 // Maximum number of "people who like (or don't like) this"
37 // that we will list by name
39 define ( 'MAX_LIKERS', 75);
41 // email notification options
43 define ( 'NOTIFY_INTRO', 0x0001 );
44 define ( 'NOTIFY_CONFIRM', 0x0002 );
45 define ( 'NOTIFY_WALL', 0x0004 );
46 define ( 'NOTIFY_COMMENT', 0x0008 );
47 define ( 'NOTIFY_MAIL', 0x0010 );
49 // various namespaces we may need to parse
51 define ( 'NAMESPACE_DFRN' , 'http://purl.org/macgirvin/dfrn/1.0' );
52 define ( 'NAMESPACE_THREAD' , 'http://purl.org/syndication/thread/1.0' );
53 define ( 'NAMESPACE_TOMB' , 'http://purl.org/atompub/tombstones/1.0' );
54 define ( 'NAMESPACE_ACTIVITY', 'http://activitystrea.ms/spec/1.0/' );
55 define ( 'NAMESPACE_ACTIVITY_SCHEMA', 'http://activitystrea.ms/schema/1.0/');
56 define ( 'NAMESPACE_SALMON_ME', 'http://salmon-protocol.org/ns/magic-env');
57 define ( 'NAMESPACE_OSTATUSSUB', 'http://ostatus.org/schema/1.0/subscribe');
59 // activity stream defines
61 define ( 'ACTIVITY_LIKE', NAMESPACE_ACTIVITY_SCHEMA . 'like' );
62 define ( 'ACTIVITY_DISLIKE', NAMESPACE_DFRN . '/dislike' );
63 define ( 'ACTIVITY_OBJ_HEART', NAMESPACE_DFRN . '/heart' );
65 define ( 'ACTIVITY_FRIEND', NAMESPACE_ACTIVITY_SCHEMA . 'make-friend' );
66 define ( 'ACTIVITY_POST', NAMESPACE_ACTIVITY_SCHEMA . 'post' );
67 define ( 'ACTIVITY_UPDATE', NAMESPACE_ACTIVITY_SCHEMA . 'update' );
69 define ( 'ACTIVITY_OBJ_COMMENT', NAMESPACE_ACTIVITY_SCHEMA . 'comment' );
70 define ( 'ACTIVITY_OBJ_NOTE', NAMESPACE_ACTIVITY_SCHEMA . 'note' );
71 define ( 'ACTIVITY_OBJ_PERSON', NAMESPACE_ACTIVITY_SCHEMA . 'person' );
72 define ( 'ACTIVITY_OBJ_PHOTO', NAMESPACE_ACTIVITY_SCHEMA . 'photo' );
73 define ( 'ACTIVITY_OBJ_P_PHOTO', NAMESPACE_ACTIVITY_SCHEMA . 'profile-photo' );
74 define ( 'ACTIVITY_OBJ_ALBUM', NAMESPACE_ACTIVITY_SCHEMA . 'photo-album' );
76 // item weight for query ordering
78 define ( 'GRAVITY_PARENT', 0);
79 define ( 'GRAVITY_LIKE', 3);
80 define ( 'GRAVITY_COMMENT', 6);
83 // Our main application structure for the life of this page
84 // Primarily deals with the URL that got us here
85 // and tries to make some sense of it, and
86 // stores our page contents and config storage
87 // and anything else that might need to be passed around
88 // before we spit the page out.
90 if(! class_exists('App')) {
93 public $module_loaded = false;
102 public $error = false;
110 public $interactive = true;
119 function __construct() {
121 $this->config = array();
122 $this->page = array();
123 $this->pager= array();
125 $this->scheme = ((isset($_SERVER['HTTPS'])
126 && ($_SERVER['HTTPS'])) ? 'https' : 'http' );
127 $this->hostname = str_replace('www.','',
128 $_SERVER['SERVER_NAME']);
129 set_include_path("include/$this->hostname"
130 . PATH_SEPARATOR . 'include'
131 . PATH_SEPARATOR . '.' );
133 if(substr($_SERVER['QUERY_STRING'],0,2) == "q=")
134 $_SERVER['QUERY_STRING'] = substr($_SERVER['QUERY_STRING'],2);
135 $this->cmd = trim($_GET['q'],'/');
138 $this->argv = explode('/',$this->cmd);
139 $this->argc = count($this->argv);
140 if((array_key_exists('0',$this->argv)) && strlen($this->argv[0])) {
141 $this->module = $this->argv[0];
144 $this->module = 'home';
147 if($this->cmd === '.well-known/host-meta')
148 require_once('include/hostxrd.php');
150 $this->pager['page'] = ((x($_GET,'page')) ? $_GET['page'] : 1);
151 $this->pager['itemspage'] = 50;
152 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
153 $this->pager['total'] = 0;
156 function get_baseurl($ssl = false) {
157 if(strlen($this->baseurl))
158 return $this->baseurl;
160 $this->baseurl = (($ssl) ? 'https' : $this->scheme) . "://" . $this->hostname
161 . ((isset($this->path) && strlen($this->path))
162 ? '/' . $this->path : '' );
163 return $this->baseurl;
166 function set_baseurl($url) {
167 $this->baseurl = $url;
168 $this->hostname = basename($url);
171 function get_hostname() {
172 return $this->hostname;
175 function set_hostname($h) {
176 $this->hostname = $h;
179 function set_path($p) {
180 $this->path = ltrim(trim($p),'/');
183 function get_path() {
187 function set_pager_total($n) {
188 $this->pager['total'] = intval($n);
191 function set_pager_itemspage($n) {
192 $this->pager['itemspage'] = intval($n);
193 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
197 function init_pagehead() {
198 $tpl = load_view_file("view/head.tpl");
199 $this->page['htmlhead'] = replace_macros($tpl,array(
200 '$baseurl' => $this->get_baseurl()
204 function set_curl_code($code) {
205 $this->curl_code = $code;
208 function get_curl_code() {
209 return $this->curl_code;
214 // retrieve the App structure
215 // useful in functions which require it but don't get it passed to them
217 if(! function_exists('get_app')) {
224 // Multi-purpose function to check variable state.
225 // Usage: x($var) or $x($array,'key')
226 // returns false if variable/key is not set
227 // if variable is set, returns 1 if has 'non-zero' value, otherwise returns 0.
228 // e.g. x('') or x(0) returns 0;
230 if(! function_exists('x')) {
231 function x($s,$k = NULL) {
233 if((is_array($s)) && (array_key_exists($k,$s))) {
251 // called from db initialisation if db is dead.
253 if(! function_exists('system_unavailable')) {
254 function system_unavailable() {
255 include('system_unavailable.php');
259 // Primarily involved with database upgrade, but also sets the
260 // base url for use in cmdline programs which don't have
261 // $_SERVER variables.
263 if(! function_exists('check_config')) {
264 function check_config(&$a) {
266 load_config('system');
268 $build = get_config('system','build');
270 $build = set_config('system','build',BUILD_ID);
272 $url = get_config('system','url');
274 $url = set_config('system','url',$a->get_baseurl());
276 if($build != BUILD_ID) {
277 $stored = intval($build);
278 $current = intval(BUILD_ID);
279 if(($stored < $current) && file_exists('update.php')) {
280 // We're reporting a different version than what is currently installed.
281 // Run any existing update scripts to bring the database up to current.
283 require_once('update.php');
284 for($x = $stored; $x < $current; $x ++) {
285 if(function_exists('update_' . $x)) {
286 $func = 'update_' . $x;
290 set_config('system','build', BUILD_ID);
297 // This is our template processor.
298 // $s is the string requiring macro substitution.
299 // $r is an array of key value pairs (search => replace)
300 // returns substituted string.
301 // WARNING: this is pretty basic, and doesn't properly handle search strings that are substrings of each other.
302 // For instance if 'test' => "foo" and 'testing' => "bar", testing could become either bar or fooing,
303 // depending on the order in which they were declared in the array.
305 if(! function_exists('replace_macros')) {
306 function replace_macros($s,$r) {
311 if(is_array($r) && count($r)) {
312 foreach ($r as $k => $v ) {
317 return str_replace($search,$replace,$s);
321 // load string translation table for alternate language
323 if(! function_exists('load_translation_table')) {
324 function load_translation_table($lang) {
327 if(file_exists("view/$lang/strings.php"))
328 include("view/$lang/strings.php");
331 // translate string if translation exists
333 if(! function_exists('t')) {
339 return $a->strings[$s];
343 // curl wrapper. If binary flag is true, return binary
346 if(! function_exists('fetch_url')) {
347 function fetch_url($url,$binary = false) {
348 $ch = curl_init($url);
349 if(! $ch) return false;
351 curl_setopt($ch, CURLOPT_HEADER, 0);
352 curl_setopt($ch, CURLOPT_FOLLOWLOCATION,true);
353 curl_setopt($ch, CURLOPT_MAXREDIRS,8);
354 curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
356 // by default we will allow self-signed certs
357 // but you can override this
359 $check_cert = get_config('system','verifyssl');
360 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
362 $prx = get_config('system','proxy');
364 curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
365 curl_setopt($ch, CURLOPT_PROXY, $prx);
366 $prxusr = get_config('system','proxyuser');
368 curl_setopt($ch, CURLOPT_PROXYUSERPWD, $prxusr);
371 curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
374 $info = curl_getinfo($ch);
376 $a->set_curl_code($info['http_code']);
381 // post request to $url. $params is an array of post variables.
383 if(! function_exists('post_url')) {
384 function post_url($url,$params) {
385 $ch = curl_init($url);
386 if(! $ch) return false;
388 curl_setopt($ch, CURLOPT_HEADER, 0);
389 curl_setopt($ch, CURLOPT_FOLLOWLOCATION,true);
390 curl_setopt($ch, CURLOPT_MAXREDIRS,8);
391 curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
392 curl_setopt($ch, CURLOPT_POST,1);
393 curl_setopt($ch, CURLOPT_POSTFIELDS,$params);
394 $check_cert = get_config('system','verifyssl');
395 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
396 $prx = get_config('system','proxy');
398 curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
399 curl_setopt($ch, CURLOPT_PROXY, $prx);
400 $prxusr = get_config('system','proxyuser');
402 curl_setopt($ch, CURLOPT_PROXYUSERPWD, $prxusr);
406 $info = curl_getinfo($ch);
408 $a->set_curl_code($info['http_code']);
413 // random hash, 64 chars
415 if(! function_exists('random_string')) {
416 function random_string() {
417 return(hash('sha256',uniqid(rand(),true)));
420 // This is our primary input filter. The high bit hack only involved some old
421 // IE browser, forget which.
422 // Use this on any text input where angle chars are not valid or permitted
423 // They will be replaced with safer brackets. This may be filtered further
424 // if these are not allowed either.
426 if(! function_exists('notags')) {
427 function notags($string) {
428 // protect against :<> with high-bit set
429 return(str_replace(array("<",">","\xBA","\xBC","\xBE"), array('[',']','','',''), $string));
432 // use this on "body" or "content" input where angle chars shouldn't be removed,
433 // and allow them to be safely displayed.
435 if(! function_exists('escape_tags')) {
436 function escape_tags($string) {
438 return(htmlspecialchars($string));
441 // wrapper for adding a login box. If $register == true provide a registration
442 // link. This will most always depend on the value of $a->config['register_policy'].
443 // returns the complete html for inserting into the page
445 if(! function_exists('login')) {
446 function login($register = false) {
448 $register_html = (($register) ? load_view_file("view/register-link.tpl") : "");
451 if(x($_SESSION,'authenticated')) {
452 $o = load_view_file("view/logout.tpl");
455 $o = load_view_file("view/login.tpl");
457 $o = replace_macros($o,array('$register_html' => $register_html ));
462 // generate a string that's random, but usually pronounceable.
463 // used to generate initial passwords
465 if(! function_exists('autoname')) {
466 function autoname($len) {
468 $vowels = array('a','a','ai','au','e','e','e','ee','ea','i','ie','o','ou','u');
469 if(mt_rand(0,5) == 4)
487 's','sc','sh','sm','sp','st',
495 $midcons = array('ck','ct','gn','ld','lf','lm','lt','mb','mm', 'mn','mp',
496 'nd','ng','nk','nt','rn','rp','rt');
498 $noend = array('bl', 'br', 'cl','cr','dr','fl','fr','gl','gr',
499 'kh', 'kl','kr','mn','pl','pr','rh','tr','qu','wh');
501 $start = mt_rand(0,2);
509 for ($x = 0; $x < $len; $x ++) {
510 $r = mt_rand(0,count($table) - 1);
513 if($table == $vowels)
514 $table = array_merge($cons,$midcons);
520 $word = substr($word,0,$len);
522 foreach($noend as $noe) {
523 if((strlen($word) > 2) && (substr($word,-2) == $noe)) {
524 $word = substr($word,0,-1);
528 if(substr($word,-1) == 'q')
529 $word = substr($word,0,-1);
533 // Used to end the current process, after saving session state.
535 if(! function_exists('killme')) {
537 session_write_close();
541 // redirect to another URL and terminate this process.
543 if(! function_exists('goaway')) {
544 function goaway($s) {
545 header("Location: $s");
549 // Generic XML return
550 // Outputs a basic dfrn XML status structure to STDOUT, with a <status> variable
551 // of $st and an optional text <message> of $message and terminates the current process.
553 if(! function_exists('xml_status')) {
554 function xml_status($st, $message = '') {
557 $xml_message = "\t<message>" . xmlify($message) . "</message>\r\n";
559 header( "Content-type: text/xml" );
560 echo '<?xml version="1.0" encoding="UTF-8"?>'."\r\n";
561 echo "<result>\r\n\t<status>$st</status>\r\n$xml_message</result>\r\n";
565 // Returns the uid of locally logged in user or false.
567 if(! function_exists('local_user')) {
568 function local_user() {
569 if((x($_SESSION,'authenticated')) && (x($_SESSION,'uid')))
570 return $_SESSION['uid'];
574 // Returns contact id of authenticated site visitor or false
576 if(! function_exists('remote_user')) {
577 function remote_user() {
578 if((x($_SESSION,'authenticated')) && (x($_SESSION,'visitor_id')))
579 return $_SESSION['visitor_id'];
583 // contents of $s are displayed prominently on the page the next time
584 // a page is loaded. Usually used for errors or alerts.
586 if(! function_exists('notice')) {
587 function notice($s) {
590 $_SESSION['sysmsg'] .= $s;
593 // wrapper around config to limit the text length of an incoming message
595 if(! function_exists('get_max_import_size')) {
596 function get_max_import_size() {
598 return ((x($a->config,'max_import_size')) ? $a->config['max_import_size'] : 0 );
602 // escape text ($str) for XML transport
603 // returns escaped text.
605 if(! function_exists('xmlify')) {
606 function xmlify($str) {
609 for($x = 0; $x < strlen($str); $x ++) {
640 $buffer = trim($buffer);
645 // pass xml escaped text ($s), returns unescaped text
647 if(! function_exists('unxmlify')) {
648 function unxmlify($s) {
649 $ret = str_replace('&','&', $s);
650 $ret = str_replace(array('<','>','"','''),array('<','>','"',"'"),$ret);
654 // convenience wrapper, reverse the operation "bin2hex"
656 if(! function_exists('hex2bin')) {
657 function hex2bin($s) {
658 return(pack("H*",$s));
661 // Automatic pagination.
662 // To use, get the count of total items.
663 // Then call $a->set_pager_total($number_items);
664 // Optionally call $a->set_pager_itemspage($n) to the number of items to display on each page
665 // Then call paginate($a) after the end of the display loop to insert the pager block on the page
666 // (assuming there are enough items to paginate).
667 // When using with SQL, the setting LIMIT %d, %d => $a->pager['start'],$a->pager['itemspage']
668 // will limit the results to the correct items for the current page.
669 // The actual page handling is then accomplished at the application layer.
671 if(! function_exists('paginate')) {
672 function paginate(&$a) {
674 $stripped = ereg_replace("(&page=[0-9]*)","",$_SERVER['QUERY_STRING']);
675 $stripped = str_replace('q=','',$stripped);
676 $stripped = trim($stripped,'/');
677 $url = $a->get_baseurl() . '/' . $stripped;
680 if($a->pager['total'] > $a->pager['itemspage']) {
681 $o .= '<div class="pager">';
682 if($a->pager['page'] != 1)
683 $o .= '<span class="pager_prev">'."<a href=\"$url".'&page='.($a->pager['page'] - 1).'">' . t('prev') . '</a></span> ';
685 $o .= "<span class=\"pager_first\"><a href=\"$url"."&page=1\">" . t('first') . "</a></span> ";
687 $numpages = $a->pager['total'] / $a->pager['itemspage'];
690 $numstop = $numpages;
693 $numstart = (($pagenum > 7) ? ($pagenum - 7) : 1);
694 $numstop = (($pagenum > ($numpages - 7)) ? $numpages : ($numstart + 14));
697 for($i = $numstart; $i <= $numstop; $i++){
698 if($i == $a->pager['page'])
699 $o .= '<span class="pager_current">'.(($i < 10) ? ' '.$i : $i);
701 $o .= "<span class=\"pager_n\"><a href=\"$url"."&page=$i\">".(($i < 10) ? ' '.$i : $i)."</a>";
705 if(($a->pager['total'] % $a->pager['itemspage']) != 0) {
706 if($i == $a->pager['page'])
707 $o .= '<span class="pager_current">'.(($i < 10) ? ' '.$i : $i);
709 $o .= "<span class=\"pager_n\"><a href=\"$url"."&page=$i\">".(($i < 10) ? ' '.$i : $i)."</a>";
713 $lastpage = (($numpages > intval($numpages)) ? intval($numpages)+1 : $numpages);
714 $o .= "<span class=\"pager_last\"><a href=\"$url"."&page=$lastpage\">" . t('last') . "</a></span> ";
716 if(($a->pager['total'] - ($a->pager['itemspage'] * $a->pager['page'])) > 0)
717 $o .= '<span class="pager_next">'."<a href=\"$url"."&page=".($a->pager['page'] + 1).'">' . t('next') . '</a></span>';
718 $o .= '</div>'."\r\n";
723 // Turn user/group ACLs stored as angle bracketed text into arrays
725 if(! function_exists('expand_acl')) {
726 function expand_acl($s) {
727 // turn string array of angle-bracketed elements into numeric array
728 // e.g. "<1><2><3>" => array(1,2,3);
732 $t = str_replace('<','',$s);
733 $a = explode('>',$t);
736 $ret[] = intval($aa);
742 // Used to wrap ACL elements in angle brackets for storage
744 if(! function_exists('sanitise_acl')) {
745 function sanitise_acl(&$item) {
747 $item = '<' . intval(notags(trim($item))) . '>';
752 // retrieve a "family" of config variables from database to cached storage
754 if(! function_exists('load_config')) {
755 function load_config($family) {
757 $r = q("SELECT * FROM `config` WHERE `cat` = '%s'",
763 $a->config[$family][$k] = $rr['v'];
768 // get a particular config variable given the family name
769 // and key. Returns false if not set.
770 // $instore is only used by the set_config function
771 // to determine if the key already exists in the DB
772 // If a key is found in the DB but doesn't exist in
773 // local config cache, pull it into the cache so we don't have
774 // to hit the DB again for this item.
776 if(! function_exists('get_config')) {
777 function get_config($family, $key, $instore = false) {
782 if(isset($a->config[$family][$key])) {
783 if($a->config[$family][$key] === '!<unset>!') {
786 return $a->config[$family][$key];
789 $ret = q("SELECT `v` FROM `config` WHERE `cat` = '%s' AND `k` = '%s' LIMIT 1",
794 $a->config[$family][$key] = $ret[0]['v'];
798 $a->config[$family][$key] = '!<unset>!';
803 // Store a config value ($value) in the category ($family)
804 // under the key ($key)
805 // Return the value, or false if the database update failed
807 if(! function_exists('set_config')) {
808 function set_config($family,$key,$value) {
811 $a->config[$family][$key] = $value;
813 if(get_config($family,$key,true) === false) {
814 $ret = q("INSERT INTO `config` ( `cat`, `k`, `v` ) VALUES ( '%s', '%s', '%s' ) ",
823 $ret = q("UPDATE `config` SET `v` = '%s' WHERE `cat` = '%s' AND `k` = '%s' LIMIT 1",
833 // convert an XML document to a normalised, case-corrected array
836 if(! function_exists('convert_xml_element_to_array')) {
837 function convert_xml_element_to_array($xml_element, &$recursion_depth=0) {
839 // If we're getting too deep, bail out
840 if ($recursion_depth > 512) {
844 if (!is_string($xml_element) &&
845 !is_array($xml_element) &&
846 (get_class($xml_element) == 'SimpleXMLElement')) {
847 $xml_element_copy = $xml_element;
848 $xml_element = get_object_vars($xml_element);
851 if (is_array($xml_element)) {
852 $result_array = array();
853 if (count($xml_element) <= 0) {
854 return (trim(strval($xml_element_copy)));
857 foreach($xml_element as $key=>$value) {
860 $result_array[strtolower($key)] =
861 convert_xml_element_to_array($value, $recursion_depth);
864 if ($recursion_depth == 0) {
865 $temp_array = $result_array;
866 $result_array = array(
867 strtolower($xml_element_copy->getName()) => $temp_array,
871 return ($result_array);
874 return (trim(strval($xml_element)));
878 // Given an email style address, perform webfinger lookup and
879 // return the resulting DFRN profile URL, or if no DFRN profile URL
880 // is located, returns an OStatus subscription template (prefixed
881 // with the string 'stat:' to identify it as on OStatus template).
882 // If this isn't an email style address just return $s.
883 // Return an empty string if email-style addresses but webfinger fails,
884 // or if the resultant personal XRD doesn't contain a supported
885 // subscription/friend-request attribute.
887 if(! function_exists('webfinger_dfrn')) {
888 function webfinger_dfrn($s) {
889 if(! strstr($s,'@')) {
892 $links = webfinger($s);
894 foreach($links as $link)
895 if($link['@attributes']['rel'] === NAMESPACE_DFRN)
896 return $link['@attributes']['href'];
897 foreach($links as $link)
898 if($link['@attributes']['rel'] === NAMESPACE_OSTATUSSUB)
899 return 'stat:' . $link['@attributes']['template'];
904 // Given an email style address, perform webfinger lookup and
905 // return the array of link attributes from the personal XRD file.
906 // On error/failure return an empty array.
909 if(! function_exists('webfinger')) {
910 function webfinger($s) {
913 $host = substr($s,strpos($s,'@') + 1);
916 $tpl = fetch_lrdd_template($host);
918 $pxrd = str_replace('{uri}', urlencode('acct://'.$s), $tpl);
919 $links = fetch_xrd_links($pxrd);
920 if(! count($links)) {
921 // try without the double slashes
922 $pxrd = str_replace('{uri}', urlencode('acct:'.$s), $tpl);
923 $links = fetch_xrd_links($pxrd);
931 // Given a host name, locate the LRDD template from that
932 // host. Returns the LRDD template or an empty string on
935 if(! function_exists('fetch_lrdd_template')) {
936 function fetch_lrdd_template($host) {
938 $url = 'http://' . $host . '/.well-known/host-meta' ;
939 $links = fetch_xrd_links($url);
941 foreach($links as $link)
942 if($link['@attributes']['rel'] && $link['@attributes']['rel'] === 'lrdd')
943 $tpl = $link['@attributes']['template'];
945 if(! strpos($tpl,'{uri}'))
950 // Given a URL, retrieve the page as an XRD document.
951 // Return an array of links.
952 // on error/failure return empty array.
954 if(! function_exists('fetch_xrd_links')) {
955 function fetch_xrd_links($url) {
957 $xml = fetch_url($url);
960 $h = simplexml_load_string($xml);
961 $arr = convert_xml_element_to_array($h);
963 if(isset($arr['xrd']['link'])) {
964 $link = $arr['xrd']['link'];
965 if(! isset($link[0]))
966 $links = array($link);
974 // Convert an ACL array to a storable string
976 if(! function_exists('perms2str')) {
977 function perms2str($p) {
981 array_walk($tmp,'sanitise_acl');
982 $ret = implode('',$tmp);
987 // generate a guaranteed unique (for this domain) item ID for ATOM
988 // safe from birthday paradox
990 if(! function_exists('item_new_uri')) {
991 function item_new_uri($hostname,$uid) {
995 $hash = random_string();
997 $uri = "urn:X-dfrn:" . $hostname . ':' . $uid . ':' . $hash;
999 $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' LIMIT 1",
1003 } while($dups == true);
1007 // Generate a guaranteed unique photo ID.
1008 // safe from birthday paradox
1010 if(! function_exists('photo_new_resource')) {
1011 function photo_new_resource() {
1015 $resource = hash('md5',uniqid(mt_rand(),true));
1016 $r = q("SELECT `id` FROM `photo` WHERE `resource-id` = '%s' LIMIT 1",
1021 } while($found == true);
1026 // Returns logged in user ID
1028 if(! function_exists('get_uid')) {
1029 function get_uid() {
1030 return local_user();
1033 // Take a URL from the wild, prepend http:// if necessary
1034 // and check DNS to see if it's real
1035 // return true if it's OK, false if something is wrong with it
1037 if(! function_exists('validate_url')) {
1038 function validate_url(&$url) {
1039 if(substr($url,0,4) != 'http')
1040 $url = 'http://' . $url;
1041 $h = parse_url($url);
1046 if(! checkdnsrr($h['host'], 'ANY')) {
1052 // Check $url against our list of allowed sites,
1053 // wildcards allowed. If allowed_sites is unset return true;
1054 // If url is allowed, return true.
1055 // otherwise, return false
1057 if(! function_exists('allowed_url')) {
1058 function allowed_url($url) {
1060 $h = parse_url($url);
1066 $str_allowed = get_config('system','allowed_sites');
1072 $host = strtolower($h['host']);
1074 // always allow our own site
1076 if($host == strtolower($_SERVER['SERVER_NAME']))
1079 $fnmatch = function_exists('fnmatch');
1080 $allowed = explode(',',$str_allowed);
1082 if(count($allowed)) {
1083 foreach($allowed as $a) {
1084 $pat = strtolower(trim($a));
1085 if(($fnmatch && fnmatch($pat,$host)) || ($pat == $host)) {
1094 // check if email address is allowed to register here.
1095 // Compare against our list (wildcards allowed).
1096 // Returns false if not allowed, true if allowed or if
1097 // allowed list is not configured.
1099 if(! function_exists('allowed_email')) {
1100 function allowed_email($email) {
1103 $domain = strtolower(substr($email,strpos($email,'@') + 1));
1107 $str_allowed = get_config('system','allowed_email');
1113 $fnmatch = function_exists('fnmatch');
1114 $allowed = explode(',',$str_allowed);
1116 if(count($allowed)) {
1117 foreach($allowed as $a) {
1118 $pat = strtolower(trim($a));
1119 if(($fnmatch && fnmatch($pat,$host)) || ($pat == $host)) {
1128 // Format the like/dislike text for a profile item
1129 // $cnt = number of people who like/dislike the item
1130 // $arr = array of pre-linked names of likers/dislikers
1131 // $type = one of 'like, 'dislike'
1133 // returns formatted text
1135 if(! function_exists('format_like')) {
1136 function format_like($cnt,$arr,$type,$id) {
1138 $o .= $arr[0] . (($type === 'like') ? t(' likes this.') : t(' doesn\'t like this.')) . EOL ;
1140 $o .= '<span class="fakelink" onclick="openClose(\'' . $type . 'list-' . $id . '\');" >'
1141 . $cnt . ' ' . t('people') . '</span> ' . (($type === 'like') ? t('like this.') : t('don\'t like this.')) . EOL ;
1142 $total = count($arr);
1143 if($total >= MAX_LIKERS)
1144 $arr = array_slice($arr, 0, MAX_LIKERS - 1);
1145 if($total < MAX_LIKERS)
1146 $arr[count($arr)-1] = t('and') . ' ' . $arr[count($arr)-1];
1147 $str = implode(', ', $arr);
1148 if($total >= MAX_LIKERS)
1149 $str .= t(', and ') . $total - MAX_LIKERS . t(' other people');
1150 $str .= (($type === 'like') ? t(' like this.') : t(' don\'t like this.'));
1151 $o .= '<div id="' . $type . 'list-' . $id . '" style="display: none;" >' . $str . '</div>';
1157 // wrapper to load a view template, checking for alternate
1158 // languages before falling back to the default
1160 if(! function_exists('load_view_file')) {
1161 function load_view_file($s) {
1164 $lang = get_config('system','language');
1165 if($lang && file_exists("$d/$lang/$b"))
1166 return file_get_contents("$d/$lang/$b");
1167 return file_get_contents($s);