5 define ( 'BUILD_ID', 1007 );
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 define ( 'REGISTER_CLOSED', 0);
12 define ( 'REGISTER_APPROVE', 1);
13 define ( 'REGISTER_OPEN', 2);
17 define ( 'REL_VIP', 1);
18 define ( 'REL_FAN', 2);
19 define ( 'REL_BUD', 3);
21 // Maximum number of "people who like (or don't like) this" we will list by name
23 define ( 'MAX_LIKERS', 75);
26 define ( 'NOTIFY_INTRO', 0x0001 );
27 define ( 'NOTIFY_CONFIRM', 0x0002 );
28 define ( 'NOTIFY_WALL', 0x0004 );
29 define ( 'NOTIFY_COMMENT', 0x0008 );
30 define ( 'NOTIFY_MAIL', 0x0010 );
32 define ( 'NAMESPACE_DFRN' , 'http://purl.org/macgirvin/dfrn/1.0' );
33 define ( 'NAMESPACE_THREAD' , 'http://purl.org/syndication/thread/1.0' );
34 define ( 'NAMESPACE_TOMB' , 'http://purl.org/atompub/tombstones/1.0' );
35 define ( 'NAMESPACE_ACTIVITY', 'http://activitystrea.ms/spec/1.0/' );
36 define ( 'NAMESPACE_ACTIVITY_SCHEMA', 'http://activitystrea.ms/schema/1.0/');
37 define ( 'NAMESPACE_SALMON_ME', 'http://salmon-protocol.org/ns/magic-env');
38 define ( 'NAMESPACE_OSTATUSSUB', 'http://ostatus.org/schema/1.0/subscribe');
40 define ( 'ACTIVITY_LIKE', NAMESPACE_ACTIVITY_SCHEMA . 'like' );
41 define ( 'ACTIVITY_DISLIKE', NAMESPACE_DFRN . '/dislike' );
42 define ( 'ACTIVITY_OBJ_HEART', NAMESPACE_DFRN . '/heart' );
44 define ( 'ACTIVITY_FRIEND', NAMESPACE_ACTIVITY_SCHEMA . 'make-friend' );
45 define ( 'ACTIVITY_POST', NAMESPACE_ACTIVITY_SCHEMA . 'post' );
46 define ( 'ACTIVITY_UPDATE', NAMESPACE_ACTIVITY_SCHEMA . 'update' );
48 define ( 'ACTIVITY_OBJ_COMMENT', NAMESPACE_ACTIVITY_SCHEMA . 'comment' );
49 define ( 'ACTIVITY_OBJ_NOTE', NAMESPACE_ACTIVITY_SCHEMA . 'note' );
50 define ( 'ACTIVITY_OBJ_PERSON', NAMESPACE_ACTIVITY_SCHEMA . 'person' );
51 define ( 'ACTIVITY_OBJ_PHOTO', NAMESPACE_ACTIVITY_SCHEMA . 'photo' );
52 define ( 'ACTIVITY_OBJ_P_PHOTO', NAMESPACE_ACTIVITY_SCHEMA . 'profile-photo' );
53 define ( 'ACTIVITY_OBJ_ALBUM', NAMESPACE_ACTIVITY_SCHEMA . 'photo-album' );
55 define ( 'GRAVITY_PARENT', 0);
56 define ( 'GRAVITY_LIKE', 3);
57 define ( 'GRAVITY_COMMENT', 6);
60 // Our main application structure for the life of this page
61 // Primarily deals with the URL that got us here
62 // and tries to make some sense of it, and
63 // stores our page contents and config storage
64 // and anything else that might need to be passed around
65 // before we spit the page out.
67 if(! class_exists('App')) {
70 public $module_loaded = false;
79 public $error = false;
93 function __construct() {
95 $this->config = array();
96 $this->page = array();
97 $this->pager= array();
99 $this->scheme = ((isset($_SERVER['HTTPS'])
100 && ($_SERVER['HTTPS'])) ? 'https' : 'http' );
101 $this->hostname = str_replace('www.','',
102 $_SERVER['SERVER_NAME']);
103 set_include_path("include/$this->hostname"
104 . PATH_SEPARATOR . 'include'
105 . PATH_SEPARATOR . '.' );
107 if(substr($_SERVER['QUERY_STRING'],0,2) == "q=")
108 $_SERVER['QUERY_STRING'] = substr($_SERVER['QUERY_STRING'],2);
109 $this->cmd = trim($_GET['q'],'/');
112 $this->argv = explode('/',$this->cmd);
113 $this->argc = count($this->argv);
114 if((array_key_exists('0',$this->argv)) && strlen($this->argv[0])) {
115 $this->module = $this->argv[0];
118 $this->module = 'home';
121 if($this->cmd === '.well-known/host-meta')
122 require_once('include/hostxrd.php');
124 $this->pager['page'] = ((x($_GET,'page')) ? $_GET['page'] : 1);
125 $this->pager['itemspage'] = 50;
126 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
127 $this->pager['total'] = 0;
130 function get_baseurl($ssl = false) {
131 if(strlen($this->baseurl))
132 return $this->baseurl;
134 $this->baseurl = (($ssl) ? 'https' : $this->scheme) . "://" . $this->hostname
135 . ((isset($this->path) && strlen($this->path))
136 ? '/' . $this->path : '' );
137 return $this->baseurl;
140 function set_baseurl($url) {
141 $this->baseurl = $url;
142 $this->hostname = basename($url);
145 function get_hostname() {
146 return $this->hostname;
149 function set_hostname($h) {
150 $this->hostname = $h;
153 function set_path($p) {
154 $this->path = ltrim(trim($p),'/');
157 function get_path() {
161 function set_pager_total($n) {
162 $this->pager['total'] = intval($n);
165 function set_pager_itemspage($n) {
166 $this->pager['itemspage'] = intval($n);
167 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
171 function init_pagehead() {
172 $tpl = load_view_file("view/head.tpl");
173 $this->page['htmlhead'] = replace_macros($tpl,array(
174 '$baseurl' => $this->get_baseurl()
180 // retrieve the App structure
181 // useful in functions which require it but don't get it passed to them
183 if(! function_exists('get_app')) {
190 // Multi-purpose function to check variable state.
191 // Usage: x($var) or $x($array,'key')
192 // returns false if variable/key is not set
193 // if variable is set, returns 1 if has 'non-zero' value, otherwise returns 0.
194 // e.g. x('') or x(0) returns 0;
196 if(! function_exists('x')) {
197 function x($s,$k = NULL) {
199 if((is_array($s)) && (array_key_exists($k,$s))) {
217 // called from db initialisation if db is dead.
219 if(! function_exists('system_unavailable')) {
220 function system_unavailable() {
221 include('system_unavailable.php');
225 // Primarily involved with database upgrade, but also sets the
226 // base url for use in cmdline programs which don't have
227 // $_SERVER variables.
229 if(! function_exists('check_config')) {
230 function check_config(&$a) {
232 load_config('system');
234 $build = get_config('system','build');
236 $build = set_config('system','build',BUILD_ID);
238 $url = get_config('system','url');
240 $url = set_config('system','url',$a->get_baseurl());
242 if($build != BUILD_ID) {
243 $stored = intval($build);
244 $current = intval(BUILD_ID);
245 if(($stored < $current) && file_exists('update.php')) {
246 // We're reporting a different version than what is currently installed.
247 // Run any existing update scripts to bring the database up to current.
249 require_once('update.php');
250 for($x = $stored; $x < $current; $x ++) {
251 if(function_exists('update_' . $x)) {
252 $func = 'update_' . $x;
256 set_config('system','build', BUILD_ID);
263 // This is our template processor.
264 // $s is the string requiring macro substitution.
265 // $r is an array of key value pairs (search => replace)
266 // returns substituted string.
267 // WARNING: this is pretty basic, and doesn't properly handle search strings that are substrings of each other.
268 // For instance if 'test' => "foo" and 'testing' => "bar", testing could become either bar or fooing,
269 // depending on the order in which they were declared in the array.
271 if(! function_exists('replace_macros')) {
272 function replace_macros($s,$r) {
277 if(is_array($r) && count($r)) {
278 foreach ($r as $k => $v ) {
283 return str_replace($search,$replace,$s);
287 // load string tranlsation table for alternate language
289 if(! function_exists('load_translation_table')) {
290 function load_translation_table($lang) {
293 if(file_exists("view/$lang/strings.php"))
294 include("view/$lang/strings.php");
297 // translate string if translation exists
299 if(! function_exists('t')) {
305 return $a->strings[$s];
309 // curl wrapper. If binary flag is true, return binary
312 if(! function_exists('fetch_url')) {
313 function fetch_url($url,$binary = false) {
314 $ch = curl_init($url);
315 if(! $ch) return false;
317 curl_setopt($ch, CURLOPT_HEADER, 0);
318 curl_setopt($ch, CURLOPT_FOLLOWLOCATION,true);
319 curl_setopt($ch, CURLOPT_MAXREDIRS,8);
320 curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
322 // by default we will allow self-signed certs
323 // but you can override this
325 $check_cert = get_config('system','verifyssl');
326 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
328 $prx = get_config('system','proxy');
330 curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
331 curl_setopt($ch, CURLOPT_PROXY, $prx);
332 $prxusr = get_config('system','proxyuser');
334 curl_setopt($ch, CURLOPT_PROXYUSERPWD, $prxusr);
337 curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
344 // post request to $url. $params is an array of post variables.
346 if(! function_exists('post_url')) {
347 function post_url($url,$params) {
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);
355 curl_setopt($ch, CURLOPT_POST,1);
356 curl_setopt($ch, CURLOPT_POSTFIELDS,$params);
357 $check_cert = get_config('system','verifyssl');
358 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
359 $prx = get_config('system','proxy');
361 curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
362 curl_setopt($ch, CURLOPT_PROXY, $prx);
363 $prxusr = get_config('system','proxyuser');
365 curl_setopt($ch, CURLOPT_PROXYUSERPWD, $prxusr);
373 // random hash, 64 chars
375 if(! function_exists('random_string')) {
376 function random_string() {
377 return(hash('sha256',uniqid(rand(),true)));
380 // This is our primary input filter. The high bit hack only involved some old
381 // IE browser, forget which.
382 // Use this on any text input where angle chars are not valid or permitted
383 // They will be replaced with safer brackets. This may be filtered further
384 // if these are not allowed either.
386 if(! function_exists('notags')) {
387 function notags($string) {
388 // protect against :<> with high-bit set
389 return(str_replace(array("<",">","\xBA","\xBC","\xBE"), array('[',']','','',''), $string));
392 // use this on "body" or "content" input where angle chars shouldn't be removed,
393 // and allow them to be safely displayed.
395 if(! function_exists('escape_tags')) {
396 function escape_tags($string) {
398 return(htmlspecialchars($string));
401 // wrapper for adding a login box. If $register == true provide a registration
402 // link. This will most always depend on the value of $a->config['register_policy'].
404 if(! function_exists('login')) {
405 function login($register = false) {
407 $register_html = (($register) ? load_view_file("view/register-link.tpl") : "");
410 if(x($_SESSION,'authenticated')) {
411 $o = load_view_file("view/logout.tpl");
414 $o = load_view_file("view/login.tpl");
416 $o = replace_macros($o,array('$register_html' => $register_html ));
421 // generate a string that's random, but usually pronounceable.
422 // used to generate initial passwords
424 if(! function_exists('autoname')) {
425 function autoname($len) {
427 $vowels = array('a','a','ai','au','e','e','e','ee','ea','i','ie','o','ou','u');
428 if(mt_rand(0,5) == 4)
446 's','sc','sh','sm','sp','st',
454 $midcons = array('ck','ct','gn','ld','lf','lm','lt','mb','mm', 'mn','mp',
455 'nd','ng','nk','nt','rn','rp','rt');
457 $noend = array('bl', 'br', 'cl','cr','dr','fl','fr','gl','gr',
458 'kh', 'kl','kr','mn','pl','pr','rh','tr','qu','wh');
460 $start = mt_rand(0,2);
468 for ($x = 0; $x < $len; $x ++) {
469 $r = mt_rand(0,count($table) - 1);
472 if($table == $vowels)
473 $table = array_merge($cons,$midcons);
479 $word = substr($word,0,$len);
481 foreach($noend as $noe) {
482 if((strlen($word) > 2) && (substr($word,-2) == $noe)) {
483 $word = substr($word,0,-1);
487 if(substr($word,-1) == 'q')
488 $word = substr($word,0,-1);
492 // Used to end the current process, after saving session state.
494 if(! function_exists('killme')) {
496 session_write_close();
500 // redirect to another URL and terminate this process.
502 if(! function_exists('goaway')) {
503 function goaway($s) {
504 header("Location: $s");
508 // Generic XML return
509 // Outputs a basic dfrn XML status structure to STDOUT, with a <status> variable
510 // of $st and an optional text <message> of $message and terminates the current process.
512 if(! function_exists('xml_status')) {
513 function xml_status($st, $message = '') {
516 $xml_message = "\t<message>" . xmlify($message) . "</message>\r\n";
518 header( "Content-type: text/xml" );
519 echo '<?xml version="1.0" encoding="UTF-8"?>'."\r\n";
520 echo "<result>\r\n\t<status>$st</status>\r\n$xml_message</result>\r\n";
524 // Returns the uid of locally logged on user or false.
526 if(! function_exists('local_user')) {
527 function local_user() {
528 if((x($_SESSION,'authenticated')) && (x($_SESSION,'uid')))
529 return $_SESSION['uid'];
533 // Returns contact id of authenticated site visitor or false
535 if(! function_exists('remote_user')) {
536 function remote_user() {
537 if((x($_SESSION,'authenticated')) && (x($_SESSION,'visitor_id')))
538 return $_SESSION['visitor_id'];
542 // contents of $s are displayed prominently on the page the next time
543 // a page is loaded. Usually used for errors or alerts.
545 if(! function_exists('notice')) {
546 function notice($s) {
548 $_SESSION['sysmsg'] .= $s;
552 // wrapper around config to limit the text length of an incoming message
554 if(! function_exists('get_max_import_size')) {
555 function get_max_import_size() {
557 return ((x($a->config,'max_import_size')) ? $a->config['max_import_size'] : 0 );
561 // escape text ($str) for XML transport
562 // returns escaped text.
564 if(! function_exists('xmlify')) {
565 function xmlify($str) {
568 for($x = 0; $x < strlen($str); $x ++) {
599 $buffer = trim($buffer);
604 // pass xml escaped text ($s), returns unescaped text
606 if(! function_exists('unxmlify')) {
607 function unxmlify($s) {
608 $ret = str_replace('&','&', $s);
609 $ret = str_replace(array('<','>','"','''),array('<','>','"',"'"),$ret);
613 // convenience wrapper, reverse the operation "bin2hex"
615 if(! function_exists('hex2bin')) {
616 function hex2bin($s) {
617 return(pack("H*",$s));
620 // Automatic pagination.
621 // To use, get the count of total items.
622 // Then call $a->set_pager_total($number_items);
623 // Optionally call $a->set_pager_itemspage($n) to the number of items to display on each page
624 // Then call paginate($a) after the end of the display loop to insert the pager block on the page
625 // (assuming there are enough items to paginate).
626 // When using with SQL, the setting LIMIT %d, %d => $a->pager['start'],$a->pager['itemspage']
627 // will limit the results to the correct items for the current page.
628 // The actual page handling is then accomplished at the application layer.
630 if(! function_exists('paginate')) {
631 function paginate(&$a) {
633 $stripped = ereg_replace("(&page=[0-9]*)","",$_SERVER['QUERY_STRING']);
634 $stripped = str_replace('q=','',$stripped);
635 $stripped = trim($stripped,'/');
636 $url = $a->get_baseurl() . '/' . $stripped;
639 if($a->pager['total'] > $a->pager['itemspage']) {
640 $o .= '<div class="pager">';
641 if($a->pager['page'] != 1)
642 $o .= '<span class="pager_prev">'."<a href=\"$url".'&page='.($a->pager['page'] - 1).'">' . t('prev') . '</a></span> ';
644 $o .= "<span class=\"pager_first\"><a href=\"$url"."&page=1\">" . t('first') . "</a></span> ";
646 $numpages = $a->pager['total'] / $a->pager['itemspage'];
649 $numstop = $numpages;
652 $numstart = (($pagenum > 7) ? ($pagenum - 7) : 1);
653 $numstop = (($pagenum > ($numpages - 7)) ? $numpages : ($numstart + 14));
656 for($i = $numstart; $i <= $numstop; $i++){
657 if($i == $a->pager['page'])
658 $o .= '<span class="pager_current">'.(($i < 10) ? ' '.$i : $i);
660 $o .= "<span class=\"pager_n\"><a href=\"$url"."&page=$i\">".(($i < 10) ? ' '.$i : $i)."</a>";
664 if(($a->pager['total'] % $a->pager['itemspage']) != 0) {
665 if($i == $a->pager['page'])
666 $o .= '<span class="pager_current">'.(($i < 10) ? ' '.$i : $i);
668 $o .= "<span class=\"pager_n\"><a href=\"$url"."&page=$i\">".(($i < 10) ? ' '.$i : $i)."</a>";
672 $lastpage = (($numpages > intval($numpages)) ? intval($numpages)+1 : $numpages);
673 $o .= "<span class=\"pager_last\"><a href=\"$url"."&page=$lastpage\">" . t('last') . "</a></span> ";
675 if(($a->pager['total'] - ($a->pager['itemspage'] * $a->pager['page'])) > 0)
676 $o .= '<span class="pager_next">'."<a href=\"$url"."&page=".($a->pager['page'] + 1).'">' . t('next') . '</a></span>';
677 $o .= '</div>'."\r\n";
682 // Turn user/group ACLs stored as angle bracketed text into arrays
684 if(! function_exists('expand_acl')) {
685 function expand_acl($s) {
686 // turn string array of angle-bracketed elements into numeric array
687 // e.g. "<1><2><3>" => array(1,2,3);
691 $t = str_replace('<','',$s);
692 $a = explode('>',$t);
695 $ret[] = intval($aa);
701 // Used to wrap ACL elements in angle brackets for storage
703 if(! function_exists('sanitise_acl')) {
704 function sanitise_acl(&$item) {
706 $item = '<' . intval(notags(trim($item))) . '>';
711 // retrieve a "family" of config variables from database to cached storage
713 if(! function_exists('load_config')) {
714 function load_config($family) {
716 $r = q("SELECT * FROM `config` WHERE `cat` = '%s'",
722 $a->config[$family][$k] = $rr['v'];
727 // get a particular config variable given the family name
728 // and key. Returns false if not set.
729 // $instore is only used by the set_config function
730 // to determine if the key already exists in the DB
731 // If a key is found in the DB but doesn't exist in
732 // local config cache, pull it into the cache so we don't have
733 // to hit the DB again for this item.
735 if(! function_exists('get_config')) {
736 function get_config($family, $key, $instore = false) {
741 if(isset($a->config[$family][$key])) {
742 if($a->config[$family][$key] === '!<unset>!') {
745 return $a->config[$family][$key];
748 $ret = q("SELECT `v` FROM `config` WHERE `cat` = '%s' AND `k` = '%s' LIMIT 1",
753 $a->config[$family][$key] = $ret[0]['v'];
757 $a->config[$family][$key] = '!<unset>!';
762 // Store a config value ($value) in the category ($family)
763 // under the key ($key)
764 // Return the value, or false if the database update failed
766 if(! function_exists('set_config')) {
767 function set_config($family,$key,$value) {
770 $a->config[$family][$key] = $value;
772 if(get_config($family,$key,true) === false) {
773 $ret = q("INSERT INTO `config` ( `cat`, `k`, `v` ) VALUES ( '%s', '%s', '%s' ) ",
782 $ret = q("UPDATE `config` SET `v` = '%s' WHERE `cat` = '%s' AND `k` = '%s' LIMIT 1",
792 // convert an XML document to a normalised, case-corrected array
795 if(! function_exists('convert_xml_element_to_array')) {
796 function convert_xml_element_to_array($xml_element, &$recursion_depth=0) {
798 // If we're getting too deep, bail out
799 if ($recursion_depth > 512) {
803 if (!is_string($xml_element) &&
804 !is_array($xml_element) &&
805 (get_class($xml_element) == 'SimpleXMLElement')) {
806 $xml_element_copy = $xml_element;
807 $xml_element = get_object_vars($xml_element);
810 if (is_array($xml_element)) {
811 $result_array = array();
812 if (count($xml_element) <= 0) {
813 return (trim(strval($xml_element_copy)));
816 foreach($xml_element as $key=>$value) {
819 $result_array[strtolower($key)] =
820 convert_xml_element_to_array($value, $recursion_depth);
823 if ($recursion_depth == 0) {
824 $temp_array = $result_array;
825 $result_array = array(
826 strtolower($xml_element_copy->getName()) => $temp_array,
830 return ($result_array);
833 return (trim(strval($xml_element)));
837 // Given an email style address, perform webfinger lookup and
838 // return the resulting DFRN profile URL.
839 // If this isn't an email style address just return $s.
840 // Return an empty string if email-style addresses but webfinger fails,
841 // or if the resultant personal XRD doesn't contain a DFRN profile.
843 if(! function_exists('webfinger_dfrn')) {
844 function webfinger_dfrn($s) {
845 if(! strstr($s,'@')) {
848 $links = webfinger($s);
850 foreach($links as $link)
851 if($link['@attributes']['rel'] === NAMESPACE_DFRN)
852 return $link['@attributes']['href'];
853 foreach($links as $link)
854 if($link['@attributes']['rel'] === NAMESPACE_OSTATUSSUB)
855 return 'stat:' . $link['@attributes']['template'];
861 // Given an email style address, perform webfinger lookup and
862 // return the array of link attributes from the personal XRD file.
863 // On error/failure return an empty array.
866 if(! function_exists('webfinger')) {
867 function webfinger($s) {
870 $host = substr($s,strpos($s,'@') + 1);
873 $tpl = fetch_lrdd_template($host);
875 $pxrd = str_replace('{uri}', urlencode('acct://'.$s), $tpl);
876 $links = fetch_xrd_links($pxrd);
877 if(! count($links)) {
878 // try without the double slashes
879 $pxrd = str_replace('{uri}', urlencode('acct:'.$s), $tpl);
880 $links = fetch_xrd_links($pxrd);
888 // Given a host name, locate the LRDD template from that
889 // host. Returns the LRDD template or an empty string on
892 if(! function_exists('fetch_lrdd_template')) {
893 function fetch_lrdd_template($host) {
895 $url = 'http://' . $host . '/.well-known/host-meta' ;
896 $links = fetch_xrd_links($url);
898 foreach($links as $link)
899 if($link['@attributes']['rel'] && $link['@attributes']['rel'] === 'lrdd')
900 $tpl = $link['@attributes']['template'];
902 if(! strpos($tpl,'{uri}'))
907 // Given a URL, retrieve the page as an XRD document.
908 // Return an array of links.
909 // on error/failure return empty array.
911 if(! function_exists('fetch_xrd_links')) {
912 function fetch_xrd_links($url) {
914 $xml = fetch_url($url);
917 $h = simplexml_load_string($xml);
918 $arr = convert_xml_element_to_array($h);
920 if(isset($arr['xrd']['link'])) {
921 $link = $arr['xrd']['link'];
922 if(! isset($link[0]))
923 $links = array($link);
931 // Convert an ACL array to a storable string
933 if(! function_exists('perms2str')) {
934 function perms2str($p) {
938 array_walk($tmp,'sanitise_acl');
939 $ret = implode('',$tmp);
944 // generate a guaranteed unique (for this domain) item ID for ATOM
945 // safe from birthday paradox
947 if(! function_exists('item_new_uri')) {
948 function item_new_uri($hostname,$uid) {
952 $hash = random_string();
954 $uri = "urn:X-dfrn:" . $hostname . ':' . $uid . ':' . $hash;
956 $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' LIMIT 1",
960 } while($dups == true);
964 // Generate a guaranteed unique photo ID.
965 // safe from birthday paradox
967 if(! function_exists('photo_new_resource')) {
968 function photo_new_resource() {
972 $resource = hash('md5',uniqid(mt_rand(),true));
973 $r = q("SELECT `id` FROM `photo` WHERE `resource-id` = '%s' LIMIT 1",
978 } while($found == true);
983 // Returns logged in user ID
985 if(! function_exists('get_uid')) {
987 return ((x($_SESSION,'uid')) ? intval($_SESSION['uid']) : 0) ;
990 // Take a URL from the wild, prepend http:// if necessary
991 // and check DNS to see if it's real
992 // return true if it's OK, false if something is wrong with it
994 if(! function_exists('validate_url')) {
995 function validate_url(&$url) {
996 if(substr($url,0,4) != 'http')
997 $url = 'http://' . $url;
998 $h = parse_url($url);
1003 if(! checkdnsrr($h['host'], 'ANY')) {
1009 // Check $url against our list of allowed sites,
1010 // wildcards allowed. If allowed_sites is unset return true;
1011 // If url is allowed, return true.
1012 // otherwise, return false
1014 if(! function_exists('allowed_url')) {
1015 function allowed_url($url) {
1017 $h = parse_url($url);
1023 $str_allowed = get_config('system','allowed_sites');
1029 $host = strtolower($h['host']);
1031 // always allow our own site
1033 if($host == strtolower($_SERVER['SERVER_NAME']))
1036 $fnmatch = function_exists('fnmatch');
1037 $allowed = explode(',',$str_allowed);
1039 if(count($allowed)) {
1040 foreach($allowed as $a) {
1041 $pat = strtolower(trim($a));
1042 if(($fnmatch && fnmatch($pat,$host)) || ($pat == $host)) {
1051 // check if email address is allowed to register here.
1052 // Compare against our list (wildcards allowed).
1053 // Returns false if not allowed, true if allowed or if
1054 // allowed list is not configured.
1056 if(! function_exists('allowed_email')) {
1057 function allowed_email($email) {
1060 $domain = strtolower(substr($email,strpos($email,'@') + 1));
1064 $str_allowed = get_config('system','allowed_email');
1070 $fnmatch = function_exists('fnmatch');
1071 $allowed = explode(',',$str_allowed);
1073 if(count($allowed)) {
1074 foreach($allowed as $a) {
1075 $pat = strtolower(trim($a));
1076 if(($fnmatch && fnmatch($pat,$host)) || ($pat == $host)) {
1085 // Format the like/dislike text for a profile item
1086 // $cnt = number of people who like/dislike the item
1087 // $arr = array of pre-linked names of likers/dislikers
1088 // $type = one of 'like, 'dislike'
1090 // returns formatted text
1092 if(! function_exists('format_like')) {
1093 function format_like($cnt,$arr,$type,$id) {
1095 $o .= $arr[0] . (($type === 'like') ? t(' likes this.') : t(' doesn\'t like this.')) . EOL ;
1097 $o .= '<span class="fakelink" onclick="openClose(\'' . $type . 'list-' . $id . '\');" >'
1098 . $cnt . ' ' . t('people') . '</span> ' . (($type === 'like') ? t('like this.') : t('don\'t like this.')) . EOL ;
1099 $total = count($arr);
1100 if($total >= MAX_LIKERS)
1101 $arr = array_slice($arr, 0, MAX_LIKERS - 1);
1102 if($total < MAX_LIKERS)
1103 $arr[count($arr)-1] = t('and') . ' ' . $arr[count($arr)-1];
1104 $str = implode(', ', $arr);
1105 if($total >= MAX_LIKERS)
1106 $str .= t(', and ') . $total - MAX_LIKERS . t(' other people');
1107 $str .= (($type === 'like') ? t(' like this.') : t(' don\'t like this.'));
1108 $o .= '<div id="' . $type . 'list-' . $id . '" style="display: none;" >' . $str . '</div>';
1114 // wrapper to load a view template, checking for alternate
1115 // languages before falling back to the default
1117 if(! function_exists('load_view_file')) {
1118 function load_view_file($s) {
1121 $lang = get_config('system','language');
1122 if($lang && file_exists("$d/$lang/$b"))
1123 return file_get_contents("$d/$lang/$b");
1124 return file_get_contents($s);