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