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