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