5 define ( 'BUILD_ID', 1027 );
6 define ( 'DFRN_PROTOCOL_VERSION', '2.0' );
8 define ( 'EOL', "<br />\r\n" );
9 define ( 'ATOM_TIME', 'Y-m-d\TH:i:s\Z' );
10 define ( 'DOWN_ARROW', '⇩' );
16 define ( 'LOGGER_NORMAL', 0 );
17 define ( 'LOGGER_TRACE', 1 );
18 define ( 'LOGGER_DEBUG', 2 );
19 define ( 'LOGGER_DATA', 3 );
20 define ( 'LOGGER_ALL', 4 );
23 * registration policies
26 define ( 'REGISTER_CLOSED', 0 );
27 define ( 'REGISTER_APPROVE', 1 );
28 define ( 'REGISTER_OPEN', 2 );
34 define ( 'REL_VIP', 1);
35 define ( 'REL_FAN', 2);
36 define ( 'REL_BUD', 3);
43 * PAGE_NORMAL is a typical personal profile account
44 * PAGE_SOAPBOX automatically approves all friend requests as REL_FAN, (readonly)
45 * PAGE_COMMUNITY automatically approves all friend requests as REL_FAN, but with
46 * write access to wall and comments (no email and not included in page owner's ACL lists)
47 * PAGE_FREELOVE automatically approves all friend requests as full friends (REL_BUD).
51 define ( 'PAGE_NORMAL', 0 );
52 define ( 'PAGE_SOAPBOX', 1 );
53 define ( 'PAGE_COMMUNITY', 2 );
54 define ( 'PAGE_FREELOVE', 3 );
57 * Maximum number of "people who like (or don't like) this" that we will list by name
60 define ( 'MAX_LIKERS', 75);
63 * email notification options
66 define ( 'NOTIFY_INTRO', 0x0001 );
67 define ( 'NOTIFY_CONFIRM', 0x0002 );
68 define ( 'NOTIFY_WALL', 0x0004 );
69 define ( 'NOTIFY_COMMENT', 0x0008 );
70 define ( 'NOTIFY_MAIL', 0x0010 );
73 * various namespaces we may need to parse
76 define ( 'NAMESPACE_DFRN' , 'http://purl.org/macgirvin/dfrn/1.0' );
77 define ( 'NAMESPACE_THREAD' , 'http://purl.org/syndication/thread/1.0' );
78 define ( 'NAMESPACE_TOMB' , 'http://purl.org/atompub/tombstones/1.0' );
79 define ( 'NAMESPACE_ACTIVITY', 'http://activitystrea.ms/spec/1.0/' );
80 define ( 'NAMESPACE_ACTIVITY_SCHEMA', 'http://activitystrea.ms/schema/1.0/' );
81 define ( 'NAMESPACE_MEDIA', 'http://purl.org/syndication/atommedia' );
82 define ( 'NAMESPACE_SALMON_ME', 'http://salmon-protocol.org/ns/magic-env' );
83 define ( 'NAMESPACE_OSTATUSSUB', 'http://ostatus.org/schema/1.0/subscribe' );
84 define ( 'NAMESPACE_GEORSS', 'http://www.georss.org/georss' );
85 define ( 'NAMESPACE_POCO', 'http://portablecontacts.net/spec/1.0' );
86 define ( 'NAMESPACE_FEED', 'http://schemas.google.com/g/2010#updates-from' );
89 * activity stream defines
92 define ( 'ACTIVITY_LIKE', NAMESPACE_ACTIVITY_SCHEMA . 'like' );
93 define ( 'ACTIVITY_DISLIKE', NAMESPACE_DFRN . '/dislike' );
94 define ( 'ACTIVITY_OBJ_HEART', NAMESPACE_DFRN . '/heart' );
96 define ( 'ACTIVITY_FRIEND', NAMESPACE_ACTIVITY_SCHEMA . 'make-friend' );
97 define ( 'ACTIVITY_FOLLOW', NAMESPACE_ACTIVITY_SCHEMA . 'follow' );
98 define ( 'ACTIVITY_UNFOLLOW', NAMESPACE_ACTIVITY_SCHEMA . 'unfollow' );
99 define ( 'ACTIVITY_POST', NAMESPACE_ACTIVITY_SCHEMA . 'post' );
100 define ( 'ACTIVITY_UPDATE', NAMESPACE_ACTIVITY_SCHEMA . 'update' );
101 define ( 'ACTIVITY_TAG', NAMESPACE_ACTIVITY_SCHEMA . 'tag' );
103 define ( 'ACTIVITY_OBJ_COMMENT', NAMESPACE_ACTIVITY_SCHEMA . 'comment' );
104 define ( 'ACTIVITY_OBJ_NOTE', NAMESPACE_ACTIVITY_SCHEMA . 'note' );
105 define ( 'ACTIVITY_OBJ_PERSON', NAMESPACE_ACTIVITY_SCHEMA . 'person' );
106 define ( 'ACTIVITY_OBJ_PHOTO', NAMESPACE_ACTIVITY_SCHEMA . 'photo' );
107 define ( 'ACTIVITY_OBJ_P_PHOTO', NAMESPACE_ACTIVITY_SCHEMA . 'profile-photo' );
108 define ( 'ACTIVITY_OBJ_ALBUM', NAMESPACE_ACTIVITY_SCHEMA . 'photo-album' );
111 * item weight for query ordering
114 define ( 'GRAVITY_PARENT', 0);
115 define ( 'GRAVITY_LIKE', 3);
116 define ( 'GRAVITY_COMMENT', 6);
120 * Reverse the effect of magic_quotes_gpc if it is enabled.
121 * Please disable magic_quotes_gpc so we don't have to do this.
122 * See http://php.net/manual/en/security.magicquotes.disabling.php
126 if (get_magic_quotes_gpc()) {
127 $process = array(&$_GET, &$_POST, &$_COOKIE, &$_REQUEST);
128 while (list($key, $val) = each($process)) {
129 foreach ($val as $k => $v) {
130 unset($process[$key][$k]);
132 $process[$key][stripslashes($k)] = $v;
133 $process[] = &$process[$key][stripslashes($k)];
135 $process[$key][stripslashes($k)] = stripslashes($v);
147 * Our main application structure for the life of this page
148 * Primarily deals with the URL that got us here
149 * and tries to make some sense of it, and
150 * stores our page contents and config storage
151 * and anything else that might need to be passed around
152 * before we spit the page out.
156 if(! class_exists('App')) {
159 public $module_loaded = false;
160 public $query_string;
169 public $error = false;
178 public $interactive = true;
187 private $curl_headers;
189 function __construct() {
191 $this->config = array();
192 $this->page = array();
193 $this->pager= array();
195 $this->query_string = '';
197 $this->scheme = ((isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS'])) ? 'https' : 'http' );
199 if(x($_SERVER,'SERVER_NAME'))
200 $this->hostname = $_SERVER['SERVER_NAME'];
202 set_include_path("include/$this->hostname" . PATH_SEPARATOR . 'include' . PATH_SEPARATOR . '.' );
204 if((x($_SERVER,'QUERY_STRING')) && substr($_SERVER['QUERY_STRING'],0,2) === "q=")
205 $this->query_string = substr($_SERVER['QUERY_STRING'],2);
207 $this->cmd = trim($_GET['q'],'/');
210 * Figure out if we are running at the top of a domain
211 * or in a sub-directory and adjust accordingly
214 $path = trim(dirname($_SERVER['SCRIPT_NAME']),'/');
215 if(isset($path) && strlen($path) && ($path != $this->path))
221 * Break the URL path into C style argc/argv style arguments for our
222 * modules. Given "http://example.com/module/arg1/arg2", $this->argc
223 * will be 3 (integer) and $this->argv will contain:
229 * There will always be one argument. If provided a naked domain
230 * URL, $this->argv[0] is set to "home".
234 $this->argv = explode('/',$this->cmd);
235 $this->argc = count($this->argv);
236 if((array_key_exists('0',$this->argv)) && strlen($this->argv[0])) {
237 $this->module = $this->argv[0];
240 $this->module = 'home';
244 * Special handling for the webfinger/lrdd host XRD file
245 * Just spit out the contents and exit.
248 if($this->cmd === '.well-known/host-meta')
249 require_once('include/hostxrd.php');
253 * See if there is any page number information, and initialise
257 $this->pager['page'] = ((x($_GET,'page')) ? $_GET['page'] : 1);
258 $this->pager['itemspage'] = 50;
259 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
260 $this->pager['total'] = 0;
263 function get_baseurl($ssl = false) {
264 if(strlen($this->baseurl))
265 return $this->baseurl;
267 $this->baseurl = (($ssl) ? 'https' : $this->scheme) . "://" . $this->hostname . ((isset($this->path) && strlen($this->path)) ? '/' . $this->path : '' );
268 return $this->baseurl;
271 function set_baseurl($url) {
272 $this->baseurl = $url;
273 $this->hostname = basename($url);
276 function get_hostname() {
277 return $this->hostname;
280 function set_hostname($h) {
281 $this->hostname = $h;
284 function set_path($p) {
285 $this->path = trim(trim($p),'/');
288 function get_path() {
292 function set_pager_total($n) {
293 $this->pager['total'] = intval($n);
296 function set_pager_itemspage($n) {
297 $this->pager['itemspage'] = intval($n);
298 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
302 function init_pagehead() {
303 $tpl = load_view_file("view/head.tpl");
304 $this->page['htmlhead'] = replace_macros($tpl,array(
305 '$baseurl' => $this->get_baseurl() . '/'
309 function set_curl_code($code) {
310 $this->curl_code = $code;
313 function get_curl_code() {
314 return $this->curl_code;
317 function set_curl_headers($headers) {
318 $this->curl_headers = $headers;
321 function get_curl_headers() {
322 return $this->curl_headers;
328 // retrieve the App structure
329 // useful in functions which require it but don't get it passed to them
331 if(! function_exists('get_app')) {
338 // Multi-purpose function to check variable state.
339 // Usage: x($var) or $x($array,'key')
340 // returns false if variable/key is not set
341 // if variable is set, returns 1 if has 'non-zero' value, otherwise returns 0.
342 // e.g. x('') or x(0) returns 0;
344 if(! function_exists('x')) {
345 function x($s,$k = NULL) {
347 if((is_array($s)) && (array_key_exists($k,$s))) {
365 // called from db initialisation if db is dead.
367 if(! function_exists('system_unavailable')) {
368 function system_unavailable() {
369 include('system_unavailable.php');
373 // Primarily involved with database upgrade, but also sets the
374 // base url for use in cmdline programs which don't have
375 // $_SERVER variables.
377 if(! function_exists('check_config')) {
378 function check_config(&$a) {
380 load_config('system');
382 $build = get_config('system','build');
384 $build = set_config('system','build',BUILD_ID);
386 $url = get_config('system','url');
388 $url = set_config('system','url',$a->get_baseurl());
390 if($build != BUILD_ID) {
391 $stored = intval($build);
392 $current = intval(BUILD_ID);
393 if(($stored < $current) && file_exists('update.php')) {
394 // We're reporting a different version than what is currently installed.
395 // Run any existing update scripts to bring the database up to current.
397 require_once('update.php');
398 for($x = $stored; $x < $current; $x ++) {
399 if(function_exists('update_' . $x)) {
400 $func = 'update_' . $x;
404 set_config('system','build', BUILD_ID);
411 // This is our template processor.
412 // $s is the string requiring macro substitution.
413 // $r is an array of key value pairs (search => replace)
414 // returns substituted string.
415 // WARNING: this is pretty basic, and doesn't properly handle search strings that are substrings of each other.
416 // For instance if 'test' => "foo" and 'testing' => "bar", testing could become either bar or fooing,
417 // depending on the order in which they were declared in the array.
419 if(! function_exists('replace_macros')) {
420 function replace_macros($s,$r) {
425 if(is_array($r) && count($r)) {
426 foreach ($r as $k => $v ) {
431 return str_replace($search,$replace,$s);
435 // load string translation table for alternate language
437 if(! function_exists('load_translation_table')) {
438 function load_translation_table($lang) {
441 if(file_exists("view/$lang/strings.php"))
442 include("view/$lang/strings.php");
445 // translate string if translation exists
447 if(! function_exists('t')) {
452 if(x($a->strings,$s))
453 return $a->strings[$s];
457 // curl wrapper. If binary flag is true, return binary
460 if(! function_exists('fetch_url')) {
461 function fetch_url($url,$binary = false, &$redirects = 0) {
465 $ch = curl_init($url);
466 if(($redirects > 8) || (! $ch))
469 curl_setopt($ch, CURLOPT_HEADER, true);
470 curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
473 $curl_time = intval(get_config('system','curl_timeout'));
474 curl_setopt($ch, CURLOPT_TIMEOUT, (($curl_time !== false) ? $curl_time : 60));
476 // by default we will allow self-signed certs
477 // but you can override this
479 $check_cert = get_config('system','verifyssl');
480 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
482 $prx = get_config('system','proxy');
484 curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
485 curl_setopt($ch, CURLOPT_PROXY, $prx);
486 $prxusr = get_config('system','proxyuser');
488 curl_setopt($ch, CURLOPT_PROXYUSERPWD, $prxusr);
491 curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
493 $a->set_curl_code(0);
495 // don't let curl abort the entire application
496 // if it throws any errors.
498 $s = @curl_exec($ch);
500 $http_code = intval(curl_getinfo($ch, CURLINFO_HTTP_CODE));
501 $header = substr($s,0,strpos($s,"\r\n\r\n"));
502 if(stristr($header,'100') && (strlen($header) < 30)) {
503 // 100 Continue has two headers, get the real one
504 $s = substr($s,strlen($header)+4);
505 $header = substr($s,0,strpos($s,"\r\n\r\n"));
507 if($http_code == 301 || $http_code == 302 || $http_code == 303) {
509 preg_match('/(Location:|URI:)(.*?)\n/', $header, $matches);
510 $url = trim(array_pop($matches));
511 $url_parsed = parse_url($url);
512 if (isset($url_parsed)) {
514 return fetch_url($url,$binary,$redirects);
517 $a->set_curl_code($http_code);
518 $body = substr($s,strlen($header)+4);
519 $a->set_curl_headers($header);
525 // post request to $url. $params is an array of post variables.
527 if(! function_exists('post_url')) {
528 function post_url($url,$params, $headers = null, &$redirects = 0) {
530 $ch = curl_init($url);
531 if(($redirects > 8) || (! $ch))
534 curl_setopt($ch, CURLOPT_HEADER, true);
535 curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
536 curl_setopt($ch, CURLOPT_POST,1);
537 curl_setopt($ch, CURLOPT_POSTFIELDS,$params);
539 $curl_time = intval(get_config('system','curl_timeout'));
540 curl_setopt($ch, CURLOPT_TIMEOUT, (($curl_time !== false) ? $curl_time : 60));
542 if(is_array($headers))
543 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
545 $check_cert = get_config('system','verifyssl');
546 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
547 $prx = get_config('system','proxy');
549 curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
550 curl_setopt($ch, CURLOPT_PROXY, $prx);
551 $prxusr = get_config('system','proxyuser');
553 curl_setopt($ch, CURLOPT_PROXYUSERPWD, $prxusr);
556 $a->set_curl_code(0);
558 // don't let curl abort the entire application
559 // if it throws any errors.
561 $s = @curl_exec($ch);
563 $http_code = intval(curl_getinfo($ch, CURLINFO_HTTP_CODE));
564 $header = substr($s,0,strpos($s,"\r\n\r\n"));
565 if(stristr($header,'100') && (strlen($header) < 30)) {
566 // 100 Continue has two headers, get the real one
567 $s = substr($s,strlen($header)+4);
568 $header = substr($s,0,strpos($s,"\r\n\r\n"));
570 if($http_code == 301 || $http_code == 302 || $http_code == 303) {
572 preg_match('/(Location:|URI:)(.*?)\n/', $header, $matches);
573 $url = trim(array_pop($matches));
574 $url_parsed = parse_url($url);
575 if (isset($url_parsed)) {
577 return post_url($url,$binary,$headers,$redirects);
580 $a->set_curl_code($http_code);
581 $body = substr($s,strlen($header)+4);
582 $a->set_curl_headers($header);
588 // random hash, 64 chars
590 if(! function_exists('random_string')) {
591 function random_string() {
592 return(hash('sha256',uniqid(rand(),true)));
596 * This is our primary input filter.
598 * The high bit hack only involved some old IE browser, forget which (IE5/Mac?)
599 * that had an XSS attack vector due to stripping the high-bit on an 8-bit character
600 * after cleansing, and angle chars with the high bit set could get through as markup.
602 * This is now disabled because it was interfering with some legitimate unicode sequences
603 * and hopefully there aren't a lot of those browsers left.
605 * Use this on any text input where angle chars are not valid or permitted
606 * They will be replaced with safer brackets. This may be filtered further
607 * if these are not allowed either.
611 if(! function_exists('notags')) {
612 function notags($string) {
614 return(str_replace(array("<",">"), array('[',']'), $string));
616 // High-bit filter no longer used
617 // return(str_replace(array("<",">","\xBA","\xBC","\xBE"), array('[',']','','',''), $string));
620 // use this on "body" or "content" input where angle chars shouldn't be removed,
621 // and allow them to be safely displayed.
623 if(! function_exists('escape_tags')) {
624 function escape_tags($string) {
626 return(htmlspecialchars($string));
629 // wrapper for adding a login box. If $register == true provide a registration
630 // link. This will most always depend on the value of $a->config['register_policy'].
631 // returns the complete html for inserting into the page
633 if(! function_exists('login')) {
634 function login($register = false) {
636 $register_html = (($register) ? load_view_file("view/register-link.tpl") : "");
638 $noid = get_config('system','no_openid');
640 $classname = 'no-openid';
641 $namelabel = t('Nickname or Email address: ');
642 $passlabel = t('Password: ');
646 $classname = 'openid';
647 $namelabel = t('Nickname/Email/OpenID: ');
648 $passlabel = t("Password \x28if not OpenID\x29: ");
651 $lostpass = t('Forgot your password?');
652 $lostlink = t('Password Reset');
654 if(x($_SESSION,'authenticated')) {
655 $tpl = load_view_file("view/logout.tpl");
658 $tpl = load_view_file("view/login.tpl");
662 $o = replace_macros($tpl,array(
663 '$register_html' => $register_html,
664 '$classname' => $classname,
665 '$namelabel' => $namelabel,
666 '$passlabel' => $passlabel,
668 '$lostpass' => $lostpass,
669 '$lostlink' => $lostlink
675 // generate a string that's random, but usually pronounceable.
676 // used to generate initial passwords
678 if(! function_exists('autoname')) {
679 function autoname($len) {
681 $vowels = array('a','a','ai','au','e','e','e','ee','ea','i','ie','o','ou','u');
682 if(mt_rand(0,5) == 4)
700 's','sc','sh','sm','sp','st',
708 $midcons = array('ck','ct','gn','ld','lf','lm','lt','mb','mm', 'mn','mp',
709 'nd','ng','nk','nt','rn','rp','rt');
711 $noend = array('bl', 'br', 'cl','cr','dr','fl','fr','gl','gr',
712 'kh', 'kl','kr','mn','pl','pr','rh','tr','qu','wh');
714 $start = mt_rand(0,2);
722 for ($x = 0; $x < $len; $x ++) {
723 $r = mt_rand(0,count($table) - 1);
726 if($table == $vowels)
727 $table = array_merge($cons,$midcons);
733 $word = substr($word,0,$len);
735 foreach($noend as $noe) {
736 if((strlen($word) > 2) && (substr($word,-2) == $noe)) {
737 $word = substr($word,0,-1);
741 if(substr($word,-1) == 'q')
742 $word = substr($word,0,-1);
746 // Used to end the current process, after saving session state.
748 if(! function_exists('killme')) {
750 session_write_close();
754 // redirect to another URL and terminate this process.
756 if(! function_exists('goaway')) {
757 function goaway($s) {
758 header("Location: $s");
762 // Generic XML return
763 // Outputs a basic dfrn XML status structure to STDOUT, with a <status> variable
764 // of $st and an optional text <message> of $message and terminates the current process.
766 if(! function_exists('xml_status')) {
767 function xml_status($st, $message = '') {
769 $xml_message = ((strlen($message)) ? "\t<message>" . xmlify($message) . "</message>\r\n" : '');
772 logger('xml_status returning non_zero: ' . $st . " message=" . $message);
774 header( "Content-type: text/xml" );
775 echo '<?xml version="1.0" encoding="UTF-8"?>'."\r\n";
776 echo "<result>\r\n\t<status>$st</status>\r\n$xml_message</result>\r\n";
780 // Returns the uid of locally logged in user or false.
782 if(! function_exists('local_user')) {
783 function local_user() {
784 if((x($_SESSION,'authenticated')) && (x($_SESSION,'uid')))
785 return intval($_SESSION['uid']);
789 // Returns contact id of authenticated site visitor or false
791 if(! function_exists('remote_user')) {
792 function remote_user() {
793 if((x($_SESSION,'authenticated')) && (x($_SESSION,'visitor_id')))
794 return intval($_SESSION['visitor_id']);
798 // contents of $s are displayed prominently on the page the next time
799 // a page is loaded. Usually used for errors or alerts.
801 if(! function_exists('notice')) {
802 function notice($s) {
805 $_SESSION['sysmsg'] .= $s;
808 // wrapper around config to limit the text length of an incoming message
810 if(! function_exists('get_max_import_size')) {
811 function get_max_import_size() {
813 return ((x($a->config,'max_import_size')) ? $a->config['max_import_size'] : 0 );
817 // escape text ($str) for XML transport
818 // returns escaped text.
820 if(! function_exists('xmlify')) {
821 function xmlify($str) {
824 for($x = 0; $x < strlen($str); $x ++) {
855 $buffer = trim($buffer);
860 // pass xml escaped text ($s), returns unescaped text
862 if(! function_exists('unxmlify')) {
863 function unxmlify($s) {
864 $ret = str_replace('&','&', $s);
865 $ret = str_replace(array('<','>','"','''),array('<','>','"',"'"),$ret);
869 // convenience wrapper, reverse the operation "bin2hex"
871 if(! function_exists('hex2bin')) {
872 function hex2bin($s) {
873 return(pack("H*",$s));
876 // Automatic pagination.
877 // To use, get the count of total items.
878 // Then call $a->set_pager_total($number_items);
879 // Optionally call $a->set_pager_itemspage($n) to the number of items to display on each page
880 // Then call paginate($a) after the end of the display loop to insert the pager block on the page
881 // (assuming there are enough items to paginate).
882 // When using with SQL, the setting LIMIT %d, %d => $a->pager['start'],$a->pager['itemspage']
883 // will limit the results to the correct items for the current page.
884 // The actual page handling is then accomplished at the application layer.
886 if(! function_exists('paginate')) {
887 function paginate(&$a) {
889 $stripped = preg_replace('/(&page=[0-9]*)/','',$a->query_string);
890 $stripped = str_replace('q=','',$stripped);
891 $stripped = trim($stripped,'/');
892 $url = $a->get_baseurl() . '/' . $stripped;
895 if($a->pager['total'] > $a->pager['itemspage']) {
896 $o .= '<div class="pager">';
897 if($a->pager['page'] != 1)
898 $o .= '<span class="pager_prev">'."<a href=\"$url".'&page='.($a->pager['page'] - 1).'">' . t('prev') . '</a></span> ';
900 $o .= "<span class=\"pager_first\"><a href=\"$url"."&page=1\">" . t('first') . "</a></span> ";
902 $numpages = $a->pager['total'] / $a->pager['itemspage'];
905 $numstop = $numpages;
908 $numstart = (($pagenum > 7) ? ($pagenum - 7) : 1);
909 $numstop = (($pagenum > ($numpages - 7)) ? $numpages : ($numstart + 14));
912 for($i = $numstart; $i <= $numstop; $i++){
913 if($i == $a->pager['page'])
914 $o .= '<span class="pager_current">'.(($i < 10) ? ' '.$i : $i);
916 $o .= "<span class=\"pager_n\"><a href=\"$url"."&page=$i\">".(($i < 10) ? ' '.$i : $i)."</a>";
920 if(($a->pager['total'] % $a->pager['itemspage']) != 0) {
921 if($i == $a->pager['page'])
922 $o .= '<span class="pager_current">'.(($i < 10) ? ' '.$i : $i);
924 $o .= "<span class=\"pager_n\"><a href=\"$url"."&page=$i\">".(($i < 10) ? ' '.$i : $i)."</a>";
928 $lastpage = (($numpages > intval($numpages)) ? intval($numpages)+1 : $numpages);
929 $o .= "<span class=\"pager_last\"><a href=\"$url"."&page=$lastpage\">" . t('last') . "</a></span> ";
931 if(($a->pager['total'] - ($a->pager['itemspage'] * $a->pager['page'])) > 0)
932 $o .= '<span class="pager_next">'."<a href=\"$url"."&page=".($a->pager['page'] + 1).'">' . t('next') . '</a></span>';
933 $o .= '</div>'."\r\n";
938 // Turn user/group ACLs stored as angle bracketed text into arrays
940 if(! function_exists('expand_acl')) {
941 function expand_acl($s) {
942 // turn string array of angle-bracketed elements into numeric array
943 // e.g. "<1><2><3>" => array(1,2,3);
947 $t = str_replace('<','',$s);
948 $a = explode('>',$t);
951 $ret[] = intval($aa);
957 // Used to wrap ACL elements in angle brackets for storage
959 if(! function_exists('sanitise_acl')) {
960 function sanitise_acl(&$item) {
962 $item = '<' . intval(notags(trim($item))) . '>';
967 // retrieve a "family" of config variables from database to cached storage
969 if(! function_exists('load_config')) {
970 function load_config($family) {
972 $r = q("SELECT * FROM `config` WHERE `cat` = '%s'",
978 $a->config[$family][$k] = $rr['v'];
983 // get a particular config variable given the family name
984 // and key. Returns false if not set.
985 // $instore is only used by the set_config function
986 // to determine if the key already exists in the DB
987 // If a key is found in the DB but doesn't exist in
988 // local config cache, pull it into the cache so we don't have
989 // to hit the DB again for this item.
991 if(! function_exists('get_config')) {
992 function get_config($family, $key, $instore = false) {
997 if(isset($a->config[$family][$key])) {
998 if($a->config[$family][$key] === '!<unset>!') {
1001 return $a->config[$family][$key];
1004 $ret = q("SELECT `v` FROM `config` WHERE `cat` = '%s' AND `k` = '%s' LIMIT 1",
1009 $a->config[$family][$key] = $ret[0]['v'];
1010 return $ret[0]['v'];
1013 $a->config[$family][$key] = '!<unset>!';
1018 // Store a config value ($value) in the category ($family)
1019 // under the key ($key)
1020 // Return the value, or false if the database update failed
1022 if(! function_exists('set_config')) {
1023 function set_config($family,$key,$value) {
1026 $a->config[$family][$key] = $value;
1028 if(get_config($family,$key,true) === false) {
1029 $ret = q("INSERT INTO `config` ( `cat`, `k`, `v` ) VALUES ( '%s', '%s', '%s' ) ",
1038 $ret = q("UPDATE `config` SET `v` = '%s' WHERE `cat` = '%s' AND `k` = '%s' LIMIT 1",
1049 if(! function_exists('get_pconfig')) {
1050 function get_pconfig($uid,$family, $key, $instore = false) {
1055 if(isset($a->config[$uid][$family][$key])) {
1056 if($a->config[$uid][$family][$key] === '!<unset>!') {
1059 return $a->config[$uid][$family][$key];
1062 $ret = q("SELECT `v` FROM `pconfig` WHERE `uid` = %d AND `cat` = '%s' AND `k` = '%s' LIMIT 1",
1068 $a->config[$uid][$family][$key] = $ret[0]['v'];
1069 return $ret[0]['v'];
1072 $a->config[$uid][$family][$key] = '!<unset>!';
1077 if(! function_exists('del_config')) {
1078 function del_config($family,$key) {
1081 if(x($a->config[$family],$key))
1082 unset($a->config[$family][$key]);
1083 $ret = q("DELETE FROM `config` WHERE `cat` = '%s' AND `k` = '%s' LIMIT 1",
1092 // Same as above functions except these are for personal config storage and take an
1093 // additional $uid argument.
1095 if(! function_exists('set_pconfig')) {
1096 function set_pconfig($uid,$family,$key,$value) {
1099 $a->config[$uid][$family][$key] = $value;
1101 if(get_pconfig($uid,$family,$key,true) === false) {
1102 $ret = q("INSERT INTO `pconfig` ( `uid`, `cat`, `k`, `v` ) VALUES ( %d, '%s', '%s', '%s' ) ",
1112 $ret = q("UPDATE `pconfig` SET `v` = '%s' WHERE `uid` = %d AND `cat` = '%s' AND `k` = '%s' LIMIT 1",
1123 if(! function_exists('del_pconfig')) {
1124 function del_pconfig($uid,$family,$key) {
1127 if(x($a->config[$uid][$family],$key))
1128 unset($a->config[$uid][$family][$key]);
1129 $ret = q("DELETE FROM `pconfig` WHERE `uid` = %d AND `cat` = '%s' AND `k` = '%s' LIMIT 1",
1138 // convert an XML document to a normalised, case-corrected array
1139 // used by webfinger
1141 if(! function_exists('convert_xml_element_to_array')) {
1142 function convert_xml_element_to_array($xml_element, &$recursion_depth=0) {
1144 // If we're getting too deep, bail out
1145 if ($recursion_depth > 512) {
1149 if (!is_string($xml_element) &&
1150 !is_array($xml_element) &&
1151 (get_class($xml_element) == 'SimpleXMLElement')) {
1152 $xml_element_copy = $xml_element;
1153 $xml_element = get_object_vars($xml_element);
1156 if (is_array($xml_element)) {
1157 $result_array = array();
1158 if (count($xml_element) <= 0) {
1159 return (trim(strval($xml_element_copy)));
1162 foreach($xml_element as $key=>$value) {
1165 $result_array[strtolower($key)] =
1166 convert_xml_element_to_array($value, $recursion_depth);
1169 if ($recursion_depth == 0) {
1170 $temp_array = $result_array;
1171 $result_array = array(
1172 strtolower($xml_element_copy->getName()) => $temp_array,
1176 return ($result_array);
1179 return (trim(strval($xml_element)));
1183 // Given an email style address, perform webfinger lookup and
1184 // return the resulting DFRN profile URL, or if no DFRN profile URL
1185 // is located, returns an OStatus subscription template (prefixed
1186 // with the string 'stat:' to identify it as on OStatus template).
1187 // If this isn't an email style address just return $s.
1188 // Return an empty string if email-style addresses but webfinger fails,
1189 // or if the resultant personal XRD doesn't contain a supported
1190 // subscription/friend-request attribute.
1192 if(! function_exists('webfinger_dfrn')) {
1193 function webfinger_dfrn($s) {
1194 if(! strstr($s,'@')) {
1197 $links = webfinger($s);
1198 logger('webfinger_dfrn: ' . $s . ':' . print_r($links,true), LOGGER_DATA);
1200 foreach($links as $link)
1201 if($link['@attributes']['rel'] === NAMESPACE_DFRN)
1202 return $link['@attributes']['href'];
1203 foreach($links as $link)
1204 if($link['@attributes']['rel'] === NAMESPACE_OSTATUSSUB)
1205 return 'stat:' . $link['@attributes']['template'];
1210 // Given an email style address, perform webfinger lookup and
1211 // return the array of link attributes from the personal XRD file.
1212 // On error/failure return an empty array.
1215 if(! function_exists('webfinger')) {
1216 function webfinger($s) {
1218 if(strstr($s,'@')) {
1219 $host = substr($s,strpos($s,'@') + 1);
1222 $tpl = fetch_lrdd_template($host);
1223 logger('webfinger: lrdd template: ' . $tpl);
1225 $pxrd = str_replace('{uri}', urlencode('acct:'.$s), $tpl);
1226 $links = fetch_xrd_links($pxrd);
1227 if(! count($links)) {
1228 // try with double slashes
1229 $pxrd = str_replace('{uri}', urlencode('acct://'.$s), $tpl);
1230 $links = fetch_xrd_links($pxrd);
1238 if(! function_exists('lrdd')) {
1239 function lrdd($uri) {
1243 if(strstr($uri,'@')) {
1244 return(webfinger($uri));
1247 $html = fetch_url($uri);
1248 $headers = $a->get_curl_headers();
1249 $lines = explode("\n",$headers);
1251 foreach($lines as $line) {
1252 // TODO alter the following regex to support multiple relations (space separated)
1253 if((stristr($line,'link:')) && preg_match('/<([^>].*)>.*rel\=[\'\"]lrdd[\'\"]/',$line,$matches)) {
1254 $link = $matches[1];
1259 if(! isset($link)) {
1260 // parse the page of the supplied URL looking for rel links
1262 require_once('library/HTML5/Parser.php');
1263 $dom = HTML5_Parser::parse($html);
1266 $items = $dom->getElementsByTagName('link');
1268 foreach($items as $item) {
1269 $x = $item->getAttribute('rel');
1271 $link = $item->getAttribute('href');
1279 return(fetch_xrd_links($link));
1286 // Given a host name, locate the LRDD template from that
1287 // host. Returns the LRDD template or an empty string on
1290 if(! function_exists('fetch_lrdd_template')) {
1291 function fetch_lrdd_template($host) {
1293 $url = 'http://' . $host . '/.well-known/host-meta' ;
1294 $links = fetch_xrd_links($url);
1296 foreach($links as $link)
1297 if($link['@attributes']['rel'] && $link['@attributes']['rel'] === 'lrdd')
1298 $tpl = $link['@attributes']['template'];
1300 if(! strpos($tpl,'{uri}'))
1305 // Given a URL, retrieve the page as an XRD document.
1306 // Return an array of links.
1307 // on error/failure return empty array.
1309 if(! function_exists('fetch_xrd_links')) {
1310 function fetch_xrd_links($url) {
1313 $xml = fetch_url($url);
1317 logger('fetch_xrd_links: ' . $xml, LOGGER_DATA);
1318 $h = simplexml_load_string($xml);
1319 $arr = convert_xml_element_to_array($h);
1321 if(isset($arr['xrd']['link'])) {
1322 $link = $arr['xrd']['link'];
1323 if(! isset($link[0]))
1324 $links = array($link);
1332 // Convert an ACL array to a storable string
1334 if(! function_exists('perms2str')) {
1335 function perms2str($p) {
1338 if(is_array($tmp)) {
1339 array_walk($tmp,'sanitise_acl');
1340 $ret = implode('',$tmp);
1345 // generate a guaranteed unique (for this domain) item ID for ATOM
1346 // safe from birthday paradox
1348 if(! function_exists('item_new_uri')) {
1349 function item_new_uri($hostname,$uid) {
1353 $hash = random_string();
1355 $uri = "urn:X-dfrn:" . $hostname . ':' . $uid . ':' . $hash;
1357 $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' LIMIT 1",
1361 } while($dups == true);
1365 // Generate a guaranteed unique photo ID.
1366 // safe from birthday paradox
1368 if(! function_exists('photo_new_resource')) {
1369 function photo_new_resource() {
1373 $resource = hash('md5',uniqid(mt_rand(),true));
1374 $r = q("SELECT `id` FROM `photo` WHERE `resource-id` = '%s' LIMIT 1",
1379 } while($found == true);
1384 // Take a URL from the wild, prepend http:// if necessary
1385 // and check DNS to see if it's real
1386 // return true if it's OK, false if something is wrong with it
1388 if(! function_exists('validate_url')) {
1389 function validate_url(&$url) {
1390 if(substr($url,0,4) != 'http')
1391 $url = 'http://' . $url;
1392 $h = parse_url($url);
1394 if(($h) && (checkdnsrr($h['host'], 'ANY'))) {
1400 // checks that email is an actual resolvable internet address
1402 if(! function_exists('validate_email')) {
1403 function validate_email($addr) {
1405 if(! strpos($addr,'@'))
1407 $h = substr($addr,strpos($addr,'@') + 1);
1409 if(($h) && (checkdnsrr($h, 'ANY'))) {
1415 // Check $url against our list of allowed sites,
1416 // wildcards allowed. If allowed_sites is unset return true;
1417 // If url is allowed, return true.
1418 // otherwise, return false
1420 if(! function_exists('allowed_url')) {
1421 function allowed_url($url) {
1423 $h = parse_url($url);
1429 $str_allowed = get_config('system','allowed_sites');
1435 $host = strtolower($h['host']);
1437 // always allow our own site
1439 if($host == strtolower($_SERVER['SERVER_NAME']))
1442 $fnmatch = function_exists('fnmatch');
1443 $allowed = explode(',',$str_allowed);
1445 if(count($allowed)) {
1446 foreach($allowed as $a) {
1447 $pat = strtolower(trim($a));
1448 if(($fnmatch && fnmatch($pat,$host)) || ($pat == $host)) {
1457 // check if email address is allowed to register here.
1458 // Compare against our list (wildcards allowed).
1459 // Returns false if not allowed, true if allowed or if
1460 // allowed list is not configured.
1462 if(! function_exists('allowed_email')) {
1463 function allowed_email($email) {
1466 $domain = strtolower(substr($email,strpos($email,'@') + 1));
1470 $str_allowed = get_config('system','allowed_email');
1476 $fnmatch = function_exists('fnmatch');
1477 $allowed = explode(',',$str_allowed);
1479 if(count($allowed)) {
1480 foreach($allowed as $a) {
1481 $pat = strtolower(trim($a));
1482 if(($fnmatch && fnmatch($pat,$host)) || ($pat == $host)) {
1491 // Format the like/dislike text for a profile item
1492 // $cnt = number of people who like/dislike the item
1493 // $arr = array of pre-linked names of likers/dislikers
1494 // $type = one of 'like, 'dislike'
1496 // returns formatted text
1498 if(! function_exists('format_like')) {
1499 function format_like($cnt,$arr,$type,$id) {
1502 $o .= $arr[0] . (($type === 'like') ? t(' likes this.') : t(' doesn\'t like this.')) . EOL ;
1504 $o .= '<span class="fakelink" onclick="openClose(\'' . $type . 'list-' . $id . '\');" >'
1505 . $cnt . ' ' . t('people') . '</span> ' . (($type === 'like') ? t('like this.') : t('don\'t like this.')) . EOL ;
1506 $total = count($arr);
1507 if($total >= MAX_LIKERS)
1508 $arr = array_slice($arr, 0, MAX_LIKERS - 1);
1509 if($total < MAX_LIKERS)
1510 $arr[count($arr)-1] = t('and') . ' ' . $arr[count($arr)-1];
1511 $str = implode(', ', $arr);
1512 if($total >= MAX_LIKERS)
1513 $str .= t(', and ') . $total - MAX_LIKERS . t(' other people');
1514 $str .= (($type === 'like') ? t(' like this.') : t(' don\'t like this.'));
1515 $o .= "\t" . '<div id="' . $type . 'list-' . $id . '" style="display: none;" >' . $str . '</div>';
1521 // wrapper to load a view template, checking for alternate
1522 // languages before falling back to the default
1524 if(! function_exists('load_view_file')) {
1525 function load_view_file($s) {
1528 $lang = get_config('system','language');
1531 if(file_exists("$d/$lang/$b"))
1532 return file_get_contents("$d/$lang/$b");
1533 return file_get_contents($s);
1536 // for html,xml parsing - let's say you've got
1537 // an attribute foobar="class1 class2 class3"
1538 // and you want to find out if it contains 'class3'.
1539 // you can't use a normal sub string search because you
1540 // might match 'notclass3' and a regex to do the job is
1541 // possible but a bit complicated.
1542 // pass the attribute string as $attr and the attribute you
1543 // are looking for as $s - returns true if found, otherwise false
1545 if(! function_exists('attribute_contains')) {
1546 function attribute_contains($attr,$s) {
1547 $a = explode(' ', $attr);
1548 if(count($a) && in_array($s,$a))
1553 if(! function_exists('logger')) {
1554 function logger($msg,$level = 0) {
1556 $debugging = get_config('system','debugging');
1557 $loglevel = intval(get_config('system','loglevel'));
1558 $logfile = get_config('system','logfile');
1560 if((! $debugging) || (! $logfile) || ($level > $loglevel))
1563 @file_put_contents($logfile, datetime_convert() . ':' . session_id() . ' ' . $msg . "\n", FILE_APPEND);
1568 if(! function_exists('activity_match')) {
1569 function activity_match($haystack,$needle) {
1570 if(($haystack === $needle) || ((basename($needle) === $haystack) && strstr($needle,NAMESPACE_ACTIVITY_SCHEMA)))
1576 // Pull out all #hashtags and @person tags from $s;
1577 // We also get @person@domain.com - which would make
1578 // the regex quite complicated as tags can also
1579 // end a sentence. So we'll run through our results
1580 // and strip the period from any tags which end with one.
1581 // Returns array of tags found, or empty array.
1584 if(! function_exists('get_tags')) {
1585 function get_tags($s) {
1587 if(preg_match_all('/([@#][^ \x0D\x0A,:?]*)([ \x0D\x0A,:?]|$)/',$s,$match)) {
1588 foreach($match[1] as $match) {
1589 if(strstr($match,"]")) {
1590 // we might be inside a bbcode color tag - leave it alone
1593 if(substr($match,-1,1) === '.')
1594 $ret[] = substr($match,0,-1);
1604 // quick and dirty quoted_printable encoding
1606 if(! function_exists('qp')) {
1608 return str_replace ("%","=",rawurlencode($s));
1612 if(! function_exists('like_puller')) {
1613 function like_puller($a,$item,&$arr,$mode) {
1617 $verb = (($mode === 'like') ? ACTIVITY_LIKE : ACTIVITY_DISLIKE);
1619 if((activity_match($item['verb'],$verb)) && ($item['id'] != $item['parent'])) {
1620 $url = $item['author-link'];
1621 if(($item['network'] === 'dfrn') && (! $item['self']) && ($item['author-link'] == $item['url'])) {
1622 $url = $a->get_baseurl() . '/redir/' . $item['contact-id'];
1623 $sparkle = ' class="sparkle" ';
1625 if(! ((isset($arr[$item['parent'] . '-l'])) && (is_array($arr[$item['parent'] . '-l']))))
1626 $arr[$item['parent'] . '-l'] = array();
1627 if(! isset($arr[$item['parent']]))
1628 $arr[$item['parent']] = 1;
1630 $arr[$item['parent']] ++;
1631 $arr[$item['parent'] . '-l'][] = '<a href="'. $url . '"'. $sparkle .'>' . $item['author-name'] . '</a>';
1636 if(! function_exists('get_mentions')) {
1637 function get_mentions($item) {
1639 if(! strlen($item['tag']))
1642 $arr = explode(',',$item['tag']);
1643 foreach($arr as $x) {
1645 if(preg_match('/@\[url=([^\]]*)\]/',$x,$matches))
1646 $o .= "\t\t" . '<link rel="mentioned" href="' . $matches[1] . '" />' . "\r\n";
1651 if(! function_exists('contact_block')) {
1652 function contact_block() {
1655 if((! is_array($a->profile)) || ($a->profile['hide-friends']))
1657 $r = q("SELECT COUNT(*) AS `total` FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 and `pending` = 0",
1658 intval($a->profile['uid'])
1661 $total = intval($r[0]['total']);
1664 $o .= '<h4 class="contact-h4">' . t('No contacts') . '</h4>';
1667 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 and `pending` = 0 ORDER BY RAND() LIMIT 24",
1668 intval($a->profile['uid'])
1671 $o .= '<h4 class="contact-h4">' . $total . ' ' . t('Contacts') . '</h4><div id="contact-block">';
1672 foreach($r as $rr) {
1673 $redirect_url = $a->get_baseurl() . '/redir/' . $rr['id'];
1674 if(local_user() && ($rr['uid'] == local_user())
1675 && ($rr['network'] === 'dfrn')) {
1676 $url = $redirect_url;
1677 $sparkle = ' sparkle';
1684 $o .= '<div class="contact-block-div"><a class="contact-block-link' . $sparkle . '" href="' . $url . '" ><img class="contact-block-img' . $sparkle . '" src="' . $rr['micro'] . '" title="' . $rr['name'] . ' [' . $rr['url'] . ']" alt="' . $rr['name'] . '" /></a></div>' . "\r\n";
1686 $o .= '</div><div id="contact-block-end"></div>';
1687 $o .= '<div id="viewcontacts"><a id="viewcontacts-link" href="viewcontacts/' . $a->profile['nickname'] . '">' . t('View Contacts') . '</a></div>';
1694 if(! function_exists('search')) {
1695 function search($s) {
1697 $o = '<div id="search-box">';
1698 $o .= '<form action="' . $a->get_baseurl() . '/search' . '" method="get" >';
1699 $o .= '<input type="text" name="search" id="search-text" value="' . $s .'" />';
1700 $o .= '<input type="submit" name="submit" id="search-submit" value="' . t('Search') . '" />';
1701 $o .= '</form></div>';
1705 if(! function_exists('valid_email')) {
1706 function valid_email($x){
1707 if(preg_match('/^[_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)+$/',$x))
1713 if(! function_exists('gravatar_img')) {
1714 function gravatar_img($email) {
1716 $opt = 'identicon'; // psuedo-random geometric pattern if not found
1718 $hash = md5(trim(strtolower($email)));
1720 $url = 'http://www.gravatar.com/avatar/' . $hash . '.jpg'
1721 . '?s=' . $size . '&d=' . $opt . '&r=' . $rating;
1723 logger('gravatar: ' . $email . ' ' . $url);
1727 if(! function_exists('aes_decrypt')) {
1728 function aes_decrypt($val,$ky)
1730 $key="\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0";
1731 for($a=0;$a<strlen($ky);$a++)
1732 $key[$a%16]=chr(ord($key[$a%16]) ^ ord($ky[$a]));
1733 $mode = MCRYPT_MODE_ECB;
1734 $enc = MCRYPT_RIJNDAEL_128;
1735 $dec = @mcrypt_decrypt($enc, $key, $val, $mode, @mcrypt_create_iv( @mcrypt_get_iv_size($enc, $mode), MCRYPT_DEV_URANDOM ) );
1736 return rtrim($dec,(( ord(substr($dec,strlen($dec)-1,1))>=0 and ord(substr($dec, strlen($dec)-1,1))<=16)? chr(ord( substr($dec,strlen($dec)-1,1))):null));
1740 if(! function_exists('aes_encrypt')) {
1741 function aes_encrypt($val,$ky)
1743 $key="\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0";
1744 for($a=0;$a<strlen($ky);$a++)
1745 $key[$a%16]=chr(ord($key[$a%16]) ^ ord($ky[$a]));
1746 $mode=MCRYPT_MODE_ECB;
1747 $enc=MCRYPT_RIJNDAEL_128;
1748 $val=str_pad($val, (16*(floor(strlen($val) / 16)+(strlen($val) % 16==0?2:1))), chr(16-(strlen($val) % 16)));
1749 return mcrypt_encrypt($enc, $key, $val, $mode, mcrypt_create_iv( mcrypt_get_iv_size($enc, $mode), MCRYPT_DEV_URANDOM));
1757 * Replace naked text hyperlink with HTML formatted hyperlink
1761 if(! function_exists('linkify')) {
1762 function linkify($s) {
1763 $s = preg_replace("/(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\.\=\_\~\#\'\%]*)/", ' <a href="$1" >$1</a>', $s);
1773 * Replaces text emoticons with graphical images
1775 * @Parameter: string $s
1780 if(! function_exists('smilies')) {
1781 function smilies($s) {
1785 array( ':-)', ';-)', ':-(', ':(', ':-P', ':-"', ':-x', ':-X', ':-D', '8-|', '8-O'),
1787 '<img src="' . $a->get_baseurl() . '/images/smiley-smile.gif" alt=":-)" />',
1788 '<img src="' . $a->get_baseurl() . '/images/smiley-wink.gif" alt=";-)" />',
1789 '<img src="' . $a->get_baseurl() . '/images/smiley-frown.gif" alt=":-(" />',
1790 '<img src="' . $a->get_baseurl() . '/images/smiley-frown.gif" alt=":(" />',
1791 '<img src="' . $a->get_baseurl() . '/images/smiley-tongue-out.gif" alt=":-P" />',
1792 '<img src="' . $a->get_baseurl() . '/images/smiley-kiss.gif" alt=":-\"" />',
1793 '<img src="' . $a->get_baseurl() . '/images/smiley-kiss.gif" alt=":-x" />',
1794 '<img src="' . $a->get_baseurl() . '/images/smiley-kiss.gif" alt=":-X" />',
1795 '<img src="' . $a->get_baseurl() . '/images/smiley-laughing.gif" alt=":-D" />',
1796 '<img src="' . $a->get_baseurl() . '/images/smiley-surprised.gif" alt="8-|" />',
1797 '<img src="' . $a->get_baseurl() . '/images/smiley-surprised.gif" alt="8-O" />'
1804 * Function : profile_load
1806 * @parameter string $nickname
1807 * @parameter int $profile
1809 * Summary: Loads a profile into the page sidebar.
1810 * The function requires a writeable copy of the main App structure, and the nickname
1811 * of a registered local account.
1813 * If the viewer is an authenticated remote viewer, the profile displayed is the
1814 * one that has been configured for his/her viewing in the Contact manager.
1815 * Passing a non-zero profile ID can also allow a preview of a selected profile
1818 * Profile information is placed in the App structure for later retrieval.
1819 * Honours the owner's chosen theme for display.
1823 if(! function_exists('profile_load')) {
1824 function profile_load(&$a, $nickname, $profile = 0) {
1826 $r = q("SELECT `profile-id` FROM `contact` WHERE `id` = %d LIMIT 1",
1827 intval($_SESSION['visitor_id']));
1829 $profile = $r[0]['profile-id'];
1835 $profile_int = intval($profile);
1836 $r = q("SELECT `profile`.`uid` AS `profile_uid`, `profile`.* , `user`.* FROM `profile`
1837 LEFT JOIN `user` ON `profile`.`uid` = `user`.`uid`
1838 WHERE `user`.`nickname` = '%s' AND `profile`.`id` = %d LIMIT 1",
1840 intval($profile_int)
1844 $r = q("SELECT `profile`.`uid` AS `profile_uid`, `profile`.* , `user`.* FROM `profile`
1845 LEFT JOIN `user` ON `profile`.`uid` = `user`.`uid`
1846 WHERE `user`.`nickname` = '%s' AND `profile`.`is-default` = 1 LIMIT 1",
1851 if(($r === false) || (! count($r))) {
1852 notice( t('No profile') . EOL );
1857 $a->profile = $r[0];
1860 $a->page['title'] = $a->profile['name'];
1861 $_SESSION['theme'] = $a->profile['theme'];
1863 if(! (x($a->page,'aside')))
1864 $a->page['aside'] = '';
1866 $a->page['aside'] .= profile_sidebar($a->profile);
1867 $a->page['aside'] .= contact_block();
1875 * Function: profile_sidebar
1877 * Formats a profile for display in the sidebar.
1878 * It is very difficult to templatise the HTML completely
1879 * because of all the conditional logic.
1881 * @parameter: array $profile
1883 * Returns HTML string stuitable for sidebar inclusion
1884 * Exceptions: Returns empty string if passed $profile is wrong type or not populated
1889 if(! function_exists('profile_sidebar')) {
1890 function profile_sidebar($profile) {
1896 if((! is_array($profile)) && (! count($profile)))
1899 $fullname = '<div class="fn">' . $profile['name'] . '</div>';
1903 $photo = '<div id="profile=photo-wrapper"><img class="photo" src="' . $profile['photo'] . '" alt="' . $profile['name'] . '" /></div>';
1905 $connect = (($profile['uid'] != local_user()) ? '<li><a id="dfrn-request-link" href="dfrn_request/' . $profile['nickname'] . '">' . t('Connect') . '</a></li>' : '');
1907 if((x($profile,'address') == 1)
1908 || (x($profile,'locality') == 1)
1909 || (x($profile,'region') == 1)
1910 || (x($profile,'postal-code') == 1)
1911 || (x($profile,'country-name') == 1))
1915 $location .= '<div class="location"><span class="location-label">' . t('Location:') . '</span> <div class="adr">';
1916 $location .= ((x($profile,'address') == 1) ? '<div class="street-address">' . $profile['address'] . '</div>' : '');
1917 $location .= (((x($profile,'locality') == 1) || (x($profile,'region') == 1) || (x($profile,'postal-code') == 1))
1918 ? '<span class="city-state-zip"><span class="locality">' . $profile['locality'] . '</span>'
1919 . ((x($profile['locality']) == 1) ? t(', ') : '')
1920 . '<span class="region">' . $profile['region'] . '</span>'
1921 . ' <span class="postal-code">' . $profile['postal-code'] . '</span></span>' : '');
1922 $location .= ((x($profile,'country-name') == 1) ? ' <span class="country-name">' . $profile['country-name'] . '</span>' : '');
1923 $location .= '</div></div><div class="profile-clear"></div>';
1927 $gender = ((x($profile,'gender') == 1) ? '<div class="mf"><span class="gender-label">' . t('Gender:') . '</span> <span class="x-gender">' . $profile['gender'] . '</span></div><div class="profile-clear"></div>' : '');
1929 $pubkey = ((x($profile,'pubkey') == 1) ? '<div class="key" style="display:none;">' . $profile['pubkey'] . '</div>' : '');
1931 $marital = ((x($profile,'marital') == 1) ? '<div class="marital"><span class="marital-label"><span class="heart">♥</span> ' . t('Status:') . ' </span><span class="marital-text">' . $profile['marital'] . '</span></div></div><div class="profile-clear"></div>' : '');
1933 $homepage = ((x($profile,'homepage') == 1) ? '<div class="homepage"><span class="homepage-label">' . t('Homepage:') . ' </span><span class="homepage-url">' . linkify($profile['homepage']) . '</span></div></div><div class="profile-clear"></div>' : '');
1935 $tpl = load_view_file('view/profile_vcard.tpl');
1937 $o .= replace_macros($tpl, array(
1938 '$fullname' => $fullname,
1941 '$connect' => $connect,
1942 '$location' => $location,
1943 '$gender' => $gender,
1944 '$pubkey' => $pubkey,
1945 '$marital' => $marital,
1946 '$homepage' => $homepage
1953 if(! function_exists('register_hook')) {
1954 function register_hook($hook,$file,$function) {
1956 $r = q("INSERT INTO `hook` (`hook`, `file`, `function`) VALUES ( '%s', '%s', '%s' ) ",
1964 if(! function_exists('unregister_hook')) {
1965 function unregister_hook($hook,$file,$function) {
1967 $r = q("DELETE FROM `hook` WHERE `hook` = '%s' AND `file` = '%s' AND `function` = '%s' LIMIT 1",
1976 if(! function_exists('load_hooks')) {
1977 function load_hooks() {
1979 $r = q("SELECT * FROM `hook` WHERE 1");
1981 foreach($r as $rr) {
1982 $a->hooks[] = array($rr['hook'], $rr['file'], $rr['function']);
1988 if(! function_exists('call_hooks')) {
1989 function call_hooks($name, $data = null) {
1992 if(count($a->hooks)) {
1993 foreach($a->hooks as $hook) {
1994 if($hook[0] === $name) {
1995 @require_once($hook[1]);
1996 if(function_exists($hook[2])) {