]> git.mxchange.org Git - friendica.git/blob - include/text.php
29c781030dd8142d065b5736c6b32e0987c6ae86
[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)
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",
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 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" 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('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"\[\/attach\]|',$r,$matches);
905                         if($cnt) {
906                                 $icontype = strtolower(substr($matches[3],0,strpos($matches[3],'/')));
907                                 switch($icontype) {
908                                         case 'video':
909                                         case 'audio':
910                                         case 'image':
911                                         case 'text':
912                                                 $icon = '<div class="attachtype icon s22 type-' . $icontype . '"></div>';
913                                                 break;
914                                         default:
915                                                 $icon = '<div class="attachtype icon s22 type-unkn"></div>';
916                                                 break;
917                                 }
918                                 $title = ((strlen(trim($matches[4]))) ? escape_tags(trim($matches[4])) : escape_tags($matches[1]));
919                                 $title .= ' ' . $matches[2] . ' ' . t('bytes');
920
921                                 $s .= '<a href="' . strip_tags($matches[1]) . '" title="' . $title . '" class="attachlink" target="external-link" >' . $icon . '</a>';
922                         }
923                 }
924                 $s .= '<div class="clear"></div></div>';
925         }
926         $matches = false;
927         $cnt = preg_match_all('/<(.*?)>/',$item['file'],$matches,PREG_SET_ORDER);
928         if($cnt) {
929 //              logger('prepare_text: categories: ' . print_r($matches,true), LOGGER_DEBUG);
930                 foreach($matches as $mtch) {
931                         if(strlen($x))
932                                 $x .= ',';
933                         $x .= xmlify(file_tag_decode($mtch[1]));
934                 }
935                 if(strlen($x))
936                         $s .= '<div class="categorytags"><span>' . t('Categories:') . ' </span>' . $x . '</div>'; 
937
938
939         }
940         $matches = false;
941         $x = '';
942         $cnt = preg_match_all('/\[(.*?)\]/',$item['file'],$matches,PREG_SET_ORDER);
943         if($cnt) {
944 //              logger('prepare_text: filed_under: ' . print_r($matches,true), LOGGER_DEBUG);
945                 foreach($matches as $mtch) {
946                         if(strlen($x))
947                                 $x .= '&nbsp;&nbsp;&nbsp;';
948                         $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>';
949                 }
950                 if(strlen($x) && (local_user() == $item['uid']))
951                         $s .= '<div class="filesavetags"><span>' . t('Filed under:') . ' </span>' . $x . '</div>'; 
952         }
953
954         // Look for spoiler
955         $spoilersearch = '<blockquote class="spoiler">';
956
957         // Remove line breaks before the spoiler
958         while ((strpos($s, "\n".$spoilersearch) !== false))
959                 $s = str_replace("\n".$spoilersearch, $spoilersearch, $s);
960         while ((strpos($s, "<br />".$spoilersearch) !== false))
961                 $s = str_replace("<br />".$spoilersearch, $spoilersearch, $s);
962
963         while ((strpos($s, $spoilersearch) !== false)) {
964
965                 $pos = strpos($s, $spoilersearch);
966                 $rnd = random_string(8);
967                 $spoilerreplace = '<br /> <span id="spoiler-wrap-'.$rnd.'" style="white-space:nowrap;" class="fakelink" onclick="openClose(\'spoiler-'.$rnd.'\');">'.sprintf(t('Click to open/close')).'</span>'.
968                                         '<blockquote class="spoiler" id="spoiler-'.$rnd.'" style="display: none;">';
969                 $s = substr($s, 0, $pos).$spoilerreplace.substr($s, $pos+strlen($spoilersearch));
970         }
971
972         // Look for quote with author
973         $authorsearch = '<blockquote class="author">';
974
975         while ((strpos($s, $authorsearch) !== false)) {
976
977                 $pos = strpos($s, $authorsearch);
978                 $rnd = random_string(8);
979                 $authorreplace = '<br /> <span id="author-wrap-'.$rnd.'" style="white-space:nowrap;" class="fakelink" onclick="openClose(\'author-'.$rnd.'\');">'.sprintf(t('Click to open/close')).'</span>'.
980                                         '<blockquote class="author" id="author-'.$rnd.'" style="display: block;">';
981                 $s = substr($s, 0, $pos).$authorreplace.substr($s, $pos+strlen($authorsearch));
982         }
983
984         $prep_arr = array('item' => $item, 'html' => $s);
985         call_hooks('prepare_body_final', $prep_arr);
986
987         return $prep_arr['html'];
988 }}
989
990
991 // Given a text string, convert from bbcode to html and add smilie icons.
992
993 if(! function_exists('prepare_text')) {
994 function prepare_text($text) {
995
996         require_once('include/bbcode.php');
997
998         if(stristr($text,'[nosmile]'))
999                 $s = bbcode($text);
1000         else
1001                 $s = smilies(bbcode($text));
1002
1003         return $s;
1004 }}
1005
1006
1007 /**
1008  * return atom link elements for all of our hubs
1009  */
1010
1011 if(! function_exists('feed_hublinks')) {
1012 function feed_hublinks() {
1013
1014         $hub = get_config('system','huburl');
1015
1016         $hubxml = '';
1017         if(strlen($hub)) {
1018                 $hubs = explode(',', $hub);
1019                 if(count($hubs)) {
1020                         foreach($hubs as $h) {
1021                                 $h = trim($h);
1022                                 if(! strlen($h))
1023                                         continue;
1024                                 $hubxml .= '<link rel="hub" href="' . xmlify($h) . '" />' . "\n" ;
1025                         }
1026                 }
1027         }
1028         return $hubxml;
1029 }}
1030
1031 /* return atom link elements for salmon endpoints */
1032
1033 if(! function_exists('feed_salmonlinks')) {
1034 function feed_salmonlinks($nick) {
1035
1036         $a = get_app();
1037
1038         $salmon  = '<link rel="salmon" href="' . xmlify($a->get_baseurl() . '/salmon/' . $nick) . '" />' . "\n" ;
1039
1040         // old style links that status.net still needed as of 12/2010 
1041
1042         $salmon .= '  <link rel="http://salmon-protocol.org/ns/salmon-replies" href="' . xmlify($a->get_baseurl() . '/salmon/' . $nick) . '" />' . "\n" ; 
1043         $salmon .= '  <link rel="http://salmon-protocol.org/ns/salmon-mention" href="' . xmlify($a->get_baseurl() . '/salmon/' . $nick) . '" />' . "\n" ; 
1044         return $salmon;
1045 }}
1046
1047 if(! function_exists('get_plink')) {
1048 function get_plink($item) {
1049         $a = get_app(); 
1050         if (x($item,'plink') && (! $item['private'])){
1051                 return array(
1052                         'href' => $item['plink'],
1053                         'title' => t('link to source'),
1054                 );
1055         } else {
1056                 return false;
1057         }
1058 }}
1059
1060 if(! function_exists('unamp')) {
1061 function unamp($s) {
1062         return str_replace('&amp;', '&', $s);
1063 }}
1064
1065
1066
1067
1068 if(! function_exists('lang_selector')) {
1069 function lang_selector() {
1070         global $lang;
1071         $o = '<div id="lang-select-icon" class="icon language" title="' . t('Select an alternate language') . '" onclick="openClose(\'language-selector\');" ></div>';
1072         $o .= '<div id="language-selector" style="display: none;" >';
1073         $o .= '<form action="#" method="post" ><select name="system_language" onchange="this.form.submit();" >';
1074         $langs = glob('view/*/strings.php');
1075         if(is_array($langs) && count($langs)) {
1076                 $langs[] = '';
1077                 if(! in_array('view/en/strings.php',$langs))
1078                         $langs[] = 'view/en/';
1079                 asort($langs);
1080                 foreach($langs as $l) {
1081                         if($l == '') {
1082                                 $default_selected = ((! x($_SESSION,'language')) ? ' selected="selected" ' : '');
1083                                 $o .= '<option value="" ' . $default_selected . '>' . t('default') . '</option>';
1084                                 continue;
1085                         }
1086                         $ll = substr($l,5);
1087                         $ll = substr($ll,0,strrpos($ll,'/'));
1088                         $selected = (($ll === $lang && (x($_SESSION, 'language'))) ? ' selected="selected" ' : '');
1089                         $o .= '<option value="' . $ll . '"' . $selected . '>' . $ll . '</option>';
1090                 }
1091         }
1092         $o .= '</select></form></div>';
1093         return $o;
1094 }}
1095
1096
1097 if(! function_exists('return_bytes')) {
1098 function return_bytes ($size_str) {
1099     switch (substr ($size_str, -1))
1100     {
1101         case 'M': case 'm': return (int)$size_str * 1048576;
1102         case 'K': case 'k': return (int)$size_str * 1024;
1103         case 'G': case 'g': return (int)$size_str * 1073741824;
1104         default: return $size_str;
1105     }
1106 }}
1107
1108 function generate_user_guid() {
1109         $found = true;
1110         do {
1111                 $guid = random_string(16);
1112                 $x = q("SELECT `uid` FROM `user` WHERE `guid` = '%s' LIMIT 1",
1113                         dbesc($guid)
1114                 );
1115                 if(! count($x))
1116                         $found = false;
1117         } while ($found == true );
1118         return $guid;
1119 }
1120
1121
1122
1123 function base64url_encode($s, $strip_padding = false) {
1124
1125         $s = strtr(base64_encode($s),'+/','-_');
1126
1127         if($strip_padding)
1128                 $s = str_replace('=','',$s);
1129
1130         return $s;
1131 }
1132
1133 function base64url_decode($s) {
1134
1135         if(is_array($s)) {
1136                 logger('base64url_decode: illegal input: ' . print_r(debug_backtrace(), true));
1137                 return $s;
1138         }
1139
1140 /*
1141  *  // Placeholder for new rev of salmon which strips base64 padding.
1142  *  // PHP base64_decode handles the un-padded input without requiring this step
1143  *  // Uncomment if you find you need it.
1144  *
1145  *      $l = strlen($s);
1146  *      if(! strpos($s,'=')) {
1147  *              $m = $l % 4;
1148  *              if($m == 2)
1149  *                      $s .= '==';
1150  *              if($m == 3)
1151  *                      $s .= '=';
1152  *      }
1153  *
1154  */
1155
1156         return base64_decode(strtr($s,'-_','+/'));
1157 }
1158
1159
1160 if (!function_exists('str_getcsv')) {
1161     function str_getcsv($input, $delimiter = ',', $enclosure = '"', $escape = '\\', $eol = '\n') {
1162         if (is_string($input) && !empty($input)) {
1163             $output = array();
1164             $tmp    = preg_split("/".$eol."/",$input);
1165             if (is_array($tmp) && !empty($tmp)) {
1166                 while (list($line_num, $line) = each($tmp)) {
1167                     if (preg_match("/".$escape.$enclosure."/",$line)) {
1168                         while ($strlen = strlen($line)) {
1169                             $pos_delimiter       = strpos($line,$delimiter);
1170                             $pos_enclosure_start = strpos($line,$enclosure);
1171                             if (
1172                                 is_int($pos_delimiter) && is_int($pos_enclosure_start)
1173                                 && ($pos_enclosure_start < $pos_delimiter)
1174                                 ) {
1175                                 $enclosed_str = substr($line,1);
1176                                 $pos_enclosure_end = strpos($enclosed_str,$enclosure);
1177                                 $enclosed_str = substr($enclosed_str,0,$pos_enclosure_end);
1178                                 $output[$line_num][] = $enclosed_str;
1179                                 $offset = $pos_enclosure_end+3;
1180                             } else {
1181                                 if (empty($pos_delimiter) && empty($pos_enclosure_start)) {
1182                                     $output[$line_num][] = substr($line,0);
1183                                     $offset = strlen($line);
1184                                 } else {
1185                                     $output[$line_num][] = substr($line,0,$pos_delimiter);
1186                                     $offset = (
1187                                                 !empty($pos_enclosure_start)
1188                                                 && ($pos_enclosure_start < $pos_delimiter)
1189                                                 )
1190                                                 ?$pos_enclosure_start
1191                                                 :$pos_delimiter+1;
1192                                 }
1193                             }
1194                             $line = substr($line,$offset);
1195                         }
1196                     } else {
1197                         $line = preg_split("/".$delimiter."/",$line);
1198    
1199                         /*
1200                          * Validating against pesky extra line breaks creating false rows.
1201                          */
1202                         if (is_array($line) && !empty($line[0])) {
1203                             $output[$line_num] = $line;
1204                         } 
1205                     }
1206                 }
1207                 return $output;
1208             } else {
1209                 return false;
1210             }
1211         } else {
1212             return false;
1213         }
1214     }
1215
1216
1217 function cleardiv() {
1218         return '<div class="clear"></div>';
1219 }
1220
1221
1222 function bb_translate_video($s) {
1223
1224         $matches = null;
1225         $r = preg_match_all("/\[video\](.*?)\[\/video\]/ism",$s,$matches,PREG_SET_ORDER);
1226         if($r) {
1227                 foreach($matches as $mtch) {
1228                         if((stristr($mtch[1],'youtube')) || (stristr($mtch[1],'youtu.be')))
1229                                 $s = str_replace($mtch[0],'[youtube]' . $mtch[1] . '[/youtube]',$s);
1230                         elseif(stristr($mtch[1],'vimeo'))
1231                                 $s = str_replace($mtch[0],'[vimeo]' . $mtch[1] . '[/vimeo]',$s);
1232                 }
1233         }
1234         return $s;      
1235 }
1236
1237 function html2bb_video($s) {
1238
1239         $s = preg_replace('#<object[^>]+>(.*?)https+://www.youtube.com/((?:v|cp)/[A-Za-z0-9\-_=]+)(.*?)</object>#ism',
1240                         '[youtube]$2[/youtube]', $s);
1241
1242         $s = preg_replace('#<iframe[^>](.*?)https+://www.youtube.com/embed/([A-Za-z0-9\-_=]+)(.*?)</iframe>#ism',
1243                         '[youtube]$2[/youtube]', $s);
1244
1245         $s = preg_replace('#<iframe[^>](.*?)https+://player.vimeo.com/video/([0-9]+)(.*?)</iframe>#ism',
1246                         '[vimeo]$2[/vimeo]', $s);
1247
1248         return $s;
1249 }
1250
1251 /**
1252  * apply xmlify() to all values of array $val, recursively
1253  */
1254 function array_xmlify($val){
1255         if (is_bool($val)) return $val?"true":"false";
1256         if (is_array($val)) return array_map('array_xmlify', $val);
1257         return xmlify((string) $val);
1258 }
1259
1260
1261 function reltoabs($text, $base)
1262 {
1263   if (empty($base))
1264     return $text;
1265
1266   $base = rtrim($base,'/');
1267
1268   $base2 = $base . "/";
1269         
1270   // Replace links
1271   $pattern = "/<a([^>]*) href=\"(?!http|https|\/)([^\"]*)\"/";
1272   $replace = "<a\${1} href=\"" . $base2 . "\${2}\"";
1273   $text = preg_replace($pattern, $replace, $text);
1274
1275   $pattern = "/<a([^>]*) href=\"(?!http|https)([^\"]*)\"/";
1276   $replace = "<a\${1} href=\"" . $base . "\${2}\"";
1277   $text = preg_replace($pattern, $replace, $text);
1278
1279   // Replace images
1280   $pattern = "/<img([^>]*) src=\"(?!http|https|\/)([^\"]*)\"/";
1281   $replace = "<img\${1} src=\"" . $base2 . "\${2}\"";
1282   $text = preg_replace($pattern, $replace, $text); 
1283
1284   $pattern = "/<img([^>]*) src=\"(?!http|https)([^\"]*)\"/";
1285   $replace = "<img\${1} src=\"" . $base . "\${2}\"";
1286   $text = preg_replace($pattern, $replace, $text); 
1287
1288
1289   // Done
1290   return $text;
1291 }
1292
1293 function item_post_type($item) {
1294         if(intval($item['event-id']))
1295                 return t('event');
1296         if(strlen($item['resource-id']))
1297                 return t('photo');
1298         if(strlen($item['verb']) && $item['verb'] !== ACTIVITY_POST)
1299                 return t('activity');
1300         if($item['id'] != $item['parent'])
1301                 return t('comment');
1302         return t('post');
1303 }
1304
1305 // post categories and "save to file" use the same item.file table for storage.
1306 // We will differentiate the different uses by wrapping categories in angle brackets
1307 // and save to file categories in square brackets.
1308 // To do this we need to escape these characters if they appear in our tag. 
1309
1310 function file_tag_encode($s) {
1311         return str_replace(array('<','>','[',']'),array('%3c','%3e','%5b','%5d'),$s);
1312 }
1313
1314 function file_tag_decode($s) {
1315         return str_replace(array('%3c','%3e','%5b','%5d'),array('<','>','[',']'),$s);
1316 }
1317
1318 function file_tag_file_query($table,$s,$type = 'file') {
1319
1320         if($type == 'file')
1321                 $str = preg_quote( '[' . str_replace('%','%%',file_tag_encode($s)) . ']' );
1322         else
1323                 $str = preg_quote( '<' . str_replace('%','%%',file_tag_encode($s)) . '>' );
1324         return " AND " . (($table) ? dbesc($table) . '.' : '') . "file regexp '" . dbesc($str) . "' ";
1325 }
1326
1327 // ex. given music,video return <music><video> or [music][video]
1328 function file_tag_list_to_file($list,$type = 'file') {
1329         $tag_list = '';
1330         if(strlen($list)) {
1331                 $list_array = explode(",",$list);
1332                 if($type == 'file') {
1333                         $lbracket = '[';
1334                         $rbracket = ']';
1335                 }
1336                 else {
1337                         $lbracket = '<';
1338                         $rbracket = '>';
1339                 }
1340
1341                 foreach($list_array as $item) {
1342                   if(strlen($item)) {
1343                                 $tag_list .= $lbracket . file_tag_encode(trim($item))  . $rbracket;
1344                         }
1345                 }
1346         }
1347         return $tag_list;
1348 }
1349
1350 // ex. given <music><video>[friends], return music,video or friends
1351 function file_tag_file_to_list($file,$type = 'file') {
1352         $matches = false;
1353         $list = '';
1354         if($type == 'file') {
1355                 $cnt = preg_match_all('/\[(.*?)\]/',$file,$matches,PREG_SET_ORDER);
1356         }
1357         else {
1358                 $cnt = preg_match_all('/<(.*?)>/',$file,$matches,PREG_SET_ORDER);
1359         }
1360         if($cnt) {
1361                 foreach($matches as $mtch) {
1362                         if(strlen($list))
1363                                 $list .= ',';
1364                         $list .= file_tag_decode($mtch[1]);
1365                 }
1366         }
1367
1368         return $list;
1369 }
1370
1371 function file_tag_update_pconfig($uid,$file_old,$file_new,$type = 'file') {
1372         // $file_old - categories previously associated with an item
1373         // $file_new - new list of categories for an item
1374
1375         if(! intval($uid))
1376                 return false;
1377
1378         if($file_old == $file_new)
1379                 return true;
1380
1381         $saved = get_pconfig($uid,'system','filetags');
1382         if(strlen($saved)) {
1383                 if($type == 'file') {
1384                         $lbracket = '[';
1385                         $rbracket = ']';
1386                 }
1387                 else {
1388                         $lbracket = '<';
1389                         $rbracket = '>';
1390                 }
1391
1392                 $filetags_updated = $saved;
1393
1394                 // check for new tags to be added as filetags in pconfig
1395                 $new_tags = array();
1396                 $check_new_tags = explode(",",file_tag_file_to_list($file_new,$type));
1397
1398                 foreach($check_new_tags as $tag) {
1399                         if(! stristr($saved,$lbracket . file_tag_encode($tag) . $rbracket))
1400                                 $new_tags[] = $tag;
1401                 }
1402
1403                 $filetags_updated .= file_tag_list_to_file(implode(",",$new_tags),$type);
1404
1405                 // check for deleted tags to be removed from filetags in pconfig
1406                 $deleted_tags = array();
1407                 $check_deleted_tags = explode(",",file_tag_file_to_list($file_old,$type));
1408
1409                 foreach($check_deleted_tags as $tag) {
1410                         if(! stristr($file_new,$lbracket . file_tag_encode($tag) . $rbracket))
1411                                 $deleted_tags[] = $tag;
1412                 }
1413
1414                 foreach($deleted_tags as $key => $tag) {
1415                         $r = q("select file from item where uid = %d " . file_tag_file_query('item',$tag,$type),
1416                                 intval($uid)
1417                         );
1418
1419                         if(count($r)) {
1420                                 unset($deleted_tags[$key]);
1421                         }
1422                         else {
1423                                 $filetags_updated = str_replace($lbracket . file_tag_encode($tag) . $rbracket,'',$filetags_updated);
1424                         }
1425                 }
1426
1427                 if($saved != $filetags_updated) {
1428                         set_pconfig($uid,'system','filetags', $filetags_updated);
1429                 }
1430                 return true;
1431         }
1432         else
1433                 if(strlen($file_new)) {
1434                         set_pconfig($uid,'system','filetags', $file_new);
1435                 }
1436                 return true;
1437 }
1438
1439 function file_tag_save_file($uid,$item,$file) {
1440         $result = false;
1441         if(! intval($uid))
1442                 return false;
1443         $r = q("select file from item where id = %d and uid = %d limit 1",
1444                 intval($item),
1445                 intval($uid)
1446         );
1447         if(count($r)) {
1448                 if(! stristr($r[0]['file'],'[' . file_tag_encode($file) . ']'))
1449                         q("update item set file = '%s' where id = %d and uid = %d limit 1",
1450                                 dbesc($r[0]['file'] . '[' . file_tag_encode($file) . ']'),
1451                                 intval($item),
1452                                 intval($uid)
1453                         );
1454                 $saved = get_pconfig($uid,'system','filetags');
1455                 if((! strlen($saved)) || (! stristr($saved,'[' . file_tag_encode($file) . ']')))
1456                         set_pconfig($uid,'system','filetags',$saved . '[' . file_tag_encode($file) . ']');
1457                 info( t('Item filed') );
1458         }
1459         return true;
1460 }
1461
1462 function file_tag_unsave_file($uid,$item,$file) {
1463         $result = false;
1464         if(! intval($uid))
1465                 return false;
1466
1467         $pattern = '[' . file_tag_encode($file) . ']' ;
1468
1469         $r = q("select file from item where id = %d and uid = %d limit 1",
1470                 intval($item),
1471                 intval($uid)
1472         );
1473         if(! count($r))
1474                 return false;
1475
1476         q("update item set file = '%s' where id = %d and uid = %d limit 1",
1477                 dbesc(str_replace($pattern,'',$r[0]['file'])),
1478                 intval($item),
1479                 intval($uid)
1480         );
1481
1482         $r = q("select file from item where uid = %d " . file_tag_file_query('item',$file),
1483                 intval($uid)
1484         );
1485
1486         if(! count($r)) {
1487                 $saved = get_pconfig($uid,'system','filetags');
1488                 set_pconfig($uid,'system','filetags',str_replace($pattern,'',$saved));
1489         }
1490         return true;
1491 }
1492
1493 function normalise_openid($s) {
1494         return trim(str_replace(array('http://','https://'),array('',''),$s),'/');
1495 }
1496
1497
1498 function undo_post_tagging($s) {
1499         $matches = null;
1500         $cnt = preg_match_all('/([@#])\[url=(.*?)\](.*?)\[\/url\]/ism',$s,$matches,PREG_SET_ORDER);
1501         if($cnt) {
1502                 foreach($matches as $mtch) {
1503                         $s = str_replace($mtch[0], $mtch[1] . $mtch[3],$s);
1504                 }
1505         }
1506         return $s;
1507 }
1508