]> git.mxchange.org Git - friendica.git/blob - include/text.php
fix !@#$ tinymce linebreaks for the thousandth time
[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
660         if(get_config('system','disable_email_validation'))
661                 return true;
662
663         if(preg_match('/^[_a-zA-Z0-9\-\+]+(\.[_a-zA-Z0-9\-\+]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)+$/',$x))
664                 return true;
665         return false;
666 }}
667
668
669 /**
670  *
671  * Function: linkify
672  *
673  * Replace naked text hyperlink with HTML formatted hyperlink
674  *
675  */
676
677 if(! function_exists('linkify')) {
678 function linkify($s) {
679         $s = preg_replace("/(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\'\%\$\!\+]*)/", ' <a href="$1" target="external-link">$1</a>', $s);
680         $s = preg_replace("/\<(.*?)(src|href)=(.*?)\&amp\;(.*?)\>/ism",'<$1$2=$3&$4>',$s);
681         return($s);
682 }}
683
684
685 /**
686  * 
687  * Function: smilies
688  *
689  * Description:
690  * Replaces text emoticons with graphical images
691  *
692  * @Parameter: string $s
693  *
694  * Returns string
695  *
696  * It is expected that this function will be called using HTML text.
697  * We will escape text between HTML pre and code blocks from being 
698  * processed. 
699  * 
700  * At a higher level, the bbcode [nosmile] tag can be used to prevent this 
701  * function from being executed by the prepare_text() routine when preparing
702  * bbcode source for HTML display
703  *
704  */
705
706 if(! function_exists('smilies')) {
707 function smilies($s, $sample = false) {
708
709         $a = get_app();
710
711         if(intval(get_config('system','no_smilies')) 
712                 || (local_user() && intval(get_pconfig(local_user(),'system','no_smilies'))))
713                 return $s;
714
715         $s = preg_replace_callback('/<pre>(.*?)<\/pre>/ism','smile_encode',$s);
716         $s = preg_replace_callback('/<code>(.*?)<\/code>/ism','smile_encode',$s);
717
718         $texts =  array( 
719                 '&lt;3', 
720                 '&lt;/3', 
721                 '&lt;\\3', 
722                 ':-)', 
723                 ';-)', 
724                 ':-(', 
725                 ':-P', 
726                 ':-p', 
727                 ':-"', 
728                 ':-&quot;', 
729                 ':-x', 
730                 ':-X', 
731                 ':-D', 
732                 '8-|', 
733                 '8-O', 
734                 ':-O', 
735                 '\\o/', 
736                 'o.O', 
737                 'O.o', 
738                 'o_O', 
739                 'O_o', 
740                 ":'(", 
741                 ":-!", 
742                 ":-/", 
743                 ":-[", 
744                 "8-)",
745                 ':beer', 
746                 ':homebrew', 
747                 ':coffee', 
748                 ':facepalm',
749                 ':like',
750                 ':dislike',
751                 '~friendika', 
752                 '~friendica'
753
754         );
755
756         $icons = array(
757                 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-heart.gif" alt="<3" />',
758                 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-brokenheart.gif" alt="</3" />',
759                 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-brokenheart.gif" alt="<\\3" />',
760                 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-smile.gif" alt=":-)" />',
761                 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-wink.gif" alt=";-)" />',
762                 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-frown.gif" alt=":-(" />',
763                 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-tongue-out.gif" alt=":-P" />',
764                 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-tongue-out.gif" alt=":-p" />',
765                 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-kiss.gif" alt=":-\"" />',
766                 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-kiss.gif" alt=":-\"" />',
767                 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-kiss.gif" alt=":-x" />',
768                 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-kiss.gif" alt=":-X" />',
769                 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-laughing.gif" alt=":-D" />',
770                 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-surprised.gif" alt="8-|" />',
771                 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-surprised.gif" alt="8-O" />',
772                 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-surprised.gif" alt=":-O" />',                
773                 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-thumbsup.gif" alt="\\o/" />',
774                 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-Oo.gif" alt="o.O" />',
775                 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-Oo.gif" alt="O.o" />',
776                 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-Oo.gif" alt="o_O" />',
777                 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-Oo.gif" alt="O_o" />',
778                 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-cry.gif" alt=":\'(" />',
779                 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-foot-in-mouth.gif" alt=":-!" />',
780                 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-undecided.gif" alt=":-/" />',
781                 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-embarassed.gif" alt=":-[" />',
782                 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-cool.gif" alt="8-)" />',
783                 '<img class="smiley" src="' . $a->get_baseurl() . '/images/beer_mug.gif" alt=":beer" />',
784                 '<img class="smiley" src="' . $a->get_baseurl() . '/images/beer_mug.gif" alt=":homebrew" />',
785                 '<img class="smiley" src="' . $a->get_baseurl() . '/images/coffee.gif" alt=":coffee" />',
786                 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-facepalm.gif" alt=":facepalm" />',
787                 '<img class="smiley" src="' . $a->get_baseurl() . '/images/like.gif" alt=":like" />',
788                 '<img class="smiley" src="' . $a->get_baseurl() . '/images/dislike.gif" alt=":dislike" />',
789                 '<a href="http://project.friendika.com">~friendika <img class="smiley" src="' . $a->get_baseurl() . '/images/friendika-16.png" alt="~friendika" /></a>',
790                 '<a href="http://friendica.com">~friendica <img class="smiley" src="' . $a->get_baseurl() . '/images/friendica-16.png" alt="~friendica" /></a>'
791         );
792
793         $params = array('texts' => $texts, 'icons' => $icons, 'string' => $s);
794         call_hooks('smilie', $params);
795
796         if($sample) {
797                 $s = '<div class="smiley-sample">';
798                 for($x = 0; $x < count($params['texts']); $x ++) {
799                         $s .= '<dl><dt>' . $params['texts'][$x] . '</dt><dd>' . $params['icons'][$x] . '</dd></dl>';
800                 }
801         }
802         else {
803                 $params['string'] = preg_replace_callback('/&lt;(3+)/','preg_heart',$params['string']);
804                 $s = str_replace($params['texts'],$params['icons'],$params['string']);
805         }
806
807         $s = preg_replace_callback('/<pre>(.*?)<\/pre>/ism','smile_decode',$s);
808         $s = preg_replace_callback('/<code>(.*?)<\/code>/ism','smile_decode',$s);
809
810         return $s;
811
812 }}
813
814 function smile_encode($m) {
815         return(str_replace($m[1],base64url_encode($m[1]),$m[0]));
816 }
817
818 function smile_decode($m) {
819         return(str_replace($m[1],base64url_decode($m[1]),$m[0]));
820 }
821
822 // expand <3333 to the correct number of hearts
823
824 function preg_heart($x) {
825         $a = get_app();
826         if(strlen($x[1]) == 1)
827                 return $x[0];
828         $t = '';
829         for($cnt = 0; $cnt < strlen($x[1]); $cnt ++)
830                 $t .= '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-heart.gif" alt="<3" />';
831         $r =  str_replace($x[0],$t,$x[0]);
832         return $r;
833 }
834
835
836 if(! function_exists('day_translate')) {
837 function day_translate($s) {
838         $ret = str_replace(array('Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'),
839                 array( t('Monday'), t('Tuesday'), t('Wednesday'), t('Thursday'), t('Friday'), t('Saturday'), t('Sunday')),
840                 $s);
841
842         $ret = str_replace(array('January','February','March','April','May','June','July','August','September','October','November','December'),
843                 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')),
844                 $ret);
845
846         return $ret;
847 }}
848
849
850 if(! function_exists('normalise_link')) {
851 function normalise_link($url) {
852         $ret = str_replace(array('https:','//www.'), array('http:','//'), $url);
853         return(rtrim($ret,'/'));
854 }}
855
856 /**
857  *
858  * Compare two URLs to see if they are the same, but ignore
859  * slight but hopefully insignificant differences such as if one 
860  * is https and the other isn't, or if one is www.something and 
861  * the other isn't - and also ignore case differences.
862  *
863  * Return true if the URLs match, otherwise false.
864  *
865  */
866
867 if(! function_exists('link_compare')) {
868 function link_compare($a,$b) {
869         if(strcasecmp(normalise_link($a),normalise_link($b)) === 0)
870                 return true;
871         return false;
872 }}
873
874 // Given an item array, convert the body element from bbcode to html and add smilie icons.
875 // If attach is true, also add icons for item attachments
876
877
878 if(! function_exists('prepare_body')) {
879 function prepare_body($item,$attach = false) {
880
881         $a = get_app();
882         call_hooks('prepare_body_init', $item); 
883
884         $cache = get_config('system','itemcache');
885
886         if (($cache != '')) {
887                 $cachefile = $cache."/".$item["guid"]."-".strtotime($item["edited"])."-".hash("crc32", $item['body']);
888
889                 if (file_exists($cachefile))
890                         $s = file_get_contents($cachefile);
891                 else {
892                         $s = prepare_text($item['body']);
893                         file_put_contents($cachefile, $s);
894                 }
895         } else
896                 $s = prepare_text($item['body']);
897
898
899         $prep_arr = array('item' => $item, 'html' => $s);
900         call_hooks('prepare_body', $prep_arr);
901         $s = $prep_arr['html'];
902
903         if(! $attach) {
904                 return $s;
905         }
906
907         $arr = explode(',',$item['attach']);
908         if(count($arr)) {
909                 $s .= '<div class="body-attach">';
910                 foreach($arr as $r) {
911                         $matches = false;
912                         $icon = '';
913                         $cnt = preg_match_all('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"\[\/attach\]|',$r,$matches, PREG_SET_ORDER);
914                         if($cnt) {
915                                 foreach($matches as $mtch) {
916                                         $icontype = strtolower(substr($mtch[3],0,strpos($mtch[3],'/')));
917                                         switch($icontype) {
918                                                 case 'video':
919                                                 case 'audio':
920                                                 case 'image':
921                                                 case 'text':
922                                                         $icon = '<div class="attachtype icon s22 type-' . $icontype . '"></div>';
923                                                         break;
924                                                 default:
925                                                         $icon = '<div class="attachtype icon s22 type-unkn"></div>';
926                                                         break;
927                                         }
928                                         $title = ((strlen(trim($mtch[4]))) ? escape_tags(trim($mtch[4])) : escape_tags($mtch[1]));
929                                         $title .= ' ' . $mtch[2] . ' ' . t('bytes');
930                                         if((local_user() == $item['uid']) && $item['contact-id'] != $a->contact['id'])
931                                                 $the_url = $a->get_baseurl() . '/redir/' . $item['contact-id'] . '?f=1&url=' . $mtch[1];
932                                         else
933                                                 $the_url = $mtch[1];
934
935                                         $s .= '<a href="' . strip_tags($the_url) . '" title="' . $title . '" class="attachlink" target="external-link" >' . $icon . '</a>';
936                                 }
937                         }
938                 }
939                 $s .= '<div class="clear"></div></div>';
940         }
941         $matches = false;
942         $cnt = preg_match_all('/<(.*?)>/',$item['file'],$matches,PREG_SET_ORDER);
943         if($cnt) {
944 //              logger('prepare_text: categories: ' . print_r($matches,true), LOGGER_DEBUG);
945                 foreach($matches as $mtch) {
946                         if(strlen($x))
947                                 $x .= ',';
948                         $x .= xmlify(file_tag_decode($mtch[1])) 
949                                 . ((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>' : '');
950                 }
951                 if(strlen($x))
952                         $s .= '<div class="categorytags"><span>' . t('Categories:') . ' </span>' . $x . '</div>'; 
953
954
955         }
956         $matches = false;
957         $x = '';
958         $cnt = preg_match_all('/\[(.*?)\]/',$item['file'],$matches,PREG_SET_ORDER);
959         if($cnt) {
960 //              logger('prepare_text: filed_under: ' . print_r($matches,true), LOGGER_DEBUG);
961                 foreach($matches as $mtch) {
962                         if(strlen($x))
963                                 $x .= '&nbsp;&nbsp;&nbsp;';
964                         $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>';
965                 }
966                 if(strlen($x) && (local_user() == $item['uid']))
967                         $s .= '<div class="filesavetags"><span>' . t('Filed under:') . ' </span>' . $x . '</div>'; 
968         }
969
970         // Look for spoiler
971         $spoilersearch = '<blockquote class="spoiler">';
972
973         // Remove line breaks before the spoiler
974         while ((strpos($s, "\n".$spoilersearch) !== false))
975                 $s = str_replace("\n".$spoilersearch, $spoilersearch, $s);
976         while ((strpos($s, "<br />".$spoilersearch) !== false))
977                 $s = str_replace("<br />".$spoilersearch, $spoilersearch, $s);
978
979         while ((strpos($s, $spoilersearch) !== false)) {
980
981                 $pos = strpos($s, $spoilersearch);
982                 $rnd = random_string(8);
983                 $spoilerreplace = '<br /> <span id="spoiler-wrap-'.$rnd.'" style="white-space:nowrap;" class="fakelink" onclick="openClose(\'spoiler-'.$rnd.'\');">'.sprintf(t('Click to open/close')).'</span>'.
984                                         '<blockquote class="spoiler" id="spoiler-'.$rnd.'" style="display: none;">';
985                 $s = substr($s, 0, $pos).$spoilerreplace.substr($s, $pos+strlen($spoilersearch));
986         }
987
988         // Look for quote with author
989         $authorsearch = '<blockquote class="author">';
990
991         while ((strpos($s, $authorsearch) !== false)) {
992
993                 $pos = strpos($s, $authorsearch);
994                 $rnd = random_string(8);
995                 $authorreplace = '<br /> <span id="author-wrap-'.$rnd.'" style="white-space:nowrap;" class="fakelink" onclick="openClose(\'author-'.$rnd.'\');">'.sprintf(t('Click to open/close')).'</span>'.
996                                         '<blockquote class="author" id="author-'.$rnd.'" style="display: block;">';
997                 $s = substr($s, 0, $pos).$authorreplace.substr($s, $pos+strlen($authorsearch));
998         }
999
1000         $prep_arr = array('item' => $item, 'html' => $s);
1001         call_hooks('prepare_body_final', $prep_arr);
1002
1003         return $prep_arr['html'];
1004 }}
1005
1006
1007 // Given a text string, convert from bbcode to html and add smilie icons.
1008
1009 if(! function_exists('prepare_text')) {
1010 function prepare_text($text) {
1011
1012         require_once('include/bbcode.php');
1013
1014         if(stristr($text,'[nosmile]'))
1015                 $s = bbcode($text);
1016         else
1017                 $s = smilies(bbcode($text));
1018
1019         return $s;
1020 }}
1021
1022
1023 /**
1024  * return atom link elements for all of our hubs
1025  */
1026
1027 if(! function_exists('feed_hublinks')) {
1028 function feed_hublinks() {
1029
1030         $hub = get_config('system','huburl');
1031
1032         $hubxml = '';
1033         if(strlen($hub)) {
1034                 $hubs = explode(',', $hub);
1035                 if(count($hubs)) {
1036                         foreach($hubs as $h) {
1037                                 $h = trim($h);
1038                                 if(! strlen($h))
1039                                         continue;
1040                                 $hubxml .= '<link rel="hub" href="' . xmlify($h) . '" />' . "\n" ;
1041                         }
1042                 }
1043         }
1044         return $hubxml;
1045 }}
1046
1047 /* return atom link elements for salmon endpoints */
1048
1049 if(! function_exists('feed_salmonlinks')) {
1050 function feed_salmonlinks($nick) {
1051
1052         $a = get_app();
1053
1054         $salmon  = '<link rel="salmon" href="' . xmlify($a->get_baseurl() . '/salmon/' . $nick) . '" />' . "\n" ;
1055
1056         // old style links that status.net still needed as of 12/2010 
1057
1058         $salmon .= '  <link rel="http://salmon-protocol.org/ns/salmon-replies" href="' . xmlify($a->get_baseurl() . '/salmon/' . $nick) . '" />' . "\n" ; 
1059         $salmon .= '  <link rel="http://salmon-protocol.org/ns/salmon-mention" href="' . xmlify($a->get_baseurl() . '/salmon/' . $nick) . '" />' . "\n" ; 
1060         return $salmon;
1061 }}
1062
1063 if(! function_exists('get_plink')) {
1064 function get_plink($item) {
1065         $a = get_app(); 
1066         if (x($item,'plink') && ($item['private'] != 1)) {
1067                 return array(
1068                         'href' => $item['plink'],
1069                         'title' => t('link to source'),
1070                 );
1071         } 
1072         else {
1073                 return false;
1074         }
1075 }}
1076
1077 if(! function_exists('unamp')) {
1078 function unamp($s) {
1079         return str_replace('&amp;', '&', $s);
1080 }}
1081
1082
1083
1084
1085 if(! function_exists('lang_selector')) {
1086 function lang_selector() {
1087         global $lang;
1088         
1089         $langs = glob('view/*/strings.php');
1090         
1091         $lang_options = array();
1092         $selected = "";
1093         
1094         if(is_array($langs) && count($langs)) {
1095                 $langs[] = '';
1096                 if(! in_array('view/en/strings.php',$langs))
1097                         $langs[] = 'view/en/';
1098                 asort($langs);
1099                 foreach($langs as $l) {
1100                         if($l == '') {
1101                                 $lang_options[""] = t('default');
1102                                 continue;
1103                         }
1104                         $ll = substr($l,5);
1105                         $ll = substr($ll,0,strrpos($ll,'/'));
1106                         $selected = (($ll === $lang && (x($_SESSION, 'language'))) ? $ll : $selected);
1107                         $lang_options[$ll]=$ll;
1108                 }
1109         }
1110
1111         $tpl = get_markup_template("lang_selector.tpl");        
1112         $o = replace_macros($tpl, array(
1113                 '$title' => t('Select an alternate language'),
1114                 '$langs' => array($lang_options, $selected),
1115                 
1116         ));
1117         return $o;
1118 }}
1119
1120
1121 if(! function_exists('return_bytes')) {
1122 function return_bytes ($size_str) {
1123     switch (substr ($size_str, -1))
1124     {
1125         case 'M': case 'm': return (int)$size_str * 1048576;
1126         case 'K': case 'k': return (int)$size_str * 1024;
1127         case 'G': case 'g': return (int)$size_str * 1073741824;
1128         default: return $size_str;
1129     }
1130 }}
1131
1132 function generate_user_guid() {
1133         $found = true;
1134         do {
1135                 $guid = random_string(16);
1136                 $x = q("SELECT `uid` FROM `user` WHERE `guid` = '%s' LIMIT 1",
1137                         dbesc($guid)
1138                 );
1139                 if(! count($x))
1140                         $found = false;
1141         } while ($found == true );
1142         return $guid;
1143 }
1144
1145
1146
1147 function base64url_encode($s, $strip_padding = false) {
1148
1149         $s = strtr(base64_encode($s),'+/','-_');
1150
1151         if($strip_padding)
1152                 $s = str_replace('=','',$s);
1153
1154         return $s;
1155 }
1156
1157 function base64url_decode($s) {
1158
1159         if(is_array($s)) {
1160                 logger('base64url_decode: illegal input: ' . print_r(debug_backtrace(), true));
1161                 return $s;
1162         }
1163
1164 /*
1165  *  // Placeholder for new rev of salmon which strips base64 padding.
1166  *  // PHP base64_decode handles the un-padded input without requiring this step
1167  *  // Uncomment if you find you need it.
1168  *
1169  *      $l = strlen($s);
1170  *      if(! strpos($s,'=')) {
1171  *              $m = $l % 4;
1172  *              if($m == 2)
1173  *                      $s .= '==';
1174  *              if($m == 3)
1175  *                      $s .= '=';
1176  *      }
1177  *
1178  */
1179
1180         return base64_decode(strtr($s,'-_','+/'));
1181 }
1182
1183
1184 if (!function_exists('str_getcsv')) {
1185     function str_getcsv($input, $delimiter = ',', $enclosure = '"', $escape = '\\', $eol = '\n') {
1186         if (is_string($input) && !empty($input)) {
1187             $output = array();
1188             $tmp    = preg_split("/".$eol."/",$input);
1189             if (is_array($tmp) && !empty($tmp)) {
1190                 while (list($line_num, $line) = each($tmp)) {
1191                     if (preg_match("/".$escape.$enclosure."/",$line)) {
1192                         while ($strlen = strlen($line)) {
1193                             $pos_delimiter       = strpos($line,$delimiter);
1194                             $pos_enclosure_start = strpos($line,$enclosure);
1195                             if (
1196                                 is_int($pos_delimiter) && is_int($pos_enclosure_start)
1197                                 && ($pos_enclosure_start < $pos_delimiter)
1198                                 ) {
1199                                 $enclosed_str = substr($line,1);
1200                                 $pos_enclosure_end = strpos($enclosed_str,$enclosure);
1201                                 $enclosed_str = substr($enclosed_str,0,$pos_enclosure_end);
1202                                 $output[$line_num][] = $enclosed_str;
1203                                 $offset = $pos_enclosure_end+3;
1204                             } else {
1205                                 if (empty($pos_delimiter) && empty($pos_enclosure_start)) {
1206                                     $output[$line_num][] = substr($line,0);
1207                                     $offset = strlen($line);
1208                                 } else {
1209                                     $output[$line_num][] = substr($line,0,$pos_delimiter);
1210                                     $offset = (
1211                                                 !empty($pos_enclosure_start)
1212                                                 && ($pos_enclosure_start < $pos_delimiter)
1213                                                 )
1214                                                 ?$pos_enclosure_start
1215                                                 :$pos_delimiter+1;
1216                                 }
1217                             }
1218                             $line = substr($line,$offset);
1219                         }
1220                     } else {
1221                         $line = preg_split("/".$delimiter."/",$line);
1222    
1223                         /*
1224                          * Validating against pesky extra line breaks creating false rows.
1225                          */
1226                         if (is_array($line) && !empty($line[0])) {
1227                             $output[$line_num] = $line;
1228                         } 
1229                     }
1230                 }
1231                 return $output;
1232             } else {
1233                 return false;
1234             }
1235         } else {
1236             return false;
1237         }
1238     }
1239
1240
1241 function cleardiv() {
1242         return '<div class="clear"></div>';
1243 }
1244
1245
1246 function bb_translate_video($s) {
1247
1248         $matches = null;
1249         $r = preg_match_all("/\[video\](.*?)\[\/video\]/ism",$s,$matches,PREG_SET_ORDER);
1250         if($r) {
1251                 foreach($matches as $mtch) {
1252                         if((stristr($mtch[1],'youtube')) || (stristr($mtch[1],'youtu.be')))
1253                                 $s = str_replace($mtch[0],'[youtube]' . $mtch[1] . '[/youtube]',$s);
1254                         elseif(stristr($mtch[1],'vimeo'))
1255                                 $s = str_replace($mtch[0],'[vimeo]' . $mtch[1] . '[/vimeo]',$s);
1256                 }
1257         }
1258         return $s;      
1259 }
1260
1261 function html2bb_video($s) {
1262
1263         $s = preg_replace('#<object[^>]+>(.*?)https?://www.youtube.com/((?:v|cp)/[A-Za-z0-9\-_=]+)(.*?)</object>#ism',
1264                         '[youtube]$2[/youtube]', $s);
1265
1266         $s = preg_replace('#<iframe[^>](.*?)https?://www.youtube.com/embed/([A-Za-z0-9\-_=]+)(.*?)</iframe>#ism',
1267                         '[youtube]$2[/youtube]', $s);
1268
1269         $s = preg_replace('#<iframe[^>](.*?)https?://player.vimeo.com/video/([0-9]+)(.*?)</iframe>#ism',
1270                         '[vimeo]$2[/vimeo]', $s);
1271
1272         return $s;
1273 }
1274
1275 /**
1276  * apply xmlify() to all values of array $val, recursively
1277  */
1278 function array_xmlify($val){
1279         if (is_bool($val)) return $val?"true":"false";
1280         if (is_array($val)) return array_map('array_xmlify', $val);
1281         return xmlify((string) $val);
1282 }
1283
1284
1285 function reltoabs($text, $base)
1286 {
1287   if (empty($base))
1288     return $text;
1289
1290   $base = rtrim($base,'/');
1291
1292   $base2 = $base . "/";
1293         
1294   // Replace links
1295   $pattern = "/<a([^>]*) href=\"(?!http|https|\/)([^\"]*)\"/";
1296   $replace = "<a\${1} href=\"" . $base2 . "\${2}\"";
1297   $text = preg_replace($pattern, $replace, $text);
1298
1299   $pattern = "/<a([^>]*) href=\"(?!http|https)([^\"]*)\"/";
1300   $replace = "<a\${1} href=\"" . $base . "\${2}\"";
1301   $text = preg_replace($pattern, $replace, $text);
1302
1303   // Replace images
1304   $pattern = "/<img([^>]*) src=\"(?!http|https|\/)([^\"]*)\"/";
1305   $replace = "<img\${1} src=\"" . $base2 . "\${2}\"";
1306   $text = preg_replace($pattern, $replace, $text); 
1307
1308   $pattern = "/<img([^>]*) src=\"(?!http|https)([^\"]*)\"/";
1309   $replace = "<img\${1} src=\"" . $base . "\${2}\"";
1310   $text = preg_replace($pattern, $replace, $text); 
1311
1312
1313   // Done
1314   return $text;
1315 }
1316
1317 function item_post_type($item) {
1318         if(intval($item['event-id']))
1319                 return t('event');
1320         if(strlen($item['resource-id']))
1321                 return t('photo');
1322         if(strlen($item['verb']) && $item['verb'] !== ACTIVITY_POST)
1323                 return t('activity');
1324         if($item['id'] != $item['parent'])
1325                 return t('comment');
1326         return t('post');
1327 }
1328
1329 // post categories and "save to file" use the same item.file table for storage.
1330 // We will differentiate the different uses by wrapping categories in angle brackets
1331 // and save to file categories in square brackets.
1332 // To do this we need to escape these characters if they appear in our tag. 
1333
1334 function file_tag_encode($s) {
1335         return str_replace(array('<','>','[',']'),array('%3c','%3e','%5b','%5d'),$s);
1336 }
1337
1338 function file_tag_decode($s) {
1339         return str_replace(array('%3c','%3e','%5b','%5d'),array('<','>','[',']'),$s);
1340 }
1341
1342 function file_tag_file_query($table,$s,$type = 'file') {
1343
1344         if($type == 'file')
1345                 $str = preg_quote( '[' . str_replace('%','%%',file_tag_encode($s)) . ']' );
1346         else
1347                 $str = preg_quote( '<' . str_replace('%','%%',file_tag_encode($s)) . '>' );
1348         return " AND " . (($table) ? dbesc($table) . '.' : '') . "file regexp '" . dbesc($str) . "' ";
1349 }
1350
1351 // ex. given music,video return <music><video> or [music][video]
1352 function file_tag_list_to_file($list,$type = 'file') {
1353         $tag_list = '';
1354         if(strlen($list)) {
1355                 $list_array = explode(",",$list);
1356                 if($type == 'file') {
1357                         $lbracket = '[';
1358                         $rbracket = ']';
1359                 }
1360                 else {
1361                         $lbracket = '<';
1362                         $rbracket = '>';
1363                 }
1364
1365                 foreach($list_array as $item) {
1366                   if(strlen($item)) {
1367                                 $tag_list .= $lbracket . file_tag_encode(trim($item))  . $rbracket;
1368                         }
1369                 }
1370         }
1371         return $tag_list;
1372 }
1373
1374 // ex. given <music><video>[friends], return music,video or friends
1375 function file_tag_file_to_list($file,$type = 'file') {
1376         $matches = false;
1377         $list = '';
1378         if($type == 'file') {
1379                 $cnt = preg_match_all('/\[(.*?)\]/',$file,$matches,PREG_SET_ORDER);
1380         }
1381         else {
1382                 $cnt = preg_match_all('/<(.*?)>/',$file,$matches,PREG_SET_ORDER);
1383         }
1384         if($cnt) {
1385                 foreach($matches as $mtch) {
1386                         if(strlen($list))
1387                                 $list .= ',';
1388                         $list .= file_tag_decode($mtch[1]);
1389                 }
1390         }
1391
1392         return $list;
1393 }
1394
1395 function file_tag_update_pconfig($uid,$file_old,$file_new,$type = 'file') {
1396         // $file_old - categories previously associated with an item
1397         // $file_new - new list of categories for an item
1398
1399         if(! intval($uid))
1400                 return false;
1401
1402         if($file_old == $file_new)
1403                 return true;
1404
1405         $saved = get_pconfig($uid,'system','filetags');
1406         if(strlen($saved)) {
1407                 if($type == 'file') {
1408                         $lbracket = '[';
1409                         $rbracket = ']';
1410                 }
1411                 else {
1412                         $lbracket = '<';
1413                         $rbracket = '>';
1414                 }
1415
1416                 $filetags_updated = $saved;
1417
1418                 // check for new tags to be added as filetags in pconfig
1419                 $new_tags = array();
1420                 $check_new_tags = explode(",",file_tag_file_to_list($file_new,$type));
1421
1422                 foreach($check_new_tags as $tag) {
1423                         if(! stristr($saved,$lbracket . file_tag_encode($tag) . $rbracket))
1424                                 $new_tags[] = $tag;
1425                 }
1426
1427                 $filetags_updated .= file_tag_list_to_file(implode(",",$new_tags),$type);
1428
1429                 // check for deleted tags to be removed from filetags in pconfig
1430                 $deleted_tags = array();
1431                 $check_deleted_tags = explode(",",file_tag_file_to_list($file_old,$type));
1432
1433                 foreach($check_deleted_tags as $tag) {
1434                         if(! stristr($file_new,$lbracket . file_tag_encode($tag) . $rbracket))
1435                                 $deleted_tags[] = $tag;
1436                 }
1437
1438                 foreach($deleted_tags as $key => $tag) {
1439                         $r = q("select file from item where uid = %d " . file_tag_file_query('item',$tag,$type),
1440                                 intval($uid)
1441                         );
1442
1443                         if(count($r)) {
1444                                 unset($deleted_tags[$key]);
1445                         }
1446                         else {
1447                                 $filetags_updated = str_replace($lbracket . file_tag_encode($tag) . $rbracket,'',$filetags_updated);
1448                         }
1449                 }
1450
1451                 if($saved != $filetags_updated) {
1452                         set_pconfig($uid,'system','filetags', $filetags_updated);
1453                 }
1454                 return true;
1455         }
1456         else
1457                 if(strlen($file_new)) {
1458                         set_pconfig($uid,'system','filetags', $file_new);
1459                 }
1460                 return true;
1461 }
1462
1463 function file_tag_save_file($uid,$item,$file) {
1464         $result = false;
1465         if(! intval($uid))
1466                 return false;
1467         $r = q("select file from item where id = %d and uid = %d limit 1",
1468                 intval($item),
1469                 intval($uid)
1470         );
1471         if(count($r)) {
1472                 if(! stristr($r[0]['file'],'[' . file_tag_encode($file) . ']'))
1473                         q("update item set file = '%s' where id = %d and uid = %d limit 1",
1474                                 dbesc($r[0]['file'] . '[' . file_tag_encode($file) . ']'),
1475                                 intval($item),
1476                                 intval($uid)
1477                         );
1478                 $saved = get_pconfig($uid,'system','filetags');
1479                 if((! strlen($saved)) || (! stristr($saved,'[' . file_tag_encode($file) . ']')))
1480                         set_pconfig($uid,'system','filetags',$saved . '[' . file_tag_encode($file) . ']');
1481                 info( t('Item filed') );
1482         }
1483         return true;
1484 }
1485
1486 function file_tag_unsave_file($uid,$item,$file,$cat = false) {
1487         $result = false;
1488         if(! intval($uid))
1489                 return false;
1490
1491         if($cat == true)
1492                 $pattern = '<' . file_tag_encode($file) . '>' ;
1493         else
1494                 $pattern = '[' . file_tag_encode($file) . ']' ;
1495
1496
1497         $r = q("select file from item where id = %d and uid = %d limit 1",
1498                 intval($item),
1499                 intval($uid)
1500         );
1501         if(! count($r))
1502                 return false;
1503
1504         q("update item set file = '%s' where id = %d and uid = %d limit 1",
1505                 dbesc(str_replace($pattern,'',$r[0]['file'])),
1506                 intval($item),
1507                 intval($uid)
1508         );
1509
1510         $r = q("select file from item where uid = %d and deleted = 0 " . file_tag_file_query('item',$file,(($cat) ? 'category' : 'file')),
1511                 intval($uid)
1512         );
1513
1514         if(! count($r)) {
1515                 $saved = get_pconfig($uid,'system','filetags');
1516                 set_pconfig($uid,'system','filetags',str_replace($pattern,'',$saved));
1517
1518         }
1519         return true;
1520 }
1521
1522 function normalise_openid($s) {
1523         return trim(str_replace(array('http://','https://'),array('',''),$s),'/');
1524 }
1525
1526
1527 function undo_post_tagging($s) {
1528         $matches = null;
1529         $cnt = preg_match_all('/([@#])\[url=(.*?)\](.*?)\[\/url\]/ism',$s,$matches,PREG_SET_ORDER);
1530         if($cnt) {
1531                 foreach($matches as $mtch) {
1532                         $s = str_replace($mtch[0], $mtch[1] . $mtch[3],$s);
1533                 }
1534         }
1535         return $s;
1536 }
1537
1538 function fix_mce_lf($s) {
1539         $s = str_replace("\r\n","\n",$s);
1540         return $s;
1541 }
1542
1543
1544 function protect_sprintf($s) {
1545         return(str_replace('%','%%',$s));
1546 }
1547
1548
1549 function is_a_date_arg($s) {
1550         $i = intval($s);
1551         if($i > 1900) {
1552                 $y = date('Y');
1553                 if($i <= $y+1 && strpos($s,'-') == 4) {
1554                         $m = intval(substr($s,5));
1555                         if($m > 0 && $m <= 12)
1556                                 return true;
1557                 }
1558         }
1559         return false;
1560 }