]> git.mxchange.org Git - friendica.git/blob - include/text.php
breaking up boot file (part of zot refactor)
[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 hash, 64 chars
23
24 if(! function_exists('random_string')) {
25 function random_string() {
26         return(hash('sha256',uniqid(rand(),true)));
27 }}
28
29 /**
30  * This is our primary input filter. 
31  *
32  * The high bit hack only involved some old IE browser, forget which (IE5/Mac?)
33  * that had an XSS attack vector due to stripping the high-bit on an 8-bit character
34  * after cleansing, and angle chars with the high bit set could get through as markup.
35  * 
36  * This is now disabled because it was interfering with some legitimate unicode sequences 
37  * and hopefully there aren't a lot of those browsers left. 
38  *
39  * Use this on any text input where angle chars are not valid or permitted
40  * They will be replaced with safer brackets. This may be filtered further
41  * if these are not allowed either.   
42  *
43  */
44
45 if(! function_exists('notags')) {
46 function notags($string) {
47
48         return(str_replace(array("<",">"), array('[',']'), $string));
49
50 //  High-bit filter no longer used
51 //      return(str_replace(array("<",">","\xBA","\xBC","\xBE"), array('[',']','','',''), $string));
52 }}
53
54 // use this on "body" or "content" input where angle chars shouldn't be removed,
55 // and allow them to be safely displayed.
56
57 if(! function_exists('escape_tags')) {
58 function escape_tags($string) {
59
60         return(htmlspecialchars($string));
61 }}
62
63
64 // generate a string that's random, but usually pronounceable. 
65 // used to generate initial passwords
66
67 if(! function_exists('autoname')) {
68 function autoname($len) {
69
70         $vowels = array('a','a','ai','au','e','e','e','ee','ea','i','ie','o','ou','u'); 
71         if(mt_rand(0,5) == 4)
72                 $vowels[] = 'y';
73
74         $cons = array(
75                         'b','bl','br',
76                         'c','ch','cl','cr',
77                         'd','dr',
78                         'f','fl','fr',
79                         'g','gh','gl','gr',
80                         'h',
81                         'j',
82                         'k','kh','kl','kr',
83                         'l',
84                         'm',
85                         'n',
86                         'p','ph','pl','pr',
87                         'qu',
88                         'r','rh',
89                         's','sc','sh','sm','sp','st',
90                         't','th','tr',
91                         'v',
92                         'w','wh',
93                         'x',
94                         'z','zh'
95                         );
96
97         $midcons = array('ck','ct','gn','ld','lf','lm','lt','mb','mm', 'mn','mp',
98                                 'nd','ng','nk','nt','rn','rp','rt');
99
100         $noend = array('bl', 'br', 'cl','cr','dr','fl','fr','gl','gr',
101                                 'kh', 'kl','kr','mn','pl','pr','rh','tr','qu','wh');
102
103         $start = mt_rand(0,2);
104         if($start == 0)
105                 $table = $vowels;
106         else
107                 $table = $cons;
108
109         $word = '';
110
111         for ($x = 0; $x < $len; $x ++) {
112                 $r = mt_rand(0,count($table) - 1);
113                 $word .= $table[$r];
114   
115                 if($table == $vowels)
116                         $table = array_merge($cons,$midcons);
117                 else
118                         $table = $vowels;
119
120         }
121
122         $word = substr($word,0,$len);
123
124         foreach($noend as $noe) {
125                 if((strlen($word) > 2) && (substr($word,-2) == $noe)) {
126                         $word = substr($word,0,-1);
127                         break;
128                 }
129         }
130         if(substr($word,-1) == 'q')
131                 $word = substr($word,0,-1);    
132         return $word;
133 }}
134
135
136 // escape text ($str) for XML transport
137 // returns escaped text.
138
139 if(! function_exists('xmlify')) {
140 function xmlify($str) {
141         $buffer = '';
142         
143         for($x = 0; $x < strlen($str); $x ++) {
144                 $char = $str[$x];
145         
146                 switch( $char ) {
147
148                         case "\r" :
149                                 break;
150                         case "&" :
151                                 $buffer .= '&amp;';
152                                 break;
153                         case "'" :
154                                 $buffer .= '&apos;';
155                                 break;
156                         case "\"" :
157                                 $buffer .= '&quot;';
158                                 break;
159                         case '<' :
160                                 $buffer .= '&lt;';
161                                 break;
162                         case '>' :
163                                 $buffer .= '&gt;';
164                                 break;
165                         case "\n" :
166                                 $buffer .= "\n";
167                                 break;
168                         default :
169                                 $buffer .= $char;
170                                 break;
171                 }       
172         }
173         $buffer = trim($buffer);
174         return($buffer);
175 }}
176
177 // undo an xmlify
178 // pass xml escaped text ($s), returns unescaped text
179
180 if(! function_exists('unxmlify')) {
181 function unxmlify($s) {
182         $ret = str_replace('&amp;','&', $s);
183         $ret = str_replace(array('&lt;','&gt;','&quot;','&apos;'),array('<','>','"',"'"),$ret);
184         return $ret;    
185 }}
186
187 // convenience wrapper, reverse the operation "bin2hex"
188
189 if(! function_exists('hex2bin')) {
190 function hex2bin($s) {
191         if(! ctype_xdigit($s)) {
192                 logger('hex2bin: illegal input: ' . print_r(debug_backtrace(), true));
193                 return($s);
194         }
195
196         return(pack("H*",$s));
197 }}
198
199 // Automatic pagination.
200 // To use, get the count of total items.
201 // Then call $a->set_pager_total($number_items);
202 // Optionally call $a->set_pager_itemspage($n) to the number of items to display on each page
203 // Then call paginate($a) after the end of the display loop to insert the pager block on the page
204 // (assuming there are enough items to paginate).
205 // When using with SQL, the setting LIMIT %d, %d => $a->pager['start'],$a->pager['itemspage']
206 // will limit the results to the correct items for the current page. 
207 // The actual page handling is then accomplished at the application layer. 
208
209 if(! function_exists('paginate')) {
210 function paginate(&$a) {
211         $o = '';
212         $stripped = preg_replace('/(&page=[0-9]*)/','',$a->query_string);
213         $stripped = str_replace('q=','',$stripped);
214         $stripped = trim($stripped,'/');
215         $pagenum = $a->pager['page'];
216         $url = $a->get_baseurl() . '/' . $stripped;
217
218
219           if($a->pager['total'] > $a->pager['itemspage']) {
220                 $o .= '<div class="pager">';
221                 if($a->pager['page'] != 1)
222                         $o .= '<span class="pager_prev">'."<a href=\"$url".'&page='.($a->pager['page'] - 1).'">' . t('prev') . '</a></span> ';
223
224                 $o .=  "<span class=\"pager_first\"><a href=\"$url"."&page=1\">" . t('first') . "</a></span> ";
225
226                 $numpages = $a->pager['total'] / $a->pager['itemspage'];
227
228                         $numstart = 1;
229                 $numstop = $numpages;
230
231                 if($numpages > 14) {
232                         $numstart = (($pagenum > 7) ? ($pagenum - 7) : 1);
233                         $numstop = (($pagenum > ($numpages - 7)) ? $numpages : ($numstart + 14));
234                 }
235    
236                 for($i = $numstart; $i <= $numstop; $i++){
237                         if($i == $a->pager['page'])
238                                 $o .= '<span class="pager_current">'.(($i < 10) ? '&nbsp;'.$i : $i);
239                         else
240                                 $o .= "<span class=\"pager_n\"><a href=\"$url"."&page=$i\">".(($i < 10) ? '&nbsp;'.$i : $i)."</a>";
241                         $o .= '</span> ';
242                 }
243
244                 if(($a->pager['total'] % $a->pager['itemspage']) != 0) {
245                         if($i == $a->pager['page'])
246                                 $o .= '<span class="pager_current">'.(($i < 10) ? '&nbsp;'.$i : $i);
247                         else
248                                 $o .= "<span class=\"pager_n\"><a href=\"$url"."&page=$i\">".(($i < 10) ? '&nbsp;'.$i : $i)."</a>";
249                         $o .= '</span> ';
250                 }
251
252                 $lastpage = (($numpages > intval($numpages)) ? intval($numpages)+1 : $numpages);
253                 $o .= "<span class=\"pager_last\"><a href=\"$url"."&page=$lastpage\">" . t('last') . "</a></span> ";
254
255                 if(($a->pager['total'] - ($a->pager['itemspage'] * $a->pager['page'])) > 0)
256                         $o .= '<span class="pager_next">'."<a href=\"$url"."&page=".($a->pager['page'] + 1).'">' . t('next') . '</a></span>';
257                 $o .= '</div>'."\r\n";
258         }
259         return $o;
260 }}
261
262 // Turn user/group ACLs stored as angle bracketed text into arrays
263
264 if(! function_exists('expand_acl')) {
265 function expand_acl($s) {
266         // turn string array of angle-bracketed elements into numeric array
267         // e.g. "<1><2><3>" => array(1,2,3);
268         $ret = array();
269
270         if(strlen($s)) {
271                 $t = str_replace('<','',$s);
272                 $a = explode('>',$t);
273                 foreach($a as $aa) {
274                         if(intval($aa))
275                                 $ret[] = intval($aa);
276                 }
277         }
278         return $ret;
279 }}              
280
281 // Used to wrap ACL elements in angle brackets for storage 
282
283 if(! function_exists('sanitise_acl')) {
284 function sanitise_acl(&$item) {
285         if(intval($item))
286                 $item = '<' . intval(notags(trim($item))) . '>';
287         else
288                 unset($item);
289 }}
290
291
292 // Convert an ACL array to a storable string
293
294 if(! function_exists('perms2str')) {
295 function perms2str($p) {
296         $ret = '';
297         $tmp = $p;
298         if(is_array($tmp)) {
299                 array_walk($tmp,'sanitise_acl');
300                 $ret = implode('',$tmp);
301         }
302         return $ret;
303 }}
304
305 // generate a guaranteed unique (for this domain) item ID for ATOM
306 // safe from birthday paradox
307
308 if(! function_exists('item_new_uri')) {
309 function item_new_uri($hostname,$uid) {
310
311         do {
312                 $dups = false;
313                 $hash = random_string();
314
315                 $uri = "urn:X-dfrn:" . $hostname . ':' . $uid . ':' . $hash;
316
317                 $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' LIMIT 1",
318                         dbesc($uri));
319                 if(count($r))
320                         $dups = true;
321         } while($dups == true);
322         return $uri;
323 }}
324
325 // Generate a guaranteed unique photo ID.
326 // safe from birthday paradox
327
328 if(! function_exists('photo_new_resource')) {
329 function photo_new_resource() {
330
331         do {
332                 $found = false;
333                 $resource = hash('md5',uniqid(mt_rand(),true));
334                 $r = q("SELECT `id` FROM `photo` WHERE `resource-id` = '%s' LIMIT 1",
335                         dbesc($resource)
336                 );
337                 if(count($r))
338                         $found = true;
339         } while($found == true);
340         return $resource;
341 }}
342
343
344 // wrapper to load a view template, checking for alternate
345 // languages before falling back to the default
346
347 // obsolete, deprecated.
348
349 if(! function_exists('load_view_file')) {
350 function load_view_file($s) {
351         global $lang, $a;
352         if(! isset($lang))
353                 $lang = 'en';
354         $b = basename($s);
355         $d = dirname($s);
356         if(file_exists("$d/$lang/$b"))
357                 return file_get_contents("$d/$lang/$b");
358         
359         $theme = current_theme();
360         
361         if(file_exists("$d/theme/$theme/$b"))
362                 return file_get_contents("$d/theme/$theme/$b");
363                         
364         return file_get_contents($s);
365 }}
366
367 if(! function_exists('get_intltext_template')) {
368 function get_intltext_template($s) {
369         global $lang;
370
371         if(! isset($lang))
372                 $lang = 'en';
373
374         if(file_exists("view/$lang/$s"))
375                 return file_get_contents("view/$lang/$s");
376         elseif(file_exists("view/en/$s"))
377                 return file_get_contents("view/en/$s");
378         else
379                 return file_get_contents("view/$s");
380 }}
381
382 if(! function_exists('get_markup_template')) {
383 function get_markup_template($s) {
384
385         $theme = current_theme();
386         
387         if(file_exists("view/theme/$theme/$s"))
388                 return file_get_contents("view/theme/$theme/$s");
389         else
390                 return file_get_contents("view/$s");
391
392 }}
393
394
395
396
397
398 // for html,xml parsing - let's say you've got
399 // an attribute foobar="class1 class2 class3"
400 // and you want to find out if it contains 'class3'.
401 // you can't use a normal sub string search because you
402 // might match 'notclass3' and a regex to do the job is 
403 // possible but a bit complicated. 
404 // pass the attribute string as $attr and the attribute you 
405 // are looking for as $s - returns true if found, otherwise false
406
407 if(! function_exists('attribute_contains')) {
408 function attribute_contains($attr,$s) {
409         $a = explode(' ', $attr);
410         if(count($a) && in_array($s,$a))
411                 return true;
412         return false;
413 }}
414
415 if(! function_exists('logger')) {
416 function logger($msg,$level = 0) {
417         $debugging = get_config('system','debugging');
418         $loglevel  = intval(get_config('system','loglevel'));
419         $logfile   = get_config('system','logfile');
420
421         if((! $debugging) || (! $logfile) || ($level > $loglevel))
422                 return;
423         
424         @file_put_contents($logfile, datetime_convert() . ':' . session_id() . ' ' . $msg . "\n", FILE_APPEND);
425         return;
426 }}
427
428
429 if(! function_exists('activity_match')) {
430 function activity_match($haystack,$needle) {
431         if(($haystack === $needle) || ((basename($needle) === $haystack) && strstr($needle,NAMESPACE_ACTIVITY_SCHEMA)))
432                 return true;
433         return false;
434 }}
435
436
437 // Pull out all #hashtags and @person tags from $s;
438 // We also get @person@domain.com - which would make 
439 // the regex quite complicated as tags can also
440 // end a sentence. So we'll run through our results
441 // and strip the period from any tags which end with one.
442 // Returns array of tags found, or empty array.
443
444
445 if(! function_exists('get_tags')) {
446 function get_tags($s) {
447         $ret = array();
448
449         // ignore anything in a code block
450
451         $s = preg_replace('/\[code\](.*?)\[\/code\]/sm','',$s);
452
453         // Match full names against @tags including the space between first and last
454         // We will look these up afterward to see if they are full names or not recognisable.
455
456         if(preg_match_all('/(@[^ \x0D\x0A,:?]+ [^ \x0D\x0A,:?]+)([ \x0D\x0A,:?]|$)/',$s,$match)) {
457                 foreach($match[1] as $mtch) {
458                         if(strstr($mtch,"]")) {
459                                 // we might be inside a bbcode color tag - leave it alone
460                                 continue;
461                         }
462                         if(substr($mtch,-1,1) === '.')
463                                 $ret[] = substr($mtch,0,-1);
464                         else
465                                 $ret[] = $mtch;
466                 }
467         }
468
469         // Otherwise pull out single word tags. These can be @nickname, @first_last
470         // and #hash tags.
471
472         if(preg_match_all('/([@#][^ \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                         // ignore strictly numeric tags like #1
479                         if((strpos($mtch,'#') === 0) && ctype_digit(substr($mtch,1)))
480                                 continue;
481                         if(substr($mtch,-1,1) === '.')
482                                 $ret[] = substr($mtch,0,-1);
483                         else
484                                 $ret[] = $mtch;
485                 }
486         }
487         return $ret;
488 }}
489
490
491 // quick and dirty quoted_printable encoding
492
493 if(! function_exists('qp')) {
494 function qp($s) {
495 return str_replace ("%","=",rawurlencode($s));
496 }} 
497
498
499
500 if(! function_exists('get_mentions')) {
501 function get_mentions($item) {
502         $o = '';
503         if(! strlen($item['tag']))
504                 return $o;
505
506         $arr = explode(',',$item['tag']);
507         foreach($arr as $x) {
508                 $matches = null;
509                 if(preg_match('/@\[url=([^\]]*)\]/',$x,$matches)) {
510                         $o .= "\t\t" . '<link rel="mentioned" href="' . $matches[1] . '" />' . "\r\n";
511                         $o .= "\t\t" . '<link rel="ostatus:attention" href="' . $matches[1] . '" />' . "\r\n";
512                 }
513         }
514         return $o;
515 }}
516
517 if(! function_exists('contact_block')) {
518 function contact_block() {
519         $o = '';
520         $a = get_app();
521
522         $shown = get_pconfig($a->profile['uid'],'system','display_friend_count');
523         if(! $shown)
524                 $shown = 24;
525
526         if((! is_array($a->profile)) || ($a->profile['hide-friends']))
527                 return $o;
528         $r = q("SELECT COUNT(*) AS `total` FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 and `pending` = 0",
529                         intval($a->profile['uid'])
530         );
531         if(count($r)) {
532                 $total = intval($r[0]['total']);
533         }
534         if(! $total) {
535                 $o .= '<h4 class="contact-h4">' . t('No contacts') . '</h4>';
536                 return $o;
537         }
538         $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 and `pending` = 0 ORDER BY RAND() LIMIT %d",
539                         intval($a->profile['uid']),
540                         intval($shown)
541         );
542         if(count($r)) {
543                 $o .= '<h4 class="contact-h4">' .  sprintf( tt('%d Contact','%d Contacts', $total),$total) . '</h4><div id="contact-block">';
544                 foreach($r as $rr) {
545                         $o .= micropro($rr,true,'mpfriend');
546                 }
547                 $o .= '</div><div id="contact-block-end"></div>';
548                 $o .=  '<div id="viewcontacts"><a id="viewcontacts-link" href="viewcontacts/' . $a->profile['nickname'] . '">' . t('View Contacts') . '</a></div>';
549                 
550         }
551
552         $arr = array('contacts' => $r, 'output' => $o);
553
554         call_hooks('contact_block_end', $arr);
555         return $o;
556
557 }}
558
559 if(! function_exists('micropro')) {
560 function micropro($contact, $redirect = false, $class = '', $textmode = false) {
561
562         if($class)
563                 $class = ' ' . $class;
564
565         $url = $contact['url'];
566         $sparkle = '';
567
568         if($redirect) {
569                 $a = get_app();
570                 $redirect_url = $a->get_baseurl() . '/redir/' . $contact['id'];
571                 if(local_user() && ($contact['uid'] == local_user()) && ($contact['network'] === 'dfrn')) {
572                         $url = $redirect_url;
573                         $sparkle = ' sparkle';
574                 }
575         }
576         $click = ((x($contact,'click')) ? ' onclick="' . $contact['click'] . '" ' : '');
577         if($click)
578                 $url = '';
579         if($textmode) {
580                 return '<div class="contact-block-textdiv' . $class . '"><a class="contact-block-link' . $class . $sparkle 
581                         . (($click) ? ' fakelink' : '') . '" '
582                         . (($url) ? ' href="' . $url . '"' : '') . $click
583                         . '" title="' . $contact['name'] . ' [' . $contact['url'] . ']" alt="' . $contact['name'] 
584                         . '" >'. $contact['name'] . '</a></div>' . "\r\n";
585         }
586         else {
587                 return '<div class="contact-block-div' . $class . '"><a class="contact-block-link' . $class . $sparkle 
588                         . (($click) ? ' fakelink' : '') . '" '
589                         . (($url) ? ' href="' . $url . '"' : '') . $click . ' ><img class="contact-block-img' . $class . $sparkle . '" src="' 
590                         . $contact['micro'] . '" title="' . $contact['name'] . ' [' . $contact['url'] . ']" alt="' . $contact['name'] 
591                         . '" /></a></div>' . "\r\n";
592         }
593 }}
594
595
596
597 if(! function_exists('search')) {
598 function search($s,$id='search-box',$url='/search') {
599         $a = get_app();
600         $o  = '<div id="' . $id . '">';
601         $o .= '<form action="' . $a->get_baseurl() . $url . '" method="get" >';
602         $o .= '<input type="text" name="search" id="search-text" value="' . $s .'" />';
603         $o .= '<input type="submit" name="submit" id="search-submit" value="' . t('Search') . '" />'; 
604         $o .= '</form></div>';
605         return $o;
606 }}
607
608 if(! function_exists('valid_email')) {
609 function valid_email($x){
610         if(preg_match('/^[_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)+$/',$x))
611                 return true;
612         return false;
613 }}
614
615
616 if(! function_exists('aes_decrypt')) {
617 function aes_decrypt($val,$ky)
618 {
619     $key="\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0";
620     for($a=0;$a<strlen($ky);$a++)
621       $key[$a%16]=chr(ord($key[$a%16]) ^ ord($ky[$a]));
622     $mode = MCRYPT_MODE_ECB;
623     $enc = MCRYPT_RIJNDAEL_128;
624     $dec = @mcrypt_decrypt($enc, $key, $val, $mode, @mcrypt_create_iv( @mcrypt_get_iv_size($enc, $mode), MCRYPT_DEV_URANDOM ) );
625     return rtrim($dec,(( ord(substr($dec,strlen($dec)-1,1))>=0 and ord(substr($dec, strlen($dec)-1,1))<=16)? chr(ord( substr($dec,strlen($dec)-1,1))):null));
626 }}
627
628
629 if(! function_exists('aes_encrypt')) {
630 function aes_encrypt($val,$ky)
631 {
632     $key="\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0";
633     for($a=0;$a<strlen($ky);$a++)
634       $key[$a%16]=chr(ord($key[$a%16]) ^ ord($ky[$a]));
635     $mode=MCRYPT_MODE_ECB;
636     $enc=MCRYPT_RIJNDAEL_128;
637     $val=str_pad($val, (16*(floor(strlen($val) / 16)+(strlen($val) % 16==0?2:1))), chr(16-(strlen($val) % 16)));
638     return mcrypt_encrypt($enc, $key, $val, $mode, mcrypt_create_iv( mcrypt_get_iv_size($enc, $mode), MCRYPT_DEV_URANDOM));
639 }} 
640
641
642 /**
643  *
644  * Function: linkify
645  *
646  * Replace naked text hyperlink with HTML formatted hyperlink
647  *
648  */
649
650 if(! function_exists('linkify')) {
651 function linkify($s) {
652         $s = preg_replace("/(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\.\=\_\~\#\'\%\$\!\+]*)/", ' <a href="$1" target="external-link">$1</a>', $s);
653         return($s);
654 }}
655
656
657 /**
658  * 
659  * Function: smilies
660  *
661  * Description:
662  * Replaces text emoticons with graphical images
663  *
664  * @Parameter: string $s
665  *
666  * Returns string
667  */
668
669 if(! function_exists('smilies')) {
670 function smilies($s) {
671         $a = get_app();
672
673         return str_replace(
674         array( '&lt;3', '&lt;/3', '&lt;\\3', ':-)', ':)', ';-)', ':-(', ':(', ':-P', ':P', ':-"', ':-x', ':-X', ':-D', '8-|', '8-O'),
675         array(
676                 '<img src="' . $a->get_baseurl() . '/images/smiley-heart.gif" alt="<3" />',
677                 '<img src="' . $a->get_baseurl() . '/images/smiley-brokenheart.gif" alt="</3" />',
678                 '<img src="' . $a->get_baseurl() . '/images/smiley-brokenheart.gif" alt="<\\3" />',
679                 '<img src="' . $a->get_baseurl() . '/images/smiley-smile.gif" alt=":-)" />',
680                 '<img src="' . $a->get_baseurl() . '/images/smiley-smile.gif" alt=":)" />',
681                 '<img src="' . $a->get_baseurl() . '/images/smiley-wink.gif" alt=";-)" />',
682                 '<img src="' . $a->get_baseurl() . '/images/smiley-frown.gif" alt=":-(" />',
683                 '<img src="' . $a->get_baseurl() . '/images/smiley-frown.gif" alt=":(" />',
684                 '<img src="' . $a->get_baseurl() . '/images/smiley-tongue-out.gif" alt=":-P" />',
685                 '<img src="' . $a->get_baseurl() . '/images/smiley-tongue-out.gif" alt=":P" />',
686                 '<img src="' . $a->get_baseurl() . '/images/smiley-kiss.gif" alt=":-\"" />',
687                 '<img src="' . $a->get_baseurl() . '/images/smiley-kiss.gif" alt=":-x" />',
688                 '<img src="' . $a->get_baseurl() . '/images/smiley-kiss.gif" alt=":-X" />',
689                 '<img src="' . $a->get_baseurl() . '/images/smiley-laughing.gif" alt=":-D" />',
690                 '<img src="' . $a->get_baseurl() . '/images/smiley-surprised.gif" alt="8-|" />',
691                 '<img src="' . $a->get_baseurl() . '/images/smiley-surprised.gif" alt="8-O" />'
692         ), $s);
693 }}
694
695
696
697 if(! function_exists('day_translate')) {
698 function day_translate($s) {
699         $ret = str_replace(array('Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'),
700                 array( t('Monday'), t('Tuesday'), t('Wednesday'), t('Thursday'), t('Friday'), t('Saturday'), t('Sunday')),
701                 $s);
702
703         $ret = str_replace(array('January','February','March','April','May','June','July','August','September','October','November','December'),
704                 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')),
705                 $ret);
706
707         return $ret;
708 }}
709
710
711 if(! function_exists('normalise_link')) {
712 function normalise_link($url) {
713         $ret = str_replace(array('https:','//www.'), array('http:','//'), $url);
714         return(rtrim($ret,'/'));
715 }}
716
717 /**
718  *
719  * Compare two URLs to see if they are the same, but ignore
720  * slight but hopefully insignificant differences such as if one 
721  * is https and the other isn't, or if one is www.something and 
722  * the other isn't - and also ignore case differences.
723  *
724  * Return true if the URLs match, otherwise false.
725  *
726  */
727
728 if(! function_exists('link_compare')) {
729 function link_compare($a,$b) {
730         if(strcasecmp(normalise_link($a),normalise_link($b)) === 0)
731                 return true;
732         return false;
733 }}
734
735
736 if(! function_exists('prepare_body')) {
737 function prepare_body($item,$attach = false) {
738
739         $s = prepare_text($item['body']);
740         if(! $attach)
741                 return $s;
742
743         $arr = explode(',',$item['attach']);
744         if(count($arr)) {
745                 $s .= '<div class="body-attach">';
746                 foreach($arr as $r) {
747                         $matches = false;
748                         $icon = '';
749                         $cnt = preg_match('|\[attach\]href=\"(.*?)\" size=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"\[\/attach\]|',$r,$matches);
750                         if($cnt) {
751                                 $icontype = strtolower(substr($matches[3],0,strpos($matches[3],'/')));
752                                 switch($icontype) {
753                                         case 'video':
754                                         case 'audio':
755                                         case 'image':
756                                         case 'text':
757                                                 $icon = '<div class="attachtype type-' . $icontype . '"></div>';
758                                                 break;
759                                         default:
760                                                 $icon = '<div class="attachtype type-unkn"></div>';
761                                                 break;
762                                 }
763                                 $title = ((strlen(trim($matches[4]))) ? escape_tags(trim($matches[4])) : escape_tags($matches[1]));
764                                 $title .= ' ' . $matches[2] . ' ' . t('bytes');
765
766                                 $s .= '<a href="' . strip_tags($matches[1]) . '" title="' . $title . '" class="attachlink" target="external-link" >' . $icon . '</a>';
767                         }
768                 }
769                 $s .= '<div class="clear"></div></div>';
770         }
771         return $s;
772 }}
773
774 if(! function_exists('prepare_text')) {
775 function prepare_text($text) {
776
777         require_once('include/bbcode.php');
778
779         $s = smilies(bbcode($text));
780
781         return $s;
782 }}
783
784
785 /**
786  * return atom link elements for all of our hubs
787  */
788
789 if(! function_exists('feed_hublinks')) {
790 function feed_hublinks() {
791
792         $hub = get_config('system','huburl');
793
794         $hubxml = '';
795         if(strlen($hub)) {
796                 $hubs = explode(',', $hub);
797                 if(count($hubs)) {
798                         foreach($hubs as $h) {
799                                 $h = trim($h);
800                                 if(! strlen($h))
801                                         continue;
802                                 $hubxml .= '<link rel="hub" href="' . xmlify($h) . '" />' . "\n" ;
803                         }
804                 }
805         }
806         return $hubxml;
807 }}
808
809 /* return atom link elements for salmon endpoints */
810
811 if(! function_exists('feed_salmonlinks')) {
812 function feed_salmonlinks($nick) {
813
814         $a = get_app();
815
816         $salmon  = '<link rel="salmon" href="' . xmlify($a->get_baseurl() . '/salmon/' . $nick) . '" />' . "\n" ;
817
818         // old style links that status.net still needed as of 12/2010 
819
820         $salmon .= '  <link rel="http://salmon-protocol.org/ns/salmon-replies" href="' . xmlify($a->get_baseurl() . '/salmon/' . $nick) . '" />' . "\n" ; 
821         $salmon .= '  <link rel="http://salmon-protocol.org/ns/salmon-mention" href="' . xmlify($a->get_baseurl() . '/salmon/' . $nick) . '" />' . "\n" ; 
822         return $salmon;
823 }}
824
825 if(! function_exists('get_plink')) {
826 function get_plink($item) {
827         $a = get_app(); 
828         $plink = (((x($item,'plink')) && (! $item['private'])) ? '<div class="wall-item-links-wrapper"><a href="' 
829                         . $item['plink'] . '" title="' . t('link to source') . '" target="external-link" class="icon remote-link"></a></div>' : '');
830         return $plink;
831 }}
832
833 if(! function_exists('unamp')) {
834 function unamp($s) {
835         return str_replace('&amp;', '&', $s);
836 }}
837
838
839
840
841 if(! function_exists('lang_selector')) {
842 function lang_selector() {
843         global $lang;
844         $o = '<div id="lang-select-icon" class="icon language" title="' . t('Select an alternate language') . '" onclick="openClose(\'language-selector\');" ></div>';
845         $o .= '<div id="language-selector" style="display: none;" >';
846         $o .= '<form action="" method="post" ><select name="system_language" onchange="this.form.submit();" >';
847         $langs = glob('view/*/strings.php');
848         if(is_array($langs) && count($langs)) {
849                 if(! in_array('view/en/strings.php',$langs))
850                         $langs[] = 'view/en/';
851                 asort($langs);
852                 foreach($langs as $l) {
853                         $ll = substr($l,5);
854                         $ll = substr($ll,0,strrpos($ll,'/'));
855                         $selected = (($ll === $lang) ? ' selected="selected" ' : '');
856                         $o .= '<option value="' . $ll . '"' . $selected . '>' . $ll . '</option>';
857                 }
858         }
859         $o .= '</select></form></div>';
860         return $o;
861 }}
862
863
864 if(! function_exists('return_bytes')) {
865 function return_bytes ($size_str) {
866     switch (substr ($size_str, -1))
867     {
868         case 'M': case 'm': return (int)$size_str * 1048576;
869         case 'K': case 'k': return (int)$size_str * 1024;
870         case 'G': case 'g': return (int)$size_str * 1073741824;
871         default: return $size_str;
872     }
873 }}
874
875 function generate_guid() {
876         $found = true;
877         do {
878                 $guid = substr(random_string(),0,16);
879                 $x = q("SELECT `uid` FROM `user` WHERE `guid` = '%s' LIMIT 1",
880                         dbesc($guid)
881                 );
882                 if(! count($x))
883                         $found = false;
884         } while ($found == true );
885         return $guid;
886 }
887
888
889 function pkcs5_pad ($text, $blocksize)
890 {
891     $pad = $blocksize - (strlen($text) % $blocksize);
892     return $text . str_repeat(chr($pad), $pad);
893 }
894
895 function pkcs5_unpad($text)
896 {
897     $pad = ord($text{strlen($text)-1});
898     if ($pad > strlen($text)) return false;
899     if (strspn($text, chr($pad), strlen($text) - $pad) != $pad) return false;
900     return substr($text, 0, -1 * $pad);
901
902
903
904 function base64url_encode($s, $strip_padding = false) {
905
906         $s = strtr(base64_encode($s),'+/','-_');
907
908         if($strip_padding)
909                 $s = str_replace('=','',$s);
910
911         return $s;
912 }
913
914 function base64url_decode($s) {
915
916 /*
917  *  // Placeholder for new rev of salmon which strips base64 padding.
918  *  // PHP base64_decode handles the un-padded input without requiring this step
919  *  // Uncomment if you find you need it.
920  *
921  *      $l = strlen($s);
922  *      if(! strpos($s,'=')) {
923  *              $m = $l % 4;
924  *              if($m == 2)
925  *                      $s .= '==';
926  *              if($m == 3)
927  *                      $s .= '=';
928  *      }
929  *
930  */
931
932         return base64_decode(strtr($s,'-_','+/'));
933 }