5 define ( 'BUILD_ID', 1010 );
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']) && ($_SERVER['HTTPS'])) ? 'https' : 'http' );
126 $this->hostname = $_SERVER['SERVER_NAME'];
127 set_include_path("include/$this->hostname" . PATH_SEPARATOR . 'include' . PATH_SEPARATOR . '.' );
129 if(substr($_SERVER['QUERY_STRING'],0,2) == "q=")
130 $_SERVER['QUERY_STRING'] = substr($_SERVER['QUERY_STRING'],2);
131 $this->cmd = trim($_GET['q'],'/');
134 $this->argv = explode('/',$this->cmd);
135 $this->argc = count($this->argv);
136 if((array_key_exists('0',$this->argv)) && strlen($this->argv[0])) {
137 $this->module = $this->argv[0];
140 $this->module = 'home';
143 if($this->cmd === '.well-known/host-meta')
144 require_once('include/hostxrd.php');
146 $this->pager['page'] = ((x($_GET,'page')) ? $_GET['page'] : 1);
147 $this->pager['itemspage'] = 50;
148 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
149 $this->pager['total'] = 0;
152 function get_baseurl($ssl = false) {
153 if(strlen($this->baseurl))
154 return $this->baseurl;
156 $this->baseurl = (($ssl) ? 'https' : $this->scheme) . "://" . $this->hostname . ((isset($this->path) && strlen($this->path)) ? '/' . $this->path : '' );
157 return $this->baseurl;
160 function set_baseurl($url) {
161 $this->baseurl = $url;
162 $this->hostname = basename($url);
165 function get_hostname() {
166 return $this->hostname;
169 function set_hostname($h) {
170 $this->hostname = $h;
173 function set_path($p) {
174 $this->path = trim(trim($p),'/');
177 function get_path() {
181 function set_pager_total($n) {
182 $this->pager['total'] = intval($n);
185 function set_pager_itemspage($n) {
186 $this->pager['itemspage'] = intval($n);
187 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
191 function init_pagehead() {
192 $tpl = load_view_file("view/head.tpl");
193 $this->page['htmlhead'] = replace_macros($tpl,array(
194 '$baseurl' => $this->get_baseurl()
198 function set_curl_code($code) {
199 $this->curl_code = $code;
202 function get_curl_code() {
203 return $this->curl_code;
208 // retrieve the App structure
209 // useful in functions which require it but don't get it passed to them
211 if(! function_exists('get_app')) {
218 // Multi-purpose function to check variable state.
219 // Usage: x($var) or $x($array,'key')
220 // returns false if variable/key is not set
221 // if variable is set, returns 1 if has 'non-zero' value, otherwise returns 0.
222 // e.g. x('') or x(0) returns 0;
224 if(! function_exists('x')) {
225 function x($s,$k = NULL) {
227 if((is_array($s)) && (array_key_exists($k,$s))) {
245 // called from db initialisation if db is dead.
247 if(! function_exists('system_unavailable')) {
248 function system_unavailable() {
249 include('system_unavailable.php');
253 // Primarily involved with database upgrade, but also sets the
254 // base url for use in cmdline programs which don't have
255 // $_SERVER variables.
257 if(! function_exists('check_config')) {
258 function check_config(&$a) {
260 load_config('system');
262 $build = get_config('system','build');
264 $build = set_config('system','build',BUILD_ID);
266 $url = get_config('system','url');
268 $url = set_config('system','url',$a->get_baseurl());
270 if($build != BUILD_ID) {
271 $stored = intval($build);
272 $current = intval(BUILD_ID);
273 if(($stored < $current) && file_exists('update.php')) {
274 // We're reporting a different version than what is currently installed.
275 // Run any existing update scripts to bring the database up to current.
277 require_once('update.php');
278 for($x = $stored; $x < $current; $x ++) {
279 if(function_exists('update_' . $x)) {
280 $func = 'update_' . $x;
284 set_config('system','build', BUILD_ID);
291 // This is our template processor.
292 // $s is the string requiring macro substitution.
293 // $r is an array of key value pairs (search => replace)
294 // returns substituted string.
295 // WARNING: this is pretty basic, and doesn't properly handle search strings that are substrings of each other.
296 // For instance if 'test' => "foo" and 'testing' => "bar", testing could become either bar or fooing,
297 // depending on the order in which they were declared in the array.
299 if(! function_exists('replace_macros')) {
300 function replace_macros($s,$r) {
305 if(is_array($r) && count($r)) {
306 foreach ($r as $k => $v ) {
311 return str_replace($search,$replace,$s);
315 // load string translation table for alternate language
317 if(! function_exists('load_translation_table')) {
318 function load_translation_table($lang) {
321 if(file_exists("view/$lang/strings.php"))
322 include("view/$lang/strings.php");
325 // translate string if translation exists
327 if(! function_exists('t')) {
333 return $a->strings[$s];
337 // curl wrapper. If binary flag is true, return binary
340 if(! function_exists('fetch_url')) {
341 function fetch_url($url,$binary = false) {
342 $ch = curl_init($url);
343 if(! $ch) return false;
345 curl_setopt($ch, CURLOPT_HEADER, 0);
346 curl_setopt($ch, CURLOPT_FOLLOWLOCATION,true);
347 curl_setopt($ch, CURLOPT_MAXREDIRS,8);
348 curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
350 // by default we will allow self-signed certs
351 // but you can override this
353 $check_cert = get_config('system','verifyssl');
354 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
356 $prx = get_config('system','proxy');
358 curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
359 curl_setopt($ch, CURLOPT_PROXY, $prx);
360 $prxusr = get_config('system','proxyuser');
362 curl_setopt($ch, CURLOPT_PROXYUSERPWD, $prxusr);
365 curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
368 $info = curl_getinfo($ch);
370 $a->set_curl_code($info['http_code']);
375 // post request to $url. $params is an array of post variables.
377 if(! function_exists('post_url')) {
378 function post_url($url,$params) {
379 $ch = curl_init($url);
380 if(! $ch) return false;
382 curl_setopt($ch, CURLOPT_HEADER, 0);
383 curl_setopt($ch, CURLOPT_FOLLOWLOCATION,true);
384 curl_setopt($ch, CURLOPT_MAXREDIRS,8);
385 curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
386 curl_setopt($ch, CURLOPT_POST,1);
387 curl_setopt($ch, CURLOPT_POSTFIELDS,$params);
388 $check_cert = get_config('system','verifyssl');
389 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
390 $prx = get_config('system','proxy');
392 curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
393 curl_setopt($ch, CURLOPT_PROXY, $prx);
394 $prxusr = get_config('system','proxyuser');
396 curl_setopt($ch, CURLOPT_PROXYUSERPWD, $prxusr);
400 $info = curl_getinfo($ch);
402 $a->set_curl_code($info['http_code']);
407 // random hash, 64 chars
409 if(! function_exists('random_string')) {
410 function random_string() {
411 return(hash('sha256',uniqid(rand(),true)));
414 // This is our primary input filter. The high bit hack only involved some old
415 // IE browser, forget which.
416 // Use this on any text input where angle chars are not valid or permitted
417 // They will be replaced with safer brackets. This may be filtered further
418 // if these are not allowed either.
420 if(! function_exists('notags')) {
421 function notags($string) {
422 // protect against :<> with high-bit set
423 return(str_replace(array("<",">","\xBA","\xBC","\xBE"), array('[',']','','',''), $string));
426 // use this on "body" or "content" input where angle chars shouldn't be removed,
427 // and allow them to be safely displayed.
429 if(! function_exists('escape_tags')) {
430 function escape_tags($string) {
432 return(htmlspecialchars($string));
435 // wrapper for adding a login box. If $register == true provide a registration
436 // link. This will most always depend on the value of $a->config['register_policy'].
437 // returns the complete html for inserting into the page
439 if(! function_exists('login')) {
440 function login($register = false) {
442 $register_html = (($register) ? load_view_file("view/register-link.tpl") : "");
445 if(x($_SESSION,'authenticated')) {
446 $o = load_view_file("view/logout.tpl");
449 $o = load_view_file("view/login.tpl");
451 $o = replace_macros($o,array('$register_html' => $register_html ));
456 // generate a string that's random, but usually pronounceable.
457 // used to generate initial passwords
459 if(! function_exists('autoname')) {
460 function autoname($len) {
462 $vowels = array('a','a','ai','au','e','e','e','ee','ea','i','ie','o','ou','u');
463 if(mt_rand(0,5) == 4)
481 's','sc','sh','sm','sp','st',
489 $midcons = array('ck','ct','gn','ld','lf','lm','lt','mb','mm', 'mn','mp',
490 'nd','ng','nk','nt','rn','rp','rt');
492 $noend = array('bl', 'br', 'cl','cr','dr','fl','fr','gl','gr',
493 'kh', 'kl','kr','mn','pl','pr','rh','tr','qu','wh');
495 $start = mt_rand(0,2);
503 for ($x = 0; $x < $len; $x ++) {
504 $r = mt_rand(0,count($table) - 1);
507 if($table == $vowels)
508 $table = array_merge($cons,$midcons);
514 $word = substr($word,0,$len);
516 foreach($noend as $noe) {
517 if((strlen($word) > 2) && (substr($word,-2) == $noe)) {
518 $word = substr($word,0,-1);
522 if(substr($word,-1) == 'q')
523 $word = substr($word,0,-1);
527 // Used to end the current process, after saving session state.
529 if(! function_exists('killme')) {
531 session_write_close();
535 // redirect to another URL and terminate this process.
537 if(! function_exists('goaway')) {
538 function goaway($s) {
539 header("Location: $s");
543 // Generic XML return
544 // Outputs a basic dfrn XML status structure to STDOUT, with a <status> variable
545 // of $st and an optional text <message> of $message and terminates the current process.
547 if(! function_exists('xml_status')) {
548 function xml_status($st, $message = '') {
551 $xml_message = "\t<message>" . xmlify($message) . "</message>\r\n";
553 header( "Content-type: text/xml" );
554 echo '<?xml version="1.0" encoding="UTF-8"?>'."\r\n";
555 echo "<result>\r\n\t<status>$st</status>\r\n$xml_message</result>\r\n";
559 // Returns the uid of locally logged in user or false.
561 if(! function_exists('local_user')) {
562 function local_user() {
563 if((x($_SESSION,'authenticated')) && (x($_SESSION,'uid')))
564 return intval($_SESSION['uid']);
568 // Returns contact id of authenticated site visitor or false
570 if(! function_exists('remote_user')) {
571 function remote_user() {
572 if((x($_SESSION,'authenticated')) && (x($_SESSION,'visitor_id')))
573 return intval($_SESSION['visitor_id']);
577 // contents of $s are displayed prominently on the page the next time
578 // a page is loaded. Usually used for errors or alerts.
580 if(! function_exists('notice')) {
581 function notice($s) {
584 $_SESSION['sysmsg'] .= $s;
587 // wrapper around config to limit the text length of an incoming message
589 if(! function_exists('get_max_import_size')) {
590 function get_max_import_size() {
592 return ((x($a->config,'max_import_size')) ? $a->config['max_import_size'] : 0 );
596 // escape text ($str) for XML transport
597 // returns escaped text.
599 if(! function_exists('xmlify')) {
600 function xmlify($str) {
603 for($x = 0; $x < strlen($str); $x ++) {
634 $buffer = trim($buffer);
639 // pass xml escaped text ($s), returns unescaped text
641 if(! function_exists('unxmlify')) {
642 function unxmlify($s) {
643 $ret = str_replace('&','&', $s);
644 $ret = str_replace(array('<','>','"','''),array('<','>','"',"'"),$ret);
648 // convenience wrapper, reverse the operation "bin2hex"
650 if(! function_exists('hex2bin')) {
651 function hex2bin($s) {
652 return(pack("H*",$s));
655 // Automatic pagination.
656 // To use, get the count of total items.
657 // Then call $a->set_pager_total($number_items);
658 // Optionally call $a->set_pager_itemspage($n) to the number of items to display on each page
659 // Then call paginate($a) after the end of the display loop to insert the pager block on the page
660 // (assuming there are enough items to paginate).
661 // When using with SQL, the setting LIMIT %d, %d => $a->pager['start'],$a->pager['itemspage']
662 // will limit the results to the correct items for the current page.
663 // The actual page handling is then accomplished at the application layer.
665 if(! function_exists('paginate')) {
666 function paginate(&$a) {
668 $stripped = ereg_replace("(&page=[0-9]*)","",$_SERVER['QUERY_STRING']);
669 $stripped = str_replace('q=','',$stripped);
670 $stripped = trim($stripped,'/');
671 $url = $a->get_baseurl() . '/' . $stripped;
674 if($a->pager['total'] > $a->pager['itemspage']) {
675 $o .= '<div class="pager">';
676 if($a->pager['page'] != 1)
677 $o .= '<span class="pager_prev">'."<a href=\"$url".'&page='.($a->pager['page'] - 1).'">' . t('prev') . '</a></span> ';
679 $o .= "<span class=\"pager_first\"><a href=\"$url"."&page=1\">" . t('first') . "</a></span> ";
681 $numpages = $a->pager['total'] / $a->pager['itemspage'];
684 $numstop = $numpages;
687 $numstart = (($pagenum > 7) ? ($pagenum - 7) : 1);
688 $numstop = (($pagenum > ($numpages - 7)) ? $numpages : ($numstart + 14));
691 for($i = $numstart; $i <= $numstop; $i++){
692 if($i == $a->pager['page'])
693 $o .= '<span class="pager_current">'.(($i < 10) ? ' '.$i : $i);
695 $o .= "<span class=\"pager_n\"><a href=\"$url"."&page=$i\">".(($i < 10) ? ' '.$i : $i)."</a>";
699 if(($a->pager['total'] % $a->pager['itemspage']) != 0) {
700 if($i == $a->pager['page'])
701 $o .= '<span class="pager_current">'.(($i < 10) ? ' '.$i : $i);
703 $o .= "<span class=\"pager_n\"><a href=\"$url"."&page=$i\">".(($i < 10) ? ' '.$i : $i)."</a>";
707 $lastpage = (($numpages > intval($numpages)) ? intval($numpages)+1 : $numpages);
708 $o .= "<span class=\"pager_last\"><a href=\"$url"."&page=$lastpage\">" . t('last') . "</a></span> ";
710 if(($a->pager['total'] - ($a->pager['itemspage'] * $a->pager['page'])) > 0)
711 $o .= '<span class="pager_next">'."<a href=\"$url"."&page=".($a->pager['page'] + 1).'">' . t('next') . '</a></span>';
712 $o .= '</div>'."\r\n";
717 // Turn user/group ACLs stored as angle bracketed text into arrays
719 if(! function_exists('expand_acl')) {
720 function expand_acl($s) {
721 // turn string array of angle-bracketed elements into numeric array
722 // e.g. "<1><2><3>" => array(1,2,3);
726 $t = str_replace('<','',$s);
727 $a = explode('>',$t);
730 $ret[] = intval($aa);
736 // Used to wrap ACL elements in angle brackets for storage
738 if(! function_exists('sanitise_acl')) {
739 function sanitise_acl(&$item) {
741 $item = '<' . intval(notags(trim($item))) . '>';
746 // retrieve a "family" of config variables from database to cached storage
748 if(! function_exists('load_config')) {
749 function load_config($family) {
751 $r = q("SELECT * FROM `config` WHERE `cat` = '%s'",
757 $a->config[$family][$k] = $rr['v'];
762 // get a particular config variable given the family name
763 // and key. Returns false if not set.
764 // $instore is only used by the set_config function
765 // to determine if the key already exists in the DB
766 // If a key is found in the DB but doesn't exist in
767 // local config cache, pull it into the cache so we don't have
768 // to hit the DB again for this item.
770 if(! function_exists('get_config')) {
771 function get_config($family, $key, $instore = false) {
776 if(isset($a->config[$family][$key])) {
777 if($a->config[$family][$key] === '!<unset>!') {
780 return $a->config[$family][$key];
783 $ret = q("SELECT `v` FROM `config` WHERE `cat` = '%s' AND `k` = '%s' LIMIT 1",
788 $a->config[$family][$key] = $ret[0]['v'];
792 $a->config[$family][$key] = '!<unset>!';
797 // Store a config value ($value) in the category ($family)
798 // under the key ($key)
799 // Return the value, or false if the database update failed
801 if(! function_exists('set_config')) {
802 function set_config($family,$key,$value) {
805 $a->config[$family][$key] = $value;
807 if(get_config($family,$key,true) === false) {
808 $ret = q("INSERT INTO `config` ( `cat`, `k`, `v` ) VALUES ( '%s', '%s', '%s' ) ",
817 $ret = q("UPDATE `config` SET `v` = '%s' WHERE `cat` = '%s' AND `k` = '%s' LIMIT 1",
827 // convert an XML document to a normalised, case-corrected array
830 if(! function_exists('convert_xml_element_to_array')) {
831 function convert_xml_element_to_array($xml_element, &$recursion_depth=0) {
833 // If we're getting too deep, bail out
834 if ($recursion_depth > 512) {
838 if (!is_string($xml_element) &&
839 !is_array($xml_element) &&
840 (get_class($xml_element) == 'SimpleXMLElement')) {
841 $xml_element_copy = $xml_element;
842 $xml_element = get_object_vars($xml_element);
845 if (is_array($xml_element)) {
846 $result_array = array();
847 if (count($xml_element) <= 0) {
848 return (trim(strval($xml_element_copy)));
851 foreach($xml_element as $key=>$value) {
854 $result_array[strtolower($key)] =
855 convert_xml_element_to_array($value, $recursion_depth);
858 if ($recursion_depth == 0) {
859 $temp_array = $result_array;
860 $result_array = array(
861 strtolower($xml_element_copy->getName()) => $temp_array,
865 return ($result_array);
868 return (trim(strval($xml_element)));
872 // Given an email style address, perform webfinger lookup and
873 // return the resulting DFRN profile URL, or if no DFRN profile URL
874 // is located, returns an OStatus subscription template (prefixed
875 // with the string 'stat:' to identify it as on OStatus template).
876 // If this isn't an email style address just return $s.
877 // Return an empty string if email-style addresses but webfinger fails,
878 // or if the resultant personal XRD doesn't contain a supported
879 // subscription/friend-request attribute.
881 if(! function_exists('webfinger_dfrn')) {
882 function webfinger_dfrn($s) {
883 if(! strstr($s,'@')) {
886 $links = webfinger($s);
888 foreach($links as $link)
889 if($link['@attributes']['rel'] === NAMESPACE_DFRN)
890 return $link['@attributes']['href'];
891 foreach($links as $link)
892 if($link['@attributes']['rel'] === NAMESPACE_OSTATUSSUB)
893 return 'stat:' . $link['@attributes']['template'];
898 // Given an email style address, perform webfinger lookup and
899 // return the array of link attributes from the personal XRD file.
900 // On error/failure return an empty array.
903 if(! function_exists('webfinger')) {
904 function webfinger($s) {
907 $host = substr($s,strpos($s,'@') + 1);
910 $tpl = fetch_lrdd_template($host);
912 $pxrd = str_replace('{uri}', urlencode('acct://'.$s), $tpl);
913 $links = fetch_xrd_links($pxrd);
914 if(! count($links)) {
915 // try without the double slashes
916 $pxrd = str_replace('{uri}', urlencode('acct:'.$s), $tpl);
917 $links = fetch_xrd_links($pxrd);
925 // Given a host name, locate the LRDD template from that
926 // host. Returns the LRDD template or an empty string on
929 if(! function_exists('fetch_lrdd_template')) {
930 function fetch_lrdd_template($host) {
932 $url = 'http://' . $host . '/.well-known/host-meta' ;
933 $links = fetch_xrd_links($url);
935 foreach($links as $link)
936 if($link['@attributes']['rel'] && $link['@attributes']['rel'] === 'lrdd')
937 $tpl = $link['@attributes']['template'];
939 if(! strpos($tpl,'{uri}'))
944 // Given a URL, retrieve the page as an XRD document.
945 // Return an array of links.
946 // on error/failure return empty array.
948 if(! function_exists('fetch_xrd_links')) {
949 function fetch_xrd_links($url) {
951 $xml = fetch_url($url);
954 $h = simplexml_load_string($xml);
955 $arr = convert_xml_element_to_array($h);
957 if(isset($arr['xrd']['link'])) {
958 $link = $arr['xrd']['link'];
959 if(! isset($link[0]))
960 $links = array($link);
968 // Convert an ACL array to a storable string
970 if(! function_exists('perms2str')) {
971 function perms2str($p) {
975 array_walk($tmp,'sanitise_acl');
976 $ret = implode('',$tmp);
981 // generate a guaranteed unique (for this domain) item ID for ATOM
982 // safe from birthday paradox
984 if(! function_exists('item_new_uri')) {
985 function item_new_uri($hostname,$uid) {
989 $hash = random_string();
991 $uri = "urn:X-dfrn:" . $hostname . ':' . $uid . ':' . $hash;
993 $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' LIMIT 1",
997 } while($dups == true);
1001 // Generate a guaranteed unique photo ID.
1002 // safe from birthday paradox
1004 if(! function_exists('photo_new_resource')) {
1005 function photo_new_resource() {
1009 $resource = hash('md5',uniqid(mt_rand(),true));
1010 $r = q("SELECT `id` FROM `photo` WHERE `resource-id` = '%s' LIMIT 1",
1015 } while($found == true);
1020 // Take a URL from the wild, prepend http:// if necessary
1021 // and check DNS to see if it's real
1022 // return true if it's OK, false if something is wrong with it
1024 if(! function_exists('validate_url')) {
1025 function validate_url(&$url) {
1026 if(substr($url,0,4) != 'http')
1027 $url = 'http://' . $url;
1028 $h = parse_url($url);
1033 if(! checkdnsrr($h['host'], 'ANY')) {
1039 // Check $url against our list of allowed sites,
1040 // wildcards allowed. If allowed_sites is unset return true;
1041 // If url is allowed, return true.
1042 // otherwise, return false
1044 if(! function_exists('allowed_url')) {
1045 function allowed_url($url) {
1047 $h = parse_url($url);
1053 $str_allowed = get_config('system','allowed_sites');
1059 $host = strtolower($h['host']);
1061 // always allow our own site
1063 if($host == strtolower($_SERVER['SERVER_NAME']))
1066 $fnmatch = function_exists('fnmatch');
1067 $allowed = explode(',',$str_allowed);
1069 if(count($allowed)) {
1070 foreach($allowed as $a) {
1071 $pat = strtolower(trim($a));
1072 if(($fnmatch && fnmatch($pat,$host)) || ($pat == $host)) {
1081 // check if email address is allowed to register here.
1082 // Compare against our list (wildcards allowed).
1083 // Returns false if not allowed, true if allowed or if
1084 // allowed list is not configured.
1086 if(! function_exists('allowed_email')) {
1087 function allowed_email($email) {
1090 $domain = strtolower(substr($email,strpos($email,'@') + 1));
1094 $str_allowed = get_config('system','allowed_email');
1100 $fnmatch = function_exists('fnmatch');
1101 $allowed = explode(',',$str_allowed);
1103 if(count($allowed)) {
1104 foreach($allowed as $a) {
1105 $pat = strtolower(trim($a));
1106 if(($fnmatch && fnmatch($pat,$host)) || ($pat == $host)) {
1115 // Format the like/dislike text for a profile item
1116 // $cnt = number of people who like/dislike the item
1117 // $arr = array of pre-linked names of likers/dislikers
1118 // $type = one of 'like, 'dislike'
1120 // returns formatted text
1122 if(! function_exists('format_like')) {
1123 function format_like($cnt,$arr,$type,$id) {
1125 $o .= $arr[0] . (($type === 'like') ? t(' likes this.') : t(' doesn\'t like this.')) . EOL ;
1127 $o .= '<span class="fakelink" onclick="openClose(\'' . $type . 'list-' . $id . '\');" >'
1128 . $cnt . ' ' . t('people') . '</span> ' . (($type === 'like') ? t('like this.') : t('don\'t like this.')) . EOL ;
1129 $total = count($arr);
1130 if($total >= MAX_LIKERS)
1131 $arr = array_slice($arr, 0, MAX_LIKERS - 1);
1132 if($total < MAX_LIKERS)
1133 $arr[count($arr)-1] = t('and') . ' ' . $arr[count($arr)-1];
1134 $str = implode(', ', $arr);
1135 if($total >= MAX_LIKERS)
1136 $str .= t(', and ') . $total - MAX_LIKERS . t(' other people');
1137 $str .= (($type === 'like') ? t(' like this.') : t(' don\'t like this.'));
1138 $o .= "\t" . '<div id="' . $type . 'list-' . $id . '" style="display: none;" >' . $str . '</div>';
1144 // wrapper to load a view template, checking for alternate
1145 // languages before falling back to the default
1147 if(! function_exists('load_view_file')) {
1148 function load_view_file($s) {
1151 $lang = get_config('system','language');
1152 if($lang && file_exists("$d/$lang/$b"))
1153 return file_get_contents("$d/$lang/$b");
1154 return file_get_contents($s);