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);
747 '<img src="' . $a->get_baseurl() . '/images/smiley-heart.gif" alt="<3" />',
748 '<img src="' . $a->get_baseurl() . '/images/smiley-brokenheart.gif" alt="</3" />',
749 '<img src="' . $a->get_baseurl() . '/images/smiley-brokenheart.gif" alt="<\\3" />',
750 '<img src="' . $a->get_baseurl() . '/images/smiley-smile.gif" alt=":-)" />',
751 // '<img src="' . $a->get_baseurl() . '/images/smiley-smile.gif" alt=":)" />',
752 '<img src="' . $a->get_baseurl() . '/images/smiley-wink.gif" alt=";-)" />',
753 // '<img src="' . $a->get_baseurl() . '/images/smiley-wink.gif" alt=";)"/>',
754 '<img src="' . $a->get_baseurl() . '/images/smiley-frown.gif" alt=":-(" />',
755 // '<img src="' . $a->get_baseurl() . '/images/smiley-frown.gif" alt=":(" />',
756 '<img src="' . $a->get_baseurl() . '/images/smiley-tongue-out.gif" alt=":-P" />',
757 // '<img src="' . $a->get_baseurl() . '/images/smiley-tongue-out.gif" alt=":P" />',
758 '<img src="' . $a->get_baseurl() . '/images/smiley-kiss.gif" alt=":-\"" />',
759 '<img src="' . $a->get_baseurl() . '/images/smiley-kiss.gif" alt=":-\"" />',
760 '<img src="' . $a->get_baseurl() . '/images/smiley-kiss.gif" alt=":-x" />',
761 '<img src="' . $a->get_baseurl() . '/images/smiley-kiss.gif" alt=":-X" />',
762 '<img src="' . $a->get_baseurl() . '/images/smiley-laughing.gif" alt=":-D" />',
763 // '<img src="' . $a->get_baseurl() . '/images/smiley-laughing.gif" alt=":D"/>',
764 '<img src="' . $a->get_baseurl() . '/images/smiley-surprised.gif" alt="8-|" />',
765 '<img src="' . $a->get_baseurl() . '/images/smiley-surprised.gif" alt="8-O" />',
766 '<img src="' . $a->get_baseurl() . '/images/smiley-surprised.gif" alt=":-O" />',
767 '<img src="' . $a->get_baseurl() . '/images/smiley-thumbsup.gif" alt="\\o/" />',
768 '<img src="' . $a->get_baseurl() . '/images/smiley-Oo.gif" alt="o.O" />',
769 '<img src="' . $a->get_baseurl() . '/images/smiley-Oo.gif" alt="O.o" />',
770 '<img src="' . $a->get_baseurl() . '/images/smiley-shaka.gif" alt="\\.../" />',
771 '<img src="' . $a->get_baseurl() . '/images/smiley-shaka.gif" alt="\\ooo/" />',
772 '<img src="' . $a->get_baseurl() . '/images/smiley-cry.gif" alt=":\'(" />',
773 '<img src="' . $a->get_baseurl() . '/images/smiley-foot-in-mouth.gif" alt=":-!" />',
774 '<img src="' . $a->get_baseurl() . '/images/smiley-undecided.gif" alt=":-/" />',
775 '<img src="' . $a->get_baseurl() . '/images/smiley-embarassed.gif" alt=":-[" />',
776 '<img src="' . $a->get_baseurl() . '/images/smiley-cool.gif" alt="8-)" />',
777 '<img src="' . $a->get_baseurl() . '/images/beer_mug.gif" alt=":beer" />',
778 '<img src="' . $a->get_baseurl() . '/images/beer_mug.gif" alt=":homebrew" />',
779 '<img src="' . $a->get_baseurl() . '/images/coffee.gif" alt=":coffee" />',
780 '<img src="' . $a->get_baseurl() . '/images/smiley-facepalm.gif" alt=":facepalm" />',
781 '<img src="' . $a->get_baseurl() . '/images/smiley-bangheaddesk.gif" alt=":headdesk" />',
782 '<a href="http://project.friendika.com">~friendika <img src="' . $a->get_baseurl() . '/images/friendika-16.png" alt="~friendika" /></a>',
783 '<a href="http://friendica.com">~friendica <img src="' . $a->get_baseurl() . '/images/friendica-16.png" alt="~friendica" /></a>',
784 // '<a href="http://diasporafoundation.org">Diaspora<img src="' . $a->get_baseurl() . '/images/diaspora.png" alt="Diaspora*" /></a>',
785 '<img src="' . $a->get_baseurl() . '/images/smiley-beard.png" alt=":beard" />',
786 '<img src="' . $a->get_baseurl() . '/images/smiley-whitebeard.png" alt=":whitebeard" />'
789 $params = array('texts' => $texts, 'icons' => $icons, 'string' => $s);
790 call_hooks('smilie', $params);
793 $s = '<div class="smiley-sample">';
794 for($x = 0; $x < count($params['texts']); $x ++) {
795 $s .= '<dl><dt>' . $params['texts'][$x] . '</dt><dd>' . $params['icons'][$x] . '</dd></dl>';
799 $params['string'] = preg_replace_callback('/<(3+)/','preg_heart',$params['string']);
800 $s = str_replace($params['texts'],$params['icons'],$params['string']);
803 $s = preg_replace_callback('/<pre>(.*?)<\/pre>/ism','smile_decode',$s);
804 $s = preg_replace_callback('/<code>(.*?)<\/code>/ism','smile_decode',$s);
810 function smile_encode($m) {
811 return(str_replace($m[1],base64url_encode($m[1]),$m[0]));
814 function smile_decode($m) {
815 return(str_replace($m[1],base64url_decode($m[1]),$m[0]));
818 // expand <3333 to the correct number of hearts
820 function preg_heart($x) {
822 if(strlen($x[1]) == 1)
825 for($cnt = 0; $cnt < strlen($x[1]); $cnt ++)
826 $t .= '<img src="' . $a->get_baseurl() . '/images/smiley-heart.gif" alt="<3" />';
827 $r = str_replace($x[0],$t,$x[0]);
832 if(! function_exists('day_translate')) {
833 function day_translate($s) {
834 $ret = str_replace(array('Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'),
835 array( t('Monday'), t('Tuesday'), t('Wednesday'), t('Thursday'), t('Friday'), t('Saturday'), t('Sunday')),
838 $ret = str_replace(array('January','February','March','April','May','June','July','August','September','October','November','December'),
839 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')),
846 if(! function_exists('normalise_link')) {
847 function normalise_link($url) {
848 $ret = str_replace(array('https:','//www.'), array('http:','//'), $url);
849 return(rtrim($ret,'/'));
854 * Compare two URLs to see if they are the same, but ignore
855 * slight but hopefully insignificant differences such as if one
856 * is https and the other isn't, or if one is www.something and
857 * the other isn't - and also ignore case differences.
859 * Return true if the URLs match, otherwise false.
863 if(! function_exists('link_compare')) {
864 function link_compare($a,$b) {
865 if(strcasecmp(normalise_link($a),normalise_link($b)) === 0)
870 // Given an item array, convert the body element from bbcode to html and add smilie icons.
871 // If attach is true, also add icons for item attachments
874 if(! function_exists('prepare_body')) {
875 function prepare_body($item,$attach = false) {
878 call_hooks('prepare_body_init', $item);
880 $cache = get_config('system','itemcache');
882 if (($cache != '')) {
883 $cachefile = $cache."/".$item["guid"]."-".strtotime($item["edited"])."-".hash("crc32", $item['body']);
885 if (file_exists($cachefile))
886 $s = file_get_contents($cachefile);
888 $s = prepare_text($item['body']);
889 file_put_contents($cachefile, $s);
892 $s = prepare_text($item['body']);
894 $prep_arr = array('item' => $item, 'html' => $s);
895 call_hooks('prepare_body', $prep_arr);
896 $s = $prep_arr['html'];
902 $arr = explode(',',$item['attach']);
904 $s .= '<div class="body-attach">';
905 foreach($arr as $r) {
908 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"\[\/attach\]|',$r,$matches);
910 $icontype = strtolower(substr($matches[3],0,strpos($matches[3],'/')));
916 $icon = '<div class="attachtype icon s22 type-' . $icontype . '"></div>';
919 $icon = '<div class="attachtype icon s22 type-unkn"></div>';
922 $title = ((strlen(trim($matches[4]))) ? escape_tags(trim($matches[4])) : escape_tags($matches[1]));
923 $title .= ' ' . $matches[2] . ' ' . t('bytes');
925 $s .= '<a href="' . strip_tags($matches[1]) . '" title="' . $title . '" class="attachlink" target="external-link" >' . $icon . '</a>';
928 $s .= '<div class="clear"></div></div>';
931 $cnt = preg_match_all('/<(.*?)>/',$item['file'],$matches,PREG_SET_ORDER);
933 // logger('prepare_text: categories: ' . print_r($matches,true), LOGGER_DEBUG);
934 foreach($matches as $mtch) {
937 $x .= file_tag_decode($mtch[1]);
940 $s .= '<div class="categorytags"><span>' . t('Categories:') . ' </span>' . $x . '</div>';
946 $cnt = preg_match_all('/\[(.*?)\]/',$item['file'],$matches,PREG_SET_ORDER);
948 // logger('prepare_text: filed_under: ' . print_r($matches,true), LOGGER_DEBUG);
949 foreach($matches as $mtch) {
951 $x .= ' ';
952 $x .= file_tag_decode($mtch[1]). ' <a href="' . $a->get_baseurl() . '/filerm/' . $item['id'] . '?f=&term=' . file_tag_decode($mtch[1]) . '" title="' . t('remove') . '" >' . t('[remove]') . '</a>';
954 if(strlen($x) && (local_user() == $item['uid']))
955 $s .= '<div class="filesavetags"><span>' . t('Filed under:') . ' </span>' . $x . '</div>';
959 $spoilersearch = '<blockquote class="spoiler">';
961 // Remove line breaks before the spoiler
962 while ((strpos($s, "\n".$spoilersearch) !== false))
963 $s = str_replace("\n".$spoilersearch, $spoilersearch, $s);
964 while ((strpos($s, "<br />".$spoilersearch) !== false))
965 $s = str_replace("<br />".$spoilersearch, $spoilersearch, $s);
967 while ((strpos($s, $spoilersearch) !== false)) {
969 $pos = strpos($s, $spoilersearch);
970 $rnd = random_string(8);
971 $spoilerreplace = '<br /> <span id="spoiler-wrap-'.$rnd.'" style="white-space:nowrap;" class="fakelink" onclick="openClose(\'spoiler-'.$rnd.'\');">'.sprintf(t('Click to open/close')).'</span>'.
972 '<blockquote class="spoiler" id="spoiler-'.$rnd.'" style="display: none;">';
973 $s = substr($s, 0, $pos).$spoilerreplace.substr($s, $pos+strlen($spoilersearch));
976 // Look for quote with author
977 $authorsearch = '<blockquote class="author">';
979 while ((strpos($s, $authorsearch) !== false)) {
981 $pos = strpos($s, $authorsearch);
982 $rnd = random_string(8);
983 $authorreplace = '<br /> <span id="author-wrap-'.$rnd.'" style="white-space:nowrap;" class="fakelink" onclick="openClose(\'author-'.$rnd.'\');">'.sprintf(t('Click to open/close')).'</span>'.
984 '<blockquote class="author" id="author-'.$rnd.'" style="display: block;">';
985 $s = substr($s, 0, $pos).$authorreplace.substr($s, $pos+strlen($authorsearch));
988 $prep_arr = array('item' => $item, 'html' => $s);
989 call_hooks('prepare_body_final', $prep_arr);
991 return $prep_arr['html'];
995 // Given a text string, convert from bbcode to html and add smilie icons.
997 if(! function_exists('prepare_text')) {
998 function prepare_text($text) {
1000 require_once('include/bbcode.php');
1002 if(stristr($text,'[nosmile]'))
1005 $s = smilies(bbcode($text));
1012 * return atom link elements for all of our hubs
1015 if(! function_exists('feed_hublinks')) {
1016 function feed_hublinks() {
1018 $hub = get_config('system','huburl');
1022 $hubs = explode(',', $hub);
1024 foreach($hubs as $h) {
1028 $hubxml .= '<link rel="hub" href="' . xmlify($h) . '" />' . "\n" ;
1035 /* return atom link elements for salmon endpoints */
1037 if(! function_exists('feed_salmonlinks')) {
1038 function feed_salmonlinks($nick) {
1042 $salmon = '<link rel="salmon" href="' . xmlify($a->get_baseurl() . '/salmon/' . $nick) . '" />' . "\n" ;
1044 // old style links that status.net still needed as of 12/2010
1046 $salmon .= ' <link rel="http://salmon-protocol.org/ns/salmon-replies" href="' . xmlify($a->get_baseurl() . '/salmon/' . $nick) . '" />' . "\n" ;
1047 $salmon .= ' <link rel="http://salmon-protocol.org/ns/salmon-mention" href="' . xmlify($a->get_baseurl() . '/salmon/' . $nick) . '" />' . "\n" ;
1051 if(! function_exists('get_plink')) {
1052 function get_plink($item) {
1054 if (x($item,'plink') && (! $item['private'])){
1056 'href' => $item['plink'],
1057 'title' => t('link to source'),
1064 if(! function_exists('unamp')) {
1065 function unamp($s) {
1066 return str_replace('&', '&', $s);
1072 if(! function_exists('lang_selector')) {
1073 function lang_selector() {
1075 $o = '<div id="lang-select-icon" class="icon language" title="' . t('Select an alternate language') . '" onclick="openClose(\'language-selector\');" ></div>';
1076 $o .= '<div id="language-selector" style="display: none;" >';
1077 $o .= '<form action="#" method="post" ><select name="system_language" onchange="this.form.submit();" >';
1078 $langs = glob('view/*/strings.php');
1079 if(is_array($langs) && count($langs)) {
1081 if(! in_array('view/en/strings.php',$langs))
1082 $langs[] = 'view/en/';
1084 foreach($langs as $l) {
1086 $default_selected = ((! x($_SESSION,'language')) ? ' selected="selected" ' : '');
1087 $o .= '<option value="" ' . $default_selected . '>' . t('default') . '</option>';
1091 $ll = substr($ll,0,strrpos($ll,'/'));
1092 $selected = (($ll === $lang && (x($_SESSION, 'language'))) ? ' selected="selected" ' : '');
1093 $o .= '<option value="' . $ll . '"' . $selected . '>' . $ll . '</option>';
1096 $o .= '</select></form></div>';
1101 if(! function_exists('return_bytes')) {
1102 function return_bytes ($size_str) {
1103 switch (substr ($size_str, -1))
1105 case 'M': case 'm': return (int)$size_str * 1048576;
1106 case 'K': case 'k': return (int)$size_str * 1024;
1107 case 'G': case 'g': return (int)$size_str * 1073741824;
1108 default: return $size_str;
1112 function generate_user_guid() {
1115 $guid = random_string(16);
1116 $x = q("SELECT `uid` FROM `user` WHERE `guid` = '%s' LIMIT 1",
1121 } while ($found == true );
1127 function base64url_encode($s, $strip_padding = false) {
1129 $s = strtr(base64_encode($s),'+/','-_');
1132 $s = str_replace('=','',$s);
1137 function base64url_decode($s) {
1140 logger('base64url_decode: illegal input: ' . print_r(debug_backtrace(), true));
1145 * // Placeholder for new rev of salmon which strips base64 padding.
1146 * // PHP base64_decode handles the un-padded input without requiring this step
1147 * // Uncomment if you find you need it.
1150 * if(! strpos($s,'=')) {
1160 return base64_decode(strtr($s,'-_','+/'));
1164 if (!function_exists('str_getcsv')) {
1165 function str_getcsv($input, $delimiter = ',', $enclosure = '"', $escape = '\\', $eol = '\n') {
1166 if (is_string($input) && !empty($input)) {
1168 $tmp = preg_split("/".$eol."/",$input);
1169 if (is_array($tmp) && !empty($tmp)) {
1170 while (list($line_num, $line) = each($tmp)) {
1171 if (preg_match("/".$escape.$enclosure."/",$line)) {
1172 while ($strlen = strlen($line)) {
1173 $pos_delimiter = strpos($line,$delimiter);
1174 $pos_enclosure_start = strpos($line,$enclosure);
1176 is_int($pos_delimiter) && is_int($pos_enclosure_start)
1177 && ($pos_enclosure_start < $pos_delimiter)
1179 $enclosed_str = substr($line,1);
1180 $pos_enclosure_end = strpos($enclosed_str,$enclosure);
1181 $enclosed_str = substr($enclosed_str,0,$pos_enclosure_end);
1182 $output[$line_num][] = $enclosed_str;
1183 $offset = $pos_enclosure_end+3;
1185 if (empty($pos_delimiter) && empty($pos_enclosure_start)) {
1186 $output[$line_num][] = substr($line,0);
1187 $offset = strlen($line);
1189 $output[$line_num][] = substr($line,0,$pos_delimiter);
1191 !empty($pos_enclosure_start)
1192 && ($pos_enclosure_start < $pos_delimiter)
1194 ?$pos_enclosure_start
1198 $line = substr($line,$offset);
1201 $line = preg_split("/".$delimiter."/",$line);
1204 * Validating against pesky extra line breaks creating false rows.
1206 if (is_array($line) && !empty($line[0])) {
1207 $output[$line_num] = $line;
1221 function cleardiv() {
1222 return '<div class="clear"></div>';
1226 function bb_translate_video($s) {
1229 $r = preg_match_all("/\[video\](.*?)\[\/video\]/ism",$s,$matches,PREG_SET_ORDER);
1231 foreach($matches as $mtch) {
1232 if((stristr($mtch[1],'youtube')) || (stristr($mtch[1],'youtu.be')))
1233 $s = str_replace($mtch[0],'[youtube]' . $mtch[1] . '[/youtube]',$s);
1234 elseif(stristr($mtch[1],'vimeo'))
1235 $s = str_replace($mtch[0],'[vimeo]' . $mtch[1] . '[/vimeo]',$s);
1241 function html2bb_video($s) {
1243 $s = preg_replace('#<object[^>]+>(.*?)https+://www.youtube.com/((?:v|cp)/[A-Za-z0-9\-_=]+)(.*?)</object>#ism',
1244 '[youtube]$2[/youtube]', $s);
1246 $s = preg_replace('#<iframe[^>](.*?)https+://www.youtube.com/embed/([A-Za-z0-9\-_=]+)(.*?)</iframe>#ism',
1247 '[youtube]$2[/youtube]', $s);
1249 $s = preg_replace('#<iframe[^>](.*?)https+://player.vimeo.com/video/([0-9]+)(.*?)</iframe>#ism',
1250 '[vimeo]$2[/vimeo]', $s);
1256 * apply xmlify() to all values of array $val, recursively
1258 function array_xmlify($val){
1259 if (is_bool($val)) return $val?"true":"false";
1260 if (is_array($val)) return array_map('array_xmlify', $val);
1261 return xmlify((string) $val);
1265 function reltoabs($text, $base)
1270 $base = rtrim($base,'/');
1272 $base2 = $base . "/";
1275 $pattern = "/<a([^>]*) href=\"(?!http|https|\/)([^\"]*)\"/";
1276 $replace = "<a\${1} href=\"" . $base2 . "\${2}\"";
1277 $text = preg_replace($pattern, $replace, $text);
1279 $pattern = "/<a([^>]*) href=\"(?!http|https)([^\"]*)\"/";
1280 $replace = "<a\${1} href=\"" . $base . "\${2}\"";
1281 $text = preg_replace($pattern, $replace, $text);
1284 $pattern = "/<img([^>]*) src=\"(?!http|https|\/)([^\"]*)\"/";
1285 $replace = "<img\${1} src=\"" . $base2 . "\${2}\"";
1286 $text = preg_replace($pattern, $replace, $text);
1288 $pattern = "/<img([^>]*) src=\"(?!http|https)([^\"]*)\"/";
1289 $replace = "<img\${1} src=\"" . $base . "\${2}\"";
1290 $text = preg_replace($pattern, $replace, $text);
1297 function item_post_type($item) {
1298 if(intval($item['event-id']))
1300 if(strlen($item['resource-id']))
1302 if(strlen($item['verb']) && $item['verb'] !== ACTIVITY_POST)
1303 return t('activity');
1304 if($item['id'] != $item['parent'])
1305 return t('comment');
1309 // post categories and "save to file" use the same item.file table for storage.
1310 // We will differentiate the different uses by wrapping categories in angle brackets
1311 // and save to file categories in square brackets.
1312 // To do this we need to escape these characters if they appear in our tag.
1314 function file_tag_encode($s) {
1315 return str_replace(array('<','>','[',']'),array('%3c','%3e','%5b','%5d'),$s);
1318 function file_tag_decode($s) {
1319 return str_replace(array('%3c','%3e','%5b','%5d'),array('<','>','[',']'),$s);
1322 function file_tag_file_query($table,$s,$type = 'file') {
1324 $str = preg_quote( '[' . file_tag_encode($s) . ']' );
1326 $str = preg_quote( '<' . file_tag_encode($s) . '>' );
1327 return " AND " . (($table) ? dbesc($table) . '.' : '') . "file regexp '" . dbesc($str) . "' ";
1330 function file_tag_save_file($uid,$item,$file) {
1334 $r = q("select file from item where id = %d and uid = %d limit 1",
1339 if(! stristr($r[0]['file'],'[' . file_tag_encode($file) . ']'))
1340 q("update item set file = '%s' where id = %d and uid = %d limit 1",
1341 dbesc($r[0]['file'] . '[' . file_tag_encode($file) . ']'),
1345 $saved = get_pconfig($uid,'system','filetags');
1346 if((! strlen($saved)) || (! stristr($saved,'[' . file_tag_encode($file) . ']')))
1347 set_pconfig($uid,'system','filetags',$saved . '[' . file_tag_encode($file) . ']');
1352 function file_tag_unsave_file($uid,$item,$file) {
1357 $pattern = '[' . file_tag_encode($file) . ']' ;
1359 $r = q("select file from item where id = %d and uid = %d limit 1",
1366 q("update item set file = '%s' where id = %d and uid = %d limit 1",
1367 dbesc(str_replace($pattern,'',$r[0]['file'])),
1372 $r = q("select file from item where uid = %d " . file_tag_file_query('item',$file),
1377 $saved = get_pconfig($uid,'system','filetags');
1378 set_pconfig($uid,'system','filetags',str_replace($pattern,'',$saved));