]> git.mxchange.org Git - friendica.git/blob - include/text.php
Merge pull request #135 from simonlnu/master
[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 $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() . $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         $a = get_app();
698
699         $s = preg_replace_callback('/<pre>(.*?)<\/pre>/ism','smile_encode',$s);
700         $s = preg_replace_callback('/<code>(.*?)<\/code>/ism','smile_encode',$s);
701
702         $texts =  array( 
703                 '&lt;3', 
704                 '&lt;/3', 
705                 '&lt;\\3', 
706                 ':-)', 
707 //              ':)', 
708                 ';-)', 
709 //              ';)', 
710                 ':-(', 
711 //              ':(', 
712                 ':-P', 
713 //              ':P', 
714                 ':-"', 
715                 ':-&quot;', 
716                 ':-x', 
717                 ':-X', 
718                 ':-D', 
719 //              ':D', 
720                 '8-|', 
721                 '8-O', 
722                 ':-O', 
723                 '\\o/', 
724                 'o.O', 
725                 'O.o', 
726                 '\\.../', 
727                 '\\ooo/', 
728                 ":'(", 
729                 ":-!", 
730                 ":-/", 
731                 ":-[", 
732                 "8-)",
733                 ':beer', 
734                 ':homebrew', 
735                 ':coffee', 
736                 ':facepalm',
737                 ':headdesk',
738                 '~friendika', 
739                 '~friendica', 
740 //              'Diaspora*' 
741                 ':beard',
742                 ':whitebeard'
743
744         );
745
746         $icons = array(
747                 '<img src="' . $a->get_baseurl() . '/images/smiley-heart.gif" alt="<3" />',
748                 '<img src="' . $a->get_baseurl() . '/images/smiley-brokenheart.gif" alt="</3" />',
749                 '<img src="' . $a->get_baseurl() . '/images/smiley-brokenheart.gif" alt="<\\3" />',
750                 '<img src="' . $a->get_baseurl() . '/images/smiley-smile.gif" alt=":-)" />',
751 //              '<img src="' . $a->get_baseurl() . '/images/smiley-smile.gif" alt=":)" />',
752                 '<img src="' . $a->get_baseurl() . '/images/smiley-wink.gif" alt=";-)" />',
753 //              '<img src="' . $a->get_baseurl() . '/images/smiley-wink.gif" alt=";)"/>',                
754                 '<img src="' . $a->get_baseurl() . '/images/smiley-frown.gif" alt=":-(" />',
755 //              '<img src="' . $a->get_baseurl() . '/images/smiley-frown.gif" alt=":(" />',
756                 '<img src="' . $a->get_baseurl() . '/images/smiley-tongue-out.gif" alt=":-P" />',
757 //              '<img src="' . $a->get_baseurl() . '/images/smiley-tongue-out.gif" alt=":P" />',
758                 '<img src="' . $a->get_baseurl() . '/images/smiley-kiss.gif" alt=":-\"" />',
759                 '<img src="' . $a->get_baseurl() . '/images/smiley-kiss.gif" alt=":-\"" />',
760                 '<img src="' . $a->get_baseurl() . '/images/smiley-kiss.gif" alt=":-x" />',
761                 '<img src="' . $a->get_baseurl() . '/images/smiley-kiss.gif" alt=":-X" />',
762                 '<img src="' . $a->get_baseurl() . '/images/smiley-laughing.gif" alt=":-D" />',
763 //              '<img src="' . $a->get_baseurl() . '/images/smiley-laughing.gif" alt=":D"/>',                
764                 '<img src="' . $a->get_baseurl() . '/images/smiley-surprised.gif" alt="8-|" />',
765                 '<img src="' . $a->get_baseurl() . '/images/smiley-surprised.gif" alt="8-O" />',
766                 '<img src="' . $a->get_baseurl() . '/images/smiley-surprised.gif" alt=":-O" />',                
767                 '<img src="' . $a->get_baseurl() . '/images/smiley-thumbsup.gif" alt="\\o/" />',
768                 '<img src="' . $a->get_baseurl() . '/images/smiley-Oo.gif" alt="o.O" />',
769                 '<img src="' . $a->get_baseurl() . '/images/smiley-Oo.gif" alt="O.o" />',
770                 '<img src="' . $a->get_baseurl() . '/images/smiley-shaka.gif" alt="\\.../" />',
771                 '<img src="' . $a->get_baseurl() . '/images/smiley-shaka.gif" alt="\\ooo/" />',
772                 '<img src="' . $a->get_baseurl() . '/images/smiley-cry.gif" alt=":\'(" />',
773                 '<img src="' . $a->get_baseurl() . '/images/smiley-foot-in-mouth.gif" alt=":-!" />',
774                 '<img src="' . $a->get_baseurl() . '/images/smiley-undecided.gif" alt=":-/" />',
775                 '<img src="' . $a->get_baseurl() . '/images/smiley-embarassed.gif" alt=":-[" />',
776                 '<img src="' . $a->get_baseurl() . '/images/smiley-cool.gif" alt="8-)" />',
777                 '<img src="' . $a->get_baseurl() . '/images/beer_mug.gif" alt=":beer" />',
778                 '<img src="' . $a->get_baseurl() . '/images/beer_mug.gif" alt=":homebrew" />',
779                 '<img src="' . $a->get_baseurl() . '/images/coffee.gif" alt=":coffee" />',
780                 '<img src="' . $a->get_baseurl() . '/images/smiley-facepalm.gif" alt=":facepalm" />',
781                 '<img src="' . $a->get_baseurl() . '/images/smiley-bangheaddesk.gif" alt=":headdesk" />',
782                 '<a href="http://project.friendika.com">~friendika <img src="' . $a->get_baseurl() . '/images/friendika-16.png" alt="~friendika" /></a>',
783                 '<a href="http://friendica.com">~friendica <img src="' . $a->get_baseurl() . '/images/friendica-16.png" alt="~friendica" /></a>',
784 //              '<a href="http://diasporafoundation.org">Diaspora<img src="' . $a->get_baseurl() . '/images/diaspora.png" alt="Diaspora*" /></a>',
785                 '<img src="' . $a->get_baseurl() . '/images/smiley-beard.png" alt=":beard" />',
786                 '<img src="' . $a->get_baseurl() . '/images/smiley-whitebeard.png" alt=":whitebeard" />'
787         );
788
789         $params = array('texts' => $texts, 'icons' => $icons, 'string' => $s);
790         call_hooks('smilie', $params);
791
792         if($sample) {
793                 $s = '<div class="smiley-sample">';
794                 for($x = 0; $x < count($params['texts']); $x ++) {
795                         $s .= '<dl><dt>' . $params['texts'][$x] . '</dt><dd>' . $params['icons'][$x] . '</dd></dl>';
796                 }
797         }
798         else {
799                 $params['string'] = preg_replace_callback('/&lt;(3+)/','preg_heart',$params['string']);
800                 $s = str_replace($params['texts'],$params['icons'],$params['string']);
801         }
802
803         $s = preg_replace_callback('/<pre>(.*?)<\/pre>/ism','smile_decode',$s);
804         $s = preg_replace_callback('/<code>(.*?)<\/code>/ism','smile_decode',$s);
805
806         return $s;
807
808 }}
809
810 function smile_encode($m) {
811         return(str_replace($m[1],base64url_encode($m[1]),$m[0]));
812 }
813
814 function smile_decode($m) {
815         return(str_replace($m[1],base64url_decode($m[1]),$m[0]));
816 }
817
818 // expand <3333 to the correct number of hearts
819
820 function preg_heart($x) {
821         $a = get_app();
822         if(strlen($x[1]) == 1)
823                 return $x[0];
824         $t = '';
825         for($cnt = 0; $cnt < strlen($x[1]); $cnt ++)
826                 $t .= '<img src="' . $a->get_baseurl() . '/images/smiley-heart.gif" alt="<3" />';
827         $r =  str_replace($x[0],$t,$x[0]);
828         return $r;
829 }
830
831
832 if(! function_exists('day_translate')) {
833 function day_translate($s) {
834         $ret = str_replace(array('Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'),
835                 array( t('Monday'), t('Tuesday'), t('Wednesday'), t('Thursday'), t('Friday'), t('Saturday'), t('Sunday')),
836                 $s);
837
838         $ret = str_replace(array('January','February','March','April','May','June','July','August','September','October','November','December'),
839                 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')),
840                 $ret);
841
842         return $ret;
843 }}
844
845
846 if(! function_exists('normalise_link')) {
847 function normalise_link($url) {
848         $ret = str_replace(array('https:','//www.'), array('http:','//'), $url);
849         return(rtrim($ret,'/'));
850 }}
851
852 /**
853  *
854  * Compare two URLs to see if they are the same, but ignore
855  * slight but hopefully insignificant differences such as if one 
856  * is https and the other isn't, or if one is www.something and 
857  * the other isn't - and also ignore case differences.
858  *
859  * Return true if the URLs match, otherwise false.
860  *
861  */
862
863 if(! function_exists('link_compare')) {
864 function link_compare($a,$b) {
865         if(strcasecmp(normalise_link($a),normalise_link($b)) === 0)
866                 return true;
867         return false;
868 }}
869
870 // Given an item array, convert the body element from bbcode to html and add smilie icons.
871 // If attach is true, also add icons for item attachments
872
873
874 if(! function_exists('prepare_body')) {
875 function prepare_body($item,$attach = false) {
876
877         $a = get_app();
878         call_hooks('prepare_body_init', $item); 
879
880         $s = prepare_text($item['body']);
881
882         $prep_arr = array('item' => $item, 'html' => $s);
883         call_hooks('prepare_body', $prep_arr);
884         $s = $prep_arr['html'];
885
886         if(! $attach)
887                 return $s;
888
889         $arr = explode(',',$item['attach']);
890         if(count($arr)) {
891                 $s .= '<div class="body-attach">';
892                 foreach($arr as $r) {
893                         $matches = false;
894                         $icon = '';
895                         $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"\[\/attach\]|',$r,$matches);
896                         if($cnt) {
897                                 $icontype = strtolower(substr($matches[3],0,strpos($matches[3],'/')));
898                                 switch($icontype) {
899                                         case 'video':
900                                         case 'audio':
901                                         case 'image':
902                                         case 'text':
903                                                 $icon = '<div class="attachtype icon s22 type-' . $icontype . '"></div>';
904                                                 break;
905                                         default:
906                                                 $icon = '<div class="attachtype icon s22 type-unkn"></div>';
907                                                 break;
908                                 }
909                                 $title = ((strlen(trim($matches[4]))) ? escape_tags(trim($matches[4])) : escape_tags($matches[1]));
910                                 $title .= ' ' . $matches[2] . ' ' . t('bytes');
911
912                                 $s .= '<a href="' . strip_tags($matches[1]) . '" title="' . $title . '" class="attachlink" target="external-link" >' . $icon . '</a>';
913                         }
914                 }
915                 $s .= '<div class="clear"></div></div>';
916         }
917         $matches = false;
918         $cnt = preg_match_all('/<(.*?)>/',$item['file'],$matches,PREG_SET_ORDER);
919         if($cnt) {
920 //              logger('prepare_text: categories: ' . print_r($matches,true), LOGGER_DEBUG);
921                 foreach($matches as $mtch) {
922                         if(strlen($x))
923                                 $x .= ',';
924                         $x .= file_tag_decode($mtch[1]);
925                 }
926                 if(strlen($x))
927                         $s .= '<div class="categorytags"><span>' . t('Categories:') . ' </span>' . $x . '</div>'; 
928
929
930         }
931         $matches = false;
932         $x = '';
933         $cnt = preg_match_all('/\[(.*?)\]/',$item['file'],$matches,PREG_SET_ORDER);
934         if($cnt) {
935 //              logger('prepare_text: filed_under: ' . print_r($matches,true), LOGGER_DEBUG);
936                 foreach($matches as $mtch) {
937                         if(strlen($x))
938                                 $x .= '&nbsp;&nbsp;&nbsp;';
939                         $x .= file_tag_decode($mtch[1]). ' <a href="' . $a->get_baseurl() . '/filerm/' . $item['id'] . '?f=&term=' . file_tag_decode($mtch[1]) . '" title="' . t('remove') . '" >' . t('[remove]') . '</a>';
940                 }
941                 if(strlen($x) && (local_user() == $item['uid']))
942                         $s .= '<div class="filesavetags"><span>' . t('Filed under:') . ' </span>' . $x . '</div>'; 
943         }
944
945
946         $prep_arr = array('item' => $item, 'html' => $s);
947         call_hooks('prepare_body_final', $prep_arr);
948         return $prep_arr['html'];
949 }}
950
951
952 // Given a text string, convert from bbcode to html and add smilie icons.
953
954 if(! function_exists('prepare_text')) {
955 function prepare_text($text) {
956
957         require_once('include/bbcode.php');
958
959         if(stristr($text,'[nosmile]'))
960                 $s = bbcode($text);
961         else
962                 $s = smilies(bbcode($text));
963
964         return $s;
965 }}
966
967
968 /**
969  * return atom link elements for all of our hubs
970  */
971
972 if(! function_exists('feed_hublinks')) {
973 function feed_hublinks() {
974
975         $hub = get_config('system','huburl');
976
977         $hubxml = '';
978         if(strlen($hub)) {
979                 $hubs = explode(',', $hub);
980                 if(count($hubs)) {
981                         foreach($hubs as $h) {
982                                 $h = trim($h);
983                                 if(! strlen($h))
984                                         continue;
985                                 $hubxml .= '<link rel="hub" href="' . xmlify($h) . '" />' . "\n" ;
986                         }
987                 }
988         }
989         return $hubxml;
990 }}
991
992 /* return atom link elements for salmon endpoints */
993
994 if(! function_exists('feed_salmonlinks')) {
995 function feed_salmonlinks($nick) {
996
997         $a = get_app();
998
999         $salmon  = '<link rel="salmon" href="' . xmlify($a->get_baseurl() . '/salmon/' . $nick) . '" />' . "\n" ;
1000
1001         // old style links that status.net still needed as of 12/2010 
1002
1003         $salmon .= '  <link rel="http://salmon-protocol.org/ns/salmon-replies" href="' . xmlify($a->get_baseurl() . '/salmon/' . $nick) . '" />' . "\n" ; 
1004         $salmon .= '  <link rel="http://salmon-protocol.org/ns/salmon-mention" href="' . xmlify($a->get_baseurl() . '/salmon/' . $nick) . '" />' . "\n" ; 
1005         return $salmon;
1006 }}
1007
1008 if(! function_exists('get_plink')) {
1009 function get_plink($item) {
1010         $a = get_app(); 
1011         if (x($item,'plink') && (! $item['private'])){
1012                 return array(
1013                         'href' => $item['plink'],
1014                         'title' => t('link to source'),
1015                 );
1016         } else {
1017                 return false;
1018         }
1019 }}
1020
1021 if(! function_exists('unamp')) {
1022 function unamp($s) {
1023         return str_replace('&amp;', '&', $s);
1024 }}
1025
1026
1027
1028
1029 if(! function_exists('lang_selector')) {
1030 function lang_selector() {
1031         global $lang;
1032         $o = '<div id="lang-select-icon" class="icon language" title="' . t('Select an alternate language') . '" onclick="openClose(\'language-selector\');" ></div>';
1033         $o .= '<div id="language-selector" style="display: none;" >';
1034         $o .= '<form action="#" method="post" ><select name="system_language" onchange="this.form.submit();" >';
1035         $langs = glob('view/*/strings.php');
1036         if(is_array($langs) && count($langs)) {
1037                 $langs[] = '';
1038                 if(! in_array('view/en/strings.php',$langs))
1039                         $langs[] = 'view/en/';
1040                 asort($langs);
1041                 foreach($langs as $l) {
1042                         if($l == '') {
1043                                 $default_selected = ((! x($_SESSION,'language')) ? ' selected="selected" ' : '');
1044                                 $o .= '<option value="" ' . $default_selected . '>' . t('default') . '</option>';
1045                                 continue;
1046                         }
1047                         $ll = substr($l,5);
1048                         $ll = substr($ll,0,strrpos($ll,'/'));
1049                         $selected = (($ll === $lang && (x($_SESSION, 'language'))) ? ' selected="selected" ' : '');
1050                         $o .= '<option value="' . $ll . '"' . $selected . '>' . $ll . '</option>';
1051                 }
1052         }
1053         $o .= '</select></form></div>';
1054         return $o;
1055 }}
1056
1057
1058 if(! function_exists('return_bytes')) {
1059 function return_bytes ($size_str) {
1060     switch (substr ($size_str, -1))
1061     {
1062         case 'M': case 'm': return (int)$size_str * 1048576;
1063         case 'K': case 'k': return (int)$size_str * 1024;
1064         case 'G': case 'g': return (int)$size_str * 1073741824;
1065         default: return $size_str;
1066     }
1067 }}
1068
1069 function generate_user_guid() {
1070         $found = true;
1071         do {
1072                 $guid = random_string(16);
1073                 $x = q("SELECT `uid` FROM `user` WHERE `guid` = '%s' LIMIT 1",
1074                         dbesc($guid)
1075                 );
1076                 if(! count($x))
1077                         $found = false;
1078         } while ($found == true );
1079         return $guid;
1080 }
1081
1082
1083
1084 function base64url_encode($s, $strip_padding = false) {
1085
1086         $s = strtr(base64_encode($s),'+/','-_');
1087
1088         if($strip_padding)
1089                 $s = str_replace('=','',$s);
1090
1091         return $s;
1092 }
1093
1094 function base64url_decode($s) {
1095
1096         if(is_array($s)) {
1097                 logger('base64url_decode: illegal input: ' . print_r(debug_backtrace(), true));
1098                 return $s;
1099         }
1100
1101 /*
1102  *  // Placeholder for new rev of salmon which strips base64 padding.
1103  *  // PHP base64_decode handles the un-padded input without requiring this step
1104  *  // Uncomment if you find you need it.
1105  *
1106  *      $l = strlen($s);
1107  *      if(! strpos($s,'=')) {
1108  *              $m = $l % 4;
1109  *              if($m == 2)
1110  *                      $s .= '==';
1111  *              if($m == 3)
1112  *                      $s .= '=';
1113  *      }
1114  *
1115  */
1116
1117         return base64_decode(strtr($s,'-_','+/'));
1118 }
1119
1120
1121 if (!function_exists('str_getcsv')) {
1122     function str_getcsv($input, $delimiter = ',', $enclosure = '"', $escape = '\\', $eol = '\n') {
1123         if (is_string($input) && !empty($input)) {
1124             $output = array();
1125             $tmp    = preg_split("/".$eol."/",$input);
1126             if (is_array($tmp) && !empty($tmp)) {
1127                 while (list($line_num, $line) = each($tmp)) {
1128                     if (preg_match("/".$escape.$enclosure."/",$line)) {
1129                         while ($strlen = strlen($line)) {
1130                             $pos_delimiter       = strpos($line,$delimiter);
1131                             $pos_enclosure_start = strpos($line,$enclosure);
1132                             if (
1133                                 is_int($pos_delimiter) && is_int($pos_enclosure_start)
1134                                 && ($pos_enclosure_start < $pos_delimiter)
1135                                 ) {
1136                                 $enclosed_str = substr($line,1);
1137                                 $pos_enclosure_end = strpos($enclosed_str,$enclosure);
1138                                 $enclosed_str = substr($enclosed_str,0,$pos_enclosure_end);
1139                                 $output[$line_num][] = $enclosed_str;
1140                                 $offset = $pos_enclosure_end+3;
1141                             } else {
1142                                 if (empty($pos_delimiter) && empty($pos_enclosure_start)) {
1143                                     $output[$line_num][] = substr($line,0);
1144                                     $offset = strlen($line);
1145                                 } else {
1146                                     $output[$line_num][] = substr($line,0,$pos_delimiter);
1147                                     $offset = (
1148                                                 !empty($pos_enclosure_start)
1149                                                 && ($pos_enclosure_start < $pos_delimiter)
1150                                                 )
1151                                                 ?$pos_enclosure_start
1152                                                 :$pos_delimiter+1;
1153                                 }
1154                             }
1155                             $line = substr($line,$offset);
1156                         }
1157                     } else {
1158                         $line = preg_split("/".$delimiter."/",$line);
1159    
1160                         /*
1161                          * Validating against pesky extra line breaks creating false rows.
1162                          */
1163                         if (is_array($line) && !empty($line[0])) {
1164                             $output[$line_num] = $line;
1165                         } 
1166                     }
1167                 }
1168                 return $output;
1169             } else {
1170                 return false;
1171             }
1172         } else {
1173             return false;
1174         }
1175     }
1176
1177
1178 function cleardiv() {
1179         return '<div class="clear"></div>';
1180 }
1181
1182
1183 function bb_translate_video($s) {
1184
1185         $matches = null;
1186         $r = preg_match_all("/\[video\](.*?)\[\/video\]/ism",$s,$matches,PREG_SET_ORDER);
1187         if($r) {
1188                 foreach($matches as $mtch) {
1189                         if((stristr($mtch[1],'youtube')) || (stristr($mtch[1],'youtu.be')))
1190                                 $s = str_replace($mtch[0],'[youtube]' . $mtch[1] . '[/youtube]',$s);
1191                         elseif(stristr($mtch[1],'vimeo'))
1192                                 $s = str_replace($mtch[0],'[vimeo]' . $mtch[1] . '[/vimeo]',$s);
1193                 }
1194         }
1195         return $s;      
1196 }
1197
1198 function html2bb_video($s) {
1199
1200         $s = preg_replace('#<object[^>]+>(.*?)https+://www.youtube.com/((?:v|cp)/[A-Za-z0-9\-_=]+)(.*?)</object>#ism',
1201                         '[youtube]$2[/youtube]', $s);
1202
1203         $s = preg_replace('#<iframe[^>](.*?)https+://www.youtube.com/embed/([A-Za-z0-9\-_=]+)(.*?)</iframe>#ism',
1204                         '[youtube]$2[/youtube]', $s);
1205
1206         $s = preg_replace('#<iframe[^>](.*?)https+://player.vimeo.com/video/([0-9]+)(.*?)</iframe>#ism',
1207                         '[vimeo]$2[/vimeo]', $s);
1208
1209         return $s;
1210 }
1211
1212 /**
1213  * apply xmlify() to all values of array $val, recursively
1214  */
1215 function array_xmlify($val){
1216         if (is_bool($val)) return $val?"true":"false";
1217         if (is_array($val)) return array_map('array_xmlify', $val);
1218         return xmlify((string) $val);
1219 }
1220
1221
1222 function reltoabs($text, $base)
1223 {
1224   if (empty($base))
1225     return $text;
1226
1227   $base = rtrim($base,'/');
1228
1229   $base2 = $base . "/";
1230         
1231   // Replace links
1232   $pattern = "/<a([^>]*) href=\"(?!http|https|\/)([^\"]*)\"/";
1233   $replace = "<a\${1} href=\"" . $base2 . "\${2}\"";
1234   $text = preg_replace($pattern, $replace, $text);
1235
1236   $pattern = "/<a([^>]*) href=\"(?!http|https)([^\"]*)\"/";
1237   $replace = "<a\${1} href=\"" . $base . "\${2}\"";
1238   $text = preg_replace($pattern, $replace, $text);
1239
1240   // Replace images
1241   $pattern = "/<img([^>]*) src=\"(?!http|https|\/)([^\"]*)\"/";
1242   $replace = "<img\${1} src=\"" . $base2 . "\${2}\"";
1243   $text = preg_replace($pattern, $replace, $text); 
1244
1245   $pattern = "/<img([^>]*) src=\"(?!http|https)([^\"]*)\"/";
1246   $replace = "<img\${1} src=\"" . $base . "\${2}\"";
1247   $text = preg_replace($pattern, $replace, $text); 
1248
1249
1250   // Done
1251   return $text;
1252 }
1253
1254 function item_post_type($item) {
1255         if(intval($item['event-id']))
1256                 return t('event');
1257         if(strlen($item['resource-id']))
1258                 return t('photo');
1259         if(strlen($item['verb']) && $item['verb'] !== ACTIVITY_POST)
1260                 return t('activity');
1261         if($item['id'] != $item['parent'])
1262                 return t('comment');
1263         return t('post');
1264 }
1265
1266 // post categories and "save to file" use the same item.file table for storage.
1267 // We will differentiate the different uses by wrapping categories in angle brackets
1268 // and save to file categories in square brackets.
1269 // To do this we need to escape these characters if they appear in our tag. 
1270
1271 function file_tag_encode($s) {
1272         return str_replace(array('<','>','[',']'),array('%3c','%3e','%5b','%5d'),$s);
1273 }
1274
1275 function file_tag_decode($s) {
1276         return str_replace(array('%3c','%3e','%5b','%5d'),array('<','>','[',']'),$s);
1277 }
1278
1279 function file_tag_file_query($table,$s,$type = 'file') {
1280         if($type == 'file')
1281                 $str = preg_quote( '[' . file_tag_encode($s) . ']' );
1282         else
1283                 $str = preg_quote( '<' . file_tag_encode($s) . '>' );
1284         return " AND " . (($table) ? dbesc($table) . '.' : '') . "file regexp '" . dbesc($str) . "' ";
1285 }
1286
1287 function file_tag_save_file($uid,$item,$file) {
1288         $result = false;
1289         if(! intval($uid))
1290                 return false;
1291         $r = q("select file from item where id = %d and uid = %d limit 1",
1292                 intval($item),
1293                 intval($uid)
1294         );
1295         if(count($r)) {
1296                 if(! stristr($r[0]['file'],'[' . file_tag_encode($file) . ']'))
1297                         q("update item set file = '%s' where id = %d and uid = %d limit 1",
1298                                 dbesc($r[0]['file'] . '[' . file_tag_encode($file) . ']'),
1299                                 intval($item),
1300                                 intval($uid)
1301                         );
1302                 $saved = get_pconfig($uid,'system','filetags');
1303                 if((! strlen($saved)) || (! stristr($saved,'[' . file_tag_encode($file) . ']')))
1304                         set_pconfig($uid,'system','filetags',$saved . '[' . file_tag_encode($file) . ']');
1305         }
1306         return true;
1307 }
1308
1309 function file_tag_unsave_file($uid,$item,$file) {
1310         $result = false;
1311         if(! intval($uid))
1312                 return false;
1313
1314         $pattern = '[' . file_tag_encode($file) . ']' ;
1315
1316         $r = q("select file from item where id = %d and uid = %d limit 1",
1317                 intval($item),
1318                 intval($uid)
1319         );
1320         if(! count($r))
1321                 return false;
1322
1323         q("update item set file = '%s' where id = %d and uid = %d limit 1",
1324                 dbesc(str_replace($pattern,'',$r[0]['file'])),
1325                 intval($item),
1326                 intval($uid)
1327         );
1328
1329         $r = q("select file from item where uid = %d " . file_tag_file_query('item',$file),
1330                 intval($uid)
1331         );
1332
1333         if(! count($r)) {
1334                 $saved = get_pconfig($uid,'system','filetags');
1335                 set_pconfig($uid,'system','filetags',str_replace($pattern,'',$saved));
1336         }
1337         return true;
1338 }
1339