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