]> git.mxchange.org Git - friendica.git/blob - include/text.php
ability to change tags in edited posts
[friendica.git] / include / text.php
1 <?php
2
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.   
10
11 require_once("include/template_processor.php");
12
13 if(! function_exists('replace_macros')) {  
14 function replace_macros($s,$r) {
15         global $t;
16         
17         //$ts = microtime();
18         $r =  $t->replace($s,$r);
19         //$tt = microtime() - $ts;
20         
21         //$a = get_app();
22         //$a->page['debug'] .= "$tt <br>\n";
23         return template_unescape($r);
24
25 }}
26
27
28 // random string, there are 86 characters max in text mode, 128 for hex
29 // output is urlsafe
30
31 define('RANDOM_STRING_HEX',  0x00 );
32 define('RANDOM_STRING_TEXT', 0x01 );
33
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));
40 }}
41
42 /**
43  * This is our primary input filter. 
44  *
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.
48  * 
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. 
51  *
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.   
55  *
56  */
57
58 if(! function_exists('notags')) {
59 function notags($string) {
60
61         return(str_replace(array("<",">"), array('[',']'), $string));
62
63 //  High-bit filter no longer used
64 //      return(str_replace(array("<",">","\xBA","\xBC","\xBE"), array('[',']','','',''), $string));
65 }}
66
67 // use this on "body" or "content" input where angle chars shouldn't be removed,
68 // and allow them to be safely displayed.
69
70 if(! function_exists('escape_tags')) {
71 function escape_tags($string) {
72
73         return(htmlspecialchars($string));
74 }}
75
76
77 // generate a string that's random, but usually pronounceable. 
78 // used to generate initial passwords
79
80 if(! function_exists('autoname')) {
81 function autoname($len) {
82
83         $vowels = array('a','a','ai','au','e','e','e','ee','ea','i','ie','o','ou','u'); 
84         if(mt_rand(0,5) == 4)
85                 $vowels[] = 'y';
86
87         $cons = array(
88                         'b','bl','br',
89                         'c','ch','cl','cr',
90                         'd','dr',
91                         'f','fl','fr',
92                         'g','gh','gl','gr',
93                         'h',
94                         'j',
95                         'k','kh','kl','kr',
96                         'l',
97                         'm',
98                         'n',
99                         'p','ph','pl','pr',
100                         'qu',
101                         'r','rh',
102                         's','sc','sh','sm','sp','st',
103                         't','th','tr',
104                         'v',
105                         'w','wh',
106                         'x',
107                         'z','zh'
108                         );
109
110         $midcons = array('ck','ct','gn','ld','lf','lm','lt','mb','mm', 'mn','mp',
111                                 'nd','ng','nk','nt','rn','rp','rt');
112
113         $noend = array('bl', 'br', 'cl','cr','dr','fl','fr','gl','gr',
114                                 'kh', 'kl','kr','mn','pl','pr','rh','tr','qu','wh');
115
116         $start = mt_rand(0,2);
117         if($start == 0)
118                 $table = $vowels;
119         else
120                 $table = $cons;
121
122         $word = '';
123
124         for ($x = 0; $x < $len; $x ++) {
125                 $r = mt_rand(0,count($table) - 1);
126                 $word .= $table[$r];
127   
128                 if($table == $vowels)
129                         $table = array_merge($cons,$midcons);
130                 else
131                         $table = $vowels;
132
133         }
134
135         $word = substr($word,0,$len);
136
137         foreach($noend as $noe) {
138                 if((strlen($word) > 2) && (substr($word,-2) == $noe)) {
139                         $word = substr($word,0,-1);
140                         break;
141                 }
142         }
143         if(substr($word,-1) == 'q')
144                 $word = substr($word,0,-1);    
145         return $word;
146 }}
147
148
149 // escape text ($str) for XML transport
150 // returns escaped text.
151
152 if(! function_exists('xmlify')) {
153 function xmlify($str) {
154         $buffer = '';
155         
156         for($x = 0; $x < mb_strlen($str); $x ++) {
157                 $char = $str[$x];
158         
159                 switch( $char ) {
160
161                         case "\r" :
162                                 break;
163                         case "&" :
164                                 $buffer .= '&amp;';
165                                 break;
166                         case "'" :
167                                 $buffer .= '&apos;';
168                                 break;
169                         case "\"" :
170                                 $buffer .= '&quot;';
171                                 break;
172                         case '<' :
173                                 $buffer .= '&lt;';
174                                 break;
175                         case '>' :
176                                 $buffer .= '&gt;';
177                                 break;
178                         case "\n" :
179                                 $buffer .= "\n";
180                                 break;
181                         default :
182                                 $buffer .= $char;
183                                 break;
184                 }       
185         }
186         $buffer = trim($buffer);
187         return($buffer);
188 }}
189
190 // undo an xmlify
191 // pass xml escaped text ($s), returns unescaped text
192
193 if(! function_exists('unxmlify')) {
194 function unxmlify($s) {
195         $ret = str_replace('&amp;','&', $s);
196         $ret = str_replace(array('&lt;','&gt;','&quot;','&apos;'),array('<','>','"',"'"),$ret);
197         return $ret;    
198 }}
199
200 // convenience wrapper, reverse the operation "bin2hex"
201
202 if(! function_exists('hex2bin')) {
203 function hex2bin($s) {
204         if(! (is_string($s) && strlen($s)))
205                 return '';
206
207         if(! ctype_xdigit($s)) {
208                 logger('hex2bin: illegal input: ' . print_r(debug_backtrace(), true));
209                 return($s);
210         }
211
212         return(pack("H*",$s));
213 }}
214
215 // Automatic pagination.
216 // To use, get the count of total items.
217 // Then call $a->set_pager_total($number_items);
218 // Optionally call $a->set_pager_itemspage($n) to the number of items to display on each page
219 // Then call paginate($a) after the end of the display loop to insert the pager block on the page
220 // (assuming there are enough items to paginate).
221 // When using with SQL, the setting LIMIT %d, %d => $a->pager['start'],$a->pager['itemspage']
222 // will limit the results to the correct items for the current page. 
223 // The actual page handling is then accomplished at the application layer. 
224
225 if(! function_exists('paginate')) {
226 function paginate(&$a) {
227         $o = '';
228         $stripped = preg_replace('/(&page=[0-9]*)/','',$a->query_string);
229         $stripped = str_replace('q=','',$stripped);
230         $stripped = trim($stripped,'/');
231         $pagenum = $a->pager['page'];
232         $url = $a->get_baseurl() . '/' . $stripped;
233
234
235           if($a->pager['total'] > $a->pager['itemspage']) {
236                 $o .= '<div class="pager">';
237                 if($a->pager['page'] != 1)
238                         $o .= '<span class="pager_prev">'."<a href=\"$url".'&page='.($a->pager['page'] - 1).'">' . t('prev') . '</a></span> ';
239
240                 $o .=  "<span class=\"pager_first\"><a href=\"$url"."&page=1\">" . t('first') . "</a></span> ";
241
242                 $numpages = $a->pager['total'] / $a->pager['itemspage'];
243
244                         $numstart = 1;
245                 $numstop = $numpages;
246
247                 if($numpages > 14) {
248                         $numstart = (($pagenum > 7) ? ($pagenum - 7) : 1);
249                         $numstop = (($pagenum > ($numpages - 7)) ? $numpages : ($numstart + 14));
250                 }
251    
252                 for($i = $numstart; $i <= $numstop; $i++){
253                         if($i == $a->pager['page'])
254                                 $o .= '<span class="pager_current">'.(($i < 10) ? '&nbsp;'.$i : $i);
255                         else
256                                 $o .= "<span class=\"pager_n\"><a href=\"$url"."&page=$i\">".(($i < 10) ? '&nbsp;'.$i : $i)."</a>";
257                         $o .= '</span> ';
258                 }
259
260                 if(($a->pager['total'] % $a->pager['itemspage']) != 0) {
261                         if($i == $a->pager['page'])
262                                 $o .= '<span class="pager_current">'.(($i < 10) ? '&nbsp;'.$i : $i);
263                         else
264                                 $o .= "<span class=\"pager_n\"><a href=\"$url"."&page=$i\">".(($i < 10) ? '&nbsp;'.$i : $i)."</a>";
265                         $o .= '</span> ';
266                 }
267
268                 $lastpage = (($numpages > intval($numpages)) ? intval($numpages)+1 : $numpages);
269                 $o .= "<span class=\"pager_last\"><a href=\"$url"."&page=$lastpage\">" . t('last') . "</a></span> ";
270
271                 if(($a->pager['total'] - ($a->pager['itemspage'] * $a->pager['page'])) > 0)
272                         $o .= '<span class="pager_next">'."<a href=\"$url"."&page=".($a->pager['page'] + 1).'">' . t('next') . '</a></span>';
273                 $o .= '</div>'."\r\n";
274         }
275         return $o;
276 }}
277
278 // Turn user/group ACLs stored as angle bracketed text into arrays
279
280 if(! function_exists('expand_acl')) {
281 function expand_acl($s) {
282         // turn string array of angle-bracketed elements into numeric array
283         // e.g. "<1><2><3>" => array(1,2,3);
284         $ret = array();
285
286         if(strlen($s)) {
287                 $t = str_replace('<','',$s);
288                 $a = explode('>',$t);
289                 foreach($a as $aa) {
290                         if(intval($aa))
291                                 $ret[] = intval($aa);
292                 }
293         }
294         return $ret;
295 }}              
296
297 // Used to wrap ACL elements in angle brackets for storage 
298
299 if(! function_exists('sanitise_acl')) {
300 function sanitise_acl(&$item) {
301         if(intval($item))
302                 $item = '<' . intval(notags(trim($item))) . '>';
303         else
304                 unset($item);
305 }}
306
307
308 // Convert an ACL array to a storable string
309
310 if(! function_exists('perms2str')) {
311 function perms2str($p) {
312         $ret = '';
313         $tmp = $p;
314         if(is_array($tmp)) {
315                 array_walk($tmp,'sanitise_acl');
316                 $ret = implode('',$tmp);
317         }
318         return $ret;
319 }}
320
321 // generate a guaranteed unique (for this domain) item ID for ATOM
322 // safe from birthday paradox
323
324 if(! function_exists('item_new_uri')) {
325 function item_new_uri($hostname,$uid) {
326
327         do {
328                 $dups = false;
329                 $hash = random_string();
330
331                 $uri = "urn:X-dfrn:" . $hostname . ':' . $uid . ':' . $hash;
332
333                 $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' LIMIT 1",
334                         dbesc($uri));
335                 if(count($r))
336                         $dups = true;
337         } while($dups == true);
338         return $uri;
339 }}
340
341 // Generate a guaranteed unique photo ID.
342 // safe from birthday paradox
343
344 if(! function_exists('photo_new_resource')) {
345 function photo_new_resource() {
346
347         do {
348                 $found = false;
349                 $resource = hash('md5',uniqid(mt_rand(),true));
350                 $r = q("SELECT `id` FROM `photo` WHERE `resource-id` = '%s' LIMIT 1",
351                         dbesc($resource)
352                 );
353                 if(count($r))
354                         $found = true;
355         } while($found == true);
356         return $resource;
357 }}
358
359
360 // wrapper to load a view template, checking for alternate
361 // languages before falling back to the default
362
363 // obsolete, deprecated.
364
365 if(! function_exists('load_view_file')) {
366 function load_view_file($s) {
367         global $lang, $a;
368         if(! isset($lang))
369                 $lang = 'en';
370         $b = basename($s);
371         $d = dirname($s);
372         if(file_exists("$d/$lang/$b"))
373                 return file_get_contents("$d/$lang/$b");
374         
375         $theme = current_theme();
376         
377         if(file_exists("$d/theme/$theme/$b"))
378                 return file_get_contents("$d/theme/$theme/$b");
379                         
380         return file_get_contents($s);
381 }}
382
383 if(! function_exists('get_intltext_template')) {
384 function get_intltext_template($s) {
385         global $lang;
386
387         if(! isset($lang))
388                 $lang = 'en';
389
390         if(file_exists("view/$lang/$s"))
391                 return file_get_contents("view/$lang/$s");
392         elseif(file_exists("view/en/$s"))
393                 return file_get_contents("view/en/$s");
394         else
395                 return file_get_contents("view/$s");
396 }}
397
398 if(! function_exists('get_markup_template')) {
399 function get_markup_template($s) {
400         $a=get_app();
401         $theme = current_theme();
402         
403         if(file_exists("view/theme/$theme/$s"))
404                 return file_get_contents("view/theme/$theme/$s");
405         elseif (x($a->theme_info,"extends") && file_exists("view/theme/".$a->theme_info["extends"]."/$s"))
406                 return file_get_contents("view/theme/".$a->theme_info["extends"]."/$s");
407         else
408                 return file_get_contents("view/$s");
409
410 }}
411
412
413
414
415
416 // for html,xml parsing - let's say you've got
417 // an attribute foobar="class1 class2 class3"
418 // and you want to find out if it contains 'class3'.
419 // you can't use a normal sub string search because you
420 // might match 'notclass3' and a regex to do the job is 
421 // possible but a bit complicated. 
422 // pass the attribute string as $attr and the attribute you 
423 // are looking for as $s - returns true if found, otherwise false
424
425 if(! function_exists('attribute_contains')) {
426 function attribute_contains($attr,$s) {
427         $a = explode(' ', $attr);
428         if(count($a) && in_array($s,$a))
429                 return true;
430         return false;
431 }}
432
433 if(! function_exists('logger')) {
434 function logger($msg,$level = 0) {
435         // turn off logger in install mode
436         global $a;
437         global $db;
438
439         if(($a->module == 'install') || (! ($db && $db->connected))) return;
440
441         $debugging = get_config('system','debugging');
442         $loglevel  = intval(get_config('system','loglevel'));
443         $logfile   = get_config('system','logfile');
444
445         if((! $debugging) || (! $logfile) || ($level > $loglevel))
446                 return;
447         
448         @file_put_contents($logfile, datetime_convert() . ':' . session_id() . ' ' . $msg . "\n", FILE_APPEND);
449         return;
450 }}
451
452
453 if(! function_exists('activity_match')) {
454 function activity_match($haystack,$needle) {
455         if(($haystack === $needle) || ((basename($needle) === $haystack) && strstr($needle,NAMESPACE_ACTIVITY_SCHEMA)))
456                 return true;
457         return false;
458 }}
459
460
461 // Pull out all #hashtags and @person tags from $s;
462 // We also get @person@domain.com - which would make 
463 // the regex quite complicated as tags can also
464 // end a sentence. So we'll run through our results
465 // and strip the period from any tags which end with one.
466 // Returns array of tags found, or empty array.
467
468
469 if(! function_exists('get_tags')) {
470 function get_tags($s) {
471         $ret = array();
472
473         // ignore anything in a code block
474
475         $s = preg_replace('/\[code\](.*?)\[\/code\]/sm','',$s);
476
477         // Match full names against @tags including the space between first and last
478         // We will look these up afterward to see if they are full names or not recognisable.
479
480         if(preg_match_all('/(@[^ \x0D\x0A,:?]+ [^ \x0D\x0A@,:?]+)([ \x0D\x0A@,:?]|$)/',$s,$match)) {
481                 foreach($match[1] as $mtch) {
482                         if(strstr($mtch,"]")) {
483                                 // we might be inside a bbcode color tag - leave it alone
484                                 continue;
485                         }
486                         if(substr($mtch,-1,1) === '.')
487                                 $ret[] = substr($mtch,0,-1);
488                         else
489                                 $ret[] = $mtch;
490                 }
491         }
492
493         // Otherwise pull out single word tags. These can be @nickname, @first_last
494         // and #hash tags.
495
496         if(preg_match_all('/([@#][^ \x0D\x0A,;:?]+)([ \x0D\x0A,;:?]|$)/',$s,$match)) {
497                 foreach($match[1] as $mtch) {
498                         if(strstr($mtch,"]")) {
499                                 // we might be inside a bbcode color tag - leave it alone
500                                 continue;
501                         }
502                         if(substr($mtch,-1,1) === '.')
503                                 $mtch = substr($mtch,0,-1);
504                         // ignore strictly numeric tags like #1
505                         if((strpos($mtch,'#') === 0) && ctype_digit(substr($mtch,1)))
506                                 continue;
507                         // try not to catch url fragments
508                         if(strpos($s,$mtch) && preg_match('/[a-zA-z0-9\/]/',substr($s,strpos($s,$mtch)-1,1)))
509                                 continue;
510                         $ret[] = $mtch;
511                 }
512         }
513         return $ret;
514 }}
515
516
517 // quick and dirty quoted_printable encoding
518
519 if(! function_exists('qp')) {
520 function qp($s) {
521 return str_replace ("%","=",rawurlencode($s));
522 }} 
523
524
525
526 if(! function_exists('get_mentions')) {
527 function get_mentions($item) {
528         $o = '';
529         if(! strlen($item['tag']))
530                 return $o;
531
532         $arr = explode(',',$item['tag']);
533         foreach($arr as $x) {
534                 $matches = null;
535                 if(preg_match('/@\[url=([^\]]*)\]/',$x,$matches)) {
536                         $o .= "\t\t" . '<link rel="mentioned" href="' . $matches[1] . '" />' . "\r\n";
537                         $o .= "\t\t" . '<link rel="ostatus:attention" href="' . $matches[1] . '" />' . "\r\n";
538                 }
539         }
540         return $o;
541 }}
542
543 if(! function_exists('contact_block')) {
544 function contact_block() {
545         $o = '';
546         $a = get_app();
547
548         $shown = get_pconfig($a->profile['uid'],'system','display_friend_count');
549         if($shown === false)
550                 $shown = 24;
551         if($shown == 0)
552                 return;
553
554         if((! is_array($a->profile)) || ($a->profile['hide-friends']))
555                 return $o;
556         $r = q("SELECT COUNT(*) AS `total` FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 and `pending` = 0 AND `hidden` = 0",
557                         intval($a->profile['uid'])
558         );
559         if(count($r)) {
560                 $total = intval($r[0]['total']);
561         }
562         if(! $total) {
563                 $contacts = t('No contacts');
564                 $micropro = Null;
565                 
566         } else {
567                 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 and `pending` = 0 AND `hidden` = 0 ORDER BY RAND() LIMIT %d",
568                                 intval($a->profile['uid']),
569                                 intval($shown)
570                 );
571                 if(count($r)) {
572                         $contacts = sprintf( tt('%d Contact','%d Contacts', $total),$total);
573                         $micropro = Array();
574                         foreach($r as $rr) {
575                                 $micropro[] = micropro($rr,true,'mpfriend');
576                         }
577                 }
578         }
579         
580         $tpl = get_markup_template('contact_block.tpl');
581         $o = replace_macros($tpl, array(
582                 '$contacts' => $contacts,
583                 '$nickname' => $a->profile['nickname'],
584                 '$viewcontacts' => t('View Contacts'),
585                 '$micropro' => $micropro,
586         ));
587
588         $arr = array('contacts' => $r, 'output' => $o);
589
590         call_hooks('contact_block_end', $arr);
591         return $o;
592
593 }}
594
595 if(! function_exists('micropro')) {
596 function micropro($contact, $redirect = false, $class = '', $textmode = false) {
597
598         if($class)
599                 $class = ' ' . $class;
600
601         $url = $contact['url'];
602         $sparkle = '';
603         $redir = false;
604
605         if($redirect) {
606                 $a = get_app();
607                 $redirect_url = $a->get_baseurl() . '/redir/' . $contact['id'];
608                 if(local_user() && ($contact['uid'] == local_user()) && ($contact['network'] === 'dfrn')) {
609                         $redir = true;
610                         $url = $redirect_url;
611                         $sparkle = ' sparkle';
612                 }
613         }
614         $click = ((x($contact,'click')) ? ' onclick="' . $contact['click'] . '" ' : '');
615         if($click)
616                 $url = '';
617         if($textmode) {
618                 return '<div class="contact-block-textdiv' . $class . '"><a class="contact-block-link' . $class . $sparkle 
619                         . (($click) ? ' fakelink' : '') . '" '
620                         . (($redir) ? ' target="redir" ' : '')
621                         . (($url) ? ' href="' . $url . '"' : '') . $click
622                         . '" title="' . $contact['name'] . ' [' . $contact['url'] . ']" alt="' . $contact['name'] 
623                         . '" >'. $contact['name'] . '</a></div>' . "\r\n";
624         }
625         else {
626                 return '<div class="contact-block-div' . $class . '"><a class="contact-block-link' . $class . $sparkle 
627                         . (($click) ? ' fakelink' : '') . '" '
628                         . (($redir) ? ' target="redir" ' : '')
629                         . (($url) ? ' href="' . $url . '"' : '') . $click . ' ><img class="contact-block-img' . $class . $sparkle . '" src="' 
630                         . $contact['micro'] . '" title="' . $contact['name'] . ' [' . $contact['url'] . ']" alt="' . $contact['name'] 
631                         . '" /></a></div>' . "\r\n";
632         }
633 }}
634
635
636
637 if(! function_exists('search')) {
638 function search($s,$id='search-box',$url='/search',$save = false) {
639         $a = get_app();
640         $o  = '<div id="' . $id . '">';
641         $o .= '<form action="' . $a->get_baseurl((stristr($url,'network')) ? true : false) . $url . '" method="get" >';
642         $o .= '<input type="text" name="search" id="search-text" value="' . $s .'" />';
643         $o .= '<input type="submit" name="submit" id="search-submit" value="' . t('Search') . '" />'; 
644         if($save)
645                 $o .= '<input type="submit" name="save" id="search-save" value="' . t('Save') . '" />'; 
646         $o .= '</form></div>';
647         return $o;
648 }}
649
650 if(! function_exists('valid_email')) {
651 function valid_email($x){
652         if(preg_match('/^[_a-zA-Z0-9\-\+]+(\.[_a-zA-Z0-9\-\+]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)+$/',$x))
653                 return true;
654         return false;
655 }}
656
657
658 /**
659  *
660  * Function: linkify
661  *
662  * Replace naked text hyperlink with HTML formatted hyperlink
663  *
664  */
665
666 if(! function_exists('linkify')) {
667 function linkify($s) {
668         $s = preg_replace("/(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\'\%\$\!\+]*)/", ' <a href="$1" target="external-link">$1</a>', $s);
669         $s = preg_replace("/\<(.*?)(src|href)=(.*?)\&amp\;(.*?)\>/ism",'<$1$2=$3&$4>',$s);
670         return($s);
671 }}
672
673
674 /**
675  * 
676  * Function: smilies
677  *
678  * Description:
679  * Replaces text emoticons with graphical images
680  *
681  * @Parameter: string $s
682  *
683  * Returns string
684  *
685  * It is expected that this function will be called using HTML text.
686  * We will escape text between HTML pre and code blocks from being 
687  * processed. 
688  * 
689  * At a higher level, the bbcode [nosmile] tag can be used to prevent this 
690  * function from being executed by the prepare_text() routine when preparing
691  * bbcode source for HTML display
692  *
693  */
694
695 if(! function_exists('smilies')) {
696 function smilies($s, $sample = false) {
697
698         $a = get_app();
699
700         if(intval(get_config('system','no_smilies')) 
701                 || (local_user() && intval(get_pconfig(local_user(),'system','no_smilies'))))
702                 return $s;
703
704         $s = preg_replace_callback('/<pre>(.*?)<\/pre>/ism','smile_encode',$s);
705         $s = preg_replace_callback('/<code>(.*?)<\/code>/ism','smile_encode',$s);
706
707         $texts =  array( 
708                 '&lt;3', 
709                 '&lt;/3', 
710                 '&lt;\\3', 
711                 ':-)', 
712                 ';-)', 
713                 ':-(', 
714                 ':-P', 
715                 ':-p', 
716                 ':-"', 
717                 ':-&quot;', 
718                 ':-x', 
719                 ':-X', 
720                 ':-D', 
721                 '8-|', 
722                 '8-O', 
723                 ':-O', 
724                 '\\o/', 
725                 'o.O', 
726                 'O.o', 
727                 ":'(", 
728                 ":-!", 
729                 ":-/", 
730                 ":-[", 
731                 "8-)",
732                 ':beer', 
733                 ':homebrew', 
734                 ':coffee', 
735                 ':facepalm',
736                 '~friendika', 
737                 '~friendica'
738
739         );
740
741         $icons = array(
742                 '<img src="' . $a->get_baseurl() . '/images/smiley-heart.gif" alt="<3" />',
743                 '<img src="' . $a->get_baseurl() . '/images/smiley-brokenheart.gif" alt="</3" />',
744                 '<img src="' . $a->get_baseurl() . '/images/smiley-brokenheart.gif" alt="<\\3" />',
745                 '<img src="' . $a->get_baseurl() . '/images/smiley-smile.gif" alt=":-)" />',
746                 '<img src="' . $a->get_baseurl() . '/images/smiley-wink.gif" alt=";-)" />',
747                 '<img src="' . $a->get_baseurl() . '/images/smiley-frown.gif" alt=":-(" />',
748                 '<img src="' . $a->get_baseurl() . '/images/smiley-tongue-out.gif" alt=":-P" />',
749                 '<img src="' . $a->get_baseurl() . '/images/smiley-tongue-out.gif" alt=":-p" />',
750                 '<img src="' . $a->get_baseurl() . '/images/smiley-kiss.gif" alt=":-\"" />',
751                 '<img src="' . $a->get_baseurl() . '/images/smiley-kiss.gif" alt=":-\"" />',
752                 '<img src="' . $a->get_baseurl() . '/images/smiley-kiss.gif" alt=":-x" />',
753                 '<img src="' . $a->get_baseurl() . '/images/smiley-kiss.gif" alt=":-X" />',
754                 '<img src="' . $a->get_baseurl() . '/images/smiley-laughing.gif" alt=":-D" />',
755                 '<img src="' . $a->get_baseurl() . '/images/smiley-surprised.gif" alt="8-|" />',
756                 '<img src="' . $a->get_baseurl() . '/images/smiley-surprised.gif" alt="8-O" />',
757                 '<img src="' . $a->get_baseurl() . '/images/smiley-surprised.gif" alt=":-O" />',                
758                 '<img src="' . $a->get_baseurl() . '/images/smiley-thumbsup.gif" alt="\\o/" />',
759                 '<img src="' . $a->get_baseurl() . '/images/smiley-Oo.gif" alt="o.O" />',
760                 '<img src="' . $a->get_baseurl() . '/images/smiley-Oo.gif" alt="O.o" />',
761                 '<img src="' . $a->get_baseurl() . '/images/smiley-cry.gif" alt=":\'(" />',
762                 '<img src="' . $a->get_baseurl() . '/images/smiley-foot-in-mouth.gif" alt=":-!" />',
763                 '<img src="' . $a->get_baseurl() . '/images/smiley-undecided.gif" alt=":-/" />',
764                 '<img src="' . $a->get_baseurl() . '/images/smiley-embarassed.gif" alt=":-[" />',
765                 '<img src="' . $a->get_baseurl() . '/images/smiley-cool.gif" alt="8-)" />',
766                 '<img src="' . $a->get_baseurl() . '/images/beer_mug.gif" alt=":beer" />',
767                 '<img src="' . $a->get_baseurl() . '/images/beer_mug.gif" alt=":homebrew" />',
768                 '<img src="' . $a->get_baseurl() . '/images/coffee.gif" alt=":coffee" />',
769                 '<img src="' . $a->get_baseurl() . '/images/smiley-facepalm.gif" alt=":facepalm" />',
770                 '<a href="http://project.friendika.com">~friendika <img src="' . $a->get_baseurl() . '/images/friendika-16.png" alt="~friendika" /></a>',
771                 '<a href="http://friendica.com">~friendica <img src="' . $a->get_baseurl() . '/images/friendica-16.png" alt="~friendica" /></a>'
772         );
773
774         $params = array('texts' => $texts, 'icons' => $icons, 'string' => $s);
775         call_hooks('smilie', $params);
776
777         if($sample) {
778                 $s = '<div class="smiley-sample">';
779                 for($x = 0; $x < count($params['texts']); $x ++) {
780                         $s .= '<dl><dt>' . $params['texts'][$x] . '</dt><dd>' . $params['icons'][$x] . '</dd></dl>';
781                 }
782         }
783         else {
784                 $params['string'] = preg_replace_callback('/&lt;(3+)/','preg_heart',$params['string']);
785                 $s = str_replace($params['texts'],$params['icons'],$params['string']);
786         }
787
788         $s = preg_replace_callback('/<pre>(.*?)<\/pre>/ism','smile_decode',$s);
789         $s = preg_replace_callback('/<code>(.*?)<\/code>/ism','smile_decode',$s);
790
791         return $s;
792
793 }}
794
795 function smile_encode($m) {
796         return(str_replace($m[1],base64url_encode($m[1]),$m[0]));
797 }
798
799 function smile_decode($m) {
800         return(str_replace($m[1],base64url_decode($m[1]),$m[0]));
801 }
802
803 // expand <3333 to the correct number of hearts
804
805 function preg_heart($x) {
806         $a = get_app();
807         if(strlen($x[1]) == 1)
808                 return $x[0];
809         $t = '';
810         for($cnt = 0; $cnt < strlen($x[1]); $cnt ++)
811                 $t .= '<img src="' . $a->get_baseurl() . '/images/smiley-heart.gif" alt="<3" />';
812         $r =  str_replace($x[0],$t,$x[0]);
813         return $r;
814 }
815
816
817 if(! function_exists('day_translate')) {
818 function day_translate($s) {
819         $ret = str_replace(array('Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'),
820                 array( t('Monday'), t('Tuesday'), t('Wednesday'), t('Thursday'), t('Friday'), t('Saturday'), t('Sunday')),
821                 $s);
822
823         $ret = str_replace(array('January','February','March','April','May','June','July','August','September','October','November','December'),
824                 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')),
825                 $ret);
826
827         return $ret;
828 }}
829
830
831 if(! function_exists('normalise_link')) {
832 function normalise_link($url) {
833         $ret = str_replace(array('https:','//www.'), array('http:','//'), $url);
834         return(rtrim($ret,'/'));
835 }}
836
837 /**
838  *
839  * Compare two URLs to see if they are the same, but ignore
840  * slight but hopefully insignificant differences such as if one 
841  * is https and the other isn't, or if one is www.something and 
842  * the other isn't - and also ignore case differences.
843  *
844  * Return true if the URLs match, otherwise false.
845  *
846  */
847
848 if(! function_exists('link_compare')) {
849 function link_compare($a,$b) {
850         if(strcasecmp(normalise_link($a),normalise_link($b)) === 0)
851                 return true;
852         return false;
853 }}
854
855 // Given an item array, convert the body element from bbcode to html and add smilie icons.
856 // If attach is true, also add icons for item attachments
857
858
859 if(! function_exists('prepare_body')) {
860 function prepare_body($item,$attach = false) {
861
862         $a = get_app();
863         call_hooks('prepare_body_init', $item); 
864
865         $cache = get_config('system','itemcache');
866
867         if (($cache != '')) {
868                 $cachefile = $cache."/".$item["guid"]."-".strtotime($item["edited"])."-".hash("crc32", $item['body']);
869
870                 if (file_exists($cachefile))
871                         $s = file_get_contents($cachefile);
872                 else {
873                         $s = prepare_text($item['body']);
874                         file_put_contents($cachefile, $s);
875                 }
876         } else
877                 $s = prepare_text($item['body']);
878
879         $prep_arr = array('item' => $item, 'html' => $s);
880         call_hooks('prepare_body', $prep_arr);
881         $s = $prep_arr['html'];
882
883         if(! $attach) {
884                 return $s;
885         }
886
887         $arr = explode(',',$item['attach']);
888         if(count($arr)) {
889                 $s .= '<div class="body-attach">';
890                 foreach($arr as $r) {
891                         $matches = false;
892                         $icon = '';
893                         $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"\[\/attach\]|',$r,$matches);
894                         if($cnt) {
895                                 $icontype = strtolower(substr($matches[3],0,strpos($matches[3],'/')));
896                                 switch($icontype) {
897                                         case 'video':
898                                         case 'audio':
899                                         case 'image':
900                                         case 'text':
901                                                 $icon = '<div class="attachtype icon s22 type-' . $icontype . '"></div>';
902                                                 break;
903                                         default:
904                                                 $icon = '<div class="attachtype icon s22 type-unkn"></div>';
905                                                 break;
906                                 }
907                                 $title = ((strlen(trim($matches[4]))) ? escape_tags(trim($matches[4])) : escape_tags($matches[1]));
908                                 $title .= ' ' . $matches[2] . ' ' . t('bytes');
909
910                                 $s .= '<a href="' . strip_tags($matches[1]) . '" title="' . $title . '" class="attachlink" target="external-link" >' . $icon . '</a>';
911                         }
912                 }
913                 $s .= '<div class="clear"></div></div>';
914         }
915         $matches = false;
916         $cnt = preg_match_all('/<(.*?)>/',$item['file'],$matches,PREG_SET_ORDER);
917         if($cnt) {
918 //              logger('prepare_text: categories: ' . print_r($matches,true), LOGGER_DEBUG);
919                 foreach($matches as $mtch) {
920                         if(strlen($x))
921                                 $x .= ',';
922                         $x .= file_tag_decode($mtch[1]);
923                 }
924                 if(strlen($x))
925                         $s .= '<div class="categorytags"><span>' . t('Categories:') . ' </span>' . $x . '</div>'; 
926
927
928         }
929         $matches = false;
930         $x = '';
931         $cnt = preg_match_all('/\[(.*?)\]/',$item['file'],$matches,PREG_SET_ORDER);
932         if($cnt) {
933 //              logger('prepare_text: filed_under: ' . print_r($matches,true), LOGGER_DEBUG);
934                 foreach($matches as $mtch) {
935                         if(strlen($x))
936                                 $x .= '&nbsp;&nbsp;&nbsp;';
937                         $x .= file_tag_decode($mtch[1]). ' <a href="' . $a->get_baseurl() . '/filerm/' . $item['id'] . '?f=&term=' . file_tag_decode($mtch[1]) . '" title="' . t('remove') . '" >' . t('[remove]') . '</a>';
938                 }
939                 if(strlen($x) && (local_user() == $item['uid']))
940                         $s .= '<div class="filesavetags"><span>' . t('Filed under:') . ' </span>' . $x . '</div>'; 
941         }
942
943         $prep_arr = array('item' => $item, 'html' => $s);
944         call_hooks('prepare_body_final', $prep_arr);
945
946         return $prep_arr['html'];
947 }}
948
949
950 // Given a text string, convert from bbcode to html and add smilie icons.
951
952 if(! function_exists('prepare_text')) {
953 function prepare_text($text) {
954
955         require_once('include/bbcode.php');
956
957         if(stristr($text,'[nosmile]'))
958                 $s = bbcode($text);
959         else
960                 $s = smilies(bbcode($text));
961
962         return $s;
963 }}
964
965
966 /**
967  * return atom link elements for all of our hubs
968  */
969
970 if(! function_exists('feed_hublinks')) {
971 function feed_hublinks() {
972
973         $hub = get_config('system','huburl');
974
975         $hubxml = '';
976         if(strlen($hub)) {
977                 $hubs = explode(',', $hub);
978                 if(count($hubs)) {
979                         foreach($hubs as $h) {
980                                 $h = trim($h);
981                                 if(! strlen($h))
982                                         continue;
983                                 $hubxml .= '<link rel="hub" href="' . xmlify($h) . '" />' . "\n" ;
984                         }
985                 }
986         }
987         return $hubxml;
988 }}
989
990 /* return atom link elements for salmon endpoints */
991
992 if(! function_exists('feed_salmonlinks')) {
993 function feed_salmonlinks($nick) {
994
995         $a = get_app();
996
997         $salmon  = '<link rel="salmon" href="' . xmlify($a->get_baseurl() . '/salmon/' . $nick) . '" />' . "\n" ;
998
999         // old style links that status.net still needed as of 12/2010 
1000
1001         $salmon .= '  <link rel="http://salmon-protocol.org/ns/salmon-replies" href="' . xmlify($a->get_baseurl() . '/salmon/' . $nick) . '" />' . "\n" ; 
1002         $salmon .= '  <link rel="http://salmon-protocol.org/ns/salmon-mention" href="' . xmlify($a->get_baseurl() . '/salmon/' . $nick) . '" />' . "\n" ; 
1003         return $salmon;
1004 }}
1005
1006 if(! function_exists('get_plink')) {
1007 function get_plink($item) {
1008         $a = get_app(); 
1009         if (x($item,'plink') && (! $item['private'])){
1010                 return array(
1011                         'href' => $item['plink'],
1012                         'title' => t('link to source'),
1013                 );
1014         } else {
1015                 return false;
1016         }
1017 }}
1018
1019 if(! function_exists('unamp')) {
1020 function unamp($s) {
1021         return str_replace('&amp;', '&', $s);
1022 }}
1023
1024
1025
1026
1027 if(! function_exists('lang_selector')) {
1028 function lang_selector() {
1029         global $lang;
1030         $o = '<div id="lang-select-icon" class="icon language" title="' . t('Select an alternate language') . '" onclick="openClose(\'language-selector\');" ></div>';
1031         $o .= '<div id="language-selector" style="display: none;" >';
1032         $o .= '<form action="#" method="post" ><select name="system_language" onchange="this.form.submit();" >';
1033         $langs = glob('view/*/strings.php');
1034         if(is_array($langs) && count($langs)) {
1035                 $langs[] = '';
1036                 if(! in_array('view/en/strings.php',$langs))
1037                         $langs[] = 'view/en/';
1038                 asort($langs);
1039                 foreach($langs as $l) {
1040                         if($l == '') {
1041                                 $default_selected = ((! x($_SESSION,'language')) ? ' selected="selected" ' : '');
1042                                 $o .= '<option value="" ' . $default_selected . '>' . t('default') . '</option>';
1043                                 continue;
1044                         }
1045                         $ll = substr($l,5);
1046                         $ll = substr($ll,0,strrpos($ll,'/'));
1047                         $selected = (($ll === $lang && (x($_SESSION, 'language'))) ? ' selected="selected" ' : '');
1048                         $o .= '<option value="' . $ll . '"' . $selected . '>' . $ll . '</option>';
1049                 }
1050         }
1051         $o .= '</select></form></div>';
1052         return $o;
1053 }}
1054
1055
1056 if(! function_exists('return_bytes')) {
1057 function return_bytes ($size_str) {
1058     switch (substr ($size_str, -1))
1059     {
1060         case 'M': case 'm': return (int)$size_str * 1048576;
1061         case 'K': case 'k': return (int)$size_str * 1024;
1062         case 'G': case 'g': return (int)$size_str * 1073741824;
1063         default: return $size_str;
1064     }
1065 }}
1066
1067 function generate_user_guid() {
1068         $found = true;
1069         do {
1070                 $guid = random_string(16);
1071                 $x = q("SELECT `uid` FROM `user` WHERE `guid` = '%s' LIMIT 1",
1072                         dbesc($guid)
1073                 );
1074                 if(! count($x))
1075                         $found = false;
1076         } while ($found == true );
1077         return $guid;
1078 }
1079
1080
1081
1082 function base64url_encode($s, $strip_padding = false) {
1083
1084         $s = strtr(base64_encode($s),'+/','-_');
1085
1086         if($strip_padding)
1087                 $s = str_replace('=','',$s);
1088
1089         return $s;
1090 }
1091
1092 function base64url_decode($s) {
1093
1094         if(is_array($s)) {
1095                 logger('base64url_decode: illegal input: ' . print_r(debug_backtrace(), true));
1096                 return $s;
1097         }
1098
1099 /*
1100  *  // Placeholder for new rev of salmon which strips base64 padding.
1101  *  // PHP base64_decode handles the un-padded input without requiring this step
1102  *  // Uncomment if you find you need it.
1103  *
1104  *      $l = strlen($s);
1105  *      if(! strpos($s,'=')) {
1106  *              $m = $l % 4;
1107  *              if($m == 2)
1108  *                      $s .= '==';
1109  *              if($m == 3)
1110  *                      $s .= '=';
1111  *      }
1112  *
1113  */
1114
1115         return base64_decode(strtr($s,'-_','+/'));
1116 }
1117
1118
1119 if (!function_exists('str_getcsv')) {
1120     function str_getcsv($input, $delimiter = ',', $enclosure = '"', $escape = '\\', $eol = '\n') {
1121         if (is_string($input) && !empty($input)) {
1122             $output = array();
1123             $tmp    = preg_split("/".$eol."/",$input);
1124             if (is_array($tmp) && !empty($tmp)) {
1125                 while (list($line_num, $line) = each($tmp)) {
1126                     if (preg_match("/".$escape.$enclosure."/",$line)) {
1127                         while ($strlen = strlen($line)) {
1128                             $pos_delimiter       = strpos($line,$delimiter);
1129                             $pos_enclosure_start = strpos($line,$enclosure);
1130                             if (
1131                                 is_int($pos_delimiter) && is_int($pos_enclosure_start)
1132                                 && ($pos_enclosure_start < $pos_delimiter)
1133                                 ) {
1134                                 $enclosed_str = substr($line,1);
1135                                 $pos_enclosure_end = strpos($enclosed_str,$enclosure);
1136                                 $enclosed_str = substr($enclosed_str,0,$pos_enclosure_end);
1137                                 $output[$line_num][] = $enclosed_str;
1138                                 $offset = $pos_enclosure_end+3;
1139                             } else {
1140                                 if (empty($pos_delimiter) && empty($pos_enclosure_start)) {
1141                                     $output[$line_num][] = substr($line,0);
1142                                     $offset = strlen($line);
1143                                 } else {
1144                                     $output[$line_num][] = substr($line,0,$pos_delimiter);
1145                                     $offset = (
1146                                                 !empty($pos_enclosure_start)
1147                                                 && ($pos_enclosure_start < $pos_delimiter)
1148                                                 )
1149                                                 ?$pos_enclosure_start
1150                                                 :$pos_delimiter+1;
1151                                 }
1152                             }
1153                             $line = substr($line,$offset);
1154                         }
1155                     } else {
1156                         $line = preg_split("/".$delimiter."/",$line);
1157    
1158                         /*
1159                          * Validating against pesky extra line breaks creating false rows.
1160                          */
1161                         if (is_array($line) && !empty($line[0])) {
1162                             $output[$line_num] = $line;
1163                         } 
1164                     }
1165                 }
1166                 return $output;
1167             } else {
1168                 return false;
1169             }
1170         } else {
1171             return false;
1172         }
1173     }
1174
1175
1176 function cleardiv() {
1177         return '<div class="clear"></div>';
1178 }
1179
1180
1181 function bb_translate_video($s) {
1182
1183         $matches = null;
1184         $r = preg_match_all("/\[video\](.*?)\[\/video\]/ism",$s,$matches,PREG_SET_ORDER);
1185         if($r) {
1186                 foreach($matches as $mtch) {
1187                         if((stristr($mtch[1],'youtube')) || (stristr($mtch[1],'youtu.be')))
1188                                 $s = str_replace($mtch[0],'[youtube]' . $mtch[1] . '[/youtube]',$s);
1189                         elseif(stristr($mtch[1],'vimeo'))
1190                                 $s = str_replace($mtch[0],'[vimeo]' . $mtch[1] . '[/vimeo]',$s);
1191                 }
1192         }
1193         return $s;      
1194 }
1195
1196 function html2bb_video($s) {
1197
1198         $s = preg_replace('#<object[^>]+>(.*?)https+://www.youtube.com/((?:v|cp)/[A-Za-z0-9\-_=]+)(.*?)</object>#ism',
1199                         '[youtube]$2[/youtube]', $s);
1200
1201         $s = preg_replace('#<iframe[^>](.*?)https+://www.youtube.com/embed/([A-Za-z0-9\-_=]+)(.*?)</iframe>#ism',
1202                         '[youtube]$2[/youtube]', $s);
1203
1204         $s = preg_replace('#<iframe[^>](.*?)https+://player.vimeo.com/video/([0-9]+)(.*?)</iframe>#ism',
1205                         '[vimeo]$2[/vimeo]', $s);
1206
1207         return $s;
1208 }
1209
1210 /**
1211  * apply xmlify() to all values of array $val, recursively
1212  */
1213 function array_xmlify($val){
1214         if (is_bool($val)) return $val?"true":"false";
1215         if (is_array($val)) return array_map('array_xmlify', $val);
1216         return xmlify((string) $val);
1217 }
1218
1219
1220 function reltoabs($text, $base)
1221 {
1222   if (empty($base))
1223     return $text;
1224
1225   $base = rtrim($base,'/');
1226
1227   $base2 = $base . "/";
1228         
1229   // Replace links
1230   $pattern = "/<a([^>]*) href=\"(?!http|https|\/)([^\"]*)\"/";
1231   $replace = "<a\${1} href=\"" . $base2 . "\${2}\"";
1232   $text = preg_replace($pattern, $replace, $text);
1233
1234   $pattern = "/<a([^>]*) href=\"(?!http|https)([^\"]*)\"/";
1235   $replace = "<a\${1} href=\"" . $base . "\${2}\"";
1236   $text = preg_replace($pattern, $replace, $text);
1237
1238   // Replace images
1239   $pattern = "/<img([^>]*) src=\"(?!http|https|\/)([^\"]*)\"/";
1240   $replace = "<img\${1} src=\"" . $base2 . "\${2}\"";
1241   $text = preg_replace($pattern, $replace, $text); 
1242
1243   $pattern = "/<img([^>]*) src=\"(?!http|https)([^\"]*)\"/";
1244   $replace = "<img\${1} src=\"" . $base . "\${2}\"";
1245   $text = preg_replace($pattern, $replace, $text); 
1246
1247
1248   // Done
1249   return $text;
1250 }
1251
1252 function item_post_type($item) {
1253         if(intval($item['event-id']))
1254                 return t('event');
1255         if(strlen($item['resource-id']))
1256                 return t('photo');
1257         if(strlen($item['verb']) && $item['verb'] !== ACTIVITY_POST)
1258                 return t('activity');
1259         if($item['id'] != $item['parent'])
1260                 return t('comment');
1261         return t('post');
1262 }
1263
1264 // post categories and "save to file" use the same item.file table for storage.
1265 // We will differentiate the different uses by wrapping categories in angle brackets
1266 // and save to file categories in square brackets.
1267 // To do this we need to escape these characters if they appear in our tag. 
1268
1269 function file_tag_encode($s) {
1270         return str_replace(array('<','>','[',']'),array('%3c','%3e','%5b','%5d'),$s);
1271 }
1272
1273 function file_tag_decode($s) {
1274         return str_replace(array('%3c','%3e','%5b','%5d'),array('<','>','[',']'),$s);
1275 }
1276
1277 function file_tag_file_query($table,$s,$type = 'file') {
1278         if($type == 'file')
1279                 $str = preg_quote( '[' . file_tag_encode($s) . ']' );
1280         else
1281                 $str = preg_quote( '<' . file_tag_encode($s) . '>' );
1282         return " AND " . (($table) ? dbesc($table) . '.' : '') . "file regexp '" . dbesc($str) . "' ";
1283 }
1284
1285 function file_tag_save_file($uid,$item,$file) {
1286         $result = false;
1287         if(! intval($uid))
1288                 return false;
1289         $r = q("select file from item where id = %d and uid = %d limit 1",
1290                 intval($item),
1291                 intval($uid)
1292         );
1293         if(count($r)) {
1294                 if(! stristr($r[0]['file'],'[' . file_tag_encode($file) . ']'))
1295                         q("update item set file = '%s' where id = %d and uid = %d limit 1",
1296                                 dbesc($r[0]['file'] . '[' . file_tag_encode($file) . ']'),
1297                                 intval($item),
1298                                 intval($uid)
1299                         );
1300                 $saved = get_pconfig($uid,'system','filetags');
1301                 if((! strlen($saved)) || (! stristr($saved,'[' . file_tag_encode($file) . ']')))
1302                         set_pconfig($uid,'system','filetags',$saved . '[' . file_tag_encode($file) . ']');
1303         }
1304         return true;
1305 }
1306
1307 function file_tag_unsave_file($uid,$item,$file) {
1308         $result = false;
1309         if(! intval($uid))
1310                 return false;
1311
1312         $pattern = '[' . file_tag_encode($file) . ']' ;
1313
1314         $r = q("select file from item where id = %d and uid = %d limit 1",
1315                 intval($item),
1316                 intval($uid)
1317         );
1318         if(! count($r))
1319                 return false;
1320
1321         q("update item set file = '%s' where id = %d and uid = %d limit 1",
1322                 dbesc(str_replace($pattern,'',$r[0]['file'])),
1323                 intval($item),
1324                 intval($uid)
1325         );
1326
1327         $r = q("select file from item where uid = %d " . file_tag_file_query('item',$file),
1328                 intval($uid)
1329         );
1330
1331         if(! count($r)) {
1332                 $saved = get_pconfig($uid,'system','filetags');
1333                 set_pconfig($uid,'system','filetags',str_replace($pattern,'',$saved));
1334         }
1335         return true;
1336 }
1337
1338 function normalise_openid($s) {
1339         return trim(str_replace(array('http://','https://'),array('',''),$s),'/');
1340 }
1341
1342
1343 function undo_post_tagging($s) {
1344         $matches = null;
1345         $cnt = preg_match_all('/([@#])\[url=(.*?)\](.*?)\[\/url\]/ism',$s,$matches,PREG_SET_ORDER);
1346         if($cnt) {
1347                 foreach($matches as $mtch) {
1348                         $s = str_replace($mtch[0], $mtch[1] . $mtch[3],$s);
1349                 }
1350         }
1351         return $s;
1352 }
1353