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 if(! function_exists('alt_pager')) {
284 function alt_pager(&$a, $i) {
286 $stripped = preg_replace('/(&page=[0-9]*)/','',$a->query_string);
287 $stripped = str_replace('q=','',$stripped);
288 $stripped = trim($stripped,'/');
289 $pagenum = $a->pager['page'];
290 $url = $a->get_baseurl() . '/' . $stripped;
292 $o .= '<div class="pager">';
294 if($a->pager['page']>1)
295 $o .= "<a href=\"$url"."&page=".($a->pager['page'] - 1).'">' . t('newer') . '</a>';
297 if($a->pager['page']>1)
298 $o .= " - ";
299 $o .= "<a href=\"$url"."&page=".($a->pager['page'] + 1).'">' . t('older') . '</a>';
303 $o .= '</div>'."\r\n";
308 // Turn user/group ACLs stored as angle bracketed text into arrays
310 if(! function_exists('expand_acl')) {
311 function expand_acl($s) {
312 // turn string array of angle-bracketed elements into numeric array
313 // e.g. "<1><2><3>" => array(1,2,3);
317 $t = str_replace('<','',$s);
318 $a = explode('>',$t);
321 $ret[] = intval($aa);
327 // Used to wrap ACL elements in angle brackets for storage
329 if(! function_exists('sanitise_acl')) {
330 function sanitise_acl(&$item) {
332 $item = '<' . intval(notags(trim($item))) . '>';
338 // Convert an ACL array to a storable string
340 if(! function_exists('perms2str')) {
341 function perms2str($p) {
345 array_walk($tmp,'sanitise_acl');
346 $ret = implode('',$tmp);
351 // generate a guaranteed unique (for this domain) item ID for ATOM
352 // safe from birthday paradox
354 if(! function_exists('item_new_uri')) {
355 function item_new_uri($hostname,$uid) {
359 $hash = random_string();
361 $uri = "urn:X-dfrn:" . $hostname . ':' . $uid . ':' . $hash;
363 $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' LIMIT 1",
367 } while($dups == true);
371 // Generate a guaranteed unique photo ID.
372 // safe from birthday paradox
374 if(! function_exists('photo_new_resource')) {
375 function photo_new_resource() {
379 $resource = hash('md5',uniqid(mt_rand(),true));
380 $r = q("SELECT `id` FROM `photo` WHERE `resource-id` = '%s' LIMIT 1",
385 } while($found == true);
390 // wrapper to load a view template, checking for alternate
391 // languages before falling back to the default
393 // obsolete, deprecated.
395 if(! function_exists('load_view_file')) {
396 function load_view_file($s) {
402 if(file_exists("$d/$lang/$b"))
403 return file_get_contents("$d/$lang/$b");
405 $theme = current_theme();
407 if(file_exists("$d/theme/$theme/$b"))
408 return file_get_contents("$d/theme/$theme/$b");
410 return file_get_contents($s);
413 if(! function_exists('get_intltext_template')) {
414 function get_intltext_template($s) {
420 if(file_exists("view/$lang/$s"))
421 return file_get_contents("view/$lang/$s");
422 elseif(file_exists("view/en/$s"))
423 return file_get_contents("view/en/$s");
425 return file_get_contents("view/$s");
428 if(! function_exists('get_markup_template')) {
429 function get_markup_template($s) {
431 $theme = current_theme();
433 if(file_exists("view/theme/$theme/$s"))
434 return file_get_contents("view/theme/$theme/$s");
435 elseif (x($a->theme_info,"extends") && file_exists("view/theme/".$a->theme_info["extends"]."/$s"))
436 return file_get_contents("view/theme/".$a->theme_info["extends"]."/$s");
438 return file_get_contents("view/$s");
446 // for html,xml parsing - let's say you've got
447 // an attribute foobar="class1 class2 class3"
448 // and you want to find out if it contains 'class3'.
449 // you can't use a normal sub string search because you
450 // might match 'notclass3' and a regex to do the job is
451 // possible but a bit complicated.
452 // pass the attribute string as $attr and the attribute you
453 // are looking for as $s - returns true if found, otherwise false
455 if(! function_exists('attribute_contains')) {
456 function attribute_contains($attr,$s) {
457 $a = explode(' ', $attr);
458 if(count($a) && in_array($s,$a))
463 if(! function_exists('logger')) {
464 function logger($msg,$level = 0) {
465 // turn off logger in install mode
469 if(($a->module == 'install') || (! ($db && $db->connected))) return;
471 $debugging = get_config('system','debugging');
472 $loglevel = intval(get_config('system','loglevel'));
473 $logfile = get_config('system','logfile');
475 if((! $debugging) || (! $logfile) || ($level > $loglevel))
478 @file_put_contents($logfile, datetime_convert() . ':' . session_id() . ' ' . $msg . "\n", FILE_APPEND);
483 if(! function_exists('activity_match')) {
484 function activity_match($haystack,$needle) {
485 if(($haystack === $needle) || ((basename($needle) === $haystack) && strstr($needle,NAMESPACE_ACTIVITY_SCHEMA)))
491 // Pull out all #hashtags and @person tags from $s;
492 // We also get @person@domain.com - which would make
493 // the regex quite complicated as tags can also
494 // end a sentence. So we'll run through our results
495 // and strip the period from any tags which end with one.
496 // Returns array of tags found, or empty array.
499 if(! function_exists('get_tags')) {
500 function get_tags($s) {
503 // ignore anything in a code block
505 $s = preg_replace('/\[code\](.*?)\[\/code\]/sm','',$s);
507 // Match full names against @tags including the space between first and last
508 // We will look these up afterward to see if they are full names or not recognisable.
510 if(preg_match_all('/(@[^ \x0D\x0A,:?]+ [^ \x0D\x0A@,:?]+)([ \x0D\x0A@,:?]|$)/',$s,$match)) {
511 foreach($match[1] as $mtch) {
512 if(strstr($mtch,"]")) {
513 // we might be inside a bbcode color tag - leave it alone
516 if(substr($mtch,-1,1) === '.')
517 $ret[] = substr($mtch,0,-1);
523 // Otherwise pull out single word tags. These can be @nickname, @first_last
526 if(preg_match_all('/([@#][^ \x0D\x0A,;:?]+)([ \x0D\x0A,;:?]|$)/',$s,$match)) {
527 foreach($match[1] as $mtch) {
528 if(strstr($mtch,"]")) {
529 // we might be inside a bbcode color tag - leave it alone
532 if(substr($mtch,-1,1) === '.')
533 $mtch = substr($mtch,0,-1);
534 // ignore strictly numeric tags like #1
535 if((strpos($mtch,'#') === 0) && ctype_digit(substr($mtch,1)))
537 // try not to catch url fragments
538 if(strpos($s,$mtch) && preg_match('/[a-zA-z0-9\/]/',substr($s,strpos($s,$mtch)-1,1)))
547 // quick and dirty quoted_printable encoding
549 if(! function_exists('qp')) {
551 return str_replace ("%","=",rawurlencode($s));
556 if(! function_exists('get_mentions')) {
557 function get_mentions($item) {
559 if(! strlen($item['tag']))
562 $arr = explode(',',$item['tag']);
563 foreach($arr as $x) {
565 if(preg_match('/@\[url=([^\]]*)\]/',$x,$matches)) {
566 $o .= "\t\t" . '<link rel="mentioned" href="' . $matches[1] . '" />' . "\r\n";
567 $o .= "\t\t" . '<link rel="ostatus:attention" href="' . $matches[1] . '" />' . "\r\n";
573 if(! function_exists('contact_block')) {
574 function contact_block() {
578 $shown = get_pconfig($a->profile['uid'],'system','display_friend_count');
584 if((! is_array($a->profile)) || ($a->profile['hide-friends']))
586 $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",
587 intval($a->profile['uid'])
590 $total = intval($r[0]['total']);
593 $contacts = t('No contacts');
597 $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",
598 intval($a->profile['uid']),
602 $contacts = sprintf( tt('%d Contact','%d Contacts', $total),$total);
605 $micropro[] = micropro($rr,true,'mpfriend');
610 $tpl = get_markup_template('contact_block.tpl');
611 $o = replace_macros($tpl, array(
612 '$contacts' => $contacts,
613 '$nickname' => $a->profile['nickname'],
614 '$viewcontacts' => t('View Contacts'),
615 '$micropro' => $micropro,
618 $arr = array('contacts' => $r, 'output' => $o);
620 call_hooks('contact_block_end', $arr);
625 if(! function_exists('micropro')) {
626 function micropro($contact, $redirect = false, $class = '', $textmode = false) {
629 $class = ' ' . $class;
631 $url = $contact['url'];
637 $redirect_url = $a->get_baseurl() . '/redir/' . $contact['id'];
638 if(local_user() && ($contact['uid'] == local_user()) && ($contact['network'] === 'dfrn')) {
640 $url = $redirect_url;
641 $sparkle = ' sparkle';
646 $click = ((x($contact,'click')) ? ' onclick="' . $contact['click'] . '" ' : '');
650 return '<div class="contact-block-textdiv' . $class . '"><a class="contact-block-link' . $class . $sparkle
651 . (($click) ? ' fakelink' : '') . '" '
652 . (($redir) ? ' target="redir" ' : '')
653 . (($url) ? ' href="' . $url . '"' : '') . $click
654 . '" title="' . $contact['name'] . ' [' . $contact['url'] . ']" alt="' . $contact['name']
655 . '" >'. $contact['name'] . '</a></div>' . "\r\n";
658 return '<div class="contact-block-div' . $class . '"><a class="contact-block-link' . $class . $sparkle
659 . (($click) ? ' fakelink' : '') . '" '
660 . (($redir) ? ' target="redir" ' : '')
661 . (($url) ? ' href="' . $url . '"' : '') . $click . ' ><img class="contact-block-img' . $class . $sparkle . '" src="'
662 . $contact['micro'] . '" title="' . $contact['name'] . ' [' . $contact['url'] . ']" alt="' . $contact['name']
663 . '" /></a></div>' . "\r\n";
669 if(! function_exists('search')) {
670 function search($s,$id='search-box',$url='/search',$save = false) {
672 $o = '<div id="' . $id . '">';
673 $o .= '<form action="' . $a->get_baseurl((stristr($url,'network')) ? true : false) . $url . '" method="get" >';
674 $o .= '<input type="text" name="search" id="search-text" placeholder="' . t('Search') . '" value="' . $s .'" />';
675 $o .= '<input type="submit" name="submit" id="search-submit" value="' . t('Search') . '" />';
677 $o .= '<input type="submit" name="save" id="search-save" value="' . t('Save') . '" />';
678 $o .= '</form></div>';
682 if(! function_exists('valid_email')) {
683 function valid_email($x){
685 if(get_config('system','disable_email_validation'))
688 if(preg_match('/^[_a-zA-Z0-9\-\+]+(\.[_a-zA-Z0-9\-\+]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)+$/',$x))
698 * Replace naked text hyperlink with HTML formatted hyperlink
702 if(! function_exists('linkify')) {
703 function linkify($s) {
704 $s = preg_replace("/(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\'\%\$\!\+]*)/", ' <a href="$1" target="external-link">$1</a>', $s);
705 $s = preg_replace("/\<(.*?)(src|href)=(.*?)\&\;(.*?)\>/ism",'<$1$2=$3&$4>',$s);
709 function get_poke_verbs() {
711 // index is present tense verb
712 // value is array containing past tense verb, translation of present, translation of past
715 'poke' => array( 'poked', t('poke'), t('poked')),
716 'ping' => array( 'pinged', t('ping'), t('pinged')),
717 'prod' => array( 'prodded', t('prod'), t('prodded')),
718 'slap' => array( 'slapped', t('slap'), t('slapped')),
719 'finger' => array( 'fingered', t('finger'), t('fingered')),
720 'rebuff' => array( 'rebuffed', t('rebuff'), t('rebuffed')),
722 call_hooks('poke_verbs', $arr);
731 * Replaces text emoticons with graphical images
733 * @Parameter: string $s
737 * It is expected that this function will be called using HTML text.
738 * We will escape text between HTML pre and code blocks from being
741 * At a higher level, the bbcode [nosmile] tag can be used to prevent this
742 * function from being executed by the prepare_text() routine when preparing
743 * bbcode source for HTML display
747 if(! function_exists('smilies')) {
748 function smilies($s, $sample = false) {
752 if(intval(get_config('system','no_smilies'))
753 || (local_user() && intval(get_pconfig(local_user(),'system','no_smilies'))))
756 $s = preg_replace_callback('/<pre>(.*?)<\/pre>/ism','smile_encode',$s);
757 $s = preg_replace_callback('/<code>(.*?)<\/code>/ism','smile_encode',$s);
798 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-heart.gif" alt="<3" />',
799 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-brokenheart.gif" alt="</3" />',
800 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-brokenheart.gif" alt="<\\3" />',
801 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-smile.gif" alt=":-)" />',
802 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-wink.gif" alt=";-)" />',
803 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-frown.gif" alt=":-(" />',
804 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-tongue-out.gif" alt=":-P" />',
805 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-tongue-out.gif" alt=":-p" />',
806 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-kiss.gif" alt=":-\"" />',
807 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-kiss.gif" alt=":-\"" />',
808 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-kiss.gif" alt=":-x" />',
809 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-kiss.gif" alt=":-X" />',
810 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-laughing.gif" alt=":-D" />',
811 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-surprised.gif" alt="8-|" />',
812 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-surprised.gif" alt="8-O" />',
813 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-surprised.gif" alt=":-O" />',
814 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-thumbsup.gif" alt="\\o/" />',
815 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-Oo.gif" alt="o.O" />',
816 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-Oo.gif" alt="O.o" />',
817 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-Oo.gif" alt="o_O" />',
818 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-Oo.gif" alt="O_o" />',
819 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-cry.gif" alt=":\'(" />',
820 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-foot-in-mouth.gif" alt=":-!" />',
821 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-undecided.gif" alt=":-/" />',
822 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-embarassed.gif" alt=":-[" />',
823 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-cool.gif" alt="8-)" />',
824 '<img class="smiley" src="' . $a->get_baseurl() . '/images/beer_mug.gif" alt=":beer" />',
825 '<img class="smiley" src="' . $a->get_baseurl() . '/images/beer_mug.gif" alt=":homebrew" />',
826 '<img class="smiley" src="' . $a->get_baseurl() . '/images/coffee.gif" alt=":coffee" />',
827 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-facepalm.gif" alt=":facepalm" />',
828 '<img class="smiley" src="' . $a->get_baseurl() . '/images/like.gif" alt=":like" />',
829 '<img class="smiley" src="' . $a->get_baseurl() . '/images/dislike.gif" alt=":dislike" />',
830 '<a href="http://project.friendika.com">~friendika <img class="smiley" src="' . $a->get_baseurl() . '/images/friendika-16.png" alt="~friendika" /></a>',
831 '<a href="http://friendica.com">~friendica <img class="smiley" src="' . $a->get_baseurl() . '/images/friendica-16.png" alt="~friendica" /></a>'
834 $params = array('texts' => $texts, 'icons' => $icons, 'string' => $s);
835 call_hooks('smilie', $params);
838 $s = '<div class="smiley-sample">';
839 for($x = 0; $x < count($params['texts']); $x ++) {
840 $s .= '<dl><dt>' . $params['texts'][$x] . '</dt><dd>' . $params['icons'][$x] . '</dd></dl>';
844 $params['string'] = preg_replace_callback('/<(3+)/','preg_heart',$params['string']);
845 $s = str_replace($params['texts'],$params['icons'],$params['string']);
848 $s = preg_replace_callback('/<pre>(.*?)<\/pre>/ism','smile_decode',$s);
849 $s = preg_replace_callback('/<code>(.*?)<\/code>/ism','smile_decode',$s);
855 function smile_encode($m) {
856 return(str_replace($m[1],base64url_encode($m[1]),$m[0]));
859 function smile_decode($m) {
860 return(str_replace($m[1],base64url_decode($m[1]),$m[0]));
863 // expand <3333 to the correct number of hearts
865 function preg_heart($x) {
867 if(strlen($x[1]) == 1)
870 for($cnt = 0; $cnt < strlen($x[1]); $cnt ++)
871 $t .= '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-heart.gif" alt="<3" />';
872 $r = str_replace($x[0],$t,$x[0]);
877 if(! function_exists('day_translate')) {
878 function day_translate($s) {
879 $ret = str_replace(array('Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'),
880 array( t('Monday'), t('Tuesday'), t('Wednesday'), t('Thursday'), t('Friday'), t('Saturday'), t('Sunday')),
883 $ret = str_replace(array('January','February','March','April','May','June','July','August','September','October','November','December'),
884 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')),
891 if(! function_exists('normalise_link')) {
892 function normalise_link($url) {
893 $ret = str_replace(array('https:','//www.'), array('http:','//'), $url);
894 return(rtrim($ret,'/'));
899 * Compare two URLs to see if they are the same, but ignore
900 * slight but hopefully insignificant differences such as if one
901 * is https and the other isn't, or if one is www.something and
902 * the other isn't - and also ignore case differences.
904 * Return true if the URLs match, otherwise false.
908 if(! function_exists('link_compare')) {
909 function link_compare($a,$b) {
910 if(strcasecmp(normalise_link($a),normalise_link($b)) === 0)
915 // Given an item array, convert the body element from bbcode to html and add smilie icons.
916 // If attach is true, also add icons for item attachments
919 if(! function_exists('prepare_body')) {
920 function prepare_body($item,$attach = false) {
923 call_hooks('prepare_body_init', $item);
925 $cache = get_config('system','itemcache');
927 if (($cache != '')) {
928 $cachefile = $cache."/".$item["guid"]."-".strtotime($item["edited"])."-".hash("crc32", $item['body']);
930 if (file_exists($cachefile))
931 $s = file_get_contents($cachefile);
933 $s = prepare_text($item['body']);
934 file_put_contents($cachefile, $s);
937 $s = prepare_text($item['body']);
940 $prep_arr = array('item' => $item, 'html' => $s);
941 call_hooks('prepare_body', $prep_arr);
942 $s = $prep_arr['html'];
948 $arr = explode(',',$item['attach']);
950 $s .= '<div class="body-attach">';
951 foreach($arr as $r) {
954 $cnt = preg_match_all('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"\[\/attach\]|',$r,$matches, PREG_SET_ORDER);
956 foreach($matches as $mtch) {
957 $icontype = strtolower(substr($mtch[3],0,strpos($mtch[3],'/')));
963 $icon = '<div class="attachtype icon s22 type-' . $icontype . '"></div>';
966 $icon = '<div class="attachtype icon s22 type-unkn"></div>';
969 $title = ((strlen(trim($mtch[4]))) ? escape_tags(trim($mtch[4])) : escape_tags($mtch[1]));
970 $title .= ' ' . $mtch[2] . ' ' . t('bytes');
971 if((local_user() == $item['uid']) && $item['contact-id'] != $a->contact['id'])
972 $the_url = $a->get_baseurl() . '/redir/' . $item['contact-id'] . '?f=1&url=' . $mtch[1];
976 $s .= '<a href="' . strip_tags($the_url) . '" title="' . $title . '" class="attachlink" target="external-link" >' . $icon . '</a>';
980 $s .= '<div class="clear"></div></div>';
983 $cnt = preg_match_all('/<(.*?)>/',$item['file'],$matches,PREG_SET_ORDER);
985 // logger('prepare_text: categories: ' . print_r($matches,true), LOGGER_DEBUG);
986 foreach($matches as $mtch) {
989 $x .= xmlify(file_tag_decode($mtch[1]))
990 . ((local_user() == $item['uid']) ? ' <a href="' . $a->get_baseurl() . '/filerm/' . $item['id'] . '?f=&cat=' . xmlify(file_tag_decode($mtch[1])) . '" title="' . t('remove') . '" >' . t('[remove]') . '</a>' : '');
993 $s .= '<div class="categorytags"><span>' . t('Categories:') . ' </span>' . $x . '</div>';
999 $cnt = preg_match_all('/\[(.*?)\]/',$item['file'],$matches,PREG_SET_ORDER);
1001 // logger('prepare_text: filed_under: ' . print_r($matches,true), LOGGER_DEBUG);
1002 foreach($matches as $mtch) {
1004 $x .= ' ';
1005 $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>';
1007 if(strlen($x) && (local_user() == $item['uid']))
1008 $s .= '<div class="filesavetags"><span>' . t('Filed under:') . ' </span>' . $x . '</div>';
1012 $spoilersearch = '<blockquote class="spoiler">';
1014 // Remove line breaks before the spoiler
1015 while ((strpos($s, "\n".$spoilersearch) !== false))
1016 $s = str_replace("\n".$spoilersearch, $spoilersearch, $s);
1017 while ((strpos($s, "<br />".$spoilersearch) !== false))
1018 $s = str_replace("<br />".$spoilersearch, $spoilersearch, $s);
1020 while ((strpos($s, $spoilersearch) !== false)) {
1022 $pos = strpos($s, $spoilersearch);
1023 $rnd = random_string(8);
1024 $spoilerreplace = '<br /> <span id="spoiler-wrap-'.$rnd.'" style="white-space:nowrap;" class="fakelink" onclick="openClose(\'spoiler-'.$rnd.'\');">'.sprintf(t('Click to open/close')).'</span>'.
1025 '<blockquote class="spoiler" id="spoiler-'.$rnd.'" style="display: none;">';
1026 $s = substr($s, 0, $pos).$spoilerreplace.substr($s, $pos+strlen($spoilersearch));
1029 // Look for quote with author
1030 $authorsearch = '<blockquote class="author">';
1032 while ((strpos($s, $authorsearch) !== false)) {
1034 $pos = strpos($s, $authorsearch);
1035 $rnd = random_string(8);
1036 $authorreplace = '<br /> <span id="author-wrap-'.$rnd.'" style="white-space:nowrap;" class="fakelink" onclick="openClose(\'author-'.$rnd.'\');">'.sprintf(t('Click to open/close')).'</span>'.
1037 '<blockquote class="author" id="author-'.$rnd.'" style="display: block;">';
1038 $s = substr($s, 0, $pos).$authorreplace.substr($s, $pos+strlen($authorsearch));
1041 $prep_arr = array('item' => $item, 'html' => $s);
1042 call_hooks('prepare_body_final', $prep_arr);
1044 return $prep_arr['html'];
1048 // Given a text string, convert from bbcode to html and add smilie icons.
1050 if(! function_exists('prepare_text')) {
1051 function prepare_text($text) {
1053 require_once('include/bbcode.php');
1055 if(stristr($text,'[nosmile]'))
1058 $s = smilies(bbcode($text));
1065 * return atom link elements for all of our hubs
1068 if(! function_exists('feed_hublinks')) {
1069 function feed_hublinks() {
1071 $hub = get_config('system','huburl');
1075 $hubs = explode(',', $hub);
1077 foreach($hubs as $h) {
1081 $hubxml .= '<link rel="hub" href="' . xmlify($h) . '" />' . "\n" ;
1088 /* return atom link elements for salmon endpoints */
1090 if(! function_exists('feed_salmonlinks')) {
1091 function feed_salmonlinks($nick) {
1095 $salmon = '<link rel="salmon" href="' . xmlify($a->get_baseurl() . '/salmon/' . $nick) . '" />' . "\n" ;
1097 // old style links that status.net still needed as of 12/2010
1099 $salmon .= ' <link rel="http://salmon-protocol.org/ns/salmon-replies" href="' . xmlify($a->get_baseurl() . '/salmon/' . $nick) . '" />' . "\n" ;
1100 $salmon .= ' <link rel="http://salmon-protocol.org/ns/salmon-mention" href="' . xmlify($a->get_baseurl() . '/salmon/' . $nick) . '" />' . "\n" ;
1104 if(! function_exists('get_plink')) {
1105 function get_plink($item) {
1107 if (x($item,'plink') && ($item['private'] != 1)) {
1109 'href' => $item['plink'],
1110 'title' => t('link to source'),
1118 if(! function_exists('unamp')) {
1119 function unamp($s) {
1120 return str_replace('&', '&', $s);
1126 if(! function_exists('lang_selector')) {
1127 function lang_selector() {
1130 $langs = glob('view/*/strings.php');
1132 $lang_options = array();
1135 if(is_array($langs) && count($langs)) {
1137 if(! in_array('view/en/strings.php',$langs))
1138 $langs[] = 'view/en/';
1140 foreach($langs as $l) {
1142 $lang_options[""] = t('default');
1146 $ll = substr($ll,0,strrpos($ll,'/'));
1147 $selected = (($ll === $lang && (x($_SESSION, 'language'))) ? $ll : $selected);
1148 $lang_options[$ll]=$ll;
1152 $tpl = get_markup_template("lang_selector.tpl");
1153 $o = replace_macros($tpl, array(
1154 '$title' => t('Select an alternate language'),
1155 '$langs' => array($lang_options, $selected),
1162 if(! function_exists('return_bytes')) {
1163 function return_bytes ($size_str) {
1164 switch (substr ($size_str, -1))
1166 case 'M': case 'm': return (int)$size_str * 1048576;
1167 case 'K': case 'k': return (int)$size_str * 1024;
1168 case 'G': case 'g': return (int)$size_str * 1073741824;
1169 default: return $size_str;
1173 function generate_user_guid() {
1176 $guid = random_string(16);
1177 $x = q("SELECT `uid` FROM `user` WHERE `guid` = '%s' LIMIT 1",
1182 } while ($found == true );
1188 function base64url_encode($s, $strip_padding = false) {
1190 $s = strtr(base64_encode($s),'+/','-_');
1193 $s = str_replace('=','',$s);
1198 function base64url_decode($s) {
1201 logger('base64url_decode: illegal input: ' . print_r(debug_backtrace(), true));
1206 * // Placeholder for new rev of salmon which strips base64 padding.
1207 * // PHP base64_decode handles the un-padded input without requiring this step
1208 * // Uncomment if you find you need it.
1211 * if(! strpos($s,'=')) {
1221 return base64_decode(strtr($s,'-_','+/'));
1225 if (!function_exists('str_getcsv')) {
1226 function str_getcsv($input, $delimiter = ',', $enclosure = '"', $escape = '\\', $eol = '\n') {
1227 if (is_string($input) && !empty($input)) {
1229 $tmp = preg_split("/".$eol."/",$input);
1230 if (is_array($tmp) && !empty($tmp)) {
1231 while (list($line_num, $line) = each($tmp)) {
1232 if (preg_match("/".$escape.$enclosure."/",$line)) {
1233 while ($strlen = strlen($line)) {
1234 $pos_delimiter = strpos($line,$delimiter);
1235 $pos_enclosure_start = strpos($line,$enclosure);
1237 is_int($pos_delimiter) && is_int($pos_enclosure_start)
1238 && ($pos_enclosure_start < $pos_delimiter)
1240 $enclosed_str = substr($line,1);
1241 $pos_enclosure_end = strpos($enclosed_str,$enclosure);
1242 $enclosed_str = substr($enclosed_str,0,$pos_enclosure_end);
1243 $output[$line_num][] = $enclosed_str;
1244 $offset = $pos_enclosure_end+3;
1246 if (empty($pos_delimiter) && empty($pos_enclosure_start)) {
1247 $output[$line_num][] = substr($line,0);
1248 $offset = strlen($line);
1250 $output[$line_num][] = substr($line,0,$pos_delimiter);
1252 !empty($pos_enclosure_start)
1253 && ($pos_enclosure_start < $pos_delimiter)
1255 ?$pos_enclosure_start
1259 $line = substr($line,$offset);
1262 $line = preg_split("/".$delimiter."/",$line);
1265 * Validating against pesky extra line breaks creating false rows.
1267 if (is_array($line) && !empty($line[0])) {
1268 $output[$line_num] = $line;
1282 function cleardiv() {
1283 return '<div class="clear"></div>';
1287 function bb_translate_video($s) {
1290 $r = preg_match_all("/\[video\](.*?)\[\/video\]/ism",$s,$matches,PREG_SET_ORDER);
1292 foreach($matches as $mtch) {
1293 if((stristr($mtch[1],'youtube')) || (stristr($mtch[1],'youtu.be')))
1294 $s = str_replace($mtch[0],'[youtube]' . $mtch[1] . '[/youtube]',$s);
1295 elseif(stristr($mtch[1],'vimeo'))
1296 $s = str_replace($mtch[0],'[vimeo]' . $mtch[1] . '[/vimeo]',$s);
1302 function html2bb_video($s) {
1304 $s = preg_replace('#<object[^>]+>(.*?)https?://www.youtube.com/((?:v|cp)/[A-Za-z0-9\-_=]+)(.*?)</object>#ism',
1305 '[youtube]$2[/youtube]', $s);
1307 $s = preg_replace('#<iframe[^>](.*?)https?://www.youtube.com/embed/([A-Za-z0-9\-_=]+)(.*?)</iframe>#ism',
1308 '[youtube]$2[/youtube]', $s);
1310 $s = preg_replace('#<iframe[^>](.*?)https?://player.vimeo.com/video/([0-9]+)(.*?)</iframe>#ism',
1311 '[vimeo]$2[/vimeo]', $s);
1317 * apply xmlify() to all values of array $val, recursively
1319 function array_xmlify($val){
1320 if (is_bool($val)) return $val?"true":"false";
1321 if (is_array($val)) return array_map('array_xmlify', $val);
1322 return xmlify((string) $val);
1326 function reltoabs($text, $base)
1331 $base = rtrim($base,'/');
1333 $base2 = $base . "/";
1336 $pattern = "/<a([^>]*) href=\"(?!http|https|\/)([^\"]*)\"/";
1337 $replace = "<a\${1} href=\"" . $base2 . "\${2}\"";
1338 $text = preg_replace($pattern, $replace, $text);
1340 $pattern = "/<a([^>]*) href=\"(?!http|https)([^\"]*)\"/";
1341 $replace = "<a\${1} href=\"" . $base . "\${2}\"";
1342 $text = preg_replace($pattern, $replace, $text);
1345 $pattern = "/<img([^>]*) src=\"(?!http|https|\/)([^\"]*)\"/";
1346 $replace = "<img\${1} src=\"" . $base2 . "\${2}\"";
1347 $text = preg_replace($pattern, $replace, $text);
1349 $pattern = "/<img([^>]*) src=\"(?!http|https)([^\"]*)\"/";
1350 $replace = "<img\${1} src=\"" . $base . "\${2}\"";
1351 $text = preg_replace($pattern, $replace, $text);
1358 function item_post_type($item) {
1359 if(intval($item['event-id']))
1361 if(strlen($item['resource-id']))
1363 if(strlen($item['verb']) && $item['verb'] !== ACTIVITY_POST)
1364 return t('activity');
1365 if($item['id'] != $item['parent'])
1366 return t('comment');
1370 // post categories and "save to file" use the same item.file table for storage.
1371 // We will differentiate the different uses by wrapping categories in angle brackets
1372 // and save to file categories in square brackets.
1373 // To do this we need to escape these characters if they appear in our tag.
1375 function file_tag_encode($s) {
1376 return str_replace(array('<','>','[',']'),array('%3c','%3e','%5b','%5d'),$s);
1379 function file_tag_decode($s) {
1380 return str_replace(array('%3c','%3e','%5b','%5d'),array('<','>','[',']'),$s);
1383 function file_tag_file_query($table,$s,$type = 'file') {
1386 $str = preg_quote( '[' . str_replace('%','%%',file_tag_encode($s)) . ']' );
1388 $str = preg_quote( '<' . str_replace('%','%%',file_tag_encode($s)) . '>' );
1389 return " AND " . (($table) ? dbesc($table) . '.' : '') . "file regexp '" . dbesc($str) . "' ";
1392 // ex. given music,video return <music><video> or [music][video]
1393 function file_tag_list_to_file($list,$type = 'file') {
1396 $list_array = explode(",",$list);
1397 if($type == 'file') {
1406 foreach($list_array as $item) {
1408 $tag_list .= $lbracket . file_tag_encode(trim($item)) . $rbracket;
1415 // ex. given <music><video>[friends], return music,video or friends
1416 function file_tag_file_to_list($file,$type = 'file') {
1419 if($type == 'file') {
1420 $cnt = preg_match_all('/\[(.*?)\]/',$file,$matches,PREG_SET_ORDER);
1423 $cnt = preg_match_all('/<(.*?)>/',$file,$matches,PREG_SET_ORDER);
1426 foreach($matches as $mtch) {
1429 $list .= file_tag_decode($mtch[1]);
1436 function file_tag_update_pconfig($uid,$file_old,$file_new,$type = 'file') {
1437 // $file_old - categories previously associated with an item
1438 // $file_new - new list of categories for an item
1443 if($file_old == $file_new)
1446 $saved = get_pconfig($uid,'system','filetags');
1447 if(strlen($saved)) {
1448 if($type == 'file') {
1457 $filetags_updated = $saved;
1459 // check for new tags to be added as filetags in pconfig
1460 $new_tags = array();
1461 $check_new_tags = explode(",",file_tag_file_to_list($file_new,$type));
1463 foreach($check_new_tags as $tag) {
1464 if(! stristr($saved,$lbracket . file_tag_encode($tag) . $rbracket))
1468 $filetags_updated .= file_tag_list_to_file(implode(",",$new_tags),$type);
1470 // check for deleted tags to be removed from filetags in pconfig
1471 $deleted_tags = array();
1472 $check_deleted_tags = explode(",",file_tag_file_to_list($file_old,$type));
1474 foreach($check_deleted_tags as $tag) {
1475 if(! stristr($file_new,$lbracket . file_tag_encode($tag) . $rbracket))
1476 $deleted_tags[] = $tag;
1479 foreach($deleted_tags as $key => $tag) {
1480 $r = q("select file from item where uid = %d " . file_tag_file_query('item',$tag,$type),
1485 unset($deleted_tags[$key]);
1488 $filetags_updated = str_replace($lbracket . file_tag_encode($tag) . $rbracket,'',$filetags_updated);
1492 if($saved != $filetags_updated) {
1493 set_pconfig($uid,'system','filetags', $filetags_updated);
1498 if(strlen($file_new)) {
1499 set_pconfig($uid,'system','filetags', $file_new);
1504 function file_tag_save_file($uid,$item,$file) {
1508 $r = q("select file from item where id = %d and uid = %d limit 1",
1513 if(! stristr($r[0]['file'],'[' . file_tag_encode($file) . ']'))
1514 q("update item set file = '%s' where id = %d and uid = %d limit 1",
1515 dbesc($r[0]['file'] . '[' . file_tag_encode($file) . ']'),
1519 $saved = get_pconfig($uid,'system','filetags');
1520 if((! strlen($saved)) || (! stristr($saved,'[' . file_tag_encode($file) . ']')))
1521 set_pconfig($uid,'system','filetags',$saved . '[' . file_tag_encode($file) . ']');
1522 info( t('Item filed') );
1527 function file_tag_unsave_file($uid,$item,$file,$cat = false) {
1533 $pattern = '<' . file_tag_encode($file) . '>' ;
1535 $pattern = '[' . file_tag_encode($file) . ']' ;
1538 $r = q("select file from item where id = %d and uid = %d limit 1",
1545 q("update item set file = '%s' where id = %d and uid = %d limit 1",
1546 dbesc(str_replace($pattern,'',$r[0]['file'])),
1551 $r = q("select file from item where uid = %d and deleted = 0 " . file_tag_file_query('item',$file,(($cat) ? 'category' : 'file')),
1556 $saved = get_pconfig($uid,'system','filetags');
1557 set_pconfig($uid,'system','filetags',str_replace($pattern,'',$saved));
1563 function normalise_openid($s) {
1564 return trim(str_replace(array('http://','https://'),array('',''),$s),'/');
1568 function undo_post_tagging($s) {
1570 $cnt = preg_match_all('/([@#])\[url=(.*?)\](.*?)\[\/url\]/ism',$s,$matches,PREG_SET_ORDER);
1572 foreach($matches as $mtch) {
1573 $s = str_replace($mtch[0], $mtch[1] . $mtch[3],$s);
1579 function fix_mce_lf($s) {
1580 $s = str_replace("\r\n","\n",$s);
1581 $s = str_replace("\n\n","\n",$s);
1586 function protect_sprintf($s) {
1587 return(str_replace('%','%%',$s));
1591 function is_a_date_arg($s) {
1595 if($i <= $y+1 && strpos($s,'-') == 4) {
1596 $m = intval(substr($s,5));
1597 if($m > 0 && $m <= 12)