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