]> git.mxchange.org Git - friendica.git/blob - include/text.php
Merge remote branch 'upstream/master'
[friendica.git] / include / text.php
1 <?php
2
3 // This is our template processor.
4 // $s is the string requiring macro substitution.
5 // $r is an array of key value pairs (search => replace)
6 // returns substituted string.
7 // WARNING: this is pretty basic, and doesn't properly handle search strings that are substrings of each other.
8 // For instance if 'test' => "foo" and 'testing' => "bar", testing could become either bar or fooing, 
9 // depending on the order in which they were declared in the array.   
10
11 require_once("include/template_processor.php");
12
13 if(! function_exists('replace_macros')) {  
14 function replace_macros($s,$r) {
15         global $t;
16         
17         //$ts = microtime();
18         $r =  $t->replace($s,$r);
19         //$tt = microtime() - $ts;
20         
21         //$a = get_app();
22         //$a->page['debug'] .= "$tt <br>\n";
23         return template_unescape($r);
24
25 }}
26
27
28 // random string, there are 86 characters max in text mode, 128 for hex
29 // output is urlsafe
30
31 define('RANDOM_STRING_HEX',  0x00 );
32 define('RANDOM_STRING_TEXT', 0x01 );
33
34 if(! function_exists('random_string')) {
35 function random_string($size = 64,$type = RANDOM_STRING_HEX) {
36         // generate a bit of entropy and run it through the whirlpool
37         $s = hash('whirlpool', (string) rand() . uniqid(rand(),true) . (string) rand(),(($type == RANDOM_STRING_TEXT) ? true : false));
38         $s = (($type == RANDOM_STRING_TEXT) ? str_replace("\n","",base64url_encode($s,true)) : $s);
39         return(substr($s,0,$size));
40 }}
41
42 /**
43  * This is our primary input filter. 
44  *
45  * The high bit hack only involved some old IE browser, forget which (IE5/Mac?)
46  * that had an XSS attack vector due to stripping the high-bit on an 8-bit character
47  * after cleansing, and angle chars with the high bit set could get through as markup.
48  * 
49  * This is now disabled because it was interfering with some legitimate unicode sequences 
50  * and hopefully there aren't a lot of those browsers left. 
51  *
52  * Use this on any text input where angle chars are not valid or permitted
53  * They will be replaced with safer brackets. This may be filtered further
54  * if these are not allowed either.   
55  *
56  */
57
58 if(! function_exists('notags')) {
59 function notags($string) {
60
61         return(str_replace(array("<",">"), array('[',']'), $string));
62
63 //  High-bit filter no longer used
64 //      return(str_replace(array("<",">","\xBA","\xBC","\xBE"), array('[',']','','',''), $string));
65 }}
66
67 // use this on "body" or "content" input where angle chars shouldn't be removed,
68 // and allow them to be safely displayed.
69
70 if(! function_exists('escape_tags')) {
71 function escape_tags($string) {
72
73         return(htmlspecialchars($string));
74 }}
75
76
77 // generate a string that's random, but usually pronounceable. 
78 // used to generate initial passwords
79
80 if(! function_exists('autoname')) {
81 function autoname($len) {
82
83         if($len <= 0)
84                 return '';
85
86         $vowels = array('a','a','ai','au','e','e','e','ee','ea','i','ie','o','ou','u'); 
87         if(mt_rand(0,5) == 4)
88                 $vowels[] = 'y';
89
90         $cons = array(
91                         'b','bl','br',
92                         'c','ch','cl','cr',
93                         'd','dr',
94                         'f','fl','fr',
95                         'g','gh','gl','gr',
96                         'h',
97                         'j',
98                         'k','kh','kl','kr',
99                         'l',
100                         'm',
101                         'n',
102                         'p','ph','pl','pr',
103                         'qu',
104                         'r','rh',
105                         's','sc','sh','sm','sp','st',
106                         't','th','tr',
107                         'v',
108                         'w','wh',
109                         'x',
110                         'z','zh'
111                         );
112
113         $midcons = array('ck','ct','gn','ld','lf','lm','lt','mb','mm', 'mn','mp',
114                                 'nd','ng','nk','nt','rn','rp','rt');
115
116         $noend = array('bl', 'br', 'cl','cr','dr','fl','fr','gl','gr',
117                                 'kh', 'kl','kr','mn','pl','pr','rh','tr','qu','wh');
118
119         $start = mt_rand(0,2);
120         if($start == 0)
121                 $table = $vowels;
122         else
123                 $table = $cons;
124
125         $word = '';
126
127         for ($x = 0; $x < $len; $x ++) {
128                 $r = mt_rand(0,count($table) - 1);
129                 $word .= $table[$r];
130   
131                 if($table == $vowels)
132                         $table = array_merge($cons,$midcons);
133                 else
134                         $table = $vowels;
135
136         }
137
138         $word = substr($word,0,$len);
139
140         foreach($noend as $noe) {
141                 if((strlen($word) > 2) && (substr($word,-2) == $noe)) {
142                         $word = substr($word,0,-1);
143                         break;
144                 }
145         }
146         if(substr($word,-1) == 'q')
147                 $word = substr($word,0,-1);    
148         return $word;
149 }}
150
151
152 // escape text ($str) for XML transport
153 // returns escaped text.
154
155 if(! function_exists('xmlify')) {
156 function xmlify($str) {
157         $buffer = '';
158         
159         for($x = 0; $x < mb_strlen($str); $x ++) {
160                 $char = $str[$x];
161         
162                 switch( $char ) {
163
164                         case "\r" :
165                                 break;
166                         case "&" :
167                                 $buffer .= '&amp;';
168                                 break;
169                         case "'" :
170                                 $buffer .= '&apos;';
171                                 break;
172                         case "\"" :
173                                 $buffer .= '&quot;';
174                                 break;
175                         case '<' :
176                                 $buffer .= '&lt;';
177                                 break;
178                         case '>' :
179                                 $buffer .= '&gt;';
180                                 break;
181                         case "\n" :
182                                 $buffer .= "\n";
183                                 break;
184                         default :
185                                 $buffer .= $char;
186                                 break;
187                 }       
188         }
189         $buffer = trim($buffer);
190         return($buffer);
191 }}
192
193 // undo an xmlify
194 // pass xml escaped text ($s), returns unescaped text
195
196 if(! function_exists('unxmlify')) {
197 function unxmlify($s) {
198         $ret = str_replace('&amp;','&', $s);
199         $ret = str_replace(array('&lt;','&gt;','&quot;','&apos;'),array('<','>','"',"'"),$ret);
200         return $ret;    
201 }}
202
203 // convenience wrapper, reverse the operation "bin2hex"
204
205 if(! function_exists('hex2bin')) {
206 function hex2bin($s) {
207         if(! (is_string($s) && strlen($s)))
208                 return '';
209
210         if(! ctype_xdigit($s)) {
211                 return($s);
212         }
213
214         return(pack("H*",$s));
215 }}
216
217 // Automatic pagination.
218 // To use, get the count of total items.
219 // Then call $a->set_pager_total($number_items);
220 // Optionally call $a->set_pager_itemspage($n) to the number of items to display on each page
221 // Then call paginate($a) after the end of the display loop to insert the pager block on the page
222 // (assuming there are enough items to paginate).
223 // When using with SQL, the setting LIMIT %d, %d => $a->pager['start'],$a->pager['itemspage']
224 // will limit the results to the correct items for the current page. 
225 // The actual page handling is then accomplished at the application layer. 
226
227 if(! function_exists('paginate')) {
228 function paginate(&$a) {
229         $o = '';
230         $stripped = preg_replace('/(&page=[0-9]*)/','',$a->query_string);
231
232 //      $stripped = preg_replace('/&zrl=(.*?)([\?&]|$)/ism','',$stripped);
233
234         $stripped = str_replace('q=','',$stripped);
235         $stripped = trim($stripped,'/');
236         $pagenum = $a->pager['page'];
237         $url = $a->get_baseurl() . '/' . $stripped;
238
239
240           if($a->pager['total'] > $a->pager['itemspage']) {
241                 $o .= '<div class="pager">';
242                 if($a->pager['page'] != 1)
243                         $o .= '<span class="pager_prev">'."<a href=\"$url".'&page='.($a->pager['page'] - 1).'">' . t('prev') . '</a></span> ';
244
245                 $o .=  "<span class=\"pager_first\"><a href=\"$url"."&page=1\">" . t('first') . "</a></span> ";
246
247                 $numpages = $a->pager['total'] / $a->pager['itemspage'];
248
249                         $numstart = 1;
250                 $numstop = $numpages;
251
252                 if($numpages > 14) {
253                         $numstart = (($pagenum > 7) ? ($pagenum - 7) : 1);
254                         $numstop = (($pagenum > ($numpages - 7)) ? $numpages : ($numstart + 14));
255                 }
256    
257                 for($i = $numstart; $i <= $numstop; $i++){
258                         if($i == $a->pager['page'])
259                                 $o .= '<span class="pager_current">'.(($i < 10) ? '&nbsp;'.$i : $i);
260                         else
261                                 $o .= "<span class=\"pager_n\"><a href=\"$url"."&page=$i\">".(($i < 10) ? '&nbsp;'.$i : $i)."</a>";
262                         $o .= '</span> ';
263                 }
264
265                 if(($a->pager['total'] % $a->pager['itemspage']) != 0) {
266                         if($i == $a->pager['page'])
267                                 $o .= '<span class="pager_current">'.(($i < 10) ? '&nbsp;'.$i : $i);
268                         else
269                                 $o .= "<span class=\"pager_n\"><a href=\"$url"."&page=$i\">".(($i < 10) ? '&nbsp;'.$i : $i)."</a>";
270                         $o .= '</span> ';
271                 }
272
273                 $lastpage = (($numpages > intval($numpages)) ? intval($numpages)+1 : $numpages);
274                 $o .= "<span class=\"pager_last\"><a href=\"$url"."&page=$lastpage\">" . t('last') . "</a></span> ";
275
276                 if(($a->pager['total'] - ($a->pager['itemspage'] * $a->pager['page'])) > 0)
277                         $o .= '<span class="pager_next">'."<a href=\"$url"."&page=".($a->pager['page'] + 1).'">' . t('next') . '</a></span>';
278                 $o .= '</div>'."\r\n";
279         }
280         return $o;
281 }}
282
283 // Turn user/group ACLs stored as angle bracketed text into arrays
284
285 if(! function_exists('expand_acl')) {
286 function expand_acl($s) {
287         // turn string array of angle-bracketed elements into numeric array
288         // e.g. "<1><2><3>" => array(1,2,3);
289         $ret = array();
290
291         if(strlen($s)) {
292                 $t = str_replace('<','',$s);
293                 $a = explode('>',$t);
294                 foreach($a as $aa) {
295                         if(intval($aa))
296                                 $ret[] = intval($aa);
297                 }
298         }
299         return $ret;
300 }}              
301
302 // Used to wrap ACL elements in angle brackets for storage 
303
304 if(! function_exists('sanitise_acl')) {
305 function sanitise_acl(&$item) {
306         if(intval($item))
307                 $item = '<' . intval(notags(trim($item))) . '>';
308         else
309                 unset($item);
310 }}
311
312
313 // Convert an ACL array to a storable string
314
315 if(! function_exists('perms2str')) {
316 function perms2str($p) {
317         $ret = '';
318         $tmp = $p;
319         if(is_array($tmp)) {
320                 array_walk($tmp,'sanitise_acl');
321                 $ret = implode('',$tmp);
322         }
323         return $ret;
324 }}
325
326 // generate a guaranteed unique (for this domain) item ID for ATOM
327 // safe from birthday paradox
328
329 if(! function_exists('item_new_uri')) {
330 function item_new_uri($hostname,$uid) {
331
332         do {
333                 $dups = false;
334                 $hash = random_string();
335
336                 $uri = "urn:X-dfrn:" . $hostname . ':' . $uid . ':' . $hash;
337
338                 $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' LIMIT 1",
339                         dbesc($uri));
340                 if(count($r))
341                         $dups = true;
342         } while($dups == true);
343         return $uri;
344 }}
345
346 // Generate a guaranteed unique photo ID.
347 // safe from birthday paradox
348
349 if(! function_exists('photo_new_resource')) {
350 function photo_new_resource() {
351
352         do {
353                 $found = false;
354                 $resource = hash('md5',uniqid(mt_rand(),true));
355                 $r = q("SELECT `id` FROM `photo` WHERE `resource-id` = '%s' LIMIT 1",
356                         dbesc($resource)
357                 );
358                 if(count($r))
359                         $found = true;
360         } while($found == true);
361         return $resource;
362 }}
363
364
365 // wrapper to load a view template, checking for alternate
366 // languages before falling back to the default
367
368 // obsolete, deprecated.
369
370 if(! function_exists('load_view_file')) {
371 function load_view_file($s) {
372         global $lang, $a;
373         if(! isset($lang))
374                 $lang = 'en';
375         $b = basename($s);
376         $d = dirname($s);
377         if(file_exists("$d/$lang/$b"))
378                 return file_get_contents("$d/$lang/$b");
379         
380         $theme = current_theme();
381         
382         if(file_exists("$d/theme/$theme/$b"))
383                 return file_get_contents("$d/theme/$theme/$b");
384                         
385         return file_get_contents($s);
386 }}
387
388 if(! function_exists('get_intltext_template')) {
389 function get_intltext_template($s) {
390         global $lang;
391
392         if(! isset($lang))
393                 $lang = 'en';
394
395         if(file_exists("view/$lang/$s"))
396                 return file_get_contents("view/$lang/$s");
397         elseif(file_exists("view/en/$s"))
398                 return file_get_contents("view/en/$s");
399         else
400                 return file_get_contents("view/$s");
401 }}
402
403 if(! function_exists('get_markup_template')) {
404 function get_markup_template($s) {
405         $a=get_app();
406         $theme = current_theme();
407         
408         if(file_exists("view/theme/$theme/$s"))
409                 return file_get_contents("view/theme/$theme/$s");
410         elseif (x($a->theme_info,"extends") && file_exists("view/theme/".$a->theme_info["extends"]."/$s"))
411                 return file_get_contents("view/theme/".$a->theme_info["extends"]."/$s");
412         else
413                 return file_get_contents("view/$s");
414
415 }}
416
417
418
419
420
421 // for html,xml parsing - let's say you've got
422 // an attribute foobar="class1 class2 class3"
423 // and you want to find out if it contains 'class3'.
424 // you can't use a normal sub string search because you
425 // might match 'notclass3' and a regex to do the job is 
426 // possible but a bit complicated. 
427 // pass the attribute string as $attr and the attribute you 
428 // are looking for as $s - returns true if found, otherwise false
429
430 if(! function_exists('attribute_contains')) {
431 function attribute_contains($attr,$s) {
432         $a = explode(' ', $attr);
433         if(count($a) && in_array($s,$a))
434                 return true;
435         return false;
436 }}
437
438 if(! function_exists('logger')) {
439 function logger($msg,$level = 0) {
440         // turn off logger in install mode
441         global $a;
442         global $db;
443
444         if(($a->module == 'install') || (! ($db && $db->connected))) return;
445
446         $debugging = get_config('system','debugging');
447         $loglevel  = intval(get_config('system','loglevel'));
448         $logfile   = get_config('system','logfile');
449
450         if((! $debugging) || (! $logfile) || ($level > $loglevel))
451                 return;
452         
453         @file_put_contents($logfile, datetime_convert() . ':' . session_id() . ' ' . $msg . "\n", FILE_APPEND);
454         return;
455 }}
456
457
458 if(! function_exists('activity_match')) {
459 function activity_match($haystack,$needle) {
460         if(($haystack === $needle) || ((basename($needle) === $haystack) && strstr($needle,NAMESPACE_ACTIVITY_SCHEMA)))
461                 return true;
462         return false;
463 }}
464
465
466 // Pull out all #hashtags and @person tags from $s;
467 // We also get @person@domain.com - which would make 
468 // the regex quite complicated as tags can also
469 // end a sentence. So we'll run through our results
470 // and strip the period from any tags which end with one.
471 // Returns array of tags found, or empty array.
472
473
474 if(! function_exists('get_tags')) {
475 function get_tags($s) {
476         $ret = array();
477
478         // ignore anything in a code block
479
480         $s = preg_replace('/\[code\](.*?)\[\/code\]/sm','',$s);
481
482         // Match full names against @tags including the space between first and last
483         // We will look these up afterward to see if they are full names or not recognisable.
484
485         if(preg_match_all('/(@[^ \x0D\x0A,:?]+ [^ \x0D\x0A@,:?]+)([ \x0D\x0A@,:?]|$)/',$s,$match)) {
486                 foreach($match[1] as $mtch) {
487                         if(strstr($mtch,"]")) {
488                                 // we might be inside a bbcode color tag - leave it alone
489                                 continue;
490                         }
491                         if(substr($mtch,-1,1) === '.')
492                                 $ret[] = substr($mtch,0,-1);
493                         else
494                                 $ret[] = $mtch;
495                 }
496         }
497
498         // Otherwise pull out single word tags. These can be @nickname, @first_last
499         // and #hash tags.
500
501         if(preg_match_all('/([@#][^ \x0D\x0A,;:?]+)([ \x0D\x0A,;:?]|$)/',$s,$match)) {
502                 foreach($match[1] as $mtch) {
503                         if(strstr($mtch,"]")) {
504                                 // we might be inside a bbcode color tag - leave it alone
505                                 continue;
506                         }
507                         if(substr($mtch,-1,1) === '.')
508                                 $mtch = substr($mtch,0,-1);
509                         // ignore strictly numeric tags like #1
510                         if((strpos($mtch,'#') === 0) && ctype_digit(substr($mtch,1)))
511                                 continue;
512                         // try not to catch url fragments
513                         if(strpos($s,$mtch) && preg_match('/[a-zA-z0-9\/]/',substr($s,strpos($s,$mtch)-1,1)))
514                                 continue;
515                         $ret[] = $mtch;
516                 }
517         }
518         return $ret;
519 }}
520
521
522 // quick and dirty quoted_printable encoding
523
524 if(! function_exists('qp')) {
525 function qp($s) {
526 return str_replace ("%","=",rawurlencode($s));
527 }} 
528
529
530
531 if(! function_exists('get_mentions')) {
532 function get_mentions($item) {
533         $o = '';
534         if(! strlen($item['tag']))
535                 return $o;
536
537         $arr = explode(',',$item['tag']);
538         foreach($arr as $x) {
539                 $matches = null;
540                 if(preg_match('/@\[url=([^\]]*)\]/',$x,$matches)) {
541                         $o .= "\t\t" . '<link rel="mentioned" href="' . $matches[1] . '" />' . "\r\n";
542                         $o .= "\t\t" . '<link rel="ostatus:attention" href="' . $matches[1] . '" />' . "\r\n";
543                 }
544         }
545         return $o;
546 }}
547
548 if(! function_exists('contact_block')) {
549 function contact_block() {
550         $o = '';
551         $a = get_app();
552
553         $shown = get_pconfig($a->profile['uid'],'system','display_friend_count');
554         if($shown === false)
555                 $shown = 24;
556         if($shown == 0)
557                 return;
558
559         if((! is_array($a->profile)) || ($a->profile['hide-friends']))
560                 return $o;
561         $r = q("SELECT COUNT(*) AS `total` FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 and `pending` = 0 AND `hidden` = 0 AND `archive` = 0",
562                         intval($a->profile['uid'])
563         );
564         if(count($r)) {
565                 $total = intval($r[0]['total']);
566         }
567         if(! $total) {
568                 $contacts = t('No contacts');
569                 $micropro = Null;
570                 
571         } else {
572                 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 and `pending` = 0 AND `hidden` = 0 AND `archive` = 0 ORDER BY RAND() LIMIT %d",
573                                 intval($a->profile['uid']),
574                                 intval($shown)
575                 );
576                 if(count($r)) {
577                         $contacts = sprintf( tt('%d Contact','%d Contacts', $total),$total);
578                         $micropro = Array();
579                         foreach($r as $rr) {
580                                 $micropro[] = micropro($rr,true,'mpfriend');
581                         }
582                 }
583         }
584         
585         $tpl = get_markup_template('contact_block.tpl');
586         $o = replace_macros($tpl, array(
587                 '$contacts' => $contacts,
588                 '$nickname' => $a->profile['nickname'],
589                 '$viewcontacts' => t('View Contacts'),
590                 '$micropro' => $micropro,
591         ));
592
593         $arr = array('contacts' => $r, 'output' => $o);
594
595         call_hooks('contact_block_end', $arr);
596         return $o;
597
598 }}
599
600 if(! function_exists('micropro')) {
601 function micropro($contact, $redirect = false, $class = '', $textmode = false) {
602
603         if($class)
604                 $class = ' ' . $class;
605
606         $url = $contact['url'];
607         $sparkle = '';
608         $redir = false;
609
610         if($redirect) {
611                 $a = get_app();
612                 $redirect_url = $a->get_baseurl() . '/redir/' . $contact['id'];
613                 if(local_user() && ($contact['uid'] == local_user()) && ($contact['network'] === 'dfrn')) {
614                         $redir = true;
615                         $url = $redirect_url;
616                         $sparkle = ' sparkle';
617                 }
618                 else
619                         $url = zrl($url);
620         }
621         $click = ((x($contact,'click')) ? ' onclick="' . $contact['click'] . '" ' : '');
622         if($click)
623                 $url = '';
624         if($textmode) {
625                 return '<div class="contact-block-textdiv' . $class . '"><a class="contact-block-link' . $class . $sparkle 
626                         . (($click) ? ' fakelink' : '') . '" '
627                         . (($redir) ? ' target="redir" ' : '')
628                         . (($url) ? ' href="' . $url . '"' : '') . $click
629                         . '" title="' . $contact['name'] . ' [' . $contact['url'] . ']" alt="' . $contact['name'] 
630                         . '" >'. $contact['name'] . '</a></div>' . "\r\n";
631         }
632         else {
633                 return '<div class="contact-block-div' . $class . '"><a class="contact-block-link' . $class . $sparkle 
634                         . (($click) ? ' fakelink' : '') . '" '
635                         . (($redir) ? ' target="redir" ' : '')
636                         . (($url) ? ' href="' . $url . '"' : '') . $click . ' ><img class="contact-block-img' . $class . $sparkle . '" src="' 
637                         . $contact['micro'] . '" title="' . $contact['name'] . ' [' . $contact['url'] . ']" alt="' . $contact['name'] 
638                         . '" /></a></div>' . "\r\n";
639         }
640 }}
641
642
643
644 if(! function_exists('search')) {
645 function search($s,$id='search-box',$url='/search',$save = false) {
646         $a = get_app();
647         $o  = '<div id="' . $id . '">';
648         $o .= '<form action="' . $a->get_baseurl((stristr($url,'network')) ? true : false) . $url . '" method="get" >';
649         $o .= '<input type="text" name="search" id="search-text" placeholder="' . t('Search') . '" value="' . $s .'" />';
650         $o .= '<input type="submit" name="submit" id="search-submit" value="' . t('Search') . '" />'; 
651         if($save)
652                 $o .= '<input type="submit" name="save" id="search-save" value="' . t('Save') . '" />'; 
653         $o .= '</form></div>';
654         return $o;
655 }}
656
657 if(! function_exists('valid_email')) {
658 function valid_email($x){
659         if(preg_match('/^[_a-zA-Z0-9\-\+]+(\.[_a-zA-Z0-9\-\+]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)+$/',$x))
660                 return true;
661         return false;
662 }}
663
664
665 /**
666  *
667  * Function: linkify
668  *
669  * Replace naked text hyperlink with HTML formatted hyperlink
670  *
671  */
672
673 if(! function_exists('linkify')) {
674 function linkify($s) {
675         $s = preg_replace("/(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\'\%\$\!\+]*)/", ' <a href="$1" target="external-link">$1</a>', $s);
676         $s = preg_replace("/\<(.*?)(src|href)=(.*?)\&amp\;(.*?)\>/ism",'<$1$2=$3&$4>',$s);
677         return($s);
678 }}
679
680
681 /**
682  * 
683  * Function: smilies
684  *
685  * Description:
686  * Replaces text emoticons with graphical images
687  *
688  * @Parameter: string $s
689  *
690  * Returns string
691  *
692  * It is expected that this function will be called using HTML text.
693  * We will escape text between HTML pre and code blocks from being 
694  * processed. 
695  * 
696  * At a higher level, the bbcode [nosmile] tag can be used to prevent this 
697  * function from being executed by the prepare_text() routine when preparing
698  * bbcode source for HTML display
699  *
700  */
701
702 if(! function_exists('smilies')) {
703 function smilies($s, $sample = false) {
704
705         $a = get_app();
706
707         if(intval(get_config('system','no_smilies')) 
708                 || (local_user() && intval(get_pconfig(local_user(),'system','no_smilies'))))
709                 return $s;
710
711         $s = preg_replace_callback('/<pre>(.*?)<\/pre>/ism','smile_encode',$s);
712         $s = preg_replace_callback('/<code>(.*?)<\/code>/ism','smile_encode',$s);
713
714         $texts =  array( 
715                 '&lt;3', 
716                 '&lt;/3', 
717                 '&lt;\\3', 
718                 ':-)', 
719                 ';-)', 
720                 ':-(', 
721                 ':-P', 
722                 ':-p', 
723                 ':-"', 
724                 ':-&quot;', 
725                 ':-x', 
726                 ':-X', 
727                 ':-D', 
728                 '8-|', 
729                 '8-O', 
730                 ':-O', 
731                 '\\o/', 
732                 'o.O', 
733                 'O.o', 
734                 'o_O', 
735                 'O_o', 
736                 ":'(", 
737                 ":-!", 
738                 ":-/", 
739                 ":-[", 
740                 "8-)",
741                 ':beer', 
742                 ':homebrew', 
743                 ':coffee', 
744                 ':facepalm',
745                 '~friendika', 
746                 '~friendica'
747
748         );
749
750         $icons = array(
751                 '<img src="' . $a->get_baseurl() . '/images/smiley-heart.gif" alt="<3" />',
752                 '<img src="' . $a->get_baseurl() . '/images/smiley-brokenheart.gif" alt="</3" />',
753                 '<img src="' . $a->get_baseurl() . '/images/smiley-brokenheart.gif" alt="<\\3" />',
754                 '<img src="' . $a->get_baseurl() . '/images/smiley-smile.gif" alt=":-)" />',
755                 '<img src="' . $a->get_baseurl() . '/images/smiley-wink.gif" alt=";-)" />',
756                 '<img src="' . $a->get_baseurl() . '/images/smiley-frown.gif" alt=":-(" />',
757                 '<img src="' . $a->get_baseurl() . '/images/smiley-tongue-out.gif" alt=":-P" />',
758                 '<img src="' . $a->get_baseurl() . '/images/smiley-tongue-out.gif" alt=":-p" />',
759                 '<img src="' . $a->get_baseurl() . '/images/smiley-kiss.gif" alt=":-\"" />',
760                 '<img src="' . $a->get_baseurl() . '/images/smiley-kiss.gif" alt=":-\"" />',
761                 '<img src="' . $a->get_baseurl() . '/images/smiley-kiss.gif" alt=":-x" />',
762                 '<img src="' . $a->get_baseurl() . '/images/smiley-kiss.gif" alt=":-X" />',
763                 '<img src="' . $a->get_baseurl() . '/images/smiley-laughing.gif" alt=":-D" />',
764                 '<img src="' . $a->get_baseurl() . '/images/smiley-surprised.gif" alt="8-|" />',
765                 '<img src="' . $a->get_baseurl() . '/images/smiley-surprised.gif" alt="8-O" />',
766                 '<img src="' . $a->get_baseurl() . '/images/smiley-surprised.gif" alt=":-O" />',                
767                 '<img src="' . $a->get_baseurl() . '/images/smiley-thumbsup.gif" alt="\\o/" />',
768                 '<img src="' . $a->get_baseurl() . '/images/smiley-Oo.gif" alt="o.O" />',
769                 '<img src="' . $a->get_baseurl() . '/images/smiley-Oo.gif" alt="O.o" />',
770                 '<img src="' . $a->get_baseurl() . '/images/smiley-Oo.gif" alt="o_O" />',
771                 '<img src="' . $a->get_baseurl() . '/images/smiley-Oo.gif" alt="O_o" />',
772                 '<img src="' . $a->get_baseurl() . '/images/smiley-cry.gif" alt=":\'(" />',
773                 '<img src="' . $a->get_baseurl() . '/images/smiley-foot-in-mouth.gif" alt=":-!" />',
774                 '<img src="' . $a->get_baseurl() . '/images/smiley-undecided.gif" alt=":-/" />',
775                 '<img src="' . $a->get_baseurl() . '/images/smiley-embarassed.gif" alt=":-[" />',
776                 '<img src="' . $a->get_baseurl() . '/images/smiley-cool.gif" alt="8-)" />',
777                 '<img src="' . $a->get_baseurl() . '/images/beer_mug.gif" alt=":beer" />',
778                 '<img src="' . $a->get_baseurl() . '/images/beer_mug.gif" alt=":homebrew" />',
779                 '<img src="' . $a->get_baseurl() . '/images/coffee.gif" alt=":coffee" />',
780                 '<img src="' . $a->get_baseurl() . '/images/smiley-facepalm.gif" alt=":facepalm" />',
781                 '<a href="http://project.friendika.com">~friendika <img src="' . $a->get_baseurl() . '/images/friendika-16.png" alt="~friendika" /></a>',
782                 '<a href="http://friendica.com">~friendica <img src="' . $a->get_baseurl() . '/images/friendica-16.png" alt="~friendica" /></a>'
783         );
784
785         $params = array('texts' => $texts, 'icons' => $icons, 'string' => $s);
786         call_hooks('smilie', $params);
787
788         if($sample) {
789                 $s = '<div class="smiley-sample">';
790                 for($x = 0; $x < count($params['texts']); $x ++) {
791                         $s .= '<dl><dt>' . $params['texts'][$x] . '</dt><dd>' . $params['icons'][$x] . '</dd></dl>';
792                 }
793         }
794         else {
795                 $params['string'] = preg_replace_callback('/&lt;(3+)/','preg_heart',$params['string']);
796                 $s = str_replace($params['texts'],$params['icons'],$params['string']);
797         }
798
799         $s = preg_replace_callback('/<pre>(.*?)<\/pre>/ism','smile_decode',$s);
800         $s = preg_replace_callback('/<code>(.*?)<\/code>/ism','smile_decode',$s);
801
802         return $s;
803
804 }}
805
806 function smile_encode($m) {
807         return(str_replace($m[1],base64url_encode($m[1]),$m[0]));
808 }
809
810 function smile_decode($m) {
811         return(str_replace($m[1],base64url_decode($m[1]),$m[0]));
812 }
813
814 // expand <3333 to the correct number of hearts
815
816 function preg_heart($x) {
817         $a = get_app();
818         if(strlen($x[1]) == 1)
819                 return $x[0];
820         $t = '';
821         for($cnt = 0; $cnt < strlen($x[1]); $cnt ++)
822                 $t .= '<img src="' . $a->get_baseurl() . '/images/smiley-heart.gif" alt="<3" />';
823         $r =  str_replace($x[0],$t,$x[0]);
824         return $r;
825 }
826
827
828 if(! function_exists('day_translate')) {
829 function day_translate($s) {
830         $ret = str_replace(array('Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'),
831                 array( t('Monday'), t('Tuesday'), t('Wednesday'), t('Thursday'), t('Friday'), t('Saturday'), t('Sunday')),
832                 $s);
833
834         $ret = str_replace(array('January','February','March','April','May','June','July','August','September','October','November','December'),
835                 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')),
836                 $ret);
837
838         return $ret;
839 }}
840
841
842 if(! function_exists('normalise_link')) {
843 function normalise_link($url) {
844         $ret = str_replace(array('https:','//www.'), array('http:','//'), $url);
845         return(rtrim($ret,'/'));
846 }}
847
848 /**
849  *
850  * Compare two URLs to see if they are the same, but ignore
851  * slight but hopefully insignificant differences such as if one 
852  * is https and the other isn't, or if one is www.something and 
853  * the other isn't - and also ignore case differences.
854  *
855  * Return true if the URLs match, otherwise false.
856  *
857  */
858
859 if(! function_exists('link_compare')) {
860 function link_compare($a,$b) {
861         if(strcasecmp(normalise_link($a),normalise_link($b)) === 0)
862                 return true;
863         return false;
864 }}
865
866 // Given an item array, convert the body element from bbcode to html and add smilie icons.
867 // If attach is true, also add icons for item attachments
868
869
870 if(! function_exists('prepare_body')) {
871 function prepare_body($item,$attach = false) {
872
873         $a = get_app();
874         call_hooks('prepare_body_init', $item); 
875
876         $cache = get_config('system','itemcache');
877
878         if (($cache != '')) {
879                 $cachefile = $cache."/".$item["guid"]."-".strtotime($item["edited"])."-".hash("crc32", $item['body']);
880
881                 if (file_exists($cachefile))
882                         $s = file_get_contents($cachefile);
883                 else {
884                         $s = prepare_text($item['body']);
885                         file_put_contents($cachefile, $s);
886                 }
887         } else
888                 $s = prepare_text($item['body']);
889
890         $prep_arr = array('item' => $item, 'html' => $s);
891         call_hooks('prepare_body', $prep_arr);
892         $s = $prep_arr['html'];
893
894         if(! $attach) {
895                 return $s;
896         }
897
898         $arr = explode(',',$item['attach']);
899         if(count($arr)) {
900                 $s .= '<div class="body-attach">';
901                 foreach($arr as $r) {
902                         $matches = false;
903                         $icon = '';
904                         $cnt = preg_match_all('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"\[\/attach\]|',$r,$matches, PREG_SET_ORDER);
905                         if($cnt) {
906                                 foreach($matches as $mtch) {
907                                         $icontype = strtolower(substr($mtch[3],0,strpos($mtch[3],'/')));
908                                         switch($icontype) {
909                                                 case 'video':
910                                                 case 'audio':
911                                                 case 'image':
912                                                 case 'text':
913                                                         $icon = '<div class="attachtype icon s22 type-' . $icontype . '"></div>';
914                                                         break;
915                                                 default:
916                                                         $icon = '<div class="attachtype icon s22 type-unkn"></div>';
917                                                         break;
918                                         }
919                                         $title = ((strlen(trim($mtch[4]))) ? escape_tags(trim($mtch[4])) : escape_tags($mtch[1]));
920                                         $title .= ' ' . $mtch[2] . ' ' . t('bytes');
921                                         if((local_user() == $item['uid']) && $item['contact-id'] != $a->contact['id'])
922                                                 $the_url = $a->get_baseurl() . '/redir/' . $item['contact-id'] . '?f=1&url=' . $mtch[1];
923                                         else
924                                                 $the_url = $mtch[1];
925
926                                         $s .= '<a href="' . strip_tags($the_url) . '" title="' . $title . '" class="attachlink" target="external-link" >' . $icon . '</a>';
927                                 }
928                         }
929                 }
930                 $s .= '<div class="clear"></div></div>';
931         }
932         $matches = false;
933         $cnt = preg_match_all('/<(.*?)>/',$item['file'],$matches,PREG_SET_ORDER);
934         if($cnt) {
935 //              logger('prepare_text: categories: ' . print_r($matches,true), LOGGER_DEBUG);
936                 foreach($matches as $mtch) {
937                         if(strlen($x))
938                                 $x .= ',';
939                         $x .= xmlify(file_tag_decode($mtch[1])) 
940                                 . ((local_user() == $item['uid']) ? ' <a href="' . $a->get_baseurl() . '/filerm/' . $item['id'] . '?f=&cat=' . xmlify(file_tag_decode($mtch[1])) . '" title="' . t('remove') . '" >' . t('[remove]') . '</a>' : '');
941                 }
942                 if(strlen($x))
943                         $s .= '<div class="categorytags"><span>' . t('Categories:') . ' </span>' . $x . '</div>'; 
944
945
946         }
947         $matches = false;
948         $x = '';
949         $cnt = preg_match_all('/\[(.*?)\]/',$item['file'],$matches,PREG_SET_ORDER);
950         if($cnt) {
951 //              logger('prepare_text: filed_under: ' . print_r($matches,true), LOGGER_DEBUG);
952                 foreach($matches as $mtch) {
953                         if(strlen($x))
954                                 $x .= '&nbsp;&nbsp;&nbsp;';
955                         $x .= xmlify(file_tag_decode($mtch[1])) . ' <a href="' . $a->get_baseurl() . '/filerm/' . $item['id'] . '?f=&term=' . xmlify(file_tag_decode($mtch[1])) . '" title="' . t('remove') . '" >' . t('[remove]') . '</a>';
956                 }
957                 if(strlen($x) && (local_user() == $item['uid']))
958                         $s .= '<div class="filesavetags"><span>' . t('Filed under:') . ' </span>' . $x . '</div>'; 
959         }
960
961         // Look for spoiler
962         $spoilersearch = '<blockquote class="spoiler">';
963
964         // Remove line breaks before the spoiler
965         while ((strpos($s, "\n".$spoilersearch) !== false))
966                 $s = str_replace("\n".$spoilersearch, $spoilersearch, $s);
967         while ((strpos($s, "<br />".$spoilersearch) !== false))
968                 $s = str_replace("<br />".$spoilersearch, $spoilersearch, $s);
969
970         while ((strpos($s, $spoilersearch) !== false)) {
971
972                 $pos = strpos($s, $spoilersearch);
973                 $rnd = random_string(8);
974                 $spoilerreplace = '<br /> <span id="spoiler-wrap-'.$rnd.'" style="white-space:nowrap;" class="fakelink" onclick="openClose(\'spoiler-'.$rnd.'\');">'.sprintf(t('Click to open/close')).'</span>'.
975                                         '<blockquote class="spoiler" id="spoiler-'.$rnd.'" style="display: none;">';
976                 $s = substr($s, 0, $pos).$spoilerreplace.substr($s, $pos+strlen($spoilersearch));
977         }
978
979         // Look for quote with author
980         $authorsearch = '<blockquote class="author">';
981
982         while ((strpos($s, $authorsearch) !== false)) {
983
984                 $pos = strpos($s, $authorsearch);
985                 $rnd = random_string(8);
986                 $authorreplace = '<br /> <span id="author-wrap-'.$rnd.'" style="white-space:nowrap;" class="fakelink" onclick="openClose(\'author-'.$rnd.'\');">'.sprintf(t('Click to open/close')).'</span>'.
987                                         '<blockquote class="author" id="author-'.$rnd.'" style="display: block;">';
988                 $s = substr($s, 0, $pos).$authorreplace.substr($s, $pos+strlen($authorsearch));
989         }
990
991         $prep_arr = array('item' => $item, 'html' => $s);
992         call_hooks('prepare_body_final', $prep_arr);
993
994         return $prep_arr['html'];
995 }}
996
997
998 // Given a text string, convert from bbcode to html and add smilie icons.
999
1000 if(! function_exists('prepare_text')) {
1001 function prepare_text($text) {
1002
1003         require_once('include/bbcode.php');
1004
1005         if(stristr($text,'[nosmile]'))
1006                 $s = bbcode($text);
1007         else
1008                 $s = smilies(bbcode($text));
1009
1010         return $s;
1011 }}
1012
1013
1014 /**
1015  * return atom link elements for all of our hubs
1016  */
1017
1018 if(! function_exists('feed_hublinks')) {
1019 function feed_hublinks() {
1020
1021         $hub = get_config('system','huburl');
1022
1023         $hubxml = '';
1024         if(strlen($hub)) {
1025                 $hubs = explode(',', $hub);
1026                 if(count($hubs)) {
1027                         foreach($hubs as $h) {
1028                                 $h = trim($h);
1029                                 if(! strlen($h))
1030                                         continue;
1031                                 $hubxml .= '<link rel="hub" href="' . xmlify($h) . '" />' . "\n" ;
1032                         }
1033                 }
1034         }
1035         return $hubxml;
1036 }}
1037
1038 /* return atom link elements for salmon endpoints */
1039
1040 if(! function_exists('feed_salmonlinks')) {
1041 function feed_salmonlinks($nick) {
1042
1043         $a = get_app();
1044
1045         $salmon  = '<link rel="salmon" href="' . xmlify($a->get_baseurl() . '/salmon/' . $nick) . '" />' . "\n" ;
1046
1047         // old style links that status.net still needed as of 12/2010 
1048
1049         $salmon .= '  <link rel="http://salmon-protocol.org/ns/salmon-replies" href="' . xmlify($a->get_baseurl() . '/salmon/' . $nick) . '" />' . "\n" ; 
1050         $salmon .= '  <link rel="http://salmon-protocol.org/ns/salmon-mention" href="' . xmlify($a->get_baseurl() . '/salmon/' . $nick) . '" />' . "\n" ; 
1051         return $salmon;
1052 }}
1053
1054 if(! function_exists('get_plink')) {
1055 function get_plink($item) {
1056         $a = get_app(); 
1057         if (x($item,'plink') && (! $item['private'])){
1058                 return array(
1059                         'href' => $item['plink'],
1060                         'title' => t('link to source'),
1061                 );
1062         } else {
1063                 return false;
1064         }
1065 }}
1066
1067 if(! function_exists('unamp')) {
1068 function unamp($s) {
1069         return str_replace('&amp;', '&', $s);
1070 }}
1071
1072
1073
1074
1075 if(! function_exists('lang_selector')) {
1076 function lang_selector() {
1077         global $lang;
1078         
1079         $langs = glob('view/*/strings.php');
1080         
1081         $lang_options = array();
1082         $selected = "";
1083         
1084         if(is_array($langs) && count($langs)) {
1085                 $langs[] = '';
1086                 if(! in_array('view/en/strings.php',$langs))
1087                         $langs[] = 'view/en/';
1088                 asort($langs);
1089                 foreach($langs as $l) {
1090                         if($l == '') {
1091                                 $lang_options[""] = t('default');
1092                                 continue;
1093                         }
1094                         $ll = substr($l,5);
1095                         $ll = substr($ll,0,strrpos($ll,'/'));
1096                         $selected = (($ll === $lang && (x($_SESSION, 'language'))) ? $ll : $selected);
1097                         $lang_options[$ll]=$ll;
1098                 }
1099         }
1100
1101         $tpl = get_markup_template("lang_selector.tpl");        
1102         $o = replace_macros($tpl, array(
1103                 '$title' => t('Select an alternate language'),
1104                 '$langs' => array($lang_options, $selected),
1105                 
1106         ));
1107         return $o;
1108 }}
1109
1110
1111 if(! function_exists('return_bytes')) {
1112 function return_bytes ($size_str) {
1113     switch (substr ($size_str, -1))
1114     {
1115         case 'M': case 'm': return (int)$size_str * 1048576;
1116         case 'K': case 'k': return (int)$size_str * 1024;
1117         case 'G': case 'g': return (int)$size_str * 1073741824;
1118         default: return $size_str;
1119     }
1120 }}
1121
1122 function generate_user_guid() {
1123         $found = true;
1124         do {
1125                 $guid = random_string(16);
1126                 $x = q("SELECT `uid` FROM `user` WHERE `guid` = '%s' LIMIT 1",
1127                         dbesc($guid)
1128                 );
1129                 if(! count($x))
1130                         $found = false;
1131         } while ($found == true );
1132         return $guid;
1133 }
1134
1135
1136
1137 function base64url_encode($s, $strip_padding = false) {
1138
1139         $s = strtr(base64_encode($s),'+/','-_');
1140
1141         if($strip_padding)
1142                 $s = str_replace('=','',$s);
1143
1144         return $s;
1145 }
1146
1147 function base64url_decode($s) {
1148
1149         if(is_array($s)) {
1150                 logger('base64url_decode: illegal input: ' . print_r(debug_backtrace(), true));
1151                 return $s;
1152         }
1153
1154 /*
1155  *  // Placeholder for new rev of salmon which strips base64 padding.
1156  *  // PHP base64_decode handles the un-padded input without requiring this step
1157  *  // Uncomment if you find you need it.
1158  *
1159  *      $l = strlen($s);
1160  *      if(! strpos($s,'=')) {
1161  *              $m = $l % 4;
1162  *              if($m == 2)
1163  *                      $s .= '==';
1164  *              if($m == 3)
1165  *                      $s .= '=';
1166  *      }
1167  *
1168  */
1169
1170         return base64_decode(strtr($s,'-_','+/'));
1171 }
1172
1173
1174 if (!function_exists('str_getcsv')) {
1175     function str_getcsv($input, $delimiter = ',', $enclosure = '"', $escape = '\\', $eol = '\n') {
1176         if (is_string($input) && !empty($input)) {
1177             $output = array();
1178             $tmp    = preg_split("/".$eol."/",$input);
1179             if (is_array($tmp) && !empty($tmp)) {
1180                 while (list($line_num, $line) = each($tmp)) {
1181                     if (preg_match("/".$escape.$enclosure."/",$line)) {
1182                         while ($strlen = strlen($line)) {
1183                             $pos_delimiter       = strpos($line,$delimiter);
1184                             $pos_enclosure_start = strpos($line,$enclosure);
1185                             if (
1186                                 is_int($pos_delimiter) && is_int($pos_enclosure_start)
1187                                 && ($pos_enclosure_start < $pos_delimiter)
1188                                 ) {
1189                                 $enclosed_str = substr($line,1);
1190                                 $pos_enclosure_end = strpos($enclosed_str,$enclosure);
1191                                 $enclosed_str = substr($enclosed_str,0,$pos_enclosure_end);
1192                                 $output[$line_num][] = $enclosed_str;
1193                                 $offset = $pos_enclosure_end+3;
1194                             } else {
1195                                 if (empty($pos_delimiter) && empty($pos_enclosure_start)) {
1196                                     $output[$line_num][] = substr($line,0);
1197                                     $offset = strlen($line);
1198                                 } else {
1199                                     $output[$line_num][] = substr($line,0,$pos_delimiter);
1200                                     $offset = (
1201                                                 !empty($pos_enclosure_start)
1202                                                 && ($pos_enclosure_start < $pos_delimiter)
1203                                                 )
1204                                                 ?$pos_enclosure_start
1205                                                 :$pos_delimiter+1;
1206                                 }
1207                             }
1208                             $line = substr($line,$offset);
1209                         }
1210                     } else {
1211                         $line = preg_split("/".$delimiter."/",$line);
1212    
1213                         /*
1214                          * Validating against pesky extra line breaks creating false rows.
1215                          */
1216                         if (is_array($line) && !empty($line[0])) {
1217                             $output[$line_num] = $line;
1218                         } 
1219                     }
1220                 }
1221                 return $output;
1222             } else {
1223                 return false;
1224             }
1225         } else {
1226             return false;
1227         }
1228     }
1229
1230
1231 function cleardiv() {
1232         return '<div class="clear"></div>';
1233 }
1234
1235
1236 function bb_translate_video($s) {
1237
1238         $matches = null;
1239         $r = preg_match_all("/\[video\](.*?)\[\/video\]/ism",$s,$matches,PREG_SET_ORDER);
1240         if($r) {
1241                 foreach($matches as $mtch) {
1242                         if((stristr($mtch[1],'youtube')) || (stristr($mtch[1],'youtu.be')))
1243                                 $s = str_replace($mtch[0],'[youtube]' . $mtch[1] . '[/youtube]',$s);
1244                         elseif(stristr($mtch[1],'vimeo'))
1245                                 $s = str_replace($mtch[0],'[vimeo]' . $mtch[1] . '[/vimeo]',$s);
1246                 }
1247         }
1248         return $s;      
1249 }
1250
1251 function html2bb_video($s) {
1252
1253         $s = preg_replace('#<object[^>]+>(.*?)https+://www.youtube.com/((?:v|cp)/[A-Za-z0-9\-_=]+)(.*?)</object>#ism',
1254                         '[youtube]$2[/youtube]', $s);
1255
1256         $s = preg_replace('#<iframe[^>](.*?)https+://www.youtube.com/embed/([A-Za-z0-9\-_=]+)(.*?)</iframe>#ism',
1257                         '[youtube]$2[/youtube]', $s);
1258
1259         $s = preg_replace('#<iframe[^>](.*?)https+://player.vimeo.com/video/([0-9]+)(.*?)</iframe>#ism',
1260                         '[vimeo]$2[/vimeo]', $s);
1261
1262         return $s;
1263 }
1264
1265 /**
1266  * apply xmlify() to all values of array $val, recursively
1267  */
1268 function array_xmlify($val){
1269         if (is_bool($val)) return $val?"true":"false";
1270         if (is_array($val)) return array_map('array_xmlify', $val);
1271         return xmlify((string) $val);
1272 }
1273
1274
1275 function reltoabs($text, $base)
1276 {
1277   if (empty($base))
1278     return $text;
1279
1280   $base = rtrim($base,'/');
1281
1282   $base2 = $base . "/";
1283         
1284   // Replace links
1285   $pattern = "/<a([^>]*) href=\"(?!http|https|\/)([^\"]*)\"/";
1286   $replace = "<a\${1} href=\"" . $base2 . "\${2}\"";
1287   $text = preg_replace($pattern, $replace, $text);
1288
1289   $pattern = "/<a([^>]*) href=\"(?!http|https)([^\"]*)\"/";
1290   $replace = "<a\${1} href=\"" . $base . "\${2}\"";
1291   $text = preg_replace($pattern, $replace, $text);
1292
1293   // Replace images
1294   $pattern = "/<img([^>]*) src=\"(?!http|https|\/)([^\"]*)\"/";
1295   $replace = "<img\${1} src=\"" . $base2 . "\${2}\"";
1296   $text = preg_replace($pattern, $replace, $text); 
1297
1298   $pattern = "/<img([^>]*) src=\"(?!http|https)([^\"]*)\"/";
1299   $replace = "<img\${1} src=\"" . $base . "\${2}\"";
1300   $text = preg_replace($pattern, $replace, $text); 
1301
1302
1303   // Done
1304   return $text;
1305 }
1306
1307 function item_post_type($item) {
1308         if(intval($item['event-id']))
1309                 return t('event');
1310         if(strlen($item['resource-id']))
1311                 return t('photo');
1312         if(strlen($item['verb']) && $item['verb'] !== ACTIVITY_POST)
1313                 return t('activity');
1314         if($item['id'] != $item['parent'])
1315                 return t('comment');
1316         return t('post');
1317 }
1318
1319 // post categories and "save to file" use the same item.file table for storage.
1320 // We will differentiate the different uses by wrapping categories in angle brackets
1321 // and save to file categories in square brackets.
1322 // To do this we need to escape these characters if they appear in our tag. 
1323
1324 function file_tag_encode($s) {
1325         return str_replace(array('<','>','[',']'),array('%3c','%3e','%5b','%5d'),$s);
1326 }
1327
1328 function file_tag_decode($s) {
1329         return str_replace(array('%3c','%3e','%5b','%5d'),array('<','>','[',']'),$s);
1330 }
1331
1332 function file_tag_file_query($table,$s,$type = 'file') {
1333
1334         if($type == 'file')
1335                 $str = preg_quote( '[' . str_replace('%','%%',file_tag_encode($s)) . ']' );
1336         else
1337                 $str = preg_quote( '<' . str_replace('%','%%',file_tag_encode($s)) . '>' );
1338         return " AND " . (($table) ? dbesc($table) . '.' : '') . "file regexp '" . dbesc($str) . "' ";
1339 }
1340
1341 // ex. given music,video return <music><video> or [music][video]
1342 function file_tag_list_to_file($list,$type = 'file') {
1343         $tag_list = '';
1344         if(strlen($list)) {
1345                 $list_array = explode(",",$list);
1346                 if($type == 'file') {
1347                         $lbracket = '[';
1348                         $rbracket = ']';
1349                 }
1350                 else {
1351                         $lbracket = '<';
1352                         $rbracket = '>';
1353                 }
1354
1355                 foreach($list_array as $item) {
1356                   if(strlen($item)) {
1357                                 $tag_list .= $lbracket . file_tag_encode(trim($item))  . $rbracket;
1358                         }
1359                 }
1360         }
1361         return $tag_list;
1362 }
1363
1364 // ex. given <music><video>[friends], return music,video or friends
1365 function file_tag_file_to_list($file,$type = 'file') {
1366         $matches = false;
1367         $list = '';
1368         if($type == 'file') {
1369                 $cnt = preg_match_all('/\[(.*?)\]/',$file,$matches,PREG_SET_ORDER);
1370         }
1371         else {
1372                 $cnt = preg_match_all('/<(.*?)>/',$file,$matches,PREG_SET_ORDER);
1373         }
1374         if($cnt) {
1375                 foreach($matches as $mtch) {
1376                         if(strlen($list))
1377                                 $list .= ',';
1378                         $list .= file_tag_decode($mtch[1]);
1379                 }
1380         }
1381
1382         return $list;
1383 }
1384
1385 function file_tag_update_pconfig($uid,$file_old,$file_new,$type = 'file') {
1386         // $file_old - categories previously associated with an item
1387         // $file_new - new list of categories for an item
1388
1389         if(! intval($uid))
1390                 return false;
1391
1392         if($file_old == $file_new)
1393                 return true;
1394
1395         $saved = get_pconfig($uid,'system','filetags');
1396         if(strlen($saved)) {
1397                 if($type == 'file') {
1398                         $lbracket = '[';
1399                         $rbracket = ']';
1400                 }
1401                 else {
1402                         $lbracket = '<';
1403                         $rbracket = '>';
1404                 }
1405
1406                 $filetags_updated = $saved;
1407
1408                 // check for new tags to be added as filetags in pconfig
1409                 $new_tags = array();
1410                 $check_new_tags = explode(",",file_tag_file_to_list($file_new,$type));
1411
1412                 foreach($check_new_tags as $tag) {
1413                         if(! stristr($saved,$lbracket . file_tag_encode($tag) . $rbracket))
1414                                 $new_tags[] = $tag;
1415                 }
1416
1417                 $filetags_updated .= file_tag_list_to_file(implode(",",$new_tags),$type);
1418
1419                 // check for deleted tags to be removed from filetags in pconfig
1420                 $deleted_tags = array();
1421                 $check_deleted_tags = explode(",",file_tag_file_to_list($file_old,$type));
1422
1423                 foreach($check_deleted_tags as $tag) {
1424                         if(! stristr($file_new,$lbracket . file_tag_encode($tag) . $rbracket))
1425                                 $deleted_tags[] = $tag;
1426                 }
1427
1428                 foreach($deleted_tags as $key => $tag) {
1429                         $r = q("select file from item where uid = %d " . file_tag_file_query('item',$tag,$type),
1430                                 intval($uid)
1431                         );
1432
1433                         if(count($r)) {
1434                                 unset($deleted_tags[$key]);
1435                         }
1436                         else {
1437                                 $filetags_updated = str_replace($lbracket . file_tag_encode($tag) . $rbracket,'',$filetags_updated);
1438                         }
1439                 }
1440
1441                 if($saved != $filetags_updated) {
1442                         set_pconfig($uid,'system','filetags', $filetags_updated);
1443                 }
1444                 return true;
1445         }
1446         else
1447                 if(strlen($file_new)) {
1448                         set_pconfig($uid,'system','filetags', $file_new);
1449                 }
1450                 return true;
1451 }
1452
1453 function file_tag_save_file($uid,$item,$file) {
1454         $result = false;
1455         if(! intval($uid))
1456                 return false;
1457         $r = q("select file from item where id = %d and uid = %d limit 1",
1458                 intval($item),
1459                 intval($uid)
1460         );
1461         if(count($r)) {
1462                 if(! stristr($r[0]['file'],'[' . file_tag_encode($file) . ']'))
1463                         q("update item set file = '%s' where id = %d and uid = %d limit 1",
1464                                 dbesc($r[0]['file'] . '[' . file_tag_encode($file) . ']'),
1465                                 intval($item),
1466                                 intval($uid)
1467                         );
1468                 $saved = get_pconfig($uid,'system','filetags');
1469                 if((! strlen($saved)) || (! stristr($saved,'[' . file_tag_encode($file) . ']')))
1470                         set_pconfig($uid,'system','filetags',$saved . '[' . file_tag_encode($file) . ']');
1471                 info( t('Item filed') );
1472         }
1473         return true;
1474 }
1475
1476 function file_tag_unsave_file($uid,$item,$file,$cat = false) {
1477         $result = false;
1478         if(! intval($uid))
1479                 return false;
1480
1481         if($cat == true)
1482                 $pattern = '<' . file_tag_encode($file) . '>' ;
1483         else
1484                 $pattern = '[' . file_tag_encode($file) . ']' ;
1485
1486
1487         $r = q("select file from item where id = %d and uid = %d limit 1",
1488                 intval($item),
1489                 intval($uid)
1490         );
1491         if(! count($r))
1492                 return false;
1493
1494         q("update item set file = '%s' where id = %d and uid = %d limit 1",
1495                 dbesc(str_replace($pattern,'',$r[0]['file'])),
1496                 intval($item),
1497                 intval($uid)
1498         );
1499
1500         $r = q("select file from item where uid = %d and deleted = 0 " . file_tag_file_query('item',$file,(($cat) ? 'category' : 'file')),
1501                 intval($uid)
1502         );
1503
1504         if(! count($r)) {
1505                 $saved = get_pconfig($uid,'system','filetags');
1506                 set_pconfig($uid,'system','filetags',str_replace($pattern,'',$saved));
1507
1508         }
1509         return true;
1510 }
1511
1512 function normalise_openid($s) {
1513         return trim(str_replace(array('http://','https://'),array('',''),$s),'/');
1514 }
1515
1516
1517 function undo_post_tagging($s) {
1518         $matches = null;
1519         $cnt = preg_match_all('/([@#])\[url=(.*?)\](.*?)\[\/url\]/ism',$s,$matches,PREG_SET_ORDER);
1520         if($cnt) {
1521                 foreach($matches as $mtch) {
1522                         $s = str_replace($mtch[0], $mtch[1] . $mtch[3],$s);
1523                 }
1524         }
1525         return $s;
1526 }
1527
1528 function fix_mce_lf($s) {
1529         $s = str_replace("\r\n","\n",$s);
1530         $s = str_replace("\n\n","\n",$s);
1531         return $s;
1532 }
1533
1534
1535 function protect_sprintf($s) {
1536         return(str_replace('%','%%',$s));
1537 }
1538