]> git.mxchange.org Git - friendica.git/blob - include/text.php
update to v4.0.0; point to local host of SWF
[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 require_once("include/friendica_smarty.php");
13
14 if(! function_exists('replace_macros')) {
15 /**
16  * This is our template processor
17  * 
18  * @param string|FriendicaSmarty $s the string requiring macro substitution, 
19  *                                                                      or an instance of FriendicaSmarty
20  * @param array $r key value pairs (search => replace)
21  * @return string substituted string
22  */
23 function replace_macros($s,$r) {
24         
25         $stamp1 = microtime(true);
26
27         $a = get_app();
28
29         $t = $a->template_engine();
30         $output = $t->replace_macros($s,$r);
31
32         $a->save_timestamp($stamp1, "rendering");
33
34         return $output;
35 }}
36
37
38 // random string, there are 86 characters max in text mode, 128 for hex
39 // output is urlsafe
40
41 define('RANDOM_STRING_HEX',  0x00 );
42 define('RANDOM_STRING_TEXT', 0x01 );
43
44 if(! function_exists('random_string')) {
45 function random_string($size = 64,$type = RANDOM_STRING_HEX) {
46         // generate a bit of entropy and run it through the whirlpool
47         $s = hash('whirlpool', (string) rand() . uniqid(rand(),true) . (string) rand(),(($type == RANDOM_STRING_TEXT) ? true : false));
48         $s = (($type == RANDOM_STRING_TEXT) ? str_replace("\n","",base64url_encode($s,true)) : $s);
49         return(substr($s,0,$size));
50 }}
51
52 if(! function_exists('notags')) {
53 /**
54  * This is our primary input filter. 
55  *
56  * The high bit hack only involved some old IE browser, forget which (IE5/Mac?)
57  * that had an XSS attack vector due to stripping the high-bit on an 8-bit character
58  * after cleansing, and angle chars with the high bit set could get through as markup.
59  * 
60  * This is now disabled because it was interfering with some legitimate unicode sequences 
61  * and hopefully there aren't a lot of those browsers left. 
62  *
63  * Use this on any text input where angle chars are not valid or permitted
64  * They will be replaced with safer brackets. This may be filtered further
65  * if these are not allowed either.   
66  *
67  * @param string $string Input string
68  * @return string Filtered string
69  */
70 function notags($string) {
71
72         return(str_replace(array("<",">"), array('[',']'), $string));
73
74 //  High-bit filter no longer used
75 //      return(str_replace(array("<",">","\xBA","\xBC","\xBE"), array('[',']','','',''), $string));
76 }}
77
78
79
80 if(! function_exists('escape_tags')) {
81 /**
82  * use this on "body" or "content" input where angle chars shouldn't be removed,
83  * and allow them to be safely displayed.
84  * @param string $string
85  * @return string
86  */
87 function escape_tags($string) {
88
89         return(htmlspecialchars($string, ENT_COMPAT, 'UTF-8', false));
90 }}
91
92
93 // generate a string that's random, but usually pronounceable. 
94 // used to generate initial passwords
95
96 if(! function_exists('autoname')) {
97 /**
98  * generate a string that's random, but usually pronounceable. 
99  * used to generate initial passwords
100  * @param int $len
101  * @return string
102  */
103 function autoname($len) {
104
105         if($len <= 0)
106                 return '';
107
108         $vowels = array('a','a','ai','au','e','e','e','ee','ea','i','ie','o','ou','u'); 
109         if(mt_rand(0,5) == 4)
110                 $vowels[] = 'y';
111
112         $cons = array(
113                         'b','bl','br',
114                         'c','ch','cl','cr',
115                         'd','dr',
116                         'f','fl','fr',
117                         'g','gh','gl','gr',
118                         'h',
119                         'j',
120                         'k','kh','kl','kr',
121                         'l',
122                         'm',
123                         'n',
124                         'p','ph','pl','pr',
125                         'qu',
126                         'r','rh',
127                         's','sc','sh','sm','sp','st',
128                         't','th','tr',
129                         'v',
130                         'w','wh',
131                         'x',
132                         'z','zh'
133                         );
134
135         $midcons = array('ck','ct','gn','ld','lf','lm','lt','mb','mm', 'mn','mp',
136                                 'nd','ng','nk','nt','rn','rp','rt');
137
138         $noend = array('bl', 'br', 'cl','cr','dr','fl','fr','gl','gr',
139                                 'kh', 'kl','kr','mn','pl','pr','rh','tr','qu','wh');
140
141         $start = mt_rand(0,2);
142         if($start == 0)
143                 $table = $vowels;
144         else
145                 $table = $cons;
146
147         $word = '';
148
149         for ($x = 0; $x < $len; $x ++) {
150                 $r = mt_rand(0,count($table) - 1);
151                 $word .= $table[$r];
152   
153                 if($table == $vowels)
154                         $table = array_merge($cons,$midcons);
155                 else
156                         $table = $vowels;
157
158         }
159
160         $word = substr($word,0,$len);
161
162         foreach($noend as $noe) {
163                 if((strlen($word) > 2) && (substr($word,-2) == $noe)) {
164                         $word = substr($word,0,-1);
165                         break;
166                 }
167         }
168         if(substr($word,-1) == 'q')
169                 $word = substr($word,0,-1);    
170         return $word;
171 }}
172
173
174 // escape text ($str) for XML transport
175 // returns escaped text.
176
177 if(! function_exists('xmlify')) {
178 /**
179  * escape text ($str) for XML transport
180  * @param string $str
181  * @return string Escaped text.
182  */
183 function xmlify($str) {
184 /*      $buffer = '';
185         
186         $len = mb_strlen($str);
187         for($x = 0; $x < $len; $x ++) {
188                 $char = mb_substr($str,$x,1);
189         
190                 switch( $char ) {
191
192                         case "\r" :
193                                 break;
194                         case "&" :
195                                 $buffer .= '&amp;';
196                                 break;
197                         case "'" :
198                                 $buffer .= '&apos;';
199                                 break;
200                         case "\"" :
201                                 $buffer .= '&quot;';
202                                 break;
203                         case '<' :
204                                 $buffer .= '&lt;';
205                                 break;
206                         case '>' :
207                                 $buffer .= '&gt;';
208                                 break;
209                         case "\n" :
210                                 $buffer .= "\n";
211                                 break;
212                         default :
213                                 $buffer .= $char;
214                                 break;
215                 }       
216         }*/
217
218         $buffer = mb_ereg_replace("&", "&amp;", $str);
219         $buffer = mb_ereg_replace("'", "&apos;", $buffer);
220         $buffer = mb_ereg_replace("\"", "&quot;", $buffer);
221         $buffer = mb_ereg_replace("<", "&lt;", $buffer);
222         $buffer = mb_ereg_replace(">", "&gt;", $buffer);
223
224         $buffer = trim($buffer);
225         return($buffer);
226 }}
227
228 if(! function_exists('unxmlify')) {
229 /**
230  * undo an xmlify
231  * @param string $s xml escaped text
232  * @return string unescaped text
233  */
234 function unxmlify($s) {
235 //      $ret = str_replace('&amp;','&', $s);
236 //      $ret = str_replace(array('&lt;','&gt;','&quot;','&apos;'),array('<','>','"',"'"),$ret);
237         $ret = mb_ereg_replace('&amp;', '&', $s);
238         $ret = mb_ereg_replace('&apos;', "'", $ret);
239         $ret = mb_ereg_replace('&quot;', '"', $ret);
240         $ret = mb_ereg_replace('&lt;', "<", $ret);
241         $ret = mb_ereg_replace('&gt;', ">", $ret);
242         return $ret;    
243 }}
244
245 if(! function_exists('hex2bin')) {
246 /**
247  * convenience wrapper, reverse the operation "bin2hex"
248  * @param string $s
249  * @return number
250  */
251 function hex2bin($s) {
252         if(! (is_string($s) && strlen($s)))
253                 return '';
254
255         if(! ctype_xdigit($s)) {
256                 return($s);
257         }
258
259         return(pack("H*",$s));
260 }}
261
262
263 if(! function_exists('paginate')) {
264 /**
265  * Automatic pagination.
266  *
267  *  To use, get the count of total items.
268  * Then call $a->set_pager_total($number_items);
269  * Optionally call $a->set_pager_itemspage($n) to the number of items to display on each page
270  * Then call paginate($a) after the end of the display loop to insert the pager block on the page
271  * (assuming there are enough items to paginate).
272  * When using with SQL, the setting LIMIT %d, %d => $a->pager['start'],$a->pager['itemspage']
273  * will limit the results to the correct items for the current page. 
274  * The actual page handling is then accomplished at the application layer. 
275  * 
276  * @param App $a App instance
277  * @return string html for pagination #FIXME remove html
278  */
279 function paginate(&$a) {
280         $o = '';
281         $stripped = preg_replace('/(&page=[0-9]*)/','',$a->query_string);
282
283 //      $stripped = preg_replace('/&zrl=(.*?)([\?&]|$)/ism','',$stripped);
284
285         $stripped = str_replace('q=','',$stripped);
286         $stripped = trim($stripped,'/');
287         $pagenum = $a->pager['page'];
288         $url = $a->get_baseurl() . '/' . $stripped;
289
290
291           if($a->pager['total'] > $a->pager['itemspage']) {
292                 $o .= '<div class="pager">';
293                 if($a->pager['page'] != 1)
294                         $o .= '<span class="pager_prev">'."<a href=\"$url".'&page='.($a->pager['page'] - 1).'">' . t('prev') . '</a></span> ';
295
296                 $o .=  "<span class=\"pager_first\"><a href=\"$url"."&page=1\">" . t('first') . "</a></span> ";
297
298                 $numpages = $a->pager['total'] / $a->pager['itemspage'];
299
300                         $numstart = 1;
301                 $numstop = $numpages;
302
303                 if($numpages > 14) {
304                         $numstart = (($pagenum > 7) ? ($pagenum - 7) : 1);
305                         $numstop = (($pagenum > ($numpages - 7)) ? $numpages : ($numstart + 14));
306                 }
307    
308                 for($i = $numstart; $i <= $numstop; $i++){
309                         if($i == $a->pager['page'])
310                                 $o .= '<span class="pager_current">'.(($i < 10) ? '&nbsp;'.$i : $i);
311                         else
312                                 $o .= "<span class=\"pager_n\"><a href=\"$url"."&page=$i\">".(($i < 10) ? '&nbsp;'.$i : $i)."</a>";
313                         $o .= '</span> ';
314                 }
315
316                 if(($a->pager['total'] % $a->pager['itemspage']) != 0) {
317                         if($i == $a->pager['page'])
318                                 $o .= '<span class="pager_current">'.(($i < 10) ? '&nbsp;'.$i : $i);
319                         else
320                                 $o .= "<span class=\"pager_n\"><a href=\"$url"."&page=$i\">".(($i < 10) ? '&nbsp;'.$i : $i)."</a>";
321                         $o .= '</span> ';
322                 }
323
324                 $lastpage = (($numpages > intval($numpages)) ? intval($numpages)+1 : $numpages);
325                 $o .= "<span class=\"pager_last\"><a href=\"$url"."&page=$lastpage\">" . t('last') . "</a></span> ";
326
327                 if(($a->pager['total'] - ($a->pager['itemspage'] * $a->pager['page'])) > 0)
328                         $o .= '<span class="pager_next">'."<a href=\"$url"."&page=".($a->pager['page'] + 1).'">' . t('next') . '</a></span>';
329                 $o .= '</div>'."\r\n";
330         }
331         return $o;
332 }}
333
334 if(! function_exists('alt_pager')) {
335 /**
336  * Alternative pager
337  * @param App $a App instance
338  * @param int $i
339  * @return string html for pagination #FIXME remove html
340  */
341 function alt_pager(&$a, $i) {
342         $o = '';
343         $stripped = preg_replace('/(&page=[0-9]*)/','',$a->query_string);
344         $stripped = str_replace('q=','',$stripped);
345         $stripped = trim($stripped,'/');
346         $pagenum = $a->pager['page'];
347         $url = $a->get_baseurl() . '/' . $stripped;
348
349         $o .= '<div class="pager">';
350
351         if($a->pager['page']>1)
352           $o .= "<a href=\"$url"."&page=".($a->pager['page'] - 1).'" class="pager_newer">' . t('newer') . '</a>';
353         if($i>0) {
354           if($a->pager['page']>1)
355                   $o .= "&nbsp;-&nbsp;";
356           $o .= "<a href=\"$url"."&page=".($a->pager['page'] + 1).'" class="pager_older">' . t('older') . '</a>';
357         }
358
359
360         $o .= '</div>'."\r\n";
361
362         return $o;
363 }}
364
365
366 if(! function_exists('expand_acl')) {
367 /**
368  * Turn user/group ACLs stored as angle bracketed text into arrays
369  * 
370  * @param string $s
371  * @return array
372  */
373 function expand_acl($s) {
374         // turn string array of angle-bracketed elements into numeric array
375         // e.g. "<1><2><3>" => array(1,2,3);
376         $ret = array();
377
378         if(strlen($s)) {
379                 $t = str_replace('<','',$s);
380                 $a = explode('>',$t);
381                 foreach($a as $aa) {
382                         if(intval($aa))
383                                 $ret[] = intval($aa);
384                 }
385         }
386         return $ret;
387 }}              
388
389 if(! function_exists('sanitise_acl')) {
390 /**
391  * Wrap ACL elements in angle brackets for storage 
392  * @param string $item
393  */
394 function sanitise_acl(&$item) {
395         if(intval($item))
396                 $item = '<' . intval(notags(trim($item))) . '>';
397         else
398                 unset($item);
399 }}
400
401
402 if(! function_exists('perms2str')) {
403 /**
404  * Convert an ACL array to a storable string
405  * 
406  * Normally ACL permissions will be an array.
407  * We'll also allow a comma-separated string.
408  * 
409  * @param string|array $p
410  * @return string
411  */
412 function perms2str($p) {
413         $ret = '';
414         if(is_array($p))
415                 $tmp = $p;
416         else
417                 $tmp = explode(',',$p);
418
419         if(is_array($tmp)) {
420                 array_walk($tmp,'sanitise_acl');
421                 $ret = implode('',$tmp);
422         }
423         return $ret;
424 }}
425
426
427 if(! function_exists('item_new_uri')) {
428 /**
429  * generate a guaranteed unique (for this domain) item ID for ATOM
430  * safe from birthday paradox
431  * 
432  * @param string $hostname
433  * @param int $uid
434  * @return string
435  */
436 function item_new_uri($hostname,$uid) {
437
438         do {
439                 $dups = false;
440                 $hash = random_string();
441
442                 $uri = "urn:X-dfrn:" . $hostname . ':' . $uid . ':' . $hash;
443
444                 $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' LIMIT 1",
445                         dbesc($uri));
446                 if(count($r))
447                         $dups = true;
448         } while($dups == true);
449         return $uri;
450 }}
451
452 // Generate a guaranteed unique photo ID.
453 // safe from birthday paradox
454
455 if(! function_exists('photo_new_resource')) {
456 /**
457  * Generate a guaranteed unique photo ID.
458  * safe from birthday paradox
459  * 
460  * @return string
461  */     
462 function photo_new_resource() {
463
464         do {
465                 $found = false;
466                 $resource = hash('md5',uniqid(mt_rand(),true));
467                 $r = q("SELECT `id` FROM `photo` WHERE `resource-id` = '%s' LIMIT 1",
468                         dbesc($resource)
469                 );
470                 if(count($r))
471                         $found = true;
472         } while($found == true);
473         return $resource;
474 }}
475
476
477 if(! function_exists('load_view_file')) {
478 /**
479  * @deprecated
480  * wrapper to load a view template, checking for alternate
481  * languages before falling back to the default
482  * 
483  * @global string $lang
484  * @global App $a
485  * @param string $s view name
486  * @return string
487  */     
488 function load_view_file($s) {
489         global $lang, $a;
490         if(! isset($lang))
491                 $lang = 'en';
492         $b = basename($s);
493         $d = dirname($s);
494         if(file_exists("$d/$lang/$b")) {
495                 $stamp1 = microtime(true);
496                 $content = file_get_contents("$d/$lang/$b");
497                 $a->save_timestamp($stamp1, "file");
498                 return $content;
499         }
500
501         $theme = current_theme();
502
503         if(file_exists("$d/theme/$theme/$b")) {
504                 $stamp1 = microtime(true);
505                 $content = file_get_contents("$d/theme/$theme/$b");
506                 $a->save_timestamp($stamp1, "file");
507                 return $content;
508         }
509
510         $stamp1 = microtime(true);
511         $content = file_get_contents($s);
512         $a->save_timestamp($stamp1, "file");
513         return $content;
514 }}
515
516 if(! function_exists('get_intltext_template')) {
517 /**
518  * load a view template, checking for alternate
519  * languages before falling back to the default
520  * 
521  * @global string $lang
522  * @param string $s view path
523  * @return string
524  */
525 function get_intltext_template($s) {
526         global $lang;
527
528         $a = get_app();
529         $engine = '';
530         if($a->theme['template_engine'] === 'smarty3')
531                 $engine = "/smarty3";
532
533         if(! isset($lang))
534                 $lang = 'en';
535
536         if(file_exists("view/$lang$engine/$s")) {
537                 $stamp1 = microtime(true);
538                 $content = file_get_contents("view/$lang$engine/$s");
539                 $a->save_timestamp($stamp1, "file");
540                 return $content;
541         } elseif(file_exists("view/en$engine/$s")) {
542                 $stamp1 = microtime(true);
543                 $content = file_get_contents("view/en$engine/$s");
544                 $a->save_timestamp($stamp1, "file");
545                 return $content;
546         } else {
547                 $stamp1 = microtime(true);
548                 $content = file_get_contents("view$engine/$s");
549                 $a->save_timestamp($stamp1, "file");
550                 return $content;
551         }
552 }}
553
554 if(! function_exists('get_markup_template')) {
555 /**
556  * load template $s
557  * 
558  * @param string $s
559  * @param string $root
560  * @return string
561  */
562 function get_markup_template($s, $root = '') {
563         $stamp1 = microtime(true);
564
565         $a = get_app();
566         $t = $a->template_engine();
567         
568         $template = $t->get_template_file($s, $root);
569         
570         $a->save_timestamp($stamp1, "file");
571         
572         return $template;
573 }}
574
575 if(! function_exists("get_template_file")) {
576 /**
577  * 
578  * @param App $a
579  * @param string $filename
580  * @param string $root
581  * @return string
582  */
583 function get_template_file($a, $filename, $root = '') {
584         $theme = current_theme();
585
586         // Make sure $root ends with a slash /
587         if($root !== '' && $root[strlen($root)-1] !== '/')
588                 $root = $root . '/';
589
590         if(file_exists("{$root}view/theme/$theme/$filename"))
591                 $template_file = "{$root}view/theme/$theme/$filename";
592         elseif (x($a->theme_info,"extends") && file_exists("{$root}view/theme/{$a->theme_info["extends"]}/$filename"))
593                 $template_file = "{$root}view/theme/{$a->theme_info["extends"]}/$filename";
594         elseif (file_exists("{$root}/$filename"))
595                 $template_file = "{$root}/$filename";
596         else
597                 $template_file = "{$root}view/$filename";
598
599         return $template_file;
600 }}
601
602
603
604
605
606
607
608 if(! function_exists('attribute_contains')) {
609 /**
610  *  for html,xml parsing - let's say you've got
611  *  an attribute foobar="class1 class2 class3"
612  *  and you want to find out if it contains 'class3'.
613  *  you can't use a normal sub string search because you
614  *  might match 'notclass3' and a regex to do the job is 
615  *  possible but a bit complicated. 
616  *  pass the attribute string as $attr and the attribute you 
617  *  are looking for as $s - returns true if found, otherwise false
618  * 
619  * @param string $attr attribute value
620  * @param string $s string to search
621  * @return boolean True if found, False otherwise
622  */
623 function attribute_contains($attr,$s) {
624         $a = explode(' ', $attr);
625         if(count($a) && in_array($s,$a))
626                 return true;
627         return false;
628 }}
629
630 if(! function_exists('logger')) {
631 /**
632  * log levels:
633  * LOGGER_NORMAL (default)
634  * LOGGER_TRACE
635  * LOGGER_DEBUG
636  * LOGGER_DATA
637  * LOGGER_ALL
638  * 
639  * @global App $a
640  * @global dba $db
641  * @param string $msg
642  * @param int $level
643  */
644 function logger($msg,$level = 0) {
645         // turn off logger in install mode
646         global $a;
647         global $db;
648
649         if(($a->module == 'install') || (! ($db && $db->connected))) return;
650
651         $debugging = get_config('system','debugging');
652         $loglevel  = intval(get_config('system','loglevel'));
653         $logfile   = get_config('system','logfile');
654
655         if((! $debugging) || (! $logfile) || ($level > $loglevel))
656                 return;
657
658         $stamp1 = microtime(true);
659         @file_put_contents($logfile, datetime_convert() . ':' . session_id() . ' ' . $msg . "\n", FILE_APPEND);
660         $a->save_timestamp($stamp1, "file");
661         return;
662 }}
663
664
665 if(! function_exists('activity_match')) {
666 /**
667  * Compare activity uri. Knows about activity namespace.
668  * 
669  * @param string $haystack
670  * @param string $needle
671  * @return boolean
672  */
673 function activity_match($haystack,$needle) {
674         if(($haystack === $needle) || ((basename($needle) === $haystack) && strstr($needle,NAMESPACE_ACTIVITY_SCHEMA)))
675                 return true;
676         return false;
677 }}
678
679
680 if(! function_exists('get_tags')) {
681 /**
682  * Pull out all #hashtags and @person tags from $s;
683  * We also get @person@domain.com - which would make 
684  * the regex quite complicated as tags can also
685  * end a sentence. So we'll run through our results
686  * and strip the period from any tags which end with one.
687  * Returns array of tags found, or empty array.
688  * 
689  * @param string $s
690  * @return array
691  */
692 function get_tags($s) {
693         $ret = array();
694
695         // ignore anything in a code block
696         $s = preg_replace('/\[code\](.*?)\[\/code\]/sm','',$s);
697
698         // Force line feeds at bbtags
699         $s = str_replace(array("[", "]"), array("\n[", "]\n"), $s);
700
701         // ignore anything in a bbtag
702         $s = preg_replace('/\[(.*?)\]/sm','',$s);
703
704         // Match full names against @tags including the space between first and last
705         // We will look these up afterward to see if they are full names or not recognisable.
706
707         if(preg_match_all('/(@[^ \x0D\x0A,:?]+ [^ \x0D\x0A@,:?]+)([ \x0D\x0A@,:?]|$)/',$s,$match)) {
708                 foreach($match[1] as $mtch) {
709                         if(strstr($mtch,"]")) {
710                                 // we might be inside a bbcode color tag - leave it alone
711                                 continue;
712                         }
713                         if(substr($mtch,-1,1) === '.')
714                                 $ret[] = substr($mtch,0,-1);
715                         else
716                                 $ret[] = $mtch;
717                 }
718         }
719
720         // Otherwise pull out single word tags. These can be @nickname, @first_last
721         // and #hash tags.
722
723         if(preg_match_all('/([@#][^ \x0D\x0A,;:?]+)([ \x0D\x0A,;:?]|$)/',$s,$match)) {
724                 foreach($match[1] as $mtch) {
725                         if(strstr($mtch,"]")) {
726                                 // we might be inside a bbcode color tag - leave it alone
727                                 continue;
728                         }
729                         if(substr($mtch,-1,1) === '.')
730                                 $mtch = substr($mtch,0,-1);
731                         // ignore strictly numeric tags like #1
732                         if((strpos($mtch,'#') === 0) && ctype_digit(substr($mtch,1)))
733                                 continue;
734                         // try not to catch url fragments
735                         if(strpos($s,$mtch) && preg_match('/[a-zA-z0-9\/]/',substr($s,strpos($s,$mtch)-1,1)))
736                                 continue;
737                         $ret[] = $mtch;
738                 }
739         }
740         return $ret;
741 }}
742
743
744 // 
745
746 if(! function_exists('qp')) {
747 /**
748  * quick and dirty quoted_printable encoding
749  * 
750  * @param string $s
751  * @return string
752  */     
753 function qp($s) {
754 return str_replace ("%","=",rawurlencode($s));
755 }} 
756
757
758
759 if(! function_exists('get_mentions')) {
760 /**
761  * @param array $item
762  * @return string html for mentions #FIXME: remove html
763  */
764 function get_mentions($item) {
765         $o = '';
766         if(! strlen($item['tag']))
767                 return $o;
768
769         $arr = explode(',',$item['tag']);
770         foreach($arr as $x) {
771                 $matches = null;
772                 if(preg_match('/@\[url=([^\]]*)\]/',$x,$matches)) {
773                         $o .= "\t\t" . '<link rel="mentioned" href="' . $matches[1] . '" />' . "\r\n";
774                         $o .= "\t\t" . '<link rel="ostatus:attention" href="' . $matches[1] . '" />' . "\r\n";
775                 }
776         }
777         return $o;
778 }}
779
780 if(! function_exists('contact_block')) {
781 /**
782  * Get html for contact block.
783  * 
784  * @template contact_block.tpl
785  * @hook contact_block_end (contacts=>array, output=>string)
786  * @return string
787  */
788 function contact_block() {
789         $o = '';
790         $a = get_app();
791
792         $shown = get_pconfig($a->profile['uid'],'system','display_friend_count');
793         if($shown === false)
794                 $shown = 24;
795         if($shown == 0)
796                 return;
797
798         if((! is_array($a->profile)) || ($a->profile['hide-friends']))
799                 return $o;
800         $r = q("SELECT COUNT(*) AS `total` FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 and `pending` = 0 AND `hidden` = 0 AND `archive` = 0",
801                         intval($a->profile['uid'])
802         );
803         if(count($r)) {
804                 $total = intval($r[0]['total']);
805         }
806         if(! $total) {
807                 $contacts = t('No contacts');
808                 $micropro = Null;
809                 
810         } else {
811                 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 and `pending` = 0 AND `hidden` = 0 AND `archive` = 0 ORDER BY RAND() LIMIT %d",
812                                 intval($a->profile['uid']),
813                                 intval($shown)
814                 );
815                 if(count($r)) {
816                         $contacts = sprintf( tt('%d Contact','%d Contacts', $total),$total);
817                         $micropro = Array();
818                         foreach($r as $rr) {
819                                 $micropro[] = micropro($rr,true,'mpfriend');
820                         }
821                 }
822         }
823         
824         $tpl = get_markup_template('contact_block.tpl');
825         $o = replace_macros($tpl, array(
826                 '$contacts' => $contacts,
827                 '$nickname' => $a->profile['nickname'],
828                 '$viewcontacts' => t('View Contacts'),
829                 '$micropro' => $micropro,
830         ));
831
832         $arr = array('contacts' => $r, 'output' => $o);
833
834         call_hooks('contact_block_end', $arr);
835         return $o;
836
837 }}
838
839 if(! function_exists('micropro')) {
840 /**
841  * 
842  * @param array $contact
843  * @param boolean $redirect
844  * @param string $class
845  * @param boolean $textmode
846  * @return string #FIXME: remove html
847  */
848 function micropro($contact, $redirect = false, $class = '', $textmode = false) {
849
850         if($class)
851                 $class = ' ' . $class;
852
853         $url = $contact['url'];
854         $sparkle = '';
855         $redir = false;
856
857         if($redirect) {
858                 $a = get_app();
859                 $redirect_url = $a->get_baseurl() . '/redir/' . $contact['id'];
860                 if(local_user() && ($contact['uid'] == local_user()) && ($contact['network'] === 'dfrn')) {
861                         $redir = true;
862                         $url = $redirect_url;
863                         $sparkle = ' sparkle';
864                 }
865                 else
866                         $url = zrl($url);
867         }
868         $click = ((x($contact,'click')) ? ' onclick="' . $contact['click'] . '" ' : '');
869         if($click)
870                 $url = '';
871         if($textmode) {
872                 return '<div class="contact-block-textdiv' . $class . '"><a class="contact-block-link' . $class . $sparkle 
873                         . (($click) ? ' fakelink' : '') . '" '
874                         . (($redir) ? ' target="redir" ' : '')
875                         . (($url) ? ' href="' . $url . '"' : '') . $click
876                         . '" title="' . $contact['name'] . ' [' . $contact['url'] . ']" alt="' . $contact['name'] 
877                         . '" >'. $contact['name'] . '</a></div>' . "\r\n";
878         }
879         else {
880                 return '<div class="contact-block-div' . $class . '"><a class="contact-block-link' . $class . $sparkle 
881                         . (($click) ? ' fakelink' : '') . '" '
882                         . (($redir) ? ' target="redir" ' : '')
883                         . (($url) ? ' href="' . $url . '"' : '') . $click . ' ><img class="contact-block-img' . $class . $sparkle . '" src="' 
884                         . $contact['micro'] . '" title="' . $contact['name'] . ' [' . $contact['url'] . ']" alt="' . $contact['name'] 
885                         . '" /></a></div>' . "\r\n";
886         }
887 }}
888
889
890
891 if(! function_exists('search')) {
892 /**
893  * search box
894  * 
895  * @param string $s search query
896  * @param string $id html id
897  * @param string $url search url
898  * @param boolean $save show save search button
899  * @return string html for search box #FIXME: remove html
900  */
901 function search($s,$id='search-box',$url='/search',$save = false) {
902         $a = get_app();
903         $o  = '<div id="' . $id . '">';
904         $o .= '<form action="' . $a->get_baseurl((stristr($url,'network')) ? true : false) . $url . '" method="get" >';
905         $o .= '<input type="text" name="search" id="search-text" placeholder="' . t('Search') . '" value="' . $s .'" />';
906         $o .= '<input type="submit" name="submit" id="search-submit" value="' . t('Search') . '" />'; 
907         if($save)
908                 $o .= '<input type="submit" name="save" id="search-save" value="' . t('Save') . '" />'; 
909         $o .= '</form></div>';
910         return $o;
911 }}
912
913 if(! function_exists('valid_email')) {
914 /**
915  * Check if $x is a valid email string
916  * 
917  * @param string $x
918  * @return boolean
919  */
920 function valid_email($x){
921
922         if(get_config('system','disable_email_validation'))
923                 return true;
924
925         if(preg_match('/^[_a-zA-Z0-9\-\+]+(\.[_a-zA-Z0-9\-\+]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)+$/',$x))
926                 return true;
927         return false;
928 }}
929
930
931 if(! function_exists('linkify')) {
932 /**
933  * Replace naked text hyperlink with HTML formatted hyperlink
934  *
935  * @param string $s
936  */
937 function linkify($s) {
938         $s = preg_replace("/(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\'\%\$\!\+]*)/", ' <a href="$1" target="external-link">$1</a>', $s);
939         $s = preg_replace("/\<(.*?)(src|href)=(.*?)\&amp\;(.*?)\>/ism",'<$1$2=$3&$4>',$s);
940         return($s);
941 }}
942
943
944 /**
945  * Load poke verbs
946  *
947  * @return array index is present tense verb
948                                  value is array containing past tense verb, translation of present, translation of past
949  * @hook poke_verbs pokes array
950  */
951 function get_poke_verbs() {
952         
953         // index is present tense verb
954         // value is array containing past tense verb, translation of present, translation of past
955
956         $arr = array(
957                 'poke' => array( 'poked', t('poke'), t('poked')),
958                 'ping' => array( 'pinged', t('ping'), t('pinged')),
959                 'prod' => array( 'prodded', t('prod'), t('prodded')),
960                 'slap' => array( 'slapped', t('slap'), t('slapped')),
961                 'finger' => array( 'fingered', t('finger'), t('fingered')),
962                 'rebuff' => array( 'rebuffed', t('rebuff'), t('rebuffed')),
963         );
964         call_hooks('poke_verbs', $arr);
965         return $arr;
966 }
967
968 /**
969  * Load moods
970  * @return array index is mood, value is translated mood
971  * @hook mood_verbs moods array
972  */
973 function get_mood_verbs() {
974         
975         $arr = array(
976                 'happy'      => t('happy'),
977                 'sad'        => t('sad'),
978                 'mellow'     => t('mellow'),
979                 'tired'      => t('tired'),
980                 'perky'      => t('perky'),
981                 'angry'      => t('angry'),
982                 'stupefied'  => t('stupified'),
983                 'puzzled'    => t('puzzled'),
984                 'interested' => t('interested'),
985                 'bitter'     => t('bitter'),
986                 'cheerful'   => t('cheerful'),
987                 'alive'      => t('alive'),
988                 'annoyed'    => t('annoyed'),
989                 'anxious'    => t('anxious'),
990                 'cranky'     => t('cranky'),
991                 'disturbed'  => t('disturbed'),
992                 'frustrated' => t('frustrated'),
993                 'motivated'  => t('motivated'),
994                 'relaxed'    => t('relaxed'),
995                 'surprised'  => t('surprised'),
996         );
997
998         call_hooks('mood_verbs', $arr);
999         return $arr;
1000 }
1001
1002
1003
1004 if(! function_exists('smilies')) {
1005 /**
1006  * Replaces text emoticons with graphical images
1007  *
1008  * It is expected that this function will be called using HTML text.
1009  * We will escape text between HTML pre and code blocks from being 
1010  * processed. 
1011  * 
1012  * At a higher level, the bbcode [nosmile] tag can be used to prevent this 
1013  * function from being executed by the prepare_text() routine when preparing
1014  * bbcode source for HTML display
1015  *
1016  * @param string $s
1017  * @param boolean $sample
1018  * @return string
1019  * @hook smilie ('texts' => smilies texts array, 'icons' => smilies html array, 'string' => $s)
1020  */
1021 function smilies($s, $sample = false) {
1022         $a = get_app();
1023
1024         if(intval(get_config('system','no_smilies')) 
1025                 || (local_user() && intval(get_pconfig(local_user(),'system','no_smilies'))))
1026                 return $s;
1027
1028         $s = preg_replace_callback('/<pre>(.*?)<\/pre>/ism','smile_encode',$s);
1029         $s = preg_replace_callback('/<code>(.*?)<\/code>/ism','smile_encode',$s);
1030
1031         $texts =  array( 
1032                 '&lt;3', 
1033                 '&lt;/3', 
1034                 '&lt;\\3', 
1035                 ':-)', 
1036                 ';-)', 
1037                 ':-(', 
1038                 ':-P', 
1039                 ':-p', 
1040                 ':-"', 
1041                 ':-&quot;', 
1042                 ':-x', 
1043                 ':-X', 
1044                 ':-D', 
1045                 '8-|', 
1046                 '8-O', 
1047                 ':-O', 
1048                 '\\o/', 
1049                 'o.O', 
1050                 'O.o', 
1051                 'o_O', 
1052                 'O_o', 
1053                 ":'(", 
1054                 ":-!", 
1055                 ":-/", 
1056                 ":-[", 
1057                 "8-)",
1058                 ':beer', 
1059                 ':homebrew', 
1060                 ':coffee', 
1061                 ':facepalm',
1062                 ':like',
1063                 ':dislike',
1064                 '~friendica'
1065
1066         );
1067
1068         $icons = array(
1069                 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-heart.gif" alt="<3" />',
1070                 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-brokenheart.gif" alt="</3" />',
1071                 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-brokenheart.gif" alt="<\\3" />',
1072                 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-smile.gif" alt=":-)" />',
1073                 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-wink.gif" alt=";-)" />',
1074                 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-frown.gif" alt=":-(" />',
1075                 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-tongue-out.gif" alt=":-P" />',
1076                 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-tongue-out.gif" alt=":-p" />',
1077                 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-kiss.gif" alt=":-\"" />',
1078                 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-kiss.gif" alt=":-\"" />',
1079                 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-kiss.gif" alt=":-x" />',
1080                 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-kiss.gif" alt=":-X" />',
1081                 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-laughing.gif" alt=":-D" />',
1082                 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-surprised.gif" alt="8-|" />',
1083                 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-surprised.gif" alt="8-O" />',
1084                 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-surprised.gif" alt=":-O" />',                
1085                 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-thumbsup.gif" alt="\\o/" />',
1086                 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-Oo.gif" alt="o.O" />',
1087                 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-Oo.gif" alt="O.o" />',
1088                 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-Oo.gif" alt="o_O" />',
1089                 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-Oo.gif" alt="O_o" />',
1090                 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-cry.gif" alt=":\'(" />',
1091                 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-foot-in-mouth.gif" alt=":-!" />',
1092                 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-undecided.gif" alt=":-/" />',
1093                 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-embarassed.gif" alt=":-[" />',
1094                 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-cool.gif" alt="8-)" />',
1095                 '<img class="smiley" src="' . $a->get_baseurl() . '/images/beer_mug.gif" alt=":beer" />',
1096                 '<img class="smiley" src="' . $a->get_baseurl() . '/images/beer_mug.gif" alt=":homebrew" />',
1097                 '<img class="smiley" src="' . $a->get_baseurl() . '/images/coffee.gif" alt=":coffee" />',
1098                 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-facepalm.gif" alt=":facepalm" />',
1099                 '<img class="smiley" src="' . $a->get_baseurl() . '/images/like.gif" alt=":like" />',
1100                 '<img class="smiley" src="' . $a->get_baseurl() . '/images/dislike.gif" alt=":dislike" />',
1101                 '<a href="http://friendica.com">~friendica <img class="smiley" src="' . $a->get_baseurl() . '/images/friendica-16.png" alt="~friendica" /></a>'
1102         );
1103
1104         $params = array('texts' => $texts, 'icons' => $icons, 'string' => $s);
1105         call_hooks('smilie', $params);
1106
1107         if($sample) {
1108                 $s = '<div class="smiley-sample">';
1109                 for($x = 0; $x < count($params['texts']); $x ++) {
1110                         $s .= '<dl><dt>' . $params['texts'][$x] . '</dt><dd>' . $params['icons'][$x] . '</dd></dl>';
1111                 }
1112         }
1113         else {
1114                 $params['string'] = preg_replace_callback('/&lt;(3+)/','preg_heart',$params['string']);
1115                 $s = str_replace($params['texts'],$params['icons'],$params['string']);
1116         }
1117
1118         $s = preg_replace_callback('/<pre>(.*?)<\/pre>/ism','smile_decode',$s);
1119         $s = preg_replace_callback('/<code>(.*?)<\/code>/ism','smile_decode',$s);
1120
1121         return $s;
1122
1123 }}
1124
1125 function smile_encode($m) {
1126         return(str_replace($m[1],base64url_encode($m[1]),$m[0]));
1127 }
1128
1129 function smile_decode($m) {
1130         return(str_replace($m[1],base64url_decode($m[1]),$m[0]));
1131 }
1132
1133
1134 /**
1135  * expand <3333 to the correct number of hearts
1136  * 
1137  * @param string $x
1138  * @return string
1139  */
1140 function preg_heart($x) {
1141         $a = get_app();
1142         if(strlen($x[1]) == 1)
1143                 return $x[0];
1144         $t = '';
1145         for($cnt = 0; $cnt < strlen($x[1]); $cnt ++)
1146                 $t .= '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-heart.gif" alt="<3" />';
1147         $r =  str_replace($x[0],$t,$x[0]);
1148         return $r;
1149 }
1150
1151
1152 if(! function_exists('day_translate')) {
1153 /**
1154  * Translate days and months names
1155  * 
1156  * @param string $s
1157  * @return string
1158  */
1159 function day_translate($s) {
1160         $ret = str_replace(array('Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'),
1161                 array( t('Monday'), t('Tuesday'), t('Wednesday'), t('Thursday'), t('Friday'), t('Saturday'), t('Sunday')),
1162                 $s);
1163
1164         $ret = str_replace(array('January','February','March','April','May','June','July','August','September','October','November','December'),
1165                 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')),
1166                 $ret);
1167
1168         return $ret;
1169 }}
1170
1171
1172 if(! function_exists('normalise_link')) {
1173 /**
1174  * Normalize url
1175  * 
1176  * @param string $url
1177  * @return string
1178  */
1179 function normalise_link($url) {
1180         $ret = str_replace(array('https:','//www.'), array('http:','//'), $url);
1181         return(rtrim($ret,'/'));
1182 }}
1183
1184
1185
1186 if(! function_exists('link_compare')) {
1187 /**
1188  * Compare two URLs to see if they are the same, but ignore
1189  * slight but hopefully insignificant differences such as if one 
1190  * is https and the other isn't, or if one is www.something and 
1191  * the other isn't - and also ignore case differences.
1192  *
1193  * @param string $a first url
1194  * @param string $b second url
1195  * @return boolean True if the URLs match, otherwise False
1196  *
1197  */     
1198 function link_compare($a,$b) {
1199         if(strcasecmp(normalise_link($a),normalise_link($b)) === 0)
1200                 return true;
1201         return false;
1202 }}
1203
1204
1205 if(! function_exists('redir_private_images')) {
1206 /**
1207  * Find any non-embedded images in private items and add redir links to them
1208  * 
1209  * @param App $a
1210  * @param array $item
1211  */
1212 function redir_private_images($a, &$item) {
1213
1214         $matches = false;
1215         $cnt = preg_match_all('|\[img\](http[^\[]*?/photo/[a-fA-F0-9]+?(-[0-9]\.[\w]+?)?)\[\/img\]|', $item['body'], $matches, PREG_SET_ORDER);
1216         if($cnt) {
1217                 //logger("redir_private_images: matches = " . print_r($matches, true));
1218                 foreach($matches as $mtch) {
1219                         if(strpos($mtch[1], '/redir') !== false)
1220                                 continue;
1221
1222                         if((local_user() == $item['uid']) && ($item['private'] != 0) && ($item['contact-id'] != $a->contact['id']) && ($item['network'] == NETWORK_DFRN)) {
1223                                 //logger("redir_private_images: redir");
1224                                 $img_url = $a->get_baseurl() . '/redir?f=1&quiet=1&url=' . $mtch[1] . '&conurl=' . $item['author-link'];
1225                                 $item['body'] = str_replace($mtch[0], "[img]".$img_url."[/img]", $item['body']);
1226                         }
1227                 }
1228         }
1229
1230 }}
1231
1232
1233 // Given an item array, convert the body element from bbcode to html and add smilie icons.
1234 // If attach is true, also add icons for item attachments
1235
1236 if(! function_exists('prepare_body')) {
1237 /**
1238  * Given an item array, convert the body element from bbcode to html and add smilie icons.
1239  * If attach is true, also add icons for item attachments
1240  * 
1241  * @param array $item
1242  * @param boolean $attach
1243  * @return string item body html
1244  * @hook prepare_body_init item array before any work
1245  * @hook prepare_body ('item'=>item array, 'html'=>body string) after first bbcode to html
1246  * @hook prepare_body_final ('item'=>item array, 'html'=>body string) after attach icons and blockquote special case handling (spoiler, author)
1247  */
1248 function prepare_body($item,$attach = false) {
1249
1250         $a = get_app();
1251         call_hooks('prepare_body_init', $item);
1252
1253         //$cachefile = get_cachefile($item["guid"]."-".strtotime($item["edited"])."-".hash("crc32", $item['body']));
1254         $cachefile = get_cachefile($item["guid"]."-".hash("md5", $item['body']));
1255
1256         if (($cachefile != '')) {
1257                 if (file_exists($cachefile)) {
1258                         $stamp1 = microtime(true);
1259                         $s = file_get_contents($cachefile);
1260                         $a->save_timestamp($stamp1, "file");
1261                 } else {
1262                         redir_private_images($a, $item);
1263                         $s = prepare_text($item['body']);
1264
1265                         $stamp1 = microtime(true);
1266                         file_put_contents($cachefile, $s);
1267                         $a->save_timestamp($stamp1, "file");
1268
1269                         logger('prepare_body: put item '.$item["id"].' into cachefile '.$cachefile);
1270                 }
1271         } else {
1272                 redir_private_images($a, $item);
1273                 $s = prepare_text($item['body']);
1274         }
1275
1276
1277         $prep_arr = array('item' => $item, 'html' => $s);
1278         call_hooks('prepare_body', $prep_arr);
1279         $s = $prep_arr['html'];
1280
1281         if(! $attach) {
1282                 // Replace the blockquotes with quotes that are used in mails
1283                 $mailquote = '<blockquote type="cite" class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex;">';
1284                 $s = str_replace(array('<blockquote>', '<blockquote class="spoiler">', '<blockquote class="author">'), array($mailquote, $mailquote, $mailquote), $s);
1285                 return $s;
1286         }
1287
1288         $as = '';
1289         $vhead = false;
1290         $arr = explode('[/attach],',$item['attach']);
1291         if(count($arr)) {
1292                 $as .= '<div class="body-attach">';
1293                 foreach($arr as $r) {
1294                         $matches = false;
1295                         $icon = '';
1296                         $cnt = preg_match_all('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|',$r,$matches, PREG_SET_ORDER);
1297                         if($cnt) {
1298                                 foreach($matches as $mtch) {
1299                                         $mime = $mtch[3];
1300
1301                                         if((local_user() == $item['uid']) && ($item['contact-id'] != $a->contact['id']) && ($item['network'] == NETWORK_DFRN))
1302                                                 $the_url = $a->get_baseurl() . '/redir/' . $item['contact-id'] . '?f=1&url=' . $mtch[1];
1303                                         else
1304                                                 $the_url = $mtch[1];
1305
1306                                         if(strpos($mime, 'video') !== false) {
1307                                                 if(!$vhead) {
1308                                                         $vhead = true;
1309                                                         $a->page['htmlhead'] .= replace_macros(get_markup_template('videos_head.tpl'), array(
1310                                                                 '$baseurl' => $a->get_baseurl(),
1311                                                         ));
1312                                                         $a->page['end'] .= replace_macros(get_markup_template('videos_end.tpl'), array(
1313                                                                 '$baseurl' => $a->get_baseurl(),
1314                                                         ));
1315                                                 }
1316
1317                                                 $id = end(explode('/', $the_url));
1318                                                 $as .= replace_macros(get_markup_template('video_top.tpl'), array(
1319                                                         '$video'        => array(
1320                                                                 'id'       => $id,
1321                                                                 'title'         => t('View Video'),
1322                                                                 'src'           => $the_url,
1323                                                                 'mime'          => $mime,
1324                                                         ),
1325                                                 ));
1326                                         }
1327
1328                                         $filetype = strtolower(substr( $mime, 0, strpos($mime,'/') ));
1329                                         if($filetype) {
1330                                                 $filesubtype = strtolower(substr( $mime, strpos($mime,'/') + 1 ));
1331                                                 $filesubtype = str_replace('.', '-', $filesubtype);
1332                                         }
1333                                         else {
1334                                                 $filetype = 'unkn';
1335                                                 $filesubtype = 'unkn';
1336                                         }
1337
1338                                         $icon = '<div class="attachtype icon s22 type-' . $filetype . ' subtype-' . $filesubtype . '"></div>';
1339                                         /*$icontype = strtolower(substr($mtch[3],0,strpos($mtch[3],'/')));
1340                                         switch($icontype) {
1341                                                 case 'video':
1342                                                 case 'audio':
1343                                                 case 'image':
1344                                                 case 'text':
1345                                                         $icon = '<div class="attachtype icon s22 type-' . $icontype . '"></div>';
1346                                                         break;
1347                                                 default:
1348                                                         $icon = '<div class="attachtype icon s22 type-unkn"></div>';
1349                                                         break;
1350                                         }*/
1351
1352                                         $title = ((strlen(trim($mtch[4]))) ? escape_tags(trim($mtch[4])) : escape_tags($mtch[1]));
1353                                         $title .= ' ' . $mtch[2] . ' ' . t('bytes');
1354
1355                                         $as .= '<a href="' . strip_tags($the_url) . '" title="' . $title . '" class="attachlink" target="external-link" >' . $icon . '</a>';
1356                                 }
1357                         }
1358                 }
1359                 $as .= '<div class="clear"></div></div>';
1360         }
1361         $s = $s . $as;
1362
1363
1364         // Look for spoiler
1365         $spoilersearch = '<blockquote class="spoiler">';
1366
1367         // Remove line breaks before the spoiler
1368         while ((strpos($s, "\n".$spoilersearch) !== false))
1369                 $s = str_replace("\n".$spoilersearch, $spoilersearch, $s);
1370         while ((strpos($s, "<br />".$spoilersearch) !== false))
1371                 $s = str_replace("<br />".$spoilersearch, $spoilersearch, $s);
1372
1373         while ((strpos($s, $spoilersearch) !== false)) {
1374
1375                 $pos = strpos($s, $spoilersearch);
1376                 $rnd = random_string(8);
1377                 $spoilerreplace = '<br /> <span id="spoiler-wrap-'.$rnd.'" style="white-space:nowrap;" class="fakelink" onclick="openClose(\'spoiler-'.$rnd.'\');">'.sprintf(t('Click to open/close')).'</span>'.
1378                                         '<blockquote class="spoiler" id="spoiler-'.$rnd.'" style="display: none;">';
1379                 $s = substr($s, 0, $pos).$spoilerreplace.substr($s, $pos+strlen($spoilersearch));
1380         }
1381
1382         // Look for quote with author
1383         $authorsearch = '<blockquote class="author">';
1384
1385         while ((strpos($s, $authorsearch) !== false)) {
1386
1387                 $pos = strpos($s, $authorsearch);
1388                 $rnd = random_string(8);
1389                 $authorreplace = '<br /> <span id="author-wrap-'.$rnd.'" style="white-space:nowrap;" class="fakelink" onclick="openClose(\'author-'.$rnd.'\');">'.sprintf(t('Click to open/close')).'</span>'.
1390                                         '<blockquote class="author" id="author-'.$rnd.'" style="display: block;">';
1391                 $s = substr($s, 0, $pos).$authorreplace.substr($s, $pos+strlen($authorsearch));
1392         }
1393
1394         $prep_arr = array('item' => $item, 'html' => $s);
1395         call_hooks('prepare_body_final', $prep_arr);
1396
1397         return $prep_arr['html'];
1398 }}
1399
1400
1401 if(! function_exists('prepare_text')) {
1402 /**
1403  * Given a text string, convert from bbcode to html and add smilie icons.
1404  * 
1405  * @param string $text
1406  * @return string
1407  */
1408 function prepare_text($text) {
1409
1410         require_once('include/bbcode.php');
1411
1412         if(stristr($text,'[nosmile]'))
1413                 $s = bbcode($text);
1414         else
1415                 $s = smilies(bbcode($text));
1416
1417         return $s;
1418 }}
1419
1420
1421
1422 /**
1423  * return array with details for categories and folders for an item
1424  * 
1425  * @param array $item
1426  * @return array
1427  * 
1428   * [
1429  *      [ // categories array
1430  *          {
1431  *               'name': 'category name',
1432  *               'removeurl': 'url to remove this category',
1433  *               'first': 'is the first in this array? true/false',
1434  *               'last': 'is the last in this array? true/false',
1435  *           } ,
1436  *           ....
1437  *       ],
1438  *       [ //folders array
1439  *                      {
1440  *               'name': 'folder name',
1441  *               'removeurl': 'url to remove this folder',
1442  *               'first': 'is the first in this array? true/false',
1443  *               'last': 'is the last in this array? true/false',
1444  *           } ,
1445  *           ....       
1446  *       ]
1447  *  ]
1448  */
1449 function get_cats_and_terms($item) {
1450
1451     $a = get_app();
1452     $categories = array();
1453     $folders = array();
1454
1455     $matches = false; $first = true;
1456     $cnt = preg_match_all('/<(.*?)>/',$item['file'],$matches,PREG_SET_ORDER);
1457     if($cnt) {
1458         foreach($matches as $mtch) {
1459             $categories[] = array(
1460                 'name' => xmlify(file_tag_decode($mtch[1])),
1461                 'url' =>  "#",
1462                 'removeurl' => ((local_user() == $item['uid'])?$a->get_baseurl() . '/filerm/' . $item['id'] . '?f=&cat=' . xmlify(file_tag_decode($mtch[1])):""),
1463                 'first' => $first,
1464                 'last' => false
1465             );
1466             $first = false;
1467         }
1468     }
1469     if (count($categories)) $categories[count($categories)-1]['last'] = true;
1470     
1471
1472         if(local_user() == $item['uid']) {
1473             $matches = false; $first = true;
1474         $cnt = preg_match_all('/\[(.*?)\]/',$item['file'],$matches,PREG_SET_ORDER);
1475             if($cnt) {
1476             foreach($matches as $mtch) {
1477                     $folders[] = array(
1478                     'name' => xmlify(file_tag_decode($mtch[1])),
1479                          'url' =>  "#",
1480                         'removeurl' => ((local_user() == $item['uid'])?$a->get_baseurl() . '/filerm/' . $item['id'] . '?f=&term=' . xmlify(file_tag_decode($mtch[1])):""),
1481                     'first' => $first,
1482                         'last' => false
1483                 );
1484                     $first = false;
1485                         }
1486         }
1487     }
1488
1489     if (count($folders)) $folders[count($folders)-1]['last'] = true;
1490
1491     return array($categories, $folders);
1492 }
1493
1494
1495
1496 if(! function_exists('feed_hublinks')) {
1497 /**
1498  * return atom link elements for all of our hubs
1499  * @return string hub link xml elements
1500  */
1501 function feed_hublinks() {
1502
1503         $hub = get_config('system','huburl');
1504
1505         $hubxml = '';
1506         if(strlen($hub)) {
1507                 $hubs = explode(',', $hub);
1508                 if(count($hubs)) {
1509                         foreach($hubs as $h) {
1510                                 $h = trim($h);
1511                                 if(! strlen($h))
1512                                         continue;
1513                                 $hubxml .= '<link rel="hub" href="' . xmlify($h) . '" />' . "\n" ;
1514                         }
1515                 }
1516         }
1517         return $hubxml;
1518 }}
1519
1520
1521 if(! function_exists('feed_salmonlinks')) {
1522 /**
1523  * return atom link elements for salmon endpoints
1524  * @param string $nick user nickname
1525  * @return string salmon link xml elements
1526  */
1527 function feed_salmonlinks($nick) {
1528
1529         $a = get_app();
1530
1531         $salmon  = '<link rel="salmon" href="' . xmlify($a->get_baseurl() . '/salmon/' . $nick) . '" />' . "\n" ;
1532
1533         // old style links that status.net still needed as of 12/2010 
1534
1535         $salmon .= '  <link rel="http://salmon-protocol.org/ns/salmon-replies" href="' . xmlify($a->get_baseurl() . '/salmon/' . $nick) . '" />' . "\n" ; 
1536         $salmon .= '  <link rel="http://salmon-protocol.org/ns/salmon-mention" href="' . xmlify($a->get_baseurl() . '/salmon/' . $nick) . '" />' . "\n" ; 
1537         return $salmon;
1538 }}
1539
1540 if(! function_exists('get_plink')) {
1541 /**
1542  * get private link for item
1543  * @param array $item
1544  * @return boolean|array False if item has not plink, otherwise array('href'=>plink url, 'title'=>translated title)
1545  */
1546 function get_plink($item) {
1547         $a = get_app(); 
1548         if (x($item,'plink') && ($item['private'] != 1)) {
1549                 return array(
1550                         'href' => $item['plink'],
1551                         'title' => t('link to source'),
1552                 );
1553         } 
1554         else {
1555                 return false;
1556         }
1557 }}
1558
1559 if(! function_exists('unamp')) {
1560 /**
1561  * replace html amp entity with amp char
1562  * @param string $s
1563  * @return string
1564  */
1565 function unamp($s) {
1566         return str_replace('&amp;', '&', $s);
1567 }}
1568
1569
1570
1571
1572 if(! function_exists('lang_selector')) {
1573 /**
1574  * get html for language selector
1575  * @global string $lang
1576  * @return string 
1577  * @template lang_selector.tpl
1578  */
1579 function lang_selector() {
1580         global $lang;
1581         
1582         $langs = glob('view/*/strings.php');
1583         
1584         $lang_options = array();
1585         $selected = "";
1586         
1587         if(is_array($langs) && count($langs)) {
1588                 $langs[] = '';
1589                 if(! in_array('view/en/strings.php',$langs))
1590                         $langs[] = 'view/en/';
1591                 asort($langs);
1592                 foreach($langs as $l) {
1593                         if($l == '') {
1594                                 $lang_options[""] = t('default');
1595                                 continue;
1596                         }
1597                         $ll = substr($l,5);
1598                         $ll = substr($ll,0,strrpos($ll,'/'));
1599                         $selected = (($ll === $lang && (x($_SESSION, 'language'))) ? $ll : $selected);
1600                         $lang_options[$ll]=$ll;
1601                 }
1602         }
1603
1604         $tpl = get_markup_template("lang_selector.tpl");        
1605         $o = replace_macros($tpl, array(
1606                 '$title' => t('Select an alternate language'),
1607                 '$langs' => array($lang_options, $selected),
1608                 
1609         ));
1610         return $o;
1611 }}
1612
1613
1614 if(! function_exists('return_bytes')) {
1615 /**
1616  * return number of bytes in size (K, M, G)
1617  * @param string $size_str
1618  * @return number
1619  */
1620 function return_bytes ($size_str) {
1621     switch (substr ($size_str, -1))
1622     {
1623         case 'M': case 'm': return (int)$size_str * 1048576;
1624         case 'K': case 'k': return (int)$size_str * 1024;
1625         case 'G': case 'g': return (int)$size_str * 1073741824;
1626         default: return $size_str;
1627     }
1628 }}
1629
1630 /**
1631  * @return string
1632  */
1633 function generate_user_guid() {
1634         $found = true;
1635         do {
1636                 $guid = random_string(16);
1637                 $x = q("SELECT `uid` FROM `user` WHERE `guid` = '%s' LIMIT 1",
1638                         dbesc($guid)
1639                 );
1640                 if(! count($x))
1641                         $found = false;
1642         } while ($found == true );
1643         return $guid;
1644 }
1645
1646
1647 /**
1648  * @param string $s
1649  * @param boolean $strip_padding
1650  * @return string
1651  */
1652 function base64url_encode($s, $strip_padding = false) {
1653
1654         $s = strtr(base64_encode($s),'+/','-_');
1655
1656         if($strip_padding)
1657                 $s = str_replace('=','',$s);
1658
1659         return $s;
1660 }
1661
1662 /**
1663  * @param string $s
1664  * @return string
1665  */
1666 function base64url_decode($s) {
1667
1668         if(is_array($s)) {
1669                 logger('base64url_decode: illegal input: ' . print_r(debug_backtrace(), true));
1670                 return $s;
1671         }
1672
1673 /*
1674  *  // Placeholder for new rev of salmon which strips base64 padding.
1675  *  // PHP base64_decode handles the un-padded input without requiring this step
1676  *  // Uncomment if you find you need it.
1677  *
1678  *      $l = strlen($s);
1679  *      if(! strpos($s,'=')) {
1680  *              $m = $l % 4;
1681  *              if($m == 2)
1682  *                      $s .= '==';
1683  *              if($m == 3)
1684  *                      $s .= '=';
1685  *      }
1686  *
1687  */
1688
1689         return base64_decode(strtr($s,'-_','+/'));
1690 }
1691
1692
1693 if (!function_exists('str_getcsv')) {
1694         /**
1695          * Parse csv string
1696          * 
1697          * @param string $input
1698          * @param string $delimiter
1699          * @param string $enclosure
1700          * @param string $escape
1701          * @param string $eol
1702          * @return boolean|array False on error, otherwise array[row][column]
1703          */
1704     function str_getcsv($input, $delimiter = ',', $enclosure = '"', $escape = '\\', $eol = '\n') {
1705         if (is_string($input) && !empty($input)) {
1706             $output = array();
1707             $tmp    = preg_split("/".$eol."/",$input);
1708             if (is_array($tmp) && !empty($tmp)) {
1709                 while (list($line_num, $line) = each($tmp)) {
1710                     if (preg_match("/".$escape.$enclosure."/",$line)) {
1711                         while ($strlen = strlen($line)) {
1712                             $pos_delimiter       = strpos($line,$delimiter);
1713                             $pos_enclosure_start = strpos($line,$enclosure);
1714                             if (
1715                                 is_int($pos_delimiter) && is_int($pos_enclosure_start)
1716                                 && ($pos_enclosure_start < $pos_delimiter)
1717                                 ) {
1718                                 $enclosed_str = substr($line,1);
1719                                 $pos_enclosure_end = strpos($enclosed_str,$enclosure);
1720                                 $enclosed_str = substr($enclosed_str,0,$pos_enclosure_end);
1721                                 $output[$line_num][] = $enclosed_str;
1722                                 $offset = $pos_enclosure_end+3;
1723                             } else {
1724                                 if (empty($pos_delimiter) && empty($pos_enclosure_start)) {
1725                                     $output[$line_num][] = substr($line,0);
1726                                     $offset = strlen($line);
1727                                 } else {
1728                                     $output[$line_num][] = substr($line,0,$pos_delimiter);
1729                                     $offset = (
1730                                                 !empty($pos_enclosure_start)
1731                                                 && ($pos_enclosure_start < $pos_delimiter)
1732                                                 )
1733                                                 ?$pos_enclosure_start
1734                                                 :$pos_delimiter+1;
1735                                 }
1736                             }
1737                             $line = substr($line,$offset);
1738                         }
1739                     } else {
1740                         $line = preg_split("/".$delimiter."/",$line);
1741    
1742                         /*
1743                          * Validating against pesky extra line breaks creating false rows.
1744                          */
1745                         if (is_array($line) && !empty($line[0])) {
1746                             $output[$line_num] = $line;
1747                         } 
1748                     }
1749                 }
1750                 return $output;
1751             } else {
1752                 return false;
1753             }
1754         } else {
1755             return false;
1756         }
1757     }
1758
1759
1760 /**
1761  * return div element with class 'clear'
1762  * @return string
1763  * @deprecated
1764  */
1765 function cleardiv() {
1766         return '<div class="clear"></div>';
1767 }
1768
1769
1770 function bb_translate_video($s) {
1771
1772         $matches = null;
1773         $r = preg_match_all("/\[video\](.*?)\[\/video\]/ism",$s,$matches,PREG_SET_ORDER);
1774         if($r) {
1775                 foreach($matches as $mtch) {
1776                         if((stristr($mtch[1],'youtube')) || (stristr($mtch[1],'youtu.be')))
1777                                 $s = str_replace($mtch[0],'[youtube]' . $mtch[1] . '[/youtube]',$s);
1778                         elseif(stristr($mtch[1],'vimeo'))
1779                                 $s = str_replace($mtch[0],'[vimeo]' . $mtch[1] . '[/vimeo]',$s);
1780                 }
1781         }
1782         return $s;      
1783 }
1784
1785 function html2bb_video($s) {
1786
1787         $s = preg_replace('#<object[^>]+>(.*?)https?://www.youtube.com/((?:v|cp)/[A-Za-z0-9\-_=]+)(.*?)</object>#ism',
1788                         '[youtube]$2[/youtube]', $s);
1789
1790         $s = preg_replace('#<iframe[^>](.*?)https?://www.youtube.com/embed/([A-Za-z0-9\-_=]+)(.*?)</iframe>#ism',
1791                         '[youtube]$2[/youtube]', $s);
1792
1793         $s = preg_replace('#<iframe[^>](.*?)https?://player.vimeo.com/video/([0-9]+)(.*?)</iframe>#ism',
1794                         '[vimeo]$2[/vimeo]', $s);
1795
1796         return $s;
1797 }
1798
1799 /**
1800  * apply xmlify() to all values of array $val, recursively
1801  * @param array $val
1802  * @return array
1803  */
1804 function array_xmlify($val){
1805         if (is_bool($val)) return $val?"true":"false";
1806         if (is_array($val)) return array_map('array_xmlify', $val);
1807         return xmlify((string) $val);
1808 }
1809
1810
1811 /**
1812  * transorm link href and img src from relative to absolute
1813  * 
1814  * @param string $text
1815  * @param string $base base url
1816  * @return string
1817  */
1818 function reltoabs($text, $base)
1819 {
1820   if (empty($base))
1821     return $text;
1822
1823   $base = rtrim($base,'/');
1824
1825   $base2 = $base . "/";
1826         
1827   // Replace links
1828   $pattern = "/<a([^>]*) href=\"(?!http|https|\/)([^\"]*)\"/";
1829   $replace = "<a\${1} href=\"" . $base2 . "\${2}\"";
1830   $text = preg_replace($pattern, $replace, $text);
1831
1832   $pattern = "/<a([^>]*) href=\"(?!http|https)([^\"]*)\"/";
1833   $replace = "<a\${1} href=\"" . $base . "\${2}\"";
1834   $text = preg_replace($pattern, $replace, $text);
1835
1836   // Replace images
1837   $pattern = "/<img([^>]*) src=\"(?!http|https|\/)([^\"]*)\"/";
1838   $replace = "<img\${1} src=\"" . $base2 . "\${2}\"";
1839   $text = preg_replace($pattern, $replace, $text); 
1840
1841   $pattern = "/<img([^>]*) src=\"(?!http|https)([^\"]*)\"/";
1842   $replace = "<img\${1} src=\"" . $base . "\${2}\"";
1843   $text = preg_replace($pattern, $replace, $text); 
1844
1845
1846   // Done
1847   return $text;
1848 }
1849
1850 /**
1851  * get translated item type
1852  * 
1853  * @param array $itme
1854  * @return string
1855  */
1856 function item_post_type($item) {
1857         if(intval($item['event-id']))
1858                 return t('event');
1859         if(strlen($item['resource-id']))
1860                 return t('photo');
1861         if(strlen($item['verb']) && $item['verb'] !== ACTIVITY_POST)
1862                 return t('activity');
1863         if($item['id'] != $item['parent'])
1864                 return t('comment');
1865         return t('post');
1866 }
1867
1868 // post categories and "save to file" use the same item.file table for storage.
1869 // We will differentiate the different uses by wrapping categories in angle brackets
1870 // and save to file categories in square brackets.
1871 // To do this we need to escape these characters if they appear in our tag. 
1872
1873 function file_tag_encode($s) {
1874         return str_replace(array('<','>','[',']'),array('%3c','%3e','%5b','%5d'),$s);
1875 }
1876
1877 function file_tag_decode($s) {
1878         return str_replace(array('%3c','%3e','%5b','%5d'),array('<','>','[',']'),$s);
1879 }
1880
1881 function file_tag_file_query($table,$s,$type = 'file') {
1882
1883         if($type == 'file')
1884                 $str = preg_quote( '[' . str_replace('%','%%',file_tag_encode($s)) . ']' );
1885         else
1886                 $str = preg_quote( '<' . str_replace('%','%%',file_tag_encode($s)) . '>' );
1887         return " AND " . (($table) ? dbesc($table) . '.' : '') . "file regexp '" . dbesc($str) . "' ";
1888 }
1889
1890 // ex. given music,video return <music><video> or [music][video]
1891 function file_tag_list_to_file($list,$type = 'file') {
1892         $tag_list = '';
1893         if(strlen($list)) {
1894                 $list_array = explode(",",$list);
1895                 if($type == 'file') {
1896                         $lbracket = '[';
1897                         $rbracket = ']';
1898                 }
1899                 else {
1900                         $lbracket = '<';
1901                         $rbracket = '>';
1902                 }
1903
1904                 foreach($list_array as $item) {
1905                   if(strlen($item)) {
1906                                 $tag_list .= $lbracket . file_tag_encode(trim($item))  . $rbracket;
1907                         }
1908                 }
1909         }
1910         return $tag_list;
1911 }
1912
1913 // ex. given <music><video>[friends], return music,video or friends
1914 function file_tag_file_to_list($file,$type = 'file') {
1915         $matches = false;
1916         $list = '';
1917         if($type == 'file') {
1918                 $cnt = preg_match_all('/\[(.*?)\]/',$file,$matches,PREG_SET_ORDER);
1919         }
1920         else {
1921                 $cnt = preg_match_all('/<(.*?)>/',$file,$matches,PREG_SET_ORDER);
1922         }
1923         if($cnt) {
1924                 foreach($matches as $mtch) {
1925                         if(strlen($list))
1926                                 $list .= ',';
1927                         $list .= file_tag_decode($mtch[1]);
1928                 }
1929         }
1930
1931         return $list;
1932 }
1933
1934 function file_tag_update_pconfig($uid,$file_old,$file_new,$type = 'file') {
1935         // $file_old - categories previously associated with an item
1936         // $file_new - new list of categories for an item
1937
1938         if(! intval($uid))
1939                 return false;
1940
1941         if($file_old == $file_new)
1942                 return true;
1943
1944         $saved = get_pconfig($uid,'system','filetags');
1945         if(strlen($saved)) {
1946                 if($type == 'file') {
1947                         $lbracket = '[';
1948                         $rbracket = ']';
1949                 }
1950                 else {
1951                         $lbracket = '<';
1952                         $rbracket = '>';
1953                 }
1954
1955                 $filetags_updated = $saved;
1956
1957                 // check for new tags to be added as filetags in pconfig
1958                 $new_tags = array();
1959                 $check_new_tags = explode(",",file_tag_file_to_list($file_new,$type));
1960
1961                 foreach($check_new_tags as $tag) {
1962                         if(! stristr($saved,$lbracket . file_tag_encode($tag) . $rbracket))
1963                                 $new_tags[] = $tag;
1964                 }
1965
1966                 $filetags_updated .= file_tag_list_to_file(implode(",",$new_tags),$type);
1967
1968                 // check for deleted tags to be removed from filetags in pconfig
1969                 $deleted_tags = array();
1970                 $check_deleted_tags = explode(",",file_tag_file_to_list($file_old,$type));
1971
1972                 foreach($check_deleted_tags as $tag) {
1973                         if(! stristr($file_new,$lbracket . file_tag_encode($tag) . $rbracket))
1974                                 $deleted_tags[] = $tag;
1975                 }
1976
1977                 foreach($deleted_tags as $key => $tag) {
1978                         $r = q("select file from item where uid = %d " . file_tag_file_query('item',$tag,$type),
1979                                 intval($uid)
1980                         );
1981
1982                         if(count($r)) {
1983                                 unset($deleted_tags[$key]);
1984                         }
1985                         else {
1986                                 $filetags_updated = str_replace($lbracket . file_tag_encode($tag) . $rbracket,'',$filetags_updated);
1987                         }
1988                 }
1989
1990                 if($saved != $filetags_updated) {
1991                         set_pconfig($uid,'system','filetags', $filetags_updated);
1992                 }
1993                 return true;
1994         }
1995         else
1996                 if(strlen($file_new)) {
1997                         set_pconfig($uid,'system','filetags', $file_new);
1998                 }
1999                 return true;
2000 }
2001
2002 function file_tag_save_file($uid,$item,$file) {
2003         $result = false;
2004         if(! intval($uid))
2005                 return false;
2006         $r = q("select file from item where id = %d and uid = %d limit 1",
2007                 intval($item),
2008                 intval($uid)
2009         );
2010         if(count($r)) {
2011                 if(! stristr($r[0]['file'],'[' . file_tag_encode($file) . ']'))
2012                         q("update item set file = '%s' where id = %d and uid = %d limit 1",
2013                                 dbesc($r[0]['file'] . '[' . file_tag_encode($file) . ']'),
2014                                 intval($item),
2015                                 intval($uid)
2016                         );
2017                 $saved = get_pconfig($uid,'system','filetags');
2018                 if((! strlen($saved)) || (! stristr($saved,'[' . file_tag_encode($file) . ']')))
2019                         set_pconfig($uid,'system','filetags',$saved . '[' . file_tag_encode($file) . ']');
2020                 info( t('Item filed') );
2021         }
2022         return true;
2023 }
2024
2025 function file_tag_unsave_file($uid,$item,$file,$cat = false) {
2026         $result = false;
2027         if(! intval($uid))
2028                 return false;
2029
2030         if($cat == true)
2031                 $pattern = '<' . file_tag_encode($file) . '>' ;
2032         else
2033                 $pattern = '[' . file_tag_encode($file) . ']' ;
2034
2035
2036         $r = q("select file from item where id = %d and uid = %d limit 1",
2037                 intval($item),
2038                 intval($uid)
2039         );
2040         if(! count($r))
2041                 return false;
2042
2043         q("update item set file = '%s' where id = %d and uid = %d limit 1",
2044                 dbesc(str_replace($pattern,'',$r[0]['file'])),
2045                 intval($item),
2046                 intval($uid)
2047         );
2048
2049         $r = q("select file from item where uid = %d and deleted = 0 " . file_tag_file_query('item',$file,(($cat) ? 'category' : 'file')),
2050                 intval($uid)
2051         );
2052
2053         if(! count($r)) {
2054                 $saved = get_pconfig($uid,'system','filetags');
2055                 set_pconfig($uid,'system','filetags',str_replace($pattern,'',$saved));
2056
2057         }
2058         return true;
2059 }
2060
2061 function normalise_openid($s) {
2062         return trim(str_replace(array('http://','https://'),array('',''),$s),'/');
2063 }
2064
2065
2066 function undo_post_tagging($s) {
2067         $matches = null;
2068         $cnt = preg_match_all('/([@#])\[url=(.*?)\](.*?)\[\/url\]/ism',$s,$matches,PREG_SET_ORDER);
2069         if($cnt) {
2070                 foreach($matches as $mtch) {
2071                         $s = str_replace($mtch[0], $mtch[1] . $mtch[3],$s);
2072                 }
2073         }
2074         return $s;
2075 }
2076
2077 function fix_mce_lf($s) {
2078         $s = str_replace("\r\n","\n",$s);
2079 //      $s = str_replace("\n\n","\n",$s);
2080         return $s;
2081 }
2082
2083
2084 function protect_sprintf($s) {
2085         return(str_replace('%','%%',$s));
2086 }
2087
2088
2089 function is_a_date_arg($s) {
2090         $i = intval($s);
2091         if($i > 1900) {
2092                 $y = date('Y');
2093                 if($i <= $y+1 && strpos($s,'-') == 4) {
2094                         $m = intval(substr($s,5));
2095                         if($m > 0 && $m <= 12)
2096                                 return true;
2097                 }
2098         }
2099         return false;
2100 }