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) {
18 $r = $t->replace($s,$r);
19 //$tt = microtime() - $ts;
22 //$a->page['debug'] .= "$tt <br>\n";
28 // random string, there are 86 characters max in text mode, 128 for hex
31 define('RANDOM_STRING_HEX', 0x00 );
32 define('RANDOM_STRING_TEXT', 0x01 );
34 if(! function_exists('random_string')) {
35 function random_string($size = 64,$type = RANDOM_STRING_HEX) {
36 // generate a bit of entropy and run it through the whirlpool
37 $s = hash('whirlpool', (string) rand() . uniqid(rand(),true) . (string) rand(),(($type == RANDOM_STRING_TEXT) ? true : false));
38 $s = (($type == RANDOM_STRING_TEXT) ? str_replace("\n","",base64url_encode($s,true)) : $s);
39 return(substr($s,0,$size));
43 * This is our primary input filter.
45 * The high bit hack only involved some old IE browser, forget which (IE5/Mac?)
46 * that had an XSS attack vector due to stripping the high-bit on an 8-bit character
47 * after cleansing, and angle chars with the high bit set could get through as markup.
49 * This is now disabled because it was interfering with some legitimate unicode sequences
50 * and hopefully there aren't a lot of those browsers left.
52 * Use this on any text input where angle chars are not valid or permitted
53 * They will be replaced with safer brackets. This may be filtered further
54 * if these are not allowed either.
58 if(! function_exists('notags')) {
59 function notags($string) {
61 return(str_replace(array("<",">"), array('[',']'), $string));
63 // High-bit filter no longer used
64 // return(str_replace(array("<",">","\xBA","\xBC","\xBE"), array('[',']','','',''), $string));
67 // use this on "body" or "content" input where angle chars shouldn't be removed,
68 // and allow them to be safely displayed.
70 if(! function_exists('escape_tags')) {
71 function escape_tags($string) {
73 return(htmlspecialchars($string));
77 // generate a string that's random, but usually pronounceable.
78 // used to generate initial passwords
80 if(! function_exists('autoname')) {
81 function autoname($len) {
83 $vowels = array('a','a','ai','au','e','e','e','ee','ea','i','ie','o','ou','u');
102 's','sc','sh','sm','sp','st',
110 $midcons = array('ck','ct','gn','ld','lf','lm','lt','mb','mm', 'mn','mp',
111 'nd','ng','nk','nt','rn','rp','rt');
113 $noend = array('bl', 'br', 'cl','cr','dr','fl','fr','gl','gr',
114 'kh', 'kl','kr','mn','pl','pr','rh','tr','qu','wh');
116 $start = mt_rand(0,2);
124 for ($x = 0; $x < $len; $x ++) {
125 $r = mt_rand(0,count($table) - 1);
128 if($table == $vowels)
129 $table = array_merge($cons,$midcons);
135 $word = substr($word,0,$len);
137 foreach($noend as $noe) {
138 if((strlen($word) > 2) && (substr($word,-2) == $noe)) {
139 $word = substr($word,0,-1);
143 if(substr($word,-1) == 'q')
144 $word = substr($word,0,-1);
149 // escape text ($str) for XML transport
150 // returns escaped text.
152 if(! function_exists('xmlify')) {
153 function xmlify($str) {
156 for($x = 0; $x < mb_strlen($str); $x ++) {
186 $buffer = trim($buffer);
191 // pass xml escaped text ($s), returns unescaped text
193 if(! function_exists('unxmlify')) {
194 function unxmlify($s) {
195 $ret = str_replace('&','&', $s);
196 $ret = str_replace(array('<','>','"','''),array('<','>','"',"'"),$ret);
200 // convenience wrapper, reverse the operation "bin2hex"
202 if(! function_exists('hex2bin')) {
203 function hex2bin($s) {
204 if(! (is_string($s) && strlen($s)))
207 if(! ctype_xdigit($s)) {
208 logger('hex2bin: illegal input: ' . print_r(debug_backtrace(), true));
212 return(pack("H*",$s));
215 // Automatic pagination.
216 // To use, get the count of total items.
217 // Then call $a->set_pager_total($number_items);
218 // Optionally call $a->set_pager_itemspage($n) to the number of items to display on each page
219 // Then call paginate($a) after the end of the display loop to insert the pager block on the page
220 // (assuming there are enough items to paginate).
221 // When using with SQL, the setting LIMIT %d, %d => $a->pager['start'],$a->pager['itemspage']
222 // will limit the results to the correct items for the current page.
223 // The actual page handling is then accomplished at the application layer.
225 if(! function_exists('paginate')) {
226 function paginate(&$a) {
228 $stripped = preg_replace('/(&page=[0-9]*)/','',$a->query_string);
229 $stripped = str_replace('q=','',$stripped);
230 $stripped = trim($stripped,'/');
231 $pagenum = $a->pager['page'];
232 $url = $a->get_baseurl() . '/' . $stripped;
235 if($a->pager['total'] > $a->pager['itemspage']) {
236 $o .= '<div class="pager">';
237 if($a->pager['page'] != 1)
238 $o .= '<span class="pager_prev">'."<a href=\"$url".'&page='.($a->pager['page'] - 1).'">' . t('prev') . '</a></span> ';
240 $o .= "<span class=\"pager_first\"><a href=\"$url"."&page=1\">" . t('first') . "</a></span> ";
242 $numpages = $a->pager['total'] / $a->pager['itemspage'];
245 $numstop = $numpages;
248 $numstart = (($pagenum > 7) ? ($pagenum - 7) : 1);
249 $numstop = (($pagenum > ($numpages - 7)) ? $numpages : ($numstart + 14));
252 for($i = $numstart; $i <= $numstop; $i++){
253 if($i == $a->pager['page'])
254 $o .= '<span class="pager_current">'.(($i < 10) ? ' '.$i : $i);
256 $o .= "<span class=\"pager_n\"><a href=\"$url"."&page=$i\">".(($i < 10) ? ' '.$i : $i)."</a>";
260 if(($a->pager['total'] % $a->pager['itemspage']) != 0) {
261 if($i == $a->pager['page'])
262 $o .= '<span class="pager_current">'.(($i < 10) ? ' '.$i : $i);
264 $o .= "<span class=\"pager_n\"><a href=\"$url"."&page=$i\">".(($i < 10) ? ' '.$i : $i)."</a>";
268 $lastpage = (($numpages > intval($numpages)) ? intval($numpages)+1 : $numpages);
269 $o .= "<span class=\"pager_last\"><a href=\"$url"."&page=$lastpage\">" . t('last') . "</a></span> ";
271 if(($a->pager['total'] - ($a->pager['itemspage'] * $a->pager['page'])) > 0)
272 $o .= '<span class="pager_next">'."<a href=\"$url"."&page=".($a->pager['page'] + 1).'">' . t('next') . '</a></span>';
273 $o .= '</div>'."\r\n";
278 // Turn user/group ACLs stored as angle bracketed text into arrays
280 if(! function_exists('expand_acl')) {
281 function expand_acl($s) {
282 // turn string array of angle-bracketed elements into numeric array
283 // e.g. "<1><2><3>" => array(1,2,3);
287 $t = str_replace('<','',$s);
288 $a = explode('>',$t);
291 $ret[] = intval($aa);
297 // Used to wrap ACL elements in angle brackets for storage
299 if(! function_exists('sanitise_acl')) {
300 function sanitise_acl(&$item) {
302 $item = '<' . intval(notags(trim($item))) . '>';
308 // Convert an ACL array to a storable string
310 if(! function_exists('perms2str')) {
311 function perms2str($p) {
315 array_walk($tmp,'sanitise_acl');
316 $ret = implode('',$tmp);
321 // generate a guaranteed unique (for this domain) item ID for ATOM
322 // safe from birthday paradox
324 if(! function_exists('item_new_uri')) {
325 function item_new_uri($hostname,$uid) {
329 $hash = random_string();
331 $uri = "urn:X-dfrn:" . $hostname . ':' . $uid . ':' . $hash;
333 $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' LIMIT 1",
337 } while($dups == true);
341 // Generate a guaranteed unique photo ID.
342 // safe from birthday paradox
344 if(! function_exists('photo_new_resource')) {
345 function photo_new_resource() {
349 $resource = hash('md5',uniqid(mt_rand(),true));
350 $r = q("SELECT `id` FROM `photo` WHERE `resource-id` = '%s' LIMIT 1",
355 } while($found == true);
360 // wrapper to load a view template, checking for alternate
361 // languages before falling back to the default
363 // obsolete, deprecated.
365 if(! function_exists('load_view_file')) {
366 function load_view_file($s) {
372 if(file_exists("$d/$lang/$b"))
373 return file_get_contents("$d/$lang/$b");
375 $theme = current_theme();
377 if(file_exists("$d/theme/$theme/$b"))
378 return file_get_contents("$d/theme/$theme/$b");
380 return file_get_contents($s);
383 if(! function_exists('get_intltext_template')) {
384 function get_intltext_template($s) {
390 if(file_exists("view/$lang/$s"))
391 return file_get_contents("view/$lang/$s");
392 elseif(file_exists("view/en/$s"))
393 return file_get_contents("view/en/$s");
395 return file_get_contents("view/$s");
398 if(! function_exists('get_markup_template')) {
399 function get_markup_template($s) {
401 $theme = current_theme();
403 if(file_exists("view/theme/$theme/$s"))
404 return file_get_contents("view/theme/$theme/$s");
405 elseif (x($a->theme_info,"extends") && file_exists("view/theme/".$a->theme_info["extends"]."/$s"))
406 return file_get_contents("view/theme/".$a->theme_info["extends"]."/$s");
408 return file_get_contents("view/$s");
416 // for html,xml parsing - let's say you've got
417 // an attribute foobar="class1 class2 class3"
418 // and you want to find out if it contains 'class3'.
419 // you can't use a normal sub string search because you
420 // might match 'notclass3' and a regex to do the job is
421 // possible but a bit complicated.
422 // pass the attribute string as $attr and the attribute you
423 // are looking for as $s - returns true if found, otherwise false
425 if(! function_exists('attribute_contains')) {
426 function attribute_contains($attr,$s) {
427 $a = explode(' ', $attr);
428 if(count($a) && in_array($s,$a))
433 if(! function_exists('logger')) {
434 function logger($msg,$level = 0) {
435 // turn off logger in install mode
439 if(($a->module == 'install') || (! ($db && $db->connected))) return;
441 $debugging = get_config('system','debugging');
442 $loglevel = intval(get_config('system','loglevel'));
443 $logfile = get_config('system','logfile');
445 if((! $debugging) || (! $logfile) || ($level > $loglevel))
448 @file_put_contents($logfile, datetime_convert() . ':' . session_id() . ' ' . $msg . "\n", FILE_APPEND);
453 if(! function_exists('activity_match')) {
454 function activity_match($haystack,$needle) {
455 if(($haystack === $needle) || ((basename($needle) === $haystack) && strstr($needle,NAMESPACE_ACTIVITY_SCHEMA)))
461 // Pull out all #hashtags and @person tags from $s;
462 // We also get @person@domain.com - which would make
463 // the regex quite complicated as tags can also
464 // end a sentence. So we'll run through our results
465 // and strip the period from any tags which end with one.
466 // Returns array of tags found, or empty array.
469 if(! function_exists('get_tags')) {
470 function get_tags($s) {
473 // ignore anything in a code block
475 $s = preg_replace('/\[code\](.*?)\[\/code\]/sm','',$s);
477 // Match full names against @tags including the space between first and last
478 // We will look these up afterward to see if they are full names or not recognisable.
480 if(preg_match_all('/(@[^ \x0D\x0A,:?]+ [^ \x0D\x0A@,:?]+)([ \x0D\x0A@,:?]|$)/',$s,$match)) {
481 foreach($match[1] as $mtch) {
482 if(strstr($mtch,"]")) {
483 // we might be inside a bbcode color tag - leave it alone
486 if(substr($mtch,-1,1) === '.')
487 $ret[] = substr($mtch,0,-1);
493 // Otherwise pull out single word tags. These can be @nickname, @first_last
496 if(preg_match_all('/([@#][^ \x0D\x0A,;:?]+)([ \x0D\x0A,;:?]|$)/',$s,$match)) {
497 foreach($match[1] as $mtch) {
498 if(strstr($mtch,"]")) {
499 // we might be inside a bbcode color tag - leave it alone
502 if(substr($mtch,-1,1) === '.')
503 $mtch = substr($mtch,0,-1);
504 // ignore strictly numeric tags like #1
505 if((strpos($mtch,'#') === 0) && ctype_digit(substr($mtch,1)))
507 // try not to catch url fragments
508 if(strpos($s,$mtch) && preg_match('/[a-zA-z0-9\/]/',substr($s,strpos($s,$mtch)-1,1)))
517 // quick and dirty quoted_printable encoding
519 if(! function_exists('qp')) {
521 return str_replace ("%","=",rawurlencode($s));
526 if(! function_exists('get_mentions')) {
527 function get_mentions($item) {
529 if(! strlen($item['tag']))
532 $arr = explode(',',$item['tag']);
533 foreach($arr as $x) {
535 if(preg_match('/@\[url=([^\]]*)\]/',$x,$matches)) {
536 $o .= "\t\t" . '<link rel="mentioned" href="' . $matches[1] . '" />' . "\r\n";
537 $o .= "\t\t" . '<link rel="ostatus:attention" href="' . $matches[1] . '" />' . "\r\n";
543 if(! function_exists('contact_block')) {
544 function contact_block() {
548 $shown = get_pconfig($a->profile['uid'],'system','display_friend_count');
554 if((! is_array($a->profile)) || ($a->profile['hide-friends']))
556 $r = q("SELECT COUNT(*) AS `total` FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 and `pending` = 0 AND `hidden` = 0",
557 intval($a->profile['uid'])
560 $total = intval($r[0]['total']);
563 $contacts = t('No contacts');
567 $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",
568 intval($a->profile['uid']),
572 $contacts = sprintf( tt('%d Contact','%d Contacts', $total),$total);
575 $micropro[] = micropro($rr,true,'mpfriend');
580 $tpl = get_markup_template('contact_block.tpl');
581 $o = replace_macros($tpl, array(
582 '$contacts' => $contacts,
583 '$nickname' => $a->profile['nickname'],
584 '$viewcontacts' => t('View Contacts'),
585 '$micropro' => $micropro,
588 $arr = array('contacts' => $r, 'output' => $o);
590 call_hooks('contact_block_end', $arr);
595 if(! function_exists('micropro')) {
596 function micropro($contact, $redirect = false, $class = '', $textmode = false) {
599 $class = ' ' . $class;
601 $url = $contact['url'];
607 $redirect_url = $a->get_baseurl() . '/redir/' . $contact['id'];
608 if(local_user() && ($contact['uid'] == local_user()) && ($contact['network'] === 'dfrn')) {
610 $url = $redirect_url;
611 $sparkle = ' sparkle';
614 $click = ((x($contact,'click')) ? ' onclick="' . $contact['click'] . '" ' : '');
618 return '<div class="contact-block-textdiv' . $class . '"><a class="contact-block-link' . $class . $sparkle
619 . (($click) ? ' fakelink' : '') . '" '
620 . (($redir) ? ' target="redir" ' : '')
621 . (($url) ? ' href="' . $url . '"' : '') . $click
622 . '" title="' . $contact['name'] . ' [' . $contact['url'] . ']" alt="' . $contact['name']
623 . '" >'. $contact['name'] . '</a></div>' . "\r\n";
626 return '<div class="contact-block-div' . $class . '"><a class="contact-block-link' . $class . $sparkle
627 . (($click) ? ' fakelink' : '') . '" '
628 . (($redir) ? ' target="redir" ' : '')
629 . (($url) ? ' href="' . $url . '"' : '') . $click . ' ><img class="contact-block-img' . $class . $sparkle . '" src="'
630 . $contact['micro'] . '" title="' . $contact['name'] . ' [' . $contact['url'] . ']" alt="' . $contact['name']
631 . '" /></a></div>' . "\r\n";
637 if(! function_exists('search')) {
638 function search($s,$id='search-box',$url='/search',$save = false) {
640 $o = '<div id="' . $id . '">';
641 $o .= '<form action="' . $a->get_baseurl() . $url . '" method="get" >';
642 $o .= '<input type="text" name="search" id="search-text" value="' . $s .'" />';
643 $o .= '<input type="submit" name="submit" id="search-submit" value="' . t('Search') . '" />';
645 $o .= '<input type="submit" name="save" id="search-save" value="' . t('Save') . '" />';
646 $o .= '</form></div>';
650 if(! function_exists('valid_email')) {
651 function valid_email($x){
652 if(preg_match('/^[_a-zA-Z0-9\-\+]+(\.[_a-zA-Z0-9\-\+]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)+$/',$x))
662 * Replace naked text hyperlink with HTML formatted hyperlink
666 if(! function_exists('linkify')) {
667 function linkify($s) {
668 $s = preg_replace("/(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\'\%\$\!\+]*)/", ' <a href="$1" target="external-link">$1</a>', $s);
669 $s = preg_replace("/\<(.*?)(src|href)=(.*?)\&\;(.*?)\>/ism",'<$1$2=$3&$4>',$s);
679 * Replaces text emoticons with graphical images
681 * @Parameter: string $s
685 * It is expected that this function will be called using HTML text.
686 * We will escape text between HTML pre and code blocks from being
689 * At a higher level, the bbcode [nosmile] tag can be used to prevent this
690 * function from being executed by the prepare_text() routine when preparing
691 * bbcode source for HTML display
695 if(! function_exists('smilies')) {
696 function smilies($s, $sample = false) {
699 $s = preg_replace_callback('/<pre>(.*?)<\/pre>/ism','smile_encode',$s);
700 $s = preg_replace_callback('/<code>(.*?)<\/code>/ism','smile_encode',$s);
744 '<img src="' . $a->get_baseurl() . '/images/smiley-heart.gif" alt="<3" />',
745 '<img src="' . $a->get_baseurl() . '/images/smiley-brokenheart.gif" alt="</3" />',
746 '<img src="' . $a->get_baseurl() . '/images/smiley-brokenheart.gif" alt="<\\3" />',
747 '<img src="' . $a->get_baseurl() . '/images/smiley-smile.gif" alt=":-)" />',
748 // '<img src="' . $a->get_baseurl() . '/images/smiley-smile.gif" alt=":)" />',
749 '<img src="' . $a->get_baseurl() . '/images/smiley-wink.gif" alt=";-)" />',
750 // '<img src="' . $a->get_baseurl() . '/images/smiley-wink.gif" alt=";)"/>',
751 '<img src="' . $a->get_baseurl() . '/images/smiley-frown.gif" alt=":-(" />',
752 // '<img src="' . $a->get_baseurl() . '/images/smiley-frown.gif" alt=":(" />',
753 '<img src="' . $a->get_baseurl() . '/images/smiley-tongue-out.gif" alt=":-P" />',
754 // '<img src="' . $a->get_baseurl() . '/images/smiley-tongue-out.gif" alt=":P" />',
755 '<img src="' . $a->get_baseurl() . '/images/smiley-kiss.gif" alt=":-\"" />',
756 '<img src="' . $a->get_baseurl() . '/images/smiley-kiss.gif" alt=":-\"" />',
757 '<img src="' . $a->get_baseurl() . '/images/smiley-kiss.gif" alt=":-x" />',
758 '<img src="' . $a->get_baseurl() . '/images/smiley-kiss.gif" alt=":-X" />',
759 '<img src="' . $a->get_baseurl() . '/images/smiley-laughing.gif" alt=":-D" />',
760 // '<img src="' . $a->get_baseurl() . '/images/smiley-laughing.gif" alt=":D"/>',
761 '<img src="' . $a->get_baseurl() . '/images/smiley-surprised.gif" alt="8-|" />',
762 '<img src="' . $a->get_baseurl() . '/images/smiley-surprised.gif" alt="8-O" />',
763 '<img src="' . $a->get_baseurl() . '/images/smiley-surprised.gif" alt=":-O" />',
764 '<img src="' . $a->get_baseurl() . '/images/smiley-thumbsup.gif" alt="\\o/" />',
765 '<img src="' . $a->get_baseurl() . '/images/smiley-Oo.gif" alt="o.O" />',
766 '<img src="' . $a->get_baseurl() . '/images/smiley-Oo.gif" alt="O.o" />',
767 '<img src="' . $a->get_baseurl() . '/images/smiley-shaka.gif" alt="\\.../" />',
768 '<img src="' . $a->get_baseurl() . '/images/smiley-shaka.gif" alt="\\ooo/" />',
769 '<img src="' . $a->get_baseurl() . '/images/smiley-cry.gif" alt=":\'(" />',
770 '<img src="' . $a->get_baseurl() . '/images/smiley-foot-in-mouth.gif" alt=":-!" />',
771 '<img src="' . $a->get_baseurl() . '/images/smiley-undecided.gif" alt=":-/" />',
772 '<img src="' . $a->get_baseurl() . '/images/smiley-embarassed.gif" alt=":-[" />',
773 '<img src="' . $a->get_baseurl() . '/images/smiley-cool.gif" alt="8-)" />',
774 '<img src="' . $a->get_baseurl() . '/images/beer_mug.gif" alt=":beer" />',
775 '<img src="' . $a->get_baseurl() . '/images/beer_mug.gif" alt=":homebrew" />',
776 '<img src="' . $a->get_baseurl() . '/images/coffee.gif" alt=":coffee" />',
777 '<img src="' . $a->get_baseurl() . '/images/smiley-facepalm.gif" alt=":facepalm" />',
778 '<img src="' . $a->get_baseurl() . '/images/smiley-bangheaddesk.gif" alt=":headdesk" />',
779 '<a href="http://project.friendika.com">~friendika <img src="' . $a->get_baseurl() . '/images/friendika-16.png" alt="~friendika" /></a>',
780 '<a href="http://friendica.com">~friendica <img src="' . $a->get_baseurl() . '/images/friendica-16.png" alt="~friendica" /></a>',
781 // '<a href="http://diasporafoundation.org">Diaspora<img src="' . $a->get_baseurl() . '/images/diaspora.png" alt="Diaspora*" /></a>',
785 $params = array('texts' => $texts, 'icons' => $icons, 'string' => $s);
786 call_hooks('smilie', $params);
789 $s = '<div class="smiley-sample">';
790 for($x = 0; $x < count($params['texts']); $x ++) {
791 $s .= '<dl><dt>' . $params['texts'][$x] . '</dt><dd>' . $params['icons'][$x] . '</dd></dl>';
795 $params['string'] = preg_replace_callback('/<(3+)/','preg_heart',$params['string']);
796 $s = str_replace($params['texts'],$params['icons'],$params['string']);
799 $s = preg_replace_callback('/<pre>(.*?)<\/pre>/ism','smile_decode',$s);
800 $s = preg_replace_callback('/<code>(.*?)<\/code>/ism','smile_decode',$s);
806 function smile_encode($m) {
807 return(str_replace($m[1],base64url_encode($m[1]),$m[0]));
810 function smile_decode($m) {
811 return(str_replace($m[1],base64url_decode($m[1]),$m[0]));
814 // expand <3333 to the correct number of hearts
816 function preg_heart($x) {
818 if(strlen($x[1]) == 1)
821 for($cnt = 0; $cnt < strlen($x[1]); $cnt ++)
822 $t .= '<img src="' . $a->get_baseurl() . '/images/smiley-heart.gif" alt="<3" />';
823 $r = str_replace($x[0],$t,$x[0]);
828 if(! function_exists('day_translate')) {
829 function day_translate($s) {
830 $ret = str_replace(array('Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'),
831 array( t('Monday'), t('Tuesday'), t('Wednesday'), t('Thursday'), t('Friday'), t('Saturday'), t('Sunday')),
834 $ret = str_replace(array('January','February','March','April','May','June','July','August','September','October','November','December'),
835 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')),
842 if(! function_exists('normalise_link')) {
843 function normalise_link($url) {
844 $ret = str_replace(array('https:','//www.'), array('http:','//'), $url);
845 return(rtrim($ret,'/'));
850 * Compare two URLs to see if they are the same, but ignore
851 * slight but hopefully insignificant differences such as if one
852 * is https and the other isn't, or if one is www.something and
853 * the other isn't - and also ignore case differences.
855 * Return true if the URLs match, otherwise false.
859 if(! function_exists('link_compare')) {
860 function link_compare($a,$b) {
861 if(strcasecmp(normalise_link($a),normalise_link($b)) === 0)
866 // Given an item array, convert the body element from bbcode to html and add smilie icons.
867 // If attach is true, also add icons for item attachments
870 if(! function_exists('prepare_body')) {
871 function prepare_body($item,$attach = false) {
873 call_hooks('prepare_body_init', $item);
875 $s = prepare_text($item['body']);
877 $prep_arr = array('item' => $item, 'html' => $s);
878 call_hooks('prepare_body', $prep_arr);
879 $s = $prep_arr['html'];
884 $arr = explode(',',$item['attach']);
886 $s .= '<div class="body-attach">';
887 foreach($arr as $r) {
890 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"\[\/attach\]|',$r,$matches);
892 $icontype = strtolower(substr($matches[3],0,strpos($matches[3],'/')));
898 $icon = '<div class="attachtype icon s22 type-' . $icontype . '"></div>';
901 $icon = '<div class="attachtype icon s22 type-unkn"></div>';
904 $title = ((strlen(trim($matches[4]))) ? escape_tags(trim($matches[4])) : escape_tags($matches[1]));
905 $title .= ' ' . $matches[2] . ' ' . t('bytes');
907 $s .= '<a href="' . strip_tags($matches[1]) . '" title="' . $title . '" class="attachlink" target="external-link" >' . $icon . '</a>';
910 $s .= '<div class="clear"></div></div>';
914 $prep_arr = array('item' => $item, 'html' => $s);
915 call_hooks('prepare_body_final', $prep_arr);
916 return $prep_arr['html'];
920 // Given a text string, convert from bbcode to html and add smilie icons.
922 if(! function_exists('prepare_text')) {
923 function prepare_text($text) {
925 require_once('include/bbcode.php');
927 if(stristr($text,'[nosmile]'))
930 $s = smilies(bbcode($text));
937 * return atom link elements for all of our hubs
940 if(! function_exists('feed_hublinks')) {
941 function feed_hublinks() {
943 $hub = get_config('system','huburl');
947 $hubs = explode(',', $hub);
949 foreach($hubs as $h) {
953 $hubxml .= '<link rel="hub" href="' . xmlify($h) . '" />' . "\n" ;
960 /* return atom link elements for salmon endpoints */
962 if(! function_exists('feed_salmonlinks')) {
963 function feed_salmonlinks($nick) {
967 $salmon = '<link rel="salmon" href="' . xmlify($a->get_baseurl() . '/salmon/' . $nick) . '" />' . "\n" ;
969 // old style links that status.net still needed as of 12/2010
971 $salmon .= ' <link rel="http://salmon-protocol.org/ns/salmon-replies" href="' . xmlify($a->get_baseurl() . '/salmon/' . $nick) . '" />' . "\n" ;
972 $salmon .= ' <link rel="http://salmon-protocol.org/ns/salmon-mention" href="' . xmlify($a->get_baseurl() . '/salmon/' . $nick) . '" />' . "\n" ;
976 if(! function_exists('get_plink')) {
977 function get_plink($item) {
979 if (x($item,'plink') && (! $item['private'])){
981 'href' => $item['plink'],
982 'title' => t('link to source'),
989 if(! function_exists('unamp')) {
991 return str_replace('&', '&', $s);
997 if(! function_exists('lang_selector')) {
998 function lang_selector() {
1000 $o = '<div id="lang-select-icon" class="icon language" title="' . t('Select an alternate language') . '" onclick="openClose(\'language-selector\');" ></div>';
1001 $o .= '<div id="language-selector" style="display: none;" >';
1002 $o .= '<form action="#" method="post" ><select name="system_language" onchange="this.form.submit();" >';
1003 $langs = glob('view/*/strings.php');
1004 if(is_array($langs) && count($langs)) {
1006 if(! in_array('view/en/strings.php',$langs))
1007 $langs[] = 'view/en/';
1009 foreach($langs as $l) {
1011 $default_selected = ((! x($_SESSION,'language')) ? ' selected="selected" ' : '');
1012 $o .= '<option value="" ' . $default_selected . '>' . t('default') . '</option>';
1016 $ll = substr($ll,0,strrpos($ll,'/'));
1017 $selected = (($ll === $lang && (x($_SESSION, 'language'))) ? ' selected="selected" ' : '');
1018 $o .= '<option value="' . $ll . '"' . $selected . '>' . $ll . '</option>';
1021 $o .= '</select></form></div>';
1026 if(! function_exists('return_bytes')) {
1027 function return_bytes ($size_str) {
1028 switch (substr ($size_str, -1))
1030 case 'M': case 'm': return (int)$size_str * 1048576;
1031 case 'K': case 'k': return (int)$size_str * 1024;
1032 case 'G': case 'g': return (int)$size_str * 1073741824;
1033 default: return $size_str;
1037 function generate_user_guid() {
1040 $guid = random_string(16);
1041 $x = q("SELECT `uid` FROM `user` WHERE `guid` = '%s' LIMIT 1",
1046 } while ($found == true );
1052 function base64url_encode($s, $strip_padding = false) {
1054 $s = strtr(base64_encode($s),'+/','-_');
1057 $s = str_replace('=','',$s);
1062 function base64url_decode($s) {
1065 logger('base64url_decode: illegal input: ' . print_r(debug_backtrace(), true));
1070 * // Placeholder for new rev of salmon which strips base64 padding.
1071 * // PHP base64_decode handles the un-padded input without requiring this step
1072 * // Uncomment if you find you need it.
1075 * if(! strpos($s,'=')) {
1085 return base64_decode(strtr($s,'-_','+/'));
1089 if (!function_exists('str_getcsv')) {
1090 function str_getcsv($input, $delimiter = ',', $enclosure = '"', $escape = '\\', $eol = '\n') {
1091 if (is_string($input) && !empty($input)) {
1093 $tmp = preg_split("/".$eol."/",$input);
1094 if (is_array($tmp) && !empty($tmp)) {
1095 while (list($line_num, $line) = each($tmp)) {
1096 if (preg_match("/".$escape.$enclosure."/",$line)) {
1097 while ($strlen = strlen($line)) {
1098 $pos_delimiter = strpos($line,$delimiter);
1099 $pos_enclosure_start = strpos($line,$enclosure);
1101 is_int($pos_delimiter) && is_int($pos_enclosure_start)
1102 && ($pos_enclosure_start < $pos_delimiter)
1104 $enclosed_str = substr($line,1);
1105 $pos_enclosure_end = strpos($enclosed_str,$enclosure);
1106 $enclosed_str = substr($enclosed_str,0,$pos_enclosure_end);
1107 $output[$line_num][] = $enclosed_str;
1108 $offset = $pos_enclosure_end+3;
1110 if (empty($pos_delimiter) && empty($pos_enclosure_start)) {
1111 $output[$line_num][] = substr($line,0);
1112 $offset = strlen($line);
1114 $output[$line_num][] = substr($line,0,$pos_delimiter);
1116 !empty($pos_enclosure_start)
1117 && ($pos_enclosure_start < $pos_delimiter)
1119 ?$pos_enclosure_start
1123 $line = substr($line,$offset);
1126 $line = preg_split("/".$delimiter."/",$line);
1129 * Validating against pesky extra line breaks creating false rows.
1131 if (is_array($line) && !empty($line[0])) {
1132 $output[$line_num] = $line;
1146 function cleardiv() {
1147 return '<div class="clear"></div>';
1151 function bb_translate_video($s) {
1154 $r = preg_match_all("/\[video\](.*?)\[\/video\]/ism",$s,$matches,PREG_SET_ORDER);
1156 foreach($matches as $mtch) {
1157 if((stristr($mtch[1],'youtube')) || (stristr($mtch[1],'youtu.be')))
1158 $s = str_replace($mtch[0],'[youtube]' . $mtch[1] . '[/youtube]',$s);
1159 elseif(stristr($mtch[1],'vimeo'))
1160 $s = str_replace($mtch[0],'[vimeo]' . $mtch[1] . '[/vimeo]',$s);
1166 function html2bb_video($s) {
1168 $s = preg_replace('#<object[^>]+>(.*?)https+://www.youtube.com/((?:v|cp)/[A-Za-z0-9\-_=]+)(.*?)</object>#ism',
1169 '[youtube]$2[/youtube]', $s);
1171 $s = preg_replace('#<iframe[^>](.*?)https+://www.youtube.com/embed/([A-Za-z0-9\-_=]+)(.*?)</iframe>#ism',
1172 '[youtube]$2[/youtube]', $s);
1174 $s = preg_replace('#<iframe[^>](.*?)https+://player.vimeo.com/video/([0-9]+)(.*?)</iframe>#ism',
1175 '[vimeo]$2[/vimeo]', $s);
1181 * apply xmlify() to all values of array $val, recursively
1183 function array_xmlify($val){
1184 if (is_bool($val)) return $val?"true":"false";
1185 if (is_array($val)) return array_map('array_xmlify', $val);
1186 return xmlify((string) $val);
1190 function reltoabs($text, $base)
1195 $base = rtrim($base,'/');
1197 $base2 = $base . "/";
1200 $pattern = "/<a([^>]*) href=\"(?!http|https|\/)([^\"]*)\"/";
1201 $replace = "<a\${1} href=\"" . $base2 . "\${2}\"";
1202 $text = preg_replace($pattern, $replace, $text);
1204 $pattern = "/<a([^>]*) href=\"(?!http|https)([^\"]*)\"/";
1205 $replace = "<a\${1} href=\"" . $base . "\${2}\"";
1206 $text = preg_replace($pattern, $replace, $text);
1209 $pattern = "/<img([^>]*) src=\"(?!http|https|\/)([^\"]*)\"/";
1210 $replace = "<img\${1} src=\"" . $base2 . "\${2}\"";
1211 $text = preg_replace($pattern, $replace, $text);
1213 $pattern = "/<img([^>]*) src=\"(?!http|https)([^\"]*)\"/";
1214 $replace = "<img\${1} src=\"" . $base . "\${2}\"";
1215 $text = preg_replace($pattern, $replace, $text);
1222 function item_post_type($item) {
1223 if(intval($item['event-id']))
1225 if(strlen($item['resource-id']))
1227 if(strlen($item['verb']) && $item['verb'] !== ACTIVITY_POST)
1228 return t('activity');
1229 if($item['id'] != $item['parent'])
1230 return t('comment');