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