5 define ( 'BUILD_ID', 1011 );
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');
58 define ( 'NAMESPACE_GEORSS', 'http://www.georss.org/georss');
60 // activity stream defines
62 define ( 'ACTIVITY_LIKE', NAMESPACE_ACTIVITY_SCHEMA . 'like' );
63 define ( 'ACTIVITY_DISLIKE', NAMESPACE_DFRN . '/dislike' );
64 define ( 'ACTIVITY_OBJ_HEART', NAMESPACE_DFRN . '/heart' );
66 define ( 'ACTIVITY_FRIEND', NAMESPACE_ACTIVITY_SCHEMA . 'make-friend' );
67 define ( 'ACTIVITY_FOLLOW', NAMESPACE_ACTIVITY_SCHEMA . 'follow' );
68 define ( 'ACTIVITY_UNFOLLOW', NAMESPACE_ACTIVITY_SCHEMA . 'unfollow' );
69 define ( 'ACTIVITY_POST', NAMESPACE_ACTIVITY_SCHEMA . 'post' );
70 define ( 'ACTIVITY_UPDATE', NAMESPACE_ACTIVITY_SCHEMA . 'update' );
72 define ( 'ACTIVITY_OBJ_COMMENT', NAMESPACE_ACTIVITY_SCHEMA . 'comment' );
73 define ( 'ACTIVITY_OBJ_NOTE', NAMESPACE_ACTIVITY_SCHEMA . 'note' );
74 define ( 'ACTIVITY_OBJ_PERSON', NAMESPACE_ACTIVITY_SCHEMA . 'person' );
75 define ( 'ACTIVITY_OBJ_PHOTO', NAMESPACE_ACTIVITY_SCHEMA . 'photo' );
76 define ( 'ACTIVITY_OBJ_P_PHOTO', NAMESPACE_ACTIVITY_SCHEMA . 'profile-photo' );
77 define ( 'ACTIVITY_OBJ_ALBUM', NAMESPACE_ACTIVITY_SCHEMA . 'photo-album' );
79 // item weight for query ordering
81 define ( 'GRAVITY_PARENT', 0);
82 define ( 'GRAVITY_LIKE', 3);
83 define ( 'GRAVITY_COMMENT', 6);
86 // Our main application structure for the life of this page
87 // Primarily deals with the URL that got us here
88 // and tries to make some sense of it, and
89 // stores our page contents and config storage
90 // and anything else that might need to be passed around
91 // before we spit the page out.
93 if(! class_exists('App')) {
96 public $module_loaded = false;
105 public $error = false;
113 public $interactive = true;
121 private $curl_headers;
123 function __construct() {
125 $this->config = array();
126 $this->page = array();
127 $this->pager= array();
129 $this->scheme = ((isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS'])) ? 'https' : 'http' );
130 $this->hostname = $_SERVER['SERVER_NAME'];
131 set_include_path("include/$this->hostname" . PATH_SEPARATOR . 'include' . 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 . ((isset($this->path) && strlen($this->path)) ? '/' . $this->path : '' );
161 return $this->baseurl;
164 function set_baseurl($url) {
165 $this->baseurl = $url;
166 $this->hostname = basename($url);
169 function get_hostname() {
170 return $this->hostname;
173 function set_hostname($h) {
174 $this->hostname = $h;
177 function set_path($p) {
178 $this->path = trim(trim($p),'/');
181 function get_path() {
185 function set_pager_total($n) {
186 $this->pager['total'] = intval($n);
189 function set_pager_itemspage($n) {
190 $this->pager['itemspage'] = intval($n);
191 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
195 function init_pagehead() {
196 $tpl = load_view_file("view/head.tpl");
197 $this->page['htmlhead'] = replace_macros($tpl,array(
198 '$baseurl' => $this->get_baseurl()
202 function set_curl_code($code) {
203 $this->curl_code = $code;
206 function get_curl_code() {
207 return $this->curl_code;
210 function set_curl_headers($headers) {
211 $this->curl_headers = $headers;
214 function get_curl_headers() {
215 return $this->curl_headers;
221 // retrieve the App structure
222 // useful in functions which require it but don't get it passed to them
224 if(! function_exists('get_app')) {
231 // Multi-purpose function to check variable state.
232 // Usage: x($var) or $x($array,'key')
233 // returns false if variable/key is not set
234 // if variable is set, returns 1 if has 'non-zero' value, otherwise returns 0.
235 // e.g. x('') or x(0) returns 0;
237 if(! function_exists('x')) {
238 function x($s,$k = NULL) {
240 if((is_array($s)) && (array_key_exists($k,$s))) {
258 // called from db initialisation if db is dead.
260 if(! function_exists('system_unavailable')) {
261 function system_unavailable() {
262 include('system_unavailable.php');
266 // Primarily involved with database upgrade, but also sets the
267 // base url for use in cmdline programs which don't have
268 // $_SERVER variables.
270 if(! function_exists('check_config')) {
271 function check_config(&$a) {
273 load_config('system');
275 $build = get_config('system','build');
277 $build = set_config('system','build',BUILD_ID);
279 $url = get_config('system','url');
281 $url = set_config('system','url',$a->get_baseurl());
283 if($build != BUILD_ID) {
284 $stored = intval($build);
285 $current = intval(BUILD_ID);
286 if(($stored < $current) && file_exists('update.php')) {
287 // We're reporting a different version than what is currently installed.
288 // Run any existing update scripts to bring the database up to current.
290 require_once('update.php');
291 for($x = $stored; $x < $current; $x ++) {
292 if(function_exists('update_' . $x)) {
293 $func = 'update_' . $x;
297 set_config('system','build', BUILD_ID);
304 // This is our template processor.
305 // $s is the string requiring macro substitution.
306 // $r is an array of key value pairs (search => replace)
307 // returns substituted string.
308 // WARNING: this is pretty basic, and doesn't properly handle search strings that are substrings of each other.
309 // For instance if 'test' => "foo" and 'testing' => "bar", testing could become either bar or fooing,
310 // depending on the order in which they were declared in the array.
312 if(! function_exists('replace_macros')) {
313 function replace_macros($s,$r) {
318 if(is_array($r) && count($r)) {
319 foreach ($r as $k => $v ) {
324 return str_replace($search,$replace,$s);
328 // load string translation table for alternate language
330 if(! function_exists('load_translation_table')) {
331 function load_translation_table($lang) {
334 if(file_exists("view/$lang/strings.php"))
335 include("view/$lang/strings.php");
338 // translate string if translation exists
340 if(! function_exists('t')) {
346 return $a->strings[$s];
350 // curl wrapper. If binary flag is true, return binary
353 if(! function_exists('fetch_url')) {
354 function fetch_url($url,$binary = false, &$redirects = 0) {
355 $ch = curl_init($url);
356 if(($redirects > 8) || (! $ch))
359 curl_setopt($ch, CURLOPT_HEADER, true);
360 curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
362 // by default we will allow self-signed certs
363 // but you can override this
365 $check_cert = get_config('system','verifyssl');
366 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
368 $prx = get_config('system','proxy');
370 curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
371 curl_setopt($ch, CURLOPT_PROXY, $prx);
372 $prxusr = get_config('system','proxyuser');
374 curl_setopt($ch, CURLOPT_PROXYUSERPWD, $prxusr);
377 curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
381 $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
382 $header = substr($s,0,strpos($s,"\r\n\r\n"));
383 if(stristr($header,'100') && (strlen($header) < 30)) {
384 // 100 Continue has two headers, get the real one
385 $s = substr($s,strlen($header)+4);
386 $header = substr($s,0,strpos($s,"\r\n\r\n"));
388 if($http_code == 301 || $http_code == 302 || $http_code == 303) {
390 preg_match('/(Location:|URI:)(.*?)\n/', $header, $matches);
391 $url = trim(array_pop($matches));
392 $url_parsed = parse_url($url);
393 if (isset($url_parsed)) {
395 return fetch_url($url,$binary,$redirects);
399 $a->set_curl_code($http_code);
400 $body = substr($s,strlen($header)+4);
401 $a->set_curl_headers($header);
407 // post request to $url. $params is an array of post variables.
409 if(! function_exists('post_url')) {
410 function post_url($url,$params, &$redirects = 0) {
411 $ch = curl_init($url);
412 if(($redirects > 8) || (! $ch))
415 curl_setopt($ch, CURLOPT_HEADER, true);
416 curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
417 curl_setopt($ch, CURLOPT_POST,1);
418 curl_setopt($ch, CURLOPT_POSTFIELDS,$params);
420 $check_cert = get_config('system','verifyssl');
421 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
422 $prx = get_config('system','proxy');
424 curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
425 curl_setopt($ch, CURLOPT_PROXY, $prx);
426 $prxusr = get_config('system','proxyuser');
428 curl_setopt($ch, CURLOPT_PROXYUSERPWD, $prxusr);
433 $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
434 $header = substr($s,0,strpos($s,"\r\n\r\n"));
435 if(stristr($header,'100') && (strlen($header) < 30)) {
436 // 100 Continue has two headers, get the real one
437 $s = substr($s,strlen($header)+4);
438 $header = substr($s,0,strpos($s,"\r\n\r\n"));
440 if($http_code == 301 || $http_code == 302 || $http_code == 303) {
442 preg_match('/(Location:|URI:)(.*?)\n/', $header, $matches);
443 $url = trim(array_pop($matches));
444 $url_parsed = parse_url($url);
445 if (isset($url_parsed)) {
447 return post_url($url,$binary,$redirects);
451 $a->set_curl_code($http_code);
452 $body = substr($s,strlen($header)+4);
453 $a->set_curl_headers($header);
459 // random hash, 64 chars
461 if(! function_exists('random_string')) {
462 function random_string() {
463 return(hash('sha256',uniqid(rand(),true)));
466 // This is our primary input filter. The high bit hack only involved some old
467 // IE browser, forget which.
468 // Use this on any text input where angle chars are not valid or permitted
469 // They will be replaced with safer brackets. This may be filtered further
470 // if these are not allowed either.
472 if(! function_exists('notags')) {
473 function notags($string) {
474 // protect against :<> with high-bit set
475 return(str_replace(array("<",">","\xBA","\xBC","\xBE"), array('[',']','','',''), $string));
478 // use this on "body" or "content" input where angle chars shouldn't be removed,
479 // and allow them to be safely displayed.
481 if(! function_exists('escape_tags')) {
482 function escape_tags($string) {
484 return(htmlspecialchars($string));
487 // wrapper for adding a login box. If $register == true provide a registration
488 // link. This will most always depend on the value of $a->config['register_policy'].
489 // returns the complete html for inserting into the page
491 if(! function_exists('login')) {
492 function login($register = false) {
494 $register_html = (($register) ? load_view_file("view/register-link.tpl") : "");
497 if(x($_SESSION,'authenticated')) {
498 $o = load_view_file("view/logout.tpl");
501 $o = load_view_file("view/login.tpl");
503 $o = replace_macros($o,array('$register_html' => $register_html ));
508 // generate a string that's random, but usually pronounceable.
509 // used to generate initial passwords
511 if(! function_exists('autoname')) {
512 function autoname($len) {
514 $vowels = array('a','a','ai','au','e','e','e','ee','ea','i','ie','o','ou','u');
515 if(mt_rand(0,5) == 4)
533 's','sc','sh','sm','sp','st',
541 $midcons = array('ck','ct','gn','ld','lf','lm','lt','mb','mm', 'mn','mp',
542 'nd','ng','nk','nt','rn','rp','rt');
544 $noend = array('bl', 'br', 'cl','cr','dr','fl','fr','gl','gr',
545 'kh', 'kl','kr','mn','pl','pr','rh','tr','qu','wh');
547 $start = mt_rand(0,2);
555 for ($x = 0; $x < $len; $x ++) {
556 $r = mt_rand(0,count($table) - 1);
559 if($table == $vowels)
560 $table = array_merge($cons,$midcons);
566 $word = substr($word,0,$len);
568 foreach($noend as $noe) {
569 if((strlen($word) > 2) && (substr($word,-2) == $noe)) {
570 $word = substr($word,0,-1);
574 if(substr($word,-1) == 'q')
575 $word = substr($word,0,-1);
579 // Used to end the current process, after saving session state.
581 if(! function_exists('killme')) {
583 session_write_close();
587 // redirect to another URL and terminate this process.
589 if(! function_exists('goaway')) {
590 function goaway($s) {
591 header("Location: $s");
595 // Generic XML return
596 // Outputs a basic dfrn XML status structure to STDOUT, with a <status> variable
597 // of $st and an optional text <message> of $message and terminates the current process.
599 if(! function_exists('xml_status')) {
600 function xml_status($st, $message = '') {
603 $xml_message = "\t<message>" . xmlify($message) . "</message>\r\n";
605 header( "Content-type: text/xml" );
606 echo '<?xml version="1.0" encoding="UTF-8"?>'."\r\n";
607 echo "<result>\r\n\t<status>$st</status>\r\n$xml_message</result>\r\n";
611 // Returns the uid of locally logged in user or false.
613 if(! function_exists('local_user')) {
614 function local_user() {
615 if((x($_SESSION,'authenticated')) && (x($_SESSION,'uid')))
616 return intval($_SESSION['uid']);
620 // Returns contact id of authenticated site visitor or false
622 if(! function_exists('remote_user')) {
623 function remote_user() {
624 if((x($_SESSION,'authenticated')) && (x($_SESSION,'visitor_id')))
625 return intval($_SESSION['visitor_id']);
629 // contents of $s are displayed prominently on the page the next time
630 // a page is loaded. Usually used for errors or alerts.
632 if(! function_exists('notice')) {
633 function notice($s) {
636 $_SESSION['sysmsg'] .= $s;
639 // wrapper around config to limit the text length of an incoming message
641 if(! function_exists('get_max_import_size')) {
642 function get_max_import_size() {
644 return ((x($a->config,'max_import_size')) ? $a->config['max_import_size'] : 0 );
648 // escape text ($str) for XML transport
649 // returns escaped text.
651 if(! function_exists('xmlify')) {
652 function xmlify($str) {
655 for($x = 0; $x < strlen($str); $x ++) {
686 $buffer = trim($buffer);
691 // pass xml escaped text ($s), returns unescaped text
693 if(! function_exists('unxmlify')) {
694 function unxmlify($s) {
695 $ret = str_replace('&','&', $s);
696 $ret = str_replace(array('<','>','"','''),array('<','>','"',"'"),$ret);
700 // convenience wrapper, reverse the operation "bin2hex"
702 if(! function_exists('hex2bin')) {
703 function hex2bin($s) {
704 return(pack("H*",$s));
707 // Automatic pagination.
708 // To use, get the count of total items.
709 // Then call $a->set_pager_total($number_items);
710 // Optionally call $a->set_pager_itemspage($n) to the number of items to display on each page
711 // Then call paginate($a) after the end of the display loop to insert the pager block on the page
712 // (assuming there are enough items to paginate).
713 // When using with SQL, the setting LIMIT %d, %d => $a->pager['start'],$a->pager['itemspage']
714 // will limit the results to the correct items for the current page.
715 // The actual page handling is then accomplished at the application layer.
717 if(! function_exists('paginate')) {
718 function paginate(&$a) {
720 $stripped = ereg_replace("(&page=[0-9]*)","",$_SERVER['QUERY_STRING']);
721 $stripped = str_replace('q=','',$stripped);
722 $stripped = trim($stripped,'/');
723 $url = $a->get_baseurl() . '/' . $stripped;
726 if($a->pager['total'] > $a->pager['itemspage']) {
727 $o .= '<div class="pager">';
728 if($a->pager['page'] != 1)
729 $o .= '<span class="pager_prev">'."<a href=\"$url".'&page='.($a->pager['page'] - 1).'">' . t('prev') . '</a></span> ';
731 $o .= "<span class=\"pager_first\"><a href=\"$url"."&page=1\">" . t('first') . "</a></span> ";
733 $numpages = $a->pager['total'] / $a->pager['itemspage'];
736 $numstop = $numpages;
739 $numstart = (($pagenum > 7) ? ($pagenum - 7) : 1);
740 $numstop = (($pagenum > ($numpages - 7)) ? $numpages : ($numstart + 14));
743 for($i = $numstart; $i <= $numstop; $i++){
744 if($i == $a->pager['page'])
745 $o .= '<span class="pager_current">'.(($i < 10) ? ' '.$i : $i);
747 $o .= "<span class=\"pager_n\"><a href=\"$url"."&page=$i\">".(($i < 10) ? ' '.$i : $i)."</a>";
751 if(($a->pager['total'] % $a->pager['itemspage']) != 0) {
752 if($i == $a->pager['page'])
753 $o .= '<span class="pager_current">'.(($i < 10) ? ' '.$i : $i);
755 $o .= "<span class=\"pager_n\"><a href=\"$url"."&page=$i\">".(($i < 10) ? ' '.$i : $i)."</a>";
759 $lastpage = (($numpages > intval($numpages)) ? intval($numpages)+1 : $numpages);
760 $o .= "<span class=\"pager_last\"><a href=\"$url"."&page=$lastpage\">" . t('last') . "</a></span> ";
762 if(($a->pager['total'] - ($a->pager['itemspage'] * $a->pager['page'])) > 0)
763 $o .= '<span class="pager_next">'."<a href=\"$url"."&page=".($a->pager['page'] + 1).'">' . t('next') . '</a></span>';
764 $o .= '</div>'."\r\n";
769 // Turn user/group ACLs stored as angle bracketed text into arrays
771 if(! function_exists('expand_acl')) {
772 function expand_acl($s) {
773 // turn string array of angle-bracketed elements into numeric array
774 // e.g. "<1><2><3>" => array(1,2,3);
778 $t = str_replace('<','',$s);
779 $a = explode('>',$t);
782 $ret[] = intval($aa);
788 // Used to wrap ACL elements in angle brackets for storage
790 if(! function_exists('sanitise_acl')) {
791 function sanitise_acl(&$item) {
793 $item = '<' . intval(notags(trim($item))) . '>';
798 // retrieve a "family" of config variables from database to cached storage
800 if(! function_exists('load_config')) {
801 function load_config($family) {
803 $r = q("SELECT * FROM `config` WHERE `cat` = '%s'",
809 $a->config[$family][$k] = $rr['v'];
814 // get a particular config variable given the family name
815 // and key. Returns false if not set.
816 // $instore is only used by the set_config function
817 // to determine if the key already exists in the DB
818 // If a key is found in the DB but doesn't exist in
819 // local config cache, pull it into the cache so we don't have
820 // to hit the DB again for this item.
822 if(! function_exists('get_config')) {
823 function get_config($family, $key, $instore = false) {
828 if(isset($a->config[$family][$key])) {
829 if($a->config[$family][$key] === '!<unset>!') {
832 return $a->config[$family][$key];
835 $ret = q("SELECT `v` FROM `config` WHERE `cat` = '%s' AND `k` = '%s' LIMIT 1",
840 $a->config[$family][$key] = $ret[0]['v'];
844 $a->config[$family][$key] = '!<unset>!';
849 // Store a config value ($value) in the category ($family)
850 // under the key ($key)
851 // Return the value, or false if the database update failed
853 if(! function_exists('set_config')) {
854 function set_config($family,$key,$value) {
857 $a->config[$family][$key] = $value;
859 if(get_config($family,$key,true) === false) {
860 $ret = q("INSERT INTO `config` ( `cat`, `k`, `v` ) VALUES ( '%s', '%s', '%s' ) ",
869 $ret = q("UPDATE `config` SET `v` = '%s' WHERE `cat` = '%s' AND `k` = '%s' LIMIT 1",
879 // convert an XML document to a normalised, case-corrected array
882 if(! function_exists('convert_xml_element_to_array')) {
883 function convert_xml_element_to_array($xml_element, &$recursion_depth=0) {
885 // If we're getting too deep, bail out
886 if ($recursion_depth > 512) {
890 if (!is_string($xml_element) &&
891 !is_array($xml_element) &&
892 (get_class($xml_element) == 'SimpleXMLElement')) {
893 $xml_element_copy = $xml_element;
894 $xml_element = get_object_vars($xml_element);
897 if (is_array($xml_element)) {
898 $result_array = array();
899 if (count($xml_element) <= 0) {
900 return (trim(strval($xml_element_copy)));
903 foreach($xml_element as $key=>$value) {
906 $result_array[strtolower($key)] =
907 convert_xml_element_to_array($value, $recursion_depth);
910 if ($recursion_depth == 0) {
911 $temp_array = $result_array;
912 $result_array = array(
913 strtolower($xml_element_copy->getName()) => $temp_array,
917 return ($result_array);
920 return (trim(strval($xml_element)));
924 // Given an email style address, perform webfinger lookup and
925 // return the resulting DFRN profile URL, or if no DFRN profile URL
926 // is located, returns an OStatus subscription template (prefixed
927 // with the string 'stat:' to identify it as on OStatus template).
928 // If this isn't an email style address just return $s.
929 // Return an empty string if email-style addresses but webfinger fails,
930 // or if the resultant personal XRD doesn't contain a supported
931 // subscription/friend-request attribute.
933 if(! function_exists('webfinger_dfrn')) {
934 function webfinger_dfrn($s) {
935 if(! strstr($s,'@')) {
938 $links = webfinger($s);
940 foreach($links as $link)
941 if($link['@attributes']['rel'] === NAMESPACE_DFRN)
942 return $link['@attributes']['href'];
943 foreach($links as $link)
944 if($link['@attributes']['rel'] === NAMESPACE_OSTATUSSUB)
945 return 'stat:' . $link['@attributes']['template'];
950 // Given an email style address, perform webfinger lookup and
951 // return the array of link attributes from the personal XRD file.
952 // On error/failure return an empty array.
955 if(! function_exists('webfinger')) {
956 function webfinger($s) {
959 $host = substr($s,strpos($s,'@') + 1);
962 $tpl = fetch_lrdd_template($host);
964 $pxrd = str_replace('{uri}', urlencode('acct://'.$s), $tpl);
965 $links = fetch_xrd_links($pxrd);
966 if(! count($links)) {
967 // try without the double slashes
968 $pxrd = str_replace('{uri}', urlencode('acct:'.$s), $tpl);
969 $links = fetch_xrd_links($pxrd);
977 // Given a host name, locate the LRDD template from that
978 // host. Returns the LRDD template or an empty string on
981 if(! function_exists('fetch_lrdd_template')) {
982 function fetch_lrdd_template($host) {
984 $url = 'http://' . $host . '/.well-known/host-meta' ;
985 $links = fetch_xrd_links($url);
987 foreach($links as $link)
988 if($link['@attributes']['rel'] && $link['@attributes']['rel'] === 'lrdd')
989 $tpl = $link['@attributes']['template'];
991 if(! strpos($tpl,'{uri}'))
996 // Given a URL, retrieve the page as an XRD document.
997 // Return an array of links.
998 // on error/failure return empty array.
1000 if(! function_exists('fetch_xrd_links')) {
1001 function fetch_xrd_links($url) {
1003 $xml = fetch_url($url);
1006 $h = simplexml_load_string($xml);
1007 $arr = convert_xml_element_to_array($h);
1009 if(isset($arr['xrd']['link'])) {
1010 $link = $arr['xrd']['link'];
1011 if(! isset($link[0]))
1012 $links = array($link);
1020 // Convert an ACL array to a storable string
1022 if(! function_exists('perms2str')) {
1023 function perms2str($p) {
1026 if(is_array($tmp)) {
1027 array_walk($tmp,'sanitise_acl');
1028 $ret = implode('',$tmp);
1033 // generate a guaranteed unique (for this domain) item ID for ATOM
1034 // safe from birthday paradox
1036 if(! function_exists('item_new_uri')) {
1037 function item_new_uri($hostname,$uid) {
1041 $hash = random_string();
1043 $uri = "urn:X-dfrn:" . $hostname . ':' . $uid . ':' . $hash;
1045 $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' LIMIT 1",
1049 } while($dups == true);
1053 // Generate a guaranteed unique photo ID.
1054 // safe from birthday paradox
1056 if(! function_exists('photo_new_resource')) {
1057 function photo_new_resource() {
1061 $resource = hash('md5',uniqid(mt_rand(),true));
1062 $r = q("SELECT `id` FROM `photo` WHERE `resource-id` = '%s' LIMIT 1",
1067 } while($found == true);
1072 // Take a URL from the wild, prepend http:// if necessary
1073 // and check DNS to see if it's real
1074 // return true if it's OK, false if something is wrong with it
1076 if(! function_exists('validate_url')) {
1077 function validate_url(&$url) {
1078 if(substr($url,0,4) != 'http')
1079 $url = 'http://' . $url;
1080 $h = parse_url($url);
1085 if(! checkdnsrr($h['host'], 'ANY')) {
1091 // Check $url against our list of allowed sites,
1092 // wildcards allowed. If allowed_sites is unset return true;
1093 // If url is allowed, return true.
1094 // otherwise, return false
1096 if(! function_exists('allowed_url')) {
1097 function allowed_url($url) {
1099 $h = parse_url($url);
1105 $str_allowed = get_config('system','allowed_sites');
1111 $host = strtolower($h['host']);
1113 // always allow our own site
1115 if($host == strtolower($_SERVER['SERVER_NAME']))
1118 $fnmatch = function_exists('fnmatch');
1119 $allowed = explode(',',$str_allowed);
1121 if(count($allowed)) {
1122 foreach($allowed as $a) {
1123 $pat = strtolower(trim($a));
1124 if(($fnmatch && fnmatch($pat,$host)) || ($pat == $host)) {
1133 // check if email address is allowed to register here.
1134 // Compare against our list (wildcards allowed).
1135 // Returns false if not allowed, true if allowed or if
1136 // allowed list is not configured.
1138 if(! function_exists('allowed_email')) {
1139 function allowed_email($email) {
1142 $domain = strtolower(substr($email,strpos($email,'@') + 1));
1146 $str_allowed = get_config('system','allowed_email');
1152 $fnmatch = function_exists('fnmatch');
1153 $allowed = explode(',',$str_allowed);
1155 if(count($allowed)) {
1156 foreach($allowed as $a) {
1157 $pat = strtolower(trim($a));
1158 if(($fnmatch && fnmatch($pat,$host)) || ($pat == $host)) {
1167 // Format the like/dislike text for a profile item
1168 // $cnt = number of people who like/dislike the item
1169 // $arr = array of pre-linked names of likers/dislikers
1170 // $type = one of 'like, 'dislike'
1172 // returns formatted text
1174 if(! function_exists('format_like')) {
1175 function format_like($cnt,$arr,$type,$id) {
1177 $o .= $arr[0] . (($type === 'like') ? t(' likes this.') : t(' doesn\'t like this.')) . EOL ;
1179 $o .= '<span class="fakelink" onclick="openClose(\'' . $type . 'list-' . $id . '\');" >'
1180 . $cnt . ' ' . t('people') . '</span> ' . (($type === 'like') ? t('like this.') : t('don\'t like this.')) . EOL ;
1181 $total = count($arr);
1182 if($total >= MAX_LIKERS)
1183 $arr = array_slice($arr, 0, MAX_LIKERS - 1);
1184 if($total < MAX_LIKERS)
1185 $arr[count($arr)-1] = t('and') . ' ' . $arr[count($arr)-1];
1186 $str = implode(', ', $arr);
1187 if($total >= MAX_LIKERS)
1188 $str .= t(', and ') . $total - MAX_LIKERS . t(' other people');
1189 $str .= (($type === 'like') ? t(' like this.') : t(' don\'t like this.'));
1190 $o .= "\t" . '<div id="' . $type . 'list-' . $id . '" style="display: none;" >' . $str . '</div>';
1196 // wrapper to load a view template, checking for alternate
1197 // languages before falling back to the default
1199 if(! function_exists('load_view_file')) {
1200 function load_view_file($s) {
1203 $lang = get_config('system','language');
1204 if($lang && file_exists("$d/$lang/$b"))
1205 return file_get_contents("$d/$lang/$b");
1206 return file_get_contents($s);