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";
23 return template_unescape($r);
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)) {
211 return(pack("H*",$s));
214 // Automatic pagination.
215 // To use, get the count of total items.
216 // Then call $a->set_pager_total($number_items);
217 // Optionally call $a->set_pager_itemspage($n) to the number of items to display on each page
218 // Then call paginate($a) after the end of the display loop to insert the pager block on the page
219 // (assuming there are enough items to paginate).
220 // When using with SQL, the setting LIMIT %d, %d => $a->pager['start'],$a->pager['itemspage']
221 // will limit the results to the correct items for the current page.
222 // The actual page handling is then accomplished at the application layer.
224 if(! function_exists('paginate')) {
225 function paginate(&$a) {
227 $stripped = preg_replace('/(&page=[0-9]*)/','',$a->query_string);
228 $stripped = str_replace('q=','',$stripped);
229 $stripped = trim($stripped,'/');
230 $pagenum = $a->pager['page'];
231 $url = $a->get_baseurl() . '/' . $stripped;
234 if($a->pager['total'] > $a->pager['itemspage']) {
235 $o .= '<div class="pager">';
236 if($a->pager['page'] != 1)
237 $o .= '<span class="pager_prev">'."<a href=\"$url".'&page='.($a->pager['page'] - 1).'">' . t('prev') . '</a></span> ';
239 $o .= "<span class=\"pager_first\"><a href=\"$url"."&page=1\">" . t('first') . "</a></span> ";
241 $numpages = $a->pager['total'] / $a->pager['itemspage'];
244 $numstop = $numpages;
247 $numstart = (($pagenum > 7) ? ($pagenum - 7) : 1);
248 $numstop = (($pagenum > ($numpages - 7)) ? $numpages : ($numstart + 14));
251 for($i = $numstart; $i <= $numstop; $i++){
252 if($i == $a->pager['page'])
253 $o .= '<span class="pager_current">'.(($i < 10) ? ' '.$i : $i);
255 $o .= "<span class=\"pager_n\"><a href=\"$url"."&page=$i\">".(($i < 10) ? ' '.$i : $i)."</a>";
259 if(($a->pager['total'] % $a->pager['itemspage']) != 0) {
260 if($i == $a->pager['page'])
261 $o .= '<span class="pager_current">'.(($i < 10) ? ' '.$i : $i);
263 $o .= "<span class=\"pager_n\"><a href=\"$url"."&page=$i\">".(($i < 10) ? ' '.$i : $i)."</a>";
267 $lastpage = (($numpages > intval($numpages)) ? intval($numpages)+1 : $numpages);
268 $o .= "<span class=\"pager_last\"><a href=\"$url"."&page=$lastpage\">" . t('last') . "</a></span> ";
270 if(($a->pager['total'] - ($a->pager['itemspage'] * $a->pager['page'])) > 0)
271 $o .= '<span class="pager_next">'."<a href=\"$url"."&page=".($a->pager['page'] + 1).'">' . t('next') . '</a></span>';
272 $o .= '</div>'."\r\n";
277 // Turn user/group ACLs stored as angle bracketed text into arrays
279 if(! function_exists('expand_acl')) {
280 function expand_acl($s) {
281 // turn string array of angle-bracketed elements into numeric array
282 // e.g. "<1><2><3>" => array(1,2,3);
286 $t = str_replace('<','',$s);
287 $a = explode('>',$t);
290 $ret[] = intval($aa);
296 // Used to wrap ACL elements in angle brackets for storage
298 if(! function_exists('sanitise_acl')) {
299 function sanitise_acl(&$item) {
301 $item = '<' . intval(notags(trim($item))) . '>';
307 // Convert an ACL array to a storable string
309 if(! function_exists('perms2str')) {
310 function perms2str($p) {
314 array_walk($tmp,'sanitise_acl');
315 $ret = implode('',$tmp);
320 // generate a guaranteed unique (for this domain) item ID for ATOM
321 // safe from birthday paradox
323 if(! function_exists('item_new_uri')) {
324 function item_new_uri($hostname,$uid) {
328 $hash = random_string();
330 $uri = "urn:X-dfrn:" . $hostname . ':' . $uid . ':' . $hash;
332 $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' LIMIT 1",
336 } while($dups == true);
340 // Generate a guaranteed unique photo ID.
341 // safe from birthday paradox
343 if(! function_exists('photo_new_resource')) {
344 function photo_new_resource() {
348 $resource = hash('md5',uniqid(mt_rand(),true));
349 $r = q("SELECT `id` FROM `photo` WHERE `resource-id` = '%s' LIMIT 1",
354 } while($found == true);
359 // wrapper to load a view template, checking for alternate
360 // languages before falling back to the default
362 // obsolete, deprecated.
364 if(! function_exists('load_view_file')) {
365 function load_view_file($s) {
371 if(file_exists("$d/$lang/$b"))
372 return file_get_contents("$d/$lang/$b");
374 $theme = current_theme();
376 if(file_exists("$d/theme/$theme/$b"))
377 return file_get_contents("$d/theme/$theme/$b");
379 return file_get_contents($s);
382 if(! function_exists('get_intltext_template')) {
383 function get_intltext_template($s) {
389 if(file_exists("view/$lang/$s"))
390 return file_get_contents("view/$lang/$s");
391 elseif(file_exists("view/en/$s"))
392 return file_get_contents("view/en/$s");
394 return file_get_contents("view/$s");
397 if(! function_exists('get_markup_template')) {
398 function get_markup_template($s) {
400 $theme = current_theme();
402 if(file_exists("view/theme/$theme/$s"))
403 return file_get_contents("view/theme/$theme/$s");
404 elseif (x($a->theme_info,"extends") && file_exists("view/theme/".$a->theme_info["extends"]."/$s"))
405 return file_get_contents("view/theme/".$a->theme_info["extends"]."/$s");
407 return file_get_contents("view/$s");
415 // for html,xml parsing - let's say you've got
416 // an attribute foobar="class1 class2 class3"
417 // and you want to find out if it contains 'class3'.
418 // you can't use a normal sub string search because you
419 // might match 'notclass3' and a regex to do the job is
420 // possible but a bit complicated.
421 // pass the attribute string as $attr and the attribute you
422 // are looking for as $s - returns true if found, otherwise false
424 if(! function_exists('attribute_contains')) {
425 function attribute_contains($attr,$s) {
426 $a = explode(' ', $attr);
427 if(count($a) && in_array($s,$a))
432 if(! function_exists('logger')) {
433 function logger($msg,$level = 0) {
434 // turn off logger in install mode
438 if(($a->module == 'install') || (! ($db && $db->connected))) return;
440 $debugging = get_config('system','debugging');
441 $loglevel = intval(get_config('system','loglevel'));
442 $logfile = get_config('system','logfile');
444 if((! $debugging) || (! $logfile) || ($level > $loglevel))
447 @file_put_contents($logfile, datetime_convert() . ':' . session_id() . ' ' . $msg . "\n", FILE_APPEND);
452 if(! function_exists('activity_match')) {
453 function activity_match($haystack,$needle) {
454 if(($haystack === $needle) || ((basename($needle) === $haystack) && strstr($needle,NAMESPACE_ACTIVITY_SCHEMA)))
460 // Pull out all #hashtags and @person tags from $s;
461 // We also get @person@domain.com - which would make
462 // the regex quite complicated as tags can also
463 // end a sentence. So we'll run through our results
464 // and strip the period from any tags which end with one.
465 // Returns array of tags found, or empty array.
468 if(! function_exists('get_tags')) {
469 function get_tags($s) {
472 // ignore anything in a code block
474 $s = preg_replace('/\[code\](.*?)\[\/code\]/sm','',$s);
476 // Match full names against @tags including the space between first and last
477 // We will look these up afterward to see if they are full names or not recognisable.
479 if(preg_match_all('/(@[^ \x0D\x0A,:?]+ [^ \x0D\x0A@,:?]+)([ \x0D\x0A@,:?]|$)/',$s,$match)) {
480 foreach($match[1] as $mtch) {
481 if(strstr($mtch,"]")) {
482 // we might be inside a bbcode color tag - leave it alone
485 if(substr($mtch,-1,1) === '.')
486 $ret[] = substr($mtch,0,-1);
492 // Otherwise pull out single word tags. These can be @nickname, @first_last
495 if(preg_match_all('/([@#][^ \x0D\x0A,;:?]+)([ \x0D\x0A,;:?]|$)/',$s,$match)) {
496 foreach($match[1] as $mtch) {
497 if(strstr($mtch,"]")) {
498 // we might be inside a bbcode color tag - leave it alone
501 if(substr($mtch,-1,1) === '.')
502 $mtch = substr($mtch,0,-1);
503 // ignore strictly numeric tags like #1
504 if((strpos($mtch,'#') === 0) && ctype_digit(substr($mtch,1)))
506 // try not to catch url fragments
507 if(strpos($s,$mtch) && preg_match('/[a-zA-z0-9\/]/',substr($s,strpos($s,$mtch)-1,1)))
516 // quick and dirty quoted_printable encoding
518 if(! function_exists('qp')) {
520 return str_replace ("%","=",rawurlencode($s));
525 if(! function_exists('get_mentions')) {
526 function get_mentions($item) {
528 if(! strlen($item['tag']))
531 $arr = explode(',',$item['tag']);
532 foreach($arr as $x) {
534 if(preg_match('/@\[url=([^\]]*)\]/',$x,$matches)) {
535 $o .= "\t\t" . '<link rel="mentioned" href="' . $matches[1] . '" />' . "\r\n";
536 $o .= "\t\t" . '<link rel="ostatus:attention" href="' . $matches[1] . '" />' . "\r\n";
542 if(! function_exists('contact_block')) {
543 function contact_block() {
547 $shown = get_pconfig($a->profile['uid'],'system','display_friend_count');
553 if((! is_array($a->profile)) || ($a->profile['hide-friends']))
555 $r = q("SELECT COUNT(*) AS `total` FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 and `pending` = 0 AND `hidden` = 0",
556 intval($a->profile['uid'])
559 $total = intval($r[0]['total']);
562 $contacts = t('No contacts');
566 $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",
567 intval($a->profile['uid']),
571 $contacts = sprintf( tt('%d Contact','%d Contacts', $total),$total);
574 $micropro[] = micropro($rr,true,'mpfriend');
579 $tpl = get_markup_template('contact_block.tpl');
580 $o = replace_macros($tpl, array(
581 '$contacts' => $contacts,
582 '$nickname' => $a->profile['nickname'],
583 '$viewcontacts' => t('View Contacts'),
584 '$micropro' => $micropro,
587 $arr = array('contacts' => $r, 'output' => $o);
589 call_hooks('contact_block_end', $arr);
594 if(! function_exists('micropro')) {
595 function micropro($contact, $redirect = false, $class = '', $textmode = false) {
598 $class = ' ' . $class;
600 $url = $contact['url'];
606 $redirect_url = $a->get_baseurl() . '/redir/' . $contact['id'];
607 if(local_user() && ($contact['uid'] == local_user()) && ($contact['network'] === 'dfrn')) {
609 $url = $redirect_url;
610 $sparkle = ' sparkle';
615 $click = ((x($contact,'click')) ? ' onclick="' . $contact['click'] . '" ' : '');
619 return '<div class="contact-block-textdiv' . $class . '"><a class="contact-block-link' . $class . $sparkle
620 . (($click) ? ' fakelink' : '') . '" '
621 . (($redir) ? ' target="redir" ' : '')
622 . (($url) ? ' href="' . $url . '"' : '') . $click
623 . '" title="' . $contact['name'] . ' [' . $contact['url'] . ']" alt="' . $contact['name']
624 . '" >'. $contact['name'] . '</a></div>' . "\r\n";
627 return '<div class="contact-block-div' . $class . '"><a class="contact-block-link' . $class . $sparkle
628 . (($click) ? ' fakelink' : '') . '" '
629 . (($redir) ? ' target="redir" ' : '')
630 . (($url) ? ' href="' . $url . '"' : '') . $click . ' ><img class="contact-block-img' . $class . $sparkle . '" src="'
631 . $contact['micro'] . '" title="' . $contact['name'] . ' [' . $contact['url'] . ']" alt="' . $contact['name']
632 . '" /></a></div>' . "\r\n";
638 if(! function_exists('search')) {
639 function search($s,$id='search-box',$url='/search',$save = false) {
641 $o = '<div id="' . $id . '">';
642 $o .= '<form action="' . $a->get_baseurl((stristr($url,'network')) ? true : false) . $url . '" method="get" >';
643 $o .= '<input type="text" name="search" id="search-text" value="' . $s .'" />';
644 $o .= '<input type="submit" name="submit" id="search-submit" value="' . t('Search') . '" />';
646 $o .= '<input type="submit" name="save" id="search-save" value="' . t('Save') . '" />';
647 $o .= '</form></div>';
651 if(! function_exists('valid_email')) {
652 function valid_email($x){
653 if(preg_match('/^[_a-zA-Z0-9\-\+]+(\.[_a-zA-Z0-9\-\+]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)+$/',$x))
663 * Replace naked text hyperlink with HTML formatted hyperlink
667 if(! function_exists('linkify')) {
668 function linkify($s) {
669 $s = preg_replace("/(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\'\%\$\!\+]*)/", ' <a href="$1" target="external-link">$1</a>', $s);
670 $s = preg_replace("/\<(.*?)(src|href)=(.*?)\&\;(.*?)\>/ism",'<$1$2=$3&$4>',$s);
680 * Replaces text emoticons with graphical images
682 * @Parameter: string $s
686 * It is expected that this function will be called using HTML text.
687 * We will escape text between HTML pre and code blocks from being
690 * At a higher level, the bbcode [nosmile] tag can be used to prevent this
691 * function from being executed by the prepare_text() routine when preparing
692 * bbcode source for HTML display
696 if(! function_exists('smilies')) {
697 function smilies($s, $sample = false) {
701 if(intval(get_config('system','no_smilies'))
702 || (local_user() && intval(get_pconfig(local_user(),'system','no_smilies'))))
705 $s = preg_replace_callback('/<pre>(.*?)<\/pre>/ism','smile_encode',$s);
706 $s = preg_replace_callback('/<code>(.*?)<\/code>/ism','smile_encode',$s);
743 '<img src="' . $a->get_baseurl() . '/images/smiley-heart.gif" alt="<3" />',
744 '<img src="' . $a->get_baseurl() . '/images/smiley-brokenheart.gif" alt="</3" />',
745 '<img src="' . $a->get_baseurl() . '/images/smiley-brokenheart.gif" alt="<\\3" />',
746 '<img src="' . $a->get_baseurl() . '/images/smiley-smile.gif" alt=":-)" />',
747 '<img src="' . $a->get_baseurl() . '/images/smiley-wink.gif" alt=";-)" />',
748 '<img src="' . $a->get_baseurl() . '/images/smiley-frown.gif" alt=":-(" />',
749 '<img src="' . $a->get_baseurl() . '/images/smiley-tongue-out.gif" alt=":-P" />',
750 '<img src="' . $a->get_baseurl() . '/images/smiley-tongue-out.gif" alt=":-p" />',
751 '<img src="' . $a->get_baseurl() . '/images/smiley-kiss.gif" alt=":-\"" />',
752 '<img src="' . $a->get_baseurl() . '/images/smiley-kiss.gif" alt=":-\"" />',
753 '<img src="' . $a->get_baseurl() . '/images/smiley-kiss.gif" alt=":-x" />',
754 '<img src="' . $a->get_baseurl() . '/images/smiley-kiss.gif" alt=":-X" />',
755 '<img src="' . $a->get_baseurl() . '/images/smiley-laughing.gif" alt=":-D" />',
756 '<img src="' . $a->get_baseurl() . '/images/smiley-surprised.gif" alt="8-|" />',
757 '<img src="' . $a->get_baseurl() . '/images/smiley-surprised.gif" alt="8-O" />',
758 '<img src="' . $a->get_baseurl() . '/images/smiley-surprised.gif" alt=":-O" />',
759 '<img src="' . $a->get_baseurl() . '/images/smiley-thumbsup.gif" alt="\\o/" />',
760 '<img src="' . $a->get_baseurl() . '/images/smiley-Oo.gif" alt="o.O" />',
761 '<img src="' . $a->get_baseurl() . '/images/smiley-Oo.gif" alt="O.o" />',
762 '<img src="' . $a->get_baseurl() . '/images/smiley-cry.gif" alt=":\'(" />',
763 '<img src="' . $a->get_baseurl() . '/images/smiley-foot-in-mouth.gif" alt=":-!" />',
764 '<img src="' . $a->get_baseurl() . '/images/smiley-undecided.gif" alt=":-/" />',
765 '<img src="' . $a->get_baseurl() . '/images/smiley-embarassed.gif" alt=":-[" />',
766 '<img src="' . $a->get_baseurl() . '/images/smiley-cool.gif" alt="8-)" />',
767 '<img src="' . $a->get_baseurl() . '/images/beer_mug.gif" alt=":beer" />',
768 '<img src="' . $a->get_baseurl() . '/images/beer_mug.gif" alt=":homebrew" />',
769 '<img src="' . $a->get_baseurl() . '/images/coffee.gif" alt=":coffee" />',
770 '<img src="' . $a->get_baseurl() . '/images/smiley-facepalm.gif" alt=":facepalm" />',
771 '<a href="http://project.friendika.com">~friendika <img src="' . $a->get_baseurl() . '/images/friendika-16.png" alt="~friendika" /></a>',
772 '<a href="http://friendica.com">~friendica <img src="' . $a->get_baseurl() . '/images/friendica-16.png" alt="~friendica" /></a>'
775 $params = array('texts' => $texts, 'icons' => $icons, 'string' => $s);
776 call_hooks('smilie', $params);
779 $s = '<div class="smiley-sample">';
780 for($x = 0; $x < count($params['texts']); $x ++) {
781 $s .= '<dl><dt>' . $params['texts'][$x] . '</dt><dd>' . $params['icons'][$x] . '</dd></dl>';
785 $params['string'] = preg_replace_callback('/<(3+)/','preg_heart',$params['string']);
786 $s = str_replace($params['texts'],$params['icons'],$params['string']);
789 $s = preg_replace_callback('/<pre>(.*?)<\/pre>/ism','smile_decode',$s);
790 $s = preg_replace_callback('/<code>(.*?)<\/code>/ism','smile_decode',$s);
796 function smile_encode($m) {
797 return(str_replace($m[1],base64url_encode($m[1]),$m[0]));
800 function smile_decode($m) {
801 return(str_replace($m[1],base64url_decode($m[1]),$m[0]));
804 // expand <3333 to the correct number of hearts
806 function preg_heart($x) {
808 if(strlen($x[1]) == 1)
811 for($cnt = 0; $cnt < strlen($x[1]); $cnt ++)
812 $t .= '<img src="' . $a->get_baseurl() . '/images/smiley-heart.gif" alt="<3" />';
813 $r = str_replace($x[0],$t,$x[0]);
818 if(! function_exists('day_translate')) {
819 function day_translate($s) {
820 $ret = str_replace(array('Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'),
821 array( t('Monday'), t('Tuesday'), t('Wednesday'), t('Thursday'), t('Friday'), t('Saturday'), t('Sunday')),
824 $ret = str_replace(array('January','February','March','April','May','June','July','August','September','October','November','December'),
825 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')),
832 if(! function_exists('normalise_link')) {
833 function normalise_link($url) {
834 $ret = str_replace(array('https:','//www.'), array('http:','//'), $url);
835 return(rtrim($ret,'/'));
840 * Compare two URLs to see if they are the same, but ignore
841 * slight but hopefully insignificant differences such as if one
842 * is https and the other isn't, or if one is www.something and
843 * the other isn't - and also ignore case differences.
845 * Return true if the URLs match, otherwise false.
849 if(! function_exists('link_compare')) {
850 function link_compare($a,$b) {
851 if(strcasecmp(normalise_link($a),normalise_link($b)) === 0)
856 // Given an item array, convert the body element from bbcode to html and add smilie icons.
857 // If attach is true, also add icons for item attachments
860 if(! function_exists('prepare_body')) {
861 function prepare_body($item,$attach = false) {
864 call_hooks('prepare_body_init', $item);
866 $cache = get_config('system','itemcache');
868 if (($cache != '')) {
869 $cachefile = $cache."/".$item["guid"]."-".strtotime($item["edited"])."-".hash("crc32", $item['body']);
871 if (file_exists($cachefile))
872 $s = file_get_contents($cachefile);
874 $s = prepare_text($item['body']);
875 file_put_contents($cachefile, $s);
878 $s = prepare_text($item['body']);
880 $prep_arr = array('item' => $item, 'html' => $s);
881 call_hooks('prepare_body', $prep_arr);
882 $s = $prep_arr['html'];
888 $arr = explode(',',$item['attach']);
890 $s .= '<div class="body-attach">';
891 foreach($arr as $r) {
894 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"\[\/attach\]|',$r,$matches);
896 $icontype = strtolower(substr($matches[3],0,strpos($matches[3],'/')));
902 $icon = '<div class="attachtype icon s22 type-' . $icontype . '"></div>';
905 $icon = '<div class="attachtype icon s22 type-unkn"></div>';
908 $title = ((strlen(trim($matches[4]))) ? escape_tags(trim($matches[4])) : escape_tags($matches[1]));
909 $title .= ' ' . $matches[2] . ' ' . t('bytes');
911 $s .= '<a href="' . strip_tags($matches[1]) . '" title="' . $title . '" class="attachlink" target="external-link" >' . $icon . '</a>';
914 $s .= '<div class="clear"></div></div>';
917 $cnt = preg_match_all('/<(.*?)>/',$item['file'],$matches,PREG_SET_ORDER);
919 // logger('prepare_text: categories: ' . print_r($matches,true), LOGGER_DEBUG);
920 foreach($matches as $mtch) {
923 $x .= file_tag_decode($mtch[1]);
926 $s .= '<div class="categorytags"><span>' . t('Categories:') . ' </span>' . $x . '</div>';
932 $cnt = preg_match_all('/\[(.*?)\]/',$item['file'],$matches,PREG_SET_ORDER);
934 // logger('prepare_text: filed_under: ' . print_r($matches,true), LOGGER_DEBUG);
935 foreach($matches as $mtch) {
937 $x .= ' ';
938 $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>';
940 if(strlen($x) && (local_user() == $item['uid']))
941 $s .= '<div class="filesavetags"><span>' . t('Filed under:') . ' </span>' . $x . '</div>';
945 $spoilersearch = '<blockquote class="spoiler">';
947 // Remove line breaks before the spoiler
948 while ((strpos($s, "\n".$spoilersearch) !== false))
949 $s = str_replace("\n".$spoilersearch, $spoilersearch, $s);
950 while ((strpos($s, "<br />".$spoilersearch) !== false))
951 $s = str_replace("<br />".$spoilersearch, $spoilersearch, $s);
953 while ((strpos($s, $spoilersearch) !== false)) {
955 $pos = strpos($s, $spoilersearch);
956 $rnd = random_string(8);
957 $spoilerreplace = '<br /> <span id="spoiler-wrap-'.$rnd.'" style="white-space:nowrap;" class="fakelink" onclick="openClose(\'spoiler-'.$rnd.'\');">'.sprintf(t('Click to open/close')).'</span>'.
958 '<blockquote class="spoiler" id="spoiler-'.$rnd.'" style="display: none;">';
959 $s = substr($s, 0, $pos).$spoilerreplace.substr($s, $pos+strlen($spoilersearch));
962 // Look for quote with author
963 $authorsearch = '<blockquote class="author">';
965 while ((strpos($s, $authorsearch) !== false)) {
967 $pos = strpos($s, $authorsearch);
968 $rnd = random_string(8);
969 $authorreplace = '<br /> <span id="author-wrap-'.$rnd.'" style="white-space:nowrap;" class="fakelink" onclick="openClose(\'author-'.$rnd.'\');">'.sprintf(t('Click to open/close')).'</span>'.
970 '<blockquote class="author" id="author-'.$rnd.'" style="display: block;">';
971 $s = substr($s, 0, $pos).$authorreplace.substr($s, $pos+strlen($authorsearch));
974 $prep_arr = array('item' => $item, 'html' => $s);
975 call_hooks('prepare_body_final', $prep_arr);
977 return $prep_arr['html'];
981 // Given a text string, convert from bbcode to html and add smilie icons.
983 if(! function_exists('prepare_text')) {
984 function prepare_text($text) {
986 require_once('include/bbcode.php');
988 if(stristr($text,'[nosmile]'))
991 $s = smilies(bbcode($text));
998 * return atom link elements for all of our hubs
1001 if(! function_exists('feed_hublinks')) {
1002 function feed_hublinks() {
1004 $hub = get_config('system','huburl');
1008 $hubs = explode(',', $hub);
1010 foreach($hubs as $h) {
1014 $hubxml .= '<link rel="hub" href="' . xmlify($h) . '" />' . "\n" ;
1021 /* return atom link elements for salmon endpoints */
1023 if(! function_exists('feed_salmonlinks')) {
1024 function feed_salmonlinks($nick) {
1028 $salmon = '<link rel="salmon" href="' . xmlify($a->get_baseurl() . '/salmon/' . $nick) . '" />' . "\n" ;
1030 // old style links that status.net still needed as of 12/2010
1032 $salmon .= ' <link rel="http://salmon-protocol.org/ns/salmon-replies" href="' . xmlify($a->get_baseurl() . '/salmon/' . $nick) . '" />' . "\n" ;
1033 $salmon .= ' <link rel="http://salmon-protocol.org/ns/salmon-mention" href="' . xmlify($a->get_baseurl() . '/salmon/' . $nick) . '" />' . "\n" ;
1037 if(! function_exists('get_plink')) {
1038 function get_plink($item) {
1040 if (x($item,'plink') && (! $item['private'])){
1042 'href' => $item['plink'],
1043 'title' => t('link to source'),
1050 if(! function_exists('unamp')) {
1051 function unamp($s) {
1052 return str_replace('&', '&', $s);
1058 if(! function_exists('lang_selector')) {
1059 function lang_selector() {
1061 $o = '<div id="lang-select-icon" class="icon language" title="' . t('Select an alternate language') . '" onclick="openClose(\'language-selector\');" ></div>';
1062 $o .= '<div id="language-selector" style="display: none;" >';
1063 $o .= '<form action="#" method="post" ><select name="system_language" onchange="this.form.submit();" >';
1064 $langs = glob('view/*/strings.php');
1065 if(is_array($langs) && count($langs)) {
1067 if(! in_array('view/en/strings.php',$langs))
1068 $langs[] = 'view/en/';
1070 foreach($langs as $l) {
1072 $default_selected = ((! x($_SESSION,'language')) ? ' selected="selected" ' : '');
1073 $o .= '<option value="" ' . $default_selected . '>' . t('default') . '</option>';
1077 $ll = substr($ll,0,strrpos($ll,'/'));
1078 $selected = (($ll === $lang && (x($_SESSION, 'language'))) ? ' selected="selected" ' : '');
1079 $o .= '<option value="' . $ll . '"' . $selected . '>' . $ll . '</option>';
1082 $o .= '</select></form></div>';
1087 if(! function_exists('return_bytes')) {
1088 function return_bytes ($size_str) {
1089 switch (substr ($size_str, -1))
1091 case 'M': case 'm': return (int)$size_str * 1048576;
1092 case 'K': case 'k': return (int)$size_str * 1024;
1093 case 'G': case 'g': return (int)$size_str * 1073741824;
1094 default: return $size_str;
1098 function generate_user_guid() {
1101 $guid = random_string(16);
1102 $x = q("SELECT `uid` FROM `user` WHERE `guid` = '%s' LIMIT 1",
1107 } while ($found == true );
1113 function base64url_encode($s, $strip_padding = false) {
1115 $s = strtr(base64_encode($s),'+/','-_');
1118 $s = str_replace('=','',$s);
1123 function base64url_decode($s) {
1126 logger('base64url_decode: illegal input: ' . print_r(debug_backtrace(), true));
1131 * // Placeholder for new rev of salmon which strips base64 padding.
1132 * // PHP base64_decode handles the un-padded input without requiring this step
1133 * // Uncomment if you find you need it.
1136 * if(! strpos($s,'=')) {
1146 return base64_decode(strtr($s,'-_','+/'));
1150 if (!function_exists('str_getcsv')) {
1151 function str_getcsv($input, $delimiter = ',', $enclosure = '"', $escape = '\\', $eol = '\n') {
1152 if (is_string($input) && !empty($input)) {
1154 $tmp = preg_split("/".$eol."/",$input);
1155 if (is_array($tmp) && !empty($tmp)) {
1156 while (list($line_num, $line) = each($tmp)) {
1157 if (preg_match("/".$escape.$enclosure."/",$line)) {
1158 while ($strlen = strlen($line)) {
1159 $pos_delimiter = strpos($line,$delimiter);
1160 $pos_enclosure_start = strpos($line,$enclosure);
1162 is_int($pos_delimiter) && is_int($pos_enclosure_start)
1163 && ($pos_enclosure_start < $pos_delimiter)
1165 $enclosed_str = substr($line,1);
1166 $pos_enclosure_end = strpos($enclosed_str,$enclosure);
1167 $enclosed_str = substr($enclosed_str,0,$pos_enclosure_end);
1168 $output[$line_num][] = $enclosed_str;
1169 $offset = $pos_enclosure_end+3;
1171 if (empty($pos_delimiter) && empty($pos_enclosure_start)) {
1172 $output[$line_num][] = substr($line,0);
1173 $offset = strlen($line);
1175 $output[$line_num][] = substr($line,0,$pos_delimiter);
1177 !empty($pos_enclosure_start)
1178 && ($pos_enclosure_start < $pos_delimiter)
1180 ?$pos_enclosure_start
1184 $line = substr($line,$offset);
1187 $line = preg_split("/".$delimiter."/",$line);
1190 * Validating against pesky extra line breaks creating false rows.
1192 if (is_array($line) && !empty($line[0])) {
1193 $output[$line_num] = $line;
1207 function cleardiv() {
1208 return '<div class="clear"></div>';
1212 function bb_translate_video($s) {
1215 $r = preg_match_all("/\[video\](.*?)\[\/video\]/ism",$s,$matches,PREG_SET_ORDER);
1217 foreach($matches as $mtch) {
1218 if((stristr($mtch[1],'youtube')) || (stristr($mtch[1],'youtu.be')))
1219 $s = str_replace($mtch[0],'[youtube]' . $mtch[1] . '[/youtube]',$s);
1220 elseif(stristr($mtch[1],'vimeo'))
1221 $s = str_replace($mtch[0],'[vimeo]' . $mtch[1] . '[/vimeo]',$s);
1227 function html2bb_video($s) {
1229 $s = preg_replace('#<object[^>]+>(.*?)https+://www.youtube.com/((?:v|cp)/[A-Za-z0-9\-_=]+)(.*?)</object>#ism',
1230 '[youtube]$2[/youtube]', $s);
1232 $s = preg_replace('#<iframe[^>](.*?)https+://www.youtube.com/embed/([A-Za-z0-9\-_=]+)(.*?)</iframe>#ism',
1233 '[youtube]$2[/youtube]', $s);
1235 $s = preg_replace('#<iframe[^>](.*?)https+://player.vimeo.com/video/([0-9]+)(.*?)</iframe>#ism',
1236 '[vimeo]$2[/vimeo]', $s);
1242 * apply xmlify() to all values of array $val, recursively
1244 function array_xmlify($val){
1245 if (is_bool($val)) return $val?"true":"false";
1246 if (is_array($val)) return array_map('array_xmlify', $val);
1247 return xmlify((string) $val);
1251 function reltoabs($text, $base)
1256 $base = rtrim($base,'/');
1258 $base2 = $base . "/";
1261 $pattern = "/<a([^>]*) href=\"(?!http|https|\/)([^\"]*)\"/";
1262 $replace = "<a\${1} href=\"" . $base2 . "\${2}\"";
1263 $text = preg_replace($pattern, $replace, $text);
1265 $pattern = "/<a([^>]*) href=\"(?!http|https)([^\"]*)\"/";
1266 $replace = "<a\${1} href=\"" . $base . "\${2}\"";
1267 $text = preg_replace($pattern, $replace, $text);
1270 $pattern = "/<img([^>]*) src=\"(?!http|https|\/)([^\"]*)\"/";
1271 $replace = "<img\${1} src=\"" . $base2 . "\${2}\"";
1272 $text = preg_replace($pattern, $replace, $text);
1274 $pattern = "/<img([^>]*) src=\"(?!http|https)([^\"]*)\"/";
1275 $replace = "<img\${1} src=\"" . $base . "\${2}\"";
1276 $text = preg_replace($pattern, $replace, $text);
1283 function item_post_type($item) {
1284 if(intval($item['event-id']))
1286 if(strlen($item['resource-id']))
1288 if(strlen($item['verb']) && $item['verb'] !== ACTIVITY_POST)
1289 return t('activity');
1290 if($item['id'] != $item['parent'])
1291 return t('comment');
1295 // post categories and "save to file" use the same item.file table for storage.
1296 // We will differentiate the different uses by wrapping categories in angle brackets
1297 // and save to file categories in square brackets.
1298 // To do this we need to escape these characters if they appear in our tag.
1300 function file_tag_encode($s) {
1301 return str_replace(array('<','>','[',']'),array('%3c','%3e','%5b','%5d'),$s);
1304 function file_tag_decode($s) {
1305 return str_replace(array('%3c','%3e','%5b','%5d'),array('<','>','[',']'),$s);
1308 function file_tag_file_query($table,$s,$type = 'file') {
1310 $str = preg_quote( '[' . file_tag_encode($s) . ']' );
1312 $str = preg_quote( '<' . file_tag_encode($s) . '>' );
1313 return " AND " . (($table) ? dbesc($table) . '.' : '') . "file regexp '" . dbesc($str) . "' ";
1316 function file_tag_save_file($uid,$item,$file) {
1320 $r = q("select file from item where id = %d and uid = %d limit 1",
1325 if(! stristr($r[0]['file'],'[' . file_tag_encode($file) . ']'))
1326 q("update item set file = '%s' where id = %d and uid = %d limit 1",
1327 dbesc($r[0]['file'] . '[' . file_tag_encode($file) . ']'),
1331 $saved = get_pconfig($uid,'system','filetags');
1332 if((! strlen($saved)) || (! stristr($saved,'[' . file_tag_encode($file) . ']')))
1333 set_pconfig($uid,'system','filetags',$saved . '[' . file_tag_encode($file) . ']');
1334 info( t('Item filed') );
1339 function file_tag_unsave_file($uid,$item,$file) {
1344 $pattern = '[' . file_tag_encode($file) . ']' ;
1346 $r = q("select file from item where id = %d and uid = %d limit 1",
1353 q("update item set file = '%s' where id = %d and uid = %d limit 1",
1354 dbesc(str_replace($pattern,'',$r[0]['file'])),
1359 $r = q("select file from item where uid = %d " . file_tag_file_query('item',$file),
1364 $saved = get_pconfig($uid,'system','filetags');
1365 set_pconfig($uid,'system','filetags',str_replace($pattern,'',$saved));
1370 function normalise_openid($s) {
1371 return trim(str_replace(array('http://','https://'),array('',''),$s),'/');
1375 function undo_post_tagging($s) {
1377 $cnt = preg_match_all('/([@#])\[url=(.*?)\](.*?)\[\/url\]/ism',$s,$matches,PREG_SET_ORDER);
1379 foreach($matches as $mtch) {
1380 $s = str_replace($mtch[0], $mtch[1] . $mtch[3],$s);