3 // This is our template processor.
4 // $s is the string requiring macro substitution.
5 // $r is an array of key value pairs (search => replace)
6 // returns substituted string.
7 // WARNING: this is pretty basic, and doesn't properly handle search strings that are substrings of each other.
8 // For instance if 'test' => "foo" and 'testing' => "bar", testing could become either bar or fooing,
9 // depending on the order in which they were declared in the array.
11 require_once("include/template_processor.php");
13 if(! function_exists('replace_macros')) {
14 function replace_macros($s,$r) {
17 return $t->replace($s,$r);
22 // random string, there are 86 characters max in text mode, 128 for hex
25 define('RANDOM_STRING_HEX', 0x00 );
26 define('RANDOM_STRING_TEXT', 0x01 );
28 if(! function_exists('random_string')) {
29 function random_string($size = 64,$type = RANDOM_STRING_HEX) {
30 // generate a bit of entropy and run it through the whirlpool
31 $s = hash('whirlpool', (string) rand() . uniqid(rand(),true) . (string) rand(),(($type == RANDOM_STRING_TEXT) ? true : false));
32 $s = (($type == RANDOM_STRING_TEXT) ? str_replace("\n","",base64url_encode($s,true)) : $s);
33 return(substr($s,0,$size));
37 * This is our primary input filter.
39 * The high bit hack only involved some old IE browser, forget which (IE5/Mac?)
40 * that had an XSS attack vector due to stripping the high-bit on an 8-bit character
41 * after cleansing, and angle chars with the high bit set could get through as markup.
43 * This is now disabled because it was interfering with some legitimate unicode sequences
44 * and hopefully there aren't a lot of those browsers left.
46 * Use this on any text input where angle chars are not valid or permitted
47 * They will be replaced with safer brackets. This may be filtered further
48 * if these are not allowed either.
52 if(! function_exists('notags')) {
53 function notags($string) {
55 return(str_replace(array("<",">"), array('[',']'), $string));
57 // High-bit filter no longer used
58 // return(str_replace(array("<",">","\xBA","\xBC","\xBE"), array('[',']','','',''), $string));
61 // use this on "body" or "content" input where angle chars shouldn't be removed,
62 // and allow them to be safely displayed.
64 if(! function_exists('escape_tags')) {
65 function escape_tags($string) {
67 return(htmlspecialchars($string));
71 // generate a string that's random, but usually pronounceable.
72 // used to generate initial passwords
74 if(! function_exists('autoname')) {
75 function autoname($len) {
77 $vowels = array('a','a','ai','au','e','e','e','ee','ea','i','ie','o','ou','u');
96 's','sc','sh','sm','sp','st',
104 $midcons = array('ck','ct','gn','ld','lf','lm','lt','mb','mm', 'mn','mp',
105 'nd','ng','nk','nt','rn','rp','rt');
107 $noend = array('bl', 'br', 'cl','cr','dr','fl','fr','gl','gr',
108 'kh', 'kl','kr','mn','pl','pr','rh','tr','qu','wh');
110 $start = mt_rand(0,2);
118 for ($x = 0; $x < $len; $x ++) {
119 $r = mt_rand(0,count($table) - 1);
122 if($table == $vowels)
123 $table = array_merge($cons,$midcons);
129 $word = substr($word,0,$len);
131 foreach($noend as $noe) {
132 if((strlen($word) > 2) && (substr($word,-2) == $noe)) {
133 $word = substr($word,0,-1);
137 if(substr($word,-1) == 'q')
138 $word = substr($word,0,-1);
143 // escape text ($str) for XML transport
144 // returns escaped text.
146 if(! function_exists('xmlify')) {
147 function xmlify($str) {
150 for($x = 0; $x < mb_strlen($str); $x ++) {
180 $buffer = trim($buffer);
185 // pass xml escaped text ($s), returns unescaped text
187 if(! function_exists('unxmlify')) {
188 function unxmlify($s) {
189 $ret = str_replace('&','&', $s);
190 $ret = str_replace(array('<','>','"','''),array('<','>','"',"'"),$ret);
194 // convenience wrapper, reverse the operation "bin2hex"
196 if(! function_exists('hex2bin')) {
197 function hex2bin($s) {
198 if(! (is_string($s) && strlen($s)))
201 if(! ctype_xdigit($s)) {
202 logger('hex2bin: illegal input: ' . print_r(debug_backtrace(), true));
206 return(pack("H*",$s));
209 // Automatic pagination.
210 // To use, get the count of total items.
211 // Then call $a->set_pager_total($number_items);
212 // Optionally call $a->set_pager_itemspage($n) to the number of items to display on each page
213 // Then call paginate($a) after the end of the display loop to insert the pager block on the page
214 // (assuming there are enough items to paginate).
215 // When using with SQL, the setting LIMIT %d, %d => $a->pager['start'],$a->pager['itemspage']
216 // will limit the results to the correct items for the current page.
217 // The actual page handling is then accomplished at the application layer.
219 if(! function_exists('paginate')) {
220 function paginate(&$a) {
222 $stripped = preg_replace('/(&page=[0-9]*)/','',$a->query_string);
223 $stripped = str_replace('q=','',$stripped);
224 $stripped = trim($stripped,'/');
225 $pagenum = $a->pager['page'];
226 $url = $a->get_baseurl() . '/' . $stripped;
229 if($a->pager['total'] > $a->pager['itemspage']) {
230 $o .= '<div class="pager">';
231 if($a->pager['page'] != 1)
232 $o .= '<span class="pager_prev">'."<a href=\"$url".'&page='.($a->pager['page'] - 1).'">' . t('prev') . '</a></span> ';
234 $o .= "<span class=\"pager_first\"><a href=\"$url"."&page=1\">" . t('first') . "</a></span> ";
236 $numpages = $a->pager['total'] / $a->pager['itemspage'];
239 $numstop = $numpages;
242 $numstart = (($pagenum > 7) ? ($pagenum - 7) : 1);
243 $numstop = (($pagenum > ($numpages - 7)) ? $numpages : ($numstart + 14));
246 for($i = $numstart; $i <= $numstop; $i++){
247 if($i == $a->pager['page'])
248 $o .= '<span class="pager_current">'.(($i < 10) ? ' '.$i : $i);
250 $o .= "<span class=\"pager_n\"><a href=\"$url"."&page=$i\">".(($i < 10) ? ' '.$i : $i)."</a>";
254 if(($a->pager['total'] % $a->pager['itemspage']) != 0) {
255 if($i == $a->pager['page'])
256 $o .= '<span class="pager_current">'.(($i < 10) ? ' '.$i : $i);
258 $o .= "<span class=\"pager_n\"><a href=\"$url"."&page=$i\">".(($i < 10) ? ' '.$i : $i)."</a>";
262 $lastpage = (($numpages > intval($numpages)) ? intval($numpages)+1 : $numpages);
263 $o .= "<span class=\"pager_last\"><a href=\"$url"."&page=$lastpage\">" . t('last') . "</a></span> ";
265 if(($a->pager['total'] - ($a->pager['itemspage'] * $a->pager['page'])) > 0)
266 $o .= '<span class="pager_next">'."<a href=\"$url"."&page=".($a->pager['page'] + 1).'">' . t('next') . '</a></span>';
267 $o .= '</div>'."\r\n";
272 // Turn user/group ACLs stored as angle bracketed text into arrays
274 if(! function_exists('expand_acl')) {
275 function expand_acl($s) {
276 // turn string array of angle-bracketed elements into numeric array
277 // e.g. "<1><2><3>" => array(1,2,3);
281 $t = str_replace('<','',$s);
282 $a = explode('>',$t);
285 $ret[] = intval($aa);
291 // Used to wrap ACL elements in angle brackets for storage
293 if(! function_exists('sanitise_acl')) {
294 function sanitise_acl(&$item) {
296 $item = '<' . intval(notags(trim($item))) . '>';
302 // Convert an ACL array to a storable string
304 if(! function_exists('perms2str')) {
305 function perms2str($p) {
309 array_walk($tmp,'sanitise_acl');
310 $ret = implode('',$tmp);
315 // generate a guaranteed unique (for this domain) item ID for ATOM
316 // safe from birthday paradox
318 if(! function_exists('item_new_uri')) {
319 function item_new_uri($hostname,$uid) {
323 $hash = random_string();
325 $uri = "urn:X-dfrn:" . $hostname . ':' . $uid . ':' . $hash;
327 $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' LIMIT 1",
331 } while($dups == true);
335 // Generate a guaranteed unique photo ID.
336 // safe from birthday paradox
338 if(! function_exists('photo_new_resource')) {
339 function photo_new_resource() {
343 $resource = hash('md5',uniqid(mt_rand(),true));
344 $r = q("SELECT `id` FROM `photo` WHERE `resource-id` = '%s' LIMIT 1",
349 } while($found == true);
354 // wrapper to load a view template, checking for alternate
355 // languages before falling back to the default
357 // obsolete, deprecated.
359 if(! function_exists('load_view_file')) {
360 function load_view_file($s) {
366 if(file_exists("$d/$lang/$b"))
367 return file_get_contents("$d/$lang/$b");
369 $theme = current_theme();
371 if(file_exists("$d/theme/$theme/$b"))
372 return file_get_contents("$d/theme/$theme/$b");
374 return file_get_contents($s);
377 if(! function_exists('get_intltext_template')) {
378 function get_intltext_template($s) {
384 if(file_exists("view/$lang/$s"))
385 return file_get_contents("view/$lang/$s");
386 elseif(file_exists("view/en/$s"))
387 return file_get_contents("view/en/$s");
389 return file_get_contents("view/$s");
392 if(! function_exists('get_markup_template')) {
393 function get_markup_template($s) {
395 $theme = current_theme();
397 if(file_exists("view/theme/$theme/$s"))
398 return file_get_contents("view/theme/$theme/$s");
399 elseif (x($a->theme_info,"extends") && file_exists("view/theme/".$a->theme_info["extends"]."/$s"))
400 return file_get_contents("view/theme/".$a->theme_info["extends"]."/$s");
402 return file_get_contents("view/$s");
410 // for html,xml parsing - let's say you've got
411 // an attribute foobar="class1 class2 class3"
412 // and you want to find out if it contains 'class3'.
413 // you can't use a normal sub string search because you
414 // might match 'notclass3' and a regex to do the job is
415 // possible but a bit complicated.
416 // pass the attribute string as $attr and the attribute you
417 // are looking for as $s - returns true if found, otherwise false
419 if(! function_exists('attribute_contains')) {
420 function attribute_contains($attr,$s) {
421 $a = explode(' ', $attr);
422 if(count($a) && in_array($s,$a))
427 if(! function_exists('logger')) {
428 function logger($msg,$level = 0) {
429 $debugging = get_config('system','debugging');
430 $loglevel = intval(get_config('system','loglevel'));
431 $logfile = get_config('system','logfile');
433 if((! $debugging) || (! $logfile) || ($level > $loglevel))
436 @file_put_contents($logfile, datetime_convert() . ':' . session_id() . ' ' . $msg . "\n", FILE_APPEND);
441 if(! function_exists('activity_match')) {
442 function activity_match($haystack,$needle) {
443 if(($haystack === $needle) || ((basename($needle) === $haystack) && strstr($needle,NAMESPACE_ACTIVITY_SCHEMA)))
449 // Pull out all #hashtags and @person tags from $s;
450 // We also get @person@domain.com - which would make
451 // the regex quite complicated as tags can also
452 // end a sentence. So we'll run through our results
453 // and strip the period from any tags which end with one.
454 // Returns array of tags found, or empty array.
457 if(! function_exists('get_tags')) {
458 function get_tags($s) {
461 // ignore anything in a code block
463 $s = preg_replace('/\[code\](.*?)\[\/code\]/sm','',$s);
465 // Match full names against @tags including the space between first and last
466 // We will look these up afterward to see if they are full names or not recognisable.
468 if(preg_match_all('/(@[^ \x0D\x0A,:?]+ [^ \x0D\x0A@,:?]+)([ \x0D\x0A@,:?]|$)/',$s,$match)) {
469 foreach($match[1] as $mtch) {
470 if(strstr($mtch,"]")) {
471 // we might be inside a bbcode color tag - leave it alone
474 if(substr($mtch,-1,1) === '.')
475 $ret[] = substr($mtch,0,-1);
481 // Otherwise pull out single word tags. These can be @nickname, @first_last
484 if(preg_match_all('/([@#][^ \x0D\x0A,;:?]+)([ \x0D\x0A,;:?]|$)/',$s,$match)) {
485 foreach($match[1] as $mtch) {
486 if(strstr($mtch,"]")) {
487 // we might be inside a bbcode color tag - leave it alone
490 if(substr($mtch,-1,1) === '.')
491 $mtch = substr($mtch,0,-1);
492 // ignore strictly numeric tags like #1
493 if((strpos($mtch,'#') === 0) && ctype_digit(substr($mtch,1)))
495 // try not to catch url fragments
496 if(strpos($s,$mtch) && preg_match('/[a-zA-z0-9\/]/',substr($s,strpos($s,$mtch)-1,1)))
505 // quick and dirty quoted_printable encoding
507 if(! function_exists('qp')) {
509 return str_replace ("%","=",rawurlencode($s));
514 if(! function_exists('get_mentions')) {
515 function get_mentions($item) {
517 if(! strlen($item['tag']))
520 $arr = explode(',',$item['tag']);
521 foreach($arr as $x) {
523 if(preg_match('/@\[url=([^\]]*)\]/',$x,$matches)) {
524 $o .= "\t\t" . '<link rel="mentioned" href="' . $matches[1] . '" />' . "\r\n";
525 $o .= "\t\t" . '<link rel="ostatus:attention" href="' . $matches[1] . '" />' . "\r\n";
531 if(! function_exists('contact_block')) {
532 function contact_block() {
536 $shown = get_pconfig($a->profile['uid'],'system','display_friend_count');
540 if((! is_array($a->profile)) || ($a->profile['hide-friends']))
542 $r = q("SELECT COUNT(*) AS `total` FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 and `pending` = 0 AND `hidden` = 0",
543 intval($a->profile['uid'])
546 $total = intval($r[0]['total']);
549 $contacts = t('No contacts');
553 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 and `pending` = 0 AND `hidden` = 0 ORDER BY RAND() LIMIT %d",
554 intval($a->profile['uid']),
558 $contacts = sprintf( tt('%d Contact','%d Contacts', $total),$total);
561 $micropro[] = micropro($rr,true,'mpfriend');
566 $tpl = get_markup_template('contact_block.tpl');
567 $o = replace_macros($tpl, array(
568 '$contacts' => $contacts,
569 '$nickname' => $a->profile['nickname'],
570 '$viewcontacts' => t('View Contacts'),
571 '$micropro' => $micropro,
574 $arr = array('contacts' => $r, 'output' => $o);
576 call_hooks('contact_block_end', $arr);
581 if(! function_exists('micropro')) {
582 function micropro($contact, $redirect = false, $class = '', $textmode = false) {
585 $class = ' ' . $class;
587 $url = $contact['url'];
593 $redirect_url = $a->get_baseurl() . '/redir/' . $contact['id'];
594 if(local_user() && ($contact['uid'] == local_user()) && ($contact['network'] === 'dfrn')) {
596 $url = $redirect_url;
597 $sparkle = ' sparkle';
600 $click = ((x($contact,'click')) ? ' onclick="' . $contact['click'] . '" ' : '');
604 return '<div class="contact-block-textdiv' . $class . '"><a class="contact-block-link' . $class . $sparkle
605 . (($click) ? ' fakelink' : '') . '" '
606 . (($redir) ? ' target="redir" ' : '')
607 . (($url) ? ' href="' . $url . '"' : '') . $click
608 . '" title="' . $contact['name'] . ' [' . $contact['url'] . ']" alt="' . $contact['name']
609 . '" >'. $contact['name'] . '</a></div>' . "\r\n";
612 return '<div class="contact-block-div' . $class . '"><a class="contact-block-link' . $class . $sparkle
613 . (($click) ? ' fakelink' : '') . '" '
614 . (($redir) ? ' target="redir" ' : '')
615 . (($url) ? ' href="' . $url . '"' : '') . $click . ' ><img class="contact-block-img' . $class . $sparkle . '" src="'
616 . $contact['micro'] . '" title="' . $contact['name'] . ' [' . $contact['url'] . ']" alt="' . $contact['name']
617 . '" /></a></div>' . "\r\n";
623 if(! function_exists('search')) {
624 function search($s,$id='search-box',$url='/search',$save = false) {
626 $o = '<div id="' . $id . '">';
627 $o .= '<form action="' . $a->get_baseurl() . $url . '" method="get" >';
628 $o .= '<input type="text" name="search" id="search-text" value="' . $s .'" />';
629 $o .= '<input type="submit" name="submit" id="search-submit" value="' . t('Search') . '" />';
631 $o .= '<input type="submit" name="save" id="search-save" value="' . t('Save') . '" />';
632 $o .= '</form></div>';
636 if(! function_exists('valid_email')) {
637 function valid_email($x){
638 if(preg_match('/^[_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)+$/',$x))
648 * Replace naked text hyperlink with HTML formatted hyperlink
652 if(! function_exists('linkify')) {
653 function linkify($s) {
654 $s = preg_replace("/(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\'\%\$\!\+]*)/", ' <a href="$1" target="external-link">$1</a>', $s);
655 $s = preg_replace("/\<(.*?)(src|href)=(.*?)\&\;(.*?)\>/ism",'<$1$2=$3&$4>',$s);
665 * Replaces text emoticons with graphical images
667 * @Parameter: string $s
672 if(! function_exists('smilies')) {
673 function smilies($s) {
677 array( '<3', '</3', '<\\3', ':-)', ':)', ';-)', ':-(', ':(', ':-P', ':P', ':-"', ':-x', ':-X', ':-D', '8-|', '8-O', '\\o/',
678 '~friendika', '~friendica', 'Diaspora*' ),
680 '<img src="' . $a->get_baseurl() . '/images/smiley-heart.gif" alt="<3" />',
681 '<img src="' . $a->get_baseurl() . '/images/smiley-brokenheart.gif" alt="</3" />',
682 '<img src="' . $a->get_baseurl() . '/images/smiley-brokenheart.gif" alt="<\\3" />',
683 '<img src="' . $a->get_baseurl() . '/images/smiley-smile.gif" alt=":-)" />',
684 '<img src="' . $a->get_baseurl() . '/images/smiley-smile.gif" alt=":)" />',
685 '<img src="' . $a->get_baseurl() . '/images/smiley-wink.gif" alt=";-)" />',
686 '<img src="' . $a->get_baseurl() . '/images/smiley-frown.gif" alt=":-(" />',
687 '<img src="' . $a->get_baseurl() . '/images/smiley-frown.gif" alt=":(" />',
688 '<img src="' . $a->get_baseurl() . '/images/smiley-tongue-out.gif" alt=":-P" />',
689 '<img src="' . $a->get_baseurl() . '/images/smiley-tongue-out.gif" alt=":P" />',
690 '<img src="' . $a->get_baseurl() . '/images/smiley-kiss.gif" alt=":-\"" />',
691 '<img src="' . $a->get_baseurl() . '/images/smiley-kiss.gif" alt=":-x" />',
692 '<img src="' . $a->get_baseurl() . '/images/smiley-kiss.gif" alt=":-X" />',
693 '<img src="' . $a->get_baseurl() . '/images/smiley-laughing.gif" alt=":-D" />',
694 '<img src="' . $a->get_baseurl() . '/images/smiley-surprised.gif" alt="8-|" />',
695 '<img src="' . $a->get_baseurl() . '/images/smiley-surprised.gif" alt="8-O" />',
696 '<img src="' . $a->get_baseurl() . '/images/smiley-thumbsup.gif" alt="\\o/" />',
697 '<a href="http://project.friendika.com">~friendika <img src="' . $a->get_baseurl() . '/images/friendika-16.png" alt="~friendika" /></a>',
698 '<a href="http://friendica.com">~friendica <img src="' . $a->get_baseurl() . '/images/friendika-16.png" alt="~friendica" /></a>',
699 '<a href="http://diasporafoundation.org">Diaspora<img src="' . $a->get_baseurl() . '/images/diaspora.png" alt="Diaspora*" /></a>',
703 call_hooks('smilie', $s);
710 if(! function_exists('day_translate')) {
711 function day_translate($s) {
712 $ret = str_replace(array('Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'),
713 array( t('Monday'), t('Tuesday'), t('Wednesday'), t('Thursday'), t('Friday'), t('Saturday'), t('Sunday')),
716 $ret = str_replace(array('January','February','March','April','May','June','July','August','September','October','November','December'),
717 array( t('January'), t('February'), t('March'), t('April'), t('May'), t('June'), t('July'), t('August'), t('September'), t('October'), t('November'), t('December')),
724 if(! function_exists('normalise_link')) {
725 function normalise_link($url) {
726 $ret = str_replace(array('https:','//www.'), array('http:','//'), $url);
727 return(rtrim($ret,'/'));
732 * Compare two URLs to see if they are the same, but ignore
733 * slight but hopefully insignificant differences such as if one
734 * is https and the other isn't, or if one is www.something and
735 * the other isn't - and also ignore case differences.
737 * Return true if the URLs match, otherwise false.
741 if(! function_exists('link_compare')) {
742 function link_compare($a,$b) {
743 if(strcasecmp(normalise_link($a),normalise_link($b)) === 0)
748 // Given an item array, convert the body element from bbcode to html and add smilie icons.
749 // If attach is true, also add icons for item attachments
752 if(! function_exists('prepare_body')) {
753 function prepare_body($item,$attach = false) {
755 call_hooks('prepare_body_init', $item);
757 $s = prepare_text($item['body']);
759 $prep_arr = array('item' => $item, 'html' => $s);
760 call_hooks('prepare_body', $prep_arr);
761 $s = $prep_arr['html'];
766 $arr = explode(',',$item['attach']);
768 $s .= '<div class="body-attach">';
769 foreach($arr as $r) {
772 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"\[\/attach\]|',$r,$matches);
774 $icontype = strtolower(substr($matches[3],0,strpos($matches[3],'/')));
780 $icon = '<div class="attachtype type-' . $icontype . '"></div>';
783 $icon = '<div class="attachtype type-unkn"></div>';
786 $title = ((strlen(trim($matches[4]))) ? escape_tags(trim($matches[4])) : escape_tags($matches[1]));
787 $title .= ' ' . $matches[2] . ' ' . t('bytes');
789 $s .= '<a href="' . strip_tags($matches[1]) . '" title="' . $title . '" class="attachlink" target="external-link" >' . $icon . '</a>';
792 $s .= '<div class="clear"></div></div>';
796 $prep_arr = array('item' => $item, 'html' => $s);
797 call_hooks('prepare_body_final', $prep_arr);
798 return $prep_arr['html'];
802 // Given a text string, convert from bbcode to html and add smilie icons.
804 if(! function_exists('prepare_text')) {
805 function prepare_text($text) {
807 require_once('include/bbcode.php');
809 $s = smilies(bbcode($text));
816 * return atom link elements for all of our hubs
819 if(! function_exists('feed_hublinks')) {
820 function feed_hublinks() {
822 $hub = get_config('system','huburl');
826 $hubs = explode(',', $hub);
828 foreach($hubs as $h) {
832 $hubxml .= '<link rel="hub" href="' . xmlify($h) . '" />' . "\n" ;
839 /* return atom link elements for salmon endpoints */
841 if(! function_exists('feed_salmonlinks')) {
842 function feed_salmonlinks($nick) {
846 $salmon = '<link rel="salmon" href="' . xmlify($a->get_baseurl() . '/salmon/' . $nick) . '" />' . "\n" ;
848 // old style links that status.net still needed as of 12/2010
850 $salmon .= ' <link rel="http://salmon-protocol.org/ns/salmon-replies" href="' . xmlify($a->get_baseurl() . '/salmon/' . $nick) . '" />' . "\n" ;
851 $salmon .= ' <link rel="http://salmon-protocol.org/ns/salmon-mention" href="' . xmlify($a->get_baseurl() . '/salmon/' . $nick) . '" />' . "\n" ;
855 if(! function_exists('get_plink')) {
856 function get_plink($item) {
858 if (x($item,'plink') && (! $item['private'])){
860 'href' => $item['plink'],
861 'title' => t('link to source'),
868 if(! function_exists('unamp')) {
870 return str_replace('&', '&', $s);
876 if(! function_exists('lang_selector')) {
877 function lang_selector() {
879 $o = '<div id="lang-select-icon" class="icon language" title="' . t('Select an alternate language') . '" onclick="openClose(\'language-selector\');" ></div>';
880 $o .= '<div id="language-selector" style="display: none;" >';
881 $o .= '<form action="#" method="post" ><select name="system_language" onchange="this.form.submit();" >';
882 $langs = glob('view/*/strings.php');
883 if(is_array($langs) && count($langs)) {
885 if(! in_array('view/en/strings.php',$langs))
886 $langs[] = 'view/en/';
888 foreach($langs as $l) {
890 $default_selected = ((! x($_SESSION,'language')) ? ' selected="selected" ' : '');
891 $o .= '<option value="" ' . $default_selected . '>' . t('default') . '</option>';
895 $ll = substr($ll,0,strrpos($ll,'/'));
896 $selected = (($ll === $lang && (x($_SESSION['language']))) ? ' selected="selected" ' : '');
897 $o .= '<option value="' . $ll . '"' . $selected . '>' . $ll . '</option>';
900 $o .= '</select></form></div>';
905 if(! function_exists('return_bytes')) {
906 function return_bytes ($size_str) {
907 switch (substr ($size_str, -1))
909 case 'M': case 'm': return (int)$size_str * 1048576;
910 case 'K': case 'k': return (int)$size_str * 1024;
911 case 'G': case 'g': return (int)$size_str * 1073741824;
912 default: return $size_str;
916 function generate_user_guid() {
919 $guid = random_string(16);
920 $x = q("SELECT `uid` FROM `user` WHERE `guid` = '%s' LIMIT 1",
925 } while ($found == true );
931 function base64url_encode($s, $strip_padding = false) {
933 $s = strtr(base64_encode($s),'+/','-_');
936 $s = str_replace('=','',$s);
941 function base64url_decode($s) {
944 * // Placeholder for new rev of salmon which strips base64 padding.
945 * // PHP base64_decode handles the un-padded input without requiring this step
946 * // Uncomment if you find you need it.
949 * if(! strpos($s,'=')) {
959 return base64_decode(strtr($s,'-_','+/'));
963 if (!function_exists('str_getcsv')) {
964 function str_getcsv($input, $delimiter = ',', $enclosure = '"', $escape = '\\', $eol = '\n') {
965 if (is_string($input) && !empty($input)) {
967 $tmp = preg_split("/".$eol."/",$input);
968 if (is_array($tmp) && !empty($tmp)) {
969 while (list($line_num, $line) = each($tmp)) {
970 if (preg_match("/".$escape.$enclosure."/",$line)) {
971 while ($strlen = strlen($line)) {
972 $pos_delimiter = strpos($line,$delimiter);
973 $pos_enclosure_start = strpos($line,$enclosure);
975 is_int($pos_delimiter) && is_int($pos_enclosure_start)
976 && ($pos_enclosure_start < $pos_delimiter)
978 $enclosed_str = substr($line,1);
979 $pos_enclosure_end = strpos($enclosed_str,$enclosure);
980 $enclosed_str = substr($enclosed_str,0,$pos_enclosure_end);
981 $output[$line_num][] = $enclosed_str;
982 $offset = $pos_enclosure_end+3;
984 if (empty($pos_delimiter) && empty($pos_enclosure_start)) {
985 $output[$line_num][] = substr($line,0);
986 $offset = strlen($line);
988 $output[$line_num][] = substr($line,0,$pos_delimiter);
990 !empty($pos_enclosure_start)
991 && ($pos_enclosure_start < $pos_delimiter)
993 ?$pos_enclosure_start
997 $line = substr($line,$offset);
1000 $line = preg_split("/".$delimiter."/",$line);
1003 * Validating against pesky extra line breaks creating false rows.
1005 if (is_array($line) && !empty($line[0])) {
1006 $output[$line_num] = $line;
1020 function cleardiv() {
1021 return '<div class="clear"></div>';
1025 function bb_translate_video($s) {
1028 $r = preg_match_all("/\[video\](.*?)\[\/video\]/ism",$s,$matches,PREG_SET_ORDER);
1030 foreach($matches as $mtch) {
1031 if((stristr($mtch[1],'youtube')) || (stristr($mtch[1],'youtu.be')))
1032 $s = str_replace($mtch[0],'[youtube]' . $mtch[1] . '[/youtube]',$s);
1033 elseif(stristr($mtch[1],'vimeo'))
1034 $s = str_replace($mtch[0],'[vimeo]' . $mtch[1] . '[/vimeo]',$s);
1040 function html2bb_video($s) {
1042 $s = preg_replace('#<object[^>]+>(.*?)https+://www.youtube.com/((?:v|cp)/[A-Za-z0-9\-_=]+)(.*?)</object>#ism',
1043 '[youtube]$2[/youtube]', $s);
1045 $s = preg_replace('#<iframe[^>](.*?)https+://www.youtube.com/embed/([A-Za-z0-9\-_=]+)(.*?)</iframe>#ism',
1046 '[youtube]$2[/youtube]', $s);
1048 $s = preg_replace('#<iframe[^>](.*?)https+://player.vimeo.com/video/([0-9]+)(.*?)</iframe>#ism',
1049 '[vimeo]$2[/vimeo]', $s);
1055 * apply xmlify() to all values of array $val, recursively
1057 function array_xmlify($val){
1058 if (is_bool($val)) return $val?"true":"false";
1059 if (is_array($val)) return array_map('array_xmlify', $val);
1060 return xmlify((string) $val);