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