]> git.mxchange.org Git - friendica.git/blob - include/text.php
63846fb10b11562799cf7b792b686e295c7b9414
[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         if ($a->module == 'install') return;
432         
433         $debugging = get_config('system','debugging');
434         $loglevel  = intval(get_config('system','loglevel'));
435         $logfile   = get_config('system','logfile');
436
437         if((! $debugging) || (! $logfile) || ($level > $loglevel))
438                 return;
439         
440         @file_put_contents($logfile, datetime_convert() . ':' . session_id() . ' ' . $msg . "\n", FILE_APPEND);
441         return;
442 }}
443
444
445 if(! function_exists('activity_match')) {
446 function activity_match($haystack,$needle) {
447         if(($haystack === $needle) || ((basename($needle) === $haystack) && strstr($needle,NAMESPACE_ACTIVITY_SCHEMA)))
448                 return true;
449         return false;
450 }}
451
452
453 // Pull out all #hashtags and @person tags from $s;
454 // We also get @person@domain.com - which would make 
455 // the regex quite complicated as tags can also
456 // end a sentence. So we'll run through our results
457 // and strip the period from any tags which end with one.
458 // Returns array of tags found, or empty array.
459
460
461 if(! function_exists('get_tags')) {
462 function get_tags($s) {
463         $ret = array();
464
465         // ignore anything in a code block
466
467         $s = preg_replace('/\[code\](.*?)\[\/code\]/sm','',$s);
468
469         // Match full names against @tags including the space between first and last
470         // We will look these up afterward to see if they are full names or not recognisable.
471
472         if(preg_match_all('/(@[^ \x0D\x0A,:?]+ [^ \x0D\x0A@,:?]+)([ \x0D\x0A@,:?]|$)/',$s,$match)) {
473                 foreach($match[1] as $mtch) {
474                         if(strstr($mtch,"]")) {
475                                 // we might be inside a bbcode color tag - leave it alone
476                                 continue;
477                         }
478                         if(substr($mtch,-1,1) === '.')
479                                 $ret[] = substr($mtch,0,-1);
480                         else
481                                 $ret[] = $mtch;
482                 }
483         }
484
485         // Otherwise pull out single word tags. These can be @nickname, @first_last
486         // and #hash tags.
487
488         if(preg_match_all('/([@#][^ \x0D\x0A,;:?]+)([ \x0D\x0A,;:?]|$)/',$s,$match)) {
489                 foreach($match[1] as $mtch) {
490                         if(strstr($mtch,"]")) {
491                                 // we might be inside a bbcode color tag - leave it alone
492                                 continue;
493                         }
494                         if(substr($mtch,-1,1) === '.')
495                                 $mtch = substr($mtch,0,-1);
496                         // ignore strictly numeric tags like #1
497                         if((strpos($mtch,'#') === 0) && ctype_digit(substr($mtch,1)))
498                                 continue;
499                         // try not to catch url fragments
500                         if(strpos($s,$mtch) && preg_match('/[a-zA-z0-9\/]/',substr($s,strpos($s,$mtch)-1,1)))
501                                 continue;
502                         $ret[] = $mtch;
503                 }
504         }
505         return $ret;
506 }}
507
508
509 // quick and dirty quoted_printable encoding
510
511 if(! function_exists('qp')) {
512 function qp($s) {
513 return str_replace ("%","=",rawurlencode($s));
514 }} 
515
516
517
518 if(! function_exists('get_mentions')) {
519 function get_mentions($item) {
520         $o = '';
521         if(! strlen($item['tag']))
522                 return $o;
523
524         $arr = explode(',',$item['tag']);
525         foreach($arr as $x) {
526                 $matches = null;
527                 if(preg_match('/@\[url=([^\]]*)\]/',$x,$matches)) {
528                         $o .= "\t\t" . '<link rel="mentioned" href="' . $matches[1] . '" />' . "\r\n";
529                         $o .= "\t\t" . '<link rel="ostatus:attention" href="' . $matches[1] . '" />' . "\r\n";
530                 }
531         }
532         return $o;
533 }}
534
535 if(! function_exists('contact_block')) {
536 function contact_block() {
537         $o = '';
538         $a = get_app();
539
540         $shown = get_pconfig($a->profile['uid'],'system','display_friend_count');
541         if($shown === false)
542                 $shown = 24;
543         if($shown == 0)
544                 return;
545
546         if((! is_array($a->profile)) || ($a->profile['hide-friends']))
547                 return $o;
548         $r = q("SELECT COUNT(*) AS `total` FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 and `pending` = 0 AND `hidden` = 0",
549                         intval($a->profile['uid'])
550         );
551         if(count($r)) {
552                 $total = intval($r[0]['total']);
553         }
554         if(! $total) {
555                 $contacts = t('No contacts');
556                 $micropro = Null;
557                 
558         } else {
559                 $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",
560                                 intval($a->profile['uid']),
561                                 intval($shown)
562                 );
563                 if(count($r)) {
564                         $contacts = sprintf( tt('%d Contact','%d Contacts', $total),$total);
565                         $micropro = Array();
566                         foreach($r as $rr) {
567                                 $micropro[] = micropro($rr,true,'mpfriend');
568                         }
569                 }
570         }
571         
572         $tpl = get_markup_template('contact_block.tpl');
573         $o = replace_macros($tpl, array(
574                 '$contacts' => $contacts,
575                 '$nickname' => $a->profile['nickname'],
576                 '$viewcontacts' => t('View Contacts'),
577                 '$micropro' => $micropro,
578         ));
579
580         $arr = array('contacts' => $r, 'output' => $o);
581
582         call_hooks('contact_block_end', $arr);
583         return $o;
584
585 }}
586
587 if(! function_exists('micropro')) {
588 function micropro($contact, $redirect = false, $class = '', $textmode = false) {
589
590         if($class)
591                 $class = ' ' . $class;
592
593         $url = $contact['url'];
594         $sparkle = '';
595         $redir = false;
596
597         if($redirect) {
598                 $a = get_app();
599                 $redirect_url = $a->get_baseurl() . '/redir/' . $contact['id'];
600                 if(local_user() && ($contact['uid'] == local_user()) && ($contact['network'] === 'dfrn')) {
601                         $redir = true;
602                         $url = $redirect_url;
603                         $sparkle = ' sparkle';
604                 }
605         }
606         $click = ((x($contact,'click')) ? ' onclick="' . $contact['click'] . '" ' : '');
607         if($click)
608                 $url = '';
609         if($textmode) {
610                 return '<div class="contact-block-textdiv' . $class . '"><a class="contact-block-link' . $class . $sparkle 
611                         . (($click) ? ' fakelink' : '') . '" '
612                         . (($redir) ? ' target="redir" ' : '')
613                         . (($url) ? ' href="' . $url . '"' : '') . $click
614                         . '" title="' . $contact['name'] . ' [' . $contact['url'] . ']" alt="' . $contact['name'] 
615                         . '" >'. $contact['name'] . '</a></div>' . "\r\n";
616         }
617         else {
618                 return '<div class="contact-block-div' . $class . '"><a class="contact-block-link' . $class . $sparkle 
619                         . (($click) ? ' fakelink' : '') . '" '
620                         . (($redir) ? ' target="redir" ' : '')
621                         . (($url) ? ' href="' . $url . '"' : '') . $click . ' ><img class="contact-block-img' . $class . $sparkle . '" src="' 
622                         . $contact['micro'] . '" title="' . $contact['name'] . ' [' . $contact['url'] . ']" alt="' . $contact['name'] 
623                         . '" /></a></div>' . "\r\n";
624         }
625 }}
626
627
628
629 if(! function_exists('search')) {
630 function search($s,$id='search-box',$url='/search',$save = false) {
631         $a = get_app();
632         $o  = '<div id="' . $id . '">';
633         $o .= '<form action="' . $a->get_baseurl() . $url . '" method="get" >';
634         $o .= '<input type="text" name="search" id="search-text" value="' . $s .'" />';
635         $o .= '<input type="submit" name="submit" id="search-submit" value="' . t('Search') . '" />'; 
636         if($save)
637                 $o .= '<input type="submit" name="save" id="search-save" value="' . t('Save') . '" />'; 
638         $o .= '</form></div>';
639         return $o;
640 }}
641
642 if(! function_exists('valid_email')) {
643 function valid_email($x){
644         if(preg_match('/^[_a-zA-Z0-9\-\+]+(\.[_a-zA-Z0-9\-\+]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)+$/',$x))
645                 return true;
646         return false;
647 }}
648
649
650 /**
651  *
652  * Function: linkify
653  *
654  * Replace naked text hyperlink with HTML formatted hyperlink
655  *
656  */
657
658 if(! function_exists('linkify')) {
659 function linkify($s) {
660         $s = preg_replace("/(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\'\%\$\!\+]*)/", ' <a href="$1" target="external-link">$1</a>', $s);
661         $s = preg_replace("/\<(.*?)(src|href)=(.*?)\&amp\;(.*?)\>/ism",'<$1$2=$3&$4>',$s);
662         return($s);
663 }}
664
665
666 /**
667  * 
668  * Function: smilies
669  *
670  * Description:
671  * Replaces text emoticons with graphical images
672  *
673  * @Parameter: string $s
674  *
675  * Returns string
676  */
677
678 if(! function_exists('smilies')) {
679 function smilies($s) {
680         $a = get_app();
681
682         $s = str_replace(
683         array( '&lt;3', '&lt;/3', '&lt;\\3', ':-)', ':)', ';-)', ':-(', ':(', ':-P', ':P', ':-"', ':-&quot;', ':-x', ':-X', ':-D', '8-|', '8-O', '\\o/', 'o.O', 'O.o', '\\.../', '\\ooo/', 
684  ':beer', ':homebrew', ':coffee', 
685                 '~friendika', '~friendica', 'Diaspora*' ),
686         array(
687                 '<img src="' . $a->get_baseurl() . '/images/smiley-heart.gif" alt="<3" />',
688                 '<img src="' . $a->get_baseurl() . '/images/smiley-brokenheart.gif" alt="</3" />',
689                 '<img src="' . $a->get_baseurl() . '/images/smiley-brokenheart.gif" alt="<\\3" />',
690                 '<img src="' . $a->get_baseurl() . '/images/smiley-smile.gif" alt=":-)" />',
691                 '<img src="' . $a->get_baseurl() . '/images/smiley-smile.gif" alt=":)" />',
692                 '<img src="' . $a->get_baseurl() . '/images/smiley-wink.gif" alt=";-)" />',
693                 '<img src="' . $a->get_baseurl() . '/images/smiley-frown.gif" alt=":-(" />',
694                 '<img src="' . $a->get_baseurl() . '/images/smiley-frown.gif" alt=":(" />',
695                 '<img src="' . $a->get_baseurl() . '/images/smiley-tongue-out.gif" alt=":-P" />',
696                 '<img src="' . $a->get_baseurl() . '/images/smiley-tongue-out.gif" alt=":P" />',
697                 '<img src="' . $a->get_baseurl() . '/images/smiley-kiss.gif" alt=":-\"" />',
698                 '<img src="' . $a->get_baseurl() . '/images/smiley-kiss.gif" alt=":-\"" />',
699                 '<img src="' . $a->get_baseurl() . '/images/smiley-kiss.gif" alt=":-x" />',
700                 '<img src="' . $a->get_baseurl() . '/images/smiley-kiss.gif" alt=":-X" />',
701                 '<img src="' . $a->get_baseurl() . '/images/smiley-laughing.gif" alt=":-D" />',
702                 '<img src="' . $a->get_baseurl() . '/images/smiley-surprised.gif" alt="8-|" />',
703                 '<img src="' . $a->get_baseurl() . '/images/smiley-surprised.gif" alt="8-O" />',
704                 '<img src="' . $a->get_baseurl() . '/images/smiley-thumbsup.gif" alt="\\o/" />',
705                 '<img src="' . $a->get_baseurl() . '/images/smiley-Oo.gif" alt="o.O" />',
706                 '<img src="' . $a->get_baseurl() . '/images/smiley-Oo.gif" alt="O.o" />',
707                 '<img src="' . $a->get_baseurl() . '/images/smiley-shaka.gif" alt="\\.../" />',
708                 '<img src="' . $a->get_baseurl() . '/images/smiley-shaka.gif" alt="\\ooo/" />',
709                 '<img src="' . $a->get_baseurl() . '/images/beer_mug.gif" alt=":beer" />',
710                 '<img src="' . $a->get_baseurl() . '/images/beer_mug.gif" alt=":homebrew" />',
711                 '<img src="' . $a->get_baseurl() . '/images/coffee.gif" alt=":coffee" />',
712
713                 '<a href="http://project.friendika.com">~friendika <img src="' . $a->get_baseurl() . '/images/friendika-16.png" alt="~friendika" /></a>',
714                 '<a href="http://friendica.com">~friendica <img src="' . $a->get_baseurl() . '/images/friendika-16.png" alt="~friendica" /></a>',
715                 '<a href="http://diasporafoundation.org">Diaspora<img src="' . $a->get_baseurl() . '/images/diaspora.png" alt="Diaspora*" /></a>',
716
717         ), $s);
718
719         call_hooks('smilie', $s);
720         return $s;
721
722 }}
723
724
725
726 if(! function_exists('day_translate')) {
727 function day_translate($s) {
728         $ret = str_replace(array('Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'),
729                 array( t('Monday'), t('Tuesday'), t('Wednesday'), t('Thursday'), t('Friday'), t('Saturday'), t('Sunday')),
730                 $s);
731
732         $ret = str_replace(array('January','February','March','April','May','June','July','August','September','October','November','December'),
733                 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')),
734                 $ret);
735
736         return $ret;
737 }}
738
739
740 if(! function_exists('normalise_link')) {
741 function normalise_link($url) {
742         $ret = str_replace(array('https:','//www.'), array('http:','//'), $url);
743         return(rtrim($ret,'/'));
744 }}
745
746 /**
747  *
748  * Compare two URLs to see if they are the same, but ignore
749  * slight but hopefully insignificant differences such as if one 
750  * is https and the other isn't, or if one is www.something and 
751  * the other isn't - and also ignore case differences.
752  *
753  * Return true if the URLs match, otherwise false.
754  *
755  */
756
757 if(! function_exists('link_compare')) {
758 function link_compare($a,$b) {
759         if(strcasecmp(normalise_link($a),normalise_link($b)) === 0)
760                 return true;
761         return false;
762 }}
763
764 // Given an item array, convert the body element from bbcode to html and add smilie icons.
765 // If attach is true, also add icons for item attachments
766
767
768 if(! function_exists('prepare_body')) {
769 function prepare_body($item,$attach = false) {
770
771         call_hooks('prepare_body_init', $item); 
772
773         $s = prepare_text($item['body']);
774
775         $prep_arr = array('item' => $item, 'html' => $s);
776         call_hooks('prepare_body', $prep_arr);
777         $s = $prep_arr['html'];
778
779         if(! $attach)
780                 return $s;
781
782         $arr = explode(',',$item['attach']);
783         if(count($arr)) {
784                 $s .= '<div class="body-attach">';
785                 foreach($arr as $r) {
786                         $matches = false;
787                         $icon = '';
788                         $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"\[\/attach\]|',$r,$matches);
789                         if($cnt) {
790                                 $icontype = strtolower(substr($matches[3],0,strpos($matches[3],'/')));
791                                 switch($icontype) {
792                                         case 'video':
793                                         case 'audio':
794                                         case 'image':
795                                         case 'text':
796                                                 $icon = '<div class="attachtype type-' . $icontype . '"></div>';
797                                                 break;
798                                         default:
799                                                 $icon = '<div class="attachtype type-unkn"></div>';
800                                                 break;
801                                 }
802                                 $title = ((strlen(trim($matches[4]))) ? escape_tags(trim($matches[4])) : escape_tags($matches[1]));
803                                 $title .= ' ' . $matches[2] . ' ' . t('bytes');
804
805                                 $s .= '<a href="' . strip_tags($matches[1]) . '" title="' . $title . '" class="attachlink" target="external-link" >' . $icon . '</a>';
806                         }
807                 }
808                 $s .= '<div class="clear"></div></div>';
809         }
810
811
812         $prep_arr = array('item' => $item, 'html' => $s);
813         call_hooks('prepare_body_final', $prep_arr);
814         return $prep_arr['html'];
815 }}
816
817
818 // Given a text string, convert from bbcode to html and add smilie icons.
819
820 if(! function_exists('prepare_text')) {
821 function prepare_text($text) {
822
823         require_once('include/bbcode.php');
824
825         $s = smilies(bbcode($text));
826
827         return $s;
828 }}
829
830
831 /**
832  * return atom link elements for all of our hubs
833  */
834
835 if(! function_exists('feed_hublinks')) {
836 function feed_hublinks() {
837
838         $hub = get_config('system','huburl');
839
840         $hubxml = '';
841         if(strlen($hub)) {
842                 $hubs = explode(',', $hub);
843                 if(count($hubs)) {
844                         foreach($hubs as $h) {
845                                 $h = trim($h);
846                                 if(! strlen($h))
847                                         continue;
848                                 $hubxml .= '<link rel="hub" href="' . xmlify($h) . '" />' . "\n" ;
849                         }
850                 }
851         }
852         return $hubxml;
853 }}
854
855 /* return atom link elements for salmon endpoints */
856
857 if(! function_exists('feed_salmonlinks')) {
858 function feed_salmonlinks($nick) {
859
860         $a = get_app();
861
862         $salmon  = '<link rel="salmon" href="' . xmlify($a->get_baseurl() . '/salmon/' . $nick) . '" />' . "\n" ;
863
864         // old style links that status.net still needed as of 12/2010 
865
866         $salmon .= '  <link rel="http://salmon-protocol.org/ns/salmon-replies" href="' . xmlify($a->get_baseurl() . '/salmon/' . $nick) . '" />' . "\n" ; 
867         $salmon .= '  <link rel="http://salmon-protocol.org/ns/salmon-mention" href="' . xmlify($a->get_baseurl() . '/salmon/' . $nick) . '" />' . "\n" ; 
868         return $salmon;
869 }}
870
871 if(! function_exists('get_plink')) {
872 function get_plink($item) {
873         $a = get_app(); 
874         if (x($item,'plink') && (! $item['private'])){
875                 return array(
876                         'href' => $item['plink'],
877                         'title' => t('link to source'),
878                 );
879         } else {
880                 return false;
881         }
882 }}
883
884 if(! function_exists('unamp')) {
885 function unamp($s) {
886         return str_replace('&amp;', '&', $s);
887 }}
888
889
890
891
892 if(! function_exists('lang_selector')) {
893 function lang_selector() {
894         global $lang;
895         $o = '<div id="lang-select-icon" class="icon language" title="' . t('Select an alternate language') . '" onclick="openClose(\'language-selector\');" ></div>';
896         $o .= '<div id="language-selector" style="display: none;" >';
897         $o .= '<form action="#" method="post" ><select name="system_language" onchange="this.form.submit();" >';
898         $langs = glob('view/*/strings.php');
899         if(is_array($langs) && count($langs)) {
900                 $langs[] = '';
901                 if(! in_array('view/en/strings.php',$langs))
902                         $langs[] = 'view/en/';
903                 asort($langs);
904                 foreach($langs as $l) {
905                         if($l == '') {
906                                 $default_selected = ((! x($_SESSION,'language')) ? ' selected="selected" ' : '');
907                                 $o .= '<option value="" ' . $default_selected . '>' . t('default') . '</option>';
908                                 continue;
909                         }
910                         $ll = substr($l,5);
911                         $ll = substr($ll,0,strrpos($ll,'/'));
912                         $selected = (($ll === $lang && (x($_SESSION['language']))) ? ' selected="selected" ' : '');
913                         $o .= '<option value="' . $ll . '"' . $selected . '>' . $ll . '</option>';
914                 }
915         }
916         $o .= '</select></form></div>';
917         return $o;
918 }}
919
920
921 if(! function_exists('return_bytes')) {
922 function return_bytes ($size_str) {
923     switch (substr ($size_str, -1))
924     {
925         case 'M': case 'm': return (int)$size_str * 1048576;
926         case 'K': case 'k': return (int)$size_str * 1024;
927         case 'G': case 'g': return (int)$size_str * 1073741824;
928         default: return $size_str;
929     }
930 }}
931
932 function generate_user_guid() {
933         $found = true;
934         do {
935                 $guid = random_string(16);
936                 $x = q("SELECT `uid` FROM `user` WHERE `guid` = '%s' LIMIT 1",
937                         dbesc($guid)
938                 );
939                 if(! count($x))
940                         $found = false;
941         } while ($found == true );
942         return $guid;
943 }
944
945
946
947 function base64url_encode($s, $strip_padding = false) {
948
949         $s = strtr(base64_encode($s),'+/','-_');
950
951         if($strip_padding)
952                 $s = str_replace('=','',$s);
953
954         return $s;
955 }
956
957 function base64url_decode($s) {
958
959         if(is_array($s)) {
960                 logger('base64url_decode: illegal input: ' . print_r(debug_backtrace(), true));
961                 return $s;
962         }
963
964 /*
965  *  // Placeholder for new rev of salmon which strips base64 padding.
966  *  // PHP base64_decode handles the un-padded input without requiring this step
967  *  // Uncomment if you find you need it.
968  *
969  *      $l = strlen($s);
970  *      if(! strpos($s,'=')) {
971  *              $m = $l % 4;
972  *              if($m == 2)
973  *                      $s .= '==';
974  *              if($m == 3)
975  *                      $s .= '=';
976  *      }
977  *
978  */
979
980         return base64_decode(strtr($s,'-_','+/'));
981 }
982
983
984 if (!function_exists('str_getcsv')) {
985     function str_getcsv($input, $delimiter = ',', $enclosure = '"', $escape = '\\', $eol = '\n') {
986         if (is_string($input) && !empty($input)) {
987             $output = array();
988             $tmp    = preg_split("/".$eol."/",$input);
989             if (is_array($tmp) && !empty($tmp)) {
990                 while (list($line_num, $line) = each($tmp)) {
991                     if (preg_match("/".$escape.$enclosure."/",$line)) {
992                         while ($strlen = strlen($line)) {
993                             $pos_delimiter       = strpos($line,$delimiter);
994                             $pos_enclosure_start = strpos($line,$enclosure);
995                             if (
996                                 is_int($pos_delimiter) && is_int($pos_enclosure_start)
997                                 && ($pos_enclosure_start < $pos_delimiter)
998                                 ) {
999                                 $enclosed_str = substr($line,1);
1000                                 $pos_enclosure_end = strpos($enclosed_str,$enclosure);
1001                                 $enclosed_str = substr($enclosed_str,0,$pos_enclosure_end);
1002                                 $output[$line_num][] = $enclosed_str;
1003                                 $offset = $pos_enclosure_end+3;
1004                             } else {
1005                                 if (empty($pos_delimiter) && empty($pos_enclosure_start)) {
1006                                     $output[$line_num][] = substr($line,0);
1007                                     $offset = strlen($line);
1008                                 } else {
1009                                     $output[$line_num][] = substr($line,0,$pos_delimiter);
1010                                     $offset = (
1011                                                 !empty($pos_enclosure_start)
1012                                                 && ($pos_enclosure_start < $pos_delimiter)
1013                                                 )
1014                                                 ?$pos_enclosure_start
1015                                                 :$pos_delimiter+1;
1016                                 }
1017                             }
1018                             $line = substr($line,$offset);
1019                         }
1020                     } else {
1021                         $line = preg_split("/".$delimiter."/",$line);
1022    
1023                         /*
1024                          * Validating against pesky extra line breaks creating false rows.
1025                          */
1026                         if (is_array($line) && !empty($line[0])) {
1027                             $output[$line_num] = $line;
1028                         } 
1029                     }
1030                 }
1031                 return $output;
1032             } else {
1033                 return false;
1034             }
1035         } else {
1036             return false;
1037         }
1038     }
1039
1040
1041 function cleardiv() {
1042         return '<div class="clear"></div>';
1043 }
1044
1045
1046 function bb_translate_video($s) {
1047
1048         $matches = null;
1049         $r = preg_match_all("/\[video\](.*?)\[\/video\]/ism",$s,$matches,PREG_SET_ORDER);
1050         if($r) {
1051                 foreach($matches as $mtch) {
1052                         if((stristr($mtch[1],'youtube')) || (stristr($mtch[1],'youtu.be')))
1053                                 $s = str_replace($mtch[0],'[youtube]' . $mtch[1] . '[/youtube]',$s);
1054                         elseif(stristr($mtch[1],'vimeo'))
1055                                 $s = str_replace($mtch[0],'[vimeo]' . $mtch[1] . '[/vimeo]',$s);
1056                 }
1057         }
1058         return $s;      
1059 }
1060
1061 function html2bb_video($s) {
1062
1063         $s = preg_replace('#<object[^>]+>(.*?)https+://www.youtube.com/((?:v|cp)/[A-Za-z0-9\-_=]+)(.*?)</object>#ism',
1064                         '[youtube]$2[/youtube]', $s);
1065
1066         $s = preg_replace('#<iframe[^>](.*?)https+://www.youtube.com/embed/([A-Za-z0-9\-_=]+)(.*?)</iframe>#ism',
1067                         '[youtube]$2[/youtube]', $s);
1068
1069         $s = preg_replace('#<iframe[^>](.*?)https+://player.vimeo.com/video/([0-9]+)(.*?)</iframe>#ism',
1070                         '[vimeo]$2[/vimeo]', $s);
1071
1072         return $s;
1073 }
1074
1075 /**
1076  * apply xmlify() to all values of array $val, recursively
1077  */
1078 function array_xmlify($val){
1079         if (is_bool($val)) return $val?"true":"false";
1080         if (is_array($val)) return array_map('array_xmlify', $val);
1081         return xmlify((string) $val);
1082 }
1083
1084
1085 function reltoabs($text, $base)
1086 {
1087   if (empty($base))
1088     return $text;
1089
1090   $base = rtrim($base,'/');
1091
1092   $base2 = $base . "/";
1093         
1094   // Replace links
1095   $pattern = "/<a([^>]*) href=\"(?!http|https|\/)([^\"]*)\"/";
1096   $replace = "<a\${1} href=\"" . $base2 . "\${2}\"";
1097   $text = preg_replace($pattern, $replace, $text);
1098
1099   $pattern = "/<a([^>]*) href=\"(?!http|https)([^\"]*)\"/";
1100   $replace = "<a\${1} href=\"" . $base . "\${2}\"";
1101   $text = preg_replace($pattern, $replace, $text);
1102
1103   // Replace images
1104   $pattern = "/<img([^>]*) src=\"(?!http|https|\/)([^\"]*)\"/";
1105   $replace = "<img\${1} src=\"" . $base2 . "\${2}\"";
1106   $text = preg_replace($pattern, $replace, $text); 
1107
1108   $pattern = "/<img([^>]*) src=\"(?!http|https)([^\"]*)\"/";
1109   $replace = "<img\${1} src=\"" . $base . "\${2}\"";
1110   $text = preg_replace($pattern, $replace, $text); 
1111
1112
1113   // Done
1114   return $text;
1115 }
1116