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