]> git.mxchange.org Git - friendica.git/blob - include/text.php
allow posted ACLs to be comma-delimited string besides the default array
[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, ENT_COMPAT, 'UTF-8', false));
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 if(! function_exists('alt_pager')) {
284 function alt_pager(&$a, $i) {
285         $o = '';
286         $stripped = preg_replace('/(&page=[0-9]*)/','',$a->query_string);
287         $stripped = str_replace('q=','',$stripped);
288         $stripped = trim($stripped,'/');
289         $pagenum = $a->pager['page'];
290         $url = $a->get_baseurl() . '/' . $stripped;
291
292         $o .= '<div class="pager">';
293
294         if($a->pager['page']>1)
295           $o .= "<a href=\"$url"."&page=".($a->pager['page'] - 1).'">' . t('newer') . '</a>';
296         if($i>0) {
297           if($a->pager['page']>1)
298                   $o .= "&nbsp;-&nbsp;";
299           $o .= "<a href=\"$url"."&page=".($a->pager['page'] + 1).'">' . t('older') . '</a>';
300         }
301
302
303         $o .= '</div>'."\r\n";
304
305         return $o;
306 }}
307
308 // Turn user/group ACLs stored as angle bracketed text into arrays
309
310 if(! function_exists('expand_acl')) {
311 function expand_acl($s) {
312         // turn string array of angle-bracketed elements into numeric array
313         // e.g. "<1><2><3>" => array(1,2,3);
314         $ret = array();
315
316         if(strlen($s)) {
317                 $t = str_replace('<','',$s);
318                 $a = explode('>',$t);
319                 foreach($a as $aa) {
320                         if(intval($aa))
321                                 $ret[] = intval($aa);
322                 }
323         }
324         return $ret;
325 }}              
326
327 // Used to wrap ACL elements in angle brackets for storage 
328
329 if(! function_exists('sanitise_acl')) {
330 function sanitise_acl(&$item) {
331         if(intval($item))
332                 $item = '<' . intval(notags(trim($item))) . '>';
333         else
334                 unset($item);
335 }}
336
337
338 // Convert an ACL array to a storable string
339 // Normally ACL permissions will be an array.
340 // We'll also allow a comma-separated string.
341
342 if(! function_exists('perms2str')) {
343 function perms2str($p) {
344         $ret = '';
345
346         if(is_array($p))
347                 $tmp = $p;
348         else
349                 $tmp = explode(',',$p);
350
351         if(is_array($tmp)) {
352                 array_walk($tmp,'sanitise_acl');
353                 $ret = implode('',$tmp);
354         }
355         return $ret;
356 }}
357
358 // generate a guaranteed unique (for this domain) item ID for ATOM
359 // safe from birthday paradox
360
361 if(! function_exists('item_new_uri')) {
362 function item_new_uri($hostname,$uid) {
363
364         do {
365                 $dups = false;
366                 $hash = random_string();
367
368                 $uri = "urn:X-dfrn:" . $hostname . ':' . $uid . ':' . $hash;
369
370                 $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' LIMIT 1",
371                         dbesc($uri));
372                 if(count($r))
373                         $dups = true;
374         } while($dups == true);
375         return $uri;
376 }}
377
378 // Generate a guaranteed unique photo ID.
379 // safe from birthday paradox
380
381 if(! function_exists('photo_new_resource')) {
382 function photo_new_resource() {
383
384         do {
385                 $found = false;
386                 $resource = hash('md5',uniqid(mt_rand(),true));
387                 $r = q("SELECT `id` FROM `photo` WHERE `resource-id` = '%s' LIMIT 1",
388                         dbesc($resource)
389                 );
390                 if(count($r))
391                         $found = true;
392         } while($found == true);
393         return $resource;
394 }}
395
396
397 // wrapper to load a view template, checking for alternate
398 // languages before falling back to the default
399
400 // obsolete, deprecated.
401
402 if(! function_exists('load_view_file')) {
403 function load_view_file($s) {
404         global $lang, $a;
405         if(! isset($lang))
406                 $lang = 'en';
407         $b = basename($s);
408         $d = dirname($s);
409         if(file_exists("$d/$lang/$b"))
410                 return file_get_contents("$d/$lang/$b");
411         
412         $theme = current_theme();
413
414         if(file_exists("$d/theme/$theme/$b"))
415                 return file_get_contents("$d/theme/$theme/$b");
416                         
417         return file_get_contents($s);
418 }}
419
420 if(! function_exists('get_intltext_template')) {
421 function get_intltext_template($s) {
422         global $lang;
423
424         if(! isset($lang))
425                 $lang = 'en';
426
427         if(file_exists("view/$lang/$s"))
428                 return file_get_contents("view/$lang/$s");
429         elseif(file_exists("view/en/$s"))
430                 return file_get_contents("view/en/$s");
431         else
432                 return file_get_contents("view/$s");
433 }}
434
435 if(! function_exists('get_markup_template')) {
436 function get_markup_template($s) {
437         $a=get_app();
438         $theme = current_theme();
439         
440         if(file_exists("view/theme/$theme/$s"))
441                 return file_get_contents("view/theme/$theme/$s");
442         elseif (x($a->theme_info,"extends") && file_exists("view/theme/".$a->theme_info["extends"]."/$s"))
443                 return file_get_contents("view/theme/".$a->theme_info["extends"]."/$s");
444         else
445                 return file_get_contents("view/$s");
446
447 }}
448
449
450
451
452
453 // for html,xml parsing - let's say you've got
454 // an attribute foobar="class1 class2 class3"
455 // and you want to find out if it contains 'class3'.
456 // you can't use a normal sub string search because you
457 // might match 'notclass3' and a regex to do the job is 
458 // possible but a bit complicated. 
459 // pass the attribute string as $attr and the attribute you 
460 // are looking for as $s - returns true if found, otherwise false
461
462 if(! function_exists('attribute_contains')) {
463 function attribute_contains($attr,$s) {
464         $a = explode(' ', $attr);
465         if(count($a) && in_array($s,$a))
466                 return true;
467         return false;
468 }}
469
470 if(! function_exists('logger')) {
471 function logger($msg,$level = 0) {
472         // turn off logger in install mode
473         global $a;
474         global $db;
475
476         if(($a->module == 'install') || (! ($db && $db->connected))) return;
477
478         $debugging = get_config('system','debugging');
479         $loglevel  = intval(get_config('system','loglevel'));
480         $logfile   = get_config('system','logfile');
481
482         if((! $debugging) || (! $logfile) || ($level > $loglevel))
483                 return;
484         
485         @file_put_contents($logfile, datetime_convert() . ':' . session_id() . ' ' . $msg . "\n", FILE_APPEND);
486         return;
487 }}
488
489
490 if(! function_exists('activity_match')) {
491 function activity_match($haystack,$needle) {
492         if(($haystack === $needle) || ((basename($needle) === $haystack) && strstr($needle,NAMESPACE_ACTIVITY_SCHEMA)))
493                 return true;
494         return false;
495 }}
496
497
498 // Pull out all #hashtags and @person tags from $s;
499 // We also get @person@domain.com - which would make 
500 // the regex quite complicated as tags can also
501 // end a sentence. So we'll run through our results
502 // and strip the period from any tags which end with one.
503 // Returns array of tags found, or empty array.
504
505
506 if(! function_exists('get_tags')) {
507 function get_tags($s) {
508         $ret = array();
509
510         // ignore anything in a code block
511
512         $s = preg_replace('/\[code\](.*?)\[\/code\]/sm','',$s);
513
514         // ignore anything in a bbtag
515
516         $s = preg_replace('/\[(.*?)\]/sm','',$s);
517
518         // Match full names against @tags including the space between first and last
519         // We will look these up afterward to see if they are full names or not recognisable.
520
521         if(preg_match_all('/(@[^ \x0D\x0A,:?]+ [^ \x0D\x0A@,:?]+)([ \x0D\x0A@,:?]|$)/',$s,$match)) {
522                 foreach($match[1] as $mtch) {
523                         if(strstr($mtch,"]")) {
524                                 // we might be inside a bbcode color tag - leave it alone
525                                 continue;
526                         }
527                         if(substr($mtch,-1,1) === '.')
528                                 $ret[] = substr($mtch,0,-1);
529                         else
530                                 $ret[] = $mtch;
531                 }
532         }
533
534         // Otherwise pull out single word tags. These can be @nickname, @first_last
535         // and #hash tags.
536
537         if(preg_match_all('/([@#][^ \x0D\x0A,;:?]+)([ \x0D\x0A,;:?]|$)/',$s,$match)) {
538                 foreach($match[1] as $mtch) {
539                         if(strstr($mtch,"]")) {
540                                 // we might be inside a bbcode color tag - leave it alone
541                                 continue;
542                         }
543                         if(substr($mtch,-1,1) === '.')
544                                 $mtch = substr($mtch,0,-1);
545                         // ignore strictly numeric tags like #1
546                         if((strpos($mtch,'#') === 0) && ctype_digit(substr($mtch,1)))
547                                 continue;
548                         // try not to catch url fragments
549                         if(strpos($s,$mtch) && preg_match('/[a-zA-z0-9\/]/',substr($s,strpos($s,$mtch)-1,1)))
550                                 continue;
551                         $ret[] = $mtch;
552                 }
553         }
554         return $ret;
555 }}
556
557
558 // quick and dirty quoted_printable encoding
559
560 if(! function_exists('qp')) {
561 function qp($s) {
562 return str_replace ("%","=",rawurlencode($s));
563 }} 
564
565
566
567 if(! function_exists('get_mentions')) {
568 function get_mentions($item) {
569         $o = '';
570         if(! strlen($item['tag']))
571                 return $o;
572
573         $arr = explode(',',$item['tag']);
574         foreach($arr as $x) {
575                 $matches = null;
576                 if(preg_match('/@\[url=([^\]]*)\]/',$x,$matches)) {
577                         $o .= "\t\t" . '<link rel="mentioned" href="' . $matches[1] . '" />' . "\r\n";
578                         $o .= "\t\t" . '<link rel="ostatus:attention" href="' . $matches[1] . '" />' . "\r\n";
579                 }
580         }
581         return $o;
582 }}
583
584 if(! function_exists('contact_block')) {
585 function contact_block() {
586         $o = '';
587         $a = get_app();
588
589         $shown = get_pconfig($a->profile['uid'],'system','display_friend_count');
590         if($shown === false)
591                 $shown = 24;
592         if($shown == 0)
593                 return;
594
595         if((! is_array($a->profile)) || ($a->profile['hide-friends']))
596                 return $o;
597         $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",
598                         intval($a->profile['uid'])
599         );
600         if(count($r)) {
601                 $total = intval($r[0]['total']);
602         }
603         if(! $total) {
604                 $contacts = t('No contacts');
605                 $micropro = Null;
606                 
607         } else {
608                 $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",
609                                 intval($a->profile['uid']),
610                                 intval($shown)
611                 );
612                 if(count($r)) {
613                         $contacts = sprintf( tt('%d Contact','%d Contacts', $total),$total);
614                         $micropro = Array();
615                         foreach($r as $rr) {
616                                 $micropro[] = micropro($rr,true,'mpfriend');
617                         }
618                 }
619         }
620         
621         $tpl = get_markup_template('contact_block.tpl');
622         $o = replace_macros($tpl, array(
623                 '$contacts' => $contacts,
624                 '$nickname' => $a->profile['nickname'],
625                 '$viewcontacts' => t('View Contacts'),
626                 '$micropro' => $micropro,
627         ));
628
629         $arr = array('contacts' => $r, 'output' => $o);
630
631         call_hooks('contact_block_end', $arr);
632         return $o;
633
634 }}
635
636 if(! function_exists('micropro')) {
637 function micropro($contact, $redirect = false, $class = '', $textmode = false) {
638
639         if($class)
640                 $class = ' ' . $class;
641
642         $url = $contact['url'];
643         $sparkle = '';
644         $redir = false;
645
646         if($redirect) {
647                 $a = get_app();
648                 $redirect_url = $a->get_baseurl() . '/redir/' . $contact['id'];
649                 if(local_user() && ($contact['uid'] == local_user()) && ($contact['network'] === 'dfrn')) {
650                         $redir = true;
651                         $url = $redirect_url;
652                         $sparkle = ' sparkle';
653                 }
654                 else
655                         $url = zrl($url);
656         }
657         $click = ((x($contact,'click')) ? ' onclick="' . $contact['click'] . '" ' : '');
658         if($click)
659                 $url = '';
660         if($textmode) {
661                 return '<div class="contact-block-textdiv' . $class . '"><a class="contact-block-link' . $class . $sparkle 
662                         . (($click) ? ' fakelink' : '') . '" '
663                         . (($redir) ? ' target="redir" ' : '')
664                         . (($url) ? ' href="' . $url . '"' : '') . $click
665                         . '" title="' . $contact['name'] . ' [' . $contact['url'] . ']" alt="' . $contact['name'] 
666                         . '" >'. $contact['name'] . '</a></div>' . "\r\n";
667         }
668         else {
669                 return '<div class="contact-block-div' . $class . '"><a class="contact-block-link' . $class . $sparkle 
670                         . (($click) ? ' fakelink' : '') . '" '
671                         . (($redir) ? ' target="redir" ' : '')
672                         . (($url) ? ' href="' . $url . '"' : '') . $click . ' ><img class="contact-block-img' . $class . $sparkle . '" src="' 
673                         . $contact['micro'] . '" title="' . $contact['name'] . ' [' . $contact['url'] . ']" alt="' . $contact['name'] 
674                         . '" /></a></div>' . "\r\n";
675         }
676 }}
677
678
679
680 if(! function_exists('search')) {
681 function search($s,$id='search-box',$url='/search',$save = false) {
682         $a = get_app();
683         $o  = '<div id="' . $id . '">';
684         $o .= '<form action="' . $a->get_baseurl((stristr($url,'network')) ? true : false) . $url . '" method="get" >';
685         $o .= '<input type="text" name="search" id="search-text" placeholder="' . t('Search') . '" value="' . $s .'" />';
686         $o .= '<input type="submit" name="submit" id="search-submit" value="' . t('Search') . '" />'; 
687         if($save)
688                 $o .= '<input type="submit" name="save" id="search-save" value="' . t('Save') . '" />'; 
689         $o .= '</form></div>';
690         return $o;
691 }}
692
693 if(! function_exists('valid_email')) {
694 function valid_email($x){
695
696         if(get_config('system','disable_email_validation'))
697                 return true;
698
699         if(preg_match('/^[_a-zA-Z0-9\-\+]+(\.[_a-zA-Z0-9\-\+]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)+$/',$x))
700                 return true;
701         return false;
702 }}
703
704
705 /**
706  *
707  * Function: linkify
708  *
709  * Replace naked text hyperlink with HTML formatted hyperlink
710  *
711  */
712
713 if(! function_exists('linkify')) {
714 function linkify($s) {
715         $s = preg_replace("/(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\'\%\$\!\+]*)/", ' <a href="$1" target="external-link">$1</a>', $s);
716         $s = preg_replace("/\<(.*?)(src|href)=(.*?)\&amp\;(.*?)\>/ism",'<$1$2=$3&$4>',$s);
717         return($s);
718 }}
719
720 function get_poke_verbs() {
721         
722         // index is present tense verb
723         // value is array containing past tense verb, translation of present, translation of past
724
725         $arr = array(
726                 'poke' => array( 'poked', t('poke'), t('poked')),
727                 'ping' => array( 'pinged', t('ping'), t('pinged')),
728                 'prod' => array( 'prodded', t('prod'), t('prodded')),
729                 'slap' => array( 'slapped', t('slap'), t('slapped')),
730                 'finger' => array( 'fingered', t('finger'), t('fingered')),
731                 'rebuff' => array( 'rebuffed', t('rebuff'), t('rebuffed')),
732         );
733         call_hooks('poke_verbs', $arr);
734         return $arr;
735 }
736
737 function get_mood_verbs() {
738         
739         // index is present tense verb
740         // value is array containing past tense verb, translation of present, translation of past
741
742         $arr = array(
743                 'happy'      => t('happy'),
744                 'sad'        => t('sad'),
745                 'mellow'     => t('mellow'),
746                 'tired'      => t('tired'),
747                 'perky'      => t('perky'),
748                 'angry'      => t('angry'),
749                 'stupefied'  => t('stupified'),
750                 'puzzled'    => t('puzzled'),
751                 'interested' => t('interested'),
752                 'bitter'     => t('bitter'),
753                 'cheerful'   => t('cheerful'),
754                 'alive'      => t('alive'),
755                 'annoyed'    => t('annoyed'),
756                 'anxious'    => t('anxious'),
757                 'cranky'     => t('cranky'),
758                 'disturbed'  => t('disturbed'),
759                 'frustrated' => t('frustrated'),
760                 'motivated'  => t('motivated'),
761                 'relaxed'    => t('relaxed'),
762                 'surprised'  => t('surprised'),
763         );
764
765         call_hooks('mood_verbs', $arr);
766         return $arr;
767 }
768
769
770 /**
771  * 
772  * Function: smilies
773  *
774  * Description:
775  * Replaces text emoticons with graphical images
776  *
777  * @Parameter: string $s
778  *
779  * Returns string
780  *
781  * It is expected that this function will be called using HTML text.
782  * We will escape text between HTML pre and code blocks from being 
783  * processed. 
784  * 
785  * At a higher level, the bbcode [nosmile] tag can be used to prevent this 
786  * function from being executed by the prepare_text() routine when preparing
787  * bbcode source for HTML display
788  *
789  */
790
791 if(! function_exists('smilies')) {
792 function smilies($s, $sample = false) {
793
794         $a = get_app();
795
796         if(intval(get_config('system','no_smilies')) 
797                 || (local_user() && intval(get_pconfig(local_user(),'system','no_smilies'))))
798                 return $s;
799
800         $s = preg_replace_callback('/<pre>(.*?)<\/pre>/ism','smile_encode',$s);
801         $s = preg_replace_callback('/<code>(.*?)<\/code>/ism','smile_encode',$s);
802
803         $texts =  array( 
804                 '&lt;3', 
805                 '&lt;/3', 
806                 '&lt;\\3', 
807                 ':-)', 
808                 ';-)', 
809                 ':-(', 
810                 ':-P', 
811                 ':-p', 
812                 ':-"', 
813                 ':-&quot;', 
814                 ':-x', 
815                 ':-X', 
816                 ':-D', 
817                 '8-|', 
818                 '8-O', 
819                 ':-O', 
820                 '\\o/', 
821                 'o.O', 
822                 'O.o', 
823                 'o_O', 
824                 'O_o', 
825                 ":'(", 
826                 ":-!", 
827                 ":-/", 
828                 ":-[", 
829                 "8-)",
830                 ':beer', 
831                 ':homebrew', 
832                 ':coffee', 
833                 ':facepalm',
834                 ':like',
835                 ':dislike',
836                 '~friendica'
837
838         );
839
840         $icons = array(
841                 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-heart.gif" alt="<3" />',
842                 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-brokenheart.gif" alt="</3" />',
843                 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-brokenheart.gif" alt="<\\3" />',
844                 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-smile.gif" alt=":-)" />',
845                 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-wink.gif" alt=";-)" />',
846                 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-frown.gif" alt=":-(" />',
847                 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-tongue-out.gif" alt=":-P" />',
848                 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-tongue-out.gif" alt=":-p" />',
849                 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-kiss.gif" alt=":-\"" />',
850                 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-kiss.gif" alt=":-\"" />',
851                 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-kiss.gif" alt=":-x" />',
852                 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-kiss.gif" alt=":-X" />',
853                 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-laughing.gif" alt=":-D" />',
854                 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-surprised.gif" alt="8-|" />',
855                 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-surprised.gif" alt="8-O" />',
856                 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-surprised.gif" alt=":-O" />',                
857                 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-thumbsup.gif" alt="\\o/" />',
858                 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-Oo.gif" alt="o.O" />',
859                 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-Oo.gif" alt="O.o" />',
860                 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-Oo.gif" alt="o_O" />',
861                 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-Oo.gif" alt="O_o" />',
862                 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-cry.gif" alt=":\'(" />',
863                 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-foot-in-mouth.gif" alt=":-!" />',
864                 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-undecided.gif" alt=":-/" />',
865                 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-embarassed.gif" alt=":-[" />',
866                 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-cool.gif" alt="8-)" />',
867                 '<img class="smiley" src="' . $a->get_baseurl() . '/images/beer_mug.gif" alt=":beer" />',
868                 '<img class="smiley" src="' . $a->get_baseurl() . '/images/beer_mug.gif" alt=":homebrew" />',
869                 '<img class="smiley" src="' . $a->get_baseurl() . '/images/coffee.gif" alt=":coffee" />',
870                 '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-facepalm.gif" alt=":facepalm" />',
871                 '<img class="smiley" src="' . $a->get_baseurl() . '/images/like.gif" alt=":like" />',
872                 '<img class="smiley" src="' . $a->get_baseurl() . '/images/dislike.gif" alt=":dislike" />',
873                 '<a href="http://friendica.com">~friendica <img class="smiley" src="' . $a->get_baseurl() . '/images/friendica-16.png" alt="~friendica" /></a>'
874         );
875
876         $params = array('texts' => $texts, 'icons' => $icons, 'string' => $s);
877         call_hooks('smilie', $params);
878
879         if($sample) {
880                 $s = '<div class="smiley-sample">';
881                 for($x = 0; $x < count($params['texts']); $x ++) {
882                         $s .= '<dl><dt>' . $params['texts'][$x] . '</dt><dd>' . $params['icons'][$x] . '</dd></dl>';
883                 }
884         }
885         else {
886                 $params['string'] = preg_replace_callback('/&lt;(3+)/','preg_heart',$params['string']);
887                 $s = str_replace($params['texts'],$params['icons'],$params['string']);
888         }
889
890         $s = preg_replace_callback('/<pre>(.*?)<\/pre>/ism','smile_decode',$s);
891         $s = preg_replace_callback('/<code>(.*?)<\/code>/ism','smile_decode',$s);
892
893         return $s;
894
895 }}
896
897 function smile_encode($m) {
898         return(str_replace($m[1],base64url_encode($m[1]),$m[0]));
899 }
900
901 function smile_decode($m) {
902         return(str_replace($m[1],base64url_decode($m[1]),$m[0]));
903 }
904
905 // expand <3333 to the correct number of hearts
906
907 function preg_heart($x) {
908         $a = get_app();
909         if(strlen($x[1]) == 1)
910                 return $x[0];
911         $t = '';
912         for($cnt = 0; $cnt < strlen($x[1]); $cnt ++)
913                 $t .= '<img class="smiley" src="' . $a->get_baseurl() . '/images/smiley-heart.gif" alt="<3" />';
914         $r =  str_replace($x[0],$t,$x[0]);
915         return $r;
916 }
917
918
919 if(! function_exists('day_translate')) {
920 function day_translate($s) {
921         $ret = str_replace(array('Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'),
922                 array( t('Monday'), t('Tuesday'), t('Wednesday'), t('Thursday'), t('Friday'), t('Saturday'), t('Sunday')),
923                 $s);
924
925         $ret = str_replace(array('January','February','March','April','May','June','July','August','September','October','November','December'),
926                 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')),
927                 $ret);
928
929         return $ret;
930 }}
931
932
933 if(! function_exists('normalise_link')) {
934 function normalise_link($url) {
935         $ret = str_replace(array('https:','//www.'), array('http:','//'), $url);
936         return(rtrim($ret,'/'));
937 }}
938
939 /**
940  *
941  * Compare two URLs to see if they are the same, but ignore
942  * slight but hopefully insignificant differences such as if one 
943  * is https and the other isn't, or if one is www.something and 
944  * the other isn't - and also ignore case differences.
945  *
946  * Return true if the URLs match, otherwise false.
947  *
948  */
949
950 if(! function_exists('link_compare')) {
951 function link_compare($a,$b) {
952         if(strcasecmp(normalise_link($a),normalise_link($b)) === 0)
953                 return true;
954         return false;
955 }}
956
957 // Given an item array, convert the body element from bbcode to html and add smilie icons.
958 // If attach is true, also add icons for item attachments
959
960
961 if(! function_exists('prepare_body')) {
962 function prepare_body($item,$attach = false) {
963
964         $a = get_app();
965         call_hooks('prepare_body_init', $item); 
966
967         $cache = get_config('system','itemcache');
968
969         if (($cache != '')) {
970                 $cachefile = $cache."/".$item["guid"]."-".strtotime($item["edited"])."-".hash("crc32", $item['body']);
971
972                 if (file_exists($cachefile))
973                         $s = file_get_contents($cachefile);
974                 else {
975                         $s = prepare_text($item['body']);
976                         file_put_contents($cachefile, $s);
977                 }
978         } else
979                 $s = prepare_text($item['body']);
980
981
982         $prep_arr = array('item' => $item, 'html' => $s);
983         call_hooks('prepare_body', $prep_arr);
984         $s = $prep_arr['html'];
985
986         if(! $attach) {
987                 return $s;
988         }
989
990         $arr = explode(',',$item['attach']);
991         if(count($arr)) {
992                 $s .= '<div class="body-attach">';
993                 foreach($arr as $r) {
994                         $matches = false;
995                         $icon = '';
996                         $cnt = preg_match_all('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"\[\/attach\]|',$r,$matches, PREG_SET_ORDER);
997                         if($cnt) {
998                                 foreach($matches as $mtch) {
999                                         $icontype = strtolower(substr($mtch[3],0,strpos($mtch[3],'/')));
1000                                         switch($icontype) {
1001                                                 case 'video':
1002                                                 case 'audio':
1003                                                 case 'image':
1004                                                 case 'text':
1005                                                         $icon = '<div class="attachtype icon s22 type-' . $icontype . '"></div>';
1006                                                         break;
1007                                                 default:
1008                                                         $icon = '<div class="attachtype icon s22 type-unkn"></div>';
1009                                                         break;
1010                                         }
1011                                         $title = ((strlen(trim($mtch[4]))) ? escape_tags(trim($mtch[4])) : escape_tags($mtch[1]));
1012                                         $title .= ' ' . $mtch[2] . ' ' . t('bytes');
1013                                         if((local_user() == $item['uid']) && ($item['contact-id'] != $a->contact['id']) && ($item['network'] == NETWORK_DFRN))
1014                                                 $the_url = $a->get_baseurl() . '/redir/' . $item['contact-id'] . '?f=1&url=' . $mtch[1];
1015                                         else
1016                                                 $the_url = $mtch[1];
1017
1018                                         $s .= '<a href="' . strip_tags($the_url) . '" title="' . $title . '" class="attachlink" target="external-link" >' . $icon . '</a>';
1019                                 }
1020                         }
1021                 }
1022                 $s .= '<div class="clear"></div></div>';
1023         }
1024
1025
1026         // Look for spoiler
1027         $spoilersearch = '<blockquote class="spoiler">';
1028
1029         // Remove line breaks before the spoiler
1030         while ((strpos($s, "\n".$spoilersearch) !== false))
1031                 $s = str_replace("\n".$spoilersearch, $spoilersearch, $s);
1032         while ((strpos($s, "<br />".$spoilersearch) !== false))
1033                 $s = str_replace("<br />".$spoilersearch, $spoilersearch, $s);
1034
1035         while ((strpos($s, $spoilersearch) !== false)) {
1036
1037                 $pos = strpos($s, $spoilersearch);
1038                 $rnd = random_string(8);
1039                 $spoilerreplace = '<br /> <span id="spoiler-wrap-'.$rnd.'" style="white-space:nowrap;" class="fakelink" onclick="openClose(\'spoiler-'.$rnd.'\');">'.sprintf(t('Click to open/close')).'</span>'.
1040                                         '<blockquote class="spoiler" id="spoiler-'.$rnd.'" style="display: none;">';
1041                 $s = substr($s, 0, $pos).$spoilerreplace.substr($s, $pos+strlen($spoilersearch));
1042         }
1043
1044         // Look for quote with author
1045         $authorsearch = '<blockquote class="author">';
1046
1047         while ((strpos($s, $authorsearch) !== false)) {
1048
1049                 $pos = strpos($s, $authorsearch);
1050                 $rnd = random_string(8);
1051                 $authorreplace = '<br /> <span id="author-wrap-'.$rnd.'" style="white-space:nowrap;" class="fakelink" onclick="openClose(\'author-'.$rnd.'\');">'.sprintf(t('Click to open/close')).'</span>'.
1052                                         '<blockquote class="author" id="author-'.$rnd.'" style="display: block;">';
1053                 $s = substr($s, 0, $pos).$authorreplace.substr($s, $pos+strlen($authorsearch));
1054         }
1055
1056         $prep_arr = array('item' => $item, 'html' => $s);
1057         call_hooks('prepare_body_final', $prep_arr);
1058
1059         return $prep_arr['html'];
1060 }}
1061
1062
1063 // Given a text string, convert from bbcode to html and add smilie icons.
1064
1065 if(! function_exists('prepare_text')) {
1066 function prepare_text($text) {
1067
1068         require_once('include/bbcode.php');
1069
1070         if(stristr($text,'[nosmile]'))
1071                 $s = bbcode($text);
1072         else
1073                 $s = smilies(bbcode($text));
1074
1075         return $s;
1076 }}
1077
1078
1079 /**
1080  * returns 
1081  * [
1082  *    //categories [
1083  *          {
1084  *               'name': 'category name',
1085  *              'removeurl': 'url to remove this category',
1086  *             'first': 'is the first in this array? true/false',
1087  *               'last': 'is the last in this array? true/false',
1088  *           } ,
1089  *           ....
1090  *       ],
1091  *       // folders [
1092  *               'name': 'folder name',
1093  *               'removeurl': 'url to remove this folder',
1094  *               'first': 'is the first in this array? true/false',
1095  *               'last': 'is the last in this array? true/false',
1096  *           } ,
1097  *           ....       
1098  *       ]
1099  *   ]
1100  */
1101 function get_cats_and_terms($item) {
1102     $a = get_app();
1103     $categories = array();
1104     $folders = array();
1105
1106     $matches = false; $first = true;
1107     $cnt = preg_match_all('/<(.*?)>/',$item['file'],$matches,PREG_SET_ORDER);
1108     if($cnt) {
1109         foreach($matches as $mtch) {
1110             $categories[] = array(
1111                 'name' => xmlify(file_tag_decode($mtch[1])),
1112                 'url' =>  "#",
1113                 'removeurl' => ((local_user() == $item['uid'])?$a->get_baseurl() . '/filerm/' . $item['id'] . '?f=&cat=' . xmlify(file_tag_decode($mtch[1])):""),
1114                 'first' => $first,
1115                 'last' => false
1116             );
1117             $first = false;
1118         }
1119     }
1120     if (count($categories)) $categories[count($categories)-1]['last'] = true;
1121     
1122
1123         if(local_user() == $item['uid']) {
1124             $matches = false; $first = true;
1125         $cnt = preg_match_all('/\[(.*?)\]/',$item['file'],$matches,PREG_SET_ORDER);
1126             if($cnt) {
1127             foreach($matches as $mtch) {
1128                     $folders[] = array(
1129                     'name' => xmlify(file_tag_decode($mtch[1])),
1130                          'url' =>  "#",
1131                         'removeurl' => ((local_user() == $item['uid'])?$a->get_baseurl() . '/filerm/' . $item['id'] . '?f=&term=' . xmlify(file_tag_decode($mtch[1])):""),
1132                     'first' => $first,
1133                         'last' => false
1134                 );
1135                     $first = false;
1136                         }
1137         }
1138     }
1139
1140     if (count($folders)) $folders[count($folders)-1]['last'] = true;
1141
1142     return array($categories, $folders);
1143 }
1144
1145
1146 /**
1147  * return atom link elements for all of our hubs
1148  */
1149
1150 if(! function_exists('feed_hublinks')) {
1151 function feed_hublinks() {
1152
1153         $hub = get_config('system','huburl');
1154
1155         $hubxml = '';
1156         if(strlen($hub)) {
1157                 $hubs = explode(',', $hub);
1158                 if(count($hubs)) {
1159                         foreach($hubs as $h) {
1160                                 $h = trim($h);
1161                                 if(! strlen($h))
1162                                         continue;
1163                                 $hubxml .= '<link rel="hub" href="' . xmlify($h) . '" />' . "\n" ;
1164                         }
1165                 }
1166         }
1167         return $hubxml;
1168 }}
1169
1170 /* return atom link elements for salmon endpoints */
1171
1172 if(! function_exists('feed_salmonlinks')) {
1173 function feed_salmonlinks($nick) {
1174
1175         $a = get_app();
1176
1177         $salmon  = '<link rel="salmon" href="' . xmlify($a->get_baseurl() . '/salmon/' . $nick) . '" />' . "\n" ;
1178
1179         // old style links that status.net still needed as of 12/2010 
1180
1181         $salmon .= '  <link rel="http://salmon-protocol.org/ns/salmon-replies" href="' . xmlify($a->get_baseurl() . '/salmon/' . $nick) . '" />' . "\n" ; 
1182         $salmon .= '  <link rel="http://salmon-protocol.org/ns/salmon-mention" href="' . xmlify($a->get_baseurl() . '/salmon/' . $nick) . '" />' . "\n" ; 
1183         return $salmon;
1184 }}
1185
1186 if(! function_exists('get_plink')) {
1187 function get_plink($item) {
1188         $a = get_app(); 
1189         if (x($item,'plink') && ($item['private'] != 1)) {
1190                 return array(
1191                         'href' => $item['plink'],
1192                         'title' => t('link to source'),
1193                 );
1194         } 
1195         else {
1196                 return false;
1197         }
1198 }}
1199
1200 if(! function_exists('unamp')) {
1201 function unamp($s) {
1202         return str_replace('&amp;', '&', $s);
1203 }}
1204
1205
1206
1207
1208 if(! function_exists('lang_selector')) {
1209 function lang_selector() {
1210         global $lang;
1211         
1212         $langs = glob('view/*/strings.php');
1213         
1214         $lang_options = array();
1215         $selected = "";
1216         
1217         if(is_array($langs) && count($langs)) {
1218                 $langs[] = '';
1219                 if(! in_array('view/en/strings.php',$langs))
1220                         $langs[] = 'view/en/';
1221                 asort($langs);
1222                 foreach($langs as $l) {
1223                         if($l == '') {
1224                                 $lang_options[""] = t('default');
1225                                 continue;
1226                         }
1227                         $ll = substr($l,5);
1228                         $ll = substr($ll,0,strrpos($ll,'/'));
1229                         $selected = (($ll === $lang && (x($_SESSION, 'language'))) ? $ll : $selected);
1230                         $lang_options[$ll]=$ll;
1231                 }
1232         }
1233
1234         $tpl = get_markup_template("lang_selector.tpl");        
1235         $o = replace_macros($tpl, array(
1236                 '$title' => t('Select an alternate language'),
1237                 '$langs' => array($lang_options, $selected),
1238                 
1239         ));
1240         return $o;
1241 }}
1242
1243
1244 if(! function_exists('return_bytes')) {
1245 function return_bytes ($size_str) {
1246     switch (substr ($size_str, -1))
1247     {
1248         case 'M': case 'm': return (int)$size_str * 1048576;
1249         case 'K': case 'k': return (int)$size_str * 1024;
1250         case 'G': case 'g': return (int)$size_str * 1073741824;
1251         default: return $size_str;
1252     }
1253 }}
1254
1255 function generate_user_guid() {
1256         $found = true;
1257         do {
1258                 $guid = random_string(16);
1259                 $x = q("SELECT `uid` FROM `user` WHERE `guid` = '%s' LIMIT 1",
1260                         dbesc($guid)
1261                 );
1262                 if(! count($x))
1263                         $found = false;
1264         } while ($found == true );
1265         return $guid;
1266 }
1267
1268
1269
1270 function base64url_encode($s, $strip_padding = false) {
1271
1272         $s = strtr(base64_encode($s),'+/','-_');
1273
1274         if($strip_padding)
1275                 $s = str_replace('=','',$s);
1276
1277         return $s;
1278 }
1279
1280 function base64url_decode($s) {
1281
1282         if(is_array($s)) {
1283                 logger('base64url_decode: illegal input: ' . print_r(debug_backtrace(), true));
1284                 return $s;
1285         }
1286
1287 /*
1288  *  // Placeholder for new rev of salmon which strips base64 padding.
1289  *  // PHP base64_decode handles the un-padded input without requiring this step
1290  *  // Uncomment if you find you need it.
1291  *
1292  *      $l = strlen($s);
1293  *      if(! strpos($s,'=')) {
1294  *              $m = $l % 4;
1295  *              if($m == 2)
1296  *                      $s .= '==';
1297  *              if($m == 3)
1298  *                      $s .= '=';
1299  *      }
1300  *
1301  */
1302
1303         return base64_decode(strtr($s,'-_','+/'));
1304 }
1305
1306
1307 if (!function_exists('str_getcsv')) {
1308     function str_getcsv($input, $delimiter = ',', $enclosure = '"', $escape = '\\', $eol = '\n') {
1309         if (is_string($input) && !empty($input)) {
1310             $output = array();
1311             $tmp    = preg_split("/".$eol."/",$input);
1312             if (is_array($tmp) && !empty($tmp)) {
1313                 while (list($line_num, $line) = each($tmp)) {
1314                     if (preg_match("/".$escape.$enclosure."/",$line)) {
1315                         while ($strlen = strlen($line)) {
1316                             $pos_delimiter       = strpos($line,$delimiter);
1317                             $pos_enclosure_start = strpos($line,$enclosure);
1318                             if (
1319                                 is_int($pos_delimiter) && is_int($pos_enclosure_start)
1320                                 && ($pos_enclosure_start < $pos_delimiter)
1321                                 ) {
1322                                 $enclosed_str = substr($line,1);
1323                                 $pos_enclosure_end = strpos($enclosed_str,$enclosure);
1324                                 $enclosed_str = substr($enclosed_str,0,$pos_enclosure_end);
1325                                 $output[$line_num][] = $enclosed_str;
1326                                 $offset = $pos_enclosure_end+3;
1327                             } else {
1328                                 if (empty($pos_delimiter) && empty($pos_enclosure_start)) {
1329                                     $output[$line_num][] = substr($line,0);
1330                                     $offset = strlen($line);
1331                                 } else {
1332                                     $output[$line_num][] = substr($line,0,$pos_delimiter);
1333                                     $offset = (
1334                                                 !empty($pos_enclosure_start)
1335                                                 && ($pos_enclosure_start < $pos_delimiter)
1336                                                 )
1337                                                 ?$pos_enclosure_start
1338                                                 :$pos_delimiter+1;
1339                                 }
1340                             }
1341                             $line = substr($line,$offset);
1342                         }
1343                     } else {
1344                         $line = preg_split("/".$delimiter."/",$line);
1345    
1346                         /*
1347                          * Validating against pesky extra line breaks creating false rows.
1348                          */
1349                         if (is_array($line) && !empty($line[0])) {
1350                             $output[$line_num] = $line;
1351                         } 
1352                     }
1353                 }
1354                 return $output;
1355             } else {
1356                 return false;
1357             }
1358         } else {
1359             return false;
1360         }
1361     }
1362
1363
1364 function cleardiv() {
1365         return '<div class="clear"></div>';
1366 }
1367
1368
1369 function bb_translate_video($s) {
1370
1371         $matches = null;
1372         $r = preg_match_all("/\[video\](.*?)\[\/video\]/ism",$s,$matches,PREG_SET_ORDER);
1373         if($r) {
1374                 foreach($matches as $mtch) {
1375                         if((stristr($mtch[1],'youtube')) || (stristr($mtch[1],'youtu.be')))
1376                                 $s = str_replace($mtch[0],'[youtube]' . $mtch[1] . '[/youtube]',$s);
1377                         elseif(stristr($mtch[1],'vimeo'))
1378                                 $s = str_replace($mtch[0],'[vimeo]' . $mtch[1] . '[/vimeo]',$s);
1379                 }
1380         }
1381         return $s;      
1382 }
1383
1384 function html2bb_video($s) {
1385
1386         $s = preg_replace('#<object[^>]+>(.*?)https?://www.youtube.com/((?:v|cp)/[A-Za-z0-9\-_=]+)(.*?)</object>#ism',
1387                         '[youtube]$2[/youtube]', $s);
1388
1389         $s = preg_replace('#<iframe[^>](.*?)https?://www.youtube.com/embed/([A-Za-z0-9\-_=]+)(.*?)</iframe>#ism',
1390                         '[youtube]$2[/youtube]', $s);
1391
1392         $s = preg_replace('#<iframe[^>](.*?)https?://player.vimeo.com/video/([0-9]+)(.*?)</iframe>#ism',
1393                         '[vimeo]$2[/vimeo]', $s);
1394
1395         return $s;
1396 }
1397
1398 /**
1399  * apply xmlify() to all values of array $val, recursively
1400  */
1401 function array_xmlify($val){
1402         if (is_bool($val)) return $val?"true":"false";
1403         if (is_array($val)) return array_map('array_xmlify', $val);
1404         return xmlify((string) $val);
1405 }
1406
1407
1408 function reltoabs($text, $base)
1409 {
1410   if (empty($base))
1411     return $text;
1412
1413   $base = rtrim($base,'/');
1414
1415   $base2 = $base . "/";
1416         
1417   // Replace links
1418   $pattern = "/<a([^>]*) href=\"(?!http|https|\/)([^\"]*)\"/";
1419   $replace = "<a\${1} href=\"" . $base2 . "\${2}\"";
1420   $text = preg_replace($pattern, $replace, $text);
1421
1422   $pattern = "/<a([^>]*) href=\"(?!http|https)([^\"]*)\"/";
1423   $replace = "<a\${1} href=\"" . $base . "\${2}\"";
1424   $text = preg_replace($pattern, $replace, $text);
1425
1426   // Replace images
1427   $pattern = "/<img([^>]*) src=\"(?!http|https|\/)([^\"]*)\"/";
1428   $replace = "<img\${1} src=\"" . $base2 . "\${2}\"";
1429   $text = preg_replace($pattern, $replace, $text); 
1430
1431   $pattern = "/<img([^>]*) src=\"(?!http|https)([^\"]*)\"/";
1432   $replace = "<img\${1} src=\"" . $base . "\${2}\"";
1433   $text = preg_replace($pattern, $replace, $text); 
1434
1435
1436   // Done
1437   return $text;
1438 }
1439
1440 function item_post_type($item) {
1441         if(intval($item['event-id']))
1442                 return t('event');
1443         if(strlen($item['resource-id']))
1444                 return t('photo');
1445         if(strlen($item['verb']) && $item['verb'] !== ACTIVITY_POST)
1446                 return t('activity');
1447         if($item['id'] != $item['parent'])
1448                 return t('comment');
1449         return t('post');
1450 }
1451
1452 // post categories and "save to file" use the same item.file table for storage.
1453 // We will differentiate the different uses by wrapping categories in angle brackets
1454 // and save to file categories in square brackets.
1455 // To do this we need to escape these characters if they appear in our tag. 
1456
1457 function file_tag_encode($s) {
1458         return str_replace(array('<','>','[',']'),array('%3c','%3e','%5b','%5d'),$s);
1459 }
1460
1461 function file_tag_decode($s) {
1462         return str_replace(array('%3c','%3e','%5b','%5d'),array('<','>','[',']'),$s);
1463 }
1464
1465 function file_tag_file_query($table,$s,$type = 'file') {
1466
1467         if($type == 'file')
1468                 $str = preg_quote( '[' . str_replace('%','%%',file_tag_encode($s)) . ']' );
1469         else
1470                 $str = preg_quote( '<' . str_replace('%','%%',file_tag_encode($s)) . '>' );
1471         return " AND " . (($table) ? dbesc($table) . '.' : '') . "file regexp '" . dbesc($str) . "' ";
1472 }
1473
1474 // ex. given music,video return <music><video> or [music][video]
1475 function file_tag_list_to_file($list,$type = 'file') {
1476         $tag_list = '';
1477         if(strlen($list)) {
1478                 $list_array = explode(",",$list);
1479                 if($type == 'file') {
1480                         $lbracket = '[';
1481                         $rbracket = ']';
1482                 }
1483                 else {
1484                         $lbracket = '<';
1485                         $rbracket = '>';
1486                 }
1487
1488                 foreach($list_array as $item) {
1489                   if(strlen($item)) {
1490                                 $tag_list .= $lbracket . file_tag_encode(trim($item))  . $rbracket;
1491                         }
1492                 }
1493         }
1494         return $tag_list;
1495 }
1496
1497 // ex. given <music><video>[friends], return music,video or friends
1498 function file_tag_file_to_list($file,$type = 'file') {
1499         $matches = false;
1500         $list = '';
1501         if($type == 'file') {
1502                 $cnt = preg_match_all('/\[(.*?)\]/',$file,$matches,PREG_SET_ORDER);
1503         }
1504         else {
1505                 $cnt = preg_match_all('/<(.*?)>/',$file,$matches,PREG_SET_ORDER);
1506         }
1507         if($cnt) {
1508                 foreach($matches as $mtch) {
1509                         if(strlen($list))
1510                                 $list .= ',';
1511                         $list .= file_tag_decode($mtch[1]);
1512                 }
1513         }
1514
1515         return $list;
1516 }
1517
1518 function file_tag_update_pconfig($uid,$file_old,$file_new,$type = 'file') {
1519         // $file_old - categories previously associated with an item
1520         // $file_new - new list of categories for an item
1521
1522         if(! intval($uid))
1523                 return false;
1524
1525         if($file_old == $file_new)
1526                 return true;
1527
1528         $saved = get_pconfig($uid,'system','filetags');
1529         if(strlen($saved)) {
1530                 if($type == 'file') {
1531                         $lbracket = '[';
1532                         $rbracket = ']';
1533                 }
1534                 else {
1535                         $lbracket = '<';
1536                         $rbracket = '>';
1537                 }
1538
1539                 $filetags_updated = $saved;
1540
1541                 // check for new tags to be added as filetags in pconfig
1542                 $new_tags = array();
1543                 $check_new_tags = explode(",",file_tag_file_to_list($file_new,$type));
1544
1545                 foreach($check_new_tags as $tag) {
1546                         if(! stristr($saved,$lbracket . file_tag_encode($tag) . $rbracket))
1547                                 $new_tags[] = $tag;
1548                 }
1549
1550                 $filetags_updated .= file_tag_list_to_file(implode(",",$new_tags),$type);
1551
1552                 // check for deleted tags to be removed from filetags in pconfig
1553                 $deleted_tags = array();
1554                 $check_deleted_tags = explode(",",file_tag_file_to_list($file_old,$type));
1555
1556                 foreach($check_deleted_tags as $tag) {
1557                         if(! stristr($file_new,$lbracket . file_tag_encode($tag) . $rbracket))
1558                                 $deleted_tags[] = $tag;
1559                 }
1560
1561                 foreach($deleted_tags as $key => $tag) {
1562                         $r = q("select file from item where uid = %d " . file_tag_file_query('item',$tag,$type),
1563                                 intval($uid)
1564                         );
1565
1566                         if(count($r)) {
1567                                 unset($deleted_tags[$key]);
1568                         }
1569                         else {
1570                                 $filetags_updated = str_replace($lbracket . file_tag_encode($tag) . $rbracket,'',$filetags_updated);
1571                         }
1572                 }
1573
1574                 if($saved != $filetags_updated) {
1575                         set_pconfig($uid,'system','filetags', $filetags_updated);
1576                 }
1577                 return true;
1578         }
1579         else
1580                 if(strlen($file_new)) {
1581                         set_pconfig($uid,'system','filetags', $file_new);
1582                 }
1583                 return true;
1584 }
1585
1586 function file_tag_save_file($uid,$item,$file) {
1587         $result = false;
1588         if(! intval($uid))
1589                 return false;
1590         $r = q("select file from item where id = %d and uid = %d limit 1",
1591                 intval($item),
1592                 intval($uid)
1593         );
1594         if(count($r)) {
1595                 if(! stristr($r[0]['file'],'[' . file_tag_encode($file) . ']'))
1596                         q("update item set file = '%s' where id = %d and uid = %d limit 1",
1597                                 dbesc($r[0]['file'] . '[' . file_tag_encode($file) . ']'),
1598                                 intval($item),
1599                                 intval($uid)
1600                         );
1601                 $saved = get_pconfig($uid,'system','filetags');
1602                 if((! strlen($saved)) || (! stristr($saved,'[' . file_tag_encode($file) . ']')))
1603                         set_pconfig($uid,'system','filetags',$saved . '[' . file_tag_encode($file) . ']');
1604                 info( t('Item filed') );
1605         }
1606         return true;
1607 }
1608
1609 function file_tag_unsave_file($uid,$item,$file,$cat = false) {
1610         $result = false;
1611         if(! intval($uid))
1612                 return false;
1613
1614         if($cat == true)
1615                 $pattern = '<' . file_tag_encode($file) . '>' ;
1616         else
1617                 $pattern = '[' . file_tag_encode($file) . ']' ;
1618
1619
1620         $r = q("select file from item where id = %d and uid = %d limit 1",
1621                 intval($item),
1622                 intval($uid)
1623         );
1624         if(! count($r))
1625                 return false;
1626
1627         q("update item set file = '%s' where id = %d and uid = %d limit 1",
1628                 dbesc(str_replace($pattern,'',$r[0]['file'])),
1629                 intval($item),
1630                 intval($uid)
1631         );
1632
1633         $r = q("select file from item where uid = %d and deleted = 0 " . file_tag_file_query('item',$file,(($cat) ? 'category' : 'file')),
1634                 intval($uid)
1635         );
1636
1637         if(! count($r)) {
1638                 $saved = get_pconfig($uid,'system','filetags');
1639                 set_pconfig($uid,'system','filetags',str_replace($pattern,'',$saved));
1640
1641         }
1642         return true;
1643 }
1644
1645 function normalise_openid($s) {
1646         return trim(str_replace(array('http://','https://'),array('',''),$s),'/');
1647 }
1648
1649
1650 function undo_post_tagging($s) {
1651         $matches = null;
1652         $cnt = preg_match_all('/([@#])\[url=(.*?)\](.*?)\[\/url\]/ism',$s,$matches,PREG_SET_ORDER);
1653         if($cnt) {
1654                 foreach($matches as $mtch) {
1655                         $s = str_replace($mtch[0], $mtch[1] . $mtch[3],$s);
1656                 }
1657         }
1658         return $s;
1659 }
1660
1661 function fix_mce_lf($s) {
1662         $s = str_replace("\r\n","\n",$s);
1663 //      $s = str_replace("\n\n","\n",$s);
1664         return $s;
1665 }
1666
1667
1668 function protect_sprintf($s) {
1669         return(str_replace('%','%%',$s));
1670 }
1671
1672
1673 function is_a_date_arg($s) {
1674         $i = intval($s);
1675         if($i > 1900) {
1676                 $y = date('Y');
1677                 if($i <= $y+1 && strpos($s,'-') == 4) {
1678                         $m = intval(substr($s,5));
1679                         if($m > 0 && $m <= 12)
1680                                 return true;
1681                 }
1682         }
1683         return false;
1684 }