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");
12 require_once("include/friendica_smarty.php");
14 if(! function_exists('replace_macros')) {
15 function replace_macros($s,$r) {
18 $stamp1 = microtime(true);
22 if($a->theme['template_engine'] === 'smarty3') {
24 if(gettype($s) === 'string') {
26 $s = new FriendicaSmarty();
28 foreach($r as $key=>$value) {
30 $key = substr($key, 1);
32 $s->assign($key, $value);
34 $output = $s->parsed($template);
37 $r = $t->replace($s,$r);
39 $output = template_unescape($r);
42 $a->save_timestamp($stamp1, "rendering");
48 // random string, there are 86 characters max in text mode, 128 for hex
51 define('RANDOM_STRING_HEX', 0x00 );
52 define('RANDOM_STRING_TEXT', 0x01 );
54 if(! function_exists('random_string')) {
55 function random_string($size = 64,$type = RANDOM_STRING_HEX) {
56 // generate a bit of entropy and run it through the whirlpool
57 $s = hash('whirlpool', (string) rand() . uniqid(rand(),true) . (string) rand(),(($type == RANDOM_STRING_TEXT) ? true : false));
58 $s = (($type == RANDOM_STRING_TEXT) ? str_replace("\n","",base64url_encode($s,true)) : $s);
59 return(substr($s,0,$size));
63 * This is our primary input filter.
65 * The high bit hack only involved some old IE browser, forget which (IE5/Mac?)
66 * that had an XSS attack vector due to stripping the high-bit on an 8-bit character
67 * after cleansing, and angle chars with the high bit set could get through as markup.
69 * This is now disabled because it was interfering with some legitimate unicode sequences
70 * and hopefully there aren't a lot of those browsers left.
72 * Use this on any text input where angle chars are not valid or permitted
73 * They will be replaced with safer brackets. This may be filtered further
74 * if these are not allowed either.
78 if(! function_exists('notags')) {
79 function notags($string) {
81 return(str_replace(array("<",">"), array('[',']'), $string));
83 // High-bit filter no longer used
84 // return(str_replace(array("<",">","\xBA","\xBC","\xBE"), array('[',']','','',''), $string));
87 // use this on "body" or "content" input where angle chars shouldn't be removed,
88 // and allow them to be safely displayed.
90 if(! function_exists('escape_tags')) {
91 function escape_tags($string) {
93 return(htmlspecialchars($string, ENT_COMPAT, 'UTF-8', false));
97 // generate a string that's random, but usually pronounceable.
98 // used to generate initial passwords
100 if(! function_exists('autoname')) {
101 function autoname($len) {
106 $vowels = array('a','a','ai','au','e','e','e','ee','ea','i','ie','o','ou','u');
107 if(mt_rand(0,5) == 4)
125 's','sc','sh','sm','sp','st',
133 $midcons = array('ck','ct','gn','ld','lf','lm','lt','mb','mm', 'mn','mp',
134 'nd','ng','nk','nt','rn','rp','rt');
136 $noend = array('bl', 'br', 'cl','cr','dr','fl','fr','gl','gr',
137 'kh', 'kl','kr','mn','pl','pr','rh','tr','qu','wh');
139 $start = mt_rand(0,2);
147 for ($x = 0; $x < $len; $x ++) {
148 $r = mt_rand(0,count($table) - 1);
151 if($table == $vowels)
152 $table = array_merge($cons,$midcons);
158 $word = substr($word,0,$len);
160 foreach($noend as $noe) {
161 if((strlen($word) > 2) && (substr($word,-2) == $noe)) {
162 $word = substr($word,0,-1);
166 if(substr($word,-1) == 'q')
167 $word = substr($word,0,-1);
172 // escape text ($str) for XML transport
173 // returns escaped text.
175 if(! function_exists('xmlify')) {
176 function xmlify($str) {
179 $len = mb_strlen($str);
180 for($x = 0; $x < $len; $x ++) {
181 $char = mb_substr($str,$x,1);
211 $buffer = mb_ereg_replace("&", "&", $str);
212 $buffer = mb_ereg_replace("'", "'", $buffer);
213 $buffer = mb_ereg_replace("\"", """, $buffer);
214 $buffer = mb_ereg_replace("<", "<", $buffer);
215 $buffer = mb_ereg_replace(">", ">", $buffer);
217 $buffer = trim($buffer);
222 // pass xml escaped text ($s), returns unescaped text
224 if(! function_exists('unxmlify')) {
225 function unxmlify($s) {
226 // $ret = str_replace('&','&', $s);
227 // $ret = str_replace(array('<','>','"','''),array('<','>','"',"'"),$ret);
228 $ret = mb_ereg_replace('&', '&', $s);
229 $ret = mb_ereg_replace(''', "'", $ret);
230 $ret = mb_ereg_replace('"', '"', $ret);
231 $ret = mb_ereg_replace('<', "<", $ret);
232 $ret = mb_ereg_replace('>', ">", $ret);
236 // convenience wrapper, reverse the operation "bin2hex"
238 if(! function_exists('hex2bin')) {
239 function hex2bin($s) {
240 if(! (is_string($s) && strlen($s)))
243 if(! ctype_xdigit($s)) {
247 return(pack("H*",$s));
250 // Automatic pagination.
251 // To use, get the count of total items.
252 // Then call $a->set_pager_total($number_items);
253 // Optionally call $a->set_pager_itemspage($n) to the number of items to display on each page
254 // Then call paginate($a) after the end of the display loop to insert the pager block on the page
255 // (assuming there are enough items to paginate).
256 // When using with SQL, the setting LIMIT %d, %d => $a->pager['start'],$a->pager['itemspage']
257 // will limit the results to the correct items for the current page.
258 // The actual page handling is then accomplished at the application layer.
260 if(! function_exists('paginate')) {
261 function paginate(&$a) {
263 $stripped = preg_replace('/(&page=[0-9]*)/','',$a->query_string);
265 // $stripped = preg_replace('/&zrl=(.*?)([\?&]|$)/ism','',$stripped);
267 $stripped = str_replace('q=','',$stripped);
268 $stripped = trim($stripped,'/');
269 $pagenum = $a->pager['page'];
270 $url = $a->get_baseurl() . '/' . $stripped;
273 if($a->pager['total'] > $a->pager['itemspage']) {
274 $o .= '<div class="pager">';
275 if($a->pager['page'] != 1)
276 $o .= '<span class="pager_prev">'."<a href=\"$url".'&page='.($a->pager['page'] - 1).'">' . t('prev') . '</a></span> ';
278 $o .= "<span class=\"pager_first\"><a href=\"$url"."&page=1\">" . t('first') . "</a></span> ";
280 $numpages = $a->pager['total'] / $a->pager['itemspage'];
283 $numstop = $numpages;
286 $numstart = (($pagenum > 7) ? ($pagenum - 7) : 1);
287 $numstop = (($pagenum > ($numpages - 7)) ? $numpages : ($numstart + 14));
290 for($i = $numstart; $i <= $numstop; $i++){
291 if($i == $a->pager['page'])
292 $o .= '<span class="pager_current">'.(($i < 10) ? ' '.$i : $i);
294 $o .= "<span class=\"pager_n\"><a href=\"$url"."&page=$i\">".(($i < 10) ? ' '.$i : $i)."</a>";
298 if(($a->pager['total'] % $a->pager['itemspage']) != 0) {
299 if($i == $a->pager['page'])
300 $o .= '<span class="pager_current">'.(($i < 10) ? ' '.$i : $i);
302 $o .= "<span class=\"pager_n\"><a href=\"$url"."&page=$i\">".(($i < 10) ? ' '.$i : $i)."</a>";
306 $lastpage = (($numpages > intval($numpages)) ? intval($numpages)+1 : $numpages);
307 $o .= "<span class=\"pager_last\"><a href=\"$url"."&page=$lastpage\">" . t('last') . "</a></span> ";
309 if(($a->pager['total'] - ($a->pager['itemspage'] * $a->pager['page'])) > 0)
310 $o .= '<span class="pager_next">'."<a href=\"$url"."&page=".($a->pager['page'] + 1).'">' . t('next') . '</a></span>';
311 $o .= '</div>'."\r\n";
316 if(! function_exists('alt_pager')) {
317 function alt_pager(&$a, $i) {
319 $stripped = preg_replace('/(&page=[0-9]*)/','',$a->query_string);
320 $stripped = str_replace('q=','',$stripped);
321 $stripped = trim($stripped,'/');
322 $pagenum = $a->pager['page'];
323 $url = $a->get_baseurl() . '/' . $stripped;
325 $o .= '<div class="pager">';
327 if($a->pager['page']>1)
328 $o .= "<a href=\"$url"."&page=".($a->pager['page'] - 1).'" class="pager_newer">' . t('newer') . '</a>';
330 if($a->pager['page']>1)
331 $o .= " - ";
332 $o .= "<a href=\"$url"."&page=".($a->pager['page'] + 1).'" class="pager_older">' . t('older') . '</a>';
336 $o .= '</div>'."\r\n";
341 // Turn user/group ACLs stored as angle bracketed text into arrays
343 if(! function_exists('expand_acl')) {
344 function expand_acl($s) {
345 // turn string array of angle-bracketed elements into numeric array
346 // e.g. "<1><2><3>" => array(1,2,3);
350 $t = str_replace('<','',$s);
351 $a = explode('>',$t);
354 $ret[] = intval($aa);
360 // Used to wrap ACL elements in angle brackets for storage
362 if(! function_exists('sanitise_acl')) {
363 function sanitise_acl(&$item) {
365 $item = '<' . intval(notags(trim($item))) . '>';
371 // Convert an ACL array to a storable string
372 // Normally ACL permissions will be an array.
373 // We'll also allow a comma-separated string.
375 if(! function_exists('perms2str')) {
376 function perms2str($p) {
382 $tmp = explode(',',$p);
385 array_walk($tmp,'sanitise_acl');
386 $ret = implode('',$tmp);
391 // generate a guaranteed unique (for this domain) item ID for ATOM
392 // safe from birthday paradox
394 if(! function_exists('item_new_uri')) {
395 function item_new_uri($hostname,$uid) {
399 $hash = random_string();
401 $uri = "urn:X-dfrn:" . $hostname . ':' . $uid . ':' . $hash;
403 $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' LIMIT 1",
407 } while($dups == true);
411 // Generate a guaranteed unique photo ID.
412 // safe from birthday paradox
414 if(! function_exists('photo_new_resource')) {
415 function photo_new_resource() {
419 $resource = hash('md5',uniqid(mt_rand(),true));
420 $r = q("SELECT `id` FROM `photo` WHERE `resource-id` = '%s' LIMIT 1",
425 } while($found == true);
430 // wrapper to load a view template, checking for alternate
431 // languages before falling back to the default
433 // obsolete, deprecated.
435 if(! function_exists('load_view_file')) {
436 function load_view_file($s) {
442 if(file_exists("$d/$lang/$b")) {
443 $stamp1 = microtime(true);
444 $content = file_get_contents("$d/$lang/$b");
445 $a->save_timestamp($stamp1, "file");
449 $theme = current_theme();
451 if(file_exists("$d/theme/$theme/$b")) {
452 $stamp1 = microtime(true);
453 $content = file_get_contents("$d/theme/$theme/$b");
454 $a->save_timestamp($stamp1, "file");
458 $stamp1 = microtime(true);
459 $content = file_get_contents($s);
460 $a->save_timestamp($stamp1, "file");
464 if(! function_exists('get_intltext_template')) {
465 function get_intltext_template($s) {
470 if($a->theme['template_engine'] === 'smarty3')
471 $engine = "/smarty3";
476 if(file_exists("view/$lang$engine/$s")) {
477 $stamp1 = microtime(true);
478 $content = file_get_contents("view/$lang$engine/$s");
479 $a->save_timestamp($stamp1, "file");
481 } elseif(file_exists("view/en$engine/$s")) {
482 $stamp1 = microtime(true);
483 $content = file_get_contents("view/en$engine/$s");
484 $a->save_timestamp($stamp1, "file");
487 $stamp1 = microtime(true);
488 $content = file_get_contents("view$engine/$s");
489 $a->save_timestamp($stamp1, "file");
494 if(! function_exists('get_markup_template')) {
495 function get_markup_template($s, $root = '') {
496 $stamp1 = microtime(true);
500 if($a->theme['template_engine'] === 'smarty3') {
501 $template_file = get_template_file($a, 'smarty3/' . $s, $root);
503 $template = new FriendicaSmarty();
504 $template->filename = $template_file;
505 $a->save_timestamp($stamp1, "rendering");
510 $template_file = get_template_file($a, $s, $root);
511 $a->save_timestamp($stamp1, "rendering");
513 $stamp1 = microtime(true);
514 $content = file_get_contents($template_file);
515 $a->save_timestamp($stamp1, "file");
521 if(! function_exists("get_template_file")) {
522 function get_template_file($a, $filename, $root = '') {
523 $theme = current_theme();
525 // Make sure $root ends with a slash /
526 if($root !== '' && $root[strlen($root)-1] !== '/')
529 if(file_exists("{$root}view/theme/$theme/$filename"))
530 $template_file = "{$root}view/theme/$theme/$filename";
531 elseif (x($a->theme_info,"extends") && file_exists("{$root}view/theme/{$a->theme_info["extends"]}/$filename"))
532 $template_file = "{$root}view/theme/{$a->theme_info["extends"]}/$filename";
534 $template_file = "{$root}view/$filename";
536 return $template_file;
543 // for html,xml parsing - let's say you've got
544 // an attribute foobar="class1 class2 class3"
545 // and you want to find out if it contains 'class3'.
546 // you can't use a normal sub string search because you
547 // might match 'notclass3' and a regex to do the job is
548 // possible but a bit complicated.
549 // pass the attribute string as $attr and the attribute you
550 // are looking for as $s - returns true if found, otherwise false
552 if(! function_exists('attribute_contains')) {
553 function attribute_contains($attr,$s) {
554 $a = explode(' ', $attr);
555 if(count($a) && in_array($s,$a))
560 if(! function_exists('logger')) {
561 function logger($msg,$level = 0) {
562 // turn off logger in install mode
566 if(($a->module == 'install') || (! ($db && $db->connected))) return;
568 $debugging = get_config('system','debugging');
569 $loglevel = intval(get_config('system','loglevel'));
570 $logfile = get_config('system','logfile');
572 if((! $debugging) || (! $logfile) || ($level > $loglevel))
575 $stamp1 = microtime(true);
576 @file_put_contents($logfile, datetime_convert() . ':' . session_id() . ' ' . $msg . "\n", FILE_APPEND);
577 $a->save_timestamp($stamp1, "file");
582 if(! function_exists('activity_match')) {
583 function activity_match($haystack,$needle) {
584 if(($haystack === $needle) || ((basename($needle) === $haystack) && strstr($needle,NAMESPACE_ACTIVITY_SCHEMA)))
590 // Pull out all #hashtags and @person tags from $s;
591 // We also get @person@domain.com - which would make
592 // the regex quite complicated as tags can also
593 // end a sentence. So we'll run through our results
594 // and strip the period from any tags which end with one.
595 // Returns array of tags found, or empty array.
598 if(! function_exists('get_tags')) {
599 function get_tags($s) {
602 // ignore anything in a code block
603 $s = preg_replace('/\[code\](.*?)\[\/code\]/sm','',$s);
605 // Force line feeds at bbtags
606 $s = str_replace(array("[", "]"), array("\n[", "]\n"), $s);
608 // ignore anything in a bbtag
609 $s = preg_replace('/\[(.*?)\]/sm','',$s);
611 // Match full names against @tags including the space between first and last
612 // We will look these up afterward to see if they are full names or not recognisable.
614 if(preg_match_all('/(@[^ \x0D\x0A,:?]+ [^ \x0D\x0A@,:?]+)([ \x0D\x0A@,:?]|$)/',$s,$match)) {
615 foreach($match[1] as $mtch) {
616 if(strstr($mtch,"]")) {
617 // we might be inside a bbcode color tag - leave it alone
620 if(substr($mtch,-1,1) === '.')
621 $ret[] = substr($mtch,0,-1);
627 // Otherwise pull out single word tags. These can be @nickname, @first_last
630 if(preg_match_all('/([@#][^ \x0D\x0A,;:?]+)([ \x0D\x0A,;:?]|$)/',$s,$match)) {
631 foreach($match[1] as $mtch) {
632 if(strstr($mtch,"]")) {
633 // we might be inside a bbcode color tag - leave it alone
636 if(substr($mtch,-1,1) === '.')
637 $mtch = substr($mtch,0,-1);
638 // ignore strictly numeric tags like #1
639 if((strpos($mtch,'#') === 0) && ctype_digit(substr($mtch,1)))
641 // try not to catch url fragments
642 if(strpos($s,$mtch) && preg_match('/[a-zA-z0-9\/]/',substr($s,strpos($s,$mtch)-1,1)))
651 // quick and dirty quoted_printable encoding
653 if(! function_exists('qp')) {
655 return str_replace ("%","=",rawurlencode($s));
660 if(! function_exists('get_mentions')) {
661 function get_mentions($item) {
663 if(! strlen($item['tag']))
666 $arr = explode(',',$item['tag']);
667 foreach($arr as $x) {
669 if(preg_match('/@\[url=([^\]]*)\]/',$x,$matches)) {
670 $o .= "\t\t" . '<link rel="mentioned" href="' . $matches[1] . '" />' . "\r\n";
671 $o .= "\t\t" . '<link rel="ostatus:attention" href="' . $matches[1] . '" />' . "\r\n";
677 if(! function_exists('contact_block')) {
678 function contact_block() {
682 $shown = get_pconfig($a->profile['uid'],'system','display_friend_count');
688 if((! is_array($a->profile)) || ($a->profile['hide-friends']))
690 $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",
691 intval($a->profile['uid'])
694 $total = intval($r[0]['total']);
697 $contacts = t('No contacts');
701 $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",
702 intval($a->profile['uid']),
706 $contacts = sprintf( tt('%d Contact','%d Contacts', $total),$total);
709 $micropro[] = micropro($rr,true,'mpfriend');
714 $tpl = get_markup_template('contact_block.tpl');
715 $o = replace_macros($tpl, array(
716 '$contacts' => $contacts,
717 '$nickname' => $a->profile['nickname'],
718 '$viewcontacts' => t('View Contacts'),
719 '$micropro' => $micropro,
722 $arr = array('contacts' => $r, 'output' => $o);
724 call_hooks('contact_block_end', $arr);
729 if(! function_exists('micropro')) {
730 function micropro($contact, $redirect = false, $class = '', $textmode = false) {
733 $class = ' ' . $class;
735 $url = $contact['url'];
741 $redirect_url = $a->get_baseurl() . '/redir/' . $contact['id'];
742 if(local_user() && ($contact['uid'] == local_user()) && ($contact['network'] === 'dfrn')) {
744 $url = $redirect_url;
745 $sparkle = ' sparkle';
750 $click = ((x($contact,'click')) ? ' onclick="' . $contact['click'] . '" ' : '');
754 return '<div class="contact-block-textdiv' . $class . '"><a class="contact-block-link' . $class . $sparkle
755 . (($click) ? ' fakelink' : '') . '" '
756 . (($redir) ? ' target="redir" ' : '')
757 . (($url) ? ' href="' . $url . '"' : '') . $click
758 . '" title="' . $contact['name'] . ' [' . $contact['url'] . ']" alt="' . $contact['name']
759 . '" >'. $contact['name'] . '</a></div>' . "\r\n";
762 return '<div class="contact-block-div' . $class . '"><a class="contact-block-link' . $class . $sparkle
763 . (($click) ? ' fakelink' : '') . '" '
764 . (($redir) ? ' target="redir" ' : '')
765 . (($url) ? ' href="' . $url . '"' : '') . $click . ' ><img class="contact-block-img' . $class . $sparkle . '" src="'
766 . $contact['micro'] . '" title="' . $contact['name'] . ' [' . $contact['url'] . ']" alt="' . $contact['name']
767 . '" /></a></div>' . "\r\n";
773 if(! function_exists('search')) {
774 function search($s,$id='search-box',$url='/search',$save = false) {
776 $o = '<div id="' . $id . '">';
777 $o .= '<form action="' . $a->get_baseurl((stristr($url,'network')) ? true : false) . $url . '" method="get" >';
778 $o .= '<input type="text" name="search" id="search-text" placeholder="' . t('Search') . '" value="' . $s .'" />';
779 $o .= '<input type="submit" name="submit" id="search-submit" value="' . t('Search') . '" />';
781 $o .= '<input type="submit" name="save" id="search-save" value="' . t('Save') . '" />';
782 $o .= '</form></div>';
786 if(! function_exists('valid_email')) {
787 function valid_email($x){
789 if(get_config('system','disable_email_validation'))
792 if(preg_match('/^[_a-zA-Z0-9\-\+]+(\.[_a-zA-Z0-9\-\+]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)+$/',$x))
802 * Replace naked text hyperlink with HTML formatted hyperlink
806 if(! function_exists('linkify')) {
807 function linkify($s) {
808 $s = preg_replace("/(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\'\%\$\!\+]*)/", ' <a href="$1" target="external-link">$1</a>', $s);
809 $s = preg_replace("/\<(.*?)(src|href)=(.*?)\&\;(.*?)\>/ism",'<$1$2=$3&$4>',$s);
813 function get_poke_verbs() {
815 // index is present tense verb
816 // value is array containing past tense verb, translation of present, translation of past
819 'poke' => array( 'poked', t('poke'), t('poked')),
820 'ping' => array( 'pinged', t('ping'), t('pinged')),
821 'prod' => array( 'prodded', t('prod'), t('prodded')),
822 'slap' => array( 'slapped', t('slap'), t('slapped')),
823 'finger' => array( 'fingered', t('finger'), t('fingered')),
824 'rebuff' => array( 'rebuffed', t('rebuff'), t('rebuffed')),
826 call_hooks('poke_verbs', $arr);
830 function get_mood_verbs() {
832 // index is present tense verb
833 // value is array containing past tense verb, translation of present, translation of past
836 'happy' => t('happy'),
838 'mellow' => t('mellow'),
839 'tired' => t('tired'),
840 'perky' => t('perky'),
841 'angry' => t('angry'),
842 'stupefied' => t('stupified'),
843 'puzzled' => t('puzzled'),
844 'interested' => t('interested'),
845 'bitter' => t('bitter'),
846 'cheerful' => t('cheerful'),
847 'alive' => t('alive'),
848 'annoyed' => t('annoyed'),
849 'anxious' => t('anxious'),
850 'cranky' => t('cranky'),
851 'disturbed' => t('disturbed'),
852 'frustrated' => t('frustrated'),
853 'motivated' => t('motivated'),
854 'relaxed' => t('relaxed'),
855 'surprised' => t('surprised'),
858 call_hooks('mood_verbs', $arr);
868 * Replaces text emoticons with graphical images
870 * @Parameter: string $s
874 * It is expected that this function will be called using HTML text.
875 * We will escape text between HTML pre and code blocks from being
878 * At a higher level, the bbcode [nosmile] tag can be used to prevent this
879 * function from being executed by the prepare_text() routine when preparing
880 * bbcode source for HTML display
884 if(! function_exists('smilies')) {
885 function smilies($s, $sample = false) {
889 if(intval(get_config('system','no_smilies'))
890 || (local_user() && intval(get_pconfig(local_user(),'system','no_smilies'))))
893 $s = preg_replace_callback('/<pre>(.*?)<\/pre>/ism','smile_encode',$s);
894 $s = preg_replace_callback('/<code>(.*?)<\/code>/ism','smile_encode',$s);
934 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-heart.gif" alt="<3" />',
935 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-brokenheart.gif" alt="</3" />',
936 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-brokenheart.gif" alt="<\\3" />',
937 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-smile.gif" alt=":-)" />',
938 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-wink.gif" alt=";-)" />',
939 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-frown.gif" alt=":-(" />',
940 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-tongue-out.gif" alt=":-P" />',
941 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-tongue-out.gif" alt=":-p" />',
942 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-kiss.gif" alt=":-\"" />',
943 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-kiss.gif" alt=":-\"" />',
944 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-kiss.gif" alt=":-x" />',
945 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-kiss.gif" alt=":-X" />',
946 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-laughing.gif" alt=":-D" />',
947 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-surprised.gif" alt="8-|" />',
948 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-surprised.gif" alt="8-O" />',
949 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-surprised.gif" alt=":-O" />',
950 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-thumbsup.gif" alt="\\o/" />',
951 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-Oo.gif" alt="o.O" />',
952 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-Oo.gif" alt="O.o" />',
953 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-Oo.gif" alt="o_O" />',
954 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-Oo.gif" alt="O_o" />',
955 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-cry.gif" alt=":\'(" />',
956 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-foot-in-mouth.gif" alt=":-!" />',
957 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-undecided.gif" alt=":-/" />',
958 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-embarassed.gif" alt=":-[" />',
959 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-cool.gif" alt="8-)" />',
960 '<img class="smiley" src="' . $a->get_baseurl() . '/images/beer_mug.gif" alt=":beer" />',
961 '<img class="smiley" src="' . $a->get_baseurl() . '/images/beer_mug.gif" alt=":homebrew" />',
962 '<img class="smiley" src="' . $a->get_baseurl() . '/images/coffee.gif" alt=":coffee" />',
963 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-facepalm.gif" alt=":facepalm" />',
964 '<img class="smiley" src="' . $a->get_baseurl() . '/images/like.gif" alt=":like" />',
965 '<img class="smiley" src="' . $a->get_baseurl() . '/images/dislike.gif" alt=":dislike" />',
966 '<a href="http://friendica.com">~friendica <img class="smiley" src="' . $a->get_baseurl() . '/images/friendica-16.png" alt="~friendica" /></a>'
969 $params = array('texts' => $texts, 'icons' => $icons, 'string' => $s);
970 call_hooks('smilie', $params);
973 $s = '<div class="smiley-sample">';
974 for($x = 0; $x < count($params['texts']); $x ++) {
975 $s .= '<dl><dt>' . $params['texts'][$x] . '</dt><dd>' . $params['icons'][$x] . '</dd></dl>';
979 $params['string'] = preg_replace_callback('/<(3+)/','preg_heart',$params['string']);
980 $s = str_replace($params['texts'],$params['icons'],$params['string']);
983 $s = preg_replace_callback('/<pre>(.*?)<\/pre>/ism','smile_decode',$s);
984 $s = preg_replace_callback('/<code>(.*?)<\/code>/ism','smile_decode',$s);
990 function smile_encode($m) {
991 return(str_replace($m[1],base64url_encode($m[1]),$m[0]));
994 function smile_decode($m) {
995 return(str_replace($m[1],base64url_decode($m[1]),$m[0]));
998 // expand <3333 to the correct number of hearts
1000 function preg_heart($x) {
1002 if(strlen($x[1]) == 1)
1005 for($cnt = 0; $cnt < strlen($x[1]); $cnt ++)
1006 $t .= '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-heart.gif" alt="<3" />';
1007 $r = str_replace($x[0],$t,$x[0]);
1012 if(! function_exists('day_translate')) {
1013 function day_translate($s) {
1014 $ret = str_replace(array('Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'),
1015 array( t('Monday'), t('Tuesday'), t('Wednesday'), t('Thursday'), t('Friday'), t('Saturday'), t('Sunday')),
1018 $ret = str_replace(array('January','February','March','April','May','June','July','August','September','October','November','December'),
1019 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')),
1026 if(! function_exists('normalise_link')) {
1027 function normalise_link($url) {
1028 $ret = str_replace(array('https:','//www.'), array('http:','//'), $url);
1029 return(rtrim($ret,'/'));
1034 * Compare two URLs to see if they are the same, but ignore
1035 * slight but hopefully insignificant differences such as if one
1036 * is https and the other isn't, or if one is www.something and
1037 * the other isn't - and also ignore case differences.
1039 * Return true if the URLs match, otherwise false.
1043 if(! function_exists('link_compare')) {
1044 function link_compare($a,$b) {
1045 if(strcasecmp(normalise_link($a),normalise_link($b)) === 0)
1050 // Given an item array, convert the body element from bbcode to html and add smilie icons.
1051 // If attach is true, also add icons for item attachments
1054 if(! function_exists('prepare_body')) {
1055 function prepare_body($item,$attach = false) {
1058 call_hooks('prepare_body_init', $item);
1060 //$cachefile = get_cachefile($item["guid"]."-".strtotime($item["edited"])."-".hash("crc32", $item['body']));
1061 $cachefile = get_cachefile($item["guid"]."-".hash("md5", $item['body']));
1063 if (($cachefile != '')) {
1064 if (file_exists($cachefile)) {
1065 $stamp1 = microtime(true);
1066 $s = file_get_contents($cachefile);
1067 $a->save_timestamp($stamp1, "file");
1069 $s = prepare_text($item['body']);
1070 $stamp1 = microtime(true);
1071 file_put_contents($cachefile, $s);
1072 $a->save_timestamp($stamp1, "file");
1073 logger('prepare_body: put item '.$item["id"].' into cachefile '.$cachefile);
1076 $s = prepare_text($item['body']);
1079 $prep_arr = array('item' => $item, 'html' => $s);
1080 call_hooks('prepare_body', $prep_arr);
1081 $s = $prep_arr['html'];
1084 // Replace the blockquotes with quotes that are used in mails
1085 $mailquote = '<blockquote type="cite" class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex;">';
1086 $s = str_replace(array('<blockquote>', '<blockquote class="spoiler">', '<blockquote class="author">'), array($mailquote, $mailquote, $mailquote), $s);
1090 $arr = explode('[/attach],',$item['attach']);
1092 $s .= '<div class="body-attach">';
1093 foreach($arr as $r) {
1096 $cnt = preg_match_all('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|',$r,$matches, PREG_SET_ORDER);
1098 foreach($matches as $mtch) {
1099 $filetype = strtolower(substr( $mtch[3], 0, strpos($mtch[3],'/') ));
1101 $filesubtype = strtolower(substr( $mtch[3], strpos($mtch[3],'/') + 1 ));
1102 $filesubtype = str_replace('.', '-', $filesubtype);
1106 $filesubtype = 'unkn';
1109 $icon = '<div class="attachtype icon s22 type-' . $filetype . ' subtype-' . $filesubtype . '"></div>';
1110 /*$icontype = strtolower(substr($mtch[3],0,strpos($mtch[3],'/')));
1116 $icon = '<div class="attachtype icon s22 type-' . $icontype . '"></div>';
1119 $icon = '<div class="attachtype icon s22 type-unkn"></div>';
1123 $title = ((strlen(trim($mtch[4]))) ? escape_tags(trim($mtch[4])) : escape_tags($mtch[1]));
1124 $title .= ' ' . $mtch[2] . ' ' . t('bytes');
1125 if((local_user() == $item['uid']) && ($item['contact-id'] != $a->contact['id']) && ($item['network'] == NETWORK_DFRN))
1126 $the_url = $a->get_baseurl() . '/redir/' . $item['contact-id'] . '?f=1&url=' . $mtch[1];
1128 $the_url = $mtch[1];
1130 $s .= '<a href="' . strip_tags($the_url) . '" title="' . $title . '" class="attachlink" target="external-link" >' . $icon . '</a>';
1134 $s .= '<div class="clear"></div></div>';
1139 $spoilersearch = '<blockquote class="spoiler">';
1141 // Remove line breaks before the spoiler
1142 while ((strpos($s, "\n".$spoilersearch) !== false))
1143 $s = str_replace("\n".$spoilersearch, $spoilersearch, $s);
1144 while ((strpos($s, "<br />".$spoilersearch) !== false))
1145 $s = str_replace("<br />".$spoilersearch, $spoilersearch, $s);
1147 while ((strpos($s, $spoilersearch) !== false)) {
1149 $pos = strpos($s, $spoilersearch);
1150 $rnd = random_string(8);
1151 $spoilerreplace = '<br /> <span id="spoiler-wrap-'.$rnd.'" style="white-space:nowrap;" class="fakelink" onclick="openClose(\'spoiler-'.$rnd.'\');">'.sprintf(t('Click to open/close')).'</span>'.
1152 '<blockquote class="spoiler" id="spoiler-'.$rnd.'" style="display: none;">';
1153 $s = substr($s, 0, $pos).$spoilerreplace.substr($s, $pos+strlen($spoilersearch));
1156 // Look for quote with author
1157 $authorsearch = '<blockquote class="author">';
1159 while ((strpos($s, $authorsearch) !== false)) {
1161 $pos = strpos($s, $authorsearch);
1162 $rnd = random_string(8);
1163 $authorreplace = '<br /> <span id="author-wrap-'.$rnd.'" style="white-space:nowrap;" class="fakelink" onclick="openClose(\'author-'.$rnd.'\');">'.sprintf(t('Click to open/close')).'</span>'.
1164 '<blockquote class="author" id="author-'.$rnd.'" style="display: block;">';
1165 $s = substr($s, 0, $pos).$authorreplace.substr($s, $pos+strlen($authorsearch));
1168 $prep_arr = array('item' => $item, 'html' => $s);
1169 call_hooks('prepare_body_final', $prep_arr);
1171 return $prep_arr['html'];
1175 // Given a text string, convert from bbcode to html and add smilie icons.
1177 if(! function_exists('prepare_text')) {
1178 function prepare_text($text) {
1180 require_once('include/bbcode.php');
1182 if(stristr($text,'[nosmile]'))
1185 $s = smilies(bbcode($text));
1196 * 'name': 'category name',
1197 * 'removeurl': 'url to remove this category',
1198 * 'first': 'is the first in this array? true/false',
1199 * 'last': 'is the last in this array? true/false',
1204 * 'name': 'folder name',
1205 * 'removeurl': 'url to remove this folder',
1206 * 'first': 'is the first in this array? true/false',
1207 * 'last': 'is the last in this array? true/false',
1213 function get_cats_and_terms($item) {
1215 $categories = array();
1218 $matches = false; $first = true;
1219 $cnt = preg_match_all('/<(.*?)>/',$item['file'],$matches,PREG_SET_ORDER);
1221 foreach($matches as $mtch) {
1222 $categories[] = array(
1223 'name' => xmlify(file_tag_decode($mtch[1])),
1225 'removeurl' => ((local_user() == $item['uid'])?$a->get_baseurl() . '/filerm/' . $item['id'] . '?f=&cat=' . xmlify(file_tag_decode($mtch[1])):""),
1232 if (count($categories)) $categories[count($categories)-1]['last'] = true;
1235 if(local_user() == $item['uid']) {
1236 $matches = false; $first = true;
1237 $cnt = preg_match_all('/\[(.*?)\]/',$item['file'],$matches,PREG_SET_ORDER);
1239 foreach($matches as $mtch) {
1241 'name' => xmlify(file_tag_decode($mtch[1])),
1243 'removeurl' => ((local_user() == $item['uid'])?$a->get_baseurl() . '/filerm/' . $item['id'] . '?f=&term=' . xmlify(file_tag_decode($mtch[1])):""),
1252 if (count($folders)) $folders[count($folders)-1]['last'] = true;
1254 return array($categories, $folders);
1259 * return atom link elements for all of our hubs
1262 if(! function_exists('feed_hublinks')) {
1263 function feed_hublinks() {
1265 $hub = get_config('system','huburl');
1269 $hubs = explode(',', $hub);
1271 foreach($hubs as $h) {
1275 $hubxml .= '<link rel="hub" href="' . xmlify($h) . '" />' . "\n" ;
1282 /* return atom link elements for salmon endpoints */
1284 if(! function_exists('feed_salmonlinks')) {
1285 function feed_salmonlinks($nick) {
1289 $salmon = '<link rel="salmon" href="' . xmlify($a->get_baseurl() . '/salmon/' . $nick) . '" />' . "\n" ;
1291 // old style links that status.net still needed as of 12/2010
1293 $salmon .= ' <link rel="http://salmon-protocol.org/ns/salmon-replies" href="' . xmlify($a->get_baseurl() . '/salmon/' . $nick) . '" />' . "\n" ;
1294 $salmon .= ' <link rel="http://salmon-protocol.org/ns/salmon-mention" href="' . xmlify($a->get_baseurl() . '/salmon/' . $nick) . '" />' . "\n" ;
1298 if(! function_exists('get_plink')) {
1299 function get_plink($item) {
1301 if (x($item,'plink') && ($item['private'] != 1)) {
1303 'href' => $item['plink'],
1304 'title' => t('link to source'),
1312 if(! function_exists('unamp')) {
1313 function unamp($s) {
1314 return str_replace('&', '&', $s);
1320 if(! function_exists('lang_selector')) {
1321 function lang_selector() {
1324 $langs = glob('view/*/strings.php');
1326 $lang_options = array();
1329 if(is_array($langs) && count($langs)) {
1331 if(! in_array('view/en/strings.php',$langs))
1332 $langs[] = 'view/en/';
1334 foreach($langs as $l) {
1336 $lang_options[""] = t('default');
1340 $ll = substr($ll,0,strrpos($ll,'/'));
1341 $selected = (($ll === $lang && (x($_SESSION, 'language'))) ? $ll : $selected);
1342 $lang_options[$ll]=$ll;
1346 $tpl = get_markup_template("lang_selector.tpl");
1347 $o = replace_macros($tpl, array(
1348 '$title' => t('Select an alternate language'),
1349 '$langs' => array($lang_options, $selected),
1356 if(! function_exists('return_bytes')) {
1357 function return_bytes ($size_str) {
1358 switch (substr ($size_str, -1))
1360 case 'M': case 'm': return (int)$size_str * 1048576;
1361 case 'K': case 'k': return (int)$size_str * 1024;
1362 case 'G': case 'g': return (int)$size_str * 1073741824;
1363 default: return $size_str;
1367 function generate_user_guid() {
1370 $guid = random_string(16);
1371 $x = q("SELECT `uid` FROM `user` WHERE `guid` = '%s' LIMIT 1",
1376 } while ($found == true );
1382 function base64url_encode($s, $strip_padding = false) {
1384 $s = strtr(base64_encode($s),'+/','-_');
1387 $s = str_replace('=','',$s);
1392 function base64url_decode($s) {
1395 logger('base64url_decode: illegal input: ' . print_r(debug_backtrace(), true));
1400 * // Placeholder for new rev of salmon which strips base64 padding.
1401 * // PHP base64_decode handles the un-padded input without requiring this step
1402 * // Uncomment if you find you need it.
1405 * if(! strpos($s,'=')) {
1415 return base64_decode(strtr($s,'-_','+/'));
1419 if (!function_exists('str_getcsv')) {
1420 function str_getcsv($input, $delimiter = ',', $enclosure = '"', $escape = '\\', $eol = '\n') {
1421 if (is_string($input) && !empty($input)) {
1423 $tmp = preg_split("/".$eol."/",$input);
1424 if (is_array($tmp) && !empty($tmp)) {
1425 while (list($line_num, $line) = each($tmp)) {
1426 if (preg_match("/".$escape.$enclosure."/",$line)) {
1427 while ($strlen = strlen($line)) {
1428 $pos_delimiter = strpos($line,$delimiter);
1429 $pos_enclosure_start = strpos($line,$enclosure);
1431 is_int($pos_delimiter) && is_int($pos_enclosure_start)
1432 && ($pos_enclosure_start < $pos_delimiter)
1434 $enclosed_str = substr($line,1);
1435 $pos_enclosure_end = strpos($enclosed_str,$enclosure);
1436 $enclosed_str = substr($enclosed_str,0,$pos_enclosure_end);
1437 $output[$line_num][] = $enclosed_str;
1438 $offset = $pos_enclosure_end+3;
1440 if (empty($pos_delimiter) && empty($pos_enclosure_start)) {
1441 $output[$line_num][] = substr($line,0);
1442 $offset = strlen($line);
1444 $output[$line_num][] = substr($line,0,$pos_delimiter);
1446 !empty($pos_enclosure_start)
1447 && ($pos_enclosure_start < $pos_delimiter)
1449 ?$pos_enclosure_start
1453 $line = substr($line,$offset);
1456 $line = preg_split("/".$delimiter."/",$line);
1459 * Validating against pesky extra line breaks creating false rows.
1461 if (is_array($line) && !empty($line[0])) {
1462 $output[$line_num] = $line;
1476 function cleardiv() {
1477 return '<div class="clear"></div>';
1481 function bb_translate_video($s) {
1484 $r = preg_match_all("/\[video\](.*?)\[\/video\]/ism",$s,$matches,PREG_SET_ORDER);
1486 foreach($matches as $mtch) {
1487 if((stristr($mtch[1],'youtube')) || (stristr($mtch[1],'youtu.be')))
1488 $s = str_replace($mtch[0],'[youtube]' . $mtch[1] . '[/youtube]',$s);
1489 elseif(stristr($mtch[1],'vimeo'))
1490 $s = str_replace($mtch[0],'[vimeo]' . $mtch[1] . '[/vimeo]',$s);
1496 function html2bb_video($s) {
1498 $s = preg_replace('#<object[^>]+>(.*?)https?://www.youtube.com/((?:v|cp)/[A-Za-z0-9\-_=]+)(.*?)</object>#ism',
1499 '[youtube]$2[/youtube]', $s);
1501 $s = preg_replace('#<iframe[^>](.*?)https?://www.youtube.com/embed/([A-Za-z0-9\-_=]+)(.*?)</iframe>#ism',
1502 '[youtube]$2[/youtube]', $s);
1504 $s = preg_replace('#<iframe[^>](.*?)https?://player.vimeo.com/video/([0-9]+)(.*?)</iframe>#ism',
1505 '[vimeo]$2[/vimeo]', $s);
1511 * apply xmlify() to all values of array $val, recursively
1513 function array_xmlify($val){
1514 if (is_bool($val)) return $val?"true":"false";
1515 if (is_array($val)) return array_map('array_xmlify', $val);
1516 return xmlify((string) $val);
1520 function reltoabs($text, $base)
1525 $base = rtrim($base,'/');
1527 $base2 = $base . "/";
1530 $pattern = "/<a([^>]*) href=\"(?!http|https|\/)([^\"]*)\"/";
1531 $replace = "<a\${1} href=\"" . $base2 . "\${2}\"";
1532 $text = preg_replace($pattern, $replace, $text);
1534 $pattern = "/<a([^>]*) href=\"(?!http|https)([^\"]*)\"/";
1535 $replace = "<a\${1} href=\"" . $base . "\${2}\"";
1536 $text = preg_replace($pattern, $replace, $text);
1539 $pattern = "/<img([^>]*) src=\"(?!http|https|\/)([^\"]*)\"/";
1540 $replace = "<img\${1} src=\"" . $base2 . "\${2}\"";
1541 $text = preg_replace($pattern, $replace, $text);
1543 $pattern = "/<img([^>]*) src=\"(?!http|https)([^\"]*)\"/";
1544 $replace = "<img\${1} src=\"" . $base . "\${2}\"";
1545 $text = preg_replace($pattern, $replace, $text);
1552 function item_post_type($item) {
1553 if(intval($item['event-id']))
1555 if(strlen($item['resource-id']))
1557 if(strlen($item['verb']) && $item['verb'] !== ACTIVITY_POST)
1558 return t('activity');
1559 if($item['id'] != $item['parent'])
1560 return t('comment');
1564 // post categories and "save to file" use the same item.file table for storage.
1565 // We will differentiate the different uses by wrapping categories in angle brackets
1566 // and save to file categories in square brackets.
1567 // To do this we need to escape these characters if they appear in our tag.
1569 function file_tag_encode($s) {
1570 return str_replace(array('<','>','[',']'),array('%3c','%3e','%5b','%5d'),$s);
1573 function file_tag_decode($s) {
1574 return str_replace(array('%3c','%3e','%5b','%5d'),array('<','>','[',']'),$s);
1577 function file_tag_file_query($table,$s,$type = 'file') {
1580 $str = preg_quote( '[' . str_replace('%','%%',file_tag_encode($s)) . ']' );
1582 $str = preg_quote( '<' . str_replace('%','%%',file_tag_encode($s)) . '>' );
1583 return " AND " . (($table) ? dbesc($table) . '.' : '') . "file regexp '" . dbesc($str) . "' ";
1586 // ex. given music,video return <music><video> or [music][video]
1587 function file_tag_list_to_file($list,$type = 'file') {
1590 $list_array = explode(",",$list);
1591 if($type == 'file') {
1600 foreach($list_array as $item) {
1602 $tag_list .= $lbracket . file_tag_encode(trim($item)) . $rbracket;
1609 // ex. given <music><video>[friends], return music,video or friends
1610 function file_tag_file_to_list($file,$type = 'file') {
1613 if($type == 'file') {
1614 $cnt = preg_match_all('/\[(.*?)\]/',$file,$matches,PREG_SET_ORDER);
1617 $cnt = preg_match_all('/<(.*?)>/',$file,$matches,PREG_SET_ORDER);
1620 foreach($matches as $mtch) {
1623 $list .= file_tag_decode($mtch[1]);
1630 function file_tag_update_pconfig($uid,$file_old,$file_new,$type = 'file') {
1631 // $file_old - categories previously associated with an item
1632 // $file_new - new list of categories for an item
1637 if($file_old == $file_new)
1640 $saved = get_pconfig($uid,'system','filetags');
1641 if(strlen($saved)) {
1642 if($type == 'file') {
1651 $filetags_updated = $saved;
1653 // check for new tags to be added as filetags in pconfig
1654 $new_tags = array();
1655 $check_new_tags = explode(",",file_tag_file_to_list($file_new,$type));
1657 foreach($check_new_tags as $tag) {
1658 if(! stristr($saved,$lbracket . file_tag_encode($tag) . $rbracket))
1662 $filetags_updated .= file_tag_list_to_file(implode(",",$new_tags),$type);
1664 // check for deleted tags to be removed from filetags in pconfig
1665 $deleted_tags = array();
1666 $check_deleted_tags = explode(",",file_tag_file_to_list($file_old,$type));
1668 foreach($check_deleted_tags as $tag) {
1669 if(! stristr($file_new,$lbracket . file_tag_encode($tag) . $rbracket))
1670 $deleted_tags[] = $tag;
1673 foreach($deleted_tags as $key => $tag) {
1674 $r = q("select file from item where uid = %d " . file_tag_file_query('item',$tag,$type),
1679 unset($deleted_tags[$key]);
1682 $filetags_updated = str_replace($lbracket . file_tag_encode($tag) . $rbracket,'',$filetags_updated);
1686 if($saved != $filetags_updated) {
1687 set_pconfig($uid,'system','filetags', $filetags_updated);
1692 if(strlen($file_new)) {
1693 set_pconfig($uid,'system','filetags', $file_new);
1698 function file_tag_save_file($uid,$item,$file) {
1702 $r = q("select file from item where id = %d and uid = %d limit 1",
1707 if(! stristr($r[0]['file'],'[' . file_tag_encode($file) . ']'))
1708 q("update item set file = '%s' where id = %d and uid = %d limit 1",
1709 dbesc($r[0]['file'] . '[' . file_tag_encode($file) . ']'),
1713 $saved = get_pconfig($uid,'system','filetags');
1714 if((! strlen($saved)) || (! stristr($saved,'[' . file_tag_encode($file) . ']')))
1715 set_pconfig($uid,'system','filetags',$saved . '[' . file_tag_encode($file) . ']');
1716 info( t('Item filed') );
1721 function file_tag_unsave_file($uid,$item,$file,$cat = false) {
1727 $pattern = '<' . file_tag_encode($file) . '>' ;
1729 $pattern = '[' . file_tag_encode($file) . ']' ;
1732 $r = q("select file from item where id = %d and uid = %d limit 1",
1739 q("update item set file = '%s' where id = %d and uid = %d limit 1",
1740 dbesc(str_replace($pattern,'',$r[0]['file'])),
1745 $r = q("select file from item where uid = %d and deleted = 0 " . file_tag_file_query('item',$file,(($cat) ? 'category' : 'file')),
1750 $saved = get_pconfig($uid,'system','filetags');
1751 set_pconfig($uid,'system','filetags',str_replace($pattern,'',$saved));
1757 function normalise_openid($s) {
1758 return trim(str_replace(array('http://','https://'),array('',''),$s),'/');
1762 function undo_post_tagging($s) {
1764 $cnt = preg_match_all('/([@#])\[url=(.*?)\](.*?)\[\/url\]/ism',$s,$matches,PREG_SET_ORDER);
1766 foreach($matches as $mtch) {
1767 $s = str_replace($mtch[0], $mtch[1] . $mtch[3],$s);
1773 function fix_mce_lf($s) {
1774 $s = str_replace("\r\n","\n",$s);
1775 // $s = str_replace("\n\n","\n",$s);
1780 function protect_sprintf($s) {
1781 return(str_replace('%','%%',$s));
1785 function is_a_date_arg($s) {
1789 if($i <= $y+1 && strpos($s,'-') == 4) {
1790 $m = intval(substr($s,5));
1791 if($m > 0 && $m <= 12)