]> git.mxchange.org Git - friendica.git/blob - include/text.php
basic video playback support using VideoJS
[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                                                         $a->page['end'] .= replace_macros(get_markup_template('videos_end.tpl'), array());
1311                                                 }
1312
1313                                                 $id = end(explode('/', $the_url));
1314                                                 $as .= replace_macros(get_markup_template('video_top.tpl'), array(
1315                                                         '$video'        => array(
1316                                                                 'id'       => $id,
1317                                                                 'title'         => t('View Video'),
1318                                                                 'src'           => $the_url,
1319                                                                 'mime'          => $mime,
1320                                                         ),
1321                                                 ));
1322                                         }
1323
1324                                         $filetype = strtolower(substr( $mime, 0, strpos($mime,'/') ));
1325                                         if($filetype) {
1326                                                 $filesubtype = strtolower(substr( $mime, strpos($mime,'/') + 1 ));
1327                                                 $filesubtype = str_replace('.', '-', $filesubtype);
1328                                         }
1329                                         else {
1330                                                 $filetype = 'unkn';
1331                                                 $filesubtype = 'unkn';
1332                                         }
1333
1334                                         $icon = '<div class="attachtype icon s22 type-' . $filetype . ' subtype-' . $filesubtype . '"></div>';
1335                                         /*$icontype = strtolower(substr($mtch[3],0,strpos($mtch[3],'/')));
1336                                         switch($icontype) {
1337                                                 case 'video':
1338                                                 case 'audio':
1339                                                 case 'image':
1340                                                 case 'text':
1341                                                         $icon = '<div class="attachtype icon s22 type-' . $icontype . '"></div>';
1342                                                         break;
1343                                                 default:
1344                                                         $icon = '<div class="attachtype icon s22 type-unkn"></div>';
1345                                                         break;
1346                                         }*/
1347
1348                                         $title = ((strlen(trim($mtch[4]))) ? escape_tags(trim($mtch[4])) : escape_tags($mtch[1]));
1349                                         $title .= ' ' . $mtch[2] . ' ' . t('bytes');
1350
1351                                         $as .= '<a href="' . strip_tags($the_url) . '" title="' . $title . '" class="attachlink" target="external-link" >' . $icon . '</a>';
1352                                 }
1353                         }
1354                 }
1355                 $as .= '<div class="clear"></div></div>';
1356         }
1357         $s = $s . $as;
1358
1359
1360         // Look for spoiler
1361         $spoilersearch = '<blockquote class="spoiler">';
1362
1363         // Remove line breaks before the spoiler
1364         while ((strpos($s, "\n".$spoilersearch) !== false))
1365                 $s = str_replace("\n".$spoilersearch, $spoilersearch, $s);
1366         while ((strpos($s, "<br />".$spoilersearch) !== false))
1367                 $s = str_replace("<br />".$spoilersearch, $spoilersearch, $s);
1368
1369         while ((strpos($s, $spoilersearch) !== false)) {
1370
1371                 $pos = strpos($s, $spoilersearch);
1372                 $rnd = random_string(8);
1373                 $spoilerreplace = '<br /> <span id="spoiler-wrap-'.$rnd.'" style="white-space:nowrap;" class="fakelink" onclick="openClose(\'spoiler-'.$rnd.'\');">'.sprintf(t('Click to open/close')).'</span>'.
1374                                         '<blockquote class="spoiler" id="spoiler-'.$rnd.'" style="display: none;">';
1375                 $s = substr($s, 0, $pos).$spoilerreplace.substr($s, $pos+strlen($spoilersearch));
1376         }
1377
1378         // Look for quote with author
1379         $authorsearch = '<blockquote class="author">';
1380
1381         while ((strpos($s, $authorsearch) !== false)) {
1382
1383                 $pos = strpos($s, $authorsearch);
1384                 $rnd = random_string(8);
1385                 $authorreplace = '<br /> <span id="author-wrap-'.$rnd.'" style="white-space:nowrap;" class="fakelink" onclick="openClose(\'author-'.$rnd.'\');">'.sprintf(t('Click to open/close')).'</span>'.
1386                                         '<blockquote class="author" id="author-'.$rnd.'" style="display: block;">';
1387                 $s = substr($s, 0, $pos).$authorreplace.substr($s, $pos+strlen($authorsearch));
1388         }
1389
1390         $prep_arr = array('item' => $item, 'html' => $s);
1391         call_hooks('prepare_body_final', $prep_arr);
1392
1393         return $prep_arr['html'];
1394 }}
1395
1396
1397 if(! function_exists('prepare_text')) {
1398 /**
1399  * Given a text string, convert from bbcode to html and add smilie icons.
1400  * 
1401  * @param string $text
1402  * @return string
1403  */
1404 function prepare_text($text) {
1405
1406         require_once('include/bbcode.php');
1407
1408         if(stristr($text,'[nosmile]'))
1409                 $s = bbcode($text);
1410         else
1411                 $s = smilies(bbcode($text));
1412
1413         return $s;
1414 }}
1415
1416
1417
1418 /**
1419  * return array with details for categories and folders for an item
1420  * 
1421  * @param array $item
1422  * @return array
1423  * 
1424   * [
1425  *      [ // categories array
1426  *          {
1427  *               'name': 'category name',
1428  *               'removeurl': 'url to remove this category',
1429  *               'first': 'is the first in this array? true/false',
1430  *               'last': 'is the last in this array? true/false',
1431  *           } ,
1432  *           ....
1433  *       ],
1434  *       [ //folders array
1435  *                      {
1436  *               'name': 'folder name',
1437  *               'removeurl': 'url to remove this folder',
1438  *               'first': 'is the first in this array? true/false',
1439  *               'last': 'is the last in this array? true/false',
1440  *           } ,
1441  *           ....       
1442  *       ]
1443  *  ]
1444  */
1445 function get_cats_and_terms($item) {
1446
1447     $a = get_app();
1448     $categories = array();
1449     $folders = array();
1450
1451     $matches = false; $first = true;
1452     $cnt = preg_match_all('/<(.*?)>/',$item['file'],$matches,PREG_SET_ORDER);
1453     if($cnt) {
1454         foreach($matches as $mtch) {
1455             $categories[] = array(
1456                 'name' => xmlify(file_tag_decode($mtch[1])),
1457                 'url' =>  "#",
1458                 'removeurl' => ((local_user() == $item['uid'])?$a->get_baseurl() . '/filerm/' . $item['id'] . '?f=&cat=' . xmlify(file_tag_decode($mtch[1])):""),
1459                 'first' => $first,
1460                 'last' => false
1461             );
1462             $first = false;
1463         }
1464     }
1465     if (count($categories)) $categories[count($categories)-1]['last'] = true;
1466     
1467
1468         if(local_user() == $item['uid']) {
1469             $matches = false; $first = true;
1470         $cnt = preg_match_all('/\[(.*?)\]/',$item['file'],$matches,PREG_SET_ORDER);
1471             if($cnt) {
1472             foreach($matches as $mtch) {
1473                     $folders[] = array(
1474                     'name' => xmlify(file_tag_decode($mtch[1])),
1475                          'url' =>  "#",
1476                         'removeurl' => ((local_user() == $item['uid'])?$a->get_baseurl() . '/filerm/' . $item['id'] . '?f=&term=' . xmlify(file_tag_decode($mtch[1])):""),
1477                     'first' => $first,
1478                         'last' => false
1479                 );
1480                     $first = false;
1481                         }
1482         }
1483     }
1484
1485     if (count($folders)) $folders[count($folders)-1]['last'] = true;
1486
1487     return array($categories, $folders);
1488 }
1489
1490
1491
1492 if(! function_exists('feed_hublinks')) {
1493 /**
1494  * return atom link elements for all of our hubs
1495  * @return string hub link xml elements
1496  */
1497 function feed_hublinks() {
1498
1499         $hub = get_config('system','huburl');
1500
1501         $hubxml = '';
1502         if(strlen($hub)) {
1503                 $hubs = explode(',', $hub);
1504                 if(count($hubs)) {
1505                         foreach($hubs as $h) {
1506                                 $h = trim($h);
1507                                 if(! strlen($h))
1508                                         continue;
1509                                 $hubxml .= '<link rel="hub" href="' . xmlify($h) . '" />' . "\n" ;
1510                         }
1511                 }
1512         }
1513         return $hubxml;
1514 }}
1515
1516
1517 if(! function_exists('feed_salmonlinks')) {
1518 /**
1519  * return atom link elements for salmon endpoints
1520  * @param string $nick user nickname
1521  * @return string salmon link xml elements
1522  */
1523 function feed_salmonlinks($nick) {
1524
1525         $a = get_app();
1526
1527         $salmon  = '<link rel="salmon" href="' . xmlify($a->get_baseurl() . '/salmon/' . $nick) . '" />' . "\n" ;
1528
1529         // old style links that status.net still needed as of 12/2010 
1530
1531         $salmon .= '  <link rel="http://salmon-protocol.org/ns/salmon-replies" href="' . xmlify($a->get_baseurl() . '/salmon/' . $nick) . '" />' . "\n" ; 
1532         $salmon .= '  <link rel="http://salmon-protocol.org/ns/salmon-mention" href="' . xmlify($a->get_baseurl() . '/salmon/' . $nick) . '" />' . "\n" ; 
1533         return $salmon;
1534 }}
1535
1536 if(! function_exists('get_plink')) {
1537 /**
1538  * get private link for item
1539  * @param array $item
1540  * @return boolean|array False if item has not plink, otherwise array('href'=>plink url, 'title'=>translated title)
1541  */
1542 function get_plink($item) {
1543         $a = get_app(); 
1544         if (x($item,'plink') && ($item['private'] != 1)) {
1545                 return array(
1546                         'href' => $item['plink'],
1547                         'title' => t('link to source'),
1548                 );
1549         } 
1550         else {
1551                 return false;
1552         }
1553 }}
1554
1555 if(! function_exists('unamp')) {
1556 /**
1557  * replace html amp entity with amp char
1558  * @param string $s
1559  * @return string
1560  */
1561 function unamp($s) {
1562         return str_replace('&amp;', '&', $s);
1563 }}
1564
1565
1566
1567
1568 if(! function_exists('lang_selector')) {
1569 /**
1570  * get html for language selector
1571  * @global string $lang
1572  * @return string 
1573  * @template lang_selector.tpl
1574  */
1575 function lang_selector() {
1576         global $lang;
1577         
1578         $langs = glob('view/*/strings.php');
1579         
1580         $lang_options = array();
1581         $selected = "";
1582         
1583         if(is_array($langs) && count($langs)) {
1584                 $langs[] = '';
1585                 if(! in_array('view/en/strings.php',$langs))
1586                         $langs[] = 'view/en/';
1587                 asort($langs);
1588                 foreach($langs as $l) {
1589                         if($l == '') {
1590                                 $lang_options[""] = t('default');
1591                                 continue;
1592                         }
1593                         $ll = substr($l,5);
1594                         $ll = substr($ll,0,strrpos($ll,'/'));
1595                         $selected = (($ll === $lang && (x($_SESSION, 'language'))) ? $ll : $selected);
1596                         $lang_options[$ll]=$ll;
1597                 }
1598         }
1599
1600         $tpl = get_markup_template("lang_selector.tpl");        
1601         $o = replace_macros($tpl, array(
1602                 '$title' => t('Select an alternate language'),
1603                 '$langs' => array($lang_options, $selected),
1604                 
1605         ));
1606         return $o;
1607 }}
1608
1609
1610 if(! function_exists('return_bytes')) {
1611 /**
1612  * return number of bytes in size (K, M, G)
1613  * @param string $size_str
1614  * @return number
1615  */
1616 function return_bytes ($size_str) {
1617     switch (substr ($size_str, -1))
1618     {
1619         case 'M': case 'm': return (int)$size_str * 1048576;
1620         case 'K': case 'k': return (int)$size_str * 1024;
1621         case 'G': case 'g': return (int)$size_str * 1073741824;
1622         default: return $size_str;
1623     }
1624 }}
1625
1626 /**
1627  * @return string
1628  */
1629 function generate_user_guid() {
1630         $found = true;
1631         do {
1632                 $guid = random_string(16);
1633                 $x = q("SELECT `uid` FROM `user` WHERE `guid` = '%s' LIMIT 1",
1634                         dbesc($guid)
1635                 );
1636                 if(! count($x))
1637                         $found = false;
1638         } while ($found == true );
1639         return $guid;
1640 }
1641
1642
1643 /**
1644  * @param string $s
1645  * @param boolean $strip_padding
1646  * @return string
1647  */
1648 function base64url_encode($s, $strip_padding = false) {
1649
1650         $s = strtr(base64_encode($s),'+/','-_');
1651
1652         if($strip_padding)
1653                 $s = str_replace('=','',$s);
1654
1655         return $s;
1656 }
1657
1658 /**
1659  * @param string $s
1660  * @return string
1661  */
1662 function base64url_decode($s) {
1663
1664         if(is_array($s)) {
1665                 logger('base64url_decode: illegal input: ' . print_r(debug_backtrace(), true));
1666                 return $s;
1667         }
1668
1669 /*
1670  *  // Placeholder for new rev of salmon which strips base64 padding.
1671  *  // PHP base64_decode handles the un-padded input without requiring this step
1672  *  // Uncomment if you find you need it.
1673  *
1674  *      $l = strlen($s);
1675  *      if(! strpos($s,'=')) {
1676  *              $m = $l % 4;
1677  *              if($m == 2)
1678  *                      $s .= '==';
1679  *              if($m == 3)
1680  *                      $s .= '=';
1681  *      }
1682  *
1683  */
1684
1685         return base64_decode(strtr($s,'-_','+/'));
1686 }
1687
1688
1689 if (!function_exists('str_getcsv')) {
1690         /**
1691          * Parse csv string
1692          * 
1693          * @param string $input
1694          * @param string $delimiter
1695          * @param string $enclosure
1696          * @param string $escape
1697          * @param string $eol
1698          * @return boolean|array False on error, otherwise array[row][column]
1699          */
1700     function str_getcsv($input, $delimiter = ',', $enclosure = '"', $escape = '\\', $eol = '\n') {
1701         if (is_string($input) && !empty($input)) {
1702             $output = array();
1703             $tmp    = preg_split("/".$eol."/",$input);
1704             if (is_array($tmp) && !empty($tmp)) {
1705                 while (list($line_num, $line) = each($tmp)) {
1706                     if (preg_match("/".$escape.$enclosure."/",$line)) {
1707                         while ($strlen = strlen($line)) {
1708                             $pos_delimiter       = strpos($line,$delimiter);
1709                             $pos_enclosure_start = strpos($line,$enclosure);
1710                             if (
1711                                 is_int($pos_delimiter) && is_int($pos_enclosure_start)
1712                                 && ($pos_enclosure_start < $pos_delimiter)
1713                                 ) {
1714                                 $enclosed_str = substr($line,1);
1715                                 $pos_enclosure_end = strpos($enclosed_str,$enclosure);
1716                                 $enclosed_str = substr($enclosed_str,0,$pos_enclosure_end);
1717                                 $output[$line_num][] = $enclosed_str;
1718                                 $offset = $pos_enclosure_end+3;
1719                             } else {
1720                                 if (empty($pos_delimiter) && empty($pos_enclosure_start)) {
1721                                     $output[$line_num][] = substr($line,0);
1722                                     $offset = strlen($line);
1723                                 } else {
1724                                     $output[$line_num][] = substr($line,0,$pos_delimiter);
1725                                     $offset = (
1726                                                 !empty($pos_enclosure_start)
1727                                                 && ($pos_enclosure_start < $pos_delimiter)
1728                                                 )
1729                                                 ?$pos_enclosure_start
1730                                                 :$pos_delimiter+1;
1731                                 }
1732                             }
1733                             $line = substr($line,$offset);
1734                         }
1735                     } else {
1736                         $line = preg_split("/".$delimiter."/",$line);
1737    
1738                         /*
1739                          * Validating against pesky extra line breaks creating false rows.
1740                          */
1741                         if (is_array($line) && !empty($line[0])) {
1742                             $output[$line_num] = $line;
1743                         } 
1744                     }
1745                 }
1746                 return $output;
1747             } else {
1748                 return false;
1749             }
1750         } else {
1751             return false;
1752         }
1753     }
1754
1755
1756 /**
1757  * return div element with class 'clear'
1758  * @return string
1759  * @deprecated
1760  */
1761 function cleardiv() {
1762         return '<div class="clear"></div>';
1763 }
1764
1765
1766 function bb_translate_video($s) {
1767
1768         $matches = null;
1769         $r = preg_match_all("/\[video\](.*?)\[\/video\]/ism",$s,$matches,PREG_SET_ORDER);
1770         if($r) {
1771                 foreach($matches as $mtch) {
1772                         if((stristr($mtch[1],'youtube')) || (stristr($mtch[1],'youtu.be')))
1773                                 $s = str_replace($mtch[0],'[youtube]' . $mtch[1] . '[/youtube]',$s);
1774                         elseif(stristr($mtch[1],'vimeo'))
1775                                 $s = str_replace($mtch[0],'[vimeo]' . $mtch[1] . '[/vimeo]',$s);
1776                 }
1777         }
1778         return $s;      
1779 }
1780
1781 function html2bb_video($s) {
1782
1783         $s = preg_replace('#<object[^>]+>(.*?)https?://www.youtube.com/((?:v|cp)/[A-Za-z0-9\-_=]+)(.*?)</object>#ism',
1784                         '[youtube]$2[/youtube]', $s);
1785
1786         $s = preg_replace('#<iframe[^>](.*?)https?://www.youtube.com/embed/([A-Za-z0-9\-_=]+)(.*?)</iframe>#ism',
1787                         '[youtube]$2[/youtube]', $s);
1788
1789         $s = preg_replace('#<iframe[^>](.*?)https?://player.vimeo.com/video/([0-9]+)(.*?)</iframe>#ism',
1790                         '[vimeo]$2[/vimeo]', $s);
1791
1792         return $s;
1793 }
1794
1795 /**
1796  * apply xmlify() to all values of array $val, recursively
1797  * @param array $val
1798  * @return array
1799  */
1800 function array_xmlify($val){
1801         if (is_bool($val)) return $val?"true":"false";
1802         if (is_array($val)) return array_map('array_xmlify', $val);
1803         return xmlify((string) $val);
1804 }
1805
1806
1807 /**
1808  * transorm link href and img src from relative to absolute
1809  * 
1810  * @param string $text
1811  * @param string $base base url
1812  * @return string
1813  */
1814 function reltoabs($text, $base)
1815 {
1816   if (empty($base))
1817     return $text;
1818
1819   $base = rtrim($base,'/');
1820
1821   $base2 = $base . "/";
1822         
1823   // Replace links
1824   $pattern = "/<a([^>]*) href=\"(?!http|https|\/)([^\"]*)\"/";
1825   $replace = "<a\${1} href=\"" . $base2 . "\${2}\"";
1826   $text = preg_replace($pattern, $replace, $text);
1827
1828   $pattern = "/<a([^>]*) href=\"(?!http|https)([^\"]*)\"/";
1829   $replace = "<a\${1} href=\"" . $base . "\${2}\"";
1830   $text = preg_replace($pattern, $replace, $text);
1831
1832   // Replace images
1833   $pattern = "/<img([^>]*) src=\"(?!http|https|\/)([^\"]*)\"/";
1834   $replace = "<img\${1} src=\"" . $base2 . "\${2}\"";
1835   $text = preg_replace($pattern, $replace, $text); 
1836
1837   $pattern = "/<img([^>]*) src=\"(?!http|https)([^\"]*)\"/";
1838   $replace = "<img\${1} src=\"" . $base . "\${2}\"";
1839   $text = preg_replace($pattern, $replace, $text); 
1840
1841
1842   // Done
1843   return $text;
1844 }
1845
1846 /**
1847  * get translated item type
1848  * 
1849  * @param array $itme
1850  * @return string
1851  */
1852 function item_post_type($item) {
1853         if(intval($item['event-id']))
1854                 return t('event');
1855         if(strlen($item['resource-id']))
1856                 return t('photo');
1857         if(strlen($item['verb']) && $item['verb'] !== ACTIVITY_POST)
1858                 return t('activity');
1859         if($item['id'] != $item['parent'])
1860                 return t('comment');
1861         return t('post');
1862 }
1863
1864 // post categories and "save to file" use the same item.file table for storage.
1865 // We will differentiate the different uses by wrapping categories in angle brackets
1866 // and save to file categories in square brackets.
1867 // To do this we need to escape these characters if they appear in our tag. 
1868
1869 function file_tag_encode($s) {
1870         return str_replace(array('<','>','[',']'),array('%3c','%3e','%5b','%5d'),$s);
1871 }
1872
1873 function file_tag_decode($s) {
1874         return str_replace(array('%3c','%3e','%5b','%5d'),array('<','>','[',']'),$s);
1875 }
1876
1877 function file_tag_file_query($table,$s,$type = 'file') {
1878
1879         if($type == 'file')
1880                 $str = preg_quote( '[' . str_replace('%','%%',file_tag_encode($s)) . ']' );
1881         else
1882                 $str = preg_quote( '<' . str_replace('%','%%',file_tag_encode($s)) . '>' );
1883         return " AND " . (($table) ? dbesc($table) . '.' : '') . "file regexp '" . dbesc($str) . "' ";
1884 }
1885
1886 // ex. given music,video return <music><video> or [music][video]
1887 function file_tag_list_to_file($list,$type = 'file') {
1888         $tag_list = '';
1889         if(strlen($list)) {
1890                 $list_array = explode(",",$list);
1891                 if($type == 'file') {
1892                         $lbracket = '[';
1893                         $rbracket = ']';
1894                 }
1895                 else {
1896                         $lbracket = '<';
1897                         $rbracket = '>';
1898                 }
1899
1900                 foreach($list_array as $item) {
1901                   if(strlen($item)) {
1902                                 $tag_list .= $lbracket . file_tag_encode(trim($item))  . $rbracket;
1903                         }
1904                 }
1905         }
1906         return $tag_list;
1907 }
1908
1909 // ex. given <music><video>[friends], return music,video or friends
1910 function file_tag_file_to_list($file,$type = 'file') {
1911         $matches = false;
1912         $list = '';
1913         if($type == 'file') {
1914                 $cnt = preg_match_all('/\[(.*?)\]/',$file,$matches,PREG_SET_ORDER);
1915         }
1916         else {
1917                 $cnt = preg_match_all('/<(.*?)>/',$file,$matches,PREG_SET_ORDER);
1918         }
1919         if($cnt) {
1920                 foreach($matches as $mtch) {
1921                         if(strlen($list))
1922                                 $list .= ',';
1923                         $list .= file_tag_decode($mtch[1]);
1924                 }
1925         }
1926
1927         return $list;
1928 }
1929
1930 function file_tag_update_pconfig($uid,$file_old,$file_new,$type = 'file') {
1931         // $file_old - categories previously associated with an item
1932         // $file_new - new list of categories for an item
1933
1934         if(! intval($uid))
1935                 return false;
1936
1937         if($file_old == $file_new)
1938                 return true;
1939
1940         $saved = get_pconfig($uid,'system','filetags');
1941         if(strlen($saved)) {
1942                 if($type == 'file') {
1943                         $lbracket = '[';
1944                         $rbracket = ']';
1945                 }
1946                 else {
1947                         $lbracket = '<';
1948                         $rbracket = '>';
1949                 }
1950
1951                 $filetags_updated = $saved;
1952
1953                 // check for new tags to be added as filetags in pconfig
1954                 $new_tags = array();
1955                 $check_new_tags = explode(",",file_tag_file_to_list($file_new,$type));
1956
1957                 foreach($check_new_tags as $tag) {
1958                         if(! stristr($saved,$lbracket . file_tag_encode($tag) . $rbracket))
1959                                 $new_tags[] = $tag;
1960                 }
1961
1962                 $filetags_updated .= file_tag_list_to_file(implode(",",$new_tags),$type);
1963
1964                 // check for deleted tags to be removed from filetags in pconfig
1965                 $deleted_tags = array();
1966                 $check_deleted_tags = explode(",",file_tag_file_to_list($file_old,$type));
1967
1968                 foreach($check_deleted_tags as $tag) {
1969                         if(! stristr($file_new,$lbracket . file_tag_encode($tag) . $rbracket))
1970                                 $deleted_tags[] = $tag;
1971                 }
1972
1973                 foreach($deleted_tags as $key => $tag) {
1974                         $r = q("select file from item where uid = %d " . file_tag_file_query('item',$tag,$type),
1975                                 intval($uid)
1976                         );
1977
1978                         if(count($r)) {
1979                                 unset($deleted_tags[$key]);
1980                         }
1981                         else {
1982                                 $filetags_updated = str_replace($lbracket . file_tag_encode($tag) . $rbracket,'',$filetags_updated);
1983                         }
1984                 }
1985
1986                 if($saved != $filetags_updated) {
1987                         set_pconfig($uid,'system','filetags', $filetags_updated);
1988                 }
1989                 return true;
1990         }
1991         else
1992                 if(strlen($file_new)) {
1993                         set_pconfig($uid,'system','filetags', $file_new);
1994                 }
1995                 return true;
1996 }
1997
1998 function file_tag_save_file($uid,$item,$file) {
1999         $result = false;
2000         if(! intval($uid))
2001                 return false;
2002         $r = q("select file from item where id = %d and uid = %d limit 1",
2003                 intval($item),
2004                 intval($uid)
2005         );
2006         if(count($r)) {
2007                 if(! stristr($r[0]['file'],'[' . file_tag_encode($file) . ']'))
2008                         q("update item set file = '%s' where id = %d and uid = %d limit 1",
2009                                 dbesc($r[0]['file'] . '[' . file_tag_encode($file) . ']'),
2010                                 intval($item),
2011                                 intval($uid)
2012                         );
2013                 $saved = get_pconfig($uid,'system','filetags');
2014                 if((! strlen($saved)) || (! stristr($saved,'[' . file_tag_encode($file) . ']')))
2015                         set_pconfig($uid,'system','filetags',$saved . '[' . file_tag_encode($file) . ']');
2016                 info( t('Item filed') );
2017         }
2018         return true;
2019 }
2020
2021 function file_tag_unsave_file($uid,$item,$file,$cat = false) {
2022         $result = false;
2023         if(! intval($uid))
2024                 return false;
2025
2026         if($cat == true)
2027                 $pattern = '<' . file_tag_encode($file) . '>' ;
2028         else
2029                 $pattern = '[' . file_tag_encode($file) . ']' ;
2030
2031
2032         $r = q("select file from item where id = %d and uid = %d limit 1",
2033                 intval($item),
2034                 intval($uid)
2035         );
2036         if(! count($r))
2037                 return false;
2038
2039         q("update item set file = '%s' where id = %d and uid = %d limit 1",
2040                 dbesc(str_replace($pattern,'',$r[0]['file'])),
2041                 intval($item),
2042                 intval($uid)
2043         );
2044
2045         $r = q("select file from item where uid = %d and deleted = 0 " . file_tag_file_query('item',$file,(($cat) ? 'category' : 'file')),
2046                 intval($uid)
2047         );
2048
2049         if(! count($r)) {
2050                 $saved = get_pconfig($uid,'system','filetags');
2051                 set_pconfig($uid,'system','filetags',str_replace($pattern,'',$saved));
2052
2053         }
2054         return true;
2055 }
2056
2057 function normalise_openid($s) {
2058         return trim(str_replace(array('http://','https://'),array('',''),$s),'/');
2059 }
2060
2061
2062 function undo_post_tagging($s) {
2063         $matches = null;
2064         $cnt = preg_match_all('/([@#])\[url=(.*?)\](.*?)\[\/url\]/ism',$s,$matches,PREG_SET_ORDER);
2065         if($cnt) {
2066                 foreach($matches as $mtch) {
2067                         $s = str_replace($mtch[0], $mtch[1] . $mtch[3],$s);
2068                 }
2069         }
2070         return $s;
2071 }
2072
2073 function fix_mce_lf($s) {
2074         $s = str_replace("\r\n","\n",$s);
2075 //      $s = str_replace("\n\n","\n",$s);
2076         return $s;
2077 }
2078
2079
2080 function protect_sprintf($s) {
2081         return(str_replace('%','%%',$s));
2082 }
2083
2084
2085 function is_a_date_arg($s) {
2086         $i = intval($s);
2087         if($i > 1900) {
2088                 $y = date('Y');
2089                 if($i <= $y+1 && strpos($s,'-') == 4) {
2090                         $m = intval(substr($s,5));
2091                         if($m > 0 && $m <= 12)
2092                                 return true;
2093                 }
2094         }
2095         return false;
2096 }