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