]> git.mxchange.org Git - friendica.git/blob - include/text.php
stuff
[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(! ctype_xdigit($s)) {
199                 logger('hex2bin: illegal input: ' . print_r(debug_backtrace(), true));
200                 return($s);
201         }
202
203         return(pack("H*",$s));
204 }}
205
206 // Automatic pagination.
207 // To use, get the count of total items.
208 // Then call $a->set_pager_total($number_items);
209 // Optionally call $a->set_pager_itemspage($n) to the number of items to display on each page
210 // Then call paginate($a) after the end of the display loop to insert the pager block on the page
211 // (assuming there are enough items to paginate).
212 // When using with SQL, the setting LIMIT %d, %d => $a->pager['start'],$a->pager['itemspage']
213 // will limit the results to the correct items for the current page. 
214 // The actual page handling is then accomplished at the application layer. 
215
216 if(! function_exists('paginate')) {
217 function paginate(&$a) {
218         $o = '';
219         $stripped = preg_replace('/(&page=[0-9]*)/','',$a->query_string);
220         $stripped = str_replace('q=','',$stripped);
221         $stripped = trim($stripped,'/');
222         $pagenum = $a->pager['page'];
223         $url = $a->get_baseurl() . '/' . $stripped;
224
225
226           if($a->pager['total'] > $a->pager['itemspage']) {
227                 $o .= '<div class="pager">';
228                 if($a->pager['page'] != 1)
229                         $o .= '<span class="pager_prev">'."<a href=\"$url".'&page='.($a->pager['page'] - 1).'">' . t('prev') . '</a></span> ';
230
231                 $o .=  "<span class=\"pager_first\"><a href=\"$url"."&page=1\">" . t('first') . "</a></span> ";
232
233                 $numpages = $a->pager['total'] / $a->pager['itemspage'];
234
235                         $numstart = 1;
236                 $numstop = $numpages;
237
238                 if($numpages > 14) {
239                         $numstart = (($pagenum > 7) ? ($pagenum - 7) : 1);
240                         $numstop = (($pagenum > ($numpages - 7)) ? $numpages : ($numstart + 14));
241                 }
242    
243                 for($i = $numstart; $i <= $numstop; $i++){
244                         if($i == $a->pager['page'])
245                                 $o .= '<span class="pager_current">'.(($i < 10) ? '&nbsp;'.$i : $i);
246                         else
247                                 $o .= "<span class=\"pager_n\"><a href=\"$url"."&page=$i\">".(($i < 10) ? '&nbsp;'.$i : $i)."</a>";
248                         $o .= '</span> ';
249                 }
250
251                 if(($a->pager['total'] % $a->pager['itemspage']) != 0) {
252                         if($i == $a->pager['page'])
253                                 $o .= '<span class="pager_current">'.(($i < 10) ? '&nbsp;'.$i : $i);
254                         else
255                                 $o .= "<span class=\"pager_n\"><a href=\"$url"."&page=$i\">".(($i < 10) ? '&nbsp;'.$i : $i)."</a>";
256                         $o .= '</span> ';
257                 }
258
259                 $lastpage = (($numpages > intval($numpages)) ? intval($numpages)+1 : $numpages);
260                 $o .= "<span class=\"pager_last\"><a href=\"$url"."&page=$lastpage\">" . t('last') . "</a></span> ";
261
262                 if(($a->pager['total'] - ($a->pager['itemspage'] * $a->pager['page'])) > 0)
263                         $o .= '<span class="pager_next">'."<a href=\"$url"."&page=".($a->pager['page'] + 1).'">' . t('next') . '</a></span>';
264                 $o .= '</div>'."\r\n";
265         }
266         return $o;
267 }}
268
269 // Turn user/group ACLs stored as angle bracketed text into arrays
270
271 if(! function_exists('expand_acl')) {
272 function expand_acl($s) {
273         // turn string array of angle-bracketed elements into numeric array
274         // e.g. "<1><2><3>" => array(1,2,3);
275         $ret = array();
276
277         if(strlen($s)) {
278                 $t = str_replace('<','',$s);
279                 $a = explode('>',$t);
280                 foreach($a as $aa) {
281                         if(intval($aa))
282                                 $ret[] = intval($aa);
283                 }
284         }
285         return $ret;
286 }}              
287
288 // Used to wrap ACL elements in angle brackets for storage 
289
290 if(! function_exists('sanitise_acl')) {
291 function sanitise_acl(&$item) {
292         if(intval($item))
293                 $item = '<' . intval(notags(trim($item))) . '>';
294         else
295                 unset($item);
296 }}
297
298
299 // Convert an ACL array to a storable string
300
301 if(! function_exists('perms2str')) {
302 function perms2str($p) {
303         $ret = '';
304         $tmp = $p;
305         if(is_array($tmp)) {
306                 array_walk($tmp,'sanitise_acl');
307                 $ret = implode('',$tmp);
308         }
309         return $ret;
310 }}
311
312 // generate a guaranteed unique (for this domain) item ID for ATOM
313 // safe from birthday paradox
314
315 if(! function_exists('item_new_uri')) {
316 function item_new_uri($hostname,$uid) {
317
318         do {
319                 $dups = false;
320                 $hash = random_string();
321
322                 $uri = "urn:X-dfrn:" . $hostname . ':' . $uid . ':' . $hash;
323
324                 $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' LIMIT 1",
325                         dbesc($uri));
326                 if(count($r))
327                         $dups = true;
328         } while($dups == true);
329         return $uri;
330 }}
331
332 // Generate a guaranteed unique photo ID.
333 // safe from birthday paradox
334
335 if(! function_exists('photo_new_resource')) {
336 function photo_new_resource() {
337
338         do {
339                 $found = false;
340                 $resource = hash('md5',uniqid(mt_rand(),true));
341                 $r = q("SELECT `id` FROM `photo` WHERE `resource-id` = '%s' LIMIT 1",
342                         dbesc($resource)
343                 );
344                 if(count($r))
345                         $found = true;
346         } while($found == true);
347         return $resource;
348 }}
349
350
351 // wrapper to load a view template, checking for alternate
352 // languages before falling back to the default
353
354 // obsolete, deprecated.
355
356 if(! function_exists('load_view_file')) {
357 function load_view_file($s) {
358         global $lang, $a;
359         if(! isset($lang))
360                 $lang = 'en';
361         $b = basename($s);
362         $d = dirname($s);
363         if(file_exists("$d/$lang/$b"))
364                 return file_get_contents("$d/$lang/$b");
365         
366         $theme = current_theme();
367         
368         if(file_exists("$d/theme/$theme/$b"))
369                 return file_get_contents("$d/theme/$theme/$b");
370                         
371         return file_get_contents($s);
372 }}
373
374 if(! function_exists('get_intltext_template')) {
375 function get_intltext_template($s) {
376         global $lang;
377
378         if(! isset($lang))
379                 $lang = 'en';
380
381         if(file_exists("view/$lang/$s"))
382                 return file_get_contents("view/$lang/$s");
383         elseif(file_exists("view/en/$s"))
384                 return file_get_contents("view/en/$s");
385         else
386                 return file_get_contents("view/$s");
387 }}
388
389 if(! function_exists('get_markup_template')) {
390 function get_markup_template($s) {
391         $a=get_app();
392         $theme = current_theme();
393         
394         if(file_exists("view/theme/$theme/$s"))
395                 return file_get_contents("view/theme/$theme/$s");
396         elseif (x($a->theme_info,"extends") && file_exists("view/theme/".$a->theme_info["extends"]."/$s"))
397                 return file_get_contents("view/theme/".$a->theme_info["extends"]."/$s");
398         else
399                 return file_get_contents("view/$s");
400
401 }}
402
403
404
405
406
407 // for html,xml parsing - let's say you've got
408 // an attribute foobar="class1 class2 class3"
409 // and you want to find out if it contains 'class3'.
410 // you can't use a normal sub string search because you
411 // might match 'notclass3' and a regex to do the job is 
412 // possible but a bit complicated. 
413 // pass the attribute string as $attr and the attribute you 
414 // are looking for as $s - returns true if found, otherwise false
415
416 if(! function_exists('attribute_contains')) {
417 function attribute_contains($attr,$s) {
418         $a = explode(' ', $attr);
419         if(count($a) && in_array($s,$a))
420                 return true;
421         return false;
422 }}
423
424 if(! function_exists('logger')) {
425 function logger($msg,$level = 0) {
426         $debugging = get_config('system','debugging');
427         $loglevel  = intval(get_config('system','loglevel'));
428         $logfile   = get_config('system','logfile');
429
430         if((! $debugging) || (! $logfile) || ($level > $loglevel))
431                 return;
432         
433         @file_put_contents($logfile, datetime_convert() . ':' . session_id() . ' ' . $msg . "\n", FILE_APPEND);
434         return;
435 }}
436
437
438 if(! function_exists('activity_match')) {
439 function activity_match($haystack,$needle) {
440         if(($haystack === $needle) || ((basename($needle) === $haystack) && strstr($needle,NAMESPACE_ACTIVITY_SCHEMA)))
441                 return true;
442         return false;
443 }}
444
445
446 // Pull out all #hashtags and @person tags from $s;
447 // We also get @person@domain.com - which would make 
448 // the regex quite complicated as tags can also
449 // end a sentence. So we'll run through our results
450 // and strip the period from any tags which end with one.
451 // Returns array of tags found, or empty array.
452
453
454 if(! function_exists('get_tags')) {
455 function get_tags($s) {
456         $ret = array();
457
458         // ignore anything in a code block
459
460         $s = preg_replace('/\[code\](.*?)\[\/code\]/sm','',$s);
461
462         // Match full names against @tags including the space between first and last
463         // We will look these up afterward to see if they are full names or not recognisable.
464
465         if(preg_match_all('/(@[^ \x0D\x0A,:?]+ [^ \x0D\x0A,:?]+)([ \x0D\x0A,:?]|$)/',$s,$match)) {
466                 foreach($match[1] as $mtch) {
467                         if(strstr($mtch,"]")) {
468                                 // we might be inside a bbcode color tag - leave it alone
469                                 continue;
470                         }
471                         if(substr($mtch,-1,1) === '.')
472                                 $ret[] = substr($mtch,0,-1);
473                         else
474                                 $ret[] = $mtch;
475                 }
476         }
477
478         // Otherwise pull out single word tags. These can be @nickname, @first_last
479         // and #hash tags.
480
481         if(preg_match_all('/([@#][^ \x0D\x0A,:?]+)([ \x0D\x0A,:?]|$)/',$s,$match)) {
482                 foreach($match[1] as $mtch) {
483                         if(strstr($mtch,"]")) {
484                                 // we might be inside a bbcode color tag - leave it alone
485                                 continue;
486                         }
487                         if(substr($mtch,-1,1) === '.')
488                                 $mtch = substr($mtch,0,-1);
489                         // ignore strictly numeric tags like #1
490                         if((strpos($mtch,'#') === 0) && ctype_digit(substr($mtch,1)))
491                                 continue;
492                         $ret[] = $mtch;
493                 }
494         }
495         return $ret;
496 }}
497
498
499 // quick and dirty quoted_printable encoding
500
501 if(! function_exists('qp')) {
502 function qp($s) {
503 return str_replace ("%","=",rawurlencode($s));
504 }} 
505
506
507
508 if(! function_exists('get_mentions')) {
509 function get_mentions($item) {
510         $o = '';
511         if(! strlen($item['tag']))
512                 return $o;
513
514         $arr = explode(',',$item['tag']);
515         foreach($arr as $x) {
516                 $matches = null;
517                 if(preg_match('/@\[url=([^\]]*)\]/',$x,$matches)) {
518                         $o .= "\t\t" . '<link rel="mentioned" href="' . $matches[1] . '" />' . "\r\n";
519                         $o .= "\t\t" . '<link rel="ostatus:attention" href="' . $matches[1] . '" />' . "\r\n";
520                 }
521         }
522         return $o;
523 }}
524
525 if(! function_exists('contact_block')) {
526 function contact_block() {
527         $o = '';
528         $a = get_app();
529
530         $shown = get_pconfig($a->profile['uid'],'system','display_friend_count');
531         if(! $shown)
532                 $shown = 24;
533
534         if((! is_array($a->profile)) || ($a->profile['hide-friends']))
535                 return $o;
536         $r = q("SELECT COUNT(*) AS `total` FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 and `pending` = 0",
537                         intval($a->profile['uid'])
538         );
539         if(count($r)) {
540                 $total = intval($r[0]['total']);
541         }
542         if(! $total) {
543                 $contacts = t('No contacts');
544                 $micropro = Null;
545                 
546         } else {
547                 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 and `pending` = 0 ORDER BY RAND() LIMIT %d",
548                                 intval($a->profile['uid']),
549                                 intval($shown)
550                 );
551                 if(count($r)) {
552                         $contacts = sprintf( tt('%d Contact','%d Contacts', $total),$total);
553                         $micropro = Array();
554                         foreach($r as $rr) {
555                                 $micropro[] = micropro($rr,true,'mpfriend');
556                         }
557                 }
558         }
559         
560         $tpl = get_markup_template('contact_block.tpl');
561         $o = replace_macros($tpl, array(
562                 '$contacts' => $contacts,
563                 '$nickname' => $a->profile['nickname'],
564                 '$viewcontacts' => t('View Contacts'),
565                 '$micropro' => $micropro,
566         ));
567
568         $arr = array('contacts' => $r, 'output' => $o);
569
570         call_hooks('contact_block_end', $arr);
571         return $o;
572
573 }}
574
575 if(! function_exists('micropro')) {
576 function micropro($contact, $redirect = false, $class = '', $textmode = false) {
577
578         if($class)
579                 $class = ' ' . $class;
580
581         $url = $contact['url'];
582         $sparkle = '';
583         $redir = false;
584
585         if($redirect) {
586                 $a = get_app();
587                 $redirect_url = $a->get_baseurl() . '/redir/' . $contact['id'];
588                 if(local_user() && ($contact['uid'] == local_user()) && ($contact['network'] === 'dfrn')) {
589                         $redir = true;
590                         $url = $redirect_url;
591                         $sparkle = ' sparkle';
592                 }
593         }
594         $click = ((x($contact,'click')) ? ' onclick="' . $contact['click'] . '" ' : '');
595         if($click)
596                 $url = '';
597         if($textmode) {
598                 return '<div class="contact-block-textdiv' . $class . '"><a class="contact-block-link' . $class . $sparkle 
599                         . (($click) ? ' fakelink' : '') . '" '
600                         . (($redir) ? ' target="redir" ' : '')
601                         . (($url) ? ' href="' . $url . '"' : '') . $click
602                         . '" title="' . $contact['name'] . ' [' . $contact['url'] . ']" alt="' . $contact['name'] 
603                         . '" >'. $contact['name'] . '</a></div>' . "\r\n";
604         }
605         else {
606                 return '<div class="contact-block-div' . $class . '"><a class="contact-block-link' . $class . $sparkle 
607                         . (($click) ? ' fakelink' : '') . '" '
608                         . (($redir) ? ' target="redir" ' : '')
609                         . (($url) ? ' href="' . $url . '"' : '') . $click . ' ><img class="contact-block-img' . $class . $sparkle . '" src="' 
610                         . $contact['micro'] . '" title="' . $contact['name'] . ' [' . $contact['url'] . ']" alt="' . $contact['name'] 
611                         . '" /></a></div>' . "\r\n";
612         }
613 }}
614
615
616
617 if(! function_exists('search')) {
618 function search($s,$id='search-box',$url='/search',$save = false) {
619         $a = get_app();
620         $o  = '<div id="' . $id . '">';
621         $o .= '<form action="' . $a->get_baseurl() . $url . '" method="get" >';
622         $o .= '<input type="text" name="search" id="search-text" value="' . $s .'" />';
623         $o .= '<input type="submit" name="submit" id="search-submit" value="' . t('Search') . '" />'; 
624         if($save)
625                 $o .= '<input type="submit" name="save" id="search-save" value="' . t('Save') . '" />'; 
626         $o .= '</form></div>';
627         return $o;
628 }}
629
630 if(! function_exists('valid_email')) {
631 function valid_email($x){
632         if(preg_match('/^[_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)+$/',$x))
633                 return true;
634         return false;
635 }}
636
637
638 /**
639  *
640  * Function: linkify
641  *
642  * Replace naked text hyperlink with HTML formatted hyperlink
643  *
644  */
645
646 if(! function_exists('linkify')) {
647 function linkify($s) {
648         $s = preg_replace("/(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\'\%\$\!\+]*)/", ' <a href="$1" target="external-link">$1</a>', $s);
649         $s = preg_replace("/\<(.*?)(src|href)=(.*?)\&amp\;(.*?)\>/ism",'<$1$2=$3&$4>',$s);
650         return($s);
651 }}
652
653
654 /**
655  * 
656  * Function: smilies
657  *
658  * Description:
659  * Replaces text emoticons with graphical images
660  *
661  * @Parameter: string $s
662  *
663  * Returns string
664  */
665
666 if(! function_exists('smilies')) {
667 function smilies($s) {
668         $a = get_app();
669
670         $s = str_replace(
671         array( '&lt;3', '&lt;/3', '&lt;\\3', ':-)', ':)', ';-)', ':-(', ':(', ':-P', ':P', ':-"', ':-x', ':-X', ':-D', '8-|', '8-O', 
672                 '~friendika', 'Diaspora*' ),
673         array(
674                 '<img src="' . $a->get_baseurl() . '/images/smiley-heart.gif" alt="<3" />',
675                 '<img src="' . $a->get_baseurl() . '/images/smiley-brokenheart.gif" alt="</3" />',
676                 '<img src="' . $a->get_baseurl() . '/images/smiley-brokenheart.gif" alt="<\\3" />',
677                 '<img src="' . $a->get_baseurl() . '/images/smiley-smile.gif" alt=":-)" />',
678                 '<img src="' . $a->get_baseurl() . '/images/smiley-smile.gif" alt=":)" />',
679                 '<img src="' . $a->get_baseurl() . '/images/smiley-wink.gif" alt=";-)" />',
680                 '<img src="' . $a->get_baseurl() . '/images/smiley-frown.gif" alt=":-(" />',
681                 '<img src="' . $a->get_baseurl() . '/images/smiley-frown.gif" alt=":(" />',
682                 '<img src="' . $a->get_baseurl() . '/images/smiley-tongue-out.gif" alt=":-P" />',
683                 '<img src="' . $a->get_baseurl() . '/images/smiley-tongue-out.gif" alt=":P" />',
684                 '<img src="' . $a->get_baseurl() . '/images/smiley-kiss.gif" alt=":-\"" />',
685                 '<img src="' . $a->get_baseurl() . '/images/smiley-kiss.gif" alt=":-x" />',
686                 '<img src="' . $a->get_baseurl() . '/images/smiley-kiss.gif" alt=":-X" />',
687                 '<img src="' . $a->get_baseurl() . '/images/smiley-laughing.gif" alt=":-D" />',
688                 '<img src="' . $a->get_baseurl() . '/images/smiley-surprised.gif" alt="8-|" />',
689                 '<img src="' . $a->get_baseurl() . '/images/smiley-surprised.gif" alt="8-O" />',
690                 '<a href="http://project.friendika.com">~friendika <img src="' . $a->get_baseurl() . '/images/friendika-16.png" alt="~friendika" /></a>',
691                 '<a href="http://diasporafoundation.org">Diaspora<img src="' . $a->get_baseurl() . '/images/diaspora.png" alt="Diaspora*" /></a>',
692
693         ), $s);
694
695         call_hooks('smilie', $s);
696         return $s;
697
698 }}
699
700
701
702 if(! function_exists('day_translate')) {
703 function day_translate($s) {
704         $ret = str_replace(array('Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'),
705                 array( t('Monday'), t('Tuesday'), t('Wednesday'), t('Thursday'), t('Friday'), t('Saturday'), t('Sunday')),
706                 $s);
707
708         $ret = str_replace(array('January','February','March','April','May','June','July','August','September','October','November','December'),
709                 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')),
710                 $ret);
711
712         return $ret;
713 }}
714
715
716 if(! function_exists('normalise_link')) {
717 function normalise_link($url) {
718         $ret = str_replace(array('https:','//www.'), array('http:','//'), $url);
719         return(rtrim($ret,'/'));
720 }}
721
722 /**
723  *
724  * Compare two URLs to see if they are the same, but ignore
725  * slight but hopefully insignificant differences such as if one 
726  * is https and the other isn't, or if one is www.something and 
727  * the other isn't - and also ignore case differences.
728  *
729  * Return true if the URLs match, otherwise false.
730  *
731  */
732
733 if(! function_exists('link_compare')) {
734 function link_compare($a,$b) {
735         if(strcasecmp(normalise_link($a),normalise_link($b)) === 0)
736                 return true;
737         return false;
738 }}
739
740 // Given an item array, convert the body element from bbcode to html and add smilie icons.
741 // If attach is true, also add icons for item attachments
742
743
744 if(! function_exists('prepare_body')) {
745 function prepare_body($item,$attach = false) {
746
747         call_hooks('prepare_body_init', $item); 
748
749         $s = prepare_text($item['body']);
750
751         call_hooks('prepare_body', $s);
752
753         if(! $attach)
754                 return $s;
755
756         $arr = explode(',',$item['attach']);
757         if(count($arr)) {
758                 $s .= '<div class="body-attach">';
759                 foreach($arr as $r) {
760                         $matches = false;
761                         $icon = '';
762                         $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"\[\/attach\]|',$r,$matches);
763                         if($cnt) {
764                                 $icontype = strtolower(substr($matches[3],0,strpos($matches[3],'/')));
765                                 switch($icontype) {
766                                         case 'video':
767                                         case 'audio':
768                                         case 'image':
769                                         case 'text':
770                                                 $icon = '<div class="attachtype type-' . $icontype . '"></div>';
771                                                 break;
772                                         default:
773                                                 $icon = '<div class="attachtype type-unkn"></div>';
774                                                 break;
775                                 }
776                                 $title = ((strlen(trim($matches[4]))) ? escape_tags(trim($matches[4])) : escape_tags($matches[1]));
777                                 $title .= ' ' . $matches[2] . ' ' . t('bytes');
778
779                                 $s .= '<a href="' . strip_tags($matches[1]) . '" title="' . $title . '" class="attachlink" target="external-link" >' . $icon . '</a>';
780                         }
781                 }
782                 $s .= '<div class="clear"></div></div>';
783         }
784         call_hooks('prepare_body_final', $s);
785         return $s;
786 }}
787
788
789 // Given a text string, convert from bbcode to html and add smilie icons.
790
791 if(! function_exists('prepare_text')) {
792 function prepare_text($text) {
793
794         require_once('include/bbcode.php');
795
796         $s = smilies(bbcode($text));
797
798         return $s;
799 }}
800
801
802 /**
803  * return atom link elements for all of our hubs
804  */
805
806 if(! function_exists('feed_hublinks')) {
807 function feed_hublinks() {
808
809         $hub = get_config('system','huburl');
810
811         $hubxml = '';
812         if(strlen($hub)) {
813                 $hubs = explode(',', $hub);
814                 if(count($hubs)) {
815                         foreach($hubs as $h) {
816                                 $h = trim($h);
817                                 if(! strlen($h))
818                                         continue;
819                                 $hubxml .= '<link rel="hub" href="' . xmlify($h) . '" />' . "\n" ;
820                         }
821                 }
822         }
823         return $hubxml;
824 }}
825
826 /* return atom link elements for salmon endpoints */
827
828 if(! function_exists('feed_salmonlinks')) {
829 function feed_salmonlinks($nick) {
830
831         $a = get_app();
832
833         $salmon  = '<link rel="salmon" href="' . xmlify($a->get_baseurl() . '/salmon/' . $nick) . '" />' . "\n" ;
834
835         // old style links that status.net still needed as of 12/2010 
836
837         $salmon .= '  <link rel="http://salmon-protocol.org/ns/salmon-replies" href="' . xmlify($a->get_baseurl() . '/salmon/' . $nick) . '" />' . "\n" ; 
838         $salmon .= '  <link rel="http://salmon-protocol.org/ns/salmon-mention" href="' . xmlify($a->get_baseurl() . '/salmon/' . $nick) . '" />' . "\n" ; 
839         return $salmon;
840 }}
841
842 if(! function_exists('get_plink')) {
843 function get_plink($item) {
844         $a = get_app(); 
845         if (x($item,'plink') && (! $item['private'])){
846                 return array(
847                         'href' => $item['plink'],
848                         'title' => t('link to source'),
849                 );
850         } else {
851                 return false;
852         }
853 }}
854
855 if(! function_exists('unamp')) {
856 function unamp($s) {
857         return str_replace('&amp;', '&', $s);
858 }}
859
860
861
862
863 if(! function_exists('lang_selector')) {
864 function lang_selector() {
865         global $lang;
866         $o = '<div id="lang-select-icon" class="icon language" title="' . t('Select an alternate language') . '" onclick="openClose(\'language-selector\');" ></div>';
867         $o .= '<div id="language-selector" style="display: none;" >';
868         $o .= '<form action="#" method="post" ><select name="system_language" onchange="this.form.submit();" >';
869         $langs = glob('view/*/strings.php');
870         if(is_array($langs) && count($langs)) {
871                 $langs[] = '';
872                 if(! in_array('view/en/strings.php',$langs))
873                         $langs[] = 'view/en/';
874                 asort($langs);
875                 foreach($langs as $l) {
876                         if($l == '') {
877                                 $default_selected = ((! x($_SESSION,'language')) ? ' selected="selected" ' : '');
878                                 $o .= '<option value="" ' . $default_selected . '>' . t('default') . '</option>';
879                                 continue;
880                         }
881                         $ll = substr($l,5);
882                         $ll = substr($ll,0,strrpos($ll,'/'));
883                         $selected = (($ll === $lang && (x($_SESSION['language']))) ? ' selected="selected" ' : '');
884                         $o .= '<option value="' . $ll . '"' . $selected . '>' . $ll . '</option>';
885                 }
886         }
887         $o .= '</select></form></div>';
888         return $o;
889 }}
890
891
892 if(! function_exists('return_bytes')) {
893 function return_bytes ($size_str) {
894     switch (substr ($size_str, -1))
895     {
896         case 'M': case 'm': return (int)$size_str * 1048576;
897         case 'K': case 'k': return (int)$size_str * 1024;
898         case 'G': case 'g': return (int)$size_str * 1073741824;
899         default: return $size_str;
900     }
901 }}
902
903 function generate_user_guid() {
904         $found = true;
905         do {
906                 $guid = random_string(16);
907                 $x = q("SELECT `uid` FROM `user` WHERE `guid` = '%s' LIMIT 1",
908                         dbesc($guid)
909                 );
910                 if(! count($x))
911                         $found = false;
912         } while ($found == true );
913         return $guid;
914 }
915
916
917
918 function base64url_encode($s, $strip_padding = false) {
919
920         $s = strtr(base64_encode($s),'+/','-_');
921
922         if($strip_padding)
923                 $s = str_replace('=','',$s);
924
925         return $s;
926 }
927
928 function base64url_decode($s) {
929
930 /*
931  *  // Placeholder for new rev of salmon which strips base64 padding.
932  *  // PHP base64_decode handles the un-padded input without requiring this step
933  *  // Uncomment if you find you need it.
934  *
935  *      $l = strlen($s);
936  *      if(! strpos($s,'=')) {
937  *              $m = $l % 4;
938  *              if($m == 2)
939  *                      $s .= '==';
940  *              if($m == 3)
941  *                      $s .= '=';
942  *      }
943  *
944  */
945
946         return base64_decode(strtr($s,'-_','+/'));
947 }
948
949
950 if (!function_exists('str_getcsv')) {
951     function str_getcsv($input, $delimiter = ',', $enclosure = '"', $escape = '\\', $eol = '\n') {
952         if (is_string($input) && !empty($input)) {
953             $output = array();
954             $tmp    = preg_split("/".$eol."/",$input);
955             if (is_array($tmp) && !empty($tmp)) {
956                 while (list($line_num, $line) = each($tmp)) {
957                     if (preg_match("/".$escape.$enclosure."/",$line)) {
958                         while ($strlen = strlen($line)) {
959                             $pos_delimiter       = strpos($line,$delimiter);
960                             $pos_enclosure_start = strpos($line,$enclosure);
961                             if (
962                                 is_int($pos_delimiter) && is_int($pos_enclosure_start)
963                                 && ($pos_enclosure_start < $pos_delimiter)
964                                 ) {
965                                 $enclosed_str = substr($line,1);
966                                 $pos_enclosure_end = strpos($enclosed_str,$enclosure);
967                                 $enclosed_str = substr($enclosed_str,0,$pos_enclosure_end);
968                                 $output[$line_num][] = $enclosed_str;
969                                 $offset = $pos_enclosure_end+3;
970                             } else {
971                                 if (empty($pos_delimiter) && empty($pos_enclosure_start)) {
972                                     $output[$line_num][] = substr($line,0);
973                                     $offset = strlen($line);
974                                 } else {
975                                     $output[$line_num][] = substr($line,0,$pos_delimiter);
976                                     $offset = (
977                                                 !empty($pos_enclosure_start)
978                                                 && ($pos_enclosure_start < $pos_delimiter)
979                                                 )
980                                                 ?$pos_enclosure_start
981                                                 :$pos_delimiter+1;
982                                 }
983                             }
984                             $line = substr($line,$offset);
985                         }
986                     } else {
987                         $line = preg_split("/".$delimiter."/",$line);
988    
989                         /*
990                          * Validating against pesky extra line breaks creating false rows.
991                          */
992                         if (is_array($line) && !empty($line[0])) {
993                             $output[$line_num] = $line;
994                         } 
995                     }
996                 }
997                 return $output;
998             } else {
999                 return false;
1000             }
1001         } else {
1002             return false;
1003         }
1004     }
1005
1006
1007 function cleardiv() {
1008         return '<div class="clear"></div>';
1009 }
1010
1011
1012 function bb_translate_video($s) {
1013
1014         $matches = null;
1015         $r = preg_match_all("/\[video\](.*?)\[\/video\]/ism",$s,$matches,PREG_SET_ORDER);
1016         if($r) {
1017                 foreach($matches as $mtch) {
1018                         if((stristr($mtch[1],'youtube')) || (stristr($mtch[1],'youtu.be')))
1019                                 $s = str_replace($mtch[0],'[youtube]' . $mtch[1] . '[/youtube]',$s);
1020                         elseif(stristr($mtch[1],'vimeo'))
1021                                 $s = str_replace($mtch[0],'[vimeo]' . $mtch[1] . '[/vimeo]',$s);
1022                 }
1023         }
1024         return $s;      
1025 }
1026
1027 function html2bb_video($s) {
1028
1029         $s = preg_replace('#<object[^>]+>(.*?)https+://www.youtube.com/((?:v|cp)/[A-Za-z0-9\-_=]+)(.*?)</object>#ism',
1030                         '[youtube]$2[/youtube]', $s);
1031
1032         $s = preg_replace('#<iframe[^>](.*?)https+://www.youtube.com/embed/([A-Za-z0-9\-_=]+)(.*?)</iframe>#ism',
1033                         '[youtube]$2[/youtube]', $s);
1034
1035         $s = preg_replace('#<iframe[^>](.*?)https+://player.vimeo.com/video/([0-9]+)(.*?)</iframe>#ism',
1036                         '[vimeo]$2[/vimeo]', $s);
1037
1038         return $s;
1039 }