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