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) {
86 $vowels = array('a','a','ai','au','e','e','e','ee','ea','i','ie','o','ou','u');
105 's','sc','sh','sm','sp','st',
113 $midcons = array('ck','ct','gn','ld','lf','lm','lt','mb','mm', 'mn','mp',
114 'nd','ng','nk','nt','rn','rp','rt');
116 $noend = array('bl', 'br', 'cl','cr','dr','fl','fr','gl','gr',
117 'kh', 'kl','kr','mn','pl','pr','rh','tr','qu','wh');
119 $start = mt_rand(0,2);
127 for ($x = 0; $x < $len; $x ++) {
128 $r = mt_rand(0,count($table) - 1);
131 if($table == $vowels)
132 $table = array_merge($cons,$midcons);
138 $word = substr($word,0,$len);
140 foreach($noend as $noe) {
141 if((strlen($word) > 2) && (substr($word,-2) == $noe)) {
142 $word = substr($word,0,-1);
146 if(substr($word,-1) == 'q')
147 $word = substr($word,0,-1);
152 // escape text ($str) for XML transport
153 // returns escaped text.
155 if(! function_exists('xmlify')) {
156 function xmlify($str) {
159 for($x = 0; $x < mb_strlen($str); $x ++) {
189 $buffer = trim($buffer);
194 // pass xml escaped text ($s), returns unescaped text
196 if(! function_exists('unxmlify')) {
197 function unxmlify($s) {
198 $ret = str_replace('&','&', $s);
199 $ret = str_replace(array('<','>','"','''),array('<','>','"',"'"),$ret);
203 // convenience wrapper, reverse the operation "bin2hex"
205 if(! function_exists('hex2bin')) {
206 function hex2bin($s) {
207 if(! (is_string($s) && strlen($s)))
210 if(! ctype_xdigit($s)) {
214 return(pack("H*",$s));
217 // Automatic pagination.
218 // To use, get the count of total items.
219 // Then call $a->set_pager_total($number_items);
220 // Optionally call $a->set_pager_itemspage($n) to the number of items to display on each page
221 // Then call paginate($a) after the end of the display loop to insert the pager block on the page
222 // (assuming there are enough items to paginate).
223 // When using with SQL, the setting LIMIT %d, %d => $a->pager['start'],$a->pager['itemspage']
224 // will limit the results to the correct items for the current page.
225 // The actual page handling is then accomplished at the application layer.
227 if(! function_exists('paginate')) {
228 function paginate(&$a) {
230 $stripped = preg_replace('/(&page=[0-9]*)/','',$a->query_string);
232 // $stripped = preg_replace('/&zrl=(.*?)([\?&]|$)/ism','',$stripped);
234 $stripped = str_replace('q=','',$stripped);
235 $stripped = trim($stripped,'/');
236 $pagenum = $a->pager['page'];
237 $url = $a->get_baseurl() . '/' . $stripped;
240 if($a->pager['total'] > $a->pager['itemspage']) {
241 $o .= '<div class="pager">';
242 if($a->pager['page'] != 1)
243 $o .= '<span class="pager_prev">'."<a href=\"$url".'&page='.($a->pager['page'] - 1).'">' . t('prev') . '</a></span> ';
245 $o .= "<span class=\"pager_first\"><a href=\"$url"."&page=1\">" . t('first') . "</a></span> ";
247 $numpages = $a->pager['total'] / $a->pager['itemspage'];
250 $numstop = $numpages;
253 $numstart = (($pagenum > 7) ? ($pagenum - 7) : 1);
254 $numstop = (($pagenum > ($numpages - 7)) ? $numpages : ($numstart + 14));
257 for($i = $numstart; $i <= $numstop; $i++){
258 if($i == $a->pager['page'])
259 $o .= '<span class="pager_current">'.(($i < 10) ? ' '.$i : $i);
261 $o .= "<span class=\"pager_n\"><a href=\"$url"."&page=$i\">".(($i < 10) ? ' '.$i : $i)."</a>";
265 if(($a->pager['total'] % $a->pager['itemspage']) != 0) {
266 if($i == $a->pager['page'])
267 $o .= '<span class="pager_current">'.(($i < 10) ? ' '.$i : $i);
269 $o .= "<span class=\"pager_n\"><a href=\"$url"."&page=$i\">".(($i < 10) ? ' '.$i : $i)."</a>";
273 $lastpage = (($numpages > intval($numpages)) ? intval($numpages)+1 : $numpages);
274 $o .= "<span class=\"pager_last\"><a href=\"$url"."&page=$lastpage\">" . t('last') . "</a></span> ";
276 if(($a->pager['total'] - ($a->pager['itemspage'] * $a->pager['page'])) > 0)
277 $o .= '<span class="pager_next">'."<a href=\"$url"."&page=".($a->pager['page'] + 1).'">' . t('next') . '</a></span>';
278 $o .= '</div>'."\r\n";
283 // Turn user/group ACLs stored as angle bracketed text into arrays
285 if(! function_exists('expand_acl')) {
286 function expand_acl($s) {
287 // turn string array of angle-bracketed elements into numeric array
288 // e.g. "<1><2><3>" => array(1,2,3);
292 $t = str_replace('<','',$s);
293 $a = explode('>',$t);
296 $ret[] = intval($aa);
302 // Used to wrap ACL elements in angle brackets for storage
304 if(! function_exists('sanitise_acl')) {
305 function sanitise_acl(&$item) {
307 $item = '<' . intval(notags(trim($item))) . '>';
313 // Convert an ACL array to a storable string
315 if(! function_exists('perms2str')) {
316 function perms2str($p) {
320 array_walk($tmp,'sanitise_acl');
321 $ret = implode('',$tmp);
326 // generate a guaranteed unique (for this domain) item ID for ATOM
327 // safe from birthday paradox
329 if(! function_exists('item_new_uri')) {
330 function item_new_uri($hostname,$uid) {
334 $hash = random_string();
336 $uri = "urn:X-dfrn:" . $hostname . ':' . $uid . ':' . $hash;
338 $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' LIMIT 1",
342 } while($dups == true);
346 // Generate a guaranteed unique photo ID.
347 // safe from birthday paradox
349 if(! function_exists('photo_new_resource')) {
350 function photo_new_resource() {
354 $resource = hash('md5',uniqid(mt_rand(),true));
355 $r = q("SELECT `id` FROM `photo` WHERE `resource-id` = '%s' LIMIT 1",
360 } while($found == true);
365 // wrapper to load a view template, checking for alternate
366 // languages before falling back to the default
368 // obsolete, deprecated.
370 if(! function_exists('load_view_file')) {
371 function load_view_file($s) {
377 if(file_exists("$d/$lang/$b"))
378 return file_get_contents("$d/$lang/$b");
380 $theme = current_theme();
382 if(file_exists("$d/theme/$theme/$b"))
383 return file_get_contents("$d/theme/$theme/$b");
385 return file_get_contents($s);
388 if(! function_exists('get_intltext_template')) {
389 function get_intltext_template($s) {
395 if(file_exists("view/$lang/$s"))
396 return file_get_contents("view/$lang/$s");
397 elseif(file_exists("view/en/$s"))
398 return file_get_contents("view/en/$s");
400 return file_get_contents("view/$s");
403 if(! function_exists('get_markup_template')) {
404 function get_markup_template($s) {
406 $theme = current_theme();
408 if(file_exists("view/theme/$theme/$s"))
409 return file_get_contents("view/theme/$theme/$s");
410 elseif (x($a->theme_info,"extends") && file_exists("view/theme/".$a->theme_info["extends"]."/$s"))
411 return file_get_contents("view/theme/".$a->theme_info["extends"]."/$s");
413 return file_get_contents("view/$s");
421 // for html,xml parsing - let's say you've got
422 // an attribute foobar="class1 class2 class3"
423 // and you want to find out if it contains 'class3'.
424 // you can't use a normal sub string search because you
425 // might match 'notclass3' and a regex to do the job is
426 // possible but a bit complicated.
427 // pass the attribute string as $attr and the attribute you
428 // are looking for as $s - returns true if found, otherwise false
430 if(! function_exists('attribute_contains')) {
431 function attribute_contains($attr,$s) {
432 $a = explode(' ', $attr);
433 if(count($a) && in_array($s,$a))
438 if(! function_exists('logger')) {
439 function logger($msg,$level = 0) {
440 // turn off logger in install mode
444 if(($a->module == 'install') || (! ($db && $db->connected))) return;
446 $debugging = get_config('system','debugging');
447 $loglevel = intval(get_config('system','loglevel'));
448 $logfile = get_config('system','logfile');
450 if((! $debugging) || (! $logfile) || ($level > $loglevel))
453 @file_put_contents($logfile, datetime_convert() . ':' . session_id() . ' ' . $msg . "\n", FILE_APPEND);
458 if(! function_exists('activity_match')) {
459 function activity_match($haystack,$needle) {
460 if(($haystack === $needle) || ((basename($needle) === $haystack) && strstr($needle,NAMESPACE_ACTIVITY_SCHEMA)))
466 // Pull out all #hashtags and @person tags from $s;
467 // We also get @person@domain.com - which would make
468 // the regex quite complicated as tags can also
469 // end a sentence. So we'll run through our results
470 // and strip the period from any tags which end with one.
471 // Returns array of tags found, or empty array.
474 if(! function_exists('get_tags')) {
475 function get_tags($s) {
478 // ignore anything in a code block
480 $s = preg_replace('/\[code\](.*?)\[\/code\]/sm','',$s);
482 // Match full names against @tags including the space between first and last
483 // We will look these up afterward to see if they are full names or not recognisable.
485 if(preg_match_all('/(@[^ \x0D\x0A,:?]+ [^ \x0D\x0A@,:?]+)([ \x0D\x0A@,:?]|$)/',$s,$match)) {
486 foreach($match[1] as $mtch) {
487 if(strstr($mtch,"]")) {
488 // we might be inside a bbcode color tag - leave it alone
491 if(substr($mtch,-1,1) === '.')
492 $ret[] = substr($mtch,0,-1);
498 // Otherwise pull out single word tags. These can be @nickname, @first_last
501 if(preg_match_all('/([@#][^ \x0D\x0A,;:?]+)([ \x0D\x0A,;:?]|$)/',$s,$match)) {
502 foreach($match[1] as $mtch) {
503 if(strstr($mtch,"]")) {
504 // we might be inside a bbcode color tag - leave it alone
507 if(substr($mtch,-1,1) === '.')
508 $mtch = substr($mtch,0,-1);
509 // ignore strictly numeric tags like #1
510 if((strpos($mtch,'#') === 0) && ctype_digit(substr($mtch,1)))
512 // try not to catch url fragments
513 if(strpos($s,$mtch) && preg_match('/[a-zA-z0-9\/]/',substr($s,strpos($s,$mtch)-1,1)))
522 // quick and dirty quoted_printable encoding
524 if(! function_exists('qp')) {
526 return str_replace ("%","=",rawurlencode($s));
531 if(! function_exists('get_mentions')) {
532 function get_mentions($item) {
534 if(! strlen($item['tag']))
537 $arr = explode(',',$item['tag']);
538 foreach($arr as $x) {
540 if(preg_match('/@\[url=([^\]]*)\]/',$x,$matches)) {
541 $o .= "\t\t" . '<link rel="mentioned" href="' . $matches[1] . '" />' . "\r\n";
542 $o .= "\t\t" . '<link rel="ostatus:attention" href="' . $matches[1] . '" />' . "\r\n";
548 if(! function_exists('contact_block')) {
549 function contact_block() {
553 $shown = get_pconfig($a->profile['uid'],'system','display_friend_count');
559 if((! is_array($a->profile)) || ($a->profile['hide-friends']))
561 $r = q("SELECT COUNT(*) AS `total` FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 and `pending` = 0 AND `hidden` = 0 AND `archive` = 0",
562 intval($a->profile['uid'])
565 $total = intval($r[0]['total']);
568 $contacts = t('No contacts');
572 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 and `pending` = 0 AND `hidden` = 0 AND `archive` = 0 ORDER BY RAND() LIMIT %d",
573 intval($a->profile['uid']),
577 $contacts = sprintf( tt('%d Contact','%d Contacts', $total),$total);
580 $micropro[] = micropro($rr,true,'mpfriend');
585 $tpl = get_markup_template('contact_block.tpl');
586 $o = replace_macros($tpl, array(
587 '$contacts' => $contacts,
588 '$nickname' => $a->profile['nickname'],
589 '$viewcontacts' => t('View Contacts'),
590 '$micropro' => $micropro,
593 $arr = array('contacts' => $r, 'output' => $o);
595 call_hooks('contact_block_end', $arr);
600 if(! function_exists('micropro')) {
601 function micropro($contact, $redirect = false, $class = '', $textmode = false) {
604 $class = ' ' . $class;
606 $url = $contact['url'];
612 $redirect_url = $a->get_baseurl() . '/redir/' . $contact['id'];
613 if(local_user() && ($contact['uid'] == local_user()) && ($contact['network'] === 'dfrn')) {
615 $url = $redirect_url;
616 $sparkle = ' sparkle';
621 $click = ((x($contact,'click')) ? ' onclick="' . $contact['click'] . '" ' : '');
625 return '<div class="contact-block-textdiv' . $class . '"><a class="contact-block-link' . $class . $sparkle
626 . (($click) ? ' fakelink' : '') . '" '
627 . (($redir) ? ' target="redir" ' : '')
628 . (($url) ? ' href="' . $url . '"' : '') . $click
629 . '" title="' . $contact['name'] . ' [' . $contact['url'] . ']" alt="' . $contact['name']
630 . '" >'. $contact['name'] . '</a></div>' . "\r\n";
633 return '<div class="contact-block-div' . $class . '"><a class="contact-block-link' . $class . $sparkle
634 . (($click) ? ' fakelink' : '') . '" '
635 . (($redir) ? ' target="redir" ' : '')
636 . (($url) ? ' href="' . $url . '"' : '') . $click . ' ><img class="contact-block-img' . $class . $sparkle . '" src="'
637 . $contact['micro'] . '" title="' . $contact['name'] . ' [' . $contact['url'] . ']" alt="' . $contact['name']
638 . '" /></a></div>' . "\r\n";
644 if(! function_exists('search')) {
645 function search($s,$id='search-box',$url='/search',$save = false) {
647 $o = '<div id="' . $id . '">';
648 $o .= '<form action="' . $a->get_baseurl((stristr($url,'network')) ? true : false) . $url . '" method="get" >';
649 $o .= '<input type="text" name="search" id="search-text" value="' . $s .'" />';
650 $o .= '<input type="submit" name="submit" id="search-submit" value="' . t('Search') . '" />';
652 $o .= '<input type="submit" name="save" id="search-save" value="' . t('Save') . '" />';
653 $o .= '</form></div>';
657 if(! function_exists('valid_email')) {
658 function valid_email($x){
659 if(preg_match('/^[_a-zA-Z0-9\-\+]+(\.[_a-zA-Z0-9\-\+]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)+$/',$x))
669 * Replace naked text hyperlink with HTML formatted hyperlink
673 if(! function_exists('linkify')) {
674 function linkify($s) {
675 $s = preg_replace("/(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\'\%\$\!\+]*)/", ' <a href="$1" target="external-link">$1</a>', $s);
676 $s = preg_replace("/\<(.*?)(src|href)=(.*?)\&\;(.*?)\>/ism",'<$1$2=$3&$4>',$s);
686 * Replaces text emoticons with graphical images
688 * @Parameter: string $s
692 * It is expected that this function will be called using HTML text.
693 * We will escape text between HTML pre and code blocks from being
696 * At a higher level, the bbcode [nosmile] tag can be used to prevent this
697 * function from being executed by the prepare_text() routine when preparing
698 * bbcode source for HTML display
702 if(! function_exists('smilies')) {
703 function smilies($s, $sample = false) {
707 if(intval(get_config('system','no_smilies'))
708 || (local_user() && intval(get_pconfig(local_user(),'system','no_smilies'))))
711 $s = preg_replace_callback('/<pre>(.*?)<\/pre>/ism','smile_encode',$s);
712 $s = preg_replace_callback('/<code>(.*?)<\/code>/ism','smile_encode',$s);
751 '<img src="' . $a->get_baseurl() . '/images/smiley-heart.gif" alt="<3" />',
752 '<img src="' . $a->get_baseurl() . '/images/smiley-brokenheart.gif" alt="</3" />',
753 '<img src="' . $a->get_baseurl() . '/images/smiley-brokenheart.gif" alt="<\\3" />',
754 '<img src="' . $a->get_baseurl() . '/images/smiley-smile.gif" alt=":-)" />',
755 '<img src="' . $a->get_baseurl() . '/images/smiley-wink.gif" alt=";-)" />',
756 '<img src="' . $a->get_baseurl() . '/images/smiley-frown.gif" alt=":-(" />',
757 '<img src="' . $a->get_baseurl() . '/images/smiley-tongue-out.gif" alt=":-P" />',
758 '<img src="' . $a->get_baseurl() . '/images/smiley-tongue-out.gif" alt=":-p" />',
759 '<img src="' . $a->get_baseurl() . '/images/smiley-kiss.gif" alt=":-\"" />',
760 '<img src="' . $a->get_baseurl() . '/images/smiley-kiss.gif" alt=":-\"" />',
761 '<img src="' . $a->get_baseurl() . '/images/smiley-kiss.gif" alt=":-x" />',
762 '<img src="' . $a->get_baseurl() . '/images/smiley-kiss.gif" alt=":-X" />',
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-Oo.gif" alt="o_O" />',
771 '<img src="' . $a->get_baseurl() . '/images/smiley-Oo.gif" alt="O_o" />',
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 '<a href="http://project.friendika.com">~friendika <img src="' . $a->get_baseurl() . '/images/friendika-16.png" alt="~friendika" /></a>',
782 '<a href="http://friendica.com">~friendica <img src="' . $a->get_baseurl() . '/images/friendica-16.png" alt="~friendica" /></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) {
874 call_hooks('prepare_body_init', $item);
876 $cache = get_config('system','itemcache');
878 if (($cache != '')) {
879 $cachefile = $cache."/".$item["guid"]."-".strtotime($item["edited"])."-".hash("crc32", $item['body']);
881 if (file_exists($cachefile))
882 $s = file_get_contents($cachefile);
884 $s = prepare_text($item['body']);
885 file_put_contents($cachefile, $s);
888 $s = prepare_text($item['body']);
890 $prep_arr = array('item' => $item, 'html' => $s);
891 call_hooks('prepare_body', $prep_arr);
892 $s = $prep_arr['html'];
898 $arr = explode(',',$item['attach']);
900 $s .= '<div class="body-attach">';
901 foreach($arr as $r) {
904 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"\[\/attach\]|',$r,$matches);
906 $icontype = strtolower(substr($matches[3],0,strpos($matches[3],'/')));
912 $icon = '<div class="attachtype icon s22 type-' . $icontype . '"></div>';
915 $icon = '<div class="attachtype icon s22 type-unkn"></div>';
918 $title = ((strlen(trim($matches[4]))) ? escape_tags(trim($matches[4])) : escape_tags($matches[1]));
919 $title .= ' ' . $matches[2] . ' ' . t('bytes');
921 $s .= '<a href="' . strip_tags($matches[1]) . '" title="' . $title . '" class="attachlink" target="external-link" >' . $icon . '</a>';
924 $s .= '<div class="clear"></div></div>';
927 $cnt = preg_match_all('/<(.*?)>/',$item['file'],$matches,PREG_SET_ORDER);
929 // logger('prepare_text: categories: ' . print_r($matches,true), LOGGER_DEBUG);
930 foreach($matches as $mtch) {
933 $x .= xmlify(file_tag_decode($mtch[1]));
936 $s .= '<div class="categorytags"><span>' . t('Categories:') . ' </span>' . $x . '</div>';
942 $cnt = preg_match_all('/\[(.*?)\]/',$item['file'],$matches,PREG_SET_ORDER);
944 // logger('prepare_text: filed_under: ' . print_r($matches,true), LOGGER_DEBUG);
945 foreach($matches as $mtch) {
947 $x .= ' ';
948 $x .= xmlify(file_tag_decode($mtch[1])) . ' <a href="' . $a->get_baseurl() . '/filerm/' . $item['id'] . '?f=&term=' . xmlify(file_tag_decode($mtch[1])) . '" title="' . t('remove') . '" >' . t('[remove]') . '</a>';
950 if(strlen($x) && (local_user() == $item['uid']))
951 $s .= '<div class="filesavetags"><span>' . t('Filed under:') . ' </span>' . $x . '</div>';
955 $spoilersearch = '<blockquote class="spoiler">';
957 // Remove line breaks before the spoiler
958 while ((strpos($s, "\n".$spoilersearch) !== false))
959 $s = str_replace("\n".$spoilersearch, $spoilersearch, $s);
960 while ((strpos($s, "<br />".$spoilersearch) !== false))
961 $s = str_replace("<br />".$spoilersearch, $spoilersearch, $s);
963 while ((strpos($s, $spoilersearch) !== false)) {
965 $pos = strpos($s, $spoilersearch);
966 $rnd = random_string(8);
967 $spoilerreplace = '<br /> <span id="spoiler-wrap-'.$rnd.'" style="white-space:nowrap;" class="fakelink" onclick="openClose(\'spoiler-'.$rnd.'\');">'.sprintf(t('Click to open/close')).'</span>'.
968 '<blockquote class="spoiler" id="spoiler-'.$rnd.'" style="display: none;">';
969 $s = substr($s, 0, $pos).$spoilerreplace.substr($s, $pos+strlen($spoilersearch));
972 // Look for quote with author
973 $authorsearch = '<blockquote class="author">';
975 while ((strpos($s, $authorsearch) !== false)) {
977 $pos = strpos($s, $authorsearch);
978 $rnd = random_string(8);
979 $authorreplace = '<br /> <span id="author-wrap-'.$rnd.'" style="white-space:nowrap;" class="fakelink" onclick="openClose(\'author-'.$rnd.'\');">'.sprintf(t('Click to open/close')).'</span>'.
980 '<blockquote class="author" id="author-'.$rnd.'" style="display: block;">';
981 $s = substr($s, 0, $pos).$authorreplace.substr($s, $pos+strlen($authorsearch));
984 $prep_arr = array('item' => $item, 'html' => $s);
985 call_hooks('prepare_body_final', $prep_arr);
987 return $prep_arr['html'];
991 // Given a text string, convert from bbcode to html and add smilie icons.
993 if(! function_exists('prepare_text')) {
994 function prepare_text($text) {
996 require_once('include/bbcode.php');
998 if(stristr($text,'[nosmile]'))
1001 $s = smilies(bbcode($text));
1008 * return atom link elements for all of our hubs
1011 if(! function_exists('feed_hublinks')) {
1012 function feed_hublinks() {
1014 $hub = get_config('system','huburl');
1018 $hubs = explode(',', $hub);
1020 foreach($hubs as $h) {
1024 $hubxml .= '<link rel="hub" href="' . xmlify($h) . '" />' . "\n" ;
1031 /* return atom link elements for salmon endpoints */
1033 if(! function_exists('feed_salmonlinks')) {
1034 function feed_salmonlinks($nick) {
1038 $salmon = '<link rel="salmon" href="' . xmlify($a->get_baseurl() . '/salmon/' . $nick) . '" />' . "\n" ;
1040 // old style links that status.net still needed as of 12/2010
1042 $salmon .= ' <link rel="http://salmon-protocol.org/ns/salmon-replies" href="' . xmlify($a->get_baseurl() . '/salmon/' . $nick) . '" />' . "\n" ;
1043 $salmon .= ' <link rel="http://salmon-protocol.org/ns/salmon-mention" href="' . xmlify($a->get_baseurl() . '/salmon/' . $nick) . '" />' . "\n" ;
1047 if(! function_exists('get_plink')) {
1048 function get_plink($item) {
1050 if (x($item,'plink') && (! $item['private'])){
1052 'href' => $item['plink'],
1053 'title' => t('link to source'),
1060 if(! function_exists('unamp')) {
1061 function unamp($s) {
1062 return str_replace('&', '&', $s);
1068 if(! function_exists('lang_selector')) {
1069 function lang_selector() {
1072 $langs = glob('view/*/strings.php');
1074 $lang_options = array();
1077 if(is_array($langs) && count($langs)) {
1079 if(! in_array('view/en/strings.php',$langs))
1080 $langs[] = 'view/en/';
1082 foreach($langs as $l) {
1084 $lang_options[""] = t('default');
1088 $ll = substr($ll,0,strrpos($ll,'/'));
1089 $selected = (($ll === $lang && (x($_SESSION, 'language'))) ? $ll : $selected);
1090 $lang_options[$ll]=$ll;
1094 $tpl = get_markup_template("lang_selector.tpl");
1095 $o = replace_macros($tpl, array(
1096 '$title' => t('Select an alternate language'),
1097 '$langs' => array($lang_options, $selected),
1104 if(! function_exists('return_bytes')) {
1105 function return_bytes ($size_str) {
1106 switch (substr ($size_str, -1))
1108 case 'M': case 'm': return (int)$size_str * 1048576;
1109 case 'K': case 'k': return (int)$size_str * 1024;
1110 case 'G': case 'g': return (int)$size_str * 1073741824;
1111 default: return $size_str;
1115 function generate_user_guid() {
1118 $guid = random_string(16);
1119 $x = q("SELECT `uid` FROM `user` WHERE `guid` = '%s' LIMIT 1",
1124 } while ($found == true );
1130 function base64url_encode($s, $strip_padding = false) {
1132 $s = strtr(base64_encode($s),'+/','-_');
1135 $s = str_replace('=','',$s);
1140 function base64url_decode($s) {
1143 logger('base64url_decode: illegal input: ' . print_r(debug_backtrace(), true));
1148 * // Placeholder for new rev of salmon which strips base64 padding.
1149 * // PHP base64_decode handles the un-padded input without requiring this step
1150 * // Uncomment if you find you need it.
1153 * if(! strpos($s,'=')) {
1163 return base64_decode(strtr($s,'-_','+/'));
1167 if (!function_exists('str_getcsv')) {
1168 function str_getcsv($input, $delimiter = ',', $enclosure = '"', $escape = '\\', $eol = '\n') {
1169 if (is_string($input) && !empty($input)) {
1171 $tmp = preg_split("/".$eol."/",$input);
1172 if (is_array($tmp) && !empty($tmp)) {
1173 while (list($line_num, $line) = each($tmp)) {
1174 if (preg_match("/".$escape.$enclosure."/",$line)) {
1175 while ($strlen = strlen($line)) {
1176 $pos_delimiter = strpos($line,$delimiter);
1177 $pos_enclosure_start = strpos($line,$enclosure);
1179 is_int($pos_delimiter) && is_int($pos_enclosure_start)
1180 && ($pos_enclosure_start < $pos_delimiter)
1182 $enclosed_str = substr($line,1);
1183 $pos_enclosure_end = strpos($enclosed_str,$enclosure);
1184 $enclosed_str = substr($enclosed_str,0,$pos_enclosure_end);
1185 $output[$line_num][] = $enclosed_str;
1186 $offset = $pos_enclosure_end+3;
1188 if (empty($pos_delimiter) && empty($pos_enclosure_start)) {
1189 $output[$line_num][] = substr($line,0);
1190 $offset = strlen($line);
1192 $output[$line_num][] = substr($line,0,$pos_delimiter);
1194 !empty($pos_enclosure_start)
1195 && ($pos_enclosure_start < $pos_delimiter)
1197 ?$pos_enclosure_start
1201 $line = substr($line,$offset);
1204 $line = preg_split("/".$delimiter."/",$line);
1207 * Validating against pesky extra line breaks creating false rows.
1209 if (is_array($line) && !empty($line[0])) {
1210 $output[$line_num] = $line;
1224 function cleardiv() {
1225 return '<div class="clear"></div>';
1229 function bb_translate_video($s) {
1232 $r = preg_match_all("/\[video\](.*?)\[\/video\]/ism",$s,$matches,PREG_SET_ORDER);
1234 foreach($matches as $mtch) {
1235 if((stristr($mtch[1],'youtube')) || (stristr($mtch[1],'youtu.be')))
1236 $s = str_replace($mtch[0],'[youtube]' . $mtch[1] . '[/youtube]',$s);
1237 elseif(stristr($mtch[1],'vimeo'))
1238 $s = str_replace($mtch[0],'[vimeo]' . $mtch[1] . '[/vimeo]',$s);
1244 function html2bb_video($s) {
1246 $s = preg_replace('#<object[^>]+>(.*?)https+://www.youtube.com/((?:v|cp)/[A-Za-z0-9\-_=]+)(.*?)</object>#ism',
1247 '[youtube]$2[/youtube]', $s);
1249 $s = preg_replace('#<iframe[^>](.*?)https+://www.youtube.com/embed/([A-Za-z0-9\-_=]+)(.*?)</iframe>#ism',
1250 '[youtube]$2[/youtube]', $s);
1252 $s = preg_replace('#<iframe[^>](.*?)https+://player.vimeo.com/video/([0-9]+)(.*?)</iframe>#ism',
1253 '[vimeo]$2[/vimeo]', $s);
1259 * apply xmlify() to all values of array $val, recursively
1261 function array_xmlify($val){
1262 if (is_bool($val)) return $val?"true":"false";
1263 if (is_array($val)) return array_map('array_xmlify', $val);
1264 return xmlify((string) $val);
1268 function reltoabs($text, $base)
1273 $base = rtrim($base,'/');
1275 $base2 = $base . "/";
1278 $pattern = "/<a([^>]*) href=\"(?!http|https|\/)([^\"]*)\"/";
1279 $replace = "<a\${1} href=\"" . $base2 . "\${2}\"";
1280 $text = preg_replace($pattern, $replace, $text);
1282 $pattern = "/<a([^>]*) href=\"(?!http|https)([^\"]*)\"/";
1283 $replace = "<a\${1} href=\"" . $base . "\${2}\"";
1284 $text = preg_replace($pattern, $replace, $text);
1287 $pattern = "/<img([^>]*) src=\"(?!http|https|\/)([^\"]*)\"/";
1288 $replace = "<img\${1} src=\"" . $base2 . "\${2}\"";
1289 $text = preg_replace($pattern, $replace, $text);
1291 $pattern = "/<img([^>]*) src=\"(?!http|https)([^\"]*)\"/";
1292 $replace = "<img\${1} src=\"" . $base . "\${2}\"";
1293 $text = preg_replace($pattern, $replace, $text);
1300 function item_post_type($item) {
1301 if(intval($item['event-id']))
1303 if(strlen($item['resource-id']))
1305 if(strlen($item['verb']) && $item['verb'] !== ACTIVITY_POST)
1306 return t('activity');
1307 if($item['id'] != $item['parent'])
1308 return t('comment');
1312 // post categories and "save to file" use the same item.file table for storage.
1313 // We will differentiate the different uses by wrapping categories in angle brackets
1314 // and save to file categories in square brackets.
1315 // To do this we need to escape these characters if they appear in our tag.
1317 function file_tag_encode($s) {
1318 return str_replace(array('<','>','[',']'),array('%3c','%3e','%5b','%5d'),$s);
1321 function file_tag_decode($s) {
1322 return str_replace(array('%3c','%3e','%5b','%5d'),array('<','>','[',']'),$s);
1325 function file_tag_file_query($table,$s,$type = 'file') {
1328 $str = preg_quote( '[' . str_replace('%','%%',file_tag_encode($s)) . ']' );
1330 $str = preg_quote( '<' . str_replace('%','%%',file_tag_encode($s)) . '>' );
1331 return " AND " . (($table) ? dbesc($table) . '.' : '') . "file regexp '" . dbesc($str) . "' ";
1334 // ex. given music,video return <music><video> or [music][video]
1335 function file_tag_list_to_file($list,$type = 'file') {
1338 $list_array = explode(",",$list);
1339 if($type == 'file') {
1348 foreach($list_array as $item) {
1350 $tag_list .= $lbracket . file_tag_encode(trim($item)) . $rbracket;
1357 // ex. given <music><video>[friends], return music,video or friends
1358 function file_tag_file_to_list($file,$type = 'file') {
1361 if($type == 'file') {
1362 $cnt = preg_match_all('/\[(.*?)\]/',$file,$matches,PREG_SET_ORDER);
1365 $cnt = preg_match_all('/<(.*?)>/',$file,$matches,PREG_SET_ORDER);
1368 foreach($matches as $mtch) {
1371 $list .= file_tag_decode($mtch[1]);
1378 function file_tag_update_pconfig($uid,$file_old,$file_new,$type = 'file') {
1379 // $file_old - categories previously associated with an item
1380 // $file_new - new list of categories for an item
1385 if($file_old == $file_new)
1388 $saved = get_pconfig($uid,'system','filetags');
1389 if(strlen($saved)) {
1390 if($type == 'file') {
1399 $filetags_updated = $saved;
1401 // check for new tags to be added as filetags in pconfig
1402 $new_tags = array();
1403 $check_new_tags = explode(",",file_tag_file_to_list($file_new,$type));
1405 foreach($check_new_tags as $tag) {
1406 if(! stristr($saved,$lbracket . file_tag_encode($tag) . $rbracket))
1410 $filetags_updated .= file_tag_list_to_file(implode(",",$new_tags),$type);
1412 // check for deleted tags to be removed from filetags in pconfig
1413 $deleted_tags = array();
1414 $check_deleted_tags = explode(",",file_tag_file_to_list($file_old,$type));
1416 foreach($check_deleted_tags as $tag) {
1417 if(! stristr($file_new,$lbracket . file_tag_encode($tag) . $rbracket))
1418 $deleted_tags[] = $tag;
1421 foreach($deleted_tags as $key => $tag) {
1422 $r = q("select file from item where uid = %d " . file_tag_file_query('item',$tag,$type),
1427 unset($deleted_tags[$key]);
1430 $filetags_updated = str_replace($lbracket . file_tag_encode($tag) . $rbracket,'',$filetags_updated);
1434 if($saved != $filetags_updated) {
1435 set_pconfig($uid,'system','filetags', $filetags_updated);
1440 if(strlen($file_new)) {
1441 set_pconfig($uid,'system','filetags', $file_new);
1446 function file_tag_save_file($uid,$item,$file) {
1450 $r = q("select file from item where id = %d and uid = %d limit 1",
1455 if(! stristr($r[0]['file'],'[' . file_tag_encode($file) . ']'))
1456 q("update item set file = '%s' where id = %d and uid = %d limit 1",
1457 dbesc($r[0]['file'] . '[' . file_tag_encode($file) . ']'),
1461 $saved = get_pconfig($uid,'system','filetags');
1462 if((! strlen($saved)) || (! stristr($saved,'[' . file_tag_encode($file) . ']')))
1463 set_pconfig($uid,'system','filetags',$saved . '[' . file_tag_encode($file) . ']');
1464 info( t('Item filed') );
1469 function file_tag_unsave_file($uid,$item,$file) {
1474 $pattern = '[' . file_tag_encode($file) . ']' ;
1476 $r = q("select file from item where id = %d and uid = %d limit 1",
1483 q("update item set file = '%s' where id = %d and uid = %d limit 1",
1484 dbesc(str_replace($pattern,'',$r[0]['file'])),
1489 $r = q("select file from item where uid = %d " . file_tag_file_query('item',$file),
1494 $saved = get_pconfig($uid,'system','filetags');
1495 set_pconfig($uid,'system','filetags',str_replace($pattern,'',$saved));
1500 function normalise_openid($s) {
1501 return trim(str_replace(array('http://','https://'),array('',''),$s),'/');
1505 function undo_post_tagging($s) {
1507 $cnt = preg_match_all('/([@#])\[url=(.*?)\](.*?)\[\/url\]/ism',$s,$matches,PREG_SET_ORDER);
1509 foreach($matches as $mtch) {
1510 $s = str_replace($mtch[0], $mtch[1] . $mtch[3],$s);
1516 function fix_mce_lf($s) {
1517 $s = str_replace("\r\n","\n",$s);
1518 $s = str_replace("\n\n","\n",$s);